appwrite-utils-cli 1.9.7 → 1.11.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 (425) hide show
  1. package/CONFIG_TODO.md +1189 -1189
  2. package/README.md +1004 -1004
  3. package/SELECTION_DIALOGS.md +145 -145
  4. package/SERVICE_IMPLEMENTATION_REPORT.md +462 -462
  5. package/package.json +6 -3
  6. package/scripts/copy-templates.ts +23 -23
  7. package/src/adapters/index.ts +11 -37
  8. package/src/backups/operations/bucketBackup.ts +277 -277
  9. package/src/backups/operations/collectionBackup.ts +310 -310
  10. package/src/backups/operations/comprehensiveBackup.ts +342 -342
  11. package/src/backups/schemas/bucketManifest.ts +78 -78
  12. package/src/backups/schemas/comprehensiveManifest.ts +76 -76
  13. package/src/backups/tracking/centralizedTracking.ts +352 -352
  14. package/src/cli/commands/configCommands.ts +265 -201
  15. package/src/cli/commands/databaseCommands.ts +931 -879
  16. package/src/cli/commands/functionCommands.ts +333 -332
  17. package/src/cli/commands/importFileCommands.ts +815 -0
  18. package/src/cli/commands/schemaCommands.ts +141 -141
  19. package/src/cli/commands/storageCommands.ts +2 -3
  20. package/src/cli/commands/transferCommands.ts +454 -457
  21. package/src/collections/attributes.ts.backup +1555 -1555
  22. package/src/collections/{attributes.ts → columns.ts} +15 -10
  23. package/src/collections/indexes.ts +350 -352
  24. package/src/collections/methods.ts +714 -700
  25. package/src/collections/tableOperations.ts +29 -8
  26. package/src/collections/transferOperations.ts +376 -377
  27. package/src/collections/wipeOperations.ts +449 -346
  28. package/src/databases/methods.ts +49 -49
  29. package/src/databases/setup.ts +77 -77
  30. package/src/examples/yamlTerminologyExample.ts +346 -346
  31. package/src/functions/deployments.ts +221 -220
  32. package/src/functions/fnConfigDiscovery.ts +2 -2
  33. package/src/functions/methods.ts +284 -284
  34. package/src/functions/templates/count-docs-in-collection/README.md +53 -53
  35. package/src/functions/templates/count-docs-in-collection/src/main.ts +159 -159
  36. package/src/functions/templates/count-docs-in-collection/src/request.ts +8 -8
  37. package/src/functions/templates/hono-typescript/README.md +285 -285
  38. package/src/functions/templates/hono-typescript/src/adapters/request.ts +73 -73
  39. package/src/functions/templates/hono-typescript/src/adapters/response.ts +105 -105
  40. package/src/functions/templates/hono-typescript/src/app.ts +179 -179
  41. package/src/functions/templates/hono-typescript/src/context.ts +102 -102
  42. package/src/functions/templates/hono-typescript/src/{index.ts → main.ts} +53 -53
  43. package/src/functions/templates/hono-typescript/src/middleware/appwrite.ts +118 -118
  44. package/src/functions/templates/typescript-node/README.md +31 -31
  45. package/src/functions/templates/typescript-node/src/context.ts +102 -102
  46. package/src/functions/templates/typescript-node/src/{index.ts → main.ts} +29 -29
  47. package/src/functions/templates/uv/README.md +30 -30
  48. package/src/functions/templates/uv/pyproject.toml +29 -29
  49. package/src/functions/templates/uv/src/context.py +124 -124
  50. package/src/functions/templates/uv/src/{index.py → main.py} +45 -45
  51. package/src/init.ts +62 -62
  52. package/src/interactiveCLI.ts +1095 -1030
  53. package/src/main.ts +1517 -1670
  54. package/src/migrations/afterImportActions.ts +579 -580
  55. package/src/migrations/appwriteToX.ts +634 -630
  56. package/src/migrations/comprehensiveTransfer.ts +2149 -2149
  57. package/src/migrations/dataLoader.ts +1729 -1702
  58. package/src/migrations/importController.ts +440 -428
  59. package/src/migrations/importDataActions.ts +315 -315
  60. package/src/migrations/relationships.ts +333 -334
  61. package/src/migrations/services/DataTransformationService.ts +195 -195
  62. package/src/migrations/services/FileHandlerService.ts +310 -310
  63. package/src/migrations/services/ImportOrchestrator.ts +674 -665
  64. package/src/migrations/services/RateLimitManager.ts +362 -362
  65. package/src/migrations/services/RelationshipResolver.ts +460 -460
  66. package/src/migrations/services/UserMappingService.ts +344 -344
  67. package/src/migrations/services/ValidationService.ts +333 -333
  68. package/src/migrations/transfer.ts +987 -942
  69. package/src/migrations/yaml/YamlImportConfigLoader.ts +438 -438
  70. package/src/migrations/yaml/YamlImportIntegration.ts +438 -438
  71. package/src/migrations/yaml/generateImportSchemas.ts +1347 -1347
  72. package/src/schemas/authUser.ts +23 -23
  73. package/src/setup.ts +8 -8
  74. package/src/setupCommands.ts +5 -6
  75. package/src/setupController.ts +42 -42
  76. package/src/shared/backupMetadataSchema.ts +93 -93
  77. package/src/shared/backupTracking.ts +211 -211
  78. package/src/shared/confirmationDialogs.ts +326 -326
  79. package/src/shared/migrationHelpers.ts +232 -232
  80. package/src/shared/operationLogger.ts +20 -20
  81. package/src/shared/operationQueue.ts +326 -327
  82. package/src/shared/operationsTable.ts +338 -338
  83. package/src/shared/operationsTableSchema.ts +60 -60
  84. package/src/shared/progressManager.ts +277 -277
  85. package/src/shared/relationshipExtractor.ts +214 -214
  86. package/src/shared/selectionDialogs.ts +775 -722
  87. package/src/storage/backupCompression.ts +88 -88
  88. package/src/storage/methods.ts +695 -682
  89. package/src/storage/schemas.ts +205 -205
  90. package/src/tables/indexManager.ts +408 -408
  91. package/src/types/node-appwrite-tablesdb.d.ts +43 -43
  92. package/src/types.ts +9 -9
  93. package/src/users/methods.ts +358 -359
  94. package/src/utils/configMigration.ts +347 -347
  95. package/src/utils/index.ts +2 -2
  96. package/src/utils/loadConfigs.ts +457 -449
  97. package/src/utils/setupFiles.ts +1236 -1238
  98. package/src/utilsController.ts +1263 -1213
  99. package/tests/README.md +496 -496
  100. package/tests/adapters/AdapterFactory.test.ts +276 -276
  101. package/tests/integration/syncOperations.test.ts +462 -462
  102. package/tests/jest.config.js +24 -24
  103. package/tests/migration/configMigration.test.ts +545 -545
  104. package/tests/setup.ts +61 -61
  105. package/tests/testUtils.ts +339 -339
  106. package/tests/utils/loadConfigs.test.ts +349 -349
  107. package/tests/validation/configValidation.test.ts +411 -411
  108. package/tsconfig.json +44 -44
  109. package/.appwrite/.yaml_schemas/appwrite-config.schema.json +0 -380
  110. package/.appwrite/.yaml_schemas/collection.schema.json +0 -255
  111. package/.appwrite/collections/Categories.yaml +0 -182
  112. package/.appwrite/collections/ExampleCollection.yaml +0 -36
  113. package/.appwrite/collections/Posts.yaml +0 -227
  114. package/.appwrite/collections/Users.yaml +0 -149
  115. package/.appwrite/config.yaml +0 -109
  116. package/.appwrite/import/README.md +0 -148
  117. package/.appwrite/import/categories-import.yaml +0 -129
  118. package/.appwrite/import/posts-import.yaml +0 -208
  119. package/.appwrite/import/users-import.yaml +0 -130
  120. package/.appwrite/importData/categories.json +0 -194
  121. package/.appwrite/importData/posts.json +0 -270
  122. package/.appwrite/importData/users.json +0 -220
  123. package/.appwrite/schemas/categories.json +0 -128
  124. package/.appwrite/schemas/exampleCollection.json +0 -52
  125. package/.appwrite/schemas/posts.json +0 -173
  126. package/.appwrite/schemas/users.json +0 -125
  127. package/dist/adapters/AdapterFactory.d.ts +0 -94
  128. package/dist/adapters/AdapterFactory.js +0 -420
  129. package/dist/adapters/DatabaseAdapter.d.ts +0 -243
  130. package/dist/adapters/DatabaseAdapter.js +0 -50
  131. package/dist/adapters/LegacyAdapter.d.ts +0 -50
  132. package/dist/adapters/LegacyAdapter.js +0 -615
  133. package/dist/adapters/TablesDBAdapter.d.ts +0 -45
  134. package/dist/adapters/TablesDBAdapter.js +0 -611
  135. package/dist/adapters/index.d.ts +0 -11
  136. package/dist/adapters/index.js +0 -12
  137. package/dist/backups/operations/bucketBackup.d.ts +0 -19
  138. package/dist/backups/operations/bucketBackup.js +0 -197
  139. package/dist/backups/operations/collectionBackup.d.ts +0 -30
  140. package/dist/backups/operations/collectionBackup.js +0 -201
  141. package/dist/backups/operations/comprehensiveBackup.d.ts +0 -25
  142. package/dist/backups/operations/comprehensiveBackup.js +0 -238
  143. package/dist/backups/schemas/bucketManifest.d.ts +0 -93
  144. package/dist/backups/schemas/bucketManifest.js +0 -33
  145. package/dist/backups/schemas/comprehensiveManifest.d.ts +0 -108
  146. package/dist/backups/schemas/comprehensiveManifest.js +0 -32
  147. package/dist/backups/tracking/centralizedTracking.d.ts +0 -34
  148. package/dist/backups/tracking/centralizedTracking.js +0 -274
  149. package/dist/cli/commands/configCommands.d.ts +0 -8
  150. package/dist/cli/commands/configCommands.js +0 -166
  151. package/dist/cli/commands/databaseCommands.d.ts +0 -14
  152. package/dist/cli/commands/databaseCommands.js +0 -644
  153. package/dist/cli/commands/functionCommands.d.ts +0 -7
  154. package/dist/cli/commands/functionCommands.js +0 -330
  155. package/dist/cli/commands/schemaCommands.d.ts +0 -7
  156. package/dist/cli/commands/schemaCommands.js +0 -169
  157. package/dist/cli/commands/storageCommands.d.ts +0 -5
  158. package/dist/cli/commands/storageCommands.js +0 -143
  159. package/dist/cli/commands/transferCommands.d.ts +0 -5
  160. package/dist/cli/commands/transferCommands.js +0 -384
  161. package/dist/collections/attributes.d.ts +0 -13
  162. package/dist/collections/attributes.js +0 -1333
  163. package/dist/collections/indexes.d.ts +0 -12
  164. package/dist/collections/indexes.js +0 -217
  165. package/dist/collections/methods.d.ts +0 -19
  166. package/dist/collections/methods.js +0 -587
  167. package/dist/collections/tableOperations.d.ts +0 -86
  168. package/dist/collections/tableOperations.js +0 -447
  169. package/dist/collections/transferOperations.d.ts +0 -8
  170. package/dist/collections/transferOperations.js +0 -412
  171. package/dist/collections/wipeOperations.d.ts +0 -16
  172. package/dist/collections/wipeOperations.js +0 -233
  173. package/dist/config/ConfigManager.d.ts +0 -450
  174. package/dist/config/ConfigManager.js +0 -650
  175. package/dist/config/configMigration.d.ts +0 -87
  176. package/dist/config/configMigration.js +0 -390
  177. package/dist/config/configValidation.d.ts +0 -66
  178. package/dist/config/configValidation.js +0 -358
  179. package/dist/config/index.d.ts +0 -8
  180. package/dist/config/index.js +0 -7
  181. package/dist/config/services/ConfigDiscoveryService.d.ts +0 -122
  182. package/dist/config/services/ConfigDiscoveryService.js +0 -322
  183. package/dist/config/services/ConfigLoaderService.d.ts +0 -129
  184. package/dist/config/services/ConfigLoaderService.js +0 -535
  185. package/dist/config/services/ConfigMergeService.d.ts +0 -208
  186. package/dist/config/services/ConfigMergeService.js +0 -308
  187. package/dist/config/services/ConfigValidationService.d.ts +0 -214
  188. package/dist/config/services/ConfigValidationService.js +0 -310
  189. package/dist/config/services/SessionAuthService.d.ts +0 -225
  190. package/dist/config/services/SessionAuthService.js +0 -456
  191. package/dist/config/services/__tests__/ConfigMergeService.test.d.ts +0 -1
  192. package/dist/config/services/__tests__/ConfigMergeService.test.js +0 -271
  193. package/dist/config/services/index.d.ts +0 -13
  194. package/dist/config/services/index.js +0 -10
  195. package/dist/config/yamlConfig.d.ts +0 -722
  196. package/dist/config/yamlConfig.js +0 -702
  197. package/dist/databases/methods.d.ts +0 -6
  198. package/dist/databases/methods.js +0 -35
  199. package/dist/databases/setup.d.ts +0 -5
  200. package/dist/databases/setup.js +0 -45
  201. package/dist/examples/yamlTerminologyExample.d.ts +0 -42
  202. package/dist/examples/yamlTerminologyExample.js +0 -272
  203. package/dist/functions/deployments.d.ts +0 -4
  204. package/dist/functions/deployments.js +0 -146
  205. package/dist/functions/fnConfigDiscovery.d.ts +0 -3
  206. package/dist/functions/fnConfigDiscovery.js +0 -108
  207. package/dist/functions/methods.d.ts +0 -16
  208. package/dist/functions/methods.js +0 -174
  209. package/dist/functions/pathResolution.d.ts +0 -37
  210. package/dist/functions/pathResolution.js +0 -185
  211. package/dist/functions/templates/count-docs-in-collection/README.md +0 -54
  212. package/dist/functions/templates/count-docs-in-collection/package.json +0 -25
  213. package/dist/functions/templates/count-docs-in-collection/src/main.ts +0 -159
  214. package/dist/functions/templates/count-docs-in-collection/src/request.ts +0 -9
  215. package/dist/functions/templates/count-docs-in-collection/tsconfig.json +0 -28
  216. package/dist/functions/templates/hono-typescript/README.md +0 -286
  217. package/dist/functions/templates/hono-typescript/package.json +0 -26
  218. package/dist/functions/templates/hono-typescript/src/adapters/request.ts +0 -74
  219. package/dist/functions/templates/hono-typescript/src/adapters/response.ts +0 -106
  220. package/dist/functions/templates/hono-typescript/src/app.ts +0 -180
  221. package/dist/functions/templates/hono-typescript/src/context.ts +0 -103
  222. package/dist/functions/templates/hono-typescript/src/index.ts +0 -54
  223. package/dist/functions/templates/hono-typescript/src/middleware/appwrite.ts +0 -119
  224. package/dist/functions/templates/hono-typescript/tsconfig.json +0 -20
  225. package/dist/functions/templates/typescript-node/README.md +0 -32
  226. package/dist/functions/templates/typescript-node/package.json +0 -25
  227. package/dist/functions/templates/typescript-node/src/context.ts +0 -103
  228. package/dist/functions/templates/typescript-node/src/index.ts +0 -29
  229. package/dist/functions/templates/typescript-node/tsconfig.json +0 -28
  230. package/dist/functions/templates/uv/README.md +0 -31
  231. package/dist/functions/templates/uv/pyproject.toml +0 -30
  232. package/dist/functions/templates/uv/src/__init__.py +0 -0
  233. package/dist/functions/templates/uv/src/context.py +0 -125
  234. package/dist/functions/templates/uv/src/index.py +0 -46
  235. package/dist/init.d.ts +0 -2
  236. package/dist/init.js +0 -57
  237. package/dist/interactiveCLI.d.ts +0 -31
  238. package/dist/interactiveCLI.js +0 -898
  239. package/dist/main.d.ts +0 -2
  240. package/dist/main.js +0 -1180
  241. package/dist/migrations/afterImportActions.d.ts +0 -17
  242. package/dist/migrations/afterImportActions.js +0 -306
  243. package/dist/migrations/appwriteToX.d.ts +0 -211
  244. package/dist/migrations/appwriteToX.js +0 -491
  245. package/dist/migrations/comprehensiveTransfer.d.ts +0 -147
  246. package/dist/migrations/comprehensiveTransfer.js +0 -1317
  247. package/dist/migrations/dataLoader.d.ts +0 -753
  248. package/dist/migrations/dataLoader.js +0 -1250
  249. package/dist/migrations/importController.d.ts +0 -23
  250. package/dist/migrations/importController.js +0 -268
  251. package/dist/migrations/importDataActions.d.ts +0 -50
  252. package/dist/migrations/importDataActions.js +0 -230
  253. package/dist/migrations/relationships.d.ts +0 -29
  254. package/dist/migrations/relationships.js +0 -204
  255. package/dist/migrations/services/DataTransformationService.d.ts +0 -55
  256. package/dist/migrations/services/DataTransformationService.js +0 -158
  257. package/dist/migrations/services/FileHandlerService.d.ts +0 -75
  258. package/dist/migrations/services/FileHandlerService.js +0 -236
  259. package/dist/migrations/services/ImportOrchestrator.d.ts +0 -97
  260. package/dist/migrations/services/ImportOrchestrator.js +0 -485
  261. package/dist/migrations/services/RateLimitManager.d.ts +0 -138
  262. package/dist/migrations/services/RateLimitManager.js +0 -279
  263. package/dist/migrations/services/RelationshipResolver.d.ts +0 -120
  264. package/dist/migrations/services/RelationshipResolver.js +0 -332
  265. package/dist/migrations/services/UserMappingService.d.ts +0 -109
  266. package/dist/migrations/services/UserMappingService.js +0 -277
  267. package/dist/migrations/services/ValidationService.d.ts +0 -74
  268. package/dist/migrations/services/ValidationService.js +0 -260
  269. package/dist/migrations/transfer.d.ts +0 -26
  270. package/dist/migrations/transfer.js +0 -608
  271. package/dist/migrations/yaml/YamlImportConfigLoader.d.ts +0 -131
  272. package/dist/migrations/yaml/YamlImportConfigLoader.js +0 -383
  273. package/dist/migrations/yaml/YamlImportIntegration.d.ts +0 -93
  274. package/dist/migrations/yaml/YamlImportIntegration.js +0 -341
  275. package/dist/migrations/yaml/generateImportSchemas.d.ts +0 -30
  276. package/dist/migrations/yaml/generateImportSchemas.js +0 -1327
  277. package/dist/schemas/authUser.d.ts +0 -24
  278. package/dist/schemas/authUser.js +0 -17
  279. package/dist/setup.d.ts +0 -2
  280. package/dist/setup.js +0 -5
  281. package/dist/setupCommands.d.ts +0 -58
  282. package/dist/setupCommands.js +0 -490
  283. package/dist/setupController.d.ts +0 -9
  284. package/dist/setupController.js +0 -34
  285. package/dist/shared/attributeMapper.d.ts +0 -20
  286. package/dist/shared/attributeMapper.js +0 -203
  287. package/dist/shared/backupMetadataSchema.d.ts +0 -94
  288. package/dist/shared/backupMetadataSchema.js +0 -38
  289. package/dist/shared/backupTracking.d.ts +0 -18
  290. package/dist/shared/backupTracking.js +0 -176
  291. package/dist/shared/confirmationDialogs.d.ts +0 -75
  292. package/dist/shared/confirmationDialogs.js +0 -236
  293. package/dist/shared/errorUtils.d.ts +0 -54
  294. package/dist/shared/errorUtils.js +0 -95
  295. package/dist/shared/functionManager.d.ts +0 -48
  296. package/dist/shared/functionManager.js +0 -348
  297. package/dist/shared/jsonSchemaGenerator.d.ts +0 -50
  298. package/dist/shared/jsonSchemaGenerator.js +0 -290
  299. package/dist/shared/logging.d.ts +0 -61
  300. package/dist/shared/logging.js +0 -116
  301. package/dist/shared/messageFormatter.d.ts +0 -39
  302. package/dist/shared/messageFormatter.js +0 -162
  303. package/dist/shared/migrationHelpers.d.ts +0 -61
  304. package/dist/shared/migrationHelpers.js +0 -145
  305. package/dist/shared/operationLogger.d.ts +0 -10
  306. package/dist/shared/operationLogger.js +0 -12
  307. package/dist/shared/operationQueue.d.ts +0 -40
  308. package/dist/shared/operationQueue.js +0 -311
  309. package/dist/shared/operationsTable.d.ts +0 -26
  310. package/dist/shared/operationsTable.js +0 -286
  311. package/dist/shared/operationsTableSchema.d.ts +0 -48
  312. package/dist/shared/operationsTableSchema.js +0 -35
  313. package/dist/shared/progressManager.d.ts +0 -62
  314. package/dist/shared/progressManager.js +0 -215
  315. package/dist/shared/pydanticModelGenerator.d.ts +0 -17
  316. package/dist/shared/pydanticModelGenerator.js +0 -615
  317. package/dist/shared/relationshipExtractor.d.ts +0 -56
  318. package/dist/shared/relationshipExtractor.js +0 -138
  319. package/dist/shared/schemaGenerator.d.ts +0 -40
  320. package/dist/shared/schemaGenerator.js +0 -556
  321. package/dist/shared/selectionDialogs.d.ts +0 -214
  322. package/dist/shared/selectionDialogs.js +0 -544
  323. package/dist/storage/backupCompression.d.ts +0 -20
  324. package/dist/storage/backupCompression.js +0 -67
  325. package/dist/storage/methods.d.ts +0 -32
  326. package/dist/storage/methods.js +0 -472
  327. package/dist/storage/schemas.d.ts +0 -842
  328. package/dist/storage/schemas.js +0 -175
  329. package/dist/tables/indexManager.d.ts +0 -65
  330. package/dist/tables/indexManager.js +0 -294
  331. package/dist/types.d.ts +0 -4
  332. package/dist/types.js +0 -3
  333. package/dist/users/methods.d.ts +0 -16
  334. package/dist/users/methods.js +0 -277
  335. package/dist/utils/ClientFactory.d.ts +0 -87
  336. package/dist/utils/ClientFactory.js +0 -212
  337. package/dist/utils/configDiscovery.d.ts +0 -78
  338. package/dist/utils/configDiscovery.js +0 -472
  339. package/dist/utils/configMigration.d.ts +0 -1
  340. package/dist/utils/configMigration.js +0 -261
  341. package/dist/utils/constantsGenerator.d.ts +0 -31
  342. package/dist/utils/constantsGenerator.js +0 -321
  343. package/dist/utils/dataConverters.d.ts +0 -46
  344. package/dist/utils/dataConverters.js +0 -139
  345. package/dist/utils/directoryUtils.d.ts +0 -22
  346. package/dist/utils/directoryUtils.js +0 -59
  347. package/dist/utils/getClientFromConfig.d.ts +0 -39
  348. package/dist/utils/getClientFromConfig.js +0 -199
  349. package/dist/utils/helperFunctions.d.ts +0 -63
  350. package/dist/utils/helperFunctions.js +0 -156
  351. package/dist/utils/index.d.ts +0 -2
  352. package/dist/utils/index.js +0 -2
  353. package/dist/utils/loadConfigs.d.ts +0 -50
  354. package/dist/utils/loadConfigs.js +0 -358
  355. package/dist/utils/pathResolvers.d.ts +0 -53
  356. package/dist/utils/pathResolvers.js +0 -72
  357. package/dist/utils/projectConfig.d.ts +0 -122
  358. package/dist/utils/projectConfig.js +0 -206
  359. package/dist/utils/retryFailedPromises.d.ts +0 -2
  360. package/dist/utils/retryFailedPromises.js +0 -23
  361. package/dist/utils/sessionAuth.d.ts +0 -48
  362. package/dist/utils/sessionAuth.js +0 -164
  363. package/dist/utils/setupFiles.d.ts +0 -4
  364. package/dist/utils/setupFiles.js +0 -1192
  365. package/dist/utils/typeGuards.d.ts +0 -35
  366. package/dist/utils/typeGuards.js +0 -57
  367. package/dist/utils/validationRules.d.ts +0 -43
  368. package/dist/utils/validationRules.js +0 -42
  369. package/dist/utils/versionDetection.d.ts +0 -58
  370. package/dist/utils/versionDetection.js +0 -251
  371. package/dist/utils/yamlConverter.d.ts +0 -100
  372. package/dist/utils/yamlConverter.js +0 -428
  373. package/dist/utils/yamlLoader.d.ts +0 -70
  374. package/dist/utils/yamlLoader.js +0 -267
  375. package/dist/utilsController.d.ts +0 -107
  376. package/dist/utilsController.js +0 -873
  377. package/src/adapters/AdapterFactory.ts +0 -529
  378. package/src/adapters/DatabaseAdapter.ts +0 -319
  379. package/src/adapters/LegacyAdapter.ts +0 -844
  380. package/src/adapters/TablesDBAdapter.ts +0 -823
  381. package/src/config/ConfigManager.ts +0 -849
  382. package/src/config/README.md +0 -274
  383. package/src/config/configMigration.ts +0 -575
  384. package/src/config/configValidation.ts +0 -445
  385. package/src/config/index.ts +0 -10
  386. package/src/config/services/ConfigDiscoveryService.ts +0 -410
  387. package/src/config/services/ConfigLoaderService.ts +0 -732
  388. package/src/config/services/ConfigMergeService.ts +0 -388
  389. package/src/config/services/ConfigValidationService.ts +0 -394
  390. package/src/config/services/SessionAuthService.ts +0 -565
  391. package/src/config/services/__tests__/ConfigMergeService.test.ts +0 -351
  392. package/src/config/services/index.ts +0 -29
  393. package/src/config/yamlConfig.ts +0 -761
  394. package/src/functions/pathResolution.ts +0 -227
  395. package/src/functions/templates/count-docs-in-collection/package.json +0 -25
  396. package/src/functions/templates/count-docs-in-collection/tsconfig.json +0 -28
  397. package/src/functions/templates/hono-typescript/package.json +0 -26
  398. package/src/functions/templates/hono-typescript/tsconfig.json +0 -20
  399. package/src/functions/templates/typescript-node/package.json +0 -25
  400. package/src/functions/templates/typescript-node/tsconfig.json +0 -28
  401. package/src/shared/attributeMapper.ts +0 -229
  402. package/src/shared/errorUtils.ts +0 -110
  403. package/src/shared/functionManager.ts +0 -537
  404. package/src/shared/jsonSchemaGenerator.ts +0 -383
  405. package/src/shared/logging.ts +0 -149
  406. package/src/shared/messageFormatter.ts +0 -208
  407. package/src/shared/pydanticModelGenerator.ts +0 -618
  408. package/src/shared/schemaGenerator.ts +0 -644
  409. package/src/utils/ClientFactory.ts +0 -240
  410. package/src/utils/configDiscovery.ts +0 -557
  411. package/src/utils/constantsGenerator.ts +0 -369
  412. package/src/utils/dataConverters.ts +0 -159
  413. package/src/utils/directoryUtils.ts +0 -61
  414. package/src/utils/getClientFromConfig.ts +0 -257
  415. package/src/utils/helperFunctions.ts +0 -228
  416. package/src/utils/pathResolvers.ts +0 -81
  417. package/src/utils/projectConfig.ts +0 -340
  418. package/src/utils/retryFailedPromises.ts +0 -29
  419. package/src/utils/sessionAuth.ts +0 -230
  420. package/src/utils/typeGuards.ts +0 -65
  421. package/src/utils/validationRules.ts +0 -88
  422. package/src/utils/versionDetection.ts +0 -292
  423. package/src/utils/yamlConverter.ts +0 -542
  424. package/src/utils/yamlLoader.ts +0 -371
  425. package/tmp-sync-test/.appwrite/collections/TestCollection.yaml +0 -7
package/dist/main.js DELETED
@@ -1,1180 +0,0 @@
1
- #!/usr/bin/env node
2
- import yargs from "yargs";
3
- import {} from "yargs";
4
- import { hideBin } from "yargs/helpers";
5
- import { InteractiveCLI } from "./interactiveCLI.js";
6
- import { UtilsController } from "./utilsController.js";
7
- import { Databases, Storage } from "node-appwrite";
8
- import { getClient } from "./utils/getClientFromConfig.js";
9
- import { fetchAllDatabases } from "./databases/methods.js";
10
- import { setupDirsFiles } from "./utils/setupFiles.js";
11
- import { fetchAllCollections } from "./collections/methods.js";
12
- import chalk from "chalk";
13
- import { listSpecifications } from "./functions/methods.js";
14
- import { MessageFormatter } from "./shared/messageFormatter.js";
15
- import { ConfirmationDialogs } from "./shared/confirmationDialogs.js";
16
- import { SelectionDialogs } from "./shared/selectionDialogs.js";
17
- import { logger } from "./shared/logging.js";
18
- import path from "path";
19
- import fs from "fs";
20
- import { createRequire } from "node:module";
21
- import { loadAppwriteProjectConfig, findAppwriteProjectConfig, projectConfigToAppwriteConfig, } from "./utils/projectConfig.js";
22
- import { hasSessionAuth, getAvailableSessions, getAuthenticationStatus, } from "./utils/sessionAuth.js";
23
- import { findYamlConfig, loadYamlConfigWithSession, } from "./config/yamlConfig.js";
24
- const require = createRequire(import.meta.url);
25
- if (!globalThis.require) {
26
- globalThis.require = require;
27
- }
28
- /**
29
- * Enhanced sync function with intelligent configuration detection and selection dialogs
30
- */
31
- async function performEnhancedSync(controller, parsedArgv) {
32
- try {
33
- MessageFormatter.banner("Enhanced Sync", "Intelligent configuration detection and selection");
34
- if (!controller.config) {
35
- MessageFormatter.error("No Appwrite configuration found", undefined, { prefix: "Sync" });
36
- return null;
37
- }
38
- // Get all available databases from remote
39
- const availableDatabases = await fetchAllDatabases(controller.database);
40
- if (availableDatabases.length === 0) {
41
- MessageFormatter.warning("No databases found in remote project", { prefix: "Sync" });
42
- return null;
43
- }
44
- // Get existing configuration
45
- const configuredDatabases = controller.config.databases || [];
46
- const configuredBuckets = controller.config.buckets || [];
47
- // Check if we have existing configuration
48
- const hasExistingConfig = configuredDatabases.length > 0 || configuredBuckets.length > 0;
49
- let syncExisting = false;
50
- let modifyConfiguration = true;
51
- if (hasExistingConfig) {
52
- // Prompt about existing configuration
53
- const response = await SelectionDialogs.promptForExistingConfig([
54
- ...configuredDatabases,
55
- ...configuredBuckets
56
- ]);
57
- syncExisting = response.syncExisting;
58
- modifyConfiguration = response.modifyConfiguration;
59
- if (syncExisting && !modifyConfiguration) {
60
- // Just sync existing configuration without changes
61
- MessageFormatter.info("Syncing existing configuration without modifications", { prefix: "Sync" });
62
- // Convert configured databases to DatabaseSelection format
63
- const databaseSelections = configuredDatabases.map(db => ({
64
- databaseId: db.$id,
65
- databaseName: db.name,
66
- tableIds: [], // Tables will be populated from collections config
67
- tableNames: [],
68
- isNew: false
69
- }));
70
- // Convert configured buckets to BucketSelection format
71
- const bucketSelections = configuredBuckets.map(bucket => ({
72
- bucketId: bucket.$id,
73
- bucketName: bucket.name,
74
- databaseId: undefined,
75
- databaseName: undefined,
76
- isNew: false
77
- }));
78
- const selectionSummary = SelectionDialogs.createSyncSelectionSummary(databaseSelections, bucketSelections);
79
- const confirmed = await SelectionDialogs.confirmSyncSelection(selectionSummary, 'pull');
80
- if (!confirmed) {
81
- MessageFormatter.info("Pull operation cancelled by user", { prefix: "Sync" });
82
- return null;
83
- }
84
- // Perform sync with existing configuration (pull from remote)
85
- await controller.selectivePull(databaseSelections, bucketSelections);
86
- return selectionSummary;
87
- }
88
- }
89
- if (!modifyConfiguration) {
90
- MessageFormatter.info("No configuration changes requested", { prefix: "Sync" });
91
- return null;
92
- }
93
- // Allow new items selection based on user choice
94
- const allowNewOnly = !syncExisting;
95
- // Select databases
96
- const selectedDatabaseIds = await SelectionDialogs.selectDatabases(availableDatabases, configuredDatabases, {
97
- showSelectAll: false,
98
- allowNewOnly,
99
- defaultSelected: []
100
- });
101
- if (selectedDatabaseIds.length === 0) {
102
- MessageFormatter.warning("No databases selected for sync", { prefix: "Sync" });
103
- return null;
104
- }
105
- // For each selected database, get available tables and select them
106
- const tableSelectionsMap = new Map();
107
- const availableTablesMap = new Map();
108
- for (const databaseId of selectedDatabaseIds) {
109
- const database = availableDatabases.find(db => db.$id === databaseId);
110
- SelectionDialogs.showProgress(`Fetching tables for database: ${database.name}`);
111
- // Get available tables from remote
112
- const availableTables = await fetchAllCollections(databaseId, controller.database);
113
- availableTablesMap.set(databaseId, availableTables);
114
- // Get configured tables for this database
115
- // Note: Collections are stored globally in the config, not per database
116
- const configuredTables = controller.config.collections || [];
117
- // Select tables for this database
118
- const selectedTableIds = await SelectionDialogs.selectTablesForDatabase(databaseId, database.name, availableTables, configuredTables, {
119
- showSelectAll: false,
120
- allowNewOnly,
121
- defaultSelected: []
122
- });
123
- tableSelectionsMap.set(databaseId, selectedTableIds);
124
- if (selectedTableIds.length === 0) {
125
- MessageFormatter.warning(`No tables selected for database: ${database.name}`, { prefix: "Sync" });
126
- }
127
- }
128
- // Select buckets
129
- let selectedBucketIds = [];
130
- // Get available buckets from remote
131
- if (controller.storage) {
132
- try {
133
- // Note: We need to implement fetchAllBuckets or use storage.listBuckets
134
- // For now, we'll use configured buckets as available
135
- SelectionDialogs.showProgress("Fetching storage buckets...");
136
- // Create a mock availableBuckets array - in real implementation,
137
- // you'd fetch this from the Appwrite API
138
- const availableBuckets = configuredBuckets; // Placeholder
139
- selectedBucketIds = await SelectionDialogs.selectBucketsForDatabases(selectedDatabaseIds, availableBuckets, configuredBuckets, {
140
- showSelectAll: false,
141
- allowNewOnly: parsedArgv.selectBuckets ? false : allowNewOnly,
142
- groupByDatabase: true,
143
- defaultSelected: []
144
- });
145
- }
146
- catch (error) {
147
- MessageFormatter.warning("Could not fetch storage buckets", { prefix: "Sync" });
148
- logger.warn("Failed to fetch buckets during sync", { error });
149
- }
150
- }
151
- // Create selection objects
152
- const databaseSelections = SelectionDialogs.createDatabaseSelection(selectedDatabaseIds, availableDatabases, tableSelectionsMap, configuredDatabases, availableTablesMap);
153
- const bucketSelections = SelectionDialogs.createBucketSelection(selectedBucketIds, [], // availableBuckets - would be populated from API
154
- configuredBuckets, availableDatabases);
155
- // Show final confirmation
156
- const selectionSummary = SelectionDialogs.createSyncSelectionSummary(databaseSelections, bucketSelections);
157
- const confirmed = await SelectionDialogs.confirmSyncSelection(selectionSummary, 'pull');
158
- if (!confirmed) {
159
- MessageFormatter.info("Pull operation cancelled by user", { prefix: "Sync" });
160
- return null;
161
- }
162
- // Perform the selective sync (pull from remote)
163
- await controller.selectivePull(databaseSelections, bucketSelections);
164
- MessageFormatter.success("Enhanced sync completed successfully", { prefix: "Sync" });
165
- return selectionSummary;
166
- }
167
- catch (error) {
168
- SelectionDialogs.showError("Enhanced sync failed", error instanceof Error ? error : new Error(String(error)));
169
- return null;
170
- }
171
- }
172
- /**
173
- * Performs selective sync with the given database and bucket selections
174
- */
175
- /**
176
- * Checks if the migration from collections to tables should be allowed
177
- * Returns an object with:
178
- * - allowed: boolean indicating if migration should proceed
179
- * - reason: string explaining why migration was blocked (if not allowed)
180
- */
181
- function checkMigrationConditions(configPath) {
182
- const collectionsPath = path.join(configPath, "collections");
183
- const tablesPath = path.join(configPath, "tables");
184
- // Check if collections/ folder exists
185
- if (!fs.existsSync(collectionsPath)) {
186
- return {
187
- allowed: false,
188
- reason: "No collections/ folder found. Migration requires existing collections to migrate.",
189
- };
190
- }
191
- // Check if collections/ folder has YAML files
192
- const collectionFiles = fs
193
- .readdirSync(collectionsPath)
194
- .filter((file) => file.endsWith(".yaml") || file.endsWith(".yml"));
195
- if (collectionFiles.length === 0) {
196
- return {
197
- allowed: false,
198
- reason: "No YAML files found in collections/ folder. Migration requires existing collection YAML files.",
199
- };
200
- }
201
- // Check if tables/ folder exists and has YAML files
202
- if (fs.existsSync(tablesPath)) {
203
- const tableFiles = fs
204
- .readdirSync(tablesPath)
205
- .filter((file) => file.endsWith(".yaml") || file.endsWith(".yml"));
206
- if (tableFiles.length > 0) {
207
- return {
208
- allowed: false,
209
- reason: `Tables folder already exists with ${tableFiles.length} YAML file(s). Migration appears to have already been completed.`,
210
- };
211
- }
212
- }
213
- // All conditions met
214
- return { allowed: true };
215
- }
216
- const argv = yargs(hideBin(process.argv))
217
- .option("config", {
218
- type: "string",
219
- description: "Path to Appwrite configuration file (appwriteConfig.ts)",
220
- })
221
- .option("appwriteConfig", {
222
- alias: ["appwrite-config", "use-appwrite-config"],
223
- type: "boolean",
224
- description: "Prefer loading from appwrite.config.json instead of config.yaml",
225
- })
226
- .option("it", {
227
- alias: ["interactive", "i"],
228
- type: "boolean",
229
- description: "Launch interactive CLI mode with guided prompts",
230
- })
231
- .option("dbIds", {
232
- type: "string",
233
- description: "Comma-separated list of database IDs to target (e.g., 'db1,db2,db3')",
234
- })
235
- .option("collectionIds", {
236
- alias: ["collIds", "tableIds", "tables"],
237
- type: "string",
238
- description: "Comma-separated list of collection/table IDs to target (e.g., 'users,posts')",
239
- })
240
- .option("bucketIds", {
241
- type: "string",
242
- description: "Comma-separated list of bucket IDs to operate on",
243
- })
244
- .option("wipe", {
245
- choices: ["all", "docs", "users"],
246
- description: "⚠️ DESTRUCTIVE: Wipe data (all: databases+storage+users, docs: documents only, users: user accounts only)",
247
- })
248
- .option("wipeCollections", {
249
- type: "boolean",
250
- description: "⚠️ DESTRUCTIVE: Wipe specific collections/tables (requires --collectionIds or --tableIds)",
251
- })
252
- .option("transferUsers", {
253
- type: "boolean",
254
- description: "Transfer users between projects",
255
- })
256
- .option("generate", {
257
- type: "boolean",
258
- description: "Generate TypeScript schemas and types from your Appwrite database schemas",
259
- })
260
- .option("import", {
261
- type: "boolean",
262
- description: "Import data from importData/ directory into your Appwrite databases",
263
- })
264
- .option("backup", {
265
- type: "boolean",
266
- description: "Create a complete backup of your databases and collections",
267
- })
268
- .option("backupFormat", {
269
- type: "string",
270
- choices: ["json", "zip"],
271
- default: "json",
272
- description: "Backup file format (json or zip)",
273
- })
274
- .option("listBackups", {
275
- type: "boolean",
276
- description: "List all backups for databases",
277
- })
278
- .option("comprehensiveBackup", {
279
- alias: ["comprehensive", "backup-all"],
280
- type: "boolean",
281
- description: "🚀 Create comprehensive backup of ALL databases and ALL storage buckets",
282
- })
283
- .option("trackingDatabaseId", {
284
- alias: ["tracking-db"],
285
- type: "string",
286
- description: "Database ID to use for centralized backup tracking (interactive prompt if not specified)",
287
- })
288
- .option("parallelDownloads", {
289
- type: "number",
290
- default: 10,
291
- description: "Number of parallel file downloads for bucket backups (default: 10)",
292
- })
293
- .option("writeData", {
294
- type: "boolean",
295
- description: "Output converted import data to files for validation before importing",
296
- })
297
- .option("push", {
298
- type: "boolean",
299
- description: "Deploy your local configuration (collections, attributes, indexes) to Appwrite",
300
- })
301
- .option("sync", {
302
- type: "boolean",
303
- description: "Pull and synchronize your local config with the remote Appwrite project schema",
304
- })
305
- .option("autoSync", {
306
- alias: ["auto"],
307
- type: "boolean",
308
- description: "Skip prompts and sync all databases, tables, and buckets (current behavior)"
309
- })
310
- .option("selectBuckets", {
311
- type: "boolean",
312
- description: "Force bucket selection dialog even if buckets are already configured"
313
- })
314
- .option("endpoint", {
315
- type: "string",
316
- description: "Set the Appwrite endpoint",
317
- })
318
- .option("projectId", {
319
- type: "string",
320
- description: "Set the Appwrite project ID",
321
- })
322
- .option("apiKey", {
323
- type: "string",
324
- description: "Set the Appwrite API key",
325
- })
326
- .option("transfer", {
327
- type: "boolean",
328
- description: "Transfer documents and files between databases, collections, or projects",
329
- })
330
- .option("fromDbId", {
331
- alias: ["fromDb", "sourceDbId", "sourceDb"],
332
- type: "string",
333
- description: "Source database ID for transfer operations",
334
- })
335
- .option("toDbId", {
336
- alias: ["toDb", "targetDbId", "targetDb"],
337
- type: "string",
338
- description: "Target database ID for transfer operations",
339
- })
340
- .option("fromCollectionId", {
341
- alias: ["fromCollId", "fromColl"],
342
- type: "string",
343
- description: "Set the source collection ID for transfer",
344
- })
345
- .option("toCollectionId", {
346
- alias: ["toCollId", "toColl"],
347
- type: "string",
348
- description: "Set the destination collection ID for transfer",
349
- })
350
- .option("fromBucketId", {
351
- type: "string",
352
- description: "Set the source bucket ID for transfer",
353
- })
354
- .option("toBucketId", {
355
- type: "string",
356
- description: "Set the destination bucket ID for transfer",
357
- })
358
- .option("remoteEndpoint", {
359
- type: "string",
360
- description: "Set the remote Appwrite endpoint for transfer",
361
- })
362
- .option("remoteProjectId", {
363
- type: "string",
364
- description: "Set the remote Appwrite project ID for transfer",
365
- })
366
- .option("remoteApiKey", {
367
- type: "string",
368
- description: "Set the remote Appwrite API key for transfer",
369
- })
370
- .option("setup", {
371
- type: "boolean",
372
- description: "Initialize project with configuration files and directory structure",
373
- })
374
- .option("updateFunctionSpec", {
375
- type: "boolean",
376
- description: "Update function specifications",
377
- })
378
- .option("functionId", {
379
- type: "string",
380
- description: "Function ID to update",
381
- })
382
- .option("specification", {
383
- type: "string",
384
- description: "New function specification (e.g., 's-1vcpu-1gb')",
385
- choices: [
386
- "s-0.5vcpu-512mb",
387
- "s-1vcpu-1gb",
388
- "s-2vcpu-2gb",
389
- "s-2vcpu-4gb",
390
- "s-4vcpu-4gb",
391
- "s-4vcpu-8gb",
392
- "s-8vcpu-4gb",
393
- "s-8vcpu-8gb",
394
- ],
395
- })
396
- .option("migrateConfig", {
397
- alias: ["migrate"],
398
- type: "boolean",
399
- description: "Migrate appwriteConfig.ts to .appwrite structure with YAML configuration",
400
- })
401
- .option("generateConstants", {
402
- alias: ["constants"],
403
- type: "boolean",
404
- description: "Generate cross-language constants file with database, collection, bucket, and function IDs",
405
- })
406
- .option("constantsLanguages", {
407
- type: "string",
408
- description: "Comma-separated list of languages for constants (typescript,javascript,python,php,dart,json,env)",
409
- default: "typescript",
410
- })
411
- .option("constantsOutput", {
412
- type: "string",
413
- description: "Output directory for generated constants files (default: config-folder/constants)",
414
- default: "auto",
415
- })
416
- .option("constantsInclude", {
417
- type: "string",
418
- description: "Comma-separated categories to include: databases,collections,buckets,functions",
419
- })
420
- .option("generateSchemas", {
421
- type: "boolean",
422
- description: "Generate schemas/models without interactive prompts",
423
- })
424
- .option("schemaFormat", {
425
- type: "string",
426
- choices: ["zod", "json", "pydantic", "both", "all"],
427
- description: "Schema format: zod, json, pydantic, both (zod+json), or all",
428
- })
429
- .option("schemaOutDir", {
430
- type: "string",
431
- description: "Output directory for generated schemas (absolute path respected)",
432
- })
433
- .option("migrateCollectionsToTables", {
434
- alias: ["migrate-collections"],
435
- type: "boolean",
436
- description: "Migrate collections to tables format for TablesDB API compatibility",
437
- })
438
- .option("useSession", {
439
- alias: ["session"],
440
- type: "boolean",
441
- description: "Use Appwrite CLI session authentication instead of API key",
442
- })
443
- .option("sessionCookie", {
444
- type: "string",
445
- description: "Explicit session cookie to use for authentication",
446
- })
447
- .parse();
448
- async function main() {
449
- const startTime = Date.now();
450
- const operationStats = {};
451
- // Early session detection for better user guidance
452
- const availableSessions = getAvailableSessions();
453
- let hasAnyValidSessions = availableSessions.length > 0;
454
- if (argv.it) {
455
- const cli = new InteractiveCLI(process.cwd());
456
- await cli.run();
457
- }
458
- else {
459
- // Enhanced config creation with session and project file support
460
- let directConfig = undefined;
461
- // Show authentication status on startup if no config provided
462
- if (!argv.config &&
463
- !argv.endpoint &&
464
- !argv.projectId &&
465
- !argv.apiKey &&
466
- !argv.useSession &&
467
- !argv.sessionCookie) {
468
- if (hasAnyValidSessions) {
469
- MessageFormatter.info(`Found ${availableSessions.length} available session(s)`, { prefix: "Auth" });
470
- availableSessions.forEach((session) => {
471
- MessageFormatter.info(` \u2022 ${session.projectId} (${session.email || "unknown"}) at ${session.endpoint}`, { prefix: "Auth" });
472
- });
473
- MessageFormatter.info("Use --session to enable session authentication", { prefix: "Auth" });
474
- }
475
- else {
476
- MessageFormatter.info("No active Appwrite sessions found", {
477
- prefix: "Auth",
478
- });
479
- MessageFormatter.info("\u2022 Run 'appwrite login' to authenticate with session", { prefix: "Auth" });
480
- MessageFormatter.info("\u2022 Or provide --apiKey for API key authentication", { prefix: "Auth" });
481
- }
482
- }
483
- // Priority 1: Check for appwrite.json project configuration
484
- const projectConfigPath = findAppwriteProjectConfig(process.cwd());
485
- if (projectConfigPath) {
486
- const projectConfig = loadAppwriteProjectConfig(projectConfigPath);
487
- if (projectConfig) {
488
- directConfig = projectConfigToAppwriteConfig(projectConfig);
489
- MessageFormatter.info(`Loaded project configuration from ${projectConfigPath}`, { prefix: "CLI" });
490
- }
491
- }
492
- // Priority 2: CLI arguments override project config
493
- if (argv.endpoint ||
494
- argv.projectId ||
495
- argv.apiKey ||
496
- argv.useSession ||
497
- argv.sessionCookie) {
498
- directConfig = {
499
- ...directConfig,
500
- appwriteEndpoint: argv.endpoint || directConfig?.appwriteEndpoint,
501
- appwriteProject: argv.projectId || directConfig?.appwriteProject,
502
- appwriteKey: argv.apiKey || directConfig?.appwriteKey,
503
- };
504
- }
505
- // Priority 3: Session authentication support with improved detection
506
- let sessionAuthAvailable = false;
507
- if (directConfig?.appwriteEndpoint && directConfig?.appwriteProject) {
508
- sessionAuthAvailable = hasSessionAuth(directConfig.appwriteEndpoint, directConfig.appwriteProject);
509
- }
510
- if (argv.useSession || argv.sessionCookie) {
511
- if (argv.sessionCookie) {
512
- // Explicit session cookie provided
513
- MessageFormatter.info("Using explicit session cookie for authentication", { prefix: "Auth" });
514
- }
515
- else if (sessionAuthAvailable) {
516
- MessageFormatter.info("Session authentication detected and will be used", { prefix: "Auth" });
517
- }
518
- else {
519
- MessageFormatter.warning("Session authentication requested but no valid session found", { prefix: "Auth" });
520
- const availableSessions = getAvailableSessions();
521
- if (availableSessions.length > 0) {
522
- MessageFormatter.info(`Available sessions: ${availableSessions
523
- .map((s) => `${s.projectId} (${s.email || "unknown"})`)
524
- .join(", ")}`, { prefix: "Auth" });
525
- MessageFormatter.info("Use --session flag to enable session authentication", { prefix: "Auth" });
526
- }
527
- else {
528
- MessageFormatter.warning("No Appwrite CLI sessions found. Please run 'appwrite login' first.", { prefix: "Auth" });
529
- }
530
- MessageFormatter.error("Session authentication requested but not available", undefined, { prefix: "Auth" });
531
- return; // Exit early if session auth was requested but not available
532
- }
533
- }
534
- else if (sessionAuthAvailable && !argv.apiKey) {
535
- // Auto-detect session authentication when no API key is provided
536
- MessageFormatter.info("Session authentication detected - no API key required", { prefix: "Auth" });
537
- MessageFormatter.info("Use --session flag to explicitly enable session authentication", { prefix: "Auth" });
538
- }
539
- // Enhanced session authentication support:
540
- // 1. If session auth is explicitly requested via flags, use it
541
- // 2. If no API key is provided but sessions are available, offer to use session auth
542
- // 3. Auto-detect session authentication when possible
543
- let finalDirectConfig = directConfig;
544
- if ((argv.useSession || argv.sessionCookie) &&
545
- (!directConfig ||
546
- !directConfig.appwriteEndpoint ||
547
- !directConfig.appwriteProject)) {
548
- // Don't pass incomplete directConfig - let UtilsController load YAML config normally
549
- finalDirectConfig = null;
550
- }
551
- else if (finalDirectConfig &&
552
- !finalDirectConfig.appwriteKey &&
553
- !argv.useSession &&
554
- !argv.sessionCookie) {
555
- // Auto-detect session authentication when no API key provided
556
- if (sessionAuthAvailable) {
557
- MessageFormatter.info("No API key provided, but session authentication is available", { prefix: "Auth" });
558
- MessageFormatter.info("Automatically using session authentication (add --session to suppress this message)", { prefix: "Auth" });
559
- // Implicitly enable session authentication
560
- argv.useSession = true;
561
- }
562
- }
563
- // Create controller with session authentication support using singleton
564
- const controller = UtilsController.getInstance(process.cwd(), finalDirectConfig);
565
- // Pass session authentication and config options to the controller
566
- const initOptions = {};
567
- if (argv.useSession || argv.sessionCookie) {
568
- initOptions.useSession = true;
569
- if (argv.sessionCookie) {
570
- initOptions.sessionCookie = argv.sessionCookie;
571
- }
572
- }
573
- if (argv.appwriteConfig) {
574
- initOptions.preferJson = true;
575
- }
576
- await controller.init(initOptions);
577
- if (argv.setup) {
578
- await setupDirsFiles(false, process.cwd());
579
- return;
580
- }
581
- if (argv.migrateConfig) {
582
- const { migrateConfig } = await import("./utils/configMigration.js");
583
- await migrateConfig(process.cwd());
584
- return;
585
- }
586
- if (argv.generateConstants) {
587
- const { ConstantsGenerator } = await import("./utils/constantsGenerator.js");
588
- if (!controller.config) {
589
- MessageFormatter.error("No Appwrite configuration found", undefined, {
590
- prefix: "Constants",
591
- });
592
- return;
593
- }
594
- const languages = argv
595
- .constantsLanguages.split(",")
596
- .map((l) => l.trim());
597
- // Determine output directory - use config folder/constants by default, or custom path if specified
598
- let outputDir;
599
- if (argv.constantsOutput === "auto") {
600
- // Default case: use config directory + constants, fallback to current directory
601
- const configPath = controller.getAppwriteFolderPath();
602
- outputDir = configPath
603
- ? path.join(configPath, "constants")
604
- : path.join(process.cwd(), "constants");
605
- }
606
- else {
607
- // Custom output directory specified
608
- outputDir = argv.constantsOutput;
609
- }
610
- MessageFormatter.info(`Generating constants for languages: ${languages.join(", ")}`, { prefix: "Constants" });
611
- const generator = new ConstantsGenerator(controller.config);
612
- await generator.generateFiles(languages, outputDir);
613
- operationStats.generatedConstants = languages.length;
614
- MessageFormatter.success(`Constants generated in ${outputDir}`, {
615
- prefix: "Constants",
616
- });
617
- return;
618
- }
619
- if (argv.migrateCollectionsToTables) {
620
- try {
621
- if (!controller.config) {
622
- MessageFormatter.error("No Appwrite configuration found", undefined, {
623
- prefix: "Migration",
624
- });
625
- return;
626
- }
627
- // Get the config path from the controller or use .appwrite in current directory
628
- let configPath = controller.getAppwriteFolderPath();
629
- if (!configPath) {
630
- // Try .appwrite in current directory
631
- const defaultPath = path.join(process.cwd(), ".appwrite");
632
- if (fs.existsSync(defaultPath)) {
633
- configPath = defaultPath;
634
- }
635
- else {
636
- MessageFormatter.error("Could not determine configuration folder path", undefined, { prefix: "Migration" });
637
- MessageFormatter.info("Make sure you have a .appwrite/ folder in your current directory", { prefix: "Migration" });
638
- return;
639
- }
640
- }
641
- // Check if migration conditions are met
642
- const migrationCheck = checkMigrationConditions(configPath);
643
- if (!migrationCheck.allowed) {
644
- MessageFormatter.error(`Migration not allowed: ${migrationCheck.reason}`, undefined, { prefix: "Migration" });
645
- MessageFormatter.info("Migration requirements:", {
646
- prefix: "Migration",
647
- });
648
- MessageFormatter.info(" • Configuration must be loaded (use --config or have .appwrite/ folder)", { prefix: "Migration" });
649
- MessageFormatter.info(" • collections/ folder must exist with YAML files", { prefix: "Migration" });
650
- MessageFormatter.info(" • tables/ folder must not exist or be empty", { prefix: "Migration" });
651
- return;
652
- }
653
- const { migrateCollectionsToTables } = await import("./config/configMigration.js");
654
- MessageFormatter.info("Starting collections to tables migration...", {
655
- prefix: "Migration",
656
- });
657
- const result = migrateCollectionsToTables(controller.config, {
658
- strategy: "full_migration",
659
- validateResult: true,
660
- dryRun: false,
661
- });
662
- if (result.success) {
663
- operationStats.migratedCollections = result.changes.length;
664
- MessageFormatter.success("Collections migration completed successfully", { prefix: "Migration" });
665
- }
666
- else {
667
- MessageFormatter.error(`Migration failed: ${result.errors.join(", ")}`, undefined, { prefix: "Migration" });
668
- process.exit(1);
669
- }
670
- }
671
- catch (error) {
672
- MessageFormatter.error("Migration failed", error instanceof Error ? error : new Error(String(error)), { prefix: "Migration" });
673
- process.exit(1);
674
- }
675
- return;
676
- }
677
- if (!controller.config) {
678
- // Provide better guidance based on available authentication methods
679
- const availableSessions = getAvailableSessions();
680
- if (availableSessions.length > 0) {
681
- MessageFormatter.error("No Appwrite configuration found", undefined, {
682
- prefix: "CLI",
683
- });
684
- MessageFormatter.info("Available authentication options:", {
685
- prefix: "Auth",
686
- });
687
- MessageFormatter.info("• Session authentication: Add --session flag", {
688
- prefix: "Auth",
689
- });
690
- MessageFormatter.info("• API key authentication: Add --apiKey YOUR_API_KEY", { prefix: "Auth" });
691
- MessageFormatter.info(`• Available sessions: ${availableSessions
692
- .map((s) => `${s.projectId} (${s.email || "unknown"})`)
693
- .join(", ")}`, { prefix: "Auth" });
694
- }
695
- else {
696
- MessageFormatter.error("No Appwrite configuration found", undefined, {
697
- prefix: "CLI",
698
- });
699
- MessageFormatter.info("Authentication options:", { prefix: "Auth" });
700
- MessageFormatter.info("• Login with Appwrite CLI: Run 'appwrite login' then use --session flag", { prefix: "Auth" });
701
- MessageFormatter.info("• Use API key: Add --apiKey YOUR_API_KEY", {
702
- prefix: "Auth",
703
- });
704
- MessageFormatter.info("• Create config file: Run with --setup to initialize project configuration", { prefix: "Auth" });
705
- }
706
- return;
707
- }
708
- const parsedArgv = argv;
709
- // List backups if requested
710
- if (parsedArgv.listBackups) {
711
- const { AdapterFactory } = await import("./adapters/AdapterFactory.js");
712
- const { listBackups } = await import("./shared/backupTracking.js");
713
- if (!controller.config) {
714
- MessageFormatter.error("No Appwrite configuration found", undefined, {
715
- prefix: "Backups",
716
- });
717
- return;
718
- }
719
- const { adapter } = await AdapterFactory.create({
720
- appwriteEndpoint: controller.config.appwriteEndpoint,
721
- appwriteProject: controller.config.appwriteProject,
722
- appwriteKey: controller.config.appwriteKey,
723
- });
724
- const databases = parsedArgv.dbIds
725
- ? await controller.getDatabasesByIds(parsedArgv.dbIds.split(","))
726
- : await fetchAllDatabases(controller.database);
727
- if (!databases || databases.length === 0) {
728
- MessageFormatter.info("No databases found", { prefix: "Backups" });
729
- return;
730
- }
731
- for (const db of databases) {
732
- const backups = await listBackups(adapter, db.$id);
733
- MessageFormatter.info(`\nBackups for database: ${db.name} (${db.$id})`, { prefix: "Backups" });
734
- if (backups.length === 0) {
735
- MessageFormatter.info(" No backups found", { prefix: "Backups" });
736
- }
737
- else {
738
- backups.forEach((backup, index) => {
739
- const date = new Date(backup.$createdAt).toLocaleString();
740
- const size = MessageFormatter.formatBytes(backup.sizeBytes);
741
- MessageFormatter.info(` ${index + 1}. ${date} - ${backup.format.toUpperCase()} - ${size} - ${backup.collections} collections, ${backup.documents} documents`, { prefix: "Backups" });
742
- });
743
- }
744
- }
745
- return;
746
- }
747
- const options = {
748
- databases: parsedArgv.dbIds
749
- ? await controller.getDatabasesByIds(parsedArgv.dbIds.split(","))
750
- : undefined,
751
- collections: parsedArgv.collectionIds?.split(","),
752
- doBackup: parsedArgv.backup,
753
- wipeDatabase: parsedArgv.wipe === "all" || parsedArgv.wipe === "docs",
754
- wipeDocumentStorage: parsedArgv.wipe === "all" || parsedArgv.wipe === "storage",
755
- wipeUsers: parsedArgv.wipe === "all" || parsedArgv.wipe === "users",
756
- generateSchemas: parsedArgv.generate,
757
- importData: parsedArgv.import,
758
- shouldWriteFile: parsedArgv.writeData,
759
- wipeCollections: parsedArgv.wipeCollections,
760
- transferUsers: parsedArgv.transferUsers,
761
- };
762
- if (parsedArgv.updateFunctionSpec) {
763
- if (!parsedArgv.functionId || !parsedArgv.specification) {
764
- throw new Error("Function ID and specification are required for updating function specs");
765
- }
766
- MessageFormatter.info(`Updating function specification for ${parsedArgv.functionId} to ${parsedArgv.specification}`, { prefix: "Functions" });
767
- const specifications = await listSpecifications(controller.appwriteServer);
768
- if (!specifications.specifications.some((s) => s.slug === parsedArgv.specification)) {
769
- MessageFormatter.error(`Specification ${parsedArgv.specification} not found`, undefined, { prefix: "Functions" });
770
- return;
771
- }
772
- await controller.updateFunctionSpecifications(parsedArgv.functionId, parsedArgv.specification);
773
- }
774
- // Add default databases if not specified (only if we need them for operations)
775
- const needsDatabases = options.doBackup ||
776
- options.wipeDatabase ||
777
- options.wipeDocumentStorage ||
778
- options.wipeUsers ||
779
- options.wipeCollections ||
780
- options.importData ||
781
- parsedArgv.sync ||
782
- parsedArgv.transfer;
783
- if (needsDatabases &&
784
- (!options.databases || options.databases.length === 0)) {
785
- const allDatabases = await fetchAllDatabases(controller.database);
786
- options.databases = allDatabases;
787
- }
788
- // Add default collections if not specified
789
- if (!options.collections || options.collections.length === 0) {
790
- if (controller.config && controller.config.collections) {
791
- options.collections = controller.config.collections.map((c) => c.name);
792
- }
793
- else {
794
- options.collections = [];
795
- }
796
- }
797
- // Comprehensive backup (all databases + all buckets)
798
- if (parsedArgv.comprehensiveBackup) {
799
- const { comprehensiveBackup } = await import("./backups/operations/comprehensiveBackup.js");
800
- const { AdapterFactory } = await import("./adapters/AdapterFactory.js");
801
- // Get tracking database ID (interactive prompt if not specified)
802
- let trackingDatabaseId = parsedArgv.trackingDatabaseId;
803
- if (!trackingDatabaseId) {
804
- // Fetch all databases for selection
805
- const allDatabases = await fetchAllDatabases(controller.database);
806
- if (allDatabases.length === 0) {
807
- MessageFormatter.error("No databases found. Cannot create comprehensive backup without a tracking database.", undefined, { prefix: "Backup" });
808
- return;
809
- }
810
- if (allDatabases.length === 1) {
811
- trackingDatabaseId = allDatabases[0].$id;
812
- MessageFormatter.info(`Using only available database for tracking: ${allDatabases[0].name} (${trackingDatabaseId})`, { prefix: "Backup" });
813
- }
814
- else {
815
- // Interactive selection
816
- const inquirer = (await import("inquirer")).default;
817
- const answer = await inquirer.prompt([
818
- {
819
- type: "list",
820
- name: "trackingDb",
821
- message: "Select database to store backup tracking metadata:",
822
- choices: allDatabases.map((db) => ({
823
- name: `${db.name} (${db.$id})`,
824
- value: db.$id,
825
- })),
826
- },
827
- ]);
828
- trackingDatabaseId = answer.trackingDb;
829
- }
830
- }
831
- // Ensure trackingDatabaseId is defined before proceeding
832
- if (!trackingDatabaseId) {
833
- throw new Error("Tracking database ID is required for comprehensive backup");
834
- }
835
- MessageFormatter.info(`Using tracking database: ${trackingDatabaseId}`, {
836
- prefix: "Backup",
837
- });
838
- // Create adapter for backup tracking
839
- const { adapter } = await AdapterFactory.create({
840
- appwriteEndpoint: controller.config.appwriteEndpoint,
841
- appwriteProject: controller.config.appwriteProject,
842
- appwriteKey: controller.config.appwriteKey,
843
- sessionCookie: controller.config.sessionCookie,
844
- });
845
- const result = await comprehensiveBackup(controller.config, controller.database, controller.storage, adapter, {
846
- trackingDatabaseId,
847
- backupFormat: parsedArgv.backupFormat || "zip",
848
- parallelDownloads: parsedArgv.parallelDownloads || 10,
849
- onProgress: (message) => {
850
- MessageFormatter.info(message, { prefix: "Backup" });
851
- },
852
- });
853
- operationStats.comprehensiveBackup = 1;
854
- operationStats.databasesBackedUp = result.databaseBackups.length;
855
- operationStats.bucketsBackedUp = result.bucketBackups.length;
856
- operationStats.totalBackupSize = result.totalSizeBytes;
857
- if (result.status === "completed") {
858
- MessageFormatter.success(`Comprehensive backup completed successfully (ID: ${result.backupId})`, { prefix: "Backup" });
859
- }
860
- else if (result.status === "partial") {
861
- MessageFormatter.warning(`Comprehensive backup completed with errors (ID: ${result.backupId})`, { prefix: "Backup" });
862
- result.errors.forEach((err) => MessageFormatter.warning(err, { prefix: "Backup" }));
863
- }
864
- else {
865
- MessageFormatter.error(`Comprehensive backup failed (ID: ${result.backupId})`, undefined, { prefix: "Backup" });
866
- result.errors.forEach((err) => MessageFormatter.error(err, undefined, { prefix: "Backup" }));
867
- }
868
- }
869
- if (options.doBackup && options.databases) {
870
- MessageFormatter.info(`Creating backups for ${options.databases.length} database(s) in ${parsedArgv.backupFormat} format`, { prefix: "Backup" });
871
- for (const db of options.databases) {
872
- await controller.backupDatabase(db, parsedArgv.backupFormat || "json");
873
- }
874
- operationStats.backups = options.databases.length;
875
- MessageFormatter.success(`Backup completed for ${options.databases.length} database(s)`, { prefix: "Backup" });
876
- }
877
- if (options.wipeDatabase ||
878
- options.wipeDocumentStorage ||
879
- options.wipeUsers ||
880
- options.wipeCollections) {
881
- // Confirm destructive operations
882
- const databaseNames = options.databases?.map((db) => db.name) || [];
883
- const confirmed = await ConfirmationDialogs.confirmDatabaseWipe(databaseNames, {
884
- includeStorage: options.wipeDocumentStorage,
885
- includeUsers: options.wipeUsers,
886
- });
887
- if (!confirmed) {
888
- MessageFormatter.info("Operation cancelled by user", { prefix: "CLI" });
889
- return;
890
- }
891
- let wipeStats = { databases: 0, collections: 0, users: 0, buckets: 0 };
892
- if (parsedArgv.wipe === "all") {
893
- if (options.databases) {
894
- for (const db of options.databases) {
895
- await controller.wipeDatabase(db, true); // true to wipe associated buckets
896
- }
897
- wipeStats.databases = options.databases.length;
898
- }
899
- await controller.wipeUsers();
900
- wipeStats.users = 1;
901
- }
902
- else if (parsedArgv.wipe === "docs") {
903
- if (options.databases) {
904
- for (const db of options.databases) {
905
- await controller.wipeBucketFromDatabase(db);
906
- }
907
- wipeStats.databases = options.databases.length;
908
- }
909
- if (parsedArgv.bucketIds) {
910
- const bucketIds = parsedArgv.bucketIds.split(",");
911
- for (const bucketId of bucketIds) {
912
- await controller.wipeDocumentStorage(bucketId);
913
- }
914
- wipeStats.buckets = bucketIds.length;
915
- }
916
- }
917
- else if (parsedArgv.wipe === "users") {
918
- await controller.wipeUsers();
919
- wipeStats.users = 1;
920
- }
921
- // Handle specific collection wipes
922
- if (options.wipeCollections && options.databases) {
923
- for (const db of options.databases) {
924
- const dbCollections = await fetchAllCollections(db.$id, controller.database);
925
- const collectionsToWipe = dbCollections.filter((c) => options.collections.includes(c.$id));
926
- // Confirm collection wipe
927
- const collectionNames = collectionsToWipe.map((c) => c.name);
928
- const collectionConfirmed = await ConfirmationDialogs.confirmCollectionWipe(db.name, collectionNames);
929
- if (collectionConfirmed) {
930
- for (const collection of collectionsToWipe) {
931
- await controller.wipeCollection(db, collection);
932
- }
933
- wipeStats.collections += collectionsToWipe.length;
934
- }
935
- }
936
- }
937
- // Show wipe operation summary
938
- if (wipeStats.databases > 0 ||
939
- wipeStats.collections > 0 ||
940
- wipeStats.users > 0 ||
941
- wipeStats.buckets > 0) {
942
- operationStats.wipedDatabases = wipeStats.databases;
943
- operationStats.wipedCollections = wipeStats.collections;
944
- operationStats.wipedUsers = wipeStats.users;
945
- operationStats.wipedBuckets = wipeStats.buckets;
946
- }
947
- }
948
- if (parsedArgv.push) {
949
- await controller.init();
950
- if (!controller.database || !controller.config) {
951
- MessageFormatter.error("Database or config not initialized", undefined, { prefix: "Push" });
952
- return;
953
- }
954
- // Fetch available DBs
955
- const availableDatabases = await fetchAllDatabases(controller.database);
956
- if (availableDatabases.length === 0) {
957
- MessageFormatter.warning("No databases found in remote project", { prefix: "Push" });
958
- return;
959
- }
960
- // Determine selected DBs
961
- let selectedDbIds = [];
962
- if (parsedArgv.dbIds) {
963
- selectedDbIds = parsedArgv.dbIds.split(/[,\s]+/).filter(Boolean);
964
- }
965
- else {
966
- selectedDbIds = await SelectionDialogs.selectDatabases(availableDatabases, controller.config.databases || [], { showSelectAll: false, allowNewOnly: false, defaultSelected: [] });
967
- }
968
- if (selectedDbIds.length === 0) {
969
- MessageFormatter.warning("No databases selected for push", { prefix: "Push" });
970
- return;
971
- }
972
- // Build DatabaseSelection[] with tableIds per DB
973
- const databaseSelections = [];
974
- const allConfigItems = controller.config.collections || controller.config.tables || [];
975
- let lastSelectedTableIds = null;
976
- for (const dbId of selectedDbIds) {
977
- const db = availableDatabases.find(d => d.$id === dbId);
978
- if (!db)
979
- continue;
980
- // Filter config items eligible for this DB according to databaseId/databaseIds rule
981
- const eligibleConfigItems = allConfigItems.filter(item => {
982
- const one = item.databaseId;
983
- const many = item.databaseIds;
984
- if (Array.isArray(many) && many.length > 0)
985
- return many.includes(dbId);
986
- if (one)
987
- return one === dbId;
988
- return true; // eligible everywhere if unspecified
989
- });
990
- // Fetch available tables from remote for selection context
991
- const availableTables = await fetchAllCollections(dbId, controller.database);
992
- // Determine selected table IDs
993
- let selectedTableIds = [];
994
- if (parsedArgv.collectionIds) {
995
- // Non-interactive: respect provided table IDs as-is (apply to each selected DB)
996
- selectedTableIds = parsedArgv.collectionIds.split(/[\,\s]+/).filter(Boolean);
997
- }
998
- else {
999
- // If we have a previous selection, offer to reuse it
1000
- if (lastSelectedTableIds && lastSelectedTableIds.length > 0) {
1001
- const inquirer = (await import("inquirer")).default;
1002
- const { reuseMode } = await inquirer.prompt([
1003
- {
1004
- type: "list",
1005
- name: "reuseMode",
1006
- message: `How do you want to select tables for ${db.name}?`,
1007
- choices: [
1008
- { name: `Use same selection as previous (${lastSelectedTableIds.length} items)`, value: "same" },
1009
- { name: `Filter by this database (manual select)`, value: "filter" },
1010
- { name: `Show all available in this database (manual select)`, value: "all" }
1011
- ],
1012
- default: "same"
1013
- }
1014
- ]);
1015
- if (reuseMode === "same") {
1016
- selectedTableIds = [...lastSelectedTableIds];
1017
- }
1018
- else if (reuseMode === "all") {
1019
- selectedTableIds = await SelectionDialogs.selectTablesForDatabase(dbId, db.name, availableTables, allConfigItems, { showSelectAll: false, allowNewOnly: false, defaultSelected: lastSelectedTableIds });
1020
- }
1021
- else {
1022
- selectedTableIds = await SelectionDialogs.selectTablesForDatabase(dbId, db.name, availableTables, eligibleConfigItems, { showSelectAll: false, allowNewOnly: true, defaultSelected: lastSelectedTableIds });
1023
- }
1024
- }
1025
- else {
1026
- selectedTableIds = await SelectionDialogs.selectTablesForDatabase(dbId, db.name, availableTables, eligibleConfigItems, { showSelectAll: false, allowNewOnly: true, defaultSelected: [] });
1027
- }
1028
- }
1029
- databaseSelections.push({
1030
- databaseId: db.$id,
1031
- databaseName: db.name,
1032
- tableIds: selectedTableIds,
1033
- tableNames: [],
1034
- isNew: false,
1035
- });
1036
- if (!parsedArgv.collectionIds) {
1037
- lastSelectedTableIds = selectedTableIds;
1038
- }
1039
- }
1040
- if (databaseSelections.every(sel => sel.tableIds.length === 0)) {
1041
- MessageFormatter.warning("No tables/collections selected for push", { prefix: "Push" });
1042
- return;
1043
- }
1044
- const pushSummary = {
1045
- databases: databaseSelections.length,
1046
- collections: databaseSelections.reduce((sum, s) => sum + s.tableIds.length, 0),
1047
- details: databaseSelections.map(s => `${s.databaseId}: ${s.tableIds.length} items`),
1048
- };
1049
- // Skip confirmation if both dbIds and collectionIds are provided (non-interactive)
1050
- if (!(parsedArgv.dbIds && parsedArgv.collectionIds)) {
1051
- const confirmed = await ConfirmationDialogs.showOperationSummary('Push', pushSummary, { confirmationRequired: true });
1052
- if (!confirmed) {
1053
- MessageFormatter.info("Push operation cancelled", { prefix: "Push" });
1054
- return;
1055
- }
1056
- }
1057
- await controller.selectivePush(databaseSelections, []);
1058
- operationStats.pushedDatabases = databaseSelections.length;
1059
- operationStats.pushedCollections = databaseSelections.reduce((sum, s) => sum + s.tableIds.length, 0);
1060
- }
1061
- else if (parsedArgv.sync) {
1062
- // Enhanced SYNC: Pull from remote with intelligent configuration detection
1063
- if (parsedArgv.autoSync) {
1064
- // Legacy behavior: sync everything without prompts
1065
- MessageFormatter.info("Using auto-sync mode (legacy behavior)", { prefix: "Sync" });
1066
- const databases = options.databases || (await fetchAllDatabases(controller.database));
1067
- await controller.synchronizeConfigurations(databases);
1068
- operationStats.syncedDatabases = databases.length;
1069
- }
1070
- else {
1071
- // Enhanced sync flow with selection dialogs
1072
- const syncResult = await performEnhancedSync(controller, parsedArgv);
1073
- if (syncResult) {
1074
- operationStats.syncedDatabases = syncResult.databases.length;
1075
- operationStats.syncedCollections = syncResult.totalTables;
1076
- operationStats.syncedBuckets = syncResult.buckets.length;
1077
- }
1078
- }
1079
- }
1080
- if (options.generateSchemas) {
1081
- await controller.generateSchemas();
1082
- operationStats.generatedSchemas = 1;
1083
- }
1084
- if (options.importData) {
1085
- await controller.importData(options);
1086
- operationStats.importCompleted = 1;
1087
- }
1088
- if (parsedArgv.transfer) {
1089
- const isRemote = !!parsedArgv.remoteEndpoint;
1090
- let fromDb, toDb;
1091
- let targetDatabases;
1092
- let targetStorage;
1093
- // Only fetch databases if database IDs are provided
1094
- if (parsedArgv.fromDbId && parsedArgv.toDbId) {
1095
- MessageFormatter.info(`Starting database transfer from ${parsedArgv.fromDbId} to ${parsedArgv.toDbId}`, { prefix: "Transfer" });
1096
- fromDb = (await controller.getDatabasesByIds([parsedArgv.fromDbId]))?.[0];
1097
- if (!fromDb) {
1098
- MessageFormatter.error("Source database not found", undefined, {
1099
- prefix: "Transfer",
1100
- });
1101
- return;
1102
- }
1103
- if (isRemote) {
1104
- if (!parsedArgv.remoteEndpoint ||
1105
- !parsedArgv.remoteProjectId ||
1106
- !parsedArgv.remoteApiKey) {
1107
- throw new Error("Remote transfer details are missing");
1108
- }
1109
- const remoteClient = getClient(parsedArgv.remoteEndpoint, parsedArgv.remoteProjectId, parsedArgv.remoteApiKey);
1110
- targetDatabases = new Databases(remoteClient);
1111
- targetStorage = new Storage(remoteClient);
1112
- const remoteDbs = await fetchAllDatabases(targetDatabases);
1113
- toDb = remoteDbs.find((db) => db.$id === parsedArgv.toDbId);
1114
- if (!toDb) {
1115
- MessageFormatter.error("Target database not found", undefined, {
1116
- prefix: "Transfer",
1117
- });
1118
- return;
1119
- }
1120
- }
1121
- else {
1122
- toDb = (await controller.getDatabasesByIds([parsedArgv.toDbId]))?.[0];
1123
- if (!toDb) {
1124
- MessageFormatter.error("Target database not found", undefined, {
1125
- prefix: "Transfer",
1126
- });
1127
- return;
1128
- }
1129
- }
1130
- if (!fromDb || !toDb) {
1131
- MessageFormatter.error("Source or target database not found", undefined, { prefix: "Transfer" });
1132
- return;
1133
- }
1134
- }
1135
- // Handle storage setup
1136
- let sourceBucket, targetBucket;
1137
- if (parsedArgv.fromBucketId) {
1138
- sourceBucket = await controller.storage?.getBucket(parsedArgv.fromBucketId);
1139
- }
1140
- if (parsedArgv.toBucketId) {
1141
- if (isRemote) {
1142
- if (!targetStorage) {
1143
- const remoteClient = getClient(parsedArgv.remoteEndpoint, parsedArgv.remoteProjectId, parsedArgv.remoteApiKey);
1144
- targetStorage = new Storage(remoteClient);
1145
- }
1146
- targetBucket = await targetStorage?.getBucket(parsedArgv.toBucketId);
1147
- }
1148
- else {
1149
- targetBucket = await controller.storage?.getBucket(parsedArgv.toBucketId);
1150
- }
1151
- }
1152
- // Validate that at least one transfer type is specified
1153
- if (!fromDb && !sourceBucket && !options.transferUsers) {
1154
- throw new Error("No source database or bucket specified for transfer");
1155
- }
1156
- const transferOptions = {
1157
- isRemote,
1158
- fromDb,
1159
- targetDb: toDb,
1160
- transferEndpoint: parsedArgv.remoteEndpoint,
1161
- transferProject: parsedArgv.remoteProjectId,
1162
- transferKey: parsedArgv.remoteApiKey,
1163
- sourceBucket: sourceBucket,
1164
- targetBucket: targetBucket,
1165
- transferUsers: options.transferUsers,
1166
- };
1167
- await controller.transferData(transferOptions);
1168
- operationStats.transfers = 1;
1169
- }
1170
- // Show final operation summary if any operations were performed
1171
- if (Object.keys(operationStats).length > 0) {
1172
- const duration = Date.now() - startTime;
1173
- MessageFormatter.operationSummary("CLI Operations", operationStats, duration);
1174
- }
1175
- }
1176
- }
1177
- main().catch((error) => {
1178
- MessageFormatter.error("CLI execution failed", error, { prefix: "CLI" });
1179
- process.exit(1);
1180
- });