appwrite-utils-cli 0.10.85 → 1.0.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 (178) hide show
  1. package/.appwrite/.yaml_schemas/appwrite-config.schema.json +380 -0
  2. package/.appwrite/.yaml_schemas/collection.schema.json +255 -0
  3. package/.appwrite/collections/Categories.yaml +182 -0
  4. package/.appwrite/collections/ExampleCollection.yaml +36 -0
  5. package/.appwrite/collections/Posts.yaml +227 -0
  6. package/.appwrite/collections/Users.yaml +149 -0
  7. package/.appwrite/config.yaml +109 -0
  8. package/.appwrite/import/README.md +148 -0
  9. package/.appwrite/import/categories-import.yaml +129 -0
  10. package/.appwrite/import/posts-import.yaml +208 -0
  11. package/.appwrite/import/users-import.yaml +130 -0
  12. package/.appwrite/importData/categories.json +194 -0
  13. package/.appwrite/importData/posts.json +270 -0
  14. package/.appwrite/importData/users.json +220 -0
  15. package/.appwrite/schemas/categories.json +128 -0
  16. package/.appwrite/schemas/exampleCollection.json +52 -0
  17. package/.appwrite/schemas/posts.json +173 -0
  18. package/.appwrite/schemas/users.json +125 -0
  19. package/README.md +261 -33
  20. package/dist/collections/attributes.js +3 -2
  21. package/dist/collections/methods.js +56 -38
  22. package/dist/config/yamlConfig.d.ts +501 -0
  23. package/dist/config/yamlConfig.js +452 -0
  24. package/dist/databases/setup.d.ts +6 -0
  25. package/dist/databases/setup.js +119 -0
  26. package/dist/functions/methods.d.ts +1 -1
  27. package/dist/functions/methods.js +5 -2
  28. package/dist/functions/openapi.d.ts +4 -0
  29. package/dist/functions/openapi.js +60 -0
  30. package/dist/interactiveCLI.d.ts +5 -0
  31. package/dist/interactiveCLI.js +196 -52
  32. package/dist/main.js +91 -30
  33. package/dist/migrations/afterImportActions.js +2 -2
  34. package/dist/migrations/appwriteToX.d.ts +10 -0
  35. package/dist/migrations/appwriteToX.js +15 -4
  36. package/dist/migrations/backup.d.ts +16 -16
  37. package/dist/migrations/dataLoader.d.ts +83 -1
  38. package/dist/migrations/dataLoader.js +4 -4
  39. package/dist/migrations/importController.js +25 -18
  40. package/dist/migrations/importDataActions.js +2 -2
  41. package/dist/migrations/logging.d.ts +9 -1
  42. package/dist/migrations/logging.js +41 -22
  43. package/dist/migrations/migrationHelper.d.ts +4 -4
  44. package/dist/migrations/relationships.js +1 -1
  45. package/dist/migrations/services/DataTransformationService.d.ts +55 -0
  46. package/dist/migrations/services/DataTransformationService.js +158 -0
  47. package/dist/migrations/services/FileHandlerService.d.ts +75 -0
  48. package/dist/migrations/services/FileHandlerService.js +236 -0
  49. package/dist/migrations/services/ImportOrchestrator.d.ts +97 -0
  50. package/dist/migrations/services/ImportOrchestrator.js +488 -0
  51. package/dist/migrations/services/RateLimitManager.d.ts +138 -0
  52. package/dist/migrations/services/RateLimitManager.js +279 -0
  53. package/dist/migrations/services/RelationshipResolver.d.ts +120 -0
  54. package/dist/migrations/services/RelationshipResolver.js +332 -0
  55. package/dist/migrations/services/UserMappingService.d.ts +109 -0
  56. package/dist/migrations/services/UserMappingService.js +277 -0
  57. package/dist/migrations/services/ValidationService.d.ts +74 -0
  58. package/dist/migrations/services/ValidationService.js +260 -0
  59. package/dist/migrations/transfer.d.ts +0 -6
  60. package/dist/migrations/transfer.js +16 -132
  61. package/dist/migrations/yaml/YamlImportConfigLoader.d.ts +384 -0
  62. package/dist/migrations/yaml/YamlImportConfigLoader.js +375 -0
  63. package/dist/migrations/yaml/YamlImportIntegration.d.ts +87 -0
  64. package/dist/migrations/yaml/YamlImportIntegration.js +330 -0
  65. package/dist/migrations/yaml/generateImportSchemas.d.ts +17 -0
  66. package/dist/migrations/yaml/generateImportSchemas.js +575 -0
  67. package/dist/schemas/authUser.d.ts +9 -9
  68. package/dist/shared/attributeManager.d.ts +17 -0
  69. package/dist/shared/attributeManager.js +273 -0
  70. package/dist/shared/confirmationDialogs.d.ts +75 -0
  71. package/dist/shared/confirmationDialogs.js +236 -0
  72. package/dist/shared/functionManager.d.ts +48 -0
  73. package/dist/shared/functionManager.js +322 -0
  74. package/dist/shared/indexManager.d.ts +24 -0
  75. package/dist/shared/indexManager.js +150 -0
  76. package/dist/shared/jsonSchemaGenerator.d.ts +51 -0
  77. package/dist/shared/jsonSchemaGenerator.js +313 -0
  78. package/dist/shared/logging.d.ts +10 -0
  79. package/dist/shared/logging.js +46 -0
  80. package/dist/shared/messageFormatter.d.ts +37 -0
  81. package/dist/shared/messageFormatter.js +152 -0
  82. package/dist/shared/migrationHelpers.d.ts +173 -0
  83. package/dist/shared/migrationHelpers.js +142 -0
  84. package/dist/shared/operationLogger.d.ts +3 -0
  85. package/dist/shared/operationLogger.js +25 -0
  86. package/dist/shared/operationQueue.d.ts +13 -0
  87. package/dist/shared/operationQueue.js +79 -0
  88. package/dist/shared/progressManager.d.ts +62 -0
  89. package/dist/shared/progressManager.js +215 -0
  90. package/dist/shared/schemaGenerator.d.ts +18 -0
  91. package/dist/shared/schemaGenerator.js +523 -0
  92. package/dist/storage/methods.d.ts +3 -1
  93. package/dist/storage/methods.js +144 -55
  94. package/dist/storage/schemas.d.ts +56 -16
  95. package/dist/types.d.ts +2 -2
  96. package/dist/types.js +1 -1
  97. package/dist/users/methods.d.ts +16 -0
  98. package/dist/users/methods.js +276 -0
  99. package/dist/utils/configMigration.d.ts +1 -0
  100. package/dist/utils/configMigration.js +156 -0
  101. package/dist/utils/dataConverters.d.ts +46 -0
  102. package/dist/utils/dataConverters.js +139 -0
  103. package/dist/utils/loadConfigs.d.ts +15 -4
  104. package/dist/utils/loadConfigs.js +377 -51
  105. package/dist/utils/schemaStrings.js +2 -1
  106. package/dist/utils/setupFiles.d.ts +2 -1
  107. package/dist/utils/setupFiles.js +723 -28
  108. package/dist/utils/validationRules.d.ts +43 -0
  109. package/dist/utils/validationRules.js +42 -0
  110. package/dist/utils/yamlConverter.d.ts +48 -0
  111. package/dist/utils/yamlConverter.js +98 -0
  112. package/dist/utilsController.js +65 -43
  113. package/package.json +19 -15
  114. package/src/collections/attributes.ts +3 -2
  115. package/src/collections/methods.ts +85 -51
  116. package/src/config/yamlConfig.ts +488 -0
  117. package/src/{migrations/setupDatabase.ts → databases/setup.ts} +11 -5
  118. package/src/functions/methods.ts +8 -4
  119. package/src/functions/templates/count-docs-in-collection/package.json +25 -0
  120. package/src/functions/templates/count-docs-in-collection/tsconfig.json +28 -0
  121. package/src/functions/templates/typescript-node/package.json +24 -0
  122. package/src/functions/templates/typescript-node/tsconfig.json +28 -0
  123. package/src/functions/templates/uv/README.md +31 -0
  124. package/src/functions/templates/uv/pyproject.toml +29 -0
  125. package/src/interactiveCLI.ts +230 -63
  126. package/src/main.ts +111 -37
  127. package/src/migrations/afterImportActions.ts +2 -2
  128. package/src/migrations/appwriteToX.ts +17 -4
  129. package/src/migrations/dataLoader.ts +4 -4
  130. package/src/migrations/importController.ts +30 -22
  131. package/src/migrations/importDataActions.ts +2 -2
  132. package/src/migrations/relationships.ts +1 -1
  133. package/src/migrations/services/DataTransformationService.ts +196 -0
  134. package/src/migrations/services/FileHandlerService.ts +311 -0
  135. package/src/migrations/services/ImportOrchestrator.ts +669 -0
  136. package/src/migrations/services/RateLimitManager.ts +363 -0
  137. package/src/migrations/services/RelationshipResolver.ts +461 -0
  138. package/src/migrations/services/UserMappingService.ts +345 -0
  139. package/src/migrations/services/ValidationService.ts +349 -0
  140. package/src/migrations/transfer.ts +22 -228
  141. package/src/migrations/yaml/YamlImportConfigLoader.ts +427 -0
  142. package/src/migrations/yaml/YamlImportIntegration.ts +419 -0
  143. package/src/migrations/yaml/generateImportSchemas.ts +589 -0
  144. package/src/shared/attributeManager.ts +429 -0
  145. package/src/shared/confirmationDialogs.ts +327 -0
  146. package/src/shared/functionManager.ts +515 -0
  147. package/src/shared/indexManager.ts +253 -0
  148. package/src/shared/jsonSchemaGenerator.ts +403 -0
  149. package/src/shared/logging.ts +74 -0
  150. package/src/shared/messageFormatter.ts +195 -0
  151. package/src/{migrations/migrationHelper.ts → shared/migrationHelpers.ts} +22 -4
  152. package/src/{migrations/helper.ts → shared/operationLogger.ts} +7 -2
  153. package/src/{migrations/queue.ts → shared/operationQueue.ts} +1 -1
  154. package/src/shared/progressManager.ts +278 -0
  155. package/src/{migrations/schemaStrings.ts → shared/schemaGenerator.ts} +71 -17
  156. package/src/storage/methods.ts +199 -78
  157. package/src/types.ts +2 -2
  158. package/src/{migrations/users.ts → users/methods.ts} +2 -2
  159. package/src/utils/configMigration.ts +212 -0
  160. package/src/utils/loadConfigs.ts +414 -52
  161. package/src/utils/schemaStrings.ts +2 -1
  162. package/src/utils/setupFiles.ts +742 -40
  163. package/src/{migrations → utils}/validationRules.ts +1 -1
  164. package/src/utils/yamlConverter.ts +131 -0
  165. package/src/utilsController.ts +75 -54
  166. package/src/functions/templates/poetry/README.md +0 -30
  167. package/src/functions/templates/poetry/pyproject.toml +0 -16
  168. package/src/migrations/attributes.ts +0 -561
  169. package/src/migrations/backup.ts +0 -205
  170. package/src/migrations/databases.ts +0 -39
  171. package/src/migrations/dbHelpers.ts +0 -92
  172. package/src/migrations/indexes.ts +0 -40
  173. package/src/migrations/logging.ts +0 -29
  174. package/src/migrations/storage.ts +0 -538
  175. /package/src/{migrations → functions}/openapi.ts +0 -0
  176. /package/src/functions/templates/{poetry → uv}/src/__init__.py +0 -0
  177. /package/src/functions/templates/{poetry → uv}/src/index.py +0 -0
  178. /package/src/{migrations/converters.ts → utils/dataConverters.ts} +0 -0
@@ -0,0 +1,236 @@
1
+ import path from "path";
2
+ import fs from "fs";
3
+ import { logger } from "../../shared/logging.js";
4
+ import { RateLimitManager } from "./RateLimitManager.js";
5
+ /**
6
+ * Service responsible for file handling during import.
7
+ * Preserves all existing file handling capabilities including URL support.
8
+ * Extracted from DataLoader to provide focused, testable file operations.
9
+ */
10
+ export class FileHandlerService {
11
+ appwriteFolderPath;
12
+ config;
13
+ importDataActions;
14
+ rateLimitManager;
15
+ constructor(appwriteFolderPath, config, importDataActions, rateLimitManager) {
16
+ this.appwriteFolderPath = appwriteFolderPath;
17
+ this.config = config;
18
+ this.importDataActions = importDataActions;
19
+ this.rateLimitManager = rateLimitManager || new RateLimitManager();
20
+ }
21
+ /**
22
+ * Generates attribute mappings with post-import actions based on the provided attribute mappings.
23
+ * This method checks each mapping for a fileData attribute and adds a post-import action to create a file
24
+ * and update the field with the file's ID if necessary.
25
+ *
26
+ * Preserves existing file handling logic from DataLoader.
27
+ *
28
+ * @param attributeMappings - The attribute mappings from the import definition.
29
+ * @param context - The context object containing information about the database, collection, and document.
30
+ * @param item - The item being imported, used for resolving template paths in fileData mappings.
31
+ * @returns The attribute mappings updated with any necessary post-import actions.
32
+ */
33
+ getAttributeMappingsWithFileActions(attributeMappings, context, item) {
34
+ // Iterate over each attribute mapping to check for fileData attributes
35
+ return attributeMappings.map((mapping) => {
36
+ if (mapping.fileData) {
37
+ // Resolve the file path using the provided template, context, and item
38
+ let mappingFilePath = this.importDataActions.resolveTemplate(mapping.fileData.path, context, item);
39
+ // Ensure the file path is absolute if it doesn't start with "http"
40
+ if (!mappingFilePath.toLowerCase().startsWith("http")) {
41
+ mappingFilePath = this.resolveLocalFilePath(mappingFilePath);
42
+ }
43
+ // Define the after-import action to create a file and update the field
44
+ const afterImportAction = {
45
+ action: "createFileAndUpdateField",
46
+ params: [
47
+ "{dbId}",
48
+ "{collId}",
49
+ "{docId}",
50
+ mapping.targetKey,
51
+ `${this.config.documentBucketId}_${context.dbName
52
+ .toLowerCase()
53
+ .replace(" ", "")}`, // Bucket ID pattern
54
+ mappingFilePath,
55
+ mapping.fileData.name,
56
+ ],
57
+ };
58
+ // Add the after-import action to the mapping's postImportActions array
59
+ const postImportActions = mapping.postImportActions
60
+ ? [...mapping.postImportActions, afterImportAction]
61
+ : [afterImportAction];
62
+ return { ...mapping, postImportActions };
63
+ }
64
+ // Return the mapping unchanged if no fileData attribute is found
65
+ return mapping;
66
+ });
67
+ }
68
+ /**
69
+ * Resolves local file path, searching in subdirectories if needed.
70
+ * Preserves existing file search logic from DataLoader.
71
+ *
72
+ * @param mappingFilePath - The relative file path from the mapping
73
+ * @returns Resolved absolute file path
74
+ */
75
+ resolveLocalFilePath(mappingFilePath) {
76
+ // First try the direct path
77
+ let fullPath = path.resolve(this.appwriteFolderPath, mappingFilePath);
78
+ // If file doesn't exist, search in subdirectories
79
+ if (!fs.existsSync(fullPath)) {
80
+ const findFileInDir = (dir) => {
81
+ try {
82
+ const files = fs.readdirSync(dir);
83
+ for (const file of files) {
84
+ const filePath = path.join(dir, file);
85
+ const stat = fs.statSync(filePath);
86
+ if (stat.isDirectory()) {
87
+ // Recursively search subdirectories
88
+ const found = findFileInDir(filePath);
89
+ if (found)
90
+ return found;
91
+ }
92
+ else if (file === path.basename(mappingFilePath)) {
93
+ return filePath;
94
+ }
95
+ }
96
+ }
97
+ catch (error) {
98
+ logger.warn(`Error reading directory ${dir}: ${error}`);
99
+ }
100
+ return null;
101
+ };
102
+ const foundPath = findFileInDir(this.appwriteFolderPath);
103
+ if (foundPath) {
104
+ mappingFilePath = foundPath;
105
+ }
106
+ else {
107
+ logger.warn(`File not found in any subdirectory: ${mappingFilePath}`);
108
+ // Keep the original resolved path as fallback
109
+ mappingFilePath = fullPath;
110
+ }
111
+ }
112
+ else {
113
+ mappingFilePath = fullPath;
114
+ }
115
+ return mappingFilePath;
116
+ }
117
+ /**
118
+ * Executes file-related post-import actions with rate limiting.
119
+ * Wraps the existing createFileAndUpdateField action with proper error handling and rate limiting.
120
+ *
121
+ * @param context - The context containing document and collection information
122
+ * @param postImportActions - The post-import actions to execute
123
+ */
124
+ async executeFileActions(context, postImportActions) {
125
+ const fileActions = postImportActions.filter(action => action.action === "createFileAndUpdateField");
126
+ if (fileActions.length === 0) {
127
+ return;
128
+ }
129
+ // Execute file actions with rate limiting
130
+ const filePromises = fileActions.map(action => this.rateLimitManager.fileUpload(() => this.executeFileAction(action, context)));
131
+ try {
132
+ await Promise.allSettled(filePromises);
133
+ }
134
+ catch (error) {
135
+ logger.error(`Error executing file actions for context: ${JSON.stringify(context, null, 2)}`, error);
136
+ }
137
+ }
138
+ /**
139
+ * Executes a single file action with proper error handling.
140
+ *
141
+ * @param action - The file action to execute
142
+ * @param context - The context for template resolution
143
+ */
144
+ async executeFileAction(action, context) {
145
+ try {
146
+ // Resolve parameters using existing template resolution
147
+ const resolvedParams = action.params.map((param) => this.importDataActions.resolveTemplate(param, context, context));
148
+ // Execute the createFileAndUpdateField action
149
+ await this.importDataActions.executeAction(action.action, resolvedParams, context, context);
150
+ }
151
+ catch (error) {
152
+ logger.error(`Failed to execute file action '${action.action}' with params: ${JSON.stringify(action.params, null, 2)}`, error);
153
+ // Don't throw - we want to continue with other file operations
154
+ }
155
+ }
156
+ /**
157
+ * Validates that file paths exist before import begins.
158
+ * Provides early validation to catch file issues before processing starts.
159
+ *
160
+ * @param attributeMappings - The attribute mappings to validate
161
+ * @param context - The context for template resolution
162
+ * @param item - The item for template resolution
163
+ * @returns Array of validation errors (empty if all valid)
164
+ */
165
+ validateFilePaths(attributeMappings, context, item) {
166
+ const errors = [];
167
+ for (const mapping of attributeMappings) {
168
+ if (mapping.fileData) {
169
+ try {
170
+ let filePath = this.importDataActions.resolveTemplate(mapping.fileData.path, context, item);
171
+ // Skip URL validation (URLs are handled by the action itself)
172
+ if (filePath.toLowerCase().startsWith("http")) {
173
+ continue;
174
+ }
175
+ // Check if local file exists
176
+ const resolvedPath = this.resolveLocalFilePath(filePath);
177
+ if (!fs.existsSync(resolvedPath)) {
178
+ errors.push(`File not found for mapping '${mapping.targetKey}': ${resolvedPath}`);
179
+ }
180
+ }
181
+ catch (error) {
182
+ errors.push(`Error validating file path for mapping '${mapping.targetKey}': ${error}`);
183
+ }
184
+ }
185
+ }
186
+ return errors;
187
+ }
188
+ /**
189
+ * Gets file statistics for import planning.
190
+ * Helps estimate import time and resource requirements.
191
+ *
192
+ * @param attributeMappings - The attribute mappings to analyze
193
+ * @param items - The items that will be imported
194
+ * @returns File statistics object
195
+ */
196
+ getFileStatistics(attributeMappings, items) {
197
+ let totalFiles = 0;
198
+ let urlFiles = 0;
199
+ let localFiles = 0;
200
+ let estimatedSize = 0;
201
+ const fileAttributeMappings = attributeMappings.filter(mapping => mapping.fileData);
202
+ for (const item of items) {
203
+ for (const mapping of fileAttributeMappings) {
204
+ totalFiles++;
205
+ try {
206
+ const filePath = this.importDataActions.resolveTemplate(mapping.fileData.path, {}, item);
207
+ if (filePath.toLowerCase().startsWith("http")) {
208
+ urlFiles++;
209
+ }
210
+ else {
211
+ localFiles++;
212
+ try {
213
+ const resolvedPath = this.resolveLocalFilePath(filePath);
214
+ if (fs.existsSync(resolvedPath)) {
215
+ const stats = fs.statSync(resolvedPath);
216
+ estimatedSize += stats.size;
217
+ }
218
+ }
219
+ catch (error) {
220
+ // Ignore errors for statistics
221
+ }
222
+ }
223
+ }
224
+ catch (error) {
225
+ // Ignore errors for statistics
226
+ }
227
+ }
228
+ }
229
+ return {
230
+ totalFiles,
231
+ urlFiles,
232
+ localFiles,
233
+ estimatedSize
234
+ };
235
+ }
236
+ }
@@ -0,0 +1,97 @@
1
+ import { type Databases, type Models, type Storage } from "node-appwrite";
2
+ import type { AppwriteConfig } from "appwrite-utils";
3
+ import { type RateLimitConfig } from "./RateLimitManager.js";
4
+ import type { ImportDataActions } from "../importDataActions.js";
5
+ import type { SetupOptions } from "../../utilsController.js";
6
+ /**
7
+ * Orchestrator for the entire import process.
8
+ * Coordinates all services while preserving existing functionality and performance characteristics.
9
+ *
10
+ * This replaces the monolithic ImportController and DataLoader with a cleaner, modular architecture.
11
+ */
12
+ export declare class ImportOrchestrator {
13
+ private config;
14
+ private database;
15
+ private storage;
16
+ private appwriteFolderPath;
17
+ private setupOptions;
18
+ private databasesToRun;
19
+ private dataTransformationService;
20
+ private fileHandlerService;
21
+ private userMappingService;
22
+ private validationService;
23
+ private relationshipResolver;
24
+ private rateLimitManager;
25
+ private importMap;
26
+ private collectionImportOperations;
27
+ private hasImportedUsers;
28
+ private batchLimit;
29
+ constructor(config: AppwriteConfig, database: Databases, storage: Storage, appwriteFolderPath: string, importDataActions: ImportDataActions, setupOptions: SetupOptions, databasesToRun?: Models.Database[], rateLimitConfig?: Partial<RateLimitConfig>);
30
+ /**
31
+ * Main entry point for the import process.
32
+ * Preserves existing import flow while using the new modular architecture.
33
+ */
34
+ run(specificCollections?: string[]): Promise<void>;
35
+ /**
36
+ * Performs the complete import process for a single database.
37
+ */
38
+ private performDatabaseImport;
39
+ /**
40
+ * Sets up import maps and operation tracking.
41
+ * Preserves existing setup logic from DataLoader.
42
+ */
43
+ private setupImportMaps;
44
+ /**
45
+ * Loads existing users and initializes user mapping service.
46
+ */
47
+ private loadExistingUsers;
48
+ /**
49
+ * Loads and prepares data for all collections.
50
+ */
51
+ private loadAndPrepareData;
52
+ /**
53
+ * Prepares data for a regular collection.
54
+ * Uses the DataTransformationService for all transformations.
55
+ */
56
+ private prepareCollectionData;
57
+ /**
58
+ * Prepares data for user collection with deduplication.
59
+ * Uses the UserMappingService for sophisticated user handling.
60
+ */
61
+ private prepareUserCollectionData;
62
+ /**
63
+ * Imports collections with rate limiting and batch processing.
64
+ * Preserves existing import logic with enhanced error handling.
65
+ */
66
+ private importCollections;
67
+ /**
68
+ * Imports a single collection with batching and rate limiting.
69
+ */
70
+ private importSingleCollection;
71
+ /**
72
+ * Imports a single item with error handling.
73
+ */
74
+ private importSingleItem;
75
+ /**
76
+ * Helper method to generate consistent collection keys.
77
+ */
78
+ private getCollectionKey;
79
+ /**
80
+ * Loads data from file based on import definition.
81
+ */
82
+ private loadDataFromFile;
83
+ /**
84
+ * Creates batches for processing with the specified batch size.
85
+ */
86
+ private createBatches;
87
+ /**
88
+ * Generates a unique ID for documents.
89
+ */
90
+ private generateUniqueId;
91
+ private findExistingCollection;
92
+ private updateOperationStatus;
93
+ private importUsersCollection;
94
+ private prepareUpdateData;
95
+ private executePostImportActions;
96
+ private transferDataBetweenDatabases;
97
+ }