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
@@ -0,0 +1,952 @@
1
+ import inquirer from "inquirer";
2
+ import { UtilsController } from "./utilsController.js";
3
+ import { fetchAllCollections } from "./collections/methods.js";
4
+ import { listBuckets, createBucket } from "./storage/methods.js";
5
+ import { Databases, Storage, Client, Compression, Query, Functions, DatabaseType, } from "node-appwrite";
6
+ import { PermissionToAppwritePermission, RuntimeSchema, permissionSchema, } from "appwrite-utils";
7
+ import { ulid } from "ulidx";
8
+ import chalk from "chalk";
9
+ import { DateTime } from "luxon";
10
+ import { getFunction, downloadLatestFunctionDeployment, listFunctions, } from "./functions/methods.js";
11
+ import { join } from "node:path";
12
+ import path from "path";
13
+ import fs from "node:fs";
14
+ import os from "node:os";
15
+ import { MessageFormatter, findYamlConfig } from "appwrite-utils-helpers";
16
+ import { findAppwriteConfig } from "./utils/loadConfigs.js";
17
+ // Import command modules
18
+ import { configCommands } from "./cli/commands/configCommands.js";
19
+ import { databaseCommands } from "./cli/commands/databaseCommands.js";
20
+ import { functionCommands } from "./cli/commands/functionCommands.js";
21
+ import { storageCommands } from "./cli/commands/storageCommands.js";
22
+ import { transferCommands } from "./cli/commands/transferCommands.js";
23
+ import { schemaCommands } from "./cli/commands/schemaCommands.js";
24
+ import { importFileCommands } from "./cli/commands/importFileCommands.js";
25
+ var CHOICES;
26
+ (function (CHOICES) {
27
+ CHOICES["MIGRATE_CONFIG"] = "\uD83D\uDD04 Migrate TypeScript config to YAML (.appwrite structure)";
28
+ CHOICES["VALIDATE_CONFIG"] = "\u2705 Validate configuration (collections/tables conflicts)";
29
+ CHOICES["MIGRATE_COLLECTIONS_TO_TABLES"] = "\uD83D\uDD00 Migrate collections to tables format";
30
+ CHOICES["CREATE_COLLECTION_CONFIG"] = "\uD83D\uDCC4 Create collection config file";
31
+ CHOICES["CREATE_FUNCTION"] = "\u26A1 Create a new function, from scratch or using a template";
32
+ CHOICES["DEPLOY_FUNCTION"] = "\uD83D\uDE80 Deploy function(s)";
33
+ CHOICES["DELETE_FUNCTION"] = "\uD83D\uDDD1\uFE0F Delete function";
34
+ CHOICES["SETUP_DIRS_FILES"] = "\uD83D\uDCC1 Setup directories and files";
35
+ CHOICES["SETUP_DIRS_FILES_WITH_EXAMPLE_DATA"] = "\uD83D\uDCC1\u2728 Setup directories and files with example data";
36
+ CHOICES["SYNC_DB"] = "\u2B06\uFE0F Push local config to Appwrite";
37
+ CHOICES["SYNCHRONIZE_CONFIGURATIONS"] = "\uD83D\uDD04 Synchronize configurations - Pull from Appwrite and write to local config";
38
+ CHOICES["TRANSFER_DATA"] = "\uD83D\uDCE6 Transfer data";
39
+ CHOICES["COMPREHENSIVE_TRANSFER"] = "\uD83D\uDE80 Comprehensive transfer (users \u2192 databases \u2192 buckets \u2192 functions)";
40
+ CHOICES["BACKUP_DATABASE"] = "\uD83D\uDCBE Backup database";
41
+ CHOICES["WIPE_DATABASE"] = "\uD83E\uDDF9 Wipe database";
42
+ CHOICES["WIPE_COLLECTIONS"] = "\uD83E\uDDF9 Wipe tables";
43
+ CHOICES["GENERATE_SCHEMAS"] = "\uD83C\uDFD7\uFE0F Generate schemas";
44
+ CHOICES["GENERATE_CONSTANTS"] = "\uD83D\uDCCB Generate cross-language constants (TypeScript, Python, PHP, Dart, etc.)";
45
+ CHOICES["IMPORT_DATA"] = "\uD83D\uDCE5 Import data";
46
+ CHOICES["IMPORT_FILE"] = "\uD83D\uDCC4 Import file (CSV/JSON) directly into a table";
47
+ CHOICES["RELOAD_CONFIG"] = "\uD83D\uDD04 Reload configuration files";
48
+ CHOICES["UPDATE_FUNCTION_SPEC"] = "\u2699\uFE0F Update function specifications";
49
+ CHOICES["MANAGE_BUCKETS"] = "\uD83E\uDEA3 Manage storage buckets";
50
+ CHOICES["EXIT"] = "\uD83D\uDC4B Exit";
51
+ })(CHOICES || (CHOICES = {}));
52
+ export class InteractiveCLI {
53
+ currentDir;
54
+ controller;
55
+ isUsingTypeScriptConfig = false;
56
+ lastSelectedCollectionIds = [];
57
+ options;
58
+ constructor(currentDir, options = {}) {
59
+ this.currentDir = currentDir;
60
+ this.options = options;
61
+ }
62
+ async run() {
63
+ MessageFormatter.banner("Appwrite Utils CLI", "Welcome to Appwrite Utils CLI Tool by Zach Handley");
64
+ MessageFormatter.info("For more information, visit https://github.com/zachhandley/AppwriteUtils");
65
+ // Detect configuration type
66
+ try {
67
+ await this.detectConfigurationType();
68
+ }
69
+ catch (error) {
70
+ // Continue if detection fails
71
+ this.isUsingTypeScriptConfig = false;
72
+ }
73
+ while (true) {
74
+ // Build choices array dynamically based on config type
75
+ const choices = this.buildChoicesList();
76
+ const { action } = await inquirer.prompt([
77
+ {
78
+ type: "list",
79
+ name: "action",
80
+ message: chalk.yellow("What would you like to do?"),
81
+ choices,
82
+ },
83
+ ]);
84
+ switch (action) {
85
+ case CHOICES.MIGRATE_CONFIG:
86
+ await configCommands.migrateTypeScriptConfig(this);
87
+ break;
88
+ case CHOICES.VALIDATE_CONFIG:
89
+ await configCommands.validateConfiguration(this);
90
+ break;
91
+ case CHOICES.MIGRATE_COLLECTIONS_TO_TABLES:
92
+ await configCommands.migrateCollectionsToTables(this);
93
+ break;
94
+ case CHOICES.CREATE_COLLECTION_CONFIG:
95
+ await configCommands.createCollectionConfig(this);
96
+ break;
97
+ case CHOICES.CREATE_FUNCTION:
98
+ await this.initControllerIfNeeded();
99
+ await functionCommands.createFunction(this);
100
+ break;
101
+ case CHOICES.DEPLOY_FUNCTION:
102
+ await this.initControllerIfNeeded();
103
+ await functionCommands.deployFunction(this);
104
+ break;
105
+ case CHOICES.DELETE_FUNCTION:
106
+ await this.initControllerIfNeeded();
107
+ await functionCommands.deleteFunction(this);
108
+ break;
109
+ case CHOICES.SETUP_DIRS_FILES:
110
+ await schemaCommands.setupDirsFiles(this, false);
111
+ break;
112
+ case CHOICES.SETUP_DIRS_FILES_WITH_EXAMPLE_DATA:
113
+ await schemaCommands.setupDirsFiles(this, true);
114
+ break;
115
+ case CHOICES.SYNCHRONIZE_CONFIGURATIONS:
116
+ await this.initControllerIfNeeded();
117
+ await databaseCommands.synchronizeConfigurations(this);
118
+ break;
119
+ case CHOICES.SYNC_DB:
120
+ await this.initControllerIfNeeded();
121
+ await databaseCommands.syncDb(this);
122
+ break;
123
+ case CHOICES.TRANSFER_DATA:
124
+ await this.initControllerIfNeeded();
125
+ await transferCommands.transferData(this);
126
+ break;
127
+ case CHOICES.COMPREHENSIVE_TRANSFER:
128
+ await transferCommands.comprehensiveTransfer(this);
129
+ break;
130
+ case CHOICES.BACKUP_DATABASE:
131
+ await this.initControllerIfNeeded();
132
+ await databaseCommands.backupDatabase(this);
133
+ break;
134
+ case CHOICES.WIPE_DATABASE:
135
+ await this.initControllerIfNeeded();
136
+ await databaseCommands.wipeDatabase(this);
137
+ break;
138
+ case CHOICES.WIPE_COLLECTIONS:
139
+ await this.initControllerIfNeeded();
140
+ await databaseCommands.wipeCollections(this);
141
+ break;
142
+ case CHOICES.GENERATE_SCHEMAS:
143
+ await this.initControllerIfNeeded();
144
+ await schemaCommands.generateSchemas(this);
145
+ break;
146
+ case CHOICES.GENERATE_CONSTANTS:
147
+ await this.initControllerIfNeeded();
148
+ await schemaCommands.generateConstants(this);
149
+ break;
150
+ case CHOICES.IMPORT_DATA:
151
+ await this.initControllerIfNeeded();
152
+ await schemaCommands.importData(this);
153
+ break;
154
+ case CHOICES.IMPORT_FILE:
155
+ await this.initControllerIfNeeded();
156
+ await importFileCommands.importFile(this);
157
+ break;
158
+ case CHOICES.RELOAD_CONFIG:
159
+ await configCommands.reloadConfigWithSessionPreservation(this);
160
+ break;
161
+ case CHOICES.UPDATE_FUNCTION_SPEC:
162
+ await this.initControllerIfNeeded();
163
+ await functionCommands.updateFunctionSpec(this);
164
+ break;
165
+ case CHOICES.MANAGE_BUCKETS:
166
+ await this.manageBuckets();
167
+ break;
168
+ case CHOICES.EXIT:
169
+ MessageFormatter.success("Goodbye!");
170
+ process.exit(0);
171
+ }
172
+ }
173
+ }
174
+ async initControllerIfNeeded(directConfig) {
175
+ if (!this.controller) {
176
+ this.controller = UtilsController.getInstance(this.currentDir, directConfig);
177
+ await this.controller.init({
178
+ useSession: this.options.useSession,
179
+ sessionCookie: this.options.sessionCookie
180
+ });
181
+ }
182
+ else {
183
+ // Extract session info from existing controller before reinitializing
184
+ const sessionInfo = await this.controller.getSessionInfo();
185
+ if (sessionInfo.hasSession && directConfig) {
186
+ // Create enhanced directConfig with session preservation
187
+ const enhancedDirectConfig = {
188
+ ...directConfig,
189
+ sessionCookie: this.controller.sessionCookie,
190
+ sessionMetadata: this.controller.sessionMetadata
191
+ };
192
+ // Reinitialize with session preservation
193
+ UtilsController.clearInstance();
194
+ this.controller = UtilsController.getInstance(this.currentDir, enhancedDirectConfig);
195
+ await this.controller.init({
196
+ useSession: this.options.useSession,
197
+ sessionCookie: this.options.sessionCookie
198
+ });
199
+ }
200
+ else if (directConfig) {
201
+ // Standard reinitialize without session
202
+ UtilsController.clearInstance();
203
+ this.controller = UtilsController.getInstance(this.currentDir, directConfig);
204
+ await this.controller.init({
205
+ useSession: this.options.useSession,
206
+ sessionCookie: this.options.sessionCookie
207
+ });
208
+ }
209
+ // If no directConfig provided, keep existing controller
210
+ }
211
+ }
212
+ async manageBuckets() {
213
+ await this.initControllerIfNeeded();
214
+ while (true) {
215
+ const { action } = await inquirer.prompt([
216
+ {
217
+ type: 'list',
218
+ name: 'action',
219
+ message: chalk.blue('Bucket management'),
220
+ choices: [
221
+ { name: 'Create bucket', value: 'create' },
222
+ { name: 'Delete buckets', value: 'delete' },
223
+ { name: 'Back', value: 'back' },
224
+ ],
225
+ },
226
+ ]);
227
+ if (action === 'back')
228
+ break;
229
+ if (action === 'create') {
230
+ await storageCommands.createBucket(this);
231
+ }
232
+ else if (action === 'delete') {
233
+ await storageCommands.deleteBuckets(this);
234
+ }
235
+ }
236
+ }
237
+ async selectDatabases(databases, message, multiSelect = true) {
238
+ await this.initControllerIfNeeded();
239
+ const configDatabases = this.getLocalDatabases();
240
+ const allDatabases = [...databases, ...configDatabases]
241
+ .reduce((acc, db) => {
242
+ // Local config takes precedence - if a database with same name or ID exists, use local version
243
+ const existingIndex = acc.findIndex((d) => d.name === db.name || d.$id === db.$id);
244
+ if (existingIndex >= 0) {
245
+ if (configDatabases.some((cdb) => cdb.name === db.name || cdb.$id === db.$id)) {
246
+ acc[existingIndex] = db; // Replace with local version
247
+ }
248
+ }
249
+ else {
250
+ acc.push(db);
251
+ }
252
+ return acc;
253
+ }, []);
254
+ const hasLocalAndRemote = allDatabases.some((db) => configDatabases.some((c) => c.name === db.name || c.$id === db.$id)) &&
255
+ allDatabases.some((db) => !configDatabases.some((c) => c.name === db.name || c.$id === db.$id));
256
+ const choices = allDatabases
257
+ .sort((a, b) => a.name.localeCompare(b.name))
258
+ .map((db) => ({
259
+ name: db.name +
260
+ (hasLocalAndRemote
261
+ ? configDatabases.some((c) => c.name === db.name || c.$id === db.$id)
262
+ ? " (Local)"
263
+ : " (Remote)"
264
+ : ""),
265
+ value: db,
266
+ }));
267
+ const { selectedDatabases } = await inquirer.prompt([
268
+ {
269
+ type: multiSelect ? "checkbox" : "list",
270
+ name: "selectedDatabases",
271
+ message: chalk.blue(message),
272
+ choices,
273
+ loop: true,
274
+ pageSize: 10,
275
+ },
276
+ ]);
277
+ // "list" type returns a single value, "checkbox" returns an array — normalize to array
278
+ return Array.isArray(selectedDatabases) ? selectedDatabases : [selectedDatabases];
279
+ }
280
+ async selectCollections(database, databasesClient, message, multiSelect = true, preferLocal = false, shouldFilterByDatabase = false) {
281
+ await this.initControllerIfNeeded();
282
+ const configCollections = this.getLocalCollections();
283
+ let remoteCollections = [];
284
+ const dbExists = await databasesClient.list([
285
+ Query.equal("name", database.name),
286
+ ]);
287
+ if (dbExists.total === 0) {
288
+ MessageFormatter.warning(`Database "${database.name}" does not exist, using only local collection/table options`, { prefix: "Database" });
289
+ shouldFilterByDatabase = false;
290
+ }
291
+ else {
292
+ remoteCollections = await fetchAllCollections(database.$id, databasesClient);
293
+ }
294
+ let allCollections = preferLocal
295
+ ? remoteCollections.reduce((acc, remoteCollection) => {
296
+ if (!acc.some((c) => c.name === remoteCollection.name || c.$id === remoteCollection.$id)) {
297
+ acc.push(remoteCollection);
298
+ }
299
+ return acc;
300
+ }, [...configCollections])
301
+ : [
302
+ ...remoteCollections,
303
+ ...configCollections.filter((c) => !remoteCollections.some((rc) => rc.name === c.name || rc.$id === c.$id)),
304
+ ];
305
+ if (shouldFilterByDatabase) {
306
+ // Show collections that EITHER exist in the remote database OR have matching local databaseId metadata
307
+ allCollections = allCollections.filter((c) => {
308
+ // Include if it exists remotely in this database
309
+ const existsInRemoteDb = remoteCollections.some((rc) => rc.name === c.name || rc.$id === c.$id);
310
+ // Include if local metadata claims it belongs to this database
311
+ const hasMatchingLocalMetadata = c.databaseId === database.$id;
312
+ return existsInRemoteDb || hasMatchingLocalMetadata;
313
+ });
314
+ }
315
+ // Filter out system tables (those starting with underscore)
316
+ allCollections = allCollections.filter((collection) => !collection.$id.startsWith('_'));
317
+ const hasLocalAndRemote = allCollections.some((coll) => configCollections.some((c) => c.name === coll.name || c.$id === coll.$id)) &&
318
+ allCollections.some((coll) => !configCollections.some((c) => c.name === coll.name || c.$id === coll.$id));
319
+ const getCollectionId = (collection) => collection.$id || collection.name;
320
+ const localCollectionIds = new Set(configCollections.map((c) => c.$id || c.name));
321
+ const localCollections = allCollections.filter((collection) => localCollectionIds.has(getCollectionId(collection)));
322
+ // Enhanced choice display with type indicators
323
+ const choices = allCollections
324
+ .sort((a, b) => {
325
+ // Sort by type first (collections before tables), then by name
326
+ const aIsTable = a._isFromTablesDir || false;
327
+ const bIsTable = b._isFromTablesDir || false;
328
+ if (aIsTable !== bIsTable) {
329
+ return aIsTable ? 1 : -1; // Collections first, then tables
330
+ }
331
+ return a.name.localeCompare(b.name);
332
+ })
333
+ .map((collection) => {
334
+ const localCollection = configCollections.find((c) => c.name === collection.name || c.$id === collection.$id);
335
+ const isLocal = !!localCollection;
336
+ const isTable = localCollection?._isFromTablesDir || collection._isFromTablesDir || false;
337
+ const sourceFolder = localCollection?._sourceFolder || collection._sourceFolder || 'collections';
338
+ let typeIndicator = '';
339
+ let locationIndicator = '';
340
+ // Type indicator
341
+ if (isTable) {
342
+ typeIndicator = chalk.cyan('[Table]');
343
+ }
344
+ else {
345
+ typeIndicator = chalk.green('[Collection]');
346
+ }
347
+ // Location indicator
348
+ if (hasLocalAndRemote) {
349
+ if (isLocal) {
350
+ locationIndicator = chalk.gray(`(Local/${sourceFolder})`);
351
+ }
352
+ else {
353
+ locationIndicator = chalk.gray('(Remote)');
354
+ }
355
+ }
356
+ else if (isLocal) {
357
+ locationIndicator = chalk.gray(`(${sourceFolder}/)`);
358
+ }
359
+ // Database indicator for tables with explicit databaseId
360
+ let dbIndicator = '';
361
+ if (isTable && collection.databaseId && shouldFilterByDatabase) {
362
+ const matchesCurrentDb = collection.databaseId === database.$id;
363
+ if (!matchesCurrentDb) {
364
+ dbIndicator = chalk.yellow(` [DB: ${collection.databaseId}]`);
365
+ }
366
+ }
367
+ return {
368
+ name: `${typeIndicator} ${collection.name} ${locationIndicator}${dbIndicator}`,
369
+ value: collection,
370
+ };
371
+ });
372
+ if (multiSelect && localCollections.length > 1) {
373
+ choices.unshift({
374
+ name: chalk.green.bold(`📋 Select All Local Items (${localCollections.length})`),
375
+ value: "__SELECT_ALL_LOCAL__"
376
+ });
377
+ }
378
+ if (multiSelect && allCollections.length > 1) {
379
+ choices.unshift({
380
+ name: chalk.green.bold(`📋 Select All Shown (${allCollections.length})`),
381
+ value: "__SELECT_ALL__"
382
+ });
383
+ }
384
+ const { selectedCollections } = await inquirer.prompt([
385
+ {
386
+ type: multiSelect ? "checkbox" : "list",
387
+ name: "selectedCollections",
388
+ message: chalk.blue(message),
389
+ choices,
390
+ loop: true,
391
+ pageSize: 15, // Increased page size to accommodate additional info
392
+ validate: (input) => {
393
+ if (!multiSelect)
394
+ return true;
395
+ if (input.includes("__SELECT_ALL__") && input.length > 1) {
396
+ return "Cannot select 'Select All' with individual items.";
397
+ }
398
+ if (input.includes("__SELECT_ALL_LOCAL__") && input.length > 1) {
399
+ return "Cannot select 'Select All Local' with individual items.";
400
+ }
401
+ return true;
402
+ }
403
+ },
404
+ ]);
405
+ if (multiSelect && Array.isArray(selectedCollections)) {
406
+ if (selectedCollections.includes("__SELECT_ALL__")) {
407
+ return allCollections;
408
+ }
409
+ if (selectedCollections.includes("__SELECT_ALL_LOCAL__")) {
410
+ return localCollections;
411
+ }
412
+ }
413
+ return selectedCollections;
414
+ }
415
+ /**
416
+ * Enhanced collection/table selection with better guidance for mixed scenarios
417
+ */
418
+ async selectCollectionsAndTables(database, databasesClient, message, multiSelect = true, preferLocal = false, shouldFilterByDatabase = false) {
419
+ const configCollections = this.getLocalCollections();
420
+ const collectionsCount = configCollections.filter(c => !c._isFromTablesDir).length;
421
+ const tablesCount = configCollections.filter(c => c._isFromTablesDir).length;
422
+ const totalCount = collectionsCount + tablesCount;
423
+ // Provide context about what's available
424
+ if (collectionsCount > 0 && tablesCount > 0) {
425
+ MessageFormatter.info(`\n${totalCount} total tables available:`, { prefix: "Tables" });
426
+ MessageFormatter.info(` From collections/ folder: ${collectionsCount}`, { prefix: "Tables" });
427
+ MessageFormatter.info(` From tables/ folder: ${tablesCount}`, { prefix: "Tables" });
428
+ }
429
+ else if (collectionsCount > 0) {
430
+ MessageFormatter.info(`${collectionsCount} tables available from collections/ folder`, { prefix: "Tables" });
431
+ }
432
+ else if (tablesCount > 0) {
433
+ MessageFormatter.info(`${tablesCount} tables available from tables/ folder`, { prefix: "Tables" });
434
+ }
435
+ // Show current database context clearly before view mode selection
436
+ MessageFormatter.info(`DB: ${database.name}`, { prefix: "Tables" });
437
+ // Ask user if they want to filter by database, show all, or reuse previous selection
438
+ const choices = [
439
+ {
440
+ name: `Show all available tables (${totalCount} total) - You can push any table to any database`,
441
+ value: "all"
442
+ },
443
+ {
444
+ name: `Filter by database "${database.name}" - Show only related tables`,
445
+ value: "filter"
446
+ }
447
+ ];
448
+ if (this.lastSelectedCollectionIds && this.lastSelectedCollectionIds.length > 0) {
449
+ choices.unshift({
450
+ name: `Use same selection as before (${this.lastSelectedCollectionIds.length} items)`,
451
+ value: "same"
452
+ });
453
+ }
454
+ const { filterChoice } = await inquirer.prompt([
455
+ {
456
+ type: "list",
457
+ name: "filterChoice",
458
+ message: chalk.blue("How would you like to view tables?"),
459
+ choices,
460
+ default: choices[0]?.value || "all"
461
+ }
462
+ ]);
463
+ // If user wants to reuse the previous selection, map IDs to current config and return
464
+ if (filterChoice === "same") {
465
+ const map = new Map(this.getLocalCollections().map((c) => [c.$id || c.id, c]));
466
+ const selected = this.lastSelectedCollectionIds
467
+ .map((id) => map.get(id))
468
+ .filter((c) => !!c);
469
+ MessageFormatter.info(`Using same selection as previous: ${selected.length} item(s)`, { prefix: "Collections" });
470
+ return selected;
471
+ }
472
+ // User's choice overrides the parameter
473
+ const userWantsFiltering = filterChoice === "filter";
474
+ // Show appropriate informational message
475
+ if (userWantsFiltering) {
476
+ MessageFormatter.info(`Showing tables related to database "${database.name}"`, { prefix: "Tables" });
477
+ if (tablesCount > 0) {
478
+ const filteredTables = configCollections.filter(c => c._isFromTablesDir && (!c.databaseId || c.databaseId === database.$id)).length;
479
+ if (filteredTables !== tablesCount) {
480
+ MessageFormatter.info(` ${filteredTables}/${tablesCount} tables match this database`, { prefix: "Tables" });
481
+ }
482
+ }
483
+ }
484
+ else {
485
+ MessageFormatter.info(`Showing all available tables - you can push any table to any database\n`, { prefix: "Tables" });
486
+ }
487
+ const result = await this.selectCollections(database, databasesClient, message, multiSelect, preferLocal, userWantsFiltering);
488
+ // Remember this selection for subsequent databases
489
+ this.lastSelectedCollectionIds = (result || []).map((c) => c.$id || c.id);
490
+ return result;
491
+ }
492
+ getTemplateDefaults(template) {
493
+ const defaults = {
494
+ "typescript-node": {
495
+ runtime: "node-21.0",
496
+ entrypoint: "src/main.ts",
497
+ commands: "npm install && npm run build",
498
+ specification: "s-0.5vcpu-512mb",
499
+ },
500
+ "hono-typescript": {
501
+ runtime: "node-21.0",
502
+ entrypoint: "src/main.ts",
503
+ commands: "npm install && npm run build",
504
+ specification: "s-0.5vcpu-512mb",
505
+ },
506
+ "uv": {
507
+ runtime: "python-3.12",
508
+ entrypoint: "src/main.py",
509
+ commands: "uv sync && uv build",
510
+ specification: "s-0.5vcpu-512mb",
511
+ },
512
+ "count-docs-in-collection": {
513
+ runtime: "node-21.0",
514
+ entrypoint: "src/main.ts",
515
+ commands: "npm install && npm run build",
516
+ specification: "s-1vcpu-512mb",
517
+ },
518
+ };
519
+ return defaults[template] || {
520
+ runtime: "node-21.0",
521
+ entrypoint: "",
522
+ commands: "",
523
+ specification: "s-0.5vcpu-512mb",
524
+ };
525
+ }
526
+ async findFunctionInSubdirectories(basePaths, functionName) {
527
+ // Common locations to check first
528
+ const commonPaths = basePaths.flatMap((basePath) => [
529
+ join(basePath, "functions", functionName),
530
+ join(basePath, functionName),
531
+ join(basePath, functionName.toLowerCase()),
532
+ join(basePath, functionName.toLowerCase().replace(/\s+/g, "")),
533
+ ]);
534
+ // Create different variations of the function name for comparison
535
+ const functionNameVariations = new Set([
536
+ functionName.toLowerCase(),
537
+ functionName.toLowerCase().replace(/\s+/g, ""),
538
+ functionName.toLowerCase().replace(/[^a-z0-9]/g, ""),
539
+ functionName.toLowerCase().replace(/[-_\s]+/g, ""),
540
+ ]);
541
+ // Check common locations first
542
+ for (const path of commonPaths) {
543
+ try {
544
+ const stats = await fs.promises.stat(path);
545
+ if (stats.isDirectory()) {
546
+ MessageFormatter.success(`Found function at common location: ${path}`, { prefix: "Functions" });
547
+ return path;
548
+ }
549
+ }
550
+ catch (error) {
551
+ // Path doesn't exist, continue to next
552
+ }
553
+ }
554
+ // If not found in common locations, do recursive search
555
+ MessageFormatter.info("Function not found in common locations, searching subdirectories...", { prefix: "Functions" });
556
+ const queue = [...basePaths];
557
+ const searched = new Set();
558
+ while (queue.length > 0) {
559
+ const currentPath = queue.shift();
560
+ if (searched.has(currentPath))
561
+ continue;
562
+ searched.add(currentPath);
563
+ try {
564
+ const entries = await fs.promises.readdir(currentPath, {
565
+ withFileTypes: true,
566
+ });
567
+ for (const entry of entries) {
568
+ const fullPath = join(currentPath, entry.name);
569
+ // Skip node_modules and hidden directories
570
+ if (entry.isDirectory() &&
571
+ !entry.name.startsWith(".") &&
572
+ entry.name !== "node_modules") {
573
+ const entryNameVariations = new Set([
574
+ entry.name.toLowerCase(),
575
+ entry.name.toLowerCase().replace(/\s+/g, ""),
576
+ entry.name.toLowerCase().replace(/[^a-z0-9]/g, ""),
577
+ entry.name.toLowerCase().replace(/[-_\s]+/g, ""),
578
+ ]);
579
+ // Check if any variation of the entry name matches any variation of the function name
580
+ const hasMatch = [...functionNameVariations].some((fnVar) => [...entryNameVariations].includes(fnVar));
581
+ if (hasMatch) {
582
+ MessageFormatter.success(`Found function at: ${fullPath}`, { prefix: "Functions" });
583
+ return fullPath;
584
+ }
585
+ queue.push(fullPath);
586
+ }
587
+ }
588
+ }
589
+ catch (error) {
590
+ MessageFormatter.warning(`Error reading directory ${currentPath}: ${error}`, { prefix: "Functions" });
591
+ }
592
+ }
593
+ return null;
594
+ }
595
+ async selectFunctions(message, multiple = true, includeRemote = false) {
596
+ const remoteFunctions = includeRemote
597
+ ? await listFunctions(this.controller.appwriteServer, [
598
+ Query.limit(1000),
599
+ ])
600
+ : { functions: [] };
601
+ const localFunctions = this.getLocalFunctions();
602
+ // Combine functions, preferring local ones
603
+ const allFunctions = [
604
+ ...localFunctions,
605
+ ...remoteFunctions.functions.filter((rf) => !localFunctions.some((lf) => lf.name === rf.name || lf.$id === rf.$id)),
606
+ ];
607
+ const { selectedFunctions } = await inquirer.prompt([
608
+ {
609
+ type: multiple ? "checkbox" : "list",
610
+ name: "selectedFunctions",
611
+ message,
612
+ choices: allFunctions.map((f) => ({
613
+ name: `${f.name} (${f.$id})${localFunctions.some((lf) => lf.name === f.name || lf.$id === f.$id)
614
+ ? " (Local)"
615
+ : " (Remote)"}`,
616
+ value: f,
617
+ })),
618
+ loop: true,
619
+ },
620
+ ]);
621
+ return multiple ? selectedFunctions : [selectedFunctions];
622
+ }
623
+ getLocalFunctions() {
624
+ const configFunctions = this.controller.config?.functions || [];
625
+ return configFunctions.map((f) => ({
626
+ $id: f.$id || ulid(),
627
+ $createdAt: DateTime.now().toISO(),
628
+ $updatedAt: DateTime.now().toISO(),
629
+ name: f.name,
630
+ runtime: f.runtime,
631
+ execute: f.execute || ["any"],
632
+ events: f.events || [],
633
+ schedule: f.schedule || "",
634
+ timeout: f.timeout || 15,
635
+ ignore: f.ignore,
636
+ enabled: f.enabled !== false,
637
+ logging: f.logging !== false,
638
+ entrypoint: f.entrypoint || "src/main.ts",
639
+ commands: f.commands || "npm install",
640
+ scopes: f.scopes || [], // Add scopes
641
+ path: f.dirPath || `functions/${f.name}`,
642
+ dirPath: f.dirPath, // Preserve original dirPath
643
+ installationId: f.installationId || "",
644
+ providerRepositoryId: f.providerRepositoryId || "",
645
+ providerBranch: f.providerBranch || "",
646
+ providerSilentMode: f.providerSilentMode || false,
647
+ providerRootDirectory: f.providerRootDirectory || "",
648
+ ...(f.specification ? { specification: f.specification } : {}),
649
+ ...(f.predeployCommands
650
+ ? { predeployCommands: f.predeployCommands }
651
+ : {}),
652
+ ...(f.deployDir ? { deployDir: f.deployDir } : {}),
653
+ }));
654
+ }
655
+ async selectBuckets(buckets, message, multiSelect = true) {
656
+ const choices = buckets.map((bucket) => ({
657
+ name: bucket.name,
658
+ value: bucket,
659
+ }));
660
+ const { selectedBuckets } = await inquirer.prompt([
661
+ {
662
+ type: multiSelect ? "checkbox" : "list",
663
+ name: "selectedBuckets",
664
+ message: chalk.blue(message),
665
+ choices,
666
+ loop: false,
667
+ pageSize: 10,
668
+ },
669
+ ]);
670
+ return selectedBuckets;
671
+ }
672
+ async configureBuckets(config, databases) {
673
+ const { storage } = this.controller;
674
+ if (!storage) {
675
+ throw new Error("Storage is not initialized. Is the config file correct and created?");
676
+ }
677
+ const allBuckets = await listBuckets(storage);
678
+ // If there are no buckets, ask to create one for each database
679
+ if (allBuckets.total === 0) {
680
+ const databasesToUse = databases ?? config.databases;
681
+ for (const database of databasesToUse) {
682
+ // If database has bucket config in local config, use that
683
+ const localDatabase = this.controller.config?.databases.find((db) => db.name === database.name);
684
+ if (localDatabase?.bucket) {
685
+ database.bucket = localDatabase.bucket;
686
+ continue;
687
+ }
688
+ const { wantCreateBucket } = await inquirer.prompt([
689
+ {
690
+ type: "confirm",
691
+ name: "wantCreateBucket",
692
+ message: chalk.blue(`There are no buckets. Do you want to create a bucket for the database "${database.name}"?`),
693
+ default: true,
694
+ },
695
+ ]);
696
+ if (wantCreateBucket) {
697
+ const createdBucket = await this.createNewBucket(storage, database.name);
698
+ database.bucket = {
699
+ ...createdBucket,
700
+ compression: createdBucket.compression,
701
+ };
702
+ }
703
+ }
704
+ return config;
705
+ }
706
+ // Configure global buckets
707
+ let globalBuckets = [];
708
+ if (allBuckets.total > 0) {
709
+ globalBuckets = await this.selectBuckets(allBuckets.buckets, "Select global buckets (buckets that are not associated with any specific database):", true);
710
+ config.buckets = globalBuckets.map((bucket) => ({
711
+ $id: bucket.$id,
712
+ name: bucket.name,
713
+ enabled: bucket.enabled,
714
+ maximumFileSize: bucket.maximumFileSize,
715
+ allowedFileExtensions: bucket.allowedFileExtensions,
716
+ compression: bucket.compression,
717
+ encryption: bucket.encryption,
718
+ antivirus: bucket.antivirus,
719
+ }));
720
+ }
721
+ else {
722
+ config.buckets = [];
723
+ }
724
+ // Configure database-specific buckets
725
+ for (const database of config.databases) {
726
+ const { assignBucket } = await inquirer.prompt([
727
+ {
728
+ type: "confirm",
729
+ name: "assignBucket",
730
+ message: `Do you want to assign or create a bucket for the database "${database.name}"?`,
731
+ default: false,
732
+ },
733
+ ]);
734
+ if (assignBucket) {
735
+ const { action } = await inquirer.prompt([
736
+ {
737
+ type: "list",
738
+ name: "action",
739
+ message: `Choose an action for the database "${database.name}":`,
740
+ choices: [
741
+ { name: "Assign existing bucket", value: "assign" },
742
+ { name: "Create new bucket", value: "create" },
743
+ ],
744
+ },
745
+ ]);
746
+ if (action === "assign") {
747
+ const selectedBuckets = await this.selectBuckets(allBuckets.buckets.filter((b) => !globalBuckets.some((gb) => gb.$id === b.$id)), `Select a bucket for the database "${database.name}":`, false // multiSelect = false
748
+ );
749
+ if (selectedBuckets.length > 0) {
750
+ const selectedBucket = selectedBuckets[0];
751
+ database.bucket = {
752
+ $id: selectedBucket.$id,
753
+ name: selectedBucket.name,
754
+ enabled: selectedBucket.enabled,
755
+ maximumFileSize: selectedBucket.maximumFileSize,
756
+ allowedFileExtensions: selectedBucket.allowedFileExtensions,
757
+ compression: selectedBucket.compression,
758
+ encryption: selectedBucket.encryption,
759
+ antivirus: selectedBucket.antivirus,
760
+ permissions: selectedBucket.$permissions.map((p) => permissionSchema.parse(p)),
761
+ };
762
+ }
763
+ }
764
+ else if (action === "create") {
765
+ const createdBucket = await this.createNewBucket(storage, database.name);
766
+ database.bucket = {
767
+ ...createdBucket,
768
+ compression: createdBucket.compression,
769
+ };
770
+ }
771
+ }
772
+ }
773
+ return config;
774
+ }
775
+ async createNewBucket(storage, databaseName) {
776
+ const { bucketName, bucketEnabled, bucketMaximumFileSize, bucketAllowedFileExtensions, bucketFileSecurity, bucketCompression, bucketCompressionType, bucketEncryption, bucketAntivirus, bucketId, } = await inquirer.prompt([
777
+ {
778
+ type: "input",
779
+ name: "bucketName",
780
+ message: `Enter the name of the bucket for database "${databaseName}":`,
781
+ default: `${databaseName}-bucket`,
782
+ },
783
+ {
784
+ type: "confirm",
785
+ name: "bucketEnabled",
786
+ message: "Is the bucket enabled?",
787
+ default: true,
788
+ },
789
+ {
790
+ type: "confirm",
791
+ name: "bucketFileSecurity",
792
+ message: "Do you want to enable file security for the bucket?",
793
+ default: false,
794
+ },
795
+ {
796
+ type: "number",
797
+ name: "bucketMaximumFileSize",
798
+ message: "Enter the maximum file size for the bucket (MB):",
799
+ default: 1000000,
800
+ },
801
+ {
802
+ type: "input",
803
+ name: "bucketAllowedFileExtensions",
804
+ message: "Enter the allowed file extensions for the bucket (comma separated):",
805
+ default: "",
806
+ },
807
+ {
808
+ type: "confirm",
809
+ name: "bucketCompression",
810
+ message: "Do you want to enable compression for the bucket?",
811
+ default: false,
812
+ },
813
+ {
814
+ type: "list",
815
+ name: "bucketCompressionType",
816
+ message: "Select the compression type for the bucket:",
817
+ choices: Object.values(Compression),
818
+ default: Compression.None,
819
+ when: (answers) => answers.bucketCompression,
820
+ },
821
+ {
822
+ type: "confirm",
823
+ name: "bucketEncryption",
824
+ message: "Do you want to enable encryption for the bucket?",
825
+ default: false,
826
+ },
827
+ {
828
+ type: "confirm",
829
+ name: "bucketAntivirus",
830
+ message: "Do you want to enable antivirus for the bucket?",
831
+ default: false,
832
+ },
833
+ {
834
+ type: "input",
835
+ name: "bucketId",
836
+ message: "Enter the ID of the bucket (or empty for auto-generation):",
837
+ },
838
+ ]);
839
+ return await createBucket(storage, {
840
+ name: bucketName,
841
+ $permissions: [],
842
+ enabled: bucketEnabled,
843
+ fileSecurity: bucketFileSecurity,
844
+ maximumFileSize: bucketMaximumFileSize * 1024 * 1024,
845
+ allowedFileExtensions: bucketAllowedFileExtensions.length > 0
846
+ ? bucketAllowedFileExtensions?.split(",")
847
+ : [],
848
+ compression: bucketCompressionType,
849
+ encryption: bucketEncryption,
850
+ antivirus: bucketAntivirus,
851
+ }, bucketId.length > 0 ? bucketId : ulid());
852
+ }
853
+ getLocalCollections() {
854
+ const configCollections = [
855
+ ...(this.controller.config?.collections || []),
856
+ ...(this.controller.config?.tables || [])
857
+ ];
858
+ // @ts-expect-error - appwrite invalid types
859
+ return configCollections.map((c) => ({
860
+ $id: c.$id || ulid(),
861
+ $createdAt: DateTime.now().toISO(),
862
+ $updatedAt: DateTime.now().toISO(),
863
+ name: c.name,
864
+ enabled: c.enabled || true,
865
+ documentSecurity: c.documentSecurity || false,
866
+ attributes: c.attributes || [],
867
+ indexes: c.indexes || [],
868
+ $permissions: PermissionToAppwritePermission(c.$permissions) || [],
869
+ databaseId: c.databaseId,
870
+ _isFromTablesDir: c._isFromTablesDir || false,
871
+ _sourceFolder: c._isFromTablesDir ? 'tables' : 'collections',
872
+ }));
873
+ }
874
+ getLocalDatabases() {
875
+ const configDatabases = this.controller.config?.databases || [];
876
+ return configDatabases.map((db) => ({
877
+ $id: db.$id || ulid(),
878
+ $createdAt: DateTime.now().toISO(),
879
+ $updatedAt: DateTime.now().toISO(),
880
+ name: db.name,
881
+ enabled: true,
882
+ type: "tablesdb",
883
+ }));
884
+ }
885
+ /**
886
+ * Extract session information from current controller for preservation
887
+ */
888
+ async extractSessionFromController() {
889
+ if (!this.controller?.config) {
890
+ return undefined;
891
+ }
892
+ const sessionInfo = await this.controller.getSessionInfo();
893
+ const config = this.controller.config;
894
+ if (!config.appwriteEndpoint || !config.appwriteProject) {
895
+ return undefined;
896
+ }
897
+ const result = {
898
+ appwriteEndpoint: config.appwriteEndpoint,
899
+ appwriteProject: config.appwriteProject,
900
+ appwriteKey: config.appwriteKey
901
+ };
902
+ // Add session data if available
903
+ if (sessionInfo.hasSession) {
904
+ result.sessionCookie = this.controller.sessionCookie;
905
+ result.sessionMetadata = this.controller.sessionMetadata;
906
+ }
907
+ return result;
908
+ }
909
+ async detectConfigurationType() {
910
+ try {
911
+ // Check for YAML config first
912
+ const yamlConfigPath = findYamlConfig(this.currentDir);
913
+ if (yamlConfigPath) {
914
+ this.isUsingTypeScriptConfig = false;
915
+ MessageFormatter.info("Using YAML configuration", { prefix: "Config" });
916
+ return;
917
+ }
918
+ // Then check for TypeScript config
919
+ const configPath = findAppwriteConfig(this.currentDir);
920
+ if (configPath) {
921
+ const tsConfigPath = join(configPath, 'appwriteConfig.ts');
922
+ if (fs.existsSync(tsConfigPath)) {
923
+ this.isUsingTypeScriptConfig = true;
924
+ MessageFormatter.info("TypeScript configuration detected", { prefix: "Config" });
925
+ MessageFormatter.info("Consider migrating to YAML for better organization", { prefix: "Config" });
926
+ return;
927
+ }
928
+ }
929
+ // No config found
930
+ this.isUsingTypeScriptConfig = false;
931
+ MessageFormatter.info("No configuration file found", { prefix: "Config" });
932
+ }
933
+ catch (error) {
934
+ // Silently handle detection errors and continue
935
+ this.isUsingTypeScriptConfig = false;
936
+ }
937
+ }
938
+ buildChoicesList() {
939
+ const allChoices = Object.values(CHOICES);
940
+ if (this.isUsingTypeScriptConfig) {
941
+ // Place migration option at the top when TS config is detected
942
+ return [
943
+ CHOICES.MIGRATE_CONFIG,
944
+ ...allChoices.filter(choice => choice !== CHOICES.MIGRATE_CONFIG)
945
+ ];
946
+ }
947
+ else {
948
+ // Hide migration option when using YAML config
949
+ return allChoices.filter(choice => choice !== CHOICES.MIGRATE_CONFIG);
950
+ }
951
+ }
952
+ }