@njdamstra/appwrite-utils-cli 1.8.9

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