@seedprotocol/sdk 0.1.17 → 0.1.19

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 (167) hide show
  1. package/dist/bin.js +102 -228
  2. package/dist/bin.js.map +1 -1
  3. package/dist/constants-KW2RTtZB.js +97 -0
  4. package/dist/constants-KW2RTtZB.js.map +1 -0
  5. package/dist/{events-CRCYmF7M.js → index-D3JMvAuO.js} +1769 -1749
  6. package/dist/index-D3JMvAuO.js.map +1 -0
  7. package/dist/{index-DR_FgAUY.js → index-scU0pJvR.js} +19 -18
  8. package/dist/index-scU0pJvR.js.map +1 -0
  9. package/dist/main.js +16 -416
  10. package/dist/main.js.map +1 -1
  11. package/dist/node/codegen/templates/index.njk +8 -0
  12. package/dist/{seed-CjMH4SeR.js → seed-BDG7IW-o.js} +19 -18
  13. package/dist/seed-BDG7IW-o.js.map +1 -0
  14. package/dist/{seed-Dn2R3xbp.js → seed-DBkf4fbe.js} +3 -2
  15. package/dist/seed-DBkf4fbe.js.map +1 -0
  16. package/dist/{seed-BJPS_-pY.js → seed-Dpo8KWqz.js} +20 -19
  17. package/dist/seed-Dpo8KWqz.js.map +1 -0
  18. package/dist/{seed.schema.config-GKCk8sOV.js → seed.schema.config-CCYo8gj-.js} +17 -16
  19. package/dist/seed.schema.config-CCYo8gj-.js.map +1 -0
  20. package/dist/shared/configs/browser.app.db.config.ts +1 -6
  21. package/dist/shared/{sdkSchema/modelUidSchema.ts → seedSchema/ModelUidSchema.ts} +1 -1
  22. package/dist/shared/{sdkSchema/propertyUidSchema.ts → seedSchema/PropertyUidSchema.ts} +1 -1
  23. package/dist/shared/seedSchema/index.ts +8 -0
  24. package/dist/types/scripts/bin.d.ts.map +1 -1
  25. package/dist/types/src/browser/db/index.d.ts +1 -4
  26. package/dist/types/src/browser/db/index.d.ts.map +1 -1
  27. package/dist/types/src/browser/db/read.d.ts +1 -1
  28. package/dist/types/src/browser/db/read.d.ts.map +1 -1
  29. package/dist/types/src/browser/db/save.d.ts.map +1 -1
  30. package/dist/types/src/browser/db/sqlWasmClient.d.ts +8 -1
  31. package/dist/types/src/browser/db/sqlWasmClient.d.ts.map +1 -1
  32. package/dist/types/src/browser/db/write.d.ts.map +1 -1
  33. package/dist/types/src/browser/events/files/download.d.ts.map +1 -1
  34. package/dist/types/src/browser/events/item/syncDbWithEas.d.ts +2 -1
  35. package/dist/types/src/browser/events/item/syncDbWithEas.d.ts.map +1 -1
  36. package/dist/types/src/browser/events/property/save.d.ts.map +1 -1
  37. package/dist/types/src/browser/events/property/saveRelation.d.ts.map +1 -1
  38. package/dist/types/src/browser/item/all/actors/fetchRelatedItems.d.ts +2 -1
  39. package/dist/types/src/browser/item/all/actors/fetchRelatedItems.d.ts.map +1 -1
  40. package/dist/types/src/browser/item/all/actors/initialize.d.ts.map +1 -1
  41. package/dist/types/src/browser/property/actors/hydrateFromDb.d.ts +1 -2
  42. package/dist/types/src/browser/property/actors/hydrateFromDb.d.ts.map +1 -1
  43. package/dist/types/src/browser/property/actors/initialize.d.ts +1 -2
  44. package/dist/types/src/browser/property/actors/initialize.d.ts.map +1 -1
  45. package/dist/types/src/browser/property/actors/waitForDb.d.ts +3 -1
  46. package/dist/types/src/browser/property/actors/waitForDb.d.ts.map +1 -1
  47. package/dist/types/src/browser/react/property.d.ts +2 -1
  48. package/dist/types/src/browser/react/property.d.ts.map +1 -1
  49. package/dist/types/src/browser/react/services.d.ts +1 -6
  50. package/dist/types/src/browser/react/services.d.ts.map +1 -1
  51. package/dist/types/src/browser/schema/file/fetchAll/actors.d.ts.map +1 -1
  52. package/dist/types/src/browser/services/db/actors/checkStatus.d.ts +4 -0
  53. package/dist/types/src/browser/services/db/actors/checkStatus.d.ts.map +1 -0
  54. package/dist/types/src/browser/services/db/actors/connectToDb.d.ts +4 -0
  55. package/dist/types/src/browser/services/db/actors/connectToDb.d.ts.map +1 -0
  56. package/dist/types/src/browser/services/db/actors/migrate.d.ts +5 -0
  57. package/dist/types/src/browser/services/db/actors/migrate.d.ts.map +1 -0
  58. package/dist/types/src/browser/services/db/actors/validate.d.ts +3 -0
  59. package/dist/types/src/browser/services/db/actors/validate.d.ts.map +1 -0
  60. package/dist/types/src/browser/services/db/dbMachine.d.ts +48 -0
  61. package/dist/types/src/browser/services/db/dbMachine.d.ts.map +1 -0
  62. package/dist/types/src/browser/services/global/actors/addModelsToDb.d.ts +4 -0
  63. package/dist/types/src/browser/services/global/actors/addModelsToDb.d.ts.map +1 -0
  64. package/dist/types/src/browser/services/global/actors/getSchemaForModel.d.ts +4 -0
  65. package/dist/types/src/browser/services/global/actors/getSchemaForModel.d.ts.map +1 -0
  66. package/dist/types/src/browser/services/global/actors/initialize.d.ts +3 -1
  67. package/dist/types/src/browser/services/global/actors/initialize.d.ts.map +1 -1
  68. package/dist/types/src/browser/services/global/globalMachine.d.ts +72 -4
  69. package/dist/types/src/browser/services/global/globalMachine.d.ts.map +1 -1
  70. package/dist/types/src/browser/services/internal/actors/configureFs.d.ts +3 -1
  71. package/dist/types/src/browser/services/internal/actors/configureFs.d.ts.map +1 -1
  72. package/dist/types/src/browser/services/internal/actors/loadAppDb.d.ts +3 -1
  73. package/dist/types/src/browser/services/internal/actors/loadAppDb.d.ts.map +1 -1
  74. package/dist/types/src/browser/services/internal/actors/prepareDb.d.ts +2 -1
  75. package/dist/types/src/browser/services/internal/actors/prepareDb.d.ts.map +1 -1
  76. package/dist/types/src/browser/services/internal/actors/saveConfig.d.ts +3 -1
  77. package/dist/types/src/browser/services/internal/actors/saveConfig.d.ts.map +1 -1
  78. package/dist/types/src/browser/services/internal/constants.d.ts +0 -8
  79. package/dist/types/src/browser/services/internal/constants.d.ts.map +1 -1
  80. package/dist/types/src/browser/services/internal/internalMachine.d.ts +1 -2
  81. package/dist/types/src/browser/services/internal/internalMachine.d.ts.map +1 -1
  82. package/dist/types/src/browser/services/syncDbWithEas/actors.d.ts.map +1 -1
  83. package/dist/types/src/node/codegen/drizzle.d.ts +1 -1
  84. package/dist/types/src/node/codegen/drizzle.d.ts.map +1 -1
  85. package/dist/types/src/node/constants.d.ts +2 -9
  86. package/dist/types/src/node/constants.d.ts.map +1 -1
  87. package/dist/types/src/node/db/index.d.ts +2 -2
  88. package/dist/types/src/node/db/index.d.ts.map +1 -1
  89. package/dist/types/src/node/db/node.app.db.config.d.ts +4 -0
  90. package/dist/types/src/node/db/node.app.db.config.d.ts.map +1 -0
  91. package/dist/types/src/node/helpers/index.d.ts +1 -1
  92. package/dist/types/src/node/helpers/index.d.ts.map +1 -1
  93. package/dist/types/src/shared/configs/browser.app.db.config.d.ts.map +1 -1
  94. package/dist/types/src/shared/helpers/constants.d.ts +0 -5
  95. package/dist/types/src/shared/helpers/constants.d.ts.map +1 -1
  96. package/dist/types/src/shared/helpers/db.d.ts.map +1 -1
  97. package/dist/types/src/shared/seedSchema/AppStateSchema.d.ts.map +1 -0
  98. package/dist/types/src/shared/{sdkSchema/configSchema.d.ts → seedSchema/ConfigSchema.d.ts} +1 -1
  99. package/dist/types/src/shared/seedSchema/ConfigSchema.d.ts.map +1 -0
  100. package/dist/types/src/{browser/db → shared}/seedSchema/MetadataSchema.d.ts.map +1 -1
  101. package/dist/types/src/shared/{sdkSchema/modelSchema.d.ts → seedSchema/ModelSchema.d.ts} +1 -1
  102. package/dist/types/src/shared/seedSchema/ModelSchema.d.ts.map +1 -0
  103. package/dist/types/src/shared/{sdkSchema/modelUidSchema.d.ts → seedSchema/ModelUidSchema.d.ts} +1 -1
  104. package/dist/types/src/shared/seedSchema/ModelUidSchema.d.ts.map +1 -0
  105. package/dist/types/src/shared/{sdkSchema/propertyUidSchema.d.ts → seedSchema/PropertyUidSchema.d.ts} +1 -1
  106. package/dist/types/src/shared/seedSchema/PropertyUidSchema.d.ts.map +1 -0
  107. package/dist/types/src/shared/seedSchema/SeedSchema.d.ts.map +1 -0
  108. package/dist/types/src/shared/seedSchema/VersionSchema.d.ts.map +1 -0
  109. package/dist/types/src/shared/seedSchema/index.d.ts +9 -0
  110. package/dist/types/src/shared/seedSchema/index.d.ts.map +1 -0
  111. package/dist/types/src/types/item.d.ts +2 -2
  112. package/dist/types/src/types/item.d.ts.map +1 -1
  113. package/dist/types/src/types/machines.d.ts +45 -2
  114. package/dist/types/src/types/machines.d.ts.map +1 -1
  115. package/dist/types/src/types/services.d.ts +1 -0
  116. package/dist/types/src/types/services.d.ts.map +1 -0
  117. package/package.json +42 -42
  118. package/dist/browser/db/seedSchema/index.ts +0 -4
  119. package/dist/events-CRCYmF7M.js.map +0 -1
  120. package/dist/index-DR_FgAUY.js.map +0 -1
  121. package/dist/seed-BJPS_-pY.js.map +0 -1
  122. package/dist/seed-CjMH4SeR.js.map +0 -1
  123. package/dist/seed-Dn2R3xbp.js.map +0 -1
  124. package/dist/seed.schema.config-GKCk8sOV.js.map +0 -1
  125. package/dist/shared/configs/sdk.db.config.ts +0 -33
  126. package/dist/shared/sdkSchema/index.ts +0 -4
  127. package/dist/types/src/browser/db/seedSchema/AppStateSchema.d.ts.map +0 -1
  128. package/dist/types/src/browser/db/seedSchema/SeedSchema.d.ts.map +0 -1
  129. package/dist/types/src/browser/db/seedSchema/VersionSchema.d.ts.map +0 -1
  130. package/dist/types/src/browser/db/seedSchema/index.d.ts +0 -5
  131. package/dist/types/src/browser/db/seedSchema/index.d.ts.map +0 -1
  132. package/dist/types/src/browser/events/item/delete.d.ts +0 -2
  133. package/dist/types/src/browser/events/item/delete.d.ts.map +0 -1
  134. package/dist/types/src/browser/services/db/actors.d.ts +0 -12
  135. package/dist/types/src/browser/services/db/actors.d.ts.map +0 -1
  136. package/dist/types/src/browser/services/db/machine.d.ts +0 -3
  137. package/dist/types/src/browser/services/db/machine.d.ts.map +0 -1
  138. package/dist/types/src/browser/services/global/actors.d.ts +0 -4
  139. package/dist/types/src/browser/services/global/actors.d.ts.map +0 -1
  140. package/dist/types/src/browser/services/internal/actors/loadSdkDb.d.ts +0 -2
  141. package/dist/types/src/browser/services/internal/actors/loadSdkDb.d.ts.map +0 -1
  142. package/dist/types/src/browser/services/internal/actors/loadSeedDb.d.ts +0 -2
  143. package/dist/types/src/browser/services/internal/actors/loadSeedDb.d.ts.map +0 -1
  144. package/dist/types/src/node/db/helpers.d.ts +0 -2
  145. package/dist/types/src/node/db/helpers.d.ts.map +0 -1
  146. package/dist/types/src/node/db/internal.d.ts +0 -5
  147. package/dist/types/src/node/db/internal.d.ts.map +0 -1
  148. package/dist/types/src/shared/configs/sdk.db.config.d.ts +0 -3
  149. package/dist/types/src/shared/configs/sdk.db.config.d.ts.map +0 -1
  150. package/dist/types/src/shared/sdkSchema/configSchema.d.ts.map +0 -1
  151. package/dist/types/src/shared/sdkSchema/index.d.ts +0 -5
  152. package/dist/types/src/shared/sdkSchema/index.d.ts.map +0 -1
  153. package/dist/types/src/shared/sdkSchema/modelSchema.d.ts.map +0 -1
  154. package/dist/types/src/shared/sdkSchema/modelUidSchema.d.ts.map +0 -1
  155. package/dist/types/src/shared/sdkSchema/propertyUidSchema.d.ts.map +0 -1
  156. package/dist/types/src/sqlite.d.ts +0 -2
  157. package/dist/types/src/sqlite.d.ts.map +0 -1
  158. /package/dist/{browser/db → shared}/seedSchema/AppStateSchema.ts +0 -0
  159. /package/dist/shared/{sdkSchema/configSchema.ts → seedSchema/ConfigSchema.ts} +0 -0
  160. /package/dist/{browser/db → shared}/seedSchema/MetadataSchema.ts +0 -0
  161. /package/dist/shared/{sdkSchema/modelSchema.ts → seedSchema/ModelSchema.ts} +0 -0
  162. /package/dist/{browser/db → shared}/seedSchema/SeedSchema.ts +0 -0
  163. /package/dist/{browser/db → shared}/seedSchema/VersionSchema.ts +0 -0
  164. /package/dist/types/src/{browser/db → shared}/seedSchema/AppStateSchema.d.ts +0 -0
  165. /package/dist/types/src/{browser/db → shared}/seedSchema/MetadataSchema.d.ts +0 -0
  166. /package/dist/types/src/{browser/db → shared}/seedSchema/SeedSchema.d.ts +0 -0
  167. /package/dist/types/src/{browser/db → shared}/seedSchema/VersionSchema.d.ts +0 -0
@@ -1,30 +1,31 @@
1
+ import { _ as __awaiter, d as __rest, i as internalPropertyNames, I as INTERNAL_DATA_TYPES } from './constants-KW2RTtZB.js';
2
+ import path, { basename } from 'path';
3
+ import 'reflect-metadata';
4
+ import { Type } from '@sinclair/typebox';
1
5
  import { fromCallback, setup, assign, createActor, waitFor, emit } from 'xstate';
2
- import { createBrowserInspector } from '@statelyai/inspect';
6
+ import { sql, relations, and, eq, max, or, count, isNull } from 'drizzle-orm';
3
7
  import { fs, configureSingle } from '@zenfs/core';
4
- import { sql, count, max, eq, and, or, isNull, relations } from 'drizzle-orm';
5
- import { drizzle } from 'drizzle-orm/sqlite-proxy';
8
+ import 'dayjs';
9
+ import { customAlphabet } from 'nanoid';
10
+ import * as nanoIdDictionary from 'nanoid-dictionary';
6
11
  import debug from 'debug';
12
+ import { startCase, debounce, camelCase, orderBy } from 'lodash-es';
13
+ import { sqliteTable, text, int, blob, check, unique } from 'drizzle-orm/sqlite-core';
14
+ import EventEmitter from 'eventemitter3';
7
15
  import { QueryClient } from '@tanstack/react-query';
8
16
  import { GraphQLClient } from 'graphql-request';
9
17
  import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister';
10
18
  import { persistQueryClient } from '@tanstack/react-query-persist-client';
11
- import path, { basename } from 'path';
12
- import { sqliteTable, text, int, blob, check, unique } from 'drizzle-orm/sqlite-core';
13
- import 'dayjs';
14
- import { customAlphabet } from 'nanoid';
15
- import * as nanoIdDictionary from 'nanoid-dictionary';
16
- import { WebAccess } from '@zenfs/dom';
17
- import Arweave from 'arweave';
18
- import { startCase, debounce, camelCase, orderBy } from 'lodash-es';
19
+ import { BehaviorSubject } from 'rxjs';
20
+ import { immerable, produce, enableMapSet } from 'immer';
19
21
  import pluralize from 'pluralize';
22
+ import Arweave from 'arweave';
20
23
  import { useState, useCallback, useEffect, useRef } from 'react';
21
- import { BehaviorSubject } from 'rxjs';
22
- import { immerable, produce } from 'immer';
23
24
  import { useImmer } from 'use-immer';
24
25
  import { useSelector } from '@xstate/react';
25
- import 'reflect-metadata';
26
- import { Type } from '@sinclair/typebox';
27
- import EventEmitter from 'eventemitter3';
26
+ import { createBrowserInspector } from '@statelyai/inspect';
27
+ import { drizzle } from 'drizzle-orm/sqlite-proxy';
28
+ import { WebAccess } from '@zenfs/dom';
28
29
 
29
30
  const isNode = () => {
30
31
  return (typeof process !== 'undefined' &&
@@ -38,686 +39,208 @@ const isReactNative = () => {
38
39
  return typeof navigator !== 'undefined' && navigator.product === 'ReactNative';
39
40
  };
40
41
 
41
- /******************************************************************************
42
- Copyright (c) Microsoft Corporation.
43
-
44
- Permission to use, copy, modify, and/or distribute this software for any
45
- purpose with or without fee is hereby granted.
46
-
47
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
48
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
49
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
50
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
51
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
52
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
53
- PERFORMANCE OF THIS SOFTWARE.
54
- ***************************************************************************** */
55
- /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
56
-
57
-
58
- function __rest(s, e) {
59
- var t = {};
60
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
61
- t[p] = s[p];
62
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
63
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
64
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
65
- t[p[i]] = s[p[i]];
66
- }
67
- return t;
68
- }
69
-
70
- function __decorate(decorators, target, key, desc) {
71
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
72
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
73
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
74
- return c > 3 && r && Object.defineProperty(target, key, r), r;
75
- }
76
-
77
- function __metadata(metadataKey, metadataValue) {
78
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
79
- }
80
-
81
- function __awaiter(thisArg, _arguments, P, generator) {
82
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
83
- return new (P || (P = Promise))(function (resolve, reject) {
84
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
85
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
86
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
87
- step((generator = generator.apply(thisArg, _arguments || [])).next());
88
- });
89
- }
90
-
91
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
92
- var e = new Error(message);
93
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
42
+ const withSeed$1 = (config, webpack, isServer) => {
43
+ // If you need to include directories outside of the project root
44
+ // config.module.rules.push({
45
+ // test: /\.ts$/,
46
+ // include: [path.resolve(process.cwd(), 'schema.ts')],
47
+ // use: 'ts-loader',
48
+ // })
49
+ config.plugins.push(
50
+ // new webpack.DefinePlugin({
51
+ // __dirname: JSON.stringify(__dirname),
52
+ // }),
53
+ new webpack.NormalModuleReplacementPlugin(/node:/, (resource) => {
54
+ resource.request = resource.request.replace(/^node:/, '');
55
+ }));
56
+ // config.externals.push({
57
+ // 'fsevents': 'commonjs2 fsevents',
58
+ // })
59
+ // console.log('__dirname:', __dirname)
60
+ // console.log('process.cwd():', process.cwd())
61
+ // console.log('crypto-browserify exists:', fs.existsSync(path.resolve(process.cwd(), './node_modules/crypto-browserify')))
62
+ // console.log('path-browserify exists:', fs.existsSync(path.resolve(process.cwd(), './node_modules/path-browserify')))
63
+ if (!isServer) {
64
+ console.log('config.resolve.alias:', config.resolve.alias);
65
+ config.resolve.alias['fs'] = path.resolve(process.cwd(), './node_modules/@zenfs/core');
66
+ config.resolve.alias['node:fs'] = path.resolve(process.cwd(), './node_modules/@zenfs/core');
67
+ config.resolve.alias['@schema'] = path.resolve(process.cwd(), 'schema.ts');
68
+ // config.resolve.alias['crypto'] = path.resolve(process.cwd(), './node_modules/crypto-browserify')
69
+ // config.resolve.alias['node:crypto'] = path.resolve(process.cwd(), './node_modules/crypto-browserify')
70
+ config.resolve.alias['node:path'] = path.resolve(process.cwd(), './node_modules/path-browserify');
71
+ config.resolve.alias['path'] = path.resolve(process.cwd(), './node_modules/path-browserify');
72
+ }
73
+ if (isServer) {
74
+ config.externals.push('@sqlite.org/sqlite-wasm');
75
+ config.externals.push('nunjucks');
76
+ config.externals.push('chokidar');
77
+ config.externals.push('arweave');
78
+ }
79
+ // config.module.rules.push({
80
+ // test: /seed\.config\.mjs$/,
81
+ // use: [
82
+ // {
83
+ // loader: 'babel-loader',
84
+ // options: {
85
+ // plugins: ['@babel/plugin-syntax-dynamic-import'],
86
+ // },
87
+ // },
88
+ // ],
89
+ // })
90
+ return config;
94
91
  };
95
92
 
96
- var MachineIds;
97
- (function (MachineIds) {
98
- MachineIds["GLOBAL"] = "@seedSdk/global";
99
- MachineIds["INTERNAL"] = "@seedSdk/internal";
100
- MachineIds["DB"] = "@seedSdk/db";
101
- MachineIds["EAS"] = "@seedSdk/eas";
102
- MachineIds["ITEM"] = "@seedSdk/item";
103
- MachineIds["ALL_ITEMS"] = "@seedSdk/allItems";
104
- MachineIds["MODEL"] = "@seedSdk/model";
105
- MachineIds["FILE_SYSTEM"] = "@seedSdk/fileSystem";
106
- })(MachineIds || (MachineIds = {}));
107
- const { INTERNAL, DB, GLOBAL, EAS, MODEL } = MachineIds;
108
- var GlobalState;
109
- (function (GlobalState) {
110
- GlobalState["UNINITIALIZED"] = "uninitialized";
111
- GlobalState["INITIALIZING"] = "initializing";
112
- GlobalState["INITIALIZED"] = "initialized";
113
- GlobalState["GETTING_SEED_CLASS"] = "gettingSeedClass";
114
- GlobalState["GETTING_SCHEMA_FOR_MODEL"] = "gettingSchemaForModel";
115
- GlobalState["GETTING_TABLE_FOR_MODEL"] = "gettingTableForModel";
116
- GlobalState["GETTING_MODEL_CLASS"] = "gettingModelClass";
117
- GlobalState["ADDING_MODELS_TO_DB"] = "addingModelsToDb";
118
- })(GlobalState || (GlobalState = {}));
119
- const { UNINITIALIZED: UNINITIALIZED$1, INITIALIZING: INITIALIZING$1, INITIALIZED: INITIALIZED$1, GETTING_SEED_CLASS: GETTING_SEED_CLASS$1, GETTING_SCHEMA_FOR_MODEL: GETTING_SCHEMA_FOR_MODEL$1, GETTING_TABLE_FOR_MODEL, GETTING_MODEL_CLASS, ADDING_MODELS_TO_DB: ADDING_MODELS_TO_DB$1, } = GlobalState;
120
- var InternalState;
121
- (function (InternalState) {
122
- InternalState["IDLE"] = "idle";
123
- InternalState["INITIALIZING"] = "initializing";
124
- InternalState["VALIDATING_INPUT"] = "validatingInput";
125
- InternalState["CONFIGURING_FS"] = "configuringFs";
126
- InternalState["LOADING_SEED_DB"] = "loadingSeedDb";
127
- InternalState["SAVING_CONFIG"] = "savingConfig";
128
- InternalState["LOADING_DBS"] = "loadingDbs";
129
- InternalState["LOADING_APP_DB"] = "loadingAppDb";
130
- InternalState["LOADING_SDK_DB"] = "loadingSdkDb";
131
- })(InternalState || (InternalState = {}));
132
- const { VALIDATING_INPUT: VALIDATING_INPUT$1, CONFIGURING_FS: CONFIGURING_FS$1, LOADING_SEED_DB: LOADING_SEED_DB$1, LOADING_APP_DB: LOADING_APP_DB$1, LOADING_SDK_DB: LOADING_SDK_DB$1, } = InternalState;
133
- var DbState;
134
- (function (DbState) {
135
- DbState["CHECKING_STATUS"] = "checkingStatus";
136
- DbState["WAITING_FOR_FILES"] = "waitingForFiles";
137
- DbState["VALIDATING"] = "validating";
138
- DbState["CONNECTING_TO_DB"] = "connectingToDb";
139
- // FETCHING_MIGRATIONS = 'fetchingMigrations',
140
- DbState["MIGRATING"] = "migrating";
141
- })(DbState || (DbState = {}));
142
- const { CHECKING_STATUS: CHECKING_STATUS$1, VALIDATING: VALIDATING$1, CONNECTING_TO_DB: CONNECTING_TO_DB$1, WAITING_FOR_FILES: WAITING_FOR_FILES$1, MIGRATING: MIGRATING$1, } = DbState;
143
- const INTERNAL_VALIDATING_INPUT_SUCCESS = `${INTERNAL}.${VALIDATING_INPUT$1}.success`;
144
- const INTERNAL_CONFIGURING_FS_SUCCESS = `${INTERNAL}.${CONFIGURING_FS$1}.success`;
145
- const INTERNAL_LOADING_SEED_DB_SUCCESS = `${INTERNAL}.${LOADING_SEED_DB$1}.success`;
146
- const INTERNAL_LOADING_APP_DB_SUCCESS = `${INTERNAL}.${LOADING_APP_DB$1}.success`;
147
- const INTERNAL_LOADING_SDK_DB_SUCCESS = `${INTERNAL}.${LOADING_SDK_DB$1}.success`;
148
- const INTERNAL_SAVING_CONFIG_SUCCESS = `${INTERNAL}.savingConfig.success`;
149
- const GLOBAL_INITIALIZING_SEND_CONFIG = `${GLOBAL}.${INITIALIZING$1}.sendConfig`;
150
- const GLOBAL_INITIALIZING_INTERNAL_SERVICE_READY = `${GLOBAL}.${INITIALIZING$1}.internalServiceReady`;
151
- const GLOBAL_ADDING_MODELS_TO_DB_SUCCESS = `${GLOBAL}.${ADDING_MODELS_TO_DB$1}.success`;
152
- const DB_CHECK_STATUS_UPDATE_PATHS = `${DB}.${CHECKING_STATUS$1}.updatePaths`;
153
- const DB_CHECK_STATUS_EXISTS = `${DB}.${CHECKING_STATUS$1}.exists`;
154
- const DB_VALIDATING_SUCCESS = `${DB}.${VALIDATING$1}.success`;
155
- const DB_VALIDATING_WAIT = `${DB}.${VALIDATING$1}.wait`;
156
- const DB_MIGRATING_WAIT = `${DB}.${MIGRATING$1}.wait`;
157
- const DB_MIGRATING_SUCCESS = `${DB}.${MIGRATING$1}.success`;
158
- const DB_CREATING_SUCCESS = `${DB}.${CONNECTING_TO_DB$1}.success`;
159
- const DB_WAITING_FOR_FILES_RECEIVED = `${DB}.${WAITING_FOR_FILES$1}.filesReceived`;
160
- const DB_ON_SNAPSHOT = `${DB}.onSnapshot`;
161
- const CHILD_SNAPSHOT = 'childSnapshot';
162
- const DB_NAME_SEED = 'seed_db';
163
- const DB_NAME_APP = 'app_db';
164
- const DB_NAME_SDK_CONFIG = 'sdk_config_db';
165
- const DB_DIR_NAME_SEED = 'seed';
166
- const DB_DIR_NAME_APP = 'app';
167
- const DB_DIR_NAME_SDK = 'sdk';
168
- const BROWSER_FS_TOP_DIR = 'app-files';
169
- const EAS_ENDPOINT = process.env.NEXT_PUBLIC_EAS_ENDPOINT ||
170
- process.env.EAS_ENDPOINT ||
171
- 'https://optimism-sepolia.easscan.org/graphql';
172
- const ARWEAVE_HOST = process.env.NEXT_PUBLIC_ARWEAVE_HOST || 'permagate.io';
173
-
174
93
  let sqlite3InitModule;
175
- let sqliteWasmClient$1;
94
+ let sqliteWasmClient;
176
95
  let isPreparing = false;
177
-
178
- const getSqlite = async () => {
179
- if (sqliteWasmClient$1) {
180
- return sqliteWasmClient$1
181
- }
182
- if (typeof window === 'undefined') {
183
- throw new Error('validateInput called from non-browser context')
184
- }
185
-
186
- if (isPreparing) {
187
- return
188
- }
189
-
190
- isPreparing = true;
191
-
192
- if (!sqlite3InitModule) {
193
- sqlite3InitModule = await import('@sqlite.org/sqlite-wasm');
194
- }
195
-
196
- if (!window.sqlite3Worker1Promiser) {
197
- await sqlite3InitModule();
198
- }
199
-
200
- if (!window.sqlite3Worker1Promiser) {
201
- console.error('window.sqlite3Worker1Promiser not found');
202
- isPreparing = false;
203
- return
204
- }
205
-
206
- try {
207
- sqliteWasmClient$1 = await window.sqlite3Worker1Promiser.v2().catch((err) => {
208
- console.error('Error initializing sqliteWasmClient:', err);
209
- isPreparing = false;
210
- });
211
- } catch (err) {
212
- console.error('Error initializing sqliteWasmClient:', err);
213
- isPreparing = false;
214
- }
96
+ const getSqliteWasmClient = () => __awaiter(void 0, void 0, void 0, function* () {
97
+ if (sqliteWasmClient) {
98
+ return sqliteWasmClient;
99
+ }
100
+ if (typeof window === 'undefined') {
101
+ throw new Error('validateInput called from non-browser context');
102
+ }
103
+ if (isPreparing) {
104
+ return;
105
+ }
106
+ isPreparing = true;
107
+ if (!sqlite3InitModule) {
108
+ sqlite3InitModule = yield import('@sqlite.org/sqlite-wasm');
109
+ }
110
+ if (!window.sqlite3Worker1Promiser) {
111
+ yield sqlite3InitModule();
112
+ }
113
+ if (!window.sqlite3Worker1Promiser) {
114
+ console.error('window.sqlite3Worker1Promiser not found');
115
+ isPreparing = false;
116
+ return;
117
+ }
118
+ try {
119
+ sqliteWasmClient = yield window.sqlite3Worker1Promiser.v2().catch((err) => {
120
+ console.error('Error initializing sqliteWasmClient:', err);
121
+ isPreparing = false;
122
+ });
123
+ }
124
+ catch (err) {
125
+ console.error('Error initializing sqliteWasmClient:', err);
126
+ isPreparing = false;
127
+ }
128
+ return sqliteWasmClient;
129
+ });
130
+ let appDb;
131
+ const setAppDb = (db) => {
132
+ appDb = db;
133
+ };
134
+ const getAppDb = () => {
135
+ if (!appDb) {
136
+ throw new Error('getAppDb: appDb is undefined');
137
+ }
138
+ return appDb;
139
+ };
140
+ const isAppDbReady = () => {
141
+ return !!appDb;
215
142
  };
143
+ const runQueryForStatement = (statement) => __awaiter(void 0, void 0, void 0, function* () {
144
+ const appDb = getAppDb();
145
+ return appDb.run(sql.raw(statement));
146
+ });
216
147
 
217
- const logger$k = debug('app:db:actors');
218
- let seedDb;
219
- let appDb;
220
- let sdkConfigDb;
221
- let sqliteWasmClient;
222
- const checkStatus = fromCallback(({ sendBack, input: { context } }) => {
223
- const { dbName, dirName } = context;
224
- logger$k('[db/actors] checkStatus context', context);
225
- const pathToDir = `${BROWSER_FS_TOP_DIR}/${dirName}`;
226
- const pathToDbDir = `${pathToDir}/db`;
227
- const pathToDb = `${pathToDbDir}/${dbName}.sqlite3`;
228
- sendBack({
229
- type: DB_CHECK_STATUS_UPDATE_PATHS,
230
- pathToDb,
231
- pathToDir,
232
- pathToDbDir,
233
- });
234
- const _checkStatus = () => __awaiter(void 0, void 0, void 0, function* () {
235
- // logger('[db/actors] _checkStatus pathToDb', pathToDb)
236
- // const exists = await fs.promises.exists(pathToJournal)
237
- // if (exists) {
238
- // sendBack({
239
- // type: DB_CHECK_STATUS_EXISTS,
240
- // })
241
- // return
242
- // }
243
- //
244
- // return new Promise((resolve) => {
245
- // sendBack({ type: DB_CHECK_STATUS_DOES_NOT_EXIST })
246
- //
247
- // })
148
+ const waitForDb$1 = fromCallback(({ sendBack }) => {
149
+ const _waitForDb = new Promise((resolve) => {
150
+ const interval = setInterval(() => {
151
+ const appDb = getAppDb();
152
+ if (appDb) {
153
+ clearInterval(interval);
154
+ resolve();
155
+ }
156
+ }, 100);
248
157
  });
249
- _checkStatus().then(() => {
250
- sendBack({ type: DB_CHECK_STATUS_EXISTS });
251
- return;
158
+ _waitForDb.then(() => {
159
+ sendBack({ type: 'waitForDbSuccess' });
252
160
  });
253
161
  });
254
- const connectToDb = fromCallback(({ sendBack, input: { context } }) => {
255
- logger$k('[db/actors] connectToDb context', context);
256
- const { dbName, pathToDir } = context;
257
- let isConnecting = false;
258
- let dbId;
259
- const _create = () => __awaiter(void 0, void 0, void 0, function* () {
260
- if (isConnecting) {
162
+
163
+ const initialize$3 = fromCallback(({ sendBack, input: { context } }) => {
164
+ const { isRelation, propertyName, storageTransactionId, seedLocalId } = context;
165
+ if (isRelation) {
166
+ sendBack({ type: 'isRelatedProperty' });
167
+ sendBack({ type: 'initializeSuccess' });
168
+ return;
169
+ }
170
+ if (!isRelation) {
171
+ if ((propertyName !== 'html' && propertyName !== 'json') ||
172
+ !storageTransactionId) {
173
+ sendBack({ type: 'initializeSuccess' });
261
174
  return;
262
175
  }
263
- isConnecting = true;
264
- let response;
265
- if (!sqliteWasmClient) {
266
- sqliteWasmClient = yield getSqlite();
267
- }
268
- //@ts-ignore
269
- response = yield sqliteWasmClient('config-get', {});
270
- logger$k(response);
271
- logger$k('Running SQLite3 version', response.result.version.libVersion);
272
- //@ts-ignore
273
- response = yield sqliteWasmClient('open', {
274
- filename: `file:${pathToDir}/db/${dbName}.sqlite3?vfs=opfs`,
176
+ const _getContentsFromFileSystem = () => __awaiter(void 0, void 0, void 0, function* () {
177
+ if (propertyName === 'html') {
178
+ const renderValue = yield fs.promises
179
+ .readFile(`/files/html/${storageTransactionId}.html`, 'utf8')
180
+ .catch((error) => {
181
+ console.warn('Error reading html file', error);
182
+ });
183
+ sendBack({ type: 'updateRenderValue', renderValue });
184
+ return;
185
+ }
186
+ if (propertyName === 'json') {
187
+ const renderValue = yield fs.promises
188
+ .readFile(`/files/json/${storageTransactionId}.json`, 'utf8')
189
+ .catch((error) => {
190
+ console.warn('Error reading json file', error);
191
+ });
192
+ sendBack({ type: 'updateRenderValue', renderValue });
193
+ return;
194
+ }
275
195
  });
276
- logger$k(response);
277
- dbId = response.dbId;
278
- // logger(`dbId: ${dbId}`)
279
- logger$k('OPFS is available, created persisted database at', response.result.filename.replace(/^file:(.*?)\?vfs=opfs$/, '$1'));
280
- });
281
- const interval = setInterval(() => {
282
- // TODO: Add a timeout
283
- // TODO: Add a cancel token to the promise so we can prevent more loops starting while we're checking the successful outcome
284
- if (dbId) {
285
- // logger(
286
- // '[db/actors] opening sqliteWasm connection with dbId:',
287
- // dbId,
288
- // )
289
- clearInterval(interval);
290
- sendBack({ type: DB_CREATING_SUCCESS, dbId });
291
- return;
292
- }
293
- _create()
294
- .then(() => {
295
- return;
296
- })
297
- .catch((e) => {
298
- isConnecting = false;
196
+ _getContentsFromFileSystem().then(() => {
197
+ sendBack({ type: 'initializeSuccess' });
299
198
  });
300
- }, 500);
301
- return () => {
302
- if (interval) {
303
- clearInterval(interval);
304
- }
305
- };
199
+ }
306
200
  });
307
- const validate = fromCallback(({ sendBack, input: { context } }) => {
308
- const { pathToDir, pathToDb } = context;
309
- const pathsToCheck = [
310
- pathToDir,
311
- `${pathToDir}/db`,
312
- `${pathToDir}/db/meta`,
313
- `${pathToDir}/db/meta/_journal.json`,
314
- ];
315
- const _validate = () => __awaiter(void 0, void 0, void 0, function* () {
316
- // If any of the necessary files don't exist, we wipe them all and recreate
317
- let exists = false;
318
- for (const path of pathsToCheck) {
319
- exists = yield fs.promises.exists(path);
320
- if (!exists) {
321
- sendBack({
322
- type: DB_VALIDATING_WAIT,
323
- });
324
- return false;
325
- }
326
- }
327
- return exists;
328
- });
329
- _validate().then(() => {
330
- sendBack({ type: DB_VALIDATING_SUCCESS, pathToDb, pathToDir });
201
+
202
+ const logger$n = debug('app:shared:helpers');
203
+ const { alphanumeric } = nanoIdDictionary;
204
+ const generateId = () => {
205
+ return customAlphabet(alphanumeric, 10)();
206
+ };
207
+ const toSnakeCase = (str) => {
208
+ return str.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase();
209
+ };
210
+ const identifyString = (str) => {
211
+ try {
212
+ JSON.parse(str);
213
+ return 'json';
214
+ }
215
+ catch (e) {
216
+ // Not JSON
217
+ }
218
+ if (!str) {
331
219
  return;
332
- });
333
- });
334
- const dbExec = (dbId_1, params_1, sql_1, dbName_1, ...args_1) => __awaiter(void 0, [dbId_1, params_1, sql_1, dbName_1, ...args_1], void 0, function* (dbId, params, sql, dbName, retries = 2) {
335
- const rowsToReturnRaw = [];
336
- const sqliteWasmClient = yield getSqlite();
337
- // For a single exec command, the callback potentially gets called several times -- once for each row.
338
- // So we need to collect all rows into a final array to return (execResult).
339
- const rowsToReturn = yield new Promise((resolve, reject) => {
340
- sqliteWasmClient('exec', {
341
- dbId,
342
- sql,
343
- bind: params,
344
- callback: (result) => {
345
- // Checks if this is the final callback of the query
346
- if (!result || !result.row || !result.rowNumber) {
347
- const returnResult = [];
348
- // Before returning the array, we process it to match the expected output format
349
- // const rowsToReturnProcessed = rowsToReturnRaw.reduce((acc, curr) => {
350
- // if (
351
- // Array.isArray(curr.row) &&
352
- // curr.row?.length > 0 &&
353
- // curr.columnNames.length > 0
354
- // ) {
355
- // const returnObj: ReturnObj = {
356
- // database: dbName,
357
- // }
358
- //
359
- // const values = []
360
- //
361
- // curr.columnNames.forEach((colName, index: number) => {
362
- // if (curr.row && curr.row[index]) {
363
- // returnObj[colName] = curr.row[index]
364
- // values.push(curr.row[index])
365
- // }
366
- // })
367
- // // rowsValueStrings.push(`(${values.join(', ')})`)
368
- // acc.push(returnObj)
369
- // }
370
- // return acc
371
- // }, [] as string[])
372
- for (const currRow of rowsToReturnRaw) {
373
- // const values: string[] = []
374
- // currRow.columnNames.forEach((colName, index: number) => {
375
- // if (currRow.row) {
376
- // values.push(currRow.row[index])
377
- // }
378
- // })
379
- // logger(`[db/actors] [dbExec] currRow`, currRow)
380
- returnResult.push(currRow.row);
381
- }
382
- resolve(returnResult);
383
- }
384
- else {
385
- // If not the final response, add this row to the return array
386
- rowsToReturnRaw.push(result);
387
- }
388
- },
389
- }).catch((error) => __awaiter(void 0, void 0, void 0, function* () {
390
- reject(error);
391
- }));
392
- });
393
- // logger(`[db/actors] [dbExec] rowsToReturn`, rowsToReturn)
394
- // logger(`[db/actors] [dbExec] rowsValues`, rowsValues)
395
- return rowsToReturn || [];
396
- });
397
- const migrate = fromCallback(({ sendBack, input: { context } }) => {
398
- const { pathToDbDir, dirName, dbId, dbName } = context;
399
- logger$k('[db/actors] migrate context', context);
400
- const schemaGlobString = `${BROWSER_FS_TOP_DIR}/${dirName}/schema/*`;
401
- const isSeedDb = dbName === DB_NAME_SEED;
402
- const isAppDb = dbName === DB_NAME_APP;
403
- const isSdkConfigDb = dbName === DB_NAME_SDK_CONFIG;
404
- if (!sqliteWasmClient) {
405
- throw new Error('Sqlite wasm client not initialized');
406
220
  }
407
- let journalExists = false;
408
- // const _initFs = async (): Promise<void> => {
409
- // const handle = await navigator.storage.getDirectory()
410
- // // await configure({ backend: WebAccess, handle })
411
- // await configureSingle({
412
- // backend: WebAccess,
413
- // handle,
414
- // })
415
- // }
416
- //
417
- // _initFs()
418
- const _checkForFiles = () => __awaiter(void 0, void 0, void 0, function* () {
419
- const { fs } = yield import('@zenfs/core');
420
- journalExists = yield fs.promises.exists(`/${pathToDbDir}/meta/_journal.json`);
421
- if (!journalExists) {
422
- window.location.reload();
423
- // setTimeout(() => {
424
- // _checkForFiles().then(() => {
425
- // return
426
- // })
427
- // }, 500)
428
- }
429
- });
430
- const _migrate = () => __awaiter(void 0, void 0, void 0, function* () {
431
- const drizzleDb = drizzle((sql, params, method) => __awaiter(void 0, void 0, void 0, function* () {
432
- try {
433
- // logger(
434
- // `executing sql on ${dbName} with id: ${dbId} and method: ${method}`,
435
- // sql,
436
- // )
437
- const finalResult = yield dbExec(dbId, params, sql, dbName);
438
- // logger(`finalResult with method: ${method}`, finalResult)
439
- // Drizzle always waits for {rows: string[][]} or {rows: string[]} for the return value.
440
- // When the method is get, you should return a value as {rows: string[]}.
441
- // Otherwise, you should return {rows: string[][]}.
442
- return { rows: finalResult };
443
- }
444
- catch (e) {
445
- console.error('Error from sqlite proxy server: ', JSON.stringify(e));
446
- return { rows: [] };
447
- }
448
- }), {
449
- schema: schemaGlobString,
450
- // logger: true,
451
- });
452
- const { migrate: drizzleMigrate } = yield import('drizzle-orm/sqlite-proxy/migrator');
453
- const { readMigrationFiles } = yield import('drizzle-orm/migrator');
454
- try {
455
- const migrations = readMigrationFiles({
456
- migrationsFolder: pathToDbDir,
457
- });
458
- if (migrations.length > 0) {
459
- const incomingMigrationHashes = migrations.map((migration) => migration.hash);
460
- let existingMigrationHashes;
461
- let rows = [];
462
- try {
463
- const query = yield drizzleDb.run(sql.raw(`SELECT hash, created_at
464
- FROM main.__drizzle_migrations;`));
465
- rows = query.rows;
466
- }
467
- catch (e) {
468
- rows = [];
469
- }
470
- if (rows && rows.length > 0) {
471
- existingMigrationHashes = rows.map((row) => row[0]);
472
- }
473
- if (existingMigrationHashes) {
474
- let shouldRebuildDb = false;
475
- for (const existingHash of existingMigrationHashes) {
476
- if (!incomingMigrationHashes.includes(existingHash)) {
477
- shouldRebuildDb = true;
478
- break;
479
- }
480
- }
481
- if (shouldRebuildDb) {
482
- yield fs.promises.unlink(`${pathToDbDir}/${dbName}.sqlite3`);
483
- }
484
- }
485
- }
486
- yield drizzleMigrate(drizzleDb, (queriesToRun) => __awaiter(void 0, void 0, void 0, function* () {
487
- // logger('queriesToRun', queriesToRun)
488
- for (const query of queriesToRun) {
489
- // logger('query', query)
490
- yield drizzleDb.run(sql.raw(query));
491
- }
492
- }), {
493
- migrationsFolder: pathToDbDir,
494
- });
495
- }
496
- catch (error) {
497
- console.error('Error migrating database: ', error);
498
- window.location.reload();
499
- }
500
- // TODO: We're currently only using seedDb for appState ... should we drop it?
501
- // Or do we want to store Seeds and Versions separately from appDb and sdkConfigDb?
502
- if (isSeedDb) {
503
- seedDb = drizzleDb;
504
- }
505
- if (isAppDb) {
506
- appDb = drizzleDb;
507
- // const createTempTableQuery = await appDb.run(
508
- // sql.raw(
509
- // `CREATE TEMP TABLE IF NOT EXISTS temp_last_inserted_id (id INTEGER, table TEXT);`,
510
- // ),
511
- // )
512
- //
513
- // logger(
514
- // '[db/actors] [migrate] createTempTableQuery',
515
- // createTempTableQuery,
516
- // )
517
- // const triggersQuery = await appDb.run(
518
- // sql.raw(
519
- // `SELECT name
520
- // FROM main.sqlite_master
521
- // WHERE type = 'trigger';`,
522
- // ),
523
- // )
524
- //
525
- // logger('[db/actors] [migrate] triggersQuery', triggersQuery)
526
- //
527
- // const triggers = triggersQuery.rows.map((row) => row[0])
528
- //
529
- // const tablesQuery = await appDb.run(
530
- // sql.raw(
531
- // `SELECT name
532
- // FROM main.sqlite_master
533
- // WHERE type = 'table';`,
534
- // ),
535
- // )
536
- //
537
- // logger('[db/actors] [migrate] tablesQuery', tablesQuery)
538
- //
539
- // const tableNames = tablesQuery.rows.map((row) => row[0])
540
- // logger('[db/actors] [migrate] tableNames', tableNames)
541
- // for (const tableName of tableNames) {
542
- // const triggerName = `after_insert_${tableName}`
543
- // if (triggers.includes(triggerName)) {
544
- // continue
545
- // }
546
- // const createTriggerQuery = await appDb.run(
547
- // sql.raw(
548
- // `CREATE TRIGGER after_insert_${tableName}
549
- // AFTER INSERT ON ${tableName}
550
- // BEGIN
551
- // DELETE FROM temp_last_inserted_id;
552
- // INSERT INTO temp_last_inserted_id (id) VALUES (new.id);
553
- // END;`,
554
- // ),
555
- // )
556
- //
557
- // logger(
558
- // '[db/actors] [migrate] createTriggerQuery',
559
- // createTriggerQuery,
560
- // )
561
- // }
562
- }
563
- if (isSdkConfigDb) {
564
- sdkConfigDb = drizzleDb;
565
- }
566
- });
567
- _checkForFiles()
568
- .then(() => {
569
- if (((isSeedDb && !seedDb) ||
570
- (isAppDb && !appDb) ||
571
- (isSdkConfigDb && !sdkConfigDb)) &&
572
- journalExists) {
573
- return _migrate();
574
- }
575
- })
576
- .then(() => {
577
- sendBack({ type: DB_MIGRATING_SUCCESS, dbName });
578
- });
579
- return () => { };
580
- });
581
- const getDb = (dbName) => {
582
- if (dbName === DB_NAME_SEED && seedDb) {
583
- return seedDb;
221
+ if (str.trim().startsWith('<') && str.trim().endsWith('>')) {
222
+ return 'html';
584
223
  }
585
- if (dbName === DB_NAME_APP && appDb) {
586
- return appDb;
224
+ // Simple markdown checks (very naive)
225
+ if (/^#{1,6}\s|^-{3,}|\*{3,}|^-{1,2}\s|\*\s/.test(str)) {
226
+ return 'markdown';
587
227
  }
588
- if (dbName === DB_NAME_SDK_CONFIG && sdkConfigDb) {
589
- return sdkConfigDb;
228
+ if (/^data:image\/[a-zA-Z]+;base64,[A-Za-z0-9+/]+={0,2}$/.test(str)) {
229
+ return 'base64';
590
230
  }
591
- return null;
231
+ // Default to plain text if unsure
232
+ return 'text';
592
233
  };
593
- const getAppDb = () => {
594
- const appDb = getDb(DB_NAME_APP);
595
- if (!appDb) {
596
- throw new Error('getAppDb: appDb is undefined');
234
+ const getMimeType = (base64) => {
235
+ if (!base64 || !Object.hasOwn(base64, 'match')) {
236
+ return null;
597
237
  }
598
- return appDb;
599
- };
600
- const getSdkDb = () => {
601
- const sdkDb = getDb(DB_NAME_SDK_CONFIG);
602
- if (!sdkDb) {
603
- throw new Error('getSdkDb: sdkDb is undefined');
604
- }
605
- return sdkDb;
606
- };
607
- // export const getDb = fromCallback<EventObject, typeof dbMachine>(
608
- // ({ sendBack, receive, input: { event } }) => {
609
- // const { dbName } = event
610
- //
611
- // const _getDb = async (): Promise<void> => {
612
- // const db = await drizzle(dbName)
613
- // sendBack({ type: 'returningDb', db })
614
- // }
615
- //
616
- // _getDb().then(() => {
617
- // return
618
- // })
619
- //
620
- // return () => {}
621
- // },
622
- // )
623
-
624
- const waitForDb$1 = fromCallback(({ sendBack }) => {
625
- const _waitForDb = new Promise((resolve) => {
626
- const interval = setInterval(() => {
627
- const appDb = getDb(DB_NAME_APP);
628
- const sdkConfigDb = getSdkDb();
629
- if (appDb || !sdkConfigDb) {
630
- clearInterval(interval);
631
- resolve();
632
- }
633
- }, 100);
634
- });
635
- _waitForDb.then(() => {
636
- sendBack({ type: 'waitForDbSuccess' });
637
- });
638
- });
639
-
640
- const initialize$3 = fromCallback(({ sendBack, input: { context } }) => {
641
- const { isRelation, propertyName, storageTransactionId, seedLocalId } = context;
642
- if (isRelation) {
643
- sendBack({ type: 'isRelatedProperty' });
644
- sendBack({ type: 'initializeSuccess' });
645
- return;
646
- }
647
- if (!isRelation) {
648
- if ((propertyName !== 'html' && propertyName !== 'json') ||
649
- !storageTransactionId) {
650
- sendBack({ type: 'initializeSuccess' });
651
- return;
652
- }
653
- const _getContentsFromFileSystem = () => __awaiter(void 0, void 0, void 0, function* () {
654
- if (propertyName === 'html') {
655
- const renderValue = yield fs.promises
656
- .readFile(`/files/html/${storageTransactionId}.html`, 'utf8')
657
- .catch((error) => {
658
- console.warn('Error reading html file', error);
659
- });
660
- sendBack({ type: 'updateRenderValue', renderValue });
661
- return;
662
- }
663
- if (propertyName === 'json') {
664
- const renderValue = yield fs.promises
665
- .readFile(`/files/json/${storageTransactionId}.json`, 'utf8')
666
- .catch((error) => {
667
- console.warn('Error reading json file', error);
668
- });
669
- sendBack({ type: 'updateRenderValue', renderValue });
670
- return;
671
- }
672
- });
673
- _getContentsFromFileSystem().then(() => {
674
- sendBack({ type: 'initializeSuccess' });
675
- });
676
- }
677
- });
678
-
679
- const logger$j = debug('app:shared:helpers');
680
- const { alphanumeric } = nanoIdDictionary;
681
- const generateId = () => {
682
- return customAlphabet(alphanumeric, 10)();
683
- };
684
- const toSnakeCase = (str) => {
685
- return str.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase();
686
- };
687
- const identifyString = (str) => {
688
- try {
689
- JSON.parse(str);
690
- return 'json';
691
- }
692
- catch (e) {
693
- // Not JSON
694
- }
695
- if (!str) {
696
- return;
697
- }
698
- if (str.trim().startsWith('<') && str.trim().endsWith('>')) {
699
- return 'html';
700
- }
701
- // Simple markdown checks (very naive)
702
- if (/^#{1,6}\s|^-{3,}|\*{3,}|^-{1,2}\s|\*\s/.test(str)) {
703
- return 'markdown';
704
- }
705
- if (/^data:image\/[a-zA-Z]+;base64,[A-Za-z0-9+/]+={0,2}$/.test(str)) {
706
- return 'base64';
707
- }
708
- // Default to plain text if unsure
709
- return 'text';
710
- };
711
- const getMimeType = (base64) => {
712
- if (!base64 || !Object.hasOwn(base64, 'match')) {
713
- return null;
714
- }
715
- const result = base64.match(/^data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+).*,/);
716
- if (result && result.length > 1) {
717
- return result[1];
718
- }
719
- else {
720
- return null; // MIME type could not be determined
238
+ const result = base64.match(/^data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+).*,/);
239
+ if (result && result.length > 1) {
240
+ return result[1];
241
+ }
242
+ else {
243
+ return null; // MIME type could not be determined
721
244
  }
722
245
  };
723
246
  const getImageDataType = (data) => {
@@ -739,7 +262,7 @@ const convertTxIdToImageSrc = (txId) => __awaiter(void 0, void 0, void 0, functi
739
262
  const imageFilePath = `/files/images/${txId}`;
740
263
  const fileExists = yield fs.promises.exists(imageFilePath);
741
264
  if (!fileExists) {
742
- logger$j(`[ItemView] [updateImageSrc] ${imageFilePath} does not exist`);
265
+ logger$n(`[ItemView] [updateImageSrc] ${imageFilePath} does not exist`);
743
266
  return;
744
267
  }
745
268
  const uint = yield fs.promises.readFile(imageFilePath);
@@ -817,30 +340,70 @@ const appState = sqliteTable('appState', {
817
340
  updatedAt: int('updated_at'),
818
341
  });
819
342
 
820
- const getItemsData = (modelName) => __awaiter(void 0, void 0, void 0, function* () {
821
- const appDb = getAppDb();
822
- const itemsData = (yield appDb
823
- .select({
824
- seedLocalId: seeds.localId,
825
- seedUid: seeds.uid,
826
- schemaUid: seeds.schemaUid,
827
- modelName: sql `${modelName}`,
828
- attestationCreatedAt: seeds.attestationCreatedAt,
829
- versionsCount: count(versions.localId),
830
- lastVersionPublishedAt: max(versions.attestationCreatedAt),
831
- lastLocalUpdateAt: max(versions.createdAt),
832
- })
833
- .from(seeds)
834
- .leftJoin(versions, eq(seeds.localId, versions.seedLocalId))
835
- .where(and(eq(seeds.type, modelName.toLowerCase()), or(isNull(seeds._markedForDeletion), eq(seeds._markedForDeletion, 0))))
836
- .groupBy(seeds.localId));
837
- return itemsData;
343
+ sqliteTable('config', {
344
+ id: int('id').primaryKey({ autoIncrement: true }),
345
+ key: text('key').notNull(),
346
+ text: text('text'),
347
+ json: text('json', { mode: 'json' }),
348
+ blob: blob('blob', { mode: 'buffer' }),
349
+ }, () => {
350
+ return {
351
+ // Add a custom check constraint
352
+ atLeastOneNotNull: check('hasValue', sql `key IS NOT NULL OR text IS NOT NULL OR json IS NOT NULL OR blob IS NOT NULL`),
353
+ };
838
354
  });
839
355
 
840
- const runQueryForStatement = (statement) => __awaiter(void 0, void 0, void 0, function* () {
841
- const appDb = getAppDb();
842
- return appDb.run(sql.raw(statement));
356
+ const models = sqliteTable('models', {
357
+ id: int('id').primaryKey({ autoIncrement: true }),
358
+ name: text('name').notNull(),
359
+ });
360
+ relations(models, ({ many }) => ({
361
+ properties: many(properties),
362
+ }));
363
+ const properties = sqliteTable('properties', {
364
+ id: int('id').primaryKey({ autoIncrement: true }),
365
+ name: text('name').notNull(),
366
+ dataType: text('data_type').notNull(),
367
+ readEndpoint: text('read_endpoint'),
368
+ updateEndpoint: text('update_endpoint'),
369
+ modelId: int('model_id')
370
+ .notNull()
371
+ .references(() => models.id),
372
+ refModelId: int('ref_model_id').references(() => models.id),
373
+ refValueType: text('ref_value_type'),
374
+ }, (table) => {
375
+ return {
376
+ uniqueNameModelId: unique('unique_name_model_id').on(table.name, table.modelId),
377
+ };
378
+ });
379
+ relations(properties, ({ one }) => ({
380
+ model: one(models),
381
+ refModel: one(models),
382
+ }));
383
+
384
+ const modelUids = sqliteTable('model_uids', {
385
+ id: int('id').primaryKey({ autoIncrement: true }),
386
+ uid: text('uid').notNull(),
387
+ modelId: int('model_id')
388
+ .notNull()
389
+ .unique()
390
+ .references(() => models.id),
391
+ });
392
+ relations(modelUids, ({ many, one }) => ({
393
+ model: one(models),
394
+ }));
395
+
396
+ const propertyUids = sqliteTable('property_uids', {
397
+ id: int('id').primaryKey({ autoIncrement: true }),
398
+ uid: text('uid').notNull(),
399
+ propertyId: int('property_id')
400
+ .notNull()
401
+ .unique()
402
+ .references(() => models.id),
843
403
  });
404
+ relations(propertyUids, ({ one }) => ({
405
+ property: one(properties),
406
+ }));
844
407
 
845
408
  const getPropertyData = (propertyName, seedLocalId) => __awaiter(void 0, void 0, void 0, function* () {
846
409
  const query = `SELECT local_id,
@@ -1314,71 +877,6 @@ const resolveRemoteStorage = fromCallback(({ sendBack, input: { context } }) =>
1314
877
  });
1315
878
  });
1316
879
 
1317
- sqliteTable('config', {
1318
- id: int('id').primaryKey({ autoIncrement: true }),
1319
- key: text('key').notNull(),
1320
- text: text('text'),
1321
- json: text('json', { mode: 'json' }),
1322
- blob: blob('blob', { mode: 'buffer' }),
1323
- }, () => {
1324
- return {
1325
- // Add a custom check constraint
1326
- atLeastOneNotNull: check('hasValue', sql `key IS NOT NULL OR text IS NOT NULL OR json IS NOT NULL OR blob IS NOT NULL`),
1327
- };
1328
- });
1329
-
1330
- const models = sqliteTable('models', {
1331
- id: int('id').primaryKey({ autoIncrement: true }),
1332
- name: text('name').notNull(),
1333
- });
1334
- relations(models, ({ many }) => ({
1335
- properties: many(properties),
1336
- }));
1337
- const properties = sqliteTable('properties', {
1338
- id: int('id').primaryKey({ autoIncrement: true }),
1339
- name: text('name').notNull(),
1340
- dataType: text('data_type').notNull(),
1341
- readEndpoint: text('read_endpoint'),
1342
- updateEndpoint: text('update_endpoint'),
1343
- modelId: int('model_id')
1344
- .notNull()
1345
- .references(() => models.id),
1346
- refModelId: int('ref_model_id').references(() => models.id),
1347
- refValueType: text('ref_value_type'),
1348
- }, (table) => {
1349
- return {
1350
- uniqueNameModelId: unique('unique_name_model_id').on(table.name, table.modelId),
1351
- };
1352
- });
1353
- relations(properties, ({ one }) => ({
1354
- model: one(models),
1355
- refModel: one(models),
1356
- }));
1357
-
1358
- const modelUids = sqliteTable('model_uids', {
1359
- id: int('id').primaryKey({ autoIncrement: true }),
1360
- uid: text('uid').notNull(),
1361
- modelId: int('model_id')
1362
- .notNull()
1363
- .unique()
1364
- .references(() => models.id),
1365
- });
1366
- relations(modelUids, ({ many, one }) => ({
1367
- model: one(models),
1368
- }));
1369
-
1370
- const propertyUids = sqliteTable('property_uids', {
1371
- id: int('id').primaryKey({ autoIncrement: true }),
1372
- uid: text('uid').notNull(),
1373
- propertyId: int('property_id')
1374
- .notNull()
1375
- .unique()
1376
- .references(() => models.id),
1377
- });
1378
- relations(propertyUids, ({ one }) => ({
1379
- property: one(properties),
1380
- }));
1381
-
1382
880
  const writeAppState = (db, key, value) => __awaiter(void 0, void 0, void 0, function* () {
1383
881
  yield db
1384
882
  .insert(appState)
@@ -1400,109 +898,17 @@ const escapeSqliteString = (value) => {
1400
898
  }
1401
899
  return value.replace(/'/g, "''");
1402
900
  };
1403
- const createOrUpdate = (db, table, values) => __awaiter(void 0, void 0, void 0, function* () {
1404
- const startTime = Date.now();
1405
- const valueFilters = [];
1406
- const propertiesToExcludeFromDb = ['ref'];
1407
- const safeValues = Object.keys(values).reduce((acc, key) => {
1408
- if (!propertiesToExcludeFromDb.includes(key)) {
1409
- acc[key] = values[key];
1410
- }
1411
- return acc;
1412
- }, {});
1413
- for (const [key, value] of Object.entries(safeValues)) {
1414
- let finalValue = value;
1415
- if (key === 'TObject') {
1416
- continue;
1417
- }
1418
- if (typeof value === 'object') {
1419
- finalValue = JSON.stringify(value);
1420
- }
1421
- const column = table[key];
1422
- if (!column) {
1423
- throw new Error(`Column not found for ${key}`);
1424
- }
1425
- if (typeof finalValue === 'undefined') {
1426
- finalValue = null;
1427
- }
1428
- if (finalValue === null) {
1429
- valueFilters.push(isNull(table[key]));
1430
- continue;
1431
- }
1432
- valueFilters.push(eq(table[key], finalValue));
901
+ const getAddressesFromDb = () => __awaiter(void 0, void 0, void 0, function* () {
902
+ const appDb = getAppDb();
903
+ if (!appDb) {
904
+ return new Promise((resolve) => {
905
+ setTimeout(() => __awaiter(void 0, void 0, void 0, function* () {
906
+ const addresses = yield getAddressesFromDb();
907
+ resolve(addresses);
908
+ }), 500);
909
+ });
1433
910
  }
1434
- const doneWithFilters = Date.now();
1435
- // console.log('valueFilters:', valueFilters)
1436
- // for ( const filter of valueFilters ) {
1437
- // console.log('filter:', Object.keys(filter))
1438
- // }
1439
- // Build a query to find the record based on properties
1440
- const existingRecords = yield db
1441
- .select()
1442
- .from(table)
1443
- .where(and(...valueFilters));
1444
- const doneWithExistingRecords = Date.now();
1445
- if (existingRecords.length > 1) {
1446
- throw new Error('Multiple records found');
1447
- }
1448
- if (existingRecords.length > 0) {
1449
- // If record exists, update it
1450
- yield db
1451
- .update(table)
1452
- .set(safeValues)
1453
- .where(and(...valueFilters));
1454
- console.log('updatedRecord:', Object.assign(Object.assign({}, existingRecords[0]), safeValues));
1455
- const doneWithUpdate = Date.now();
1456
- console.log('[helpers/db] [createOrUpdate] filters duration:', doneWithFilters - startTime);
1457
- console.log('[helpers/db] [createOrUpdate] existingRecords duration:', doneWithExistingRecords - doneWithFilters);
1458
- console.log('[helpers/db] [createOrUpdate] update duration:', doneWithUpdate - doneWithExistingRecords);
1459
- return existingRecords[0];
1460
- }
1461
- else {
1462
- // If no record exists, create a new one
1463
- const newRecord = yield db.insert(table).values(safeValues).returning();
1464
- console.log('newRecord:', newRecord);
1465
- return newRecord[0];
1466
- }
1467
- });
1468
- const addModelsToInternalDb = (db, models$1) => __awaiter(void 0, void 0, void 0, function* () {
1469
- for (const [modelName, modelClass] of Object.entries(models$1)) {
1470
- console.log('[helpers/db] [addModelsToInternalDb] starting modelName:', modelName);
1471
- const modelRecord = yield createOrUpdate(db, models, {
1472
- name: modelName,
1473
- });
1474
- for (let [propertyName, propertyValues] of Object.entries(modelClass.schema)) {
1475
- if (!propertyValues) {
1476
- throw new Error(`Property values not found for ${propertyName}`);
1477
- }
1478
- propertyValues.name = propertyName;
1479
- propertyValues.modelId = modelRecord.id;
1480
- for (let [key, value] of Object.entries(propertyValues)) {
1481
- if (key === 'ref') {
1482
- const refModel = yield createOrUpdate(db, models, {
1483
- name: value,
1484
- });
1485
- // delete propertyValues.ref
1486
- propertyValues.refModelId = refModel.id;
1487
- }
1488
- }
1489
- const propertyRecord = yield createOrUpdate(db, properties, propertyValues);
1490
- console.log('propertyRecord:', propertyRecord);
1491
- }
1492
- console.log('[helpers/db] [addModelsToInternalDb] done modelName:', modelName);
1493
- }
1494
- });
1495
- const getAddressesFromDb = () => __awaiter(void 0, void 0, void 0, function* () {
1496
- const seedDb = getDb(DB_NAME_SEED);
1497
- if (!seedDb) {
1498
- return new Promise((resolve) => {
1499
- setTimeout(() => __awaiter(void 0, void 0, void 0, function* () {
1500
- const addresses = yield getAddressesFromDb();
1501
- resolve(addresses);
1502
- }), 500);
1503
- });
1504
- }
1505
- const appStatesRecords = yield seedDb
911
+ const appStatesRecords = yield appDb
1506
912
  .select()
1507
913
  .from(appState)
1508
914
  .where(eq(appState.key, 'addresses'))
@@ -1518,7 +924,7 @@ const getAddressesFromDb = () => __awaiter(void 0, void 0, void 0, function* ()
1518
924
  return JSON.parse(addressArrayString);
1519
925
  });
1520
926
 
1521
- const logger$i = debug('app:property:actors:hydrateFromDb');
927
+ const logger$m = debug('app:property:actors:hydrateFromDb');
1522
928
  const hydrateFromDb = fromCallback(({ sendBack, input: { context } }) => {
1523
929
  const { seedUid, seedLocalId, propertyName: propertyNameRaw, propertyValue, propertyRecordSchema, itemModelName, } = context;
1524
930
  let propertyName = propertyNameRaw;
@@ -1586,23 +992,23 @@ const hydrateFromDb = fromCallback(({ sendBack, input: { context } }) => {
1586
992
  const firstRow = rows[0];
1587
993
  const { localId, uid, propertyName: propertyNameFromDb, propertyValue: propertyValueFromDb, seedLocalId: seedLocalIdFromDb, seedUid: seedUidFromDb, schemaUid: schemaUidFromDb, refResolvedValue, refResolvedDisplayValue, } = firstRow;
1588
994
  if (propertyName && !propertyNameFromDb) {
1589
- logger$i(`Property name from code is ${propertyName} but has not value in db ${propertyNameFromDb} for Property.${localId}`);
995
+ logger$m(`Property name from code is ${propertyName} but has not value in db ${propertyNameFromDb} for Property.${localId}`);
1590
996
  }
1591
997
  if (propertyName &&
1592
998
  propertyNameFromDb &&
1593
999
  !propertyNameFromDb.includes(propertyName) &&
1594
1000
  !propertyName.includes(propertyNameFromDb) &&
1595
1001
  propertyNameFromDb !== propertyName) {
1596
- logger$i(`Property name from db ${propertyNameFromDb} does not match property name ${propertyName} for Property.${localId}`);
1002
+ logger$m(`Property name from db ${propertyNameFromDb} does not match property name ${propertyName} for Property.${localId}`);
1597
1003
  }
1598
1004
  if (propertyValue && propertyValueFromDb !== propertyValue) {
1599
- logger$i(`Property value from db ${propertyValueFromDb} does not match property value ${propertyValue} for Property.${localId}`);
1005
+ logger$m(`Property value from db ${propertyValueFromDb} does not match property value ${propertyValue} for Property.${localId}`);
1600
1006
  }
1601
1007
  if (seedLocalIdFromDb !== seedLocalId) {
1602
- logger$i(`Seed local id from db ${seedLocalIdFromDb} does not match seed local id ${seedLocalId} for Property.${localId}`);
1008
+ logger$m(`Seed local id from db ${seedLocalIdFromDb} does not match seed local id ${seedLocalId} for Property.${localId}`);
1603
1009
  }
1604
1010
  if (seedUidFromDb !== seedUid) {
1605
- logger$i(`Seed uid from db ${seedUidFromDb} does not match seed uid ${seedUid} for Property.${localId}`);
1011
+ logger$m(`Seed uid from db ${seedUidFromDb} does not match seed uid ${seedUid} for Property.${localId}`);
1606
1012
  }
1607
1013
  sendBack({
1608
1014
  type: 'updateContext',
@@ -1617,7 +1023,7 @@ const hydrateFromDb = fromCallback(({ sendBack, input: { context } }) => {
1617
1023
  renderValue: refResolvedDisplayValue,
1618
1024
  });
1619
1025
  if (propertyNameFromDb === 'storageTransactionId') {
1620
- const { Item } = yield import('./index-DR_FgAUY.js');
1026
+ const { Item } = yield import('./index-scU0pJvR.js');
1621
1027
  const item = yield Item.find({
1622
1028
  seedLocalId,
1623
1029
  modelName: itemModelName,
@@ -1635,7 +1041,7 @@ const hydrateFromDb = fromCallback(({ sendBack, input: { context } }) => {
1635
1041
  const renderValue = yield fs.promises
1636
1042
  .readFile(htmlFilePath, 'utf8')
1637
1043
  .catch((error) => {
1638
- logger$i('Error reading html file', error);
1044
+ logger$m('Error reading html file', error);
1639
1045
  });
1640
1046
  property
1641
1047
  .getService()
@@ -1716,7 +1122,7 @@ const getVersionData = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seed
1716
1122
 
1717
1123
  const eventEmitter = new EventEmitter();
1718
1124
 
1719
- const logger$h = debug('app:write');
1125
+ const logger$l = debug('app:write');
1720
1126
  const sendItemUpdateEvent = ({ modelName, seedLocalId, seedUid }) => {
1721
1127
  if (!modelName || (!seedLocalId && !seedUid)) {
1722
1128
  return;
@@ -1794,7 +1200,7 @@ const deleteItem = (_a) => __awaiter(void 0, [_a], void 0, function* ({ seedLoca
1794
1200
  });
1795
1201
  const updateItemPropertyValue = (_a) => __awaiter(void 0, [_a], void 0, function* ({ propertyLocalId, propertyName, newValue, seedUid, seedLocalId, modelName, refSeedType, refResolvedValue, refResolvedDisplayValue, versionLocalId, versionUid, schemaUid, }) {
1796
1202
  if (!propertyLocalId && !seedLocalId) {
1797
- logger$h(`[db/write] [updateItemPropertyValue] no propertyLocalId or seedLocalId for property: ${propertyName}`);
1203
+ logger$l(`[db/write] [updateItemPropertyValue] no propertyLocalId or seedLocalId for property: ${propertyName}`);
1798
1204
  return;
1799
1205
  }
1800
1206
  let safeNewValue = newValue;
@@ -1833,7 +1239,7 @@ const updateItemPropertyValue = (_a) => __awaiter(void 0, [_a], void 0, function
1833
1239
  const schemaUid = mostRecentRecord[9];
1834
1240
  const easDataType = mostRecentRecord[10];
1835
1241
  if (propertyValueFromDb === newValue) {
1836
- logger$h(`[db/write] [updateItemPropertyValue] value is the same as most recent record for property: ${propertyNameFromDb}`);
1242
+ logger$l(`[db/write] [updateItemPropertyValue] value is the same as most recent record for property: ${propertyNameFromDb}`);
1837
1243
  return;
1838
1244
  }
1839
1245
  // This means we already have a local-only record so we should just update that one
@@ -1929,6 +1335,76 @@ const updateItemPropertyValue = (_a) => __awaiter(void 0, [_a], void 0, function
1929
1335
  sendItemUpdateEvent({ modelName, seedLocalId, seedUid });
1930
1336
  });
1931
1337
 
1338
+ var MachineIds;
1339
+ (function (MachineIds) {
1340
+ MachineIds["GLOBAL"] = "@seedSdk/global";
1341
+ MachineIds["INTERNAL"] = "@seedSdk/internal";
1342
+ MachineIds["DB"] = "@seedSdk/db";
1343
+ MachineIds["EAS"] = "@seedSdk/eas";
1344
+ MachineIds["ITEM"] = "@seedSdk/item";
1345
+ MachineIds["ALL_ITEMS"] = "@seedSdk/allItems";
1346
+ MachineIds["MODEL"] = "@seedSdk/model";
1347
+ MachineIds["FILE_SYSTEM"] = "@seedSdk/fileSystem";
1348
+ })(MachineIds || (MachineIds = {}));
1349
+ const { INTERNAL, DB, GLOBAL, EAS, MODEL } = MachineIds;
1350
+ var GlobalState;
1351
+ (function (GlobalState) {
1352
+ GlobalState["UNINITIALIZED"] = "uninitialized";
1353
+ GlobalState["INITIALIZING"] = "initializing";
1354
+ GlobalState["INITIALIZED"] = "initialized";
1355
+ GlobalState["GETTING_SEED_CLASS"] = "gettingSeedClass";
1356
+ GlobalState["GETTING_SCHEMA_FOR_MODEL"] = "gettingSchemaForModel";
1357
+ GlobalState["GETTING_TABLE_FOR_MODEL"] = "gettingTableForModel";
1358
+ GlobalState["GETTING_MODEL_CLASS"] = "gettingModelClass";
1359
+ GlobalState["ADDING_MODELS_TO_DB"] = "addingModelsToDb";
1360
+ })(GlobalState || (GlobalState = {}));
1361
+ const { UNINITIALIZED: UNINITIALIZED$1, INITIALIZING: INITIALIZING$1, INITIALIZED: INITIALIZED$1, GETTING_SEED_CLASS: GETTING_SEED_CLASS$1, GETTING_SCHEMA_FOR_MODEL: GETTING_SCHEMA_FOR_MODEL$1, GETTING_TABLE_FOR_MODEL, GETTING_MODEL_CLASS, ADDING_MODELS_TO_DB: ADDING_MODELS_TO_DB$1, } = GlobalState;
1362
+ var InternalState;
1363
+ (function (InternalState) {
1364
+ InternalState["IDLE"] = "idle";
1365
+ InternalState["INITIALIZING"] = "initializing";
1366
+ InternalState["VALIDATING_INPUT"] = "validatingInput";
1367
+ InternalState["CONFIGURING_FS"] = "configuringFs";
1368
+ InternalState["LOADING_SEED_DB"] = "loadingSeedDb";
1369
+ InternalState["SAVING_CONFIG"] = "savingConfig";
1370
+ InternalState["LOADING_APP_DB"] = "loadingAppDb";
1371
+ InternalState["LOADING_SDK_DB"] = "loadingSdkDb";
1372
+ })(InternalState || (InternalState = {}));
1373
+ const { VALIDATING_INPUT: VALIDATING_INPUT$1, CONFIGURING_FS: CONFIGURING_FS$1, LOADING_SEED_DB, LOADING_APP_DB: LOADING_APP_DB$1 } = InternalState;
1374
+ var DbState;
1375
+ (function (DbState) {
1376
+ DbState["CHECKING_STATUS"] = "checkingStatus";
1377
+ DbState["WAITING_FOR_FILES"] = "waitingForFiles";
1378
+ DbState["VALIDATING"] = "validating";
1379
+ DbState["CONNECTING_TO_DB"] = "connectingToDb";
1380
+ // FETCHING_MIGRATIONS = 'fetchingMigrations',
1381
+ DbState["MIGRATING"] = "migrating";
1382
+ })(DbState || (DbState = {}));
1383
+ const { CHECKING_STATUS: CHECKING_STATUS$1, VALIDATING: VALIDATING$1, CONNECTING_TO_DB: CONNECTING_TO_DB$1, WAITING_FOR_FILES: WAITING_FOR_FILES$1, MIGRATING: MIGRATING$1, } = DbState;
1384
+ const INTERNAL_VALIDATING_INPUT_SUCCESS = `${INTERNAL}.${VALIDATING_INPUT$1}.success`;
1385
+ const INTERNAL_CONFIGURING_FS_SUCCESS = `${INTERNAL}.${CONFIGURING_FS$1}.success`;
1386
+ const INTERNAL_LOADING_APP_DB_SUCCESS = `${INTERNAL}.${LOADING_APP_DB$1}.success`;
1387
+ const INTERNAL_SAVING_CONFIG_SUCCESS = `${INTERNAL}.savingConfig.success`;
1388
+ const GLOBAL_INITIALIZING_SEND_CONFIG = `${GLOBAL}.${INITIALIZING$1}.sendConfig`;
1389
+ const GLOBAL_INITIALIZING_INTERNAL_SERVICE_READY = `${GLOBAL}.${INITIALIZING$1}.internalServiceReady`;
1390
+ const GLOBAL_ADDING_MODELS_TO_DB_SUCCESS = `${GLOBAL}.${ADDING_MODELS_TO_DB$1}.success`;
1391
+ const DB_CHECK_STATUS_UPDATE_PATHS = `${DB}.${CHECKING_STATUS$1}.updatePaths`;
1392
+ const DB_CHECK_STATUS_EXISTS = `${DB}.${CHECKING_STATUS$1}.exists`;
1393
+ const DB_VALIDATING_SUCCESS = `${DB}.${VALIDATING$1}.success`;
1394
+ const DB_VALIDATING_WAIT = `${DB}.${VALIDATING$1}.wait`;
1395
+ const DB_MIGRATING_WAIT = `${DB}.${MIGRATING$1}.wait`;
1396
+ const DB_MIGRATING_SUCCESS = `${DB}.${MIGRATING$1}.success`;
1397
+ const DB_CREATING_SUCCESS = `${DB}.${CONNECTING_TO_DB$1}.success`;
1398
+ const DB_WAITING_FOR_FILES_RECEIVED = `${DB}.${WAITING_FOR_FILES$1}.filesReceived`;
1399
+ const DB_ON_SNAPSHOT = `${DB}.onSnapshot`;
1400
+ const CHILD_SNAPSHOT = 'childSnapshot';
1401
+ const DB_NAME_APP = 'app_db';
1402
+ const BROWSER_FS_TOP_DIR = 'app-files';
1403
+ const EAS_ENDPOINT = process.env.NEXT_PUBLIC_EAS_ENDPOINT ||
1404
+ process.env.EAS_ENDPOINT ||
1405
+ 'https://optimism-sepolia.easscan.org/graphql';
1406
+ const ARWEAVE_HOST = process.env.NEXT_PUBLIC_ARWEAVE_HOST || 'permagate.io';
1407
+
1932
1408
  const queryClient = new QueryClient({
1933
1409
  defaultOptions: {
1934
1410
  queries: {
@@ -2190,49 +1666,6 @@ const propertyMachine = setup({
2190
1666
  // },
2191
1667
  });
2192
1668
 
2193
- const APP_DB_CONFIG = 'browser.app.db.config.ts';
2194
- const SDK_DB_CONFIG = 'sdk.db.config.ts';
2195
- const SEED_DB_CONFIG = 'browser.seed.db.config.ts';
2196
- const SCHEMA_NJK = 'schema.njk';
2197
- const SCHEMA_TS = 'schema.ts';
2198
- const INTERNAL_DATA_TYPES = {
2199
- Text: {
2200
- eas: 'string',
2201
- },
2202
- Number: {
2203
- eas: 'uint8',
2204
- },
2205
- ImageSrc: {
2206
- eas: 'string',
2207
- },
2208
- Relation: {
2209
- eas: 'bytes32',
2210
- },
2211
- List: {
2212
- eas: 'bytes32[]',
2213
- },
2214
- };
2215
- const internalPropertyNames = [
2216
- 'localId',
2217
- 'uid',
2218
- 'seedLocalId',
2219
- 'seedUid',
2220
- 'schemaUid',
2221
- 'attestationCreatedAt',
2222
- 'createdAt',
2223
- 'updatedAt',
2224
- 'versionsCount',
2225
- 'lastVersionPublishedAt',
2226
- 'versionLocalId',
2227
- 'lastLocalUpdateAt',
2228
- 'storageTransactionId',
2229
- 'versionUid',
2230
- 'refSeedType',
2231
- 'refValueType',
2232
- 'resolvedValue',
2233
- 'resolvedDisplayValue',
2234
- ];
2235
-
2236
1669
  const modelStore = new Map();
2237
1670
  const getModels = () => {
2238
1671
  return Object.fromEntries(modelStore);
@@ -2247,8 +1680,8 @@ const setModel = (modelName, model) => {
2247
1680
  modelStore.set(modelName, model);
2248
1681
  };
2249
1682
 
2250
- var _a$1;
2251
- const logger$g = debug('app:property:class');
1683
+ var _a$2;
1684
+ const logger$k = debug('app:property:class');
2252
1685
  const namesThatEndWithId = [];
2253
1686
  class ItemProperty {
2254
1687
  // private constructor(localIdOrUid) {
@@ -2256,7 +1689,7 @@ class ItemProperty {
2256
1689
  constructor({ propertyValue, seedUid, seedLocalId, itemModelName, propertyName, storageTransactionId, schemaUid, }) {
2257
1690
  this._isRelation = false;
2258
1691
  this._isList = false;
2259
- this[_a$1] = true;
1692
+ this[_a$2] = true;
2260
1693
  const ModelClass = getModel(itemModelName);
2261
1694
  if (!ModelClass) {
2262
1695
  throw new Error(`Model ${itemModelName} not found`);
@@ -2296,7 +1729,7 @@ class ItemProperty {
2296
1729
  serviceInput.propertyValue = JSON.parse(propertyValue);
2297
1730
  }
2298
1731
  catch (e) {
2299
- logger$g('List property value is not JSON', e);
1732
+ logger$k('List property value is not JSON', e);
2300
1733
  }
2301
1734
  }
2302
1735
  const propertyNameSingular = pluralize(propertyName, 1);
@@ -2358,7 +1791,7 @@ class ItemProperty {
2358
1791
  this._service.start();
2359
1792
  }
2360
1793
  _updateResponseListener(event) {
2361
- logger$g(`[ItemProperty] [_updateResponseListener] [${this.itemModelName}.${this.seedLocalId}] ${this.propertyName} event`, event);
1794
+ logger$k(`[ItemProperty] [_updateResponseListener] [${this.itemModelName}.${this.seedLocalId}] ${this.propertyName} event`, event);
2362
1795
  }
2363
1796
  static create(props) {
2364
1797
  const { propertyName, seedLocalId, uid } = props;
@@ -2494,11 +1927,11 @@ class ItemProperty {
2494
1927
  }
2495
1928
  unload() {
2496
1929
  this._service.stop();
2497
- logger$g(`[XXXXXX] [ItemProperty] [${this.seedLocalId}] [unload] removing listener`, this._updateResponseEvent);
1930
+ logger$k(`[XXXXXX] [ItemProperty] [${this.seedLocalId}] [unload] removing listener`, this._updateResponseEvent);
2498
1931
  eventEmitter.removeListener(this._updateResponseEvent, this._updateResponseListener);
2499
1932
  }
2500
1933
  }
2501
- _a$1 = immerable;
1934
+ _a$2 = immerable;
2502
1935
  ItemProperty.instanceCache = new Map();
2503
1936
 
2504
1937
  const TPropertyDataType = Type.Union([
@@ -2562,7 +1995,7 @@ const List = (ref, reValueType) => PropertyConstructor(Property.List(ref, reValu
2562
1995
  const waitForDb = fromCallback(({ sendBack }) => {
2563
1996
  const _waitForDb = new Promise((resolve) => {
2564
1997
  const interval = setInterval(() => {
2565
- const appDb = getDb(DB_NAME_APP);
1998
+ const appDb = getAppDb();
2566
1999
  if (appDb) {
2567
2000
  clearInterval(interval);
2568
2001
  resolve();
@@ -3206,8 +2639,8 @@ const getRelatedSeedsAndVersions = () => __awaiter(void 0, void 0, void 0, funct
3206
2639
  });
3207
2640
  });
3208
2641
  const syncDbWithEasHandler = debounce((_) => __awaiter(void 0, void 0, void 0, function* () {
3209
- const sdkConfigDb = getSdkDb();
3210
- const { modelSchemas, schemaStringToModelRecord, modelRecords } = yield getModelSchemas({ sdkConfigDb });
2642
+ const appDb = getAppDb();
2643
+ const { modelSchemas, schemaStringToModelRecord, modelRecords } = yield getModelSchemas({ sdkConfigDb: appDb });
3211
2644
  if (!modelSchemas ||
3212
2645
  !modelSchemas.schemas ||
3213
2646
  modelSchemas.schemas.length === 0) {
@@ -3220,7 +2653,7 @@ const syncDbWithEasHandler = debounce((_) => __awaiter(void 0, void 0, void 0, f
3220
2653
  throw new Error(`Model not found for schema ${modelSchema.schema}`);
3221
2654
  }
3222
2655
  schemaUids.push(modelSchema.id);
3223
- yield sdkConfigDb
2656
+ yield appDb
3224
2657
  .insert(modelUids)
3225
2658
  .values({
3226
2659
  modelId: foundModel.id,
@@ -3228,7 +2661,7 @@ const syncDbWithEasHandler = debounce((_) => __awaiter(void 0, void 0, void 0, f
3228
2661
  })
3229
2662
  .onConflictDoNothing();
3230
2663
  yield processPropertiesFoundInDb({
3231
- sdkConfigDb,
2664
+ sdkConfigDb: appDb,
3232
2665
  foundModel,
3233
2666
  });
3234
2667
  }
@@ -3696,6 +3129,26 @@ const itemMachineSingle = setup({
3696
3129
  },
3697
3130
  });
3698
3131
 
3132
+ const getItemsData = (modelName) => __awaiter(void 0, void 0, void 0, function* () {
3133
+ const appDb = getAppDb();
3134
+ const itemsData = (yield appDb
3135
+ .select({
3136
+ seedLocalId: seeds.localId,
3137
+ seedUid: seeds.uid,
3138
+ schemaUid: seeds.schemaUid,
3139
+ modelName: sql `${modelName}`,
3140
+ attestationCreatedAt: seeds.attestationCreatedAt,
3141
+ versionsCount: count(versions.localId),
3142
+ lastVersionPublishedAt: max(versions.attestationCreatedAt),
3143
+ lastLocalUpdateAt: max(versions.createdAt),
3144
+ })
3145
+ .from(seeds)
3146
+ .leftJoin(versions, eq(seeds.localId, versions.seedLocalId))
3147
+ .where(and(eq(seeds.type, modelName.toLowerCase()), or(isNull(seeds._markedForDeletion), eq(seeds._markedForDeletion, 0))))
3148
+ .groupBy(seeds.localId));
3149
+ return itemsData;
3150
+ });
3151
+
3699
3152
  const getPropertiesForSeed = (seedLocalId, seedUid) => __awaiter(void 0, void 0, void 0, function* () {
3700
3153
  if (seedLocalId && !seedUid) {
3701
3154
  const seedQueryStatement = `SELECT uid
@@ -3783,7 +3236,7 @@ const getPropertiesForSeed = (seedLocalId, seedUid) => __awaiter(void 0, void 0,
3783
3236
  return propertiesData;
3784
3237
  });
3785
3238
 
3786
- const logger$f = debug('app:db:queries:getItem');
3239
+ const logger$j = debug('app:db:queries:getItem');
3787
3240
  const getItemDataFromDb = (_a) => __awaiter(void 0, [_a], void 0, function* ({ modelName, seedLocalId, seedUid, }) {
3788
3241
  if (!seedLocalId && !seedUid) {
3789
3242
  throw new Error('[db/queries] [getItem] no seedLocalId or seedUid');
@@ -3791,7 +3244,7 @@ const getItemDataFromDb = (_a) => __awaiter(void 0, [_a], void 0, function* ({ m
3791
3244
  if (seedUid && !seedLocalId) {
3792
3245
  const seedData = yield getSeedData({ seedUid });
3793
3246
  if (!seedData) {
3794
- logger$f('[db/queries] [getItem] no seedData seedUid', seedUid);
3247
+ logger$j('[db/queries] [getItem] no seedData seedUid', seedUid);
3795
3248
  return;
3796
3249
  }
3797
3250
  seedLocalId = seedData.localId;
@@ -3846,10 +3299,10 @@ const getItemDataFromDb = (_a) => __awaiter(void 0, [_a], void 0, function* ({ m
3846
3299
  return initObj;
3847
3300
  });
3848
3301
 
3849
- var _a;
3302
+ var _a$1;
3850
3303
  class Item {
3851
3304
  constructor(initialValues) {
3852
- this[_a] = true;
3305
+ this[_a$1] = true;
3853
3306
  this._propertiesSubject = new BehaviorSubject({});
3854
3307
  this.subscribe = (callback) => {
3855
3308
  return this._service.subscribe((snapshot) => {
@@ -4020,7 +3473,7 @@ class Item {
4020
3473
  this._service.stop();
4021
3474
  }
4022
3475
  }
4023
- _a = immerable;
3476
+ _a$1 = immerable;
4024
3477
  Item.instanceCache = new Map();
4025
3478
 
4026
3479
  const initialize$1 = fromCallback(({ sendBack, input: { context } }) => {
@@ -4034,9 +3487,9 @@ const initialize$1 = fromCallback(({ sendBack, input: { context } }) => {
4034
3487
  let modelNameLowercase;
4035
3488
  let modelNamePlural;
4036
3489
  let queryVariables;
4037
- let sdkConfigDb;
3490
+ let appDb;
4038
3491
  const _initialize = () => __awaiter(void 0, void 0, void 0, function* () {
4039
- sdkConfigDb = getSdkDb();
3492
+ appDb = getAppDb();
4040
3493
  // const rows = await getItemsDataFromDb(modelName)
4041
3494
  //
4042
3495
  // if (rows && rows.length > 0) {
@@ -4086,7 +3539,7 @@ const initialize$1 = fromCallback(({ sendBack, input: { context } }) => {
4086
3539
  if (!modelSchema.id) {
4087
3540
  throw new Error(`No schema ID found for schema ${JSON.stringify(modelSchema)}`);
4088
3541
  }
4089
- const foundModels = yield sdkConfigDb
3542
+ const foundModels = yield appDb
4090
3543
  .select({
4091
3544
  id: models.id,
4092
3545
  name: models.name,
@@ -4101,14 +3554,14 @@ const initialize$1 = fromCallback(({ sendBack, input: { context } }) => {
4101
3554
  sendBack({ type: 'modelNotFound', modelName });
4102
3555
  return;
4103
3556
  }
4104
- yield sdkConfigDb
3557
+ yield appDb
4105
3558
  .insert(modelUids)
4106
3559
  .values({
4107
3560
  modelId: foundModel.id,
4108
3561
  uid: modelSchema.id,
4109
3562
  })
4110
3563
  .onConflictDoNothing();
4111
- const foundPropertiesDb = yield sdkConfigDb
3564
+ const foundPropertiesDb = yield appDb
4112
3565
  .select({
4113
3566
  id: properties.id,
4114
3567
  name: properties.name,
@@ -4158,7 +3611,7 @@ const initialize$1 = fromCallback(({ sendBack, input: { context } }) => {
4158
3611
  // TODO: We should create the schema here?
4159
3612
  continue;
4160
3613
  }
4161
- yield sdkConfigDb
3614
+ yield appDb
4162
3615
  .insert(propertyUids)
4163
3616
  .values({
4164
3617
  propertyId: foundProperty.id,
@@ -4167,10 +3620,6 @@ const initialize$1 = fromCallback(({ sendBack, input: { context } }) => {
4167
3620
  .onConflictDoNothing();
4168
3621
  }
4169
3622
  }
4170
- const seedDb = getDb(DB_NAME_SEED);
4171
- if (!seedDb) {
4172
- throw new Error('Seed DB not found');
4173
- }
4174
3623
  const addresses = yield getAddressesFromDb();
4175
3624
  queryVariables = {
4176
3625
  where: {
@@ -4219,7 +3668,7 @@ const fetchDbData = fromCallback(({ sendBack, input: { context } }) => {
4219
3668
  return () => { };
4220
3669
  });
4221
3670
 
4222
- const logger$e = debug('app:allItemsActors:fetchSeeds');
3671
+ const logger$i = debug('app:allItemsActors:fetchSeeds');
4223
3672
  const fetchSeeds = fromCallback(({ sendBack, input: { context } }) => {
4224
3673
  const { queryVariables, modelName } = context;
4225
3674
  if (!queryVariables) {
@@ -4229,7 +3678,7 @@ const fetchSeeds = fromCallback(({ sendBack, input: { context } }) => {
4229
3678
  const _fetchSeeds = () => __awaiter(void 0, void 0, void 0, function* () {
4230
3679
  const queryKey = [`getSeeds${modelName}`];
4231
3680
  const cachedResults = queryClient.getQueryData(queryKey);
4232
- logger$e(`[allItemsActors] [fetchSeeds] cachedResults ${Date.now()}`, cachedResults);
3681
+ logger$i(`[allItemsActors] [fetchSeeds] cachedResults ${Date.now()}`, cachedResults);
4233
3682
  const results = yield queryClient.fetchQuery({
4234
3683
  queryKey,
4235
3684
  queryFn: () => __awaiter(void 0, void 0, void 0, function* () { return easClient.request(GET_SEEDS, queryVariables); }),
@@ -4272,14 +3721,7 @@ const fetchVersions = fromCallback(({ sendBack, input: { context } }) => {
4272
3721
 
4273
3722
  const fetchRelatedItems = fromCallback(({ sendBack, input: { context } }) => {
4274
3723
  const { ModelClass, modelName } = context;
4275
- const sdkConfigDb = getSdkDb();
4276
- const seedDb = getDb(DB_NAME_SEED);
4277
- if (!sdkConfigDb) {
4278
- throw new Error('SDK DB not found');
4279
- }
4280
- if (!seedDb) {
4281
- throw new Error('Seed DB not found');
4282
- }
3724
+ const appDb = getAppDb();
4283
3725
  const relatedProperties = new Map();
4284
3726
  const relatedVersionsBySeedUid = new Map();
4285
3727
  const schemaUidsByModelName = new Map();
@@ -4296,7 +3738,7 @@ const fetchRelatedItems = fromCallback(({ sendBack, input: { context } }) => {
4296
3738
  const addresses = yield getAddressesFromDb();
4297
3739
  // Get the models they point to from sdkConfigDb
4298
3740
  for (const [propertyName, propertyDef] of relatedProperties.entries()) {
4299
- const relatedModelQuery = yield sdkConfigDb
3741
+ const relatedModelQuery = yield appDb
4300
3742
  .select({
4301
3743
  id: models.id,
4302
3744
  name: models.name,
@@ -4800,554 +4242,540 @@ const getArweave = () => {
4800
4242
  });
4801
4243
  };
4802
4244
 
4803
- const logger$d = debug('app:react:db');
4804
- const useDbsAreReady = () => {
4805
- const [dbsAreReady, setDbsAreReady] = useState(false);
4806
- const update = useCallback(() => {
4807
- if (dbsAreReady) {
4245
+ const initSeedSync = () => {
4246
+ if (isNode()) {
4247
+ return {
4248
+ Model,
4249
+ Property,
4250
+ ImageSrc,
4251
+ List,
4252
+ Text,
4253
+ Json,
4254
+ Relation,
4255
+ withSeed: withSeed$1,
4256
+ };
4257
+ }
4258
+ else {
4259
+ return {
4260
+ Model,
4261
+ Property,
4262
+ ImageSrc,
4263
+ Relation,
4264
+ Text,
4265
+ List,
4266
+ Json,
4267
+ };
4268
+ }
4269
+ };
4270
+
4271
+ const logger$h = debug('app:services:global:actors:initialize');
4272
+ const initialize = fromCallback(({ sendBack, input: { event, context } }) => {
4273
+ const { internalService, models, endpoints } = context;
4274
+ const { addresses } = event;
4275
+ let environment = 'browser';
4276
+ if (isNode()) {
4277
+ environment = 'node';
4278
+ }
4279
+ if (isReactNative()) {
4280
+ environment = 'react-native';
4281
+ }
4282
+ let internalSubscription;
4283
+ if (environment === 'browser' && models) {
4284
+ const _initFileSystem = () => __awaiter(void 0, void 0, void 0, function* () {
4808
4285
  return;
4809
- }
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$d('[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
- });
4286
+ // return new Promise((resolve) => {
4287
+ // })
4288
+ });
4289
+ const _initInternal = () => __awaiter(void 0, void 0, void 0, function* () {
4290
+ return new Promise((resolve) => {
4291
+ internalSubscription = internalService.subscribe((snapshot) => {
4292
+ logger$h('[sdk] [internal] snapshot', snapshot);
4293
+ if (snapshot.value === 'ready') {
4294
+ resolve();
4829
4295
  }
4830
4296
  });
4831
- return;
4832
- }
4833
- const currentState = internalService.getSnapshot().value;
4834
- if (currentState === 'ready') {
4835
- update();
4836
- return;
4837
- }
4838
- internalSubscription = internalService.subscribe((snapshot) => {
4839
- if (snapshot.value === 'ready') {
4840
- update();
4841
- internalSubscription === null || internalSubscription === void 0 ? void 0 : internalSubscription.unsubscribe();
4842
- }
4297
+ internalService.send({ type: 'init', endpoints, addresses });
4843
4298
  });
4844
4299
  });
4845
- _waitForDbs();
4846
- return () => {
4847
- if (globalSubscription) {
4848
- globalSubscription.unsubscribe();
4849
- }
4850
- if (internalSubscription) {
4851
- internalSubscription.unsubscribe();
4852
- }
4853
- };
4854
- }, []);
4855
- return {
4856
- dbsAreReady,
4300
+ _initFileSystem().then(() => {
4301
+ logger$h('[global/actors] File system initialized');
4302
+ });
4303
+ _initInternal().then(() => {
4304
+ logger$h('[global/actors] Internal initialized');
4305
+ sendBack({ type: GLOBAL_INITIALIZING_INTERNAL_SERVICE_READY });
4306
+ internalSubscription === null || internalSubscription === void 0 ? void 0 : internalSubscription.unsubscribe();
4307
+ });
4308
+ // _initEas().then(() => {
4309
+ // logger('EAS initialized')
4310
+ // })
4311
+ }
4312
+ sendBack({ type: GLOBAL_INITIALIZING_SEND_CONFIG, environment });
4313
+ return () => {
4314
+ internalSubscription === null || internalSubscription === void 0 ? void 0 : internalSubscription.unsubscribe();
4857
4315
  };
4858
- };
4316
+ });
4859
4317
 
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';
4882
- }
4318
+ const logger$g = debug('app:services:global:actors:getSchemaForModel');
4319
+ const getSchemaForModel = fromCallback(({ sendBack, input: { context, event } }) => {
4320
+ const { modelName } = event;
4321
+ if (!modelName) {
4322
+ console.warn('No modelName found');
4323
+ return;
4883
4324
  }
4884
- return value;
4885
- };
4886
- const getServiceUniqueKey = (service) => {
4887
- if (!service || !service.logic || !service.logic.config) {
4325
+ const { models } = context;
4326
+ if (!models) {
4327
+ console.warn('No models found');
4888
4328
  return;
4889
4329
  }
4890
- const config = service.logic.config;
4891
- if (!config.id) {
4892
- return;
4893
- }
4894
- let uniqueKey = config.id;
4895
- if (config.id.includes('@seedSdk/')) {
4896
- uniqueKey = config.id.match(/^.*@seedSdk\/(\w+)[\.\w]*/)[1];
4897
- }
4898
- let snapshot;
4899
- try {
4900
- snapshot = service.getSnapshot();
4901
- }
4902
- catch (error) {
4903
- console.error('Error:', error);
4904
- return;
4330
+ const model = Object.entries(models).find(([modelNameFromConfig]) => modelNameFromConfig === modelName);
4331
+ if (!model) {
4332
+ throw new Error(`Model ${modelName} not found`);
4905
4333
  }
4906
- if (snapshot) {
4907
- const context = snapshot.context;
4908
- if (context && context.dbName) {
4909
- uniqueKey = context.dbName;
4910
- }
4911
- if (context && context.modelNamePlural) {
4912
- uniqueKey = context.modelNamePlural;
4913
- }
4914
- if (context && context.modelName) {
4915
- uniqueKey = pluralize(context.modelName.toLowerCase());
4334
+ logger$g('[service/actor] [getSchemaForModel] model:', model);
4335
+ sendBack({ type: 'schemaForModel', schema: model.schema });
4336
+ return () => { };
4337
+ });
4338
+
4339
+ const logger$f = debug('app:services:global:actors:addModelsToDb');
4340
+ const addModelsToDb = fromCallback(({ sendBack, input: { context } }) => {
4341
+ const { models: models$1 } = context;
4342
+ const _addModelsToDb = () => __awaiter(void 0, void 0, void 0, function* () {
4343
+ var _a;
4344
+ const appDb = getAppDb();
4345
+ if (!models$1) {
4346
+ return;
4916
4347
  }
4917
- }
4918
- return uniqueKey;
4919
- };
4920
- const useServices = () => {
4921
- const [actors, setActors] = useState([]);
4922
- const [percentComplete, setPercentComplete] = useState(5);
4923
- const actorsMap = new Map();
4924
- useEffect(() => {
4925
- const globalServiceListener = (event) => {
4926
- if (event && event.type === 'init') {
4927
- return;
4348
+ const { models: SeedModels } = yield import('./seed.schema.config-CCYo8gj-.js');
4349
+ const allModels = Object.assign(Object.assign({}, SeedModels), models$1);
4350
+ let hasModelsInDb = false;
4351
+ const schemaDefsByModelName = new Map();
4352
+ for (const [modelName, _] of Object.entries(allModels)) {
4353
+ logger$f('[helpers/db] [addModelsToInternalDb] starting modelName:', modelName);
4354
+ let foundModel;
4355
+ const foundModelsQuery = yield appDb
4356
+ .select()
4357
+ .from(models)
4358
+ .where(eq(models.name, modelName));
4359
+ if (!foundModelsQuery || foundModelsQuery.length === 0) {
4360
+ yield appDb.insert(models).values({
4361
+ name: modelName,
4362
+ });
4363
+ logger$f('[global/actors] [addModelsToDb] inserted model:', modelName);
4364
+ const foundModels = yield appDb
4365
+ .select({
4366
+ id: models.id,
4367
+ name: models.name,
4368
+ uid: modelUids.uid,
4369
+ })
4370
+ .from(models)
4371
+ .leftJoin(modelUids, eq(models.id, modelUids.modelId))
4372
+ .where(eq(models.name, modelName))
4373
+ .limit(1);
4374
+ foundModel = foundModels[0];
4928
4375
  }
4929
- if (event.actorRef &&
4930
- event.actorRef.logic &&
4931
- event.actorRef.logic.config) {
4932
- const uniqueKey = getServiceUniqueKey(event.actorRef);
4933
- if (!uniqueKey) {
4934
- return;
4935
- }
4936
- event.actorRef.uniqueKey = uniqueKey;
4937
- actorsMap.set(uniqueKey, event.actorRef);
4938
- let actorsArray = Array.from(actorsMap.values());
4939
- actorsArray = orderBy(actorsArray, (a) => a.logic.config.id, ['asc']);
4940
- setActors(produce(actors, (draft) => {
4941
- return actorsArray;
4942
- }));
4376
+ if (foundModelsQuery && foundModelsQuery.length > 0) {
4377
+ foundModel = foundModelsQuery[0];
4943
4378
  }
4944
- };
4945
- eventEmitter.addListener('inspect.globalService', globalServiceListener);
4946
- return () => {
4947
- eventEmitter.removeListener('inspect.globalService', globalServiceListener);
4948
- };
4949
- }, []);
4950
- useEffect(() => {
4951
- const globalService = actors.find((actor) => getServiceName(actor) === 'global');
4952
- const internalService = actors.find((actor) => getServiceName(actor) === 'internal');
4953
- if (!globalService || !internalService) {
4954
- return;
4955
- }
4956
- if (getServiceValue(globalService) === 'ready' &&
4957
- getServiceValue(internalService) === 'ready') {
4958
- const denominator = actors.length;
4959
- const finishedActors = actors.filter((actor) => {
4960
- const value = getServiceValue(actor);
4961
- return finalStrings.includes(value);
4379
+ if (!foundModel) {
4380
+ hasModelsInDb = false;
4381
+ break;
4382
+ }
4383
+ schemaDefsByModelName.set(modelName, {
4384
+ dbId: foundModel.id,
4385
+ schemaDef: `bytes32 ${toSnakeCase(modelName)}`,
4962
4386
  });
4963
- const numerator = finishedActors.length;
4964
- const percentComplete = (numerator / denominator) * 100;
4965
- setPercentComplete(percentComplete);
4966
4387
  }
4967
- }, [actors]);
4968
- return {
4969
- services: actors,
4970
- percentComplete,
4971
- };
4972
- };
4973
- const useGlobalServiceStatus = () => {
4974
- const globalService = getGlobalService();
4975
- const status = useSelector(globalService, (snapshot) => {
4976
- return snapshot.value;
4388
+ if (!hasModelsInDb) {
4389
+ return false;
4390
+ }
4391
+ const schemaDefs = Array.from(schemaDefsByModelName.values()).map(({ schemaDef }) => schemaDef);
4392
+ const { schemas } = yield queryClient.fetchQuery({
4393
+ queryKey: [`getSchemasVersion`],
4394
+ queryFn: () => __awaiter(void 0, void 0, void 0, function* () {
4395
+ return easClient.request(GET_SCHEMAS, {
4396
+ where: {
4397
+ schema: {
4398
+ in: schemaDefs,
4399
+ },
4400
+ },
4401
+ });
4402
+ }),
4403
+ });
4404
+ if (!schemas || schemas.length === 0) {
4405
+ throw new Error(`No schemas found`);
4406
+ }
4407
+ for (const schema of schemas) {
4408
+ const modelId = (_a = Array.from(schemaDefsByModelName.values()).find(({ schemaDef }) => schemaDef === schema.schema)) === null || _a === void 0 ? void 0 : _a.dbId;
4409
+ if (!modelId) {
4410
+ throw new Error(`No modelId found for schema ${schema.schema}`);
4411
+ }
4412
+ yield appDb
4413
+ .insert(modelUids)
4414
+ .values({
4415
+ modelId,
4416
+ uid: schema.id,
4417
+ })
4418
+ .onConflictDoNothing();
4419
+ }
4977
4420
  });
4978
- const internalStatus = useSelector(globalService.getSnapshot().context.internalService, (snapshot) => {
4979
- if (!snapshot) {
4980
- return;
4421
+ _addModelsToDb().then((hasModelsInDb) => {
4422
+ sendBack({ type: GLOBAL_ADDING_MODELS_TO_DB_SUCCESS });
4423
+ for (const [modelName, model] of Object.entries(models$1)) {
4424
+ const service = context[`${modelName}Service`];
4425
+ service.send({ type: 'modelsFound' });
4981
4426
  }
4982
- return snapshot.value;
4427
+ eventEmitter.emit('syncDbWithEas');
4428
+ return;
4983
4429
  });
4984
- useSelector(globalService, (snapshot) => {
4985
- return snapshot.context.internalService;
4430
+ return () => { };
4431
+ });
4432
+
4433
+ const logger$e = debug('app:services:db:actors:checkStatus');
4434
+ const checkStatus = fromCallback(({ sendBack, input: { context } }) => {
4435
+ const { dbName } = context;
4436
+ logger$e('[db/actors] checkStatus context', context);
4437
+ const pathToDir = `${BROWSER_FS_TOP_DIR}`;
4438
+ const pathToDbDir = `${pathToDir}/db`;
4439
+ const pathToDb = `${pathToDbDir}/${dbName}.sqlite3`;
4440
+ sendBack({
4441
+ type: DB_CHECK_STATUS_UPDATE_PATHS,
4442
+ pathToDb,
4443
+ pathToDir,
4444
+ pathToDbDir,
4986
4445
  });
4987
- return {
4988
- status,
4989
- internalStatus,
4990
- };
4991
- };
4446
+ const _checkStatus = () => __awaiter(void 0, void 0, void 0, function* () {
4447
+ // logger('[db/actors] _checkStatus pathToDb', pathToDb)
4448
+ // const exists = await fs.promises.exists(pathToJournal)
4449
+ // if (exists) {
4450
+ // sendBack({
4451
+ // type: DB_CHECK_STATUS_EXISTS,
4452
+ // })
4453
+ // return
4454
+ // }
4455
+ //
4456
+ // return new Promise((resolve) => {
4457
+ // sendBack({ type: DB_CHECK_STATUS_DOES_NOT_EXIST })
4458
+ //
4459
+ // })
4460
+ });
4461
+ _checkStatus().then(() => {
4462
+ sendBack({ type: DB_CHECK_STATUS_EXISTS });
4463
+ return;
4464
+ });
4465
+ });
4992
4466
 
4993
- const logger$c = debug('app:react:item');
4994
- const useItem = ({ modelName, seedLocalId, seedUid }) => {
4995
- const [item, setItem] = useImmer(undefined);
4996
- const [itemSubscription, setItemSubscription] = useState();
4997
- const { status, internalStatus } = useGlobalServiceStatus();
4998
- const isReadingDb = useRef(false);
4999
- const itemStatus = useSelector(item === null || item === void 0 ? void 0 : item.getService(), (snapshot) => snapshot === null || snapshot === void 0 ? void 0 : snapshot.value);
5000
- const updateItem = useCallback((newItem) => {
5001
- setItem(() => newItem);
5002
- }, []);
5003
- const readFromDb = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
5004
- if (isReadingDb.current ||
5005
- internalStatus !== 'ready' ||
5006
- (!seedUid && !seedLocalId)) {
4467
+ const logger$d = debug('app:services:db:actors:connectToDb');
4468
+ const connectToDb = fromCallback(({ sendBack, input: { context } }) => {
4469
+ logger$d('[db/actors] connectToDb context', context);
4470
+ const { dbName, pathToDir } = context;
4471
+ let isConnecting = false;
4472
+ let dbId;
4473
+ const _create = () => __awaiter(void 0, void 0, void 0, function* () {
4474
+ if (isConnecting) {
5007
4475
  return;
5008
4476
  }
5009
- isReadingDb.current = true;
5010
- const foundItem = yield Item.find({
5011
- modelName,
5012
- seedLocalId,
5013
- seedUid,
4477
+ isConnecting = true;
4478
+ let response;
4479
+ const sqliteWasmClient = yield getSqliteWasmClient();
4480
+ //@ts-ignore
4481
+ response = yield sqliteWasmClient('config-get', {});
4482
+ logger$d(response);
4483
+ logger$d('Running SQLite3 version', response.result.version.libVersion);
4484
+ //@ts-ignore
4485
+ response = yield sqliteWasmClient('open', {
4486
+ filename: `file:${pathToDir}/db/${dbName}.sqlite3?vfs=opfs`,
5014
4487
  });
5015
- if (!foundItem) {
5016
- logger$c('[useItem] [getItemFromDb] no item found', modelName, seedLocalId);
4488
+ logger$d(response);
4489
+ dbId = response.dbId;
4490
+ // logger(`dbId: ${dbId}`)
4491
+ logger$d('OPFS is available, created persisted database at', response.result.filename.replace(/^file:(.*?)\?vfs=opfs$/, '$1'));
4492
+ });
4493
+ const interval = setInterval(() => {
4494
+ // TODO: Add a timeout
4495
+ // TODO: Add a cancel token to the promise so we can prevent more loops starting while we're checking the successful outcome
4496
+ if (dbId) {
4497
+ // logger(
4498
+ // '[db/actors] opening sqliteWasm connection with dbId:',
4499
+ // dbId,
4500
+ // )
4501
+ clearInterval(interval);
4502
+ sendBack({ type: DB_CREATING_SUCCESS, dbId });
5017
4503
  return;
5018
4504
  }
5019
- updateItem(foundItem);
5020
- isReadingDb.current = false;
5021
- }), [internalStatus]);
5022
- useEffect(() => {
5023
- if (internalStatus === 'ready') {
5024
- readFromDb();
5025
- }
5026
- }, [internalStatus, status]);
5027
- useEffect(() => {
5028
- if (item && !itemSubscription) {
5029
- const subscription = item.subscribe((_) => __awaiter(void 0, void 0, void 0, function* () {
5030
- const newItem = yield Item.find({ modelName, seedLocalId, seedUid });
5031
- if (!newItem) {
5032
- logger$c('[useItem] [itemSubscription] no item found', modelName, seedLocalId);
5033
- return;
5034
- }
5035
- setItem(() => newItem);
5036
- }));
5037
- setItemSubscription(subscription);
5038
- }
5039
- return () => {
5040
- itemSubscription === null || itemSubscription === void 0 ? void 0 : itemSubscription.unsubscribe();
5041
- };
5042
- }, [item, itemSubscription]);
5043
- useEffect(() => {
5044
- const seedId = seedUid || seedLocalId;
5045
- eventEmitter.addListener(`item.${modelName}.${seedId}.update`, readFromDb);
5046
- return () => {
5047
- eventEmitter.removeListener(`item.${modelName}.${seedId}.update`, readFromDb);
5048
- };
5049
- }, []);
5050
- return {
5051
- item,
5052
- itemStatus,
5053
- };
5054
- };
5055
- const useItems = ({ modelName, options }) => {
5056
- const [items, setItems] = useImmer([]);
5057
- const [isReadingDb, setIsReadingDb] = useState(false);
5058
- const [isInitialized, setIsInitialized] = useState(false);
5059
- const { dbsAreReady } = useDbsAreReady();
5060
- const modelNameRef = useRef(modelName);
5061
- const readFromDb = useCallback((event) => __awaiter(void 0, void 0, void 0, function* () {
5062
- if (!event ||
5063
- !event.modelName ||
5064
- event.modelName !== modelNameRef.current ||
5065
- isReadingDb) {
5066
- return;
5067
- }
5068
- setIsReadingDb(true);
5069
- const allItems = yield Item.all(modelNameRef.current);
5070
- setItems(() => allItems);
5071
- setIsReadingDb(false);
5072
- }), [modelName]);
5073
- useEffect(() => {
5074
- if (dbsAreReady && !isInitialized) {
5075
- const _fetchItems = () => __awaiter(void 0, void 0, void 0, function* () {
5076
- yield readFromDb({ modelName });
5077
- setIsInitialized(true);
5078
- });
5079
- _fetchItems();
5080
- }
5081
- }, [dbsAreReady, isInitialized]);
5082
- useEffect(() => {
5083
- eventEmitter.addListener('item.requestAll', readFromDb);
5084
- return () => {
5085
- eventEmitter.removeListener('item.requestAll');
5086
- };
5087
- }, []);
5088
- return {
5089
- items: orderBy(items, [
5090
- (item) => item.lastVersionPublishedAt ||
5091
- item.attestationCreatedAt ||
5092
- item.createdAt,
5093
- ], ['desc']).slice(0, 10),
5094
- isReadingDb,
5095
- isInitialized,
5096
- };
5097
- };
5098
- const useItemIsReady = () => {
5099
- const [itemListenersReady, setItemListenersReady] = useState(false);
5100
- const itemEventListenersHandler = useCallback((_) => {
5101
- setItemListenersReady(true);
5102
- }, []);
5103
- useEffect(() => {
5104
- const areReady = getAreItemEventHandlersReady();
5105
- if (areReady) {
5106
- itemEventListenersHandler(true);
5107
- }
5108
- eventEmitter.addListener('item.events.setupAllItemsEventHandlers', itemEventListenersHandler);
5109
- return () => {
5110
- eventEmitter.removeListener('item.events.setupAllItemsEventHandlers');
5111
- };
5112
- }, []);
5113
- return {
5114
- isReady: itemListenersReady,
5115
- };
5116
- };
5117
- const useCreateItem = (modelName) => {
5118
- const [isCreatingItem, setIsCreatingItem] = useState(false);
5119
- const { isReady } = useItemIsReady();
5120
- const createItem = useCallback((itemData) => __awaiter(void 0, void 0, void 0, function* () {
5121
- if (!isReady) {
5122
- console.error(`[useCreateItem] [createItem] called before listeners are ready`, itemData);
5123
- return;
5124
- }
5125
- if (isCreatingItem) {
5126
- // TODO: should we setup a queue for this?
5127
- console.error(`[useCreateItem] [createItem] already creating item`, itemData);
5128
- return;
5129
- }
5130
- setIsCreatingItem(true);
5131
- const { seedLocalId } = yield createNewItem(Object.assign({ modelName }, itemData));
5132
- yield Item.find({ modelName, seedLocalId });
5133
- eventEmitter.emit('item.requestAll', { modelName });
5134
- setIsCreatingItem(false);
5135
- }), [isCreatingItem, isReady]);
5136
- return {
5137
- createItem,
5138
- isCreatingItem,
5139
- };
5140
- };
5141
- const useDeleteItem = () => {
5142
- const [isDeletingItem, setIsDeletingItem] = useState(false);
5143
- const destroy = useCallback((item) => __awaiter(void 0, void 0, void 0, function* () {
5144
- if (!item) {
5145
- return;
5146
- }
5147
- setIsDeletingItem(true);
5148
- const { modelName } = item.getService().getSnapshot().context;
5149
- yield deleteItem({ seedLocalId: item.seedLocalId });
5150
- eventEmitter.emit('item.requestAll', { modelName });
5151
- setIsDeletingItem(false);
5152
- }), [isDeletingItem]);
5153
- useEffect(() => { }, []);
5154
- return {
5155
- deleteItem: destroy,
5156
- isDeletingItem,
5157
- };
5158
- };
5159
-
5160
- const logger$b = debug('app:react:property');
5161
- const useItemProperty = (propertyName, seedLocalId) => {
5162
- const [property, setProperty] = useImmer(undefined);
5163
- const [isReadingFromDb, setIsReadingFromDb] = useState(false);
5164
- const [isInitialized, setIsInitialized] = useState(false);
5165
- const dbsAreReady = useDbsAreReady();
5166
- const value = useSelector(property === null || property === void 0 ? void 0 : property.getService(), (snapshot) => {
5167
- if (!snapshot || !snapshot.context) {
5168
- return;
5169
- }
5170
- return snapshot.context.renderValue || snapshot.context.propertyValue;
5171
- });
5172
- const status = useSelector(property === null || property === void 0 ? void 0 : property.getService(), (snapshot) => snapshot === null || snapshot === void 0 ? void 0 : snapshot.value);
5173
- useEffect(() => {
5174
- if (dbsAreReady && property && property.value !== value) {
5175
- readFromDb();
5176
- }
5177
- }, [dbsAreReady, property, value]);
5178
- const readFromDb = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
5179
- if (!dbsAreReady && isReadingFromDb) {
5180
- return;
5181
- }
5182
- setIsReadingFromDb(true);
5183
- const foundProperty = yield ItemProperty.find({ propertyName, seedLocalId });
5184
- setIsReadingFromDb(false);
5185
- if (!foundProperty) {
5186
- logger$b(`[useItemPropertyTest] [readFromDb] no property found for Item.${seedLocalId}.${propertyName}`);
5187
- return;
5188
- }
5189
- setProperty(() => foundProperty);
5190
- setIsInitialized(true);
5191
- }), [dbsAreReady, isReadingFromDb]);
5192
- useEffect(() => {
5193
- readFromDb();
5194
- }, []);
5195
- // TODO: How can we force a re-render when the property is updated?
5196
- // Right now, the value will trigger an update because it's using a selector
5197
- // and a change is pushed to the hook listener.
5198
- return {
5199
- property,
5200
- isInitialized,
5201
- isReadingFromDb,
5202
- value,
5203
- status,
5204
- };
5205
- };
5206
- const useItemProperties = (item) => {
5207
- const [propertyObj, setPropertyObj] = useImmer({});
5208
- useState(false);
5209
- const updatePropertyObj = useCallback((event) => {
5210
- if (!item) {
5211
- console.error('[XXXXXX] [updatePropertyObj] no item when expected');
5212
- return;
5213
- }
5214
- const { propertyName, propertyValue } = event;
5215
- if (!propertyName) {
4505
+ _create()
4506
+ .then(() => {
5216
4507
  return;
5217
- }
5218
- setPropertyObj((draft) => {
5219
- draft[propertyName] = propertyValue;
4508
+ })
4509
+ .catch((e) => {
4510
+ isConnecting = false;
5220
4511
  });
5221
- }, [item]);
5222
- useEffect(() => {
5223
- if (!item) {
5224
- return;
4512
+ }, 500);
4513
+ return () => {
4514
+ if (interval) {
4515
+ clearInterval(interval);
5225
4516
  }
5226
- const eventKey = `item.${item.seedLocalId}.property.update`;
5227
- eventEmitter.addListener(eventKey, updatePropertyObj);
5228
- return () => {
5229
- eventEmitter.removeListener(eventKey, updatePropertyObj);
5230
- };
5231
- }, [item]);
5232
- return {
5233
- properties: propertyObj,
5234
4517
  };
5235
- };
4518
+ });
5236
4519
 
5237
- const logger$a = debug('app:global:actors');
5238
- const addModelsToDb = fromCallback(({ sendBack, input: { context } }) => {
5239
- const { models: models$1 } = context;
5240
- const _addModelsToDb = () => __awaiter(void 0, void 0, void 0, function* () {
5241
- var _a;
5242
- const sdkConfigDb = getSdkDb();
5243
- if (!models$1) {
5244
- return;
5245
- }
5246
- const { models: SeedModels } = yield import('./seed.schema.config-GKCk8sOV.js');
5247
- const allModels = Object.assign(Object.assign({}, SeedModels), models$1);
5248
- let hasModelsInDb = false;
5249
- const schemaDefsByModelName = new Map();
5250
- for (const [modelName, _] of Object.entries(allModels)) {
5251
- logger$a('[helpers/db] [addModelsToInternalDb] starting modelName:', modelName);
5252
- let foundModel;
5253
- const foundModelsQuery = yield sdkConfigDb
5254
- .select()
5255
- .from(models)
5256
- .where(eq(models.name, modelName));
5257
- if (!foundModelsQuery || foundModelsQuery.length === 0) {
5258
- yield sdkConfigDb.insert(models).values({
5259
- name: modelName,
4520
+ const validate = fromCallback(({ sendBack, input: { context } }) => {
4521
+ const { pathToDir, pathToDb } = context;
4522
+ const pathsToCheck = [
4523
+ pathToDir,
4524
+ `${pathToDir}/db`,
4525
+ `${pathToDir}/db/meta`,
4526
+ `${pathToDir}/db/meta/_journal.json`,
4527
+ ];
4528
+ const _validate = () => __awaiter(void 0, void 0, void 0, function* () {
4529
+ // If any of the necessary files don't exist, we wipe them all and recreate
4530
+ let exists = false;
4531
+ for (const path of pathsToCheck) {
4532
+ exists = yield fs.promises.exists(path);
4533
+ if (!exists) {
4534
+ sendBack({
4535
+ type: DB_VALIDATING_WAIT,
5260
4536
  });
5261
- logger$a('[global/actors] [addModelsToDb] inserted model:', modelName);
5262
- const foundModels = yield sdkConfigDb
5263
- .select({
5264
- id: models.id,
5265
- name: models.name,
5266
- uid: modelUids.uid,
5267
- })
5268
- .from(models)
5269
- .leftJoin(modelUids, eq(models.id, modelUids.modelId))
5270
- .where(eq(models.name, modelName))
5271
- .limit(1);
5272
- foundModel = foundModels[0];
4537
+ return false;
5273
4538
  }
5274
- if (foundModelsQuery && foundModelsQuery.length > 0) {
5275
- foundModel = foundModelsQuery[0];
5276
- }
5277
- if (!foundModel) {
5278
- hasModelsInDb = false;
5279
- break;
5280
- }
5281
- schemaDefsByModelName.set(modelName, {
5282
- dbId: foundModel.id,
5283
- schemaDef: `bytes32 ${toSnakeCase(modelName)}`,
5284
- });
5285
4539
  }
5286
- if (!hasModelsInDb) {
5287
- return false;
4540
+ return exists;
4541
+ });
4542
+ _validate().then(() => {
4543
+ sendBack({ type: DB_VALIDATING_SUCCESS, pathToDb, pathToDir });
4544
+ return;
4545
+ });
4546
+ });
4547
+
4548
+ const logger$c = debug('app:services:db:actors:migrate');
4549
+ const dbExec = (dbId_1, params_1, sql_1, dbName_1, ...args_1) => __awaiter(void 0, [dbId_1, params_1, sql_1, dbName_1, ...args_1], void 0, function* (dbId, params, sql, dbName, retries = 2) {
4550
+ const rowsToReturnRaw = [];
4551
+ const sqliteWasmClient = yield getSqliteWasmClient();
4552
+ // For a single exec command, the callback potentially gets called several times -- once for each row.
4553
+ // So we need to collect all rows into a final array to return (execResult).
4554
+ const rowsToReturn = yield new Promise((resolve, reject) => {
4555
+ sqliteWasmClient('exec', {
4556
+ dbId,
4557
+ sql,
4558
+ bind: params,
4559
+ callback: (result) => {
4560
+ // Checks if this is the final callback of the query
4561
+ if (!result || !result.row || !result.rowNumber) {
4562
+ const returnResult = [];
4563
+ // Before returning the array, we process it to match the expected output format
4564
+ // const rowsToReturnProcessed = rowsToReturnRaw.reduce((acc, curr) => {
4565
+ // if (
4566
+ // Array.isArray(curr.row) &&
4567
+ // curr.row?.length > 0 &&
4568
+ // curr.columnNames.length > 0
4569
+ // ) {
4570
+ // const returnObj: ReturnObj = {
4571
+ // database: dbName,
4572
+ // }
4573
+ //
4574
+ // const values = []
4575
+ //
4576
+ // curr.columnNames.forEach((colName, index: number) => {
4577
+ // if (curr.row && curr.row[index]) {
4578
+ // returnObj[colName] = curr.row[index]
4579
+ // values.push(curr.row[index])
4580
+ // }
4581
+ // })
4582
+ // // rowsValueStrings.push(`(${values.join(', ')})`)
4583
+ // acc.push(returnObj)
4584
+ // }
4585
+ // return acc
4586
+ // }, [] as string[])
4587
+ for (const currRow of rowsToReturnRaw) {
4588
+ // const values: string[] = []
4589
+ // currRow.columnNames.forEach((colName, index: number) => {
4590
+ // if (currRow.row) {
4591
+ // values.push(currRow.row[index])
4592
+ // }
4593
+ // })
4594
+ // logger(`[db/actors] [dbExec] currRow`, currRow)
4595
+ returnResult.push(currRow.row);
4596
+ }
4597
+ resolve(returnResult);
4598
+ }
4599
+ else {
4600
+ // If not the final response, add this row to the return array
4601
+ rowsToReturnRaw.push(result);
4602
+ }
4603
+ },
4604
+ }).catch((error) => __awaiter(void 0, void 0, void 0, function* () {
4605
+ reject(error);
4606
+ }));
4607
+ });
4608
+ // logger(`[db/actors] [dbExec] rowsToReturn`, rowsToReturn)
4609
+ // logger(`[db/actors] [dbExec] rowsValues`, rowsValues)
4610
+ return rowsToReturn || [];
4611
+ });
4612
+ const migrate = fromCallback(({ sendBack, input: { context } }) => {
4613
+ const { pathToDbDir, dirName, dbId, dbName } = context;
4614
+ logger$c('[db/actors] migrate context', context);
4615
+ const schemaGlobString = `${BROWSER_FS_TOP_DIR}/${dirName}/schema/*`;
4616
+ let journalExists = false;
4617
+ // const _initFs = async (): Promise<void> => {
4618
+ // const handle = await navigator.storage.getDirectory()
4619
+ // // await configure({ backend: WebAccess, handle })
4620
+ // await configureSingle({
4621
+ // backend: WebAccess,
4622
+ // handle,
4623
+ // })
4624
+ // }
4625
+ //
4626
+ // _initFs()
4627
+ const _checkForFiles = () => __awaiter(void 0, void 0, void 0, function* () {
4628
+ const { fs } = yield import('@zenfs/core');
4629
+ journalExists = yield fs.promises.exists(`/${pathToDbDir}/meta/_journal.json`);
4630
+ if (!journalExists) {
4631
+ window.location.reload();
4632
+ // setTimeout(() => {
4633
+ // _checkForFiles().then(() => {
4634
+ // return
4635
+ // })
4636
+ // }, 500)
5288
4637
  }
5289
- const schemaDefs = Array.from(schemaDefsByModelName.values()).map(({ schemaDef }) => schemaDef);
5290
- const { schemas } = yield queryClient.fetchQuery({
5291
- queryKey: [`getSchemasVersion`],
5292
- queryFn: () => __awaiter(void 0, void 0, void 0, function* () {
5293
- return easClient.request(GET_SCHEMAS, {
5294
- where: {
5295
- schema: {
5296
- in: schemaDefs,
5297
- },
5298
- },
5299
- });
5300
- }),
4638
+ });
4639
+ const _migrate = () => __awaiter(void 0, void 0, void 0, function* () {
4640
+ const drizzleDb = drizzle((sql, params, method) => __awaiter(void 0, void 0, void 0, function* () {
4641
+ try {
4642
+ // logger(
4643
+ // `executing sql on ${dbName} with id: ${dbId} and method: ${method}`,
4644
+ // sql,
4645
+ // )
4646
+ const finalResult = yield dbExec(dbId, params, sql, dbName);
4647
+ // logger(`finalResult with method: ${method}`, finalResult)
4648
+ // Drizzle always waits for {rows: string[][]} or {rows: string[]} for the return value.
4649
+ // When the method is get, you should return a value as {rows: string[]}.
4650
+ // Otherwise, you should return {rows: string[][]}.
4651
+ return { rows: finalResult };
4652
+ }
4653
+ catch (e) {
4654
+ console.error('Error from sqlite proxy server: ', JSON.stringify(e));
4655
+ return { rows: [] };
4656
+ }
4657
+ }), {
4658
+ schema: schemaGlobString,
4659
+ // logger: true,
5301
4660
  });
5302
- if (!schemas || schemas.length === 0) {
5303
- throw new Error(`No schemas found`);
5304
- }
5305
- for (const schema of schemas) {
5306
- const modelId = (_a = Array.from(schemaDefsByModelName.values()).find(({ schemaDef }) => schemaDef === schema.schema)) === null || _a === void 0 ? void 0 : _a.dbId;
5307
- if (!modelId) {
5308
- throw new Error(`No modelId found for schema ${schema.schema}`);
4661
+ const { migrate: drizzleMigrate } = yield import('drizzle-orm/sqlite-proxy/migrator');
4662
+ const { readMigrationFiles } = yield import('drizzle-orm/migrator');
4663
+ try {
4664
+ const migrations = readMigrationFiles({
4665
+ migrationsFolder: pathToDbDir,
4666
+ });
4667
+ if (migrations.length > 0) {
4668
+ const incomingMigrationHashes = migrations.map((migration) => migration.hash);
4669
+ let existingMigrationHashes;
4670
+ let rows = [];
4671
+ try {
4672
+ const query = yield drizzleDb.run(sql.raw(`SELECT hash, created_at
4673
+ FROM main.__drizzle_migrations;`));
4674
+ rows = query.rows;
4675
+ }
4676
+ catch (e) {
4677
+ rows = [];
4678
+ }
4679
+ if (rows && rows.length > 0) {
4680
+ existingMigrationHashes = rows.map((row) => row[0]);
4681
+ }
4682
+ if (existingMigrationHashes) {
4683
+ let shouldRebuildDb = false;
4684
+ for (const existingHash of existingMigrationHashes) {
4685
+ if (!incomingMigrationHashes.includes(existingHash)) {
4686
+ shouldRebuildDb = true;
4687
+ break;
4688
+ }
4689
+ }
4690
+ if (shouldRebuildDb) {
4691
+ yield fs.promises.unlink(`${pathToDbDir}/${dbName}.sqlite3`);
4692
+ }
4693
+ }
5309
4694
  }
5310
- yield sdkConfigDb
5311
- .insert(modelUids)
5312
- .values({
5313
- modelId,
5314
- uid: schema.id,
5315
- })
5316
- .onConflictDoNothing();
4695
+ yield drizzleMigrate(drizzleDb, (queriesToRun) => __awaiter(void 0, void 0, void 0, function* () {
4696
+ // logger('queriesToRun', queriesToRun)
4697
+ for (const query of queriesToRun) {
4698
+ // logger('query', query)
4699
+ yield drizzleDb.run(sql.raw(query));
4700
+ }
4701
+ }), {
4702
+ migrationsFolder: pathToDbDir,
4703
+ });
4704
+ }
4705
+ catch (error) {
4706
+ console.error('Error migrating database: ', error);
4707
+ window.location.reload();
5317
4708
  }
4709
+ setAppDb(drizzleDb);
4710
+ // const createTempTableQuery = await appDb.run(
4711
+ // sql.raw(
4712
+ // `CREATE TEMP TABLE IF NOT EXISTS temp_last_inserted_id (id INTEGER, table TEXT);`,
4713
+ // ),
4714
+ // )
4715
+ //
4716
+ // logger(
4717
+ // '[db/actors] [migrate] createTempTableQuery',
4718
+ // createTempTableQuery,
4719
+ // )
4720
+ // const triggersQuery = await appDb.run(
4721
+ // sql.raw(
4722
+ // `SELECT name
4723
+ // FROM main.sqlite_master
4724
+ // WHERE type = 'trigger';`,
4725
+ // ),
4726
+ // )
4727
+ //
4728
+ // logger('[db/actors] [migrate] triggersQuery', triggersQuery)
4729
+ //
4730
+ // const triggers = triggersQuery.rows.map((row) => row[0])
4731
+ //
4732
+ // const tablesQuery = await appDb.run(
4733
+ // sql.raw(
4734
+ // `SELECT name
4735
+ // FROM main.sqlite_master
4736
+ // WHERE type = 'table';`,
4737
+ // ),
4738
+ // )
4739
+ //
4740
+ // logger('[db/actors] [migrate] tablesQuery', tablesQuery)
4741
+ //
4742
+ // const tableNames = tablesQuery.rows.map((row) => row[0])
4743
+ // logger('[db/actors] [migrate] tableNames', tableNames)
4744
+ // for (const tableName of tableNames) {
4745
+ // const triggerName = `after_insert_${tableName}`
4746
+ // if (triggers.includes(triggerName)) {
4747
+ // continue
4748
+ // }
4749
+ // const createTriggerQuery = await appDb.run(
4750
+ // sql.raw(
4751
+ // `CREATE TRIGGER after_insert_${tableName}
4752
+ // AFTER INSERT ON ${tableName}
4753
+ // BEGIN
4754
+ // DELETE FROM temp_last_inserted_id;
4755
+ // INSERT INTO temp_last_inserted_id (id) VALUES (new.id);
4756
+ // END;`,
4757
+ // ),
4758
+ // )
4759
+ //
4760
+ // logger(
4761
+ // '[db/actors] [migrate] createTriggerQuery',
4762
+ // createTriggerQuery,
4763
+ // )
4764
+ // }
5318
4765
  });
5319
- _addModelsToDb().then((hasModelsInDb) => {
5320
- sendBack({ type: GLOBAL_ADDING_MODELS_TO_DB_SUCCESS });
5321
- for (const [modelName, model] of Object.entries(models$1)) {
5322
- const service = context[`${modelName}Service`];
5323
- service.send({ type: 'modelsFound' });
4766
+ _checkForFiles()
4767
+ .then(() => {
4768
+ if (journalExists) {
4769
+ return _migrate();
5324
4770
  }
5325
- eventEmitter.emit('syncDbWithEas');
5326
- return;
4771
+ })
4772
+ .then(() => {
4773
+ sendBack({ type: DB_MIGRATING_SUCCESS, dbName });
5327
4774
  });
5328
4775
  return () => { };
5329
4776
  });
5330
- const getSchemaForModel = fromCallback(({ sendBack, input: { context, event } }) => {
5331
- const { modelName } = event;
5332
- if (!modelName) {
5333
- console.warn('No modelName found');
5334
- return;
5335
- }
5336
- const { models } = context;
5337
- if (!models) {
5338
- console.warn('No models found');
5339
- return;
5340
- }
5341
- const model = Object.entries(models).find(([modelNameFromConfig]) => modelNameFromConfig === modelName);
5342
- if (!model) {
5343
- throw new Error(`Model ${modelName} not found`);
5344
- }
5345
- logger$a('[service/actor] [getSchemaForModel] model:', model);
5346
- sendBack({ type: 'schemaForModel', schema: model.schema });
5347
- return () => { };
5348
- });
5349
4777
 
5350
- const logger$9 = debug('app:services:db:machine');
4778
+ const logger$b = debug('app:services:db:machine');
5351
4779
  const { CHECKING_STATUS, VALIDATING, WAITING_FOR_FILES, CONNECTING_TO_DB, MIGRATING, } = DbState;
5352
4780
  const dbMachine = setup({
5353
4781
  types: {
@@ -5368,7 +4796,7 @@ const dbMachine = setup({
5368
4796
  [DB_WAITING_FOR_FILES_RECEIVED]: {
5369
4797
  actions: assign({
5370
4798
  hasFiles: ({ event }) => {
5371
- logger$9('[db/machine] DB_WAITING_FOR_FILES_RECEIVED event:', event);
4799
+ logger$b('[db/machine] DB_WAITING_FOR_FILES_RECEIVED event:', event);
5372
4800
  return true;
5373
4801
  },
5374
4802
  }),
@@ -5377,8 +4805,8 @@ const dbMachine = setup({
5377
4805
  target: `.${CHECKING_STATUS}`,
5378
4806
  actions: assign({
5379
4807
  hasFiles: ({ context, event }) => {
5380
- logger$9('[db/machine] updateHasFiles event:', event);
5381
- logger$9('[db/machine] updateHasFiles context:', context);
4808
+ logger$b('[db/machine] updateHasFiles event:', event);
4809
+ logger$b('[db/machine] updateHasFiles context:', context);
5382
4810
  return event.hasFiles;
5383
4811
  },
5384
4812
  }),
@@ -5571,13 +4999,13 @@ class SqliteConnectionManager {
5571
4999
  }
5572
5000
  }
5573
5001
 
5574
- const prepareDb = fromCallback(({ sendBack, input: { event, context } }) => {
5002
+ const prepareDb = fromCallback(({ sendBack }) => {
5575
5003
  let sqliteWasmClient;
5576
5004
  const _prepareDb = () => __awaiter(void 0, void 0, void 0, function* () {
5577
5005
  if (typeof window === 'undefined') {
5578
5006
  return;
5579
5007
  }
5580
- sqliteWasmClient = yield getSqlite();
5008
+ sqliteWasmClient = yield getSqliteWasmClient();
5581
5009
  });
5582
5010
  const interval = setInterval(() => {
5583
5011
  // TODO: Add a timeout
@@ -5599,7 +5027,7 @@ const prepareDb = fromCallback(({ sendBack, input: { event, context } }) => {
5599
5027
  };
5600
5028
  });
5601
5029
 
5602
- const logger$8 = debug('app:services:internal:helpers');
5030
+ const logger$a = debug('app:services:internal:helpers');
5603
5031
  /**
5604
5032
  * Recursively create directories if they don't exist.
5605
5033
  * @param {string} dirPath - The directory path to create.
@@ -5675,7 +5103,7 @@ const downloadFile = (url, localFilePath) => __awaiter(void 0, void 0, void 0, f
5675
5103
  if (JSON.stringify(error).includes('File exists')) {
5676
5104
  yield fs.promises.readFile(localFilePath, 'utf-8');
5677
5105
  }
5678
- logger$8(`[Error] Failed to download file from ${url}:`, error);
5106
+ logger$a(`[Error] Failed to download file from ${url}:`, error);
5679
5107
  }
5680
5108
  busy = false;
5681
5109
  });
@@ -5713,17 +5141,31 @@ const syncDbFiles = (_a) => __awaiter(void 0, [_a], void 0, function* ({ filePat
5713
5141
  const fileList = yield fetchDirectory(filePaths);
5714
5142
  yield fetchFilesRecursively(files, BROWSER_FS_TOP_DIR, fileList);
5715
5143
  yield confirmFilesExist(fileList);
5716
- logger$8('[syncDbFiles] Files synced!');
5144
+ logger$a('[syncDbFiles] Files synced!');
5717
5145
  });
5718
5146
 
5719
- const logger$7 = debug('app:files:download');
5147
+ const logger$9 = debug('app:files:download');
5720
5148
  const downloadAllFilesRequestHandler = (_a) => __awaiter(void 0, [_a], void 0, function* ({ endpoints, eventId, }) {
5721
5149
  yield syncDbFiles(endpoints);
5722
5150
  eventEmitter.emit('fs.downloadAll.success', { eventId });
5723
5151
  eventEmitter.emit('fs.downloadAllBinary.request', { endpoints });
5724
5152
  });
5725
5153
  const downloadAllFilesBinaryRequestHandler = () => __awaiter(void 0, void 0, void 0, function* () {
5726
- const addresses = yield getAddressesFromDb();
5154
+ let addresses;
5155
+ if (isAppDbReady()) {
5156
+ addresses = yield getAddressesFromDb();
5157
+ }
5158
+ if (!isAppDbReady()) {
5159
+ const globalService = getGlobalService();
5160
+ const internalService = globalService.getSnapshot().context.internalService;
5161
+ if (internalService) {
5162
+ yield waitFor(internalService, (snapshot) => snapshot.value === 'ready');
5163
+ addresses = yield getAddressesFromDb();
5164
+ }
5165
+ }
5166
+ if (!addresses || addresses.length === 0) {
5167
+ return;
5168
+ }
5727
5169
  const { filesMetadata } = yield queryClient.fetchQuery({
5728
5170
  queryKey: ['getFilesMetadata', ...addresses],
5729
5171
  queryFn: () => __awaiter(void 0, void 0, void 0, function* () {
@@ -5755,15 +5197,15 @@ const downloadAllFilesBinaryRequestHandler = () => __awaiter(void 0, void 0, voi
5755
5197
  if (!(yield fs.promises.exists('/files/images'))) {
5756
5198
  yield fs.promises.mkdir('/files/images', { recursive: true });
5757
5199
  }
5758
- const seedDb = getDb(DB_NAME_SEED);
5759
- if (!seedDb) {
5200
+ const appDb = getAppDb();
5201
+ if (!appDb) {
5760
5202
  console.warn('[fetchAll/actors] [fetchAllBinaryData] seedDb not available');
5761
5203
  return [];
5762
5204
  }
5763
5205
  for (const fileMetadata of filesMetadata) {
5764
5206
  const json = JSON.parse(fileMetadata.decodedDataJson);
5765
5207
  const transactionId = json[0].value.value;
5766
- const excludedTransactionsQuery = yield seedDb
5208
+ const excludedTransactionsQuery = yield appDb
5767
5209
  .select()
5768
5210
  .from(appState)
5769
5211
  .where(eq(appState.key, 'excludedTransactions'));
@@ -5786,9 +5228,9 @@ const downloadAllFilesBinaryRequestHandler = () => __awaiter(void 0, void 0, voi
5786
5228
  try {
5787
5229
  const res = yield fetch(`https://${ARWEAVE_HOST}/tx/${transactionId}/status`);
5788
5230
  if (res.status !== 200) {
5789
- logger$7(`[fetchAll/actors] [fetchAllBinaryData] error fetching transaction data for ${transactionId}`);
5231
+ logger$9(`[fetchAll/actors] [fetchAllBinaryData] error fetching transaction data for ${transactionId}`);
5790
5232
  excludedTransactions.add(transactionId);
5791
- yield writeAppState(seedDb, 'excludedTransactions', JSON.stringify(Array.from(excludedTransactions)));
5233
+ yield writeAppState(appDb, 'excludedTransactions', JSON.stringify(Array.from(excludedTransactions)));
5792
5234
  continue;
5793
5235
  }
5794
5236
  const dataString = yield arweave.transactions
@@ -5800,7 +5242,7 @@ const downloadAllFilesBinaryRequestHandler = () => __awaiter(void 0, void 0, voi
5800
5242
  console.error(`[fetchAll/actors] [fetchAllBinaryData] error fetching transaction data for ${transactionId}`, error);
5801
5243
  });
5802
5244
  if (!dataString) {
5803
- logger$7(`[fetchAll/actors] [fetchAllBinaryData] transaction ${transactionId} data not found`);
5245
+ logger$9(`[fetchAll/actors] [fetchAllBinaryData] transaction ${transactionId} data not found`);
5804
5246
  }
5805
5247
  let contentType = identifyString(dataString);
5806
5248
  if (contentType !== 'json' &&
@@ -5808,7 +5250,7 @@ const downloadAllFilesBinaryRequestHandler = () => __awaiter(void 0, void 0, voi
5808
5250
  contentType !== 'html') {
5809
5251
  const possibleImageType = getImageDataType(dataString);
5810
5252
  if (!possibleImageType) {
5811
- logger$7(`[fetchAll/actors] [fetchAllBinaryData] transaction ${transactionId} data not in expected format: ${possibleImageType}`);
5253
+ logger$9(`[fetchAll/actors] [fetchAllBinaryData] transaction ${transactionId} data not in expected format: ${possibleImageType}`);
5812
5254
  continue;
5813
5255
  }
5814
5256
  contentType = possibleImageType;
@@ -5871,7 +5313,7 @@ const downloadAllFilesBinaryRequestHandler = () => __awaiter(void 0, void 0, voi
5871
5313
  }
5872
5314
  }
5873
5315
  catch (error) {
5874
- logger$7(error);
5316
+ logger$9(error);
5875
5317
  }
5876
5318
  }
5877
5319
  });
@@ -5917,15 +5359,14 @@ const isFsInitialized = () => {
5917
5359
  return isInitialized;
5918
5360
  };
5919
5361
 
5920
- const logger$6 = debug('app:internal:actors:configureFs');
5362
+ const logger$8 = debug('app:internal:actors:configureFs');
5921
5363
  const configureFs = fromCallback(({ sendBack, input: { context } }) => {
5922
- const { endpoints, seedDbService, appDbService, sdkDbService } = context;
5923
- logger$6('[internal/actors] [configureFs] Configuring FS');
5924
- const services = [seedDbService, appDbService, sdkDbService];
5364
+ const { endpoints, appDbService } = context;
5365
+ logger$8('[internal/actors] [configureFs] Configuring FS');
5925
5366
  const _configureFs = () => __awaiter(void 0, void 0, void 0, function* () {
5926
- logger$6('[internal/actors] [configureFs] calling _configureFs');
5927
- logger$6('[internal/actors] [configureFs] areFsListenersReady:', areFsListenersReady());
5928
- logger$6('[internal/actors] [configureFs] isFsInitialized:', isFsInitialized());
5367
+ logger$8('[internal/actors] [configureFs] calling _configureFs');
5368
+ logger$8('[internal/actors] [configureFs] areFsListenersReady:', areFsListenersReady());
5369
+ logger$8('[internal/actors] [configureFs] isFsInitialized:', isFsInitialized());
5929
5370
  yield waitForEvent({
5930
5371
  req: {
5931
5372
  eventLabel: 'fs.downloadAll.request',
@@ -5935,30 +5376,27 @@ const configureFs = fromCallback(({ sendBack, input: { context } }) => {
5935
5376
  eventLabel: 'fs.downloadAll.success',
5936
5377
  },
5937
5378
  });
5938
- yield Promise.all(services.map((service) => __awaiter(void 0, void 0, void 0, function* () {
5939
- const { dirName } = service.getSnapshot().context;
5940
- const journalPath = `${BROWSER_FS_TOP_DIR}/${dirName}/db/meta/_journal.json`;
5941
- const journalExists = yield fs.promises.exists(journalPath);
5942
- if (journalExists) {
5943
- service.send({ type: DB_WAITING_FOR_FILES_RECEIVED });
5944
- }
5945
- // return new Promise<void>((resolve) => {
5946
- // const interval = setInterval(() => {
5947
- // journalExistsSync = fs.existsSync(journalPath)
5948
- // logger(
5949
- // '[internal/actors] [configureFs] journalExistsSync:',
5950
- // journalExistsSync,
5951
- // )
5952
- // if (journalExistsSync) {
5953
- // service.send({ type: DB_WAITING_FOR_FILES_RECEIVED })
5954
- // clearInterval(interval)
5955
- // resolve()
5956
- // }
5957
- // }, 200)
5958
- // })
5959
- })));
5960
- logger$6('[internal/actors] [configureFs] fs configured!');
5961
- });
5379
+ const journalPath = `${BROWSER_FS_TOP_DIR}/db/meta/_journal.json`;
5380
+ const journalExists = yield fs.promises.exists(journalPath);
5381
+ if (journalExists) {
5382
+ appDbService.send({ type: DB_WAITING_FOR_FILES_RECEIVED });
5383
+ }
5384
+ // return new Promise<void>((resolve) => {
5385
+ // const interval = setInterval(() => {
5386
+ // journalExistsSync = fs.existsSync(journalPath)
5387
+ // logger(
5388
+ // '[internal/actors] [configureFs] journalExistsSync:',
5389
+ // journalExistsSync,
5390
+ // )
5391
+ // if (journalExistsSync) {
5392
+ // service.send({ type: DB_WAITING_FOR_FILES_RECEIVED })
5393
+ // clearInterval(interval)
5394
+ // resolve()
5395
+ // }
5396
+ // }, 200)
5397
+ // })
5398
+ logger$8('[internal/actors] [configureFs] fs configured!');
5399
+ });
5962
5400
  // Some of our dependencies use fs sync functions, which don't work with
5963
5401
  // OPFS. ZenFS creates an async cache of all files so that the sync functions
5964
5402
  // work, but we have to wait for it to be built. Otherwise things like
@@ -5970,33 +5408,8 @@ const configureFs = fromCallback(({ sendBack, input: { context } }) => {
5970
5408
  return () => { };
5971
5409
  });
5972
5410
 
5973
- const loadSeedDb = fromCallback(({ sendBack, input: { context } }) => {
5974
- const { seedDbService } = context;
5975
- if (seedDbService.getSnapshot().value === 'ready') {
5976
- sendBack({ type: INTERNAL_LOADING_SEED_DB_SUCCESS });
5977
- return () => { };
5978
- }
5979
- let subscription;
5980
- const _loadSeedDb = () => __awaiter(void 0, void 0, void 0, function* () {
5981
- yield waitFor(seedDbService, (snapshot) => snapshot.value === 'ready');
5982
- subscription = seedDbService.subscribe({
5983
- next: (snapshot) => {
5984
- sendBack({ type: DB_ON_SNAPSHOT, dbName: DB_NAME_SEED, snapshot });
5985
- },
5986
- });
5987
- });
5988
- _loadSeedDb().then(() => {
5989
- sendBack({ type: INTERNAL_LOADING_SEED_DB_SUCCESS });
5990
- });
5991
- return () => {
5992
- if (subscription) {
5993
- subscription.unsubscribe();
5994
- }
5995
- };
5996
- });
5997
-
5998
- const logger$5 = debug('app:services:internal:actors:saveConfig');
5999
- const saveConfig = fromCallback(({ sendBack, receive, input: { context } }) => {
5411
+ const logger$7 = debug('app:services:internal:actors:saveConfig');
5412
+ const saveConfig = fromCallback(({ sendBack, input: { context } }) => {
6000
5413
  if (typeof window === 'undefined') {
6001
5414
  console.error('seedInitBrowser called from non-browser context');
6002
5415
  sendBack({
@@ -6010,16 +5423,16 @@ const saveConfig = fromCallback(({ sendBack, receive, input: { context } }) => {
6010
5423
  }
6011
5424
  const _saveConfig = () => __awaiter(void 0, void 0, void 0, function* () {
6012
5425
  // logger('[sdk] [internal/actors] starting _saveConfig')
6013
- const seedDb = getDb(DB_NAME_SEED);
6014
- if (!seedDb) {
6015
- throw new Error('Seed DB not found');
5426
+ const appDb = getAppDb();
5427
+ if (!appDb) {
5428
+ throw new Error('App DB not found');
6016
5429
  }
6017
5430
  const endpointsValueString = JSON.stringify(endpoints);
6018
5431
  const addressesValueString = JSON.stringify(addresses);
6019
5432
  // TODO: Figure out how to define on conflict with multiple rows added
6020
5433
  try {
6021
5434
  // logger('[sdk] [internal/actors] Saving endpoints to db')
6022
- yield seedDb
5435
+ yield appDb
6023
5436
  .insert(appState)
6024
5437
  .values({
6025
5438
  key: 'endpoints',
@@ -6033,7 +5446,7 @@ const saveConfig = fromCallback(({ sendBack, receive, input: { context } }) => {
6033
5446
  setWhere: sql `key = 'endpoints'`,
6034
5447
  });
6035
5448
  // logger('[sdk] [internal/actors] Saving addresses to db')
6036
- yield seedDb
5449
+ yield appDb
6037
5450
  .insert(appState)
6038
5451
  .values({
6039
5452
  key: 'addresses',
@@ -6046,20 +5459,20 @@ const saveConfig = fromCallback(({ sendBack, receive, input: { context } }) => {
6046
5459
  },
6047
5460
  setWhere: sql `key = 'addresses'`,
6048
5461
  });
6049
- logger$5('[sdk] [internal/actors] Should be done saving');
5462
+ logger$7('[sdk] [internal/actors] Should be done saving');
6050
5463
  }
6051
5464
  catch (error) {
6052
5465
  console.error('Error saving config:', error);
6053
5466
  }
6054
5467
  });
6055
5468
  _saveConfig().then(() => {
6056
- logger$5('[sdk] [internal/actors] Successfully saved config');
5469
+ logger$7('[sdk] [internal/actors] Successfully saved config');
6057
5470
  return sendBack({ type: INTERNAL_SAVING_CONFIG_SUCCESS });
6058
5471
  });
6059
5472
  return () => { };
6060
5473
  });
6061
5474
 
6062
- const logger$4 = debug('app:services:internal:actors:loadAppDb');
5475
+ const logger$6 = debug('app:services:internal:actors:loadAppDb');
6063
5476
  const loadAppDb = fromCallback(({ sendBack, input: { context } }) => {
6064
5477
  const { appDbService } = context;
6065
5478
  let subscription;
@@ -6080,42 +5493,7 @@ const loadAppDb = fromCallback(({ sendBack, input: { context } }) => {
6080
5493
  });
6081
5494
  _loadAppDb().then(() => {
6082
5495
  sendBack({ type: INTERNAL_LOADING_APP_DB_SUCCESS });
6083
- logger$4('[sdk] [internal/actors] Successfully loaded app DB');
6084
- });
6085
- return () => {
6086
- if (subscription) {
6087
- subscription.unsubscribe();
6088
- }
6089
- };
6090
- });
6091
-
6092
- const logger$3 = debug('app:internal:actors:loadSdkDb');
6093
- const loadSdkDb = fromCallback(({ sendBack, input: { context } }) => {
6094
- const { sdkDbService } = context;
6095
- logger$3('[sdk] [internal/actors] Loading SDK DB');
6096
- let subscription;
6097
- const _loadSdkDb = () => __awaiter(void 0, void 0, void 0, function* () {
6098
- return new Promise((resolve) => {
6099
- if (sdkDbService.getSnapshot().value === 'ready') {
6100
- return resolve();
6101
- }
6102
- subscription = sdkDbService.subscribe({
6103
- next: (snapshot) => {
6104
- if (snapshot.value === 'ready') {
6105
- return resolve();
6106
- }
6107
- sendBack({
6108
- type: DB_ON_SNAPSHOT,
6109
- dbName: DB_NAME_SDK_CONFIG,
6110
- snapshot,
6111
- });
6112
- },
6113
- });
6114
- });
6115
- });
6116
- _loadSdkDb().then(() => {
6117
- sendBack({ type: INTERNAL_LOADING_SDK_DB_SUCCESS });
6118
- logger$3('[sdk] [internal/actors] Successfully loaded SDK DB');
5496
+ logger$6('[sdk] [internal/actors] Successfully loaded app DB');
6119
5497
  });
6120
5498
  return () => {
6121
5499
  if (subscription) {
@@ -6124,11 +5502,11 @@ const loadSdkDb = fromCallback(({ sendBack, input: { context } }) => {
6124
5502
  };
6125
5503
  });
6126
5504
 
6127
- const logger$2 = debug('app:services:internal:machine');
5505
+ const logger$5 = debug('app:services:internal:machine');
6128
5506
  createBrowserInspector({
6129
5507
  autoStart: false,
6130
5508
  });
6131
- const { IDLE, VALIDATING_INPUT, SAVING_CONFIG, CONFIGURING_FS, LOADING_DBS, LOADING_SEED_DB, LOADING_APP_DB, LOADING_SDK_DB, } = InternalState;
5509
+ const { IDLE, VALIDATING_INPUT, SAVING_CONFIG, CONFIGURING_FS, LOADING_APP_DB, } = InternalState;
6132
5510
  // Create the state machine
6133
5511
  const internalMachine = setup({
6134
5512
  types: {
@@ -6139,10 +5517,8 @@ const internalMachine = setup({
6139
5517
  prepareDb,
6140
5518
  validateInput,
6141
5519
  configureFs,
6142
- loadSeedDb,
6143
- saveConfig,
6144
5520
  loadAppDb,
6145
- loadSdkDb,
5521
+ saveConfig,
6146
5522
  },
6147
5523
  }).createMachine({
6148
5524
  id: MachineIds.INTERNAL,
@@ -6157,27 +5533,10 @@ const internalMachine = setup({
6157
5533
  init: {
6158
5534
  target: VALIDATING_INPUT,
6159
5535
  actions: [
6160
- assign({
6161
- seedDbService: ({ spawn }) => spawn(dbMachine, {
6162
- input: {
6163
- dbName: DB_NAME_SEED,
6164
- dirName: DB_DIR_NAME_SEED,
6165
- },
6166
- }),
6167
- }),
6168
5536
  assign({
6169
5537
  appDbService: ({ spawn }) => spawn(dbMachine, {
6170
5538
  input: {
6171
5539
  dbName: DB_NAME_APP,
6172
- dirName: DB_DIR_NAME_APP,
6173
- },
6174
- }),
6175
- }),
6176
- assign({
6177
- sdkDbService: ({ spawn }) => spawn(dbMachine, {
6178
- input: {
6179
- dbName: DB_NAME_SDK_CONFIG,
6180
- dirName: DB_DIR_NAME_SDK,
6181
5540
  },
6182
5541
  }),
6183
5542
  }),
@@ -6223,7 +5582,7 @@ const internalMachine = setup({
6223
5582
  [CONFIGURING_FS]: {
6224
5583
  on: {
6225
5584
  [INTERNAL_CONFIGURING_FS_SUCCESS]: {
6226
- target: LOADING_SEED_DB,
5585
+ target: LOADING_APP_DB,
6227
5586
  actions: assign({ hasFiles: true }),
6228
5587
  },
6229
5588
  },
@@ -6237,32 +5596,24 @@ const internalMachine = setup({
6237
5596
  },
6238
5597
  tags: ['loading'],
6239
5598
  },
6240
- // We run this before the other DBs because it holds the config we need to
6241
- // rebuild. If we get interrupted after this then we don't have to start
6242
- // from scratch.
6243
- [LOADING_SEED_DB]: {
5599
+ [LOADING_APP_DB]: {
6244
5600
  on: {
6245
- [INTERNAL_LOADING_SEED_DB_SUCCESS]: SAVING_CONFIG,
6246
- // [DB_ON_SNAPSHOT]: {
6247
- // actions: emit(({ event: { snapshot } }) => {
6248
- // return { type: CHILD_SNAPSHOT, snapshot }
6249
- // }),
6250
- // },
5601
+ [INTERNAL_LOADING_APP_DB_SUCCESS]: {
5602
+ target: SAVING_CONFIG,
5603
+ actions: () => {
5604
+ logger$5('[sdk] [internal/index] App DB loaded!');
5605
+ },
5606
+ },
6251
5607
  },
6252
5608
  invoke: {
6253
- src: 'loadSeedDb',
5609
+ src: 'loadAppDb',
6254
5610
  input: ({ context, event }) => ({ context, event }),
6255
5611
  },
6256
- meta: {
6257
- displayText: 'Loading seed database',
6258
- percentComplete: 50,
6259
- },
6260
- tags: ['loading'],
6261
5612
  },
6262
5613
  // Save developer's config to DB
6263
5614
  [SAVING_CONFIG]: {
6264
5615
  on: {
6265
- [INTERNAL_SAVING_CONFIG_SUCCESS]: LOADING_DBS,
5616
+ [INTERNAL_SAVING_CONFIG_SUCCESS]: 'ready',
6266
5617
  },
6267
5618
  invoke: {
6268
5619
  src: 'saveConfig',
@@ -6274,77 +5625,9 @@ const internalMachine = setup({
6274
5625
  },
6275
5626
  tags: ['loading'],
6276
5627
  },
6277
- // The DBs can be loaded in parallel since they are independent of each other
6278
- [LOADING_DBS]: {
6279
- type: 'parallel',
6280
- states: {
6281
- [LOADING_APP_DB]: {
6282
- initial: 'loading',
6283
- states: {
6284
- loading: {
6285
- on: {
6286
- [INTERNAL_LOADING_APP_DB_SUCCESS]: {
6287
- target: 'appDbLoaded',
6288
- actions: () => {
6289
- logger$2('[sdk] [internal/index] App DB loaded!');
6290
- },
6291
- },
6292
- },
6293
- invoke: {
6294
- src: 'loadAppDb',
6295
- input: ({ context, event }) => ({ context, event }),
6296
- },
6297
- },
6298
- appDbLoaded: {
6299
- type: 'final',
6300
- entry: () => {
6301
- logger$2('[sdk] [internal/index] Entered appDbLoaded!');
6302
- },
6303
- },
6304
- },
6305
- },
6306
- [LOADING_SDK_DB]: {
6307
- initial: 'loading',
6308
- states: {
6309
- loading: {
6310
- on: {
6311
- [INTERNAL_LOADING_SDK_DB_SUCCESS]: {
6312
- target: 'sdkConfigDbLoaded',
6313
- actions: () => {
6314
- logger$2('[sdk] [internal/index] SDK Config DB loaded!');
6315
- },
6316
- },
6317
- },
6318
- invoke: {
6319
- src: 'loadSdkDb',
6320
- input: ({ context, event }) => ({ context, event }),
6321
- },
6322
- },
6323
- sdkConfigDbLoaded: {
6324
- type: 'final',
6325
- entry: () => {
6326
- logger$2('[sdk] [internal/index] Entered sdkConfigDbLoaded!');
6327
- },
6328
- },
6329
- },
6330
- },
6331
- },
6332
- onDone: {
6333
- target: 'ready',
6334
- actions: () => {
6335
- logger$2('[sdk] [internal/index] All DBs loaded! Should be headed to ready');
6336
- eventEmitter.emit('allDbsLoaded');
6337
- },
6338
- },
6339
- meta: {
6340
- displayText: 'Loading databases',
6341
- percentComplete: 90,
6342
- },
6343
- tags: ['loading'],
6344
- },
6345
5628
  ready: {
6346
5629
  entry: () => {
6347
- logger$2('[sdk] [internal/index] Ready!');
5630
+ logger$5('[sdk] [internal/index] Ready!');
6348
5631
  },
6349
5632
  meta: {
6350
5633
  displayText: "Crossing the t's ...",
@@ -6359,7 +5642,7 @@ const internalMachine = setup({
6359
5642
  },
6360
5643
  },
6361
5644
  entry: () => {
6362
- logger$2('[sdk] [internal/index] Error!');
5645
+ logger$5('[sdk] [internal/index] Error!');
6363
5646
  },
6364
5647
  meta: {
6365
5648
  displayText: 'Whoops! Something went wrong.',
@@ -6369,53 +5652,39 @@ const internalMachine = setup({
6369
5652
  },
6370
5653
  },
6371
5654
  });
6372
-
6373
- const logger$1 = debug('app:global:actors');
6374
- const initialize = fromCallback(({ sendBack, input: { event, context } }) => {
6375
- const { internalService, models, endpoints } = context;
6376
- const { addresses } = event;
6377
- let environment = 'browser';
6378
- if (isNode()) {
6379
- environment = 'node';
6380
- }
6381
- if (isReactNative()) {
6382
- environment = 'react-native';
6383
- }
6384
- let internalSubscription;
6385
- if (environment === 'browser' && models) {
6386
- const _initFileSystem = () => __awaiter(void 0, void 0, void 0, function* () {
6387
- return;
6388
- // return new Promise((resolve) => {
6389
- // })
6390
- });
6391
- const _initInternal = () => __awaiter(void 0, void 0, void 0, function* () {
6392
- return new Promise((resolve) => {
6393
- internalSubscription = internalService.subscribe((snapshot) => {
6394
- logger$1('[sdk] [internal] snapshot', snapshot);
6395
- if (snapshot.value === 'ready') {
6396
- resolve();
6397
- }
6398
- });
6399
- internalService.send({ type: 'init', endpoints, addresses });
6400
- });
6401
- });
6402
- _initFileSystem().then(() => {
6403
- logger$1('[global/actors] File system initialized');
6404
- });
6405
- _initInternal().then(() => {
6406
- logger$1('[global/actors] Internal initialized');
6407
- sendBack({ type: GLOBAL_INITIALIZING_INTERNAL_SERVICE_READY });
6408
- internalSubscription === null || internalSubscription === void 0 ? void 0 : internalSubscription.unsubscribe();
6409
- });
6410
- // _initEas().then(() => {
6411
- // logger('EAS initialized')
6412
- // })
6413
- }
6414
- sendBack({ type: GLOBAL_INITIALIZING_SEND_CONFIG, environment });
6415
- return () => {
6416
- internalSubscription === null || internalSubscription === void 0 ? void 0 : internalSubscription.unsubscribe();
6417
- };
6418
- });
5655
+ // const internalService = createActor(internalMachine, {
5656
+ // input: {},
5657
+ // inspect: (inspEvent) => {
5658
+ // if (inspEvent.type === '@xstate.snapshot') {
5659
+ // if (
5660
+ // inspEvent.event &&
5661
+ // inspEvent.event.snapshot &&
5662
+ // inspEvent.event.snapshot.value
5663
+ // ) {
5664
+ // logger(
5665
+ // `[internalService] ${inspEvent.event.snapshot.value}`,
5666
+ // inspEvent,
5667
+ // )
5668
+ // return
5669
+ // }
5670
+ //
5671
+ // if (inspEvent.snapshot && inspEvent.snapshot.value) {
5672
+ // logger(`[internalService] ${inspEvent.snapshot.value}`, inspEvent)
5673
+ // return
5674
+ // }
5675
+ //
5676
+ // // logger(`[internalService] Uncaught event`, inspEvent)
5677
+ // }
5678
+ // },
5679
+ // })
5680
+ // internalService.subscribe((snapshot) => {
5681
+ // globalService.send({ type: INTERNAL_SERVICE_SNAPSHOT, snapshot })
5682
+ // })
5683
+ //
5684
+ // internalService.on(CHILD_SNAPSHOT, (emitted) => {
5685
+ // globalService.send({ ...emitted })
5686
+ // })
5687
+ // internalService.start()
6419
5688
 
6420
5689
  const { UNINITIALIZED, INITIALIZING, INITIALIZED, GETTING_SEED_CLASS, GETTING_SCHEMA_FOR_MODEL, ADDING_MODELS_TO_DB, } = GlobalState;
6421
5690
  createBrowserInspector({
@@ -6457,14 +5726,6 @@ const globalMachine = setup({
6457
5726
  },
6458
5727
  });
6459
5728
  },
6460
- // fileSystemService: ({ spawn, event }) => {
6461
- // return spawn(fileSystemMachine, {
6462
- // systemId: MachineIds.FILE_SYSTEM,
6463
- // input: {
6464
- // addresses: event.addresses,
6465
- // },
6466
- // })
6467
- // },
6468
5729
  }),
6469
5730
  assign(({ event, spawn }) => {
6470
5731
  const allItemsServices = {};
@@ -6548,11 +5809,11 @@ const globalMachine = setup({
6548
5809
  (_a) => __awaiter(void 0, [_a], void 0, function* ({ context }) {
6549
5810
  let SeedClass;
6550
5811
  if (context.environment === 'node') {
6551
- const { SeedNode } = yield import('./seed-BJPS_-pY.js');
5812
+ const { SeedNode } = yield import('./seed-Dpo8KWqz.js');
6552
5813
  SeedClass = SeedNode;
6553
5814
  }
6554
5815
  else {
6555
- const { SeedBrowser } = yield import('./seed-CjMH4SeR.js');
5816
+ const { SeedBrowser } = yield import('./seed-BDG7IW-o.js');
6556
5817
  SeedClass = SeedBrowser;
6557
5818
  }
6558
5819
  return SeedClass;
@@ -6646,6 +5907,444 @@ const globalService = createActor(globalMachine, {
6646
5907
  globalService.start();
6647
5908
  const getGlobalService = () => globalService;
6648
5909
 
5910
+ const logger$4 = debug('app:react:db');
5911
+ const useDbsAreReady = () => {
5912
+ const [dbsAreReady, setDbsAreReady] = useState(false);
5913
+ const update = useCallback(() => {
5914
+ if (dbsAreReady) {
5915
+ return;
5916
+ }
5917
+ setDbsAreReady(true);
5918
+ }, []);
5919
+ useEffect(() => {
5920
+ let globalSubscription;
5921
+ let internalSubscription;
5922
+ const _waitForDbs = () => __awaiter(void 0, void 0, void 0, function* () {
5923
+ const globalService = getGlobalService();
5924
+ const internalService = globalService.getSnapshot().context.internalService;
5925
+ if (!internalService) {
5926
+ logger$4('[useDbsAreReady] [useEffect] no internalService');
5927
+ globalSubscription = globalService.subscribe(({ context }) => {
5928
+ if (!internalSubscription && context && context.internalService) {
5929
+ globalSubscription === null || globalSubscription === void 0 ? void 0 : globalSubscription.unsubscribe();
5930
+ internalSubscription = context.internalService.subscribe((snapshot) => {
5931
+ if (snapshot.value === 'ready') {
5932
+ update();
5933
+ internalSubscription === null || internalSubscription === void 0 ? void 0 : internalSubscription.unsubscribe();
5934
+ }
5935
+ });
5936
+ }
5937
+ });
5938
+ return;
5939
+ }
5940
+ const currentState = internalService.getSnapshot().value;
5941
+ if (currentState === 'ready') {
5942
+ update();
5943
+ return;
5944
+ }
5945
+ internalSubscription = internalService.subscribe((snapshot) => {
5946
+ if (snapshot.value === 'ready') {
5947
+ update();
5948
+ internalSubscription === null || internalSubscription === void 0 ? void 0 : internalSubscription.unsubscribe();
5949
+ }
5950
+ });
5951
+ });
5952
+ _waitForDbs();
5953
+ return () => {
5954
+ if (globalSubscription) {
5955
+ globalSubscription.unsubscribe();
5956
+ }
5957
+ if (internalSubscription) {
5958
+ internalSubscription.unsubscribe();
5959
+ }
5960
+ };
5961
+ }, []);
5962
+ return {
5963
+ dbsAreReady,
5964
+ };
5965
+ };
5966
+
5967
+ const logger$3 = debug('app:react:services');
5968
+ const finalStrings = ['idle', 'ready', 'done', 'success'];
5969
+ const getServiceName = (service) => {
5970
+ let name = 'actor';
5971
+ if (service && service.uniqueKey) {
5972
+ name = service.uniqueKey;
5973
+ }
5974
+ if (service && !service.uniqueKey && service.logic && service.logic.config) {
5975
+ name = getServiceUniqueKey(service);
5976
+ }
5977
+ return name;
5978
+ };
5979
+ const getServiceValue = (service) => {
5980
+ let value;
5981
+ if (service && service.getSnapshot() && service.getSnapshot().value) {
5982
+ value = service.getSnapshot().value;
5983
+ }
5984
+ if (getServiceName(service) === 'global') {
5985
+ if (value &&
5986
+ typeof value === 'object' &&
5987
+ Object.keys(value).length > 0 &&
5988
+ Object.keys(value)[0] === 'initialized') {
5989
+ value = 'ready';
5990
+ }
5991
+ }
5992
+ if (value && typeof value === 'object') {
5993
+ value = JSON.stringify(value);
5994
+ }
5995
+ return value;
5996
+ };
5997
+ const getServiceUniqueKey = (service) => {
5998
+ if (!service || !service.logic || !service.logic.config) {
5999
+ return;
6000
+ }
6001
+ const config = service.logic.config;
6002
+ if (!config.id) {
6003
+ return;
6004
+ }
6005
+ let uniqueKey = config.id;
6006
+ if (config.id.includes('@seedSdk/')) {
6007
+ uniqueKey = config.id.match(/^.*@seedSdk\/(\w+)[\.\w]*/)[1];
6008
+ }
6009
+ let snapshot;
6010
+ try {
6011
+ snapshot = service.getSnapshot();
6012
+ }
6013
+ catch (error) {
6014
+ logger$3('Error:', error);
6015
+ return uniqueKey;
6016
+ }
6017
+ if (snapshot) {
6018
+ const context = snapshot.context;
6019
+ if (context && context.dbName) {
6020
+ uniqueKey = context.dbName;
6021
+ }
6022
+ if (context && context.modelNamePlural) {
6023
+ uniqueKey = context.modelNamePlural;
6024
+ }
6025
+ if (context && context.modelName) {
6026
+ uniqueKey = pluralize(context.modelName.toLowerCase());
6027
+ }
6028
+ }
6029
+ return uniqueKey;
6030
+ };
6031
+ const useServices = () => {
6032
+ const [actors, setActors] = useState([]);
6033
+ const [percentComplete, setPercentComplete] = useState(5);
6034
+ const actorsMap = new Map();
6035
+ useEffect(() => {
6036
+ const globalServiceListener = (event) => {
6037
+ if (event && event.type === 'init') {
6038
+ return;
6039
+ }
6040
+ if (event.actorRef &&
6041
+ event.actorRef.logic &&
6042
+ event.actorRef.logic.config) {
6043
+ const uniqueKey = getServiceUniqueKey(event.actorRef);
6044
+ if (!uniqueKey) {
6045
+ return;
6046
+ }
6047
+ event.actorRef.uniqueKey = uniqueKey;
6048
+ actorsMap.set(uniqueKey, event.actorRef);
6049
+ let actorsArray = Array.from(actorsMap.values());
6050
+ actorsArray = orderBy(actorsArray, (a) => a.logic.config.id, ['asc']);
6051
+ setActors(produce(actors, (draft) => {
6052
+ return actorsArray;
6053
+ }));
6054
+ }
6055
+ };
6056
+ eventEmitter.addListener('inspect.globalService', globalServiceListener);
6057
+ return () => {
6058
+ eventEmitter.removeListener('inspect.globalService', globalServiceListener);
6059
+ };
6060
+ }, []);
6061
+ useEffect(() => {
6062
+ const globalService = actors.find((actor) => getServiceName(actor) === 'global');
6063
+ const internalService = actors.find((actor) => getServiceName(actor) === 'internal');
6064
+ if (!globalService || !internalService) {
6065
+ return;
6066
+ }
6067
+ if (getServiceValue(globalService) === 'ready' &&
6068
+ getServiceValue(internalService) === 'ready') {
6069
+ const denominator = actors.length;
6070
+ const finishedActors = actors.filter((actor) => {
6071
+ const value = getServiceValue(actor);
6072
+ return finalStrings.includes(value);
6073
+ });
6074
+ const numerator = finishedActors.length;
6075
+ const percentComplete = (numerator / denominator) * 100;
6076
+ setPercentComplete(percentComplete);
6077
+ }
6078
+ }, [actors]);
6079
+ return {
6080
+ services: actors,
6081
+ percentComplete,
6082
+ };
6083
+ };
6084
+ const useGlobalServiceStatus = () => {
6085
+ const globalService = getGlobalService();
6086
+ const status = useSelector(globalService, (snapshot) => {
6087
+ return snapshot.value;
6088
+ });
6089
+ const internalStatus = useSelector(globalService.getSnapshot().context.internalService, (snapshot) => {
6090
+ if (!snapshot) {
6091
+ return;
6092
+ }
6093
+ return snapshot.value;
6094
+ });
6095
+ useSelector(globalService, (snapshot) => {
6096
+ return snapshot.context.internalService;
6097
+ });
6098
+ return {
6099
+ status,
6100
+ internalStatus,
6101
+ };
6102
+ };
6103
+
6104
+ const logger$2 = debug('app:react:item');
6105
+ const useItem = ({ modelName, seedLocalId, seedUid }) => {
6106
+ const [item, setItem] = useImmer(undefined);
6107
+ const [itemSubscription, setItemSubscription] = useState();
6108
+ const { status, internalStatus } = useGlobalServiceStatus();
6109
+ const isReadingDb = useRef(false);
6110
+ const itemStatus = useSelector(item === null || item === void 0 ? void 0 : item.getService(), (snapshot) => snapshot === null || snapshot === void 0 ? void 0 : snapshot.value);
6111
+ const updateItem = useCallback((newItem) => {
6112
+ setItem(() => newItem);
6113
+ }, []);
6114
+ const readFromDb = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
6115
+ if (isReadingDb.current ||
6116
+ internalStatus !== 'ready' ||
6117
+ (!seedUid && !seedLocalId)) {
6118
+ return;
6119
+ }
6120
+ isReadingDb.current = true;
6121
+ const foundItem = yield Item.find({
6122
+ modelName,
6123
+ seedLocalId,
6124
+ seedUid,
6125
+ });
6126
+ if (!foundItem) {
6127
+ logger$2('[useItem] [getItemFromDb] no item found', modelName, seedLocalId);
6128
+ return;
6129
+ }
6130
+ updateItem(foundItem);
6131
+ isReadingDb.current = false;
6132
+ }), [internalStatus]);
6133
+ useEffect(() => {
6134
+ if (internalStatus === 'ready') {
6135
+ readFromDb();
6136
+ }
6137
+ }, [internalStatus, status]);
6138
+ useEffect(() => {
6139
+ if (item && !itemSubscription) {
6140
+ const subscription = item.subscribe((_) => __awaiter(void 0, void 0, void 0, function* () {
6141
+ const newItem = yield Item.find({ modelName, seedLocalId, seedUid });
6142
+ if (!newItem) {
6143
+ logger$2('[useItem] [itemSubscription] no item found', modelName, seedLocalId);
6144
+ return;
6145
+ }
6146
+ setItem(() => newItem);
6147
+ }));
6148
+ setItemSubscription(subscription);
6149
+ }
6150
+ return () => {
6151
+ itemSubscription === null || itemSubscription === void 0 ? void 0 : itemSubscription.unsubscribe();
6152
+ };
6153
+ }, [item, itemSubscription]);
6154
+ useEffect(() => {
6155
+ const seedId = seedUid || seedLocalId;
6156
+ eventEmitter.addListener(`item.${modelName}.${seedId}.update`, readFromDb);
6157
+ return () => {
6158
+ eventEmitter.removeListener(`item.${modelName}.${seedId}.update`, readFromDb);
6159
+ };
6160
+ }, []);
6161
+ return {
6162
+ item,
6163
+ itemStatus,
6164
+ };
6165
+ };
6166
+ const useItems = ({ modelName, options }) => {
6167
+ const [items, setItems] = useImmer([]);
6168
+ const [isReadingDb, setIsReadingDb] = useState(false);
6169
+ const [isInitialized, setIsInitialized] = useState(false);
6170
+ const { dbsAreReady } = useDbsAreReady();
6171
+ const modelNameRef = useRef(modelName);
6172
+ const readFromDb = useCallback((event) => __awaiter(void 0, void 0, void 0, function* () {
6173
+ if (!event ||
6174
+ !event.modelName ||
6175
+ event.modelName !== modelNameRef.current ||
6176
+ isReadingDb) {
6177
+ return;
6178
+ }
6179
+ setIsReadingDb(true);
6180
+ const allItems = yield Item.all(modelNameRef.current);
6181
+ setItems(() => allItems);
6182
+ setIsReadingDb(false);
6183
+ }), [modelName]);
6184
+ useEffect(() => {
6185
+ if (dbsAreReady && !isInitialized) {
6186
+ const _fetchItems = () => __awaiter(void 0, void 0, void 0, function* () {
6187
+ yield readFromDb({ modelName });
6188
+ setIsInitialized(true);
6189
+ });
6190
+ _fetchItems();
6191
+ }
6192
+ }, [dbsAreReady, isInitialized]);
6193
+ useEffect(() => {
6194
+ eventEmitter.addListener('item.requestAll', readFromDb);
6195
+ return () => {
6196
+ eventEmitter.removeListener('item.requestAll');
6197
+ };
6198
+ }, []);
6199
+ return {
6200
+ items: orderBy(items, [
6201
+ (item) => item.lastVersionPublishedAt ||
6202
+ item.attestationCreatedAt ||
6203
+ item.createdAt,
6204
+ ], ['desc']).slice(0, 10),
6205
+ isReadingDb,
6206
+ isInitialized,
6207
+ };
6208
+ };
6209
+ const useItemIsReady = () => {
6210
+ const [itemListenersReady, setItemListenersReady] = useState(false);
6211
+ const itemEventListenersHandler = useCallback((_) => {
6212
+ setItemListenersReady(true);
6213
+ }, []);
6214
+ useEffect(() => {
6215
+ const areReady = getAreItemEventHandlersReady();
6216
+ if (areReady) {
6217
+ itemEventListenersHandler(true);
6218
+ }
6219
+ eventEmitter.addListener('item.events.setupAllItemsEventHandlers', itemEventListenersHandler);
6220
+ return () => {
6221
+ eventEmitter.removeListener('item.events.setupAllItemsEventHandlers');
6222
+ };
6223
+ }, []);
6224
+ return {
6225
+ isReady: itemListenersReady,
6226
+ };
6227
+ };
6228
+ const useCreateItem = (modelName) => {
6229
+ const [isCreatingItem, setIsCreatingItem] = useState(false);
6230
+ const { isReady } = useItemIsReady();
6231
+ const createItem = useCallback((itemData) => __awaiter(void 0, void 0, void 0, function* () {
6232
+ if (!isReady) {
6233
+ console.error(`[useCreateItem] [createItem] called before listeners are ready`, itemData);
6234
+ return;
6235
+ }
6236
+ if (isCreatingItem) {
6237
+ // TODO: should we setup a queue for this?
6238
+ console.error(`[useCreateItem] [createItem] already creating item`, itemData);
6239
+ return;
6240
+ }
6241
+ setIsCreatingItem(true);
6242
+ const { seedLocalId } = yield createNewItem(Object.assign({ modelName }, itemData));
6243
+ yield Item.find({ modelName, seedLocalId });
6244
+ eventEmitter.emit('item.requestAll', { modelName });
6245
+ setIsCreatingItem(false);
6246
+ }), [isCreatingItem, isReady]);
6247
+ return {
6248
+ createItem,
6249
+ isCreatingItem,
6250
+ };
6251
+ };
6252
+ const useDeleteItem = () => {
6253
+ const [isDeletingItem, setIsDeletingItem] = useState(false);
6254
+ const destroy = useCallback((item) => __awaiter(void 0, void 0, void 0, function* () {
6255
+ if (!item) {
6256
+ return;
6257
+ }
6258
+ setIsDeletingItem(true);
6259
+ const { modelName } = item.getService().getSnapshot().context;
6260
+ yield deleteItem({ seedLocalId: item.seedLocalId });
6261
+ eventEmitter.emit('item.requestAll', { modelName });
6262
+ setIsDeletingItem(false);
6263
+ }), [isDeletingItem]);
6264
+ useEffect(() => { }, []);
6265
+ return {
6266
+ deleteItem: destroy,
6267
+ isDeletingItem,
6268
+ };
6269
+ };
6270
+
6271
+ const logger$1 = debug('app:react:property');
6272
+ const useItemProperty = (propertyName, seedLocalId) => {
6273
+ const [property, setProperty] = useImmer(undefined);
6274
+ const [isReadingFromDb, setIsReadingFromDb] = useState(false);
6275
+ const [isInitialized, setIsInitialized] = useState(false);
6276
+ const { dbsAreReady } = useDbsAreReady();
6277
+ const value = useSelector(property === null || property === void 0 ? void 0 : property.getService(), (snapshot) => {
6278
+ if (!snapshot || !snapshot.context) {
6279
+ return;
6280
+ }
6281
+ return snapshot.context.renderValue || snapshot.context.propertyValue;
6282
+ });
6283
+ const status = useSelector(property === null || property === void 0 ? void 0 : property.getService(), (snapshot) => snapshot === null || snapshot === void 0 ? void 0 : snapshot.value);
6284
+ useEffect(() => {
6285
+ if (dbsAreReady && property && property.value !== value) {
6286
+ readFromDb();
6287
+ }
6288
+ }, [dbsAreReady, property, value]);
6289
+ const readFromDb = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
6290
+ if (!dbsAreReady && isReadingFromDb) {
6291
+ return;
6292
+ }
6293
+ setIsReadingFromDb(true);
6294
+ const foundProperty = yield ItemProperty.find({ propertyName, seedLocalId });
6295
+ setIsReadingFromDb(false);
6296
+ if (!foundProperty) {
6297
+ logger$1(`[useItemPropertyTest] [readFromDb] no property found for Item.${seedLocalId}.${propertyName}`);
6298
+ return;
6299
+ }
6300
+ setProperty(() => foundProperty);
6301
+ setIsInitialized(true);
6302
+ }), [dbsAreReady, isReadingFromDb]);
6303
+ useEffect(() => {
6304
+ readFromDb();
6305
+ }, []);
6306
+ // TODO: How can we force a re-render when the property is updated?
6307
+ // Right now, the value will trigger an update because it's using a selector
6308
+ // and a change is pushed to the hook listener.
6309
+ return {
6310
+ property,
6311
+ isInitialized,
6312
+ isReadingFromDb,
6313
+ value,
6314
+ status,
6315
+ };
6316
+ };
6317
+ const useItemProperties = (item) => {
6318
+ const [propertyObj, setPropertyObj] = useImmer({});
6319
+ useState(false);
6320
+ const updatePropertyObj = useCallback((event) => {
6321
+ if (!item) {
6322
+ console.error('[XXXXXX] [updatePropertyObj] no item when expected');
6323
+ return;
6324
+ }
6325
+ const { propertyName, propertyValue } = event;
6326
+ if (!propertyName) {
6327
+ return;
6328
+ }
6329
+ setPropertyObj((draft) => {
6330
+ draft[propertyName] = propertyValue;
6331
+ });
6332
+ }, [item]);
6333
+ useEffect(() => {
6334
+ if (!item) {
6335
+ return;
6336
+ }
6337
+ const eventKey = `item.${item.seedLocalId}.property.update`;
6338
+ eventEmitter.addListener(eventKey, updatePropertyObj);
6339
+ return () => {
6340
+ eventEmitter.removeListener(eventKey, updatePropertyObj);
6341
+ };
6342
+ }, [item]);
6343
+ return {
6344
+ properties: propertyObj,
6345
+ };
6346
+ };
6347
+
6649
6348
  const logger = debug('app:services:events');
6650
6349
  const handleServiceSaveState = (event) => {
6651
6350
  const { state, serviceId } = event;
@@ -6656,5 +6355,326 @@ const setupServicesEventHandlers = () => {
6656
6355
  eventEmitter.addListener('service.saveState.request', handleServiceSaveState);
6657
6356
  };
6658
6357
 
6659
- 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 };
6660
- //# sourceMappingURL=events-CRCYmF7M.js.map
6358
+ const propertySaveHandler = (event) => __awaiter(void 0, void 0, void 0, function* () {
6359
+ const { localId, seedLocalId, propertyName, propertyValue, seedUid, modelType, refSeedType, } = event;
6360
+ const appDb = getAppDb();
6361
+ if (!appDb) {
6362
+ throw new Error('initialize: appDb is undefined');
6363
+ }
6364
+ if (!seedUid && !seedLocalId) {
6365
+ throw new Error('seedUid and seedLocalId are both undefined');
6366
+ }
6367
+ if (seedUid && !seedLocalId) {
6368
+ throw new Error("seedUid is defined but seedLocalId is not. This shouldn't happen since seedLocalIds are saved to the db at the same time as seedUid.");
6369
+ }
6370
+ let recordToUpdate;
6371
+ let recordToUseAsSource;
6372
+ let localRecordQuery;
6373
+ const selectStatement = `SELECT local_id, uid, property_value, seed_local_id, seed_uid, created_at, attestation_created_at, schema_uid, model_type, version_local_id, version_uid, eas_data_type, ref_value_type, ref_schema_uid, ref_seed_type, ref_resolved_value, ref_resolved_display_value, attestation_raw`;
6374
+ if (localId) {
6375
+ localRecordQuery = yield appDb.run(sql.raw(`${selectStatement}
6376
+ FROM metadata
6377
+ WHERE local_id = '${localId}'
6378
+ ORDER BY created_at DESC;
6379
+ `));
6380
+ }
6381
+ if (!localId && !seedLocalId && seedUid) {
6382
+ localRecordQuery = yield appDb.run(sql.raw(`${selectStatement}
6383
+ FROM metadata
6384
+ WHERE seed_uid = '${seedUid}'
6385
+ AND property_name = '${propertyName}'
6386
+ ORDER BY created_at DESC;
6387
+ `));
6388
+ }
6389
+ if (!localId && seedLocalId && !seedUid) {
6390
+ localRecordQuery = yield appDb.run(sql.raw(`${selectStatement}
6391
+ FROM metadata
6392
+ WHERE seed_local_id = '${seedLocalId}'
6393
+ AND property_name = '${propertyName}'
6394
+ ORDER BY created_at DESC;
6395
+ `));
6396
+ }
6397
+ if (!localId && seedLocalId && seedUid) {
6398
+ localRecordQuery = yield appDb.run(sql.raw(`${selectStatement}
6399
+ FROM metadata
6400
+ WHERE seed_local_id = '${seedLocalId}'
6401
+ AND seed_uid = '${seedUid}'
6402
+ AND property_name = '${propertyName}'
6403
+ ORDER BY created_at DESC;
6404
+ `));
6405
+ }
6406
+ if (localRecordQuery &&
6407
+ localRecordQuery.rows &&
6408
+ localRecordQuery.rows.length > 0) {
6409
+ const propertyValueFromDb = localRecordQuery.rows[0][2];
6410
+ if (propertyValueFromDb === propertyValue) {
6411
+ // This should be a no-op since the property is already properly saved to the local db.
6412
+ return;
6413
+ }
6414
+ const localIdFromDb = localRecordQuery.rows[0][0];
6415
+ const uidFromDb = localRecordQuery.rows[0][1];
6416
+ const shouldUpdate = !!localId || !uidFromDb;
6417
+ const shouldCreateNew = !!localIdFromDb && !!uidFromDb;
6418
+ if (shouldUpdate) {
6419
+ recordToUpdate = {
6420
+ localId: localId || localIdFromDb,
6421
+ };
6422
+ }
6423
+ if (shouldCreateNew) {
6424
+ recordToUseAsSource = {
6425
+ localId: localIdFromDb,
6426
+ uid: uidFromDb,
6427
+ propertyValue: localRecordQuery.rows[0][2],
6428
+ seedLocalId: localRecordQuery.rows[0][3],
6429
+ seedUid: localRecordQuery.rows[0][4],
6430
+ createdAt: localRecordQuery.rows[0][5],
6431
+ attestationCreatedAt: localRecordQuery.rows[0][6],
6432
+ schemaUid: localRecordQuery.rows[0][7],
6433
+ modelType: localRecordQuery.rows[0][8],
6434
+ versionLocalId: localRecordQuery.rows[0][9],
6435
+ versionUid: localRecordQuery.rows[0][10],
6436
+ easDataType: localRecordQuery.rows[0][11],
6437
+ refValueType: localRecordQuery.rows[0][12],
6438
+ refSchemaUid: localRecordQuery.rows[0][13],
6439
+ refSeedType: localRecordQuery.rows[0][14],
6440
+ refResolvedValue: localRecordQuery.rows[0][15],
6441
+ refResolvedDisplayValue: localRecordQuery.rows[0][16],
6442
+ attestationRaw: localRecordQuery.rows[0][17],
6443
+ };
6444
+ }
6445
+ }
6446
+ if (recordToUpdate) {
6447
+ yield appDb.run(sql.raw(`UPDATE metadata
6448
+ SET property_value = '${propertyValue}'
6449
+ WHERE local_id = '${recordToUpdate.localId}';
6450
+ `));
6451
+ }
6452
+ if (recordToUseAsSource) {
6453
+ yield createNewMetadataFromExistingRecord({
6454
+ existingRecord: recordToUseAsSource,
6455
+ propertyName,
6456
+ propertyValue,
6457
+ });
6458
+ }
6459
+ if (!recordToUpdate && !recordToUseAsSource) {
6460
+ const newLocalId = generateId();
6461
+ yield appDb.run(sql.raw(`INSERT INTO metadata (local_id, seed_local_id, seed_uid, property_name, property_value, created_at, updated_at,
6462
+ model_type, ref_seed_type)
6463
+ VALUES ('${newLocalId}', '${seedLocalId}', '${seedUid}', '${propertyName}', '${propertyValue}',
6464
+ ${Date.now()}, ${Date.now()}, '${modelType.toLowerCase()}',
6465
+ ${refSeedType ? `'${refSeedType.toLowerCase()}'` : 'NULL'});
6466
+ `));
6467
+ }
6468
+ eventEmitter.emit(`property.${seedLocalId}.${propertyName}.save.response`, {
6469
+ status: 'success',
6470
+ });
6471
+ });
6472
+
6473
+ const propertySaveRelationHandler = (event) => __awaiter(void 0, void 0, void 0, function* () {
6474
+ const { localId, seedLocalId, propertyName, propertyValue, seedUid, modelType, refSeedType, } = event;
6475
+ const appDb = getAppDb();
6476
+ if (!appDb) {
6477
+ throw new Error('initialize: appDb is undefined');
6478
+ }
6479
+ if (!seedUid && !seedLocalId) {
6480
+ throw new Error('seedUid and seedLocalId are both undefined');
6481
+ }
6482
+ if (seedUid && !seedLocalId) {
6483
+ throw new Error("seedUid is defined but seedLocalId is not. This shouldn't happen since seedLocalIds are saved to the db at the same time as seedUid.");
6484
+ }
6485
+ let recordToUpdate;
6486
+ let recordToUseAsSource;
6487
+ let localRecordQuery;
6488
+ const selectStatement = `SELECT local_id, uid, property_value, seed_local_id, seed_uid, created_at, attestation_created_at, schema_uid, model_type, version_local_id, version_uid, eas_data_type, ref_value_type, ref_schema_uid, ref_seed_type, ref_resolved_value, ref_resolved_display_value, attestation_raw`;
6489
+ if (localId) {
6490
+ localRecordQuery = yield appDb.run(sql.raw(`${selectStatement}
6491
+ FROM metadata
6492
+ WHERE local_id = '${localId}'
6493
+ ORDER BY created_at DESC;
6494
+ `));
6495
+ }
6496
+ if (!localId && !seedLocalId && seedUid) {
6497
+ localRecordQuery = yield appDb.run(sql.raw(`${selectStatement}
6498
+ FROM metadata
6499
+ WHERE seed_uid = '${seedUid}'
6500
+ AND property_name = '${propertyName}'
6501
+ ORDER BY created_at DESC;
6502
+ `));
6503
+ }
6504
+ if (!localId && seedLocalId && !seedUid) {
6505
+ localRecordQuery = yield appDb.run(sql.raw(`${selectStatement}
6506
+ FROM metadata
6507
+ WHERE seed_local_id = '${seedLocalId}'
6508
+ AND property_name = '${propertyName}'
6509
+ ORDER BY created_at DESC;
6510
+ `));
6511
+ }
6512
+ if (!localId && seedLocalId && seedUid) {
6513
+ localRecordQuery = yield appDb.run(sql.raw(`${selectStatement}
6514
+ FROM metadata
6515
+ WHERE seed_local_id = '${seedLocalId}'
6516
+ AND seed_uid = '${seedUid}'
6517
+ AND property_name = '${propertyName}'
6518
+ ORDER BY created_at DESC;
6519
+ `));
6520
+ }
6521
+ if (localRecordQuery &&
6522
+ localRecordQuery.rows &&
6523
+ localRecordQuery.rows.length > 0) {
6524
+ const propertyValueFromDb = localRecordQuery.rows[0][2];
6525
+ if (propertyValueFromDb === propertyValue) {
6526
+ // This should be a no-op since the property is already properly saved to the local db.
6527
+ return;
6528
+ }
6529
+ const localIdFromDb = localRecordQuery.rows[0][0];
6530
+ const uidFromDb = localRecordQuery.rows[0][1];
6531
+ const shouldUpdate = !!localId || !uidFromDb;
6532
+ const shouldCreateNew = !!localIdFromDb && !!uidFromDb;
6533
+ if (shouldUpdate) {
6534
+ recordToUpdate = {
6535
+ localId: localId || localIdFromDb,
6536
+ };
6537
+ }
6538
+ if (shouldCreateNew) {
6539
+ recordToUseAsSource = {
6540
+ localId: localIdFromDb,
6541
+ uid: uidFromDb,
6542
+ propertyValue: localRecordQuery.rows[0][2],
6543
+ seedLocalId: localRecordQuery.rows[0][3],
6544
+ seedUid: localRecordQuery.rows[0][4],
6545
+ createdAt: localRecordQuery.rows[0][5],
6546
+ attestationCreatedAt: localRecordQuery.rows[0][6],
6547
+ schemaUid: localRecordQuery.rows[0][7],
6548
+ modelType: localRecordQuery.rows[0][8],
6549
+ versionLocalId: localRecordQuery.rows[0][9],
6550
+ versionUid: localRecordQuery.rows[0][10],
6551
+ easDataType: localRecordQuery.rows[0][11],
6552
+ refValueType: localRecordQuery.rows[0][12],
6553
+ refSchemaUid: localRecordQuery.rows[0][13],
6554
+ refSeedType: localRecordQuery.rows[0][14],
6555
+ refResolvedValue: localRecordQuery.rows[0][15],
6556
+ refResolvedDisplayValue: localRecordQuery.rows[0][16],
6557
+ attestationRaw: localRecordQuery.rows[0][17],
6558
+ };
6559
+ }
6560
+ }
6561
+ if (recordToUpdate) {
6562
+ yield appDb.run(sql.raw(`UPDATE metadata
6563
+ SET property_value = '${propertyValue}'
6564
+ WHERE local_id = '${recordToUpdate.localId}';
6565
+ `));
6566
+ }
6567
+ if (recordToUseAsSource) {
6568
+ yield createNewMetadataFromExistingRecord({
6569
+ existingRecord: recordToUseAsSource,
6570
+ propertyName,
6571
+ propertyValue,
6572
+ });
6573
+ }
6574
+ if (!recordToUpdate && !recordToUseAsSource) {
6575
+ const newSeedLocalId = generateId();
6576
+ yield appDb.run(sql.raw(`INSERT INTO seeds (local_id, type, created_at, updated_at)
6577
+ VALUES ('${newSeedLocalId}', '${refSeedType.toLowerCase()}', ${Date.now()}, ${Date.now()});
6578
+ `));
6579
+ const newVersionLocalId = generateId();
6580
+ yield appDb.run(sql.raw(`INSERT INTO versions (local_id, seed_local_id, created_at, updated_at)
6581
+ VALUES ('${newVersionLocalId}', '${newSeedLocalId}', ${Date.now()}, ${Date.now()});
6582
+ `));
6583
+ const newPropertyLocalId = generateId();
6584
+ yield appDb.run(sql.raw(`INSERT INTO metadata (local_id, seed_local_id, version_local_id, property_name, property_value,
6585
+ ref_resolved_value, created_at,
6586
+ updated_at,
6587
+ model_type)
6588
+ VALUES ('${newPropertyLocalId}', '${seedLocalId}', '${newVersionLocalId}', '${propertyName}',
6589
+ '${newSeedLocalId}', '${propertyValue}',
6590
+ ${Date.now()}, ${Date.now()}, '${modelType.toLowerCase()}');
6591
+ `));
6592
+ }
6593
+ eventEmitter.emit(`property.${seedLocalId}.${propertyName}.saveRelation.response`, {
6594
+ status: 'success',
6595
+ });
6596
+ });
6597
+
6598
+ const setupPropertyEventHandlers = () => {
6599
+ eventEmitter.addListener('property.request', (event) => {
6600
+ console.log('property.request', event);
6601
+ });
6602
+ eventEmitter.addListener('property.save.request', propertySaveHandler);
6603
+ eventEmitter.addListener('property.saveRelation.request', propertySaveRelationHandler);
6604
+ };
6605
+
6606
+ const client = {
6607
+ init: ({ config, addresses }) => {
6608
+ const { endpoints, models } = config;
6609
+ for (const [key, value] of Object.entries(models)) {
6610
+ setModel(key, value);
6611
+ }
6612
+ setupFsListeners();
6613
+ setupAllItemsEventHandlers();
6614
+ setupServicesEventHandlers();
6615
+ setupPropertyEventHandlers();
6616
+ if (areFsListenersReady()) {
6617
+ eventEmitter.emit('fs.init');
6618
+ }
6619
+ if (!areFsListenersReady()) {
6620
+ console.error('fs listeners not ready during init');
6621
+ }
6622
+ globalService.send({ type: 'init', endpoints, models, addresses });
6623
+ import('./seed.schema.config-CCYo8gj-.js').then(({ models }) => {
6624
+ for (const [key, value] of Object.entries(models)) {
6625
+ setModel(key, value);
6626
+ }
6627
+ });
6628
+ },
6629
+ subscribe: (callback) => {
6630
+ callback({
6631
+ type: '@xstate.snapshot',
6632
+ actorRef: globalService,
6633
+ snapshot: globalService.getSnapshot(),
6634
+ });
6635
+ eventEmitter.addListener('globalService', callback);
6636
+ return {
6637
+ unsubscribe: () => {
6638
+ eventEmitter.removeListener('globalService', callback);
6639
+ },
6640
+ };
6641
+ },
6642
+ on: (outerEvent, callback) => {
6643
+ eventEmitter.addListener(outerEvent, callback);
6644
+ return {
6645
+ unsubscribe: () => {
6646
+ eventEmitter.removeListener(outerEvent, callback);
6647
+ },
6648
+ };
6649
+ },
6650
+ getSeedClass: () => __awaiter(void 0, void 0, void 0, function* () {
6651
+ return new Promise((resolve) => {
6652
+ const subscription = globalService.subscribe((snapshot) => {
6653
+ if (snapshot.status === 'done') {
6654
+ resolve(snapshot.output);
6655
+ }
6656
+ });
6657
+ globalService.send({ type: 'getSeed' });
6658
+ subscription.unsubscribe();
6659
+ });
6660
+ }),
6661
+ getModel: (modelName) => {
6662
+ return getModel(modelName);
6663
+ },
6664
+ getModels: () => {
6665
+ return getModels();
6666
+ },
6667
+ getModelNames: () => {
6668
+ return getModelNames();
6669
+ },
6670
+ };
6671
+
6672
+ var _a;
6673
+ enableMapSet();
6674
+ let withSeed;
6675
+ if (isNode()) {
6676
+ withSeed = (_a = initSeedSync()) === null || _a === void 0 ? void 0 : _a.withSeed;
6677
+ }
6678
+
6679
+ export { CHILD_SNAPSHOT as C, GET_SCHEMAS as G, Item as I, Json as J, List as L, Model as M, Property as P, Relation as R, Text as T, GET_SEEDS as a, GET_SEED_IDS as b, GET_STORAGE_TRANSACTION_ID as c, GET_VERSIONS as d, GET_PROPERTIES as e, GET_ALL_PROPERTIES_FOR_ALL_VERSIONS as f, itemMachineAll as g, internalMachine as h, itemMachineSingle as i, isNode as j, isBrowser as k, isReactNative as l, ImageSrc as m, ItemProperty as n, useItem as o, useItemProperties as p, useCreateItem as q, useItemProperty as r, useDeleteItem as s, useServices as t, useItems as u, getGlobalService as v, withSeed as w, client as x, getCorrectId as y };
6680
+ //# sourceMappingURL=index-D3JMvAuO.js.map