appwrite-utils-cli 1.5.1 → 1.6.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 (233) hide show
  1. package/CHANGELOG.md +199 -0
  2. package/README.md +251 -29
  3. package/dist/adapters/AdapterFactory.d.ts +10 -3
  4. package/dist/adapters/AdapterFactory.js +213 -17
  5. package/dist/adapters/TablesDBAdapter.js +60 -17
  6. package/dist/backups/operations/bucketBackup.d.ts +19 -0
  7. package/dist/backups/operations/bucketBackup.js +197 -0
  8. package/dist/backups/operations/collectionBackup.d.ts +30 -0
  9. package/dist/backups/operations/collectionBackup.js +201 -0
  10. package/dist/backups/operations/comprehensiveBackup.d.ts +25 -0
  11. package/dist/backups/operations/comprehensiveBackup.js +238 -0
  12. package/dist/backups/schemas/bucketManifest.d.ts +93 -0
  13. package/dist/backups/schemas/bucketManifest.js +33 -0
  14. package/dist/backups/schemas/comprehensiveManifest.d.ts +108 -0
  15. package/dist/backups/schemas/comprehensiveManifest.js +32 -0
  16. package/dist/backups/tracking/centralizedTracking.d.ts +34 -0
  17. package/dist/backups/tracking/centralizedTracking.js +274 -0
  18. package/dist/cli/commands/configCommands.d.ts +8 -0
  19. package/dist/cli/commands/configCommands.js +160 -0
  20. package/dist/cli/commands/databaseCommands.d.ts +13 -0
  21. package/dist/cli/commands/databaseCommands.js +478 -0
  22. package/dist/cli/commands/functionCommands.d.ts +7 -0
  23. package/dist/cli/commands/functionCommands.js +289 -0
  24. package/dist/cli/commands/schemaCommands.d.ts +7 -0
  25. package/dist/cli/commands/schemaCommands.js +134 -0
  26. package/dist/cli/commands/transferCommands.d.ts +5 -0
  27. package/dist/cli/commands/transferCommands.js +384 -0
  28. package/dist/collections/attributes.d.ts +5 -4
  29. package/dist/collections/attributes.js +539 -246
  30. package/dist/collections/indexes.js +39 -37
  31. package/dist/collections/methods.d.ts +2 -16
  32. package/dist/collections/methods.js +90 -538
  33. package/dist/collections/transferOperations.d.ts +7 -0
  34. package/dist/collections/transferOperations.js +331 -0
  35. package/dist/collections/wipeOperations.d.ts +16 -0
  36. package/dist/collections/wipeOperations.js +328 -0
  37. package/dist/config/configMigration.d.ts +87 -0
  38. package/dist/config/configMigration.js +390 -0
  39. package/dist/config/configValidation.d.ts +66 -0
  40. package/dist/config/configValidation.js +358 -0
  41. package/dist/config/yamlConfig.d.ts +455 -1
  42. package/dist/config/yamlConfig.js +145 -52
  43. package/dist/databases/methods.js +3 -2
  44. package/dist/databases/setup.d.ts +1 -2
  45. package/dist/databases/setup.js +9 -87
  46. package/dist/examples/yamlTerminologyExample.d.ts +42 -0
  47. package/dist/examples/yamlTerminologyExample.js +269 -0
  48. package/dist/functions/deployments.js +11 -10
  49. package/dist/functions/methods.d.ts +1 -1
  50. package/dist/functions/methods.js +5 -4
  51. package/dist/init.js +9 -9
  52. package/dist/interactiveCLI.d.ts +8 -17
  53. package/dist/interactiveCLI.js +186 -1171
  54. package/dist/main.js +364 -21
  55. package/dist/migrations/afterImportActions.js +22 -30
  56. package/dist/migrations/appwriteToX.js +71 -25
  57. package/dist/migrations/dataLoader.js +35 -26
  58. package/dist/migrations/importController.js +29 -30
  59. package/dist/migrations/relationships.js +13 -12
  60. package/dist/migrations/services/ImportOrchestrator.js +16 -19
  61. package/dist/migrations/transfer.js +46 -46
  62. package/dist/migrations/yaml/YamlImportConfigLoader.d.ts +3 -1
  63. package/dist/migrations/yaml/YamlImportConfigLoader.js +6 -3
  64. package/dist/migrations/yaml/YamlImportIntegration.d.ts +9 -3
  65. package/dist/migrations/yaml/YamlImportIntegration.js +22 -11
  66. package/dist/migrations/yaml/generateImportSchemas.d.ts +14 -1
  67. package/dist/migrations/yaml/generateImportSchemas.js +736 -7
  68. package/dist/schemas/authUser.d.ts +1 -1
  69. package/dist/setupController.js +3 -2
  70. package/dist/shared/backupMetadataSchema.d.ts +94 -0
  71. package/dist/shared/backupMetadataSchema.js +38 -0
  72. package/dist/shared/backupTracking.d.ts +18 -0
  73. package/dist/shared/backupTracking.js +176 -0
  74. package/dist/shared/confirmationDialogs.js +15 -15
  75. package/dist/shared/errorUtils.d.ts +54 -0
  76. package/dist/shared/errorUtils.js +95 -0
  77. package/dist/shared/functionManager.js +20 -19
  78. package/dist/shared/indexManager.js +12 -11
  79. package/dist/shared/jsonSchemaGenerator.js +10 -26
  80. package/dist/shared/logging.d.ts +51 -0
  81. package/dist/shared/logging.js +70 -0
  82. package/dist/shared/messageFormatter.d.ts +2 -0
  83. package/dist/shared/messageFormatter.js +10 -0
  84. package/dist/shared/migrationHelpers.d.ts +6 -16
  85. package/dist/shared/migrationHelpers.js +24 -21
  86. package/dist/shared/operationLogger.d.ts +8 -1
  87. package/dist/shared/operationLogger.js +11 -24
  88. package/dist/shared/operationQueue.d.ts +28 -1
  89. package/dist/shared/operationQueue.js +268 -66
  90. package/dist/shared/operationsTable.d.ts +26 -0
  91. package/dist/shared/operationsTable.js +286 -0
  92. package/dist/shared/operationsTableSchema.d.ts +48 -0
  93. package/dist/shared/operationsTableSchema.js +35 -0
  94. package/dist/shared/relationshipExtractor.d.ts +56 -0
  95. package/dist/shared/relationshipExtractor.js +138 -0
  96. package/dist/shared/schemaGenerator.d.ts +19 -1
  97. package/dist/shared/schemaGenerator.js +56 -75
  98. package/dist/storage/backupCompression.d.ts +20 -0
  99. package/dist/storage/backupCompression.js +67 -0
  100. package/dist/storage/methods.d.ts +16 -2
  101. package/dist/storage/methods.js +98 -14
  102. package/dist/users/methods.js +9 -8
  103. package/dist/utils/configDiscovery.d.ts +78 -0
  104. package/dist/utils/configDiscovery.js +430 -0
  105. package/dist/utils/directoryUtils.d.ts +22 -0
  106. package/dist/utils/directoryUtils.js +59 -0
  107. package/dist/utils/getClientFromConfig.d.ts +17 -8
  108. package/dist/utils/getClientFromConfig.js +162 -17
  109. package/dist/utils/helperFunctions.d.ts +16 -2
  110. package/dist/utils/helperFunctions.js +19 -5
  111. package/dist/utils/loadConfigs.d.ts +34 -9
  112. package/dist/utils/loadConfigs.js +236 -316
  113. package/dist/utils/pathResolvers.d.ts +53 -0
  114. package/dist/utils/pathResolvers.js +72 -0
  115. package/dist/utils/projectConfig.d.ts +119 -0
  116. package/dist/utils/projectConfig.js +171 -0
  117. package/dist/utils/retryFailedPromises.js +4 -2
  118. package/dist/utils/sessionAuth.d.ts +48 -0
  119. package/dist/utils/sessionAuth.js +164 -0
  120. package/dist/utils/sessionPreservationExample.d.ts +1666 -0
  121. package/dist/utils/sessionPreservationExample.js +101 -0
  122. package/dist/utils/setupFiles.js +301 -41
  123. package/dist/utils/typeGuards.d.ts +35 -0
  124. package/dist/utils/typeGuards.js +57 -0
  125. package/dist/utils/versionDetection.js +145 -9
  126. package/dist/utils/yamlConverter.d.ts +53 -3
  127. package/dist/utils/yamlConverter.js +232 -13
  128. package/dist/utils/yamlLoader.d.ts +70 -0
  129. package/dist/utils/yamlLoader.js +263 -0
  130. package/dist/utilsController.d.ts +36 -3
  131. package/dist/utilsController.js +186 -56
  132. package/package.json +12 -2
  133. package/src/adapters/AdapterFactory.ts +263 -35
  134. package/src/adapters/TablesDBAdapter.ts +225 -36
  135. package/src/backups/operations/bucketBackup.ts +277 -0
  136. package/src/backups/operations/collectionBackup.ts +310 -0
  137. package/src/backups/operations/comprehensiveBackup.ts +342 -0
  138. package/src/backups/schemas/bucketManifest.ts +78 -0
  139. package/src/backups/schemas/comprehensiveManifest.ts +76 -0
  140. package/src/backups/tracking/centralizedTracking.ts +352 -0
  141. package/src/cli/commands/configCommands.ts +194 -0
  142. package/src/cli/commands/databaseCommands.ts +635 -0
  143. package/src/cli/commands/functionCommands.ts +379 -0
  144. package/src/cli/commands/schemaCommands.ts +163 -0
  145. package/src/cli/commands/transferCommands.ts +457 -0
  146. package/src/collections/attributes.ts +900 -621
  147. package/src/collections/attributes.ts.backup +1555 -0
  148. package/src/collections/indexes.ts +116 -114
  149. package/src/collections/methods.ts +295 -968
  150. package/src/collections/transferOperations.ts +516 -0
  151. package/src/collections/wipeOperations.ts +501 -0
  152. package/src/config/README.md +274 -0
  153. package/src/config/configMigration.ts +575 -0
  154. package/src/config/configValidation.ts +445 -0
  155. package/src/config/yamlConfig.ts +168 -55
  156. package/src/databases/methods.ts +3 -2
  157. package/src/databases/setup.ts +11 -138
  158. package/src/examples/yamlTerminologyExample.ts +341 -0
  159. package/src/functions/deployments.ts +14 -12
  160. package/src/functions/methods.ts +11 -11
  161. package/src/functions/templates/hono-typescript/README.md +286 -0
  162. package/src/functions/templates/hono-typescript/package.json +26 -0
  163. package/src/functions/templates/hono-typescript/src/adapters/request.ts +74 -0
  164. package/src/functions/templates/hono-typescript/src/adapters/response.ts +106 -0
  165. package/src/functions/templates/hono-typescript/src/app.ts +180 -0
  166. package/src/functions/templates/hono-typescript/src/context.ts +103 -0
  167. package/src/functions/templates/hono-typescript/src/index.ts +54 -0
  168. package/src/functions/templates/hono-typescript/src/middleware/appwrite.ts +119 -0
  169. package/src/functions/templates/hono-typescript/tsconfig.json +20 -0
  170. package/src/functions/templates/typescript-node/package.json +2 -1
  171. package/src/functions/templates/typescript-node/src/context.ts +103 -0
  172. package/src/functions/templates/typescript-node/src/index.ts +18 -12
  173. package/src/functions/templates/uv/pyproject.toml +1 -0
  174. package/src/functions/templates/uv/src/context.py +125 -0
  175. package/src/functions/templates/uv/src/index.py +35 -5
  176. package/src/init.ts +9 -11
  177. package/src/interactiveCLI.ts +276 -1591
  178. package/src/main.ts +418 -24
  179. package/src/migrations/afterImportActions.ts +71 -44
  180. package/src/migrations/appwriteToX.ts +100 -34
  181. package/src/migrations/dataLoader.ts +48 -34
  182. package/src/migrations/importController.ts +44 -39
  183. package/src/migrations/relationships.ts +28 -18
  184. package/src/migrations/services/ImportOrchestrator.ts +24 -27
  185. package/src/migrations/transfer.ts +159 -121
  186. package/src/migrations/yaml/YamlImportConfigLoader.ts +11 -4
  187. package/src/migrations/yaml/YamlImportIntegration.ts +47 -20
  188. package/src/migrations/yaml/generateImportSchemas.ts +751 -12
  189. package/src/setupController.ts +3 -2
  190. package/src/shared/backupMetadataSchema.ts +93 -0
  191. package/src/shared/backupTracking.ts +211 -0
  192. package/src/shared/confirmationDialogs.ts +19 -19
  193. package/src/shared/errorUtils.ts +110 -0
  194. package/src/shared/functionManager.ts +21 -20
  195. package/src/shared/indexManager.ts +12 -11
  196. package/src/shared/jsonSchemaGenerator.ts +38 -52
  197. package/src/shared/logging.ts +75 -0
  198. package/src/shared/messageFormatter.ts +14 -1
  199. package/src/shared/migrationHelpers.ts +45 -38
  200. package/src/shared/operationLogger.ts +11 -36
  201. package/src/shared/operationQueue.ts +322 -93
  202. package/src/shared/operationsTable.ts +338 -0
  203. package/src/shared/operationsTableSchema.ts +60 -0
  204. package/src/shared/relationshipExtractor.ts +214 -0
  205. package/src/shared/schemaGenerator.ts +179 -219
  206. package/src/storage/backupCompression.ts +88 -0
  207. package/src/storage/methods.ts +131 -34
  208. package/src/users/methods.ts +11 -9
  209. package/src/utils/configDiscovery.ts +502 -0
  210. package/src/utils/directoryUtils.ts +61 -0
  211. package/src/utils/getClientFromConfig.ts +205 -22
  212. package/src/utils/helperFunctions.ts +23 -5
  213. package/src/utils/loadConfigs.ts +313 -345
  214. package/src/utils/pathResolvers.ts +81 -0
  215. package/src/utils/projectConfig.ts +299 -0
  216. package/src/utils/retryFailedPromises.ts +4 -2
  217. package/src/utils/sessionAuth.ts +230 -0
  218. package/src/utils/setupFiles.ts +322 -54
  219. package/src/utils/typeGuards.ts +65 -0
  220. package/src/utils/versionDetection.ts +218 -64
  221. package/src/utils/yamlConverter.ts +296 -13
  222. package/src/utils/yamlLoader.ts +364 -0
  223. package/src/utilsController.ts +314 -110
  224. package/tests/README.md +497 -0
  225. package/tests/adapters/AdapterFactory.test.ts +277 -0
  226. package/tests/integration/syncOperations.test.ts +463 -0
  227. package/tests/jest.config.js +25 -0
  228. package/tests/migration/configMigration.test.ts +546 -0
  229. package/tests/setup.ts +62 -0
  230. package/tests/testUtils.ts +340 -0
  231. package/tests/utils/loadConfigs.test.ts +350 -0
  232. package/tests/validation/configValidation.test.ts +412 -0
  233. package/src/utils/schemaStrings.ts +0 -517
@@ -0,0 +1,635 @@
1
+ import inquirer from "inquirer";
2
+ import chalk from "chalk";
3
+ import { join } from "node:path";
4
+ import { MessageFormatter } from "../../shared/messageFormatter.js";
5
+ import { ConfirmationDialogs } from "../../shared/confirmationDialogs.js";
6
+ import { fetchAllDatabases } from "../../databases/methods.js";
7
+ import { listBuckets } from "../../storage/methods.js";
8
+ import { getFunction, downloadLatestFunctionDeployment } from "../../functions/methods.js";
9
+ import type { InteractiveCLI } from "../../interactiveCLI.js";
10
+
11
+ export const databaseCommands = {
12
+ async syncDb(cli: InteractiveCLI): Promise<void> {
13
+ MessageFormatter.progress("Pushing local configuration to Appwrite...", { prefix: "Database" });
14
+
15
+ const databases = await (cli as any).selectDatabases(
16
+ (cli as any).getLocalDatabases(),
17
+ chalk.blue("Select local databases to push:"),
18
+ true
19
+ );
20
+
21
+ if (!databases.length) {
22
+ MessageFormatter.warning("No databases selected. Skipping database sync.", { prefix: "Database" });
23
+ return;
24
+ }
25
+
26
+ const collections = await (cli as any).selectCollectionsAndTables(
27
+ databases[0],
28
+ (cli as any).controller!.database!,
29
+ chalk.blue("Select local collections/tables to push:"),
30
+ true,
31
+ true, // prefer local
32
+ true // filter by selected database
33
+ );
34
+
35
+ const { syncFunctions } = await inquirer.prompt([
36
+ {
37
+ type: "confirm",
38
+ name: "syncFunctions",
39
+ message: "Do you want to push local functions to remote?",
40
+ default: false,
41
+ },
42
+ ]);
43
+
44
+ try {
45
+ // First sync databases and collections
46
+ await (cli as any).controller!.syncDb(databases, collections);
47
+ MessageFormatter.success("Database and collections pushed successfully", { prefix: "Database" });
48
+
49
+ // Then handle functions if requested
50
+ if (syncFunctions && (cli as any).controller!.config?.functions?.length) {
51
+ const functions = await (cli as any).selectFunctions(
52
+ chalk.blue("Select local functions to push:"),
53
+ true,
54
+ true // prefer local
55
+ );
56
+
57
+ for (const func of functions) {
58
+ try {
59
+ await (cli as any).controller!.deployFunction(func.name);
60
+ MessageFormatter.success(`Function ${func.name} deployed successfully`, { prefix: "Functions" });
61
+ } catch (error) {
62
+ MessageFormatter.error(`Failed to deploy function ${func.name}`, error instanceof Error ? error : new Error(String(error)), { prefix: "Functions" });
63
+ }
64
+ }
65
+ }
66
+
67
+ MessageFormatter.success("Local configuration push completed successfully!", { prefix: "Database" });
68
+ } catch (error) {
69
+ MessageFormatter.error("Failed to push local configuration", error instanceof Error ? error : new Error(String(error)), { prefix: "Database" });
70
+ throw error;
71
+ }
72
+ },
73
+
74
+ async synchronizeConfigurations(cli: InteractiveCLI): Promise<void> {
75
+ MessageFormatter.progress("Synchronizing configurations...", { prefix: "Config" });
76
+ await (cli as any).controller!.init();
77
+
78
+ // Sync databases, collections, and buckets
79
+ const { syncDatabases } = await inquirer.prompt([
80
+ {
81
+ type: "confirm",
82
+ name: "syncDatabases",
83
+ message: "Do you want to synchronize databases, collections, and their buckets?",
84
+ default: true,
85
+ },
86
+ ]);
87
+
88
+ if (syncDatabases) {
89
+ const remoteDatabases = await fetchAllDatabases(
90
+ (cli as any).controller!.database!
91
+ );
92
+
93
+ // Use the controller's synchronizeConfigurations method which handles collections properly
94
+ MessageFormatter.progress("Pulling collections and generating collection files...", { prefix: "Collections" });
95
+ await (cli as any).controller!.synchronizeConfigurations(remoteDatabases);
96
+
97
+ // Also configure buckets for any new databases
98
+ const localDatabases = (cli as any).controller!.config?.databases || [];
99
+ const updatedConfig = await (cli as any).configureBuckets({
100
+ ...(cli as any).controller!.config!,
101
+ databases: [
102
+ ...localDatabases,
103
+ ...remoteDatabases.filter(
104
+ (rd: any) => !localDatabases.some((ld: any) => ld.name === rd.name)
105
+ ),
106
+ ],
107
+ });
108
+
109
+ (cli as any).controller!.config = updatedConfig;
110
+ }
111
+
112
+ // Then sync functions
113
+ const { syncFunctions } = await inquirer.prompt([
114
+ {
115
+ type: "confirm",
116
+ name: "syncFunctions",
117
+ message: "Do you want to synchronize functions?",
118
+ default: true,
119
+ },
120
+ ]);
121
+
122
+ if (syncFunctions) {
123
+ const remoteFunctions = await (cli as any).controller!.listAllFunctions();
124
+ const localFunctions = (cli as any).controller!.config?.functions || [];
125
+
126
+ const allFunctions = [
127
+ ...remoteFunctions,
128
+ ...localFunctions.filter(
129
+ (f: any) => !remoteFunctions.some((rf: any) => rf.$id === f.$id)
130
+ ),
131
+ ];
132
+
133
+ for (const func of allFunctions) {
134
+ const hasLocal = localFunctions.some((lf: any) => lf.$id === func.$id);
135
+ const hasRemote = remoteFunctions.some((rf: any) => rf.$id === func.$id);
136
+
137
+ if (hasLocal && hasRemote) {
138
+ // Function exists in both local and remote
139
+ const { preference } = await inquirer.prompt([
140
+ {
141
+ type: "list",
142
+ name: "preference",
143
+ message: `Function "${func.name}" exists both locally and remotely. What would you like to do?`,
144
+ choices: [
145
+ { name: "Keep local version (deploy to remote)", value: "local" },
146
+ { name: "Use remote version (download)", value: "remote" },
147
+ { name: "Update config only", value: "config" },
148
+ { name: "Skip this function", value: "skip" },
149
+ ],
150
+ },
151
+ ]);
152
+
153
+ if (preference === "local") {
154
+ await (cli as any).controller!.deployFunction(func.name);
155
+ } else if (preference === "remote") {
156
+ await downloadLatestFunctionDeployment(
157
+ (cli as any).controller!.appwriteServer!,
158
+ func.$id,
159
+ join((cli as any).controller!.getAppwriteFolderPath()!, "functions")
160
+ );
161
+ } else if (preference === "config") {
162
+ // Update config with remote function details
163
+ const remoteFunction = await getFunction(
164
+ (cli as any).controller!.appwriteServer!,
165
+ func.$id
166
+ );
167
+
168
+ const newFunction = {
169
+ $id: remoteFunction.$id,
170
+ name: remoteFunction.name,
171
+ runtime: remoteFunction.runtime,
172
+ execute: remoteFunction.execute || [],
173
+ events: remoteFunction.events || [],
174
+ schedule: remoteFunction.schedule || "",
175
+ timeout: remoteFunction.timeout || 15,
176
+ enabled: remoteFunction.enabled !== false,
177
+ logging: remoteFunction.logging !== false,
178
+ entrypoint: remoteFunction.entrypoint || "src/index.ts",
179
+ commands: remoteFunction.commands || "npm install",
180
+ scopes: remoteFunction.scopes || [],
181
+ installationId: remoteFunction.installationId,
182
+ providerRepositoryId: remoteFunction.providerRepositoryId,
183
+ providerBranch: remoteFunction.providerBranch,
184
+ providerSilentMode: remoteFunction.providerSilentMode,
185
+ providerRootDirectory: remoteFunction.providerRootDirectory,
186
+ specification: remoteFunction.specification,
187
+ };
188
+
189
+ const existingIndex = (cli as any).controller!.config!.functions!.findIndex(
190
+ (f: any) => f.$id === remoteFunction.$id
191
+ );
192
+
193
+ if (existingIndex >= 0) {
194
+ (cli as any).controller!.config!.functions![existingIndex] = newFunction;
195
+ } else {
196
+ (cli as any).controller!.config!.functions!.push(newFunction);
197
+ }
198
+ MessageFormatter.success(`Updated config for function: ${func.name}`, { prefix: "Functions" });
199
+ }
200
+ } else if (hasLocal) {
201
+ // Function exists only locally
202
+ const { action } = await inquirer.prompt([
203
+ {
204
+ type: "list",
205
+ name: "action",
206
+ message: `Function "${func.name}" exists only locally. What would you like to do?`,
207
+ choices: [
208
+ { name: "Deploy to remote", value: "deploy" },
209
+ { name: "Skip this function", value: "skip" },
210
+ ],
211
+ },
212
+ ]);
213
+
214
+ if (action === "deploy") {
215
+ await (cli as any).controller!.deployFunction(func.name);
216
+ }
217
+ } else if (hasRemote) {
218
+ // Function exists only remotely
219
+ const { action } = await inquirer.prompt([
220
+ {
221
+ type: "list",
222
+ name: "action",
223
+ message: `Function "${func.name}" exists only remotely. What would you like to do?`,
224
+ choices: [
225
+ { name: "Update config only", value: "config" },
226
+ { name: "Download locally", value: "download" },
227
+ { name: "Skip this function", value: "skip" },
228
+ ],
229
+ },
230
+ ]);
231
+
232
+ if (action === "download") {
233
+ await downloadLatestFunctionDeployment(
234
+ (cli as any).controller!.appwriteServer!,
235
+ func.$id,
236
+ join((cli as any).controller!.getAppwriteFolderPath()!, "functions")
237
+ );
238
+ } else if (action === "config") {
239
+ const remoteFunction = await getFunction(
240
+ (cli as any).controller!.appwriteServer!,
241
+ func.$id
242
+ );
243
+
244
+ const newFunction = {
245
+ $id: remoteFunction.$id,
246
+ name: remoteFunction.name,
247
+ runtime: remoteFunction.runtime,
248
+ execute: remoteFunction.execute || [],
249
+ events: remoteFunction.events || [],
250
+ schedule: remoteFunction.schedule || "",
251
+ timeout: remoteFunction.timeout || 15,
252
+ enabled: remoteFunction.enabled !== false,
253
+ logging: remoteFunction.logging !== false,
254
+ entrypoint: remoteFunction.entrypoint || "src/index.ts",
255
+ commands: remoteFunction.commands || "npm install",
256
+ scopes: remoteFunction.scopes || [],
257
+ installationId: remoteFunction.installationId,
258
+ providerRepositoryId: remoteFunction.providerRepositoryId,
259
+ providerBranch: remoteFunction.providerBranch,
260
+ providerSilentMode: remoteFunction.providerSilentMode,
261
+ providerRootDirectory: remoteFunction.providerRootDirectory,
262
+ specification: remoteFunction.specification,
263
+ };
264
+
265
+ (cli as any).controller!.config!.functions =
266
+ (cli as any).controller!.config!.functions || [];
267
+ (cli as any).controller!.config!.functions.push(newFunction);
268
+ MessageFormatter.success(`Added config for remote function: ${func.name}`, { prefix: "Functions" });
269
+ }
270
+ }
271
+ }
272
+ }
273
+
274
+ MessageFormatter.success("✨ Configurations synchronized successfully!", { prefix: "Config" });
275
+ },
276
+
277
+ async backupDatabase(cli: InteractiveCLI): Promise<void> {
278
+ if (!(cli as any).controller!.database || !(cli as any).controller!.storage) {
279
+ throw new Error(
280
+ "Database or Storage is not initialized, is the config file correct & created?"
281
+ );
282
+ }
283
+
284
+ try {
285
+ // STEP 1: Select tracking database
286
+ MessageFormatter.info("Step 1/5: Select tracking database", { prefix: "Backup" });
287
+ const trackingDb = await this.selectTrackingDatabase(cli);
288
+
289
+ // STEP 2: Ensure backup tracking table exists
290
+ MessageFormatter.info("Step 2/5: Initializing backup tracking", { prefix: "Backup" });
291
+ await this.ensureBackupTrackingTable(cli, trackingDb);
292
+
293
+ // STEP 3: Select backup scope
294
+ MessageFormatter.info("Step 3/5: Select backup scope", { prefix: "Backup" });
295
+ const scope = await this.selectBackupScope(cli);
296
+
297
+ // STEP 4: Show confirmation
298
+ MessageFormatter.info("Step 4/5: Confirm backup plan", { prefix: "Backup" });
299
+ const confirmed = await this.confirmBackupPlan(scope);
300
+ if (!confirmed) {
301
+ MessageFormatter.info("Backup cancelled by user", { prefix: "Backup" });
302
+ return;
303
+ }
304
+
305
+ // STEP 5: Execute unified backup
306
+ MessageFormatter.info("Step 5/5: Executing backup", { prefix: "Backup" });
307
+ await this.executeUnifiedBackup(cli, trackingDb, scope);
308
+
309
+ MessageFormatter.success("Backup operation completed successfully", { prefix: "Backup" });
310
+ } catch (error) {
311
+ MessageFormatter.error(
312
+ "Backup operation failed",
313
+ error instanceof Error ? error : new Error(String(error)),
314
+ { prefix: "Backup" }
315
+ );
316
+ throw error;
317
+ }
318
+ },
319
+
320
+ // Helper method: Select tracking database
321
+ async selectTrackingDatabase(cli: InteractiveCLI): Promise<string> {
322
+ const databases = await fetchAllDatabases((cli as any).controller!.database);
323
+
324
+ const { trackingDatabaseId } = await inquirer.prompt([
325
+ {
326
+ type: "list",
327
+ name: "trackingDatabaseId",
328
+ message: "Select database to store backup metadata:",
329
+ choices: databases.map(db => ({
330
+ name: `${db.name} (${db.$id})`,
331
+ value: db.$id
332
+ }))
333
+ }
334
+ ]);
335
+
336
+ MessageFormatter.info(`Using ${trackingDatabaseId} for backup tracking`, { prefix: "Backup" });
337
+ return trackingDatabaseId;
338
+ },
339
+
340
+ // Helper method: Ensure backup tracking table exists
341
+ async ensureBackupTrackingTable(cli: InteractiveCLI, trackingDatabaseId: string): Promise<void> {
342
+ const { createCentralizedBackupTrackingTable } = await import("../../backups/tracking/centralizedTracking.js");
343
+ const adapter = (cli as any).controller!.adapter;
344
+
345
+ await createCentralizedBackupTrackingTable(adapter, trackingDatabaseId);
346
+ MessageFormatter.success("Backup tracking table ready", { prefix: "Backup" });
347
+ },
348
+
349
+ // Helper method: Select backup scope
350
+ async selectBackupScope(cli: InteractiveCLI): Promise<any> {
351
+ const { scopeType } = await inquirer.prompt([
352
+ {
353
+ type: "list",
354
+ name: "scopeType",
355
+ message: "What would you like to backup?",
356
+ choices: [
357
+ { name: "Comprehensive (ALL databases + ALL buckets)", value: "comprehensive" },
358
+ { name: "Selective databases (choose specific databases)", value: "selective-databases" },
359
+ { name: "Selective collections (choose specific collections)", value: "selective-collections" }
360
+ ]
361
+ }
362
+ ]);
363
+
364
+ if (scopeType === "comprehensive") {
365
+ return { type: "comprehensive" };
366
+ }
367
+
368
+ if (scopeType === "selective-databases") {
369
+ const databases = await fetchAllDatabases((cli as any).controller!.database);
370
+ const selectedDatabases = await (cli as any).selectDatabases(
371
+ databases,
372
+ "Select databases to backup:"
373
+ );
374
+
375
+ const { includeBuckets } = await inquirer.prompt([
376
+ {
377
+ type: "confirm",
378
+ name: "includeBuckets",
379
+ message: "Include storage buckets in backup?",
380
+ default: false
381
+ }
382
+ ]);
383
+
384
+ let selectedBuckets: string[] = [];
385
+ if (includeBuckets) {
386
+ const buckets = await listBuckets((cli as any).controller!.storage);
387
+ const { bucketIds } = await inquirer.prompt([
388
+ {
389
+ type: "checkbox",
390
+ name: "bucketIds",
391
+ message: "Select buckets to backup:",
392
+ choices: buckets.buckets.map((b: any) => ({
393
+ name: `${b.name} (${b.$id})`,
394
+ value: b.$id
395
+ }))
396
+ }
397
+ ]);
398
+ selectedBuckets = bucketIds;
399
+ }
400
+
401
+ return {
402
+ type: "selective-databases",
403
+ databases: selectedDatabases,
404
+ buckets: selectedBuckets
405
+ };
406
+ }
407
+
408
+ if (scopeType === "selective-collections") {
409
+ const databases = await fetchAllDatabases((cli as any).controller!.database);
410
+ const selectedDatabase = await (cli as any).selectDatabases(
411
+ databases,
412
+ "Select database containing collections:",
413
+ false // single selection
414
+ );
415
+
416
+ if (!selectedDatabase || selectedDatabase.length === 0) {
417
+ throw new Error("No database selected");
418
+ }
419
+
420
+ const db = selectedDatabase[0];
421
+ const collections = await (cli as any).selectCollectionsAndTables(
422
+ db,
423
+ (cli as any).controller!.database!,
424
+ "Select collections to backup:",
425
+ true,
426
+ true,
427
+ true
428
+ );
429
+
430
+ return {
431
+ type: "selective-collections",
432
+ databaseId: db.$id,
433
+ databaseName: db.name,
434
+ collections: collections
435
+ };
436
+ }
437
+
438
+ throw new Error("Invalid backup scope selected");
439
+ },
440
+
441
+ // Helper method: Confirm backup plan
442
+ async confirmBackupPlan(scope: any): Promise<boolean> {
443
+ let summary = "\n" + chalk.bold("Backup Plan Summary:") + "\n";
444
+
445
+ if (scope.type === "comprehensive") {
446
+ summary += " • ALL databases\n";
447
+ summary += " • ALL storage buckets\n";
448
+ } else if (scope.type === "selective-databases") {
449
+ summary += ` • ${scope.databases.length} selected databases\n`;
450
+ if (scope.buckets.length > 0) {
451
+ summary += ` • ${scope.buckets.length} selected buckets\n`;
452
+ }
453
+ } else if (scope.type === "selective-collections") {
454
+ summary += ` • Database: ${scope.databaseName}\n`;
455
+ summary += ` • ${scope.collections.length} selected collections\n`;
456
+ }
457
+
458
+ console.log(summary);
459
+
460
+ const { confirmed } = await inquirer.prompt([
461
+ {
462
+ type: "confirm",
463
+ name: "confirmed",
464
+ message: "Proceed with backup?",
465
+ default: true
466
+ }
467
+ ]);
468
+
469
+ return confirmed;
470
+ },
471
+
472
+ // Helper method: Execute unified backup
473
+ async executeUnifiedBackup(cli: InteractiveCLI, trackingDatabaseId: string, scope: any): Promise<void> {
474
+ if (scope.type === "comprehensive") {
475
+ const { comprehensiveBackup } = await import("../../backups/operations/comprehensiveBackup.js");
476
+
477
+ await comprehensiveBackup(
478
+ (cli as any).controller!.config,
479
+ (cli as any).controller!.database,
480
+ (cli as any).controller!.storage,
481
+ (cli as any).controller!.adapter,
482
+ {
483
+ trackingDatabaseId,
484
+ backupFormat: 'zip',
485
+ parallelDownloads: 10,
486
+ onProgress: (message: string) => {
487
+ MessageFormatter.progress(message, { prefix: "Backup" });
488
+ }
489
+ }
490
+ );
491
+ } else if (scope.type === "selective-databases") {
492
+ // Backup each selected database
493
+ for (const db of scope.databases) {
494
+ MessageFormatter.progress(`Backing up database: ${db.name}`, { prefix: "Backup" });
495
+ await (cli as any).controller!.backupDatabase(db);
496
+ }
497
+
498
+ // Backup selected buckets if any
499
+ for (const bucketId of scope.buckets) {
500
+ MessageFormatter.progress(`Backing up bucket: ${bucketId}`, { prefix: "Backup" });
501
+ const { backupBucket } = await import("../../backups/operations/bucketBackup.js");
502
+ await backupBucket(
503
+ (cli as any).controller!.storage,
504
+ bucketId,
505
+ "appwrite-backups",
506
+ { parallelDownloads: 10 }
507
+ );
508
+ }
509
+ } else if (scope.type === "selective-collections") {
510
+ const { backupCollections } = await import("../../backups/operations/collectionBackup.js");
511
+
512
+ await backupCollections(
513
+ (cli as any).controller!.config,
514
+ (cli as any).controller!.database,
515
+ (cli as any).controller!.storage,
516
+ (cli as any).controller!.adapter,
517
+ {
518
+ trackingDatabaseId,
519
+ databaseId: scope.databaseId,
520
+ collectionIds: scope.collections.map((c: any) => c.$id || c.id),
521
+ backupFormat: 'zip',
522
+ onProgress: (message: string) => {
523
+ MessageFormatter.progress(message, { prefix: "Backup" });
524
+ }
525
+ }
526
+ );
527
+ }
528
+ },
529
+
530
+ async wipeDatabase(cli: InteractiveCLI): Promise<void> {
531
+ if (!(cli as any).controller!.database || !(cli as any).controller!.storage) {
532
+ throw new Error(
533
+ "Database or Storage is not initialized, is the config file correct & created?"
534
+ );
535
+ }
536
+ const databases = await fetchAllDatabases((cli as any).controller!.database);
537
+ const storage = await listBuckets((cli as any).controller!.storage);
538
+
539
+ const selectedDatabases = await (cli as any).selectDatabases(
540
+ databases,
541
+ "Select databases to wipe:"
542
+ );
543
+
544
+ const { selectedStorage } = await inquirer.prompt([
545
+ {
546
+ type: "checkbox",
547
+ name: "selectedStorage",
548
+ message: "Select storage buckets to wipe:",
549
+ choices: storage.buckets.map((s: any) => ({ name: s.name, value: s.$id })),
550
+ },
551
+ ]);
552
+
553
+ const { wipeUsers } = await inquirer.prompt([
554
+ {
555
+ type: "confirm",
556
+ name: "wipeUsers",
557
+ message: "Do you want to wipe users as well?",
558
+ default: false,
559
+ },
560
+ ]);
561
+
562
+ const databaseNames = selectedDatabases.map((db: any) => db.name);
563
+ const confirmed = await ConfirmationDialogs.confirmDatabaseWipe(databaseNames, {
564
+ includeStorage: selectedStorage.length > 0,
565
+ includeUsers: wipeUsers
566
+ });
567
+
568
+ if (confirmed) {
569
+ MessageFormatter.info("Starting wipe operation...", { prefix: "Wipe" });
570
+ for (const db of selectedDatabases) {
571
+ await (cli as any).controller!.wipeDatabase(db);
572
+ }
573
+ for (const bucketId of selectedStorage) {
574
+ await (cli as any).controller!.wipeDocumentStorage(bucketId);
575
+ }
576
+ if (wipeUsers) {
577
+ await (cli as any).controller!.wipeUsers();
578
+ }
579
+ MessageFormatter.success("Wipe operation completed", { prefix: "Wipe" });
580
+ } else {
581
+ MessageFormatter.info("Wipe operation cancelled", { prefix: "Wipe" });
582
+ }
583
+ },
584
+
585
+ async wipeCollections(cli: InteractiveCLI): Promise<void> {
586
+ if (!(cli as any).controller!.database) {
587
+ throw new Error(
588
+ "Database is not initialized, is the config file correct & created?"
589
+ );
590
+ }
591
+ const databases = await fetchAllDatabases((cli as any).controller!.database);
592
+ const selectedDatabases = await (cli as any).selectDatabases(
593
+ databases,
594
+ "Select the database(s) containing the collections to wipe:",
595
+ true
596
+ );
597
+
598
+ for (const database of selectedDatabases) {
599
+ const collections = await (cli as any).selectCollectionsAndTables(
600
+ database,
601
+ (cli as any).controller!.database,
602
+ `Select collections/tables to wipe from ${database.name}:`,
603
+ true,
604
+ undefined,
605
+ true
606
+ );
607
+
608
+ const collectionNames = collections.map((c: any) => c.name);
609
+ const confirmed = await ConfirmationDialogs.confirmCollectionWipe(
610
+ database.name,
611
+ collectionNames
612
+ );
613
+
614
+ if (confirmed) {
615
+ MessageFormatter.info(
616
+ `Wiping selected collections from ${database.name}...`,
617
+ { prefix: "Wipe" }
618
+ );
619
+ for (const collection of collections) {
620
+ await (cli as any).controller!.wipeCollection(database, collection);
621
+ MessageFormatter.success(
622
+ `Collection ${collection.name} wiped successfully`,
623
+ { prefix: "Wipe" }
624
+ );
625
+ }
626
+ } else {
627
+ MessageFormatter.info(
628
+ `Wipe operation cancelled for ${database.name}`,
629
+ { prefix: "Wipe" }
630
+ );
631
+ }
632
+ }
633
+ MessageFormatter.success("Wipe collections operation completed", { prefix: "Wipe" });
634
+ }
635
+ };