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