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