appwrite-utils-cli 1.6.3 → 1.6.4

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 (55) hide show
  1. package/CONFIG_TODO.md +1189 -0
  2. package/SERVICE_IMPLEMENTATION_REPORT.md +462 -0
  3. package/dist/cli/commands/configCommands.js +7 -1
  4. package/dist/collections/attributes.js +102 -30
  5. package/dist/config/ConfigManager.d.ts +445 -0
  6. package/dist/config/ConfigManager.js +625 -0
  7. package/dist/config/index.d.ts +8 -0
  8. package/dist/config/index.js +7 -0
  9. package/dist/config/services/ConfigDiscoveryService.d.ts +126 -0
  10. package/dist/config/services/ConfigDiscoveryService.js +374 -0
  11. package/dist/config/services/ConfigLoaderService.d.ts +105 -0
  12. package/dist/config/services/ConfigLoaderService.js +410 -0
  13. package/dist/config/services/ConfigMergeService.d.ts +208 -0
  14. package/dist/config/services/ConfigMergeService.js +307 -0
  15. package/dist/config/services/ConfigValidationService.d.ts +214 -0
  16. package/dist/config/services/ConfigValidationService.js +310 -0
  17. package/dist/config/services/SessionAuthService.d.ts +225 -0
  18. package/dist/config/services/SessionAuthService.js +456 -0
  19. package/dist/config/services/__tests__/ConfigMergeService.test.d.ts +1 -0
  20. package/dist/config/services/__tests__/ConfigMergeService.test.js +271 -0
  21. package/dist/config/services/index.d.ts +13 -0
  22. package/dist/config/services/index.js +10 -0
  23. package/dist/interactiveCLI.js +8 -6
  24. package/dist/main.js +2 -2
  25. package/dist/migrations/yaml/YamlImportConfigLoader.d.ts +1 -1
  26. package/dist/shared/operationQueue.js +1 -1
  27. package/dist/utils/ClientFactory.d.ts +87 -0
  28. package/dist/utils/ClientFactory.js +164 -0
  29. package/dist/utils/getClientFromConfig.js +4 -3
  30. package/dist/utils/helperFunctions.d.ts +1 -0
  31. package/dist/utils/helperFunctions.js +21 -5
  32. package/dist/utils/yamlConverter.d.ts +2 -2
  33. package/dist/utils/yamlConverter.js +2 -2
  34. package/dist/utilsController.d.ts +18 -15
  35. package/dist/utilsController.js +83 -131
  36. package/package.json +1 -1
  37. package/src/cli/commands/configCommands.ts +8 -1
  38. package/src/collections/attributes.ts +118 -31
  39. package/src/config/ConfigManager.ts +808 -0
  40. package/src/config/index.ts +10 -0
  41. package/src/config/services/ConfigDiscoveryService.ts +463 -0
  42. package/src/config/services/ConfigLoaderService.ts +560 -0
  43. package/src/config/services/ConfigMergeService.ts +386 -0
  44. package/src/config/services/ConfigValidationService.ts +394 -0
  45. package/src/config/services/SessionAuthService.ts +565 -0
  46. package/src/config/services/__tests__/ConfigMergeService.test.ts +351 -0
  47. package/src/config/services/index.ts +29 -0
  48. package/src/interactiveCLI.ts +9 -7
  49. package/src/main.ts +2 -2
  50. package/src/shared/operationQueue.ts +1 -1
  51. package/src/utils/ClientFactory.ts +186 -0
  52. package/src/utils/getClientFromConfig.ts +4 -3
  53. package/src/utils/helperFunctions.ts +27 -7
  54. package/src/utils/yamlConverter.ts +4 -4
  55. package/src/utilsController.ts +99 -187
@@ -0,0 +1,310 @@
1
+ import { validateCollectionsTablesConfig, reportValidationResults } from "../configValidation.js";
2
+ import { MessageFormatter } from "../../shared/messageFormatter.js";
3
+ import { logger } from "../../shared/logging.js";
4
+ /**
5
+ * Service for validating Appwrite configuration with support for multiple validation modes
6
+ *
7
+ * This service provides centralized configuration validation with:
8
+ * - Standard validation (warnings allowed)
9
+ * - Strict validation (warnings treated as errors)
10
+ * - Detailed error reporting with suggestions
11
+ * - Configurable output verbosity
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * const validationService = new ConfigValidationService();
16
+ *
17
+ * // Standard validation
18
+ * const result = validationService.validate(config);
19
+ * if (!result.isValid) {
20
+ * validationService.reportResults(result, { verbose: true });
21
+ * }
22
+ *
23
+ * // Strict validation (warnings become errors)
24
+ * const strictResult = validationService.validateStrict(config);
25
+ * if (!strictResult.isValid) {
26
+ * throw new Error("Configuration validation failed in strict mode");
27
+ * }
28
+ * ```
29
+ */
30
+ export class ConfigValidationService {
31
+ /**
32
+ * Validate configuration with standard rules
33
+ *
34
+ * Standard validation allows warnings - the configuration is considered valid
35
+ * even if warnings are present. Only errors cause validation to fail.
36
+ *
37
+ * Validation checks include:
38
+ * - Basic structure validation (required fields, array structure)
39
+ * - Naming conflict detection (collections vs tables)
40
+ * - Database reference validation
41
+ * - Schema consistency validation
42
+ * - Duplicate definition detection
43
+ *
44
+ * @param config - Appwrite configuration to validate
45
+ * @returns Validation result with errors, warnings, and suggestions
46
+ *
47
+ * @example
48
+ * ```typescript
49
+ * const result = validationService.validate(config);
50
+ *
51
+ * if (result.isValid) {
52
+ * console.log("Configuration is valid");
53
+ * if (result.warnings.length > 0) {
54
+ * console.log(`Found ${result.warnings.length} warnings`);
55
+ * }
56
+ * } else {
57
+ * console.error(`Configuration has ${result.errors.length} errors`);
58
+ * }
59
+ * ```
60
+ */
61
+ validate(config) {
62
+ logger.debug("Starting configuration validation (standard mode)");
63
+ try {
64
+ const baseResult = validateCollectionsTablesConfig(config);
65
+ const result = {
66
+ isValid: baseResult.isValid,
67
+ errors: baseResult.errors,
68
+ warnings: baseResult.warnings,
69
+ suggestions: baseResult.suggestions
70
+ };
71
+ logger.debug("Configuration validation complete", {
72
+ isValid: result.isValid,
73
+ errorCount: result.errors.length,
74
+ warningCount: result.warnings.length,
75
+ suggestionCount: result.suggestions?.length || 0
76
+ });
77
+ return result;
78
+ }
79
+ catch (error) {
80
+ logger.error("Configuration validation failed with exception", {
81
+ error: error instanceof Error ? error.message : String(error)
82
+ });
83
+ return {
84
+ isValid: false,
85
+ errors: [
86
+ {
87
+ type: "schema_inconsistency",
88
+ message: "Configuration validation failed",
89
+ details: error instanceof Error ? error.message : String(error),
90
+ suggestion: "Check configuration file for syntax errors or invalid structure",
91
+ severity: "error"
92
+ }
93
+ ],
94
+ warnings: []
95
+ };
96
+ }
97
+ }
98
+ /**
99
+ * Validate configuration with strict rules
100
+ *
101
+ * Strict validation treats all warnings as errors. This is useful for:
102
+ * - CI/CD pipelines (fail builds on any issues)
103
+ * - Production deployments (ensure highest quality)
104
+ * - Configuration audits (enforce best practices)
105
+ *
106
+ * All warnings are promoted to errors, so the configuration is only
107
+ * considered valid if there are zero warnings and zero errors.
108
+ *
109
+ * @param config - Appwrite configuration to validate
110
+ * @returns Validation result with promoted warnings as errors
111
+ *
112
+ * @example
113
+ * ```typescript
114
+ * const result = validationService.validateStrict(config);
115
+ *
116
+ * if (!result.isValid) {
117
+ * console.error("Configuration failed strict validation");
118
+ * result.errors.forEach(err => {
119
+ * console.error(` - ${err.message}`);
120
+ * });
121
+ * process.exit(1);
122
+ * }
123
+ * ```
124
+ */
125
+ validateStrict(config) {
126
+ logger.debug("Starting configuration validation (strict mode)");
127
+ try {
128
+ const baseResult = validateCollectionsTablesConfig(config);
129
+ // In strict mode, promote all warnings to errors
130
+ const promotedWarnings = baseResult.warnings.map(warning => ({
131
+ ...warning,
132
+ severity: "error"
133
+ }));
134
+ const allErrors = [...baseResult.errors, ...promotedWarnings];
135
+ const result = {
136
+ isValid: allErrors.length === 0,
137
+ errors: allErrors,
138
+ warnings: [], // No warnings in strict mode - all promoted to errors
139
+ suggestions: baseResult.suggestions
140
+ };
141
+ logger.debug("Configuration validation complete (strict mode)", {
142
+ isValid: result.isValid,
143
+ errorCount: result.errors.length,
144
+ promotedWarnings: promotedWarnings.length,
145
+ suggestionCount: result.suggestions?.length || 0
146
+ });
147
+ return result;
148
+ }
149
+ catch (error) {
150
+ logger.error("Configuration validation failed with exception (strict mode)", {
151
+ error: error instanceof Error ? error.message : String(error)
152
+ });
153
+ return {
154
+ isValid: false,
155
+ errors: [
156
+ {
157
+ type: "schema_inconsistency",
158
+ message: "Configuration validation failed in strict mode",
159
+ details: error instanceof Error ? error.message : String(error),
160
+ suggestion: "Check configuration file for syntax errors or invalid structure",
161
+ severity: "error"
162
+ }
163
+ ],
164
+ warnings: []
165
+ };
166
+ }
167
+ }
168
+ /**
169
+ * Report validation results to console with formatted output
170
+ *
171
+ * Provides user-friendly formatting of validation results:
172
+ * - Color-coded output (errors in red, warnings in yellow, etc.)
173
+ * - Detailed error descriptions with suggestions
174
+ * - Affected items listing
175
+ * - Optional verbose mode for additional details
176
+ *
177
+ * @param validation - Validation result to report
178
+ * @param options - Reporting options (verbose, silent, exitOnError)
179
+ *
180
+ * @example
181
+ * ```typescript
182
+ * const result = validationService.validate(config);
183
+ *
184
+ * // Basic reporting
185
+ * validationService.reportResults(result);
186
+ *
187
+ * // Verbose reporting with all details
188
+ * validationService.reportResults(result, { verbose: true });
189
+ *
190
+ * // Report and exit on error (useful for scripts)
191
+ * validationService.reportResults(result, { exitOnError: true });
192
+ * ```
193
+ */
194
+ reportResults(validation, options = {}) {
195
+ const { verbose = false, silent = false, exitOnError = false } = options;
196
+ if (silent) {
197
+ // Only log to file, don't print to console
198
+ logger.info("Configuration validation results", {
199
+ isValid: validation.isValid,
200
+ errorCount: validation.errors.length,
201
+ warningCount: validation.warnings.length,
202
+ suggestionCount: validation.suggestions?.length || 0
203
+ });
204
+ if (validation.errors.length > 0) {
205
+ validation.errors.forEach(error => {
206
+ logger.error("Validation error", {
207
+ type: error.type,
208
+ message: error.message,
209
+ details: error.details,
210
+ suggestion: error.suggestion,
211
+ affectedItems: error.affectedItems
212
+ });
213
+ });
214
+ }
215
+ return;
216
+ }
217
+ // Use existing reportValidationResults for formatted console output
218
+ reportValidationResults({
219
+ isValid: validation.isValid,
220
+ errors: validation.errors,
221
+ warnings: validation.warnings,
222
+ suggestions: validation.suggestions || []
223
+ }, { verbose });
224
+ // Exit on error if requested
225
+ if (exitOnError && !validation.isValid) {
226
+ logger.error("Exiting due to validation errors");
227
+ process.exit(1);
228
+ }
229
+ }
230
+ /**
231
+ * Validate and report in a single call
232
+ *
233
+ * Convenience method that combines validation and reporting.
234
+ * Useful for quick validation checks in CLI commands.
235
+ *
236
+ * @param config - Appwrite configuration to validate
237
+ * @param strict - Use strict validation mode
238
+ * @param reportOptions - Reporting options
239
+ * @returns Validation result
240
+ *
241
+ * @example
242
+ * ```typescript
243
+ * // Quick validation with reporting
244
+ * const result = validationService.validateAndReport(config, false, {
245
+ * verbose: true,
246
+ * exitOnError: true
247
+ * });
248
+ * ```
249
+ */
250
+ validateAndReport(config, strict = false, reportOptions = {}) {
251
+ const result = strict ? this.validateStrict(config) : this.validate(config);
252
+ this.reportResults(result, reportOptions);
253
+ return result;
254
+ }
255
+ /**
256
+ * Check if configuration is valid without detailed reporting
257
+ *
258
+ * Quick validation check that returns a simple boolean.
259
+ * Useful for conditional logic where you don't need detailed error information.
260
+ *
261
+ * @param config - Appwrite configuration to validate
262
+ * @param strict - Use strict validation mode
263
+ * @returns true if configuration is valid, false otherwise
264
+ *
265
+ * @example
266
+ * ```typescript
267
+ * if (validationService.isValid(config)) {
268
+ * // Proceed with configuration
269
+ * } else {
270
+ * // Show error and prompt for correction
271
+ * }
272
+ * ```
273
+ */
274
+ isValid(config, strict = false) {
275
+ const result = strict ? this.validateStrict(config) : this.validate(config);
276
+ return result.isValid;
277
+ }
278
+ /**
279
+ * Get a summary of validation results as a formatted string
280
+ *
281
+ * Returns a human-readable summary of validation results suitable for
282
+ * logging or display in UIs.
283
+ *
284
+ * @param validation - Validation result to summarize
285
+ * @returns Formatted summary string
286
+ *
287
+ * @example
288
+ * ```typescript
289
+ * const result = validationService.validate(config);
290
+ * const summary = validationService.getSummary(result);
291
+ * console.log(summary);
292
+ * // Output: "Configuration valid with 2 warnings, 1 suggestion"
293
+ * ```
294
+ */
295
+ getSummary(validation) {
296
+ if (validation.isValid) {
297
+ const parts = ["Configuration valid"];
298
+ if (validation.warnings.length > 0) {
299
+ parts.push(`${validation.warnings.length} warning${validation.warnings.length > 1 ? "s" : ""}`);
300
+ }
301
+ if (validation.suggestions && validation.suggestions.length > 0) {
302
+ parts.push(`${validation.suggestions.length} suggestion${validation.suggestions.length > 1 ? "s" : ""}`);
303
+ }
304
+ return parts.join(" with ");
305
+ }
306
+ else {
307
+ return `Configuration invalid: ${validation.errors.length} error${validation.errors.length > 1 ? "s" : ""}`;
308
+ }
309
+ }
310
+ }
@@ -0,0 +1,225 @@
1
+ /**
2
+ * Session preferences stored in ~/.appwrite/prefs.json
3
+ */
4
+ export interface AppwriteSessionPrefs {
5
+ [projectId: string]: {
6
+ endpoint: string;
7
+ email: string;
8
+ cookie: string;
9
+ expiresAt?: string;
10
+ };
11
+ }
12
+ /**
13
+ * Session authentication information for a specific endpoint and project
14
+ */
15
+ export interface SessionAuthInfo {
16
+ endpoint: string;
17
+ projectId: string;
18
+ email?: string;
19
+ cookie: string;
20
+ expiresAt?: string;
21
+ }
22
+ /**
23
+ * Authentication status information
24
+ */
25
+ export interface AuthenticationStatus {
26
+ hasValidSession: boolean;
27
+ hasApiKey: boolean;
28
+ sessionExists: boolean;
29
+ endpointMatches: boolean;
30
+ cookieValid: boolean;
31
+ sessionInfo?: SessionAuthInfo;
32
+ message: string;
33
+ authMethod?: "session" | "apikey" | "none";
34
+ }
35
+ /**
36
+ * Service for managing Appwrite CLI session authentication with intelligent caching
37
+ *
38
+ * This service provides centralized session management with minimal file I/O through
39
+ * a multi-layered caching strategy:
40
+ * - Time-based cache (5 minute TTL)
41
+ * - File modification time validation
42
+ * - Content hash validation
43
+ *
44
+ * @example
45
+ * ```typescript
46
+ * const sessionService = new SessionAuthService();
47
+ * const session = await sessionService.findSession("https://cloud.appwrite.io/v1", "my-project-id");
48
+ *
49
+ * if (session && sessionService.isValidSession(session)) {
50
+ * // Use session for authentication
51
+ * console.log(`Authenticated as ${session.email}`);
52
+ * }
53
+ * ```
54
+ */
55
+ export declare class SessionAuthService {
56
+ private cache;
57
+ private readonly CACHE_TTL;
58
+ private readonly PREFS_PATH;
59
+ /**
60
+ * Creates a new SessionAuthService instance
61
+ *
62
+ * @param prefsPath - Optional custom path to prefs.json (defaults to ~/.appwrite/prefs.json)
63
+ */
64
+ constructor(prefsPath?: string);
65
+ /**
66
+ * Load session preferences from ~/.appwrite/prefs.json with intelligent caching
67
+ *
68
+ * Caching Strategy:
69
+ * 1. Return cached data if TTL has not expired
70
+ * 2. Validate file modification time - reload if changed
71
+ * 3. Validate content hash - reload if content changed
72
+ * 4. Cache is automatically invalidated after 5 minutes
73
+ *
74
+ * @returns Session preferences object or null if file doesn't exist or is invalid
75
+ *
76
+ * @example
77
+ * ```typescript
78
+ * const prefs = await sessionService.loadSessionPrefs();
79
+ * if (prefs) {
80
+ * console.log(`Found ${Object.keys(prefs).length} stored sessions`);
81
+ * }
82
+ * ```
83
+ */
84
+ loadSessionPrefs(): Promise<AppwriteSessionPrefs | null>;
85
+ /**
86
+ * Find session authentication info for a specific endpoint and project
87
+ *
88
+ * This method searches the session preferences for a matching endpoint and project ID.
89
+ * Both endpoint and projectId must match for a session to be returned.
90
+ *
91
+ * @param endpoint - Appwrite endpoint URL (e.g., "https://cloud.appwrite.io/v1")
92
+ * @param projectId - Appwrite project ID
93
+ * @returns Session info or null if no matching session found
94
+ *
95
+ * @example
96
+ * ```typescript
97
+ * const session = await sessionService.findSession(
98
+ * "https://cloud.appwrite.io/v1",
99
+ * "my-project-id"
100
+ * );
101
+ *
102
+ * if (session) {
103
+ * console.log(`Using session for ${session.email}`);
104
+ * }
105
+ * ```
106
+ */
107
+ findSession(endpoint: string, projectId: string): Promise<SessionAuthInfo | null>;
108
+ /**
109
+ * Validate if a session appears to be valid
110
+ *
111
+ * Performs structural validation of the session:
112
+ * - Cookie format validation (JWT-like structure)
113
+ * - Expiration check (if expiresAt is provided)
114
+ * - Basic cookie integrity checks
115
+ *
116
+ * Note: This does NOT verify the session with the server.
117
+ *
118
+ * @param session - Session info to validate
119
+ * @returns true if session appears valid, false otherwise
120
+ *
121
+ * @example
122
+ * ```typescript
123
+ * const session = await sessionService.findSession(endpoint, projectId);
124
+ * if (session && sessionService.isValidSession(session)) {
125
+ * // Session is structurally valid
126
+ * }
127
+ * ```
128
+ */
129
+ isValidSession(session: SessionAuthInfo): boolean;
130
+ /**
131
+ * Get detailed authentication status for a given endpoint and project
132
+ *
133
+ * Provides comprehensive authentication status including:
134
+ * - Session validation
135
+ * - API key presence
136
+ * - Detailed diagnostic information
137
+ * - Actionable error messages
138
+ *
139
+ * @param endpoint - Appwrite endpoint URL
140
+ * @param projectId - Appwrite project ID
141
+ * @param apiKey - Optional API key for authentication
142
+ * @param session - Optional pre-loaded session (avoids re-loading)
143
+ * @returns Detailed authentication status
144
+ *
145
+ * @example
146
+ * ```typescript
147
+ * const status = await sessionService.getAuthenticationStatus(
148
+ * "https://cloud.appwrite.io/v1",
149
+ * "my-project-id",
150
+ * process.env.APPWRITE_API_KEY
151
+ * );
152
+ *
153
+ * console.log(status.message);
154
+ * if (status.hasValidSession) {
155
+ * console.log(`Authenticated as ${status.sessionInfo?.email}`);
156
+ * } else if (status.hasApiKey) {
157
+ * console.log("Using API key authentication");
158
+ * }
159
+ * ```
160
+ */
161
+ getAuthenticationStatus(endpoint: string, projectId: string, apiKey?: string, session?: SessionAuthInfo | null): Promise<AuthenticationStatus>;
162
+ /**
163
+ * Manually invalidate the cache
164
+ *
165
+ * Forces the next loadSessionPrefs() call to read from disk.
166
+ * Useful after external changes to prefs.json (e.g., after login/logout).
167
+ *
168
+ * @example
169
+ * ```typescript
170
+ * // After user logs in
171
+ * sessionService.invalidateCache();
172
+ * const newSession = await sessionService.loadSessionPrefs();
173
+ * ```
174
+ */
175
+ invalidateCache(): void;
176
+ /**
177
+ * Normalize an endpoint URL for comparison
178
+ *
179
+ * @param url - Endpoint URL to normalize
180
+ * @returns Normalized URL (lowercase, no trailing slashes)
181
+ */
182
+ private normalizeEndpoint;
183
+ /**
184
+ * Validate session cookie format
185
+ *
186
+ * Performs basic validation to check if a cookie appears to be a valid Appwrite session:
187
+ * - Minimum length check
188
+ * - JWT-like structure (contains dots)
189
+ * - Valid character set
190
+ * - Multi-part structure
191
+ *
192
+ * @param cookie - Cookie string to validate
193
+ * @returns true if cookie appears valid, false otherwise
194
+ */
195
+ private isValidSessionCookie;
196
+ /**
197
+ * Generate MD5 hash of content for cache validation
198
+ *
199
+ * @param content - Content to hash
200
+ * @returns MD5 hash as hex string
201
+ */
202
+ private hashContent;
203
+ /**
204
+ * Get all available sessions from prefs
205
+ *
206
+ * Returns all sessions stored in the preferences file that pass
207
+ * basic validation checks.
208
+ *
209
+ * @returns Array of valid session info objects
210
+ *
211
+ * @example
212
+ * ```typescript
213
+ * const sessions = await sessionService.getAvailableSessions();
214
+ * console.log(`Found ${sessions.length} available sessions`);
215
+ * sessions.forEach(s => console.log(` - ${s.projectId} (${s.email})`));
216
+ * ```
217
+ */
218
+ getAvailableSessions(): Promise<SessionAuthInfo[]>;
219
+ /**
220
+ * Get the path to the prefs.json file
221
+ *
222
+ * @returns Absolute path to prefs.json
223
+ */
224
+ getPrefsPath(): string;
225
+ }