@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,326 @@
1
+
2
+ export default `(
3
+ ${
4
+ function () {
5
+
6
+ const identifyString = (str: string) => {
7
+ try {
8
+ JSON.parse(str)
9
+ return 'json'
10
+ } catch (e) {
11
+ // Not JSON
12
+ }
13
+
14
+ if (!str) {
15
+ return
16
+ }
17
+
18
+ if (str.trim().startsWith('<') && str.trim().endsWith('>')) {
19
+ return 'html'
20
+ }
21
+
22
+ // Simple markdown checks (very naive)
23
+ if (/^#{1,6}\s|^-{3,}|\*{3,}|^-{1,2}\s|\*\s/.test(str)) {
24
+ return 'markdown'
25
+ }
26
+
27
+ if (/^data:image\/[a-zA-Z]+;base64,[A-Za-z0-9+/]+={0,2}$/.test(str)) {
28
+ return 'base64'
29
+ }
30
+
31
+ // Default to plain text if unsure
32
+ return 'text'
33
+ }
34
+
35
+ const getMimeType = (base64: string) => {
36
+ if (!base64) {
37
+ return null
38
+ }
39
+ const result = base64.match(/^data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+).*,/)
40
+
41
+ if (result && result.length > 1) {
42
+ return result[1]
43
+ } else {
44
+ return null // MIME type could not be determined
45
+ }
46
+ }
47
+
48
+ const getDataTypeFromString = (
49
+ data: string,
50
+ ): 'imageBase64' | 'base64' | 'url' | null => {
51
+ const nonImageBase64Regex =
52
+ /^(?!data:image\/(?:jpeg|png|gif|bmp|webp);base64,)[A-Za-z0-9+/=]+$/
53
+
54
+ if (nonImageBase64Regex.test(data)) {
55
+ return 'base64'
56
+ }
57
+
58
+ // Regular expression for base64 (simple version, checking for base64 format)
59
+ const imageBase64Regex = /^data:image\/[a-zA-Z]+;base64,[A-Za-z0-9+/]+={0,2}$/
60
+
61
+ if (imageBase64Regex.test(data)) {
62
+ return 'imageBase64'
63
+ }
64
+
65
+ // Regular expression for URL (simple version, checking for common URL format)
66
+ const urlRegex =
67
+ /^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/
68
+
69
+ if (urlRegex.test(data)) {
70
+ return 'url'
71
+ }
72
+
73
+ return null
74
+ }
75
+
76
+ const isBinary = (arrayBuffer: ArrayBuffer): boolean => {
77
+ const view = new Uint8Array(arrayBuffer);
78
+
79
+ let nonTextCount = 0;
80
+ const threshold = 0.2; // Adjust as needed (e.g., 20% non-text implies binary)
81
+
82
+ for (let i = 0; i < view.length; i++) {
83
+ const byte = view[i];
84
+
85
+ // ASCII printable characters (32-126) and common whitespace (9, 10, 13)
86
+ if (
87
+ (byte >= 32 && byte <= 126) || // Printable ASCII
88
+ byte === 9 || byte === 10 || byte === 13 // Tab, LF, CR
89
+ ) {
90
+ continue;
91
+ }
92
+
93
+ nonTextCount++;
94
+ if (nonTextCount / view.length > threshold) {
95
+ return true; // More than threshold are non-text bytes
96
+ }
97
+ }
98
+
99
+ return false; // Fewer than threshold are non-text bytes
100
+ }
101
+
102
+ const saveBufferToOPFS = async (filePath: string, buffer: Uint8Array): Promise<void> => {
103
+ // Access the OPFS root directory
104
+ const rootHandle = await navigator.storage.getDirectory();
105
+
106
+ // Split the filePath into directory segments and file name
107
+ const segments = filePath.split('/').filter(Boolean);
108
+ const fileName = segments.pop(); // Extract the file name
109
+ if (!fileName) {
110
+ throw new Error('Invalid file path: No file name provided.');
111
+ }
112
+
113
+ // Traverse or create directories as needed
114
+ let currentDirHandle = rootHandle;
115
+ for (const segment of segments) {
116
+ currentDirHandle = await currentDirHandle.getDirectoryHandle(segment, { create: true });
117
+ }
118
+
119
+ // Create or open the file in OPFS
120
+ const fileHandleAsync = await currentDirHandle.getFileHandle(fileName, { create: true });
121
+ const fileHandle = await fileHandleAsync.createSyncAccessHandle();
122
+ // Write the buffer to the file
123
+ fileHandle.write(buffer);
124
+ fileHandle.flush();
125
+ fileHandle.close();
126
+ }
127
+
128
+ const downloadFiles = async ({
129
+ transactionIds,
130
+ arweaveHost,
131
+ }: {
132
+ transactionIds: string[],
133
+ arweaveHost: string,
134
+ }) => {
135
+
136
+ let arrayBuffer: ArrayBuffer | undefined
137
+
138
+ for (const transactionId of transactionIds) {
139
+ try {
140
+ const response = await fetch(`https://${arweaveHost}/raw/${transactionId}`);
141
+
142
+ arrayBuffer = await response.arrayBuffer();
143
+ } catch(error) {
144
+ console.log(`[filesDownload] transaction ${transactionId} data not found`, error)
145
+ globalThis.postMessage({
146
+ message: 'excludeTransaction',
147
+ transactionId,
148
+ })
149
+ continue
150
+ }
151
+
152
+ let dataString
153
+ const isBinaryData = isBinary(arrayBuffer)
154
+
155
+ if (!isBinaryData) {
156
+ const decoder = new TextDecoder('utf-8')
157
+ const text = decoder.decode(arrayBuffer)
158
+ dataString = text
159
+ }
160
+
161
+ if (!dataString && !arrayBuffer) {
162
+ console.log(
163
+ `[filesDownload] transaction ${transactionId} data not found`,
164
+ )
165
+ }
166
+
167
+ if (dataString && dataString.startsWith('===FILE_SEPARATOR===')) {
168
+ const dataStringParts = dataString
169
+ .split('===FILE_SEPARATOR===')
170
+ .slice(1)
171
+
172
+ if (dataStringParts.length % 2 !== 0) {
173
+ throw new Error('Input array must have an even number of elements.')
174
+ }
175
+
176
+ for (let i = 0; i < dataStringParts.length; i += 2) {
177
+ const contentType = dataStringParts[i]
178
+ const content = dataStringParts[i + 1]
179
+ const encoder = new TextEncoder()
180
+ if (contentType === 'html') {
181
+ const fileName = `${transactionId}.html`
182
+ const buffer = encoder.encode(content)
183
+ saveBufferToOPFS(`/files/html/${fileName}`, buffer)
184
+ }
185
+ if (contentType === 'json') {
186
+ const fileName = `${transactionId}.json`
187
+ const buffer = encoder.encode(content)
188
+ saveBufferToOPFS(`/files/json/${fileName}`, buffer)
189
+ }
190
+ }
191
+
192
+ continue
193
+ }
194
+
195
+ if (!dataString && arrayBuffer) {
196
+ saveBufferToOPFS(
197
+ `/files/images/${transactionId}`,
198
+ new Uint8Array(arrayBuffer),
199
+ )
200
+ continue
201
+ }
202
+
203
+ if (!dataString) {
204
+ continue
205
+ }
206
+
207
+ let contentType = identifyString(dataString)
208
+
209
+ if (
210
+ contentType !== 'json' &&
211
+ contentType !== 'base64' &&
212
+ contentType !== 'html'
213
+ ) {
214
+ const possibleImageType = getDataTypeFromString(dataString)
215
+ if (!possibleImageType) {
216
+ console.log(
217
+ `[filesDownload] transaction ${transactionId} data not in expected format: ${possibleImageType}`,
218
+ )
219
+ continue
220
+ }
221
+
222
+ contentType = possibleImageType
223
+ }
224
+
225
+ if (contentType === 'url') {
226
+ const url = dataString as string
227
+
228
+ let buffer: ArrayBuffer | undefined
229
+
230
+ try {
231
+ const response = await fetch(url)
232
+
233
+ buffer = await response.arrayBuffer()
234
+
235
+ } catch(error) {
236
+ console.log(`[filesDownload] transaction ${transactionId} value was url: ${dataString} but failed to fetch`, error)
237
+ globalThis.postMessage({
238
+ message: 'excludeTransaction',
239
+ transactionId,
240
+ })
241
+ continue
242
+ }
243
+
244
+ const bufferUint8Array = new Uint8Array(buffer)
245
+
246
+ // Extract the file extension from the URL
247
+ const extensionMatch = url.match(/\.(jpg|jpeg|png|gif|bmp|webp|svg)$/i)
248
+ if (!extensionMatch) {
249
+ throw new Error(
250
+ 'Unable to determine the file extension from the URL.',
251
+ )
252
+ }
253
+ const fileExtension = extensionMatch[0] // e.g., ".jpg"
254
+
255
+ // Set the file name (you can customize this)
256
+ // const fileNameFromUrl = `${transactionId}${fileExtension}`
257
+
258
+ await saveBufferToOPFS(
259
+ `/files/images/${transactionId}`,
260
+ bufferUint8Array,
261
+ )
262
+
263
+ continue
264
+ }
265
+
266
+ const mimeType = getMimeType(dataString as string)
267
+ let fileExtension = mimeType
268
+
269
+ if (fileExtension && fileExtension?.startsWith('image')) {
270
+ fileExtension = fileExtension.replace('image/', '')
271
+ }
272
+
273
+ let fileName = transactionId
274
+
275
+ if (contentType === 'base64') {
276
+ if (fileExtension) {
277
+ fileName += `.${fileExtension}`
278
+ }
279
+
280
+ // Remove the Base64 header if it exists (e.g., "data:image/png;base64,")
281
+ const base64Data = dataString.split(',').pop() || ''
282
+
283
+ // Decode the Base64 string to binary
284
+ const binaryString = atob(base64Data)
285
+ const length = binaryString.length
286
+ const binaryData = new Uint8Array(length)
287
+
288
+ for (let i = 0; i < length; i++) {
289
+ binaryData[i] = binaryString.charCodeAt(i)
290
+ }
291
+
292
+ await saveBufferToOPFS(`/files/images/${fileName}`, binaryData)
293
+
294
+ }
295
+
296
+ if (contentType === 'html') {
297
+ fileName += '.html'
298
+ const encoder = new TextEncoder()
299
+ const buffer = encoder.encode(dataString)
300
+ await saveBufferToOPFS(`/files/html/${fileName}`, buffer)
301
+ }
302
+
303
+ if (contentType === 'json') {
304
+ fileName += '.json'
305
+ const encoder = new TextEncoder()
306
+ const buffer = encoder.encode(dataString)
307
+ await saveBufferToOPFS(`/files/json/${fileName}`, buffer)
308
+ }
309
+ }
310
+ }
311
+
312
+ onmessage = async (e) => {
313
+ console.log({
314
+ message: 'filesDownload onmessage',
315
+ data: e.data,
316
+ })
317
+ await downloadFiles(e.data);
318
+ globalThis.postMessage({
319
+ message: 'filesDownload onmessage done',
320
+ done: true,
321
+ })
322
+
323
+ }
324
+ }.toString()
325
+ }
326
+ )()`
@@ -0,0 +1,87 @@
1
+ /* eslint-disable */
2
+ import { ResultOf, DocumentTypeDecoration, TypedDocumentNode } from '@graphql-typed-document-node/core';
3
+ import { FragmentDefinitionNode } from 'graphql';
4
+ import { Incremental } from './graphql';
5
+
6
+
7
+ export type FragmentType<TDocumentType extends DocumentTypeDecoration<any, any>> = TDocumentType extends DocumentTypeDecoration<
8
+ infer TType,
9
+ any
10
+ >
11
+ ? [TType] extends [{ ' $fragmentName'?: infer TKey }]
12
+ ? TKey extends string
13
+ ? { ' $fragmentRefs'?: { [key in TKey]: TType } }
14
+ : never
15
+ : never
16
+ : never;
17
+
18
+ // return non-nullable if `fragmentType` is non-nullable
19
+ export function useFragment<TType>(
20
+ _documentNode: DocumentTypeDecoration<TType, any>,
21
+ fragmentType: FragmentType<DocumentTypeDecoration<TType, any>>
22
+ ): TType;
23
+ // return nullable if `fragmentType` is undefined
24
+ export function useFragment<TType>(
25
+ _documentNode: DocumentTypeDecoration<TType, any>,
26
+ fragmentType: FragmentType<DocumentTypeDecoration<TType, any>> | undefined
27
+ ): TType | undefined;
28
+ // return nullable if `fragmentType` is nullable
29
+ export function useFragment<TType>(
30
+ _documentNode: DocumentTypeDecoration<TType, any>,
31
+ fragmentType: FragmentType<DocumentTypeDecoration<TType, any>> | null
32
+ ): TType | null;
33
+ // return nullable if `fragmentType` is nullable or undefined
34
+ export function useFragment<TType>(
35
+ _documentNode: DocumentTypeDecoration<TType, any>,
36
+ fragmentType: FragmentType<DocumentTypeDecoration<TType, any>> | null | undefined
37
+ ): TType | null | undefined;
38
+ // return array of non-nullable if `fragmentType` is array of non-nullable
39
+ export function useFragment<TType>(
40
+ _documentNode: DocumentTypeDecoration<TType, any>,
41
+ fragmentType: Array<FragmentType<DocumentTypeDecoration<TType, any>>>
42
+ ): Array<TType>;
43
+ // return array of nullable if `fragmentType` is array of nullable
44
+ export function useFragment<TType>(
45
+ _documentNode: DocumentTypeDecoration<TType, any>,
46
+ fragmentType: Array<FragmentType<DocumentTypeDecoration<TType, any>>> | null | undefined
47
+ ): Array<TType> | null | undefined;
48
+ // return readonly array of non-nullable if `fragmentType` is array of non-nullable
49
+ export function useFragment<TType>(
50
+ _documentNode: DocumentTypeDecoration<TType, any>,
51
+ fragmentType: ReadonlyArray<FragmentType<DocumentTypeDecoration<TType, any>>>
52
+ ): ReadonlyArray<TType>;
53
+ // return readonly array of nullable if `fragmentType` is array of nullable
54
+ export function useFragment<TType>(
55
+ _documentNode: DocumentTypeDecoration<TType, any>,
56
+ fragmentType: ReadonlyArray<FragmentType<DocumentTypeDecoration<TType, any>>> | null | undefined
57
+ ): ReadonlyArray<TType> | null | undefined;
58
+ export function useFragment<TType>(
59
+ _documentNode: DocumentTypeDecoration<TType, any>,
60
+ fragmentType: FragmentType<DocumentTypeDecoration<TType, any>> | Array<FragmentType<DocumentTypeDecoration<TType, any>>> | ReadonlyArray<FragmentType<DocumentTypeDecoration<TType, any>>> | null | undefined
61
+ ): TType | Array<TType> | ReadonlyArray<TType> | null | undefined {
62
+ return fragmentType as any;
63
+ }
64
+
65
+
66
+ export function makeFragmentData<
67
+ F extends DocumentTypeDecoration<any, any>,
68
+ FT extends ResultOf<F>
69
+ >(data: FT, _fragment: F): FragmentType<F> {
70
+ return data as FragmentType<F>;
71
+ }
72
+ export function isFragmentReady<TQuery, TFrag>(
73
+ queryNode: DocumentTypeDecoration<TQuery, any>,
74
+ fragmentNode: TypedDocumentNode<TFrag>,
75
+ data: FragmentType<TypedDocumentNode<Incremental<TFrag>, any>> | null | undefined
76
+ ): data is FragmentType<typeof fragmentNode> {
77
+ const deferredFields = (queryNode as { __meta__?: { deferredFields: Record<string, (keyof TFrag)[]> } }).__meta__
78
+ ?.deferredFields;
79
+
80
+ if (!deferredFields) return true;
81
+
82
+ const fragDef = fragmentNode.definitions[0] as FragmentDefinitionNode | undefined;
83
+ const fragName = fragDef?.name?.value;
84
+
85
+ const fields = (fragName && deferredFields[fragName]) || [];
86
+ return fields.length > 0 && fields.every(field => data && field in data);
87
+ }
@@ -0,0 +1,60 @@
1
+ import { BaseDb } from '@/db/Db/BaseDb'
2
+ import { seeds } from '@/seedSchema'
3
+ import { and, eq, isNotNull, not, or } from 'drizzle-orm'
4
+
5
+ type GetExistingItemProps = {
6
+ seedLocalId: string
7
+ seedUid: string
8
+ }
9
+
10
+ type GetExistingItemReturn = {
11
+ seedLocalId: string
12
+ seedUid: string
13
+ createdAt: string
14
+ }
15
+
16
+ export const getExistingItem = async ({
17
+ seedLocalId,
18
+ seedUid,
19
+ }: GetExistingItemProps): Promise<GetExistingItemReturn | undefined> => {
20
+ const appDb = BaseDb.getAppDb()
21
+
22
+ const rows = await appDb
23
+ .select({
24
+ seedLocalId: seeds.localId,
25
+ seedUid: seeds.uid,
26
+ createdAt: seeds.createdAt,
27
+ })
28
+ .from(seeds)
29
+ .where(
30
+ or(
31
+ and(
32
+ isNotNull(seeds.uid),
33
+ not(eq(seeds.uid, '')),
34
+ not(eq(seeds.uid, 'undefined')),
35
+ not(eq(seeds.uid, 'null')),
36
+ not(eq(seeds.uid, 'false')),
37
+ not(eq(seeds.uid, '0')),
38
+ eq(seeds.uid, seedUid)
39
+ ),
40
+ and(
41
+ isNotNull(seeds.localId),
42
+ not(eq(seeds.localId, '')),
43
+ not(eq(seeds.localId, 'undefined')),
44
+ not(eq(seeds.localId, 'null')),
45
+ not(eq(seeds.localId, 'false')),
46
+ not(eq(seeds.localId, '0')),
47
+ eq(seeds.localId, seedLocalId)
48
+ )
49
+ )
50
+ )
51
+
52
+ if (!rows || rows.length === 0) {
53
+ return undefined
54
+ }
55
+
56
+ const matchingRow = rows.find(row => row.seedUid === seedUid) ||
57
+ rows.find(row => row.seedLocalId === seedLocalId)
58
+
59
+ return matchingRow
60
+ }
@@ -0,0 +1,32 @@
1
+ import { getItemData } from './getItemData'
2
+ import { GetItem } from '@/types'
3
+ import { BaseItem } from '@/Item/BaseItem'
4
+ import { startCase } from 'lodash-es'
5
+
6
+ export const getItem: GetItem = async ({ modelName, seedLocalId, seedUid }) => {
7
+ const itemInitObj = await getItemData({
8
+ modelName,
9
+ seedLocalId,
10
+ seedUid,
11
+ })
12
+
13
+ if (!itemInitObj) {
14
+ console.error(
15
+ `[db/queries] [getItem] no itemInitObj modelName: ${modelName} seedLocalId: ${seedLocalId} seedUid: ${seedUid}`,
16
+ )
17
+ return
18
+ }
19
+
20
+ if (!itemInitObj.seedLocalId) {
21
+ console.error(
22
+ `[db/queries] [getItem] no itemInitObj.seedLocalId modelName: ${modelName} seedLocalId: ${seedLocalId} seedUid: ${seedUid}`,
23
+ )
24
+ return
25
+ }
26
+
27
+ if (!itemInitObj.modelName && itemInitObj.type) {
28
+ itemInitObj.modelName = startCase(itemInitObj.type)
29
+ }
30
+
31
+ return BaseItem.create(itemInitObj)
32
+ }
@@ -0,0 +1,99 @@
1
+ import { GetItemData, ItemData } from "@/types"
2
+ import debug from "debug"
3
+ import { BaseDb } from "../Db/BaseDb"
4
+ import { and, eq, getTableColumns, gt, SQL, sql } from "drizzle-orm"
5
+ import { getItemProperties } from "./getItemProperties"
6
+ import { getVersionData } from "./subqueries/versionData"
7
+ import { seeds } from "@/seedSchema"
8
+ import { getSeedData } from "./getSeedData"
9
+
10
+ const logger = debug('app:db:read:getItemData')
11
+
12
+ export const getItemData: GetItemData = async ({
13
+ modelName,
14
+ seedLocalId,
15
+ seedUid,
16
+ }) => {
17
+ if (!seedLocalId && !seedUid) {
18
+ throw new Error('[db/queries] [getItem] no seedLocalId or seedUid')
19
+ }
20
+
21
+ if (seedUid && !seedLocalId) {
22
+ const seedData = await getSeedData({ seedUid })
23
+ if (!seedData) {
24
+ logger('[db/queries] [getItem] no seedData seedUid', seedUid)
25
+ return
26
+ }
27
+ seedLocalId = seedData.localId
28
+ }
29
+
30
+ const appDb = BaseDb.getAppDb()
31
+
32
+ const { localId, uid, ...rest } = getTableColumns(seeds)
33
+
34
+ const whereClauses: SQL[] = []
35
+
36
+ if (modelName) {
37
+ whereClauses.push(eq(seeds.type, modelName.toLowerCase()))
38
+ }
39
+
40
+ if (seedUid) {
41
+ whereClauses.push(eq(seeds.uid, seedUid))
42
+ }
43
+
44
+ if (seedLocalId && !seedUid) {
45
+ whereClauses.push(eq(seeds.localId, seedLocalId))
46
+ }
47
+
48
+ const versionData = getVersionData()
49
+
50
+ const itemDataRows = await appDb
51
+ .with(versionData)
52
+ .select({
53
+ ...rest,
54
+ seedLocalId: seeds.localId,
55
+ seedUid: seeds.uid,
56
+ versionsCount: versionData.versionsCount,
57
+ lastVersionPublishedAt: versionData.lastVersionPublishedAt,
58
+ latestVersionUid: versionData.latestVersionUid,
59
+ latestVersionLocalId: versionData.latestVersionLocalId,
60
+ })
61
+ .from(seeds)
62
+ .leftJoin(versionData, eq(seeds.localId, versionData.seedLocalId))
63
+ .where(and(...whereClauses, gt(versionData.versionsCount, 0)))
64
+ .orderBy(sql.raw('COALESCE(attestation_created_at, created_at) DESC'))
65
+ .groupBy(seeds.localId) as ItemData[]
66
+
67
+ if (!itemDataRows || itemDataRows.length === 0) {
68
+ logger('[db/queries] [getItemDataFromDb] no itemDataRows')
69
+ return
70
+ }
71
+
72
+ let itemData = itemDataRows[0] as ItemData & { [key: string]: any }
73
+
74
+ const propertiesData = await getItemProperties({
75
+ seedLocalId,
76
+ seedUid: itemData.seedUid || undefined,
77
+ })
78
+
79
+ if (!propertiesData || propertiesData.length === 0) {
80
+ return itemData
81
+ }
82
+
83
+ for (const propertyData of propertiesData) {
84
+ const propertyName = propertyData.propertyName
85
+
86
+ let propertyValue = propertyData.propertyValue
87
+
88
+ if (propertyName.endsWith('Id') || propertyName.endsWith('Ids')) {
89
+ if (propertyData.refSeedType) {
90
+ const propertyNameVariant = propertyName.replace(/Ids?$/, '')
91
+ itemData[propertyNameVariant] = propertyValue
92
+ }
93
+ }
94
+
95
+ itemData[propertyName] = propertyValue
96
+ }
97
+
98
+ if (itemData) return itemData
99
+ }
@@ -0,0 +1,56 @@
1
+ import { GetItemProperties, PropertyData } from '@/types'
2
+ import { metadata, seeds, versions } from '@/seedSchema'
3
+ import { and, eq, getTableColumns, isNotNull, isNull, sql, SQL } from 'drizzle-orm'
4
+ import { BaseDb } from '@/db/Db/BaseDb'
5
+ import { getMetadataLatest } from './subqueries/metadataLatest'
6
+
7
+
8
+ export const getItemProperties: GetItemProperties = async ({
9
+ seedLocalId,
10
+ seedUid,
11
+ edited,
12
+ }) => {
13
+ const appDb = BaseDb.getAppDb()
14
+
15
+ const whereClauses: SQL[] = [isNotNull(metadata.propertyName)]
16
+
17
+ if (seedUid) {
18
+ whereClauses.push(eq(seeds.uid, seedUid))
19
+ }
20
+
21
+ if (seedLocalId) {
22
+ whereClauses.push(eq(seeds.localId, seedLocalId))
23
+ }
24
+
25
+ whereClauses.push(isNotNull(metadata.propertyName))
26
+
27
+ if (typeof edited !== 'undefined') {
28
+ if (edited) {
29
+ whereClauses.push(isNull(metadata.uid))
30
+ }
31
+ if (!edited) {
32
+ whereClauses.push(isNotNull(metadata.uid))
33
+ }
34
+ }
35
+
36
+ // const metadataColumns = getTableColumns(metadata)
37
+
38
+ const metadataLatest = getMetadataLatest({seedLocalId, seedUid})
39
+
40
+ const propertiesData = await appDb
41
+ .with(metadataLatest)
42
+ .select()
43
+ .from(metadataLatest)
44
+ .where(eq(metadataLatest.rowNum, 1))
45
+
46
+ return propertiesData.map(data => ({
47
+ ...data,
48
+ localId: data.localId || '',
49
+ uid: data.uid || '',
50
+ propertyName: data.propertyName || '',
51
+ propertyValue: data.propertyValue || '',
52
+ schemaUid: data.schemaUid || '',
53
+ modelType: data.modelType || '',
54
+ seedLocalId: data.seedLocalId || '',
55
+ })) as PropertyData[]
56
+ }
@@ -0,0 +1,34 @@
1
+ import { BaseDb } from '@/db/Db/BaseDb'
2
+ import { metadata, MetadataType } from '@/seedSchema'
3
+ import { and, eq, getTableColumns } from 'drizzle-orm'
4
+
5
+ type GetItemPropertyProps = Partial<MetadataType>
6
+
7
+ type GetItemPropertyData = (
8
+ props: GetItemPropertyProps,
9
+ ) => Promise<Partial<MetadataType>>
10
+
11
+ export const getItemPropertyData: GetItemPropertyData = async (props) => {
12
+ const appDb = BaseDb.getAppDb()
13
+
14
+ const whereClauses = []
15
+
16
+ const tableColumns = getTableColumns(metadata)
17
+
18
+ for (const [propertyName, propertyValue] of Object.entries(props)) {
19
+ if (Object.keys(tableColumns).includes(propertyName)) {
20
+ whereClauses.push(eq(tableColumns[propertyName], propertyValue))
21
+ }
22
+ }
23
+
24
+ const queryRows = await appDb
25
+ .select()
26
+ .from(metadata)
27
+ .where(and(...whereClauses))
28
+
29
+ if (!queryRows || queryRows.length === 0) {
30
+ return
31
+ }
32
+
33
+ return queryRows[0]
34
+ }