appwrite-utils-cli 1.11.0 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (250) hide show
  1. package/{src/adapters/index.ts → dist/adapters/index.d.ts} +0 -1
  2. package/dist/adapters/index.js +10 -0
  3. package/dist/backups/operations/bucketBackup.d.ts +19 -0
  4. package/dist/backups/operations/bucketBackup.js +197 -0
  5. package/dist/backups/operations/collectionBackup.d.ts +30 -0
  6. package/dist/backups/operations/collectionBackup.js +201 -0
  7. package/dist/backups/operations/comprehensiveBackup.d.ts +25 -0
  8. package/dist/backups/operations/comprehensiveBackup.js +238 -0
  9. package/dist/backups/schemas/bucketManifest.d.ts +93 -0
  10. package/dist/backups/schemas/bucketManifest.js +33 -0
  11. package/dist/backups/schemas/comprehensiveManifest.d.ts +108 -0
  12. package/dist/backups/schemas/comprehensiveManifest.js +32 -0
  13. package/dist/backups/tracking/centralizedTracking.d.ts +34 -0
  14. package/dist/backups/tracking/centralizedTracking.js +274 -0
  15. package/dist/cli/commands/configCommands.d.ts +8 -0
  16. package/dist/cli/commands/configCommands.js +210 -0
  17. package/dist/cli/commands/databaseCommands.d.ts +14 -0
  18. package/dist/cli/commands/databaseCommands.js +696 -0
  19. package/dist/cli/commands/functionCommands.d.ts +7 -0
  20. package/dist/cli/commands/functionCommands.js +330 -0
  21. package/dist/cli/commands/importFileCommands.d.ts +7 -0
  22. package/dist/cli/commands/importFileCommands.js +674 -0
  23. package/dist/cli/commands/schemaCommands.d.ts +7 -0
  24. package/dist/cli/commands/schemaCommands.js +169 -0
  25. package/dist/cli/commands/storageCommands.d.ts +5 -0
  26. package/dist/cli/commands/storageCommands.js +142 -0
  27. package/dist/cli/commands/transferCommands.d.ts +5 -0
  28. package/dist/cli/commands/transferCommands.js +382 -0
  29. package/dist/collections/columns.d.ts +13 -0
  30. package/dist/collections/columns.js +1339 -0
  31. package/dist/collections/indexes.d.ts +12 -0
  32. package/dist/collections/indexes.js +215 -0
  33. package/dist/collections/methods.d.ts +19 -0
  34. package/dist/collections/methods.js +605 -0
  35. package/dist/collections/tableOperations.d.ts +87 -0
  36. package/dist/collections/tableOperations.js +466 -0
  37. package/dist/collections/transferOperations.d.ts +8 -0
  38. package/dist/collections/transferOperations.js +411 -0
  39. package/dist/collections/wipeOperations.d.ts +17 -0
  40. package/dist/collections/wipeOperations.js +306 -0
  41. package/dist/databases/methods.d.ts +6 -0
  42. package/dist/databases/methods.js +35 -0
  43. package/dist/databases/setup.d.ts +5 -0
  44. package/dist/databases/setup.js +45 -0
  45. package/dist/examples/yamlTerminologyExample.d.ts +42 -0
  46. package/dist/examples/yamlTerminologyExample.js +272 -0
  47. package/dist/functions/deployments.d.ts +4 -0
  48. package/dist/functions/deployments.js +146 -0
  49. package/dist/functions/fnConfigDiscovery.d.ts +3 -0
  50. package/dist/functions/fnConfigDiscovery.js +108 -0
  51. package/dist/functions/methods.d.ts +16 -0
  52. package/dist/functions/methods.js +174 -0
  53. package/dist/init.d.ts +2 -0
  54. package/dist/init.js +57 -0
  55. package/dist/interactiveCLI.d.ts +36 -0
  56. package/dist/interactiveCLI.js +952 -0
  57. package/dist/main.d.ts +2 -0
  58. package/dist/main.js +1125 -0
  59. package/dist/migrations/afterImportActions.d.ts +17 -0
  60. package/dist/migrations/afterImportActions.js +305 -0
  61. package/dist/migrations/appwriteToX.d.ts +211 -0
  62. package/dist/migrations/appwriteToX.js +493 -0
  63. package/dist/migrations/comprehensiveTransfer.d.ts +147 -0
  64. package/dist/migrations/comprehensiveTransfer.js +1315 -0
  65. package/dist/migrations/dataLoader.d.ts +755 -0
  66. package/dist/migrations/dataLoader.js +1272 -0
  67. package/dist/migrations/importController.d.ts +25 -0
  68. package/dist/migrations/importController.js +283 -0
  69. package/dist/migrations/importDataActions.d.ts +50 -0
  70. package/dist/migrations/importDataActions.js +230 -0
  71. package/dist/migrations/relationships.d.ts +29 -0
  72. package/dist/migrations/relationships.js +203 -0
  73. package/dist/migrations/services/DataTransformationService.d.ts +55 -0
  74. package/dist/migrations/services/DataTransformationService.js +158 -0
  75. package/dist/migrations/services/FileHandlerService.d.ts +75 -0
  76. package/dist/migrations/services/FileHandlerService.js +236 -0
  77. package/dist/migrations/services/ImportOrchestrator.d.ts +99 -0
  78. package/dist/migrations/services/ImportOrchestrator.js +493 -0
  79. package/dist/migrations/services/RateLimitManager.d.ts +138 -0
  80. package/dist/migrations/services/RateLimitManager.js +279 -0
  81. package/dist/migrations/services/RelationshipResolver.d.ts +120 -0
  82. package/dist/migrations/services/RelationshipResolver.js +332 -0
  83. package/dist/migrations/services/UserMappingService.d.ts +109 -0
  84. package/dist/migrations/services/UserMappingService.js +277 -0
  85. package/dist/migrations/services/ValidationService.d.ts +74 -0
  86. package/dist/migrations/services/ValidationService.js +260 -0
  87. package/dist/migrations/transfer.d.ts +30 -0
  88. package/dist/migrations/transfer.js +661 -0
  89. package/dist/migrations/yaml/YamlImportConfigLoader.d.ts +131 -0
  90. package/dist/migrations/yaml/YamlImportConfigLoader.js +383 -0
  91. package/dist/migrations/yaml/YamlImportIntegration.d.ts +93 -0
  92. package/dist/migrations/yaml/YamlImportIntegration.js +341 -0
  93. package/dist/migrations/yaml/generateImportSchemas.d.ts +30 -0
  94. package/dist/migrations/yaml/generateImportSchemas.js +1327 -0
  95. package/dist/schemas/authUser.d.ts +24 -0
  96. package/dist/schemas/authUser.js +17 -0
  97. package/dist/setup.d.ts +2 -0
  98. package/{src/setup.ts → dist/setup.js} +0 -3
  99. package/dist/setupCommands.d.ts +58 -0
  100. package/dist/setupCommands.js +489 -0
  101. package/dist/setupController.d.ts +9 -0
  102. package/dist/setupController.js +34 -0
  103. package/dist/shared/backupMetadataSchema.d.ts +94 -0
  104. package/dist/shared/backupMetadataSchema.js +38 -0
  105. package/dist/shared/backupTracking.d.ts +18 -0
  106. package/dist/shared/backupTracking.js +176 -0
  107. package/dist/shared/confirmationDialogs.d.ts +75 -0
  108. package/dist/shared/confirmationDialogs.js +236 -0
  109. package/dist/shared/migrationHelpers.d.ts +61 -0
  110. package/dist/shared/migrationHelpers.js +145 -0
  111. package/{src/shared/operationLogger.ts → dist/shared/operationLogger.d.ts} +1 -11
  112. package/dist/shared/operationLogger.js +12 -0
  113. package/dist/shared/operationQueue.d.ts +40 -0
  114. package/dist/shared/operationQueue.js +310 -0
  115. package/dist/shared/operationsTable.d.ts +26 -0
  116. package/dist/shared/operationsTable.js +287 -0
  117. package/dist/shared/operationsTableSchema.d.ts +48 -0
  118. package/dist/shared/operationsTableSchema.js +35 -0
  119. package/dist/shared/progressManager.d.ts +62 -0
  120. package/dist/shared/progressManager.js +215 -0
  121. package/dist/shared/relationshipExtractor.d.ts +56 -0
  122. package/dist/shared/relationshipExtractor.js +138 -0
  123. package/dist/shared/selectionDialogs.d.ts +220 -0
  124. package/dist/shared/selectionDialogs.js +588 -0
  125. package/dist/storage/backupCompression.d.ts +20 -0
  126. package/dist/storage/backupCompression.js +67 -0
  127. package/dist/storage/methods.d.ts +44 -0
  128. package/dist/storage/methods.js +475 -0
  129. package/dist/storage/schemas.d.ts +842 -0
  130. package/dist/storage/schemas.js +175 -0
  131. package/dist/tables/indexManager.d.ts +65 -0
  132. package/dist/tables/indexManager.js +294 -0
  133. package/{src/types.ts → dist/types.d.ts} +1 -6
  134. package/dist/types.js +3 -0
  135. package/dist/users/methods.d.ts +16 -0
  136. package/dist/users/methods.js +276 -0
  137. package/dist/utils/configMigration.d.ts +1 -0
  138. package/dist/utils/configMigration.js +261 -0
  139. package/dist/utils/index.js +2 -0
  140. package/dist/utils/loadConfigs.d.ts +50 -0
  141. package/dist/utils/loadConfigs.js +357 -0
  142. package/dist/utils/setupFiles.d.ts +4 -0
  143. package/dist/utils/setupFiles.js +1190 -0
  144. package/dist/utilsController.d.ts +114 -0
  145. package/dist/utilsController.js +898 -0
  146. package/package.json +6 -3
  147. package/CHANGELOG.md +0 -35
  148. package/CONFIG_TODO.md +0 -1189
  149. package/SELECTION_DIALOGS.md +0 -146
  150. package/SERVICE_IMPLEMENTATION_REPORT.md +0 -462
  151. package/scripts/copy-templates.ts +0 -23
  152. package/src/backups/operations/bucketBackup.ts +0 -277
  153. package/src/backups/operations/collectionBackup.ts +0 -310
  154. package/src/backups/operations/comprehensiveBackup.ts +0 -342
  155. package/src/backups/schemas/bucketManifest.ts +0 -78
  156. package/src/backups/schemas/comprehensiveManifest.ts +0 -76
  157. package/src/backups/tracking/centralizedTracking.ts +0 -352
  158. package/src/cli/commands/configCommands.ts +0 -265
  159. package/src/cli/commands/databaseCommands.ts +0 -931
  160. package/src/cli/commands/functionCommands.ts +0 -419
  161. package/src/cli/commands/importFileCommands.ts +0 -815
  162. package/src/cli/commands/schemaCommands.ts +0 -200
  163. package/src/cli/commands/storageCommands.ts +0 -151
  164. package/src/cli/commands/transferCommands.ts +0 -454
  165. package/src/collections/attributes.ts.backup +0 -1555
  166. package/src/collections/columns.ts +0 -2025
  167. package/src/collections/indexes.ts +0 -350
  168. package/src/collections/methods.ts +0 -714
  169. package/src/collections/tableOperations.ts +0 -542
  170. package/src/collections/transferOperations.ts +0 -589
  171. package/src/collections/wipeOperations.ts +0 -449
  172. package/src/databases/methods.ts +0 -49
  173. package/src/databases/setup.ts +0 -77
  174. package/src/examples/yamlTerminologyExample.ts +0 -346
  175. package/src/functions/deployments.ts +0 -221
  176. package/src/functions/fnConfigDiscovery.ts +0 -103
  177. package/src/functions/methods.ts +0 -284
  178. package/src/init.ts +0 -62
  179. package/src/interactiveCLI.ts +0 -1201
  180. package/src/main.ts +0 -1517
  181. package/src/migrations/afterImportActions.ts +0 -579
  182. package/src/migrations/appwriteToX.ts +0 -668
  183. package/src/migrations/comprehensiveTransfer.ts +0 -2285
  184. package/src/migrations/dataLoader.ts +0 -1729
  185. package/src/migrations/importController.ts +0 -440
  186. package/src/migrations/importDataActions.ts +0 -315
  187. package/src/migrations/relationships.ts +0 -333
  188. package/src/migrations/services/DataTransformationService.ts +0 -196
  189. package/src/migrations/services/FileHandlerService.ts +0 -311
  190. package/src/migrations/services/ImportOrchestrator.ts +0 -675
  191. package/src/migrations/services/RateLimitManager.ts +0 -363
  192. package/src/migrations/services/RelationshipResolver.ts +0 -461
  193. package/src/migrations/services/UserMappingService.ts +0 -345
  194. package/src/migrations/services/ValidationService.ts +0 -349
  195. package/src/migrations/transfer.ts +0 -1113
  196. package/src/migrations/yaml/YamlImportConfigLoader.ts +0 -439
  197. package/src/migrations/yaml/YamlImportIntegration.ts +0 -446
  198. package/src/migrations/yaml/generateImportSchemas.ts +0 -1354
  199. package/src/schemas/authUser.ts +0 -23
  200. package/src/setupCommands.ts +0 -602
  201. package/src/setupController.ts +0 -43
  202. package/src/shared/backupMetadataSchema.ts +0 -93
  203. package/src/shared/backupTracking.ts +0 -211
  204. package/src/shared/confirmationDialogs.ts +0 -327
  205. package/src/shared/migrationHelpers.ts +0 -232
  206. package/src/shared/operationQueue.ts +0 -376
  207. package/src/shared/operationsTable.ts +0 -338
  208. package/src/shared/operationsTableSchema.ts +0 -60
  209. package/src/shared/progressManager.ts +0 -278
  210. package/src/shared/relationshipExtractor.ts +0 -214
  211. package/src/shared/selectionDialogs.ts +0 -802
  212. package/src/storage/backupCompression.ts +0 -88
  213. package/src/storage/methods.ts +0 -711
  214. package/src/storage/schemas.ts +0 -205
  215. package/src/tables/indexManager.ts +0 -409
  216. package/src/types/node-appwrite-tablesdb.d.ts +0 -44
  217. package/src/users/methods.ts +0 -358
  218. package/src/utils/configMigration.ts +0 -348
  219. package/src/utils/loadConfigs.ts +0 -457
  220. package/src/utils/setupFiles.ts +0 -1236
  221. package/src/utilsController.ts +0 -1263
  222. package/tests/README.md +0 -497
  223. package/tests/adapters/AdapterFactory.test.ts +0 -277
  224. package/tests/integration/syncOperations.test.ts +0 -463
  225. package/tests/jest.config.js +0 -25
  226. package/tests/migration/configMigration.test.ts +0 -546
  227. package/tests/setup.ts +0 -62
  228. package/tests/testUtils.ts +0 -340
  229. package/tests/utils/loadConfigs.test.ts +0 -350
  230. package/tests/validation/configValidation.test.ts +0 -412
  231. package/tsconfig.json +0 -44
  232. /package/{src → dist}/functions/templates/count-docs-in-collection/README.md +0 -0
  233. /package/{src → dist}/functions/templates/count-docs-in-collection/src/main.ts +0 -0
  234. /package/{src → dist}/functions/templates/count-docs-in-collection/src/request.ts +0 -0
  235. /package/{src → dist}/functions/templates/hono-typescript/README.md +0 -0
  236. /package/{src → dist}/functions/templates/hono-typescript/src/adapters/request.ts +0 -0
  237. /package/{src → dist}/functions/templates/hono-typescript/src/adapters/response.ts +0 -0
  238. /package/{src → dist}/functions/templates/hono-typescript/src/app.ts +0 -0
  239. /package/{src → dist}/functions/templates/hono-typescript/src/context.ts +0 -0
  240. /package/{src → dist}/functions/templates/hono-typescript/src/main.ts +0 -0
  241. /package/{src → dist}/functions/templates/hono-typescript/src/middleware/appwrite.ts +0 -0
  242. /package/{src → dist}/functions/templates/typescript-node/README.md +0 -0
  243. /package/{src → dist}/functions/templates/typescript-node/src/context.ts +0 -0
  244. /package/{src → dist}/functions/templates/typescript-node/src/main.ts +0 -0
  245. /package/{src → dist}/functions/templates/uv/README.md +0 -0
  246. /package/{src → dist}/functions/templates/uv/pyproject.toml +0 -0
  247. /package/{src → dist}/functions/templates/uv/src/__init__.py +0 -0
  248. /package/{src → dist}/functions/templates/uv/src/context.py +0 -0
  249. /package/{src → dist}/functions/templates/uv/src/main.py +0 -0
  250. /package/{src/utils/index.ts → dist/utils/index.d.ts} +0 -0
@@ -0,0 +1,17 @@
1
+ import { Databases, Storage, type Models } from "node-appwrite";
2
+ import { type AppwriteConfig } from "appwrite-utils";
3
+ export declare const getDatabaseFromConfig: (config: AppwriteConfig) => Databases;
4
+ export declare const getStorageFromConfig: (config: AppwriteConfig) => Storage;
5
+ export declare const afterImportActions: {
6
+ updateCreatedDocument: (config: AppwriteConfig, dbId: string, collId: string, docId: string, data: any) => Promise<void>;
7
+ checkAndUpdateFieldInDocument: (config: AppwriteConfig, dbId: string, collId: string, docId: string, fieldName: string, oldFieldValue: any, newFieldValue: any) => Promise<void>;
8
+ setFieldFromOtherCollectionDocument: (config: AppwriteConfig, dbId: string, collIdOrName: string, docId: string, fieldName: string, otherCollIdOrName: string, otherDocId: string, otherFieldName: string) => Promise<void>;
9
+ /**
10
+ * Updates a field in a document by setting it with document IDs from another collection
11
+ * based on a matching field value.
12
+ */
13
+ setFieldFromOtherCollectionDocuments: (config: AppwriteConfig, dbId: string, collIdOrName: string, docId: string, fieldName: string, otherCollIdOrName: string, matchingFieldName: string, matchingFieldValue: any, fieldToSet?: string) => Promise<void>;
14
+ setTargetFieldFromOtherCollectionDocumentsByMatchingField: (config: AppwriteConfig, dbId: string, collIdOrName: string, docId: string, fieldName: string, otherCollIdOrName: string, matchingFieldName: string, matchingFieldValue: any, targetField: string) => Promise<void>;
15
+ createOrGetBucket: (config: AppwriteConfig, bucketName: string, bucketId?: string, permissions?: string[], fileSecurity?: boolean, enabled?: boolean, maxFileSize?: number, allowedExtensions?: string[], compression?: string, encryption?: boolean, antivirus?: boolean) => Promise<Models.Bucket | undefined>;
16
+ createFileAndUpdateField: (config: AppwriteConfig, dbId: string, collId: string, docId: string, fieldName: string, bucketId: string, filePath: string, fileName: string) => Promise<void>;
17
+ };
@@ -0,0 +1,305 @@
1
+ import { Databases, Storage, Query, ID, Compression, } from "node-appwrite";
2
+ import { InputFile } from "node-appwrite/file";
3
+ import path from "path";
4
+ import fs from "fs";
5
+ import os from "os";
6
+ import { logger, MessageFormatter } from "appwrite-utils-helpers";
7
+ import { tryAwaitWithRetry, } from "appwrite-utils";
8
+ import { getClientFromConfig } from "appwrite-utils-helpers";
9
+ export const getDatabaseFromConfig = (config) => {
10
+ getClientFromConfig(config); // Sets config.appwriteClient if missing
11
+ return new Databases(config.appwriteClient);
12
+ };
13
+ export const getStorageFromConfig = (config) => {
14
+ getClientFromConfig(config); // Sets config.appwriteClient if missing
15
+ return new Storage(config.appwriteClient);
16
+ };
17
+ export const afterImportActions = {
18
+ updateCreatedDocument: async (config, dbId, collId, docId, data) => {
19
+ try {
20
+ const db = getDatabaseFromConfig(config);
21
+ await tryAwaitWithRetry(async () => await db.updateDocument(dbId, collId, docId, data));
22
+ }
23
+ catch (error) {
24
+ MessageFormatter.error("Error updating document", error instanceof Error ? error : new Error(String(error)), { prefix: "Import" });
25
+ }
26
+ },
27
+ checkAndUpdateFieldInDocument: async (config, dbId, collId, docId, fieldName, oldFieldValue, newFieldValue) => {
28
+ try {
29
+ const db = getDatabaseFromConfig(config);
30
+ const doc = await tryAwaitWithRetry(async () => await db.getDocument(dbId, collId, docId));
31
+ if (doc[fieldName] == oldFieldValue) {
32
+ await tryAwaitWithRetry(async () => await db.updateDocument(dbId, collId, docId, {
33
+ [fieldName]: newFieldValue,
34
+ }));
35
+ }
36
+ }
37
+ catch (error) {
38
+ MessageFormatter.error("Error updating document", error instanceof Error ? error : new Error(String(error)), { prefix: "Import" });
39
+ }
40
+ },
41
+ setFieldFromOtherCollectionDocument: async (config, dbId, collIdOrName, docId, fieldName, otherCollIdOrName, otherDocId, otherFieldName) => {
42
+ const db = getDatabaseFromConfig(config);
43
+ // Helper function to find a collection ID by name or return the ID if given
44
+ const findCollectionId = async (collectionIdentifier) => {
45
+ const collectionsPulled = await tryAwaitWithRetry(async () => await db.listCollections(dbId, [
46
+ Query.limit(25),
47
+ Query.equal("name", collectionIdentifier),
48
+ ]));
49
+ if (collectionsPulled.total > 0) {
50
+ return collectionsPulled.collections[0].$id;
51
+ }
52
+ else {
53
+ // Assuming the passed identifier might directly be an ID if not found by name
54
+ return collectionIdentifier;
55
+ }
56
+ };
57
+ try {
58
+ // Resolve the IDs for both the target and other collections
59
+ const targetCollectionId = await findCollectionId(collIdOrName);
60
+ const otherCollectionId = await findCollectionId(otherCollIdOrName);
61
+ // Retrieve the "other" document
62
+ const otherDoc = await db.getDocument(dbId, otherCollectionId, otherDocId);
63
+ const valueToSet = otherDoc[otherFieldName];
64
+ if (valueToSet) {
65
+ // Update the target document
66
+ await tryAwaitWithRetry(async () => await db.updateDocument(dbId, targetCollectionId, docId, {
67
+ [fieldName]: valueToSet,
68
+ }));
69
+ }
70
+ MessageFormatter.success(`Field ${fieldName} updated successfully in document ${docId}`, { prefix: "Import" });
71
+ }
72
+ catch (error) {
73
+ MessageFormatter.error("Error setting field from other collection document", error instanceof Error ? error : new Error(String(error)), { prefix: "Import" });
74
+ }
75
+ },
76
+ /**
77
+ * Updates a field in a document by setting it with document IDs from another collection
78
+ * based on a matching field value.
79
+ */
80
+ setFieldFromOtherCollectionDocuments: async (config, dbId, collIdOrName, docId, fieldName, otherCollIdOrName, matchingFieldName, matchingFieldValue, fieldToSet) => {
81
+ const db = getDatabaseFromConfig(config);
82
+ // Helper function to find a collection ID by name or return the ID if given
83
+ const findCollectionId = async (collectionIdentifier) => {
84
+ const collections = await tryAwaitWithRetry(async () => await db.listCollections(dbId, [
85
+ Query.equal("name", collectionIdentifier),
86
+ Query.limit(1),
87
+ ]));
88
+ return collections.total > 0
89
+ ? collections.collections[0].$id
90
+ : collectionIdentifier;
91
+ };
92
+ // Function to check if the target field is an array
93
+ const isTargetFieldArray = async (collectionId, fieldName) => {
94
+ const collection = await tryAwaitWithRetry(async () => await db.getCollection(dbId, collectionId));
95
+ const attribute = collection.attributes.find((attr) => attr.key === fieldName);
96
+ // @ts-ignore
97
+ return attribute?.array === true;
98
+ };
99
+ try {
100
+ const targetCollectionId = await findCollectionId(collIdOrName);
101
+ const otherCollectionId = await findCollectionId(otherCollIdOrName);
102
+ const targetFieldIsArray = await isTargetFieldArray(targetCollectionId, fieldName);
103
+ // Function to recursively fetch all matching documents from the other collection
104
+ const fetchAllMatchingDocuments = async (cursor) => {
105
+ const docLimit = 100;
106
+ const queries = targetFieldIsArray
107
+ ? // @ts-ignore
108
+ [Query.contains(matchingFieldName, [matchingFieldValue])]
109
+ : [Query.equal(matchingFieldName, matchingFieldValue)];
110
+ if (cursor) {
111
+ queries.push(Query.cursorAfter(cursor));
112
+ }
113
+ queries.push(Query.limit(docLimit));
114
+ const response = await tryAwaitWithRetry(async () => await db.listDocuments(dbId, otherCollectionId, queries));
115
+ const documents = response.documents;
116
+ if (documents.length === 0 || documents.length < docLimit) {
117
+ return documents;
118
+ }
119
+ const nextCursor = documents[documents.length - 1].$id;
120
+ const nextBatch = await fetchAllMatchingDocuments(nextCursor);
121
+ return documents.concat(nextBatch);
122
+ };
123
+ const matchingDocuments = await fetchAllMatchingDocuments();
124
+ const documentIds = matchingDocuments.map((doc) => doc.$id);
125
+ if (documentIds.length > 0) {
126
+ const updatePayload = targetFieldIsArray
127
+ ? { [fieldName]: documentIds }
128
+ : { [fieldName]: documentIds[0] };
129
+ await tryAwaitWithRetry(async () => await db.updateDocument(dbId, targetCollectionId, docId, updatePayload));
130
+ MessageFormatter.success(`Field ${fieldName} updated successfully in document ${docId} with ${documentIds.length} document IDs`, { prefix: "Import" });
131
+ }
132
+ }
133
+ catch (error) {
134
+ MessageFormatter.error("Error setting field from other collection documents", error instanceof Error ? error : new Error(String(error)), { prefix: "Import" });
135
+ }
136
+ },
137
+ setTargetFieldFromOtherCollectionDocumentsByMatchingField: async (config, dbId, collIdOrName, docId, fieldName, otherCollIdOrName, matchingFieldName, matchingFieldValue, targetField) => {
138
+ const db = getDatabaseFromConfig(config);
139
+ const findCollectionId = async (collectionIdentifier) => {
140
+ const collections = await tryAwaitWithRetry(async () => await db.listCollections(dbId, [
141
+ Query.equal("name", collectionIdentifier),
142
+ Query.limit(1),
143
+ ]));
144
+ return collections.total > 0
145
+ ? collections.collections[0].$id
146
+ : collectionIdentifier;
147
+ };
148
+ const isTargetFieldArray = async (collectionId, fieldName) => {
149
+ const collection = await db.getCollection(dbId, collectionId);
150
+ const attribute = collection.attributes.find((attr) => attr.key === fieldName);
151
+ // @ts-ignore
152
+ return attribute?.array === true;
153
+ };
154
+ try {
155
+ const targetCollectionId = await findCollectionId(collIdOrName);
156
+ const otherCollectionId = await findCollectionId(otherCollIdOrName);
157
+ const targetFieldIsArray = await isTargetFieldArray(targetCollectionId, fieldName);
158
+ const fetchAllMatchingDocuments = async (cursor) => {
159
+ const docLimit = 100;
160
+ const queries = [
161
+ Query.equal(matchingFieldName, matchingFieldValue),
162
+ Query.limit(docLimit),
163
+ ];
164
+ if (cursor) {
165
+ queries.push(Query.cursorAfter(cursor));
166
+ }
167
+ const response = await tryAwaitWithRetry(async () => await db.listDocuments(dbId, otherCollectionId, queries));
168
+ const documents = response.documents;
169
+ if (documents.length === 0 || documents.length < docLimit) {
170
+ return documents;
171
+ }
172
+ const nextCursor = documents[documents.length - 1].$id;
173
+ const nextBatch = await fetchAllMatchingDocuments(nextCursor);
174
+ return documents.concat(nextBatch);
175
+ };
176
+ const matchingDocuments = await fetchAllMatchingDocuments();
177
+ // Map the values from the targetField instead of the document IDs
178
+ const targetFieldValues = matchingDocuments.map((doc) => doc[targetField]);
179
+ if (targetFieldValues.length > 0) {
180
+ const updatePayload = targetFieldIsArray
181
+ ? { [fieldName]: targetFieldValues }
182
+ : { [fieldName]: targetFieldValues[0] };
183
+ await tryAwaitWithRetry(async () => await db.updateDocument(dbId, targetCollectionId, docId, updatePayload));
184
+ MessageFormatter.success(`Field ${fieldName} updated successfully in document ${docId} with values from field ${targetField}`, { prefix: "Import" });
185
+ }
186
+ }
187
+ catch (error) {
188
+ MessageFormatter.error("Error setting field from other collection documents", error instanceof Error ? error : new Error(String(error)), { prefix: "Import" });
189
+ }
190
+ },
191
+ createOrGetBucket: async (config, bucketName, bucketId, permissions, fileSecurity, enabled, maxFileSize, allowedExtensions, compression, encryption, antivirus) => {
192
+ try {
193
+ const storage = getStorageFromConfig(config);
194
+ const bucket = await tryAwaitWithRetry(async () => await storage.listBuckets([Query.equal("name", bucketName)]));
195
+ if (bucket.buckets.length > 0) {
196
+ return bucket.buckets[0];
197
+ }
198
+ else if (bucketId) {
199
+ try {
200
+ return await tryAwaitWithRetry(async () => await storage.getBucket(bucketId));
201
+ }
202
+ catch (error) {
203
+ return await tryAwaitWithRetry(async () => await storage.createBucket(bucketId, bucketName, permissions, fileSecurity, enabled, maxFileSize, allowedExtensions, compression ? Compression.Gzip : undefined, encryption, antivirus));
204
+ }
205
+ }
206
+ else {
207
+ return await tryAwaitWithRetry(async () => await storage.createBucket(bucketId || ID.unique(), bucketName, permissions, fileSecurity, enabled, maxFileSize, allowedExtensions, compression ? Compression.Gzip : undefined, encryption, antivirus));
208
+ }
209
+ }
210
+ catch (error) {
211
+ MessageFormatter.error("Error creating or getting bucket", error instanceof Error ? error : new Error(String(error)), { prefix: "Import" });
212
+ }
213
+ },
214
+ createFileAndUpdateField: async (config, dbId, collId, docId, fieldName, bucketId, filePath, fileName) => {
215
+ try {
216
+ const db = getDatabaseFromConfig(config);
217
+ const storage = getStorageFromConfig(config);
218
+ const collection = await tryAwaitWithRetry(async () => await db.getCollection(dbId, collId));
219
+ const attributes = collection.attributes;
220
+ const attribute = attributes.find((a) => a.key === fieldName);
221
+ // console.log(
222
+ // `Processing field ${fieldName} in collection ${collId} for document ${docId} in database ${dbId} in bucket ${bucketId} with path ${filePath} and name ${fileName}...`
223
+ // );
224
+ if (filePath.length === 0 || fileName.length === 0) {
225
+ MessageFormatter.error(`File path or name is empty for field ${fieldName} in collection ${collId}, skipping...`, undefined, { prefix: "Import" });
226
+ return;
227
+ }
228
+ let isArray = false;
229
+ if (!attribute) {
230
+ MessageFormatter.warning(`Field ${fieldName} not found in collection ${collId}, weird, skipping...`, { prefix: "Import" });
231
+ return;
232
+ }
233
+ else if (attribute.array === true) {
234
+ isArray = true;
235
+ }
236
+ // Define a helper function to check if a value is a URL
237
+ const isUrl = (value) => typeof value === "string" &&
238
+ (value.startsWith("http://") || value.startsWith("https://"));
239
+ const doc = await tryAwaitWithRetry(async () => await db.getDocument(dbId, collId, docId));
240
+ const existingFieldValue = doc[fieldName];
241
+ // Handle the case where the field is an array
242
+ let updateData = isArray ? [] : "";
243
+ if (isArray && Array.isArray(existingFieldValue)) {
244
+ updateData = existingFieldValue.filter((val) => !isUrl(val)); // Remove URLs from the array
245
+ }
246
+ // Process file upload and update logic
247
+ if (isUrl(filePath)) {
248
+ // Create a temporary directory
249
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "appwrite_tmp"));
250
+ const tempFilePath = path.join(tempDir, fileName);
251
+ // Download the file using fetch
252
+ const response = await tryAwaitWithRetry(async () => await fetch(filePath));
253
+ if (!response.ok)
254
+ MessageFormatter.error(`Failed to fetch ${filePath}: ${response.statusText} for document ${docId} with field ${fieldName}`, undefined, { prefix: "Import" });
255
+ // Use arrayBuffer if buffer is not available
256
+ const arrayBuffer = await response.arrayBuffer();
257
+ const buffer = Buffer.from(arrayBuffer);
258
+ fs.writeFileSync(tempFilePath, new Uint8Array(buffer));
259
+ // Create InputFile from the downloaded file
260
+ const inputFile = InputFile.fromPath(tempFilePath, fileName);
261
+ // Use the full file name (with extension) for creating the file
262
+ const file = await tryAwaitWithRetry(async () => await storage.createFile(bucketId, ID.unique(), inputFile));
263
+ MessageFormatter.success(`Created file from URL: ${file.$id}`, { prefix: "Import" });
264
+ // After uploading, adjust the updateData based on whether the field is an array or not
265
+ if (isArray) {
266
+ updateData = [...updateData, file.$id]; // Append the new file ID
267
+ }
268
+ else {
269
+ updateData = file.$id; // Set the new file ID
270
+ }
271
+ await tryAwaitWithRetry(async () => await db.updateDocument(dbId, collId, doc.$id, {
272
+ [fieldName]: updateData,
273
+ }));
274
+ // If the file was downloaded, delete it after uploading
275
+ fs.unlinkSync(tempFilePath);
276
+ }
277
+ else {
278
+ const files = fs.readdirSync(filePath);
279
+ const fileFullName = files.find((file) => file.includes(fileName));
280
+ if (!fileFullName) {
281
+ MessageFormatter.error(`File starting with '${fileName}' not found in '${filePath}'`, undefined, { prefix: "Import" });
282
+ return;
283
+ }
284
+ const pathToFile = path.join(filePath, fileFullName);
285
+ const inputFile = InputFile.fromPath(pathToFile, fileName);
286
+ const file = await tryAwaitWithRetry(async () => await storage.createFile(bucketId, ID.unique(), inputFile));
287
+ if (isArray) {
288
+ updateData = [...updateData, file.$id]; // Append the new file ID
289
+ }
290
+ else {
291
+ updateData = file.$id; // Set the new file ID
292
+ }
293
+ tryAwaitWithRetry(async () => await db.updateDocument(dbId, collId, doc.$id, {
294
+ [fieldName]: updateData,
295
+ }));
296
+ MessageFormatter.success(`Created file from path: ${file.$id}`, { prefix: "Import" });
297
+ }
298
+ }
299
+ catch (error) {
300
+ logger.error(`Error creating file and updating field, params were:\ndbId: ${dbId}, collId: ${collId}, docId: ${docId}, fieldName: ${fieldName}, filePath: ${filePath}, fileName: ${fileName}\n\nError: ${error}`);
301
+ MessageFormatter.error("Error creating file and updating field", error instanceof Error ? error : new Error(String(error)), { prefix: "Import" });
302
+ MessageFormatter.info(`Params were: dbId: ${dbId}, collId: ${collId}, docId: ${docId}, fieldName: ${fieldName}, filePath: ${filePath}, fileName: ${fileName}`, { prefix: "Import" });
303
+ }
304
+ },
305
+ };
@@ -0,0 +1,211 @@
1
+ import { Storage, type Models } from "node-appwrite";
2
+ import { type AppwriteConfig } from "appwrite-utils";
3
+ import type { DatabaseAdapter } from "appwrite-utils-helpers";
4
+ import type { DatabaseSelection, BucketSelection } from "../shared/selectionDialogs.js";
5
+ export declare class AppwriteToX {
6
+ config: AppwriteConfig;
7
+ storage: Storage;
8
+ updatedConfig: AppwriteConfig;
9
+ collToAttributeMap: Map<string, ({
10
+ key: string;
11
+ required: boolean;
12
+ type: "string";
13
+ size: number;
14
+ array?: boolean | undefined;
15
+ format?: string | undefined;
16
+ status?: string | undefined;
17
+ attributes?: string[] | undefined;
18
+ orders?: string[] | undefined;
19
+ $createdAt?: string | undefined;
20
+ $updatedAt?: string | undefined;
21
+ error?: string | undefined;
22
+ xdefault?: string | null | undefined;
23
+ encrypt?: boolean | undefined;
24
+ } | {
25
+ key: string;
26
+ required: boolean;
27
+ type: "integer";
28
+ array?: boolean | undefined;
29
+ format?: string | undefined;
30
+ status?: string | undefined;
31
+ attributes?: string[] | undefined;
32
+ orders?: string[] | undefined;
33
+ $createdAt?: string | undefined;
34
+ $updatedAt?: string | undefined;
35
+ error?: string | undefined;
36
+ min?: number | undefined;
37
+ max?: number | undefined;
38
+ xdefault?: number | null | undefined;
39
+ } | {
40
+ key: string;
41
+ required: boolean;
42
+ type: "double";
43
+ array?: boolean | undefined;
44
+ format?: string | undefined;
45
+ status?: string | undefined;
46
+ attributes?: string[] | undefined;
47
+ orders?: string[] | undefined;
48
+ $createdAt?: string | undefined;
49
+ $updatedAt?: string | undefined;
50
+ error?: string | undefined;
51
+ min?: number | undefined;
52
+ max?: number | undefined;
53
+ xdefault?: number | null | undefined;
54
+ } | {
55
+ key: string;
56
+ required: boolean;
57
+ type: "float";
58
+ array?: boolean | undefined;
59
+ format?: string | undefined;
60
+ status?: string | undefined;
61
+ attributes?: string[] | undefined;
62
+ orders?: string[] | undefined;
63
+ $createdAt?: string | undefined;
64
+ $updatedAt?: string | undefined;
65
+ error?: string | undefined;
66
+ min?: number | undefined;
67
+ max?: number | undefined;
68
+ xdefault?: number | null | undefined;
69
+ } | {
70
+ key: string;
71
+ required: boolean;
72
+ type: "boolean";
73
+ array?: boolean | undefined;
74
+ format?: string | undefined;
75
+ status?: string | undefined;
76
+ attributes?: string[] | undefined;
77
+ orders?: string[] | undefined;
78
+ $createdAt?: string | undefined;
79
+ $updatedAt?: string | undefined;
80
+ error?: string | undefined;
81
+ xdefault?: boolean | null | undefined;
82
+ } | {
83
+ key: string;
84
+ required: boolean;
85
+ type: "datetime";
86
+ array?: boolean | undefined;
87
+ format?: string | undefined;
88
+ status?: string | undefined;
89
+ attributes?: string[] | undefined;
90
+ orders?: string[] | undefined;
91
+ $createdAt?: string | undefined;
92
+ $updatedAt?: string | undefined;
93
+ error?: string | undefined;
94
+ xdefault?: string | null | undefined;
95
+ } | {
96
+ key: string;
97
+ required: boolean;
98
+ type: "email";
99
+ array?: boolean | undefined;
100
+ format?: string | undefined;
101
+ status?: string | undefined;
102
+ attributes?: string[] | undefined;
103
+ orders?: string[] | undefined;
104
+ $createdAt?: string | undefined;
105
+ $updatedAt?: string | undefined;
106
+ error?: string | undefined;
107
+ xdefault?: string | null | undefined;
108
+ } | {
109
+ key: string;
110
+ required: boolean;
111
+ type: "ip";
112
+ array?: boolean | undefined;
113
+ format?: string | undefined;
114
+ status?: string | undefined;
115
+ attributes?: string[] | undefined;
116
+ orders?: string[] | undefined;
117
+ $createdAt?: string | undefined;
118
+ $updatedAt?: string | undefined;
119
+ error?: string | undefined;
120
+ xdefault?: string | null | undefined;
121
+ } | {
122
+ key: string;
123
+ required: boolean;
124
+ type: "url";
125
+ array?: boolean | undefined;
126
+ format?: string | undefined;
127
+ status?: string | undefined;
128
+ attributes?: string[] | undefined;
129
+ orders?: string[] | undefined;
130
+ $createdAt?: string | undefined;
131
+ $updatedAt?: string | undefined;
132
+ error?: string | undefined;
133
+ xdefault?: string | null | undefined;
134
+ } | {
135
+ key: string;
136
+ required: boolean;
137
+ type: "enum";
138
+ elements: string[];
139
+ array?: boolean | undefined;
140
+ format?: string | undefined;
141
+ status?: string | undefined;
142
+ attributes?: string[] | undefined;
143
+ orders?: string[] | undefined;
144
+ $createdAt?: string | undefined;
145
+ $updatedAt?: string | undefined;
146
+ error?: string | undefined;
147
+ xdefault?: string | null | undefined;
148
+ } | {
149
+ key: string;
150
+ required: boolean;
151
+ type: "relationship";
152
+ relatedCollection: string;
153
+ relationType: "oneToMany" | "manyToOne" | "oneToOne" | "manyToMany";
154
+ twoWay: boolean;
155
+ onDelete: "setNull" | "cascade" | "restrict";
156
+ array?: boolean | undefined;
157
+ format?: string | undefined;
158
+ status?: string | undefined;
159
+ attributes?: string[] | undefined;
160
+ orders?: string[] | undefined;
161
+ $createdAt?: string | undefined;
162
+ $updatedAt?: string | undefined;
163
+ error?: string | undefined;
164
+ twoWayKey?: string | undefined;
165
+ side?: "parent" | "child" | undefined;
166
+ importMapping?: {
167
+ originalIdField: string;
168
+ targetField?: string | undefined;
169
+ } | undefined;
170
+ })[]>;
171
+ appwriteFolderPath: string;
172
+ adapter?: DatabaseAdapter;
173
+ apiMode?: 'legacy' | 'tablesdb';
174
+ databaseApiModes: Map<string, "legacy" | "tablesdb">;
175
+ constructor(config: AppwriteConfig, appwriteFolderPath: string, storage: Storage);
176
+ /**
177
+ * Initialize adapter for database operations with API mode detection
178
+ */
179
+ private initializeAdapter;
180
+ private ensureClientInitialized;
181
+ parsePermissionString: (permissionString: string) => {
182
+ permission: string;
183
+ target: string;
184
+ };
185
+ parsePermissionsArray: (permissions: string[]) => ({
186
+ permission: string;
187
+ target: string;
188
+ } | {
189
+ permission: string;
190
+ target: string;
191
+ })[];
192
+ updateCollectionConfigAttributes: (collection: Models.Collection) => void;
193
+ /**
194
+ * Fetch collections/tables using the appropriate adapter or legacy client
195
+ */
196
+ private fetchCollectionsOrTables;
197
+ /**
198
+ * Get collection/table using the appropriate adapter or legacy client
199
+ */
200
+ private getCollectionOrTable;
201
+ /**
202
+ * Detect API mode for a specific database by testing adapter capabilities
203
+ */
204
+ private detectDatabaseApiMode;
205
+ /**
206
+ * Get API mode context for schema generation
207
+ */
208
+ private getSchemaGeneratorApiContext;
209
+ appwriteSync(config: AppwriteConfig, databases?: Models.Database[], databaseSelections?: DatabaseSelection[], bucketSelections?: BucketSelection[]): Promise<void>;
210
+ toSchemas(databases?: Models.Database[], databaseSelections?: DatabaseSelection[], bucketSelections?: BucketSelection[]): Promise<void>;
211
+ }