appwrite-utils-cli 0.10.86 → 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 +260 -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 +194 -49
  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 +226 -61
  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,277 @@
1
+ import { z } from "zod";
2
+ import { ID } from "node-appwrite";
3
+ import { AuthUserCreateSchema } from "../../schemas/authUser.js";
4
+ import { logger } from "../../shared/logging.js";
5
+ /**
6
+ * Service responsible for user mapping and deduplication during import.
7
+ * Preserves all existing sophisticated user handling logic from DataLoader.
8
+ * Extracted to provide focused, testable user management operations.
9
+ */
10
+ export class UserMappingService {
11
+ config;
12
+ dataTransformationService;
13
+ // Maps to hold email and phone to user ID mappings for uniqueness in User Accounts
14
+ emailToUserIdMap = new Map();
15
+ phoneToUserIdMap = new Map();
16
+ userIdSet = new Set();
17
+ // Map to hold the merged user map for relationship resolution
18
+ // Will hold an array of the old user ID's that are mapped to the same new user ID
19
+ // For example, if there are two users with the same email, they will both be mapped to the same new user ID
20
+ // Prevents duplicate users with the other two maps below it and allows me to keep the old ID's
21
+ mergedUserMap = new Map();
22
+ // Map to track existing users
23
+ userExistsMap = new Map();
24
+ constructor(config, dataTransformationService) {
25
+ this.config = config;
26
+ this.dataTransformationService = dataTransformationService;
27
+ }
28
+ /**
29
+ * Initializes user maps with existing users from the system.
30
+ * Preserves existing user loading logic from DataLoader.
31
+ *
32
+ * @param existingUsers - Array of existing users from the system
33
+ */
34
+ initializeWithExistingUsers(existingUsers) {
35
+ // Clear existing maps
36
+ this.emailToUserIdMap.clear();
37
+ this.phoneToUserIdMap.clear();
38
+ this.userIdSet.clear();
39
+ this.userExistsMap.clear();
40
+ // Iterate over the users and setup our maps ahead of time for email and phone
41
+ for (const user of existingUsers) {
42
+ if (user.email) {
43
+ this.emailToUserIdMap.set(user.email.toLowerCase(), user.$id);
44
+ }
45
+ if (user.phone) {
46
+ this.phoneToUserIdMap.set(user.phone, user.$id);
47
+ }
48
+ this.userExistsMap.set(user.$id, true);
49
+ this.userIdSet.add(user.$id);
50
+ }
51
+ logger.info(`Initialized user maps with ${existingUsers.length} existing users`);
52
+ }
53
+ /**
54
+ * Generates a unique ID that doesn't conflict with existing user IDs.
55
+ * Preserves existing unique ID generation logic from DataLoader.
56
+ *
57
+ * @param collectionName - The collection name for context
58
+ * @returns A truly unique ID
59
+ */
60
+ getTrueUniqueUserId(collectionName) {
61
+ let newId = ID.unique();
62
+ let condition = this.userExistsMap.has(newId) ||
63
+ this.userIdSet.has(newId) ||
64
+ Array.from(this.emailToUserIdMap.values()).includes(newId) ||
65
+ Array.from(this.phoneToUserIdMap.values()).includes(newId);
66
+ while (condition) {
67
+ newId = ID.unique();
68
+ condition =
69
+ this.userExistsMap.has(newId) ||
70
+ this.userIdSet.has(newId) ||
71
+ Array.from(this.emailToUserIdMap.values()).includes(newId) ||
72
+ Array.from(this.phoneToUserIdMap.values()).includes(newId);
73
+ }
74
+ return newId;
75
+ }
76
+ /**
77
+ * Prepares user data by checking for duplicates based on email or phone, adding to a duplicate map if found,
78
+ * and then returning the transformed item without user-specific keys.
79
+ *
80
+ * Preserves existing sophisticated user deduplication logic from DataLoader.
81
+ *
82
+ * @param item - The raw item to be processed.
83
+ * @param attributeMappings - The attribute mappings for the item.
84
+ * @param primaryKeyField - The primary key field name
85
+ * @param newId - The proposed new ID for the user
86
+ * @returns Object containing transformed item, existing ID if duplicate, and user data
87
+ */
88
+ prepareUserData(item, attributeMappings, primaryKeyField, newId) {
89
+ // Ensure we have a truly unique ID
90
+ if (this.userIdSet.has(newId) ||
91
+ this.userExistsMap.has(newId) ||
92
+ Array.from(this.emailToUserIdMap.values()).includes(newId) ||
93
+ Array.from(this.phoneToUserIdMap.values()).includes(newId)) {
94
+ newId = this.getTrueUniqueUserId("users");
95
+ }
96
+ let transformedItem = this.dataTransformationService.transformData(item, attributeMappings);
97
+ let userData = AuthUserCreateSchema.safeParse(transformedItem);
98
+ if (userData.data?.email) {
99
+ userData.data.email = userData.data.email.toLowerCase();
100
+ }
101
+ if (!userData.success || !(userData.data.email || userData.data.phone)) {
102
+ logger.error(`Invalid user data: ${JSON.stringify(userData.error?.errors, undefined, 2)} or missing email/phone`);
103
+ const userKeys = ["email", "phone", "name", "labels", "prefs"];
104
+ userKeys.forEach((key) => {
105
+ if (transformedItem.hasOwnProperty(key)) {
106
+ delete transformedItem[key];
107
+ }
108
+ });
109
+ return {
110
+ transformedItem,
111
+ existingId: undefined,
112
+ userData: {
113
+ rawData: item,
114
+ finalData: transformedItem,
115
+ },
116
+ };
117
+ }
118
+ const email = userData.data.email?.toLowerCase();
119
+ const phone = userData.data.phone;
120
+ let existingId;
121
+ // Check for duplicate email and phone
122
+ if (email && this.emailToUserIdMap.has(email)) {
123
+ existingId = this.emailToUserIdMap.get(email);
124
+ if (phone && !this.phoneToUserIdMap.has(phone)) {
125
+ this.phoneToUserIdMap.set(phone, newId);
126
+ }
127
+ }
128
+ else if (phone && this.phoneToUserIdMap.has(phone)) {
129
+ existingId = this.phoneToUserIdMap.get(phone);
130
+ if (email && !this.emailToUserIdMap.has(email)) {
131
+ this.emailToUserIdMap.set(email, newId);
132
+ }
133
+ }
134
+ else {
135
+ if (email)
136
+ this.emailToUserIdMap.set(email, newId);
137
+ if (phone)
138
+ this.phoneToUserIdMap.set(phone, newId);
139
+ }
140
+ if (existingId) {
141
+ userData.data.userId = existingId;
142
+ const mergedUsers = this.mergedUserMap.get(existingId) || [];
143
+ mergedUsers.push(`${item[primaryKeyField]}`);
144
+ this.mergedUserMap.set(existingId, mergedUsers);
145
+ const userKeys = ["email", "phone", "name", "labels", "prefs"];
146
+ userKeys.forEach((key) => {
147
+ if (transformedItem.hasOwnProperty(key)) {
148
+ delete transformedItem[key];
149
+ }
150
+ });
151
+ return {
152
+ transformedItem: {
153
+ ...transformedItem,
154
+ userId: existingId,
155
+ docId: existingId,
156
+ },
157
+ existingId,
158
+ userData: {
159
+ rawData: item,
160
+ finalData: userData.data,
161
+ },
162
+ };
163
+ }
164
+ else {
165
+ existingId = newId;
166
+ userData.data.userId = existingId;
167
+ }
168
+ const userKeys = ["email", "phone", "name", "labels", "prefs"];
169
+ userKeys.forEach((key) => {
170
+ if (transformedItem.hasOwnProperty(key)) {
171
+ delete transformedItem[key];
172
+ }
173
+ });
174
+ this.userIdSet.add(existingId);
175
+ return {
176
+ transformedItem: {
177
+ ...transformedItem,
178
+ userId: existingId,
179
+ docId: existingId,
180
+ },
181
+ existingId,
182
+ userData: {
183
+ rawData: item,
184
+ finalData: userData.data,
185
+ },
186
+ };
187
+ }
188
+ /**
189
+ * Checks if a collection is the users collection based on configuration.
190
+ *
191
+ * @param collectionName - The collection name to check
192
+ * @returns True if this is the users collection
193
+ */
194
+ isUsersCollection(collectionName) {
195
+ return !!(this.config.usersCollectionName &&
196
+ this.getCollectionKey(this.config.usersCollectionName) ===
197
+ this.getCollectionKey(collectionName));
198
+ }
199
+ /**
200
+ * Helper method to generate a consistent key for collections.
201
+ * Preserves existing logic from DataLoader.
202
+ */
203
+ getCollectionKey(name) {
204
+ return name.toLowerCase().replace(" ", "");
205
+ }
206
+ /**
207
+ * Gets merged user mappings for relationship resolution.
208
+ *
209
+ * @returns Map of merged user IDs to arrays of original IDs
210
+ */
211
+ getMergedUserMap() {
212
+ return new Map(this.mergedUserMap);
213
+ }
214
+ /**
215
+ * Finds the new user ID for an old user ID, considering merged users.
216
+ * Preserves existing merged user lookup logic from DataLoader.
217
+ *
218
+ * @param oldId - The old user ID to look up
219
+ * @returns The new user ID if found, otherwise the original ID
220
+ */
221
+ findNewUserIdForOldId(oldId) {
222
+ // Check if this old ID was merged into another user
223
+ for (const [newUserId, oldUserIds] of this.mergedUserMap.entries()) {
224
+ if (oldUserIds.includes(`${oldId}`)) {
225
+ return newUserId;
226
+ }
227
+ }
228
+ // If not found in merged users, return the original ID
229
+ return oldId;
230
+ }
231
+ /**
232
+ * Merges user data from duplicate entries.
233
+ * Preserves existing user data merging logic.
234
+ *
235
+ * @param existingUserData - The existing user data
236
+ * @param newUserData - The new user data to merge
237
+ * @returns Merged user data
238
+ */
239
+ mergeUserData(existingUserData, newUserData) {
240
+ return this.dataTransformationService.mergeObjects(existingUserData, newUserData);
241
+ }
242
+ /**
243
+ * Gets statistics about user mapping operations.
244
+ * Useful for import planning and reporting.
245
+ *
246
+ * @returns User mapping statistics
247
+ */
248
+ getStatistics() {
249
+ let totalMergedOldIds = 0;
250
+ for (const oldIds of this.mergedUserMap.values()) {
251
+ totalMergedOldIds += oldIds.length;
252
+ }
253
+ return {
254
+ totalExistingUsers: this.userExistsMap.size,
255
+ emailMappings: this.emailToUserIdMap.size,
256
+ phoneMappings: this.phoneToUserIdMap.size,
257
+ mergedUsers: this.mergedUserMap.size,
258
+ totalMergedOldIds,
259
+ };
260
+ }
261
+ /**
262
+ * Validates user mapping configuration.
263
+ * Ensures the user mapping setup is correct before import.
264
+ *
265
+ * @returns Array of validation errors (empty if valid)
266
+ */
267
+ validateConfiguration() {
268
+ const errors = [];
269
+ if (!this.config.usersCollectionName) {
270
+ errors.push("usersCollectionName is not configured");
271
+ }
272
+ if (!this.config.documentBucketId) {
273
+ errors.push("documentBucketId is not configured");
274
+ }
275
+ return errors;
276
+ }
277
+ }
@@ -0,0 +1,74 @@
1
+ import type { AttributeMappings, ImportDef, CollectionCreate } from "appwrite-utils";
2
+ import type { ImportDataActions } from "../importDataActions.js";
3
+ /**
4
+ * Service responsible for validation during import operations.
5
+ * Provides centralized validation logic extracted from ImportDataActions and DataLoader.
6
+ */
7
+ export declare class ValidationService {
8
+ private importDataActions;
9
+ constructor(importDataActions: ImportDataActions);
10
+ /**
11
+ * Validates a single data item based on defined validation rules.
12
+ * Preserves existing validation logic from ImportDataActions.
13
+ *
14
+ * @param item - The data item to validate
15
+ * @param attributeMappings - The attribute mappings for the data item
16
+ * @param context - The context for resolving templated parameters in validation rules
17
+ * @returns True if the item is valid, false otherwise
18
+ */
19
+ validateDataItem(item: any, attributeMappings: AttributeMappings, context: {
20
+ [key: string]: any;
21
+ }): boolean;
22
+ /**
23
+ * Validates an import definition before processing begins.
24
+ * Provides early validation to catch configuration issues.
25
+ *
26
+ * @param importDef - The import definition to validate
27
+ * @returns Array of validation errors (empty if valid)
28
+ */
29
+ validateImportDefinition(importDef: ImportDef): string[];
30
+ /**
31
+ * Validates a collection configuration for import compatibility.
32
+ * Ensures the collection has the necessary attributes for import operations.
33
+ *
34
+ * @param collection - The collection to validate
35
+ * @param importDefs - The import definitions that will be used with this collection
36
+ * @returns Array of validation errors (empty if valid)
37
+ */
38
+ validateCollectionForImport(collection: CollectionCreate, importDefs: ImportDef[]): string[];
39
+ /**
40
+ * Validates data consistency across multiple collections.
41
+ * Checks for relationship integrity and data consistency.
42
+ *
43
+ * @param collections - Array of collections to validate
44
+ * @returns Array of validation errors (empty if valid)
45
+ */
46
+ validateCrossCollectionConsistency(collections: CollectionCreate[]): string[];
47
+ /**
48
+ * Performs comprehensive pre-import validation.
49
+ * Validates all aspects of the import configuration before starting.
50
+ *
51
+ * @param collections - Collections that will be imported
52
+ * @param appwriteFolderPath - Path to the appwrite folder for file validation
53
+ * @returns Validation result with errors and warnings
54
+ */
55
+ performPreImportValidation(collections: CollectionCreate[], appwriteFolderPath: string): {
56
+ errors: string[];
57
+ warnings: string[];
58
+ isValid: boolean;
59
+ };
60
+ /**
61
+ * Validates import progress and data integrity during import.
62
+ * Can be used for periodic validation during long-running imports.
63
+ *
64
+ * @param processedItems - Number of items processed so far
65
+ * @param totalItems - Total number of items to process
66
+ * @param errorCount - Number of errors encountered
67
+ * @returns Validation status with recommendations
68
+ */
69
+ validateImportProgress(processedItems: number, totalItems: number, errorCount: number): {
70
+ status: "healthy" | "warning" | "critical";
71
+ message: string;
72
+ shouldContinue: boolean;
73
+ };
74
+ }
@@ -0,0 +1,260 @@
1
+ import { logger } from "../../shared/logging.js";
2
+ /**
3
+ * Service responsible for validation during import operations.
4
+ * Provides centralized validation logic extracted from ImportDataActions and DataLoader.
5
+ */
6
+ export class ValidationService {
7
+ importDataActions;
8
+ constructor(importDataActions) {
9
+ this.importDataActions = importDataActions;
10
+ }
11
+ /**
12
+ * Validates a single data item based on defined validation rules.
13
+ * Preserves existing validation logic from ImportDataActions.
14
+ *
15
+ * @param item - The data item to validate
16
+ * @param attributeMappings - The attribute mappings for the data item
17
+ * @param context - The context for resolving templated parameters in validation rules
18
+ * @returns True if the item is valid, false otherwise
19
+ */
20
+ validateDataItem(item, attributeMappings, context) {
21
+ try {
22
+ return this.importDataActions.validateItem(item, attributeMappings, context);
23
+ }
24
+ catch (error) {
25
+ logger.error(`Validation error for item: ${JSON.stringify(item, null, 2)}`, error);
26
+ return false;
27
+ }
28
+ }
29
+ /**
30
+ * Validates an import definition before processing begins.
31
+ * Provides early validation to catch configuration issues.
32
+ *
33
+ * @param importDef - The import definition to validate
34
+ * @returns Array of validation errors (empty if valid)
35
+ */
36
+ validateImportDefinition(importDef) {
37
+ const errors = [];
38
+ // Validate required fields
39
+ if (!importDef.filePath) {
40
+ errors.push("filePath is required");
41
+ }
42
+ if (!importDef.attributeMappings || importDef.attributeMappings.length === 0) {
43
+ errors.push("attributeMappings are required");
44
+ }
45
+ // Validate attribute mappings
46
+ if (importDef.attributeMappings) {
47
+ for (let i = 0; i < importDef.attributeMappings.length; i++) {
48
+ const mapping = importDef.attributeMappings[i];
49
+ if (!mapping.targetKey) {
50
+ errors.push(`attributeMappings[${i}]: targetKey is required`);
51
+ }
52
+ if (!mapping.oldKey && !mapping.oldKeys && mapping.valueToSet === undefined) {
53
+ errors.push(`attributeMappings[${i}]: must have either oldKey, oldKeys, or valueToSet`);
54
+ }
55
+ // Validate file data if present
56
+ if (mapping.fileData) {
57
+ if (!mapping.fileData.path) {
58
+ errors.push(`attributeMappings[${i}].fileData: path is required`);
59
+ }
60
+ if (!mapping.fileData.name) {
61
+ errors.push(`attributeMappings[${i}].fileData: name is required`);
62
+ }
63
+ }
64
+ // Validate converters if present
65
+ if (mapping.converters && !Array.isArray(mapping.converters)) {
66
+ errors.push(`attributeMappings[${i}].converters: must be an array`);
67
+ }
68
+ // Validate validation actions if present
69
+ if (mapping.validationActions) {
70
+ if (!Array.isArray(mapping.validationActions)) {
71
+ errors.push(`attributeMappings[${i}].validationActions: must be an array`);
72
+ }
73
+ else {
74
+ for (let j = 0; j < mapping.validationActions.length; j++) {
75
+ const action = mapping.validationActions[j];
76
+ if (!action.action) {
77
+ errors.push(`attributeMappings[${i}].validationActions[${j}]: action is required`);
78
+ }
79
+ if (!Array.isArray(action.params)) {
80
+ errors.push(`attributeMappings[${i}].validationActions[${j}]: params must be an array`);
81
+ }
82
+ }
83
+ }
84
+ }
85
+ // Validate post-import actions if present
86
+ if (mapping.postImportActions) {
87
+ if (!Array.isArray(mapping.postImportActions)) {
88
+ errors.push(`attributeMappings[${i}].postImportActions: must be an array`);
89
+ }
90
+ else {
91
+ for (let j = 0; j < mapping.postImportActions.length; j++) {
92
+ const action = mapping.postImportActions[j];
93
+ if (!action.action) {
94
+ errors.push(`attributeMappings[${i}].postImportActions[${j}]: action is required`);
95
+ }
96
+ if (!Array.isArray(action.params)) {
97
+ errors.push(`attributeMappings[${i}].postImportActions[${j}]: params must be an array`);
98
+ }
99
+ }
100
+ }
101
+ }
102
+ }
103
+ }
104
+ // Validate ID mappings if present
105
+ if (importDef.idMappings) {
106
+ for (let i = 0; i < importDef.idMappings.length; i++) {
107
+ const idMapping = importDef.idMappings[i];
108
+ if (!idMapping.sourceField) {
109
+ errors.push(`idMappings[${i}]: sourceField is required`);
110
+ }
111
+ if (!idMapping.targetField) {
112
+ errors.push(`idMappings[${i}]: targetField is required`);
113
+ }
114
+ if (!idMapping.targetCollection) {
115
+ errors.push(`idMappings[${i}]: targetCollection is required`);
116
+ }
117
+ }
118
+ }
119
+ // Validate update mapping if present
120
+ if (importDef.updateMapping) {
121
+ if (!importDef.updateMapping.originalIdField) {
122
+ errors.push("updateMapping: originalIdField is required");
123
+ }
124
+ if (!importDef.updateMapping.targetField) {
125
+ errors.push("updateMapping: targetField is required");
126
+ }
127
+ }
128
+ return errors;
129
+ }
130
+ /**
131
+ * Validates a collection configuration for import compatibility.
132
+ * Ensures the collection has the necessary attributes for import operations.
133
+ *
134
+ * @param collection - The collection to validate
135
+ * @param importDefs - The import definitions that will be used with this collection
136
+ * @returns Array of validation errors (empty if valid)
137
+ */
138
+ validateCollectionForImport(collection, importDefs) {
139
+ const errors = [];
140
+ if (!collection.name) {
141
+ errors.push("Collection name is required");
142
+ }
143
+ if (!collection.attributes || collection.attributes.length === 0) {
144
+ errors.push("Collection must have attributes defined");
145
+ }
146
+ // Validate that target keys in import definitions exist as attributes
147
+ for (const importDef of importDefs) {
148
+ for (const mapping of importDef.attributeMappings) {
149
+ const attributeExists = collection.attributes?.some(attr => attr.key === mapping.targetKey);
150
+ if (!attributeExists) {
151
+ errors.push(`Attribute '${mapping.targetKey}' referenced in import mapping not found in collection`);
152
+ }
153
+ }
154
+ }
155
+ return errors;
156
+ }
157
+ /**
158
+ * Validates data consistency across multiple collections.
159
+ * Checks for relationship integrity and data consistency.
160
+ *
161
+ * @param collections - Array of collections to validate
162
+ * @returns Array of validation errors (empty if valid)
163
+ */
164
+ validateCrossCollectionConsistency(collections) {
165
+ const errors = [];
166
+ const collectionNames = new Set(collections.map(c => c.name));
167
+ for (const collection of collections) {
168
+ if (!collection.importDefs)
169
+ continue;
170
+ for (const importDef of collection.importDefs) {
171
+ if (!importDef.idMappings)
172
+ continue;
173
+ for (const idMapping of importDef.idMappings) {
174
+ // Check if target collection exists
175
+ if (!collectionNames.has(idMapping.targetCollection)) {
176
+ errors.push(`Collection '${collection.name}' references non-existent target collection '${idMapping.targetCollection}' in ID mapping`);
177
+ }
178
+ }
179
+ }
180
+ }
181
+ return errors;
182
+ }
183
+ /**
184
+ * Performs comprehensive pre-import validation.
185
+ * Validates all aspects of the import configuration before starting.
186
+ *
187
+ * @param collections - Collections that will be imported
188
+ * @param appwriteFolderPath - Path to the appwrite folder for file validation
189
+ * @returns Validation result with errors and warnings
190
+ */
191
+ performPreImportValidation(collections, appwriteFolderPath) {
192
+ const errors = [];
193
+ const warnings = [];
194
+ // Validate each collection
195
+ for (const collection of collections) {
196
+ const collectionErrors = this.validateCollectionForImport(collection, collection.importDefs || []);
197
+ errors.push(...collectionErrors.map(err => `${collection.name}: ${err}`));
198
+ // Validate each import definition
199
+ if (collection.importDefs) {
200
+ for (let i = 0; i < collection.importDefs.length; i++) {
201
+ const importDef = collection.importDefs[i];
202
+ const importDefErrors = this.validateImportDefinition(importDef);
203
+ errors.push(...importDefErrors.map(err => `${collection.name}.importDefs[${i}]: ${err}`));
204
+ // Check if import file exists
205
+ try {
206
+ const fs = require("fs");
207
+ const path = require("path");
208
+ const filePath = path.resolve(appwriteFolderPath, importDef.filePath);
209
+ if (!fs.existsSync(filePath)) {
210
+ errors.push(`${collection.name}.importDefs[${i}]: Import file not found: ${filePath}`);
211
+ }
212
+ }
213
+ catch (error) {
214
+ warnings.push(`${collection.name}.importDefs[${i}]: Could not validate file existence: ${error}`);
215
+ }
216
+ }
217
+ }
218
+ }
219
+ // Validate cross-collection consistency
220
+ const crossCollectionErrors = this.validateCrossCollectionConsistency(collections);
221
+ errors.push(...crossCollectionErrors);
222
+ return {
223
+ errors,
224
+ warnings,
225
+ isValid: errors.length === 0,
226
+ };
227
+ }
228
+ /**
229
+ * Validates import progress and data integrity during import.
230
+ * Can be used for periodic validation during long-running imports.
231
+ *
232
+ * @param processedItems - Number of items processed so far
233
+ * @param totalItems - Total number of items to process
234
+ * @param errorCount - Number of errors encountered
235
+ * @returns Validation status with recommendations
236
+ */
237
+ validateImportProgress(processedItems, totalItems, errorCount) {
238
+ const errorRate = errorCount / Math.max(processedItems, 1);
239
+ const progress = processedItems / totalItems;
240
+ if (errorRate > 0.5) {
241
+ return {
242
+ status: "critical",
243
+ message: `Error rate too high: ${(errorRate * 100).toFixed(1)}%. Consider stopping import.`,
244
+ shouldContinue: false,
245
+ };
246
+ }
247
+ if (errorRate > 0.1) {
248
+ return {
249
+ status: "warning",
250
+ message: `Elevated error rate: ${(errorRate * 100).toFixed(1)}%. Monitor closely.`,
251
+ shouldContinue: true,
252
+ };
253
+ }
254
+ return {
255
+ status: "healthy",
256
+ message: `Import progressing normally: ${(progress * 100).toFixed(1)}% complete, ${(errorRate * 100).toFixed(1)}% error rate.`,
257
+ shouldContinue: true,
258
+ };
259
+ }
260
+ }
@@ -13,12 +13,6 @@ export interface TransferOptions {
13
13
  }
14
14
  export declare const transferStorageLocalToLocal: (storage: Storage, fromBucketId: string, toBucketId: string) => Promise<void>;
15
15
  export declare const transferStorageLocalToRemote: (localStorage: Storage, endpoint: string, projectId: string, apiKey: string, fromBucketId: string, toBucketId: string) => Promise<void>;
16
- /**
17
- * Transfers all documents from one collection to another in a different database
18
- * within the same Appwrite Project
19
- */
20
- export declare const transferDocumentsBetweenDbsLocalToLocal: (db: Databases, fromDbId: string, toDbId: string, fromCollId: string, toCollId: string) => Promise<void>;
21
- export declare const transferDocumentsBetweenDbsLocalToRemote: (localDb: Databases, endpoint: string, projectId: string, apiKey: string, fromDbId: string, toDbId: string, fromCollId: string, toCollId: string) => Promise<void>;
22
16
  /**
23
17
  * Transfers all collections and documents from one local database to another local database.
24
18
  *