@njdamstra/appwrite-utils-cli 1.8.9

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 (392) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +1133 -0
  3. package/dist/adapters/AdapterFactory.d.ts +94 -0
  4. package/dist/adapters/AdapterFactory.js +405 -0
  5. package/dist/adapters/DatabaseAdapter.d.ts +233 -0
  6. package/dist/adapters/DatabaseAdapter.js +50 -0
  7. package/dist/adapters/LegacyAdapter.d.ts +50 -0
  8. package/dist/adapters/LegacyAdapter.js +612 -0
  9. package/dist/adapters/TablesDBAdapter.d.ts +45 -0
  10. package/dist/adapters/TablesDBAdapter.js +571 -0
  11. package/dist/adapters/index.d.ts +11 -0
  12. package/dist/adapters/index.js +12 -0
  13. package/dist/backups/operations/bucketBackup.d.ts +19 -0
  14. package/dist/backups/operations/bucketBackup.js +197 -0
  15. package/dist/backups/operations/collectionBackup.d.ts +30 -0
  16. package/dist/backups/operations/collectionBackup.js +201 -0
  17. package/dist/backups/operations/comprehensiveBackup.d.ts +25 -0
  18. package/dist/backups/operations/comprehensiveBackup.js +238 -0
  19. package/dist/backups/schemas/bucketManifest.d.ts +93 -0
  20. package/dist/backups/schemas/bucketManifest.js +33 -0
  21. package/dist/backups/schemas/comprehensiveManifest.d.ts +108 -0
  22. package/dist/backups/schemas/comprehensiveManifest.js +32 -0
  23. package/dist/backups/tracking/centralizedTracking.d.ts +34 -0
  24. package/dist/backups/tracking/centralizedTracking.js +274 -0
  25. package/dist/cli/commands/configCommands.d.ts +8 -0
  26. package/dist/cli/commands/configCommands.js +166 -0
  27. package/dist/cli/commands/databaseCommands.d.ts +13 -0
  28. package/dist/cli/commands/databaseCommands.js +554 -0
  29. package/dist/cli/commands/functionCommands.d.ts +7 -0
  30. package/dist/cli/commands/functionCommands.js +330 -0
  31. package/dist/cli/commands/schemaCommands.d.ts +7 -0
  32. package/dist/cli/commands/schemaCommands.js +169 -0
  33. package/dist/cli/commands/storageCommands.d.ts +5 -0
  34. package/dist/cli/commands/storageCommands.js +143 -0
  35. package/dist/cli/commands/transferCommands.d.ts +5 -0
  36. package/dist/cli/commands/transferCommands.js +384 -0
  37. package/dist/collections/attributes.d.ts +13 -0
  38. package/dist/collections/attributes.js +1364 -0
  39. package/dist/collections/indexes.d.ts +12 -0
  40. package/dist/collections/indexes.js +217 -0
  41. package/dist/collections/methods.d.ts +19 -0
  42. package/dist/collections/methods.js +682 -0
  43. package/dist/collections/tableOperations.d.ts +86 -0
  44. package/dist/collections/tableOperations.js +434 -0
  45. package/dist/collections/transferOperations.d.ts +8 -0
  46. package/dist/collections/transferOperations.js +412 -0
  47. package/dist/collections/wipeOperations.d.ts +16 -0
  48. package/dist/collections/wipeOperations.js +233 -0
  49. package/dist/config/ConfigManager.d.ts +445 -0
  50. package/dist/config/ConfigManager.js +625 -0
  51. package/dist/config/configMigration.d.ts +87 -0
  52. package/dist/config/configMigration.js +390 -0
  53. package/dist/config/configValidation.d.ts +66 -0
  54. package/dist/config/configValidation.js +358 -0
  55. package/dist/config/index.d.ts +8 -0
  56. package/dist/config/index.js +7 -0
  57. package/dist/config/services/ConfigDiscoveryService.d.ts +126 -0
  58. package/dist/config/services/ConfigDiscoveryService.js +374 -0
  59. package/dist/config/services/ConfigLoaderService.d.ts +129 -0
  60. package/dist/config/services/ConfigLoaderService.js +540 -0
  61. package/dist/config/services/ConfigMergeService.d.ts +208 -0
  62. package/dist/config/services/ConfigMergeService.js +308 -0
  63. package/dist/config/services/ConfigValidationService.d.ts +214 -0
  64. package/dist/config/services/ConfigValidationService.js +310 -0
  65. package/dist/config/services/SessionAuthService.d.ts +225 -0
  66. package/dist/config/services/SessionAuthService.js +456 -0
  67. package/dist/config/services/__tests__/ConfigMergeService.test.d.ts +1 -0
  68. package/dist/config/services/__tests__/ConfigMergeService.test.js +271 -0
  69. package/dist/config/services/index.d.ts +13 -0
  70. package/dist/config/services/index.js +10 -0
  71. package/dist/config/yamlConfig.d.ts +722 -0
  72. package/dist/config/yamlConfig.js +702 -0
  73. package/dist/databases/methods.d.ts +6 -0
  74. package/dist/databases/methods.js +35 -0
  75. package/dist/databases/setup.d.ts +5 -0
  76. package/dist/databases/setup.js +45 -0
  77. package/dist/examples/yamlTerminologyExample.d.ts +42 -0
  78. package/dist/examples/yamlTerminologyExample.js +272 -0
  79. package/dist/functions/deployments.d.ts +4 -0
  80. package/dist/functions/deployments.js +146 -0
  81. package/dist/functions/fnConfigDiscovery.d.ts +3 -0
  82. package/dist/functions/fnConfigDiscovery.js +108 -0
  83. package/dist/functions/methods.d.ts +16 -0
  84. package/dist/functions/methods.js +162 -0
  85. package/dist/functions/pathResolution.d.ts +37 -0
  86. package/dist/functions/pathResolution.js +185 -0
  87. package/dist/functions/templates/count-docs-in-collection/README.md +54 -0
  88. package/dist/functions/templates/count-docs-in-collection/src/main.ts +159 -0
  89. package/dist/functions/templates/count-docs-in-collection/src/request.ts +9 -0
  90. package/dist/functions/templates/hono-typescript/README.md +286 -0
  91. package/dist/functions/templates/hono-typescript/src/adapters/request.ts +74 -0
  92. package/dist/functions/templates/hono-typescript/src/adapters/response.ts +106 -0
  93. package/dist/functions/templates/hono-typescript/src/app.ts +180 -0
  94. package/dist/functions/templates/hono-typescript/src/context.ts +103 -0
  95. package/dist/functions/templates/hono-typescript/src/index.ts +54 -0
  96. package/dist/functions/templates/hono-typescript/src/middleware/appwrite.ts +119 -0
  97. package/dist/functions/templates/typescript-node/README.md +32 -0
  98. package/dist/functions/templates/typescript-node/src/context.ts +103 -0
  99. package/dist/functions/templates/typescript-node/src/index.ts +29 -0
  100. package/dist/functions/templates/uv/README.md +31 -0
  101. package/dist/functions/templates/uv/pyproject.toml +30 -0
  102. package/dist/functions/templates/uv/src/__init__.py +0 -0
  103. package/dist/functions/templates/uv/src/context.py +125 -0
  104. package/dist/functions/templates/uv/src/index.py +46 -0
  105. package/dist/init.d.ts +2 -0
  106. package/dist/init.js +57 -0
  107. package/dist/interactiveCLI.d.ts +31 -0
  108. package/dist/interactiveCLI.js +898 -0
  109. package/dist/main.d.ts +2 -0
  110. package/dist/main.js +1172 -0
  111. package/dist/migrations/afterImportActions.d.ts +17 -0
  112. package/dist/migrations/afterImportActions.js +306 -0
  113. package/dist/migrations/appwriteToX.d.ts +211 -0
  114. package/dist/migrations/appwriteToX.js +491 -0
  115. package/dist/migrations/comprehensiveTransfer.d.ts +147 -0
  116. package/dist/migrations/comprehensiveTransfer.js +1317 -0
  117. package/dist/migrations/dataLoader.d.ts +753 -0
  118. package/dist/migrations/dataLoader.js +1250 -0
  119. package/dist/migrations/importController.d.ts +23 -0
  120. package/dist/migrations/importController.js +268 -0
  121. package/dist/migrations/importDataActions.d.ts +50 -0
  122. package/dist/migrations/importDataActions.js +230 -0
  123. package/dist/migrations/relationships.d.ts +29 -0
  124. package/dist/migrations/relationships.js +204 -0
  125. package/dist/migrations/services/DataTransformationService.d.ts +55 -0
  126. package/dist/migrations/services/DataTransformationService.js +158 -0
  127. package/dist/migrations/services/FileHandlerService.d.ts +75 -0
  128. package/dist/migrations/services/FileHandlerService.js +236 -0
  129. package/dist/migrations/services/ImportOrchestrator.d.ts +97 -0
  130. package/dist/migrations/services/ImportOrchestrator.js +485 -0
  131. package/dist/migrations/services/RateLimitManager.d.ts +138 -0
  132. package/dist/migrations/services/RateLimitManager.js +279 -0
  133. package/dist/migrations/services/RelationshipResolver.d.ts +120 -0
  134. package/dist/migrations/services/RelationshipResolver.js +332 -0
  135. package/dist/migrations/services/UserMappingService.d.ts +109 -0
  136. package/dist/migrations/services/UserMappingService.js +277 -0
  137. package/dist/migrations/services/ValidationService.d.ts +74 -0
  138. package/dist/migrations/services/ValidationService.js +260 -0
  139. package/dist/migrations/transfer.d.ts +26 -0
  140. package/dist/migrations/transfer.js +608 -0
  141. package/dist/migrations/yaml/YamlImportConfigLoader.d.ts +131 -0
  142. package/dist/migrations/yaml/YamlImportConfigLoader.js +383 -0
  143. package/dist/migrations/yaml/YamlImportIntegration.d.ts +93 -0
  144. package/dist/migrations/yaml/YamlImportIntegration.js +341 -0
  145. package/dist/migrations/yaml/generateImportSchemas.d.ts +30 -0
  146. package/dist/migrations/yaml/generateImportSchemas.js +1327 -0
  147. package/dist/schemas/authUser.d.ts +24 -0
  148. package/dist/schemas/authUser.js +17 -0
  149. package/dist/setup.d.ts +2 -0
  150. package/dist/setup.js +5 -0
  151. package/dist/setupCommands.d.ts +58 -0
  152. package/dist/setupCommands.js +490 -0
  153. package/dist/setupController.d.ts +9 -0
  154. package/dist/setupController.js +34 -0
  155. package/dist/shared/attributeMapper.d.ts +20 -0
  156. package/dist/shared/attributeMapper.js +203 -0
  157. package/dist/shared/backupMetadataSchema.d.ts +94 -0
  158. package/dist/shared/backupMetadataSchema.js +38 -0
  159. package/dist/shared/backupTracking.d.ts +18 -0
  160. package/dist/shared/backupTracking.js +176 -0
  161. package/dist/shared/confirmationDialogs.d.ts +75 -0
  162. package/dist/shared/confirmationDialogs.js +236 -0
  163. package/dist/shared/errorUtils.d.ts +54 -0
  164. package/dist/shared/errorUtils.js +95 -0
  165. package/dist/shared/functionManager.d.ts +48 -0
  166. package/dist/shared/functionManager.js +336 -0
  167. package/dist/shared/indexManager.d.ts +24 -0
  168. package/dist/shared/indexManager.js +151 -0
  169. package/dist/shared/jsonSchemaGenerator.d.ts +50 -0
  170. package/dist/shared/jsonSchemaGenerator.js +290 -0
  171. package/dist/shared/logging.d.ts +61 -0
  172. package/dist/shared/logging.js +116 -0
  173. package/dist/shared/messageFormatter.d.ts +39 -0
  174. package/dist/shared/messageFormatter.js +162 -0
  175. package/dist/shared/migrationHelpers.d.ts +61 -0
  176. package/dist/shared/migrationHelpers.js +145 -0
  177. package/dist/shared/operationLogger.d.ts +10 -0
  178. package/dist/shared/operationLogger.js +12 -0
  179. package/dist/shared/operationQueue.d.ts +40 -0
  180. package/dist/shared/operationQueue.js +311 -0
  181. package/dist/shared/operationsTable.d.ts +26 -0
  182. package/dist/shared/operationsTable.js +286 -0
  183. package/dist/shared/operationsTableSchema.d.ts +48 -0
  184. package/dist/shared/operationsTableSchema.js +35 -0
  185. package/dist/shared/progressManager.d.ts +62 -0
  186. package/dist/shared/progressManager.js +215 -0
  187. package/dist/shared/pydanticModelGenerator.d.ts +17 -0
  188. package/dist/shared/pydanticModelGenerator.js +615 -0
  189. package/dist/shared/relationshipExtractor.d.ts +56 -0
  190. package/dist/shared/relationshipExtractor.js +138 -0
  191. package/dist/shared/schemaGenerator.d.ts +40 -0
  192. package/dist/shared/schemaGenerator.js +556 -0
  193. package/dist/shared/selectionDialogs.d.ts +214 -0
  194. package/dist/shared/selectionDialogs.js +544 -0
  195. package/dist/storage/backupCompression.d.ts +20 -0
  196. package/dist/storage/backupCompression.js +67 -0
  197. package/dist/storage/methods.d.ts +32 -0
  198. package/dist/storage/methods.js +472 -0
  199. package/dist/storage/schemas.d.ts +842 -0
  200. package/dist/storage/schemas.js +175 -0
  201. package/dist/types.d.ts +4 -0
  202. package/dist/types.js +3 -0
  203. package/dist/users/methods.d.ts +16 -0
  204. package/dist/users/methods.js +277 -0
  205. package/dist/utils/ClientFactory.d.ts +87 -0
  206. package/dist/utils/ClientFactory.js +212 -0
  207. package/dist/utils/configDiscovery.d.ts +78 -0
  208. package/dist/utils/configDiscovery.js +472 -0
  209. package/dist/utils/configMigration.d.ts +1 -0
  210. package/dist/utils/configMigration.js +261 -0
  211. package/dist/utils/constantsGenerator.d.ts +31 -0
  212. package/dist/utils/constantsGenerator.js +321 -0
  213. package/dist/utils/dataConverters.d.ts +46 -0
  214. package/dist/utils/dataConverters.js +139 -0
  215. package/dist/utils/directoryUtils.d.ts +22 -0
  216. package/dist/utils/directoryUtils.js +59 -0
  217. package/dist/utils/getClientFromConfig.d.ts +39 -0
  218. package/dist/utils/getClientFromConfig.js +199 -0
  219. package/dist/utils/helperFunctions.d.ts +63 -0
  220. package/dist/utils/helperFunctions.js +156 -0
  221. package/dist/utils/index.d.ts +2 -0
  222. package/dist/utils/index.js +2 -0
  223. package/dist/utils/loadConfigs.d.ts +50 -0
  224. package/dist/utils/loadConfigs.js +358 -0
  225. package/dist/utils/pathResolvers.d.ts +53 -0
  226. package/dist/utils/pathResolvers.js +72 -0
  227. package/dist/utils/projectConfig.d.ts +119 -0
  228. package/dist/utils/projectConfig.js +171 -0
  229. package/dist/utils/retryFailedPromises.d.ts +2 -0
  230. package/dist/utils/retryFailedPromises.js +23 -0
  231. package/dist/utils/sessionAuth.d.ts +48 -0
  232. package/dist/utils/sessionAuth.js +164 -0
  233. package/dist/utils/setupFiles.d.ts +4 -0
  234. package/dist/utils/setupFiles.js +1192 -0
  235. package/dist/utils/typeGuards.d.ts +35 -0
  236. package/dist/utils/typeGuards.js +57 -0
  237. package/dist/utils/validationRules.d.ts +43 -0
  238. package/dist/utils/validationRules.js +42 -0
  239. package/dist/utils/versionDetection.d.ts +58 -0
  240. package/dist/utils/versionDetection.js +251 -0
  241. package/dist/utils/yamlConverter.d.ts +100 -0
  242. package/dist/utils/yamlConverter.js +428 -0
  243. package/dist/utils/yamlLoader.d.ts +70 -0
  244. package/dist/utils/yamlLoader.js +267 -0
  245. package/dist/utilsController.d.ts +106 -0
  246. package/dist/utilsController.js +863 -0
  247. package/package.json +75 -0
  248. package/scripts/copy-templates.ts +23 -0
  249. package/src/adapters/AdapterFactory.ts +510 -0
  250. package/src/adapters/DatabaseAdapter.ts +306 -0
  251. package/src/adapters/LegacyAdapter.ts +841 -0
  252. package/src/adapters/TablesDBAdapter.ts +773 -0
  253. package/src/adapters/index.ts +37 -0
  254. package/src/backups/operations/bucketBackup.ts +277 -0
  255. package/src/backups/operations/collectionBackup.ts +310 -0
  256. package/src/backups/operations/comprehensiveBackup.ts +342 -0
  257. package/src/backups/schemas/bucketManifest.ts +78 -0
  258. package/src/backups/schemas/comprehensiveManifest.ts +76 -0
  259. package/src/backups/tracking/centralizedTracking.ts +352 -0
  260. package/src/cli/commands/configCommands.ts +201 -0
  261. package/src/cli/commands/databaseCommands.ts +749 -0
  262. package/src/cli/commands/functionCommands.ts +418 -0
  263. package/src/cli/commands/schemaCommands.ts +200 -0
  264. package/src/cli/commands/storageCommands.ts +152 -0
  265. package/src/cli/commands/transferCommands.ts +457 -0
  266. package/src/collections/attributes.ts +2054 -0
  267. package/src/collections/attributes.ts.backup +1555 -0
  268. package/src/collections/indexes.ts +352 -0
  269. package/src/collections/methods.ts +745 -0
  270. package/src/collections/tableOperations.ts +506 -0
  271. package/src/collections/transferOperations.ts +590 -0
  272. package/src/collections/wipeOperations.ts +346 -0
  273. package/src/config/ConfigManager.ts +808 -0
  274. package/src/config/README.md +274 -0
  275. package/src/config/configMigration.ts +575 -0
  276. package/src/config/configValidation.ts +445 -0
  277. package/src/config/index.ts +10 -0
  278. package/src/config/services/ConfigDiscoveryService.ts +463 -0
  279. package/src/config/services/ConfigLoaderService.ts +740 -0
  280. package/src/config/services/ConfigMergeService.ts +388 -0
  281. package/src/config/services/ConfigValidationService.ts +394 -0
  282. package/src/config/services/SessionAuthService.ts +565 -0
  283. package/src/config/services/__tests__/ConfigMergeService.test.ts +351 -0
  284. package/src/config/services/index.ts +29 -0
  285. package/src/config/yamlConfig.ts +761 -0
  286. package/src/databases/methods.ts +49 -0
  287. package/src/databases/setup.ts +77 -0
  288. package/src/examples/yamlTerminologyExample.ts +346 -0
  289. package/src/functions/deployments.ts +220 -0
  290. package/src/functions/fnConfigDiscovery.ts +103 -0
  291. package/src/functions/methods.ts +271 -0
  292. package/src/functions/pathResolution.ts +227 -0
  293. package/src/functions/templates/count-docs-in-collection/README.md +54 -0
  294. package/src/functions/templates/count-docs-in-collection/src/main.ts +159 -0
  295. package/src/functions/templates/count-docs-in-collection/src/request.ts +9 -0
  296. package/src/functions/templates/hono-typescript/README.md +286 -0
  297. package/src/functions/templates/hono-typescript/src/adapters/request.ts +74 -0
  298. package/src/functions/templates/hono-typescript/src/adapters/response.ts +106 -0
  299. package/src/functions/templates/hono-typescript/src/app.ts +180 -0
  300. package/src/functions/templates/hono-typescript/src/context.ts +103 -0
  301. package/src/functions/templates/hono-typescript/src/index.ts +54 -0
  302. package/src/functions/templates/hono-typescript/src/middleware/appwrite.ts +119 -0
  303. package/src/functions/templates/typescript-node/README.md +32 -0
  304. package/src/functions/templates/typescript-node/src/context.ts +103 -0
  305. package/src/functions/templates/typescript-node/src/index.ts +29 -0
  306. package/src/functions/templates/uv/README.md +31 -0
  307. package/src/functions/templates/uv/pyproject.toml +30 -0
  308. package/src/functions/templates/uv/src/__init__.py +0 -0
  309. package/src/functions/templates/uv/src/context.py +125 -0
  310. package/src/functions/templates/uv/src/index.py +46 -0
  311. package/src/init.ts +62 -0
  312. package/src/interactiveCLI.ts +1136 -0
  313. package/src/main.ts +1661 -0
  314. package/src/migrations/afterImportActions.ts +580 -0
  315. package/src/migrations/appwriteToX.ts +664 -0
  316. package/src/migrations/comprehensiveTransfer.ts +2285 -0
  317. package/src/migrations/dataLoader.ts +1702 -0
  318. package/src/migrations/importController.ts +428 -0
  319. package/src/migrations/importDataActions.ts +315 -0
  320. package/src/migrations/relationships.ts +334 -0
  321. package/src/migrations/services/DataTransformationService.ts +196 -0
  322. package/src/migrations/services/FileHandlerService.ts +311 -0
  323. package/src/migrations/services/ImportOrchestrator.ts +666 -0
  324. package/src/migrations/services/RateLimitManager.ts +363 -0
  325. package/src/migrations/services/RelationshipResolver.ts +461 -0
  326. package/src/migrations/services/UserMappingService.ts +345 -0
  327. package/src/migrations/services/ValidationService.ts +349 -0
  328. package/src/migrations/transfer.ts +1068 -0
  329. package/src/migrations/yaml/YamlImportConfigLoader.ts +439 -0
  330. package/src/migrations/yaml/YamlImportIntegration.ts +446 -0
  331. package/src/migrations/yaml/generateImportSchemas.ts +1354 -0
  332. package/src/schemas/authUser.ts +23 -0
  333. package/src/setup.ts +8 -0
  334. package/src/setupCommands.ts +603 -0
  335. package/src/setupController.ts +43 -0
  336. package/src/shared/attributeMapper.ts +229 -0
  337. package/src/shared/backupMetadataSchema.ts +93 -0
  338. package/src/shared/backupTracking.ts +211 -0
  339. package/src/shared/confirmationDialogs.ts +327 -0
  340. package/src/shared/errorUtils.ts +110 -0
  341. package/src/shared/functionManager.ts +525 -0
  342. package/src/shared/indexManager.ts +254 -0
  343. package/src/shared/jsonSchemaGenerator.ts +383 -0
  344. package/src/shared/logging.ts +149 -0
  345. package/src/shared/messageFormatter.ts +208 -0
  346. package/src/shared/migrationHelpers.ts +232 -0
  347. package/src/shared/operationLogger.ts +20 -0
  348. package/src/shared/operationQueue.ts +377 -0
  349. package/src/shared/operationsTable.ts +338 -0
  350. package/src/shared/operationsTableSchema.ts +60 -0
  351. package/src/shared/progressManager.ts +278 -0
  352. package/src/shared/pydanticModelGenerator.ts +618 -0
  353. package/src/shared/relationshipExtractor.ts +214 -0
  354. package/src/shared/schemaGenerator.ts +644 -0
  355. package/src/shared/selectionDialogs.ts +749 -0
  356. package/src/storage/backupCompression.ts +88 -0
  357. package/src/storage/methods.ts +698 -0
  358. package/src/storage/schemas.ts +205 -0
  359. package/src/types/node-appwrite-tablesdb.d.ts +44 -0
  360. package/src/types.ts +9 -0
  361. package/src/users/methods.ts +359 -0
  362. package/src/utils/ClientFactory.ts +240 -0
  363. package/src/utils/configDiscovery.ts +557 -0
  364. package/src/utils/configMigration.ts +348 -0
  365. package/src/utils/constantsGenerator.ts +369 -0
  366. package/src/utils/dataConverters.ts +159 -0
  367. package/src/utils/directoryUtils.ts +61 -0
  368. package/src/utils/getClientFromConfig.ts +257 -0
  369. package/src/utils/helperFunctions.ts +228 -0
  370. package/src/utils/index.ts +2 -0
  371. package/src/utils/loadConfigs.ts +449 -0
  372. package/src/utils/pathResolvers.ts +81 -0
  373. package/src/utils/projectConfig.ts +299 -0
  374. package/src/utils/retryFailedPromises.ts +29 -0
  375. package/src/utils/sessionAuth.ts +230 -0
  376. package/src/utils/setupFiles.ts +1238 -0
  377. package/src/utils/typeGuards.ts +65 -0
  378. package/src/utils/validationRules.ts +88 -0
  379. package/src/utils/versionDetection.ts +292 -0
  380. package/src/utils/yamlConverter.ts +542 -0
  381. package/src/utils/yamlLoader.ts +371 -0
  382. package/src/utilsController.ts +1203 -0
  383. package/tests/README.md +497 -0
  384. package/tests/adapters/AdapterFactory.test.ts +277 -0
  385. package/tests/integration/syncOperations.test.ts +463 -0
  386. package/tests/jest.config.js +25 -0
  387. package/tests/migration/configMigration.test.ts +546 -0
  388. package/tests/setup.ts +62 -0
  389. package/tests/testUtils.ts +340 -0
  390. package/tests/utils/loadConfigs.test.ts +350 -0
  391. package/tests/validation/configValidation.test.ts +412 -0
  392. package/tsconfig.json +44 -0
@@ -0,0 +1,1250 @@
1
+ import { AttributeMappingsSchema, CollectionCreateSchema, importDefSchema, } from "@njdamstra/appwrite-utils";
2
+ import path from "path";
3
+ import fs from "fs";
4
+ import { convertObjectByAttributeMappings } from "../utils/dataConverters.js";
5
+ import { z } from "zod";
6
+ import { checkForCollection } from "../collections/methods.js";
7
+ import { ID, Users } from "node-appwrite";
8
+ import { logger } from "../shared/logging.js";
9
+ import { findOrCreateOperation, updateOperation } from "../shared/migrationHelpers.js";
10
+ import { AuthUserCreateSchema } from "../schemas/authUser.js";
11
+ import { LegacyAdapter } from "../adapters/LegacyAdapter.js";
12
+ import { UsersController } from "../users/methods.js";
13
+ import { finalizeByAttributeMap } from "../utils/helperFunctions.js";
14
+ import { isEmpty } from "es-toolkit/compat";
15
+ import { MessageFormatter } from "../shared/messageFormatter.js";
16
+ // Define a schema for the structure of collection import data using Zod for validation
17
+ export const CollectionImportDataSchema = z.object({
18
+ // Optional collection creation schema
19
+ collection: CollectionCreateSchema.optional(),
20
+ // Array of data objects each containing rawData, finalData, context, and an import definition
21
+ data: z.array(z.object({
22
+ rawData: z.any(), // The initial raw data
23
+ finalData: z.any(), // The transformed data ready for import
24
+ context: z.any(), // Additional context for the data transformation
25
+ importDef: importDefSchema.optional(), // The import definition schema
26
+ })),
27
+ });
28
+ // DataLoader class to handle the loading of data into collections
29
+ export class DataLoader {
30
+ // Private member variables to hold configuration and state
31
+ appwriteFolderPath;
32
+ importDataActions;
33
+ database;
34
+ usersController;
35
+ config;
36
+ // Map to hold the import data for each collection by name
37
+ importMap = new Map();
38
+ // Map to track old to new ID mappings for each collection, if applicable
39
+ oldIdToNewIdPerCollectionMap = new Map();
40
+ // Map to hold the import operation ID for each collection
41
+ collectionImportOperations = new Map();
42
+ // Map to hold the merged user map for relationship resolution
43
+ // Will hold an array of the old user ID's that are mapped to the same new user ID
44
+ // For example, if there are two users with the same email, they will both be mapped to the same new user ID
45
+ // Prevents duplicate users with the other two maps below it and allows me to keep the old ID's
46
+ mergedUserMap = new Map();
47
+ // Maps to hold email and phone to user ID mappings for unique-ness in User Accounts
48
+ emailToUserIdMap = new Map();
49
+ phoneToUserIdMap = new Map();
50
+ userIdSet = new Set();
51
+ userExistsMap = new Map();
52
+ shouldWriteFile = false;
53
+ // Constructor to initialize the DataLoader with necessary configurations
54
+ constructor(appwriteFolderPath, importDataActions, database, config, shouldWriteFile) {
55
+ this.appwriteFolderPath = appwriteFolderPath;
56
+ this.importDataActions = importDataActions;
57
+ this.database = database;
58
+ this.usersController = new UsersController(config, database);
59
+ this.config = config;
60
+ this.shouldWriteFile = shouldWriteFile || false;
61
+ }
62
+ // Helper method to generate a consistent key for collections
63
+ getCollectionKey(name) {
64
+ return name.toLowerCase().replace(" ", "");
65
+ }
66
+ /**
67
+ * Merges two objects by updating the source object with the target object's values.
68
+ * It iterates through the target object's keys and updates the source object if:
69
+ * - The source object has the key.
70
+ * - The target object's value for that key is not null, undefined, or an empty string.
71
+ * - If the target object has an array value, it concatenates the values and removes duplicates.
72
+ *
73
+ * @param source - The source object to be updated.
74
+ * @param target - The target object with values to update the source object.
75
+ * @returns The updated source object.
76
+ */
77
+ mergeObjects(source, update) {
78
+ // Create a new object to hold the merged result
79
+ const result = { ...source };
80
+ // Loop through the keys of the object we care about
81
+ for (const [key, value] of Object.entries(source)) {
82
+ // Check if the key exists in the target object
83
+ if (!Object.hasOwn(update, key)) {
84
+ // If the key doesn't exist, we can just skip it like bad cheese
85
+ continue;
86
+ }
87
+ if (update[key] === value) {
88
+ continue;
89
+ }
90
+ // If the value ain't here, we can just do whatever man
91
+ if (value === undefined || value === null || value === "") {
92
+ // If the update key is defined
93
+ if (update[key] !== undefined &&
94
+ update[key] !== null &&
95
+ update[key] !== "") {
96
+ // might as well use it eh?
97
+ result[key] = update[key];
98
+ }
99
+ // ELSE if the value is an array, because it would then not be === to those things above
100
+ }
101
+ else if (Array.isArray(value)) {
102
+ // Get the update value
103
+ const updateValue = update[key];
104
+ // If the update value is an array, concatenate and remove duplicates
105
+ // and poopy data
106
+ if (Array.isArray(updateValue)) {
107
+ result[key] = [...new Set([...value, ...updateValue])].filter((item) => item !== null && item !== undefined && item !== "");
108
+ }
109
+ else {
110
+ // If the update value is not an array, just use it
111
+ result[key] = [...value, updateValue].filter((item) => item !== null && item !== undefined && item !== "");
112
+ }
113
+ }
114
+ else if (typeof value === "object" && !Array.isArray(value)) {
115
+ // If the value is an object, we need to merge it
116
+ if (typeof update[key] === "object" && !Array.isArray(update[key])) {
117
+ result[key] = this.mergeObjects(value, update[key]);
118
+ }
119
+ }
120
+ else {
121
+ // Finally, the source value is defined, and not an array, so we don't care about the update value
122
+ continue;
123
+ }
124
+ }
125
+ // Because the objects should technically always be validated FIRST, we can assume the update keys are also defined on the source object
126
+ for (const [key, value] of Object.entries(update)) {
127
+ if (value === undefined || value === null || value === "") {
128
+ continue;
129
+ }
130
+ else if (!Object.hasOwn(source, key)) {
131
+ result[key] = value;
132
+ }
133
+ else if (typeof source[key] === "object" &&
134
+ typeof value === "object" &&
135
+ !Array.isArray(source[key]) &&
136
+ !Array.isArray(value)) {
137
+ result[key] = this.mergeObjects(source[key], value);
138
+ }
139
+ else if (Array.isArray(source[key]) && Array.isArray(value)) {
140
+ result[key] = [...new Set([...source[key], ...value])].filter((item) => item !== null && item !== undefined && item !== "");
141
+ }
142
+ else if (source[key] === undefined ||
143
+ source[key] === null ||
144
+ source[key] === "") {
145
+ result[key] = value;
146
+ }
147
+ }
148
+ return result;
149
+ }
150
+ // Method to load data from a file specified in the import definition
151
+ loadData(importDef) {
152
+ // Simply join appwriteFolderPath with the importDef.filePath
153
+ const filePath = path.resolve(this.appwriteFolderPath, importDef.filePath);
154
+ MessageFormatter.info(`Loading data from: ${filePath}`, { prefix: "Data" });
155
+ if (!fs.existsSync(filePath)) {
156
+ MessageFormatter.error(`File not found: ${filePath}`, undefined, { prefix: "Data" });
157
+ return [];
158
+ }
159
+ // Read the file and parse the JSON data
160
+ const rawData = fs.readFileSync(filePath, "utf8");
161
+ const parsedData = importDef.basePath
162
+ ? JSON.parse(rawData)[importDef.basePath]
163
+ : JSON.parse(rawData);
164
+ MessageFormatter.success(`Loaded ${parsedData?.length || 0} items from ${filePath}`, { prefix: "Data" });
165
+ return parsedData;
166
+ }
167
+ // Helper method to check if a new ID already exists in the old-to-new ID map
168
+ checkMapValuesForId(newId, collectionName) {
169
+ const oldIdMap = this.oldIdToNewIdPerCollectionMap.get(collectionName);
170
+ for (const [key, value] of oldIdMap?.entries() || []) {
171
+ if (value === newId) {
172
+ return key;
173
+ }
174
+ }
175
+ return false;
176
+ }
177
+ // Method to generate a unique ID that doesn't conflict with existing IDs
178
+ getTrueUniqueId(collectionName) {
179
+ let newId = ID.unique();
180
+ let condition = this.checkMapValuesForId(newId, collectionName) ||
181
+ this.userExistsMap.has(newId) ||
182
+ this.userIdSet.has(newId) ||
183
+ this.importMap
184
+ .get(this.getCollectionKey("users"))
185
+ ?.data.some((user) => user.finalData.docId === newId || user.finalData.userId === newId);
186
+ while (condition) {
187
+ newId = ID.unique();
188
+ condition =
189
+ this.checkMapValuesForId(newId, collectionName) ||
190
+ this.userExistsMap.has(newId) ||
191
+ this.userIdSet.has(newId) ||
192
+ this.importMap
193
+ .get(this.getCollectionKey("users"))
194
+ ?.data.some((user) => user.finalData.docId === newId || user.finalData.userId === newId);
195
+ }
196
+ return newId;
197
+ }
198
+ // Method to create a context object for data transformation
199
+ createContext(db, collection, item, docId) {
200
+ return {
201
+ ...item, // Spread the item data for easy access to its properties
202
+ dbId: db.$id,
203
+ dbName: db.name,
204
+ collId: collection.$id,
205
+ collName: collection.name,
206
+ docId: docId,
207
+ createdDoc: {}, // Initially null, to be updated when the document is created
208
+ };
209
+ }
210
+ /**
211
+ * Transforms the given item based on the provided attribute mappings.
212
+ * This method applies conversion rules to the item's attributes as defined in the attribute mappings.
213
+ *
214
+ * @param item - The item to be transformed.
215
+ * @param attributeMappings - The mappings that define how each attribute should be transformed.
216
+ * @returns The transformed item.
217
+ */
218
+ transformData(item, attributeMappings) {
219
+ // Convert the item using the attribute mappings provided
220
+ const convertedItem = convertObjectByAttributeMappings(item, attributeMappings);
221
+ // Run additional converter functions on the converted item, if any
222
+ return this.importDataActions.runConverterFunctions(convertedItem, attributeMappings);
223
+ }
224
+ async setupMaps(dbId) {
225
+ // Initialize the users collection in the import map
226
+ this.importMap.set(this.getCollectionKey("users"), {
227
+ data: [],
228
+ });
229
+ for (const db of this.config.databases) {
230
+ if (db.$id !== dbId) {
231
+ continue;
232
+ }
233
+ if (!this.config.collections) {
234
+ continue;
235
+ }
236
+ for (let index = 0; index < this.config.collections.length; index++) {
237
+ const collectionConfig = this.config.collections[index];
238
+ let collection = CollectionCreateSchema.parse(collectionConfig);
239
+ // Check if the collection exists in the database
240
+ const collectionExists = await checkForCollection(this.database, db.$id, collection);
241
+ if (!collectionExists) {
242
+ logger.error(`No collection found for ${collection.name}`);
243
+ continue;
244
+ }
245
+ else if (!collection.name) {
246
+ logger.error(`Collection ${collection.name} has no name`);
247
+ continue;
248
+ }
249
+ // Update the collection ID with the existing one
250
+ collectionConfig.$id = collectionExists.$id;
251
+ collection.$id = collectionExists.$id;
252
+ this.config.collections[index] = collectionConfig;
253
+ // Find or create an import operation for the collection
254
+ const adapter = new LegacyAdapter(this.database.client);
255
+ const collectionImportOperation = await findOrCreateOperation(adapter, dbId, "importData", collection.$id);
256
+ // Store the operation ID in the map
257
+ this.collectionImportOperations.set(this.getCollectionKey(collection.name), collectionImportOperation.$id);
258
+ // Initialize the collection in the import map
259
+ this.importMap.set(this.getCollectionKey(collection.name), {
260
+ collection: collection,
261
+ data: [],
262
+ });
263
+ }
264
+ }
265
+ }
266
+ async getAllUsers() {
267
+ const users = new UsersController(this.config, this.database);
268
+ const allUsers = await users.getAllUsers();
269
+ // Iterate over the users and setup our maps ahead of time for email and phone
270
+ for (const user of allUsers) {
271
+ if (user.email) {
272
+ this.emailToUserIdMap.set(user.email.toLowerCase(), user.$id);
273
+ }
274
+ if (user.phone) {
275
+ this.phoneToUserIdMap.set(user.phone, user.$id);
276
+ }
277
+ this.userExistsMap.set(user.$id, true);
278
+ this.userIdSet.add(user.$id);
279
+ let importData = this.importMap.get(this.getCollectionKey("users"));
280
+ if (!importData) {
281
+ importData = {
282
+ data: [],
283
+ };
284
+ }
285
+ importData.data.push({
286
+ finalData: {
287
+ ...user,
288
+ email: user.email?.toLowerCase(),
289
+ userId: user.$id,
290
+ docId: user.$id,
291
+ },
292
+ context: {
293
+ ...user,
294
+ email: user.email?.toLowerCase(),
295
+ userId: user.$id,
296
+ docId: user.$id,
297
+ },
298
+ rawData: user,
299
+ });
300
+ this.importMap.set(this.getCollectionKey("users"), importData);
301
+ }
302
+ return allUsers;
303
+ }
304
+ // Main method to start the data loading process for a given database ID
305
+ async start(dbId) {
306
+ MessageFormatter.divider();
307
+ MessageFormatter.info(`Starting data setup for database: ${dbId}`, { prefix: "Data" });
308
+ MessageFormatter.divider();
309
+ await this.setupMaps(dbId);
310
+ const allUsers = await this.getAllUsers();
311
+ MessageFormatter.info(`Fetched ${allUsers.length} users, waiting a few seconds to let the program catch up...`, { prefix: "Data" });
312
+ await new Promise((resolve) => setTimeout(resolve, 5000));
313
+ // Iterate over the configured databases to find the matching one
314
+ for (const db of this.config.databases) {
315
+ if (db.$id !== dbId) {
316
+ continue;
317
+ }
318
+ if (!this.config.collections) {
319
+ continue;
320
+ }
321
+ // Iterate over the configured collections to process each
322
+ for (const collectionConfig of this.config.collections) {
323
+ const collection = collectionConfig;
324
+ // Determine if this is the users collection
325
+ let isUsersCollection = this.getCollectionKey(this.config.usersCollectionName) ===
326
+ this.getCollectionKey(collection.name);
327
+ const collectionDefs = collection.importDefs;
328
+ if (!collectionDefs || !collectionDefs.length) {
329
+ continue;
330
+ }
331
+ // Process create and update definitions for the collection
332
+ const createDefs = collection.importDefs.filter((def) => def.type === "create" || !def.type);
333
+ const updateDefs = collection.importDefs.filter((def) => def.type === "update");
334
+ for (const createDef of createDefs) {
335
+ if (!isUsersCollection || !createDef.createUsers) {
336
+ await this.prepareCreateData(db, collection, createDef);
337
+ }
338
+ else {
339
+ // Special handling for users collection if needed
340
+ await this.prepareUserCollectionCreateData(db, collection, createDef);
341
+ }
342
+ }
343
+ for (const updateDef of updateDefs) {
344
+ if (!this.importMap.has(this.getCollectionKey(collection.name))) {
345
+ logger.error(`No data found for collection ${collection.name} for updateDef but it says it's supposed to have one...`);
346
+ continue;
347
+ }
348
+ // Prepare the update data for the collection
349
+ this.prepareUpdateData(db, collection, updateDef);
350
+ }
351
+ }
352
+ MessageFormatter.info("Running update references", { prefix: "Data" });
353
+ // this.dealWithMergedUsers();
354
+ this.updateOldReferencesForNew();
355
+ MessageFormatter.success("Done running update references", { prefix: "Data" });
356
+ }
357
+ // for (const collection of this.config.collections) {
358
+ // this.resolveDataItemRelationships(collection);
359
+ // }
360
+ MessageFormatter.divider();
361
+ MessageFormatter.success(`Data setup for database: ${dbId} completed`, { prefix: "Data" });
362
+ MessageFormatter.divider();
363
+ if (this.shouldWriteFile) {
364
+ this.writeMapsToJsonFile();
365
+ }
366
+ }
367
+ /**
368
+ * Deals with merged users by iterating through all collections in the configuration.
369
+ * We have merged users if there are duplicate emails or phones in the import data.
370
+ * This function will iterate through all collections that are the same name as the
371
+ * users collection and pull out their primaryKeyField's. It will then loop through
372
+ * each collection and find any documents that have a
373
+ *
374
+ * @return {void} This function does not return anything.
375
+ */
376
+ // dealWithMergedUsers() {
377
+ // const usersCollectionKey = this.getCollectionKey(
378
+ // this.config.usersCollectionName
379
+ // );
380
+ // const usersCollectionData = this.importMap.get(usersCollectionKey);
381
+ // if (!this.config.collections) {
382
+ // console.log("No collections found in configuration.");
383
+ // return;
384
+ // }
385
+ // let needsUpdate = false;
386
+ // let numUpdates = 0;
387
+ // for (const collectionConfig of this.config.collections) {
388
+ // const collectionKey = this.getCollectionKey(collectionConfig.name);
389
+ // const collectionData = this.importMap.get(collectionKey);
390
+ // const collectionImportDefs = collectionConfig.importDefs;
391
+ // const collectionIdMappings = collectionImportDefs
392
+ // .map((importDef) => importDef.idMappings)
393
+ // .flat()
394
+ // .filter((idMapping) => idMapping !== undefined && idMapping !== null);
395
+ // if (!collectionData || !collectionData.data) continue;
396
+ // for (const dataItem of collectionData.data) {
397
+ // for (const idMapping of collectionIdMappings) {
398
+ // // We know it's the users collection here
399
+ // if (this.getCollectionKey(idMapping.targetCollection) === usersCollectionKey) {
400
+ // const targetFieldKey = idMapping.targetFieldToMatch || idMapping.targetField;
401
+ // if (targetFieldKey === )
402
+ // const targetValue = dataItem.finalData[targetFieldKey];
403
+ // const targetCollectionData = this.importMap.get(this.getCollectionKey(idMapping.targetCollection));
404
+ // if (!targetCollectionData || !targetCollectionData.data) continue;
405
+ // const foundData = targetCollectionData.data.filter(({ context }) => {
406
+ // const targetValue = context[targetFieldKey];
407
+ // const isMatch = `${targetValue}` === `${valueToMatch}`;
408
+ // return isMatch && targetValue !== undefined && targetValue !== null;
409
+ // });
410
+ // }
411
+ // }
412
+ // }
413
+ // }
414
+ // }
415
+ /**
416
+ * Gets the value to match for a given key in the final data or context.
417
+ * @param finalData - The final data object.
418
+ * @param context - The context object.
419
+ * @param key - The key to get the value for.
420
+ * @returns The value to match for from finalData or Context
421
+ */
422
+ getValueFromData(finalData, context, key) {
423
+ if (context[key] !== undefined &&
424
+ context[key] !== null &&
425
+ context[key] !== "") {
426
+ return context[key];
427
+ }
428
+ return finalData[key];
429
+ }
430
+ updateOldReferencesForNew() {
431
+ if (!this.config.collections) {
432
+ return;
433
+ }
434
+ for (const collectionConfig of this.config.collections) {
435
+ const collectionKey = this.getCollectionKey(collectionConfig.name);
436
+ const collectionData = this.importMap.get(collectionKey);
437
+ if (!collectionData || !collectionData.data)
438
+ continue;
439
+ MessageFormatter.processing(`Updating references for collection: ${collectionConfig.name}`, { prefix: "Data" });
440
+ let needsUpdate = false;
441
+ // Iterate over each data item in the current collection
442
+ for (let i = 0; i < collectionData.data.length; i++) {
443
+ if (collectionConfig.importDefs) {
444
+ for (const importDef of collectionConfig.importDefs) {
445
+ if (importDef.idMappings) {
446
+ for (const idMapping of importDef.idMappings) {
447
+ const targetCollectionKey = this.getCollectionKey(idMapping.targetCollection);
448
+ const fieldToSetKey = idMapping.fieldToSet || idMapping.sourceField;
449
+ const targetFieldKey = idMapping.targetFieldToMatch || idMapping.targetField;
450
+ const sourceValue = this.getValueFromData(collectionData.data[i].finalData, collectionData.data[i].context, idMapping.sourceField);
451
+ // Skip if value to match is missing or empty
452
+ if (!sourceValue ||
453
+ isEmpty(sourceValue) ||
454
+ sourceValue === null)
455
+ continue;
456
+ const isFieldToSetArray = collectionConfig.attributes.find((attribute) => attribute.key === fieldToSetKey)?.array;
457
+ const targetCollectionData = this.importMap.get(targetCollectionKey);
458
+ if (!targetCollectionData || !targetCollectionData.data)
459
+ continue;
460
+ // Handle cases where sourceValue is an array
461
+ const sourceValues = Array.isArray(sourceValue)
462
+ ? sourceValue.map((sourceValue) => `${sourceValue}`)
463
+ : [`${sourceValue}`];
464
+ let newData = [];
465
+ for (const valueToMatch of sourceValues) {
466
+ // Find matching data in the target collection
467
+ const foundData = targetCollectionData.data.filter(({ context, finalData }) => {
468
+ const targetValue = this.getValueFromData(finalData, context, targetFieldKey);
469
+ const isMatch = `${targetValue}` === `${valueToMatch}`;
470
+ // Ensure the targetValue is defined and not null
471
+ return (isMatch &&
472
+ targetValue !== undefined &&
473
+ targetValue !== null);
474
+ });
475
+ if (foundData.length) {
476
+ newData.push(...foundData.map((data) => {
477
+ const newValue = this.getValueFromData(data.finalData, data.context, idMapping.targetField);
478
+ return newValue;
479
+ }));
480
+ }
481
+ else {
482
+ logger.info(`No data found for collection: ${targetCollectionKey} with value: ${valueToMatch} for field: ${fieldToSetKey} -- idMapping: ${JSON.stringify(idMapping, null, 2)}`);
483
+ }
484
+ continue;
485
+ }
486
+ const getCurrentDataFiltered = (currentData) => {
487
+ if (Array.isArray(currentData.finalData[fieldToSetKey])) {
488
+ return currentData.finalData[fieldToSetKey].filter((data) => !sourceValues.includes(`${data}`));
489
+ }
490
+ return currentData.finalData[fieldToSetKey];
491
+ };
492
+ // Get the current data to be updated
493
+ const currentDataFiltered = getCurrentDataFiltered(collectionData.data[i]);
494
+ if (newData.length) {
495
+ needsUpdate = true;
496
+ // Handle cases where current data is an array
497
+ if (isFieldToSetArray) {
498
+ if (!currentDataFiltered) {
499
+ // Set new data if current data is undefined
500
+ collectionData.data[i].finalData[fieldToSetKey] =
501
+ Array.isArray(newData) ? newData : [newData];
502
+ }
503
+ else {
504
+ if (Array.isArray(currentDataFiltered)) {
505
+ // Convert current data to array and merge if new data is non-empty array
506
+ collectionData.data[i].finalData[fieldToSetKey] = [
507
+ ...new Set([...currentDataFiltered, ...newData].filter((value) => value !== null &&
508
+ value !== undefined &&
509
+ value !== "")),
510
+ ];
511
+ }
512
+ else {
513
+ // Merge arrays if new data is non-empty array and filter for uniqueness
514
+ collectionData.data[i].finalData[fieldToSetKey] = [
515
+ ...new Set([
516
+ ...(Array.isArray(currentDataFiltered)
517
+ ? currentDataFiltered
518
+ : [currentDataFiltered]),
519
+ ...newData,
520
+ ].filter((value) => value !== null &&
521
+ value !== undefined &&
522
+ value !== "" &&
523
+ !sourceValues.includes(`${value}`))),
524
+ ];
525
+ }
526
+ }
527
+ }
528
+ else {
529
+ if (!currentDataFiltered) {
530
+ // Set new data if current data is undefined
531
+ collectionData.data[i].finalData[fieldToSetKey] =
532
+ Array.isArray(newData) ? newData[0] : newData;
533
+ }
534
+ else if (Array.isArray(newData) && newData.length > 0) {
535
+ // Convert current data to array and merge if new data is non-empty array, then filter for uniqueness
536
+ // and take the first value, because it's an array and the attribute is not an array
537
+ collectionData.data[i].finalData[fieldToSetKey] = [
538
+ ...new Set([currentDataFiltered, ...newData].filter((value) => value !== null &&
539
+ value !== undefined &&
540
+ value !== "" &&
541
+ !sourceValues.includes(`${value}`))),
542
+ ].slice(0, 1)[0];
543
+ }
544
+ else if (!Array.isArray(newData) &&
545
+ newData !== undefined) {
546
+ // Simply update the field if new data is not an array and defined
547
+ collectionData.data[i].finalData[fieldToSetKey] = newData;
548
+ }
549
+ }
550
+ }
551
+ }
552
+ }
553
+ }
554
+ }
555
+ }
556
+ // Update the import map if any changes were made
557
+ if (needsUpdate) {
558
+ this.importMap.set(collectionKey, collectionData);
559
+ }
560
+ }
561
+ }
562
+ writeMapsToJsonFile() {
563
+ const outputDir = path.resolve(process.cwd(), "zlogs");
564
+ // Ensure the logs directory exists
565
+ if (!fs.existsSync(outputDir)) {
566
+ fs.mkdirSync(outputDir);
567
+ }
568
+ // Helper function to write data to a file
569
+ const writeToFile = (fileName, data) => {
570
+ const outputFile = path.join(outputDir, fileName);
571
+ fs.writeFile(outputFile, JSON.stringify(data, null, 2), "utf8", (err) => {
572
+ if (err) {
573
+ MessageFormatter.error(`Error writing data to ${fileName}`, err instanceof Error ? err : new Error(String(err)), { prefix: "Data" });
574
+ return;
575
+ }
576
+ MessageFormatter.success(`Data successfully written to ${fileName}`, { prefix: "Data" });
577
+ });
578
+ };
579
+ // Convert Maps to arrays of entries for serialization
580
+ const oldIdToNewIdPerCollectionMap = Array.from(this.oldIdToNewIdPerCollectionMap.entries()).map(([key, value]) => {
581
+ return {
582
+ collection: key,
583
+ data: Array.from(value.entries()),
584
+ };
585
+ });
586
+ const mergedUserMap = Array.from(this.mergedUserMap.entries());
587
+ // Write each part to a separate file
588
+ writeToFile("oldIdToNewIdPerCollectionMap.json", oldIdToNewIdPerCollectionMap);
589
+ writeToFile("mergedUserMap.json", mergedUserMap);
590
+ // Write each collection's data to a separate file
591
+ this.importMap.forEach((value, key) => {
592
+ const data = {
593
+ collection: key,
594
+ data: value.data.map((item) => {
595
+ return {
596
+ finalData: item.finalData,
597
+ context: item.context,
598
+ };
599
+ }),
600
+ };
601
+ writeToFile(`${key}.json`, data);
602
+ });
603
+ }
604
+ /**
605
+ * Prepares user data by checking for duplicates based on email or phone, adding to a duplicate map if found,
606
+ * and then returning the transformed item without user-specific keys.
607
+ *
608
+ * @param item - The raw item to be processed.
609
+ * @param attributeMappings - The attribute mappings for the item.
610
+ * @returns The transformed item with user-specific keys removed.
611
+ */
612
+ prepareUserData(item, attributeMappings, primaryKeyField, newId) {
613
+ if (this.userIdSet.has(newId) ||
614
+ this.userExistsMap.has(newId) ||
615
+ Array.from(this.emailToUserIdMap.values()).includes(newId) ||
616
+ Array.from(this.phoneToUserIdMap.values()).includes(newId)) {
617
+ newId = this.getTrueUniqueId(this.getCollectionKey("users"));
618
+ }
619
+ let transformedItem = this.transformData(item, attributeMappings);
620
+ let userData = AuthUserCreateSchema.safeParse(transformedItem);
621
+ if (userData.data?.email) {
622
+ userData.data.email = userData.data.email.toLowerCase();
623
+ }
624
+ if (!userData.success || !(userData.data.email || userData.data.phone)) {
625
+ logger.error(`Invalid user data: ${JSON.stringify(userData.error?.issues, undefined, 2)} or missing email/phone`);
626
+ const userKeys = ["email", "phone", "name", "labels", "prefs"];
627
+ userKeys.forEach((key) => {
628
+ if (transformedItem.hasOwnProperty(key)) {
629
+ delete transformedItem[key];
630
+ }
631
+ });
632
+ return {
633
+ transformedItem,
634
+ existingId: undefined,
635
+ userData: {
636
+ rawData: item,
637
+ finalData: transformedItem,
638
+ },
639
+ };
640
+ }
641
+ const email = userData.data.email?.toLowerCase();
642
+ const phone = userData.data.phone;
643
+ let existingId;
644
+ // Check for duplicate email and phone
645
+ if (email && this.emailToUserIdMap.has(email)) {
646
+ existingId = this.emailToUserIdMap.get(email);
647
+ if (phone && !this.phoneToUserIdMap.has(phone)) {
648
+ this.phoneToUserIdMap.set(phone, newId);
649
+ }
650
+ }
651
+ else if (phone && this.phoneToUserIdMap.has(phone)) {
652
+ existingId = this.phoneToUserIdMap.get(phone);
653
+ if (email && !this.emailToUserIdMap.has(email)) {
654
+ this.emailToUserIdMap.set(email, newId);
655
+ }
656
+ }
657
+ else {
658
+ if (email)
659
+ this.emailToUserIdMap.set(email, newId);
660
+ if (phone)
661
+ this.phoneToUserIdMap.set(phone, newId);
662
+ }
663
+ if (existingId) {
664
+ userData.data.userId = existingId;
665
+ const mergedUsers = this.mergedUserMap.get(existingId) || [];
666
+ mergedUsers.push(`${item[primaryKeyField]}`);
667
+ this.mergedUserMap.set(existingId, mergedUsers);
668
+ const userFound = this.importMap
669
+ .get(this.getCollectionKey("users"))
670
+ ?.data.find((userDataExisting) => {
671
+ let userIdToMatch;
672
+ if (userDataExisting?.finalData?.userId) {
673
+ userIdToMatch = userDataExisting?.finalData?.userId;
674
+ }
675
+ else if (userDataExisting?.finalData?.docId) {
676
+ userIdToMatch = userDataExisting?.finalData?.docId;
677
+ }
678
+ else if (userDataExisting?.context?.userId) {
679
+ userIdToMatch = userDataExisting.context.userId;
680
+ }
681
+ else if (userDataExisting?.context?.docId) {
682
+ userIdToMatch = userDataExisting.context.docId;
683
+ }
684
+ return userIdToMatch === existingId;
685
+ });
686
+ if (userFound) {
687
+ userFound.finalData.userId = existingId;
688
+ userFound.finalData.docId = existingId;
689
+ this.userIdSet.add(existingId);
690
+ transformedItem = {
691
+ ...transformedItem,
692
+ userId: existingId,
693
+ docId: existingId,
694
+ };
695
+ }
696
+ const userKeys = ["email", "phone", "name", "labels", "prefs"];
697
+ userKeys.forEach((key) => {
698
+ if (transformedItem.hasOwnProperty(key)) {
699
+ delete transformedItem[key];
700
+ }
701
+ });
702
+ return {
703
+ transformedItem,
704
+ existingId,
705
+ userData: {
706
+ rawData: userFound?.rawData,
707
+ finalData: userFound?.finalData,
708
+ },
709
+ };
710
+ }
711
+ else {
712
+ existingId = newId;
713
+ userData.data.userId = existingId;
714
+ }
715
+ const userKeys = ["email", "phone", "name", "labels", "prefs"];
716
+ userKeys.forEach((key) => {
717
+ if (transformedItem.hasOwnProperty(key)) {
718
+ delete transformedItem[key];
719
+ }
720
+ });
721
+ const usersMap = this.importMap.get(this.getCollectionKey("users"));
722
+ const userDataToAdd = {
723
+ rawData: item,
724
+ finalData: userData.data,
725
+ context: {},
726
+ };
727
+ this.importMap.set(this.getCollectionKey("users"), {
728
+ data: [...(usersMap?.data || []), userDataToAdd],
729
+ });
730
+ this.userIdSet.add(existingId);
731
+ return {
732
+ transformedItem,
733
+ existingId,
734
+ userData: userDataToAdd,
735
+ };
736
+ }
737
+ /**
738
+ * Prepares the data for creating user collection documents.
739
+ * This involves loading the data, transforming it according to the import definition,
740
+ * and handling the creation of new unique IDs for each item.
741
+ *
742
+ * @param db - The database configuration.
743
+ * @param collection - The collection configuration.
744
+ * @param importDef - The import definition containing the attribute mappings and other relevant info.
745
+ */
746
+ async prepareUserCollectionCreateData(db, collection, importDef) {
747
+ // Load the raw data based on the import definition
748
+ const rawData = this.loadData(importDef);
749
+ let operationId = this.collectionImportOperations.get(this.getCollectionKey(collection.name));
750
+ // Initialize a new map for old ID to new ID mappings
751
+ const oldIdToNewIdMap = new Map();
752
+ // Retrieve or initialize the collection-specific old ID to new ID map
753
+ const collectionOldIdToNewIdMap = this.oldIdToNewIdPerCollectionMap.get(this.getCollectionKey(collection.name)) ||
754
+ this.oldIdToNewIdPerCollectionMap
755
+ .set(this.getCollectionKey(collection.name), oldIdToNewIdMap)
756
+ .get(this.getCollectionKey(collection.name));
757
+ const adapter = new LegacyAdapter(this.database.client);
758
+ if (!operationId) {
759
+ const collectionImportOperation = await findOrCreateOperation(adapter, db.$id, "importData", collection.$id);
760
+ // Store the operation ID in the map
761
+ this.collectionImportOperations.set(this.getCollectionKey(collection.name), collectionImportOperation.$id);
762
+ operationId = collectionImportOperation.$id;
763
+ }
764
+ if (operationId) {
765
+ await updateOperation(adapter, db.$id, operationId, {
766
+ status: "ready",
767
+ total: rawData.length,
768
+ });
769
+ }
770
+ // Retrieve the current user data and the current collection data from the import map
771
+ const currentUserData = this.importMap.get(this.getCollectionKey("users"));
772
+ const currentData = this.importMap.get(this.getCollectionKey(collection.name));
773
+ // Log errors if the necessary data is not found in the import map
774
+ if (!currentUserData) {
775
+ logger.error(`No data found for collection ${"users"} for createDef but it says it's supposed to have one...`);
776
+ return;
777
+ }
778
+ else if (!currentData) {
779
+ logger.error(`No data found for collection ${collection.name} for createDef but it says it's supposed to have one...`);
780
+ return;
781
+ }
782
+ // Iterate through each item in the raw data
783
+ for (const item of rawData) {
784
+ // Prepare user data, check for duplicates, and remove user-specific keys
785
+ let { transformedItem, existingId, userData } = this.prepareUserData(item, importDef.attributeMappings, importDef.primaryKeyField, this.getTrueUniqueId(this.getCollectionKey("users")));
786
+ logger.info(`In create user -- transformedItem: ${JSON.stringify(transformedItem, null, 2)}`);
787
+ // Generate a new unique ID for the item or use existing ID
788
+ if (!existingId && !userData.finalData?.userId) {
789
+ // No existing user ID, generate a new unique ID
790
+ existingId = this.getTrueUniqueId(this.getCollectionKey(collection.name));
791
+ transformedItem = {
792
+ ...transformedItem,
793
+ userId: existingId,
794
+ docId: existingId,
795
+ };
796
+ }
797
+ else if (!existingId && userData.finalData?.userId) {
798
+ // Existing user ID, use it as the new ID
799
+ existingId = userData.finalData.userId;
800
+ transformedItem = {
801
+ ...transformedItem,
802
+ userId: existingId,
803
+ docId: existingId,
804
+ };
805
+ }
806
+ // Create a context object for the item, including the new ID
807
+ let context = this.createContext(db, collection, item, existingId);
808
+ // Merge the transformed data into the context
809
+ context = { ...context, ...transformedItem, ...userData.finalData };
810
+ // If a primary key field is defined, handle the ID mapping and check for duplicates
811
+ if (importDef.primaryKeyField) {
812
+ const oldId = item[importDef.primaryKeyField];
813
+ // Check if the oldId already exists to handle potential duplicates
814
+ if (this.oldIdToNewIdPerCollectionMap
815
+ .get(this.getCollectionKey(collection.name))
816
+ ?.has(`${oldId}`)) {
817
+ // Found a duplicate oldId, now decide how to merge or handle these duplicates
818
+ for (const data of currentData.data) {
819
+ if (data.finalData.docId === oldId ||
820
+ data.finalData.userId === oldId ||
821
+ data.context.docId === oldId ||
822
+ data.context.userId === oldId) {
823
+ transformedItem = this.mergeObjects(data.finalData, transformedItem);
824
+ }
825
+ }
826
+ }
827
+ else {
828
+ // No duplicate found, simply map the oldId to the new itemId
829
+ collectionOldIdToNewIdMap?.set(`${oldId}`, `${existingId}`);
830
+ }
831
+ }
832
+ // Handle merging for currentUserData
833
+ for (let i = 0; i < currentUserData.data.length; i++) {
834
+ const currentUserDataItem = currentUserData.data[i];
835
+ const samePhones = currentUserDataItem.finalData.phone &&
836
+ transformedItem.phone &&
837
+ currentUserDataItem.finalData.phone === transformedItem.phone;
838
+ const sameEmails = currentUserDataItem.finalData.email &&
839
+ transformedItem.email &&
840
+ currentUserDataItem.finalData.email === transformedItem.email;
841
+ if ((currentUserDataItem.finalData.docId === existingId ||
842
+ currentUserDataItem.finalData.userId === existingId) &&
843
+ (samePhones || sameEmails) &&
844
+ currentUserDataItem.finalData &&
845
+ userData.finalData) {
846
+ const userDataMerged = this.mergeObjects(currentUserData.data[i].finalData, userData.finalData);
847
+ currentUserData.data[i].finalData = userDataMerged;
848
+ this.importMap.set(this.getCollectionKey("users"), currentUserData);
849
+ }
850
+ }
851
+ // Update the attribute mappings with any actions that need to be performed post-import
852
+ // We added the basePath to get the folder from the filePath
853
+ const mappingsWithActions = this.getAttributeMappingsWithActions(importDef.attributeMappings, context, transformedItem);
854
+ // Update the import definition with the new attribute mappings
855
+ const newImportDef = {
856
+ ...importDef,
857
+ attributeMappings: mappingsWithActions,
858
+ };
859
+ const updatedData = this.importMap.get(this.getCollectionKey(collection.name));
860
+ let foundData = false;
861
+ for (let i = 0; i < updatedData.data.length; i++) {
862
+ if (updatedData.data[i].finalData.docId === existingId ||
863
+ updatedData.data[i].finalData.userId === existingId ||
864
+ updatedData.data[i].context.docId === existingId ||
865
+ updatedData.data[i].context.userId === existingId) {
866
+ updatedData.data[i].finalData = this.mergeObjects(updatedData.data[i].finalData, transformedItem);
867
+ updatedData.data[i].context = this.mergeObjects(updatedData.data[i].context, context);
868
+ const mergedImportDef = {
869
+ ...updatedData.data[i].importDef,
870
+ idMappings: [
871
+ ...(updatedData.data[i].importDef?.idMappings || []),
872
+ ...(newImportDef.idMappings || []),
873
+ ],
874
+ attributeMappings: [
875
+ ...(updatedData.data[i].importDef?.attributeMappings || []),
876
+ ...(newImportDef.attributeMappings || []),
877
+ ],
878
+ };
879
+ updatedData.data[i].importDef = mergedImportDef;
880
+ this.importMap.set(this.getCollectionKey(collection.name), updatedData);
881
+ this.oldIdToNewIdPerCollectionMap.set(this.getCollectionKey(collection.name), collectionOldIdToNewIdMap);
882
+ foundData = true;
883
+ }
884
+ }
885
+ if (!foundData) {
886
+ // Add new data to the associated collection
887
+ updatedData.data.push({
888
+ rawData: item,
889
+ context: context,
890
+ importDef: newImportDef,
891
+ finalData: transformedItem,
892
+ });
893
+ this.importMap.set(this.getCollectionKey(collection.name), updatedData);
894
+ this.oldIdToNewIdPerCollectionMap.set(this.getCollectionKey(collection.name), collectionOldIdToNewIdMap);
895
+ }
896
+ }
897
+ }
898
+ /**
899
+ * Prepares the data for creating documents in a collection.
900
+ * This involves loading the data, transforming it, and handling ID mappings.
901
+ *
902
+ * @param db - The database configuration.
903
+ * @param collection - The collection configuration.
904
+ * @param importDef - The import definition containing the attribute mappings and other relevant info.
905
+ */
906
+ async prepareCreateData(db, collection, importDef) {
907
+ // Load the raw data based on the import definition
908
+ const rawData = this.loadData(importDef);
909
+ let operationId = this.collectionImportOperations.get(this.getCollectionKey(collection.name));
910
+ const adapter = new LegacyAdapter(this.database.client);
911
+ if (!operationId) {
912
+ const collectionImportOperation = await findOrCreateOperation(adapter, db.$id, "importData", collection.$id);
913
+ // Store the operation ID in the map
914
+ this.collectionImportOperations.set(this.getCollectionKey(collection.name), collectionImportOperation.$id);
915
+ operationId = collectionImportOperation.$id;
916
+ }
917
+ if (operationId) {
918
+ await updateOperation(adapter, db.$id, operationId, {
919
+ status: "ready",
920
+ total: rawData.length,
921
+ });
922
+ }
923
+ // Initialize a new map for old ID to new ID mappings
924
+ const oldIdToNewIdMapNew = new Map();
925
+ // Retrieve or initialize the collection-specific old ID to new ID map
926
+ const collectionOldIdToNewIdMap = this.oldIdToNewIdPerCollectionMap.get(this.getCollectionKey(collection.name)) ||
927
+ this.oldIdToNewIdPerCollectionMap
928
+ .set(this.getCollectionKey(collection.name), oldIdToNewIdMapNew)
929
+ .get(this.getCollectionKey(collection.name));
930
+ const isRegions = collection.name.toLowerCase() === "regions";
931
+ // Iterate through each item in the raw data
932
+ for (const item of rawData) {
933
+ // Generate a new unique ID for the item
934
+ const itemIdNew = this.getTrueUniqueId(this.getCollectionKey(collection.name));
935
+ if (isRegions) {
936
+ logger.info(`Creating region: ${JSON.stringify(item, null, 2)}`);
937
+ }
938
+ // Retrieve the current collection data from the import map
939
+ const currentData = this.importMap.get(this.getCollectionKey(collection.name));
940
+ // Create a context object for the item, including the new ID
941
+ let context = this.createContext(db, collection, item, itemIdNew);
942
+ // Transform the item data based on the attribute mappings
943
+ let transformedData = this.transformData(item, importDef.attributeMappings);
944
+ // If a primary key field is defined, handle the ID mapping and check for duplicates
945
+ if (importDef.primaryKeyField) {
946
+ const oldId = item[importDef.primaryKeyField];
947
+ if (collectionOldIdToNewIdMap?.has(`${oldId}`)) {
948
+ logger.error(`Collection ${collection.name} has multiple documents with the same primary key ${oldId}`);
949
+ continue;
950
+ }
951
+ collectionOldIdToNewIdMap?.set(`${oldId}`, `${itemIdNew}`);
952
+ }
953
+ // Merge the transformed data into the context
954
+ context = { ...context, ...transformedData };
955
+ // Validate the item before proceeding
956
+ const isValid = this.importDataActions.validateItem(transformedData, importDef.attributeMappings, context);
957
+ if (!isValid) {
958
+ continue;
959
+ }
960
+ // Update the attribute mappings with any actions that need to be performed post-import
961
+ // We added the basePath to get the folder from the filePath
962
+ const mappingsWithActions = this.getAttributeMappingsWithActions(importDef.attributeMappings, context, transformedData);
963
+ // Update the import definition with the new attribute mappings
964
+ const newImportDef = {
965
+ ...importDef,
966
+ attributeMappings: mappingsWithActions,
967
+ };
968
+ // If the current collection data exists, add the item with its context and final data
969
+ if (currentData && currentData.data) {
970
+ currentData.data.push({
971
+ rawData: item,
972
+ context: context,
973
+ importDef: newImportDef,
974
+ finalData: transformedData,
975
+ });
976
+ this.importMap.set(this.getCollectionKey(collection.name), currentData);
977
+ this.oldIdToNewIdPerCollectionMap.set(this.getCollectionKey(collection.name), collectionOldIdToNewIdMap);
978
+ }
979
+ else {
980
+ logger.error(`No data found for collection ${collection.name} for createDef but it says it's supposed to have one...`);
981
+ continue;
982
+ }
983
+ }
984
+ }
985
+ /**
986
+ * Prepares the data for updating documents within a collection.
987
+ * This method loads the raw data based on the import definition, transforms it according to the attribute mappings,
988
+ * finds the new ID for each item based on the primary key or update mapping, and then validates the transformed data.
989
+ * If the data is valid, it updates the import definition with any post-import actions and adds the item to the current collection data.
990
+ *
991
+ * @param db - The database configuration.
992
+ * @param collection - The collection configuration.
993
+ * @param importDef - The import definition containing the attribute mappings and other relevant info.
994
+ */
995
+ async prepareUpdateData(db, collection, importDef) {
996
+ const currentData = this.importMap.get(this.getCollectionKey(collection.name));
997
+ const oldIdToNewIdMap = this.oldIdToNewIdPerCollectionMap.get(this.getCollectionKey(collection.name));
998
+ if (!(currentData?.data && currentData?.data.length > 0) &&
999
+ !oldIdToNewIdMap) {
1000
+ logger.error(`No data found for collection ${collection.name} for updateDef but it says it's supposed to have one...`);
1001
+ return;
1002
+ }
1003
+ const rawData = this.loadData(importDef);
1004
+ const operationId = this.collectionImportOperations.get(this.getCollectionKey(collection.name));
1005
+ if (!operationId) {
1006
+ throw new Error(`No import operation found for collection ${collection.name}`);
1007
+ }
1008
+ for (const item of rawData) {
1009
+ let transformedData = this.transformData(item, importDef.attributeMappings);
1010
+ let newId;
1011
+ let oldId;
1012
+ let itemDataToUpdate;
1013
+ // Try to find itemDataToUpdate using updateMapping
1014
+ if (importDef.updateMapping) {
1015
+ oldId =
1016
+ item[importDef.updateMapping.originalIdField] ||
1017
+ transformedData[importDef.updateMapping.originalIdField];
1018
+ if (oldId) {
1019
+ itemDataToUpdate = currentData?.data.find(({ context, finalData }) => {
1020
+ const targetField = importDef.updateMapping.targetField ??
1021
+ importDef.updateMapping.originalIdField;
1022
+ return (`${context[targetField]}` === `${oldId}` ||
1023
+ `${finalData[targetField]}` === `${oldId}`);
1024
+ });
1025
+ if (itemDataToUpdate) {
1026
+ newId = itemDataToUpdate.context.docId;
1027
+ }
1028
+ }
1029
+ }
1030
+ // If updateMapping is not defined or did not find the item, use primaryKeyField
1031
+ if (!itemDataToUpdate && importDef.primaryKeyField) {
1032
+ oldId =
1033
+ item[importDef.primaryKeyField] ||
1034
+ transformedData[importDef.primaryKeyField];
1035
+ if (oldId && oldId.length > 0) {
1036
+ newId = oldIdToNewIdMap?.get(`${oldId}`);
1037
+ if (!newId &&
1038
+ this.getCollectionKey(this.config.usersCollectionName) ===
1039
+ this.getCollectionKey(collection.name)) {
1040
+ for (const [key, value] of this.mergedUserMap.entries()) {
1041
+ if (value.includes(`${oldId}`)) {
1042
+ newId = key;
1043
+ break;
1044
+ }
1045
+ }
1046
+ }
1047
+ }
1048
+ if (oldId && !itemDataToUpdate) {
1049
+ itemDataToUpdate = currentData?.data.find((data) => `${data.context[importDef.primaryKeyField]}` === `${oldId}`);
1050
+ }
1051
+ }
1052
+ if (!oldId) {
1053
+ logger.error(`No old ID found (to update another document with) in prepareUpdateData for ${collection.name}, ${JSON.stringify(item, null, 2)}`);
1054
+ continue;
1055
+ }
1056
+ if (!newId && !itemDataToUpdate) {
1057
+ logger.error(`No new id && no data found for collection ${collection.name} for updateDef ${JSON.stringify(item, null, 2)} but it says it's supposed to have one...`);
1058
+ continue;
1059
+ }
1060
+ else if (itemDataToUpdate) {
1061
+ newId =
1062
+ itemDataToUpdate.finalData.docId || itemDataToUpdate.context.docId;
1063
+ if (!newId) {
1064
+ logger.error(`No new id found for collection ${collection.name} for updateDef ${JSON.stringify(item, null, 2)} but has itemDataToUpdate ${JSON.stringify(itemDataToUpdate, null, 2)} but it says it's supposed to have one...`);
1065
+ continue;
1066
+ }
1067
+ }
1068
+ if (!itemDataToUpdate || !newId) {
1069
+ logger.error(`No data or ID (docId) found for collection ${collection.name} for updateDef ${JSON.stringify(item, null, 2)} but it says it's supposed to have one...`);
1070
+ continue;
1071
+ }
1072
+ transformedData = this.mergeObjects(itemDataToUpdate.finalData, transformedData);
1073
+ // Create a context object for the item, including the new ID and transformed data
1074
+ let context = itemDataToUpdate.context;
1075
+ context = this.mergeObjects(context, transformedData);
1076
+ // Validate the item before proceeding
1077
+ const isValid = this.importDataActions.validateItem(item, importDef.attributeMappings, context);
1078
+ if (!isValid) {
1079
+ logger.info(`Skipping item: ${JSON.stringify(item, null, 2)} because it's invalid`);
1080
+ continue;
1081
+ }
1082
+ // Update the attribute mappings with any actions that need to be performed post-import
1083
+ // We added the basePath to get the folder from the filePath
1084
+ const mappingsWithActions = this.getAttributeMappingsWithActions(importDef.attributeMappings, context, transformedData);
1085
+ // Update the import definition with the new attribute mappings
1086
+ const newImportDef = {
1087
+ ...importDef,
1088
+ attributeMappings: mappingsWithActions,
1089
+ };
1090
+ if (itemDataToUpdate) {
1091
+ itemDataToUpdate.finalData = this.mergeObjects(itemDataToUpdate.finalData, transformedData);
1092
+ itemDataToUpdate.context = context;
1093
+ // Fix: Ensure we properly merge the attribute mappings and their actions
1094
+ const mergedAttributeMappings = newImportDef.attributeMappings.map((newMapping) => {
1095
+ const existingMapping = itemDataToUpdate.importDef?.attributeMappings.find((m) => m.targetKey === newMapping.targetKey);
1096
+ return {
1097
+ ...newMapping,
1098
+ postImportActions: [
1099
+ ...(existingMapping?.postImportActions || []),
1100
+ ...(newMapping.postImportActions || []),
1101
+ ],
1102
+ };
1103
+ });
1104
+ itemDataToUpdate.importDef = {
1105
+ ...newImportDef,
1106
+ attributeMappings: mergedAttributeMappings,
1107
+ };
1108
+ // Debug logging
1109
+ if (mergedAttributeMappings.some((m) => m.postImportActions?.length > 0)) {
1110
+ logger.info(`Post-import actions for ${collection.name}: ${JSON.stringify(mergedAttributeMappings
1111
+ .filter((m) => m.postImportActions?.length > 0)
1112
+ .map((m) => ({
1113
+ targetKey: m.targetKey,
1114
+ actions: m.postImportActions,
1115
+ })), null, 2)}`);
1116
+ }
1117
+ }
1118
+ else {
1119
+ currentData.data.push({
1120
+ rawData: item,
1121
+ context: context,
1122
+ importDef: newImportDef,
1123
+ finalData: transformedData,
1124
+ });
1125
+ }
1126
+ // Since we're modifying currentData in place, we ensure no duplicates are added
1127
+ this.importMap.set(this.getCollectionKey(collection.name), currentData);
1128
+ }
1129
+ }
1130
+ updateReferencesBasedOnAttributeMappings() {
1131
+ if (!this.config.collections) {
1132
+ return;
1133
+ }
1134
+ this.config.collections.forEach((collectionConfig) => {
1135
+ const collectionName = collectionConfig.name;
1136
+ const collectionData = this.importMap.get(this.getCollectionKey(collectionName));
1137
+ if (!collectionData) {
1138
+ logger.error(`No data found for collection ${collectionName}`);
1139
+ return;
1140
+ }
1141
+ collectionData.data.forEach((dataItem) => {
1142
+ collectionConfig.importDefs.forEach((importDef) => {
1143
+ if (!importDef.idMappings)
1144
+ return; // Skip collections without idMappings
1145
+ importDef.idMappings.forEach((mapping) => {
1146
+ if (mapping && mapping.targetField) {
1147
+ const idsToUpdate = Array.isArray(dataItem[mapping.targetField])
1148
+ ? dataItem[mapping.targetField]
1149
+ : [dataItem[mapping.targetField]];
1150
+ const updatedIds = idsToUpdate.map((id) => this.getMergedId(id, mapping.targetCollection));
1151
+ // Update the dataItem with the new IDs
1152
+ dataItem[mapping.targetField] =
1153
+ Array.isArray(dataItem[mapping.targetField])
1154
+ ? updatedIds
1155
+ : updatedIds[0];
1156
+ }
1157
+ });
1158
+ });
1159
+ });
1160
+ });
1161
+ }
1162
+ getMergedId(oldId, relatedCollectionName) {
1163
+ // Retrieve the old to new ID map for the related collection
1164
+ const oldToNewIdMap = this.oldIdToNewIdPerCollectionMap.get(this.getCollectionKey(relatedCollectionName));
1165
+ // If there's a mapping for the old ID, return the new ID
1166
+ if (oldToNewIdMap && oldToNewIdMap.has(`${oldId}`)) {
1167
+ return oldToNewIdMap.get(`${oldId}`); // The non-null assertion (!) is used because we checked if the map has the key
1168
+ }
1169
+ // If no mapping is found, return the old ID as a fallback
1170
+ return oldId;
1171
+ }
1172
+ /**
1173
+ * Generates attribute mappings with post-import actions based on the provided attribute mappings.
1174
+ * This method checks each mapping for a fileData attribute and adds a post-import action to create a file
1175
+ * and update the field with the file's ID if necessary.
1176
+ *
1177
+ * @param attributeMappings - The attribute mappings from the import definition.
1178
+ * @param context - The context object containing information about the database, collection, and document.
1179
+ * @param item - The item being imported, used for resolving template paths in fileData mappings.
1180
+ * @returns The attribute mappings updated with any necessary post-import actions.
1181
+ */
1182
+ getAttributeMappingsWithActions(attributeMappings, context, item) {
1183
+ // Iterate over each attribute mapping to check for fileData attributes
1184
+ return attributeMappings.map((mapping) => {
1185
+ if (mapping.fileData) {
1186
+ // Resolve the file path using the provided template, context, and item
1187
+ let mappingFilePath = this.importDataActions.resolveTemplate(mapping.fileData.path, context, item);
1188
+ // Ensure the file path is absolute if it doesn't start with "http"
1189
+ if (!mappingFilePath.toLowerCase().startsWith("http")) {
1190
+ // First try the direct path
1191
+ let fullPath = path.resolve(this.appwriteFolderPath, mappingFilePath);
1192
+ // If file doesn't exist, search in subdirectories
1193
+ if (!fs.existsSync(fullPath)) {
1194
+ const findFileInDir = (dir) => {
1195
+ const files = fs.readdirSync(dir);
1196
+ for (const file of files) {
1197
+ const filePath = path.join(dir, file);
1198
+ const stat = fs.statSync(filePath);
1199
+ if (stat.isDirectory()) {
1200
+ // Recursively search subdirectories
1201
+ const found = findFileInDir(filePath);
1202
+ if (found)
1203
+ return found;
1204
+ }
1205
+ else if (file === path.basename(mappingFilePath)) {
1206
+ return filePath;
1207
+ }
1208
+ }
1209
+ return null;
1210
+ };
1211
+ const foundPath = findFileInDir(this.appwriteFolderPath);
1212
+ if (foundPath) {
1213
+ mappingFilePath = foundPath;
1214
+ }
1215
+ else {
1216
+ logger.warn(`File not found in any subdirectory: ${mappingFilePath}`);
1217
+ // Keep the original resolved path as fallback
1218
+ mappingFilePath = fullPath;
1219
+ }
1220
+ }
1221
+ else {
1222
+ mappingFilePath = fullPath;
1223
+ }
1224
+ }
1225
+ // Define the after-import action to create a file and update the field
1226
+ const afterImportAction = {
1227
+ action: "createFileAndUpdateField",
1228
+ params: [
1229
+ "{dbId}",
1230
+ "{collId}",
1231
+ "{docId}",
1232
+ mapping.targetKey,
1233
+ `${this.config.documentBucketId}_${context.dbName
1234
+ .toLowerCase()
1235
+ .replace(" ", "")}`, // Assuming 'images' is your bucket ID
1236
+ mappingFilePath,
1237
+ mapping.fileData.name,
1238
+ ],
1239
+ };
1240
+ // Add the after-import action to the mapping's postImportActions array
1241
+ const postImportActions = mapping.postImportActions
1242
+ ? [...mapping.postImportActions, afterImportAction]
1243
+ : [afterImportAction];
1244
+ return { ...mapping, postImportActions };
1245
+ }
1246
+ // Return the mapping unchanged if no fileData attribute is found
1247
+ return mapping;
1248
+ });
1249
+ }
1250
+ }