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
package/src/main.ts DELETED
@@ -1,1670 +0,0 @@
1
- #!/usr/bin/env node
2
- import yargs from "yargs";
3
- import { type ArgumentsCamelCase } from "yargs";
4
- import { hideBin } from "yargs/helpers";
5
- import { InteractiveCLI } from "./interactiveCLI.js";
6
- import { UtilsController, type SetupOptions } from "./utilsController.js";
7
- import type { TransferOptions } from "./migrations/transfer.js";
8
- import { Databases, Storage, type Models } from "node-appwrite";
9
- import { getClient } from "./utils/getClientFromConfig.js";
10
- import { fetchAllDatabases } from "./databases/methods.js";
11
- import { setupDirsFiles } from "./utils/setupFiles.js";
12
- import { fetchAllCollections } from "./collections/methods.js";
13
- import type { Specification } from "appwrite-utils";
14
- import chalk from "chalk";
15
- import { listSpecifications } from "./functions/methods.js";
16
- import { MessageFormatter } from "./shared/messageFormatter.js";
17
- import { ConfirmationDialogs } from "./shared/confirmationDialogs.js";
18
- import { SelectionDialogs } from "./shared/selectionDialogs.js";
19
- import { logger } from "./shared/logging.js";
20
- import type { SyncSelectionSummary, DatabaseSelection, BucketSelection } from "./shared/selectionDialogs.js";
21
- import path from "path";
22
- import fs from "fs";
23
- import { createRequire } from "node:module";
24
- import {
25
- loadAppwriteProjectConfig,
26
- findAppwriteProjectConfig,
27
- projectConfigToAppwriteConfig,
28
- } from "./utils/projectConfig.js";
29
- import {
30
- hasSessionAuth,
31
- getAvailableSessions,
32
- getAuthenticationStatus,
33
- } from "./utils/sessionAuth.js";
34
- import {
35
- findYamlConfig,
36
- loadYamlConfigWithSession,
37
- } from "./config/yamlConfig.js";
38
-
39
- const require = createRequire(import.meta.url);
40
- if (!(globalThis as any).require) {
41
- (globalThis as any).require = require;
42
- }
43
-
44
- interface CliOptions {
45
- config?: string;
46
- appwriteConfig?: boolean;
47
- it?: boolean;
48
- dbIds?: string;
49
- collectionIds?: string;
50
- bucketIds?: string;
51
- wipe?: "all" | "storage" | "docs" | "users";
52
- wipeCollections?: boolean;
53
- generate?: boolean;
54
- import?: boolean;
55
- backup?: boolean;
56
- backupFormat?: "json" | "zip";
57
- comprehensiveBackup?: boolean;
58
- trackingDatabaseId?: string;
59
- parallelDownloads?: number;
60
- writeData?: boolean;
61
- push?: boolean;
62
- sync?: boolean;
63
- endpoint?: string;
64
- projectId?: string;
65
- apiKey?: string;
66
- transfer?: boolean;
67
- transferUsers?: boolean;
68
- fromDbId?: string;
69
- toDbId?: string;
70
- fromCollectionId?: string;
71
- toCollectionId?: string;
72
- fromBucketId?: string;
73
- toBucketId?: string;
74
- remoteEndpoint?: string;
75
- remoteProjectId?: string;
76
- remoteApiKey?: string;
77
- setup?: boolean;
78
- updateFunctionSpec?: boolean;
79
- functionId?: string;
80
- specification?: string;
81
- migrateConfig?: boolean;
82
- generateConstants?: boolean;
83
- constantsLanguages?: string;
84
- constantsOutput?: string;
85
- migrateCollectionsToTables?: boolean;
86
- useSession?: boolean;
87
- session?: string;
88
- listBackups?: boolean;
89
- autoSync?: boolean;
90
- selectBuckets?: boolean;
91
- // New schema/constant CLI flags
92
- generateSchemas?: boolean;
93
- schemaFormat?: 'zod' | 'json' | 'pydantic' | 'both' | 'all';
94
- schemaOutDir?: string;
95
- constantsInclude?: string;
96
- }
97
-
98
- type ParsedArgv = ArgumentsCamelCase<CliOptions>;
99
-
100
- /**
101
- * Enhanced sync function with intelligent configuration detection and selection dialogs
102
- */
103
- async function performEnhancedSync(
104
- controller: UtilsController,
105
- parsedArgv: ParsedArgv
106
- ): Promise<SyncSelectionSummary | null> {
107
- try {
108
- MessageFormatter.banner("Enhanced Sync", "Intelligent configuration detection and selection");
109
-
110
- if (!controller.config) {
111
- MessageFormatter.error("No Appwrite configuration found", undefined, { prefix: "Sync" });
112
- return null;
113
- }
114
-
115
- // Get all available databases from remote
116
- const availableDatabases = await fetchAllDatabases(controller.database!);
117
- if (availableDatabases.length === 0) {
118
- MessageFormatter.warning("No databases found in remote project", { prefix: "Sync" });
119
- return null;
120
- }
121
-
122
- // Get existing configuration
123
- const configuredDatabases = controller.config.databases || [];
124
- const configuredBuckets = controller.config.buckets || [];
125
-
126
- // Check if we have existing configuration
127
- const hasExistingConfig = configuredDatabases.length > 0 || configuredBuckets.length > 0;
128
-
129
- let syncExisting = false;
130
- let modifyConfiguration = true;
131
-
132
- if (hasExistingConfig) {
133
- // Prompt about existing configuration
134
- const response = await SelectionDialogs.promptForExistingConfig([
135
- ...configuredDatabases,
136
- ...configuredBuckets
137
- ]);
138
- syncExisting = response.syncExisting;
139
- modifyConfiguration = response.modifyConfiguration;
140
-
141
- if (syncExisting && !modifyConfiguration) {
142
- // Just sync existing configuration without changes
143
- MessageFormatter.info("Syncing existing configuration without modifications", { prefix: "Sync" });
144
-
145
- // Convert configured databases to DatabaseSelection format
146
- const databaseSelections: DatabaseSelection[] = configuredDatabases.map(db => ({
147
- databaseId: db.$id,
148
- databaseName: db.name,
149
- tableIds: [], // Tables will be populated from collections config
150
- tableNames: [],
151
- isNew: false
152
- }));
153
-
154
- // Convert configured buckets to BucketSelection format
155
- const bucketSelections: BucketSelection[] = configuredBuckets.map(bucket => ({
156
- bucketId: bucket.$id,
157
- bucketName: bucket.name,
158
- databaseId: undefined,
159
- databaseName: undefined,
160
- isNew: false
161
- }));
162
-
163
- const selectionSummary = SelectionDialogs.createSyncSelectionSummary(
164
- databaseSelections,
165
- bucketSelections
166
- );
167
-
168
- const confirmed = await SelectionDialogs.confirmSyncSelection(selectionSummary, 'pull');
169
- if (!confirmed) {
170
- MessageFormatter.info("Pull operation cancelled by user", { prefix: "Sync" });
171
- return null;
172
- }
173
-
174
- // Perform sync with existing configuration (pull from remote)
175
- await controller.selectivePull(databaseSelections, bucketSelections);
176
- return selectionSummary;
177
- }
178
- }
179
-
180
- if (!modifyConfiguration) {
181
- MessageFormatter.info("No configuration changes requested", { prefix: "Sync" });
182
- return null;
183
- }
184
-
185
- // Allow new items selection based on user choice
186
- const allowNewOnly = !syncExisting;
187
-
188
- // Select databases
189
- const selectedDatabaseIds = await SelectionDialogs.selectDatabases(
190
- availableDatabases,
191
- configuredDatabases,
192
- {
193
- showSelectAll: false,
194
- allowNewOnly,
195
- defaultSelected: []
196
- }
197
- );
198
-
199
- if (selectedDatabaseIds.length === 0) {
200
- MessageFormatter.warning("No databases selected for sync", { prefix: "Sync" });
201
- return null;
202
- }
203
-
204
- // For each selected database, get available tables and select them
205
- const tableSelectionsMap = new Map<string, string[]>();
206
- const availableTablesMap = new Map<string, any[]>();
207
-
208
- for (const databaseId of selectedDatabaseIds) {
209
- const database = availableDatabases.find(db => db.$id === databaseId)!;
210
-
211
- SelectionDialogs.showProgress(`Fetching tables for database: ${database.name}`);
212
-
213
- // Get available tables from remote
214
- const availableTables = await fetchAllCollections(databaseId, controller.database!);
215
- availableTablesMap.set(databaseId, availableTables);
216
-
217
- // Get configured tables for this database
218
- // Note: Collections are stored globally in the config, not per database
219
- const configuredTables = controller.config.collections || [];
220
-
221
- // Select tables for this database
222
- const selectedTableIds = await SelectionDialogs.selectTablesForDatabase(
223
- databaseId,
224
- database.name,
225
- availableTables,
226
- configuredTables,
227
- {
228
- showSelectAll: false,
229
- allowNewOnly,
230
- defaultSelected: []
231
- }
232
- );
233
-
234
- tableSelectionsMap.set(databaseId, selectedTableIds);
235
-
236
- if (selectedTableIds.length === 0) {
237
- MessageFormatter.warning(`No tables selected for database: ${database.name}`, { prefix: "Sync" });
238
- }
239
- }
240
-
241
- // Select buckets
242
- let selectedBucketIds: string[] = [];
243
-
244
- // Get available buckets from remote
245
- if (controller.storage) {
246
- try {
247
- // Note: We need to implement fetchAllBuckets or use storage.listBuckets
248
- // For now, we'll use configured buckets as available
249
- SelectionDialogs.showProgress("Fetching storage buckets...");
250
-
251
- // Create a mock availableBuckets array - in real implementation,
252
- // you'd fetch this from the Appwrite API
253
- const availableBuckets = configuredBuckets; // Placeholder
254
-
255
- selectedBucketIds = await SelectionDialogs.selectBucketsForDatabases(
256
- selectedDatabaseIds,
257
- availableBuckets,
258
- configuredBuckets,
259
- {
260
- showSelectAll: false,
261
- allowNewOnly: parsedArgv.selectBuckets ? false : allowNewOnly,
262
- groupByDatabase: true,
263
- defaultSelected: []
264
- }
265
- );
266
- } catch (error) {
267
- MessageFormatter.warning("Could not fetch storage buckets", { prefix: "Sync" });
268
- logger.warn("Failed to fetch buckets during sync", { error });
269
- }
270
- }
271
-
272
- // Create selection objects
273
- const databaseSelections = SelectionDialogs.createDatabaseSelection(
274
- selectedDatabaseIds,
275
- availableDatabases,
276
- tableSelectionsMap,
277
- configuredDatabases,
278
- availableTablesMap
279
- );
280
-
281
- const bucketSelections = SelectionDialogs.createBucketSelection(
282
- selectedBucketIds,
283
- [], // availableBuckets - would be populated from API
284
- configuredBuckets,
285
- availableDatabases
286
- );
287
-
288
- // Show final confirmation
289
- const selectionSummary = SelectionDialogs.createSyncSelectionSummary(
290
- databaseSelections,
291
- bucketSelections
292
- );
293
-
294
- const confirmed = await SelectionDialogs.confirmSyncSelection(selectionSummary, 'pull');
295
- if (!confirmed) {
296
- MessageFormatter.info("Pull operation cancelled by user", { prefix: "Sync" });
297
- return null;
298
- }
299
-
300
- // Perform the selective sync (pull from remote)
301
- await controller.selectivePull(databaseSelections, bucketSelections);
302
-
303
- MessageFormatter.success("Enhanced sync completed successfully", { prefix: "Sync" });
304
- return selectionSummary;
305
-
306
- } catch (error) {
307
- SelectionDialogs.showError("Enhanced sync failed", error instanceof Error ? error : new Error(String(error)));
308
- return null;
309
- }
310
- }
311
-
312
- /**
313
- * Performs selective sync with the given database and bucket selections
314
- */
315
-
316
- /**
317
- * Checks if the migration from collections to tables should be allowed
318
- * Returns an object with:
319
- * - allowed: boolean indicating if migration should proceed
320
- * - reason: string explaining why migration was blocked (if not allowed)
321
- */
322
- function checkMigrationConditions(configPath: string): {
323
- allowed: boolean;
324
- reason?: string;
325
- } {
326
- const collectionsPath = path.join(configPath, "collections");
327
- const tablesPath = path.join(configPath, "tables");
328
-
329
- // Check if collections/ folder exists
330
- if (!fs.existsSync(collectionsPath)) {
331
- return {
332
- allowed: false,
333
- reason:
334
- "No collections/ folder found. Migration requires existing collections to migrate.",
335
- };
336
- }
337
-
338
- // Check if collections/ folder has YAML files
339
- const collectionFiles = fs
340
- .readdirSync(collectionsPath)
341
- .filter((file) => file.endsWith(".yaml") || file.endsWith(".yml"));
342
-
343
- if (collectionFiles.length === 0) {
344
- return {
345
- allowed: false,
346
- reason:
347
- "No YAML files found in collections/ folder. Migration requires existing collection YAML files.",
348
- };
349
- }
350
-
351
- // Check if tables/ folder exists and has YAML files
352
- if (fs.existsSync(tablesPath)) {
353
- const tableFiles = fs
354
- .readdirSync(tablesPath)
355
- .filter((file) => file.endsWith(".yaml") || file.endsWith(".yml"));
356
-
357
- if (tableFiles.length > 0) {
358
- return {
359
- allowed: false,
360
- reason: `Tables folder already exists with ${tableFiles.length} YAML file(s). Migration appears to have already been completed.`,
361
- };
362
- }
363
- }
364
-
365
- // All conditions met
366
- return { allowed: true };
367
- }
368
-
369
- const argv = yargs(hideBin(process.argv))
370
- .option("config", {
371
- type: "string",
372
- description: "Path to Appwrite configuration file (appwriteConfig.ts)",
373
- })
374
- .option("appwriteConfig", {
375
- alias: ["appwrite-config", "use-appwrite-config"],
376
- type: "boolean",
377
- description: "Prefer loading from appwrite.config.json instead of config.yaml",
378
- })
379
- .option("it", {
380
- alias: ["interactive", "i"],
381
- type: "boolean",
382
- description: "Launch interactive CLI mode with guided prompts",
383
- })
384
- .option("dbIds", {
385
- type: "string",
386
- description:
387
- "Comma-separated list of database IDs to target (e.g., 'db1,db2,db3')",
388
- })
389
- .option("collectionIds", {
390
- alias: ["collIds", "tableIds", "tables"],
391
- type: "string",
392
- description:
393
- "Comma-separated list of collection/table IDs to target (e.g., 'users,posts')",
394
- })
395
- .option("bucketIds", {
396
- type: "string",
397
- description: "Comma-separated list of bucket IDs to operate on",
398
- })
399
- .option("wipe", {
400
- choices: ["all", "docs", "users"] as const,
401
- description:
402
- "⚠️ DESTRUCTIVE: Wipe data (all: databases+storage+users, docs: documents only, users: user accounts only)",
403
- })
404
- .option("wipeCollections", {
405
- type: "boolean",
406
- description:
407
- "⚠️ DESTRUCTIVE: Wipe specific collections/tables (requires --collectionIds or --tableIds)",
408
- })
409
- .option("transferUsers", {
410
- type: "boolean",
411
- description: "Transfer users between projects",
412
- })
413
- .option("generate", {
414
- type: "boolean",
415
- description:
416
- "Generate TypeScript schemas and types from your Appwrite database schemas",
417
- })
418
- .option("import", {
419
- type: "boolean",
420
- description:
421
- "Import data from importData/ directory into your Appwrite databases",
422
- })
423
- .option("backup", {
424
- type: "boolean",
425
- description: "Create a complete backup of your databases and collections",
426
- })
427
- .option("backupFormat", {
428
- type: "string",
429
- choices: ["json", "zip"] as const,
430
- default: "json",
431
- description: "Backup file format (json or zip)",
432
- })
433
- .option("listBackups", {
434
- type: "boolean",
435
- description: "List all backups for databases",
436
- })
437
- .option("comprehensiveBackup", {
438
- alias: ["comprehensive", "backup-all"],
439
- type: "boolean",
440
- description:
441
- "🚀 Create comprehensive backup of ALL databases and ALL storage buckets",
442
- })
443
- .option("trackingDatabaseId", {
444
- alias: ["tracking-db"],
445
- type: "string",
446
- description:
447
- "Database ID to use for centralized backup tracking (interactive prompt if not specified)",
448
- })
449
- .option("parallelDownloads", {
450
- type: "number",
451
- default: 10,
452
- description:
453
- "Number of parallel file downloads for bucket backups (default: 10)",
454
- })
455
- .option("writeData", {
456
- type: "boolean",
457
- description:
458
- "Output converted import data to files for validation before importing",
459
- })
460
- .option("push", {
461
- type: "boolean",
462
- description:
463
- "Deploy your local configuration (collections, attributes, indexes) to Appwrite",
464
- })
465
- .option("sync", {
466
- type: "boolean",
467
- description:
468
- "Pull and synchronize your local config with the remote Appwrite project schema",
469
- })
470
- .option("autoSync", {
471
- alias: ["auto"],
472
- type: "boolean",
473
- description: "Skip prompts and sync all databases, tables, and buckets (current behavior)"
474
- })
475
- .option("selectBuckets", {
476
- type: "boolean",
477
- description: "Force bucket selection dialog even if buckets are already configured"
478
- })
479
- .option("endpoint", {
480
- type: "string",
481
- description: "Set the Appwrite endpoint",
482
- })
483
- .option("projectId", {
484
- type: "string",
485
- description: "Set the Appwrite project ID",
486
- })
487
- .option("apiKey", {
488
- type: "string",
489
- description: "Set the Appwrite API key",
490
- })
491
- .option("transfer", {
492
- type: "boolean",
493
- description:
494
- "Transfer documents and files between databases, collections, or projects",
495
- })
496
- .option("fromDbId", {
497
- alias: ["fromDb", "sourceDbId", "sourceDb"],
498
- type: "string",
499
- description: "Source database ID for transfer operations",
500
- })
501
- .option("toDbId", {
502
- alias: ["toDb", "targetDbId", "targetDb"],
503
- type: "string",
504
- description: "Target database ID for transfer operations",
505
- })
506
- .option("fromCollectionId", {
507
- alias: ["fromCollId", "fromColl"],
508
- type: "string",
509
- description: "Set the source collection ID for transfer",
510
- })
511
- .option("toCollectionId", {
512
- alias: ["toCollId", "toColl"],
513
- type: "string",
514
- description: "Set the destination collection ID for transfer",
515
- })
516
- .option("fromBucketId", {
517
- type: "string",
518
- description: "Set the source bucket ID for transfer",
519
- })
520
- .option("toBucketId", {
521
- type: "string",
522
- description: "Set the destination bucket ID for transfer",
523
- })
524
- .option("remoteEndpoint", {
525
- type: "string",
526
- description: "Set the remote Appwrite endpoint for transfer",
527
- })
528
- .option("remoteProjectId", {
529
- type: "string",
530
- description: "Set the remote Appwrite project ID for transfer",
531
- })
532
- .option("remoteApiKey", {
533
- type: "string",
534
- description: "Set the remote Appwrite API key for transfer",
535
- })
536
- .option("setup", {
537
- type: "boolean",
538
- description:
539
- "Initialize project with configuration files and directory structure",
540
- })
541
- .option("updateFunctionSpec", {
542
- type: "boolean",
543
- description: "Update function specifications",
544
- })
545
- .option("functionId", {
546
- type: "string",
547
- description: "Function ID to update",
548
- })
549
- .option("specification", {
550
- type: "string",
551
- description: "New function specification (e.g., 's-1vcpu-1gb')",
552
- choices: [
553
- "s-0.5vcpu-512mb",
554
- "s-1vcpu-1gb",
555
- "s-2vcpu-2gb",
556
- "s-2vcpu-4gb",
557
- "s-4vcpu-4gb",
558
- "s-4vcpu-8gb",
559
- "s-8vcpu-4gb",
560
- "s-8vcpu-8gb",
561
- ],
562
- })
563
- .option("migrateConfig", {
564
- alias: ["migrate"],
565
- type: "boolean",
566
- description:
567
- "Migrate appwriteConfig.ts to .appwrite structure with YAML configuration",
568
- })
569
- .option("generateConstants", {
570
- alias: ["constants"],
571
- type: "boolean",
572
- description:
573
- "Generate cross-language constants file with database, collection, bucket, and function IDs",
574
- })
575
- .option("constantsLanguages", {
576
- type: "string",
577
- description:
578
- "Comma-separated list of languages for constants (typescript,javascript,python,php,dart,json,env)",
579
- default: "typescript",
580
- })
581
- .option("constantsOutput", {
582
- type: "string",
583
- description:
584
- "Output directory for generated constants files (default: config-folder/constants)",
585
- default: "auto",
586
- })
587
- .option("constantsInclude", {
588
- type: "string",
589
- description:
590
- "Comma-separated categories to include: databases,collections,buckets,functions",
591
- })
592
- .option("generateSchemas", {
593
- type: "boolean",
594
- description: "Generate schemas/models without interactive prompts",
595
- })
596
- .option("schemaFormat", {
597
- type: "string",
598
- choices: ["zod", "json", "pydantic", "both", "all"],
599
- description: "Schema format: zod, json, pydantic, both (zod+json), or all",
600
- })
601
- .option("schemaOutDir", {
602
- type: "string",
603
- description: "Output directory for generated schemas (absolute path respected)",
604
- })
605
- .option("migrateCollectionsToTables", {
606
- alias: ["migrate-collections"],
607
- type: "boolean",
608
- description:
609
- "Migrate collections to tables format for TablesDB API compatibility",
610
- })
611
- .option("useSession", {
612
- alias: ["session"],
613
- type: "boolean",
614
- description: "Use Appwrite CLI session authentication instead of API key",
615
- })
616
- .option("sessionCookie", {
617
- type: "string",
618
- description: "Explicit session cookie to use for authentication",
619
- })
620
- .parse() as ParsedArgv;
621
-
622
- async function main() {
623
- const startTime = Date.now();
624
- const operationStats: Record<string, number> = {};
625
-
626
- // Early session detection for better user guidance
627
- const availableSessions = getAvailableSessions();
628
- let hasAnyValidSessions = availableSessions.length > 0;
629
-
630
- if (argv.it) {
631
- const cli = new InteractiveCLI(process.cwd());
632
- await cli.run();
633
- } else {
634
- // Enhanced config creation with session and project file support
635
- let directConfig: any = undefined;
636
-
637
- // Show authentication status on startup if no config provided
638
- if (
639
- !argv.config &&
640
- !argv.endpoint &&
641
- !argv.projectId &&
642
- !argv.apiKey &&
643
- !argv.useSession &&
644
- !argv.sessionCookie
645
- ) {
646
- if (hasAnyValidSessions) {
647
- MessageFormatter.info(
648
- `Found ${availableSessions.length} available session(s)`,
649
- { prefix: "Auth" }
650
- );
651
- availableSessions.forEach((session) => {
652
- MessageFormatter.info(
653
- ` \u2022 ${session.projectId} (${session.email || "unknown"}) at ${
654
- session.endpoint
655
- }`,
656
- { prefix: "Auth" }
657
- );
658
- });
659
- MessageFormatter.info(
660
- "Use --session to enable session authentication",
661
- { prefix: "Auth" }
662
- );
663
- } else {
664
- MessageFormatter.info("No active Appwrite sessions found", {
665
- prefix: "Auth",
666
- });
667
- MessageFormatter.info(
668
- "\u2022 Run 'appwrite login' to authenticate with session",
669
- { prefix: "Auth" }
670
- );
671
- MessageFormatter.info(
672
- "\u2022 Or provide --apiKey for API key authentication",
673
- { prefix: "Auth" }
674
- );
675
- }
676
- }
677
-
678
- // Priority 1: Check for appwrite.json project configuration
679
- const projectConfigPath = findAppwriteProjectConfig(process.cwd());
680
- if (projectConfigPath) {
681
- const projectConfig = loadAppwriteProjectConfig(projectConfigPath);
682
- if (projectConfig) {
683
- directConfig = projectConfigToAppwriteConfig(projectConfig);
684
- MessageFormatter.info(
685
- `Loaded project configuration from ${projectConfigPath}`,
686
- { prefix: "CLI" }
687
- );
688
- }
689
- }
690
-
691
- // Priority 2: CLI arguments override project config
692
- if (
693
- argv.endpoint ||
694
- argv.projectId ||
695
- argv.apiKey ||
696
- argv.useSession ||
697
- argv.sessionCookie
698
- ) {
699
- directConfig = {
700
- ...directConfig,
701
- appwriteEndpoint: argv.endpoint || directConfig?.appwriteEndpoint,
702
- appwriteProject: argv.projectId || directConfig?.appwriteProject,
703
- appwriteKey: argv.apiKey || directConfig?.appwriteKey,
704
- };
705
- }
706
-
707
- // Priority 3: Session authentication support with improved detection
708
- let sessionAuthAvailable = false;
709
-
710
- if (directConfig?.appwriteEndpoint && directConfig?.appwriteProject) {
711
- sessionAuthAvailable = hasSessionAuth(
712
- directConfig.appwriteEndpoint,
713
- directConfig.appwriteProject
714
- );
715
- }
716
-
717
- if (argv.useSession || argv.sessionCookie) {
718
- if (argv.sessionCookie) {
719
- // Explicit session cookie provided
720
- MessageFormatter.info(
721
- "Using explicit session cookie for authentication",
722
- { prefix: "Auth" }
723
- );
724
- } else if (sessionAuthAvailable) {
725
- MessageFormatter.info(
726
- "Session authentication detected and will be used",
727
- { prefix: "Auth" }
728
- );
729
- } else {
730
- MessageFormatter.warning(
731
- "Session authentication requested but no valid session found",
732
- { prefix: "Auth" }
733
- );
734
- const availableSessions = getAvailableSessions();
735
- if (availableSessions.length > 0) {
736
- MessageFormatter.info(
737
- `Available sessions: ${availableSessions
738
- .map((s) => `${s.projectId} (${s.email || "unknown"})`)
739
- .join(", ")}`,
740
- { prefix: "Auth" }
741
- );
742
- MessageFormatter.info(
743
- "Use --session flag to enable session authentication",
744
- { prefix: "Auth" }
745
- );
746
- } else {
747
- MessageFormatter.warning(
748
- "No Appwrite CLI sessions found. Please run 'appwrite login' first.",
749
- { prefix: "Auth" }
750
- );
751
- }
752
- MessageFormatter.error(
753
- "Session authentication requested but not available",
754
- undefined,
755
- { prefix: "Auth" }
756
- );
757
- return; // Exit early if session auth was requested but not available
758
- }
759
- } else if (sessionAuthAvailable && !argv.apiKey) {
760
- // Auto-detect session authentication when no API key is provided
761
- MessageFormatter.info(
762
- "Session authentication detected - no API key required",
763
- { prefix: "Auth" }
764
- );
765
- MessageFormatter.info(
766
- "Use --session flag to explicitly enable session authentication",
767
- { prefix: "Auth" }
768
- );
769
- }
770
-
771
- // Enhanced session authentication support:
772
- // 1. If session auth is explicitly requested via flags, use it
773
- // 2. If no API key is provided but sessions are available, offer to use session auth
774
- // 3. Auto-detect session authentication when possible
775
- let finalDirectConfig = directConfig;
776
-
777
- if (
778
- (argv.useSession || argv.sessionCookie) &&
779
- (!directConfig ||
780
- !directConfig.appwriteEndpoint ||
781
- !directConfig.appwriteProject)
782
- ) {
783
- // Don't pass incomplete directConfig - let UtilsController load YAML config normally
784
- finalDirectConfig = null;
785
- } else if (
786
- finalDirectConfig &&
787
- !finalDirectConfig.appwriteKey &&
788
- !argv.useSession &&
789
- !argv.sessionCookie
790
- ) {
791
- // Auto-detect session authentication when no API key provided
792
- if (sessionAuthAvailable) {
793
- MessageFormatter.info(
794
- "No API key provided, but session authentication is available",
795
- { prefix: "Auth" }
796
- );
797
- MessageFormatter.info(
798
- "Automatically using session authentication (add --session to suppress this message)",
799
- { prefix: "Auth" }
800
- );
801
- // Implicitly enable session authentication
802
- argv.useSession = true;
803
- }
804
- }
805
-
806
- // Create controller with session authentication support using singleton
807
- const controller = UtilsController.getInstance(
808
- process.cwd(),
809
- finalDirectConfig
810
- );
811
-
812
- // Pass session authentication and config options to the controller
813
- const initOptions: any = {};
814
- if (argv.useSession || argv.sessionCookie) {
815
- initOptions.useSession = true;
816
- if (argv.sessionCookie) {
817
- initOptions.sessionCookie = argv.sessionCookie;
818
- }
819
- }
820
- if (argv.appwriteConfig) {
821
- initOptions.preferJson = true;
822
- }
823
-
824
- await controller.init(initOptions);
825
-
826
- if (argv.setup) {
827
- await setupDirsFiles(false, process.cwd());
828
- return;
829
- }
830
-
831
- if (argv.migrateConfig) {
832
- const { migrateConfig } = await import("./utils/configMigration.js");
833
- await migrateConfig(process.cwd());
834
- return;
835
- }
836
-
837
- if (argv.generateConstants) {
838
- const { ConstantsGenerator } = await import(
839
- "./utils/constantsGenerator.js"
840
- );
841
- type SupportedLanguage =
842
- import("./utils/constantsGenerator.js").SupportedLanguage;
843
-
844
- if (!controller.config) {
845
- MessageFormatter.error("No Appwrite configuration found", undefined, {
846
- prefix: "Constants",
847
- });
848
- return;
849
- }
850
-
851
- const languages = argv
852
- .constantsLanguages!.split(",")
853
- .map((l) => l.trim()) as SupportedLanguage[];
854
-
855
- // Determine output directory - use config folder/constants by default, or custom path if specified
856
- let outputDir: string;
857
- if (argv.constantsOutput === "auto") {
858
- // Default case: use config directory + constants, fallback to current directory
859
- const configPath = controller.getAppwriteFolderPath();
860
- outputDir = configPath
861
- ? path.join(configPath, "constants")
862
- : path.join(process.cwd(), "constants");
863
- } else {
864
- // Custom output directory specified
865
- outputDir = argv.constantsOutput!;
866
- }
867
-
868
- MessageFormatter.info(
869
- `Generating constants for languages: ${languages.join(", ")}`,
870
- { prefix: "Constants" }
871
- );
872
-
873
- const generator = new ConstantsGenerator(controller.config);
874
- await generator.generateFiles(languages, outputDir);
875
-
876
- operationStats.generatedConstants = languages.length;
877
- MessageFormatter.success(`Constants generated in ${outputDir}`, {
878
- prefix: "Constants",
879
- });
880
- return;
881
- }
882
-
883
- if (argv.migrateCollectionsToTables) {
884
- try {
885
- if (!controller.config) {
886
- MessageFormatter.error("No Appwrite configuration found", undefined, {
887
- prefix: "Migration",
888
- });
889
- return;
890
- }
891
-
892
- // Get the config path from the controller or use .appwrite in current directory
893
- let configPath = controller.getAppwriteFolderPath();
894
- if (!configPath) {
895
- // Try .appwrite in current directory
896
- const defaultPath = path.join(process.cwd(), ".appwrite");
897
- if (fs.existsSync(defaultPath)) {
898
- configPath = defaultPath;
899
- } else {
900
- MessageFormatter.error(
901
- "Could not determine configuration folder path",
902
- undefined,
903
- { prefix: "Migration" }
904
- );
905
- MessageFormatter.info(
906
- "Make sure you have a .appwrite/ folder in your current directory",
907
- { prefix: "Migration" }
908
- );
909
- return;
910
- }
911
- }
912
-
913
- // Check if migration conditions are met
914
- const migrationCheck = checkMigrationConditions(configPath);
915
- if (!migrationCheck.allowed) {
916
- MessageFormatter.error(
917
- `Migration not allowed: ${migrationCheck.reason}`,
918
- undefined,
919
- { prefix: "Migration" }
920
- );
921
- MessageFormatter.info("Migration requirements:", {
922
- prefix: "Migration",
923
- });
924
- MessageFormatter.info(
925
- " • Configuration must be loaded (use --config or have .appwrite/ folder)",
926
- { prefix: "Migration" }
927
- );
928
- MessageFormatter.info(
929
- " • collections/ folder must exist with YAML files",
930
- { prefix: "Migration" }
931
- );
932
- MessageFormatter.info(
933
- " • tables/ folder must not exist or be empty",
934
- { prefix: "Migration" }
935
- );
936
- return;
937
- }
938
-
939
- const { migrateCollectionsToTables } = await import(
940
- "./config/configMigration.js"
941
- );
942
-
943
- MessageFormatter.info("Starting collections to tables migration...", {
944
- prefix: "Migration",
945
- });
946
- const result = migrateCollectionsToTables(controller.config, {
947
- strategy: "full_migration",
948
- validateResult: true,
949
- dryRun: false,
950
- });
951
-
952
- if (result.success) {
953
- operationStats.migratedCollections = result.changes.length;
954
- MessageFormatter.success(
955
- "Collections migration completed successfully",
956
- { prefix: "Migration" }
957
- );
958
- } else {
959
- MessageFormatter.error(
960
- `Migration failed: ${result.errors.join(", ")}`,
961
- undefined,
962
- { prefix: "Migration" }
963
- );
964
- process.exit(1);
965
- }
966
- } catch (error) {
967
- MessageFormatter.error(
968
- "Migration failed",
969
- error instanceof Error ? error : new Error(String(error)),
970
- { prefix: "Migration" }
971
- );
972
- process.exit(1);
973
- }
974
- return;
975
- }
976
-
977
- if (!controller.config) {
978
- // Provide better guidance based on available authentication methods
979
- const availableSessions = getAvailableSessions();
980
-
981
- if (availableSessions.length > 0) {
982
- MessageFormatter.error("No Appwrite configuration found", undefined, {
983
- prefix: "CLI",
984
- });
985
- MessageFormatter.info("Available authentication options:", {
986
- prefix: "Auth",
987
- });
988
- MessageFormatter.info("• Session authentication: Add --session flag", {
989
- prefix: "Auth",
990
- });
991
- MessageFormatter.info(
992
- "• API key authentication: Add --apiKey YOUR_API_KEY",
993
- { prefix: "Auth" }
994
- );
995
- MessageFormatter.info(
996
- `• Available sessions: ${availableSessions
997
- .map((s) => `${s.projectId} (${s.email || "unknown"})`)
998
- .join(", ")}`,
999
- { prefix: "Auth" }
1000
- );
1001
- } else {
1002
- MessageFormatter.error("No Appwrite configuration found", undefined, {
1003
- prefix: "CLI",
1004
- });
1005
- MessageFormatter.info("Authentication options:", { prefix: "Auth" });
1006
- MessageFormatter.info(
1007
- "• Login with Appwrite CLI: Run 'appwrite login' then use --session flag",
1008
- { prefix: "Auth" }
1009
- );
1010
- MessageFormatter.info("• Use API key: Add --apiKey YOUR_API_KEY", {
1011
- prefix: "Auth",
1012
- });
1013
- MessageFormatter.info(
1014
- "• Create config file: Run with --setup to initialize project configuration",
1015
- { prefix: "Auth" }
1016
- );
1017
- }
1018
- return;
1019
- }
1020
-
1021
- const parsedArgv = argv;
1022
-
1023
- // List backups if requested
1024
- if (parsedArgv.listBackups) {
1025
- const { AdapterFactory } = await import("./adapters/AdapterFactory.js");
1026
- const { listBackups } = await import("./shared/backupTracking.js");
1027
-
1028
- if (!controller.config) {
1029
- MessageFormatter.error("No Appwrite configuration found", undefined, {
1030
- prefix: "Backups",
1031
- });
1032
- return;
1033
- }
1034
-
1035
- const { adapter } = await AdapterFactory.create({
1036
- appwriteEndpoint: controller.config.appwriteEndpoint,
1037
- appwriteProject: controller.config.appwriteProject,
1038
- appwriteKey: controller.config.appwriteKey,
1039
- });
1040
-
1041
- const databases = parsedArgv.dbIds
1042
- ? await controller.getDatabasesByIds(parsedArgv.dbIds.split(","))
1043
- : await fetchAllDatabases(controller.database!);
1044
-
1045
- if (!databases || databases.length === 0) {
1046
- MessageFormatter.info("No databases found", { prefix: "Backups" });
1047
- return;
1048
- }
1049
-
1050
- for (const db of databases!) {
1051
- const backups = await listBackups(adapter, db.$id);
1052
-
1053
- MessageFormatter.info(
1054
- `\nBackups for database: ${db.name} (${db.$id})`,
1055
- { prefix: "Backups" }
1056
- );
1057
-
1058
- if (backups.length === 0) {
1059
- MessageFormatter.info(" No backups found", { prefix: "Backups" });
1060
- } else {
1061
- backups.forEach((backup, index) => {
1062
- const date = new Date(backup.$createdAt).toLocaleString();
1063
- const size = MessageFormatter.formatBytes(backup.sizeBytes);
1064
- MessageFormatter.info(
1065
- ` ${
1066
- index + 1
1067
- }. ${date} - ${backup.format.toUpperCase()} - ${size} - ${
1068
- backup.collections
1069
- } collections, ${backup.documents} documents`,
1070
- { prefix: "Backups" }
1071
- );
1072
- });
1073
- }
1074
- }
1075
-
1076
- return;
1077
- }
1078
-
1079
- const options: SetupOptions = {
1080
- databases: parsedArgv.dbIds
1081
- ? await controller.getDatabasesByIds(parsedArgv.dbIds.split(","))
1082
- : undefined,
1083
- collections: parsedArgv.collectionIds?.split(","),
1084
- doBackup: parsedArgv.backup,
1085
- wipeDatabase: parsedArgv.wipe === "all" || parsedArgv.wipe === "docs",
1086
- wipeDocumentStorage:
1087
- parsedArgv.wipe === "all" || parsedArgv.wipe === "storage",
1088
- wipeUsers: parsedArgv.wipe === "all" || parsedArgv.wipe === "users",
1089
- generateSchemas: parsedArgv.generate,
1090
- importData: parsedArgv.import,
1091
- shouldWriteFile: parsedArgv.writeData,
1092
- wipeCollections: parsedArgv.wipeCollections,
1093
- transferUsers: parsedArgv.transferUsers,
1094
- };
1095
-
1096
- if (parsedArgv.updateFunctionSpec) {
1097
- if (!parsedArgv.functionId || !parsedArgv.specification) {
1098
- throw new Error(
1099
- "Function ID and specification are required for updating function specs"
1100
- );
1101
- }
1102
- MessageFormatter.info(
1103
- `Updating function specification for ${parsedArgv.functionId} to ${parsedArgv.specification}`,
1104
- { prefix: "Functions" }
1105
- );
1106
- const specifications = await listSpecifications(
1107
- controller.appwriteServer!
1108
- );
1109
- if (
1110
- !specifications.specifications.some(
1111
- (s: { slug: string }) => s.slug === parsedArgv.specification
1112
- )
1113
- ) {
1114
- MessageFormatter.error(
1115
- `Specification ${parsedArgv.specification} not found`,
1116
- undefined,
1117
- { prefix: "Functions" }
1118
- );
1119
- return;
1120
- }
1121
- await controller.updateFunctionSpecifications(
1122
- parsedArgv.functionId,
1123
- parsedArgv.specification as Specification
1124
- );
1125
- }
1126
-
1127
- // Add default databases if not specified (only if we need them for operations)
1128
- const needsDatabases =
1129
- options.doBackup ||
1130
- options.wipeDatabase ||
1131
- options.wipeDocumentStorage ||
1132
- options.wipeUsers ||
1133
- options.wipeCollections ||
1134
- options.importData ||
1135
- parsedArgv.sync ||
1136
- parsedArgv.transfer;
1137
-
1138
- if (
1139
- needsDatabases &&
1140
- (!options.databases || options.databases.length === 0)
1141
- ) {
1142
- const allDatabases = await fetchAllDatabases(controller.database!);
1143
- options.databases = allDatabases;
1144
- }
1145
-
1146
- // Add default collections if not specified
1147
- if (!options.collections || options.collections.length === 0) {
1148
- if (controller.config && controller.config.collections) {
1149
- options.collections = controller.config.collections.map(
1150
- (c: any) => c.name
1151
- );
1152
- } else {
1153
- options.collections = [];
1154
- }
1155
- }
1156
-
1157
- // Comprehensive backup (all databases + all buckets)
1158
- if (parsedArgv.comprehensiveBackup) {
1159
- const { comprehensiveBackup } = await import(
1160
- "./backups/operations/comprehensiveBackup.js"
1161
- );
1162
- const { AdapterFactory } = await import("./adapters/AdapterFactory.js");
1163
-
1164
- // Get tracking database ID (interactive prompt if not specified)
1165
- let trackingDatabaseId = parsedArgv.trackingDatabaseId;
1166
-
1167
- if (!trackingDatabaseId) {
1168
- // Fetch all databases for selection
1169
- const allDatabases = await fetchAllDatabases(controller.database!);
1170
-
1171
- if (allDatabases.length === 0) {
1172
- MessageFormatter.error(
1173
- "No databases found. Cannot create comprehensive backup without a tracking database.",
1174
- undefined,
1175
- { prefix: "Backup" }
1176
- );
1177
- return;
1178
- }
1179
-
1180
- if (allDatabases.length === 1) {
1181
- trackingDatabaseId = allDatabases[0].$id;
1182
- MessageFormatter.info(
1183
- `Using only available database for tracking: ${allDatabases[0].name} (${trackingDatabaseId})`,
1184
- { prefix: "Backup" }
1185
- );
1186
- } else {
1187
- // Interactive selection
1188
- const inquirer = (await import("inquirer")).default;
1189
- const answer = await inquirer.prompt([
1190
- {
1191
- type: "list",
1192
- name: "trackingDb",
1193
- message: "Select database to store backup tracking metadata:",
1194
- choices: allDatabases.map((db) => ({
1195
- name: `${db.name} (${db.$id})`,
1196
- value: db.$id,
1197
- })),
1198
- },
1199
- ]);
1200
- trackingDatabaseId = answer.trackingDb;
1201
- }
1202
- }
1203
-
1204
- // Ensure trackingDatabaseId is defined before proceeding
1205
- if (!trackingDatabaseId) {
1206
- throw new Error(
1207
- "Tracking database ID is required for comprehensive backup"
1208
- );
1209
- }
1210
-
1211
- MessageFormatter.info(`Using tracking database: ${trackingDatabaseId}`, {
1212
- prefix: "Backup",
1213
- });
1214
-
1215
- // Create adapter for backup tracking
1216
- const { adapter } = await AdapterFactory.create({
1217
- appwriteEndpoint: controller.config!.appwriteEndpoint,
1218
- appwriteProject: controller.config!.appwriteProject,
1219
- appwriteKey: controller.config!.appwriteKey,
1220
- sessionCookie: controller.config!.sessionCookie,
1221
- });
1222
-
1223
- const result = await comprehensiveBackup(
1224
- controller.config!,
1225
- controller.database!,
1226
- controller.storage!,
1227
- adapter,
1228
- {
1229
- trackingDatabaseId,
1230
- backupFormat: parsedArgv.backupFormat || "zip",
1231
- parallelDownloads: parsedArgv.parallelDownloads || 10,
1232
- onProgress: (message) => {
1233
- MessageFormatter.info(message, { prefix: "Backup" });
1234
- },
1235
- }
1236
- );
1237
-
1238
- operationStats.comprehensiveBackup = 1;
1239
- operationStats.databasesBackedUp = result.databaseBackups.length;
1240
- operationStats.bucketsBackedUp = result.bucketBackups.length;
1241
- operationStats.totalBackupSize = result.totalSizeBytes;
1242
-
1243
- if (result.status === "completed") {
1244
- MessageFormatter.success(
1245
- `Comprehensive backup completed successfully (ID: ${result.backupId})`,
1246
- { prefix: "Backup" }
1247
- );
1248
- } else if (result.status === "partial") {
1249
- MessageFormatter.warning(
1250
- `Comprehensive backup completed with errors (ID: ${result.backupId})`,
1251
- { prefix: "Backup" }
1252
- );
1253
- result.errors.forEach((err) =>
1254
- MessageFormatter.warning(err, { prefix: "Backup" })
1255
- );
1256
- } else {
1257
- MessageFormatter.error(
1258
- `Comprehensive backup failed (ID: ${result.backupId})`,
1259
- undefined,
1260
- { prefix: "Backup" }
1261
- );
1262
- result.errors.forEach((err) =>
1263
- MessageFormatter.error(err, undefined, { prefix: "Backup" })
1264
- );
1265
- }
1266
- }
1267
-
1268
- if (options.doBackup && options.databases) {
1269
- MessageFormatter.info(
1270
- `Creating backups for ${options.databases.length} database(s) in ${parsedArgv.backupFormat} format`,
1271
- { prefix: "Backup" }
1272
- );
1273
- for (const db of options.databases) {
1274
- await controller.backupDatabase(db, parsedArgv.backupFormat || "json");
1275
- }
1276
- operationStats.backups = options.databases.length;
1277
- MessageFormatter.success(
1278
- `Backup completed for ${options.databases.length} database(s)`,
1279
- { prefix: "Backup" }
1280
- );
1281
- }
1282
-
1283
- if (
1284
- options.wipeDatabase ||
1285
- options.wipeDocumentStorage ||
1286
- options.wipeUsers ||
1287
- options.wipeCollections
1288
- ) {
1289
- // Confirm destructive operations
1290
- const databaseNames = options.databases?.map((db) => db.name) || [];
1291
- const confirmed = await ConfirmationDialogs.confirmDatabaseWipe(
1292
- databaseNames,
1293
- {
1294
- includeStorage: options.wipeDocumentStorage,
1295
- includeUsers: options.wipeUsers,
1296
- }
1297
- );
1298
-
1299
- if (!confirmed) {
1300
- MessageFormatter.info("Operation cancelled by user", { prefix: "CLI" });
1301
- return;
1302
- }
1303
-
1304
- let wipeStats = { databases: 0, collections: 0, users: 0, buckets: 0 };
1305
-
1306
- if (parsedArgv.wipe === "all") {
1307
- if (options.databases) {
1308
- for (const db of options.databases) {
1309
- await controller.wipeDatabase(db, true); // true to wipe associated buckets
1310
- }
1311
- wipeStats.databases = options.databases.length;
1312
- }
1313
- await controller.wipeUsers();
1314
- wipeStats.users = 1;
1315
- } else if (parsedArgv.wipe === "docs") {
1316
- if (options.databases) {
1317
- for (const db of options.databases) {
1318
- await controller.wipeBucketFromDatabase(db);
1319
- }
1320
- wipeStats.databases = options.databases.length;
1321
- }
1322
- if (parsedArgv.bucketIds) {
1323
- const bucketIds = parsedArgv.bucketIds.split(",");
1324
- for (const bucketId of bucketIds) {
1325
- await controller.wipeDocumentStorage(bucketId);
1326
- }
1327
- wipeStats.buckets = bucketIds.length;
1328
- }
1329
- } else if (parsedArgv.wipe === "users") {
1330
- await controller.wipeUsers();
1331
- wipeStats.users = 1;
1332
- }
1333
-
1334
- // Handle specific collection wipes
1335
- if (options.wipeCollections && options.databases) {
1336
- for (const db of options.databases) {
1337
- const dbCollections = await fetchAllCollections(
1338
- db.$id,
1339
- controller.database!
1340
- );
1341
- const collectionsToWipe = dbCollections.filter((c) =>
1342
- options.collections!.includes(c.$id)
1343
- );
1344
-
1345
- // Confirm collection wipe
1346
- const collectionNames = collectionsToWipe.map((c) => c.name);
1347
- const collectionConfirmed =
1348
- await ConfirmationDialogs.confirmCollectionWipe(
1349
- db.name,
1350
- collectionNames
1351
- );
1352
-
1353
- if (collectionConfirmed) {
1354
- for (const collection of collectionsToWipe) {
1355
- await controller.wipeCollection(db, collection);
1356
- }
1357
- wipeStats.collections += collectionsToWipe.length;
1358
- }
1359
- }
1360
- }
1361
-
1362
- // Show wipe operation summary
1363
- if (
1364
- wipeStats.databases > 0 ||
1365
- wipeStats.collections > 0 ||
1366
- wipeStats.users > 0 ||
1367
- wipeStats.buckets > 0
1368
- ) {
1369
- operationStats.wipedDatabases = wipeStats.databases;
1370
- operationStats.wipedCollections = wipeStats.collections;
1371
- operationStats.wipedUsers = wipeStats.users;
1372
- operationStats.wipedBuckets = wipeStats.buckets;
1373
- }
1374
- }
1375
-
1376
- if (parsedArgv.push) {
1377
- await controller.init();
1378
- if (!controller.database || !controller.config) {
1379
- MessageFormatter.error("Database or config not initialized", undefined, { prefix: "Push" });
1380
- return;
1381
- }
1382
-
1383
- // Fetch available DBs
1384
- const availableDatabases = await fetchAllDatabases(controller.database);
1385
- if (availableDatabases.length === 0) {
1386
- MessageFormatter.warning("No databases found in remote project", { prefix: "Push" });
1387
- return;
1388
- }
1389
-
1390
- // Determine selected DBs
1391
- let selectedDbIds: string[] = [];
1392
- if (parsedArgv.dbIds) {
1393
- selectedDbIds = parsedArgv.dbIds.split(/[,\s]+/).filter(Boolean);
1394
- } else {
1395
- selectedDbIds = await SelectionDialogs.selectDatabases(
1396
- availableDatabases,
1397
- controller.config.databases || [],
1398
- { showSelectAll: false, allowNewOnly: false, defaultSelected: [] }
1399
- );
1400
- }
1401
-
1402
- if (selectedDbIds.length === 0) {
1403
- MessageFormatter.warning("No databases selected for push", { prefix: "Push" });
1404
- return;
1405
- }
1406
-
1407
- // Build DatabaseSelection[] with tableIds per DB
1408
- const databaseSelections: DatabaseSelection[] = [];
1409
- const allConfigItems = controller.config.collections || controller.config.tables || [];
1410
- let lastSelectedTableIds: string[] | null = null;
1411
-
1412
- for (const dbId of selectedDbIds) {
1413
- const db = availableDatabases.find(d => d.$id === dbId);
1414
- if (!db) continue;
1415
-
1416
- // Filter config items eligible for this DB according to databaseId/databaseIds rule
1417
- const eligibleConfigItems = (allConfigItems as any[]).filter(item => {
1418
- const one = item.databaseId as string | undefined;
1419
- const many = item.databaseIds as string[] | undefined;
1420
- if (Array.isArray(many) && many.length > 0) return many.includes(dbId);
1421
- if (one) return one === dbId;
1422
- return true; // eligible everywhere if unspecified
1423
- });
1424
-
1425
- // Fetch available tables from remote for selection context
1426
- const availableTables = await fetchAllCollections(dbId, controller.database);
1427
-
1428
- // Determine selected table IDs
1429
- let selectedTableIds: string[] = [];
1430
- if (parsedArgv.collectionIds) {
1431
- // Non-interactive: respect provided table IDs as-is (apply to each selected DB)
1432
- selectedTableIds = parsedArgv.collectionIds.split(/[\,\s]+/).filter(Boolean);
1433
- } else {
1434
- // If we have a previous selection, offer to reuse it
1435
- if (lastSelectedTableIds && lastSelectedTableIds.length > 0) {
1436
- const inquirer = (await import("inquirer")).default;
1437
- const { reuseMode } = await inquirer.prompt([
1438
- {
1439
- type: "list",
1440
- name: "reuseMode",
1441
- message: `How do you want to select tables for ${db.name}?`,
1442
- choices: [
1443
- { name: `Use same selection as previous (${lastSelectedTableIds.length} items)`, value: "same" },
1444
- { name: `Filter by this database (manual select)`, value: "filter" },
1445
- { name: `Show all available in this database (manual select)`, value: "all" }
1446
- ],
1447
- default: "same"
1448
- }
1449
- ]);
1450
-
1451
- if (reuseMode === "same") {
1452
- selectedTableIds = [...lastSelectedTableIds];
1453
- } else if (reuseMode === "all") {
1454
- selectedTableIds = await SelectionDialogs.selectTablesForDatabase(
1455
- dbId,
1456
- db.name,
1457
- availableTables,
1458
- allConfigItems as any[],
1459
- { showSelectAll: false, allowNewOnly: false, defaultSelected: lastSelectedTableIds }
1460
- );
1461
- } else {
1462
- selectedTableIds = await SelectionDialogs.selectTablesForDatabase(
1463
- dbId,
1464
- db.name,
1465
- availableTables,
1466
- eligibleConfigItems,
1467
- { showSelectAll: false, allowNewOnly: true, defaultSelected: lastSelectedTableIds }
1468
- );
1469
- }
1470
- } else {
1471
- selectedTableIds = await SelectionDialogs.selectTablesForDatabase(
1472
- dbId,
1473
- db.name,
1474
- availableTables,
1475
- eligibleConfigItems,
1476
- { showSelectAll: false, allowNewOnly: true, defaultSelected: [] }
1477
- );
1478
- }
1479
- }
1480
-
1481
- databaseSelections.push({
1482
- databaseId: db.$id,
1483
- databaseName: db.name,
1484
- tableIds: selectedTableIds,
1485
- tableNames: [],
1486
- isNew: false,
1487
- });
1488
- if (!parsedArgv.collectionIds) {
1489
- lastSelectedTableIds = selectedTableIds;
1490
- }
1491
- }
1492
-
1493
- if (databaseSelections.every(sel => sel.tableIds.length === 0)) {
1494
- MessageFormatter.warning("No tables/collections selected for push", { prefix: "Push" });
1495
- return;
1496
- }
1497
-
1498
- const pushSummary: Record<string, string | number | string[]> = {
1499
- databases: databaseSelections.length,
1500
- collections: databaseSelections.reduce((sum, s) => sum + s.tableIds.length, 0),
1501
- details: databaseSelections.map(s => `${s.databaseId}: ${s.tableIds.length} items`),
1502
- };
1503
- // Skip confirmation if both dbIds and collectionIds are provided (non-interactive)
1504
- if (!(parsedArgv.dbIds && parsedArgv.collectionIds)) {
1505
- const confirmed = await ConfirmationDialogs.showOperationSummary('Push', pushSummary, { confirmationRequired: true });
1506
- if (!confirmed) {
1507
- MessageFormatter.info("Push operation cancelled", { prefix: "Push" });
1508
- return;
1509
- }
1510
- }
1511
-
1512
- await controller.selectivePush(databaseSelections, []);
1513
- operationStats.pushedDatabases = databaseSelections.length;
1514
- operationStats.pushedCollections = databaseSelections.reduce((sum, s) => sum + s.tableIds.length, 0);
1515
- } else if (parsedArgv.sync) {
1516
- // Enhanced SYNC: Pull from remote with intelligent configuration detection
1517
- if (parsedArgv.autoSync) {
1518
- // Legacy behavior: sync everything without prompts
1519
- MessageFormatter.info("Using auto-sync mode (legacy behavior)", { prefix: "Sync" });
1520
- const databases =
1521
- options.databases || (await fetchAllDatabases(controller.database!));
1522
- await controller.synchronizeConfigurations(databases);
1523
- operationStats.syncedDatabases = databases.length;
1524
- } else {
1525
- // Enhanced sync flow with selection dialogs
1526
- const syncResult = await performEnhancedSync(controller, parsedArgv);
1527
- if (syncResult) {
1528
- operationStats.syncedDatabases = syncResult.databases.length;
1529
- operationStats.syncedCollections = syncResult.totalTables;
1530
- operationStats.syncedBuckets = syncResult.buckets.length;
1531
- }
1532
- }
1533
- }
1534
-
1535
- if (options.generateSchemas) {
1536
- await controller.generateSchemas();
1537
- operationStats.generatedSchemas = 1;
1538
- }
1539
-
1540
- if (options.importData) {
1541
- await controller.importData(options);
1542
- operationStats.importCompleted = 1;
1543
- }
1544
-
1545
- if (parsedArgv.transfer) {
1546
- const isRemote = !!parsedArgv.remoteEndpoint;
1547
- let fromDb, toDb: Models.Database | undefined;
1548
- let targetDatabases: Databases | undefined;
1549
- let targetStorage: Storage | undefined;
1550
-
1551
- // Only fetch databases if database IDs are provided
1552
- if (parsedArgv.fromDbId && parsedArgv.toDbId) {
1553
- MessageFormatter.info(
1554
- `Starting database transfer from ${parsedArgv.fromDbId} to ${parsedArgv.toDbId}`,
1555
- { prefix: "Transfer" }
1556
- );
1557
- fromDb = (
1558
- await controller.getDatabasesByIds([parsedArgv.fromDbId])
1559
- )?.[0];
1560
- if (!fromDb) {
1561
- MessageFormatter.error("Source database not found", undefined, {
1562
- prefix: "Transfer",
1563
- });
1564
- return;
1565
- }
1566
- if (isRemote) {
1567
- if (
1568
- !parsedArgv.remoteEndpoint ||
1569
- !parsedArgv.remoteProjectId ||
1570
- !parsedArgv.remoteApiKey
1571
- ) {
1572
- throw new Error("Remote transfer details are missing");
1573
- }
1574
- const remoteClient = getClient(
1575
- parsedArgv.remoteEndpoint,
1576
- parsedArgv.remoteProjectId,
1577
- parsedArgv.remoteApiKey
1578
- );
1579
- targetDatabases = new Databases(remoteClient);
1580
- targetStorage = new Storage(remoteClient);
1581
- const remoteDbs = await fetchAllDatabases(targetDatabases);
1582
- toDb = remoteDbs.find((db) => db.$id === parsedArgv.toDbId);
1583
- if (!toDb) {
1584
- MessageFormatter.error("Target database not found", undefined, {
1585
- prefix: "Transfer",
1586
- });
1587
- return;
1588
- }
1589
- } else {
1590
- toDb = (await controller.getDatabasesByIds([parsedArgv.toDbId]))?.[0];
1591
- if (!toDb) {
1592
- MessageFormatter.error("Target database not found", undefined, {
1593
- prefix: "Transfer",
1594
- });
1595
- return;
1596
- }
1597
- }
1598
-
1599
- if (!fromDb || !toDb) {
1600
- MessageFormatter.error(
1601
- "Source or target database not found",
1602
- undefined,
1603
- { prefix: "Transfer" }
1604
- );
1605
- return;
1606
- }
1607
- }
1608
-
1609
- // Handle storage setup
1610
- let sourceBucket, targetBucket;
1611
- if (parsedArgv.fromBucketId) {
1612
- sourceBucket = await controller.storage?.getBucket(
1613
- parsedArgv.fromBucketId
1614
- );
1615
- }
1616
- if (parsedArgv.toBucketId) {
1617
- if (isRemote) {
1618
- if (!targetStorage) {
1619
- const remoteClient = getClient(
1620
- parsedArgv.remoteEndpoint!,
1621
- parsedArgv.remoteProjectId!,
1622
- parsedArgv.remoteApiKey!
1623
- );
1624
- targetStorage = new Storage(remoteClient);
1625
- }
1626
- targetBucket = await targetStorage?.getBucket(parsedArgv.toBucketId);
1627
- } else {
1628
- targetBucket = await controller.storage?.getBucket(
1629
- parsedArgv.toBucketId
1630
- );
1631
- }
1632
- }
1633
-
1634
- // Validate that at least one transfer type is specified
1635
- if (!fromDb && !sourceBucket && !options.transferUsers) {
1636
- throw new Error("No source database or bucket specified for transfer");
1637
- }
1638
-
1639
- const transferOptions: TransferOptions = {
1640
- isRemote,
1641
- fromDb,
1642
- targetDb: toDb,
1643
- transferEndpoint: parsedArgv.remoteEndpoint,
1644
- transferProject: parsedArgv.remoteProjectId,
1645
- transferKey: parsedArgv.remoteApiKey,
1646
- sourceBucket: sourceBucket,
1647
- targetBucket: targetBucket,
1648
- transferUsers: options.transferUsers,
1649
- };
1650
-
1651
- await controller.transferData(transferOptions);
1652
- operationStats.transfers = 1;
1653
- }
1654
-
1655
- // Show final operation summary if any operations were performed
1656
- if (Object.keys(operationStats).length > 0) {
1657
- const duration = Date.now() - startTime;
1658
- MessageFormatter.operationSummary(
1659
- "CLI Operations",
1660
- operationStats,
1661
- duration
1662
- );
1663
- }
1664
- }
1665
- }
1666
-
1667
- main().catch((error) => {
1668
- MessageFormatter.error("CLI execution failed", error, { prefix: "CLI" });
1669
- process.exit(1);
1670
- });