@seedprotocol/sdk 0.1.13 → 0.1.15

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 (34) hide show
  1. package/dist/bin.js +15 -15
  2. package/dist/{events-DbpQM9qG.js → events-DgKqHqww.js} +1784 -1675
  3. package/dist/events-DgKqHqww.js.map +1 -0
  4. package/dist/{index-D2_skdGT.js → index-CckG4Nv5.js} +18 -17
  5. package/dist/index-CckG4Nv5.js.map +1 -0
  6. package/dist/main.js +15 -15
  7. package/dist/{seed-DM5koJUz.js → seed-C8JBI4UL.js} +19 -18
  8. package/dist/seed-C8JBI4UL.js.map +1 -0
  9. package/dist/{seed-DHOFK9DF.js → seed-CJB6INNH.js} +19 -18
  10. package/dist/seed-CJB6INNH.js.map +1 -0
  11. package/dist/{seed-CSOeghww.js → seed-z1eQdEXy.js} +2 -2
  12. package/dist/{seed-CSOeghww.js.map → seed-z1eQdEXy.js.map} +1 -1
  13. package/dist/{seed.schema.config-Cz8esgav.js → seed.schema.config-C9CEFOxM.js} +15 -15
  14. package/dist/{seed.schema.config-Cz8esgav.js.map → seed.schema.config-C9CEFOxM.js.map} +1 -1
  15. package/dist/types/src/browser/index.d.ts +0 -1
  16. package/dist/types/src/browser/index.d.ts.map +1 -1
  17. package/dist/types/src/browser/react/db.d.ts +4 -0
  18. package/dist/types/src/browser/react/db.d.ts.map +1 -0
  19. package/dist/types/src/browser/react/index.d.ts +4 -53
  20. package/dist/types/src/browser/react/index.d.ts.map +1 -1
  21. package/dist/types/src/browser/react/item.d.ts +36 -0
  22. package/dist/types/src/browser/react/item.d.ts.map +1 -0
  23. package/dist/types/src/browser/react/property.d.ts +12 -0
  24. package/dist/types/src/browser/react/property.d.ts.map +1 -0
  25. package/dist/types/src/browser/react/services.d.ts +30 -0
  26. package/dist/types/src/browser/react/services.d.ts.map +1 -0
  27. package/dist/types/src/index.d.ts +1 -2
  28. package/dist/types/src/index.d.ts.map +1 -1
  29. package/dist/types/src/shared/helpers/index.d.ts +1 -1
  30. package/package.json +1 -1
  31. package/dist/events-DbpQM9qG.js.map +0 -1
  32. package/dist/index-D2_skdGT.js.map +0 -1
  33. package/dist/seed-DHOFK9DF.js.map +0 -1
  34. package/dist/seed-DM5koJUz.js.map +0 -1
@@ -1,28 +1,29 @@
1
- import { Type } from '@sinclair/typebox';
2
- import { useState, useEffect, useCallback, useRef } from 'react';
1
+ import { useImmer } from 'use-immer';
2
+ import { sql, count, max, eq, and, or, isNull, relations } from 'drizzle-orm';
3
+ import { useState, useCallback, useEffect, useRef } from 'react';
4
+ import debug from 'debug';
3
5
  import { fromCallback, setup, assign, createActor, waitFor, emit } from 'xstate';
4
6
  import { BehaviorSubject } from 'rxjs';
5
7
  import { fs, configureSingle } from '@zenfs/core';
6
- import { sql, count, max, eq, and, or, isNull, relations } from 'drizzle-orm';
7
- import { drizzle } from 'drizzle-orm/sqlite-proxy';
8
- import debug from 'debug';
9
- import 'dayjs';
10
- import { customAlphabet } from 'nanoid';
11
- import * as nanoIdDictionary from 'nanoid-dictionary';
12
8
  import { startCase, debounce, camelCase, orderBy } from 'lodash-es';
13
- import { sqliteTable, text, int, blob, check, unique } from 'drizzle-orm/sqlite-core';
9
+ import { immerable, produce } from 'immer';
10
+ import pluralize from 'pluralize';
11
+ import { useSelector } from '@xstate/react';
12
+ import { createBrowserInspector } from '@statelyai/inspect';
13
+ import 'reflect-metadata';
14
+ import { Type } from '@sinclair/typebox';
15
+ import Arweave from 'arweave';
16
+ import { WebAccess } from '@zenfs/dom';
17
+ import { drizzle } from 'drizzle-orm/sqlite-proxy';
14
18
  import { QueryClient } from '@tanstack/react-query';
15
19
  import { GraphQLClient } from 'graphql-request';
16
20
  import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister';
17
21
  import { persistQueryClient } from '@tanstack/react-query-persist-client';
18
22
  import path, { basename } from 'path';
19
- import { immerable } from 'immer';
20
- import pluralize from 'pluralize';
21
- import { createBrowserInspector } from '@statelyai/inspect';
22
- import { WebAccess } from '@zenfs/dom';
23
- import Arweave from 'arweave';
24
- import { useImmer } from 'use-immer';
25
- import { useSelector } from '@xstate/react';
23
+ import { sqliteTable, text, int, blob, check, unique } from 'drizzle-orm/sqlite-core';
24
+ import 'dayjs';
25
+ import { customAlphabet } from 'nanoid';
26
+ import * as nanoIdDictionary from 'nanoid-dictionary';
26
27
  import EventEmitter from 'eventemitter3';
27
28
 
28
29
  const isNode = () => {
@@ -213,14 +214,14 @@ const getSqlite = async () => {
213
214
  }
214
215
  };
215
216
 
216
- const logger$e = debug('app:db:actors');
217
+ const logger$g = debug('app:db:actors');
217
218
  let seedDb;
218
219
  let appDb;
219
220
  let sdkConfigDb;
220
221
  let sqliteWasmClient$1;
221
222
  const checkStatus = fromCallback(({ sendBack, input: { context } }) => {
222
223
  const { dbName, dirName } = context;
223
- logger$e('[db/actors] checkStatus context', context);
224
+ logger$g('[db/actors] checkStatus context', context);
224
225
  const pathToDir = `${BROWSER_FS_TOP_DIR}/${dirName}`;
225
226
  const pathToDbDir = `${pathToDir}/db`;
226
227
  const pathToDb = `${pathToDbDir}/${dbName}.sqlite3`;
@@ -251,7 +252,7 @@ const checkStatus = fromCallback(({ sendBack, input: { context } }) => {
251
252
  });
252
253
  });
253
254
  const connectToDb = fromCallback(({ sendBack, input: { context } }) => {
254
- logger$e('[db/actors] connectToDb context', context);
255
+ logger$g('[db/actors] connectToDb context', context);
255
256
  const { dbName, pathToDir } = context;
256
257
  let isConnecting = false;
257
258
  let dbId;
@@ -266,16 +267,16 @@ const connectToDb = fromCallback(({ sendBack, input: { context } }) => {
266
267
  }
267
268
  //@ts-ignore
268
269
  response = yield sqliteWasmClient$1('config-get', {});
269
- logger$e(response);
270
- logger$e('Running SQLite3 version', response.result.version.libVersion);
270
+ logger$g(response);
271
+ logger$g('Running SQLite3 version', response.result.version.libVersion);
271
272
  //@ts-ignore
272
273
  response = yield sqliteWasmClient$1('open', {
273
274
  filename: `file:${pathToDir}/db/${dbName}.sqlite3?vfs=opfs`,
274
275
  });
275
- logger$e(response);
276
+ logger$g(response);
276
277
  dbId = response.dbId;
277
278
  // logger(`dbId: ${dbId}`)
278
- logger$e('OPFS is available, created persisted database at', response.result.filename.replace(/^file:(.*?)\?vfs=opfs$/, '$1'));
279
+ logger$g('OPFS is available, created persisted database at', response.result.filename.replace(/^file:(.*?)\?vfs=opfs$/, '$1'));
279
280
  });
280
281
  const interval = setInterval(() => {
281
282
  // TODO: Add a timeout
@@ -395,7 +396,7 @@ const dbExec = (dbId_1, params_1, sql_1, dbName_1, ...args_1) => __awaiter(void
395
396
  });
396
397
  const migrate = fromCallback(({ sendBack, input: { context } }) => {
397
398
  const { pathToDbDir, dirName, dbId, dbName } = context;
398
- logger$e('[db/actors] migrate context', context);
399
+ logger$g('[db/actors] migrate context', context);
399
400
  const schemaGlobString = `${BROWSER_FS_TOP_DIR}/${dirName}/schema/*`;
400
401
  const isSeedDb = dbName === DB_NAME_SEED;
401
402
  const isAppDb = dbName === DB_NAME_APP;
@@ -675,7 +676,7 @@ const initialize$3 = fromCallback(({ sendBack, input: { context } }) => {
675
676
  }
676
677
  });
677
678
 
678
- const logger$d = debug('app:shared:helpers');
679
+ const logger$f = debug('app:shared:helpers');
679
680
  const { alphanumeric } = nanoIdDictionary;
680
681
  const generateId = () => {
681
682
  return customAlphabet(alphanumeric, 10)();
@@ -738,7 +739,7 @@ const convertTxIdToImageSrc = (txId) => __awaiter(void 0, void 0, void 0, functi
738
739
  const imageFilePath = `/files/images/${txId}`;
739
740
  const fileExists = yield fs.promises.exists(imageFilePath);
740
741
  if (!fileExists) {
741
- logger$d(`[ItemView] [updateImageSrc] ${imageFilePath} does not exist`);
742
+ logger$f(`[ItemView] [updateImageSrc] ${imageFilePath} does not exist`);
742
743
  return;
743
744
  }
744
745
  const uint = yield fs.promises.readFile(imageFilePath);
@@ -1517,7 +1518,7 @@ const getAddressesFromDb = () => __awaiter(void 0, void 0, void 0, function* ()
1517
1518
  return JSON.parse(addressArrayString);
1518
1519
  });
1519
1520
 
1520
- const logger$c = debug('app:property:actors:hydrateFromDb');
1521
+ const logger$e = debug('app:property:actors:hydrateFromDb');
1521
1522
  const hydrateFromDb = fromCallback(({ sendBack, input: { context } }) => {
1522
1523
  const { seedUid, seedLocalId, propertyName: propertyNameRaw, propertyValue, propertyRecordSchema, itemModelName, } = context;
1523
1524
  let propertyName = propertyNameRaw;
@@ -1585,23 +1586,23 @@ const hydrateFromDb = fromCallback(({ sendBack, input: { context } }) => {
1585
1586
  const firstRow = rows[0];
1586
1587
  const { localId, uid, propertyName: propertyNameFromDb, propertyValue: propertyValueFromDb, seedLocalId: seedLocalIdFromDb, seedUid: seedUidFromDb, schemaUid: schemaUidFromDb, refResolvedValue, refResolvedDisplayValue, } = firstRow;
1587
1588
  if (propertyName && !propertyNameFromDb) {
1588
- logger$c(`Property name from code is ${propertyName} but has not value in db ${propertyNameFromDb} for Property.${localId}`);
1589
+ logger$e(`Property name from code is ${propertyName} but has not value in db ${propertyNameFromDb} for Property.${localId}`);
1589
1590
  }
1590
1591
  if (propertyName &&
1591
1592
  propertyNameFromDb &&
1592
1593
  !propertyNameFromDb.includes(propertyName) &&
1593
1594
  !propertyName.includes(propertyNameFromDb) &&
1594
1595
  propertyNameFromDb !== propertyName) {
1595
- logger$c(`Property name from db ${propertyNameFromDb} does not match property name ${propertyName} for Property.${localId}`);
1596
+ logger$e(`Property name from db ${propertyNameFromDb} does not match property name ${propertyName} for Property.${localId}`);
1596
1597
  }
1597
1598
  if (propertyValue && propertyValueFromDb !== propertyValue) {
1598
- logger$c(`Property value from db ${propertyValueFromDb} does not match property value ${propertyValue} for Property.${localId}`);
1599
+ logger$e(`Property value from db ${propertyValueFromDb} does not match property value ${propertyValue} for Property.${localId}`);
1599
1600
  }
1600
1601
  if (seedLocalIdFromDb !== seedLocalId) {
1601
- logger$c(`Seed local id from db ${seedLocalIdFromDb} does not match seed local id ${seedLocalId} for Property.${localId}`);
1602
+ logger$e(`Seed local id from db ${seedLocalIdFromDb} does not match seed local id ${seedLocalId} for Property.${localId}`);
1602
1603
  }
1603
1604
  if (seedUidFromDb !== seedUid) {
1604
- logger$c(`Seed uid from db ${seedUidFromDb} does not match seed uid ${seedUid} for Property.${localId}`);
1605
+ logger$e(`Seed uid from db ${seedUidFromDb} does not match seed uid ${seedUid} for Property.${localId}`);
1605
1606
  }
1606
1607
  sendBack({
1607
1608
  type: 'updateContext',
@@ -1616,7 +1617,7 @@ const hydrateFromDb = fromCallback(({ sendBack, input: { context } }) => {
1616
1617
  renderValue: refResolvedDisplayValue,
1617
1618
  });
1618
1619
  if (propertyNameFromDb === 'storageTransactionId') {
1619
- const { Item } = yield import('./index-D2_skdGT.js');
1620
+ const { Item } = yield import('./index-CckG4Nv5.js');
1620
1621
  const item = yield Item.find({
1621
1622
  seedLocalId,
1622
1623
  modelName: itemModelName,
@@ -1634,7 +1635,7 @@ const hydrateFromDb = fromCallback(({ sendBack, input: { context } }) => {
1634
1635
  const renderValue = yield fs.promises
1635
1636
  .readFile(htmlFilePath, 'utf8')
1636
1637
  .catch((error) => {
1637
- logger$c('Error reading html file', error);
1638
+ logger$e('Error reading html file', error);
1638
1639
  });
1639
1640
  property
1640
1641
  .getService()
@@ -1715,7 +1716,7 @@ const getVersionData = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seed
1715
1716
 
1716
1717
  const eventEmitter = new EventEmitter();
1717
1718
 
1718
- const logger$b = debug('app:write');
1719
+ const logger$d = debug('app:write');
1719
1720
  const sendItemUpdateEvent = ({ modelName, seedLocalId, seedUid }) => {
1720
1721
  if (!modelName || (!seedLocalId && !seedUid)) {
1721
1722
  return;
@@ -1793,7 +1794,7 @@ const deleteItem = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seedLoca
1793
1794
  });
1794
1795
  const updateItemPropertyValue = (_a) => __awaiter(void 0, [_a], void 0, function* ({ propertyLocalId, propertyName, newValue, seedUid, seedLocalId, modelName, refSeedType, refResolvedValue, refResolvedDisplayValue, versionLocalId, versionUid, schemaUid, }) {
1795
1796
  if (!propertyLocalId && !seedLocalId) {
1796
- logger$b(`[db/write] [updateItemPropertyValue] no propertyLocalId or seedLocalId for property: ${propertyName}`);
1797
+ logger$d(`[db/write] [updateItemPropertyValue] no propertyLocalId or seedLocalId for property: ${propertyName}`);
1797
1798
  return;
1798
1799
  }
1799
1800
  let safeNewValue = newValue;
@@ -1832,7 +1833,7 @@ const updateItemPropertyValue = (_a) => __awaiter(void 0, [_a], void 0, function
1832
1833
  const schemaUid = mostRecentRecord[9];
1833
1834
  const easDataType = mostRecentRecord[10];
1834
1835
  if (propertyValueFromDb === newValue) {
1835
- logger$b(`[db/write] [updateItemPropertyValue] value is the same as most recent record for property: ${propertyNameFromDb}`);
1836
+ logger$d(`[db/write] [updateItemPropertyValue] value is the same as most recent record for property: ${propertyNameFromDb}`);
1836
1837
  return;
1837
1838
  }
1838
1839
  // This means we already have a local-only record so we should just update that one
@@ -2247,7 +2248,7 @@ const setModel = (modelName, model) => {
2247
2248
  };
2248
2249
 
2249
2250
  var _a$1;
2250
- const logger$a = debug('app:property:class');
2251
+ const logger$c = debug('app:property:class');
2251
2252
  const namesThatEndWithId = [];
2252
2253
  class ItemProperty {
2253
2254
  // private constructor(localIdOrUid) {
@@ -2295,7 +2296,7 @@ class ItemProperty {
2295
2296
  serviceInput.propertyValue = JSON.parse(propertyValue);
2296
2297
  }
2297
2298
  catch (e) {
2298
- logger$a('List property value is not JSON', e);
2299
+ logger$c('List property value is not JSON', e);
2299
2300
  }
2300
2301
  }
2301
2302
  const propertyNameSingular = pluralize(propertyName, 1);
@@ -2357,7 +2358,7 @@ class ItemProperty {
2357
2358
  this._service.start();
2358
2359
  }
2359
2360
  _updateResponseListener(event) {
2360
- logger$a(`[ItemProperty] [_updateResponseListener] [${this.itemModelName}.${this.seedLocalId}] ${this.propertyName} event`, event);
2361
+ logger$c(`[ItemProperty] [_updateResponseListener] [${this.itemModelName}.${this.seedLocalId}] ${this.propertyName} event`, event);
2361
2362
  }
2362
2363
  static create(props) {
2363
2364
  const { propertyName, seedLocalId, uid } = props;
@@ -2493,7 +2494,7 @@ class ItemProperty {
2493
2494
  }
2494
2495
  unload() {
2495
2496
  this._service.stop();
2496
- logger$a(`[XXXXXX] [ItemProperty] [${this.seedLocalId}] [unload] removing listener`, this._updateResponseEvent);
2497
+ logger$c(`[XXXXXX] [ItemProperty] [${this.seedLocalId}] [unload] removing listener`, this._updateResponseEvent);
2497
2498
  eventEmitter.removeListener(this._updateResponseEvent, this._updateResponseListener);
2498
2499
  }
2499
2500
  }
@@ -3782,7 +3783,7 @@ const getPropertiesForSeed = (seedLocalId, seedUid) => __awaiter(void 0, void 0,
3782
3783
  return propertiesData;
3783
3784
  });
3784
3785
 
3785
- const logger$9 = debug('app:db:queries:getItem');
3786
+ const logger$b = debug('app:db:queries:getItem');
3786
3787
  const getItemDataFromDb = (_a) => __awaiter(void 0, [_a], void 0, function* ({ modelName, seedLocalId, seedUid, }) {
3787
3788
  if (!seedLocalId && !seedUid) {
3788
3789
  throw new Error('[db/queries] [getItem] no seedLocalId or seedUid');
@@ -3790,7 +3791,7 @@ const getItemDataFromDb = (_a) => __awaiter(void 0, [_a], void 0, function* ({ m
3790
3791
  if (seedUid && !seedLocalId) {
3791
3792
  const seedData = yield getSeedData({ seedUid });
3792
3793
  if (!seedData) {
3793
- logger$9('[db/queries] [getItem] no seedData seedUid', seedUid);
3794
+ logger$b('[db/queries] [getItem] no seedData seedUid', seedUid);
3794
3795
  return;
3795
3796
  }
3796
3797
  seedLocalId = seedData.localId;
@@ -4218,7 +4219,7 @@ const fetchDbData = fromCallback(({ sendBack, input: { context } }) => {
4218
4219
  return () => { };
4219
4220
  });
4220
4221
 
4221
- const logger$8 = debug('app:allItemsActors:fetchSeeds');
4222
+ const logger$a = debug('app:allItemsActors:fetchSeeds');
4222
4223
  const fetchSeeds = fromCallback(({ sendBack, input: { context } }) => {
4223
4224
  const { queryVariables, modelName } = context;
4224
4225
  if (!queryVariables) {
@@ -4228,7 +4229,7 @@ const fetchSeeds = fromCallback(({ sendBack, input: { context } }) => {
4228
4229
  const _fetchSeeds = () => __awaiter(void 0, void 0, void 0, function* () {
4229
4230
  const queryKey = [`getSeeds${modelName}`];
4230
4231
  const cachedResults = queryClient.getQueryData(queryKey);
4231
- logger$8(`[allItemsActors] [fetchSeeds] cachedResults ${Date.now()}`, cachedResults);
4232
+ logger$a(`[allItemsActors] [fetchSeeds] cachedResults ${Date.now()}`, cachedResults);
4232
4233
  const results = yield queryClient.fetchQuery({
4233
4234
  queryKey,
4234
4235
  queryFn: () => __awaiter(void 0, void 0, void 0, function* () { return easClient.request(GET_SEEDS, queryVariables); }),
@@ -4799,1723 +4800,1831 @@ const getArweave = () => {
4799
4800
  });
4800
4801
  };
4801
4802
 
4802
- const logger$7 = debug('app:global:actors');
4803
- const initialize = fromCallback(({ sendBack, input: { event, context } }) => {
4804
- const { internalService, models, endpoints } = context;
4805
- const { addresses } = event;
4806
- let environment = 'browser';
4807
- if (isNode()) {
4808
- environment = 'node';
4809
- }
4810
- if (isReactNative()) {
4811
- environment = 'react-native';
4812
- }
4813
- let internalSubscription;
4814
- if (environment === 'browser' && models) {
4815
- const _initFileSystem = () => __awaiter(void 0, void 0, void 0, function* () {
4816
- return;
4817
- // return new Promise((resolve) => {
4818
- // })
4819
- });
4820
- const _initInternal = () => __awaiter(void 0, void 0, void 0, function* () {
4821
- return new Promise((resolve) => {
4822
- internalSubscription = internalService.subscribe((snapshot) => {
4823
- logger$7('[sdk] [internal] snapshot', snapshot);
4824
- if (snapshot.value === 'ready') {
4825
- resolve();
4826
- }
4827
- });
4828
- internalService.send({ type: 'init', endpoints, addresses });
4829
- });
4830
- });
4831
- _initFileSystem().then(() => {
4832
- logger$7('[global/actors] File system initialized');
4833
- });
4834
- _initInternal().then(() => {
4835
- logger$7('[global/actors] Internal initialized');
4836
- sendBack({ type: GLOBAL_INITIALIZING_INTERNAL_SERVICE_READY });
4837
- internalSubscription === null || internalSubscription === void 0 ? void 0 : internalSubscription.unsubscribe();
4838
- });
4839
- // _initEas().then(() => {
4840
- // logger('EAS initialized')
4841
- // })
4842
- }
4843
- sendBack({ type: GLOBAL_INITIALIZING_SEND_CONFIG, environment });
4844
- return () => {
4845
- internalSubscription === null || internalSubscription === void 0 ? void 0 : internalSubscription.unsubscribe();
4846
- };
4847
- });
4848
- const addModelsToDb = fromCallback(({ sendBack, input: { context } }) => {
4849
- const { models: models$1 } = context;
4850
- const _addModelsToDb = () => __awaiter(void 0, void 0, void 0, function* () {
4851
- var _a;
4852
- const sdkConfigDb = getSdkDb();
4853
- if (!models$1) {
4803
+ const logger$9 = debug('app:react:db');
4804
+ const useDbsAreReady = () => {
4805
+ const [dbsAreReady, setDbsAreReady] = useState(false);
4806
+ const update = useCallback(() => {
4807
+ if (dbsAreReady) {
4854
4808
  return;
4855
4809
  }
4856
- const { models: SeedModels } = yield import('./seed.schema.config-Cz8esgav.js');
4857
- const allModels = Object.assign(Object.assign({}, SeedModels), models$1);
4858
- let hasModelsInDb = false;
4859
- const schemaDefsByModelName = new Map();
4860
- for (const [modelName, _] of Object.entries(allModels)) {
4861
- logger$7('[helpers/db] [addModelsToInternalDb] starting modelName:', modelName);
4862
- let foundModel;
4863
- const foundModelsQuery = yield sdkConfigDb
4864
- .select()
4865
- .from(models)
4866
- .where(eq(models.name, modelName));
4867
- if (!foundModelsQuery || foundModelsQuery.length === 0) {
4868
- yield sdkConfigDb.insert(models).values({
4869
- name: modelName,
4810
+ setDbsAreReady(true);
4811
+ }, []);
4812
+ useEffect(() => {
4813
+ let globalSubscription;
4814
+ let internalSubscription;
4815
+ const _waitForDbs = () => __awaiter(void 0, void 0, void 0, function* () {
4816
+ const globalService = getGlobalService();
4817
+ const internalService = globalService.getSnapshot().context.internalService;
4818
+ if (!internalService) {
4819
+ logger$9('[useDbsAreReady] [useEffect] no internalService');
4820
+ globalSubscription = globalService.subscribe(({ context }) => {
4821
+ if (!internalSubscription && context && context.internalService) {
4822
+ globalSubscription === null || globalSubscription === void 0 ? void 0 : globalSubscription.unsubscribe();
4823
+ internalSubscription = context.internalService.subscribe((snapshot) => {
4824
+ if (snapshot.value === 'ready') {
4825
+ update();
4826
+ internalSubscription === null || internalSubscription === void 0 ? void 0 : internalSubscription.unsubscribe();
4827
+ }
4828
+ });
4829
+ }
4870
4830
  });
4871
- logger$7('[global/actors] [addModelsToDb] inserted model:', modelName);
4872
- const foundModels = yield sdkConfigDb
4873
- .select({
4874
- id: models.id,
4875
- name: models.name,
4876
- uid: modelUids.uid,
4877
- })
4878
- .from(models)
4879
- .leftJoin(modelUids, eq(models.id, modelUids.modelId))
4880
- .where(eq(models.name, modelName))
4881
- .limit(1);
4882
- foundModel = foundModels[0];
4883
- }
4884
- if (foundModelsQuery && foundModelsQuery.length > 0) {
4885
- foundModel = foundModelsQuery[0];
4831
+ return;
4886
4832
  }
4887
- if (!foundModel) {
4888
- hasModelsInDb = false;
4889
- break;
4833
+ const currentState = internalService.getSnapshot().value;
4834
+ if (currentState === 'ready') {
4835
+ update();
4836
+ return;
4890
4837
  }
4891
- schemaDefsByModelName.set(modelName, {
4892
- dbId: foundModel.id,
4893
- schemaDef: `bytes32 ${toSnakeCase(modelName)}`,
4838
+ internalSubscription = internalService.subscribe((snapshot) => {
4839
+ if (snapshot.value === 'ready') {
4840
+ update();
4841
+ internalSubscription === null || internalSubscription === void 0 ? void 0 : internalSubscription.unsubscribe();
4842
+ }
4894
4843
  });
4895
- }
4896
- if (!hasModelsInDb) {
4897
- return false;
4898
- }
4899
- const schemaDefs = Array.from(schemaDefsByModelName.values()).map(({ schemaDef }) => schemaDef);
4900
- const { schemas } = yield queryClient.fetchQuery({
4901
- queryKey: [`getSchemasVersion`],
4902
- queryFn: () => __awaiter(void 0, void 0, void 0, function* () {
4903
- return easClient.request(GET_SCHEMAS, {
4904
- where: {
4905
- schema: {
4906
- in: schemaDefs,
4907
- },
4908
- },
4909
- });
4910
- }),
4911
4844
  });
4912
- if (!schemas || schemas.length === 0) {
4913
- throw new Error(`No schemas found`);
4914
- }
4915
- for (const schema of schemas) {
4916
- const modelId = (_a = Array.from(schemaDefsByModelName.values()).find(({ schemaDef }) => schemaDef === schema.schema)) === null || _a === void 0 ? void 0 : _a.dbId;
4917
- if (!modelId) {
4918
- throw new Error(`No modelId found for schema ${schema.schema}`);
4845
+ _waitForDbs();
4846
+ return () => {
4847
+ if (globalSubscription) {
4848
+ globalSubscription.unsubscribe();
4919
4849
  }
4920
- yield sdkConfigDb
4921
- .insert(modelUids)
4922
- .values({
4923
- modelId,
4924
- uid: schema.id,
4925
- })
4926
- .onConflictDoNothing();
4927
- }
4928
- });
4929
- _addModelsToDb().then((hasModelsInDb) => {
4930
- sendBack({ type: GLOBAL_ADDING_MODELS_TO_DB_SUCCESS });
4931
- for (const [modelName, model] of Object.entries(models$1)) {
4932
- const service = context[`${modelName}Service`];
4933
- service.send({ type: 'modelsFound' });
4850
+ if (internalSubscription) {
4851
+ internalSubscription.unsubscribe();
4852
+ }
4853
+ };
4854
+ }, []);
4855
+ return {
4856
+ dbsAreReady,
4857
+ };
4858
+ };
4859
+
4860
+ const finalStrings = ['idle', 'ready', 'done', 'success'];
4861
+ const getServiceName = (service) => {
4862
+ let name = 'actor';
4863
+ if (service && service.uniqueKey) {
4864
+ name = service.uniqueKey;
4865
+ }
4866
+ if (service && !service.uniqueKey && service.logic && service.logic.config) {
4867
+ name = getServiceUniqueKey(service);
4868
+ }
4869
+ return name;
4870
+ };
4871
+ const getServiceValue = (service) => {
4872
+ let value;
4873
+ if (service && service.getSnapshot() && service.getSnapshot().value) {
4874
+ value = service.getSnapshot().value;
4875
+ }
4876
+ if (getServiceName(service) === 'global') {
4877
+ if (value &&
4878
+ typeof value === 'object' &&
4879
+ Object.keys(value).length > 0 &&
4880
+ Object.keys(value)[0] === 'initialized') {
4881
+ value = 'ready';
4934
4882
  }
4935
- eventEmitter.emit('syncDbWithEas');
4936
- return;
4937
- });
4938
- return () => { };
4939
- });
4940
- const getSchemaForModel = fromCallback(({ sendBack, input: { context, event } }) => {
4941
- const { modelName } = event;
4942
- if (!modelName) {
4943
- console.warn('No modelName found');
4944
- return;
4945
4883
  }
4946
- const { models } = context;
4947
- if (!models) {
4948
- console.warn('No models found');
4884
+ return value;
4885
+ };
4886
+ const getServiceUniqueKey = (service) => {
4887
+ if (!service || !service.logic || !service.logic.config) {
4949
4888
  return;
4950
4889
  }
4951
- const model = Object.entries(models).find(([modelNameFromConfig]) => modelNameFromConfig === modelName);
4952
- if (!model) {
4953
- throw new Error(`Model ${modelName} not found`);
4890
+ const config = service.logic.config;
4891
+ if (!config.id) {
4892
+ return;
4954
4893
  }
4955
- logger$7('[service/actor] [getSchemaForModel] model:', model);
4956
- sendBack({ type: 'schemaForModel', schema: model.schema });
4957
- return () => { };
4958
- });
4959
-
4960
- class SqliteConnectionManager {
4961
- constructor(sqliteModule, idleTimeout = 300000) {
4962
- // Default idle timeout: 5 minutes
4963
- this.sqliteModule = sqliteModule;
4964
- this.idleTimeout = idleTimeout;
4965
- this.databases = {};
4966
- this.idleTimers = {};
4894
+ let uniqueKey = config.id;
4895
+ if (config.id.includes('@seedSdk/')) {
4896
+ uniqueKey = config.id.match(/^.*@seedSdk\/(\w+)[\.\w]*/)[1];
4967
4897
  }
4968
- resetIdleTimer(dbName) {
4969
- if (this.idleTimers[dbName]) {
4970
- clearTimeout(this.idleTimers[dbName]);
4898
+ const snapshot = service.getSnapshot();
4899
+ if (snapshot) {
4900
+ const context = snapshot.context;
4901
+ if (context && context.dbName) {
4902
+ uniqueKey = context.dbName;
4903
+ }
4904
+ if (context && context.modelNamePlural) {
4905
+ uniqueKey = context.modelNamePlural;
4906
+ }
4907
+ if (context && context.modelName) {
4908
+ uniqueKey = pluralize(context.modelName.toLowerCase());
4971
4909
  }
4972
- this.idleTimers[dbName] = setTimeout(() => {
4973
- this.closeConnection(dbName);
4974
- }, this.idleTimeout);
4975
4910
  }
4976
- getConnection(dbName) {
4977
- return __awaiter(this, void 0, void 0, function* () {
4978
- if (this.databases[dbName]) {
4979
- this.resetIdleTimer(dbName);
4980
- return this.databases[dbName];
4981
- }
4982
- const db = new this.sqliteModule();
4983
- yield db.open(dbName);
4984
- this.databases[dbName] = db;
4985
- this.resetIdleTimer(dbName);
4986
- return db;
4987
- });
4988
- }
4989
- execute(dbName_1, sql_1) {
4990
- return __awaiter(this, arguments, void 0, function* (dbName, sql, params = []) {
4991
- const db = yield this.getConnection(dbName);
4992
- const result = db.exec(sql, params);
4993
- this.resetIdleTimer(dbName);
4994
- return result;
4995
- });
4996
- }
4997
- closeConnection(dbName) {
4998
- if (this.databases[dbName]) {
4999
- this.databases[dbName].close();
5000
- delete this.databases[dbName];
5001
- if (this.idleTimers[dbName]) {
5002
- clearTimeout(this.idleTimers[dbName]);
5003
- delete this.idleTimers[dbName];
4911
+ return uniqueKey;
4912
+ };
4913
+ const useServices = () => {
4914
+ const [actors, setActors] = useState([]);
4915
+ const [percentComplete, setPercentComplete] = useState(5);
4916
+ const actorsMap = new Map();
4917
+ useEffect(() => {
4918
+ const globalServiceListener = (event) => {
4919
+ if (event.actorRef &&
4920
+ event.actorRef.logic &&
4921
+ event.actorRef.logic.config) {
4922
+ const uniqueKey = getServiceUniqueKey(event.actorRef);
4923
+ if (!uniqueKey) {
4924
+ return;
4925
+ }
4926
+ event.actorRef.uniqueKey = uniqueKey;
4927
+ actorsMap.set(uniqueKey, event.actorRef);
4928
+ let actorsArray = Array.from(actorsMap.values());
4929
+ actorsArray = orderBy(actorsArray, (a) => a.logic.config.id, ['asc']);
4930
+ setActors(produce(actors, (draft) => {
4931
+ return actorsArray;
4932
+ }));
5004
4933
  }
4934
+ };
4935
+ eventEmitter.addListener('inspect.globalService', globalServiceListener);
4936
+ return () => {
4937
+ eventEmitter.removeListener('inspect.globalService', globalServiceListener);
4938
+ };
4939
+ }, []);
4940
+ useEffect(() => {
4941
+ const globalService = actors.find((actor) => getServiceName(actor) === 'global');
4942
+ const internalService = actors.find((actor) => getServiceName(actor) === 'internal');
4943
+ if (!globalService || !internalService) {
4944
+ return;
5005
4945
  }
5006
- }
5007
- }
4946
+ if (getServiceValue(globalService) === 'ready' &&
4947
+ getServiceValue(internalService) === 'ready') {
4948
+ const denominator = actors.length;
4949
+ const finishedActors = actors.filter((actor) => {
4950
+ const value = getServiceValue(actor);
4951
+ return finalStrings.includes(value);
4952
+ });
4953
+ const numerator = finishedActors.length;
4954
+ const percentComplete = (numerator / denominator) * 100;
4955
+ setPercentComplete(percentComplete);
4956
+ }
4957
+ }, [actors]);
4958
+ return {
4959
+ services: actors,
4960
+ percentComplete,
4961
+ };
4962
+ };
4963
+ const useGlobalServiceStatus = () => {
4964
+ const globalService = getGlobalService();
4965
+ const status = useSelector(globalService, (snapshot) => {
4966
+ return snapshot.value;
4967
+ });
4968
+ const internalStatus = useSelector(globalService.getSnapshot().context.internalService, (snapshot) => {
4969
+ if (!snapshot) {
4970
+ return;
4971
+ }
4972
+ return snapshot.value;
4973
+ });
4974
+ useSelector(globalService, (snapshot) => {
4975
+ return snapshot.context.internalService;
4976
+ });
4977
+ return {
4978
+ status,
4979
+ internalStatus,
4980
+ };
4981
+ };
5008
4982
 
5009
- const logger$6 = debug('app:services:internal:helpers');
5010
- /**
5011
- * Recursively create directories if they don't exist.
5012
- * @param {string} dirPath - The directory path to create.
5013
- */
5014
- const createDirectories = (dirPath) => __awaiter(void 0, void 0, void 0, function* () {
5015
- const dirPathExists = yield fs.promises.exists(dirPath);
5016
- if (dirPathExists) {
5017
- return;
5018
- }
5019
- const parentDir = path.dirname(dirPath);
5020
- const parentDirExists = yield fs.promises.exists(parentDir);
5021
- if (!parentDirExists) {
5022
- yield createDirectories(parentDir);
5023
- }
5024
- yield fs.promises.mkdir(dirPath, { recursive: true });
5025
- });
5026
- let busy = false;
5027
- const downloadFile = (url, localFilePath) => __awaiter(void 0, void 0, void 0, function* () {
5028
- try {
5029
- const response = yield fetch(url);
5030
- const fileData = yield response.text().catch((error) => {
5031
- console.error(`Failed to parse text from ${url}:`, error);
5032
- });
5033
- if (!fileData) {
5034
- console.error(`No file data from ${url}`);
4983
+ const logger$8 = debug('app:react:item');
4984
+ const useItem = ({ modelName, seedLocalId, seedUid }) => {
4985
+ const [item, setItem] = useImmer(undefined);
4986
+ const [itemSubscription, setItemSubscription] = useState();
4987
+ const { status, internalStatus } = useGlobalServiceStatus();
4988
+ const isReadingDb = useRef(false);
4989
+ const itemStatus = useSelector(item === null || item === void 0 ? void 0 : item.getService(), (snapshot) => snapshot === null || snapshot === void 0 ? void 0 : snapshot.value);
4990
+ const updateItem = useCallback((newItem) => {
4991
+ setItem(() => newItem);
4992
+ }, []);
4993
+ const readFromDb = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
4994
+ if (isReadingDb.current ||
4995
+ internalStatus !== 'ready' ||
4996
+ (!seedUid && !seedLocalId)) {
5035
4997
  return;
5036
4998
  }
5037
- const localDirPath = path.dirname(localFilePath);
5038
- if (busy) {
4999
+ isReadingDb.current = true;
5000
+ const foundItem = yield Item.find({
5001
+ modelName,
5002
+ seedLocalId,
5003
+ seedUid,
5004
+ });
5005
+ if (!foundItem) {
5006
+ logger$8('[useItem] [getItemFromDb] no item found', modelName, seedLocalId);
5039
5007
  return;
5040
5008
  }
5041
- busy = true;
5042
- yield createDirectories(localDirPath);
5043
- const filename = path.basename(localFilePath);
5044
- const regex = /(\d+)[\w_]+\.(sql|json)$/;
5045
- const match = filename.match(regex);
5046
- let migrationNumber;
5047
- if (match && match.length > 1) {
5048
- migrationNumber = match[1];
5009
+ updateItem(foundItem);
5010
+ isReadingDb.current = false;
5011
+ }), [internalStatus]);
5012
+ useEffect(() => {
5013
+ if (internalStatus === 'ready') {
5014
+ readFromDb();
5049
5015
  }
5050
- if (migrationNumber) {
5051
- const filesInDir = yield fs.promises.readdir(localDirPath);
5052
- for (const file of filesInDir) {
5053
- if (file === filename) {
5054
- continue;
5055
- }
5056
- const innerMatch = file.match(regex);
5057
- let existingFileMigrationNumber;
5058
- if (innerMatch && innerMatch.length > 1) {
5059
- existingFileMigrationNumber = innerMatch[1];
5060
- }
5061
- if (migrationNumber &&
5062
- existingFileMigrationNumber &&
5063
- existingFileMigrationNumber === migrationNumber) {
5064
- yield fs.promises.unlink(path.join(localDirPath, file));
5016
+ }, [internalStatus, status]);
5017
+ useEffect(() => {
5018
+ if (item && !itemSubscription) {
5019
+ const subscription = item.subscribe((_) => __awaiter(void 0, void 0, void 0, function* () {
5020
+ const newItem = yield Item.find({ modelName, seedLocalId, seedUid });
5021
+ if (!newItem) {
5022
+ logger$8('[useItem] [itemSubscription] no item found', modelName, seedLocalId);
5023
+ return;
5065
5024
  }
5066
- }
5067
- }
5068
- // if (filename === '_journal.json') {
5069
- // const exists = await fs.promises.exists(localFilePath)
5070
- // if (exists) {
5071
- // await fs.promises.rm(localFilePath)
5072
- // }
5073
- // await fs.promises.writeFile(localFilePath, fileData)
5074
- // }
5075
- //
5076
- // if (filename !== '_journal.json') {
5077
- // await fs.promises.writeFile(localFilePath, fileData)
5078
- // }
5079
- yield fs.promises.writeFile(localFilePath, fileData);
5080
- }
5081
- catch (error) {
5082
- if (JSON.stringify(error).includes('File exists')) {
5083
- yield fs.promises.readFile(localFilePath, 'utf-8');
5025
+ setItem(() => newItem);
5026
+ }));
5027
+ setItemSubscription(subscription);
5084
5028
  }
5085
- logger$6(`[Error] Failed to download file from ${url}:`, error);
5086
- }
5087
- busy = false;
5088
- });
5089
- const fetchDirectory = (url) => __awaiter(void 0, void 0, void 0, function* () {
5090
- const response = yield fetch(url);
5091
- return response.json();
5092
- });
5093
- const fetchFilesRecursively = (url, localPath, fileList) => __awaiter(void 0, void 0, void 0, function* () {
5094
- try {
5095
- for (const file of fileList) {
5096
- const fileUrl = `${url}/${file}`;
5097
- const fileLocalPath = path.join(localPath, file);
5098
- // logger(`[fetchFilesRecursively] fileUrl: ${fileUrl}`)
5099
- // logger(`[fetchFilesRecursively] fileLocalPath: ${fileLocalPath}`)
5100
- yield downloadFile(fileUrl, fileLocalPath);
5029
+ return () => {
5030
+ itemSubscription === null || itemSubscription === void 0 ? void 0 : itemSubscription.unsubscribe();
5031
+ };
5032
+ }, [item, itemSubscription]);
5033
+ useEffect(() => {
5034
+ const seedId = seedUid || seedLocalId;
5035
+ eventEmitter.addListener(`item.${modelName}.${seedId}.update`, readFromDb);
5036
+ return () => {
5037
+ eventEmitter.removeListener(`item.${modelName}.${seedId}.update`, readFromDb);
5038
+ };
5039
+ }, []);
5040
+ return {
5041
+ item,
5042
+ itemStatus,
5043
+ };
5044
+ };
5045
+ const useItems = ({ modelName, options }) => {
5046
+ const [items, setItems] = useImmer([]);
5047
+ const [isReadingDb, setIsReadingDb] = useState(false);
5048
+ const [isInitialized, setIsInitialized] = useState(false);
5049
+ const { dbsAreReady } = useDbsAreReady();
5050
+ const modelNameRef = useRef(modelName);
5051
+ const readFromDb = useCallback((event) => __awaiter(void 0, void 0, void 0, function* () {
5052
+ if (!event ||
5053
+ !event.modelName ||
5054
+ event.modelName !== modelNameRef.current ||
5055
+ isReadingDb) {
5056
+ return;
5101
5057
  }
5102
- }
5103
- catch (error) {
5104
- console.error(`Failed to fetch files from ${url}:`, error);
5105
- }
5106
- });
5107
- const confirmFilesExist = (filePaths) => __awaiter(void 0, void 0, void 0, function* () {
5108
- let everythingDownloaded = false;
5109
- for (const filePath of filePaths) {
5110
- const fullPath = path.join(BROWSER_FS_TOP_DIR, filePath);
5111
- everythingDownloaded = yield fs.promises.exists(fullPath);
5112
- }
5113
- if (!everythingDownloaded) {
5114
- setTimeout(() => __awaiter(void 0, void 0, void 0, function* () {
5115
- yield confirmFilesExist(filePaths);
5116
- }), 500);
5117
- }
5118
- });
5119
- const syncDbFiles = (_a) => __awaiter(void 0, [_a], void 0, function* ({ filePaths, files }) {
5120
- const fileList = yield fetchDirectory(filePaths);
5121
- yield fetchFilesRecursively(files, BROWSER_FS_TOP_DIR, fileList);
5122
- yield confirmFilesExist(fileList);
5123
- logger$6('[syncDbFiles] Files synced!');
5124
- });
5125
-
5126
- const logger$5 = debug('app:files:download');
5127
- const downloadAllFilesRequestHandler = (_a) => __awaiter(void 0, [_a], void 0, function* ({ endpoints, eventId, }) {
5128
- yield syncDbFiles(endpoints);
5129
- eventEmitter.emit('fs.downloadAll.success', { eventId });
5130
- eventEmitter.emit('fs.downloadAllBinary.request', { endpoints });
5131
- });
5132
- const downloadAllFilesBinaryRequestHandler = () => __awaiter(void 0, void 0, void 0, function* () {
5133
- const addresses = yield getAddressesFromDb();
5134
- const { filesMetadata } = yield queryClient.fetchQuery({
5135
- queryKey: ['getFilesMetadata', ...addresses],
5136
- queryFn: () => __awaiter(void 0, void 0, void 0, function* () {
5137
- return easClient.request(GET_FILES_METADATA, {
5138
- where: {
5139
- attester: {
5140
- in: addresses,
5141
- },
5142
- schema: {
5143
- is: {
5144
- id: {
5145
- equals: '0x55fdefb36fcbbaebeb7d6b41dc3a1a9666e4e42154267c889de064faa7ede517',
5146
- },
5147
- },
5148
- },
5149
- },
5150
- });
5151
- }),
5152
- });
5153
- if (!(yield fs.promises.exists('/files'))) {
5154
- yield fs.promises.mkdir('/files', { recursive: true });
5155
- }
5156
- if (!(yield fs.promises.exists('/files/html'))) {
5157
- yield fs.promises.mkdir('/files/html', { recursive: true });
5158
- }
5159
- if (!(yield fs.promises.exists('/files/json'))) {
5160
- yield fs.promises.mkdir('/files/json', { recursive: true });
5161
- }
5162
- if (!(yield fs.promises.exists('/files/images'))) {
5163
- yield fs.promises.mkdir('/files/images', { recursive: true });
5164
- }
5165
- const seedDb = getDb(DB_NAME_SEED);
5166
- if (!seedDb) {
5167
- console.warn('[fetchAll/actors] [fetchAllBinaryData] seedDb not available');
5168
- return [];
5169
- }
5170
- for (const fileMetadata of filesMetadata) {
5171
- const json = JSON.parse(fileMetadata.decodedDataJson);
5172
- const transactionId = json[0].value.value;
5173
- const excludedTransactionsQuery = yield seedDb
5174
- .select()
5175
- .from(appState)
5176
- .where(eq(appState.key, 'excludedTransactions'));
5177
- let excludedTransactions = new Set();
5178
- if (excludedTransactionsQuery && excludedTransactionsQuery.length === 1) {
5179
- const valueString = excludedTransactionsQuery[0].value;
5180
- if (valueString) {
5181
- const excludedTransactionsArray = JSON.parse(valueString);
5182
- excludedTransactions = new Set(excludedTransactionsArray);
5183
- }
5184
- }
5185
- if (excludedTransactions.has(transactionId)) {
5186
- continue;
5187
- }
5188
- const arweave = getArweave();
5189
- if (!arweave) {
5190
- console.warn('[fetchAll/actors] [fetchAllBinaryData] arweave not available');
5191
- return [];
5192
- }
5193
- try {
5194
- const res = yield fetch(`https://${ARWEAVE_HOST}/tx/${transactionId}/status`);
5195
- if (res.status !== 200) {
5196
- logger$5(`[fetchAll/actors] [fetchAllBinaryData] error fetching transaction data for ${transactionId}`);
5197
- excludedTransactions.add(transactionId);
5198
- yield writeAppState(seedDb, 'excludedTransactions', JSON.stringify(Array.from(excludedTransactions)));
5199
- continue;
5200
- }
5201
- const dataString = yield arweave.transactions
5202
- .getData(transactionId, {
5203
- decode: true,
5204
- string: true,
5205
- })
5206
- .catch((error) => {
5207
- console.error(`[fetchAll/actors] [fetchAllBinaryData] error fetching transaction data for ${transactionId}`, error);
5208
- });
5209
- if (!dataString) {
5210
- logger$5(`[fetchAll/actors] [fetchAllBinaryData] transaction ${transactionId} data not found`);
5211
- }
5212
- let contentType = identifyString(dataString);
5213
- if (contentType !== 'json' &&
5214
- contentType !== 'base64' &&
5215
- contentType !== 'html') {
5216
- const possibleImageType = getImageDataType(dataString);
5217
- if (!possibleImageType) {
5218
- logger$5(`[fetchAll/actors] [fetchAllBinaryData] transaction ${transactionId} data not in expected format: ${possibleImageType}`);
5219
- continue;
5220
- }
5221
- contentType = possibleImageType;
5222
- }
5223
- if (contentType === 'url') {
5224
- const url = dataString;
5225
- const response = yield fetch(url);
5226
- if (!response.ok) {
5227
- throw new Error(`Failed to fetch image: ${response.statusText}`);
5228
- }
5229
- // Get the image as a Blob
5230
- const blob = yield response.blob();
5231
- const buffer = yield blob.arrayBuffer();
5232
- const bufferUint8Array = new Uint8Array(buffer);
5233
- // Extract the file extension from the URL
5234
- const extensionMatch = url.match(/\.(jpg|jpeg|png|gif|bmp|webp|svg)$/i);
5235
- if (!extensionMatch) {
5236
- throw new Error('Unable to determine the file extension from the URL.');
5237
- }
5238
- const fileExtension = extensionMatch[0]; // e.g., ".jpg"
5239
- // Set the file name (you can customize this)
5240
- // const fileNameFromUrl = `${transactionId}${fileExtension}`
5241
- yield fs.promises.writeFile(`/files/images/${transactionId}`, bufferUint8Array, {
5242
- encoding: 'binary',
5243
- });
5244
- continue;
5245
- }
5246
- const mimeType = getMimeType(dataString);
5247
- let fileName = transactionId;
5248
- if (contentType === 'base64') {
5249
- if (mimeType) {
5250
- fileName += `.${mimeType}`;
5251
- }
5252
- // Remove the Base64 header if it exists (e.g., "data:image/png;base64,")
5253
- const base64Data = dataString.split(',').pop() || '';
5254
- // Decode the Base64 string to binary
5255
- const binaryString = atob(base64Data);
5256
- const length = binaryString.length;
5257
- const binaryData = new Uint8Array(length);
5258
- for (let i = 0; i < length; i++) {
5259
- binaryData[i] = binaryString.charCodeAt(i);
5260
- }
5261
- yield fs.promises.writeFile(`/files/images/${fileName}`, binaryData, {
5262
- encoding: 'binary',
5263
- });
5264
- // if (dataUint8Array && dataUint8Array instanceof Uint8Array) {
5265
- // await fs.promises.writeFile(
5266
- // `/files/images/${fileName}`,
5267
- // dataUint8Array,
5268
- // )
5269
- // }
5270
- }
5271
- if (contentType === 'html') {
5272
- fileName += '.html';
5273
- yield fs.promises.writeFile(`/files/html/${fileName}`, dataString);
5274
- }
5275
- if (contentType === 'json') {
5276
- fileName += '.json';
5277
- yield fs.promises.writeFile(`/files/json/${fileName}`, dataString);
5278
- }
5279
- }
5280
- catch (error) {
5281
- logger$5(error);
5282
- }
5283
- }
5284
- });
5285
-
5286
- let isInitialized = false;
5287
- const fsInitHandler = (_) => __awaiter(void 0, void 0, void 0, function* () {
5288
- if (isInitialized) {
5289
- eventEmitter.emit('fs.init.response', { success: true });
5290
- return;
5291
- }
5292
- try {
5293
- const handle = yield navigator.storage.getDirectory();
5294
- // await configure({ backend: WebAccess, handle })
5295
- yield configureSingle({
5296
- backend: WebAccess,
5297
- handle,
5298
- });
5299
- isInitialized = true;
5300
- eventEmitter.emit('fs.init.response', { success: true });
5301
- }
5302
- catch (e) {
5303
- if (!isInitialized) {
5304
- console.error('[fs.init] error initializing fs', e);
5305
- eventEmitter.emit('fs.init.response', {
5306
- success: false,
5307
- error: e,
5058
+ setIsReadingDb(true);
5059
+ const allItems = yield Item.all(modelNameRef.current);
5060
+ setItems(() => allItems);
5061
+ setIsReadingDb(false);
5062
+ }), [modelName]);
5063
+ useEffect(() => {
5064
+ if (dbsAreReady && !isInitialized) {
5065
+ const _fetchItems = () => __awaiter(void 0, void 0, void 0, function* () {
5066
+ yield readFromDb({ modelName });
5067
+ setIsInitialized(true);
5308
5068
  });
5069
+ _fetchItems();
5309
5070
  }
5310
- // TODO: We can ignore this for now but should figure out if this is being called excessively
5311
- }
5312
- });
5313
- let areReady = false;
5314
- const setupFsListeners = () => {
5315
- eventEmitter.addListener('fs.downloadAll.request', downloadAllFilesRequestHandler);
5316
- eventEmitter.addListener('fs.downloadAllBinary.request', downloadAllFilesBinaryRequestHandler);
5317
- eventEmitter.addListener('fs.init', fsInitHandler);
5318
- areReady = true;
5319
- };
5320
- const areFsListenersReady = () => {
5321
- return areReady;
5322
- };
5323
- const isFsInitialized = () => {
5324
- return isInitialized;
5071
+ }, [dbsAreReady, isInitialized]);
5072
+ useEffect(() => {
5073
+ eventEmitter.addListener('item.requestAll', readFromDb);
5074
+ return () => {
5075
+ eventEmitter.removeListener('item.requestAll');
5076
+ };
5077
+ }, []);
5078
+ return {
5079
+ items: orderBy(items, [
5080
+ (item) => item.lastVersionPublishedAt ||
5081
+ item.attestationCreatedAt ||
5082
+ item.createdAt,
5083
+ ], ['desc']).slice(0, 10),
5084
+ isReadingDb,
5085
+ isInitialized,
5086
+ };
5325
5087
  };
5326
-
5327
- const logger$4 = debug('app:internal:actors');
5328
- let sqliteWasmClient;
5329
- let manager;
5330
- const validateInput = fromCallback(({ sendBack, input: { event } }) => {
5331
- const { endpoints, addresses } = event;
5332
- if (typeof window === 'undefined') {
5333
- throw new Error('validateInput called from non-browser context');
5334
- }
5335
- if (!endpoints || !endpoints.filePaths || !endpoints.files) {
5336
- throw new Error('validateInput called with invalid endpoints');
5337
- }
5338
- if (!addresses || !addresses.length) {
5339
- throw new Error('validateInput called with invalid addresses');
5340
- }
5341
- const _validateInput = () => __awaiter(void 0, void 0, void 0, function* () {
5342
- sendBack({
5343
- type: INTERNAL_VALIDATING_INPUT_SUCCESS,
5344
- endpoints,
5345
- addresses,
5346
- });
5347
- });
5348
- _validateInput().then(() => {
5349
- return;
5350
- });
5351
- });
5352
- const prepareDb = fromCallback(({ sendBack, input: { event, context } }) => {
5353
- const _prepareDb = () => __awaiter(void 0, void 0, void 0, function* () {
5354
- if (typeof window === 'undefined') {
5355
- return;
5088
+ const useItemIsReady = () => {
5089
+ const [itemListenersReady, setItemListenersReady] = useState(false);
5090
+ const itemEventListenersHandler = useCallback((_) => {
5091
+ setItemListenersReady(true);
5092
+ }, []);
5093
+ useEffect(() => {
5094
+ const areReady = getAreItemEventHandlersReady();
5095
+ if (areReady) {
5096
+ itemEventListenersHandler(true);
5356
5097
  }
5357
- sqliteWasmClient = yield getSqlite();
5358
- });
5359
- const interval = setInterval(() => {
5360
- // TODO: Add a timeout
5361
- // TODO: Add a cancel token to the promise so we can prevent more loops starting while we're checking the successful outcome
5362
- if (sqliteWasmClient) {
5363
- clearInterval(interval);
5364
- manager = new SqliteConnectionManager(sqliteWasmClient);
5365
- sendBack({ type: 'prepareDbSuccess', manager });
5098
+ eventEmitter.addListener('item.events.setupAllItemsEventHandlers', itemEventListenersHandler);
5099
+ return () => {
5100
+ eventEmitter.removeListener('item.events.setupAllItemsEventHandlers');
5101
+ };
5102
+ }, []);
5103
+ return {
5104
+ isReady: itemListenersReady,
5105
+ };
5106
+ };
5107
+ const useCreateItem = (modelName) => {
5108
+ const [isCreatingItem, setIsCreatingItem] = useState(false);
5109
+ const { isReady } = useItemIsReady();
5110
+ const createItem = useCallback((itemData) => __awaiter(void 0, void 0, void 0, function* () {
5111
+ if (!isReady) {
5112
+ console.error(`[useCreateItem] [createItem] called before listeners are ready`, itemData);
5366
5113
  return;
5367
5114
  }
5368
- _prepareDb().then(() => {
5115
+ if (isCreatingItem) {
5116
+ // TODO: should we setup a queue for this?
5117
+ console.error(`[useCreateItem] [createItem] already creating item`, itemData);
5369
5118
  return;
5370
- });
5371
- }, 500);
5372
- return () => {
5373
- if (interval) {
5374
- clearInterval(interval);
5375
5119
  }
5120
+ setIsCreatingItem(true);
5121
+ const { seedLocalId } = yield createNewItem(Object.assign({ modelName }, itemData));
5122
+ yield Item.find({ modelName, seedLocalId });
5123
+ eventEmitter.emit('item.requestAll', { modelName });
5124
+ setIsCreatingItem(false);
5125
+ }), [isCreatingItem, isReady]);
5126
+ return {
5127
+ createItem,
5128
+ isCreatingItem,
5376
5129
  };
5377
- });
5378
- const configureFs = fromCallback(({ sendBack, input: { context } }) => {
5379
- const { endpoints, seedDbService, appDbService, sdkDbService } = context;
5380
- logger$4('[internal/actors] [configureFs] Configuring FS');
5381
- const services = [seedDbService, appDbService, sdkDbService];
5382
- const _configureFs = () => __awaiter(void 0, void 0, void 0, function* () {
5383
- logger$4('[internal/actors] [configureFs] calling _configureFs');
5384
- logger$4('[internal/actors] [configureFs] areFsListenersReady:', areFsListenersReady());
5385
- logger$4('[internal/actors] [configureFs] isFsInitialized:', isFsInitialized());
5386
- yield waitForEvent({
5387
- req: {
5388
- eventLabel: 'fs.downloadAll.request',
5389
- data: { endpoints },
5390
- },
5391
- res: {
5392
- eventLabel: 'fs.downloadAll.success',
5393
- },
5394
- });
5395
- yield Promise.all(services.map((service) => __awaiter(void 0, void 0, void 0, function* () {
5396
- const { dirName } = service.getSnapshot().context;
5397
- const journalPath = `${BROWSER_FS_TOP_DIR}/${dirName}/db/meta/_journal.json`;
5398
- const journalExists = yield fs.promises.exists(journalPath);
5399
- if (journalExists) {
5400
- service.send({ type: DB_WAITING_FOR_FILES_RECEIVED });
5401
- }
5402
- // return new Promise<void>((resolve) => {
5403
- // const interval = setInterval(() => {
5404
- // journalExistsSync = fs.existsSync(journalPath)
5405
- // logger(
5406
- // '[internal/actors] [configureFs] journalExistsSync:',
5407
- // journalExistsSync,
5408
- // )
5409
- // if (journalExistsSync) {
5410
- // service.send({ type: DB_WAITING_FOR_FILES_RECEIVED })
5411
- // clearInterval(interval)
5412
- // resolve()
5413
- // }
5414
- // }, 200)
5415
- // })
5416
- })));
5417
- logger$4('[internal/actors] [configureFs] fs configured!');
5418
- });
5419
- // Some of our dependencies use fs sync functions, which don't work with
5420
- // OPFS. ZenFS creates an async cache of all files so that the sync functions
5421
- // work, but we have to wait for it to be built. Otherwise things like
5422
- // drizzleMigrate will fail since they can't see the migration files yet.
5423
- _configureFs().then(() => {
5424
- sendBack({ type: INTERNAL_CONFIGURING_FS_SUCCESS });
5425
- return;
5426
- });
5427
- return () => { };
5428
- });
5429
- const loadSeedDb = fromCallback(({ sendBack, input: { context } }) => {
5430
- const { seedDbService } = context;
5431
- if (seedDbService.getSnapshot().value === 'ready') {
5432
- sendBack({ type: INTERNAL_LOADING_SEED_DB_SUCCESS });
5433
- return () => { };
5434
- }
5435
- let subscription;
5436
- const _loadSeedDb = () => __awaiter(void 0, void 0, void 0, function* () {
5437
- yield waitFor(seedDbService, (snapshot) => snapshot.value === 'ready');
5438
- subscription = seedDbService.subscribe({
5439
- next: (snapshot) => {
5440
- sendBack({ type: DB_ON_SNAPSHOT, dbName: DB_NAME_SEED, snapshot });
5441
- },
5442
- });
5443
- });
5444
- _loadSeedDb().then(() => {
5445
- sendBack({ type: INTERNAL_LOADING_SEED_DB_SUCCESS });
5130
+ };
5131
+ const useDeleteItem = () => {
5132
+ const [isDeletingItem, setIsDeletingItem] = useState(false);
5133
+ const destroy = useCallback((item) => __awaiter(void 0, void 0, void 0, function* () {
5134
+ if (!item) {
5135
+ return;
5136
+ }
5137
+ setIsDeletingItem(true);
5138
+ const { modelName } = item.getService().getSnapshot().context;
5139
+ yield deleteItem({ seedLocalId: item.seedLocalId });
5140
+ eventEmitter.emit('item.requestAll', { modelName });
5141
+ setIsDeletingItem(false);
5142
+ }), [isDeletingItem]);
5143
+ useEffect(() => { }, []);
5144
+ return {
5145
+ deleteItem: destroy,
5146
+ isDeletingItem,
5147
+ };
5148
+ };
5149
+
5150
+ const logger$7 = debug('app:react:property');
5151
+ const useItemProperty = (propertyName, seedLocalId) => {
5152
+ const [property, setProperty] = useImmer(undefined);
5153
+ const [isReadingFromDb, setIsReadingFromDb] = useState(false);
5154
+ const [isInitialized, setIsInitialized] = useState(false);
5155
+ const dbsAreReady = useDbsAreReady();
5156
+ const value = useSelector(property === null || property === void 0 ? void 0 : property.getService(), (snapshot) => {
5157
+ if (!snapshot || !snapshot.context) {
5158
+ return;
5159
+ }
5160
+ return snapshot.context.renderValue || snapshot.context.propertyValue;
5446
5161
  });
5447
- return () => {
5448
- if (subscription) {
5449
- subscription.unsubscribe();
5162
+ const status = useSelector(property === null || property === void 0 ? void 0 : property.getService(), (snapshot) => snapshot === null || snapshot === void 0 ? void 0 : snapshot.value);
5163
+ useEffect(() => {
5164
+ if (dbsAreReady && property && property.value !== value) {
5165
+ readFromDb();
5166
+ }
5167
+ }, [dbsAreReady, property, value]);
5168
+ const readFromDb = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
5169
+ if (!dbsAreReady && isReadingFromDb) {
5170
+ return;
5450
5171
  }
5172
+ setIsReadingFromDb(true);
5173
+ const foundProperty = yield ItemProperty.find({ propertyName, seedLocalId });
5174
+ setIsReadingFromDb(false);
5175
+ if (!foundProperty) {
5176
+ logger$7(`[useItemPropertyTest] [readFromDb] no property found for Item.${seedLocalId}.${propertyName}`);
5177
+ return;
5178
+ }
5179
+ setProperty(() => foundProperty);
5180
+ setIsInitialized(true);
5181
+ }), [dbsAreReady, isReadingFromDb]);
5182
+ useEffect(() => {
5183
+ readFromDb();
5184
+ }, []);
5185
+ // TODO: How can we force a re-render when the property is updated?
5186
+ // Right now, the value will trigger an update because it's using a selector
5187
+ // and a change is pushed to the hook listener.
5188
+ return {
5189
+ property,
5190
+ isInitialized,
5191
+ isReadingFromDb,
5192
+ value,
5193
+ status,
5451
5194
  };
5452
- });
5453
- const saveConfig = fromCallback(({ sendBack, receive, input: { context } }) => {
5454
- if (typeof window === 'undefined') {
5455
- console.error('seedInitBrowser called from non-browser context');
5456
- sendBack({
5457
- type: 'error',
5458
- error: 'Browser method called from non-browser context',
5459
- });
5460
- }
5461
- const { endpoints, addresses } = context;
5462
- if (!endpoints) {
5463
- throw new Error('saveConfig called with invalid endpoints');
5464
- }
5465
- const _saveConfig = () => __awaiter(void 0, void 0, void 0, function* () {
5466
- // logger('[sdk] [internal/actors] starting _saveConfig')
5467
- const seedDb = getDb(DB_NAME_SEED);
5468
- if (!seedDb) {
5469
- throw new Error('Seed DB not found');
5195
+ };
5196
+ const useItemProperties = (item) => {
5197
+ const [propertyObj, setPropertyObj] = useImmer({});
5198
+ useState(false);
5199
+ const updatePropertyObj = useCallback((event) => {
5200
+ if (!item) {
5201
+ console.error('[XXXXXX] [updatePropertyObj] no item when expected');
5202
+ return;
5470
5203
  }
5471
- const endpointsValueString = JSON.stringify(endpoints);
5472
- const addressesValueString = JSON.stringify(addresses);
5473
- // TODO: Figure out how to define on conflict with multiple rows added
5474
- try {
5475
- // logger('[sdk] [internal/actors] Saving endpoints to db')
5476
- yield seedDb
5477
- .insert(appState)
5478
- .values({
5479
- key: 'endpoints',
5480
- value: endpointsValueString,
5481
- })
5482
- .onConflictDoUpdate({
5483
- target: appState.key,
5484
- set: {
5485
- value: endpointsValueString,
5486
- },
5487
- setWhere: sql `key = 'endpoints'`,
5488
- });
5489
- // logger('[sdk] [internal/actors] Saving addresses to db')
5490
- yield seedDb
5491
- .insert(appState)
5492
- .values({
5493
- key: 'addresses',
5494
- value: addressesValueString,
5495
- })
5496
- .onConflictDoUpdate({
5497
- target: appState.key,
5498
- set: {
5499
- value: addressesValueString,
5500
- },
5501
- setWhere: sql `key = 'addresses'`,
5502
- });
5503
- logger$4('[sdk] [internal/actors] Should be done saving');
5204
+ const { propertyName, propertyValue } = event;
5205
+ if (!propertyName) {
5206
+ return;
5504
5207
  }
5505
- catch (error) {
5506
- console.error('Error saving config:', error);
5208
+ setPropertyObj((draft) => {
5209
+ draft[propertyName] = propertyValue;
5210
+ });
5211
+ }, [item]);
5212
+ useEffect(() => {
5213
+ if (!item) {
5214
+ return;
5507
5215
  }
5508
- });
5509
- _saveConfig().then(() => {
5510
- logger$4('[sdk] [internal/actors] Successfully saved config');
5511
- return sendBack({ type: INTERNAL_SAVING_CONFIG_SUCCESS });
5512
- });
5513
- return () => { };
5514
- });
5515
- const loadAppDb = fromCallback(({ sendBack, input: { context } }) => {
5516
- const { appDbService } = context;
5517
- let subscription;
5518
- const _loadAppDb = () => __awaiter(void 0, void 0, void 0, function* () {
5519
- return new Promise((resolve) => {
5520
- if (appDbService.getSnapshot().value === 'ready') {
5521
- return resolve();
5522
- }
5523
- subscription = appDbService.subscribe({
5524
- next: (snapshot) => {
5216
+ const eventKey = `item.${item.seedLocalId}.property.update`;
5217
+ eventEmitter.addListener(eventKey, updatePropertyObj);
5218
+ return () => {
5219
+ eventEmitter.removeListener(eventKey, updatePropertyObj);
5220
+ };
5221
+ }, [item]);
5222
+ return {
5223
+ properties: propertyObj,
5224
+ };
5225
+ };
5226
+
5227
+ const logger$6 = debug('app:global:actors');
5228
+ const initialize = fromCallback(({ sendBack, input: { event, context } }) => {
5229
+ const { internalService, models, endpoints } = context;
5230
+ const { addresses } = event;
5231
+ let environment = 'browser';
5232
+ if (isNode()) {
5233
+ environment = 'node';
5234
+ }
5235
+ if (isReactNative()) {
5236
+ environment = 'react-native';
5237
+ }
5238
+ let internalSubscription;
5239
+ if (environment === 'browser' && models) {
5240
+ const _initFileSystem = () => __awaiter(void 0, void 0, void 0, function* () {
5241
+ return;
5242
+ // return new Promise((resolve) => {
5243
+ // })
5244
+ });
5245
+ const _initInternal = () => __awaiter(void 0, void 0, void 0, function* () {
5246
+ return new Promise((resolve) => {
5247
+ internalSubscription = internalService.subscribe((snapshot) => {
5248
+ logger$6('[sdk] [internal] snapshot', snapshot);
5525
5249
  if (snapshot.value === 'ready') {
5526
- return resolve();
5250
+ resolve();
5527
5251
  }
5528
- sendBack({ type: DB_ON_SNAPSHOT, dbName: DB_NAME_APP, snapshot });
5529
- },
5252
+ });
5253
+ internalService.send({ type: 'init', endpoints, addresses });
5530
5254
  });
5531
5255
  });
5532
- });
5533
- _loadAppDb().then(() => {
5534
- sendBack({ type: INTERNAL_LOADING_APP_DB_SUCCESS });
5535
- logger$4('[sdk] [internal/actors] Successfully loaded app DB');
5536
- });
5537
- return () => {
5538
- if (subscription) {
5539
- subscription.unsubscribe();
5540
- }
5256
+ _initFileSystem().then(() => {
5257
+ logger$6('[global/actors] File system initialized');
5258
+ });
5259
+ _initInternal().then(() => {
5260
+ logger$6('[global/actors] Internal initialized');
5261
+ sendBack({ type: GLOBAL_INITIALIZING_INTERNAL_SERVICE_READY });
5262
+ internalSubscription === null || internalSubscription === void 0 ? void 0 : internalSubscription.unsubscribe();
5263
+ });
5264
+ // _initEas().then(() => {
5265
+ // logger('EAS initialized')
5266
+ // })
5267
+ }
5268
+ sendBack({ type: GLOBAL_INITIALIZING_SEND_CONFIG, environment });
5269
+ return () => {
5270
+ internalSubscription === null || internalSubscription === void 0 ? void 0 : internalSubscription.unsubscribe();
5541
5271
  };
5542
5272
  });
5543
- const loadSdkDb = fromCallback(({ sendBack, input: { context } }) => {
5544
- const { sdkDbService } = context;
5545
- logger$4('[sdk] [internal/actors] Loading SDK DB');
5546
- let subscription;
5547
- const _loadSdkDb = () => __awaiter(void 0, void 0, void 0, function* () {
5548
- return new Promise((resolve) => {
5549
- if (sdkDbService.getSnapshot().value === 'ready') {
5550
- return resolve();
5273
+ const addModelsToDb = fromCallback(({ sendBack, input: { context } }) => {
5274
+ const { models: models$1 } = context;
5275
+ const _addModelsToDb = () => __awaiter(void 0, void 0, void 0, function* () {
5276
+ var _a;
5277
+ const sdkConfigDb = getSdkDb();
5278
+ if (!models$1) {
5279
+ return;
5280
+ }
5281
+ const { models: SeedModels } = yield import('./seed.schema.config-C9CEFOxM.js');
5282
+ const allModels = Object.assign(Object.assign({}, SeedModels), models$1);
5283
+ let hasModelsInDb = false;
5284
+ const schemaDefsByModelName = new Map();
5285
+ for (const [modelName, _] of Object.entries(allModels)) {
5286
+ logger$6('[helpers/db] [addModelsToInternalDb] starting modelName:', modelName);
5287
+ let foundModel;
5288
+ const foundModelsQuery = yield sdkConfigDb
5289
+ .select()
5290
+ .from(models)
5291
+ .where(eq(models.name, modelName));
5292
+ if (!foundModelsQuery || foundModelsQuery.length === 0) {
5293
+ yield sdkConfigDb.insert(models).values({
5294
+ name: modelName,
5295
+ });
5296
+ logger$6('[global/actors] [addModelsToDb] inserted model:', modelName);
5297
+ const foundModels = yield sdkConfigDb
5298
+ .select({
5299
+ id: models.id,
5300
+ name: models.name,
5301
+ uid: modelUids.uid,
5302
+ })
5303
+ .from(models)
5304
+ .leftJoin(modelUids, eq(models.id, modelUids.modelId))
5305
+ .where(eq(models.name, modelName))
5306
+ .limit(1);
5307
+ foundModel = foundModels[0];
5551
5308
  }
5552
- subscription = sdkDbService.subscribe({
5553
- next: (snapshot) => {
5554
- if (snapshot.value === 'ready') {
5555
- return resolve();
5556
- }
5557
- sendBack({
5558
- type: DB_ON_SNAPSHOT,
5559
- dbName: DB_NAME_SDK_CONFIG,
5560
- snapshot,
5561
- });
5562
- },
5309
+ if (foundModelsQuery && foundModelsQuery.length > 0) {
5310
+ foundModel = foundModelsQuery[0];
5311
+ }
5312
+ if (!foundModel) {
5313
+ hasModelsInDb = false;
5314
+ break;
5315
+ }
5316
+ schemaDefsByModelName.set(modelName, {
5317
+ dbId: foundModel.id,
5318
+ schemaDef: `bytes32 ${toSnakeCase(modelName)}`,
5563
5319
  });
5320
+ }
5321
+ if (!hasModelsInDb) {
5322
+ return false;
5323
+ }
5324
+ const schemaDefs = Array.from(schemaDefsByModelName.values()).map(({ schemaDef }) => schemaDef);
5325
+ const { schemas } = yield queryClient.fetchQuery({
5326
+ queryKey: [`getSchemasVersion`],
5327
+ queryFn: () => __awaiter(void 0, void 0, void 0, function* () {
5328
+ return easClient.request(GET_SCHEMAS, {
5329
+ where: {
5330
+ schema: {
5331
+ in: schemaDefs,
5332
+ },
5333
+ },
5334
+ });
5335
+ }),
5564
5336
  });
5337
+ if (!schemas || schemas.length === 0) {
5338
+ throw new Error(`No schemas found`);
5339
+ }
5340
+ for (const schema of schemas) {
5341
+ const modelId = (_a = Array.from(schemaDefsByModelName.values()).find(({ schemaDef }) => schemaDef === schema.schema)) === null || _a === void 0 ? void 0 : _a.dbId;
5342
+ if (!modelId) {
5343
+ throw new Error(`No modelId found for schema ${schema.schema}`);
5344
+ }
5345
+ yield sdkConfigDb
5346
+ .insert(modelUids)
5347
+ .values({
5348
+ modelId,
5349
+ uid: schema.id,
5350
+ })
5351
+ .onConflictDoNothing();
5352
+ }
5565
5353
  });
5566
- _loadSdkDb().then(() => {
5567
- sendBack({ type: INTERNAL_LOADING_SDK_DB_SUCCESS });
5568
- logger$4('[sdk] [internal/actors] Successfully loaded SDK DB');
5569
- });
5570
- return () => {
5571
- if (subscription) {
5572
- subscription.unsubscribe();
5354
+ _addModelsToDb().then((hasModelsInDb) => {
5355
+ sendBack({ type: GLOBAL_ADDING_MODELS_TO_DB_SUCCESS });
5356
+ for (const [modelName, model] of Object.entries(models$1)) {
5357
+ const service = context[`${modelName}Service`];
5358
+ service.send({ type: 'modelsFound' });
5573
5359
  }
5574
- };
5360
+ eventEmitter.emit('syncDbWithEas');
5361
+ return;
5362
+ });
5363
+ return () => { };
5364
+ });
5365
+ const getSchemaForModel = fromCallback(({ sendBack, input: { context, event } }) => {
5366
+ const { modelName } = event;
5367
+ if (!modelName) {
5368
+ console.warn('No modelName found');
5369
+ return;
5370
+ }
5371
+ const { models } = context;
5372
+ if (!models) {
5373
+ console.warn('No models found');
5374
+ return;
5375
+ }
5376
+ const model = Object.entries(models).find(([modelNameFromConfig]) => modelNameFromConfig === modelName);
5377
+ if (!model) {
5378
+ throw new Error(`Model ${modelName} not found`);
5379
+ }
5380
+ logger$6('[service/actor] [getSchemaForModel] model:', model);
5381
+ sendBack({ type: 'schemaForModel', schema: model.schema });
5382
+ return () => { };
5575
5383
  });
5576
5384
 
5577
- const logger$3 = debug('app:services:db:machine');
5578
- const { CHECKING_STATUS, VALIDATING, WAITING_FOR_FILES, CONNECTING_TO_DB, MIGRATING, } = DbState;
5579
- const dbMachine = setup({
5580
- types: {
5581
- context: {},
5582
- input: {},
5583
- },
5584
- actors: {
5585
- checkStatus,
5586
- validate,
5587
- connectToDb,
5588
- migrate,
5589
- },
5590
- }).createMachine({
5591
- id: MachineIds.DB,
5592
- initial: CHECKING_STATUS,
5593
- context: ({ input }) => input,
5594
- on: {
5595
- [DB_WAITING_FOR_FILES_RECEIVED]: {
5596
- actions: assign({
5597
- hasFiles: ({ event }) => {
5598
- logger$3('[db/machine] DB_WAITING_FOR_FILES_RECEIVED event:', event);
5599
- return true;
5600
- },
5601
- }),
5602
- },
5603
- updateHasFiles: {
5604
- target: `.${CHECKING_STATUS}`,
5605
- actions: assign({
5606
- hasFiles: ({ context, event }) => {
5607
- logger$3('[db/machine] updateHasFiles event:', event);
5608
- logger$3('[db/machine] updateHasFiles context:', context);
5609
- return event.hasFiles;
5610
- },
5611
- }),
5612
- },
5613
- },
5614
- // always: {
5615
- // target: `.${CHECKING_STATUS}`,
5616
- // guard: ({ context, event }) => context.hasFiles && event.type === 'updateHasFiles',
5617
- // },
5618
- states: {
5619
- idle: {
5620
- on: {
5621
- start: CHECKING_STATUS,
5622
- },
5623
- meta: {
5624
- displayText: 'DB starting ...',
5625
- percentComplete: 0,
5626
- },
5627
- },
5628
- [CHECKING_STATUS]: {
5629
- on: {
5630
- [DB_CHECK_STATUS_UPDATE_PATHS]: {
5631
- actions: assign({
5632
- pathToDb: ({ event }) => event.pathToDb,
5633
- pathToDir: ({ event }) => event.pathToDir,
5634
- pathToDbDir: ({ event }) => event.pathToDbDir,
5635
- }),
5636
- },
5637
- [DB_CHECK_STATUS_EXISTS]: CONNECTING_TO_DB,
5638
- },
5639
- invoke: {
5640
- src: 'checkStatus',
5641
- input: ({ context, event }) => ({ context, event }),
5642
- },
5643
- meta: {
5644
- displayText: 'Checking DB status',
5645
- percentComplete: 60,
5646
- },
5647
- },
5648
- [CONNECTING_TO_DB]: {
5649
- on: {
5650
- [DB_CREATING_SUCCESS]: {
5651
- target: VALIDATING,
5652
- actions: assign({
5653
- dbId: ({ event }) => event.dbId,
5654
- }),
5655
- },
5656
- },
5657
- invoke: {
5658
- src: 'connectToDb',
5659
- input: ({ context }) => ({ context }),
5660
- },
5661
- meta: {
5662
- displayText: 'Connecting to local DB',
5663
- percentComplete: 70,
5664
- },
5665
- },
5666
- [VALIDATING]: {
5667
- on: {
5668
- [DB_VALIDATING_SUCCESS]: {
5669
- target: MIGRATING,
5670
- // guard: ({ context }) => context.hasFiles,
5671
- },
5672
- [DB_VALIDATING_WAIT]: {
5673
- target: WAITING_FOR_FILES,
5674
- // guard: ({ context }) => !context.hasFiles,
5675
- },
5676
- },
5677
- invoke: {
5678
- src: 'validate',
5679
- input: ({ context }) => ({ context }),
5680
- },
5681
- meta: {
5682
- displayText: 'Validating DB',
5683
- percentComplete: 80,
5684
- },
5685
- },
5686
- // Here we're waiting for migration and schema files to be downloaded
5687
- [WAITING_FOR_FILES]: {
5688
- on: {
5689
- [DB_WAITING_FOR_FILES_RECEIVED]: {
5690
- target: MIGRATING,
5691
- actions: assign({
5692
- hasFiles: true,
5693
- }),
5694
- },
5695
- [DB_MIGRATING_SUCCESS]: 'ready',
5696
- },
5697
- entry: ({ context }) => {
5698
- if (context.hasFiles) {
5699
- emit({ type: DB_WAITING_FOR_FILES_RECEIVED });
5385
+ class SqliteConnectionManager {
5386
+ constructor(sqliteModule, idleTimeout = 300000) {
5387
+ // Default idle timeout: 5 minutes
5388
+ this.sqliteModule = sqliteModule;
5389
+ this.idleTimeout = idleTimeout;
5390
+ this.databases = {};
5391
+ this.idleTimers = {};
5392
+ }
5393
+ resetIdleTimer(dbName) {
5394
+ if (this.idleTimers[dbName]) {
5395
+ clearTimeout(this.idleTimers[dbName]);
5396
+ }
5397
+ this.idleTimers[dbName] = setTimeout(() => {
5398
+ this.closeConnection(dbName);
5399
+ }, this.idleTimeout);
5400
+ }
5401
+ getConnection(dbName) {
5402
+ return __awaiter(this, void 0, void 0, function* () {
5403
+ if (this.databases[dbName]) {
5404
+ this.resetIdleTimer(dbName);
5405
+ return this.databases[dbName];
5406
+ }
5407
+ const db = new this.sqliteModule();
5408
+ yield db.open(dbName);
5409
+ this.databases[dbName] = db;
5410
+ this.resetIdleTimer(dbName);
5411
+ return db;
5412
+ });
5413
+ }
5414
+ execute(dbName_1, sql_1) {
5415
+ return __awaiter(this, arguments, void 0, function* (dbName, sql, params = []) {
5416
+ const db = yield this.getConnection(dbName);
5417
+ const result = db.exec(sql, params);
5418
+ this.resetIdleTimer(dbName);
5419
+ return result;
5420
+ });
5421
+ }
5422
+ closeConnection(dbName) {
5423
+ if (this.databases[dbName]) {
5424
+ this.databases[dbName].close();
5425
+ delete this.databases[dbName];
5426
+ if (this.idleTimers[dbName]) {
5427
+ clearTimeout(this.idleTimers[dbName]);
5428
+ delete this.idleTimers[dbName];
5429
+ }
5430
+ }
5431
+ }
5432
+ }
5433
+
5434
+ const logger$5 = debug('app:services:internal:helpers');
5435
+ /**
5436
+ * Recursively create directories if they don't exist.
5437
+ * @param {string} dirPath - The directory path to create.
5438
+ */
5439
+ const createDirectories = (dirPath) => __awaiter(void 0, void 0, void 0, function* () {
5440
+ const dirPathExists = yield fs.promises.exists(dirPath);
5441
+ if (dirPathExists) {
5442
+ return;
5443
+ }
5444
+ const parentDir = path.dirname(dirPath);
5445
+ const parentDirExists = yield fs.promises.exists(parentDir);
5446
+ if (!parentDirExists) {
5447
+ yield createDirectories(parentDir);
5448
+ }
5449
+ yield fs.promises.mkdir(dirPath, { recursive: true });
5450
+ });
5451
+ let busy = false;
5452
+ const downloadFile = (url, localFilePath) => __awaiter(void 0, void 0, void 0, function* () {
5453
+ try {
5454
+ const response = yield fetch(url);
5455
+ const fileData = yield response.text().catch((error) => {
5456
+ console.error(`Failed to parse text from ${url}:`, error);
5457
+ });
5458
+ if (!fileData) {
5459
+ console.error(`No file data from ${url}`);
5460
+ return;
5461
+ }
5462
+ const localDirPath = path.dirname(localFilePath);
5463
+ if (busy) {
5464
+ return;
5465
+ }
5466
+ busy = true;
5467
+ yield createDirectories(localDirPath);
5468
+ const filename = path.basename(localFilePath);
5469
+ const regex = /(\d+)[\w_]+\.(sql|json)$/;
5470
+ const match = filename.match(regex);
5471
+ let migrationNumber;
5472
+ if (match && match.length > 1) {
5473
+ migrationNumber = match[1];
5474
+ }
5475
+ if (migrationNumber) {
5476
+ const filesInDir = yield fs.promises.readdir(localDirPath);
5477
+ for (const file of filesInDir) {
5478
+ if (file === filename) {
5479
+ continue;
5700
5480
  }
5701
- },
5702
- },
5703
- [MIGRATING]: {
5704
- on: {
5705
- [DB_MIGRATING_WAIT]: WAITING_FOR_FILES,
5706
- [DB_MIGRATING_SUCCESS]: {
5707
- target: 'ready',
5708
- },
5709
- },
5710
- invoke: {
5711
- src: 'migrate',
5712
- input: ({ context }) => ({ context }),
5713
- },
5714
- meta: {
5715
- displayText: 'Migrating DB',
5716
- percentComplete: 90,
5717
- },
5718
- },
5719
- ready: {
5720
- target: 'idle',
5721
- meta: {
5722
- displayText: 'Wrapping up the db ...',
5723
- percentComplete: 100,
5724
- },
5725
- },
5726
- },
5481
+ const innerMatch = file.match(regex);
5482
+ let existingFileMigrationNumber;
5483
+ if (innerMatch && innerMatch.length > 1) {
5484
+ existingFileMigrationNumber = innerMatch[1];
5485
+ }
5486
+ if (migrationNumber &&
5487
+ existingFileMigrationNumber &&
5488
+ existingFileMigrationNumber === migrationNumber) {
5489
+ yield fs.promises.unlink(path.join(localDirPath, file));
5490
+ }
5491
+ }
5492
+ }
5493
+ // if (filename === '_journal.json') {
5494
+ // const exists = await fs.promises.exists(localFilePath)
5495
+ // if (exists) {
5496
+ // await fs.promises.rm(localFilePath)
5497
+ // }
5498
+ // await fs.promises.writeFile(localFilePath, fileData)
5499
+ // }
5500
+ //
5501
+ // if (filename !== '_journal.json') {
5502
+ // await fs.promises.writeFile(localFilePath, fileData)
5503
+ // }
5504
+ yield fs.promises.writeFile(localFilePath, fileData);
5505
+ }
5506
+ catch (error) {
5507
+ if (JSON.stringify(error).includes('File exists')) {
5508
+ yield fs.promises.readFile(localFilePath, 'utf-8');
5509
+ }
5510
+ logger$5(`[Error] Failed to download file from ${url}:`, error);
5511
+ }
5512
+ busy = false;
5513
+ });
5514
+ const fetchDirectory = (url) => __awaiter(void 0, void 0, void 0, function* () {
5515
+ const response = yield fetch(url);
5516
+ return response.json();
5517
+ });
5518
+ const fetchFilesRecursively = (url, localPath, fileList) => __awaiter(void 0, void 0, void 0, function* () {
5519
+ try {
5520
+ for (const file of fileList) {
5521
+ const fileUrl = `${url}/${file}`;
5522
+ const fileLocalPath = path.join(localPath, file);
5523
+ // logger(`[fetchFilesRecursively] fileUrl: ${fileUrl}`)
5524
+ // logger(`[fetchFilesRecursively] fileLocalPath: ${fileLocalPath}`)
5525
+ yield downloadFile(fileUrl, fileLocalPath);
5526
+ }
5527
+ }
5528
+ catch (error) {
5529
+ console.error(`Failed to fetch files from ${url}:`, error);
5530
+ }
5531
+ });
5532
+ const confirmFilesExist = (filePaths) => __awaiter(void 0, void 0, void 0, function* () {
5533
+ let everythingDownloaded = false;
5534
+ for (const filePath of filePaths) {
5535
+ const fullPath = path.join(BROWSER_FS_TOP_DIR, filePath);
5536
+ everythingDownloaded = yield fs.promises.exists(fullPath);
5537
+ }
5538
+ if (!everythingDownloaded) {
5539
+ setTimeout(() => __awaiter(void 0, void 0, void 0, function* () {
5540
+ yield confirmFilesExist(filePaths);
5541
+ }), 500);
5542
+ }
5543
+ });
5544
+ const syncDbFiles = (_a) => __awaiter(void 0, [_a], void 0, function* ({ filePaths, files }) {
5545
+ const fileList = yield fetchDirectory(filePaths);
5546
+ yield fetchFilesRecursively(files, BROWSER_FS_TOP_DIR, fileList);
5547
+ yield confirmFilesExist(fileList);
5548
+ logger$5('[syncDbFiles] Files synced!');
5727
5549
  });
5728
5550
 
5729
- const logger$2 = debug('app:services:internal:machine');
5730
- createBrowserInspector({
5731
- autoStart: false,
5551
+ const logger$4 = debug('app:files:download');
5552
+ const downloadAllFilesRequestHandler = (_a) => __awaiter(void 0, [_a], void 0, function* ({ endpoints, eventId, }) {
5553
+ yield syncDbFiles(endpoints);
5554
+ eventEmitter.emit('fs.downloadAll.success', { eventId });
5555
+ eventEmitter.emit('fs.downloadAllBinary.request', { endpoints });
5732
5556
  });
5733
- const { IDLE, VALIDATING_INPUT, SAVING_CONFIG, CONFIGURING_FS, LOADING_DBS, LOADING_SEED_DB, LOADING_APP_DB, LOADING_SDK_DB, } = InternalState;
5734
- // Create the state machine
5735
- const internalMachine = setup({
5736
- types: {
5737
- context: {},
5738
- input: {},
5739
- },
5740
- actors: {
5741
- prepareDb,
5742
- validateInput,
5743
- configureFs,
5744
- loadSeedDb,
5745
- saveConfig,
5746
- loadAppDb,
5747
- loadSdkDb,
5748
- },
5749
- }).createMachine({
5750
- id: MachineIds.INTERNAL,
5751
- initial: IDLE,
5752
- context: ({ input }) => {
5753
- return Object.assign(Object.assign({}, input), { error: undefined, hasFiles: false });
5754
- },
5755
- states: {
5756
- [IDLE]: {
5757
- on: {
5758
- reValidate: VALIDATING_INPUT,
5759
- init: {
5760
- target: VALIDATING_INPUT,
5761
- actions: [
5762
- assign({
5763
- seedDbService: ({ spawn }) => spawn(dbMachine, {
5764
- input: {
5765
- dbName: DB_NAME_SEED,
5766
- dirName: DB_DIR_NAME_SEED,
5767
- },
5768
- }),
5769
- }),
5770
- assign({
5771
- appDbService: ({ spawn }) => spawn(dbMachine, {
5772
- input: {
5773
- dbName: DB_NAME_APP,
5774
- dirName: DB_DIR_NAME_APP,
5775
- },
5776
- }),
5777
- }),
5778
- assign({
5779
- sdkDbService: ({ spawn }) => spawn(dbMachine, {
5780
- input: {
5781
- dbName: DB_NAME_SDK_CONFIG,
5782
- dirName: DB_DIR_NAME_SDK,
5783
- },
5784
- }),
5785
- }),
5786
- ],
5787
- },
5788
- },
5789
- meta: {
5790
- displayText: 'Waiting for something to happen ...',
5791
- percentComplete: 0,
5792
- },
5793
- },
5794
- [VALIDATING_INPUT]: {
5795
- on: {
5796
- [INTERNAL_VALIDATING_INPUT_SUCCESS]: {
5797
- target: 'preparingDb',
5798
- actions: assign({
5799
- endpoints: ({ event }) => event.endpoints,
5800
- addresses: ({ event }) => event.addresses,
5801
- }),
5802
- },
5803
- },
5804
- invoke: {
5805
- src: 'validateInput',
5806
- input: ({ context, event }) => ({ context, event }),
5807
- },
5808
- meta: {
5809
- displayText: 'Validating input',
5810
- percentComplete: 20,
5811
- },
5812
- tags: ['loading'],
5813
- },
5814
- preparingDb: {
5815
- on: {
5816
- prepareDbSuccess: {
5817
- target: CONFIGURING_FS,
5818
- },
5819
- },
5820
- invoke: {
5821
- src: 'prepareDb',
5822
- input: ({ context, event }) => ({ context, event }),
5823
- },
5824
- },
5825
- [CONFIGURING_FS]: {
5826
- on: {
5827
- [INTERNAL_CONFIGURING_FS_SUCCESS]: {
5828
- target: LOADING_SEED_DB,
5829
- actions: assign({ hasFiles: true }),
5830
- },
5831
- },
5832
- invoke: {
5833
- src: 'configureFs',
5834
- input: ({ context, event }) => ({ context, event }),
5835
- },
5836
- meta: {
5837
- displayText: 'Downloading app files',
5838
- percentComplete: 30,
5839
- },
5840
- tags: ['loading'],
5841
- },
5842
- // We run this before the other DBs because it holds the config we need to
5843
- // rebuild. If we get interrupted after this then we don't have to start
5844
- // from scratch.
5845
- [LOADING_SEED_DB]: {
5846
- on: {
5847
- [INTERNAL_LOADING_SEED_DB_SUCCESS]: SAVING_CONFIG,
5848
- // [DB_ON_SNAPSHOT]: {
5849
- // actions: emit(({ event: { snapshot } }) => {
5850
- // return { type: CHILD_SNAPSHOT, snapshot }
5851
- // }),
5852
- // },
5853
- },
5854
- invoke: {
5855
- src: 'loadSeedDb',
5856
- input: ({ context, event }) => ({ context, event }),
5857
- },
5858
- meta: {
5859
- displayText: 'Loading seed database',
5860
- percentComplete: 50,
5861
- },
5862
- tags: ['loading'],
5863
- },
5864
- // Save developer's config to DB
5865
- [SAVING_CONFIG]: {
5866
- on: {
5867
- [INTERNAL_SAVING_CONFIG_SUCCESS]: LOADING_DBS,
5868
- },
5869
- invoke: {
5870
- src: 'saveConfig',
5871
- input: ({ context, event }) => ({ context, event }),
5872
- },
5873
- meta: {
5874
- displayText: 'Saving configuration',
5875
- percentComplete: 80,
5876
- },
5877
- tags: ['loading'],
5878
- },
5879
- // The DBs can be loaded in parallel since they are independent of each other
5880
- [LOADING_DBS]: {
5881
- type: 'parallel',
5882
- states: {
5883
- [LOADING_APP_DB]: {
5884
- initial: 'loading',
5885
- states: {
5886
- loading: {
5887
- on: {
5888
- [INTERNAL_LOADING_APP_DB_SUCCESS]: {
5889
- target: 'appDbLoaded',
5890
- actions: () => {
5891
- logger$2('[sdk] [internal/index] App DB loaded!');
5892
- },
5893
- },
5894
- },
5895
- invoke: {
5896
- src: 'loadAppDb',
5897
- input: ({ context, event }) => ({ context, event }),
5898
- },
5899
- },
5900
- appDbLoaded: {
5901
- type: 'final',
5902
- entry: () => {
5903
- logger$2('[sdk] [internal/index] Entered appDbLoaded!');
5904
- },
5905
- },
5557
+ const downloadAllFilesBinaryRequestHandler = () => __awaiter(void 0, void 0, void 0, function* () {
5558
+ const addresses = yield getAddressesFromDb();
5559
+ const { filesMetadata } = yield queryClient.fetchQuery({
5560
+ queryKey: ['getFilesMetadata', ...addresses],
5561
+ queryFn: () => __awaiter(void 0, void 0, void 0, function* () {
5562
+ return easClient.request(GET_FILES_METADATA, {
5563
+ where: {
5564
+ attester: {
5565
+ in: addresses,
5906
5566
  },
5907
- },
5908
- [LOADING_SDK_DB]: {
5909
- initial: 'loading',
5910
- states: {
5911
- loading: {
5912
- on: {
5913
- [INTERNAL_LOADING_SDK_DB_SUCCESS]: {
5914
- target: 'sdkConfigDbLoaded',
5915
- actions: () => {
5916
- logger$2('[sdk] [internal/index] SDK Config DB loaded!');
5917
- },
5918
- },
5919
- },
5920
- invoke: {
5921
- src: 'loadSdkDb',
5922
- input: ({ context, event }) => ({ context, event }),
5923
- },
5924
- },
5925
- sdkConfigDbLoaded: {
5926
- type: 'final',
5927
- entry: () => {
5928
- logger$2('[sdk] [internal/index] Entered sdkConfigDbLoaded!');
5567
+ schema: {
5568
+ is: {
5569
+ id: {
5570
+ equals: '0x55fdefb36fcbbaebeb7d6b41dc3a1a9666e4e42154267c889de064faa7ede517',
5929
5571
  },
5930
5572
  },
5931
5573
  },
5932
5574
  },
5933
- },
5934
- onDone: {
5935
- target: 'ready',
5936
- actions: () => {
5937
- logger$2('[sdk] [internal/index] All DBs loaded! Should be headed to ready');
5938
- eventEmitter.emit('allDbsLoaded');
5939
- },
5940
- },
5941
- meta: {
5942
- displayText: 'Loading databases',
5943
- percentComplete: 90,
5944
- },
5945
- tags: ['loading'],
5946
- },
5947
- ready: {
5948
- entry: () => {
5949
- logger$2('[sdk] [internal/index] Ready!');
5950
- },
5951
- meta: {
5952
- displayText: "Crossing the t's ...",
5953
- percentComplete: 90,
5954
- },
5955
- },
5956
- error: {
5957
- on: {
5958
- retry: {
5959
- target: CONFIGURING_FS,
5960
- actions: assign({ error: undefined }),
5961
- },
5962
- },
5963
- entry: () => {
5964
- logger$2('[sdk] [internal/index] Error!');
5965
- },
5966
- meta: {
5967
- displayText: 'Whoops! Something went wrong.',
5968
- percentComplete: null,
5969
- },
5970
- tags: ['error'],
5971
- },
5972
- },
5973
- });
5974
-
5975
- const { UNINITIALIZED, INITIALIZING, INITIALIZED, GETTING_SEED_CLASS, GETTING_SCHEMA_FOR_MODEL, ADDING_MODELS_TO_DB, } = GlobalState;
5976
- createBrowserInspector({
5977
- autoStart: false,
5978
- });
5979
- const globalMachine = setup({
5980
- types: {
5981
- context: {},
5982
- input: {},
5983
- },
5984
- actors: {
5985
- initialize,
5986
- addModelsToDb,
5987
- getSchemaForModel,
5988
- },
5989
- }).createMachine({
5990
- id: MachineIds.GLOBAL,
5991
- initial: UNINITIALIZED,
5992
- context: ({ input }) => input,
5993
- states: {
5994
- [UNINITIALIZED]: {
5995
- on: {
5996
- init: {
5997
- target: INITIALIZING,
5998
- guard: ({ context }) => {
5999
- return typeof window !== 'undefined';
6000
- },
6001
- actions: [
6002
- assign({
6003
- isInitialized: false,
6004
- addedModelRecordsToDb: false,
6005
- models: ({ event }) => event.models,
6006
- endpoints: ({ event }) => event.endpoints,
6007
- internalService: ({ spawn, context }) => {
6008
- return spawn(internalMachine, {
6009
- systemId: MachineIds.INTERNAL,
6010
- input: {
6011
- endpoints: context.endpoints,
6012
- },
6013
- });
6014
- },
6015
- // fileSystemService: ({ spawn, event }) => {
6016
- // return spawn(fileSystemMachine, {
6017
- // systemId: MachineIds.FILE_SYSTEM,
6018
- // input: {
6019
- // addresses: event.addresses,
6020
- // },
6021
- // })
6022
- // },
6023
- }),
6024
- assign(({ event, spawn }) => {
6025
- const allItemsServices = {};
6026
- for (const [modelName, ModelClass] of Object.entries(event.models)) {
6027
- const service = spawn(itemMachineAll, {
6028
- systemId: modelName,
6029
- input: {
6030
- modelName,
6031
- ModelClass,
6032
- modelSchema: ModelClass.schema,
6033
- items: [],
6034
- },
6035
- });
6036
- allItemsServices[`${modelName}Service`] = service;
6037
- }
6038
- return allItemsServices;
6039
- }),
6040
- ],
6041
- },
6042
- },
6043
- meta: {
6044
- displayText: 'Booting up',
6045
- percentComplete: 5,
6046
- },
6047
- tags: ['loading'],
6048
- },
6049
- [INITIALIZING]: {
6050
- on: {
6051
- [GLOBAL_INITIALIZING_SEND_CONFIG]: {
6052
- actions: assign({
6053
- endpoints: ({ event }) => event.endpoints,
6054
- environment: ({ event }) => event.environment,
6055
- addresses: ({ event }) => event.addresses,
6056
- isInitialized: true,
6057
- }),
6058
- },
6059
- [GLOBAL_INITIALIZING_INTERNAL_SERVICE_READY]: ADDING_MODELS_TO_DB,
6060
- },
6061
- invoke: {
6062
- src: 'initialize',
6063
- input: ({ event, context }) => ({ event, context }),
6064
- meta: {
6065
- displayText: 'Initializing Seed SDK',
6066
- percentComplete: 10,
6067
- },
6068
- tags: ['loading'],
6069
- },
6070
- },
6071
- [ADDING_MODELS_TO_DB]: {
6072
- on: {
6073
- [GLOBAL_ADDING_MODELS_TO_DB_SUCCESS]: {
6074
- target: INITIALIZED,
6075
- actions: assign({
6076
- addedModelRecordsToDb: true,
6077
- }),
6078
- },
6079
- },
6080
- invoke: {
6081
- src: 'addModelsToDb',
6082
- input: ({ context }) => ({ context }),
6083
- meta: {
6084
- displayText: 'Adding models to database',
6085
- },
6086
- tags: ['loading'],
6087
- },
6088
- },
6089
- [INITIALIZED]: {
6090
- type: 'parallel',
6091
- on: {
6092
- getSeedClass: `.${GETTING_SEED_CLASS}`,
6093
- getSchemaForModel: `.${GETTING_SCHEMA_FOR_MODEL}`,
6094
- },
6095
- meta: {
6096
- displayText: 'Global service ready',
6097
- percentComplete: 40,
6098
- },
6099
- tags: ['loading'],
6100
- states: {
6101
- [GETTING_SEED_CLASS]: {
6102
- entry: [
6103
- (_a) => __awaiter(void 0, [_a], void 0, function* ({ context }) {
6104
- let SeedClass;
6105
- if (context.environment === 'node') {
6106
- const { SeedNode } = yield import('./seed-DM5koJUz.js');
6107
- SeedClass = SeedNode;
6108
- }
6109
- else {
6110
- const { SeedBrowser } = yield import('./seed-DHOFK9DF.js');
6111
- SeedClass = SeedBrowser;
6112
- }
6113
- return SeedClass;
6114
- }),
6115
- ],
6116
- meta: {
6117
- displayText: 'Getting SeedClass',
6118
- },
6119
- tags: ['loading'],
6120
- },
6121
- [GETTING_SCHEMA_FOR_MODEL]: {
6122
- invoke: {
6123
- src: 'getSchemaForModel',
6124
- input: ({ event, context }) => ({ event, context }),
6125
- meta: {
6126
- displayText: 'Getting schema for model',
6127
- },
6128
- tags: ['loading'],
6129
- },
6130
- },
6131
- },
6132
- },
6133
- },
6134
- // on: {
6135
- // '*': {
6136
- // actions: emit(({ event }) => {
6137
- // return event
6138
- // }),
6139
- // },
6140
- // },
6141
- });
6142
- const globalService = createActor(globalMachine, {
6143
- input: {},
6144
- // inspect,
6145
- inspect: (inspEvent) => {
6146
- eventEmitter.emit('inspect.globalService', inspEvent);
6147
- // console.log('[sdk] [service/index] inspEvent', inspEvent)
6148
- // eventEmitter.emit('globalService', inspEvent)
6149
- // let eventType: string = inspEvent.type
6150
- // if (inspEvent.event && inspEvent.event.type) {
6151
- // eventType = inspEvent.event.type
6152
- // }
6153
- //
6154
- // if (typeof eventType === 'object') {
6155
- // eventType = JSON.stringify(eventType)
6156
- // }
6157
- //
6158
- // let srcId = inspEvent.actorRef.id
6159
- //
6160
- // if (!srcId.includes('seedSdk')) {
6161
- // srcId = inspEvent.actorRef.logic.config.id
6162
- // }
6163
- //
6164
- // if (inspEvent.type === '@xstate.snapshot') {
6165
- // if (
6166
- // inspEvent.event.type === CHILD_SNAPSHOT &&
6167
- // inspEvent.snapshot &&
6168
- // inspEvent.snapshot.machine.id === MachineIds.GLOBAL
6169
- // ) {
6170
- // return
6171
- // }
6172
- // if (inspEvent.snapshot && inspEvent.snapshot.value) {
6173
- // if (typeof window !== 'undefined') {
6174
- // eventEmitter.emit('globalService', {
6175
- // type: eventType,
6176
- // src: srcId,
6177
- // snapshot: inspEvent.snapshot,
6178
- // })
6179
- // }
6180
- // }
6181
- // } else {
6182
- // if (typeof window !== 'undefined') {
6183
- // let snapshot
6184
- //
6185
- // try {
6186
- // snapshot = inspEvent.actorRef.getSnapshot()
6187
- // } catch (e) {
6188
- // // This fails if the actor hasn't initialized yet, but that's OK I think
6189
- // // console.log('[sdk] [service/index] ERROR', e)
6190
- // }
6191
- //
6192
- // eventEmitter.emit('globalService', {
6193
- // type: eventType,
6194
- // src: srcId,
6195
- // snapshot,
6196
- // })
6197
- // }
6198
- // }
6199
- },
6200
- });
6201
- globalService.start();
6202
- const getGlobalService = () => globalService;
6203
-
6204
- const logger$1 = debug('app:react:index');
6205
- const useItemProperty = (propertyName, seedLocalId) => {
6206
- const [property, setProperty] = useImmer(undefined);
6207
- const [isReadingFromDb, setIsReadingFromDb] = useState(false);
6208
- const [isInitialized, setIsInitialized] = useState(false);
6209
- const dbsAreReady = useDbsAreReady();
6210
- const value = useSelector(property === null || property === void 0 ? void 0 : property.getService(), (snapshot) => {
6211
- if (!snapshot || !snapshot.context) {
6212
- return;
6213
- }
6214
- return snapshot.context.renderValue || snapshot.context.propertyValue;
5575
+ });
5576
+ }),
6215
5577
  });
6216
- const status = useSelector(property === null || property === void 0 ? void 0 : property.getService(), (snapshot) => snapshot === null || snapshot === void 0 ? void 0 : snapshot.value);
6217
- useEffect(() => {
6218
- if (dbsAreReady && property && property.value !== value) {
6219
- readFromDb();
6220
- }
6221
- }, [dbsAreReady, property, value]);
6222
- const readFromDb = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
6223
- if (!dbsAreReady && isReadingFromDb) {
6224
- return;
6225
- }
6226
- setIsReadingFromDb(true);
6227
- const foundProperty = yield ItemProperty.find({ propertyName, seedLocalId });
6228
- setIsReadingFromDb(false);
6229
- if (!foundProperty) {
6230
- logger$1(`[useItemPropertyTest] [readFromDb] no property found for Item.${seedLocalId}.${propertyName}`);
6231
- return;
5578
+ if (!(yield fs.promises.exists('/files'))) {
5579
+ yield fs.promises.mkdir('/files', { recursive: true });
5580
+ }
5581
+ if (!(yield fs.promises.exists('/files/html'))) {
5582
+ yield fs.promises.mkdir('/files/html', { recursive: true });
5583
+ }
5584
+ if (!(yield fs.promises.exists('/files/json'))) {
5585
+ yield fs.promises.mkdir('/files/json', { recursive: true });
5586
+ }
5587
+ if (!(yield fs.promises.exists('/files/images'))) {
5588
+ yield fs.promises.mkdir('/files/images', { recursive: true });
5589
+ }
5590
+ const seedDb = getDb(DB_NAME_SEED);
5591
+ if (!seedDb) {
5592
+ console.warn('[fetchAll/actors] [fetchAllBinaryData] seedDb not available');
5593
+ return [];
5594
+ }
5595
+ for (const fileMetadata of filesMetadata) {
5596
+ const json = JSON.parse(fileMetadata.decodedDataJson);
5597
+ const transactionId = json[0].value.value;
5598
+ const excludedTransactionsQuery = yield seedDb
5599
+ .select()
5600
+ .from(appState)
5601
+ .where(eq(appState.key, 'excludedTransactions'));
5602
+ let excludedTransactions = new Set();
5603
+ if (excludedTransactionsQuery && excludedTransactionsQuery.length === 1) {
5604
+ const valueString = excludedTransactionsQuery[0].value;
5605
+ if (valueString) {
5606
+ const excludedTransactionsArray = JSON.parse(valueString);
5607
+ excludedTransactions = new Set(excludedTransactionsArray);
5608
+ }
6232
5609
  }
6233
- setProperty(() => foundProperty);
6234
- setIsInitialized(true);
6235
- }), [dbsAreReady, isReadingFromDb]);
6236
- useEffect(() => {
6237
- readFromDb();
6238
- }, []);
6239
- // TODO: How can we force a re-render when the property is updated?
6240
- // Right now, the value will trigger an update because it's using a selector
6241
- // and a change is pushed to the hook listener.
6242
- return {
6243
- property,
6244
- isInitialized,
6245
- isReadingFromDb,
6246
- value,
6247
- status,
6248
- };
6249
- };
6250
- const useItem = ({ modelName, seedLocalId, seedUid }) => {
6251
- const [item, setItem] = useImmer(undefined);
6252
- const [itemSubscription, setItemSubscription] = useState();
6253
- const { status, internalStatus } = useGlobalServiceStatus();
6254
- const isReadingDb = useRef(false);
6255
- const itemStatus = useSelector(item === null || item === void 0 ? void 0 : item.getService(), (snapshot) => snapshot === null || snapshot === void 0 ? void 0 : snapshot.value);
6256
- const updateItem = useCallback((newItem) => {
6257
- setItem(() => newItem);
6258
- }, []);
6259
- const readFromDb = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
6260
- if (isReadingDb.current ||
6261
- internalStatus !== 'ready' ||
6262
- (!seedUid && !seedLocalId)) {
6263
- return;
5610
+ if (excludedTransactions.has(transactionId)) {
5611
+ continue;
6264
5612
  }
6265
- isReadingDb.current = true;
6266
- const foundItem = yield Item.find({
6267
- modelName,
6268
- seedLocalId,
6269
- seedUid,
6270
- });
6271
- if (!foundItem) {
6272
- logger$1('[useItem] [getItemFromDb] no item found', modelName, seedLocalId);
6273
- return;
5613
+ const arweave = getArweave();
5614
+ if (!arweave) {
5615
+ console.warn('[fetchAll/actors] [fetchAllBinaryData] arweave not available');
5616
+ return [];
6274
5617
  }
6275
- updateItem(foundItem);
6276
- isReadingDb.current = false;
6277
- }), [internalStatus]);
6278
- useEffect(() => {
6279
- if (internalStatus === 'ready') {
6280
- readFromDb();
6281
- }
6282
- }, [internalStatus, status]);
6283
- useEffect(() => {
6284
- if (item && !itemSubscription) {
6285
- const subscription = item.subscribe((_) => __awaiter(void 0, void 0, void 0, function* () {
6286
- const newItem = yield Item.find({ modelName, seedLocalId, seedUid });
6287
- if (!newItem) {
6288
- logger$1('[useItem] [itemSubscription] no item found', modelName, seedLocalId);
6289
- return;
6290
- }
6291
- setItem(() => newItem);
6292
- }));
6293
- setItemSubscription(subscription);
6294
- }
6295
- return () => {
6296
- itemSubscription === null || itemSubscription === void 0 ? void 0 : itemSubscription.unsubscribe();
6297
- };
6298
- }, [item, itemSubscription]);
6299
- useEffect(() => {
6300
- const seedId = seedUid || seedLocalId;
6301
- eventEmitter.addListener(`item.${modelName}.${seedId}.update`, readFromDb);
6302
- return () => {
6303
- eventEmitter.removeListener(`item.${modelName}.${seedId}.update`, readFromDb);
6304
- };
6305
- }, []);
6306
- return {
6307
- item,
6308
- itemStatus,
6309
- };
6310
- };
6311
- const useItems = ({ modelName, options }) => {
6312
- const [items, setItems] = useImmer([]);
6313
- const [isReadingDb, setIsReadingDb] = useState(false);
6314
- const [isInitialized, setIsInitialized] = useState(false);
6315
- const { dbsAreReady } = useDbsAreReady();
6316
- const modelNameRef = useRef(modelName);
6317
- const readFromDb = useCallback((event) => __awaiter(void 0, void 0, void 0, function* () {
6318
- if (!event ||
6319
- !event.modelName ||
6320
- event.modelName !== modelNameRef.current ||
6321
- isReadingDb) {
6322
- return;
6323
- }
6324
- setIsReadingDb(true);
6325
- const allItems = yield Item.all(modelNameRef.current);
6326
- setItems(() => allItems);
6327
- setIsReadingDb(false);
6328
- }), [modelName]);
6329
- useEffect(() => {
6330
- if (dbsAreReady && !isInitialized) {
6331
- const _fetchItems = () => __awaiter(void 0, void 0, void 0, function* () {
6332
- yield readFromDb({ modelName });
6333
- setIsInitialized(true);
5618
+ try {
5619
+ const res = yield fetch(`https://${ARWEAVE_HOST}/tx/${transactionId}/status`);
5620
+ if (res.status !== 200) {
5621
+ logger$4(`[fetchAll/actors] [fetchAllBinaryData] error fetching transaction data for ${transactionId}`);
5622
+ excludedTransactions.add(transactionId);
5623
+ yield writeAppState(seedDb, 'excludedTransactions', JSON.stringify(Array.from(excludedTransactions)));
5624
+ continue;
5625
+ }
5626
+ const dataString = yield arweave.transactions
5627
+ .getData(transactionId, {
5628
+ decode: true,
5629
+ string: true,
5630
+ })
5631
+ .catch((error) => {
5632
+ console.error(`[fetchAll/actors] [fetchAllBinaryData] error fetching transaction data for ${transactionId}`, error);
6334
5633
  });
6335
- _fetchItems();
6336
- }
6337
- }, [dbsAreReady, isInitialized]);
6338
- useEffect(() => {
6339
- eventEmitter.addListener('item.requestAll', readFromDb);
6340
- return () => {
6341
- eventEmitter.removeListener('item.requestAll');
6342
- };
6343
- }, []);
6344
- return {
6345
- items: orderBy(items, [
6346
- (item) => item.lastVersionPublishedAt ||
6347
- item.attestationCreatedAt ||
6348
- item.createdAt,
6349
- ], ['desc']).slice(0, 10),
6350
- isReadingDb,
6351
- isInitialized,
6352
- };
6353
- };
6354
- const useDbsAreReady = () => {
6355
- const [dbsAreReady, setDbsAreReady] = useState(false);
6356
- const update = useCallback(() => {
6357
- if (dbsAreReady) {
6358
- return;
6359
- }
6360
- setDbsAreReady(true);
6361
- }, []);
6362
- useEffect(() => {
6363
- let globalSubscription;
6364
- let internalSubscription;
6365
- const _waitForDbs = () => __awaiter(void 0, void 0, void 0, function* () {
6366
- const globalService = getGlobalService();
6367
- const internalService = globalService.getSnapshot().context.internalService;
6368
- if (!internalService) {
6369
- logger$1('[useDbsAreReady] [useEffect] no internalService');
6370
- globalSubscription = globalService.subscribe(({ context }) => {
6371
- if (!internalSubscription && context && context.internalService) {
6372
- globalSubscription === null || globalSubscription === void 0 ? void 0 : globalSubscription.unsubscribe();
6373
- internalSubscription = context.internalService.subscribe((snapshot) => {
6374
- if (snapshot.value === 'ready') {
6375
- update();
6376
- internalSubscription === null || internalSubscription === void 0 ? void 0 : internalSubscription.unsubscribe();
6377
- }
6378
- });
6379
- }
6380
- });
6381
- return;
5634
+ if (!dataString) {
5635
+ logger$4(`[fetchAll/actors] [fetchAllBinaryData] transaction ${transactionId} data not found`);
6382
5636
  }
6383
- const currentState = internalService.getSnapshot().value;
6384
- if (currentState === 'ready') {
6385
- update();
6386
- return;
5637
+ let contentType = identifyString(dataString);
5638
+ if (contentType !== 'json' &&
5639
+ contentType !== 'base64' &&
5640
+ contentType !== 'html') {
5641
+ const possibleImageType = getImageDataType(dataString);
5642
+ if (!possibleImageType) {
5643
+ logger$4(`[fetchAll/actors] [fetchAllBinaryData] transaction ${transactionId} data not in expected format: ${possibleImageType}`);
5644
+ continue;
5645
+ }
5646
+ contentType = possibleImageType;
6387
5647
  }
6388
- internalSubscription = internalService.subscribe((snapshot) => {
6389
- if (snapshot.value === 'ready') {
6390
- update();
6391
- internalSubscription === null || internalSubscription === void 0 ? void 0 : internalSubscription.unsubscribe();
5648
+ if (contentType === 'url') {
5649
+ const url = dataString;
5650
+ const response = yield fetch(url);
5651
+ if (!response.ok) {
5652
+ throw new Error(`Failed to fetch image: ${response.statusText}`);
6392
5653
  }
6393
- });
6394
- });
6395
- _waitForDbs();
6396
- return () => {
6397
- if (globalSubscription) {
6398
- globalSubscription.unsubscribe();
5654
+ // Get the image as a Blob
5655
+ const blob = yield response.blob();
5656
+ const buffer = yield blob.arrayBuffer();
5657
+ const bufferUint8Array = new Uint8Array(buffer);
5658
+ // Extract the file extension from the URL
5659
+ const extensionMatch = url.match(/\.(jpg|jpeg|png|gif|bmp|webp|svg)$/i);
5660
+ if (!extensionMatch) {
5661
+ throw new Error('Unable to determine the file extension from the URL.');
5662
+ }
5663
+ const fileExtension = extensionMatch[0]; // e.g., ".jpg"
5664
+ // Set the file name (you can customize this)
5665
+ // const fileNameFromUrl = `${transactionId}${fileExtension}`
5666
+ yield fs.promises.writeFile(`/files/images/${transactionId}`, bufferUint8Array, {
5667
+ encoding: 'binary',
5668
+ });
5669
+ continue;
6399
5670
  }
6400
- if (internalSubscription) {
6401
- internalSubscription.unsubscribe();
5671
+ const mimeType = getMimeType(dataString);
5672
+ let fileName = transactionId;
5673
+ if (contentType === 'base64') {
5674
+ if (mimeType) {
5675
+ fileName += `.${mimeType}`;
5676
+ }
5677
+ // Remove the Base64 header if it exists (e.g., "data:image/png;base64,")
5678
+ const base64Data = dataString.split(',').pop() || '';
5679
+ // Decode the Base64 string to binary
5680
+ const binaryString = atob(base64Data);
5681
+ const length = binaryString.length;
5682
+ const binaryData = new Uint8Array(length);
5683
+ for (let i = 0; i < length; i++) {
5684
+ binaryData[i] = binaryString.charCodeAt(i);
5685
+ }
5686
+ yield fs.promises.writeFile(`/files/images/${fileName}`, binaryData, {
5687
+ encoding: 'binary',
5688
+ });
5689
+ // if (dataUint8Array && dataUint8Array instanceof Uint8Array) {
5690
+ // await fs.promises.writeFile(
5691
+ // `/files/images/${fileName}`,
5692
+ // dataUint8Array,
5693
+ // )
5694
+ // }
5695
+ }
5696
+ if (contentType === 'html') {
5697
+ fileName += '.html';
5698
+ yield fs.promises.writeFile(`/files/html/${fileName}`, dataString);
5699
+ }
5700
+ if (contentType === 'json') {
5701
+ fileName += '.json';
5702
+ yield fs.promises.writeFile(`/files/json/${fileName}`, dataString);
6402
5703
  }
6403
- };
6404
- }, []);
6405
- return {
6406
- dbsAreReady,
6407
- };
6408
- };
6409
- const useItemIsReady = () => {
6410
- const [itemListenersReady, setItemListenersReady] = useState(false);
6411
- const itemEventListenersHandler = useCallback((_) => {
6412
- setItemListenersReady(true);
6413
- }, []);
6414
- useEffect(() => {
6415
- const areReady = getAreItemEventHandlersReady();
6416
- if (areReady) {
6417
- itemEventListenersHandler(true);
6418
- }
6419
- eventEmitter.addListener('item.events.setupAllItemsEventHandlers', itemEventListenersHandler);
6420
- return () => {
6421
- eventEmitter.removeListener('item.events.setupAllItemsEventHandlers');
6422
- };
6423
- }, []);
6424
- return {
6425
- isReady: itemListenersReady,
6426
- };
6427
- };
6428
- const useItemProperties = (item) => {
6429
- const [propertyObj, setPropertyObj] = useImmer({});
6430
- useState(false);
6431
- const updatePropertyObj = useCallback((event) => {
6432
- if (!item) {
6433
- console.error('[XXXXXX] [updatePropertyObj] no item when expected');
6434
- return;
6435
5704
  }
6436
- const { propertyName, propertyValue } = event;
6437
- if (!propertyName) {
6438
- return;
5705
+ catch (error) {
5706
+ logger$4(error);
6439
5707
  }
6440
- setPropertyObj((draft) => {
6441
- draft[propertyName] = propertyValue;
5708
+ }
5709
+ });
5710
+
5711
+ let isInitialized = false;
5712
+ const fsInitHandler = (_) => __awaiter(void 0, void 0, void 0, function* () {
5713
+ if (isInitialized) {
5714
+ eventEmitter.emit('fs.init.response', { success: true });
5715
+ return;
5716
+ }
5717
+ try {
5718
+ const handle = yield navigator.storage.getDirectory();
5719
+ // await configure({ backend: WebAccess, handle })
5720
+ yield configureSingle({
5721
+ backend: WebAccess,
5722
+ handle,
6442
5723
  });
6443
- }, [item]);
6444
- useEffect(() => {
6445
- if (!item) {
6446
- return;
6447
- }
6448
- const eventKey = `item.${item.seedLocalId}.property.update`;
6449
- eventEmitter.addListener(eventKey, updatePropertyObj);
6450
- return () => {
6451
- eventEmitter.removeListener(eventKey, updatePropertyObj);
6452
- };
6453
- }, [item]);
6454
- return {
6455
- properties: propertyObj,
6456
- };
5724
+ isInitialized = true;
5725
+ eventEmitter.emit('fs.init.response', { success: true });
5726
+ }
5727
+ catch (e) {
5728
+ if (!isInitialized) {
5729
+ console.error('[fs.init] error initializing fs', e);
5730
+ eventEmitter.emit('fs.init.response', {
5731
+ success: false,
5732
+ error: e,
5733
+ });
5734
+ }
5735
+ // TODO: We can ignore this for now but should figure out if this is being called excessively
5736
+ }
5737
+ });
5738
+ let areReady = false;
5739
+ const setupFsListeners = () => {
5740
+ eventEmitter.addListener('fs.downloadAll.request', downloadAllFilesRequestHandler);
5741
+ eventEmitter.addListener('fs.downloadAllBinary.request', downloadAllFilesBinaryRequestHandler);
5742
+ eventEmitter.addListener('fs.init', fsInitHandler);
5743
+ areReady = true;
6457
5744
  };
6458
- const useCreateItem = (modelName) => {
6459
- const [isCreatingItem, setIsCreatingItem] = useState(false);
6460
- const { isReady } = useItemIsReady();
6461
- const createItem = useCallback((itemData) => __awaiter(void 0, void 0, void 0, function* () {
6462
- if (!isReady) {
6463
- console.error(`[useCreateItem] [createItem] called before listeners are ready`, itemData);
5745
+ const areFsListenersReady = () => {
5746
+ return areReady;
5747
+ };
5748
+ const isFsInitialized = () => {
5749
+ return isInitialized;
5750
+ };
5751
+
5752
+ const logger$3 = debug('app:internal:actors');
5753
+ let sqliteWasmClient;
5754
+ let manager;
5755
+ const validateInput = fromCallback(({ sendBack, input: { event } }) => {
5756
+ const { endpoints, addresses } = event;
5757
+ if (typeof window === 'undefined') {
5758
+ throw new Error('validateInput called from non-browser context');
5759
+ }
5760
+ if (!endpoints || !endpoints.filePaths || !endpoints.files) {
5761
+ throw new Error('validateInput called with invalid endpoints');
5762
+ }
5763
+ if (!addresses || !addresses.length) {
5764
+ throw new Error('validateInput called with invalid addresses');
5765
+ }
5766
+ const _validateInput = () => __awaiter(void 0, void 0, void 0, function* () {
5767
+ sendBack({
5768
+ type: INTERNAL_VALIDATING_INPUT_SUCCESS,
5769
+ endpoints,
5770
+ addresses,
5771
+ });
5772
+ });
5773
+ _validateInput().then(() => {
5774
+ return;
5775
+ });
5776
+ });
5777
+ const prepareDb = fromCallback(({ sendBack, input: { event, context } }) => {
5778
+ const _prepareDb = () => __awaiter(void 0, void 0, void 0, function* () {
5779
+ if (typeof window === 'undefined') {
6464
5780
  return;
6465
5781
  }
6466
- if (isCreatingItem) {
6467
- // TODO: should we setup a queue for this?
6468
- console.error(`[useCreateItem] [createItem] already creating item`, itemData);
5782
+ sqliteWasmClient = yield getSqlite();
5783
+ });
5784
+ const interval = setInterval(() => {
5785
+ // TODO: Add a timeout
5786
+ // TODO: Add a cancel token to the promise so we can prevent more loops starting while we're checking the successful outcome
5787
+ if (sqliteWasmClient) {
5788
+ clearInterval(interval);
5789
+ manager = new SqliteConnectionManager(sqliteWasmClient);
5790
+ sendBack({ type: 'prepareDbSuccess', manager });
6469
5791
  return;
6470
5792
  }
6471
- setIsCreatingItem(true);
6472
- const { seedLocalId } = yield createNewItem(Object.assign({ modelName }, itemData));
6473
- yield Item.find({ modelName, seedLocalId });
6474
- eventEmitter.emit('item.requestAll', { modelName });
6475
- setIsCreatingItem(false);
6476
- }), [isCreatingItem, isReady]);
6477
- return {
6478
- createItem,
6479
- isCreatingItem,
6480
- };
6481
- };
6482
- const useDeleteItem = () => {
6483
- const [isDeletingItem, setIsDeletingItem] = useState(false);
6484
- const destroy = useCallback((item) => __awaiter(void 0, void 0, void 0, function* () {
6485
- if (!item) {
5793
+ _prepareDb().then(() => {
6486
5794
  return;
5795
+ });
5796
+ }, 500);
5797
+ return () => {
5798
+ if (interval) {
5799
+ clearInterval(interval);
6487
5800
  }
6488
- setIsDeletingItem(true);
6489
- const { modelName } = item.getService().getSnapshot().context;
6490
- yield deleteItem({ seedLocalId: item.seedLocalId });
6491
- eventEmitter.emit('item.requestAll', { modelName });
6492
- setIsDeletingItem(false);
6493
- }), [isDeletingItem]);
6494
- useEffect(() => { }, []);
6495
- return {
6496
- deleteItem: destroy,
6497
- isDeletingItem,
6498
5801
  };
6499
- };
6500
- const useGlobalServiceStatus = () => {
6501
- const globalService = getGlobalService();
6502
- const status = useSelector(globalService, (snapshot) => {
6503
- return snapshot.value;
5802
+ });
5803
+ const configureFs = fromCallback(({ sendBack, input: { context } }) => {
5804
+ const { endpoints, seedDbService, appDbService, sdkDbService } = context;
5805
+ logger$3('[internal/actors] [configureFs] Configuring FS');
5806
+ const services = [seedDbService, appDbService, sdkDbService];
5807
+ const _configureFs = () => __awaiter(void 0, void 0, void 0, function* () {
5808
+ logger$3('[internal/actors] [configureFs] calling _configureFs');
5809
+ logger$3('[internal/actors] [configureFs] areFsListenersReady:', areFsListenersReady());
5810
+ logger$3('[internal/actors] [configureFs] isFsInitialized:', isFsInitialized());
5811
+ yield waitForEvent({
5812
+ req: {
5813
+ eventLabel: 'fs.downloadAll.request',
5814
+ data: { endpoints },
5815
+ },
5816
+ res: {
5817
+ eventLabel: 'fs.downloadAll.success',
5818
+ },
5819
+ });
5820
+ yield Promise.all(services.map((service) => __awaiter(void 0, void 0, void 0, function* () {
5821
+ const { dirName } = service.getSnapshot().context;
5822
+ const journalPath = `${BROWSER_FS_TOP_DIR}/${dirName}/db/meta/_journal.json`;
5823
+ const journalExists = yield fs.promises.exists(journalPath);
5824
+ if (journalExists) {
5825
+ service.send({ type: DB_WAITING_FOR_FILES_RECEIVED });
5826
+ }
5827
+ // return new Promise<void>((resolve) => {
5828
+ // const interval = setInterval(() => {
5829
+ // journalExistsSync = fs.existsSync(journalPath)
5830
+ // logger(
5831
+ // '[internal/actors] [configureFs] journalExistsSync:',
5832
+ // journalExistsSync,
5833
+ // )
5834
+ // if (journalExistsSync) {
5835
+ // service.send({ type: DB_WAITING_FOR_FILES_RECEIVED })
5836
+ // clearInterval(interval)
5837
+ // resolve()
5838
+ // }
5839
+ // }, 200)
5840
+ // })
5841
+ })));
5842
+ logger$3('[internal/actors] [configureFs] fs configured!');
6504
5843
  });
6505
- const internalStatus = useSelector(globalService.getSnapshot().context.internalService, (snapshot) => {
6506
- if (!snapshot) {
6507
- return;
6508
- }
6509
- return snapshot.value;
5844
+ // Some of our dependencies use fs sync functions, which don't work with
5845
+ // OPFS. ZenFS creates an async cache of all files so that the sync functions
5846
+ // work, but we have to wait for it to be built. Otherwise things like
5847
+ // drizzleMigrate will fail since they can't see the migration files yet.
5848
+ _configureFs().then(() => {
5849
+ sendBack({ type: INTERNAL_CONFIGURING_FS_SUCCESS });
5850
+ return;
6510
5851
  });
6511
- useSelector(globalService, (snapshot) => {
6512
- return snapshot.context.internalService;
5852
+ return () => { };
5853
+ });
5854
+ const loadSeedDb = fromCallback(({ sendBack, input: { context } }) => {
5855
+ const { seedDbService } = context;
5856
+ if (seedDbService.getSnapshot().value === 'ready') {
5857
+ sendBack({ type: INTERNAL_LOADING_SEED_DB_SUCCESS });
5858
+ return () => { };
5859
+ }
5860
+ let subscription;
5861
+ const _loadSeedDb = () => __awaiter(void 0, void 0, void 0, function* () {
5862
+ yield waitFor(seedDbService, (snapshot) => snapshot.value === 'ready');
5863
+ subscription = seedDbService.subscribe({
5864
+ next: (snapshot) => {
5865
+ sendBack({ type: DB_ON_SNAPSHOT, dbName: DB_NAME_SEED, snapshot });
5866
+ },
5867
+ });
6513
5868
  });
6514
- return {
6515
- status,
6516
- internalStatus,
5869
+ _loadSeedDb().then(() => {
5870
+ sendBack({ type: INTERNAL_LOADING_SEED_DB_SUCCESS });
5871
+ });
5872
+ return () => {
5873
+ if (subscription) {
5874
+ subscription.unsubscribe();
5875
+ }
6517
5876
  };
6518
- };
5877
+ });
5878
+ const saveConfig = fromCallback(({ sendBack, receive, input: { context } }) => {
5879
+ if (typeof window === 'undefined') {
5880
+ console.error('seedInitBrowser called from non-browser context');
5881
+ sendBack({
5882
+ type: 'error',
5883
+ error: 'Browser method called from non-browser context',
5884
+ });
5885
+ }
5886
+ const { endpoints, addresses } = context;
5887
+ if (!endpoints) {
5888
+ throw new Error('saveConfig called with invalid endpoints');
5889
+ }
5890
+ const _saveConfig = () => __awaiter(void 0, void 0, void 0, function* () {
5891
+ // logger('[sdk] [internal/actors] starting _saveConfig')
5892
+ const seedDb = getDb(DB_NAME_SEED);
5893
+ if (!seedDb) {
5894
+ throw new Error('Seed DB not found');
5895
+ }
5896
+ const endpointsValueString = JSON.stringify(endpoints);
5897
+ const addressesValueString = JSON.stringify(addresses);
5898
+ // TODO: Figure out how to define on conflict with multiple rows added
5899
+ try {
5900
+ // logger('[sdk] [internal/actors] Saving endpoints to db')
5901
+ yield seedDb
5902
+ .insert(appState)
5903
+ .values({
5904
+ key: 'endpoints',
5905
+ value: endpointsValueString,
5906
+ })
5907
+ .onConflictDoUpdate({
5908
+ target: appState.key,
5909
+ set: {
5910
+ value: endpointsValueString,
5911
+ },
5912
+ setWhere: sql `key = 'endpoints'`,
5913
+ });
5914
+ // logger('[sdk] [internal/actors] Saving addresses to db')
5915
+ yield seedDb
5916
+ .insert(appState)
5917
+ .values({
5918
+ key: 'addresses',
5919
+ value: addressesValueString,
5920
+ })
5921
+ .onConflictDoUpdate({
5922
+ target: appState.key,
5923
+ set: {
5924
+ value: addressesValueString,
5925
+ },
5926
+ setWhere: sql `key = 'addresses'`,
5927
+ });
5928
+ logger$3('[sdk] [internal/actors] Should be done saving');
5929
+ }
5930
+ catch (error) {
5931
+ console.error('Error saving config:', error);
5932
+ }
5933
+ });
5934
+ _saveConfig().then(() => {
5935
+ logger$3('[sdk] [internal/actors] Successfully saved config');
5936
+ return sendBack({ type: INTERNAL_SAVING_CONFIG_SUCCESS });
5937
+ });
5938
+ return () => { };
5939
+ });
5940
+ const loadAppDb = fromCallback(({ sendBack, input: { context } }) => {
5941
+ const { appDbService } = context;
5942
+ let subscription;
5943
+ const _loadAppDb = () => __awaiter(void 0, void 0, void 0, function* () {
5944
+ return new Promise((resolve) => {
5945
+ if (appDbService.getSnapshot().value === 'ready') {
5946
+ return resolve();
5947
+ }
5948
+ subscription = appDbService.subscribe({
5949
+ next: (snapshot) => {
5950
+ if (snapshot.value === 'ready') {
5951
+ return resolve();
5952
+ }
5953
+ sendBack({ type: DB_ON_SNAPSHOT, dbName: DB_NAME_APP, snapshot });
5954
+ },
5955
+ });
5956
+ });
5957
+ });
5958
+ _loadAppDb().then(() => {
5959
+ sendBack({ type: INTERNAL_LOADING_APP_DB_SUCCESS });
5960
+ logger$3('[sdk] [internal/actors] Successfully loaded app DB');
5961
+ });
5962
+ return () => {
5963
+ if (subscription) {
5964
+ subscription.unsubscribe();
5965
+ }
5966
+ };
5967
+ });
5968
+ const loadSdkDb = fromCallback(({ sendBack, input: { context } }) => {
5969
+ const { sdkDbService } = context;
5970
+ logger$3('[sdk] [internal/actors] Loading SDK DB');
5971
+ let subscription;
5972
+ const _loadSdkDb = () => __awaiter(void 0, void 0, void 0, function* () {
5973
+ return new Promise((resolve) => {
5974
+ if (sdkDbService.getSnapshot().value === 'ready') {
5975
+ return resolve();
5976
+ }
5977
+ subscription = sdkDbService.subscribe({
5978
+ next: (snapshot) => {
5979
+ if (snapshot.value === 'ready') {
5980
+ return resolve();
5981
+ }
5982
+ sendBack({
5983
+ type: DB_ON_SNAPSHOT,
5984
+ dbName: DB_NAME_SDK_CONFIG,
5985
+ snapshot,
5986
+ });
5987
+ },
5988
+ });
5989
+ });
5990
+ });
5991
+ _loadSdkDb().then(() => {
5992
+ sendBack({ type: INTERNAL_LOADING_SDK_DB_SUCCESS });
5993
+ logger$3('[sdk] [internal/actors] Successfully loaded SDK DB');
5994
+ });
5995
+ return () => {
5996
+ if (subscription) {
5997
+ subscription.unsubscribe();
5998
+ }
5999
+ };
6000
+ });
6001
+
6002
+ const logger$2 = debug('app:services:db:machine');
6003
+ const { CHECKING_STATUS, VALIDATING, WAITING_FOR_FILES, CONNECTING_TO_DB, MIGRATING, } = DbState;
6004
+ const dbMachine = setup({
6005
+ types: {
6006
+ context: {},
6007
+ input: {},
6008
+ },
6009
+ actors: {
6010
+ checkStatus,
6011
+ validate,
6012
+ connectToDb,
6013
+ migrate,
6014
+ },
6015
+ }).createMachine({
6016
+ id: MachineIds.DB,
6017
+ initial: CHECKING_STATUS,
6018
+ context: ({ input }) => input,
6019
+ on: {
6020
+ [DB_WAITING_FOR_FILES_RECEIVED]: {
6021
+ actions: assign({
6022
+ hasFiles: ({ event }) => {
6023
+ logger$2('[db/machine] DB_WAITING_FOR_FILES_RECEIVED event:', event);
6024
+ return true;
6025
+ },
6026
+ }),
6027
+ },
6028
+ updateHasFiles: {
6029
+ target: `.${CHECKING_STATUS}`,
6030
+ actions: assign({
6031
+ hasFiles: ({ context, event }) => {
6032
+ logger$2('[db/machine] updateHasFiles event:', event);
6033
+ logger$2('[db/machine] updateHasFiles context:', context);
6034
+ return event.hasFiles;
6035
+ },
6036
+ }),
6037
+ },
6038
+ },
6039
+ // always: {
6040
+ // target: `.${CHECKING_STATUS}`,
6041
+ // guard: ({ context, event }) => context.hasFiles && event.type === 'updateHasFiles',
6042
+ // },
6043
+ states: {
6044
+ idle: {
6045
+ on: {
6046
+ start: CHECKING_STATUS,
6047
+ },
6048
+ meta: {
6049
+ displayText: 'DB starting ...',
6050
+ percentComplete: 0,
6051
+ },
6052
+ },
6053
+ [CHECKING_STATUS]: {
6054
+ on: {
6055
+ [DB_CHECK_STATUS_UPDATE_PATHS]: {
6056
+ actions: assign({
6057
+ pathToDb: ({ event }) => event.pathToDb,
6058
+ pathToDir: ({ event }) => event.pathToDir,
6059
+ pathToDbDir: ({ event }) => event.pathToDbDir,
6060
+ }),
6061
+ },
6062
+ [DB_CHECK_STATUS_EXISTS]: CONNECTING_TO_DB,
6063
+ },
6064
+ invoke: {
6065
+ src: 'checkStatus',
6066
+ input: ({ context, event }) => ({ context, event }),
6067
+ },
6068
+ meta: {
6069
+ displayText: 'Checking DB status',
6070
+ percentComplete: 60,
6071
+ },
6072
+ },
6073
+ [CONNECTING_TO_DB]: {
6074
+ on: {
6075
+ [DB_CREATING_SUCCESS]: {
6076
+ target: VALIDATING,
6077
+ actions: assign({
6078
+ dbId: ({ event }) => event.dbId,
6079
+ }),
6080
+ },
6081
+ },
6082
+ invoke: {
6083
+ src: 'connectToDb',
6084
+ input: ({ context }) => ({ context }),
6085
+ },
6086
+ meta: {
6087
+ displayText: 'Connecting to local DB',
6088
+ percentComplete: 70,
6089
+ },
6090
+ },
6091
+ [VALIDATING]: {
6092
+ on: {
6093
+ [DB_VALIDATING_SUCCESS]: {
6094
+ target: MIGRATING,
6095
+ // guard: ({ context }) => context.hasFiles,
6096
+ },
6097
+ [DB_VALIDATING_WAIT]: {
6098
+ target: WAITING_FOR_FILES,
6099
+ // guard: ({ context }) => !context.hasFiles,
6100
+ },
6101
+ },
6102
+ invoke: {
6103
+ src: 'validate',
6104
+ input: ({ context }) => ({ context }),
6105
+ },
6106
+ meta: {
6107
+ displayText: 'Validating DB',
6108
+ percentComplete: 80,
6109
+ },
6110
+ },
6111
+ // Here we're waiting for migration and schema files to be downloaded
6112
+ [WAITING_FOR_FILES]: {
6113
+ on: {
6114
+ [DB_WAITING_FOR_FILES_RECEIVED]: {
6115
+ target: MIGRATING,
6116
+ actions: assign({
6117
+ hasFiles: true,
6118
+ }),
6119
+ },
6120
+ [DB_MIGRATING_SUCCESS]: 'ready',
6121
+ },
6122
+ entry: ({ context }) => {
6123
+ if (context.hasFiles) {
6124
+ emit({ type: DB_WAITING_FOR_FILES_RECEIVED });
6125
+ }
6126
+ },
6127
+ },
6128
+ [MIGRATING]: {
6129
+ on: {
6130
+ [DB_MIGRATING_WAIT]: WAITING_FOR_FILES,
6131
+ [DB_MIGRATING_SUCCESS]: {
6132
+ target: 'ready',
6133
+ },
6134
+ },
6135
+ invoke: {
6136
+ src: 'migrate',
6137
+ input: ({ context }) => ({ context }),
6138
+ },
6139
+ meta: {
6140
+ displayText: 'Migrating DB',
6141
+ percentComplete: 90,
6142
+ },
6143
+ },
6144
+ ready: {
6145
+ target: 'idle',
6146
+ meta: {
6147
+ displayText: 'Wrapping up the db ...',
6148
+ percentComplete: 100,
6149
+ },
6150
+ },
6151
+ },
6152
+ });
6153
+
6154
+ const logger$1 = debug('app:services:internal:machine');
6155
+ createBrowserInspector({
6156
+ autoStart: false,
6157
+ });
6158
+ const { IDLE, VALIDATING_INPUT, SAVING_CONFIG, CONFIGURING_FS, LOADING_DBS, LOADING_SEED_DB, LOADING_APP_DB, LOADING_SDK_DB, } = InternalState;
6159
+ // Create the state machine
6160
+ const internalMachine = setup({
6161
+ types: {
6162
+ context: {},
6163
+ input: {},
6164
+ },
6165
+ actors: {
6166
+ prepareDb,
6167
+ validateInput,
6168
+ configureFs,
6169
+ loadSeedDb,
6170
+ saveConfig,
6171
+ loadAppDb,
6172
+ loadSdkDb,
6173
+ },
6174
+ }).createMachine({
6175
+ id: MachineIds.INTERNAL,
6176
+ initial: IDLE,
6177
+ context: ({ input }) => {
6178
+ return Object.assign(Object.assign({}, input), { error: undefined, hasFiles: false });
6179
+ },
6180
+ states: {
6181
+ [IDLE]: {
6182
+ on: {
6183
+ reValidate: VALIDATING_INPUT,
6184
+ init: {
6185
+ target: VALIDATING_INPUT,
6186
+ actions: [
6187
+ assign({
6188
+ seedDbService: ({ spawn }) => spawn(dbMachine, {
6189
+ input: {
6190
+ dbName: DB_NAME_SEED,
6191
+ dirName: DB_DIR_NAME_SEED,
6192
+ },
6193
+ }),
6194
+ }),
6195
+ assign({
6196
+ appDbService: ({ spawn }) => spawn(dbMachine, {
6197
+ input: {
6198
+ dbName: DB_NAME_APP,
6199
+ dirName: DB_DIR_NAME_APP,
6200
+ },
6201
+ }),
6202
+ }),
6203
+ assign({
6204
+ sdkDbService: ({ spawn }) => spawn(dbMachine, {
6205
+ input: {
6206
+ dbName: DB_NAME_SDK_CONFIG,
6207
+ dirName: DB_DIR_NAME_SDK,
6208
+ },
6209
+ }),
6210
+ }),
6211
+ ],
6212
+ },
6213
+ },
6214
+ meta: {
6215
+ displayText: 'Waiting for something to happen ...',
6216
+ percentComplete: 0,
6217
+ },
6218
+ },
6219
+ [VALIDATING_INPUT]: {
6220
+ on: {
6221
+ [INTERNAL_VALIDATING_INPUT_SUCCESS]: {
6222
+ target: 'preparingDb',
6223
+ actions: assign({
6224
+ endpoints: ({ event }) => event.endpoints,
6225
+ addresses: ({ event }) => event.addresses,
6226
+ }),
6227
+ },
6228
+ },
6229
+ invoke: {
6230
+ src: 'validateInput',
6231
+ input: ({ context, event }) => ({ context, event }),
6232
+ },
6233
+ meta: {
6234
+ displayText: 'Validating input',
6235
+ percentComplete: 20,
6236
+ },
6237
+ tags: ['loading'],
6238
+ },
6239
+ preparingDb: {
6240
+ on: {
6241
+ prepareDbSuccess: {
6242
+ target: CONFIGURING_FS,
6243
+ },
6244
+ },
6245
+ invoke: {
6246
+ src: 'prepareDb',
6247
+ input: ({ context, event }) => ({ context, event }),
6248
+ },
6249
+ },
6250
+ [CONFIGURING_FS]: {
6251
+ on: {
6252
+ [INTERNAL_CONFIGURING_FS_SUCCESS]: {
6253
+ target: LOADING_SEED_DB,
6254
+ actions: assign({ hasFiles: true }),
6255
+ },
6256
+ },
6257
+ invoke: {
6258
+ src: 'configureFs',
6259
+ input: ({ context, event }) => ({ context, event }),
6260
+ },
6261
+ meta: {
6262
+ displayText: 'Downloading app files',
6263
+ percentComplete: 30,
6264
+ },
6265
+ tags: ['loading'],
6266
+ },
6267
+ // We run this before the other DBs because it holds the config we need to
6268
+ // rebuild. If we get interrupted after this then we don't have to start
6269
+ // from scratch.
6270
+ [LOADING_SEED_DB]: {
6271
+ on: {
6272
+ [INTERNAL_LOADING_SEED_DB_SUCCESS]: SAVING_CONFIG,
6273
+ // [DB_ON_SNAPSHOT]: {
6274
+ // actions: emit(({ event: { snapshot } }) => {
6275
+ // return { type: CHILD_SNAPSHOT, snapshot }
6276
+ // }),
6277
+ // },
6278
+ },
6279
+ invoke: {
6280
+ src: 'loadSeedDb',
6281
+ input: ({ context, event }) => ({ context, event }),
6282
+ },
6283
+ meta: {
6284
+ displayText: 'Loading seed database',
6285
+ percentComplete: 50,
6286
+ },
6287
+ tags: ['loading'],
6288
+ },
6289
+ // Save developer's config to DB
6290
+ [SAVING_CONFIG]: {
6291
+ on: {
6292
+ [INTERNAL_SAVING_CONFIG_SUCCESS]: LOADING_DBS,
6293
+ },
6294
+ invoke: {
6295
+ src: 'saveConfig',
6296
+ input: ({ context, event }) => ({ context, event }),
6297
+ },
6298
+ meta: {
6299
+ displayText: 'Saving configuration',
6300
+ percentComplete: 80,
6301
+ },
6302
+ tags: ['loading'],
6303
+ },
6304
+ // The DBs can be loaded in parallel since they are independent of each other
6305
+ [LOADING_DBS]: {
6306
+ type: 'parallel',
6307
+ states: {
6308
+ [LOADING_APP_DB]: {
6309
+ initial: 'loading',
6310
+ states: {
6311
+ loading: {
6312
+ on: {
6313
+ [INTERNAL_LOADING_APP_DB_SUCCESS]: {
6314
+ target: 'appDbLoaded',
6315
+ actions: () => {
6316
+ logger$1('[sdk] [internal/index] App DB loaded!');
6317
+ },
6318
+ },
6319
+ },
6320
+ invoke: {
6321
+ src: 'loadAppDb',
6322
+ input: ({ context, event }) => ({ context, event }),
6323
+ },
6324
+ },
6325
+ appDbLoaded: {
6326
+ type: 'final',
6327
+ entry: () => {
6328
+ logger$1('[sdk] [internal/index] Entered appDbLoaded!');
6329
+ },
6330
+ },
6331
+ },
6332
+ },
6333
+ [LOADING_SDK_DB]: {
6334
+ initial: 'loading',
6335
+ states: {
6336
+ loading: {
6337
+ on: {
6338
+ [INTERNAL_LOADING_SDK_DB_SUCCESS]: {
6339
+ target: 'sdkConfigDbLoaded',
6340
+ actions: () => {
6341
+ logger$1('[sdk] [internal/index] SDK Config DB loaded!');
6342
+ },
6343
+ },
6344
+ },
6345
+ invoke: {
6346
+ src: 'loadSdkDb',
6347
+ input: ({ context, event }) => ({ context, event }),
6348
+ },
6349
+ },
6350
+ sdkConfigDbLoaded: {
6351
+ type: 'final',
6352
+ entry: () => {
6353
+ logger$1('[sdk] [internal/index] Entered sdkConfigDbLoaded!');
6354
+ },
6355
+ },
6356
+ },
6357
+ },
6358
+ },
6359
+ onDone: {
6360
+ target: 'ready',
6361
+ actions: () => {
6362
+ logger$1('[sdk] [internal/index] All DBs loaded! Should be headed to ready');
6363
+ eventEmitter.emit('allDbsLoaded');
6364
+ },
6365
+ },
6366
+ meta: {
6367
+ displayText: 'Loading databases',
6368
+ percentComplete: 90,
6369
+ },
6370
+ tags: ['loading'],
6371
+ },
6372
+ ready: {
6373
+ entry: () => {
6374
+ logger$1('[sdk] [internal/index] Ready!');
6375
+ },
6376
+ meta: {
6377
+ displayText: "Crossing the t's ...",
6378
+ percentComplete: 90,
6379
+ },
6380
+ },
6381
+ error: {
6382
+ on: {
6383
+ retry: {
6384
+ target: CONFIGURING_FS,
6385
+ actions: assign({ error: undefined }),
6386
+ },
6387
+ },
6388
+ entry: () => {
6389
+ logger$1('[sdk] [internal/index] Error!');
6390
+ },
6391
+ meta: {
6392
+ displayText: 'Whoops! Something went wrong.',
6393
+ percentComplete: null,
6394
+ },
6395
+ tags: ['error'],
6396
+ },
6397
+ },
6398
+ });
6399
+
6400
+ const { UNINITIALIZED, INITIALIZING, INITIALIZED, GETTING_SEED_CLASS, GETTING_SCHEMA_FOR_MODEL, ADDING_MODELS_TO_DB, } = GlobalState;
6401
+ createBrowserInspector({
6402
+ autoStart: false,
6403
+ });
6404
+ const globalMachine = setup({
6405
+ types: {
6406
+ context: {},
6407
+ input: {},
6408
+ },
6409
+ actors: {
6410
+ initialize,
6411
+ addModelsToDb,
6412
+ getSchemaForModel,
6413
+ },
6414
+ }).createMachine({
6415
+ id: MachineIds.GLOBAL,
6416
+ initial: UNINITIALIZED,
6417
+ context: ({ input }) => input,
6418
+ states: {
6419
+ [UNINITIALIZED]: {
6420
+ on: {
6421
+ init: {
6422
+ target: INITIALIZING,
6423
+ guard: ({ context }) => {
6424
+ return typeof window !== 'undefined';
6425
+ },
6426
+ actions: [
6427
+ assign({
6428
+ isInitialized: false,
6429
+ addedModelRecordsToDb: false,
6430
+ models: ({ event }) => event.models,
6431
+ endpoints: ({ event }) => event.endpoints,
6432
+ internalService: ({ spawn, context }) => {
6433
+ return spawn(internalMachine, {
6434
+ systemId: MachineIds.INTERNAL,
6435
+ input: {
6436
+ endpoints: context.endpoints,
6437
+ },
6438
+ });
6439
+ },
6440
+ // fileSystemService: ({ spawn, event }) => {
6441
+ // return spawn(fileSystemMachine, {
6442
+ // systemId: MachineIds.FILE_SYSTEM,
6443
+ // input: {
6444
+ // addresses: event.addresses,
6445
+ // },
6446
+ // })
6447
+ // },
6448
+ }),
6449
+ assign(({ event, spawn }) => {
6450
+ const allItemsServices = {};
6451
+ for (const [modelName, ModelClass] of Object.entries(event.models)) {
6452
+ const service = spawn(itemMachineAll, {
6453
+ systemId: modelName,
6454
+ input: {
6455
+ modelName,
6456
+ ModelClass,
6457
+ modelSchema: ModelClass.schema,
6458
+ items: [],
6459
+ },
6460
+ });
6461
+ allItemsServices[`${modelName}Service`] = service;
6462
+ }
6463
+ return allItemsServices;
6464
+ }),
6465
+ ],
6466
+ },
6467
+ },
6468
+ meta: {
6469
+ displayText: 'Booting up',
6470
+ percentComplete: 5,
6471
+ },
6472
+ tags: ['loading'],
6473
+ },
6474
+ [INITIALIZING]: {
6475
+ on: {
6476
+ [GLOBAL_INITIALIZING_SEND_CONFIG]: {
6477
+ actions: assign({
6478
+ endpoints: ({ event }) => event.endpoints,
6479
+ environment: ({ event }) => event.environment,
6480
+ addresses: ({ event }) => event.addresses,
6481
+ isInitialized: true,
6482
+ }),
6483
+ },
6484
+ [GLOBAL_INITIALIZING_INTERNAL_SERVICE_READY]: ADDING_MODELS_TO_DB,
6485
+ },
6486
+ invoke: {
6487
+ src: 'initialize',
6488
+ input: ({ event, context }) => ({ event, context }),
6489
+ meta: {
6490
+ displayText: 'Initializing Seed SDK',
6491
+ percentComplete: 10,
6492
+ },
6493
+ tags: ['loading'],
6494
+ },
6495
+ },
6496
+ [ADDING_MODELS_TO_DB]: {
6497
+ on: {
6498
+ [GLOBAL_ADDING_MODELS_TO_DB_SUCCESS]: {
6499
+ target: INITIALIZED,
6500
+ actions: assign({
6501
+ addedModelRecordsToDb: true,
6502
+ }),
6503
+ },
6504
+ },
6505
+ invoke: {
6506
+ src: 'addModelsToDb',
6507
+ input: ({ context }) => ({ context }),
6508
+ meta: {
6509
+ displayText: 'Adding models to database',
6510
+ },
6511
+ tags: ['loading'],
6512
+ },
6513
+ },
6514
+ [INITIALIZED]: {
6515
+ type: 'parallel',
6516
+ on: {
6517
+ getSeedClass: `.${GETTING_SEED_CLASS}`,
6518
+ getSchemaForModel: `.${GETTING_SCHEMA_FOR_MODEL}`,
6519
+ },
6520
+ meta: {
6521
+ displayText: 'Global service ready',
6522
+ percentComplete: 40,
6523
+ },
6524
+ tags: ['loading'],
6525
+ states: {
6526
+ [GETTING_SEED_CLASS]: {
6527
+ entry: [
6528
+ (_a) => __awaiter(void 0, [_a], void 0, function* ({ context }) {
6529
+ let SeedClass;
6530
+ if (context.environment === 'node') {
6531
+ const { SeedNode } = yield import('./seed-C8JBI4UL.js');
6532
+ SeedClass = SeedNode;
6533
+ }
6534
+ else {
6535
+ const { SeedBrowser } = yield import('./seed-CJB6INNH.js');
6536
+ SeedClass = SeedBrowser;
6537
+ }
6538
+ return SeedClass;
6539
+ }),
6540
+ ],
6541
+ meta: {
6542
+ displayText: 'Getting SeedClass',
6543
+ },
6544
+ tags: ['loading'],
6545
+ },
6546
+ [GETTING_SCHEMA_FOR_MODEL]: {
6547
+ invoke: {
6548
+ src: 'getSchemaForModel',
6549
+ input: ({ event, context }) => ({ event, context }),
6550
+ meta: {
6551
+ displayText: 'Getting schema for model',
6552
+ },
6553
+ tags: ['loading'],
6554
+ },
6555
+ },
6556
+ },
6557
+ },
6558
+ },
6559
+ // on: {
6560
+ // '*': {
6561
+ // actions: emit(({ event }) => {
6562
+ // return event
6563
+ // }),
6564
+ // },
6565
+ // },
6566
+ });
6567
+ const globalService = createActor(globalMachine, {
6568
+ input: {},
6569
+ // inspect,
6570
+ inspect: (inspEvent) => {
6571
+ eventEmitter.emit('inspect.globalService', inspEvent);
6572
+ // console.log('[sdk] [service/index] inspEvent', inspEvent)
6573
+ // eventEmitter.emit('globalService', inspEvent)
6574
+ // let eventType: string = inspEvent.type
6575
+ // if (inspEvent.event && inspEvent.event.type) {
6576
+ // eventType = inspEvent.event.type
6577
+ // }
6578
+ //
6579
+ // if (typeof eventType === 'object') {
6580
+ // eventType = JSON.stringify(eventType)
6581
+ // }
6582
+ //
6583
+ // let srcId = inspEvent.actorRef.id
6584
+ //
6585
+ // if (!srcId.includes('seedSdk')) {
6586
+ // srcId = inspEvent.actorRef.logic.config.id
6587
+ // }
6588
+ //
6589
+ // if (inspEvent.type === '@xstate.snapshot') {
6590
+ // if (
6591
+ // inspEvent.event.type === CHILD_SNAPSHOT &&
6592
+ // inspEvent.snapshot &&
6593
+ // inspEvent.snapshot.machine.id === MachineIds.GLOBAL
6594
+ // ) {
6595
+ // return
6596
+ // }
6597
+ // if (inspEvent.snapshot && inspEvent.snapshot.value) {
6598
+ // if (typeof window !== 'undefined') {
6599
+ // eventEmitter.emit('globalService', {
6600
+ // type: eventType,
6601
+ // src: srcId,
6602
+ // snapshot: inspEvent.snapshot,
6603
+ // })
6604
+ // }
6605
+ // }
6606
+ // } else {
6607
+ // if (typeof window !== 'undefined') {
6608
+ // let snapshot
6609
+ //
6610
+ // try {
6611
+ // snapshot = inspEvent.actorRef.getSnapshot()
6612
+ // } catch (e) {
6613
+ // // This fails if the actor hasn't initialized yet, but that's OK I think
6614
+ // // console.log('[sdk] [service/index] ERROR', e)
6615
+ // }
6616
+ //
6617
+ // eventEmitter.emit('globalService', {
6618
+ // type: eventType,
6619
+ // src: srcId,
6620
+ // snapshot,
6621
+ // })
6622
+ // }
6623
+ // }
6624
+ },
6625
+ });
6626
+ globalService.start();
6627
+ const getGlobalService = () => globalService;
6519
6628
 
6520
6629
  const logger = debug('app:services:events');
6521
6630
  const handleServiceSaveState = (event) => {
@@ -6527,5 +6636,5 @@ const setupServicesEventHandlers = () => {
6527
6636
  eventEmitter.addListener('service.saveState.request', handleServiceSaveState);
6528
6637
  };
6529
6638
 
6530
- export { useDeleteItem as $, APP_DB_CONFIG as A, setupFsListeners as B, CHILD_SNAPSHOT as C, DB_NAME_SDK_CONFIG as D, setupAllItemsEventHandlers as E, setupServicesEventHandlers as F, GET_SCHEMAS as G, globalService as H, Item as I, Json as J, getModel as K, List as L, Model as M, getModels as N, getModelNames as O, Property as P, areFsListenersReady as Q, Relation as R, SCHEMA_NJK as S, Text as T, ItemProperty as U, useItems as V, useItem as W, useItemProperties as X, useCreateItem as Y, useItemProperty as Z, __awaiter as _, GET_SEEDS as a, getGlobalService as a0, getCorrectId as a1, GET_SEED_IDS as b, GET_STORAGE_TRANSACTION_ID as c, GET_VERSIONS as d, GET_PROPERTIES as e, GET_ALL_PROPERTIES_FOR_ALL_VERSIONS as f, itemMachineAll as g, internalMachine as h, itemMachineSingle as i, isNode as j, isBrowser as k, isReactNative as l, __decorate as m, __metadata as n, models as o, SCHEMA_TS as p, SDK_DB_CONFIG as q, SEED_DB_CONFIG as r, addModelsToInternalDb as s, ImageSrc as t, createNewMetadataFromExistingRecord as u, generateId as v, eventEmitter as w, getDb as x, DB_NAME_APP as y, setModel as z };
6531
- //# sourceMappingURL=events-DbpQM9qG.js.map
6639
+ export { useDeleteItem as $, APP_DB_CONFIG as A, setupFsListeners as B, CHILD_SNAPSHOT as C, DB_NAME_SDK_CONFIG as D, setupAllItemsEventHandlers as E, setupServicesEventHandlers as F, GET_SCHEMAS as G, globalService as H, Item as I, Json as J, getModel as K, List as L, Model as M, getModels as N, getModelNames as O, Property as P, areFsListenersReady as Q, Relation as R, SCHEMA_NJK as S, Text as T, ItemProperty as U, useItems as V, useItem as W, useItemProperties as X, useCreateItem as Y, useItemProperty as Z, __awaiter as _, GET_SEEDS as a, useServices as a0, getGlobalService as a1, getCorrectId as a2, GET_SEED_IDS as b, GET_STORAGE_TRANSACTION_ID as c, GET_VERSIONS as d, GET_PROPERTIES as e, GET_ALL_PROPERTIES_FOR_ALL_VERSIONS as f, itemMachineAll as g, internalMachine as h, itemMachineSingle as i, isNode as j, isBrowser as k, isReactNative as l, __decorate as m, __metadata as n, models as o, SCHEMA_TS as p, SDK_DB_CONFIG as q, SEED_DB_CONFIG as r, addModelsToInternalDb as s, ImageSrc as t, createNewMetadataFromExistingRecord as u, generateId as v, eventEmitter as w, getDb as x, DB_NAME_APP as y, setModel as z };
6640
+ //# sourceMappingURL=events-DgKqHqww.js.map