@njdamstra/appwrite-utils-cli 1.8.9 → 1.10.1

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 (285) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/CONFIG_TODO.md +1189 -0
  3. package/SELECTION_DIALOGS.md +146 -0
  4. package/SERVICE_IMPLEMENTATION_REPORT.md +462 -0
  5. package/dist/adapters/index.d.ts +7 -8
  6. package/dist/adapters/index.js +7 -9
  7. package/dist/backups/operations/bucketBackup.js +2 -2
  8. package/dist/backups/operations/collectionBackup.d.ts +1 -1
  9. package/dist/backups/operations/collectionBackup.js +3 -3
  10. package/dist/backups/operations/comprehensiveBackup.d.ts +1 -1
  11. package/dist/backups/operations/comprehensiveBackup.js +2 -2
  12. package/dist/backups/tracking/centralizedTracking.d.ts +1 -1
  13. package/dist/backups/tracking/centralizedTracking.js +2 -2
  14. package/dist/cli/commands/configCommands.js +51 -7
  15. package/dist/cli/commands/databaseCommands.d.ts +1 -0
  16. package/dist/cli/commands/databaseCommands.js +119 -9
  17. package/dist/cli/commands/functionCommands.js +3 -3
  18. package/dist/cli/commands/importFileCommands.d.ts +7 -0
  19. package/dist/cli/commands/importFileCommands.js +674 -0
  20. package/dist/cli/commands/schemaCommands.js +3 -3
  21. package/dist/cli/commands/storageCommands.js +2 -3
  22. package/dist/cli/commands/transferCommands.js +3 -5
  23. package/dist/collections/attributes.d.ts +1 -1
  24. package/dist/collections/attributes.js +85 -35
  25. package/dist/collections/indexes.js +2 -4
  26. package/dist/collections/methods.d.ts +1 -1
  27. package/dist/collections/methods.js +111 -192
  28. package/dist/collections/tableOperations.d.ts +1 -0
  29. package/dist/collections/tableOperations.js +90 -23
  30. package/dist/collections/transferOperations.d.ts +1 -1
  31. package/dist/collections/transferOperations.js +3 -4
  32. package/dist/collections/wipeOperations.d.ts +4 -3
  33. package/dist/collections/wipeOperations.js +112 -39
  34. package/dist/databases/methods.js +2 -2
  35. package/dist/databases/setup.js +2 -2
  36. package/dist/examples/yamlTerminologyExample.js +2 -2
  37. package/dist/functions/deployments.d.ts +1 -1
  38. package/dist/functions/deployments.js +5 -5
  39. package/dist/functions/fnConfigDiscovery.js +2 -2
  40. package/dist/functions/methods.js +16 -4
  41. package/dist/init.js +1 -1
  42. package/dist/interactiveCLI.d.ts +6 -1
  43. package/dist/interactiveCLI.js +64 -10
  44. package/dist/main.js +130 -177
  45. package/dist/migrations/afterImportActions.js +2 -3
  46. package/dist/migrations/appwriteToX.d.ts +97 -1
  47. package/dist/migrations/appwriteToX.js +9 -7
  48. package/dist/migrations/comprehensiveTransfer.js +3 -5
  49. package/dist/migrations/dataLoader.d.ts +194 -2
  50. package/dist/migrations/dataLoader.js +2 -5
  51. package/dist/migrations/importController.js +3 -4
  52. package/dist/migrations/importDataActions.js +3 -3
  53. package/dist/migrations/relationships.js +1 -2
  54. package/dist/migrations/services/DataTransformationService.js +2 -2
  55. package/dist/migrations/services/FileHandlerService.js +1 -1
  56. package/dist/migrations/services/ImportOrchestrator.js +4 -4
  57. package/dist/migrations/services/RateLimitManager.js +1 -1
  58. package/dist/migrations/services/RelationshipResolver.js +1 -1
  59. package/dist/migrations/services/UserMappingService.js +1 -1
  60. package/dist/migrations/services/ValidationService.js +1 -1
  61. package/dist/migrations/transfer.d.ts +8 -4
  62. package/dist/migrations/transfer.js +106 -55
  63. package/dist/migrations/yaml/YamlImportConfigLoader.js +1 -1
  64. package/dist/migrations/yaml/YamlImportIntegration.js +2 -2
  65. package/dist/migrations/yaml/generateImportSchemas.js +1 -1
  66. package/dist/setupCommands.d.ts +1 -1
  67. package/dist/setupCommands.js +5 -6
  68. package/dist/setupController.js +1 -1
  69. package/dist/shared/backupTracking.d.ts +1 -1
  70. package/dist/shared/backupTracking.js +2 -2
  71. package/dist/shared/confirmationDialogs.js +1 -1
  72. package/dist/shared/migrationHelpers.d.ts +1 -1
  73. package/dist/shared/migrationHelpers.js +3 -3
  74. package/dist/shared/operationQueue.d.ts +1 -1
  75. package/dist/shared/operationQueue.js +2 -3
  76. package/dist/shared/operationsTable.d.ts +1 -1
  77. package/dist/shared/operationsTable.js +2 -2
  78. package/dist/shared/progressManager.js +1 -1
  79. package/dist/shared/selectionDialogs.js +9 -8
  80. package/dist/storage/methods.js +4 -4
  81. package/dist/storage/schemas.d.ts +386 -2
  82. package/dist/tables/indexManager.d.ts +65 -0
  83. package/dist/tables/indexManager.js +294 -0
  84. package/dist/types.d.ts +2 -2
  85. package/dist/types.js +1 -1
  86. package/dist/users/methods.js +2 -3
  87. package/dist/utils/configMigration.js +1 -1
  88. package/dist/utils/index.d.ts +1 -1
  89. package/dist/utils/index.js +1 -1
  90. package/dist/utils/loadConfigs.d.ts +2 -2
  91. package/dist/utils/loadConfigs.js +6 -7
  92. package/dist/utils/setupFiles.js +5 -7
  93. package/dist/utilsController.d.ts +15 -8
  94. package/dist/utilsController.js +57 -28
  95. package/package.json +8 -4
  96. package/src/adapters/index.ts +8 -34
  97. package/src/backups/operations/bucketBackup.ts +2 -2
  98. package/src/backups/operations/collectionBackup.ts +4 -4
  99. package/src/backups/operations/comprehensiveBackup.ts +3 -3
  100. package/src/backups/tracking/centralizedTracking.ts +3 -3
  101. package/src/cli/commands/configCommands.ts +72 -8
  102. package/src/cli/commands/databaseCommands.ts +161 -9
  103. package/src/cli/commands/functionCommands.ts +4 -3
  104. package/src/cli/commands/importFileCommands.ts +815 -0
  105. package/src/cli/commands/schemaCommands.ts +3 -3
  106. package/src/cli/commands/storageCommands.ts +2 -3
  107. package/src/cli/commands/transferCommands.ts +3 -6
  108. package/src/collections/attributes.ts +155 -39
  109. package/src/collections/indexes.ts +5 -7
  110. package/src/collections/methods.ts +115 -150
  111. package/src/collections/tableOperations.ts +92 -21
  112. package/src/collections/transferOperations.ts +4 -5
  113. package/src/collections/wipeOperations.ts +154 -51
  114. package/src/databases/methods.ts +2 -2
  115. package/src/databases/setup.ts +2 -2
  116. package/src/examples/yamlTerminologyExample.ts +2 -2
  117. package/src/functions/deployments.ts +6 -5
  118. package/src/functions/fnConfigDiscovery.ts +2 -2
  119. package/src/functions/methods.ts +19 -6
  120. package/src/init.ts +1 -1
  121. package/src/interactiveCLI.ts +78 -13
  122. package/src/main.ts +143 -287
  123. package/src/migrations/afterImportActions.ts +2 -3
  124. package/src/migrations/appwriteToX.ts +12 -8
  125. package/src/migrations/comprehensiveTransfer.ts +6 -6
  126. package/src/migrations/dataLoader.ts +2 -5
  127. package/src/migrations/importController.ts +3 -4
  128. package/src/migrations/importDataActions.ts +3 -3
  129. package/src/migrations/relationships.ts +1 -2
  130. package/src/migrations/services/DataTransformationService.ts +2 -2
  131. package/src/migrations/services/FileHandlerService.ts +1 -1
  132. package/src/migrations/services/ImportOrchestrator.ts +4 -4
  133. package/src/migrations/services/RateLimitManager.ts +1 -1
  134. package/src/migrations/services/RelationshipResolver.ts +1 -1
  135. package/src/migrations/services/UserMappingService.ts +1 -1
  136. package/src/migrations/services/ValidationService.ts +1 -1
  137. package/src/migrations/transfer.ts +126 -83
  138. package/src/migrations/yaml/YamlImportConfigLoader.ts +1 -1
  139. package/src/migrations/yaml/YamlImportIntegration.ts +2 -2
  140. package/src/migrations/yaml/generateImportSchemas.ts +1 -1
  141. package/src/setupCommands.ts +5 -6
  142. package/src/setupController.ts +1 -1
  143. package/src/shared/backupTracking.ts +3 -3
  144. package/src/shared/confirmationDialogs.ts +1 -1
  145. package/src/shared/migrationHelpers.ts +4 -4
  146. package/src/shared/operationQueue.ts +3 -4
  147. package/src/shared/operationsTable.ts +3 -3
  148. package/src/shared/progressManager.ts +1 -1
  149. package/src/shared/selectionDialogs.ts +9 -8
  150. package/src/storage/methods.ts +4 -4
  151. package/src/tables/indexManager.ts +409 -0
  152. package/src/types.ts +2 -2
  153. package/src/users/methods.ts +2 -3
  154. package/src/utils/configMigration.ts +1 -1
  155. package/src/utils/index.ts +1 -1
  156. package/src/utils/loadConfigs.ts +15 -7
  157. package/src/utils/setupFiles.ts +5 -7
  158. package/src/utilsController.ts +86 -32
  159. package/dist/adapters/AdapterFactory.d.ts +0 -94
  160. package/dist/adapters/AdapterFactory.js +0 -405
  161. package/dist/adapters/DatabaseAdapter.d.ts +0 -233
  162. package/dist/adapters/DatabaseAdapter.js +0 -50
  163. package/dist/adapters/LegacyAdapter.d.ts +0 -50
  164. package/dist/adapters/LegacyAdapter.js +0 -612
  165. package/dist/adapters/TablesDBAdapter.d.ts +0 -45
  166. package/dist/adapters/TablesDBAdapter.js +0 -571
  167. package/dist/config/ConfigManager.d.ts +0 -445
  168. package/dist/config/ConfigManager.js +0 -625
  169. package/dist/config/configMigration.d.ts +0 -87
  170. package/dist/config/configMigration.js +0 -390
  171. package/dist/config/configValidation.d.ts +0 -66
  172. package/dist/config/configValidation.js +0 -358
  173. package/dist/config/index.d.ts +0 -8
  174. package/dist/config/index.js +0 -7
  175. package/dist/config/services/ConfigDiscoveryService.d.ts +0 -126
  176. package/dist/config/services/ConfigDiscoveryService.js +0 -374
  177. package/dist/config/services/ConfigLoaderService.d.ts +0 -129
  178. package/dist/config/services/ConfigLoaderService.js +0 -540
  179. package/dist/config/services/ConfigMergeService.d.ts +0 -208
  180. package/dist/config/services/ConfigMergeService.js +0 -308
  181. package/dist/config/services/ConfigValidationService.d.ts +0 -214
  182. package/dist/config/services/ConfigValidationService.js +0 -310
  183. package/dist/config/services/SessionAuthService.d.ts +0 -225
  184. package/dist/config/services/SessionAuthService.js +0 -456
  185. package/dist/config/services/__tests__/ConfigMergeService.test.d.ts +0 -1
  186. package/dist/config/services/__tests__/ConfigMergeService.test.js +0 -271
  187. package/dist/config/services/index.d.ts +0 -13
  188. package/dist/config/services/index.js +0 -10
  189. package/dist/config/yamlConfig.d.ts +0 -722
  190. package/dist/config/yamlConfig.js +0 -702
  191. package/dist/functions/pathResolution.d.ts +0 -37
  192. package/dist/functions/pathResolution.js +0 -185
  193. package/dist/shared/attributeMapper.d.ts +0 -20
  194. package/dist/shared/attributeMapper.js +0 -203
  195. package/dist/shared/errorUtils.d.ts +0 -54
  196. package/dist/shared/errorUtils.js +0 -95
  197. package/dist/shared/functionManager.d.ts +0 -48
  198. package/dist/shared/functionManager.js +0 -336
  199. package/dist/shared/indexManager.d.ts +0 -24
  200. package/dist/shared/indexManager.js +0 -151
  201. package/dist/shared/jsonSchemaGenerator.d.ts +0 -50
  202. package/dist/shared/jsonSchemaGenerator.js +0 -290
  203. package/dist/shared/logging.d.ts +0 -61
  204. package/dist/shared/logging.js +0 -116
  205. package/dist/shared/messageFormatter.d.ts +0 -39
  206. package/dist/shared/messageFormatter.js +0 -162
  207. package/dist/shared/pydanticModelGenerator.d.ts +0 -17
  208. package/dist/shared/pydanticModelGenerator.js +0 -615
  209. package/dist/shared/schemaGenerator.d.ts +0 -40
  210. package/dist/shared/schemaGenerator.js +0 -556
  211. package/dist/utils/ClientFactory.d.ts +0 -87
  212. package/dist/utils/ClientFactory.js +0 -212
  213. package/dist/utils/configDiscovery.d.ts +0 -78
  214. package/dist/utils/configDiscovery.js +0 -472
  215. package/dist/utils/constantsGenerator.d.ts +0 -31
  216. package/dist/utils/constantsGenerator.js +0 -321
  217. package/dist/utils/dataConverters.d.ts +0 -46
  218. package/dist/utils/dataConverters.js +0 -139
  219. package/dist/utils/directoryUtils.d.ts +0 -22
  220. package/dist/utils/directoryUtils.js +0 -59
  221. package/dist/utils/getClientFromConfig.d.ts +0 -39
  222. package/dist/utils/getClientFromConfig.js +0 -199
  223. package/dist/utils/helperFunctions.d.ts +0 -63
  224. package/dist/utils/helperFunctions.js +0 -156
  225. package/dist/utils/pathResolvers.d.ts +0 -53
  226. package/dist/utils/pathResolvers.js +0 -72
  227. package/dist/utils/projectConfig.d.ts +0 -119
  228. package/dist/utils/projectConfig.js +0 -171
  229. package/dist/utils/retryFailedPromises.d.ts +0 -2
  230. package/dist/utils/retryFailedPromises.js +0 -23
  231. package/dist/utils/sessionAuth.d.ts +0 -48
  232. package/dist/utils/sessionAuth.js +0 -164
  233. package/dist/utils/typeGuards.d.ts +0 -35
  234. package/dist/utils/typeGuards.js +0 -57
  235. package/dist/utils/validationRules.d.ts +0 -43
  236. package/dist/utils/validationRules.js +0 -42
  237. package/dist/utils/versionDetection.d.ts +0 -58
  238. package/dist/utils/versionDetection.js +0 -251
  239. package/dist/utils/yamlConverter.d.ts +0 -100
  240. package/dist/utils/yamlConverter.js +0 -428
  241. package/dist/utils/yamlLoader.d.ts +0 -70
  242. package/dist/utils/yamlLoader.js +0 -267
  243. package/src/adapters/AdapterFactory.ts +0 -510
  244. package/src/adapters/DatabaseAdapter.ts +0 -306
  245. package/src/adapters/LegacyAdapter.ts +0 -841
  246. package/src/adapters/TablesDBAdapter.ts +0 -773
  247. package/src/config/ConfigManager.ts +0 -808
  248. package/src/config/README.md +0 -274
  249. package/src/config/configMigration.ts +0 -575
  250. package/src/config/configValidation.ts +0 -445
  251. package/src/config/index.ts +0 -10
  252. package/src/config/services/ConfigDiscoveryService.ts +0 -463
  253. package/src/config/services/ConfigLoaderService.ts +0 -740
  254. package/src/config/services/ConfigMergeService.ts +0 -388
  255. package/src/config/services/ConfigValidationService.ts +0 -394
  256. package/src/config/services/SessionAuthService.ts +0 -565
  257. package/src/config/services/__tests__/ConfigMergeService.test.ts +0 -351
  258. package/src/config/services/index.ts +0 -29
  259. package/src/config/yamlConfig.ts +0 -761
  260. package/src/functions/pathResolution.ts +0 -227
  261. package/src/shared/attributeMapper.ts +0 -229
  262. package/src/shared/errorUtils.ts +0 -110
  263. package/src/shared/functionManager.ts +0 -525
  264. package/src/shared/indexManager.ts +0 -254
  265. package/src/shared/jsonSchemaGenerator.ts +0 -383
  266. package/src/shared/logging.ts +0 -149
  267. package/src/shared/messageFormatter.ts +0 -208
  268. package/src/shared/pydanticModelGenerator.ts +0 -618
  269. package/src/shared/schemaGenerator.ts +0 -644
  270. package/src/utils/ClientFactory.ts +0 -240
  271. package/src/utils/configDiscovery.ts +0 -557
  272. package/src/utils/constantsGenerator.ts +0 -369
  273. package/src/utils/dataConverters.ts +0 -159
  274. package/src/utils/directoryUtils.ts +0 -61
  275. package/src/utils/getClientFromConfig.ts +0 -257
  276. package/src/utils/helperFunctions.ts +0 -228
  277. package/src/utils/pathResolvers.ts +0 -81
  278. package/src/utils/projectConfig.ts +0 -299
  279. package/src/utils/retryFailedPromises.ts +0 -29
  280. package/src/utils/sessionAuth.ts +0 -230
  281. package/src/utils/typeGuards.ts +0 -65
  282. package/src/utils/validationRules.ts +0 -88
  283. package/src/utils/versionDetection.ts +0 -292
  284. package/src/utils/yamlConverter.ts +0 -542
  285. package/src/utils/yamlLoader.ts +0 -371
@@ -1,761 +0,0 @@
1
- import { z } from "zod";
2
- import yaml from "js-yaml";
3
- import fs from "fs";
4
- import path from "path";
5
- import { AppwriteConfigSchema, type AppwriteConfig, RuntimeSchema, FunctionScopes, FunctionSpecifications, permissionsSchema, PermissionToAppwritePermission, type AppwriteFunction } from "@njdamstra/appwrite-utils";
6
- import { shouldIgnoreDirectory } from "../utils/directoryUtils.js";
7
- import { MessageFormatter } from "../shared/messageFormatter.js";
8
-
9
- const YamlConfigSchema = z.object({
10
- appwrite: z.object({
11
- endpoint: z.string().default("https://cloud.appwrite.io/v1"),
12
- project: z.string(),
13
- key: z.string(),
14
- // Session authentication support
15
- sessionCookie: z.string().optional(),
16
- authMethod: z.enum(["session", "apikey", "auto"]).optional().default("auto"),
17
- sessionMetadata: z.object({
18
- email: z.string().optional(),
19
- expiresAt: z.string().optional(),
20
- }).optional(),
21
- }),
22
- logging: z
23
- .object({
24
- enabled: z.boolean().default(false),
25
- level: z.enum(["error", "warn", "info", "debug"]).default("info"),
26
- directory: z.string().optional(),
27
- console: z.boolean().default(false),
28
- })
29
- .optional()
30
- .default({ enabled: false, level: "info", console: false }),
31
- backups: z
32
- .object({
33
- enabled: z.boolean().default(true),
34
- interval: z.number().default(3600),
35
- retention: z.number().default(30),
36
- cleanup: z.boolean().default(true),
37
- })
38
- .optional()
39
- .default({ enabled: true, interval: 3600, retention: 30, cleanup: true }),
40
- data: z
41
- .object({
42
- enableMockData: z.boolean().default(false),
43
- documentBucketId: z.string().default("documents"),
44
- usersCollectionName: z.string().default("Members"),
45
- importDirectory: z.string().default("importData"),
46
- })
47
- .optional()
48
- .default({
49
- enableMockData: false,
50
- documentBucketId: "documents",
51
- usersCollectionName: "Members",
52
- importDirectory: "importData",
53
- }),
54
- schemas: z
55
- .object({
56
- outputDirectory: z.string().default("schemas"),
57
- yamlSchemaDirectory: z.string().default(".yaml_schemas"),
58
- collectionsDirectory: z.string().default("collections"),
59
- tablesDirectory: z.string().default("tables"),
60
- })
61
- .optional()
62
- .default({
63
- outputDirectory: "schemas",
64
- yamlSchemaDirectory: ".yaml_schemas",
65
- collectionsDirectory: "collections",
66
- tablesDirectory: "tables",
67
- }),
68
- migrations: z
69
- .object({
70
- enabled: z.boolean().default(false),
71
- })
72
- .optional()
73
- .default({
74
- enabled: true,
75
- }),
76
- databases: z
77
- .array(
78
- z.object({
79
- id: z.string(),
80
- name: z.string(),
81
- bucket: z
82
- .object({
83
- id: z.string(),
84
- name: z.string(),
85
- permissions: permissionsSchema,
86
- fileSecurity: z.boolean().optional(),
87
- enabled: z.boolean().optional(),
88
- maximumFileSize: z.number().optional(),
89
- allowedFileExtensions: z.array(z.string()).optional(),
90
- compression: z.enum(["none", "gzip", "zstd"]).optional(),
91
- encryption: z.boolean().optional(),
92
- antivirus: z.boolean().optional(),
93
- })
94
- .optional(),
95
- })
96
- )
97
- .optional()
98
- .default([
99
- { id: "dev", name: "Development" },
100
- { id: "main", name: "Main" },
101
- { id: "staging", name: "Staging" },
102
- ]),
103
- buckets: z
104
- .array(
105
- z.object({
106
- id: z.string(),
107
- name: z.string(),
108
- permissions: permissionsSchema,
109
- fileSecurity: z.boolean().optional(),
110
- enabled: z.boolean().optional(),
111
- maximumFileSize: z.number().optional(),
112
- allowedFileExtensions: z.array(z.string()).optional(),
113
- compression: z.enum(["none", "gzip", "zstd"]).optional(),
114
- encryption: z.boolean().optional(),
115
- antivirus: z.boolean().optional(),
116
- })
117
- )
118
- .optional()
119
- .default([]),
120
- functions: z
121
- .array(
122
- z.object({
123
- id: z.string(),
124
- name: z.string(),
125
- runtime: RuntimeSchema,
126
- execute: z.array(z.string()).optional(),
127
- events: z.array(z.string()).optional(),
128
- schedule: z.string().optional(),
129
- timeout: z.number().optional(),
130
- enabled: z.boolean().optional(),
131
- logging: z.boolean().optional(),
132
- entrypoint: z.string().optional(),
133
- commands: z.string().optional(),
134
- scopes: z.array(FunctionScopes).optional(),
135
- installationId: z.string().optional(),
136
- providerRepositoryId: z.string().optional(),
137
- providerBranch: z.string().optional(),
138
- providerSilentMode: z.boolean().optional(),
139
- providerRootDirectory: z.string().optional(),
140
- templateRepository: z.string().optional(),
141
- templateOwner: z.string().optional(),
142
- templateRootDirectory: z.string().optional(),
143
- templateBranch: z.string().optional(),
144
- specification: FunctionSpecifications.optional(),
145
- // Critical missing fields for function deployment
146
- dirPath: z.string().optional(),
147
- predeployCommands: z.array(z.string()).optional(),
148
- deployDir: z.string().optional(),
149
- ignore: z.array(z.string()).optional(),
150
- templateVersion: z.string().optional(),
151
- })
152
- )
153
- .optional()
154
- .default([]),
155
- });
156
-
157
- export type YamlConfig = z.infer<typeof YamlConfigSchema>;
158
-
159
- export const convertYamlToAppwriteConfig = (yamlConfig: YamlConfig): AppwriteConfig => {
160
- const appwriteConfig: AppwriteConfig = {
161
- appwriteEndpoint: yamlConfig.appwrite.endpoint,
162
- appwriteProject: yamlConfig.appwrite.project,
163
- appwriteKey: yamlConfig.appwrite.key,
164
- // Session authentication support from YAML
165
- sessionCookie: yamlConfig.appwrite.sessionCookie,
166
- authMethod: yamlConfig.appwrite.authMethod || "auto",
167
- sessionMetadata: yamlConfig.appwrite.sessionMetadata,
168
- apiMode: "auto", // Default to auto-detect for dual API support
169
- appwriteClient: null,
170
- logging: {
171
- enabled: yamlConfig.logging.enabled,
172
- level: yamlConfig.logging.level,
173
- logDirectory: yamlConfig.logging.directory,
174
- console: yamlConfig.logging.console,
175
- },
176
- enableBackups: yamlConfig.backups.enabled,
177
- backupInterval: yamlConfig.backups.interval,
178
- backupRetention: yamlConfig.backups.retention,
179
- enableBackupCleanup: yamlConfig.backups.cleanup,
180
- enableMockData: yamlConfig.data.enableMockData,
181
- documentBucketId: yamlConfig.data.documentBucketId,
182
- usersCollectionName: yamlConfig.data.usersCollectionName,
183
- schemaConfig: {
184
- outputDirectory: yamlConfig.schemas.outputDirectory,
185
- yamlSchemaDirectory: yamlConfig.schemas.yamlSchemaDirectory,
186
- importDirectory: yamlConfig.data.importDirectory,
187
- collectionsDirectory: yamlConfig.schemas.collectionsDirectory || "collections",
188
- tablesDirectory: yamlConfig.schemas.tablesDirectory || "tables",
189
- },
190
- databases: yamlConfig.databases.map((db) => ({
191
- $id: db.id,
192
- name: db.name,
193
- bucket: db.bucket
194
- ? {
195
- $id: db.bucket.id,
196
- name: db.bucket.name,
197
- $permissions: PermissionToAppwritePermission(db.bucket.permissions),
198
- fileSecurity: db.bucket.fileSecurity || false,
199
- enabled: db.bucket.enabled || true,
200
- maximumFileSize: db.bucket.maximumFileSize || 30000000,
201
- allowedFileExtensions: db.bucket.allowedFileExtensions || [],
202
- compression: (db.bucket.compression as "none" | "gzip" | "zstd") || "none",
203
- encryption: db.bucket.encryption || false,
204
- antivirus: db.bucket.antivirus || false,
205
- }
206
- : undefined,
207
- })),
208
- buckets: yamlConfig.buckets.map((bucket) => ({
209
- $id: bucket.id,
210
- name: bucket.name,
211
- $permissions: PermissionToAppwritePermission(bucket.permissions),
212
- fileSecurity: bucket.fileSecurity || false,
213
- enabled: bucket.enabled || true,
214
- maximumFileSize: bucket.maximumFileSize || 30000000,
215
- allowedFileExtensions: bucket.allowedFileExtensions || [],
216
- compression: (bucket.compression as "none" | "gzip" | "zstd") || "none",
217
- encryption: bucket.encryption || false,
218
- antivirus: bucket.antivirus || false,
219
- })),
220
- functions: yamlConfig.functions?.map((func) => ({
221
- $id: func.id,
222
- name: func.name,
223
- runtime: func.runtime,
224
- execute: func.execute || [],
225
- events: func.events || [],
226
- schedule: func.schedule || "",
227
- timeout: func.timeout || 15,
228
- enabled: func.enabled || true,
229
- logging: func.logging || true,
230
- entrypoint: func.entrypoint || "",
231
- commands: func.commands || "",
232
- scopes: func.scopes || [],
233
- installationId: func.installationId || "",
234
- providerRepositoryId: func.providerRepositoryId || "",
235
- providerBranch: func.providerBranch || "",
236
- providerSilentMode: func.providerSilentMode || false,
237
- providerRootDirectory: func.providerRootDirectory || "",
238
- templateRepository: func.templateRepository || "",
239
- templateOwner: func.templateOwner || "",
240
- templateRootDirectory: func.templateRootDirectory || "",
241
- templateBranch: func.templateBranch || "",
242
- specification: func.specification || "s-0.5vcpu-512mb",
243
- // Include critical missing fields for function deployment
244
- dirPath: func.dirPath,
245
- predeployCommands: func.predeployCommands,
246
- deployDir: func.deployDir,
247
- ignore: func.ignore,
248
- templateVersion: func.templateVersion,
249
- })),
250
- collections: [], // Note: Collections are managed separately in YAML configs via individual collection files
251
- };
252
-
253
- return appwriteConfig;
254
- };
255
-
256
- /**
257
- * Enhanced config loading with session authentication support
258
- * Supports session override options for preserving session state
259
- */
260
- export interface YamlSessionOptions {
261
- sessionCookie?: string;
262
- authMethod?: "session" | "apikey" | "auto";
263
- sessionMetadata?: { email?: string; expiresAt?: string; };
264
- }
265
-
266
- /**
267
- * Load YAML config with optional session preservation
268
- * Maintains authentication priority: explicit session > YAML file > system prefs
269
- */
270
- export const loadYamlConfigWithSession = async (
271
- configPath: string,
272
- sessionOptions?: YamlSessionOptions
273
- ): Promise<AppwriteConfig | null> => {
274
- try {
275
- const fileContent = fs.readFileSync(configPath, "utf8");
276
- const yamlData = yaml.load(fileContent) as unknown;
277
-
278
- const yamlConfig = YamlConfigSchema.parse(yamlData);
279
- const appwriteConfig = convertYamlToAppwriteConfig(yamlConfig);
280
-
281
- // Apply session preservation if provided (explicit overrides take priority)
282
- if (sessionOptions) {
283
- if (sessionOptions.sessionCookie) {
284
- appwriteConfig.sessionCookie = sessionOptions.sessionCookie;
285
- }
286
- if (sessionOptions.authMethod) {
287
- appwriteConfig.authMethod = sessionOptions.authMethod;
288
- }
289
- if (sessionOptions.sessionMetadata) {
290
- appwriteConfig.sessionMetadata = sessionOptions.sessionMetadata;
291
- }
292
- }
293
-
294
- return appwriteConfig;
295
- } catch (error) {
296
- if (error instanceof z.ZodError) {
297
- MessageFormatter.error("YAML config validation failed", undefined, { prefix: "Config" });
298
- error.issues.forEach((err) => {
299
- MessageFormatter.error(`${err.path.join('.')} → ${err.message}`, undefined, { prefix: "Config" });
300
- });
301
- } else {
302
- MessageFormatter.error("Error loading YAML config", error instanceof Error ? error : undefined, { prefix: "Config" });
303
- if (error instanceof Error && error.stack) {
304
- MessageFormatter.debug("Stack trace", error.stack, { prefix: "Config" });
305
- }
306
- }
307
- return null;
308
- }
309
- };
310
-
311
- export const loadYamlConfig = async (configPath: string): Promise<AppwriteConfig | null> => {
312
- try {
313
- const fileContent = fs.readFileSync(configPath, "utf8");
314
- const yamlData = yaml.load(fileContent) as unknown;
315
-
316
- const yamlConfig = YamlConfigSchema.parse(yamlData);
317
- return convertYamlToAppwriteConfig(yamlConfig);
318
- } catch (error) {
319
- if (error instanceof z.ZodError) {
320
- MessageFormatter.error("YAML config validation failed", undefined, { prefix: "Config" });
321
- error.issues.forEach((err) => {
322
- MessageFormatter.error(`${err.path.join('.')} → ${err.message}`, undefined, { prefix: "Config" });
323
- });
324
- } else {
325
- MessageFormatter.error("Error loading YAML config", error instanceof Error ? error : undefined, { prefix: "Config" });
326
- if (error instanceof Error && error.stack) {
327
- MessageFormatter.debug("Stack trace", error.stack, { prefix: "Config" });
328
- }
329
- }
330
- return null;
331
- }
332
- };
333
-
334
- export const findYamlConfig = (startDir: string): string | null => {
335
- // First check current directory for YAML configs
336
- const possiblePaths = [
337
- path.join(startDir, ".appwrite", "config.yaml"),
338
- path.join(startDir, ".appwrite", "config.yml"),
339
- path.join(startDir, ".appwrite", "appwriteConfig.yaml"),
340
- path.join(startDir, ".appwrite", "appwriteConfig.yml"),
341
- path.join(startDir, "appwrite.yaml"),
342
- path.join(startDir, "appwrite.yml"),
343
- ];
344
-
345
- for (const configPath of possiblePaths) {
346
- if (fs.existsSync(configPath)) {
347
- return configPath;
348
- }
349
- }
350
-
351
- // Recursively search subdirectories for .appwrite folders
352
- const yamlConfigInSubdirs = findYamlConfigRecursive(startDir);
353
- if (yamlConfigInSubdirs) {
354
- return yamlConfigInSubdirs;
355
- }
356
-
357
- // Only check one level up to avoid infinite traversal
358
- const parentDir = path.dirname(startDir);
359
- if (parentDir !== startDir && path.basename(parentDir) !== 'node_modules') {
360
- const parentPossiblePaths = [
361
- path.join(parentDir, ".appwrite", "config.yaml"),
362
- path.join(parentDir, ".appwrite", "config.yml"),
363
- path.join(parentDir, ".appwrite", "appwriteConfig.yaml"),
364
- path.join(parentDir, ".appwrite", "appwriteConfig.yml"),
365
- path.join(parentDir, "appwrite.yaml"),
366
- path.join(parentDir, "appwrite.yml"),
367
- ];
368
-
369
- for (const configPath of parentPossiblePaths) {
370
- if (fs.existsSync(configPath)) {
371
- return configPath;
372
- }
373
- }
374
- }
375
-
376
- return null;
377
- };
378
-
379
- const findYamlConfigRecursive = (dir: string, depth: number = 0): string | null => {
380
- // Limit search depth to prevent infinite recursion
381
- if (depth > 5) {
382
- return null;
383
- }
384
-
385
- if (shouldIgnoreDirectory(path.basename(dir))) {
386
- return null;
387
- }
388
-
389
- try {
390
- const entries = fs.readdirSync(dir, { withFileTypes: true });
391
-
392
- for (const entry of entries) {
393
- if (entry.isDirectory() && !shouldIgnoreDirectory(entry.name)) {
394
- const fullPath = path.join(dir, entry.name);
395
-
396
- // Check if this is an .appwrite directory
397
- if (entry.name === ".appwrite") {
398
- const configPaths = [
399
- path.join(fullPath, "config.yaml"),
400
- path.join(fullPath, "config.yml"),
401
- path.join(fullPath, "appwriteConfig.yaml"),
402
- path.join(fullPath, "appwriteConfig.yml"),
403
- ];
404
-
405
- for (const configPath of configPaths) {
406
- if (fs.existsSync(configPath)) {
407
- return configPath;
408
- }
409
- }
410
- }
411
-
412
- // Recurse into other directories with increased depth
413
- const result = findYamlConfigRecursive(fullPath, depth + 1);
414
- if (result) return result;
415
- }
416
- }
417
- } catch (error) {
418
- // Ignore directory access errors
419
- }
420
-
421
- return null;
422
- };
423
-
424
- export const generateYamlConfigTemplate = (outputPath: string) => {
425
- const template: YamlConfig = {
426
- appwrite: {
427
- endpoint: "https://cloud.appwrite.io/v1",
428
- project: "YOUR_PROJECT_ID",
429
- key: "YOUR_API_KEY",
430
- authMethod: "auto" as const,
431
- // Optional session authentication (leave empty to use API key)
432
- // sessionCookie: "session_cookie_from_appwrite_cli",
433
- },
434
- logging: {
435
- enabled: false,
436
- level: "info",
437
- console: false,
438
- },
439
- backups: {
440
- enabled: true,
441
- interval: 3600,
442
- retention: 30,
443
- cleanup: true,
444
- },
445
- data: {
446
- enableMockData: false,
447
- documentBucketId: "documents",
448
- usersCollectionName: "Members",
449
- importDirectory: "importData",
450
- },
451
- schemas: {
452
- outputDirectory: "schemas",
453
- yamlSchemaDirectory: ".yaml_schemas",
454
- collectionsDirectory: "collections",
455
- tablesDirectory: "tables",
456
- },
457
- migrations: {
458
- enabled: true,
459
- },
460
- databases: [
461
- { id: "dev", name: "Development" },
462
- { id: "main", name: "Main" },
463
- { id: "staging", name: "Staging" },
464
- ],
465
- buckets: [],
466
- functions: [],
467
- };
468
-
469
- let yamlContent = yaml.dump(template, {
470
- indent: 2,
471
- lineWidth: 120,
472
- sortKeys: false,
473
- });
474
-
475
- // Add inline comments to the schemas section
476
- yamlContent = yamlContent.replace(
477
- /schemas:\s*\n(\s*)outputDirectory: schemas\n(\s*)yamlSchemaDirectory: \.yaml_schemas\n(\s*)collectionsDirectory: collections\n(\s*)tablesDirectory: tables/,
478
- `schemas:
479
- $1outputDirectory: schemas
480
- $2yamlSchemaDirectory: .yaml_schemas
481
- $3# Directory for legacy Databases API collection definitions
482
- $3collectionsDirectory: collections
483
- $4# Directory for new TablesDB API table definitions
484
- $4tablesDirectory: tables`
485
- );
486
-
487
- // Add schema reference header and documentation
488
- const schemaReference = "# yaml-language-server: $schema=./.yaml_schemas/appwrite-config.schema.json\n";
489
- const documentation = `# Appwrite Project Configuration
490
- #
491
- # Authentication Configuration:
492
- # - key: Standard API key authentication
493
- # - sessionCookie: Session cookie from Appwrite CLI authentication
494
- # - authMethod: "auto" (detects available method), "session" (prefer session), "apikey" (prefer API key)
495
- # - Priority: Explicit CLI args > YAML config > ~/.appwrite/prefs.json > Error
496
- #
497
- # Directory Configuration:
498
- # - collectionsDirectory: Use for legacy Databases API (default: "collections")
499
- # - tablesDirectory: Use for new TablesDB API (default: "tables")
500
- # - API mode is auto-detected based on server version, or set explicitly via apiMode
501
- #
502
- # For dual API support, both directories can coexist with different definitions
503
-
504
- `;
505
- const finalContent = schemaReference + documentation + yamlContent;
506
-
507
- fs.writeFileSync(outputPath, finalContent, "utf8");
508
- };
509
-
510
- /**
511
- * Converts AppwriteConfig back to YAML format and writes to file
512
- * @param configPath Path to the YAML config file
513
- * @param config The AppwriteConfig to convert and save
514
- */
515
- export const writeYamlConfig = async (configPath: string, config: AppwriteConfig): Promise<void> => {
516
- try {
517
- // Convert AppwriteConfig back to YAML format
518
- const yamlConfig: YamlConfig = {
519
- appwrite: {
520
- endpoint: config.appwriteEndpoint,
521
- project: config.appwriteProject,
522
- key: config.appwriteKey,
523
- // Include session authentication fields
524
- sessionCookie: config.sessionCookie,
525
- authMethod: config.authMethod || "auto",
526
- sessionMetadata: config.sessionMetadata,
527
- },
528
- logging: {
529
- enabled: config.logging?.enabled || false,
530
- level: config.logging?.level || "info",
531
- directory: config.logging?.logDirectory,
532
- console: config.logging?.console || false,
533
- },
534
- backups: {
535
- enabled: config.enableBackups !== false,
536
- interval: config.backupInterval || 3600,
537
- retention: config.backupRetention || 30,
538
- cleanup: config.enableBackupCleanup !== false,
539
- },
540
- data: {
541
- enableMockData: config.enableMockData || false,
542
- documentBucketId: config.documentBucketId || "documents",
543
- usersCollectionName: config.usersCollectionName || "Members",
544
- importDirectory: config.schemaConfig?.importDirectory || "importData",
545
- },
546
- schemas: {
547
- outputDirectory: config.schemaConfig?.outputDirectory || "schemas",
548
- yamlSchemaDirectory: config.schemaConfig?.yamlSchemaDirectory || ".yaml_schemas",
549
- collectionsDirectory: config.schemaConfig?.collectionsDirectory || "collections",
550
- tablesDirectory: config.schemaConfig?.tablesDirectory || "tables",
551
- },
552
- migrations: {
553
- enabled: true,
554
- },
555
- databases: config.databases?.map(db => ({
556
- id: db.$id,
557
- name: db.name,
558
- bucket: db.bucket ? {
559
- id: db.bucket.$id,
560
- name: db.bucket.name,
561
- permissions: db.bucket.permissions || [],
562
- fileSecurity: db.bucket.fileSecurity,
563
- enabled: db.bucket.enabled,
564
- maximumFileSize: db.bucket.maximumFileSize,
565
- allowedFileExtensions: db.bucket.allowedFileExtensions,
566
- compression: db.bucket.compression as "none" | "gzip" | "zstd",
567
- encryption: db.bucket.encryption,
568
- antivirus: db.bucket.antivirus,
569
- } : undefined,
570
- })) || [],
571
- buckets: config.buckets?.map(bucket => ({
572
- id: bucket.$id,
573
- name: bucket.name,
574
- permissions: bucket.permissions || [],
575
- fileSecurity: bucket.fileSecurity,
576
- enabled: bucket.enabled,
577
- maximumFileSize: bucket.maximumFileSize,
578
- allowedFileExtensions: bucket.allowedFileExtensions,
579
- compression: bucket.compression as "none" | "gzip" | "zstd",
580
- encryption: bucket.encryption,
581
- antivirus: bucket.antivirus,
582
- })) || [],
583
- functions: config.functions?.map(func => ({
584
- id: func.$id,
585
- name: func.name,
586
- runtime: func.runtime,
587
- execute: func.execute,
588
- events: func.events,
589
- schedule: func.schedule,
590
- timeout: func.timeout,
591
- enabled: func.enabled,
592
- logging: func.logging,
593
- entrypoint: func.entrypoint,
594
- commands: func.commands,
595
- scopes: func.scopes,
596
- installationId: func.installationId,
597
- providerRepositoryId: func.providerRepositoryId,
598
- providerBranch: func.providerBranch,
599
- providerSilentMode: func.providerSilentMode,
600
- providerRootDirectory: func.providerRootDirectory,
601
- templateRepository: func.templateRepository,
602
- templateOwner: func.templateOwner,
603
- templateRootDirectory: func.templateRootDirectory,
604
- specification: func.specification,
605
- // Include critical fields for function deployment
606
- dirPath: func.dirPath,
607
- predeployCommands: func.predeployCommands,
608
- deployDir: func.deployDir,
609
- ignore: func.ignore,
610
- templateVersion: func.templateVersion,
611
- })) || [],
612
- };
613
-
614
- // Write YAML config
615
- const yamlContent = yaml.dump(yamlConfig, {
616
- indent: 2,
617
- lineWidth: 120,
618
- sortKeys: false,
619
- });
620
-
621
- // Preserve schema reference if it exists
622
- let finalContent = yamlContent;
623
- if (fs.existsSync(configPath)) {
624
- const existingContent = fs.readFileSync(configPath, "utf8");
625
- const lines = existingContent.split('\n');
626
- const schemaLine = lines.find(line => line.startsWith('# yaml-language-server:'));
627
- const commentLine = lines.find(line => line.startsWith('# Appwrite Project Configuration'));
628
-
629
- if (schemaLine) {
630
- finalContent = schemaLine + '\n';
631
- if (commentLine) {
632
- finalContent += commentLine + '\n';
633
- }
634
- finalContent += yamlContent;
635
- }
636
- } else {
637
- // Add schema reference for new files
638
- const schemaReference = "# yaml-language-server: $schema=./.yaml_schemas/appwrite-config.schema.json\n";
639
- finalContent = schemaReference + "# Appwrite Project Configuration\n" + yamlContent;
640
- }
641
-
642
- fs.writeFileSync(configPath, finalContent, "utf8");
643
- MessageFormatter.success(`Updated YAML configuration at ${configPath}`, { prefix: "Config" });
644
- } catch (error) {
645
- MessageFormatter.error("Error writing YAML config", error instanceof Error ? error : undefined, { prefix: "Config" });
646
- throw error;
647
- }
648
- };
649
-
650
- /**
651
- * Adds a new function to the YAML config file
652
- * @param configPath Path to the YAML config file
653
- * @param newFunction The function configuration to add
654
- */
655
- export const addFunctionToYamlConfig = async (configPath: string, newFunction: AppwriteFunction): Promise<void> => {
656
- try {
657
- // Read current config
658
- const fileContent = fs.readFileSync(configPath, "utf8");
659
- const yamlData = yaml.load(fileContent) as any;
660
-
661
- // Initialize functions array if it doesn't exist
662
- if (!yamlData.functions) {
663
- yamlData.functions = [];
664
- }
665
-
666
- // Convert AppwriteFunction to YAML format
667
- const yamlFunction = {
668
- id: newFunction.$id,
669
- name: newFunction.name,
670
- runtime: newFunction.runtime,
671
- execute: newFunction.execute || ["any"],
672
- events: newFunction.events || [],
673
- schedule: newFunction.schedule || "",
674
- timeout: newFunction.timeout || 15,
675
- enabled: newFunction.enabled !== false,
676
- logging: newFunction.logging !== false,
677
- entrypoint: newFunction.entrypoint || "",
678
- commands: newFunction.commands || "",
679
- scopes: newFunction.scopes || [],
680
- specification: newFunction.specification || "s-0.5vcpu-512mb",
681
- // Include critical fields for function deployment if they exist
682
- ...(newFunction.dirPath && { dirPath: newFunction.dirPath }),
683
- ...(newFunction.predeployCommands && { predeployCommands: newFunction.predeployCommands }),
684
- ...(newFunction.deployDir && { deployDir: newFunction.deployDir }),
685
- ...(newFunction.ignore && { ignore: newFunction.ignore }),
686
- ...(newFunction.templateVersion && { templateVersion: newFunction.templateVersion }),
687
- };
688
-
689
- // Add new function
690
- yamlData.functions.push(yamlFunction);
691
-
692
- // Write back to file
693
- const updatedYamlContent = yaml.dump(yamlData, {
694
- indent: 2,
695
- lineWidth: 120,
696
- sortKeys: false,
697
- });
698
-
699
- // Preserve schema reference if it exists
700
- const lines = fileContent.split('\n');
701
- const schemaLine = lines.find(line => line.startsWith('# yaml-language-server:'));
702
- let finalContent = updatedYamlContent;
703
-
704
- if (schemaLine) {
705
- finalContent = schemaLine + '\n' + updatedYamlContent;
706
- }
707
-
708
- fs.writeFileSync(configPath, finalContent, "utf8");
709
- MessageFormatter.success(`Added function "${newFunction.name}" to YAML config`, { prefix: "Config" });
710
- } catch (error) {
711
- MessageFormatter.error("Error adding function to YAML config", error instanceof Error ? error : undefined, { prefix: "Config" });
712
- throw error;
713
- }
714
- };
715
-
716
- /**
717
- * Extract session options from AppwriteConfig for YAML operations
718
- * Useful for preserving session state during config reloads
719
- */
720
- export const extractSessionOptionsFromConfig = (config: AppwriteConfig): YamlSessionOptions => {
721
- return {
722
- sessionCookie: config.sessionCookie,
723
- authMethod: config.authMethod,
724
- sessionMetadata: config.sessionMetadata,
725
- };
726
- };
727
-
728
- /**
729
- * Create session-preserved YAML config operations
730
- * Maintains authentication state during config file updates
731
- */
732
- export const createSessionPreservingYamlConfig = (configPath: string, sessionOptions: YamlSessionOptions) => {
733
- return {
734
- load: () => loadYamlConfigWithSession(configPath, sessionOptions),
735
- write: (config: AppwriteConfig) => {
736
- // Merge session options into config before writing
737
- const enhancedConfig = {
738
- ...config,
739
- sessionCookie: sessionOptions.sessionCookie || config.sessionCookie,
740
- authMethod: sessionOptions.authMethod || config.authMethod,
741
- sessionMetadata: sessionOptions.sessionMetadata || config.sessionMetadata,
742
- };
743
- return writeYamlConfig(configPath, enhancedConfig);
744
- },
745
- addFunction: (func: AppwriteFunction) => addFunctionToYamlConfig(configPath, func),
746
- };
747
- };
748
-
749
- /**
750
- * Determine if YAML config has session authentication configured
751
- */
752
- export const hasYamlSessionAuth = (configPath: string): boolean => {
753
- try {
754
- const fileContent = fs.readFileSync(configPath, "utf8");
755
- const yamlData = yaml.load(fileContent) as any;
756
-
757
- return !!(yamlData?.appwrite?.sessionCookie && yamlData.appwrite.sessionCookie.trim());
758
- } catch (error) {
759
- return false;
760
- }
761
- };