@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,1702 @@
1
+ import type { ImportDataActions } from "./importDataActions.js";
2
+ import {
3
+ AttributeMappingsSchema,
4
+ CollectionCreateSchema,
5
+ importDefSchema,
6
+ type AppwriteConfig,
7
+ type AttributeMappings,
8
+ type CollectionCreate,
9
+ type ConfigDatabase,
10
+ type IdMapping,
11
+ type ImportDef,
12
+ type ImportDefs,
13
+ type RelationshipAttribute,
14
+ } from "@njdamstra/appwrite-utils";
15
+ import path from "path";
16
+ import fs from "fs";
17
+ import { convertObjectByAttributeMappings } from "../utils/dataConverters.js";
18
+ import { z } from "zod";
19
+ import { checkForCollection } from "../collections/methods.js";
20
+ import { ID, Users, type Databases } from "node-appwrite";
21
+ import { logger } from "../shared/logging.js";
22
+ import { findOrCreateOperation, updateOperation } from "../shared/migrationHelpers.js";
23
+ import { AuthUserCreateSchema } from "../schemas/authUser.js";
24
+ import { LegacyAdapter } from "../adapters/LegacyAdapter.js";
25
+ import { UsersController } from "../users/methods.js";
26
+ import { finalizeByAttributeMap } from "../utils/helperFunctions.js";
27
+ import { isEmpty } from "es-toolkit/compat";
28
+ import { MessageFormatter } from "../shared/messageFormatter.js";
29
+
30
+ // Define a schema for the structure of collection import data using Zod for validation
31
+ export const CollectionImportDataSchema = z.object({
32
+ // Optional collection creation schema
33
+ collection: CollectionCreateSchema.optional(),
34
+ // Array of data objects each containing rawData, finalData, context, and an import definition
35
+ data: z.array(
36
+ z.object({
37
+ rawData: z.any(), // The initial raw data
38
+ finalData: z.any(), // The transformed data ready for import
39
+ context: z.any(), // Additional context for the data transformation
40
+ importDef: importDefSchema.optional(), // The import definition schema
41
+ })
42
+ ),
43
+ });
44
+
45
+ // Infer the TypeScript type from the Zod schema
46
+ export type CollectionImportData = z.infer<typeof CollectionImportDataSchema>;
47
+
48
+ // DataLoader class to handle the loading of data into collections
49
+ export class DataLoader {
50
+ // Private member variables to hold configuration and state
51
+ private appwriteFolderPath: string;
52
+ private importDataActions: ImportDataActions;
53
+ private database: Databases;
54
+ private usersController: UsersController;
55
+ private config: AppwriteConfig;
56
+ // Map to hold the import data for each collection by name
57
+ importMap = new Map<string, CollectionImportData>();
58
+ // Map to track old to new ID mappings for each collection, if applicable
59
+ private oldIdToNewIdPerCollectionMap = new Map<string, Map<string, string>>();
60
+ // Map to hold the import operation ID for each collection
61
+ collectionImportOperations = new Map<string, string>();
62
+ // Map to hold the merged user map for relationship resolution
63
+ // Will hold an array of the old user ID's that are mapped to the same new user ID
64
+ // For example, if there are two users with the same email, they will both be mapped to the same new user ID
65
+ // Prevents duplicate users with the other two maps below it and allows me to keep the old ID's
66
+ private mergedUserMap = new Map<string, string[]>();
67
+ // Maps to hold email and phone to user ID mappings for unique-ness in User Accounts
68
+ private emailToUserIdMap = new Map<string, string>();
69
+ private phoneToUserIdMap = new Map<string, string>();
70
+ private userIdSet = new Set<string>();
71
+ userExistsMap = new Map<string, boolean>();
72
+ private shouldWriteFile = false;
73
+
74
+ // Constructor to initialize the DataLoader with necessary configurations
75
+ constructor(
76
+ appwriteFolderPath: string,
77
+ importDataActions: ImportDataActions,
78
+ database: Databases,
79
+ config: AppwriteConfig,
80
+ shouldWriteFile?: boolean
81
+ ) {
82
+ this.appwriteFolderPath = appwriteFolderPath;
83
+ this.importDataActions = importDataActions;
84
+ this.database = database;
85
+ this.usersController = new UsersController(config, database);
86
+ this.config = config;
87
+ this.shouldWriteFile = shouldWriteFile || false;
88
+ }
89
+
90
+ // Helper method to generate a consistent key for collections
91
+ getCollectionKey(name: string) {
92
+ return name.toLowerCase().replace(" ", "");
93
+ }
94
+
95
+ /**
96
+ * Merges two objects by updating the source object with the target object's values.
97
+ * It iterates through the target object's keys and updates the source object if:
98
+ * - The source object has the key.
99
+ * - The target object's value for that key is not null, undefined, or an empty string.
100
+ * - If the target object has an array value, it concatenates the values and removes duplicates.
101
+ *
102
+ * @param source - The source object to be updated.
103
+ * @param target - The target object with values to update the source object.
104
+ * @returns The updated source object.
105
+ */
106
+ mergeObjects(source: any, update: any): any {
107
+ // Create a new object to hold the merged result
108
+ const result = { ...source };
109
+
110
+ // Loop through the keys of the object we care about
111
+ for (const [key, value] of Object.entries(source)) {
112
+ // Check if the key exists in the target object
113
+ if (!Object.hasOwn(update, key)) {
114
+ // If the key doesn't exist, we can just skip it like bad cheese
115
+ continue;
116
+ }
117
+ if (update[key] === value) {
118
+ continue;
119
+ }
120
+ // If the value ain't here, we can just do whatever man
121
+ if (value === undefined || value === null || value === "") {
122
+ // If the update key is defined
123
+ if (
124
+ update[key] !== undefined &&
125
+ update[key] !== null &&
126
+ update[key] !== ""
127
+ ) {
128
+ // might as well use it eh?
129
+ result[key] = update[key];
130
+ }
131
+ // ELSE if the value is an array, because it would then not be === to those things above
132
+ } else if (Array.isArray(value)) {
133
+ // Get the update value
134
+ const updateValue = update[key];
135
+ // If the update value is an array, concatenate and remove duplicates
136
+ // and poopy data
137
+ if (Array.isArray(updateValue)) {
138
+ result[key] = [...new Set([...value, ...updateValue])].filter(
139
+ (item) => item !== null && item !== undefined && item !== ""
140
+ );
141
+ } else {
142
+ // If the update value is not an array, just use it
143
+ result[key] = [...value, updateValue].filter(
144
+ (item) => item !== null && item !== undefined && item !== ""
145
+ );
146
+ }
147
+ } else if (typeof value === "object" && !Array.isArray(value)) {
148
+ // If the value is an object, we need to merge it
149
+ if (typeof update[key] === "object" && !Array.isArray(update[key])) {
150
+ result[key] = this.mergeObjects(value, update[key]);
151
+ }
152
+ } else {
153
+ // Finally, the source value is defined, and not an array, so we don't care about the update value
154
+ continue;
155
+ }
156
+ }
157
+ // Because the objects should technically always be validated FIRST, we can assume the update keys are also defined on the source object
158
+ for (const [key, value] of Object.entries(update)) {
159
+ if (value === undefined || value === null || value === "") {
160
+ continue;
161
+ } else if (!Object.hasOwn(source, key)) {
162
+ result[key] = value;
163
+ } else if (
164
+ typeof source[key] === "object" &&
165
+ typeof value === "object" &&
166
+ !Array.isArray(source[key]) &&
167
+ !Array.isArray(value)
168
+ ) {
169
+ result[key] = this.mergeObjects(source[key], value);
170
+ } else if (Array.isArray(source[key]) && Array.isArray(value)) {
171
+ result[key] = [...new Set([...source[key], ...value])].filter(
172
+ (item) => item !== null && item !== undefined && item !== ""
173
+ );
174
+ } else if (
175
+ source[key] === undefined ||
176
+ source[key] === null ||
177
+ source[key] === ""
178
+ ) {
179
+ result[key] = value;
180
+ }
181
+ }
182
+
183
+ return result;
184
+ }
185
+
186
+ // Method to load data from a file specified in the import definition
187
+ loadData(importDef: ImportDef): any[] {
188
+ // Simply join appwriteFolderPath with the importDef.filePath
189
+ const filePath = path.resolve(this.appwriteFolderPath, importDef.filePath);
190
+ MessageFormatter.info(`Loading data from: ${filePath}`, { prefix: "Data" });
191
+ if (!fs.existsSync(filePath)) {
192
+ MessageFormatter.error(`File not found: ${filePath}`, undefined, { prefix: "Data" });
193
+ return [];
194
+ }
195
+
196
+ // Read the file and parse the JSON data
197
+ const rawData = fs.readFileSync(filePath, "utf8");
198
+ const parsedData = importDef.basePath
199
+ ? JSON.parse(rawData)[importDef.basePath]
200
+ : JSON.parse(rawData);
201
+
202
+ MessageFormatter.success(`Loaded ${parsedData?.length || 0} items from ${filePath}`, { prefix: "Data" });
203
+ return parsedData;
204
+ }
205
+
206
+ // Helper method to check if a new ID already exists in the old-to-new ID map
207
+ checkMapValuesForId(newId: string, collectionName: string) {
208
+ const oldIdMap = this.oldIdToNewIdPerCollectionMap.get(collectionName);
209
+ for (const [key, value] of oldIdMap?.entries() || []) {
210
+ if (value === newId) {
211
+ return key;
212
+ }
213
+ }
214
+ return false;
215
+ }
216
+
217
+ // Method to generate a unique ID that doesn't conflict with existing IDs
218
+ getTrueUniqueId(collectionName: string) {
219
+ let newId = ID.unique();
220
+ let condition =
221
+ this.checkMapValuesForId(newId, collectionName) ||
222
+ this.userExistsMap.has(newId) ||
223
+ this.userIdSet.has(newId) ||
224
+ this.importMap
225
+ .get(this.getCollectionKey("users"))
226
+ ?.data.some(
227
+ (user) =>
228
+ user.finalData.docId === newId || user.finalData.userId === newId
229
+ );
230
+ while (condition) {
231
+ newId = ID.unique();
232
+ condition =
233
+ this.checkMapValuesForId(newId, collectionName) ||
234
+ this.userExistsMap.has(newId) ||
235
+ this.userIdSet.has(newId) ||
236
+ this.importMap
237
+ .get(this.getCollectionKey("users"))
238
+ ?.data.some(
239
+ (user) =>
240
+ user.finalData.docId === newId || user.finalData.userId === newId
241
+ );
242
+ }
243
+ return newId;
244
+ }
245
+
246
+ // Method to create a context object for data transformation
247
+ createContext(
248
+ db: ConfigDatabase,
249
+ collection: CollectionCreate,
250
+ item: any,
251
+ docId: string
252
+ ) {
253
+ return {
254
+ ...item, // Spread the item data for easy access to its properties
255
+ dbId: db.$id,
256
+ dbName: db.name,
257
+ collId: collection.$id,
258
+ collName: collection.name,
259
+ docId: docId,
260
+ createdDoc: {}, // Initially null, to be updated when the document is created
261
+ };
262
+ }
263
+
264
+ /**
265
+ * Transforms the given item based on the provided attribute mappings.
266
+ * This method applies conversion rules to the item's attributes as defined in the attribute mappings.
267
+ *
268
+ * @param item - The item to be transformed.
269
+ * @param attributeMappings - The mappings that define how each attribute should be transformed.
270
+ * @returns The transformed item.
271
+ */
272
+ transformData(item: any, attributeMappings: AttributeMappings): any {
273
+ // Convert the item using the attribute mappings provided
274
+ const convertedItem = convertObjectByAttributeMappings(
275
+ item,
276
+ attributeMappings
277
+ );
278
+ // Run additional converter functions on the converted item, if any
279
+ return this.importDataActions.runConverterFunctions(
280
+ convertedItem,
281
+ attributeMappings
282
+ );
283
+ }
284
+
285
+ async setupMaps(dbId: string) {
286
+ // Initialize the users collection in the import map
287
+ this.importMap.set(this.getCollectionKey("users"), {
288
+ data: [],
289
+ });
290
+ for (const db of this.config.databases) {
291
+ if (db.$id !== dbId) {
292
+ continue;
293
+ }
294
+ if (!this.config.collections) {
295
+ continue;
296
+ }
297
+ for (let index = 0; index < this.config.collections.length; index++) {
298
+ const collectionConfig = this.config.collections[index];
299
+ let collection = CollectionCreateSchema.parse(collectionConfig);
300
+ // Check if the collection exists in the database
301
+ const collectionExists = await checkForCollection(
302
+ this.database,
303
+ db.$id,
304
+ collection
305
+ );
306
+ if (!collectionExists) {
307
+ logger.error(`No collection found for ${collection.name}`);
308
+ continue;
309
+ } else if (!collection.name) {
310
+ logger.error(`Collection ${collection.name} has no name`);
311
+ continue;
312
+ }
313
+ // Update the collection ID with the existing one
314
+ collectionConfig.$id = collectionExists.$id;
315
+ collection.$id = collectionExists.$id;
316
+ this.config.collections[index] = collectionConfig;
317
+ // Find or create an import operation for the collection
318
+ const adapter = new LegacyAdapter(this.database.client);
319
+ const collectionImportOperation = await findOrCreateOperation(
320
+ adapter,
321
+ dbId,
322
+ "importData",
323
+ collection.$id!
324
+ );
325
+ // Store the operation ID in the map
326
+ this.collectionImportOperations.set(
327
+ this.getCollectionKey(collection.name),
328
+ collectionImportOperation.$id
329
+ );
330
+ // Initialize the collection in the import map
331
+ this.importMap.set(this.getCollectionKey(collection.name), {
332
+ collection: collection,
333
+ data: [],
334
+ });
335
+ }
336
+ }
337
+ }
338
+
339
+ async getAllUsers() {
340
+ const users = new UsersController(this.config, this.database);
341
+ const allUsers = await users.getAllUsers();
342
+ // Iterate over the users and setup our maps ahead of time for email and phone
343
+ for (const user of allUsers) {
344
+ if (user.email) {
345
+ this.emailToUserIdMap.set(user.email.toLowerCase(), user.$id);
346
+ }
347
+ if (user.phone) {
348
+ this.phoneToUserIdMap.set(user.phone, user.$id);
349
+ }
350
+ this.userExistsMap.set(user.$id, true);
351
+ this.userIdSet.add(user.$id);
352
+ let importData = this.importMap.get(this.getCollectionKey("users"));
353
+ if (!importData) {
354
+ importData = {
355
+ data: [],
356
+ };
357
+ }
358
+ importData.data.push({
359
+ finalData: {
360
+ ...user,
361
+ email: user.email?.toLowerCase(),
362
+ userId: user.$id,
363
+ docId: user.$id,
364
+ },
365
+ context: {
366
+ ...user,
367
+ email: user.email?.toLowerCase(),
368
+ userId: user.$id,
369
+ docId: user.$id,
370
+ },
371
+ rawData: user,
372
+ });
373
+ this.importMap.set(this.getCollectionKey("users"), importData);
374
+ }
375
+ return allUsers;
376
+ }
377
+
378
+ // Main method to start the data loading process for a given database ID
379
+ async start(dbId: string) {
380
+ MessageFormatter.divider();
381
+ MessageFormatter.info(`Starting data setup for database: ${dbId}`, { prefix: "Data" });
382
+ MessageFormatter.divider();
383
+ await this.setupMaps(dbId);
384
+ const allUsers = await this.getAllUsers();
385
+ MessageFormatter.info(
386
+ `Fetched ${allUsers.length} users, waiting a few seconds to let the program catch up...`,
387
+ { prefix: "Data" }
388
+ );
389
+ await new Promise((resolve) => setTimeout(resolve, 5000));
390
+ // Iterate over the configured databases to find the matching one
391
+ for (const db of this.config.databases) {
392
+ if (db.$id !== dbId) {
393
+ continue;
394
+ }
395
+ if (!this.config.collections) {
396
+ continue;
397
+ }
398
+ // Iterate over the configured collections to process each
399
+ for (const collectionConfig of this.config.collections) {
400
+ const collection = collectionConfig;
401
+ // Determine if this is the users collection
402
+ let isUsersCollection =
403
+ this.getCollectionKey(this.config.usersCollectionName) ===
404
+ this.getCollectionKey(collection.name);
405
+ const collectionDefs = collection.importDefs;
406
+ if (!collectionDefs || !collectionDefs.length) {
407
+ continue;
408
+ }
409
+ // Process create and update definitions for the collection
410
+ const createDefs = collection.importDefs.filter(
411
+ (def: ImportDef) => def.type === "create" || !def.type
412
+ );
413
+ const updateDefs = collection.importDefs.filter(
414
+ (def: ImportDef) => def.type === "update"
415
+ );
416
+ for (const createDef of createDefs) {
417
+ if (!isUsersCollection || !createDef.createUsers) {
418
+ await this.prepareCreateData(db, collection, createDef);
419
+ } else {
420
+ // Special handling for users collection if needed
421
+ await this.prepareUserCollectionCreateData(
422
+ db,
423
+ collection,
424
+ createDef
425
+ );
426
+ }
427
+ }
428
+ for (const updateDef of updateDefs) {
429
+ if (!this.importMap.has(this.getCollectionKey(collection.name))) {
430
+ logger.error(
431
+ `No data found for collection ${collection.name} for updateDef but it says it's supposed to have one...`
432
+ );
433
+ continue;
434
+ }
435
+ // Prepare the update data for the collection
436
+ this.prepareUpdateData(db, collection, updateDef);
437
+ }
438
+ }
439
+ MessageFormatter.info("Running update references", { prefix: "Data" });
440
+ // this.dealWithMergedUsers();
441
+ this.updateOldReferencesForNew();
442
+ MessageFormatter.success("Done running update references", { prefix: "Data" });
443
+ }
444
+ // for (const collection of this.config.collections) {
445
+ // this.resolveDataItemRelationships(collection);
446
+ // }
447
+ MessageFormatter.divider();
448
+ MessageFormatter.success(`Data setup for database: ${dbId} completed`, { prefix: "Data" });
449
+ MessageFormatter.divider();
450
+ if (this.shouldWriteFile) {
451
+ this.writeMapsToJsonFile();
452
+ }
453
+ }
454
+
455
+ /**
456
+ * Deals with merged users by iterating through all collections in the configuration.
457
+ * We have merged users if there are duplicate emails or phones in the import data.
458
+ * This function will iterate through all collections that are the same name as the
459
+ * users collection and pull out their primaryKeyField's. It will then loop through
460
+ * each collection and find any documents that have a
461
+ *
462
+ * @return {void} This function does not return anything.
463
+ */
464
+ // dealWithMergedUsers() {
465
+ // const usersCollectionKey = this.getCollectionKey(
466
+ // this.config.usersCollectionName
467
+ // );
468
+ // const usersCollectionData = this.importMap.get(usersCollectionKey);
469
+
470
+ // if (!this.config.collections) {
471
+ // console.log("No collections found in configuration.");
472
+ // return;
473
+ // }
474
+
475
+ // let needsUpdate = false;
476
+ // let numUpdates = 0;
477
+
478
+ // for (const collectionConfig of this.config.collections) {
479
+ // const collectionKey = this.getCollectionKey(collectionConfig.name);
480
+ // const collectionData = this.importMap.get(collectionKey);
481
+ // const collectionImportDefs = collectionConfig.importDefs;
482
+ // const collectionIdMappings = collectionImportDefs
483
+ // .map((importDef) => importDef.idMappings)
484
+ // .flat()
485
+ // .filter((idMapping) => idMapping !== undefined && idMapping !== null);
486
+ // if (!collectionData || !collectionData.data) continue;
487
+ // for (const dataItem of collectionData.data) {
488
+ // for (const idMapping of collectionIdMappings) {
489
+ // // We know it's the users collection here
490
+ // if (this.getCollectionKey(idMapping.targetCollection) === usersCollectionKey) {
491
+ // const targetFieldKey = idMapping.targetFieldToMatch || idMapping.targetField;
492
+ // if (targetFieldKey === )
493
+ // const targetValue = dataItem.finalData[targetFieldKey];
494
+ // const targetCollectionData = this.importMap.get(this.getCollectionKey(idMapping.targetCollection));
495
+ // if (!targetCollectionData || !targetCollectionData.data) continue;
496
+ // const foundData = targetCollectionData.data.filter(({ context }) => {
497
+ // const targetValue = context[targetFieldKey];
498
+ // const isMatch = `${targetValue}` === `${valueToMatch}`;
499
+ // return isMatch && targetValue !== undefined && targetValue !== null;
500
+ // });
501
+ // }
502
+ // }
503
+ // }
504
+ // }
505
+ // }
506
+
507
+ /**
508
+ * Gets the value to match for a given key in the final data or context.
509
+ * @param finalData - The final data object.
510
+ * @param context - The context object.
511
+ * @param key - The key to get the value for.
512
+ * @returns The value to match for from finalData or Context
513
+ */
514
+ getValueFromData(finalData: any, context: any, key: string) {
515
+ if (
516
+ context[key] !== undefined &&
517
+ context[key] !== null &&
518
+ context[key] !== ""
519
+ ) {
520
+ return context[key];
521
+ }
522
+ return finalData[key];
523
+ }
524
+
525
+ updateOldReferencesForNew() {
526
+ if (!this.config.collections) {
527
+ return;
528
+ }
529
+
530
+ for (const collectionConfig of this.config.collections) {
531
+ const collectionKey = this.getCollectionKey(collectionConfig.name);
532
+ const collectionData = this.importMap.get(collectionKey);
533
+
534
+ if (!collectionData || !collectionData.data) continue;
535
+
536
+ MessageFormatter.processing(
537
+ `Updating references for collection: ${collectionConfig.name}`,
538
+ { prefix: "Data" }
539
+ );
540
+
541
+ let needsUpdate = false;
542
+
543
+ // Iterate over each data item in the current collection
544
+ for (let i = 0; i < collectionData.data.length; i++) {
545
+ if (collectionConfig.importDefs) {
546
+ for (const importDef of collectionConfig.importDefs) {
547
+ if (importDef.idMappings) {
548
+ for (const idMapping of importDef.idMappings) {
549
+ const targetCollectionKey = this.getCollectionKey(
550
+ idMapping.targetCollection
551
+ );
552
+ const fieldToSetKey =
553
+ idMapping.fieldToSet || idMapping.sourceField;
554
+ const targetFieldKey =
555
+ idMapping.targetFieldToMatch || idMapping.targetField;
556
+ const sourceValue = this.getValueFromData(
557
+ collectionData.data[i].finalData,
558
+ collectionData.data[i].context,
559
+ idMapping.sourceField
560
+ );
561
+
562
+ // Skip if value to match is missing or empty
563
+ if (
564
+ !sourceValue ||
565
+ isEmpty(sourceValue) ||
566
+ sourceValue === null
567
+ )
568
+ continue;
569
+
570
+ const isFieldToSetArray = collectionConfig.attributes.find(
571
+ (attribute) => attribute.key === fieldToSetKey
572
+ )?.array;
573
+
574
+ const targetCollectionData =
575
+ this.importMap.get(targetCollectionKey);
576
+ if (!targetCollectionData || !targetCollectionData.data)
577
+ continue;
578
+
579
+ // Handle cases where sourceValue is an array
580
+ const sourceValues = Array.isArray(sourceValue)
581
+ ? sourceValue.map((sourceValue) => `${sourceValue}`)
582
+ : [`${sourceValue}`];
583
+ let newData = [];
584
+
585
+ for (const valueToMatch of sourceValues) {
586
+ // Find matching data in the target collection
587
+ const foundData = targetCollectionData.data.filter(
588
+ ({ context, finalData }) => {
589
+ const targetValue = this.getValueFromData(
590
+ finalData,
591
+ context,
592
+ targetFieldKey
593
+ );
594
+ const isMatch = `${targetValue}` === `${valueToMatch}`;
595
+ // Ensure the targetValue is defined and not null
596
+ return (
597
+ isMatch &&
598
+ targetValue !== undefined &&
599
+ targetValue !== null
600
+ );
601
+ }
602
+ );
603
+
604
+ if (foundData.length) {
605
+ newData.push(
606
+ ...foundData.map((data) => {
607
+ const newValue = this.getValueFromData(
608
+ data.finalData,
609
+ data.context,
610
+ idMapping.targetField
611
+ );
612
+ return newValue;
613
+ })
614
+ );
615
+ } else {
616
+ logger.info(
617
+ `No data found for collection: ${targetCollectionKey} with value: ${valueToMatch} for field: ${fieldToSetKey} -- idMapping: ${JSON.stringify(
618
+ idMapping,
619
+ null,
620
+ 2
621
+ )}`
622
+ );
623
+ }
624
+ continue;
625
+ }
626
+
627
+ const getCurrentDataFiltered = (currentData: any) => {
628
+ if (Array.isArray(currentData.finalData[fieldToSetKey])) {
629
+ return currentData.finalData[fieldToSetKey].filter(
630
+ (data: any) => !sourceValues.includes(`${data}`)
631
+ );
632
+ }
633
+ return currentData.finalData[fieldToSetKey];
634
+ };
635
+
636
+ // Get the current data to be updated
637
+ const currentDataFiltered = getCurrentDataFiltered(
638
+ collectionData.data[i]
639
+ );
640
+
641
+ if (newData.length) {
642
+ needsUpdate = true;
643
+
644
+ // Handle cases where current data is an array
645
+ if (isFieldToSetArray) {
646
+ if (!currentDataFiltered) {
647
+ // Set new data if current data is undefined
648
+ collectionData.data[i].finalData[fieldToSetKey] =
649
+ Array.isArray(newData) ? newData : [newData];
650
+ } else {
651
+ if (Array.isArray(currentDataFiltered)) {
652
+ // Convert current data to array and merge if new data is non-empty array
653
+ collectionData.data[i].finalData[fieldToSetKey] = [
654
+ ...new Set(
655
+ [...currentDataFiltered, ...newData].filter(
656
+ (value: any) =>
657
+ value !== null &&
658
+ value !== undefined &&
659
+ value !== ""
660
+ )
661
+ ),
662
+ ];
663
+ } else {
664
+ // Merge arrays if new data is non-empty array and filter for uniqueness
665
+ collectionData.data[i].finalData[fieldToSetKey] = [
666
+ ...new Set(
667
+ [
668
+ ...(Array.isArray(currentDataFiltered)
669
+ ? currentDataFiltered
670
+ : [currentDataFiltered]),
671
+ ...newData,
672
+ ].filter(
673
+ (value: any) =>
674
+ value !== null &&
675
+ value !== undefined &&
676
+ value !== "" &&
677
+ !sourceValues.includes(`${value}`)
678
+ )
679
+ ),
680
+ ];
681
+ }
682
+ }
683
+ } else {
684
+ if (!currentDataFiltered) {
685
+ // Set new data if current data is undefined
686
+ collectionData.data[i].finalData[fieldToSetKey] =
687
+ Array.isArray(newData) ? newData[0] : newData;
688
+ } else if (Array.isArray(newData) && newData.length > 0) {
689
+ // Convert current data to array and merge if new data is non-empty array, then filter for uniqueness
690
+ // and take the first value, because it's an array and the attribute is not an array
691
+ collectionData.data[i].finalData[fieldToSetKey] = [
692
+ ...new Set(
693
+ [currentDataFiltered, ...newData].filter(
694
+ (value: any) =>
695
+ value !== null &&
696
+ value !== undefined &&
697
+ value !== "" &&
698
+ !sourceValues.includes(`${value}`)
699
+ )
700
+ ),
701
+ ].slice(0, 1)[0];
702
+ } else if (
703
+ !Array.isArray(newData) &&
704
+ newData !== undefined
705
+ ) {
706
+ // Simply update the field if new data is not an array and defined
707
+ collectionData.data[i].finalData[fieldToSetKey] = newData;
708
+ }
709
+ }
710
+ }
711
+ }
712
+ }
713
+ }
714
+ }
715
+ }
716
+
717
+ // Update the import map if any changes were made
718
+ if (needsUpdate) {
719
+ this.importMap.set(collectionKey, collectionData);
720
+ }
721
+ }
722
+ }
723
+
724
+ private writeMapsToJsonFile() {
725
+ const outputDir = path.resolve(process.cwd(), "zlogs");
726
+
727
+ // Ensure the logs directory exists
728
+ if (!fs.existsSync(outputDir)) {
729
+ fs.mkdirSync(outputDir);
730
+ }
731
+
732
+ // Helper function to write data to a file
733
+ const writeToFile = (fileName: string, data: any) => {
734
+ const outputFile = path.join(outputDir, fileName);
735
+ fs.writeFile(outputFile, JSON.stringify(data, null, 2), "utf8", (err) => {
736
+ if (err) {
737
+ MessageFormatter.error(`Error writing data to ${fileName}`, err instanceof Error ? err : new Error(String(err)), { prefix: "Data" });
738
+ return;
739
+ }
740
+ MessageFormatter.success(`Data successfully written to ${fileName}`, { prefix: "Data" });
741
+ });
742
+ };
743
+
744
+ // Convert Maps to arrays of entries for serialization
745
+ const oldIdToNewIdPerCollectionMap = Array.from(
746
+ this.oldIdToNewIdPerCollectionMap.entries()
747
+ ).map(([key, value]) => {
748
+ return {
749
+ collection: key,
750
+ data: Array.from(value.entries()),
751
+ };
752
+ });
753
+
754
+ const mergedUserMap = Array.from(this.mergedUserMap.entries());
755
+
756
+ // Write each part to a separate file
757
+ writeToFile(
758
+ "oldIdToNewIdPerCollectionMap.json",
759
+ oldIdToNewIdPerCollectionMap
760
+ );
761
+ writeToFile("mergedUserMap.json", mergedUserMap);
762
+
763
+ // Write each collection's data to a separate file
764
+ this.importMap.forEach((value, key) => {
765
+ const data = {
766
+ collection: key,
767
+ data: value.data.map((item: any) => {
768
+ return {
769
+ finalData: item.finalData,
770
+ context: item.context,
771
+ };
772
+ }),
773
+ };
774
+ writeToFile(`${key}.json`, data);
775
+ });
776
+ }
777
+
778
+ /**
779
+ * Prepares user data by checking for duplicates based on email or phone, adding to a duplicate map if found,
780
+ * and then returning the transformed item without user-specific keys.
781
+ *
782
+ * @param item - The raw item to be processed.
783
+ * @param attributeMappings - The attribute mappings for the item.
784
+ * @returns The transformed item with user-specific keys removed.
785
+ */
786
+ prepareUserData(
787
+ item: any,
788
+ attributeMappings: AttributeMappings,
789
+ primaryKeyField: string,
790
+ newId: string
791
+ ): {
792
+ transformedItem: any;
793
+ existingId: string | undefined;
794
+ userData: {
795
+ rawData: any;
796
+ finalData: z.infer<typeof AuthUserCreateSchema>;
797
+ };
798
+ } {
799
+ if (
800
+ this.userIdSet.has(newId) ||
801
+ this.userExistsMap.has(newId) ||
802
+ Array.from(this.emailToUserIdMap.values()).includes(newId) ||
803
+ Array.from(this.phoneToUserIdMap.values()).includes(newId)
804
+ ) {
805
+ newId = this.getTrueUniqueId(this.getCollectionKey("users"));
806
+ }
807
+ let transformedItem = this.transformData(item, attributeMappings);
808
+ let userData = AuthUserCreateSchema.safeParse(transformedItem);
809
+ if (userData.data?.email) {
810
+ userData.data.email = userData.data.email.toLowerCase();
811
+ }
812
+ if (!userData.success || !(userData.data.email || userData.data.phone)) {
813
+ logger.error(
814
+ `Invalid user data: ${JSON.stringify(
815
+ userData.error?.issues,
816
+ undefined,
817
+ 2
818
+ )} or missing email/phone`
819
+ );
820
+
821
+ const userKeys = ["email", "phone", "name", "labels", "prefs"];
822
+ userKeys.forEach((key) => {
823
+ if (transformedItem.hasOwnProperty(key)) {
824
+ delete transformedItem[key];
825
+ }
826
+ });
827
+ return {
828
+ transformedItem,
829
+ existingId: undefined,
830
+ userData: {
831
+ rawData: item,
832
+ finalData: transformedItem,
833
+ },
834
+ };
835
+ }
836
+ const email = userData.data.email?.toLowerCase();
837
+ const phone = userData.data.phone;
838
+ let existingId: string | undefined;
839
+
840
+ // Check for duplicate email and phone
841
+ if (email && this.emailToUserIdMap.has(email)) {
842
+ existingId = this.emailToUserIdMap.get(email);
843
+ if (phone && !this.phoneToUserIdMap.has(phone)) {
844
+ this.phoneToUserIdMap.set(phone, newId);
845
+ }
846
+ } else if (phone && this.phoneToUserIdMap.has(phone)) {
847
+ existingId = this.phoneToUserIdMap.get(phone);
848
+ if (email && !this.emailToUserIdMap.has(email)) {
849
+ this.emailToUserIdMap.set(email, newId);
850
+ }
851
+ } else {
852
+ if (email) this.emailToUserIdMap.set(email, newId);
853
+ if (phone) this.phoneToUserIdMap.set(phone, newId);
854
+ }
855
+
856
+ if (existingId) {
857
+ userData.data.userId = existingId;
858
+ const mergedUsers = this.mergedUserMap.get(existingId) || [];
859
+ mergedUsers.push(`${item[primaryKeyField]}`);
860
+ this.mergedUserMap.set(existingId, mergedUsers);
861
+ const userFound = this.importMap
862
+ .get(this.getCollectionKey("users"))
863
+ ?.data.find((userDataExisting) => {
864
+ let userIdToMatch: string | undefined;
865
+ if (userDataExisting?.finalData?.userId) {
866
+ userIdToMatch = userDataExisting?.finalData?.userId;
867
+ } else if (userDataExisting?.finalData?.docId) {
868
+ userIdToMatch = userDataExisting?.finalData?.docId;
869
+ } else if (userDataExisting?.context?.userId) {
870
+ userIdToMatch = userDataExisting.context.userId;
871
+ } else if (userDataExisting?.context?.docId) {
872
+ userIdToMatch = userDataExisting.context.docId;
873
+ }
874
+ return userIdToMatch === existingId;
875
+ });
876
+ if (userFound) {
877
+ userFound.finalData.userId = existingId;
878
+ userFound.finalData.docId = existingId;
879
+ this.userIdSet.add(existingId);
880
+ transformedItem = {
881
+ ...transformedItem,
882
+ userId: existingId,
883
+ docId: existingId,
884
+ };
885
+ }
886
+
887
+ const userKeys = ["email", "phone", "name", "labels", "prefs"];
888
+ userKeys.forEach((key) => {
889
+ if (transformedItem.hasOwnProperty(key)) {
890
+ delete transformedItem[key];
891
+ }
892
+ });
893
+ return {
894
+ transformedItem,
895
+ existingId,
896
+ userData: {
897
+ rawData: userFound?.rawData,
898
+ finalData: userFound?.finalData,
899
+ },
900
+ };
901
+ } else {
902
+ existingId = newId;
903
+ userData.data.userId = existingId;
904
+ }
905
+
906
+ const userKeys = ["email", "phone", "name", "labels", "prefs"];
907
+ userKeys.forEach((key) => {
908
+ if (transformedItem.hasOwnProperty(key)) {
909
+ delete transformedItem[key];
910
+ }
911
+ });
912
+
913
+ const usersMap = this.importMap.get(this.getCollectionKey("users"));
914
+ const userDataToAdd = {
915
+ rawData: item,
916
+ finalData: userData.data,
917
+ context: {},
918
+ };
919
+ this.importMap.set(this.getCollectionKey("users"), {
920
+ data: [...(usersMap?.data || []), userDataToAdd],
921
+ });
922
+ this.userIdSet.add(existingId);
923
+
924
+ return {
925
+ transformedItem,
926
+ existingId,
927
+ userData: userDataToAdd,
928
+ };
929
+ }
930
+
931
+ /**
932
+ * Prepares the data for creating user collection documents.
933
+ * This involves loading the data, transforming it according to the import definition,
934
+ * and handling the creation of new unique IDs for each item.
935
+ *
936
+ * @param db - The database configuration.
937
+ * @param collection - The collection configuration.
938
+ * @param importDef - The import definition containing the attribute mappings and other relevant info.
939
+ */
940
+ async prepareUserCollectionCreateData(
941
+ db: ConfigDatabase,
942
+ collection: CollectionCreate,
943
+ importDef: ImportDef
944
+ ): Promise<void> {
945
+ // Load the raw data based on the import definition
946
+ const rawData = this.loadData(importDef);
947
+ let operationId = this.collectionImportOperations.get(
948
+ this.getCollectionKey(collection.name)
949
+ );
950
+ // Initialize a new map for old ID to new ID mappings
951
+ const oldIdToNewIdMap = new Map<string, string>();
952
+ // Retrieve or initialize the collection-specific old ID to new ID map
953
+ const collectionOldIdToNewIdMap =
954
+ this.oldIdToNewIdPerCollectionMap.get(
955
+ this.getCollectionKey(collection.name)
956
+ ) ||
957
+ this.oldIdToNewIdPerCollectionMap
958
+ .set(this.getCollectionKey(collection.name), oldIdToNewIdMap)
959
+ .get(this.getCollectionKey(collection.name));
960
+ const adapter = new LegacyAdapter(this.database.client);
961
+ if (!operationId) {
962
+ const collectionImportOperation = await findOrCreateOperation(
963
+ adapter,
964
+ db.$id,
965
+ "importData",
966
+ collection.$id!
967
+ );
968
+ // Store the operation ID in the map
969
+ this.collectionImportOperations.set(
970
+ this.getCollectionKey(collection.name),
971
+ collectionImportOperation.$id
972
+ );
973
+ operationId = collectionImportOperation.$id;
974
+ }
975
+ if (operationId) {
976
+ await updateOperation(adapter, db.$id, operationId, {
977
+ status: "ready",
978
+ total: rawData.length,
979
+ });
980
+ }
981
+ // Retrieve the current user data and the current collection data from the import map
982
+ const currentUserData = this.importMap.get(this.getCollectionKey("users"));
983
+ const currentData = this.importMap.get(
984
+ this.getCollectionKey(collection.name)
985
+ );
986
+ // Log errors if the necessary data is not found in the import map
987
+ if (!currentUserData) {
988
+ logger.error(
989
+ `No data found for collection ${"users"} for createDef but it says it's supposed to have one...`
990
+ );
991
+ return;
992
+ } else if (!currentData) {
993
+ logger.error(
994
+ `No data found for collection ${collection.name} for createDef but it says it's supposed to have one...`
995
+ );
996
+ return;
997
+ }
998
+ // Iterate through each item in the raw data
999
+ for (const item of rawData) {
1000
+ // Prepare user data, check for duplicates, and remove user-specific keys
1001
+ let { transformedItem, existingId, userData } = this.prepareUserData(
1002
+ item,
1003
+ importDef.attributeMappings,
1004
+ importDef.primaryKeyField,
1005
+ this.getTrueUniqueId(this.getCollectionKey("users"))
1006
+ );
1007
+
1008
+ logger.info(
1009
+ `In create user -- transformedItem: ${JSON.stringify(
1010
+ transformedItem,
1011
+ null,
1012
+ 2
1013
+ )}`
1014
+ );
1015
+
1016
+ // Generate a new unique ID for the item or use existing ID
1017
+ if (!existingId && !userData.finalData?.userId) {
1018
+ // No existing user ID, generate a new unique ID
1019
+ existingId = this.getTrueUniqueId(
1020
+ this.getCollectionKey(collection.name)
1021
+ );
1022
+ transformedItem = {
1023
+ ...transformedItem,
1024
+ userId: existingId,
1025
+ docId: existingId,
1026
+ };
1027
+ } else if (!existingId && userData.finalData?.userId) {
1028
+ // Existing user ID, use it as the new ID
1029
+ existingId = userData.finalData.userId;
1030
+ transformedItem = {
1031
+ ...transformedItem,
1032
+ userId: existingId,
1033
+ docId: existingId,
1034
+ };
1035
+ }
1036
+
1037
+ // Create a context object for the item, including the new ID
1038
+ let context = this.createContext(db, collection, item, existingId!);
1039
+
1040
+ // Merge the transformed data into the context
1041
+ context = { ...context, ...transformedItem, ...userData.finalData };
1042
+
1043
+ // If a primary key field is defined, handle the ID mapping and check for duplicates
1044
+ if (importDef.primaryKeyField) {
1045
+ const oldId = item[importDef.primaryKeyField];
1046
+
1047
+ // Check if the oldId already exists to handle potential duplicates
1048
+ if (
1049
+ this.oldIdToNewIdPerCollectionMap
1050
+ .get(this.getCollectionKey(collection.name))
1051
+ ?.has(`${oldId}`)
1052
+ ) {
1053
+ // Found a duplicate oldId, now decide how to merge or handle these duplicates
1054
+ for (const data of currentData.data) {
1055
+ if (
1056
+ data.finalData.docId === oldId ||
1057
+ data.finalData.userId === oldId ||
1058
+ data.context.docId === oldId ||
1059
+ data.context.userId === oldId
1060
+ ) {
1061
+ transformedItem = this.mergeObjects(
1062
+ data.finalData,
1063
+ transformedItem
1064
+ );
1065
+ }
1066
+ }
1067
+ } else {
1068
+ // No duplicate found, simply map the oldId to the new itemId
1069
+ collectionOldIdToNewIdMap?.set(`${oldId}`, `${existingId}`);
1070
+ }
1071
+ }
1072
+
1073
+ // Handle merging for currentUserData
1074
+ for (let i = 0; i < currentUserData.data.length; i++) {
1075
+ const currentUserDataItem = currentUserData.data[i];
1076
+ const samePhones =
1077
+ currentUserDataItem.finalData.phone &&
1078
+ transformedItem.phone &&
1079
+ currentUserDataItem.finalData.phone === transformedItem.phone;
1080
+ const sameEmails =
1081
+ currentUserDataItem.finalData.email &&
1082
+ transformedItem.email &&
1083
+ currentUserDataItem.finalData.email === transformedItem.email;
1084
+ if (
1085
+ (currentUserDataItem.finalData.docId === existingId ||
1086
+ currentUserDataItem.finalData.userId === existingId) &&
1087
+ (samePhones || sameEmails) &&
1088
+ currentUserDataItem.finalData &&
1089
+ userData.finalData
1090
+ ) {
1091
+ const userDataMerged = this.mergeObjects(
1092
+ currentUserData.data[i].finalData,
1093
+ userData.finalData
1094
+ );
1095
+ currentUserData.data[i].finalData = userDataMerged;
1096
+ this.importMap.set(this.getCollectionKey("users"), currentUserData);
1097
+ }
1098
+ }
1099
+ // Update the attribute mappings with any actions that need to be performed post-import
1100
+ // We added the basePath to get the folder from the filePath
1101
+ const mappingsWithActions = this.getAttributeMappingsWithActions(
1102
+ importDef.attributeMappings,
1103
+ context,
1104
+ transformedItem
1105
+ );
1106
+ // Update the import definition with the new attribute mappings
1107
+ const newImportDef = {
1108
+ ...importDef,
1109
+ attributeMappings: mappingsWithActions,
1110
+ };
1111
+
1112
+ const updatedData = this.importMap.get(
1113
+ this.getCollectionKey(collection.name)
1114
+ )!;
1115
+
1116
+ let foundData = false;
1117
+ for (let i = 0; i < updatedData.data.length; i++) {
1118
+ if (
1119
+ updatedData.data[i].finalData.docId === existingId ||
1120
+ updatedData.data[i].finalData.userId === existingId ||
1121
+ updatedData.data[i].context.docId === existingId ||
1122
+ updatedData.data[i].context.userId === existingId
1123
+ ) {
1124
+ updatedData.data[i].finalData = this.mergeObjects(
1125
+ updatedData.data[i].finalData,
1126
+ transformedItem
1127
+ );
1128
+ updatedData.data[i].context = this.mergeObjects(
1129
+ updatedData.data[i].context,
1130
+ context
1131
+ );
1132
+ const mergedImportDef = {
1133
+ ...updatedData.data[i].importDef,
1134
+ idMappings: [
1135
+ ...(updatedData.data[i].importDef?.idMappings || []),
1136
+ ...(newImportDef.idMappings || []),
1137
+ ],
1138
+ attributeMappings: [
1139
+ ...(updatedData.data[i].importDef?.attributeMappings || []),
1140
+ ...(newImportDef.attributeMappings || []),
1141
+ ],
1142
+ };
1143
+ updatedData.data[i].importDef = mergedImportDef as ImportDef;
1144
+ this.importMap.set(
1145
+ this.getCollectionKey(collection.name),
1146
+ updatedData
1147
+ );
1148
+ this.oldIdToNewIdPerCollectionMap.set(
1149
+ this.getCollectionKey(collection.name),
1150
+ collectionOldIdToNewIdMap!
1151
+ );
1152
+
1153
+ foundData = true;
1154
+ }
1155
+ }
1156
+ if (!foundData) {
1157
+ // Add new data to the associated collection
1158
+ updatedData.data.push({
1159
+ rawData: item,
1160
+ context: context,
1161
+ importDef: newImportDef,
1162
+ finalData: transformedItem,
1163
+ });
1164
+ this.importMap.set(this.getCollectionKey(collection.name), updatedData);
1165
+ this.oldIdToNewIdPerCollectionMap.set(
1166
+ this.getCollectionKey(collection.name),
1167
+ collectionOldIdToNewIdMap!
1168
+ );
1169
+ }
1170
+ }
1171
+ }
1172
+
1173
+ /**
1174
+ * Prepares the data for creating documents in a collection.
1175
+ * This involves loading the data, transforming it, and handling ID mappings.
1176
+ *
1177
+ * @param db - The database configuration.
1178
+ * @param collection - The collection configuration.
1179
+ * @param importDef - The import definition containing the attribute mappings and other relevant info.
1180
+ */
1181
+ async prepareCreateData(
1182
+ db: ConfigDatabase,
1183
+ collection: CollectionCreate,
1184
+ importDef: ImportDef
1185
+ ): Promise<void> {
1186
+ // Load the raw data based on the import definition
1187
+ const rawData = this.loadData(importDef);
1188
+ let operationId = this.collectionImportOperations.get(
1189
+ this.getCollectionKey(collection.name)
1190
+ );
1191
+ const adapter = new LegacyAdapter(this.database.client);
1192
+ if (!operationId) {
1193
+ const collectionImportOperation = await findOrCreateOperation(
1194
+ adapter,
1195
+ db.$id,
1196
+ "importData",
1197
+ collection.$id!
1198
+ );
1199
+ // Store the operation ID in the map
1200
+ this.collectionImportOperations.set(
1201
+ this.getCollectionKey(collection.name),
1202
+ collectionImportOperation.$id
1203
+ );
1204
+ operationId = collectionImportOperation.$id;
1205
+ }
1206
+ if (operationId) {
1207
+ await updateOperation(adapter, db.$id, operationId, {
1208
+ status: "ready",
1209
+ total: rawData.length,
1210
+ });
1211
+ }
1212
+ // Initialize a new map for old ID to new ID mappings
1213
+ const oldIdToNewIdMapNew = new Map<string, string>();
1214
+ // Retrieve or initialize the collection-specific old ID to new ID map
1215
+ const collectionOldIdToNewIdMap =
1216
+ this.oldIdToNewIdPerCollectionMap.get(
1217
+ this.getCollectionKey(collection.name)
1218
+ ) ||
1219
+ this.oldIdToNewIdPerCollectionMap
1220
+ .set(this.getCollectionKey(collection.name), oldIdToNewIdMapNew)
1221
+ .get(this.getCollectionKey(collection.name));
1222
+ const isRegions = collection.name.toLowerCase() === "regions";
1223
+ // Iterate through each item in the raw data
1224
+ for (const item of rawData) {
1225
+ // Generate a new unique ID for the item
1226
+ const itemIdNew = this.getTrueUniqueId(
1227
+ this.getCollectionKey(collection.name)
1228
+ );
1229
+ if (isRegions) {
1230
+ logger.info(`Creating region: ${JSON.stringify(item, null, 2)}`);
1231
+ }
1232
+ // Retrieve the current collection data from the import map
1233
+ const currentData = this.importMap.get(
1234
+ this.getCollectionKey(collection.name)
1235
+ );
1236
+ // Create a context object for the item, including the new ID
1237
+ let context = this.createContext(db, collection, item, itemIdNew);
1238
+ // Transform the item data based on the attribute mappings
1239
+ let transformedData = this.transformData(
1240
+ item,
1241
+ importDef.attributeMappings
1242
+ );
1243
+ // If a primary key field is defined, handle the ID mapping and check for duplicates
1244
+ if (importDef.primaryKeyField) {
1245
+ const oldId = item[importDef.primaryKeyField];
1246
+ if (collectionOldIdToNewIdMap?.has(`${oldId}`)) {
1247
+ logger.error(
1248
+ `Collection ${collection.name} has multiple documents with the same primary key ${oldId}`
1249
+ );
1250
+ continue;
1251
+ }
1252
+ collectionOldIdToNewIdMap?.set(`${oldId}`, `${itemIdNew}`);
1253
+ }
1254
+ // Merge the transformed data into the context
1255
+ context = { ...context, ...transformedData };
1256
+ // Validate the item before proceeding
1257
+ const isValid = this.importDataActions.validateItem(
1258
+ transformedData,
1259
+ importDef.attributeMappings,
1260
+ context
1261
+ );
1262
+ if (!isValid) {
1263
+ continue;
1264
+ }
1265
+ // Update the attribute mappings with any actions that need to be performed post-import
1266
+ // We added the basePath to get the folder from the filePath
1267
+ const mappingsWithActions = this.getAttributeMappingsWithActions(
1268
+ importDef.attributeMappings,
1269
+ context,
1270
+ transformedData
1271
+ );
1272
+ // Update the import definition with the new attribute mappings
1273
+ const newImportDef = {
1274
+ ...importDef,
1275
+ attributeMappings: mappingsWithActions,
1276
+ };
1277
+ // If the current collection data exists, add the item with its context and final data
1278
+ if (currentData && currentData.data) {
1279
+ currentData.data.push({
1280
+ rawData: item,
1281
+ context: context,
1282
+ importDef: newImportDef,
1283
+ finalData: transformedData,
1284
+ });
1285
+ this.importMap.set(this.getCollectionKey(collection.name), currentData);
1286
+ this.oldIdToNewIdPerCollectionMap.set(
1287
+ this.getCollectionKey(collection.name),
1288
+ collectionOldIdToNewIdMap!
1289
+ );
1290
+ } else {
1291
+ logger.error(
1292
+ `No data found for collection ${collection.name} for createDef but it says it's supposed to have one...`
1293
+ );
1294
+ continue;
1295
+ }
1296
+ }
1297
+ }
1298
+
1299
+ /**
1300
+ * Prepares the data for updating documents within a collection.
1301
+ * This method loads the raw data based on the import definition, transforms it according to the attribute mappings,
1302
+ * finds the new ID for each item based on the primary key or update mapping, and then validates the transformed data.
1303
+ * If the data is valid, it updates the import definition with any post-import actions and adds the item to the current collection data.
1304
+ *
1305
+ * @param db - The database configuration.
1306
+ * @param collection - The collection configuration.
1307
+ * @param importDef - The import definition containing the attribute mappings and other relevant info.
1308
+ */
1309
+ async prepareUpdateData(
1310
+ db: ConfigDatabase,
1311
+ collection: CollectionCreate,
1312
+ importDef: ImportDef
1313
+ ) {
1314
+ const currentData = this.importMap.get(
1315
+ this.getCollectionKey(collection.name)
1316
+ );
1317
+ const oldIdToNewIdMap = this.oldIdToNewIdPerCollectionMap.get(
1318
+ this.getCollectionKey(collection.name)
1319
+ );
1320
+
1321
+ if (
1322
+ !(currentData?.data && currentData?.data.length > 0) &&
1323
+ !oldIdToNewIdMap
1324
+ ) {
1325
+ logger.error(
1326
+ `No data found for collection ${collection.name} for updateDef but it says it's supposed to have one...`
1327
+ );
1328
+ return;
1329
+ }
1330
+
1331
+ const rawData = this.loadData(importDef);
1332
+ const operationId = this.collectionImportOperations.get(
1333
+ this.getCollectionKey(collection.name)
1334
+ );
1335
+ if (!operationId) {
1336
+ throw new Error(
1337
+ `No import operation found for collection ${collection.name}`
1338
+ );
1339
+ }
1340
+
1341
+ for (const item of rawData) {
1342
+ let transformedData = this.transformData(
1343
+ item,
1344
+ importDef.attributeMappings
1345
+ );
1346
+ let newId: string | undefined;
1347
+ let oldId: string | undefined;
1348
+ let itemDataToUpdate: CollectionImportData["data"][number] | undefined;
1349
+
1350
+ // Try to find itemDataToUpdate using updateMapping
1351
+ if (importDef.updateMapping) {
1352
+ oldId =
1353
+ item[importDef.updateMapping.originalIdField] ||
1354
+ transformedData[importDef.updateMapping.originalIdField];
1355
+ if (oldId) {
1356
+ itemDataToUpdate = currentData?.data.find(
1357
+ ({ context, finalData }) => {
1358
+ const targetField =
1359
+ importDef.updateMapping!.targetField ??
1360
+ importDef.updateMapping!.originalIdField;
1361
+
1362
+ return (
1363
+ `${context[targetField]}` === `${oldId}` ||
1364
+ `${finalData[targetField]}` === `${oldId}`
1365
+ );
1366
+ }
1367
+ );
1368
+
1369
+ if (itemDataToUpdate) {
1370
+ newId = itemDataToUpdate.context.docId;
1371
+ }
1372
+ }
1373
+ }
1374
+
1375
+ // If updateMapping is not defined or did not find the item, use primaryKeyField
1376
+ if (!itemDataToUpdate && importDef.primaryKeyField) {
1377
+ oldId =
1378
+ item[importDef.primaryKeyField] ||
1379
+ transformedData[importDef.primaryKeyField];
1380
+ if (oldId && oldId.length > 0) {
1381
+ newId = oldIdToNewIdMap?.get(`${oldId}`);
1382
+ if (
1383
+ !newId &&
1384
+ this.getCollectionKey(this.config.usersCollectionName) ===
1385
+ this.getCollectionKey(collection.name)
1386
+ ) {
1387
+ for (const [key, value] of this.mergedUserMap.entries()) {
1388
+ if (value.includes(`${oldId}`)) {
1389
+ newId = key;
1390
+ break;
1391
+ }
1392
+ }
1393
+ }
1394
+ }
1395
+
1396
+ if (oldId && !itemDataToUpdate) {
1397
+ itemDataToUpdate = currentData?.data.find(
1398
+ (data) =>
1399
+ `${data.context[importDef.primaryKeyField]}` === `${oldId}`
1400
+ );
1401
+ }
1402
+ }
1403
+
1404
+ if (!oldId) {
1405
+ logger.error(
1406
+ `No old ID found (to update another document with) in prepareUpdateData for ${
1407
+ collection.name
1408
+ }, ${JSON.stringify(item, null, 2)}`
1409
+ );
1410
+ continue;
1411
+ }
1412
+
1413
+ if (!newId && !itemDataToUpdate) {
1414
+ logger.error(
1415
+ `No new id && no data found for collection ${
1416
+ collection.name
1417
+ } for updateDef ${JSON.stringify(
1418
+ item,
1419
+ null,
1420
+ 2
1421
+ )} but it says it's supposed to have one...`
1422
+ );
1423
+ continue;
1424
+ } else if (itemDataToUpdate) {
1425
+ newId =
1426
+ itemDataToUpdate.finalData.docId || itemDataToUpdate.context.docId;
1427
+ if (!newId) {
1428
+ logger.error(
1429
+ `No new id found for collection ${
1430
+ collection.name
1431
+ } for updateDef ${JSON.stringify(
1432
+ item,
1433
+ null,
1434
+ 2
1435
+ )} but has itemDataToUpdate ${JSON.stringify(
1436
+ itemDataToUpdate,
1437
+ null,
1438
+ 2
1439
+ )} but it says it's supposed to have one...`
1440
+ );
1441
+ continue;
1442
+ }
1443
+ }
1444
+
1445
+ if (!itemDataToUpdate || !newId) {
1446
+ logger.error(
1447
+ `No data or ID (docId) found for collection ${
1448
+ collection.name
1449
+ } for updateDef ${JSON.stringify(
1450
+ item,
1451
+ null,
1452
+ 2
1453
+ )} but it says it's supposed to have one...`
1454
+ );
1455
+ continue;
1456
+ }
1457
+
1458
+ transformedData = this.mergeObjects(
1459
+ itemDataToUpdate.finalData,
1460
+ transformedData
1461
+ );
1462
+
1463
+ // Create a context object for the item, including the new ID and transformed data
1464
+ let context = itemDataToUpdate.context;
1465
+ context = this.mergeObjects(context, transformedData);
1466
+
1467
+ // Validate the item before proceeding
1468
+ const isValid = this.importDataActions.validateItem(
1469
+ item,
1470
+ importDef.attributeMappings,
1471
+ context
1472
+ );
1473
+
1474
+ if (!isValid) {
1475
+ logger.info(
1476
+ `Skipping item: ${JSON.stringify(item, null, 2)} because it's invalid`
1477
+ );
1478
+ continue;
1479
+ }
1480
+
1481
+ // Update the attribute mappings with any actions that need to be performed post-import
1482
+ // We added the basePath to get the folder from the filePath
1483
+ const mappingsWithActions = this.getAttributeMappingsWithActions(
1484
+ importDef.attributeMappings,
1485
+ context,
1486
+ transformedData
1487
+ );
1488
+
1489
+ // Update the import definition with the new attribute mappings
1490
+ const newImportDef = {
1491
+ ...importDef,
1492
+ attributeMappings: mappingsWithActions,
1493
+ };
1494
+
1495
+ if (itemDataToUpdate) {
1496
+ itemDataToUpdate.finalData = this.mergeObjects(
1497
+ itemDataToUpdate.finalData,
1498
+ transformedData
1499
+ );
1500
+ itemDataToUpdate.context = context;
1501
+
1502
+ // Fix: Ensure we properly merge the attribute mappings and their actions
1503
+ const mergedAttributeMappings = newImportDef.attributeMappings.map(
1504
+ (newMapping) => {
1505
+ const existingMapping =
1506
+ itemDataToUpdate.importDef?.attributeMappings.find(
1507
+ (m) => m.targetKey === newMapping.targetKey
1508
+ );
1509
+
1510
+ return {
1511
+ ...newMapping,
1512
+ postImportActions: [
1513
+ ...(existingMapping?.postImportActions || []),
1514
+ ...(newMapping.postImportActions || []),
1515
+ ],
1516
+ };
1517
+ }
1518
+ );
1519
+
1520
+ itemDataToUpdate.importDef = {
1521
+ ...newImportDef,
1522
+ attributeMappings: mergedAttributeMappings,
1523
+ };
1524
+
1525
+ // Debug logging
1526
+ if (
1527
+ mergedAttributeMappings.some((m) => m.postImportActions?.length > 0)
1528
+ ) {
1529
+ logger.info(
1530
+ `Post-import actions for ${collection.name}: ${JSON.stringify(
1531
+ mergedAttributeMappings
1532
+ .filter((m) => m.postImportActions?.length > 0)
1533
+ .map((m) => ({
1534
+ targetKey: m.targetKey,
1535
+ actions: m.postImportActions,
1536
+ })),
1537
+ null,
1538
+ 2
1539
+ )}`
1540
+ );
1541
+ }
1542
+ } else {
1543
+ currentData!.data.push({
1544
+ rawData: item,
1545
+ context: context,
1546
+ importDef: newImportDef,
1547
+ finalData: transformedData,
1548
+ });
1549
+ }
1550
+
1551
+ // Since we're modifying currentData in place, we ensure no duplicates are added
1552
+ this.importMap.set(this.getCollectionKey(collection.name), currentData!);
1553
+ }
1554
+ }
1555
+
1556
+ private updateReferencesBasedOnAttributeMappings() {
1557
+ if (!this.config.collections) {
1558
+ return;
1559
+ }
1560
+ this.config.collections.forEach((collectionConfig) => {
1561
+ const collectionName = collectionConfig.name;
1562
+ const collectionData = this.importMap.get(
1563
+ this.getCollectionKey(collectionName)
1564
+ );
1565
+
1566
+ if (!collectionData) {
1567
+ logger.error(`No data found for collection ${collectionName}`);
1568
+ return;
1569
+ }
1570
+
1571
+ collectionData.data.forEach((dataItem) => {
1572
+ collectionConfig.importDefs.forEach((importDef) => {
1573
+ if (!importDef.idMappings) return; // Skip collections without idMappings
1574
+ importDef.idMappings.forEach((mapping) => {
1575
+ if (mapping && mapping.targetField) {
1576
+ const idsToUpdate = Array.isArray(
1577
+ dataItem[mapping.targetField as keyof typeof dataItem]
1578
+ )
1579
+ ? dataItem[mapping.targetField as keyof typeof dataItem]
1580
+ : [dataItem[mapping.targetField as keyof typeof dataItem]];
1581
+ const updatedIds = idsToUpdate.map((id: string) =>
1582
+ this.getMergedId(id, mapping.targetCollection)
1583
+ );
1584
+
1585
+ // Update the dataItem with the new IDs
1586
+ dataItem[mapping.targetField as keyof typeof dataItem] =
1587
+ Array.isArray(
1588
+ dataItem[mapping.targetField as keyof typeof dataItem]
1589
+ )
1590
+ ? updatedIds
1591
+ : updatedIds[0];
1592
+ }
1593
+ });
1594
+ });
1595
+ });
1596
+ });
1597
+ }
1598
+
1599
+ private getMergedId(oldId: string, relatedCollectionName: string): string {
1600
+ // Retrieve the old to new ID map for the related collection
1601
+ const oldToNewIdMap = this.oldIdToNewIdPerCollectionMap.get(
1602
+ this.getCollectionKey(relatedCollectionName)
1603
+ );
1604
+
1605
+ // If there's a mapping for the old ID, return the new ID
1606
+ if (oldToNewIdMap && oldToNewIdMap.has(`${oldId}`)) {
1607
+ return oldToNewIdMap.get(`${oldId}`)!; // The non-null assertion (!) is used because we checked if the map has the key
1608
+ }
1609
+
1610
+ // If no mapping is found, return the old ID as a fallback
1611
+ return oldId;
1612
+ }
1613
+
1614
+ /**
1615
+ * Generates attribute mappings with post-import actions based on the provided attribute mappings.
1616
+ * This method checks each mapping for a fileData attribute and adds a post-import action to create a file
1617
+ * and update the field with the file's ID if necessary.
1618
+ *
1619
+ * @param attributeMappings - The attribute mappings from the import definition.
1620
+ * @param context - The context object containing information about the database, collection, and document.
1621
+ * @param item - The item being imported, used for resolving template paths in fileData mappings.
1622
+ * @returns The attribute mappings updated with any necessary post-import actions.
1623
+ */
1624
+ getAttributeMappingsWithActions(
1625
+ attributeMappings: AttributeMappings,
1626
+ context: any,
1627
+ item: any
1628
+ ) {
1629
+ // Iterate over each attribute mapping to check for fileData attributes
1630
+ return attributeMappings.map((mapping) => {
1631
+ if (mapping.fileData) {
1632
+ // Resolve the file path using the provided template, context, and item
1633
+ let mappingFilePath = this.importDataActions.resolveTemplate(
1634
+ mapping.fileData.path,
1635
+ context,
1636
+ item
1637
+ );
1638
+ // Ensure the file path is absolute if it doesn't start with "http"
1639
+ if (!mappingFilePath.toLowerCase().startsWith("http")) {
1640
+ // First try the direct path
1641
+ let fullPath = path.resolve(this.appwriteFolderPath, mappingFilePath);
1642
+
1643
+ // If file doesn't exist, search in subdirectories
1644
+ if (!fs.existsSync(fullPath)) {
1645
+ const findFileInDir = (dir: string): string | null => {
1646
+ const files = fs.readdirSync(dir);
1647
+
1648
+ for (const file of files) {
1649
+ const filePath = path.join(dir, file);
1650
+ const stat = fs.statSync(filePath);
1651
+
1652
+ if (stat.isDirectory()) {
1653
+ // Recursively search subdirectories
1654
+ const found = findFileInDir(filePath);
1655
+ if (found) return found;
1656
+ } else if (file === path.basename(mappingFilePath)) {
1657
+ return filePath;
1658
+ }
1659
+ }
1660
+ return null;
1661
+ };
1662
+
1663
+ const foundPath = findFileInDir(this.appwriteFolderPath);
1664
+ if (foundPath) {
1665
+ mappingFilePath = foundPath;
1666
+ } else {
1667
+ logger.warn(
1668
+ `File not found in any subdirectory: ${mappingFilePath}`
1669
+ );
1670
+ // Keep the original resolved path as fallback
1671
+ mappingFilePath = fullPath;
1672
+ }
1673
+ } else {
1674
+ mappingFilePath = fullPath;
1675
+ }
1676
+ }
1677
+ // Define the after-import action to create a file and update the field
1678
+ const afterImportAction = {
1679
+ action: "createFileAndUpdateField",
1680
+ params: [
1681
+ "{dbId}",
1682
+ "{collId}",
1683
+ "{docId}",
1684
+ mapping.targetKey,
1685
+ `${this.config!.documentBucketId}_${context.dbName
1686
+ .toLowerCase()
1687
+ .replace(" ", "")}`, // Assuming 'images' is your bucket ID
1688
+ mappingFilePath,
1689
+ mapping.fileData.name,
1690
+ ],
1691
+ };
1692
+ // Add the after-import action to the mapping's postImportActions array
1693
+ const postImportActions = mapping.postImportActions
1694
+ ? [...mapping.postImportActions, afterImportAction]
1695
+ : [afterImportAction];
1696
+ return { ...mapping, postImportActions };
1697
+ }
1698
+ // Return the mapping unchanged if no fileData attribute is found
1699
+ return mapping;
1700
+ });
1701
+ }
1702
+ }