appwrite-utils-cli 1.9.7 → 1.12.0

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 (376) hide show
  1. package/README.md +1004 -1004
  2. package/dist/adapters/index.d.ts +7 -8
  3. package/dist/adapters/index.js +7 -9
  4. package/dist/backups/operations/bucketBackup.js +2 -2
  5. package/dist/backups/operations/collectionBackup.d.ts +1 -1
  6. package/dist/backups/operations/collectionBackup.js +3 -3
  7. package/dist/backups/operations/comprehensiveBackup.d.ts +1 -1
  8. package/dist/backups/operations/comprehensiveBackup.js +2 -2
  9. package/dist/backups/tracking/centralizedTracking.d.ts +1 -1
  10. package/dist/backups/tracking/centralizedTracking.js +2 -2
  11. package/dist/cli/commands/configCommands.js +51 -7
  12. package/dist/cli/commands/databaseCommands.js +156 -104
  13. package/dist/cli/commands/functionCommands.js +3 -3
  14. package/dist/cli/commands/importFileCommands.d.ts +7 -0
  15. package/dist/cli/commands/importFileCommands.js +674 -0
  16. package/dist/cli/commands/schemaCommands.js +3 -3
  17. package/dist/cli/commands/storageCommands.js +2 -3
  18. package/dist/cli/commands/transferCommands.js +3 -5
  19. package/dist/collections/{attributes.d.ts → columns.d.ts} +1 -1
  20. package/dist/collections/{attributes.js → columns.js} +15 -9
  21. package/dist/collections/indexes.js +1 -3
  22. package/dist/collections/methods.d.ts +1 -1
  23. package/dist/collections/methods.js +38 -20
  24. package/dist/collections/tableOperations.d.ts +1 -0
  25. package/dist/collections/tableOperations.js +30 -11
  26. package/dist/collections/transferOperations.d.ts +1 -1
  27. package/dist/collections/transferOperations.js +3 -4
  28. package/dist/collections/wipeOperations.d.ts +4 -3
  29. package/dist/collections/wipeOperations.js +112 -39
  30. package/dist/databases/methods.js +2 -2
  31. package/dist/databases/setup.js +2 -2
  32. package/dist/examples/yamlTerminologyExample.js +2 -2
  33. package/dist/functions/deployments.d.ts +1 -1
  34. package/dist/functions/deployments.js +6 -6
  35. package/dist/functions/fnConfigDiscovery.js +2 -2
  36. package/dist/functions/methods.js +2 -2
  37. package/dist/functions/templates/count-docs-in-collection/README.md +53 -53
  38. package/dist/functions/templates/count-docs-in-collection/src/main.ts +159 -159
  39. package/dist/functions/templates/count-docs-in-collection/src/request.ts +8 -8
  40. package/dist/functions/templates/hono-typescript/README.md +285 -285
  41. package/dist/functions/templates/hono-typescript/src/adapters/request.ts +73 -73
  42. package/dist/functions/templates/hono-typescript/src/adapters/response.ts +105 -105
  43. package/dist/functions/templates/hono-typescript/src/app.ts +179 -179
  44. package/dist/functions/templates/hono-typescript/src/context.ts +102 -102
  45. package/{src/functions/templates/hono-typescript/src/index.ts → dist/functions/templates/hono-typescript/src/main.ts} +53 -53
  46. package/dist/functions/templates/hono-typescript/src/middleware/appwrite.ts +118 -118
  47. package/dist/functions/templates/typescript-node/README.md +31 -31
  48. package/dist/functions/templates/typescript-node/src/context.ts +102 -102
  49. package/dist/functions/templates/typescript-node/src/{index.ts → main.ts} +29 -29
  50. package/dist/functions/templates/uv/README.md +30 -30
  51. package/dist/functions/templates/uv/pyproject.toml +29 -29
  52. package/dist/functions/templates/uv/src/context.py +124 -124
  53. package/dist/functions/templates/uv/src/{index.py → main.py} +45 -45
  54. package/dist/init.js +1 -1
  55. package/dist/interactiveCLI.d.ts +6 -1
  56. package/dist/interactiveCLI.js +79 -25
  57. package/dist/main.js +125 -180
  58. package/dist/migrations/afterImportActions.js +2 -3
  59. package/dist/migrations/appwriteToX.d.ts +1 -1
  60. package/dist/migrations/appwriteToX.js +10 -8
  61. package/dist/migrations/comprehensiveTransfer.js +3 -5
  62. package/dist/migrations/dataLoader.d.ts +4 -2
  63. package/dist/migrations/dataLoader.js +42 -20
  64. package/dist/migrations/importController.d.ts +2 -0
  65. package/dist/migrations/importController.js +39 -24
  66. package/dist/migrations/importDataActions.js +3 -3
  67. package/dist/migrations/relationships.js +1 -2
  68. package/dist/migrations/services/DataTransformationService.js +2 -2
  69. package/dist/migrations/services/FileHandlerService.js +1 -1
  70. package/dist/migrations/services/ImportOrchestrator.d.ts +2 -0
  71. package/dist/migrations/services/ImportOrchestrator.js +15 -7
  72. package/dist/migrations/services/RateLimitManager.js +1 -1
  73. package/dist/migrations/services/RelationshipResolver.js +1 -1
  74. package/dist/migrations/services/UserMappingService.js +1 -1
  75. package/dist/migrations/services/ValidationService.js +1 -1
  76. package/dist/migrations/transfer.d.ts +8 -4
  77. package/dist/migrations/transfer.js +108 -55
  78. package/dist/migrations/yaml/YamlImportConfigLoader.js +52 -52
  79. package/dist/migrations/yaml/YamlImportIntegration.js +2 -2
  80. package/dist/migrations/yaml/generateImportSchemas.js +174 -174
  81. package/dist/setupCommands.d.ts +1 -1
  82. package/dist/setupCommands.js +5 -6
  83. package/dist/setupController.js +1 -1
  84. package/dist/shared/backupTracking.d.ts +1 -1
  85. package/dist/shared/backupTracking.js +2 -2
  86. package/dist/shared/confirmationDialogs.js +1 -1
  87. package/dist/shared/migrationHelpers.d.ts +1 -1
  88. package/dist/shared/migrationHelpers.js +4 -4
  89. package/dist/shared/operationQueue.d.ts +1 -1
  90. package/dist/shared/operationQueue.js +3 -4
  91. package/dist/shared/operationsTable.d.ts +1 -1
  92. package/dist/shared/operationsTable.js +35 -34
  93. package/dist/shared/operationsTableSchema.d.ts +3 -3
  94. package/dist/shared/operationsTableSchema.js +2 -2
  95. package/dist/shared/progressManager.js +1 -1
  96. package/dist/shared/selectionDialogs.d.ts +6 -0
  97. package/dist/shared/selectionDialogs.js +56 -12
  98. package/dist/storage/methods.d.ts +12 -0
  99. package/dist/storage/methods.js +92 -89
  100. package/dist/storage/schemas.d.ts +2 -2
  101. package/dist/tables/indexManager.d.ts +1 -1
  102. package/dist/tables/indexManager.js +2 -2
  103. package/dist/types.d.ts +2 -2
  104. package/dist/types.js +1 -1
  105. package/dist/users/methods.js +2 -3
  106. package/dist/utils/configMigration.js +1 -1
  107. package/dist/utils/index.d.ts +1 -1
  108. package/dist/utils/index.js +1 -1
  109. package/dist/utils/loadConfigs.d.ts +2 -2
  110. package/dist/utils/loadConfigs.js +6 -7
  111. package/dist/utils/setupFiles.js +139 -141
  112. package/dist/utilsController.d.ts +16 -9
  113. package/dist/utilsController.js +93 -68
  114. package/package.json +9 -3
  115. package/.appwrite/.yaml_schemas/appwrite-config.schema.json +0 -380
  116. package/.appwrite/.yaml_schemas/collection.schema.json +0 -255
  117. package/.appwrite/collections/Categories.yaml +0 -182
  118. package/.appwrite/collections/ExampleCollection.yaml +0 -36
  119. package/.appwrite/collections/Posts.yaml +0 -227
  120. package/.appwrite/collections/Users.yaml +0 -149
  121. package/.appwrite/config.yaml +0 -109
  122. package/.appwrite/import/README.md +0 -148
  123. package/.appwrite/import/categories-import.yaml +0 -129
  124. package/.appwrite/import/posts-import.yaml +0 -208
  125. package/.appwrite/import/users-import.yaml +0 -130
  126. package/.appwrite/importData/categories.json +0 -194
  127. package/.appwrite/importData/posts.json +0 -270
  128. package/.appwrite/importData/users.json +0 -220
  129. package/.appwrite/schemas/categories.json +0 -128
  130. package/.appwrite/schemas/exampleCollection.json +0 -52
  131. package/.appwrite/schemas/posts.json +0 -173
  132. package/.appwrite/schemas/users.json +0 -125
  133. package/CHANGELOG.md +0 -35
  134. package/CONFIG_TODO.md +0 -1189
  135. package/SELECTION_DIALOGS.md +0 -146
  136. package/SERVICE_IMPLEMENTATION_REPORT.md +0 -462
  137. package/dist/adapters/AdapterFactory.d.ts +0 -94
  138. package/dist/adapters/AdapterFactory.js +0 -420
  139. package/dist/adapters/DatabaseAdapter.d.ts +0 -243
  140. package/dist/adapters/DatabaseAdapter.js +0 -50
  141. package/dist/adapters/LegacyAdapter.d.ts +0 -50
  142. package/dist/adapters/LegacyAdapter.js +0 -615
  143. package/dist/adapters/TablesDBAdapter.d.ts +0 -45
  144. package/dist/adapters/TablesDBAdapter.js +0 -611
  145. package/dist/config/ConfigManager.d.ts +0 -450
  146. package/dist/config/ConfigManager.js +0 -650
  147. package/dist/config/configMigration.d.ts +0 -87
  148. package/dist/config/configMigration.js +0 -390
  149. package/dist/config/configValidation.d.ts +0 -66
  150. package/dist/config/configValidation.js +0 -358
  151. package/dist/config/index.d.ts +0 -8
  152. package/dist/config/index.js +0 -7
  153. package/dist/config/services/ConfigDiscoveryService.d.ts +0 -122
  154. package/dist/config/services/ConfigDiscoveryService.js +0 -322
  155. package/dist/config/services/ConfigLoaderService.d.ts +0 -129
  156. package/dist/config/services/ConfigLoaderService.js +0 -535
  157. package/dist/config/services/ConfigMergeService.d.ts +0 -208
  158. package/dist/config/services/ConfigMergeService.js +0 -308
  159. package/dist/config/services/ConfigValidationService.d.ts +0 -214
  160. package/dist/config/services/ConfigValidationService.js +0 -310
  161. package/dist/config/services/SessionAuthService.d.ts +0 -225
  162. package/dist/config/services/SessionAuthService.js +0 -456
  163. package/dist/config/services/__tests__/ConfigMergeService.test.d.ts +0 -1
  164. package/dist/config/services/__tests__/ConfigMergeService.test.js +0 -271
  165. package/dist/config/services/index.d.ts +0 -13
  166. package/dist/config/services/index.js +0 -10
  167. package/dist/config/yamlConfig.d.ts +0 -722
  168. package/dist/config/yamlConfig.js +0 -702
  169. package/dist/functions/pathResolution.d.ts +0 -37
  170. package/dist/functions/pathResolution.js +0 -185
  171. package/dist/functions/templates/count-docs-in-collection/package.json +0 -25
  172. package/dist/functions/templates/count-docs-in-collection/tsconfig.json +0 -28
  173. package/dist/functions/templates/hono-typescript/package.json +0 -26
  174. package/dist/functions/templates/hono-typescript/src/index.ts +0 -54
  175. package/dist/functions/templates/hono-typescript/tsconfig.json +0 -20
  176. package/dist/functions/templates/typescript-node/package.json +0 -25
  177. package/dist/functions/templates/typescript-node/tsconfig.json +0 -28
  178. package/dist/shared/attributeMapper.d.ts +0 -20
  179. package/dist/shared/attributeMapper.js +0 -203
  180. package/dist/shared/errorUtils.d.ts +0 -54
  181. package/dist/shared/errorUtils.js +0 -95
  182. package/dist/shared/functionManager.d.ts +0 -48
  183. package/dist/shared/functionManager.js +0 -348
  184. package/dist/shared/jsonSchemaGenerator.d.ts +0 -50
  185. package/dist/shared/jsonSchemaGenerator.js +0 -290
  186. package/dist/shared/logging.d.ts +0 -61
  187. package/dist/shared/logging.js +0 -116
  188. package/dist/shared/messageFormatter.d.ts +0 -39
  189. package/dist/shared/messageFormatter.js +0 -162
  190. package/dist/shared/pydanticModelGenerator.d.ts +0 -17
  191. package/dist/shared/pydanticModelGenerator.js +0 -615
  192. package/dist/shared/schemaGenerator.d.ts +0 -40
  193. package/dist/shared/schemaGenerator.js +0 -556
  194. package/dist/utils/ClientFactory.d.ts +0 -87
  195. package/dist/utils/ClientFactory.js +0 -212
  196. package/dist/utils/configDiscovery.d.ts +0 -78
  197. package/dist/utils/configDiscovery.js +0 -472
  198. package/dist/utils/constantsGenerator.d.ts +0 -31
  199. package/dist/utils/constantsGenerator.js +0 -321
  200. package/dist/utils/dataConverters.d.ts +0 -46
  201. package/dist/utils/dataConverters.js +0 -139
  202. package/dist/utils/directoryUtils.d.ts +0 -22
  203. package/dist/utils/directoryUtils.js +0 -59
  204. package/dist/utils/getClientFromConfig.d.ts +0 -39
  205. package/dist/utils/getClientFromConfig.js +0 -199
  206. package/dist/utils/helperFunctions.d.ts +0 -63
  207. package/dist/utils/helperFunctions.js +0 -156
  208. package/dist/utils/pathResolvers.d.ts +0 -53
  209. package/dist/utils/pathResolvers.js +0 -72
  210. package/dist/utils/projectConfig.d.ts +0 -122
  211. package/dist/utils/projectConfig.js +0 -206
  212. package/dist/utils/retryFailedPromises.d.ts +0 -2
  213. package/dist/utils/retryFailedPromises.js +0 -23
  214. package/dist/utils/sessionAuth.d.ts +0 -48
  215. package/dist/utils/sessionAuth.js +0 -164
  216. package/dist/utils/typeGuards.d.ts +0 -35
  217. package/dist/utils/typeGuards.js +0 -57
  218. package/dist/utils/validationRules.d.ts +0 -43
  219. package/dist/utils/validationRules.js +0 -42
  220. package/dist/utils/versionDetection.d.ts +0 -58
  221. package/dist/utils/versionDetection.js +0 -251
  222. package/dist/utils/yamlConverter.d.ts +0 -100
  223. package/dist/utils/yamlConverter.js +0 -428
  224. package/dist/utils/yamlLoader.d.ts +0 -70
  225. package/dist/utils/yamlLoader.js +0 -267
  226. package/scripts/copy-templates.ts +0 -23
  227. package/src/adapters/AdapterFactory.ts +0 -529
  228. package/src/adapters/DatabaseAdapter.ts +0 -319
  229. package/src/adapters/LegacyAdapter.ts +0 -844
  230. package/src/adapters/TablesDBAdapter.ts +0 -823
  231. package/src/adapters/index.ts +0 -37
  232. package/src/backups/operations/bucketBackup.ts +0 -277
  233. package/src/backups/operations/collectionBackup.ts +0 -310
  234. package/src/backups/operations/comprehensiveBackup.ts +0 -342
  235. package/src/backups/schemas/bucketManifest.ts +0 -78
  236. package/src/backups/schemas/comprehensiveManifest.ts +0 -76
  237. package/src/backups/tracking/centralizedTracking.ts +0 -352
  238. package/src/cli/commands/configCommands.ts +0 -201
  239. package/src/cli/commands/databaseCommands.ts +0 -879
  240. package/src/cli/commands/functionCommands.ts +0 -418
  241. package/src/cli/commands/schemaCommands.ts +0 -200
  242. package/src/cli/commands/storageCommands.ts +0 -152
  243. package/src/cli/commands/transferCommands.ts +0 -457
  244. package/src/collections/attributes.ts +0 -2020
  245. package/src/collections/attributes.ts.backup +0 -1555
  246. package/src/collections/indexes.ts +0 -352
  247. package/src/collections/methods.ts +0 -700
  248. package/src/collections/tableOperations.ts +0 -521
  249. package/src/collections/transferOperations.ts +0 -590
  250. package/src/collections/wipeOperations.ts +0 -346
  251. package/src/config/ConfigManager.ts +0 -849
  252. package/src/config/README.md +0 -274
  253. package/src/config/configMigration.ts +0 -575
  254. package/src/config/configValidation.ts +0 -445
  255. package/src/config/index.ts +0 -10
  256. package/src/config/services/ConfigDiscoveryService.ts +0 -410
  257. package/src/config/services/ConfigLoaderService.ts +0 -732
  258. package/src/config/services/ConfigMergeService.ts +0 -388
  259. package/src/config/services/ConfigValidationService.ts +0 -394
  260. package/src/config/services/SessionAuthService.ts +0 -565
  261. package/src/config/services/__tests__/ConfigMergeService.test.ts +0 -351
  262. package/src/config/services/index.ts +0 -29
  263. package/src/config/yamlConfig.ts +0 -761
  264. package/src/databases/methods.ts +0 -49
  265. package/src/databases/setup.ts +0 -77
  266. package/src/examples/yamlTerminologyExample.ts +0 -346
  267. package/src/functions/deployments.ts +0 -220
  268. package/src/functions/fnConfigDiscovery.ts +0 -103
  269. package/src/functions/methods.ts +0 -284
  270. package/src/functions/pathResolution.ts +0 -227
  271. package/src/functions/templates/count-docs-in-collection/README.md +0 -54
  272. package/src/functions/templates/count-docs-in-collection/package.json +0 -25
  273. package/src/functions/templates/count-docs-in-collection/src/main.ts +0 -159
  274. package/src/functions/templates/count-docs-in-collection/src/request.ts +0 -9
  275. package/src/functions/templates/count-docs-in-collection/tsconfig.json +0 -28
  276. package/src/functions/templates/hono-typescript/README.md +0 -286
  277. package/src/functions/templates/hono-typescript/package.json +0 -26
  278. package/src/functions/templates/hono-typescript/src/adapters/request.ts +0 -74
  279. package/src/functions/templates/hono-typescript/src/adapters/response.ts +0 -106
  280. package/src/functions/templates/hono-typescript/src/app.ts +0 -180
  281. package/src/functions/templates/hono-typescript/src/context.ts +0 -103
  282. package/src/functions/templates/hono-typescript/src/middleware/appwrite.ts +0 -119
  283. package/src/functions/templates/hono-typescript/tsconfig.json +0 -20
  284. package/src/functions/templates/typescript-node/README.md +0 -32
  285. package/src/functions/templates/typescript-node/package.json +0 -25
  286. package/src/functions/templates/typescript-node/src/context.ts +0 -103
  287. package/src/functions/templates/typescript-node/src/index.ts +0 -29
  288. package/src/functions/templates/typescript-node/tsconfig.json +0 -28
  289. package/src/functions/templates/uv/README.md +0 -31
  290. package/src/functions/templates/uv/pyproject.toml +0 -30
  291. package/src/functions/templates/uv/src/__init__.py +0 -0
  292. package/src/functions/templates/uv/src/context.py +0 -125
  293. package/src/functions/templates/uv/src/index.py +0 -46
  294. package/src/init.ts +0 -62
  295. package/src/interactiveCLI.ts +0 -1136
  296. package/src/main.ts +0 -1670
  297. package/src/migrations/afterImportActions.ts +0 -580
  298. package/src/migrations/appwriteToX.ts +0 -664
  299. package/src/migrations/comprehensiveTransfer.ts +0 -2285
  300. package/src/migrations/dataLoader.ts +0 -1702
  301. package/src/migrations/importController.ts +0 -428
  302. package/src/migrations/importDataActions.ts +0 -315
  303. package/src/migrations/relationships.ts +0 -334
  304. package/src/migrations/services/DataTransformationService.ts +0 -196
  305. package/src/migrations/services/FileHandlerService.ts +0 -311
  306. package/src/migrations/services/ImportOrchestrator.ts +0 -666
  307. package/src/migrations/services/RateLimitManager.ts +0 -363
  308. package/src/migrations/services/RelationshipResolver.ts +0 -461
  309. package/src/migrations/services/UserMappingService.ts +0 -345
  310. package/src/migrations/services/ValidationService.ts +0 -349
  311. package/src/migrations/transfer.ts +0 -1068
  312. package/src/migrations/yaml/YamlImportConfigLoader.ts +0 -439
  313. package/src/migrations/yaml/YamlImportIntegration.ts +0 -446
  314. package/src/migrations/yaml/generateImportSchemas.ts +0 -1354
  315. package/src/schemas/authUser.ts +0 -23
  316. package/src/setup.ts +0 -8
  317. package/src/setupCommands.ts +0 -603
  318. package/src/setupController.ts +0 -43
  319. package/src/shared/attributeMapper.ts +0 -229
  320. package/src/shared/backupMetadataSchema.ts +0 -93
  321. package/src/shared/backupTracking.ts +0 -211
  322. package/src/shared/confirmationDialogs.ts +0 -327
  323. package/src/shared/errorUtils.ts +0 -110
  324. package/src/shared/functionManager.ts +0 -537
  325. package/src/shared/jsonSchemaGenerator.ts +0 -383
  326. package/src/shared/logging.ts +0 -149
  327. package/src/shared/messageFormatter.ts +0 -208
  328. package/src/shared/migrationHelpers.ts +0 -232
  329. package/src/shared/operationLogger.ts +0 -20
  330. package/src/shared/operationQueue.ts +0 -377
  331. package/src/shared/operationsTable.ts +0 -338
  332. package/src/shared/operationsTableSchema.ts +0 -60
  333. package/src/shared/progressManager.ts +0 -278
  334. package/src/shared/pydanticModelGenerator.ts +0 -618
  335. package/src/shared/relationshipExtractor.ts +0 -214
  336. package/src/shared/schemaGenerator.ts +0 -644
  337. package/src/shared/selectionDialogs.ts +0 -749
  338. package/src/storage/backupCompression.ts +0 -88
  339. package/src/storage/methods.ts +0 -698
  340. package/src/storage/schemas.ts +0 -205
  341. package/src/tables/indexManager.ts +0 -409
  342. package/src/types/node-appwrite-tablesdb.d.ts +0 -44
  343. package/src/types.ts +0 -9
  344. package/src/users/methods.ts +0 -359
  345. package/src/utils/ClientFactory.ts +0 -240
  346. package/src/utils/configDiscovery.ts +0 -557
  347. package/src/utils/configMigration.ts +0 -348
  348. package/src/utils/constantsGenerator.ts +0 -369
  349. package/src/utils/dataConverters.ts +0 -159
  350. package/src/utils/directoryUtils.ts +0 -61
  351. package/src/utils/getClientFromConfig.ts +0 -257
  352. package/src/utils/helperFunctions.ts +0 -228
  353. package/src/utils/index.ts +0 -2
  354. package/src/utils/loadConfigs.ts +0 -449
  355. package/src/utils/pathResolvers.ts +0 -81
  356. package/src/utils/projectConfig.ts +0 -340
  357. package/src/utils/retryFailedPromises.ts +0 -29
  358. package/src/utils/sessionAuth.ts +0 -230
  359. package/src/utils/setupFiles.ts +0 -1238
  360. package/src/utils/typeGuards.ts +0 -65
  361. package/src/utils/validationRules.ts +0 -88
  362. package/src/utils/versionDetection.ts +0 -292
  363. package/src/utils/yamlConverter.ts +0 -542
  364. package/src/utils/yamlLoader.ts +0 -371
  365. package/src/utilsController.ts +0 -1213
  366. package/tests/README.md +0 -497
  367. package/tests/adapters/AdapterFactory.test.ts +0 -277
  368. package/tests/integration/syncOperations.test.ts +0 -463
  369. package/tests/jest.config.js +0 -25
  370. package/tests/migration/configMigration.test.ts +0 -546
  371. package/tests/setup.ts +0 -62
  372. package/tests/testUtils.ts +0 -340
  373. package/tests/utils/loadConfigs.test.ts +0 -350
  374. package/tests/validation/configValidation.test.ts +0 -412
  375. package/tmp-sync-test/.appwrite/collections/TestCollection.yaml +0 -7
  376. package/tsconfig.json +0 -44
@@ -1,1068 +0,0 @@
1
- import { converterFunctions, tryAwaitWithRetry } from "appwrite-utils";
2
- import {
3
- Client,
4
- Databases,
5
- IndexType,
6
- Query,
7
- Storage,
8
- Users,
9
- type Models,
10
- } from "node-appwrite";
11
- import { InputFile } from "node-appwrite/file";
12
- import { getAppwriteClient } from "../utils/helperFunctions.js";
13
- // Legacy attribute helpers retained only for local-to-local flows if needed
14
- import { parseAttribute } from "appwrite-utils";
15
- import chalk from "chalk";
16
- import { fetchAllCollections } from "../collections/methods.js";
17
- import { MessageFormatter } from "../shared/messageFormatter.js";
18
- import { LegacyAdapter } from "../adapters/LegacyAdapter.js";
19
- import { ProgressManager } from "../shared/progressManager.js";
20
- import { getClient, getAdapter } from "../utils/getClientFromConfig.js";
21
- import { diffTableColumns } from "../collections/tableOperations.js";
22
- import { mapToCreateAttributeParams } from "../shared/attributeMapper.js";
23
- import type { DatabaseAdapter } from "../adapters/DatabaseAdapter.js";
24
-
25
- export interface TransferOptions {
26
- fromDb: Models.Database | undefined;
27
- targetDb: Models.Database | undefined;
28
- isRemote: boolean;
29
- collections?: string[];
30
- transferEndpoint?: string;
31
- transferProject?: string;
32
- transferKey?: string;
33
- sourceBucket?: Models.Bucket;
34
- targetBucket?: Models.Bucket;
35
- transferUsers?: boolean;
36
- }
37
-
38
- export const transferStorageLocalToLocal = async (
39
- storage: Storage,
40
- fromBucketId: string,
41
- toBucketId: string
42
- ) => {
43
- MessageFormatter.info(
44
- `Transferring files from ${fromBucketId} to ${toBucketId}`,
45
- { prefix: "Transfer" }
46
- );
47
- let lastFileId: string | undefined;
48
- let fromFiles = await tryAwaitWithRetry(
49
- async () => await storage.listFiles(fromBucketId, [Query.limit(100)])
50
- );
51
- const allFromFiles = fromFiles.files;
52
- let numberOfFiles = 0;
53
-
54
- const downloadFileWithRetry = async (bucketId: string, fileId: string) => {
55
- let attempts = 3;
56
- while (attempts > 0) {
57
- try {
58
- return await storage.getFileDownload(bucketId, fileId);
59
- } catch (error) {
60
- MessageFormatter.error(
61
- `Error downloading file ${fileId}`,
62
- error instanceof Error ? error : new Error(String(error)),
63
- { prefix: "Transfer" }
64
- );
65
- attempts--;
66
- if (attempts === 0) throw error;
67
- }
68
- }
69
- };
70
-
71
- if (fromFiles.files.length < 100) {
72
- for (const file of allFromFiles) {
73
- const fileData = await tryAwaitWithRetry(
74
- async () => await downloadFileWithRetry(file.bucketId, file.$id)
75
- );
76
- if (!fileData) {
77
- MessageFormatter.error(
78
- `Error downloading file ${file.$id}`,
79
- undefined,
80
- { prefix: "Transfer" }
81
- );
82
- continue;
83
- }
84
- const fileToCreate = InputFile.fromBuffer(
85
- new Uint8Array(fileData),
86
- file.name
87
- );
88
- MessageFormatter.progress(`Creating file: ${file.name}`, {
89
- prefix: "Transfer",
90
- });
91
- try {
92
- await tryAwaitWithRetry(
93
- async () =>
94
- await storage.createFile(
95
- toBucketId,
96
- file.$id,
97
- fileToCreate,
98
- file.$permissions
99
- )
100
- );
101
- } catch (error: any) {
102
- // File already exists, so we can skip it
103
- continue;
104
- }
105
- numberOfFiles++;
106
- }
107
- } else {
108
- lastFileId = fromFiles.files[fromFiles.files.length - 1].$id;
109
- while (lastFileId) {
110
- const files = await tryAwaitWithRetry(
111
- async () =>
112
- await storage.listFiles(fromBucketId, [
113
- Query.limit(100),
114
- Query.cursorAfter(lastFileId!),
115
- ])
116
- );
117
- allFromFiles.push(...files.files);
118
- if (files.files.length < 100) {
119
- lastFileId = undefined;
120
- } else {
121
- lastFileId = files.files[files.files.length - 1].$id;
122
- }
123
- }
124
- for (const file of allFromFiles) {
125
- const fileData = await tryAwaitWithRetry(
126
- async () => await downloadFileWithRetry(file.bucketId, file.$id)
127
- );
128
- if (!fileData) {
129
- MessageFormatter.error(
130
- `Error downloading file ${file.$id}`,
131
- undefined,
132
- { prefix: "Transfer" }
133
- );
134
- continue;
135
- }
136
- const fileToCreate = InputFile.fromBuffer(
137
- new Uint8Array(fileData),
138
- file.name
139
- );
140
- try {
141
- await tryAwaitWithRetry(
142
- async () =>
143
- await storage.createFile(
144
- toBucketId,
145
- file.$id,
146
- fileToCreate,
147
- file.$permissions
148
- )
149
- );
150
- } catch (error: any) {
151
- // File already exists, so we can skip it
152
- MessageFormatter.warning(
153
- `File ${file.$id} already exists, skipping...`,
154
- { prefix: "Transfer" }
155
- );
156
- continue;
157
- }
158
- numberOfFiles++;
159
- }
160
- }
161
-
162
- MessageFormatter.success(
163
- `Transferred ${numberOfFiles} files from ${fromBucketId} to ${toBucketId}`,
164
- { prefix: "Transfer" }
165
- );
166
- };
167
-
168
- export const transferStorageLocalToRemote = async (
169
- localStorage: Storage,
170
- endpoint: string,
171
- projectId: string,
172
- apiKey: string,
173
- fromBucketId: string,
174
- toBucketId: string
175
- ) => {
176
- MessageFormatter.info(
177
- `Transferring files from current storage ${fromBucketId} to ${endpoint} bucket ${toBucketId}`,
178
- { prefix: "Transfer" }
179
- );
180
- const client = getAppwriteClient(endpoint, projectId, apiKey);
181
- const remoteStorage = new Storage(client);
182
- let numberOfFiles = 0;
183
- let lastFileId: string | undefined;
184
- let fromFiles = await tryAwaitWithRetry(
185
- async () => await localStorage.listFiles(fromBucketId, [Query.limit(100)])
186
- );
187
- const allFromFiles = fromFiles.files;
188
- if (fromFiles.files.length === 100) {
189
- lastFileId = fromFiles.files[fromFiles.files.length - 1].$id;
190
- while (lastFileId) {
191
- const files = await tryAwaitWithRetry(
192
- async () =>
193
- await localStorage.listFiles(fromBucketId, [
194
- Query.limit(100),
195
- Query.cursorAfter(lastFileId!),
196
- ])
197
- );
198
- allFromFiles.push(...files.files);
199
- if (files.files.length < 100) {
200
- break;
201
- }
202
- lastFileId = files.files[files.files.length - 1].$id;
203
- }
204
- }
205
-
206
- for (const file of allFromFiles) {
207
- const fileData = await tryAwaitWithRetry(
208
- async () => await localStorage.getFileDownload(file.bucketId, file.$id)
209
- );
210
- const fileToCreate = InputFile.fromBuffer(
211
- new Uint8Array(fileData),
212
- file.name
213
- );
214
- try {
215
- await tryAwaitWithRetry(
216
- async () =>
217
- await remoteStorage.createFile(
218
- toBucketId,
219
- file.$id,
220
- fileToCreate,
221
- file.$permissions
222
- )
223
- );
224
- } catch (error: any) {
225
- // File already exists, so we can skip it
226
- MessageFormatter.warning(`File ${file.$id} already exists, skipping...`, {
227
- prefix: "Transfer",
228
- });
229
- continue;
230
- }
231
- numberOfFiles++;
232
- }
233
- MessageFormatter.success(
234
- `Transferred ${numberOfFiles} files from ${fromBucketId} to ${toBucketId}`,
235
- { prefix: "Transfer" }
236
- );
237
- };
238
-
239
- // Document transfer functions moved to collections/methods.ts with enhanced UX
240
-
241
- // Remote document transfer functions moved to collections/methods.ts with enhanced UX
242
-
243
- /**
244
- * Transfers all collections and documents from one local database to another local database.
245
- *
246
- * @param {Databases} localDb - The local database instance.
247
- * @param {string} fromDbId - The ID of the source database.
248
- * @param {string} targetDbId - The ID of the target database.
249
- * @return {Promise<void>} A promise that resolves when the transfer is complete.
250
- */
251
- export const transferDatabaseLocalToLocal = async (
252
- localDb: Databases,
253
- fromDbId: string,
254
- targetDbId: string
255
- ) => {
256
- MessageFormatter.info(
257
- `Starting database transfer from ${fromDbId} to ${targetDbId}`,
258
- { prefix: "Transfer" }
259
- );
260
- // Get all collections from source database
261
- const sourceCollections = await fetchAllCollections(fromDbId, localDb);
262
- MessageFormatter.info(
263
- `Found ${sourceCollections.length} collections in source database`,
264
- { prefix: "Transfer" }
265
- );
266
-
267
- // Process each collection
268
- for (const collection of sourceCollections) {
269
- MessageFormatter.processing(
270
- `Processing collection: ${collection.name} (${collection.$id})`,
271
- { prefix: "Transfer" }
272
- );
273
-
274
- try {
275
- // Create or update collection in target
276
- let targetCollection: Models.Collection;
277
- const existingCollection = await tryAwaitWithRetry(async () =>
278
- localDb.listCollections(targetDbId, [
279
- Query.equal("$id", collection.$id),
280
- ])
281
- );
282
-
283
- if (existingCollection.collections.length > 0) {
284
- targetCollection = existingCollection.collections[0];
285
- MessageFormatter.info(
286
- `Collection ${collection.name} exists in target database`,
287
- { prefix: "Transfer" }
288
- );
289
-
290
- // Update collection if needed
291
- if (
292
- targetCollection.name !== collection.name ||
293
- targetCollection.$permissions !== collection.$permissions ||
294
- targetCollection.documentSecurity !== collection.documentSecurity ||
295
- targetCollection.enabled !== collection.enabled
296
- ) {
297
- targetCollection = await tryAwaitWithRetry(async () =>
298
- localDb.updateCollection(
299
- targetDbId,
300
- collection.$id,
301
- collection.name,
302
- collection.$permissions,
303
- collection.documentSecurity,
304
- collection.enabled
305
- )
306
- );
307
- MessageFormatter.success(
308
- `Collection ${collection.name} updated`,
309
- { prefix: "Transfer" }
310
- );
311
- }
312
- } else {
313
- MessageFormatter.progress(
314
- `Creating collection ${collection.name} in target database...`,
315
- { prefix: "Transfer" }
316
- );
317
- targetCollection = await tryAwaitWithRetry(async () =>
318
- localDb.createCollection(
319
- targetDbId,
320
- collection.$id,
321
- collection.name,
322
- collection.$permissions,
323
- collection.documentSecurity,
324
- collection.enabled
325
- )
326
- );
327
- }
328
-
329
- // Create attributes via local adapter (wrap the existing client)
330
- const localAdapter: DatabaseAdapter = new LegacyAdapter((localDb as any).client);
331
- MessageFormatter.info(`Creating attributes for ${collection.name} via adapter...`, { prefix: 'Transfer' });
332
- const uniformAttrs = collection.attributes.map((attr) => parseAttribute(attr as any));
333
- const nonRel = uniformAttrs.filter((a: any) => a.type !== 'relationship');
334
- for (const attr of nonRel) {
335
- const params = mapToCreateAttributeParams(attr as any, { databaseId: targetDbId, tableId: targetCollection.$id });
336
- await localAdapter.createAttribute(params);
337
- await new Promise((r) => setTimeout(r, 150));
338
- }
339
-
340
- // Wait for attributes to become available
341
- for (const attr of nonRel) {
342
- const maxWait = 60000; const start = Date.now();
343
- let lastStatus = '';
344
- while (Date.now() - start < maxWait) {
345
- try {
346
- const tableRes = await localAdapter.getTable({ databaseId: targetDbId, tableId: targetCollection.$id });
347
- const attrs = (tableRes as any).attributes || (tableRes as any).columns || [];
348
- const found = attrs.find((a: any) => a.key === attr.key);
349
- if (found) {
350
- if (found.status === 'available') break;
351
- if (found.status === 'failed' || found.status === 'stuck') {
352
- throw new Error(found.error || `Attribute ${attr.key} failed`);
353
- }
354
- lastStatus = found.status;
355
- }
356
- await new Promise((r) => setTimeout(r, 2000));
357
- } catch {
358
- await new Promise((r) => setTimeout(r, 2000));
359
- }
360
- }
361
- if (Date.now() - start >= maxWait) {
362
- MessageFormatter.warning(`Attribute ${attr.key} did not become available within 60s (last: ${lastStatus})`, { prefix: 'Transfer' });
363
- }
364
- }
365
-
366
- // Relationship attributes
367
- const rels = uniformAttrs.filter((a: any) => a.type === 'relationship');
368
- for (const attr of rels) {
369
- const params = mapToCreateAttributeParams(attr as any, { databaseId: targetDbId, tableId: targetCollection.$id });
370
- await localAdapter.createAttribute(params);
371
- await new Promise((r) => setTimeout(r, 150));
372
- }
373
-
374
- // Handle indexes via adapter (create or update)
375
- for (const idx of collection.indexes) {
376
- try {
377
- await localAdapter.createIndex({
378
- databaseId: targetDbId,
379
- tableId: targetCollection.$id,
380
- key: (idx as any).key,
381
- type: (idx as any).type,
382
- attributes: (idx as any).attributes,
383
- orders: (idx as any).orders || []
384
- });
385
- await new Promise((r) => setTimeout(r, 150));
386
- MessageFormatter.success(`Index ${(idx as any).key} created`, { prefix: 'Transfer' });
387
- } catch (e) {
388
- // Try update path by deleting and recreating if necessary
389
- try {
390
- await localAdapter.deleteIndex({ databaseId: targetDbId, tableId: targetCollection.$id, key: (idx as any).key });
391
- await localAdapter.createIndex({
392
- databaseId: targetDbId,
393
- tableId: targetCollection.$id,
394
- key: (idx as any).key,
395
- type: (idx as any).type,
396
- attributes: (idx as any).attributes,
397
- orders: (idx as any).orders || []
398
- });
399
- await new Promise((r) => setTimeout(r, 150));
400
- MessageFormatter.info(`Index ${(idx as any).key} recreated`, { prefix: 'Transfer' });
401
- } catch (e2) {
402
- MessageFormatter.error(`Failed to ensure index ${(idx as any).key}`, e2 instanceof Error ? e2 : new Error(String(e2)), { prefix: 'Transfer' });
403
- }
404
- }
405
- }
406
-
407
- // Transfer documents
408
- const { transferDocumentsBetweenDbsLocalToLocal } = await import(
409
- "../collections/methods.js"
410
- );
411
- await transferDocumentsBetweenDbsLocalToLocal(
412
- localDb,
413
- fromDbId,
414
- targetDbId,
415
- collection.$id,
416
- targetCollection.$id
417
- );
418
- } catch (error) {
419
- MessageFormatter.error(
420
- `Error processing collection ${collection.name}`,
421
- error instanceof Error ? error : new Error(String(error)),
422
- { prefix: "Transfer" }
423
- );
424
- }
425
- }
426
- };
427
-
428
- export const transferDatabaseLocalToRemote = async (
429
- localDb: Databases,
430
- endpoint: string,
431
- projectId: string,
432
- apiKey: string,
433
- fromDbId: string,
434
- toDbId: string
435
- ) => {
436
- const client = getAppwriteClient(endpoint, projectId, apiKey);
437
- const remoteDb = new Databases(client);
438
-
439
- // Get all collections from source database
440
- const sourceCollections = await fetchAllCollections(fromDbId, localDb);
441
- MessageFormatter.info(
442
- `Found ${sourceCollections.length} collections in source database`,
443
- { prefix: "Transfer" }
444
- );
445
-
446
- // Process each collection
447
- for (const collection of sourceCollections) {
448
- MessageFormatter.processing(
449
- `Processing collection: ${collection.name} (${collection.$id})`,
450
- { prefix: "Transfer" }
451
- );
452
-
453
- try {
454
- // Create or update collection in target
455
- let targetCollection: Models.Collection;
456
- const existingCollection = await tryAwaitWithRetry(async () =>
457
- remoteDb.listCollections(toDbId, [Query.equal("$id", collection.$id)])
458
- );
459
-
460
- if (existingCollection.collections.length > 0) {
461
- targetCollection = existingCollection.collections[0];
462
- MessageFormatter.info(
463
- `Collection ${collection.name} exists in remote database`,
464
- { prefix: "Transfer" }
465
- );
466
-
467
- // Update collection if needed
468
- if (
469
- targetCollection.name !== collection.name ||
470
- targetCollection.$permissions !== collection.$permissions ||
471
- targetCollection.documentSecurity !== collection.documentSecurity ||
472
- targetCollection.enabled !== collection.enabled
473
- ) {
474
- targetCollection = await tryAwaitWithRetry(async () =>
475
- remoteDb.updateCollection(
476
- toDbId,
477
- collection.$id,
478
- collection.name,
479
- collection.$permissions,
480
- collection.documentSecurity,
481
- collection.enabled
482
- )
483
- );
484
- MessageFormatter.success(
485
- `Collection ${collection.name} updated`,
486
- { prefix: "Transfer" }
487
- );
488
- }
489
- } else {
490
- MessageFormatter.progress(
491
- `Creating collection ${collection.name} in remote database...`,
492
- { prefix: "Transfer" }
493
- );
494
- targetCollection = await tryAwaitWithRetry(async () =>
495
- remoteDb.createCollection(
496
- toDbId,
497
- collection.$id,
498
- collection.name,
499
- collection.$permissions,
500
- collection.documentSecurity,
501
- collection.enabled
502
- )
503
- );
504
- }
505
-
506
- // Create/Update attributes via adapter (prefer adapter for remote)
507
- const { adapter: remoteAdapter } = await getAdapter(endpoint, projectId, apiKey, 'auto');
508
- MessageFormatter.info(`Creating attributes for ${collection.name} via adapter...`, { prefix: 'Transfer' });
509
- const uniformAttrs = collection.attributes.map((attr) => parseAttribute(attr as any));
510
- const nonRel = uniformAttrs.filter((a: any) => a.type !== 'relationship');
511
- if (nonRel.length > 0) {
512
- const tableInfo = await (remoteAdapter as DatabaseAdapter).getTable({ databaseId: toDbId, tableId: collection.$id });
513
- const existingCols: any[] = (tableInfo as any).columns || (tableInfo as any).attributes || [];
514
- const { toCreate, toUpdate } = diffTableColumns(existingCols, nonRel as any);
515
- for (const a of toUpdate) { const p = mapToCreateAttributeParams(a as any, { databaseId: toDbId, tableId: collection.$id }); await (remoteAdapter as DatabaseAdapter).updateAttribute(p as any); await new Promise((r)=>setTimeout(r,150)); }
516
- for (const a of toCreate) { const p = mapToCreateAttributeParams(a as any, { databaseId: toDbId, tableId: collection.$id }); await (remoteAdapter as DatabaseAdapter).createAttribute(p); await new Promise((r)=>setTimeout(r,150)); }
517
- }
518
-
519
- // Wait for non-relationship attributes to become available
520
- for (const attr of nonRel) {
521
- const maxWait = 60000; const start = Date.now();
522
- let lastStatus = '';
523
- while (Date.now() - start < maxWait) {
524
- try {
525
- const tableRes = await (remoteAdapter as DatabaseAdapter).getTable({ databaseId: toDbId, tableId: collection.$id });
526
- const attrs = (tableRes as any).attributes || (tableRes as any).columns || [];
527
- const found = attrs.find((a: any) => a.key === attr.key);
528
- if (found) {
529
- if (found.status === 'available') break;
530
- if (found.status === 'failed' || found.status === 'stuck') {
531
- throw new Error(found.error || `Attribute ${attr.key} failed`);
532
- }
533
- lastStatus = found.status;
534
- }
535
- await new Promise((r) => setTimeout(r, 2000));
536
- } catch {
537
- await new Promise((r) => setTimeout(r, 2000));
538
- }
539
- }
540
- if (Date.now() - start >= maxWait) {
541
- MessageFormatter.warning(`Attribute ${attr.key} did not become available within 60s (last: ${lastStatus})`, { prefix: 'Transfer' });
542
- }
543
- }
544
-
545
- // Relationship attributes
546
- const rels = uniformAttrs.filter((a: any) => a.type === 'relationship');
547
- if (rels.length > 0) {
548
- const tableInfo2 = await (remoteAdapter as DatabaseAdapter).getTable({ databaseId: toDbId, tableId: collection.$id });
549
- const existingCols2: any[] = (tableInfo2 as any).columns || (tableInfo2 as any).attributes || [];
550
- const { toCreate: rCreate, toUpdate: rUpdate } = diffTableColumns(existingCols2, rels as any);
551
- for (const a of rUpdate) { const p = mapToCreateAttributeParams(a as any, { databaseId: toDbId, tableId: collection.$id }); await (remoteAdapter as DatabaseAdapter).updateAttribute(p as any); await new Promise((r)=>setTimeout(r,150)); }
552
- for (const a of rCreate) { const p = mapToCreateAttributeParams(a as any, { databaseId: toDbId, tableId: collection.$id }); await (remoteAdapter as DatabaseAdapter).createAttribute(p); await new Promise((r)=>setTimeout(r,150)); }
553
- }
554
-
555
- // Handle indexes with enhanced status checking
556
- MessageFormatter.info(
557
- `Creating indexes for collection ${collection.name} with enhanced monitoring...`,
558
- { prefix: "Transfer" }
559
- );
560
-
561
- // Create indexes via adapter
562
- for (const idx of (collection.indexes as any[]) || []) {
563
- try {
564
- await (remoteAdapter as DatabaseAdapter).createIndex({
565
- databaseId: toDbId,
566
- tableId: collection.$id,
567
- key: idx.key,
568
- type: idx.type,
569
- attributes: idx.attributes,
570
- orders: idx.orders || []
571
- });
572
- await new Promise((r) => setTimeout(r, 150));
573
- } catch (e) {
574
- MessageFormatter.error(`Failed to create index ${idx.key}`, e instanceof Error ? e : new Error(String(e)), { prefix: 'Transfer' });
575
- }
576
- }
577
-
578
- // Transfer documents
579
- const { transferDocumentsBetweenDbsLocalToRemote } = await import(
580
- "../collections/methods.js"
581
- );
582
- await transferDocumentsBetweenDbsLocalToRemote(
583
- localDb,
584
- endpoint,
585
- projectId,
586
- apiKey,
587
- fromDbId,
588
- toDbId,
589
- collection.$id,
590
- targetCollection.$id
591
- );
592
- } catch (error) {
593
- MessageFormatter.error(
594
- `Error processing collection ${collection.name}`,
595
- error instanceof Error ? error : new Error(String(error)),
596
- { prefix: "Transfer" }
597
- );
598
- }
599
- }
600
- };
601
-
602
- export const transferUsersLocalToRemote = async (
603
- localUsers: Users,
604
- endpoint: string,
605
- projectId: string,
606
- apiKey: string
607
- ) => {
608
- MessageFormatter.info(
609
- "Starting user transfer to remote instance...",
610
- { prefix: "Transfer" }
611
- );
612
-
613
- const client = getClient(endpoint, projectId, apiKey);
614
- const remoteUsers = new Users(client);
615
-
616
- let totalTransferred = 0;
617
- let lastId: string | undefined;
618
-
619
- while (true) {
620
- const queries = [Query.limit(100)];
621
- if (lastId) {
622
- queries.push(Query.cursorAfter(lastId));
623
- }
624
-
625
- const usersList = await tryAwaitWithRetry(async () =>
626
- localUsers.list(queries)
627
- );
628
-
629
- if (usersList.users.length === 0) {
630
- break;
631
- }
632
-
633
- for (const user of usersList.users) {
634
- try {
635
- // Check if user already exists in remote
636
- let remoteUser: Models.User<Models.Preferences> | undefined;
637
- try {
638
- remoteUser = await tryAwaitWithRetry(async () =>
639
- remoteUsers.get(user.$id)
640
- );
641
-
642
- // If user exists, update only the differences
643
- if (remoteUser) {
644
- MessageFormatter.info(
645
- `User ${user.$id} exists, checking for updates...`,
646
- { prefix: "Transfer" }
647
- );
648
- let hasUpdates = false;
649
-
650
- // Update name if different
651
- if (remoteUser.name !== user.name) {
652
- await tryAwaitWithRetry(async () =>
653
- remoteUsers.updateName(user.$id, user.name)
654
- );
655
- MessageFormatter.success(
656
- `Updated name for user ${user.$id}`,
657
- { prefix: "Transfer" }
658
- );
659
- hasUpdates = true;
660
- }
661
-
662
- // Update email if different
663
- if (remoteUser.email !== user.email) {
664
- await tryAwaitWithRetry(async () =>
665
- remoteUsers.updateEmail(user.$id, user.email)
666
- );
667
- MessageFormatter.success(
668
- `Updated email for user ${user.$id}`,
669
- { prefix: "Transfer" }
670
- );
671
- hasUpdates = true;
672
- }
673
-
674
- // Update phone if different
675
- const normalizedLocalPhone = user.phone
676
- ? converterFunctions.convertPhoneStringToUSInternational(user.phone)
677
- : undefined;
678
- if (remoteUser.phone !== normalizedLocalPhone) {
679
- if (normalizedLocalPhone) {
680
- await tryAwaitWithRetry(async () =>
681
- remoteUsers.updatePhone(user.$id, normalizedLocalPhone)
682
- );
683
- }
684
- MessageFormatter.success(
685
- `Updated phone for user ${user.$id}`,
686
- { prefix: "Transfer" }
687
- );
688
- hasUpdates = true;
689
- }
690
-
691
- // Update preferences if different
692
- if (JSON.stringify(remoteUser.prefs) !== JSON.stringify(user.prefs)) {
693
- await tryAwaitWithRetry(async () =>
694
- remoteUsers.updatePrefs(user.$id, user.prefs)
695
- );
696
- MessageFormatter.success(
697
- `Updated preferences for user ${user.$id}`,
698
- { prefix: "Transfer" }
699
- );
700
- hasUpdates = true;
701
- }
702
-
703
- // Update labels if different
704
- if (JSON.stringify(remoteUser.labels) !== JSON.stringify(user.labels)) {
705
- await tryAwaitWithRetry(async () =>
706
- remoteUsers.updateLabels(user.$id, user.labels)
707
- );
708
- MessageFormatter.success(
709
- `Updated labels for user ${user.$id}`,
710
- { prefix: "Transfer" }
711
- );
712
- hasUpdates = true;
713
- }
714
-
715
- // Update email verification if different
716
- if (remoteUser.emailVerification !== user.emailVerification) {
717
- await tryAwaitWithRetry(async () =>
718
- remoteUsers.updateEmailVerification(user.$id, user.emailVerification)
719
- );
720
- MessageFormatter.success(
721
- `Updated email verification for user ${user.$id}`,
722
- { prefix: "Transfer" }
723
- );
724
- hasUpdates = true;
725
- }
726
-
727
- // Update phone verification if different
728
- if (remoteUser.phoneVerification !== user.phoneVerification) {
729
- await tryAwaitWithRetry(async () =>
730
- remoteUsers.updatePhoneVerification(user.$id, user.phoneVerification)
731
- );
732
- MessageFormatter.success(
733
- `Updated phone verification for user ${user.$id}`,
734
- { prefix: "Transfer" }
735
- );
736
- hasUpdates = true;
737
- }
738
-
739
- // Update status if different
740
- if (remoteUser.status !== user.status) {
741
- await tryAwaitWithRetry(async () =>
742
- remoteUsers.updateStatus(user.$id, user.status)
743
- );
744
- MessageFormatter.success(
745
- `Updated status for user ${user.$id}`,
746
- { prefix: "Transfer" }
747
- );
748
- hasUpdates = true;
749
- }
750
-
751
- if (!hasUpdates) {
752
- MessageFormatter.info(
753
- `User ${user.$id} is already up to date, skipping...`,
754
- { prefix: "Transfer" }
755
- );
756
- } else {
757
- totalTransferred++;
758
- MessageFormatter.success(
759
- `Updated user ${user.$id}`,
760
- { prefix: "Transfer" }
761
- );
762
- }
763
- continue;
764
- }
765
- } catch (error: any) {
766
- // User doesn't exist, proceed with creation
767
- }
768
-
769
- const phone = user.phone
770
- ? converterFunctions.convertPhoneStringToUSInternational(user.phone)
771
- : undefined;
772
-
773
- // Handle user creation based on hash type
774
- if (user.hash && user.password) {
775
- // User has a hashed password - recreate with proper hash method
776
- const hashType = user.hash.toLowerCase();
777
- const hashedPassword = user.password; // This is already hashed
778
- const hashOptions = (user.hashOptions as Record<string, any>) || {};
779
-
780
- try {
781
- switch (hashType) {
782
- case "argon2":
783
- await tryAwaitWithRetry(async () =>
784
- remoteUsers.createArgon2User(
785
- user.$id,
786
- user.email,
787
- hashedPassword,
788
- user.name
789
- )
790
- );
791
- break;
792
-
793
- case "bcrypt":
794
- await tryAwaitWithRetry(async () =>
795
- remoteUsers.createBcryptUser(
796
- user.$id,
797
- user.email,
798
- hashedPassword,
799
- user.name
800
- )
801
- );
802
- break;
803
-
804
- case "scrypt":
805
- // Scrypt requires additional parameters from hashOptions
806
- const salt =
807
- typeof hashOptions.salt === "string" ? hashOptions.salt : "";
808
- const costCpu =
809
- typeof hashOptions.costCpu === "number"
810
- ? hashOptions.costCpu
811
- : 32768;
812
- const costMemory =
813
- typeof hashOptions.costMemory === "number"
814
- ? hashOptions.costMemory
815
- : 14;
816
- const costParallel =
817
- typeof hashOptions.costParallel === "number"
818
- ? hashOptions.costParallel
819
- : 1;
820
- const length =
821
- typeof hashOptions.length === "number"
822
- ? hashOptions.length
823
- : 64;
824
-
825
- // Warn if using default values due to missing hash options
826
- if (
827
- !hashOptions.salt ||
828
- typeof hashOptions.costCpu !== "number"
829
- ) {
830
- MessageFormatter.warning(
831
- `User ${user.$id}: Using default Scrypt parameters due to missing hashOptions`,
832
- { prefix: "Transfer" }
833
- );
834
- }
835
-
836
- await tryAwaitWithRetry(async () =>
837
- remoteUsers.createScryptUser(
838
- user.$id,
839
- user.email,
840
- hashedPassword,
841
- salt,
842
- costCpu,
843
- costMemory,
844
- costParallel,
845
- length,
846
- user.name
847
- )
848
- );
849
- break;
850
-
851
- case "scryptmodified":
852
- // Scrypt Modified (Firebase) requires salt, separator, and signer key
853
- const modSalt =
854
- typeof hashOptions.salt === "string" ? hashOptions.salt : "";
855
- const saltSeparator =
856
- typeof hashOptions.saltSeparator === "string"
857
- ? hashOptions.saltSeparator
858
- : "";
859
- const signerKey =
860
- typeof hashOptions.signerKey === "string"
861
- ? hashOptions.signerKey
862
- : "";
863
-
864
- // Warn if critical parameters are missing
865
- if (
866
- !hashOptions.salt ||
867
- !hashOptions.saltSeparator ||
868
- !hashOptions.signerKey
869
- ) {
870
- MessageFormatter.warning(
871
- `User ${user.$id}: Missing critical Scrypt Modified parameters in hashOptions`,
872
- { prefix: "Transfer" }
873
- );
874
- }
875
-
876
- await tryAwaitWithRetry(async () =>
877
- remoteUsers.createScryptModifiedUser(
878
- user.$id,
879
- user.email,
880
- hashedPassword,
881
- modSalt,
882
- saltSeparator,
883
- signerKey,
884
- user.name
885
- )
886
- );
887
- break;
888
-
889
- case "md5":
890
- await tryAwaitWithRetry(async () =>
891
- remoteUsers.createMD5User(
892
- user.$id,
893
- user.email,
894
- hashedPassword,
895
- user.name
896
- )
897
- );
898
- break;
899
-
900
- case "sha":
901
- case "sha1":
902
- case "sha256":
903
- case "sha512":
904
- // SHA variants - determine version from hash type
905
- const getPasswordHashVersion = (hash: string) => {
906
- switch (hash.toLowerCase()) {
907
- case "sha1":
908
- return "sha1" as any;
909
- case "sha256":
910
- return "sha256" as any;
911
- case "sha512":
912
- return "sha512" as any;
913
- default:
914
- return "sha256" as any; // Default to SHA256
915
- }
916
- };
917
-
918
- await tryAwaitWithRetry(async () =>
919
- remoteUsers.createSHAUser(
920
- user.$id,
921
- user.email,
922
- hashedPassword,
923
- getPasswordHashVersion(hashType),
924
- user.name
925
- )
926
- );
927
- break;
928
-
929
- case "phpass":
930
- await tryAwaitWithRetry(async () =>
931
- remoteUsers.createPHPassUser(
932
- user.$id,
933
- user.email,
934
- hashedPassword,
935
- user.name
936
- )
937
- );
938
- break;
939
-
940
- default:
941
- MessageFormatter.warning(
942
- `Unknown hash type '${hashType}' for user ${user.$id}, falling back to Argon2`,
943
- { prefix: "Transfer" }
944
- );
945
- await tryAwaitWithRetry(async () =>
946
- remoteUsers.createArgon2User(
947
- user.$id,
948
- user.email,
949
- hashedPassword,
950
- user.name
951
- )
952
- );
953
- break;
954
- }
955
-
956
- MessageFormatter.success(
957
- `User ${user.$id} created with preserved ${hashType} password`,
958
- { prefix: "Transfer" }
959
- );
960
- } catch (error) {
961
- MessageFormatter.warning(
962
- `Failed to create user ${user.$id} with ${hashType} hash, trying with temporary password`,
963
- { prefix: "Transfer" }
964
- );
965
-
966
- // Fallback to creating user with temporary password
967
- await tryAwaitWithRetry(async () =>
968
- remoteUsers.create(
969
- user.$id,
970
- user.email,
971
- phone,
972
- `changeMe${user.email}`,
973
- user.name
974
- )
975
- );
976
-
977
- MessageFormatter.warning(
978
- `User ${user.$id} created with temporary password - password reset required`,
979
- { prefix: "Transfer" }
980
- );
981
- }
982
- } else {
983
- // No hash or password - create with temporary password
984
- const tempPassword = user.password || `changeMe${user.email}`;
985
-
986
- await tryAwaitWithRetry(async () =>
987
- remoteUsers.create(
988
- user.$id,
989
- user.email,
990
- phone,
991
- tempPassword,
992
- user.name
993
- )
994
- );
995
-
996
- if (!user.password) {
997
- MessageFormatter.warning(
998
- `User ${user.$id} created with temporary password - password reset required`,
999
- { prefix: "Transfer" }
1000
- );
1001
- }
1002
- }
1003
-
1004
- // Update phone, labels, and other attributes for newly created users
1005
- if (phone) {
1006
- await tryAwaitWithRetry(async () =>
1007
- remoteUsers.updatePhone(user.$id, phone)
1008
- );
1009
- }
1010
-
1011
- if (user.labels && user.labels.length > 0) {
1012
- await tryAwaitWithRetry(async () =>
1013
- remoteUsers.updateLabels(user.$id, user.labels)
1014
- );
1015
- }
1016
-
1017
- // Update user preferences and status for newly created users
1018
- await tryAwaitWithRetry(async () =>
1019
- remoteUsers.updatePrefs(user.$id, user.prefs)
1020
- );
1021
-
1022
- if (user.emailVerification) {
1023
- await tryAwaitWithRetry(async () =>
1024
- remoteUsers.updateEmailVerification(user.$id, true)
1025
- );
1026
- } else {
1027
- await tryAwaitWithRetry(async () =>
1028
- remoteUsers.updateEmailVerification(user.$id, false)
1029
- );
1030
- }
1031
-
1032
- if (user.phoneVerification) {
1033
- await tryAwaitWithRetry(async () =>
1034
- remoteUsers.updatePhoneVerification(user.$id, true)
1035
- );
1036
- }
1037
-
1038
- if (user.status === false) {
1039
- await tryAwaitWithRetry(async () =>
1040
- remoteUsers.updateStatus(user.$id, false)
1041
- );
1042
- }
1043
-
1044
- totalTransferred++;
1045
- MessageFormatter.success(
1046
- `Transferred user ${user.$id}`,
1047
- { prefix: "Transfer" }
1048
- );
1049
- } catch (error) {
1050
- MessageFormatter.error(
1051
- `Failed to transfer user ${user.$id}`,
1052
- error instanceof Error ? error : new Error(String(error)),
1053
- { prefix: "Transfer" }
1054
- );
1055
- }
1056
- }
1057
-
1058
- if (usersList.users.length < 100) {
1059
- break;
1060
- }
1061
- lastId = usersList.users[usersList.users.length - 1].$id;
1062
- }
1063
-
1064
- MessageFormatter.success(
1065
- `Successfully transferred ${totalTransferred} users`,
1066
- { prefix: "Transfer" }
1067
- );
1068
- };