appwrite-utils-cli 1.9.6 → 1.11.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 (426) hide show
  1. package/CONFIG_TODO.md +1189 -1189
  2. package/README.md +1004 -1004
  3. package/SELECTION_DIALOGS.md +145 -145
  4. package/SERVICE_IMPLEMENTATION_REPORT.md +462 -462
  5. package/package.json +6 -3
  6. package/scripts/copy-templates.ts +23 -23
  7. package/src/adapters/index.ts +11 -37
  8. package/src/backups/operations/bucketBackup.ts +277 -277
  9. package/src/backups/operations/collectionBackup.ts +310 -310
  10. package/src/backups/operations/comprehensiveBackup.ts +342 -342
  11. package/src/backups/schemas/bucketManifest.ts +78 -78
  12. package/src/backups/schemas/comprehensiveManifest.ts +76 -76
  13. package/src/backups/tracking/centralizedTracking.ts +352 -352
  14. package/src/cli/commands/configCommands.ts +265 -201
  15. package/src/cli/commands/databaseCommands.ts +931 -879
  16. package/src/cli/commands/functionCommands.ts +333 -332
  17. package/src/cli/commands/importFileCommands.ts +815 -0
  18. package/src/cli/commands/schemaCommands.ts +141 -141
  19. package/src/cli/commands/storageCommands.ts +2 -3
  20. package/src/cli/commands/transferCommands.ts +454 -457
  21. package/src/collections/attributes.ts.backup +1555 -1555
  22. package/src/collections/{attributes.ts → columns.ts} +15 -44
  23. package/src/collections/indexes.ts +350 -352
  24. package/src/collections/methods.ts +714 -815
  25. package/src/collections/tableOperations.ts +57 -21
  26. package/src/collections/transferOperations.ts +376 -377
  27. package/src/collections/wipeOperations.ts +449 -346
  28. package/src/databases/methods.ts +49 -49
  29. package/src/databases/setup.ts +77 -77
  30. package/src/examples/yamlTerminologyExample.ts +346 -346
  31. package/src/functions/deployments.ts +221 -220
  32. package/src/functions/fnConfigDiscovery.ts +2 -2
  33. package/src/functions/methods.ts +284 -284
  34. package/src/functions/templates/count-docs-in-collection/README.md +53 -53
  35. package/src/functions/templates/count-docs-in-collection/src/main.ts +159 -159
  36. package/src/functions/templates/count-docs-in-collection/src/request.ts +8 -8
  37. package/src/functions/templates/hono-typescript/README.md +285 -285
  38. package/src/functions/templates/hono-typescript/src/adapters/request.ts +73 -73
  39. package/src/functions/templates/hono-typescript/src/adapters/response.ts +105 -105
  40. package/src/functions/templates/hono-typescript/src/app.ts +179 -179
  41. package/src/functions/templates/hono-typescript/src/context.ts +102 -102
  42. package/src/functions/templates/hono-typescript/src/{index.ts → main.ts} +53 -53
  43. package/src/functions/templates/hono-typescript/src/middleware/appwrite.ts +118 -118
  44. package/src/functions/templates/typescript-node/README.md +31 -31
  45. package/src/functions/templates/typescript-node/src/context.ts +102 -102
  46. package/src/functions/templates/typescript-node/src/{index.ts → main.ts} +29 -29
  47. package/src/functions/templates/uv/README.md +30 -30
  48. package/src/functions/templates/uv/pyproject.toml +29 -29
  49. package/src/functions/templates/uv/src/context.py +124 -124
  50. package/src/functions/templates/uv/src/{index.py → main.py} +45 -45
  51. package/src/init.ts +62 -62
  52. package/src/interactiveCLI.ts +1095 -1030
  53. package/src/main.ts +1517 -1670
  54. package/src/migrations/afterImportActions.ts +579 -580
  55. package/src/migrations/appwriteToX.ts +634 -630
  56. package/src/migrations/comprehensiveTransfer.ts +2149 -2149
  57. package/src/migrations/dataLoader.ts +1729 -1702
  58. package/src/migrations/importController.ts +440 -428
  59. package/src/migrations/importDataActions.ts +315 -315
  60. package/src/migrations/relationships.ts +333 -334
  61. package/src/migrations/services/DataTransformationService.ts +195 -195
  62. package/src/migrations/services/FileHandlerService.ts +310 -310
  63. package/src/migrations/services/ImportOrchestrator.ts +674 -665
  64. package/src/migrations/services/RateLimitManager.ts +362 -362
  65. package/src/migrations/services/RelationshipResolver.ts +460 -460
  66. package/src/migrations/services/UserMappingService.ts +344 -344
  67. package/src/migrations/services/ValidationService.ts +333 -333
  68. package/src/migrations/transfer.ts +987 -942
  69. package/src/migrations/yaml/YamlImportConfigLoader.ts +438 -438
  70. package/src/migrations/yaml/YamlImportIntegration.ts +438 -438
  71. package/src/migrations/yaml/generateImportSchemas.ts +1347 -1347
  72. package/src/schemas/authUser.ts +23 -23
  73. package/src/setup.ts +8 -8
  74. package/src/setupCommands.ts +5 -6
  75. package/src/setupController.ts +42 -42
  76. package/src/shared/backupMetadataSchema.ts +93 -93
  77. package/src/shared/backupTracking.ts +211 -211
  78. package/src/shared/confirmationDialogs.ts +326 -326
  79. package/src/shared/migrationHelpers.ts +232 -232
  80. package/src/shared/operationLogger.ts +20 -20
  81. package/src/shared/operationQueue.ts +326 -327
  82. package/src/shared/operationsTable.ts +338 -338
  83. package/src/shared/operationsTableSchema.ts +60 -60
  84. package/src/shared/progressManager.ts +277 -277
  85. package/src/shared/relationshipExtractor.ts +214 -214
  86. package/src/shared/selectionDialogs.ts +775 -722
  87. package/src/storage/backupCompression.ts +88 -88
  88. package/src/storage/methods.ts +695 -682
  89. package/src/storage/schemas.ts +205 -205
  90. package/src/tables/indexManager.ts +409 -0
  91. package/src/types/node-appwrite-tablesdb.d.ts +43 -43
  92. package/src/types.ts +9 -9
  93. package/src/users/methods.ts +358 -359
  94. package/src/utils/configMigration.ts +347 -347
  95. package/src/utils/index.ts +2 -2
  96. package/src/utils/loadConfigs.ts +457 -449
  97. package/src/utils/setupFiles.ts +1236 -1238
  98. package/src/utilsController.ts +1263 -1213
  99. package/tests/README.md +496 -496
  100. package/tests/adapters/AdapterFactory.test.ts +276 -276
  101. package/tests/integration/syncOperations.test.ts +462 -462
  102. package/tests/jest.config.js +24 -24
  103. package/tests/migration/configMigration.test.ts +545 -545
  104. package/tests/setup.ts +61 -61
  105. package/tests/testUtils.ts +339 -339
  106. package/tests/utils/loadConfigs.test.ts +349 -349
  107. package/tests/validation/configValidation.test.ts +411 -411
  108. package/tsconfig.json +44 -44
  109. package/.appwrite/.yaml_schemas/appwrite-config.schema.json +0 -380
  110. package/.appwrite/.yaml_schemas/collection.schema.json +0 -255
  111. package/.appwrite/collections/Categories.yaml +0 -182
  112. package/.appwrite/collections/ExampleCollection.yaml +0 -36
  113. package/.appwrite/collections/Posts.yaml +0 -227
  114. package/.appwrite/collections/Users.yaml +0 -149
  115. package/.appwrite/config.yaml +0 -109
  116. package/.appwrite/import/README.md +0 -148
  117. package/.appwrite/import/categories-import.yaml +0 -129
  118. package/.appwrite/import/posts-import.yaml +0 -208
  119. package/.appwrite/import/users-import.yaml +0 -130
  120. package/.appwrite/importData/categories.json +0 -194
  121. package/.appwrite/importData/posts.json +0 -270
  122. package/.appwrite/importData/users.json +0 -220
  123. package/.appwrite/schemas/categories.json +0 -128
  124. package/.appwrite/schemas/exampleCollection.json +0 -52
  125. package/.appwrite/schemas/posts.json +0 -173
  126. package/.appwrite/schemas/users.json +0 -125
  127. package/dist/adapters/AdapterFactory.d.ts +0 -94
  128. package/dist/adapters/AdapterFactory.js +0 -405
  129. package/dist/adapters/DatabaseAdapter.d.ts +0 -242
  130. package/dist/adapters/DatabaseAdapter.js +0 -50
  131. package/dist/adapters/LegacyAdapter.d.ts +0 -50
  132. package/dist/adapters/LegacyAdapter.js +0 -612
  133. package/dist/adapters/TablesDBAdapter.d.ts +0 -45
  134. package/dist/adapters/TablesDBAdapter.js +0 -596
  135. package/dist/adapters/index.d.ts +0 -11
  136. package/dist/adapters/index.js +0 -12
  137. package/dist/backups/operations/bucketBackup.d.ts +0 -19
  138. package/dist/backups/operations/bucketBackup.js +0 -197
  139. package/dist/backups/operations/collectionBackup.d.ts +0 -30
  140. package/dist/backups/operations/collectionBackup.js +0 -201
  141. package/dist/backups/operations/comprehensiveBackup.d.ts +0 -25
  142. package/dist/backups/operations/comprehensiveBackup.js +0 -238
  143. package/dist/backups/schemas/bucketManifest.d.ts +0 -93
  144. package/dist/backups/schemas/bucketManifest.js +0 -33
  145. package/dist/backups/schemas/comprehensiveManifest.d.ts +0 -108
  146. package/dist/backups/schemas/comprehensiveManifest.js +0 -32
  147. package/dist/backups/tracking/centralizedTracking.d.ts +0 -34
  148. package/dist/backups/tracking/centralizedTracking.js +0 -274
  149. package/dist/cli/commands/configCommands.d.ts +0 -8
  150. package/dist/cli/commands/configCommands.js +0 -166
  151. package/dist/cli/commands/databaseCommands.d.ts +0 -14
  152. package/dist/cli/commands/databaseCommands.js +0 -644
  153. package/dist/cli/commands/functionCommands.d.ts +0 -7
  154. package/dist/cli/commands/functionCommands.js +0 -330
  155. package/dist/cli/commands/schemaCommands.d.ts +0 -7
  156. package/dist/cli/commands/schemaCommands.js +0 -169
  157. package/dist/cli/commands/storageCommands.d.ts +0 -5
  158. package/dist/cli/commands/storageCommands.js +0 -143
  159. package/dist/cli/commands/transferCommands.d.ts +0 -5
  160. package/dist/cli/commands/transferCommands.js +0 -384
  161. package/dist/collections/attributes.d.ts +0 -13
  162. package/dist/collections/attributes.js +0 -1364
  163. package/dist/collections/indexes.d.ts +0 -12
  164. package/dist/collections/indexes.js +0 -217
  165. package/dist/collections/methods.d.ts +0 -19
  166. package/dist/collections/methods.js +0 -734
  167. package/dist/collections/tableOperations.d.ts +0 -86
  168. package/dist/collections/tableOperations.js +0 -434
  169. package/dist/collections/transferOperations.d.ts +0 -8
  170. package/dist/collections/transferOperations.js +0 -412
  171. package/dist/collections/wipeOperations.d.ts +0 -16
  172. package/dist/collections/wipeOperations.js +0 -233
  173. package/dist/config/ConfigManager.d.ts +0 -450
  174. package/dist/config/ConfigManager.js +0 -625
  175. package/dist/config/configMigration.d.ts +0 -87
  176. package/dist/config/configMigration.js +0 -390
  177. package/dist/config/configValidation.d.ts +0 -66
  178. package/dist/config/configValidation.js +0 -358
  179. package/dist/config/index.d.ts +0 -8
  180. package/dist/config/index.js +0 -7
  181. package/dist/config/services/ConfigDiscoveryService.d.ts +0 -122
  182. package/dist/config/services/ConfigDiscoveryService.js +0 -322
  183. package/dist/config/services/ConfigLoaderService.d.ts +0 -129
  184. package/dist/config/services/ConfigLoaderService.js +0 -535
  185. package/dist/config/services/ConfigMergeService.d.ts +0 -208
  186. package/dist/config/services/ConfigMergeService.js +0 -308
  187. package/dist/config/services/ConfigValidationService.d.ts +0 -214
  188. package/dist/config/services/ConfigValidationService.js +0 -310
  189. package/dist/config/services/SessionAuthService.d.ts +0 -225
  190. package/dist/config/services/SessionAuthService.js +0 -456
  191. package/dist/config/services/__tests__/ConfigMergeService.test.d.ts +0 -1
  192. package/dist/config/services/__tests__/ConfigMergeService.test.js +0 -271
  193. package/dist/config/services/index.d.ts +0 -13
  194. package/dist/config/services/index.js +0 -10
  195. package/dist/config/yamlConfig.d.ts +0 -722
  196. package/dist/config/yamlConfig.js +0 -702
  197. package/dist/databases/methods.d.ts +0 -6
  198. package/dist/databases/methods.js +0 -35
  199. package/dist/databases/setup.d.ts +0 -5
  200. package/dist/databases/setup.js +0 -45
  201. package/dist/examples/yamlTerminologyExample.d.ts +0 -42
  202. package/dist/examples/yamlTerminologyExample.js +0 -272
  203. package/dist/functions/deployments.d.ts +0 -4
  204. package/dist/functions/deployments.js +0 -146
  205. package/dist/functions/fnConfigDiscovery.d.ts +0 -3
  206. package/dist/functions/fnConfigDiscovery.js +0 -108
  207. package/dist/functions/methods.d.ts +0 -16
  208. package/dist/functions/methods.js +0 -174
  209. package/dist/functions/pathResolution.d.ts +0 -37
  210. package/dist/functions/pathResolution.js +0 -185
  211. package/dist/functions/templates/count-docs-in-collection/README.md +0 -54
  212. package/dist/functions/templates/count-docs-in-collection/package.json +0 -25
  213. package/dist/functions/templates/count-docs-in-collection/src/main.ts +0 -159
  214. package/dist/functions/templates/count-docs-in-collection/src/request.ts +0 -9
  215. package/dist/functions/templates/count-docs-in-collection/tsconfig.json +0 -28
  216. package/dist/functions/templates/hono-typescript/README.md +0 -286
  217. package/dist/functions/templates/hono-typescript/package.json +0 -26
  218. package/dist/functions/templates/hono-typescript/src/adapters/request.ts +0 -74
  219. package/dist/functions/templates/hono-typescript/src/adapters/response.ts +0 -106
  220. package/dist/functions/templates/hono-typescript/src/app.ts +0 -180
  221. package/dist/functions/templates/hono-typescript/src/context.ts +0 -103
  222. package/dist/functions/templates/hono-typescript/src/index.ts +0 -54
  223. package/dist/functions/templates/hono-typescript/src/middleware/appwrite.ts +0 -119
  224. package/dist/functions/templates/hono-typescript/tsconfig.json +0 -20
  225. package/dist/functions/templates/typescript-node/README.md +0 -32
  226. package/dist/functions/templates/typescript-node/package.json +0 -25
  227. package/dist/functions/templates/typescript-node/src/context.ts +0 -103
  228. package/dist/functions/templates/typescript-node/src/index.ts +0 -29
  229. package/dist/functions/templates/typescript-node/tsconfig.json +0 -28
  230. package/dist/functions/templates/uv/README.md +0 -31
  231. package/dist/functions/templates/uv/pyproject.toml +0 -30
  232. package/dist/functions/templates/uv/src/__init__.py +0 -0
  233. package/dist/functions/templates/uv/src/context.py +0 -125
  234. package/dist/functions/templates/uv/src/index.py +0 -46
  235. package/dist/init.d.ts +0 -2
  236. package/dist/init.js +0 -57
  237. package/dist/interactiveCLI.d.ts +0 -31
  238. package/dist/interactiveCLI.js +0 -898
  239. package/dist/main.d.ts +0 -2
  240. package/dist/main.js +0 -1180
  241. package/dist/migrations/afterImportActions.d.ts +0 -17
  242. package/dist/migrations/afterImportActions.js +0 -306
  243. package/dist/migrations/appwriteToX.d.ts +0 -211
  244. package/dist/migrations/appwriteToX.js +0 -491
  245. package/dist/migrations/comprehensiveTransfer.d.ts +0 -147
  246. package/dist/migrations/comprehensiveTransfer.js +0 -1317
  247. package/dist/migrations/dataLoader.d.ts +0 -753
  248. package/dist/migrations/dataLoader.js +0 -1250
  249. package/dist/migrations/importController.d.ts +0 -23
  250. package/dist/migrations/importController.js +0 -268
  251. package/dist/migrations/importDataActions.d.ts +0 -50
  252. package/dist/migrations/importDataActions.js +0 -230
  253. package/dist/migrations/relationships.d.ts +0 -29
  254. package/dist/migrations/relationships.js +0 -204
  255. package/dist/migrations/services/DataTransformationService.d.ts +0 -55
  256. package/dist/migrations/services/DataTransformationService.js +0 -158
  257. package/dist/migrations/services/FileHandlerService.d.ts +0 -75
  258. package/dist/migrations/services/FileHandlerService.js +0 -236
  259. package/dist/migrations/services/ImportOrchestrator.d.ts +0 -97
  260. package/dist/migrations/services/ImportOrchestrator.js +0 -485
  261. package/dist/migrations/services/RateLimitManager.d.ts +0 -138
  262. package/dist/migrations/services/RateLimitManager.js +0 -279
  263. package/dist/migrations/services/RelationshipResolver.d.ts +0 -120
  264. package/dist/migrations/services/RelationshipResolver.js +0 -332
  265. package/dist/migrations/services/UserMappingService.d.ts +0 -109
  266. package/dist/migrations/services/UserMappingService.js +0 -277
  267. package/dist/migrations/services/ValidationService.d.ts +0 -74
  268. package/dist/migrations/services/ValidationService.js +0 -260
  269. package/dist/migrations/transfer.d.ts +0 -26
  270. package/dist/migrations/transfer.js +0 -608
  271. package/dist/migrations/yaml/YamlImportConfigLoader.d.ts +0 -131
  272. package/dist/migrations/yaml/YamlImportConfigLoader.js +0 -383
  273. package/dist/migrations/yaml/YamlImportIntegration.d.ts +0 -93
  274. package/dist/migrations/yaml/YamlImportIntegration.js +0 -341
  275. package/dist/migrations/yaml/generateImportSchemas.d.ts +0 -30
  276. package/dist/migrations/yaml/generateImportSchemas.js +0 -1327
  277. package/dist/schemas/authUser.d.ts +0 -24
  278. package/dist/schemas/authUser.js +0 -17
  279. package/dist/setup.d.ts +0 -2
  280. package/dist/setup.js +0 -5
  281. package/dist/setupCommands.d.ts +0 -58
  282. package/dist/setupCommands.js +0 -490
  283. package/dist/setupController.d.ts +0 -9
  284. package/dist/setupController.js +0 -34
  285. package/dist/shared/attributeMapper.d.ts +0 -20
  286. package/dist/shared/attributeMapper.js +0 -203
  287. package/dist/shared/backupMetadataSchema.d.ts +0 -94
  288. package/dist/shared/backupMetadataSchema.js +0 -38
  289. package/dist/shared/backupTracking.d.ts +0 -18
  290. package/dist/shared/backupTracking.js +0 -176
  291. package/dist/shared/confirmationDialogs.d.ts +0 -75
  292. package/dist/shared/confirmationDialogs.js +0 -236
  293. package/dist/shared/errorUtils.d.ts +0 -54
  294. package/dist/shared/errorUtils.js +0 -95
  295. package/dist/shared/functionManager.d.ts +0 -48
  296. package/dist/shared/functionManager.js +0 -348
  297. package/dist/shared/indexManager.d.ts +0 -24
  298. package/dist/shared/indexManager.js +0 -151
  299. package/dist/shared/jsonSchemaGenerator.d.ts +0 -50
  300. package/dist/shared/jsonSchemaGenerator.js +0 -290
  301. package/dist/shared/logging.d.ts +0 -61
  302. package/dist/shared/logging.js +0 -116
  303. package/dist/shared/messageFormatter.d.ts +0 -39
  304. package/dist/shared/messageFormatter.js +0 -162
  305. package/dist/shared/migrationHelpers.d.ts +0 -61
  306. package/dist/shared/migrationHelpers.js +0 -145
  307. package/dist/shared/operationLogger.d.ts +0 -10
  308. package/dist/shared/operationLogger.js +0 -12
  309. package/dist/shared/operationQueue.d.ts +0 -40
  310. package/dist/shared/operationQueue.js +0 -311
  311. package/dist/shared/operationsTable.d.ts +0 -26
  312. package/dist/shared/operationsTable.js +0 -286
  313. package/dist/shared/operationsTableSchema.d.ts +0 -48
  314. package/dist/shared/operationsTableSchema.js +0 -35
  315. package/dist/shared/progressManager.d.ts +0 -62
  316. package/dist/shared/progressManager.js +0 -215
  317. package/dist/shared/pydanticModelGenerator.d.ts +0 -17
  318. package/dist/shared/pydanticModelGenerator.js +0 -615
  319. package/dist/shared/relationshipExtractor.d.ts +0 -56
  320. package/dist/shared/relationshipExtractor.js +0 -138
  321. package/dist/shared/schemaGenerator.d.ts +0 -40
  322. package/dist/shared/schemaGenerator.js +0 -556
  323. package/dist/shared/selectionDialogs.d.ts +0 -214
  324. package/dist/shared/selectionDialogs.js +0 -544
  325. package/dist/storage/backupCompression.d.ts +0 -20
  326. package/dist/storage/backupCompression.js +0 -67
  327. package/dist/storage/methods.d.ts +0 -32
  328. package/dist/storage/methods.js +0 -472
  329. package/dist/storage/schemas.d.ts +0 -842
  330. package/dist/storage/schemas.js +0 -175
  331. package/dist/types.d.ts +0 -4
  332. package/dist/types.js +0 -3
  333. package/dist/users/methods.d.ts +0 -16
  334. package/dist/users/methods.js +0 -277
  335. package/dist/utils/ClientFactory.d.ts +0 -87
  336. package/dist/utils/ClientFactory.js +0 -212
  337. package/dist/utils/configDiscovery.d.ts +0 -78
  338. package/dist/utils/configDiscovery.js +0 -472
  339. package/dist/utils/configMigration.d.ts +0 -1
  340. package/dist/utils/configMigration.js +0 -261
  341. package/dist/utils/constantsGenerator.d.ts +0 -31
  342. package/dist/utils/constantsGenerator.js +0 -321
  343. package/dist/utils/dataConverters.d.ts +0 -46
  344. package/dist/utils/dataConverters.js +0 -139
  345. package/dist/utils/directoryUtils.d.ts +0 -22
  346. package/dist/utils/directoryUtils.js +0 -59
  347. package/dist/utils/getClientFromConfig.d.ts +0 -39
  348. package/dist/utils/getClientFromConfig.js +0 -199
  349. package/dist/utils/helperFunctions.d.ts +0 -63
  350. package/dist/utils/helperFunctions.js +0 -156
  351. package/dist/utils/index.d.ts +0 -2
  352. package/dist/utils/index.js +0 -2
  353. package/dist/utils/loadConfigs.d.ts +0 -50
  354. package/dist/utils/loadConfigs.js +0 -358
  355. package/dist/utils/pathResolvers.d.ts +0 -53
  356. package/dist/utils/pathResolvers.js +0 -72
  357. package/dist/utils/projectConfig.d.ts +0 -122
  358. package/dist/utils/projectConfig.js +0 -206
  359. package/dist/utils/retryFailedPromises.d.ts +0 -2
  360. package/dist/utils/retryFailedPromises.js +0 -23
  361. package/dist/utils/sessionAuth.d.ts +0 -48
  362. package/dist/utils/sessionAuth.js +0 -164
  363. package/dist/utils/setupFiles.d.ts +0 -4
  364. package/dist/utils/setupFiles.js +0 -1192
  365. package/dist/utils/typeGuards.d.ts +0 -35
  366. package/dist/utils/typeGuards.js +0 -57
  367. package/dist/utils/validationRules.d.ts +0 -43
  368. package/dist/utils/validationRules.js +0 -42
  369. package/dist/utils/versionDetection.d.ts +0 -58
  370. package/dist/utils/versionDetection.js +0 -251
  371. package/dist/utils/yamlConverter.d.ts +0 -100
  372. package/dist/utils/yamlConverter.js +0 -428
  373. package/dist/utils/yamlLoader.d.ts +0 -70
  374. package/dist/utils/yamlLoader.js +0 -267
  375. package/dist/utilsController.d.ts +0 -107
  376. package/dist/utilsController.js +0 -873
  377. package/src/adapters/AdapterFactory.ts +0 -510
  378. package/src/adapters/DatabaseAdapter.ts +0 -318
  379. package/src/adapters/LegacyAdapter.ts +0 -841
  380. package/src/adapters/TablesDBAdapter.ts +0 -815
  381. package/src/config/ConfigManager.ts +0 -817
  382. package/src/config/README.md +0 -274
  383. package/src/config/configMigration.ts +0 -575
  384. package/src/config/configValidation.ts +0 -445
  385. package/src/config/index.ts +0 -10
  386. package/src/config/services/ConfigDiscoveryService.ts +0 -410
  387. package/src/config/services/ConfigLoaderService.ts +0 -732
  388. package/src/config/services/ConfigMergeService.ts +0 -388
  389. package/src/config/services/ConfigValidationService.ts +0 -394
  390. package/src/config/services/SessionAuthService.ts +0 -565
  391. package/src/config/services/__tests__/ConfigMergeService.test.ts +0 -351
  392. package/src/config/services/index.ts +0 -29
  393. package/src/config/yamlConfig.ts +0 -761
  394. package/src/functions/pathResolution.ts +0 -227
  395. package/src/functions/templates/count-docs-in-collection/package.json +0 -25
  396. package/src/functions/templates/count-docs-in-collection/tsconfig.json +0 -28
  397. package/src/functions/templates/hono-typescript/package.json +0 -26
  398. package/src/functions/templates/hono-typescript/tsconfig.json +0 -20
  399. package/src/functions/templates/typescript-node/package.json +0 -25
  400. package/src/functions/templates/typescript-node/tsconfig.json +0 -28
  401. package/src/shared/attributeMapper.ts +0 -229
  402. package/src/shared/errorUtils.ts +0 -110
  403. package/src/shared/functionManager.ts +0 -537
  404. package/src/shared/indexManager.ts +0 -254
  405. package/src/shared/jsonSchemaGenerator.ts +0 -383
  406. package/src/shared/logging.ts +0 -149
  407. package/src/shared/messageFormatter.ts +0 -208
  408. package/src/shared/pydanticModelGenerator.ts +0 -618
  409. package/src/shared/schemaGenerator.ts +0 -644
  410. package/src/utils/ClientFactory.ts +0 -240
  411. package/src/utils/configDiscovery.ts +0 -557
  412. package/src/utils/constantsGenerator.ts +0 -369
  413. package/src/utils/dataConverters.ts +0 -159
  414. package/src/utils/directoryUtils.ts +0 -61
  415. package/src/utils/getClientFromConfig.ts +0 -257
  416. package/src/utils/helperFunctions.ts +0 -228
  417. package/src/utils/pathResolvers.ts +0 -81
  418. package/src/utils/projectConfig.ts +0 -340
  419. package/src/utils/retryFailedPromises.ts +0 -29
  420. package/src/utils/sessionAuth.ts +0 -230
  421. package/src/utils/typeGuards.ts +0 -65
  422. package/src/utils/validationRules.ts +0 -88
  423. package/src/utils/versionDetection.ts +0 -292
  424. package/src/utils/yamlConverter.ts +0 -542
  425. package/src/utils/yamlLoader.ts +0 -371
  426. package/tmp-sync-test/.appwrite/collections/TestCollection.yaml +0 -7
@@ -1,815 +1,714 @@
1
- import {
2
- Databases,
3
- ID,
4
- Permission,
5
- Query,
6
- type Models,
7
- } from "node-appwrite";
8
- import type { AppwriteConfig, CollectionCreate, Indexes, Attribute } from "appwrite-utils";
9
- import type { DatabaseAdapter } from "../adapters/DatabaseAdapter.js";
10
- import { getAdapterFromConfig } from "../utils/getClientFromConfig.js";
11
- import {
12
- nameToIdMapping,
13
- processQueue,
14
- queuedOperations,
15
- clearProcessingState,
16
- isCollectionProcessed,
17
- markCollectionProcessed,
18
- enqueueOperation
19
- } from "../shared/operationQueue.js";
20
- import { logger } from "../shared/logging.js";
21
- // Legacy attribute/index helpers removed in favor of unified adapter path
22
- import { SchemaGenerator } from "../shared/schemaGenerator.js";
23
- import {
24
- isNull,
25
- isUndefined,
26
- isNil,
27
- isPlainObject,
28
- isString,
29
- } from "es-toolkit";
30
- import { delay, tryAwaitWithRetry } from "../utils/helperFunctions.js";
31
- import { MessageFormatter } from "../shared/messageFormatter.js";
32
- import { isLegacyDatabases } from "../utils/typeGuards.js";
33
- import { mapToCreateAttributeParams, mapToUpdateAttributeParams } from "../shared/attributeMapper.js";
34
- import { diffTableColumns, isIndexEqualToIndex, diffColumnsDetailed, executeColumnOperations } from "./tableOperations.js";
35
-
36
- // Re-export wipe operations
37
- export {
38
- wipeDatabase,
39
- wipeCollection,
40
- wipeAllTables,
41
- wipeTableRows,
42
- } from "./wipeOperations.js";
43
-
44
- // Re-export transfer operations
45
- export {
46
- transferDocumentsBetweenDbsLocalToLocal,
47
- transferDocumentsBetweenDbsLocalToRemote,
48
- } from "./transferOperations.js";
49
-
50
- export const documentExists = async (
51
- db: Databases | DatabaseAdapter,
52
- dbId: string,
53
- targetCollectionId: string,
54
- toCreateObject: any
55
- ): Promise<Models.Document | null> => {
56
- const collection = await (isLegacyDatabases(db) ?
57
- db.getCollection(dbId, targetCollectionId) :
58
- db.getTable({ databaseId: dbId, tableId: targetCollectionId }));
59
- const attributes = (collection as any).attributes as any[];
60
- let arrayTypeAttributes = attributes
61
- .filter((attribute: any) => attribute.array === true)
62
- .map((attribute: any) => attribute.key);
63
-
64
- const isJsonString = (str: string) => {
65
- try {
66
- const json = JSON.parse(str);
67
- return typeof json === "object" && json !== null;
68
- } catch (e) {
69
- return false;
70
- }
71
- };
72
-
73
- // Convert object to entries and filter
74
- const validEntries = Object.entries(toCreateObject).filter(
75
- ([key, value]) =>
76
- !arrayTypeAttributes.includes(key) &&
77
- !key.startsWith("$") &&
78
- !isNull(value) &&
79
- !isUndefined(value) &&
80
- !isNil(value) &&
81
- !isPlainObject(value) &&
82
- !Array.isArray(value) &&
83
- !(isString(value) && isJsonString(value)) &&
84
- (isString(value) ? value.length < 4096 && value.length > 0 : true)
85
- );
86
-
87
- // Map and filter valid entries
88
- const validMappedEntries = validEntries
89
- .map(([key, value]) => [
90
- key,
91
- isString(value) || typeof value === "number" || typeof value === "boolean"
92
- ? value
93
- : null,
94
- ])
95
- .filter(([key, value]) => !isNull(value) && isString(key))
96
- .slice(0, 25);
97
-
98
- // Convert to Query parameters
99
- const validQueryParams = validMappedEntries.map(([key, value]) =>
100
- Query.equal(key as string, value as any)
101
- );
102
-
103
- // Execute the query with the validated and prepared parameters
104
- const result = await (isLegacyDatabases(db) ?
105
- db.listDocuments(dbId, targetCollectionId, validQueryParams) :
106
- db.listRows({ databaseId: dbId, tableId: targetCollectionId, queries: validQueryParams }));
107
-
108
- const items = isLegacyDatabases(db) ? result.documents : ((result as any).rows || result.documents);
109
- return items?.[0] || null;
110
- };
111
-
112
- export const checkForCollection = async (
113
- db: Databases | DatabaseAdapter,
114
- dbId: string,
115
- collection: Partial<CollectionCreate>
116
- ): Promise<Models.Collection | null> => {
117
- try {
118
- MessageFormatter.progress(`Checking for collection with name: ${collection.name}`, { prefix: "Collections" });
119
- const response = await tryAwaitWithRetry(
120
- async () => isLegacyDatabases(db) ?
121
- await db.listCollections(dbId, [Query.equal("name", collection.name!)]) :
122
- await db.listTables({ databaseId: dbId, queries: [Query.equal("name", collection.name!)] })
123
- );
124
- const items = isLegacyDatabases(db) ? response.collections : ((response as any).tables || response.collections);
125
- if (items && items.length > 0) {
126
- MessageFormatter.info(`Collection found: ${items[0].$id}`, { prefix: "Collections" });
127
- // Return remote collection for update operations (don't merge local config over it)
128
- return items[0] as Models.Collection;
129
- } else {
130
- MessageFormatter.info(`No collection found with name: ${collection.name}`, { prefix: "Collections" });
131
- return null;
132
- }
133
- } catch (error) {
134
- const errorMessage = error instanceof Error ? error.message : String(error);
135
- MessageFormatter.error(`Error checking for collection: ${collection.name}`, error instanceof Error ? error : new Error(String(error)), { prefix: "Collections" });
136
- logger.error('Collection check failed', {
137
- collectionName: collection.name,
138
- dbId,
139
- error: errorMessage,
140
- operation: 'checkForCollection'
141
- });
142
- return null;
143
- }
144
- };
145
-
146
- // Helper function to fetch and cache collection by name
147
- export const fetchAndCacheCollectionByName = async (
148
- db: Databases | DatabaseAdapter,
149
- dbId: string,
150
- collectionName: string
151
- ): Promise<Models.Collection | undefined> => {
152
- if (nameToIdMapping.has(collectionName)) {
153
- const collectionId = nameToIdMapping.get(collectionName);
154
- MessageFormatter.debug(`Collection found in cache: ${collectionId}`, undefined, { prefix: "Collections" });
155
- return await tryAwaitWithRetry(
156
- async () => isLegacyDatabases(db) ?
157
- await db.getCollection(dbId, collectionId!) :
158
- await db.getTable({ databaseId: dbId, tableId: collectionId! })
159
- ) as Models.Collection;
160
- } else {
161
- MessageFormatter.progress(`Fetching collection by name: ${collectionName}`, { prefix: "Collections" });
162
- const collectionsPulled = await tryAwaitWithRetry(
163
- async () => isLegacyDatabases(db) ?
164
- await db.listCollections(dbId, [Query.equal("name", collectionName)]) :
165
- await db.listTables({ databaseId: dbId, queries: [Query.equal("name", collectionName)] })
166
- );
167
- const items = isLegacyDatabases(db) ? collectionsPulled.collections : ((collectionsPulled as any).tables || collectionsPulled.collections);
168
- if ((collectionsPulled.total || items?.length) > 0) {
169
- const collection = items[0];
170
- MessageFormatter.info(`Collection found: ${collection.$id}`, { prefix: "Collections" });
171
- nameToIdMapping.set(collectionName, collection.$id);
172
- return collection;
173
- } else {
174
- MessageFormatter.warning(`Collection not found by name: ${collectionName}`, { prefix: "Collections" });
175
- return undefined;
176
- }
177
- }
178
- };
179
-
180
- export const generateSchemas = async (
181
- config: AppwriteConfig,
182
- appwriteFolderPath: string
183
- ): Promise<void> => {
184
- const schemaGenerator = new SchemaGenerator(config, appwriteFolderPath);
185
- await schemaGenerator.generateSchemas();
186
- };
187
-
188
- export const createOrUpdateCollections = async (
189
- database: Databases,
190
- databaseId: string,
191
- config: AppwriteConfig,
192
- deletedCollections?: { collectionId: string; collectionName: string }[],
193
- selectedCollections: Models.Collection[] = []
194
- ): Promise<void> => {
195
- // Clear processing state at the start of a new operation
196
- clearProcessingState();
197
-
198
- // Always use adapter path (LegacyAdapter translates when pre-1.8)
199
- const { adapter } = await getAdapterFromConfig(config);
200
- await createOrUpdateCollectionsViaAdapter(
201
- adapter,
202
- databaseId,
203
- config,
204
- deletedCollections,
205
- selectedCollections
206
- );
207
- };
208
-
209
- // New: Adapter-based implementation for TablesDB with state management
210
- export const createOrUpdateCollectionsViaAdapter = async (
211
- adapter: DatabaseAdapter,
212
- databaseId: string,
213
- config: AppwriteConfig,
214
- deletedCollections?: { collectionId: string; collectionName: string }[],
215
- selectedCollections: Models.Collection[] = []
216
- ): Promise<void> => {
217
- const collectionsToProcess =
218
- selectedCollections.length > 0 ? selectedCollections : (config.collections || []);
219
- if (!collectionsToProcess || collectionsToProcess.length === 0) return;
220
-
221
- const usedIds = new Set<string>();
222
- MessageFormatter.info(`Processing ${collectionsToProcess.length} tables via adapter with intelligent state management`, { prefix: "Tables" });
223
-
224
- // Helpers for attribute operations through adapter
225
- const createAttr = async (tableId: string, attr: Attribute) => {
226
- const params = mapToCreateAttributeParams(attr as any, { databaseId, tableId });
227
- await adapter.createAttribute(params);
228
- await delay(150);
229
- };
230
- const updateAttr = async (tableId: string, attr: Attribute) => {
231
- const params = mapToUpdateAttributeParams(attr as any, { databaseId, tableId }) as any;
232
- await adapter.updateAttribute(params);
233
- await delay(150);
234
- };
235
-
236
- // Local queue for unresolved relationships
237
- const relQueue: { tableId: string; attr: Attribute }[] = [];
238
-
239
- for (const collection of collectionsToProcess) {
240
- const { attributes, indexes, ...collectionData } = collection as any;
241
-
242
- // Check if this table has already been processed in this session (per database)
243
- if (collectionData.$id && isCollectionProcessed(collectionData.$id, databaseId)) {
244
- MessageFormatter.info(`Table '${collectionData.name}' already processed, skipping`, { prefix: "Tables" });
245
- continue;
246
- }
247
-
248
- // Prepare permissions as strings (reuse Permission helper)
249
- const permissions: string[] = [];
250
- if (collection.$permissions && collection.$permissions.length > 0) {
251
- for (const p of collection.$permissions as any[]) {
252
- if (typeof p === 'string') permissions.push(p);
253
- else {
254
- switch (p.permission) {
255
- case 'read': permissions.push(Permission.read(p.target)); break;
256
- case 'create': permissions.push(Permission.create(p.target)); break;
257
- case 'update': permissions.push(Permission.update(p.target)); break;
258
- case 'delete': permissions.push(Permission.delete(p.target)); break;
259
- case 'write': permissions.push(Permission.write(p.target)); break;
260
- default: break;
261
- }
262
- }
263
- }
264
- }
265
-
266
- // Find existing table — prefer lookup by ID (if provided), then by name
267
- let table: any | undefined;
268
- let tableId: string;
269
-
270
- // 1) Try by explicit $id first (handles rename scenarios)
271
- if (collectionData.$id) {
272
- try {
273
- const byId = await adapter.getTable({ databaseId, tableId: collectionData.$id });
274
- table = (byId as any).data || (byId as any).tables?.[0];
275
- if (table?.$id) {
276
- MessageFormatter.info(`Found existing table by ID: ${table.$id}`, { prefix: 'Tables' });
277
- }
278
- } catch {
279
- // Not found by ID; fall back to name lookup
280
- }
281
- }
282
-
283
- // 2) If not found by ID, try by name
284
- if (!table) {
285
- const list = await adapter.listTables({ databaseId, queries: [Query.equal('name', collectionData.name)] });
286
- const items: any[] = (list as any).tables || [];
287
- table = items[0];
288
- if (table?.$id) {
289
- // If local has $id that differs from remote, prefer remote (IDs are immutable)
290
- if (collectionData.$id && collectionData.$id !== table.$id) {
291
- MessageFormatter.warning(`Config $id '${collectionData.$id}' differs from existing table ID '${table.$id}'. Using existing table.`, { prefix: 'Tables' });
292
- }
293
- }
294
- }
295
-
296
- if (!table) {
297
- // Determine ID (prefer provided $id or re-use deleted one)
298
- let foundColl = deletedCollections?.find(
299
- (coll) => coll.collectionName.toLowerCase().trim().replace(" ", "") === collectionData.name.toLowerCase().trim().replace(" ", "")
300
- );
301
- if (collectionData.$id) tableId = collectionData.$id;
302
- else if (foundColl && !usedIds.has(foundColl.collectionId)) tableId = foundColl.collectionId;
303
- else tableId = ID.unique();
304
- usedIds.add(tableId);
305
-
306
- const res = await adapter.createTable({
307
- databaseId,
308
- id: tableId,
309
- name: collectionData.name,
310
- permissions,
311
- documentSecurity: !!collectionData.documentSecurity,
312
- enabled: collectionData.enabled !== false
313
- });
314
- table = (res as any).data || res;
315
- nameToIdMapping.set(collectionData.name, tableId);
316
- } else {
317
- tableId = table.$id;
318
- await adapter.updateTable({
319
- databaseId,
320
- id: tableId,
321
- name: collectionData.name,
322
- permissions,
323
- documentSecurity: !!collectionData.documentSecurity,
324
- enabled: collectionData.enabled !== false
325
- });
326
- // Cache the existing table ID
327
- nameToIdMapping.set(collectionData.name, tableId);
328
- }
329
-
330
- // Add small delay after table create/update
331
- await delay(250);
332
-
333
- // Create/Update attributes: non-relationship first using enhanced planning
334
- const nonRel = (attributes || []).filter((a: Attribute) => a.type !== 'relationship');
335
- if (nonRel.length > 0) {
336
- // Fetch existing columns once
337
- const tableInfo = await adapter.getTable({ databaseId, tableId });
338
- const existingCols: any[] = (tableInfo as any).data?.columns || (tableInfo as any).data?.attributes || [];
339
-
340
- // Plan with icons
341
- const plan = diffColumnsDetailed(nonRel as any, existingCols);
342
- const plus = plan.toCreate.map((a: any) => a.key);
343
- const plusminus = plan.toUpdate.map((u: any) => (u.attribute as any).key);
344
- const minus = plan.toRecreate.map((r: any) => (r.newAttribute as any).key);
345
- const skip = plan.unchanged;
346
-
347
- // Compute deletions (remote extras not present locally)
348
- const desiredKeysForDelete = new Set((attributes || []).map((a: any) => a.key));
349
- const extraRemoteKeys = (existingCols || [])
350
- .map((c: any) => c?.key)
351
- .filter((k: any): k is string => !!k && !desiredKeysForDelete.has(k));
352
-
353
- const parts: string[] = [];
354
- if (plus.length) parts.push(`➕ ${plus.length} (${plus.join(', ')})`);
355
- if (plusminus.length) parts.push(`🔧 ${plusminus.length} (${plusminus.join(', ')})`);
356
- if (minus.length) parts.push(`♻️ ${minus.length} (${minus.join(', ')})`);
357
- if (skip.length) parts.push(`⏭️ ${skip.length}`);
358
- parts.push(`🗑️ ${extraRemoteKeys.length}${extraRemoteKeys.length ? ` (${extraRemoteKeys.join(', ')})` : ''}`);
359
- MessageFormatter.info(`Plan ${parts.join(' | ') || 'no changes'}`, { prefix: 'Attributes' });
360
-
361
- // Execute
362
- const colResults = await executeColumnOperations(adapter, databaseId, tableId, plan);
363
-
364
- if (colResults.success.length > 0) {
365
- MessageFormatter.success(`Processed ${colResults.success.length} ops`, { prefix: 'Attributes' });
366
- }
367
- if (colResults.errors.length > 0) {
368
- MessageFormatter.error(`${colResults.errors.length} attribute operations failed:`, undefined, { prefix: 'Attributes' });
369
- for (const err of colResults.errors) {
370
- MessageFormatter.error(` ${err.column}: ${err.error}`, undefined, { prefix: 'Attributes' });
371
- }
372
- }
373
- MessageFormatter.info(
374
- `Summary → ➕ ${plan.toCreate.length} | 🔧 ${plan.toUpdate.length} | ♻️ ${plan.toRecreate.length} | ⏭️ ${plan.unchanged.length}`,
375
- { prefix: 'Attributes' }
376
- );
377
- }
378
-
379
- // Relationship attributes — resolve relatedCollection to ID, then diff and create/update with recreate support
380
- const relsAll = (attributes || []).filter((a: Attribute) => a.type === 'relationship') as any[];
381
- if (relsAll.length > 0) {
382
- const relsResolved: any[] = [];
383
- const relsDeferred: any[] = [];
384
-
385
- // Resolve related collections (names -> IDs) using cache or lookup.
386
- // If not resolvable yet (target table created later in the same push), queue for later.
387
- for (const attr of relsAll) {
388
- const relNameOrId = attr.relatedCollection as string | undefined;
389
- if (!relNameOrId) continue;
390
- let relId = nameToIdMapping.get(relNameOrId) || relNameOrId;
391
- let resolved = false;
392
- if (nameToIdMapping.has(relNameOrId)) {
393
- resolved = true;
394
- } else {
395
- // Try resolve by name
396
- try {
397
- const relList = await adapter.listTables({ databaseId, queries: [Query.equal('name', relNameOrId)] });
398
- const relItems: any[] = (relList as any).tables || [];
399
- if (relItems[0]?.$id) {
400
- relId = relItems[0].$id;
401
- nameToIdMapping.set(relNameOrId, relId);
402
- resolved = true;
403
- }
404
- } catch {}
405
-
406
- // If the relNameOrId looks like an ID but isn't resolved yet, attempt a direct get
407
- if (!resolved && relNameOrId && relNameOrId.length >= 10) {
408
- try {
409
- const probe = await adapter.getTable({ databaseId, tableId: relNameOrId });
410
- if ((probe as any).data?.$id) {
411
- nameToIdMapping.set(relNameOrId, relNameOrId);
412
- relId = relNameOrId;
413
- resolved = true;
414
- }
415
- } catch {}
416
- }
417
- }
418
-
419
- if (resolved && relId && typeof relId === 'string') {
420
- attr.relatedCollection = relId;
421
- relsResolved.push(attr);
422
- } else {
423
- // Defer until related table exists; queue a surgical operation
424
- enqueueOperation({
425
- type: 'attribute',
426
- collectionId: tableId,
427
- attribute: attr,
428
- dependencies: [relNameOrId]
429
- });
430
- relsDeferred.push(attr);
431
- }
432
- }
433
-
434
- // Compute a detailed plan for immediately resolvable relationships
435
- const tableInfo2 = await adapter.getTable({ databaseId, tableId });
436
- const existingCols2: any[] = (tableInfo2 as any).data?.columns || (tableInfo2 as any).data?.attributes || [];
437
- const relPlan = diffColumnsDetailed(relsResolved as any, existingCols2);
438
-
439
- // Relationship plan with icons (includes recreates)
440
- {
441
- const parts: string[] = [];
442
- if (relPlan.toCreate.length) parts.push(`➕ ${relPlan.toCreate.length} (${relPlan.toCreate.map((a:any)=>a.key).join(', ')})`);
443
- if (relPlan.toUpdate.length) parts.push(`🔧 ${relPlan.toUpdate.length} (${relPlan.toUpdate.map((u:any)=>u.attribute?.key ?? u.key).join(', ')})`);
444
- if (relPlan.toRecreate.length) parts.push(`♻️ ${relPlan.toRecreate.length} (${relPlan.toRecreate.map((r:any)=>r.newAttribute?.key ?? r?.key).join(', ')})`);
445
- if (relPlan.unchanged.length) parts.push(`⏭️ ${relPlan.unchanged.length}`);
446
- MessageFormatter.info(`Plan ${parts.join(' | ') || 'no changes'}`, { prefix: 'Relationships' });
447
- }
448
-
449
- // Execute plan using the same operation executor to properly handle deletes/recreates
450
- const relResults = await executeColumnOperations(adapter, databaseId, tableId, relPlan);
451
- if (relResults.success.length > 0) {
452
- const totalRelationships = relPlan.toCreate.length + relPlan.toUpdate.length + relPlan.toRecreate.length + relPlan.unchanged.length;
453
- const activeRelationships = relPlan.toCreate.length + relPlan.toUpdate.length + relPlan.toRecreate.length;
454
-
455
- if (relResults.success.length !== activeRelationships) {
456
- // Show both counts when they differ (usually due to recreations)
457
- MessageFormatter.success(`Processed ${relResults.success.length} operations for ${activeRelationships} relationship${activeRelationships === 1 ? '' : 's'}`, { prefix: 'Relationships' });
458
- } else {
459
- MessageFormatter.success(`Processed ${relResults.success.length} relationship${relResults.success.length === 1 ? '' : 's'}`, { prefix: 'Relationships' });
460
- }
461
- }
462
- if (relResults.errors.length > 0) {
463
- MessageFormatter.error(`${relResults.errors.length} relationship operations failed:`, undefined, { prefix: 'Relationships' });
464
- for (const err of relResults.errors) {
465
- MessageFormatter.error(` ${err.column}: ${err.error}`, undefined, { prefix: 'Relationships' });
466
- }
467
- }
468
-
469
- if (relsDeferred.length > 0) {
470
- MessageFormatter.info(`Deferred ${relsDeferred.length} relationship(s) until related tables become available`, { prefix: 'Relationships' });
471
- }
472
- }
473
-
474
- // Wait for all attributes to become available before creating indexes
475
- const allAttrKeys = [
476
- ...nonRel.map((a: any) => a.key),
477
- ...relsAll.filter((a: any) => a.relatedCollection).map((a: any) => a.key)
478
- ];
479
-
480
- if (allAttrKeys.length > 0) {
481
- for (const attrKey of allAttrKeys) {
482
- const maxWait = 60000; // 60 seconds
483
- const startTime = Date.now();
484
- let lastStatus = '';
485
-
486
- while (Date.now() - startTime < maxWait) {
487
- try {
488
- const tableData = await adapter.getTable({ databaseId, tableId });
489
- const attrs = (tableData as any).data?.columns || (tableData as any).data?.attributes || [];
490
- const attr = attrs.find((a: any) => a.key === attrKey);
491
-
492
- if (attr) {
493
- if (attr.status === 'available') {
494
- break; // Attribute is ready
495
- }
496
- if (attr.status === 'failed' || attr.status === 'stuck') {
497
- throw new Error(`Attribute ${attrKey} failed to create: ${attr.error || 'unknown error'}`);
498
- }
499
- // Still processing, continue waiting
500
- lastStatus = attr.status;
501
- }
502
-
503
- await delay(2000); // Check every 2 seconds
504
- } catch (e) {
505
- // If we can't check status, assume it's processing and continue
506
- await delay(2000);
507
- }
508
- }
509
-
510
- // Timeout check
511
- if (Date.now() - startTime >= maxWait) {
512
- MessageFormatter.warning(
513
- `Attribute ${attrKey} did not become available within ${maxWait / 1000}s (last status: ${lastStatus}). Proceeding anyway.`,
514
- { prefix: 'Attributes' }
515
- );
516
- }
517
- }
518
- }
519
-
520
- // Prefer local config indexes, but fall back to collection's own indexes if no local config exists (TablesDB path)
521
- const localTableConfig = config.collections?.find(
522
- c => c.name === collectionData.name || c.$id === collectionData.$id
523
- );
524
- const idxs = (localTableConfig?.indexes ?? indexes ?? []) as any[];
525
- // Compare with existing indexes and create/update accordingly with status checks
526
- try {
527
- const existingIdxRes = await adapter.listIndexes({ databaseId, tableId });
528
- const existingIdx: any[] = (existingIdxRes as any).data || (existingIdxRes as any).indexes || [];
529
- MessageFormatter.debug(`Existing index keys: ${existingIdx.map((i:any)=>i.key).join(', ')}`, undefined, { prefix: 'Indexes' });
530
- // Show a concise plan with icons before executing
531
- const idxPlanPlus: string[] = [];
532
- const idxPlanPlusMinus: string[] = [];
533
- const idxPlanSkip: string[] = [];
534
- for (const idx of idxs) {
535
- const found = existingIdx.find((i: any) => i.key === idx.key);
536
- if (found) {
537
- if (isIndexEqualToIndex(found, idx)) idxPlanSkip.push(idx.key);
538
- else idxPlanPlusMinus.push(idx.key);
539
- } else idxPlanPlus.push(idx.key);
540
- }
541
- const planParts: string[] = [];
542
- if (idxPlanPlus.length) planParts.push(`➕ ${idxPlanPlus.length} (${idxPlanPlus.join(', ')})`);
543
- if (idxPlanPlusMinus.length) planParts.push(`🔧 ${idxPlanPlusMinus.length} (${idxPlanPlusMinus.join(', ')})`);
544
- if (idxPlanSkip.length) planParts.push(`⏭️ ${idxPlanSkip.length}`);
545
- MessageFormatter.info(`Plan → ${planParts.join(' | ') || 'no changes'}`, { prefix: 'Indexes' });
546
- const created: string[] = [];
547
- const updated: string[] = [];
548
- const skipped: string[] = [];
549
- for (const idx of idxs) {
550
- const found = existingIdx.find((i: any) => i.key === idx.key);
551
- if (found) {
552
- if (isIndexEqualToIndex(found, idx)) {
553
- MessageFormatter.info(`Index ${idx.key} unchanged`, { prefix: 'Indexes' });
554
- skipped.push(idx.key);
555
- } else {
556
- try { await adapter.deleteIndex({ databaseId, tableId, key: idx.key }); await delay(100); } catch {}
557
- try {
558
- await adapter.createIndex({ databaseId, tableId, key: idx.key, type: idx.type, attributes: idx.attributes, orders: idx.orders || [] });
559
- updated.push(idx.key);
560
- } catch (e: any) {
561
- const msg = (e?.message || '').toString().toLowerCase();
562
- if (msg.includes('already exists')) {
563
- MessageFormatter.info(`Index ${idx.key} already exists after delete attempt, skipping`, { prefix: 'Indexes' });
564
- skipped.push(idx.key);
565
- } else {
566
- throw e;
567
- }
568
- }
569
- }
570
- } else {
571
- try {
572
- await adapter.createIndex({ databaseId, tableId, key: idx.key, type: idx.type, attributes: idx.attributes, orders: idx.orders || [] });
573
- created.push(idx.key);
574
- } catch (e: any) {
575
- const msg = (e?.message || '').toString().toLowerCase();
576
- if (msg.includes('already exists')) {
577
- MessageFormatter.info(`Index ${idx.key} already exists (create), skipping`, { prefix: 'Indexes' });
578
- skipped.push(idx.key);
579
- } else {
580
- throw e;
581
- }
582
- }
583
- }
584
- // Wait for index availability
585
- const maxWait = 60000; const start = Date.now(); let lastStatus = '';
586
- while (Date.now() - start < maxWait) {
587
- try {
588
- const li = await adapter.listIndexes({ databaseId, tableId });
589
- const list: any[] = (li as any).data || (li as any).indexes || [];
590
- const cur = list.find((i: any) => i.key === idx.key);
591
- if (cur) {
592
- if (cur.status === 'available') break;
593
- if (cur.status === 'failed' || cur.status === 'stuck') { throw new Error(cur.error || `Index ${idx.key} failed`); }
594
- lastStatus = cur.status;
595
- }
596
- await delay(2000);
597
- } catch { await delay(2000); }
598
- }
599
- await delay(150);
600
- }
601
- MessageFormatter.info(`Summary → ➕ ${created.length} | 🔧 ${updated.length} | ⏭️ ${skipped.length}` , { prefix: 'Indexes' });
602
- } catch (e) {
603
- MessageFormatter.error(`Failed to list/create indexes`, e instanceof Error ? e : new Error(String(e)), { prefix: 'Indexes' });
604
- }
605
-
606
- // Deletions for indexes: remove remote indexes not declared in YAML/config
607
- try {
608
- const desiredIndexKeys = new Set((indexes || []).map((i: any) => i.key));
609
- const idxRes = await adapter.listIndexes({ databaseId, tableId });
610
- const existingIdx: any[] = (idxRes as any).data || (idxRes as any).indexes || [];
611
- const extraIdx = existingIdx
612
- .filter((i: any) => i?.key && !desiredIndexKeys.has(i.key))
613
- .map((i: any) => i.key as string);
614
- if (extraIdx.length > 0) {
615
- MessageFormatter.info(`Plan → 🗑️ ${extraIdx.length} indexes (${extraIdx.join(', ')})`, { prefix: 'Indexes' });
616
- const deleted: string[] = [];
617
- const errors: Array<{ key: string; error: string }> = [];
618
- for (const key of extraIdx) {
619
- try {
620
- await adapter.deleteIndex({ databaseId, tableId, key });
621
- // Optionally wait for index to disappear
622
- const start = Date.now();
623
- const maxWait = 30000;
624
- while (Date.now() - start < maxWait) {
625
- try {
626
- const li = await adapter.listIndexes({ databaseId, tableId });
627
- const list: any[] = (li as any).data || (li as any).indexes || [];
628
- if (!list.find((ix: any) => ix.key === key)) break;
629
- } catch {}
630
- await delay(1000);
631
- }
632
- deleted.push(key);
633
- } catch (e: any) {
634
- errors.push({ key, error: e?.message || String(e) });
635
- }
636
- }
637
- if (deleted.length) {
638
- MessageFormatter.success(`Deleted ${deleted.length} indexes: ${deleted.join(', ')}`, { prefix: 'Indexes' });
639
- }
640
- if (errors.length) {
641
- MessageFormatter.error(`${errors.length} index deletions failed`, undefined, { prefix: 'Indexes' });
642
- errors.forEach(er => MessageFormatter.error(` ${er.key}: ${er.error}`, undefined, { prefix: 'Indexes' }));
643
- }
644
- } else {
645
- MessageFormatter.info(`Plan → 🗑️ 0 indexes`, { prefix: 'Indexes' });
646
- }
647
- } catch (e) {
648
- MessageFormatter.warning(`Could not evaluate index deletions: ${(e as Error)?.message || e}`, { prefix: 'Indexes' });
649
- }
650
-
651
- // Deletions: remove columns/attributes that are present remotely but not in desired config
652
- try {
653
- const desiredKeys = new Set((attributes || []).map((a: any) => a.key));
654
- const tableInfo3 = await adapter.getTable({ databaseId, tableId });
655
- const existingCols3: any[] = (tableInfo3 as any).data?.columns || (tableInfo3 as any).data?.attributes || [];
656
- const toDelete = existingCols3
657
- .filter((col: any) => col?.key && !desiredKeys.has(col.key))
658
- .map((col: any) => col.key as string);
659
-
660
- if (toDelete.length > 0) {
661
- MessageFormatter.info(`Plan → 🗑️ ${toDelete.length} (${toDelete.join(', ')})`, { prefix: 'Attributes' });
662
- const deleted: string[] = [];
663
- const errors: Array<{ key: string; error: string }> = [];
664
- for (const key of toDelete) {
665
- try {
666
- // Drop any indexes that reference this attribute to avoid server errors
667
- try {
668
- const idxRes = await adapter.listIndexes({ databaseId, tableId });
669
- const ilist: any[] = (idxRes as any).data || (idxRes as any).indexes || [];
670
- for (const idx of ilist) {
671
- const attrs: string[] = Array.isArray(idx.attributes) ? idx.attributes : [];
672
- if (attrs.includes(key)) {
673
- MessageFormatter.info(`🗑️ Deleting index '${idx.key}' referencing '${key}'`, { prefix: 'Indexes' });
674
- await adapter.deleteIndex({ databaseId, tableId, key: idx.key });
675
- await delay(500);
676
- }
677
- }
678
- } catch {}
679
-
680
- await adapter.deleteAttribute({ databaseId, tableId, key });
681
- // Wait briefly for deletion to settle
682
- const start = Date.now();
683
- const maxWaitMs = 60000;
684
- while (Date.now() - start < maxWaitMs) {
685
- try {
686
- const tinfo = await adapter.getTable({ databaseId, tableId });
687
- const cols = (tinfo as any).data?.columns || (tinfo as any).data?.attributes || [];
688
- const found = cols.find((c: any) => c.key === key);
689
- if (!found) break;
690
- if (found.status && found.status !== 'deleting') break;
691
- } catch {}
692
- await delay(1000);
693
- }
694
- deleted.push(key);
695
- } catch (e: any) {
696
- errors.push({ key, error: e?.message || String(e) });
697
- }
698
- }
699
- if (deleted.length) {
700
- MessageFormatter.success(`Deleted ${deleted.length} attributes: ${deleted.join(', ')}`, { prefix: 'Attributes' });
701
- }
702
- if (errors.length) {
703
- MessageFormatter.error(`${errors.length} deletions failed`, undefined, { prefix: 'Attributes' });
704
- errors.forEach(er => MessageFormatter.error(` ${er.key}: ${er.error}`, undefined, { prefix: 'Attributes' }));
705
- }
706
- } else {
707
- MessageFormatter.info(`Plan → 🗑️ 0`, { prefix: 'Attributes' });
708
- }
709
- } catch (e) {
710
- MessageFormatter.warning(`Could not evaluate deletions: ${(e as Error)?.message || e}`, { prefix: 'Attributes' });
711
- }
712
-
713
- // Mark this table as fully processed for this database to prevent re-processing in the same DB only
714
- markCollectionProcessed(tableId, collectionData.name, databaseId);
715
- }
716
-
717
- // Process queued relationships once mapping likely populated
718
- if (relQueue.length > 0) {
719
- MessageFormatter.info(`🔧 Processing ${relQueue.length} queued relationship attributes for tables`, { prefix: "Tables" });
720
- for (const { tableId, attr } of relQueue) {
721
- const relNameOrId = (attr as any).relatedCollection as string | undefined;
722
- if (!relNameOrId) continue;
723
- const relId = nameToIdMapping.get(relNameOrId) || relNameOrId;
724
- if (relId) {
725
- (attr as any).relatedCollection = relId;
726
- try {
727
- await adapter.createAttribute({
728
- databaseId,
729
- tableId,
730
- key: (attr as any).key,
731
- type: (attr as any).type,
732
- size: (attr as any).size,
733
- required: !!(attr as any).required,
734
- default: (attr as any).xdefault,
735
- array: !!(attr as any).array,
736
- min: (attr as any).min,
737
- max: (attr as any).max,
738
- elements: (attr as any).elements,
739
- relatedCollection: relId,
740
- relationType: (attr as any).relationType,
741
- twoWay: (attr as any).twoWay,
742
- twoWayKey: (attr as any).twoWayKey,
743
- onDelete: (attr as any).onDelete,
744
- side: (attr as any).side
745
- });
746
- await delay(150);
747
- MessageFormatter.info(`✅ Successfully processed queued relationship: ${attr.key}`, { prefix: "Tables" });
748
- } catch (e) {
749
- MessageFormatter.error(`Failed queued relationship ${attr.key}`, e instanceof Error ? e : new Error(String(e)), { prefix: 'Attributes' });
750
- }
751
- } else {
752
- MessageFormatter.warning(`Could not resolve relationship ${attr.key} -> ${relNameOrId}`, { prefix: "Tables" });
753
- }
754
- }
755
- }
756
-
757
- // Process any remaining queued operations to complete relationship sync
758
- try {
759
- MessageFormatter.info(`🔄 Processing final operation queue for database ${databaseId}`, { prefix: "Tables" });
760
- await processQueue(adapter, databaseId);
761
- MessageFormatter.info(`✅ Operation queue processing completed`, { prefix: "Tables" });
762
- } catch (error) {
763
- MessageFormatter.error(`Failed to process operation queue`, error instanceof Error ? error : new Error(String(error)), { prefix: 'Tables' });
764
- }
765
- };
766
-
767
- export const generateMockData = async (
768
- database: Databases,
769
- databaseId: string,
770
- configCollections: any[]
771
- ): Promise<void> => {
772
- for (const { collection, mockFunction } of configCollections) {
773
- if (mockFunction) {
774
- MessageFormatter.progress(`Generating mock data for collection: ${collection.name}`, { prefix: "Mock Data" });
775
- const mockData = mockFunction();
776
- for (const data of mockData) {
777
- await database.createDocument(
778
- databaseId,
779
- collection.$id,
780
- ID.unique(),
781
- data
782
- );
783
- }
784
- }
785
- }
786
- };
787
-
788
- export const fetchAllCollections = async (
789
- dbId: string,
790
- database: Databases
791
- ): Promise<Models.Collection[]> => {
792
- MessageFormatter.progress(`Fetching all collections for database ID: ${dbId}`, { prefix: "Collections" });
793
- let collections: Models.Collection[] = [];
794
- let moreCollections = true;
795
- let lastCollectionId: string | undefined;
796
-
797
- while (moreCollections) {
798
- const queries = [Query.limit(500)];
799
- if (lastCollectionId) {
800
- queries.push(Query.cursorAfter(lastCollectionId));
801
- }
802
- const response = await tryAwaitWithRetry(
803
- async () => await database.listCollections(dbId, queries)
804
- );
805
- collections = collections.concat(response.collections);
806
- moreCollections = response.collections.length === 500;
807
- if (moreCollections) {
808
- lastCollectionId =
809
- response.collections[response.collections.length - 1].$id;
810
- }
811
- }
812
-
813
- MessageFormatter.success(`Fetched a total of ${collections.length} collections`, { prefix: "Collections" });
814
- return collections;
815
- };
1
+ import {
2
+ Databases,
3
+ ID,
4
+ Permission,
5
+ Query,
6
+ type Models,
7
+ } from "node-appwrite";
8
+ import type { AppwriteConfig, CollectionCreate, Indexes, Attribute } from "appwrite-utils";
9
+ import type { DatabaseAdapter } from "appwrite-utils-helpers";
10
+ import { getAdapterFromConfig } from "appwrite-utils-helpers";
11
+ import {
12
+ nameToIdMapping,
13
+ processQueue,
14
+ queuedOperations,
15
+ clearProcessingState,
16
+ isCollectionProcessed,
17
+ markCollectionProcessed,
18
+ enqueueOperation
19
+ } from "../shared/operationQueue.js";
20
+ import { logger, SchemaGenerator } from "appwrite-utils-helpers";
21
+ // Legacy attribute/index helpers removed in favor of unified adapter path
22
+ import {
23
+ isNull,
24
+ isUndefined,
25
+ isNil,
26
+ isPlainObject,
27
+ isString,
28
+ } from "es-toolkit";
29
+ import { delay, tryAwaitWithRetry } from "appwrite-utils-helpers";
30
+ import { MessageFormatter, mapToCreateAttributeParams, mapToUpdateAttributeParams } from "appwrite-utils-helpers";
31
+ import { isLegacyDatabases } from "appwrite-utils-helpers";
32
+ import { diffTableColumns, isIndexEqualToIndex, diffColumnsDetailed, executeColumnOperations } from "./tableOperations.js";
33
+ import { createOrUpdateIndexesViaAdapter, deleteObsoleteIndexesViaAdapter } from "../tables/indexManager.js";
34
+
35
+ // Re-export wipe operations
36
+ export {
37
+ wipeDatabase,
38
+ wipeCollection,
39
+ wipeAllTables,
40
+ wipeTableRows,
41
+ } from "./wipeOperations.js";
42
+
43
+ // Re-export transfer operations
44
+ export {
45
+ transferDocumentsBetweenDbsLocalToLocal,
46
+ transferDocumentsBetweenDbsLocalToRemote,
47
+ } from "./transferOperations.js";
48
+
49
+ export const documentExists = async (
50
+ db: Databases | DatabaseAdapter,
51
+ dbId: string,
52
+ targetCollectionId: string,
53
+ toCreateObject: any
54
+ ): Promise<Models.Document | null> => {
55
+ const collection = await (isLegacyDatabases(db) ?
56
+ db.getCollection(dbId, targetCollectionId) :
57
+ db.getTable({ databaseId: dbId, tableId: targetCollectionId }));
58
+ const attributes = (collection as any).attributes as any[];
59
+ let arrayTypeAttributes = attributes
60
+ .filter((attribute: any) => attribute.array === true)
61
+ .map((attribute: any) => attribute.key);
62
+
63
+ const isJsonString = (str: string) => {
64
+ try {
65
+ const json = JSON.parse(str);
66
+ return typeof json === "object" && json !== null;
67
+ } catch (e) {
68
+ return false;
69
+ }
70
+ };
71
+
72
+ // Convert object to entries and filter
73
+ const validEntries = Object.entries(toCreateObject).filter(
74
+ ([key, value]) =>
75
+ !arrayTypeAttributes.includes(key) &&
76
+ !key.startsWith("$") &&
77
+ !isNull(value) &&
78
+ !isUndefined(value) &&
79
+ !isNil(value) &&
80
+ !isPlainObject(value) &&
81
+ !Array.isArray(value) &&
82
+ !(isString(value) && isJsonString(value)) &&
83
+ (isString(value) ? value.length < 4096 && value.length > 0 : true)
84
+ );
85
+
86
+ // Map and filter valid entries
87
+ const validMappedEntries = validEntries
88
+ .map(([key, value]) => [
89
+ key,
90
+ isString(value) || typeof value === "number" || typeof value === "boolean"
91
+ ? value
92
+ : null,
93
+ ])
94
+ .filter(([key, value]) => !isNull(value) && isString(key))
95
+ .slice(0, 25);
96
+
97
+ // Convert to Query parameters
98
+ const validQueryParams = validMappedEntries.map(([key, value]) =>
99
+ Query.equal(key as string, value as any)
100
+ );
101
+
102
+ // Execute the query with the validated and prepared parameters
103
+ const result = await (isLegacyDatabases(db) ?
104
+ db.listDocuments(dbId, targetCollectionId, validQueryParams) :
105
+ db.listRows({ databaseId: dbId, tableId: targetCollectionId, queries: validQueryParams }));
106
+
107
+ const items = isLegacyDatabases(db) ? result.documents : ((result as any).rows || result.documents);
108
+ return items?.[0] || null;
109
+ };
110
+
111
+ export const checkForCollection = async (
112
+ db: Databases | DatabaseAdapter,
113
+ dbId: string,
114
+ collection: Partial<CollectionCreate>
115
+ ): Promise<Models.Collection | null> => {
116
+ try {
117
+ const isLegacy = isLegacyDatabases(db);
118
+ const entityType = isLegacy ? "Collection" : "Table";
119
+ MessageFormatter.progress(`Checking for ${entityType.toLowerCase()} with name: ${collection.name}`, { prefix: entityType + "s" });
120
+ const response = await tryAwaitWithRetry(
121
+ async () => isLegacy ?
122
+ await db.listCollections(dbId, [Query.equal("name", collection.name!)]) :
123
+ await db.listTables({ databaseId: dbId, queries: [Query.equal("name", collection.name!)] })
124
+ );
125
+ const items = isLegacy ? response.collections : ((response as any).tables || response.collections);
126
+ if (items && items.length > 0) {
127
+ MessageFormatter.info(`${entityType} found: ${items[0].$id}`, { prefix: entityType + "s" });
128
+ // Return remote collection for update operations (don't merge local config over it)
129
+ return items[0] as Models.Collection;
130
+ } else {
131
+ MessageFormatter.info(`No ${entityType.toLowerCase()} found with name: ${collection.name}`, { prefix: entityType + "s" });
132
+ return null;
133
+ }
134
+ } catch (error) {
135
+ const errorMessage = error instanceof Error ? error.message : String(error);
136
+ MessageFormatter.error(`Error checking for collection: ${collection.name}`, error instanceof Error ? error : new Error(String(error)), { prefix: "Collections" });
137
+ logger.error('Collection check failed', {
138
+ collectionName: collection.name,
139
+ dbId,
140
+ error: errorMessage,
141
+ operation: 'checkForCollection'
142
+ });
143
+ return null;
144
+ }
145
+ };
146
+
147
+ // Helper function to fetch and cache collection by name
148
+ export const fetchAndCacheCollectionByName = async (
149
+ db: Databases | DatabaseAdapter,
150
+ dbId: string,
151
+ collectionName: string
152
+ ): Promise<Models.Collection | undefined> => {
153
+ const isLegacy = isLegacyDatabases(db);
154
+ const entityType = isLegacy ? "Collection" : "Table";
155
+ if (nameToIdMapping.has(collectionName)) {
156
+ const collectionId = nameToIdMapping.get(collectionName);
157
+ MessageFormatter.debug(`${entityType} found in cache: ${collectionId}`, undefined, { prefix: entityType + "s" });
158
+ return await tryAwaitWithRetry(
159
+ async () => isLegacy ?
160
+ await db.getCollection(dbId, collectionId!) :
161
+ await db.getTable({ databaseId: dbId, tableId: collectionId! })
162
+ ) as Models.Collection;
163
+ } else {
164
+ MessageFormatter.progress(`Fetching ${entityType.toLowerCase()} by name: ${collectionName}`, { prefix: entityType + "s" });
165
+ const collectionsPulled = await tryAwaitWithRetry(
166
+ async () => isLegacy ?
167
+ await db.listCollections(dbId, [Query.equal("name", collectionName)]) :
168
+ await db.listTables({ databaseId: dbId, queries: [Query.equal("name", collectionName)] })
169
+ );
170
+ const items = isLegacy ? collectionsPulled.collections : ((collectionsPulled as any).tables || collectionsPulled.collections);
171
+ if ((collectionsPulled.total || items?.length) > 0) {
172
+ const collection = items[0];
173
+ MessageFormatter.info(`${entityType} found: ${collection.$id}`, { prefix: entityType + "s" });
174
+ nameToIdMapping.set(collectionName, collection.$id);
175
+ return collection;
176
+ } else {
177
+ MessageFormatter.warning(`${entityType} not found by name: ${collectionName}`, { prefix: entityType + "s" });
178
+ return undefined;
179
+ }
180
+ }
181
+ };
182
+
183
+ export const generateSchemas = async (
184
+ config: AppwriteConfig,
185
+ appwriteFolderPath: string
186
+ ): Promise<void> => {
187
+ const schemaGenerator = new SchemaGenerator(config, appwriteFolderPath);
188
+ await schemaGenerator.generateSchemas();
189
+ };
190
+
191
+ export const createOrUpdateCollections = async (
192
+ database: Databases,
193
+ databaseId: string,
194
+ config: AppwriteConfig,
195
+ deletedCollections?: { collectionId: string; collectionName: string }[],
196
+ selectedCollections: Models.Collection[] = []
197
+ ): Promise<void> => {
198
+ // Clear processing state at the start of a new operation
199
+ clearProcessingState();
200
+
201
+ // Always use adapter path (LegacyAdapter translates when pre-1.8)
202
+ const { adapter } = await getAdapterFromConfig(config);
203
+ await createOrUpdateCollectionsViaAdapter(
204
+ adapter,
205
+ databaseId,
206
+ config,
207
+ deletedCollections,
208
+ selectedCollections
209
+ );
210
+ };
211
+
212
+ // New: Adapter-based implementation for TablesDB with state management
213
+ export const createOrUpdateCollectionsViaAdapter = async (
214
+ adapter: DatabaseAdapter,
215
+ databaseId: string,
216
+ config: AppwriteConfig,
217
+ deletedCollections?: { collectionId: string; collectionName: string }[],
218
+ selectedCollections: Models.Collection[] = []
219
+ ): Promise<void> => {
220
+ const collectionsToProcess =
221
+ selectedCollections.length > 0 ? selectedCollections : (config.collections || []);
222
+ if (!collectionsToProcess || collectionsToProcess.length === 0) return;
223
+
224
+ const usedIds = new Set<string>();
225
+ MessageFormatter.info(`Processing ${collectionsToProcess.length} tables via adapter with intelligent state management`, { prefix: "Tables" });
226
+
227
+ // Helpers for attribute operations through adapter
228
+ const createAttr = async (tableId: string, attr: Attribute) => {
229
+ const params = mapToCreateAttributeParams(attr as any, { databaseId, tableId });
230
+ await adapter.createAttribute(params);
231
+ await delay(150);
232
+ };
233
+ const updateAttr = async (tableId: string, attr: Attribute) => {
234
+ const params = mapToUpdateAttributeParams(attr as any, { databaseId, tableId }) as any;
235
+ await adapter.updateAttribute(params);
236
+ await delay(150);
237
+ };
238
+
239
+ // Local queue for unresolved relationships
240
+ const relQueue: { tableId: string; attr: Attribute }[] = [];
241
+
242
+ for (const collection of collectionsToProcess) {
243
+ const { attributes, indexes, ...collectionData } = collection as any;
244
+
245
+ // Check if this table has already been processed in this session (per database)
246
+ if (collectionData.$id && isCollectionProcessed(collectionData.$id, databaseId)) {
247
+ MessageFormatter.info(`Table '${collectionData.name}' already processed, skipping`, { prefix: "Tables" });
248
+ continue;
249
+ }
250
+
251
+ // Prepare permissions as strings (reuse Permission helper)
252
+ const permissions: string[] = [];
253
+ if (collection.$permissions && collection.$permissions.length > 0) {
254
+ for (const p of collection.$permissions as any[]) {
255
+ if (typeof p === 'string') permissions.push(p);
256
+ else {
257
+ switch (p.permission) {
258
+ case 'read': permissions.push(Permission.read(p.target)); break;
259
+ case 'create': permissions.push(Permission.create(p.target)); break;
260
+ case 'update': permissions.push(Permission.update(p.target)); break;
261
+ case 'delete': permissions.push(Permission.delete(p.target)); break;
262
+ case 'write': permissions.push(Permission.write(p.target)); break;
263
+ default: break;
264
+ }
265
+ }
266
+ }
267
+ }
268
+
269
+ // Find existing table — prefer lookup by ID (if provided), then by name
270
+ let table: any | undefined;
271
+ let tableId: string;
272
+
273
+ // 1) Try by explicit $id first (handles rename scenarios)
274
+ if (collectionData.$id) {
275
+ try {
276
+ const byId = await adapter.getTable({ databaseId, tableId: collectionData.$id });
277
+ table = (byId as any).data || (byId as any).tables?.[0];
278
+ if (table?.$id) {
279
+ MessageFormatter.info(`Found existing table by ID: ${table.$id}`, { prefix: 'Tables' });
280
+ }
281
+ } catch {
282
+ // Not found by ID; fall back to name lookup
283
+ }
284
+ }
285
+
286
+ // 2) If not found by ID, try by name
287
+ if (!table) {
288
+ const list = await adapter.listTables({ databaseId, queries: [Query.equal('name', collectionData.name)] });
289
+ const items: any[] = (list as any).tables || [];
290
+ table = items[0];
291
+ if (table?.$id) {
292
+ // If local has $id that differs from remote, prefer remote (IDs are immutable)
293
+ if (collectionData.$id && collectionData.$id !== table.$id) {
294
+ MessageFormatter.warning(`Config $id '${collectionData.$id}' differs from existing table ID '${table.$id}'. Using existing table.`, { prefix: 'Tables' });
295
+ }
296
+ }
297
+ }
298
+
299
+ if (!table) {
300
+ // Determine ID (prefer provided $id or re-use deleted one)
301
+ let foundColl = deletedCollections?.find(
302
+ (coll) => coll.collectionName.toLowerCase().trim().replace(" ", "") === collectionData.name.toLowerCase().trim().replace(" ", "")
303
+ );
304
+ if (collectionData.$id) tableId = collectionData.$id;
305
+ else if (foundColl && !usedIds.has(foundColl.collectionId)) tableId = foundColl.collectionId;
306
+ else tableId = ID.unique();
307
+ usedIds.add(tableId);
308
+
309
+ const res = await adapter.createTable({
310
+ databaseId,
311
+ id: tableId,
312
+ name: collectionData.name,
313
+ permissions,
314
+ documentSecurity: !!collectionData.documentSecurity,
315
+ enabled: collectionData.enabled !== false
316
+ });
317
+ table = (res as any).data || res;
318
+ nameToIdMapping.set(collectionData.name, tableId);
319
+ } else {
320
+ tableId = table.$id;
321
+ await adapter.updateTable({
322
+ databaseId,
323
+ id: tableId,
324
+ name: collectionData.name,
325
+ permissions,
326
+ documentSecurity: !!collectionData.documentSecurity,
327
+ enabled: collectionData.enabled !== false
328
+ });
329
+ // Cache the existing table ID
330
+ nameToIdMapping.set(collectionData.name, tableId);
331
+ }
332
+
333
+ // Add small delay after table create/update
334
+ await delay(250);
335
+
336
+ // Create/Update attributes: non-relationship first using enhanced planning
337
+ const nonRel = (attributes || []).filter((a: Attribute) => a.type !== 'relationship');
338
+ if (nonRel.length > 0) {
339
+ // Fetch existing columns once
340
+ const tableInfo = await adapter.getTable({ databaseId, tableId });
341
+ const existingCols: any[] = (tableInfo as any).data?.columns || (tableInfo as any).data?.attributes || [];
342
+
343
+ // Plan with icons
344
+ const plan = diffColumnsDetailed(nonRel as any, existingCols);
345
+ const plus = plan.toCreate.map((a: any) => a.key);
346
+ const plusminus = plan.toUpdate.map((u: any) => (u.attribute as any).key);
347
+ const minus = plan.toRecreate.map((r: any) => (r.newAttribute as any).key);
348
+ const skip = plan.unchanged;
349
+
350
+ // Compute deletions (remote extras not present locally)
351
+ const desiredKeysForDelete = new Set((attributes || []).map((a: any) => a.key));
352
+ const extraRemoteKeys = (existingCols || [])
353
+ .map((c: any) => c?.key)
354
+ .filter((k: any): k is string => !!k && !desiredKeysForDelete.has(k));
355
+
356
+ const parts: string[] = [];
357
+ if (plus.length) parts.push(`➕ ${plus.length} (${plus.join(', ')})`);
358
+ if (plusminus.length) parts.push(`🔧 ${plusminus.length} (${plusminus.join(', ')})`);
359
+ if (minus.length) parts.push(`♻️ ${minus.length} (${minus.join(', ')})`);
360
+ if (skip.length) parts.push(`⏭️ ${skip.length}`);
361
+ parts.push(`🗑️ ${extraRemoteKeys.length}${extraRemoteKeys.length ? ` (${extraRemoteKeys.join(', ')})` : ''}`);
362
+ MessageFormatter.info(`Plan ${parts.join(' | ') || 'no changes'}`, { prefix: 'Attributes' });
363
+
364
+ // Execute
365
+ const colResults = await executeColumnOperations(adapter, databaseId, tableId, plan);
366
+
367
+ if (colResults.success.length > 0) {
368
+ MessageFormatter.success(`Processed ${colResults.success.length} ops`, { prefix: 'Attributes' });
369
+ }
370
+ if (colResults.errors.length > 0) {
371
+ MessageFormatter.error(`${colResults.errors.length} attribute operations failed:`, undefined, { prefix: 'Attributes' });
372
+ for (const err of colResults.errors) {
373
+ MessageFormatter.error(` ${err.column}: ${err.error}`, undefined, { prefix: 'Attributes' });
374
+ }
375
+ }
376
+ MessageFormatter.info(
377
+ `Summary → ➕ ${plan.toCreate.length} | 🔧 ${plan.toUpdate.length} | ♻️ ${plan.toRecreate.length} | ⏭️ ${plan.unchanged.length}`,
378
+ { prefix: 'Attributes' }
379
+ );
380
+ }
381
+
382
+ // Relationship attributes resolve relatedCollection to ID, then diff and create/update with recreate support
383
+ const relsAll = (attributes || []).filter((a: Attribute) => a.type === 'relationship') as any[];
384
+ if (relsAll.length > 0) {
385
+ const relsResolved: any[] = [];
386
+ const relsDeferred: any[] = [];
387
+
388
+ // Resolve related collections (names -> IDs) using cache or lookup.
389
+ // If not resolvable yet (target table created later in the same push), queue for later.
390
+ for (const attr of relsAll) {
391
+ const relNameOrId = attr.relatedCollection as string | undefined;
392
+ if (!relNameOrId) continue;
393
+ let relId = nameToIdMapping.get(relNameOrId) || relNameOrId;
394
+ let resolved = false;
395
+ if (nameToIdMapping.has(relNameOrId)) {
396
+ resolved = true;
397
+ } else {
398
+ // Try resolve by name
399
+ try {
400
+ const relList = await adapter.listTables({ databaseId, queries: [Query.equal('name', relNameOrId)] });
401
+ const relItems: any[] = (relList as any).tables || [];
402
+ if (relItems[0]?.$id) {
403
+ relId = relItems[0].$id;
404
+ nameToIdMapping.set(relNameOrId, relId);
405
+ resolved = true;
406
+ }
407
+ } catch {}
408
+
409
+ // If the relNameOrId looks like an ID but isn't resolved yet, attempt a direct get
410
+ if (!resolved && relNameOrId && relNameOrId.length >= 10) {
411
+ try {
412
+ const probe = await adapter.getTable({ databaseId, tableId: relNameOrId });
413
+ if ((probe as any).data?.$id) {
414
+ nameToIdMapping.set(relNameOrId, relNameOrId);
415
+ relId = relNameOrId;
416
+ resolved = true;
417
+ }
418
+ } catch {}
419
+ }
420
+ }
421
+
422
+ if (resolved && relId && typeof relId === 'string') {
423
+ attr.relatedCollection = relId;
424
+ relsResolved.push(attr);
425
+ } else {
426
+ // Defer until related table exists; queue a surgical operation
427
+ enqueueOperation({
428
+ type: 'attribute',
429
+ collectionId: tableId,
430
+ attribute: attr,
431
+ dependencies: [relNameOrId]
432
+ });
433
+ relsDeferred.push(attr);
434
+ }
435
+ }
436
+
437
+ // Compute a detailed plan for immediately resolvable relationships
438
+ const tableInfo2 = await adapter.getTable({ databaseId, tableId });
439
+ const existingCols2: any[] = (tableInfo2 as any).data?.columns || (tableInfo2 as any).data?.attributes || [];
440
+ const relPlan = diffColumnsDetailed(relsResolved as any, existingCols2);
441
+
442
+ // Relationship plan with icons (includes recreates)
443
+ {
444
+ const parts: string[] = [];
445
+ if (relPlan.toCreate.length) parts.push(`➕ ${relPlan.toCreate.length} (${relPlan.toCreate.map((a:any)=>a.key).join(', ')})`);
446
+ if (relPlan.toUpdate.length) parts.push(`🔧 ${relPlan.toUpdate.length} (${relPlan.toUpdate.map((u:any)=>u.attribute?.key ?? u.key).join(', ')})`);
447
+ if (relPlan.toRecreate.length) parts.push(`♻️ ${relPlan.toRecreate.length} (${relPlan.toRecreate.map((r:any)=>r.newAttribute?.key ?? r?.key).join(', ')})`);
448
+ if (relPlan.unchanged.length) parts.push(`⏭️ ${relPlan.unchanged.length}`);
449
+ MessageFormatter.info(`Plan ${parts.join(' | ') || 'no changes'}`, { prefix: 'Relationships' });
450
+ }
451
+
452
+ // Execute plan using the same operation executor to properly handle deletes/recreates
453
+ const relResults = await executeColumnOperations(adapter, databaseId, tableId, relPlan);
454
+ if (relResults.success.length > 0) {
455
+ const totalRelationships = relPlan.toCreate.length + relPlan.toUpdate.length + relPlan.toRecreate.length + relPlan.unchanged.length;
456
+ const activeRelationships = relPlan.toCreate.length + relPlan.toUpdate.length + relPlan.toRecreate.length;
457
+
458
+ if (relResults.success.length !== activeRelationships) {
459
+ // Show both counts when they differ (usually due to recreations)
460
+ MessageFormatter.success(`Processed ${relResults.success.length} operations for ${activeRelationships} relationship${activeRelationships === 1 ? '' : 's'}`, { prefix: 'Relationships' });
461
+ } else {
462
+ MessageFormatter.success(`Processed ${relResults.success.length} relationship${relResults.success.length === 1 ? '' : 's'}`, { prefix: 'Relationships' });
463
+ }
464
+ }
465
+ if (relResults.errors.length > 0) {
466
+ MessageFormatter.error(`${relResults.errors.length} relationship operations failed:`, undefined, { prefix: 'Relationships' });
467
+ for (const err of relResults.errors) {
468
+ MessageFormatter.error(` ${err.column}: ${err.error}`, undefined, { prefix: 'Relationships' });
469
+ }
470
+ }
471
+
472
+ if (relsDeferred.length > 0) {
473
+ MessageFormatter.info(`Deferred ${relsDeferred.length} relationship(s) until related tables become available`, { prefix: 'Relationships' });
474
+ }
475
+ }
476
+
477
+ // Wait for all attributes to become available before creating indexes
478
+ const allAttrKeys = [
479
+ ...nonRel.map((a: any) => a.key),
480
+ ...relsAll.filter((a: any) => a.relatedCollection).map((a: any) => a.key)
481
+ ];
482
+
483
+ if (allAttrKeys.length > 0) {
484
+ for (const attrKey of allAttrKeys) {
485
+ const maxWait = 60000; // 60 seconds
486
+ const startTime = Date.now();
487
+ let lastStatus = '';
488
+
489
+ while (Date.now() - startTime < maxWait) {
490
+ try {
491
+ const tableData = await adapter.getTable({ databaseId, tableId });
492
+ const attrs = (tableData as any).data?.columns || (tableData as any).data?.attributes || [];
493
+ const attr = attrs.find((a: any) => a.key === attrKey);
494
+
495
+ if (attr) {
496
+ if (attr.status === 'available') {
497
+ break; // Attribute is ready
498
+ }
499
+ if (attr.status === 'failed' || attr.status === 'stuck') {
500
+ throw new Error(`Attribute ${attrKey} failed to create: ${attr.error || 'unknown error'}`);
501
+ }
502
+ // Still processing, continue waiting
503
+ lastStatus = attr.status;
504
+ }
505
+
506
+ await delay(2000); // Check every 2 seconds
507
+ } catch (e) {
508
+ // If we can't check status, assume it's processing and continue
509
+ await delay(2000);
510
+ }
511
+ }
512
+
513
+ // Timeout check
514
+ if (Date.now() - startTime >= maxWait) {
515
+ MessageFormatter.warning(
516
+ `Attribute ${attrKey} did not become available within ${maxWait / 1000}s (last status: ${lastStatus}). Proceeding anyway.`,
517
+ { prefix: 'Attributes' }
518
+ );
519
+ }
520
+ }
521
+ }
522
+
523
+ // Index management: create/update indexes using clean adapter-based system
524
+ const localTableConfig = config.collections?.find(
525
+ c => c.name === collectionData.name || c.$id === collectionData.$id
526
+ );
527
+ const idxs = (localTableConfig?.indexes ?? indexes ?? []) as any[];
528
+
529
+ // Create/update indexes with proper planning and execution
530
+ await createOrUpdateIndexesViaAdapter(adapter, databaseId, tableId, idxs, indexes);
531
+
532
+ // Handle obsolete index deletions
533
+ const desiredIndexKeys: Set<string> = new Set((indexes || []).map((i: any) => i.key as string));
534
+ await deleteObsoleteIndexesViaAdapter(adapter, databaseId, tableId, desiredIndexKeys);
535
+
536
+ // Deletions: remove columns/attributes that are present remotely but not in desired config
537
+ try {
538
+ const desiredKeys = new Set((attributes || []).map((a: any) => a.key));
539
+ // Also track case-insensitive keys to avoid double-deletion of renames (handled as recreates)
540
+ const desiredKeysLower = new Set((attributes || []).map((a: any) => a.key?.toLowerCase()));
541
+ const tableInfo3 = await adapter.getTable({ databaseId, tableId });
542
+ const existingCols3: any[] = (tableInfo3 as any).data?.columns || (tableInfo3 as any).data?.attributes || [];
543
+ const toDelete = existingCols3
544
+ .filter((col: any) => {
545
+ if (!col?.key) return false;
546
+ // Exact match - keep it
547
+ if (desiredKeys.has(col.key)) return false;
548
+ // Case-insensitive match (rename scenario) - already handled as recreate, don't delete again
549
+ if (desiredKeysLower.has(col.key?.toLowerCase())) return false;
550
+ // Don't delete child-side relationship attributes - they're auto-managed by Appwrite
551
+ // for two-way relationships and deleting them would break the parent relationship
552
+ if (col.type === 'relationship' && col.side === 'child') return false;
553
+ return true;
554
+ })
555
+ .map((col: any) => col.key as string);
556
+
557
+ if (toDelete.length > 0) {
558
+ MessageFormatter.info(`Plan 🗑️ ${toDelete.length} (${toDelete.join(', ')})`, { prefix: 'Attributes' });
559
+ const deleted: string[] = [];
560
+ const errors: Array<{ key: string; error: string }> = [];
561
+ for (const key of toDelete) {
562
+ try {
563
+ // Drop any indexes that reference this attribute to avoid server errors
564
+ try {
565
+ const idxRes = await adapter.listIndexes({ databaseId, tableId });
566
+ const ilist: any[] = (idxRes as any).data || (idxRes as any).indexes || [];
567
+ for (const idx of ilist) {
568
+ const attrs: string[] = Array.isArray(idx.attributes)
569
+ ? idx.attributes
570
+ : (Array.isArray((idx as any).columns) ? (idx as any).columns : []);
571
+ if (attrs.includes(key)) {
572
+ MessageFormatter.info(`🗑️ Deleting index '${idx.key}' referencing '${key}'`, { prefix: 'Indexes' });
573
+ await adapter.deleteIndex({ databaseId, tableId, key: idx.key });
574
+ await delay(500);
575
+ }
576
+ }
577
+ } catch {}
578
+
579
+ await adapter.deleteAttribute({ databaseId, tableId, key });
580
+ // Wait briefly for deletion to settle
581
+ const start = Date.now();
582
+ const maxWaitMs = 60000;
583
+ while (Date.now() - start < maxWaitMs) {
584
+ try {
585
+ const tinfo = await adapter.getTable({ databaseId, tableId });
586
+ const cols = (tinfo as any).data?.columns || (tinfo as any).data?.attributes || [];
587
+ const found = cols.find((c: any) => c.key === key);
588
+ if (!found) break;
589
+ if (found.status && found.status !== 'deleting') break;
590
+ } catch {}
591
+ await delay(1000);
592
+ }
593
+ deleted.push(key);
594
+ } catch (e: any) {
595
+ errors.push({ key, error: e?.message || String(e) });
596
+ }
597
+ }
598
+ if (deleted.length) {
599
+ MessageFormatter.success(`Deleted ${deleted.length} attributes: ${deleted.join(', ')}`, { prefix: 'Attributes' });
600
+ }
601
+ if (errors.length) {
602
+ MessageFormatter.error(`${errors.length} deletions failed`, undefined, { prefix: 'Attributes' });
603
+ errors.forEach(er => MessageFormatter.error(` ${er.key}: ${er.error}`, undefined, { prefix: 'Attributes' }));
604
+ }
605
+ } else {
606
+ MessageFormatter.info(`Plan 🗑️ 0`, { prefix: 'Attributes' });
607
+ }
608
+ } catch (e) {
609
+ MessageFormatter.warning(`Could not evaluate deletions: ${(e as Error)?.message || e}`, { prefix: 'Attributes' });
610
+ }
611
+
612
+ // Mark this table as fully processed for this database to prevent re-processing in the same DB only
613
+ markCollectionProcessed(tableId, collectionData.name, databaseId);
614
+ }
615
+
616
+ // Process queued relationships once mapping likely populated
617
+ if (relQueue.length > 0) {
618
+ MessageFormatter.info(`🔧 Processing ${relQueue.length} queued relationship attributes for tables`, { prefix: "Tables" });
619
+ for (const { tableId, attr } of relQueue) {
620
+ const relNameOrId = (attr as any).relatedCollection as string | undefined;
621
+ if (!relNameOrId) continue;
622
+ const relId = nameToIdMapping.get(relNameOrId) || relNameOrId;
623
+ if (relId) {
624
+ (attr as any).relatedCollection = relId;
625
+ try {
626
+ await adapter.createAttribute({
627
+ databaseId,
628
+ tableId,
629
+ key: (attr as any).key,
630
+ type: (attr as any).type,
631
+ size: (attr as any).size,
632
+ required: !!(attr as any).required,
633
+ default: (attr as any).xdefault,
634
+ array: !!(attr as any).array,
635
+ min: (attr as any).min,
636
+ max: (attr as any).max,
637
+ elements: (attr as any).elements,
638
+ relatedCollection: relId,
639
+ relationType: (attr as any).relationType,
640
+ twoWay: (attr as any).twoWay,
641
+ twoWayKey: (attr as any).twoWayKey,
642
+ onDelete: (attr as any).onDelete,
643
+ side: (attr as any).side
644
+ });
645
+ await delay(150);
646
+ MessageFormatter.info(`✅ Successfully processed queued relationship: ${attr.key}`, { prefix: "Tables" });
647
+ } catch (e) {
648
+ MessageFormatter.error(`Failed queued relationship ${attr.key}`, e instanceof Error ? e : new Error(String(e)), { prefix: 'Attributes' });
649
+ }
650
+ } else {
651
+ MessageFormatter.warning(`Could not resolve relationship ${attr.key} -> ${relNameOrId}`, { prefix: "Tables" });
652
+ }
653
+ }
654
+ }
655
+
656
+ // Process any remaining queued operations to complete relationship sync
657
+ try {
658
+ MessageFormatter.info(`🔄 Processing final operation queue for database ${databaseId}`, { prefix: "Tables" });
659
+ await processQueue(adapter, databaseId);
660
+ MessageFormatter.info(`✅ Operation queue processing completed`, { prefix: "Tables" });
661
+ } catch (error) {
662
+ MessageFormatter.error(`Failed to process operation queue`, error instanceof Error ? error : new Error(String(error)), { prefix: 'Tables' });
663
+ }
664
+ };
665
+
666
+ export const generateMockData = async (
667
+ database: Databases,
668
+ databaseId: string,
669
+ configCollections: any[]
670
+ ): Promise<void> => {
671
+ for (const { collection, mockFunction } of configCollections) {
672
+ if (mockFunction) {
673
+ MessageFormatter.progress(`Generating mock data for collection: ${collection.name}`, { prefix: "Mock Data" });
674
+ const mockData = mockFunction();
675
+ for (const data of mockData) {
676
+ await database.createDocument(
677
+ databaseId,
678
+ collection.$id,
679
+ ID.unique(),
680
+ data
681
+ );
682
+ }
683
+ }
684
+ }
685
+ };
686
+
687
+ export const fetchAllCollections = async (
688
+ dbId: string,
689
+ database: Databases
690
+ ): Promise<Models.Collection[]> => {
691
+ MessageFormatter.progress(`Fetching all collections for database ID: ${dbId}`, { prefix: "Collections" });
692
+ let collections: Models.Collection[] = [];
693
+ let moreCollections = true;
694
+ let lastCollectionId: string | undefined;
695
+
696
+ while (moreCollections) {
697
+ const queries = [Query.limit(500)];
698
+ if (lastCollectionId) {
699
+ queries.push(Query.cursorAfter(lastCollectionId));
700
+ }
701
+ const response = await tryAwaitWithRetry(
702
+ async () => await database.listCollections(dbId, queries)
703
+ );
704
+ collections = collections.concat(response.collections);
705
+ moreCollections = response.collections.length === 500;
706
+ if (moreCollections) {
707
+ lastCollectionId =
708
+ response.collections[response.collections.length - 1].$id;
709
+ }
710
+ }
711
+
712
+ MessageFormatter.success(`Fetched a total of ${collections.length} collections`, { prefix: "Collections" });
713
+ return collections;
714
+ };