@seedprotocol/sdk 0.2.54 → 0.3.1

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 (243) hide show
  1. package/dist/{ArweaveClient-D5iJisYr.js → ArweaveClient-C0g0es2v.js} +2 -2
  2. package/dist/{ArweaveClient-D5iJisYr.js.map → ArweaveClient-C0g0es2v.js.map} +1 -1
  3. package/dist/{ArweaveClient-HEIIuOfB.js → ArweaveClient-CzkBgiZY.js} +2 -2
  4. package/dist/{ArweaveClient-HEIIuOfB.js.map → ArweaveClient-CzkBgiZY.js.map} +1 -1
  5. package/dist/{Db-jMth8Y2g.js → Db-C4oog-0n.js} +4 -3
  6. package/dist/{Db-jMth8Y2g.js.map → Db-C4oog-0n.js.map} +1 -1
  7. package/dist/Db-VPouegkr.js +82 -0
  8. package/dist/Db-VPouegkr.js.map +1 -0
  9. package/dist/EasClient-B9a3NsTi.js +10 -0
  10. package/dist/EasClient-B9a3NsTi.js.map +1 -0
  11. package/dist/{EasClient-D3wKgt0o.js → EasClient-DQ93i2ci.js} +2 -2
  12. package/dist/{EasClient-D3wKgt0o.js.map → EasClient-DQ93i2ci.js.map} +1 -1
  13. package/dist/{FileManager-4mWYO3Mt.js → FileManager-_ErxVuwb.js} +9 -5
  14. package/dist/FileManager-_ErxVuwb.js.map +1 -0
  15. package/dist/{Item-CbgjLSUx.js → Item-D9HFPxsK.js} +4 -3
  16. package/dist/{Item-CbgjLSUx.js.map → Item-D9HFPxsK.js.map} +1 -1
  17. package/dist/{ItemProperty-DduurIcl.js → ItemProperty-BdtvKrEy.js} +4 -3
  18. package/dist/{ItemProperty-DduurIcl.js.map → ItemProperty-BdtvKrEy.js.map} +1 -1
  19. package/dist/QueryClient-Bmnv_moN.js +22 -0
  20. package/dist/QueryClient-Bmnv_moN.js.map +1 -0
  21. package/dist/{QueryClient-CBOP3OoU.js → QueryClient-hzOtFe99.js} +3 -2
  22. package/dist/{QueryClient-CBOP3OoU.js.map → QueryClient-hzOtFe99.js.map} +1 -1
  23. package/dist/bin.js +30 -34
  24. package/dist/bin.js.map +1 -1
  25. package/dist/{constants-CIDbABDz.js → constants-Bhl5dZpN.js} +9 -4
  26. package/dist/constants-Bhl5dZpN.js.map +1 -0
  27. package/dist/db/configs/node.app.db.config.ts +27 -0
  28. package/dist/{index-DQNTvzqi.js → index-BAtjd9W-.js} +4 -3
  29. package/dist/index-BAtjd9W-.js.map +1 -0
  30. package/dist/{index-CTZqN6WI.js → index-BSR5hv7Q.js} +305 -268
  31. package/dist/index-BSR5hv7Q.js.map +1 -0
  32. package/dist/main.js +3 -2
  33. package/dist/main.js.map +1 -1
  34. package/dist/node/db/node.app.db.config.ts +1 -1
  35. package/dist/{seed.schema.config-B-4U2RRq.js → seed.schema.config-BxJYabim.js} +10 -9
  36. package/dist/seed.schema.config-BxJYabim.js.map +1 -0
  37. package/dist/src/AppStateSchema.ts +10 -0
  38. package/dist/src/ArweaveClient.ts +13 -0
  39. package/dist/src/Attestation.ts +21 -0
  40. package/dist/src/BaseArweaveClient.ts +13 -0
  41. package/dist/src/BaseClientManager.ts +35 -0
  42. package/dist/src/BaseDb.ts +35 -0
  43. package/dist/src/BaseEasClient.ts +14 -0
  44. package/dist/src/BaseFileManager.ts +60 -0
  45. package/dist/src/BaseItem.ts +413 -0
  46. package/dist/src/BaseItemProperty.ts +416 -0
  47. package/dist/src/BaseQueryClient.ts +13 -0
  48. package/dist/src/ClientManager.ts +63 -0
  49. package/dist/src/ConfigSchema.ts +15 -0
  50. package/dist/src/Db.ts +82 -0
  51. package/dist/src/EasClient.ts +13 -0
  52. package/dist/src/FileDownloader.ts +63 -0
  53. package/dist/src/FileManager.ts +59 -0
  54. package/dist/src/IDb.ts +7 -0
  55. package/dist/src/IEasClient.ts +2 -0
  56. package/dist/src/IItem.ts +26 -0
  57. package/dist/src/IItemProperty.ts +28 -0
  58. package/dist/src/IQueryClient.ts +11 -0
  59. package/dist/src/ImageResizer.ts +81 -0
  60. package/dist/src/Item.ts +12 -0
  61. package/dist/src/ItemProperty.ts +9 -0
  62. package/dist/src/MetadataSchema.ts +28 -0
  63. package/dist/src/ModelSchema.ts +46 -0
  64. package/dist/src/ModelUidSchema.ts +16 -0
  65. package/dist/src/PropertyUidSchema.ts +16 -0
  66. package/dist/src/QueryClient.ts +26 -0
  67. package/dist/src/Schema.ts +17 -0
  68. package/dist/src/SeedProtocolSdk.d.ts +19 -0
  69. package/dist/src/SeedSchema.ts +29 -0
  70. package/dist/src/VersionSchema.ts +16 -0
  71. package/dist/src/actors.ts +295 -0
  72. package/dist/src/addModelsToDb.ts +152 -0
  73. package/dist/src/allItems.ts +31 -0
  74. package/dist/src/analyzeInput.ts +144 -0
  75. package/dist/src/browser.app.db.config.ts +27 -0
  76. package/dist/src/browser.ts +30 -0
  77. package/dist/src/checkStatus.ts +57 -0
  78. package/dist/src/clientManagerMachine.ts +59 -0
  79. package/dist/src/configureFs.ts +98 -0
  80. package/dist/src/connectToDb.ts +41 -0
  81. package/dist/src/connectionManager.ts +67 -0
  82. package/dist/src/constants.ts +125 -0
  83. package/dist/src/content-hash.ts +30 -0
  84. package/dist/src/create.ts +39 -0
  85. package/dist/src/createMetadata.ts +77 -0
  86. package/dist/src/createNewItem.ts +61 -0
  87. package/dist/src/createPublishAttempt.ts +16 -0
  88. package/dist/src/createSeed.ts +31 -0
  89. package/dist/src/createSeeds.ts +24 -0
  90. package/dist/src/createVersion.ts +33 -0
  91. package/dist/src/dbMachine.ts +182 -0
  92. package/dist/src/deleteItem.ts +19 -0
  93. package/dist/src/download.ts +208 -0
  94. package/dist/src/drizzle.ts +78 -0
  95. package/dist/src/eas.ts +40 -0
  96. package/dist/src/environment.ts +35 -0
  97. package/dist/src/eventBus.ts +5 -0
  98. package/dist/src/events.ts +14 -0
  99. package/dist/src/fetchDataFromEas.ts +94 -0
  100. package/dist/src/fetchDbData.ts +19 -0
  101. package/dist/src/fetchRelatedItems.ts +184 -0
  102. package/dist/src/fetchSeeds.ts +45 -0
  103. package/dist/src/fetchVersions.ts +49 -0
  104. package/dist/src/files.ts +81 -0
  105. package/dist/src/filesDownload.ts +326 -0
  106. package/dist/src/fragment-masking.ts +87 -0
  107. package/dist/src/getExistingItem.ts +60 -0
  108. package/dist/src/getItem.ts +32 -0
  109. package/dist/src/getItemData.ts +99 -0
  110. package/dist/src/getItemProperties.ts +56 -0
  111. package/dist/src/getItemProperty.ts +34 -0
  112. package/dist/src/getItems.ts +70 -0
  113. package/dist/src/getMetadata.ts +40 -0
  114. package/dist/src/getModelSchemas.ts +89 -0
  115. package/dist/src/getPropertyData.ts +50 -0
  116. package/dist/src/getPublishPayload.ts +355 -0
  117. package/dist/src/getPublishUploads.ts +207 -0
  118. package/dist/src/getRelationValueData.ts +27 -0
  119. package/dist/src/getSchemaForItemProperty.ts +68 -0
  120. package/dist/src/getSchemaForModel.ts +42 -0
  121. package/dist/src/getSchemaUidForModel.ts +32 -0
  122. package/dist/src/getSeedData.ts +34 -0
  123. package/dist/src/getSegmentedItemProperties.ts +65 -0
  124. package/dist/src/getStorageTransactionIdForSeedUid.ts +38 -0
  125. package/dist/src/getVersionData.ts +46 -0
  126. package/dist/src/getVersionsForVersionUids.ts +39 -0
  127. package/dist/src/globalMachine.ts +280 -0
  128. package/dist/src/gql.ts +118 -0
  129. package/dist/src/graphql.ts +3209 -0
  130. package/dist/src/helpers.ts +273 -0
  131. package/dist/src/hydrateExistingItem.ts +137 -0
  132. package/dist/src/hydrateFromDb.ts +270 -0
  133. package/dist/src/hydrateNewItem.ts +34 -0
  134. package/dist/src/imageResize.ts +507 -0
  135. package/dist/src/index.d.ts +5 -0
  136. package/dist/src/index.ts +4 -0
  137. package/dist/src/initialize.ts +124 -0
  138. package/dist/src/internalMachine.ts +241 -0
  139. package/dist/src/itemMachineAll.ts +157 -0
  140. package/dist/src/itemMachineSingle.ts +158 -0
  141. package/dist/src/loadAppDb.ts +44 -0
  142. package/dist/src/machines.ts +66 -0
  143. package/dist/src/metadataLatest.ts +34 -0
  144. package/dist/src/migrate.ts +57 -0
  145. package/dist/src/model.ts +72 -0
  146. package/dist/src/modelClass.ts +19 -0
  147. package/dist/src/node.app.db.config.ts +41 -0
  148. package/dist/src/prepareDb.ts +29 -0
  149. package/dist/src/preparePublishRequestData.ts +81 -0
  150. package/dist/src/processItems.ts +74 -0
  151. package/dist/src/property.ts +156 -0
  152. package/dist/src/propertyMachine.ts +202 -0
  153. package/dist/src/publish.ts +28 -0
  154. package/dist/src/publishMachine.ts +77 -0
  155. package/dist/src/queries.ts +13 -0
  156. package/dist/src/recoverDeletedItem.ts +14 -0
  157. package/dist/src/reload.ts +33 -0
  158. package/dist/src/request.ts +45 -0
  159. package/dist/src/requestAll.ts +157 -0
  160. package/dist/src/resolveRelatedValue.ts +367 -0
  161. package/dist/src/resolveRemoteStorage.ts +88 -0
  162. package/dist/src/saveAppState.ts +50 -0
  163. package/dist/src/saveConfig.ts +106 -0
  164. package/dist/src/saveDataToDb.ts +145 -0
  165. package/dist/src/saveImageSrc.ts +242 -0
  166. package/dist/src/saveItemStorage.ts +156 -0
  167. package/dist/src/saveMetadata.ts +18 -0
  168. package/dist/src/savePublishService.ts +30 -0
  169. package/dist/src/saveRelation.ts +112 -0
  170. package/dist/src/seed.schema.config.ts +25 -0
  171. package/dist/src/seed.ts +10 -0
  172. package/dist/src/seedProtocol.ts +17 -0
  173. package/dist/src/services.ts +365 -0
  174. package/dist/src/setAddresses.ts +16 -0
  175. package/dist/src/sqlWasmClient.ts +88 -0
  176. package/dist/src/syncDbWithEas.ts +628 -0
  177. package/dist/src/trash.ts +29 -0
  178. package/dist/src/ts-to-proto.ts +101 -0
  179. package/dist/src/types.ts +12 -0
  180. package/dist/src/updateItemPropertyValue.ts +243 -0
  181. package/dist/src/updateMachineContext.ts +21 -0
  182. package/dist/src/updateMetadata.ts +59 -0
  183. package/dist/src/upload.ts +86 -0
  184. package/dist/src/validate.ts +45 -0
  185. package/dist/src/validateInput.ts +43 -0
  186. package/dist/src/validateItemData.ts +20 -0
  187. package/dist/src/versionData.ts +24 -0
  188. package/dist/src/waitForDb.ts +25 -0
  189. package/dist/src/waitForFiles.ts +41 -0
  190. package/dist/src/wasm.d.ts +8300 -0
  191. package/dist/types/scripts/bin.d.ts.map +1 -1
  192. package/dist/types/src/browser/helpers/EasClient.d.ts +1 -3
  193. package/dist/types/src/browser/helpers/EasClient.d.ts.map +1 -1
  194. package/dist/types/src/browser/helpers/FileManager.d.ts +2 -1
  195. package/dist/types/src/browser/helpers/FileManager.d.ts.map +1 -1
  196. package/dist/types/src/client/ClientManager.d.ts +44 -0
  197. package/dist/types/src/client/ClientManager.d.ts.map +1 -0
  198. package/dist/types/src/client/actions/setAddresses.d.ts.map +1 -1
  199. package/dist/types/src/client/actors/initialize.d.ts.map +1 -1
  200. package/dist/types/src/client/actors/saveAppState.d.ts.map +1 -1
  201. package/dist/types/src/client/clientManagerMachine.d.ts.map +1 -1
  202. package/dist/types/src/client/index.d.ts +2 -40
  203. package/dist/types/src/client/index.d.ts.map +1 -1
  204. package/dist/types/src/db/configs/node.app.db.config.d.ts +3 -0
  205. package/dist/types/src/db/configs/node.app.db.config.d.ts.map +1 -0
  206. package/dist/types/src/events/files/download.d.ts.map +1 -1
  207. package/dist/types/src/helpers/EasClient/BaseEasClient.d.ts.map +1 -1
  208. package/dist/types/src/helpers/FileManager/BaseFileManager.d.ts +1 -0
  209. package/dist/types/src/helpers/FileManager/BaseFileManager.d.ts.map +1 -1
  210. package/dist/types/src/helpers/constants.d.ts +1 -0
  211. package/dist/types/src/helpers/constants.d.ts.map +1 -1
  212. package/dist/types/src/interfaces/IQueryClient.d.ts +7 -1
  213. package/dist/types/src/interfaces/IQueryClient.d.ts.map +1 -1
  214. package/dist/types/src/node/db/Db.d.ts +5 -10
  215. package/dist/types/src/node/db/Db.d.ts.map +1 -1
  216. package/dist/types/src/node/helpers/FileManager.d.ts +2 -1
  217. package/dist/types/src/node/helpers/FileManager.d.ts.map +1 -1
  218. package/dist/types/src/node/helpers/QueryClient.d.ts +2 -4
  219. package/dist/types/src/node/helpers/QueryClient.d.ts.map +1 -1
  220. package/dist/types/src/services/allItems/actors/fetchSeeds.d.ts.map +1 -1
  221. package/dist/types/src/services/db/actors/checkStatus.d.ts.map +1 -1
  222. package/dist/types/src/services/db/actors/migrate.d.ts.map +1 -1
  223. package/dist/types/src/services/db/actors/waitForFiles.d.ts.map +1 -1
  224. package/dist/types/src/services/internal/actors/configureFs.d.ts.map +1 -1
  225. package/dist/types/src/services/internal/actors/loadAppDb.d.ts.map +1 -1
  226. package/dist/types/src/services/internal/actors/saveConfig.d.ts.map +1 -1
  227. package/dist/types/src/services/internal/actors/waitForFiles.d.ts.map +1 -1
  228. package/dist/types/src/services/internal/internalMachine.d.ts.map +1 -1
  229. package/package.json +10 -10
  230. package/dist/Db-DK9wSNIH.js +0 -120
  231. package/dist/Db-DK9wSNIH.js.map +0 -1
  232. package/dist/EasClient-jqkT2ZBt.js +0 -13
  233. package/dist/EasClient-jqkT2ZBt.js.map +0 -1
  234. package/dist/FileManager-4mWYO3Mt.js.map +0 -1
  235. package/dist/QueryClient-bKb3SB0W.js +0 -23
  236. package/dist/QueryClient-bKb3SB0W.js.map +0 -1
  237. package/dist/constants-CIDbABDz.js.map +0 -1
  238. package/dist/index-CTZqN6WI.js.map +0 -1
  239. package/dist/index-DQNTvzqi.js.map +0 -1
  240. package/dist/package.json +0 -189
  241. package/dist/seed.schema.config-B-4U2RRq.js.map +0 -1
  242. package/dist/types/src/client.d.ts +0 -18
  243. package/dist/types/src/client.d.ts.map +0 -1
@@ -0,0 +1,57 @@
1
+ import { EventObject, fromCallback } from 'xstate'
2
+ import { DbServiceContext, FromCallbackInput } from '@/types'
3
+ import {
4
+ BROWSER_FS_TOP_DIR,
5
+ DB_CHECK_STATUS_EXISTS,
6
+ DB_CHECK_STATUS_UPDATE_PATHS,
7
+ } from '@/services/internal/constants'
8
+ import debug from 'debug'
9
+ import { isBrowser } from '@/helpers/environment'
10
+
11
+ const logger = debug('app:services:db:actors:checkStatus')
12
+
13
+ export const checkStatus = fromCallback<
14
+ EventObject,
15
+ FromCallbackInput<DbServiceContext>
16
+ >(({ sendBack, input: { context, event, } }) => {
17
+ const { dbName, } = context
18
+ let { pathToDir, } = context
19
+
20
+
21
+ logger('[db/actors] checkStatus context', context)
22
+ console.log('[db/actors] checkStatus context', context)
23
+ console.log('[db/actors] checkStatus event', event)
24
+ if (isBrowser()) {
25
+ pathToDir = BROWSER_FS_TOP_DIR
26
+ }
27
+ const pathToDbDir = `${pathToDir}/db`
28
+ const pathToDb = `${pathToDbDir}/${dbName}.sqlite3`
29
+
30
+ sendBack({
31
+ type: DB_CHECK_STATUS_UPDATE_PATHS,
32
+ pathToDb,
33
+ pathToDir,
34
+ pathToDbDir,
35
+ })
36
+
37
+ const _checkStatus = async (): Promise<void> => {
38
+ // logger('[db/actors] _checkStatus pathToDb', pathToDb)
39
+ // const exists = await fs.promises.exists(pathToJournal)
40
+ // if (exists) {
41
+ // sendBack({
42
+ // type: DB_CHECK_STATUS_EXISTS,
43
+ // })
44
+ // return
45
+ // }
46
+ //
47
+ // return new Promise((resolve) => {
48
+ // sendBack({ type: DB_CHECK_STATUS_DOES_NOT_EXIST })
49
+ //
50
+ // })
51
+ }
52
+
53
+ _checkStatus().then(() => {
54
+ sendBack({ type: DB_CHECK_STATUS_EXISTS })
55
+ return
56
+ })
57
+ })
@@ -0,0 +1,59 @@
1
+ import { ClientManagerContext } from "@/types"
2
+ import { assign, setup } from "xstate"
3
+ import { initialize } from "./actors/initialize"
4
+ import { setAddresses } from "./actions/setAddresses"
5
+
6
+ export const clientManagerMachine = setup({
7
+ types: {
8
+ context: {} as ClientManagerContext,
9
+ input: {} as ClientManagerContext | undefined,
10
+ },
11
+ actions: {
12
+ setAddresses,
13
+ },
14
+ actors: {
15
+ initialize,
16
+ },
17
+ }).createMachine({
18
+ id: 'clientManager',
19
+ initial: 'uninitialized',
20
+ context: ({ input }) => input as ClientManagerContext,
21
+ states: {
22
+ uninitialized: {
23
+ on: {
24
+ init: {
25
+ target: 'initializing',
26
+ },
27
+ },
28
+ },
29
+ initializing: {
30
+ on: {
31
+ initialized: {
32
+ target: 'idle',
33
+ },
34
+ },
35
+ invoke: {
36
+ src: 'initialize',
37
+ input: ({ event, context }) => ({ event, context }),
38
+ },
39
+ },
40
+ idle: {
41
+ entry: assign({
42
+ isInitialized: true,
43
+ }),
44
+ on: {
45
+ saveAppStateSuccess: {
46
+ actions: assign(({ event }) => {
47
+ const { key, value } = event
48
+ return {
49
+ isSaving: false
50
+ }
51
+ }),
52
+ },
53
+ setAddresses: {
54
+ actions: ['setAddresses'],
55
+ },
56
+ },
57
+ },
58
+ },
59
+ })
@@ -0,0 +1,98 @@
1
+ import { EventObject, fromCallback } from 'xstate'
2
+ import { areFsListenersReady, isFsInitialized } from '@/events/files'
3
+ import { waitForEvent } from '@/events'
4
+ import {
5
+ BROWSER_FS_TOP_DIR,
6
+ DB_WAITING_FOR_FILES_RECEIVED,
7
+ INTERNAL_CONFIGURING_FS_SUCCESS,
8
+ } from '@/services/internal/constants'
9
+ import fs from '@zenfs/core'
10
+ import debug from 'debug'
11
+ import { FromCallbackInput, InternalMachineContext } from '@/types'
12
+ import { isBrowser } from '@/helpers/environment'
13
+
14
+ const logger = debug('app:internal:actors:configureFs')
15
+
16
+ export const configureFs = fromCallback<
17
+ EventObject,
18
+ FromCallbackInput<InternalMachineContext>
19
+ >(({ sendBack, input: { context } }) => {
20
+ const { endpoints, appDbService, filesDir, } = context
21
+
22
+ logger('[internal/actors] [configureFs] Configuring FS')
23
+
24
+ const _configureFs = async (): Promise<boolean> => {
25
+ logger('[internal/actors] [configureFs] calling _configureFs')
26
+
27
+ logger(
28
+ '[internal/actors] [configureFs] areFsListenersReady:',
29
+ areFsListenersReady(),
30
+ )
31
+ logger(
32
+ '[internal/actors] [configureFs] isFsInitialized:',
33
+ isFsInitialized(),
34
+ )
35
+
36
+ if (isBrowser()) {
37
+ await waitForEvent({
38
+ req: {
39
+ eventLabel: 'fs.downloadAll.request',
40
+ data: { endpoints },
41
+ },
42
+ res: {
43
+ eventLabel: 'fs.downloadAll.success',
44
+ },
45
+ })
46
+ }
47
+
48
+
49
+ const journalPath = `${filesDir || BROWSER_FS_TOP_DIR}/db/meta/_journal.json`
50
+
51
+
52
+ let journalExists = await fs.promises.exists(journalPath)
53
+
54
+ if (!journalExists) {
55
+ journalExists = fs.existsSync(journalPath)
56
+ }
57
+
58
+ if (journalExists) {
59
+ appDbService.send({ type: DB_WAITING_FOR_FILES_RECEIVED })
60
+ logger('[internal/actors] [configureFs] fs configured!')
61
+ return true
62
+ }
63
+
64
+ sendBack({ type: 'shouldWaitForFiles' })
65
+
66
+
67
+ return false
68
+
69
+ // return new Promise<void>((resolve) => {
70
+ // const interval = setInterval(() => {
71
+ // journalExistsSync = fs.existsSync(journalPath)
72
+ // logger(
73
+ // '[internal/actors] [configureFs] journalExistsSync:',
74
+ // journalExistsSync,
75
+ // )
76
+ // if (journalExistsSync) {
77
+ // service.send({ type: DB_WAITING_FOR_FILES_RECEIVED })
78
+ // clearInterval(interval)
79
+ // resolve()
80
+ // }
81
+ // }, 200)
82
+ // })
83
+
84
+ }
85
+
86
+ // Some of our dependencies use fs sync functions, which don't work with
87
+ // OPFS. ZenFS creates an async cache of all files so that the sync functions
88
+ // work, but we have to wait for it to be built. Otherwise things like
89
+ // drizzleMigrate will fail since they can't see the migration files yet.
90
+ _configureFs().then((fsConfigured) => {
91
+ if (fsConfigured) {
92
+ sendBack({ type: INTERNAL_CONFIGURING_FS_SUCCESS })
93
+ }
94
+ return
95
+ })
96
+
97
+ return () => { }
98
+ })
@@ -0,0 +1,41 @@
1
+ import { EventObject, fromCallback } from 'xstate'
2
+ import { DbServiceContext, FromCallbackInput } from '@/types'
3
+ import { getSqliteWasmClient } from '@/db/sqlWasmClient'
4
+ import { DB_CREATING_SUCCESS } from '@/services/internal/constants'
5
+ import debug from 'debug'
6
+ import { BaseDb } from '@/db/Db/BaseDb'
7
+
8
+ const logger = debug('app:services:db:actors:connectToDb')
9
+
10
+ export const connectToDb = fromCallback<
11
+ EventObject,
12
+ FromCallbackInput<DbServiceContext>
13
+ >(({ sendBack, input: { context } }) => {
14
+ logger('[db/actors] connectToDb context', context)
15
+
16
+ const { dbName, pathToDir } = context
17
+
18
+ if (!pathToDir || !dbName) {
19
+ throw new Error('pathToDir and dbName are required')
20
+ }
21
+
22
+ let isConnecting = false
23
+ let dbId: string | undefined
24
+
25
+ const _connectToDb = async (): Promise<void> => {
26
+ if (isConnecting) {
27
+ return
28
+ }
29
+ isConnecting = true
30
+ const dbId = await BaseDb.connectToDb(pathToDir, dbName)
31
+ if (dbId) {
32
+ sendBack({ type: DB_CREATING_SUCCESS, dbId, })
33
+ }
34
+ isConnecting = false
35
+ }
36
+
37
+ _connectToDb().then(() => {
38
+ return
39
+ })
40
+
41
+ })
@@ -0,0 +1,67 @@
1
+ type SqliteDatabase = {
2
+ open: (filename: string) => Promise<void>
3
+ exec: (sql: string, params?: any[]) => any
4
+ close: () => void
5
+ }
6
+
7
+ class SqliteConnectionManager {
8
+ private sqliteModule: SqliteDatabase
9
+ private idleTimeout: number
10
+ private databases: { [key: string]: SqliteDatabase }
11
+ private idleTimers: { [key: string]: NodeJS.Timeout }
12
+
13
+ constructor(sqliteModule: SqliteDatabase, idleTimeout: number = 300000) {
14
+ // Default idle timeout: 5 minutes
15
+ this.sqliteModule = sqliteModule
16
+ this.idleTimeout = idleTimeout
17
+ this.databases = {}
18
+ this.idleTimers = {}
19
+ }
20
+
21
+ private resetIdleTimer(dbName: string): void {
22
+ if (this.idleTimers[dbName]) {
23
+ clearTimeout(this.idleTimers[dbName])
24
+ }
25
+
26
+ this.idleTimers[dbName] = setTimeout(() => {
27
+ this.closeConnection(dbName)
28
+ }, this.idleTimeout)
29
+ }
30
+
31
+ private async getConnection(dbName: string): Promise<SqliteDatabase> {
32
+ if (this.databases[dbName]) {
33
+ this.resetIdleTimer(dbName)
34
+ return this.databases[dbName]
35
+ }
36
+
37
+ const db = new this.sqliteModule()
38
+ await db.open(dbName)
39
+ this.databases[dbName] = db
40
+ this.resetIdleTimer(dbName)
41
+ return db
42
+ }
43
+
44
+ public async execute(
45
+ dbName: string,
46
+ sql: string,
47
+ params: any[] = [],
48
+ ): Promise<any> {
49
+ const db = await this.getConnection(dbName)
50
+ const result = db.exec(sql, params)
51
+ this.resetIdleTimer(dbName)
52
+ return result
53
+ }
54
+
55
+ public closeConnection(dbName: string): void {
56
+ if (this.databases[dbName]) {
57
+ this.databases[dbName].close()
58
+ delete this.databases[dbName]
59
+ if (this.idleTimers[dbName]) {
60
+ clearTimeout(this.idleTimers[dbName])
61
+ delete this.idleTimers[dbName]
62
+ }
63
+ }
64
+ }
65
+ }
66
+
67
+ export { SqliteConnectionManager }
@@ -0,0 +1,125 @@
1
+ const ENV = (typeof process !== 'undefined' && process.env)
2
+ ? process.env
3
+ : (typeof window !== 'undefined' && (window as any).env)
4
+ ? (window as any).env
5
+ : {};
6
+
7
+
8
+ const MACHINE_ID_SCOPE = '@seedSdk'
9
+
10
+ export enum MachineIds {
11
+ GLOBAL = `${MACHINE_ID_SCOPE}/global`,
12
+ INTERNAL = `${MACHINE_ID_SCOPE}/internal`,
13
+ DB = `${MACHINE_ID_SCOPE}/db`,
14
+ EAS = `${MACHINE_ID_SCOPE}/eas`,
15
+ ITEM = `${MACHINE_ID_SCOPE}/item`,
16
+ ALL_ITEMS = `${MACHINE_ID_SCOPE}/allItems`,
17
+ MODEL = `${MACHINE_ID_SCOPE}/model`,
18
+ FILE_SYSTEM = `${MACHINE_ID_SCOPE}/fileSystem`,
19
+ }
20
+
21
+ const { INTERNAL, DB, GLOBAL, EAS, MODEL } = MachineIds
22
+
23
+ export enum GlobalState {
24
+ UNINITIALIZED = 'uninitialized',
25
+ INITIALIZING = 'initializing',
26
+ INITIALIZED = 'initialized',
27
+ PUBLISHING_ITEM = 'publishingItem',
28
+ ADDING_MODELS_TO_DB = 'addingModelsToDb',
29
+ }
30
+
31
+ const {
32
+ UNINITIALIZED,
33
+ INITIALIZING,
34
+ INITIALIZED,
35
+ PUBLISHING_ITEM,
36
+ ADDING_MODELS_TO_DB,
37
+ } = GlobalState
38
+
39
+ export enum InternalState {
40
+ IDLE = 'idle',
41
+ INITIALIZING = 'initializing',
42
+ VALIDATING_INPUT = 'validatingInput',
43
+ CONFIGURING_FS = 'configuringFs',
44
+ LOADING_SEED_DB = 'loadingSeedDb',
45
+ SAVING_CONFIG = 'savingConfig',
46
+ LOADING_APP_DB = 'loadingAppDb',
47
+ LOADING_SDK_DB = 'loadingSdkDb',
48
+ }
49
+
50
+ const { VALIDATING_INPUT, CONFIGURING_FS, LOADING_SEED_DB, LOADING_APP_DB } =
51
+ InternalState
52
+
53
+ export enum DbState {
54
+ CHECKING_STATUS = 'checkingStatus',
55
+ WAITING_FOR_FILES = 'waitingForFiles',
56
+ VALIDATING = 'validating',
57
+ CONNECTING_TO_DB = 'connectingToDb',
58
+ // FETCHING_MIGRATIONS = 'fetchingMigrations',
59
+ MIGRATING = 'migrating',
60
+ }
61
+
62
+ const {
63
+ CHECKING_STATUS,
64
+ VALIDATING,
65
+ CONNECTING_TO_DB,
66
+ WAITING_FOR_FILES,
67
+ MIGRATING,
68
+ } = DbState
69
+
70
+ export enum PublishMachineStates {
71
+ VALIDATING_ITEM_DATA = 'validatingItemData',
72
+ CREATING_PUBLISH_ATTEMPT = 'creatingPublishAttempt',
73
+ UPLOADING = 'uploading',
74
+ PREPARING_PUBLISH_REQUEST_DATA = 'preparingPublishRequestData',
75
+ PUBLISHING = 'publishing',
76
+ IDLE = 'idle',
77
+ }
78
+
79
+ export const INTERNAL_VALIDATING_INPUT_SUCCESS = `${INTERNAL}.${VALIDATING_INPUT}.success`
80
+
81
+ export const INTERNAL_CONFIGURING_FS_SUCCESS = `${INTERNAL}.${CONFIGURING_FS}.success`
82
+ export const INTERNAL_CONFIGURING_FS_FAILURE = `${INTERNAL}.${CONFIGURING_FS}.failure`
83
+
84
+ export const INTERNAL_LOADING_SEED_DB_SUCCESS = `${INTERNAL}.${LOADING_SEED_DB}.success`
85
+ export const INTERNAL_LOADING_SEED_DB_FAILURE = `${INTERNAL}.${LOADING_SEED_DB}.failure`
86
+
87
+ export const INTERNAL_LOADING_APP_DB_SUCCESS = `${INTERNAL}.${LOADING_APP_DB}.success`
88
+ export const INTERNAL_LOADING_APP_DB_FAILURE = `${INTERNAL}.${LOADING_APP_DB}.failure`
89
+
90
+ export const INTERNAL_SAVING_CONFIG_SUCCESS = `${INTERNAL}.savingConfig.success`
91
+ export const INTERNAL_SAVING_CONFIG_FAILURE = `${INTERNAL}.savingConfig.failure`
92
+
93
+ export const GLOBAL_GETTING_SEED_CLASS_SUCCESS = `${GLOBAL}.${PUBLISHING_ITEM}.success`
94
+ export const GLOBAL_INITIALIZING_SEND_CONFIG = `${GLOBAL}.${INITIALIZING}.sendConfig`
95
+ export const GLOBAL_INITIALIZING_INTERNAL_SERVICE_READY = `${GLOBAL}.${INITIALIZING}.internalServiceReady`
96
+ export const GLOBAL_INITIALIZING_CREATE_ALL_ITEMS_SERVICES = `${GLOBAL}.${INITIALIZING}.createAllItemsServices`
97
+ export const GLOBAL_ADDING_MODELS_TO_DB_SUCCESS = `${GLOBAL}.${ADDING_MODELS_TO_DB}.success`
98
+
99
+ export const DB_CHECK_STATUS_UPDATE_PATHS = `${DB}.${CHECKING_STATUS}.updatePaths`
100
+ export const DB_CHECK_STATUS_EXISTS = `${DB}.${CHECKING_STATUS}.exists`
101
+ export const DB_CHECK_STATUS_DOES_NOT_EXIST = `${DB}.${CHECKING_STATUS}.doesNotExist`
102
+ export const DB_CHECK_STATUS_FAILURE = `${DB}.${CHECKING_STATUS}.failure`
103
+
104
+ export const DB_VALIDATING_SUCCESS = `${DB}.${VALIDATING}.success`
105
+ export const DB_VALIDATING_WAIT = `${DB}.${VALIDATING}.wait`
106
+ export const DB_MIGRATING_WAIT = `${DB}.${MIGRATING}.wait`
107
+ export const DB_MIGRATING_SUCCESS = `${DB}.${MIGRATING}.success`
108
+ export const DB_CREATING_SUCCESS = `${DB}.${CONNECTING_TO_DB}.success`
109
+ export const DB_WAITING_FOR_FILES_RECEIVED = `${DB}.${WAITING_FOR_FILES}.filesReceived`
110
+ export const DB_ON_SNAPSHOT = `${DB}.onSnapshot`
111
+ export const CHILD_SNAPSHOT = 'childSnapshot'
112
+
113
+ export const INTERNAL_SERVICE_SNAPSHOT = 'internalServiceSnapshot'
114
+
115
+ export const DB_NAME_APP = 'app_db'
116
+ export const BROWSER_FS_TOP_DIR = 'app-files'
117
+
118
+ export const EAS_ENDPOINT =
119
+ ENV.NEXT_PUBLIC_EAS_ENDPOINT ||
120
+ ENV.EAS_ENDPOINT ||
121
+ 'https://optimism-sepolia.easscan.org/graphql'
122
+
123
+ export const ARWEAVE_HOST =
124
+ ENV.NEXT_PUBLIC_ARWEAVE_HOST || 'arweave.net'
125
+ export const ARWEAVE_ENDPOINT = `https://${ARWEAVE_HOST}/graphql`
@@ -0,0 +1,30 @@
1
+ const hashLargeString = async ( input: string, ): Promise<string> => {
2
+ // Convert the string to an ArrayBuffer
3
+ const encoder = new TextEncoder()
4
+ const data = encoder.encode(input,)
5
+
6
+ // Hash the data with SHA-256
7
+ const hashBuffer = await crypto.subtle.digest('SHA-256', data,)
8
+
9
+ // Convert the ArrayBuffer to a hex string
10
+ const hashArray = Array.from(new Uint8Array(hashBuffer,),)
11
+ const hashHex = hashArray.map(( b, ) => b.toString(16,).padStart(2, '0',),).join('',)
12
+
13
+ return hashHex
14
+ }
15
+
16
+ onmessage = async (event,) => {
17
+ postMessage('Content hash worker received message',)
18
+ if (!event || !event.data || !event.data.trackingId || !event.data.base64) {
19
+ postMessage('No event data received',)
20
+ return
21
+ }
22
+ const { trackingId, base64, } = event.data
23
+ postMessage('Beginning content hash calculation',)
24
+ const contentHash = await hashLargeString(base64,)
25
+ postMessage('Content hash calculation complete',)
26
+ postMessage({
27
+ trackingId,
28
+ contentHash,
29
+ },)
30
+ }
@@ -0,0 +1,39 @@
1
+ import { eventEmitter } from '@/eventBus'
2
+ import { createItemCacheKey, getItemCache, updateItemCache } from './requestAll'
3
+ import { BaseItem } from '@/Item/BaseItem'
4
+
5
+ export const createItemRequestHandler = async (event) => {
6
+ const { ModelClass, itemData } = event
7
+
8
+ const itemCache = getItemCache()
9
+
10
+ const itemCacheKey = createItemCacheKey(itemData)
11
+
12
+ if (!itemCacheKey) {
13
+ console.warn('itemCacheKey not found for itemData', itemData)
14
+ return
15
+ }
16
+
17
+ if (itemCache.has(itemCacheKey)) {
18
+ return
19
+ }
20
+
21
+ const newItem = await BaseItem.create({
22
+ modelName: ModelClass.originalConstructor.name,
23
+ ...itemData,
24
+ })
25
+
26
+ updateItemCache(itemCacheKey, newItem)
27
+
28
+ return new Promise<void>((resolve) => {
29
+ const subscription = newItem.subscribe((context) => {
30
+ if (context && context.versionLocalId && context.seedLocalId) {
31
+ subscription.unsubscribe()
32
+ // allItemsService.send({ type: 'addItemToContext', item: newItem })
33
+ eventEmitter.emit('item.create.response', { item: newItem })
34
+ // eventEmitter.emit('item.requestAll', { modelName })
35
+ resolve()
36
+ }
37
+ })
38
+ })
39
+ }
@@ -0,0 +1,77 @@
1
+ import { metadata, MetadataType } from '@/seedSchema'
2
+ import { BaseEasClient, BaseQueryClient, generateId } from '@/helpers'
3
+ import { PropertyType } from '@/types'
4
+ import { BaseDb } from '../Db/BaseDb'
5
+ import { GET_SCHEMA_BY_NAME, } from '@/Item/queries'
6
+ import { INTERNAL_DATA_TYPES } from '@/helpers/constants'
7
+ import { toSnakeCase } from 'drizzle-orm/casing'
8
+ import { Schema } from '@/graphql/gql/graphql'
9
+ import path from 'path'
10
+ import fs from '@zenfs/core'
11
+
12
+ type CreateMetadata = (
13
+ metadataValues: Partial<MetadataType>,
14
+ propertyRecordSchema?: PropertyType | undefined,
15
+ ) => Promise<MetadataType>
16
+
17
+ export const createMetadata: CreateMetadata = async (
18
+ metadataValues,
19
+ propertyRecordSchema?,
20
+ ) => {
21
+ const appDb = BaseDb.getAppDb()
22
+
23
+ metadataValues.localId = generateId()
24
+
25
+ if (!metadataValues.modelType && metadataValues.modelName) {
26
+ metadataValues.modelType = toSnakeCase(metadataValues.modelName)
27
+ }
28
+
29
+ const isItemStorage = propertyRecordSchema && propertyRecordSchema.storageType === 'ItemStorage'
30
+
31
+ // if (
32
+ // propertyRecordSchema &&
33
+ // propertyRecordSchema.localStorageDir &&
34
+ // isItemStorage
35
+ // ) {
36
+ // const filename = `${metadataValues.seedUid || metadataValues.seedLocalId}${propertyRecordSchema.filenameSuffix}`
37
+ // const filePath = path.join(propertyRecordSchema.localStorageDir, filename)
38
+ // await fs.promises.writeFile(filePath, metadataValues.propertyValue)
39
+ // metadataValues.propertyValue = filename
40
+ // metadataValues.refValueType = 'file'
41
+ // }
42
+
43
+ if (!isItemStorage && !metadataValues.schemaUid && propertyRecordSchema) {
44
+ const queryClient = BaseQueryClient.getQueryClient()
45
+ const easClient = BaseEasClient.getEasClient()
46
+
47
+ const easDataType = INTERNAL_DATA_TYPES[propertyRecordSchema.dataType].eas
48
+
49
+ const propertyNameSnakeCase = toSnakeCase(metadataValues.propertyName)
50
+
51
+ const queryResult = await queryClient.fetchQuery({
52
+ queryKey: [`getSchemaByName${metadataValues.propertyName}`],
53
+ queryFn: async (): Promise<{schemas: Schema[]}> =>
54
+ easClient.request(GET_SCHEMA_BY_NAME, {
55
+ where: {
56
+ schema: {
57
+ equals: `${easDataType} ${propertyNameSnakeCase}`,
58
+ },
59
+ },
60
+ }),
61
+ })
62
+
63
+ if (queryResult && queryResult.schemas.length > 0) {
64
+ metadataValues.schemaUid = queryResult.schemas[0].id
65
+ }
66
+
67
+ }
68
+
69
+ return appDb
70
+ .insert(metadata)
71
+ .values({
72
+ ...metadataValues,
73
+ createdAt: Date.now(),
74
+ updatedAt: Date.now(),
75
+ })
76
+ .returning()
77
+ }
@@ -0,0 +1,61 @@
1
+ import { ModelValues } from '@/types'
2
+ import { getModel } from '@/stores/modelClass'
3
+ import { createSeed } from './createSeed'
4
+ import { createVersion } from './createVersion'
5
+ import { createMetadata } from './createMetadata'
6
+ import { toSnakeCase } from 'drizzle-orm/casing'
7
+ import { eventEmitter } from '@/eventBus'
8
+
9
+ type CreateNewItemProps = Partial<ModelValues<any>> & {
10
+ modelName: string
11
+ }
12
+
13
+ type CreateNewItemReturnType = {
14
+ modelName: string
15
+ seedLocalId: string
16
+ versionLocalId: string
17
+ }
18
+
19
+ export const createNewItem = async ({
20
+ modelName,
21
+ ...propertyData
22
+ }: CreateNewItemProps): Promise<CreateNewItemReturnType> => {
23
+ if (!modelName) {
24
+ throw new Error('A model name is required for createNewItem')
25
+ }
26
+
27
+ const seedType = toSnakeCase(modelName)
28
+
29
+ const newSeedId = await createSeed({ type: seedType })
30
+
31
+ const newVersionId = await createVersion({ seedLocalId: newSeedId, seedType: toSnakeCase(modelName) })
32
+
33
+ const propertySchemas = getModel(modelName)?.schema
34
+
35
+ for (const [propertyName, propertyValue] of Object.entries(propertyData)) {
36
+ let propertyRecordSchema
37
+
38
+ if (propertySchemas && propertySchemas[propertyName]) {
39
+ propertyRecordSchema = propertySchemas[propertyName]
40
+ }
41
+
42
+ await createMetadata(
43
+ {
44
+ seedLocalId: newSeedId,
45
+ versionLocalId: newVersionId,
46
+ propertyName,
47
+ propertyValue,
48
+ modelName,
49
+ },
50
+ propertyRecordSchema,
51
+ )
52
+ }
53
+
54
+ eventEmitter.emit('item.requestAll', { modelName })
55
+
56
+ return {
57
+ modelName,
58
+ seedLocalId: newSeedId,
59
+ versionLocalId: newVersionId,
60
+ }
61
+ }
@@ -0,0 +1,16 @@
1
+ import { EventObject, fromCallback } from 'xstate'
2
+ import { FromCallbackInput, PublishMachineContext } from '@/types'
3
+
4
+ export const createPublishAttempt = fromCallback<
5
+ EventObject,
6
+ FromCallbackInput<PublishMachineContext>
7
+ >(({ sendBack, input: { context } }) => {
8
+ const _createPublishAttempt = async () => {
9
+ // Do some stuff
10
+ return true
11
+ }
12
+
13
+ _createPublishAttempt().then(() => {
14
+ sendBack({ type: 'createPublishAttemptSuccess' })
15
+ })
16
+ })