@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,1317 @@
1
+ import { converterFunctions, tryAwaitWithRetry, parseAttribute, objectNeedsUpdate, } from "@njdamstra/appwrite-utils";
2
+ import { Client, Databases, Storage, Users, Functions, Teams, Query, AppwriteException, } from "node-appwrite";
3
+ import { InputFile } from "node-appwrite/file";
4
+ import { MessageFormatter } from "../shared/messageFormatter.js";
5
+ import { processQueue, queuedOperations } from "../shared/operationQueue.js";
6
+ import { ProgressManager } from "../shared/progressManager.js";
7
+ import { getClient } from "../utils/getClientFromConfig.js";
8
+ import { transferDatabaseLocalToLocal, transferDatabaseLocalToRemote, transferStorageLocalToLocal, transferStorageLocalToRemote, transferUsersLocalToRemote, } from "./transfer.js";
9
+ import { deployLocalFunction } from "../functions/deployments.js";
10
+ import { listFunctions, downloadLatestFunctionDeployment, } from "../functions/methods.js";
11
+ import pLimit from "p-limit";
12
+ import chalk from "chalk";
13
+ import { join } from "node:path";
14
+ import fs from "node:fs";
15
+ import { getAdapter } from "../utils/getClientFromConfig.js";
16
+ import { mapToCreateAttributeParams } from "../shared/attributeMapper.js";
17
+ export class ComprehensiveTransfer {
18
+ options;
19
+ sourceClient;
20
+ targetClient;
21
+ sourceUsers;
22
+ targetUsers;
23
+ sourceTeams;
24
+ targetTeams;
25
+ sourceDatabases;
26
+ targetDatabases;
27
+ sourceStorage;
28
+ targetStorage;
29
+ sourceFunctions;
30
+ targetFunctions;
31
+ limit;
32
+ userLimit;
33
+ fileLimit;
34
+ results;
35
+ startTime;
36
+ tempDir;
37
+ cachedMaxFileSize; // Cache successful maximumFileSize for subsequent buckets
38
+ sourceAdapter;
39
+ targetAdapter;
40
+ constructor(options) {
41
+ this.options = options;
42
+ this.sourceClient = getClient(options.sourceEndpoint, options.sourceProject, options.sourceKey);
43
+ this.targetClient = getClient(options.targetEndpoint, options.targetProject, options.targetKey);
44
+ this.sourceUsers = new Users(this.sourceClient);
45
+ this.targetUsers = new Users(this.targetClient);
46
+ this.sourceTeams = new Teams(this.sourceClient);
47
+ this.targetTeams = new Teams(this.targetClient);
48
+ this.sourceDatabases = new Databases(this.sourceClient);
49
+ this.targetDatabases = new Databases(this.targetClient);
50
+ this.sourceStorage = new Storage(this.sourceClient);
51
+ this.targetStorage = new Storage(this.targetClient);
52
+ this.sourceFunctions = new Functions(this.sourceClient);
53
+ this.targetFunctions = new Functions(this.targetClient);
54
+ const baseLimit = options.concurrencyLimit || 10;
55
+ this.limit = pLimit(baseLimit);
56
+ // Different rate limits for different operations to prevent API throttling
57
+ // Users: Half speed (more sensitive operations)
58
+ // Files: Quarter speed (most bandwidth intensive)
59
+ this.userLimit = pLimit(Math.max(1, Math.floor(baseLimit / 2)));
60
+ this.fileLimit = pLimit(Math.max(1, Math.floor(baseLimit / 4)));
61
+ this.results = {
62
+ users: { transferred: 0, skipped: 0, failed: 0 },
63
+ teams: { transferred: 0, skipped: 0, failed: 0 },
64
+ databases: { transferred: 0, skipped: 0, failed: 0 },
65
+ buckets: { transferred: 0, skipped: 0, failed: 0 },
66
+ functions: { transferred: 0, skipped: 0, failed: 0 },
67
+ totalTime: 0,
68
+ };
69
+ this.startTime = Date.now();
70
+ this.tempDir = join(process.cwd(), ".appwrite-transfer-temp");
71
+ }
72
+ async execute() {
73
+ try {
74
+ MessageFormatter.info("Starting comprehensive transfer", {
75
+ prefix: "Transfer",
76
+ });
77
+ // Initialize adapters for unified API (TablesDB or legacy via adapter)
78
+ const source = await getAdapter(this.options.sourceEndpoint, this.options.sourceProject, this.options.sourceKey, 'auto');
79
+ const target = await getAdapter(this.options.targetEndpoint, this.options.targetProject, this.options.targetKey, 'auto');
80
+ this.sourceAdapter = source.adapter;
81
+ this.targetAdapter = target.adapter;
82
+ if (this.options.dryRun) {
83
+ MessageFormatter.info("DRY RUN MODE - No actual changes will be made", {
84
+ prefix: "Transfer",
85
+ });
86
+ }
87
+ // Show rate limiting configuration
88
+ const baseLimit = this.options.concurrencyLimit || 10;
89
+ const userLimit = Math.max(1, Math.floor(baseLimit / 2));
90
+ const fileLimit = Math.max(1, Math.floor(baseLimit / 4));
91
+ MessageFormatter.info(`Rate limits: General=${baseLimit}, Users=${userLimit}, Files=${fileLimit}`, { prefix: "Transfer" });
92
+ // Ensure temp directory exists
93
+ if (!fs.existsSync(this.tempDir)) {
94
+ fs.mkdirSync(this.tempDir, { recursive: true });
95
+ }
96
+ // Execute transfers in the correct order
97
+ if (this.options.transferUsers !== false) {
98
+ await this.transferAllUsers();
99
+ }
100
+ if (this.options.transferTeams !== false) {
101
+ await this.transferAllTeams();
102
+ }
103
+ if (this.options.transferDatabases !== false) {
104
+ await this.transferAllDatabases();
105
+ }
106
+ if (this.options.transferBuckets !== false) {
107
+ await this.transferAllBuckets();
108
+ }
109
+ if (this.options.transferFunctions !== false) {
110
+ await this.transferAllFunctions();
111
+ }
112
+ this.results.totalTime = Date.now() - this.startTime;
113
+ this.printSummary();
114
+ return this.results;
115
+ }
116
+ catch (error) {
117
+ MessageFormatter.error("Comprehensive transfer failed", error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
118
+ throw error;
119
+ }
120
+ finally {
121
+ // Clean up temp directory
122
+ if (fs.existsSync(this.tempDir)) {
123
+ fs.rmSync(this.tempDir, { recursive: true, force: true });
124
+ }
125
+ }
126
+ }
127
+ async transferAllUsers() {
128
+ MessageFormatter.info("Starting user transfer phase", {
129
+ prefix: "Transfer",
130
+ });
131
+ if (this.options.dryRun) {
132
+ const usersList = await this.sourceUsers.list([Query.limit(1)]);
133
+ MessageFormatter.info(`DRY RUN: Would transfer ${usersList.total} users`, { prefix: "Transfer" });
134
+ return;
135
+ }
136
+ try {
137
+ // Use the existing user transfer function
138
+ // Note: The rate limiting is handled at the API level, not per-user
139
+ // since user operations are already sequential in the existing implementation
140
+ await transferUsersLocalToRemote(this.sourceUsers, this.options.targetEndpoint, this.options.targetProject, this.options.targetKey);
141
+ // Get actual count for results
142
+ const usersList = await this.sourceUsers.list([Query.limit(1)]);
143
+ this.results.users.transferred = usersList.total;
144
+ MessageFormatter.success(`User transfer completed`, {
145
+ prefix: "Transfer",
146
+ });
147
+ }
148
+ catch (error) {
149
+ MessageFormatter.error("User transfer failed", error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
150
+ this.results.users.failed = 1;
151
+ }
152
+ }
153
+ async transferAllTeams() {
154
+ MessageFormatter.info("Starting team transfer phase", {
155
+ prefix: "Transfer",
156
+ });
157
+ try {
158
+ // Fetch all teams from source with pagination
159
+ const allSourceTeams = await this.fetchAllTeams(this.sourceTeams);
160
+ const allTargetTeams = await this.fetchAllTeams(this.targetTeams);
161
+ if (this.options.dryRun) {
162
+ let totalMemberships = 0;
163
+ for (const team of allSourceTeams) {
164
+ const memberships = await this.sourceTeams.listMemberships(team.$id, [
165
+ Query.limit(1),
166
+ ]);
167
+ totalMemberships += memberships.total;
168
+ }
169
+ MessageFormatter.info(`DRY RUN: Would transfer ${allSourceTeams.length} teams with ${totalMemberships} memberships`, { prefix: "Transfer" });
170
+ return;
171
+ }
172
+ const transferTasks = allSourceTeams.map((team) => this.limit(async () => {
173
+ try {
174
+ // Check if team exists in target
175
+ const existingTeam = allTargetTeams.find((tt) => tt.$id === team.$id);
176
+ if (!existingTeam) {
177
+ // Fetch all memberships to extract unique roles before creating team
178
+ MessageFormatter.info(`Fetching memberships for team ${team.name} to extract roles`, { prefix: "Transfer" });
179
+ const memberships = await this.fetchAllMemberships(team.$id);
180
+ // Extract unique roles from all memberships
181
+ const allRoles = new Set();
182
+ memberships.forEach((membership) => {
183
+ membership.roles.forEach((role) => allRoles.add(role));
184
+ });
185
+ const uniqueRoles = Array.from(allRoles);
186
+ MessageFormatter.info(`Found ${uniqueRoles.length} unique roles for team ${team.name}: ${uniqueRoles.join(", ")}`, { prefix: "Transfer" });
187
+ // Create team in target with the collected roles
188
+ await this.targetTeams.create(team.$id, team.name, uniqueRoles);
189
+ MessageFormatter.success(`Created team: ${team.name} with roles: ${uniqueRoles.join(", ")}`, { prefix: "Transfer" });
190
+ }
191
+ else {
192
+ MessageFormatter.info(`Team ${team.name} already exists, updating if needed`, { prefix: "Transfer" });
193
+ // Update team if needed
194
+ if (existingTeam.name !== team.name) {
195
+ await this.targetTeams.updateName(team.$id, team.name);
196
+ MessageFormatter.success(`Updated team name: ${team.name}`, {
197
+ prefix: "Transfer",
198
+ });
199
+ }
200
+ }
201
+ // Transfer team memberships
202
+ await this.transferTeamMemberships(team.$id);
203
+ this.results.teams.transferred++;
204
+ MessageFormatter.success(`Team ${team.name} transferred successfully`, { prefix: "Transfer" });
205
+ }
206
+ catch (error) {
207
+ MessageFormatter.error(`Team ${team.name} transfer failed`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
208
+ this.results.teams.failed++;
209
+ }
210
+ }));
211
+ await Promise.all(transferTasks);
212
+ MessageFormatter.success("Team transfer phase completed", {
213
+ prefix: "Transfer",
214
+ });
215
+ }
216
+ catch (error) {
217
+ MessageFormatter.error("Team transfer phase failed", error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
218
+ }
219
+ }
220
+ async transferAllDatabases() {
221
+ MessageFormatter.info("Starting database transfer phase", {
222
+ prefix: "Transfer",
223
+ });
224
+ try {
225
+ const sourceDatabases = await this.sourceDatabases.list();
226
+ const targetDatabases = await this.targetDatabases.list();
227
+ if (this.options.dryRun) {
228
+ MessageFormatter.info(`DRY RUN: Would transfer ${sourceDatabases.databases.length} databases`, { prefix: "Transfer" });
229
+ return;
230
+ }
231
+ // Phase 1: Create all databases and collections (structure only)
232
+ MessageFormatter.info("Phase 1: Creating database structures (databases, collections, attributes, indexes)", { prefix: "Transfer" });
233
+ const structureCreationTasks = sourceDatabases.databases.map((db) => this.limit(async () => {
234
+ try {
235
+ // Check if database exists in target
236
+ const existingDb = targetDatabases.databases.find((tdb) => tdb.$id === db.$id);
237
+ if (!existingDb) {
238
+ // Create database in target
239
+ await this.targetDatabases.create(db.$id, db.name, db.enabled);
240
+ MessageFormatter.success(`Created database: ${db.name}`, {
241
+ prefix: "Transfer",
242
+ });
243
+ }
244
+ // Create collections, attributes, and indexes WITHOUT transferring documents
245
+ await this.createDatabaseStructure(db.$id);
246
+ MessageFormatter.success(`Database structure created: ${db.name}`, {
247
+ prefix: "Transfer",
248
+ });
249
+ }
250
+ catch (error) {
251
+ MessageFormatter.error(`Database structure creation failed for ${db.name}`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
252
+ this.results.databases.failed++;
253
+ }
254
+ }));
255
+ await Promise.all(structureCreationTasks);
256
+ // Phase 2: Transfer all documents after all structures are created
257
+ MessageFormatter.info("Phase 2: Transferring documents to all collections", { prefix: "Transfer" });
258
+ const documentTransferTasks = sourceDatabases.databases.map((db) => this.limit(async () => {
259
+ try {
260
+ // Transfer documents for this database
261
+ await this.transferDatabaseDocuments(db.$id);
262
+ this.results.databases.transferred++;
263
+ MessageFormatter.success(`Database documents transferred: ${db.name}`, { prefix: "Transfer" });
264
+ }
265
+ catch (error) {
266
+ MessageFormatter.error(`Document transfer failed for ${db.name}`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
267
+ this.results.databases.failed++;
268
+ }
269
+ }));
270
+ await Promise.all(documentTransferTasks);
271
+ MessageFormatter.success("Database transfer phase completed", {
272
+ prefix: "Transfer",
273
+ });
274
+ }
275
+ catch (error) {
276
+ MessageFormatter.error("Database transfer phase failed", error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
277
+ }
278
+ }
279
+ /**
280
+ * Phase 1: Create database structure (collections, attributes, indexes) without transferring documents
281
+ */
282
+ async createDatabaseStructure(dbId) {
283
+ MessageFormatter.info(`Creating database structure for ${dbId}`, {
284
+ prefix: "Transfer",
285
+ });
286
+ try {
287
+ // Get all collections from source database
288
+ const sourceCollections = await this.fetchAllCollections(dbId, this.sourceDatabases);
289
+ MessageFormatter.info(`Found ${sourceCollections.length} collections in source database ${dbId}`, { prefix: "Transfer" });
290
+ // Process each collection
291
+ for (const collection of sourceCollections) {
292
+ MessageFormatter.info(`Processing collection: ${collection.name} (${collection.$id})`, { prefix: "Transfer" });
293
+ try {
294
+ // Create or update collection in target
295
+ let targetCollection;
296
+ const existingCollection = await tryAwaitWithRetry(async () => this.targetDatabases.listCollections(dbId, [
297
+ Query.equal("$id", collection.$id),
298
+ ]));
299
+ if (existingCollection.collections.length > 0) {
300
+ targetCollection = existingCollection.collections[0];
301
+ MessageFormatter.info(`Collection ${collection.name} exists in target database`, { prefix: "Transfer" });
302
+ // Update collection if needed
303
+ if (targetCollection.name !== collection.name ||
304
+ JSON.stringify(targetCollection.$permissions) !==
305
+ JSON.stringify(collection.$permissions) ||
306
+ targetCollection.documentSecurity !==
307
+ collection.documentSecurity ||
308
+ targetCollection.enabled !== collection.enabled) {
309
+ targetCollection = await tryAwaitWithRetry(async () => this.targetDatabases.updateCollection(dbId, collection.$id, collection.name, collection.$permissions, collection.documentSecurity, collection.enabled));
310
+ MessageFormatter.success(`Collection ${collection.name} updated`, { prefix: "Transfer" });
311
+ }
312
+ }
313
+ else {
314
+ MessageFormatter.info(`Creating collection ${collection.name} in target database...`, { prefix: "Transfer" });
315
+ targetCollection = await tryAwaitWithRetry(async () => this.targetDatabases.createCollection(dbId, collection.$id, collection.name, collection.$permissions, collection.documentSecurity, collection.enabled));
316
+ MessageFormatter.success(`Collection ${collection.name} created`, {
317
+ prefix: "Transfer",
318
+ });
319
+ }
320
+ // Handle attributes with enhanced status checking
321
+ MessageFormatter.info(`Creating attributes for collection ${collection.name} with enhanced monitoring...`, { prefix: "Transfer" });
322
+ const attributesToCreate = collection.attributes.map((attr) => parseAttribute(attr));
323
+ const attributesSuccess = await this.createCollectionAttributesWithStatusCheck(this.targetDatabases, dbId, targetCollection, attributesToCreate);
324
+ if (!attributesSuccess) {
325
+ MessageFormatter.error(`Failed to create some attributes for collection ${collection.name}`, undefined, { prefix: "Transfer" });
326
+ MessageFormatter.error(`Skipping index creation and document transfer for collection ${collection.name} due to attribute failures`, undefined, { prefix: "Transfer" });
327
+ // Skip indexes and document transfer if attributes failed
328
+ continue;
329
+ }
330
+ else {
331
+ MessageFormatter.success(`All attributes created successfully for collection ${collection.name}`, { prefix: "Transfer" });
332
+ }
333
+ // Handle indexes with enhanced status checking
334
+ MessageFormatter.info(`Creating indexes for collection ${collection.name} with enhanced monitoring...`, { prefix: "Transfer" });
335
+ let indexesSuccess = true;
336
+ // Check if indexes need to be created ahead of time
337
+ if (collection.indexes.some((index) => !targetCollection.indexes.some((ti) => ti.key === index.key ||
338
+ ti.attributes.sort().join(",") ===
339
+ index.attributes.sort().join(","))) ||
340
+ collection.indexes.length !== targetCollection.indexes.length) {
341
+ indexesSuccess = await this.createCollectionIndexesWithStatusCheck(dbId, this.targetDatabases, targetCollection.$id, targetCollection, collection.indexes);
342
+ }
343
+ if (!indexesSuccess) {
344
+ MessageFormatter.error(`Failed to create some indexes for collection ${collection.name}`, undefined, { prefix: "Transfer" });
345
+ MessageFormatter.warning(`Proceeding with document transfer despite index failures for collection ${collection.name}`, { prefix: "Transfer" });
346
+ }
347
+ else {
348
+ MessageFormatter.success(`All indexes created successfully for collection ${collection.name}`, { prefix: "Transfer" });
349
+ }
350
+ MessageFormatter.success(`Structure complete for collection ${collection.name}`, { prefix: "Transfer" });
351
+ }
352
+ catch (error) {
353
+ MessageFormatter.error(`Error processing collection ${collection.name}`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
354
+ }
355
+ }
356
+ // After processing all collections' attributes and indexes, process any queued
357
+ // relationship attributes so dependencies are resolved within this phase.
358
+ if (queuedOperations.length > 0) {
359
+ MessageFormatter.info(`Processing ${queuedOperations.length} queued relationship operations`, { prefix: "Transfer" });
360
+ await processQueue(this.targetDatabases, dbId);
361
+ }
362
+ else {
363
+ MessageFormatter.info("No queued relationship operations to process", {
364
+ prefix: "Transfer",
365
+ });
366
+ }
367
+ }
368
+ catch (error) {
369
+ MessageFormatter.error(`Failed to create database structure for ${dbId}`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
370
+ throw error;
371
+ }
372
+ }
373
+ /**
374
+ * Phase 2: Transfer documents to all collections in the database
375
+ */
376
+ async transferDatabaseDocuments(dbId) {
377
+ MessageFormatter.info(`Transferring documents for database ${dbId}`, {
378
+ prefix: "Transfer",
379
+ });
380
+ try {
381
+ // Get all collections from source database
382
+ const sourceCollections = await this.fetchAllCollections(dbId, this.sourceDatabases);
383
+ MessageFormatter.info(`Transferring documents for ${sourceCollections.length} collections in database ${dbId}`, { prefix: "Transfer" });
384
+ // Process each collection
385
+ for (const collection of sourceCollections) {
386
+ MessageFormatter.info(`Transferring documents for collection: ${collection.name} (${collection.$id})`, { prefix: "Transfer" });
387
+ try {
388
+ // Transfer documents
389
+ await this.transferDocumentsBetweenDatabases(this.sourceDatabases, this.targetDatabases, dbId, dbId, collection.$id, collection.$id);
390
+ MessageFormatter.success(`Documents transferred for collection ${collection.name}`, { prefix: "Transfer" });
391
+ }
392
+ catch (error) {
393
+ MessageFormatter.error(`Error transferring documents for collection ${collection.name}`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
394
+ }
395
+ }
396
+ }
397
+ catch (error) {
398
+ MessageFormatter.error(`Failed to transfer documents for database ${dbId}`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
399
+ throw error;
400
+ }
401
+ }
402
+ async transferAllBuckets() {
403
+ MessageFormatter.info("Starting bucket transfer phase", {
404
+ prefix: "Transfer",
405
+ });
406
+ try {
407
+ // Get all buckets from source with pagination
408
+ const allSourceBuckets = await this.fetchAllBuckets(this.sourceStorage);
409
+ const allTargetBuckets = await this.fetchAllBuckets(this.targetStorage);
410
+ if (this.options.dryRun) {
411
+ let totalFiles = 0;
412
+ for (const bucket of allSourceBuckets) {
413
+ const files = await this.sourceStorage.listFiles(bucket.$id, [
414
+ Query.limit(1),
415
+ ]);
416
+ totalFiles += files.total;
417
+ }
418
+ MessageFormatter.info(`DRY RUN: Would transfer ${allSourceBuckets.length} buckets with ${totalFiles} files`, { prefix: "Transfer" });
419
+ return;
420
+ }
421
+ const transferTasks = allSourceBuckets.map((bucket) => this.limit(async () => {
422
+ try {
423
+ // Check if bucket exists in target
424
+ const existingBucket = allTargetBuckets.find((tb) => tb.$id === bucket.$id);
425
+ if (!existingBucket) {
426
+ // Create bucket with fallback strategy for maximumFileSize
427
+ await this.createBucketWithFallback(bucket);
428
+ MessageFormatter.success(`Created bucket: ${bucket.name}`, {
429
+ prefix: "Transfer",
430
+ });
431
+ }
432
+ else {
433
+ // Compare bucket permissions and update if needed
434
+ const sourcePermissions = JSON.stringify(bucket.$permissions?.sort() || []);
435
+ const targetPermissions = JSON.stringify(existingBucket.$permissions?.sort() || []);
436
+ if (sourcePermissions !== targetPermissions ||
437
+ existingBucket.name !== bucket.name ||
438
+ existingBucket.fileSecurity !== bucket.fileSecurity ||
439
+ existingBucket.enabled !== bucket.enabled) {
440
+ MessageFormatter.warning(`Bucket ${bucket.name} exists but has different settings. Updating to match source.`, { prefix: "Transfer" });
441
+ try {
442
+ await this.targetStorage.updateBucket(bucket.$id, bucket.name, bucket.$permissions, bucket.fileSecurity, bucket.enabled, bucket.maximumFileSize, bucket.allowedFileExtensions, bucket.compression, bucket.encryption, bucket.antivirus);
443
+ MessageFormatter.success(`Updated bucket ${bucket.name} to match source`, { prefix: "Transfer" });
444
+ }
445
+ catch (updateError) {
446
+ MessageFormatter.error(`Failed to update bucket ${bucket.name}`, updateError instanceof Error
447
+ ? updateError
448
+ : new Error(String(updateError)), { prefix: "Transfer" });
449
+ }
450
+ }
451
+ else {
452
+ MessageFormatter.info(`Bucket ${bucket.name} already exists with matching settings`, { prefix: "Transfer" });
453
+ }
454
+ }
455
+ // Transfer bucket files with enhanced validation
456
+ await this.transferBucketFiles(bucket.$id, bucket.$id);
457
+ this.results.buckets.transferred++;
458
+ MessageFormatter.success(`Bucket ${bucket.name} transferred successfully`, { prefix: "Transfer" });
459
+ }
460
+ catch (error) {
461
+ MessageFormatter.error(`Bucket ${bucket.name} transfer failed`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
462
+ this.results.buckets.failed++;
463
+ }
464
+ }));
465
+ await Promise.all(transferTasks);
466
+ MessageFormatter.success("Bucket transfer phase completed", {
467
+ prefix: "Transfer",
468
+ });
469
+ }
470
+ catch (error) {
471
+ MessageFormatter.error("Bucket transfer phase failed", error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
472
+ }
473
+ }
474
+ async createBucketWithFallback(bucket) {
475
+ // Determine the optimal size to try first
476
+ let sizeToTry;
477
+ if (this.cachedMaxFileSize) {
478
+ // Use cached size if it's smaller than or equal to the bucket's original size
479
+ if (bucket.maximumFileSize >= this.cachedMaxFileSize) {
480
+ sizeToTry = this.cachedMaxFileSize;
481
+ MessageFormatter.info(`Bucket ${bucket.name}: Using cached maximumFileSize ${sizeToTry} (${(sizeToTry / 1_000_000_000).toFixed(1)}GB)`, { prefix: "Transfer" });
482
+ }
483
+ else {
484
+ // Original size is smaller than cached size, try original first
485
+ sizeToTry = bucket.maximumFileSize;
486
+ }
487
+ }
488
+ else {
489
+ // No cached size yet, try original size first
490
+ sizeToTry = bucket.maximumFileSize;
491
+ }
492
+ // Try the optimal size first
493
+ try {
494
+ await this.targetStorage.createBucket(bucket.$id, bucket.name, bucket.$permissions, bucket.fileSecurity, bucket.enabled, sizeToTry, bucket.allowedFileExtensions, bucket.compression, bucket.encryption, bucket.antivirus);
495
+ // Success - cache this size if it's not already cached or is smaller than cached
496
+ if (!this.cachedMaxFileSize || sizeToTry < this.cachedMaxFileSize) {
497
+ this.cachedMaxFileSize = sizeToTry;
498
+ MessageFormatter.info(`Bucket ${bucket.name}: Cached successful maximumFileSize ${sizeToTry} (${(sizeToTry / 1_000_000_000).toFixed(1)}GB)`, { prefix: "Transfer" });
499
+ }
500
+ // Log if we used a different size than original
501
+ if (sizeToTry !== bucket.maximumFileSize) {
502
+ MessageFormatter.warning(`Bucket ${bucket.name}: maximumFileSize used ${sizeToTry} instead of original ${bucket.maximumFileSize} (${(sizeToTry / 1_000_000_000).toFixed(1)}GB)`, { prefix: "Transfer" });
503
+ }
504
+ return; // Success, exit the function
505
+ }
506
+ catch (error) {
507
+ const err = error instanceof Error ? error : new Error(String(error));
508
+ // Check if the error is related to maximumFileSize validation
509
+ if (err.message.includes("maximumFileSize") ||
510
+ err.message.includes("valid range")) {
511
+ MessageFormatter.warning(`Bucket ${bucket.name}: Failed with maximumFileSize ${sizeToTry}, falling back to smaller sizes...`, { prefix: "Transfer" });
512
+ // Continue to fallback logic below
513
+ }
514
+ else {
515
+ // Different error, don't retry
516
+ throw err;
517
+ }
518
+ }
519
+ // Fallback to progressively smaller sizes
520
+ const fallbackSizes = [
521
+ 5_000_000_000, // 5GB
522
+ 2_500_000_000, // 2.5GB
523
+ 2_000_000_000, // 2GB
524
+ 1_000_000_000, // 1GB
525
+ 500_000_000, // 500MB
526
+ 100_000_000, // 100MB
527
+ ];
528
+ // Remove sizes that are larger than or equal to the already-tried size
529
+ const validSizes = fallbackSizes
530
+ .filter((size) => size < sizeToTry)
531
+ .sort((a, b) => b - a); // Sort descending
532
+ let lastError = null;
533
+ for (const fileSize of validSizes) {
534
+ try {
535
+ await this.targetStorage.createBucket(bucket.$id, bucket.name, bucket.$permissions, bucket.fileSecurity, bucket.enabled, fileSize, bucket.allowedFileExtensions, bucket.compression, bucket.encryption, bucket.antivirus);
536
+ // Success - cache this size if it's not already cached or is smaller than cached
537
+ if (!this.cachedMaxFileSize || fileSize < this.cachedMaxFileSize) {
538
+ this.cachedMaxFileSize = fileSize;
539
+ MessageFormatter.info(`Bucket ${bucket.name}: Cached successful maximumFileSize ${fileSize} (${(fileSize / 1_000_000_000).toFixed(1)}GB)`, { prefix: "Transfer" });
540
+ }
541
+ // Log if we had to reduce the file size
542
+ if (fileSize !== bucket.maximumFileSize) {
543
+ MessageFormatter.warning(`Bucket ${bucket.name}: maximumFileSize reduced from ${bucket.maximumFileSize} to ${fileSize} (${(fileSize / 1_000_000_000).toFixed(1)}GB)`, { prefix: "Transfer" });
544
+ }
545
+ return; // Success, exit the function
546
+ }
547
+ catch (error) {
548
+ lastError = error instanceof Error ? error : new Error(String(error));
549
+ // Check if the error is related to maximumFileSize validation
550
+ if (lastError.message.includes("maximumFileSize") ||
551
+ lastError.message.includes("valid range")) {
552
+ MessageFormatter.warning(`Bucket ${bucket.name}: Failed with maximumFileSize ${fileSize}, trying smaller size...`, { prefix: "Transfer" });
553
+ continue; // Try next smaller size
554
+ }
555
+ else {
556
+ // Different error, don't retry
557
+ throw lastError;
558
+ }
559
+ }
560
+ }
561
+ // If we get here, all fallback sizes failed
562
+ MessageFormatter.error(`Bucket ${bucket.name}: All fallback file sizes failed. Last error: ${lastError?.message}`, lastError || undefined, { prefix: "Transfer" });
563
+ throw lastError || new Error("All fallback file sizes failed");
564
+ }
565
+ async transferBucketFiles(sourceBucketId, targetBucketId) {
566
+ let lastFileId;
567
+ let transferredFiles = 0;
568
+ while (true) {
569
+ const queries = [Query.limit(50)]; // Smaller batch size for better rate limiting
570
+ if (lastFileId) {
571
+ queries.push(Query.cursorAfter(lastFileId));
572
+ }
573
+ const files = await this.sourceStorage.listFiles(sourceBucketId, queries);
574
+ if (files.files.length === 0)
575
+ break;
576
+ // Process files with rate limiting
577
+ const fileTasks = files.files.map((file) => this.fileLimit(async () => {
578
+ try {
579
+ // Check if file already exists and compare permissions
580
+ let existingFile = null;
581
+ try {
582
+ existingFile = await this.targetStorage.getFile(targetBucketId, file.$id);
583
+ // Compare permissions between source and target file
584
+ const sourcePermissions = JSON.stringify(file.$permissions?.sort() || []);
585
+ const targetPermissions = JSON.stringify(existingFile.$permissions?.sort() || []);
586
+ if (sourcePermissions !== targetPermissions) {
587
+ MessageFormatter.warning(`File ${file.name} (${file.$id}) exists but has different permissions. Source: ${sourcePermissions}, Target: ${targetPermissions}`, { prefix: "Transfer" });
588
+ // Update file permissions to match source
589
+ try {
590
+ await this.targetStorage.updateFile(targetBucketId, file.$id, file.name, file.$permissions);
591
+ MessageFormatter.success(`Updated file ${file.name} permissions to match source`, { prefix: "Transfer" });
592
+ }
593
+ catch (updateError) {
594
+ MessageFormatter.error(`Failed to update permissions for file ${file.name}`, updateError instanceof Error
595
+ ? updateError
596
+ : new Error(String(updateError)), { prefix: "Transfer" });
597
+ }
598
+ }
599
+ else {
600
+ MessageFormatter.info(`File ${file.name} already exists with matching permissions, skipping`, { prefix: "Transfer" });
601
+ }
602
+ return;
603
+ }
604
+ catch (error) {
605
+ // File doesn't exist, proceed with transfer
606
+ }
607
+ // Download file with validation
608
+ const fileData = await this.validateAndDownloadFile(sourceBucketId, file.$id);
609
+ if (!fileData) {
610
+ MessageFormatter.warning(`File ${file.name} failed validation, skipping`, { prefix: "Transfer" });
611
+ return;
612
+ }
613
+ // Upload file to target
614
+ const fileToCreate = InputFile.fromBuffer(new Uint8Array(fileData), file.name);
615
+ await this.targetStorage.createFile(targetBucketId, file.$id, fileToCreate, file.$permissions);
616
+ transferredFiles++;
617
+ MessageFormatter.success(`Transferred file: ${file.name}`, {
618
+ prefix: "Transfer",
619
+ });
620
+ }
621
+ catch (error) {
622
+ MessageFormatter.error(`Failed to transfer file ${file.name}`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
623
+ }
624
+ }));
625
+ await Promise.all(fileTasks);
626
+ if (files.files.length < 50)
627
+ break;
628
+ lastFileId = files.files[files.files.length - 1].$id;
629
+ }
630
+ MessageFormatter.info(`Transferred ${transferredFiles} files from bucket ${sourceBucketId}`, { prefix: "Transfer" });
631
+ }
632
+ async validateAndDownloadFile(bucketId, fileId) {
633
+ let attempts = 3;
634
+ while (attempts > 0) {
635
+ try {
636
+ const fileData = await this.sourceStorage.getFileDownload(bucketId, fileId);
637
+ // Basic validation - ensure file is not empty and not too large
638
+ if (fileData.byteLength === 0) {
639
+ MessageFormatter.warning(`File ${fileId} is empty`, {
640
+ prefix: "Transfer",
641
+ });
642
+ return null;
643
+ }
644
+ if (fileData.byteLength > 50 * 1024 * 1024) {
645
+ // 50MB limit
646
+ MessageFormatter.warning(`File ${fileId} is too large (${fileData.byteLength} bytes)`, { prefix: "Transfer" });
647
+ return null;
648
+ }
649
+ return fileData;
650
+ }
651
+ catch (error) {
652
+ attempts--;
653
+ MessageFormatter.warning(`Error downloading file ${fileId}, attempts left: ${attempts}`, { prefix: "Transfer" });
654
+ if (attempts === 0) {
655
+ MessageFormatter.error(`Failed to download file ${fileId} after all attempts`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
656
+ return null;
657
+ }
658
+ // Wait before retry
659
+ await new Promise((resolve) => setTimeout(resolve, 1000 * (4 - attempts)));
660
+ }
661
+ }
662
+ return null;
663
+ }
664
+ async transferAllFunctions() {
665
+ MessageFormatter.info("Starting function transfer phase", {
666
+ prefix: "Transfer",
667
+ });
668
+ try {
669
+ const sourceFunctions = await listFunctions(this.sourceClient, [
670
+ Query.limit(1000),
671
+ ]);
672
+ const targetFunctions = await listFunctions(this.targetClient, [
673
+ Query.limit(1000),
674
+ ]);
675
+ if (this.options.dryRun) {
676
+ MessageFormatter.info(`DRY RUN: Would transfer ${sourceFunctions.functions.length} functions`, { prefix: "Transfer" });
677
+ return;
678
+ }
679
+ const transferTasks = sourceFunctions.functions.map((func) => this.limit(async () => {
680
+ try {
681
+ // Check if function exists in target
682
+ const existingFunc = targetFunctions.functions.find((tf) => tf.$id === func.$id);
683
+ if (existingFunc) {
684
+ MessageFormatter.info(`Function ${func.name} already exists, skipping creation`, { prefix: "Transfer" });
685
+ this.results.functions.skipped++;
686
+ return;
687
+ }
688
+ // Download function from source
689
+ const functionPath = await this.downloadFunction(func);
690
+ if (!functionPath) {
691
+ MessageFormatter.error(`Failed to download function ${func.name}`, undefined, { prefix: "Transfer" });
692
+ this.results.functions.failed++;
693
+ return;
694
+ }
695
+ // Deploy function to target
696
+ const functionConfig = {
697
+ $id: func.$id,
698
+ name: func.name,
699
+ runtime: func.runtime,
700
+ execute: func.execute,
701
+ events: func.events,
702
+ enabled: func.enabled,
703
+ logging: func.logging,
704
+ entrypoint: func.entrypoint,
705
+ commands: func.commands,
706
+ scopes: func.scopes,
707
+ timeout: func.timeout,
708
+ schedule: func.schedule,
709
+ installationId: func.installationId,
710
+ providerRepositoryId: func.providerRepositoryId,
711
+ providerBranch: func.providerBranch,
712
+ providerSilentMode: func.providerSilentMode,
713
+ providerRootDirectory: func.providerRootDirectory,
714
+ specification: func.specification,
715
+ dirPath: functionPath,
716
+ };
717
+ await deployLocalFunction(this.targetClient, func.name, functionConfig);
718
+ this.results.functions.transferred++;
719
+ MessageFormatter.success(`Function ${func.name} transferred successfully`, { prefix: "Transfer" });
720
+ }
721
+ catch (error) {
722
+ MessageFormatter.error(`Function ${func.name} transfer failed`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
723
+ this.results.functions.failed++;
724
+ }
725
+ }));
726
+ await Promise.all(transferTasks);
727
+ MessageFormatter.success("Function transfer phase completed", {
728
+ prefix: "Transfer",
729
+ });
730
+ }
731
+ catch (error) {
732
+ MessageFormatter.error("Function transfer phase failed", error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
733
+ }
734
+ }
735
+ async downloadFunction(func) {
736
+ try {
737
+ const { path } = await downloadLatestFunctionDeployment(this.sourceClient, func.$id, this.tempDir);
738
+ return path;
739
+ }
740
+ catch (error) {
741
+ MessageFormatter.error(`Failed to download function ${func.name}`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
742
+ return null;
743
+ }
744
+ }
745
+ /**
746
+ * Helper method to fetch all collections from a database
747
+ */
748
+ async fetchAllCollections(dbId, databases) {
749
+ const collections = [];
750
+ let lastId;
751
+ while (true) {
752
+ const queries = [Query.limit(100)];
753
+ if (lastId) {
754
+ queries.push(Query.cursorAfter(lastId));
755
+ }
756
+ const result = await tryAwaitWithRetry(async () => databases.listCollections(dbId, queries));
757
+ if (result.collections.length === 0) {
758
+ break;
759
+ }
760
+ collections.push(...result.collections);
761
+ if (result.collections.length < 100) {
762
+ break;
763
+ }
764
+ lastId = result.collections[result.collections.length - 1].$id;
765
+ }
766
+ return collections;
767
+ }
768
+ /**
769
+ * Helper method to fetch all buckets with pagination
770
+ */
771
+ async fetchAllBuckets(storage) {
772
+ const buckets = [];
773
+ let lastId;
774
+ while (true) {
775
+ const queries = [Query.limit(100)];
776
+ if (lastId) {
777
+ queries.push(Query.cursorAfter(lastId));
778
+ }
779
+ const result = await tryAwaitWithRetry(async () => storage.listBuckets(queries));
780
+ if (result.buckets.length === 0) {
781
+ break;
782
+ }
783
+ buckets.push(...result.buckets);
784
+ if (result.buckets.length < 100) {
785
+ break;
786
+ }
787
+ lastId = result.buckets[result.buckets.length - 1].$id;
788
+ }
789
+ return buckets;
790
+ }
791
+ /**
792
+ * Helper method to parse attribute objects (simplified version of parseAttribute)
793
+ */
794
+ parseAttribute(attr) {
795
+ // This is a simplified version - in production you'd use the actual parseAttribute from appwrite-utils
796
+ return {
797
+ key: attr.key,
798
+ type: attr.type,
799
+ size: attr.size,
800
+ required: attr.required,
801
+ array: attr.array,
802
+ default: attr.default,
803
+ format: attr.format,
804
+ elements: attr.elements,
805
+ min: attr.min,
806
+ max: attr.max,
807
+ relatedCollection: attr.relatedCollection,
808
+ relationType: attr.relationType,
809
+ twoWay: attr.twoWay,
810
+ twoWayKey: attr.twoWayKey,
811
+ onDelete: attr.onDelete,
812
+ side: attr.side,
813
+ };
814
+ }
815
+ /**
816
+ * Helper method to create collection attributes with status checking
817
+ */
818
+ async createCollectionAttributesWithStatusCheck(databases, dbId, collection, attributes) {
819
+ if (!this.targetAdapter) {
820
+ throw new Error('Target adapter not initialized');
821
+ }
822
+ try {
823
+ // Create non-relationship attributes first
824
+ const nonRel = (attributes || []).filter((a) => a.type !== 'relationship');
825
+ for (const attr of nonRel) {
826
+ const params = mapToCreateAttributeParams(attr, { databaseId: dbId, tableId: collection.$id });
827
+ await this.targetAdapter.createAttribute(params);
828
+ // Small delay between creations
829
+ await new Promise((r) => setTimeout(r, 150));
830
+ }
831
+ // Wait for attributes to become available
832
+ for (const attr of nonRel) {
833
+ const maxWait = 60000; // 60s
834
+ const start = Date.now();
835
+ let lastStatus = '';
836
+ while (Date.now() - start < maxWait) {
837
+ try {
838
+ const tableRes = await this.targetAdapter.getTable({ databaseId: dbId, tableId: collection.$id });
839
+ const cols = tableRes.attributes || tableRes.columns || [];
840
+ const col = cols.find((c) => c.key === attr.key);
841
+ if (col) {
842
+ if (col.status === 'available')
843
+ break;
844
+ if (col.status === 'failed' || col.status === 'stuck') {
845
+ throw new Error(col.error || `Attribute ${attr.key} failed`);
846
+ }
847
+ lastStatus = col.status;
848
+ }
849
+ await new Promise((r) => setTimeout(r, 2000));
850
+ }
851
+ catch {
852
+ await new Promise((r) => setTimeout(r, 2000));
853
+ }
854
+ }
855
+ if (Date.now() - start >= maxWait) {
856
+ MessageFormatter.warning(`Attribute ${attr.key} did not become available within 60s (last status: ${lastStatus})`, { prefix: 'Attributes' });
857
+ }
858
+ }
859
+ // Create relationship attributes
860
+ const rels = (attributes || []).filter((a) => a.type === 'relationship');
861
+ for (const attr of rels) {
862
+ const params = mapToCreateAttributeParams(attr, { databaseId: dbId, tableId: collection.$id });
863
+ await this.targetAdapter.createAttribute(params);
864
+ await new Promise((r) => setTimeout(r, 150));
865
+ }
866
+ return true;
867
+ }
868
+ catch (e) {
869
+ MessageFormatter.error('Failed creating attributes via adapter', e instanceof Error ? e : new Error(String(e)), { prefix: 'Attributes' });
870
+ return false;
871
+ }
872
+ }
873
+ /**
874
+ * Helper method to create collection indexes with status checking
875
+ */
876
+ async createCollectionIndexesWithStatusCheck(dbId, databases, collectionId, collection, indexes) {
877
+ if (!this.targetAdapter) {
878
+ throw new Error('Target adapter not initialized');
879
+ }
880
+ try {
881
+ for (const idx of indexes || []) {
882
+ await this.targetAdapter.createIndex({
883
+ databaseId: dbId,
884
+ tableId: collectionId,
885
+ key: idx.key,
886
+ type: idx.type,
887
+ attributes: idx.attributes,
888
+ orders: idx.orders || []
889
+ });
890
+ await new Promise((r) => setTimeout(r, 150));
891
+ }
892
+ return true;
893
+ }
894
+ catch (e) {
895
+ MessageFormatter.error('Failed creating indexes via adapter', e instanceof Error ? e : new Error(String(e)), { prefix: 'Indexes' });
896
+ return false;
897
+ }
898
+ }
899
+ /**
900
+ * Helper method to transfer documents between databases using bulk operations with content and permission-based filtering
901
+ */
902
+ async transferDocumentsBetweenDatabases(sourceDb, targetDb, sourceDbId, targetDbId, sourceCollectionId, targetCollectionId) {
903
+ MessageFormatter.info(`Transferring documents from ${sourceCollectionId} to ${targetCollectionId} with bulk operations, content comparison, and permission filtering`, { prefix: "Transfer" });
904
+ let lastId;
905
+ let totalTransferred = 0;
906
+ let totalSkipped = 0;
907
+ let totalUpdated = 0;
908
+ // Check if bulk operations are supported
909
+ const bulkEnabled = false;
910
+ // Temporarily disable to see if it fixes my permissions issues
911
+ const supportsBulk = bulkEnabled ? this.options.targetEndpoint.includes("cloud.appwrite.io") : false;
912
+ if (supportsBulk) {
913
+ MessageFormatter.info(`Using bulk operations for enhanced performance`, {
914
+ prefix: "Transfer",
915
+ });
916
+ }
917
+ while (true) {
918
+ // Fetch source documents in larger batches (1000 instead of 50)
919
+ const queries = [Query.limit(1000)];
920
+ if (lastId) {
921
+ queries.push(Query.cursorAfter(lastId));
922
+ }
923
+ const sourceDocuments = await tryAwaitWithRetry(async () => sourceDb.listDocuments(sourceDbId, sourceCollectionId, queries));
924
+ if (sourceDocuments.documents.length === 0) {
925
+ break;
926
+ }
927
+ MessageFormatter.info(`Processing batch of ${sourceDocuments.documents.length} source documents`, { prefix: "Transfer" });
928
+ // Extract document IDs from the current batch
929
+ const sourceDocIds = sourceDocuments.documents.map((doc) => doc.$id);
930
+ // Fetch existing documents from target in a single query
931
+ const existingTargetDocs = await this.fetchTargetDocumentsBatch(targetDb, targetDbId, targetCollectionId, sourceDocIds);
932
+ // Create a map for quick lookup of existing documents
933
+ const existingDocsMap = new Map();
934
+ existingTargetDocs.forEach((doc) => {
935
+ existingDocsMap.set(doc.$id, doc);
936
+ });
937
+ // Filter documents based on existence, content comparison, and permission comparison
938
+ const documentsToTransfer = [];
939
+ const documentsToUpdate = [];
940
+ for (const sourceDoc of sourceDocuments.documents) {
941
+ const existingTargetDoc = existingDocsMap.get(sourceDoc.$id);
942
+ if (!existingTargetDoc) {
943
+ // Document doesn't exist in target, needs to be transferred
944
+ documentsToTransfer.push(sourceDoc);
945
+ }
946
+ else {
947
+ // Document exists, compare both content and permissions
948
+ const sourcePermissions = Array.from(new Set(sourceDoc.$permissions || [])).sort();
949
+ const targetPermissions = Array.from(new Set(existingTargetDoc.$permissions || [])).sort();
950
+ const permissionsDiffer = sourcePermissions.join(",") !== targetPermissions.join(",") ||
951
+ sourcePermissions.length !== targetPermissions.length;
952
+ // Use objectNeedsUpdate to compare document content (excluding system fields)
953
+ const contentDiffers = objectNeedsUpdate(existingTargetDoc, sourceDoc);
954
+ if (contentDiffers && permissionsDiffer) {
955
+ // Both content and permissions differ
956
+ documentsToUpdate.push({
957
+ doc: sourceDoc,
958
+ targetDoc: existingTargetDoc,
959
+ reason: "content and permissions differ",
960
+ });
961
+ }
962
+ else if (contentDiffers) {
963
+ // Only content differs
964
+ documentsToUpdate.push({
965
+ doc: sourceDoc,
966
+ targetDoc: existingTargetDoc,
967
+ reason: "content differs",
968
+ });
969
+ }
970
+ else if (permissionsDiffer) {
971
+ // Only permissions differ
972
+ documentsToUpdate.push({
973
+ doc: sourceDoc,
974
+ targetDoc: existingTargetDoc,
975
+ reason: "permissions differ",
976
+ });
977
+ }
978
+ else {
979
+ // Document exists with identical content AND permissions, skip
980
+ totalSkipped++;
981
+ }
982
+ }
983
+ }
984
+ MessageFormatter.info(`Batch analysis: ${documentsToTransfer.length} to create, ${documentsToUpdate.length} to update, ${totalSkipped} skipped so far`, { prefix: "Transfer" });
985
+ // Process new documents with bulk operations if supported and available
986
+ if (documentsToTransfer.length > 0) {
987
+ if (supportsBulk && documentsToTransfer.length >= 10) {
988
+ // Use bulk operations for large batches
989
+ await this.transferDocumentsBulk(targetDb, targetDbId, targetCollectionId, documentsToTransfer);
990
+ totalTransferred += documentsToTransfer.length;
991
+ }
992
+ else {
993
+ // Use individual transfers for smaller batches or non-bulk endpoints
994
+ const transferCount = await this.transferDocumentsIndividual(targetDb, targetDbId, targetCollectionId, documentsToTransfer);
995
+ totalTransferred += transferCount;
996
+ }
997
+ }
998
+ // Process document updates (always individual since bulk update with permissions needs special handling)
999
+ if (documentsToUpdate.length > 0) {
1000
+ const updateCount = await this.updateDocumentsIndividual(targetDb, targetDbId, targetCollectionId, documentsToUpdate);
1001
+ totalUpdated += updateCount;
1002
+ }
1003
+ if (sourceDocuments.documents.length < 1000) {
1004
+ break;
1005
+ }
1006
+ lastId =
1007
+ sourceDocuments.documents[sourceDocuments.documents.length - 1].$id;
1008
+ }
1009
+ MessageFormatter.info(`Transfer complete: ${totalTransferred} new, ${totalUpdated} updated, ${totalSkipped} skipped from ${sourceCollectionId} to ${targetCollectionId}`, { prefix: "Transfer" });
1010
+ }
1011
+ /**
1012
+ * Fetch target documents by IDs in batches to check existence and permissions
1013
+ */
1014
+ async fetchTargetDocumentsBatch(targetDb, targetDbId, targetCollectionId, docIds) {
1015
+ const documents = [];
1016
+ // Split IDs into chunks of 100 for Query.equal limitations
1017
+ const idChunks = this.chunkArray(docIds, 100);
1018
+ for (const chunk of idChunks) {
1019
+ try {
1020
+ const result = await tryAwaitWithRetry(async () => targetDb.listDocuments(targetDbId, targetCollectionId, [
1021
+ Query.equal("$id", chunk),
1022
+ Query.limit(100),
1023
+ ]));
1024
+ documents.push(...result.documents);
1025
+ }
1026
+ catch (error) {
1027
+ // If query fails, fall back to individual gets (less efficient but more reliable)
1028
+ MessageFormatter.warning(`Batch query failed for ${chunk.length} documents, falling back to individual checks`, { prefix: "Transfer" });
1029
+ for (const docId of chunk) {
1030
+ try {
1031
+ const doc = await targetDb.getDocument(targetDbId, targetCollectionId, docId);
1032
+ documents.push(doc);
1033
+ }
1034
+ catch (getError) {
1035
+ // Document doesn't exist, which is fine
1036
+ }
1037
+ }
1038
+ }
1039
+ }
1040
+ return documents;
1041
+ }
1042
+ /**
1043
+ * Transfer documents using bulk operations with proper batch size handling
1044
+ */
1045
+ async transferDocumentsBulk(targetDb, targetDbId, targetCollectionId, documents) {
1046
+ // Prepare documents for bulk upsert
1047
+ const preparedDocs = documents.map((doc) => {
1048
+ const { $id, $createdAt, $updatedAt, $permissions, $databaseId, $collectionId, $sequence, ...docData } = doc;
1049
+ return {
1050
+ $id,
1051
+ $permissions,
1052
+ ...docData,
1053
+ };
1054
+ });
1055
+ // Process in smaller chunks for bulk operations (1000 for Pro, 100 for Free tier)
1056
+ const batchSizes = [1000, 100]; // Start with Pro plan, fallback to Free
1057
+ let processed = false;
1058
+ for (const maxBatchSize of batchSizes) {
1059
+ const documentBatches = this.chunkArray(preparedDocs, maxBatchSize);
1060
+ try {
1061
+ for (const batch of documentBatches) {
1062
+ await this.bulkUpsertDocuments(this.targetClient, targetDbId, targetCollectionId, batch);
1063
+ MessageFormatter.success(`✅ Bulk upserted ${batch.length} documents`, { prefix: "Transfer" });
1064
+ }
1065
+ processed = true;
1066
+ break; // Success, exit batch size loop
1067
+ }
1068
+ catch (error) {
1069
+ MessageFormatter.warning(`Bulk upsert with batch size ${maxBatchSize} failed, trying smaller size...`, { prefix: "Transfer" });
1070
+ continue; // Try next smaller batch size
1071
+ }
1072
+ }
1073
+ if (!processed) {
1074
+ MessageFormatter.warning(`All bulk operations failed, falling back to individual transfers`, { prefix: "Transfer" });
1075
+ // Fall back to individual transfers
1076
+ await this.transferDocumentsIndividual(targetDb, targetDbId, targetCollectionId, documents);
1077
+ }
1078
+ }
1079
+ /**
1080
+ * Direct HTTP implementation of bulk upsert API
1081
+ */
1082
+ async bulkUpsertDocuments(client, dbId, collectionId, documents) {
1083
+ const apiPath = `/databases/${dbId}/collections/${collectionId}/documents`;
1084
+ const url = new URL(client.config.endpoint + apiPath);
1085
+ const headers = {
1086
+ "Content-Type": "application/json",
1087
+ "X-Appwrite-Project": client.config.project,
1088
+ "X-Appwrite-Key": client.config.key,
1089
+ };
1090
+ const response = await fetch(url.toString(), {
1091
+ method: "PUT",
1092
+ headers,
1093
+ body: JSON.stringify({ documents }),
1094
+ });
1095
+ if (!response.ok) {
1096
+ const errorData = await response
1097
+ .json()
1098
+ .catch(() => ({ message: "Unknown error" }));
1099
+ throw new Error(`Bulk upsert failed: ${response.status} - ${errorData.message || "Unknown error"}`);
1100
+ }
1101
+ return await response.json();
1102
+ }
1103
+ /**
1104
+ * Transfer documents individually with rate limiting
1105
+ */
1106
+ async transferDocumentsIndividual(targetDb, targetDbId, targetCollectionId, documents) {
1107
+ let successCount = 0;
1108
+ const transferTasks = documents.map((doc) => this.limit(async () => {
1109
+ try {
1110
+ const { $id, $createdAt, $updatedAt, $permissions, $databaseId, $collectionId, $sequence, ...docData } = doc;
1111
+ await tryAwaitWithRetry(async () => targetDb.createDocument(targetDbId, targetCollectionId, doc.$id, docData, doc.$permissions));
1112
+ successCount++;
1113
+ }
1114
+ catch (error) {
1115
+ if (error instanceof AppwriteException &&
1116
+ error.message.includes("already exists")) {
1117
+ try {
1118
+ // Update it! It's here because it needs an update or a create
1119
+ const { $id, $createdAt, $updatedAt, $permissions, $databaseId, $collectionId, $sequence, ...docData } = doc;
1120
+ await tryAwaitWithRetry(async () => targetDb.updateDocument(targetDbId, targetCollectionId, doc.$id, docData, doc.$permissions));
1121
+ successCount++;
1122
+ }
1123
+ catch (updateError) {
1124
+ // just send the error to the formatter
1125
+ MessageFormatter.error(`Failed to transfer document ${doc.$id}`, updateError instanceof Error
1126
+ ? updateError
1127
+ : new Error(String(updateError)), { prefix: "Transfer" });
1128
+ }
1129
+ }
1130
+ MessageFormatter.error(`Failed to transfer document ${doc.$id}`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
1131
+ }
1132
+ }));
1133
+ await Promise.all(transferTasks);
1134
+ return successCount;
1135
+ }
1136
+ /**
1137
+ * Update documents individually with content and/or permission changes
1138
+ */
1139
+ async updateDocumentsIndividual(targetDb, targetDbId, targetCollectionId, documentPairs) {
1140
+ let successCount = 0;
1141
+ const updateTasks = documentPairs.map(({ doc, targetDoc, reason }) => this.limit(async () => {
1142
+ try {
1143
+ const { $id, $createdAt, $updatedAt, $permissions, $databaseId, $collectionId, $sequence, ...docData } = doc;
1144
+ await tryAwaitWithRetry(async () => targetDb.updateDocument(targetDbId, targetCollectionId, doc.$id, docData, $permissions));
1145
+ successCount++;
1146
+ }
1147
+ catch (error) {
1148
+ MessageFormatter.error(`Failed to update document ${doc.$id} (${reason})`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
1149
+ }
1150
+ }));
1151
+ await Promise.all(updateTasks);
1152
+ return successCount;
1153
+ }
1154
+ /**
1155
+ * Utility method to chunk arrays
1156
+ */
1157
+ chunkArray(array, size) {
1158
+ const chunks = [];
1159
+ for (let i = 0; i < array.length; i += size) {
1160
+ chunks.push(array.slice(i, i + size));
1161
+ }
1162
+ return chunks;
1163
+ }
1164
+ /**
1165
+ * Helper method to fetch all teams with pagination
1166
+ */
1167
+ async fetchAllTeams(teams) {
1168
+ const teamsList = [];
1169
+ let lastId;
1170
+ while (true) {
1171
+ const queries = [Query.limit(100)];
1172
+ if (lastId) {
1173
+ queries.push(Query.cursorAfter(lastId));
1174
+ }
1175
+ const result = await tryAwaitWithRetry(async () => teams.list(queries));
1176
+ if (result.teams.length === 0) {
1177
+ break;
1178
+ }
1179
+ teamsList.push(...result.teams);
1180
+ if (result.teams.length < 100) {
1181
+ break;
1182
+ }
1183
+ lastId = result.teams[result.teams.length - 1].$id;
1184
+ }
1185
+ return teamsList;
1186
+ }
1187
+ /**
1188
+ * Helper method to fetch all memberships for a team with pagination
1189
+ */
1190
+ async fetchAllMemberships(teamId) {
1191
+ const membershipsList = [];
1192
+ let lastId;
1193
+ while (true) {
1194
+ const queries = [Query.limit(100)];
1195
+ if (lastId) {
1196
+ queries.push(Query.cursorAfter(lastId));
1197
+ }
1198
+ const result = await tryAwaitWithRetry(async () => this.sourceTeams.listMemberships(teamId, queries));
1199
+ if (result.memberships.length === 0) {
1200
+ break;
1201
+ }
1202
+ membershipsList.push(...result.memberships);
1203
+ if (result.memberships.length < 100) {
1204
+ break;
1205
+ }
1206
+ lastId = result.memberships[result.memberships.length - 1].$id;
1207
+ }
1208
+ return membershipsList;
1209
+ }
1210
+ /**
1211
+ * Helper method to transfer team memberships
1212
+ */
1213
+ async transferTeamMemberships(teamId) {
1214
+ MessageFormatter.info(`Transferring memberships for team ${teamId}`, {
1215
+ prefix: "Transfer",
1216
+ });
1217
+ try {
1218
+ // Fetch all memberships for this team
1219
+ const memberships = await this.fetchAllMemberships(teamId);
1220
+ if (memberships.length === 0) {
1221
+ MessageFormatter.info(`No memberships found for team ${teamId}`, {
1222
+ prefix: "Transfer",
1223
+ });
1224
+ return;
1225
+ }
1226
+ MessageFormatter.info(`Found ${memberships.length} memberships for team ${teamId}`, { prefix: "Transfer" });
1227
+ let totalTransferred = 0;
1228
+ // Transfer memberships with rate limiting
1229
+ const transferTasks = memberships.map((membership) => this.userLimit(async () => {
1230
+ // Use userLimit for team operations (more sensitive)
1231
+ try {
1232
+ // Check if membership already exists and compare roles
1233
+ let existingMembership = null;
1234
+ try {
1235
+ existingMembership = await this.targetTeams.getMembership(teamId, membership.$id);
1236
+ // Compare roles between source and target membership
1237
+ const sourceRoles = JSON.stringify(membership.roles?.sort() || []);
1238
+ const targetRoles = JSON.stringify(existingMembership.roles?.sort() || []);
1239
+ if (sourceRoles !== targetRoles) {
1240
+ MessageFormatter.warning(`Membership ${membership.$id} exists but has different roles. Source: ${sourceRoles}, Target: ${targetRoles}`, { prefix: "Transfer" });
1241
+ // Update membership roles to match source
1242
+ try {
1243
+ await this.targetTeams.updateMembership(teamId, membership.$id, membership.roles);
1244
+ MessageFormatter.success(`Updated membership ${membership.$id} roles to match source`, { prefix: "Transfer" });
1245
+ }
1246
+ catch (updateError) {
1247
+ MessageFormatter.error(`Failed to update roles for membership ${membership.$id}`, updateError instanceof Error
1248
+ ? updateError
1249
+ : new Error(String(updateError)), { prefix: "Transfer" });
1250
+ }
1251
+ }
1252
+ else {
1253
+ MessageFormatter.info(`Membership ${membership.$id} already exists with matching roles, skipping`, { prefix: "Transfer" });
1254
+ }
1255
+ return;
1256
+ }
1257
+ catch (error) {
1258
+ // Membership doesn't exist, proceed with creation
1259
+ }
1260
+ // Get user data from target (users should already be transferred)
1261
+ let userData = null;
1262
+ try {
1263
+ userData = await this.targetUsers.get(membership.userId);
1264
+ }
1265
+ catch (error) {
1266
+ MessageFormatter.warning(`User ${membership.userId} not found in target, membership ${membership.$id} may fail`, { prefix: "Transfer" });
1267
+ }
1268
+ // Create membership using the comprehensive user data
1269
+ await tryAwaitWithRetry(async () => this.targetTeams.createMembership(teamId, membership.roles, userData?.email || membership.userEmail, // Use target user email if available, fallback to membership email
1270
+ membership.userId, // User ID
1271
+ userData?.phone || undefined, // Use target user phone if available
1272
+ undefined, // Invitation URL placeholder
1273
+ userData?.name || membership.userName // Use target user name if available, fallback to membership name
1274
+ ));
1275
+ totalTransferred++;
1276
+ MessageFormatter.success(`Transferred membership ${membership.$id} for user ${userData?.name || membership.userName}`, { prefix: "Transfer" });
1277
+ }
1278
+ catch (error) {
1279
+ MessageFormatter.error(`Failed to transfer membership ${membership.$id}`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
1280
+ }
1281
+ }));
1282
+ await Promise.all(transferTasks);
1283
+ MessageFormatter.info(`Transferred ${totalTransferred} memberships for team ${teamId}`, { prefix: "Transfer" });
1284
+ }
1285
+ catch (error) {
1286
+ MessageFormatter.error(`Failed to transfer memberships for team ${teamId}`, error instanceof Error ? error : new Error(String(error)), { prefix: "Transfer" });
1287
+ }
1288
+ }
1289
+ printSummary() {
1290
+ const duration = Math.round((Date.now() - this.startTime) / 1000);
1291
+ MessageFormatter.info("=== COMPREHENSIVE TRANSFER SUMMARY ===", {
1292
+ prefix: "Transfer",
1293
+ });
1294
+ MessageFormatter.info(`Total Time: ${duration}s`, { prefix: "Transfer" });
1295
+ MessageFormatter.info(`Users: ${this.results.users.transferred} transferred, ${this.results.users.skipped} skipped, ${this.results.users.failed} failed`, { prefix: "Transfer" });
1296
+ MessageFormatter.info(`Teams: ${this.results.teams.transferred} transferred, ${this.results.teams.skipped} skipped, ${this.results.teams.failed} failed`, { prefix: "Transfer" });
1297
+ MessageFormatter.info(`Databases: ${this.results.databases.transferred} transferred, ${this.results.databases.skipped} skipped, ${this.results.databases.failed} failed`, { prefix: "Transfer" });
1298
+ MessageFormatter.info(`Buckets: ${this.results.buckets.transferred} transferred, ${this.results.buckets.skipped} skipped, ${this.results.buckets.failed} failed`, { prefix: "Transfer" });
1299
+ MessageFormatter.info(`Functions: ${this.results.functions.transferred} transferred, ${this.results.functions.skipped} skipped, ${this.results.functions.failed} failed`, { prefix: "Transfer" });
1300
+ const totalTransferred = this.results.users.transferred +
1301
+ this.results.teams.transferred +
1302
+ this.results.databases.transferred +
1303
+ this.results.buckets.transferred +
1304
+ this.results.functions.transferred;
1305
+ const totalFailed = this.results.users.failed +
1306
+ this.results.teams.failed +
1307
+ this.results.databases.failed +
1308
+ this.results.buckets.failed +
1309
+ this.results.functions.failed;
1310
+ if (totalFailed === 0) {
1311
+ MessageFormatter.success(`All ${totalTransferred} items transferred successfully!`, { prefix: "Transfer" });
1312
+ }
1313
+ else {
1314
+ MessageFormatter.warning(`${totalTransferred} items transferred, ${totalFailed} failed`, { prefix: "Transfer" });
1315
+ }
1316
+ }
1317
+ }