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,1339 @@
1
+ import { Query } from "node-appwrite";
2
+ import { attributeSchema, parseAttribute, } from "appwrite-utils";
3
+ import { nameToIdMapping, enqueueOperation, markAttributeProcessed, isAttributeProcessed, } from "../shared/operationQueue.js";
4
+ import { delay, tryAwaitWithRetry, calculateExponentialBackoff, } from "appwrite-utils-helpers";
5
+ import chalk from "chalk";
6
+ import { Decimal } from "decimal.js";
7
+ import { logger, MessageFormatter, isDatabaseAdapter } from "appwrite-utils-helpers";
8
+ // Extreme values that Appwrite may return, which should be treated as undefined
9
+ const EXTREME_MIN_INTEGER = -9223372036854776000;
10
+ const EXTREME_MAX_INTEGER = 9223372036854776000;
11
+ const EXTREME_MIN_FLOAT = -1.7976931348623157e308;
12
+ const EXTREME_MAX_FLOAT = 1.7976931348623157e308;
13
+ /** Get columns/attributes array, preferring modern 'columns' over legacy 'attributes' */
14
+ function getColumns(obj) {
15
+ return obj.columns || obj.attributes || [];
16
+ }
17
+ /**
18
+ * Type guard to check if an attribute has min/max properties
19
+ */
20
+ const hasMinMaxProperties = (attribute) => {
21
+ return (attribute.type === "integer" ||
22
+ attribute.type === "double" ||
23
+ attribute.type === "float");
24
+ };
25
+ /**
26
+ * Normalizes min/max values for integer and float attributes using Decimal.js for precision
27
+ * Validates that min < max and handles extreme database values
28
+ */
29
+ const normalizeMinMaxValues = (attribute) => {
30
+ if (!hasMinMaxProperties(attribute)) {
31
+ logger.debug(`Attribute '${attribute.key}' does not have min/max properties`, {
32
+ type: attribute.type,
33
+ operation: "normalizeMinMaxValues",
34
+ });
35
+ return {};
36
+ }
37
+ const { type, min, max } = attribute;
38
+ let normalizedMin = min;
39
+ let normalizedMax = max;
40
+ logger.debug(`Normalizing min/max values for attribute '${attribute.key}'`, {
41
+ type,
42
+ originalMin: min,
43
+ originalMax: max,
44
+ operation: "normalizeMinMaxValues",
45
+ });
46
+ // Handle min value - only filter out extreme database values
47
+ if (normalizedMin !== undefined && normalizedMin !== null) {
48
+ const minValue = Number(normalizedMin);
49
+ const originalMin = normalizedMin;
50
+ // Check if it's an extreme database value (but don't filter out large numbers)
51
+ if (type === 'integer') {
52
+ if (minValue === EXTREME_MIN_INTEGER) {
53
+ logger.debug(`Min value normalized to undefined for attribute '${attribute.key}'`, {
54
+ type,
55
+ originalValue: originalMin,
56
+ numericValue: minValue,
57
+ reason: 'extreme_database_value',
58
+ extremeValue: EXTREME_MIN_INTEGER,
59
+ operation: 'normalizeMinMaxValues'
60
+ });
61
+ normalizedMin = undefined;
62
+ }
63
+ }
64
+ else { // float/double
65
+ if (minValue === EXTREME_MIN_FLOAT) {
66
+ logger.debug(`Min value normalized to undefined for attribute '${attribute.key}'`, {
67
+ type,
68
+ originalValue: originalMin,
69
+ numericValue: minValue,
70
+ reason: 'extreme_database_value',
71
+ extremeValue: EXTREME_MIN_FLOAT,
72
+ operation: 'normalizeMinMaxValues'
73
+ });
74
+ normalizedMin = undefined;
75
+ }
76
+ }
77
+ }
78
+ // Handle max value - only filter out extreme database values
79
+ if (normalizedMax !== undefined && normalizedMax !== null) {
80
+ const maxValue = Number(normalizedMax);
81
+ const originalMax = normalizedMax;
82
+ // Check if it's an extreme database value (but don't filter out large numbers)
83
+ if (type === 'integer') {
84
+ if (maxValue === EXTREME_MAX_INTEGER) {
85
+ logger.debug(`Max value normalized to undefined for attribute '${attribute.key}'`, {
86
+ type,
87
+ originalValue: originalMax,
88
+ numericValue: maxValue,
89
+ reason: 'extreme_database_value',
90
+ extremeValue: EXTREME_MAX_INTEGER,
91
+ operation: 'normalizeMinMaxValues'
92
+ });
93
+ normalizedMax = undefined;
94
+ }
95
+ }
96
+ else { // float/double
97
+ if (maxValue === EXTREME_MAX_FLOAT) {
98
+ logger.debug(`Max value normalized to undefined for attribute '${attribute.key}'`, {
99
+ type,
100
+ originalValue: originalMax,
101
+ numericValue: maxValue,
102
+ reason: 'extreme_database_value',
103
+ extremeValue: EXTREME_MAX_FLOAT,
104
+ operation: 'normalizeMinMaxValues'
105
+ });
106
+ normalizedMax = undefined;
107
+ }
108
+ }
109
+ }
110
+ // Validate that min < max using multiple comparison methods for reliability
111
+ if (normalizedMin !== undefined && normalizedMax !== undefined &&
112
+ normalizedMin !== null && normalizedMax !== null) {
113
+ logger.debug(`Validating min/max values for attribute '${attribute.key}'`, {
114
+ type,
115
+ normalizedMin,
116
+ normalizedMax,
117
+ normalizedMinType: typeof normalizedMin,
118
+ normalizedMaxType: typeof normalizedMax,
119
+ operation: 'normalizeMinMaxValues'
120
+ });
121
+ // Use multiple validation approaches to ensure reliability
122
+ let needsSwap = false;
123
+ let comparisonMethod = '';
124
+ try {
125
+ // Method 1: Direct number comparison (most reliable for normal numbers)
126
+ const minNum = Number(normalizedMin);
127
+ const maxNum = Number(normalizedMax);
128
+ if (!isNaN(minNum) && !isNaN(maxNum)) {
129
+ needsSwap = minNum >= maxNum;
130
+ comparisonMethod = 'direct_number_comparison';
131
+ logger.debug(`Direct number comparison: ${minNum} >= ${maxNum} = ${needsSwap}`, {
132
+ operation: 'normalizeMinMaxValues'
133
+ });
134
+ }
135
+ // Method 2: Fallback to string comparison for very large numbers
136
+ if (!needsSwap && (isNaN(minNum) || isNaN(maxNum) || Math.abs(minNum) > Number.MAX_SAFE_INTEGER || Math.abs(maxNum) > Number.MAX_SAFE_INTEGER)) {
137
+ const minStr = normalizedMin.toString();
138
+ const maxStr = normalizedMax.toString();
139
+ // Simple string length and lexicographical comparison for very large numbers
140
+ if (minStr.length !== maxStr.length) {
141
+ needsSwap = minStr.length > maxStr.length;
142
+ }
143
+ else {
144
+ needsSwap = minStr >= maxStr;
145
+ }
146
+ comparisonMethod = 'string_comparison_fallback';
147
+ logger.debug(`String comparison fallback: '${minStr}' >= '${maxStr}' = ${needsSwap}`, {
148
+ operation: 'normalizeMinMaxValues'
149
+ });
150
+ }
151
+ // Method 3: Final validation using Decimal.js as last resort
152
+ if (!needsSwap && (typeof normalizedMin === 'string' || typeof normalizedMax === 'string')) {
153
+ try {
154
+ const minDecimal = new Decimal(normalizedMin.toString());
155
+ const maxDecimal = new Decimal(normalizedMax.toString());
156
+ needsSwap = minDecimal.greaterThanOrEqualTo(maxDecimal);
157
+ comparisonMethod = 'decimal_js_fallback';
158
+ logger.debug(`Decimal.js fallback: ${normalizedMin} >= ${normalizedMax} = ${needsSwap}`, {
159
+ operation: 'normalizeMinMaxValues'
160
+ });
161
+ }
162
+ catch (decimalError) {
163
+ logger.warn(`Decimal.js comparison failed for attribute '${attribute.key}': ${decimalError instanceof Error ? decimalError.message : String(decimalError)}`, {
164
+ operation: 'normalizeMinMaxValues'
165
+ });
166
+ }
167
+ }
168
+ // Log final validation result
169
+ if (needsSwap) {
170
+ logger.error(`Invalid min/max values detected for attribute '${attribute.key}': min (${normalizedMin}) must be less than max (${normalizedMax})`, {
171
+ type,
172
+ min: normalizedMin,
173
+ max: normalizedMax,
174
+ comparisonMethod,
175
+ operation: 'normalizeMinMaxValues'
176
+ });
177
+ // Swap values to ensure min < max (graceful handling)
178
+ logger.warn(`Swapping min/max values for attribute '${attribute.key}' to fix validation`, {
179
+ type,
180
+ originalMin: normalizedMin,
181
+ originalMax: normalizedMax,
182
+ newMin: normalizedMax,
183
+ newMax: normalizedMin,
184
+ comparisonMethod,
185
+ operation: 'normalizeMinMaxValues'
186
+ });
187
+ const temp = normalizedMin;
188
+ normalizedMin = normalizedMax;
189
+ normalizedMax = temp;
190
+ }
191
+ else {
192
+ logger.debug(`Min/max validation passed for attribute '${attribute.key}'`, {
193
+ type,
194
+ min: normalizedMin,
195
+ max: normalizedMax,
196
+ comparisonMethod,
197
+ operation: 'normalizeMinMaxValues'
198
+ });
199
+ }
200
+ }
201
+ catch (error) {
202
+ logger.error(`Critical error during min/max validation for attribute '${attribute.key}'`, {
203
+ type,
204
+ min: normalizedMin,
205
+ max: normalizedMax,
206
+ error: error instanceof Error ? error.message : String(error),
207
+ operation: 'normalizeMinMaxValues'
208
+ });
209
+ // If all comparison methods fail, set both to undefined to avoid API errors
210
+ normalizedMin = undefined;
211
+ normalizedMax = undefined;
212
+ }
213
+ }
214
+ const result = { min: normalizedMin, max: normalizedMax };
215
+ logger.debug(`Min/max normalization complete for attribute '${attribute.key}'`, {
216
+ type,
217
+ result,
218
+ operation: "normalizeMinMaxValues",
219
+ });
220
+ return result;
221
+ };
222
+ /**
223
+ * Normalizes an attribute for comparison by handling extreme database values
224
+ * This is used when comparing database attributes with config attributes
225
+ */
226
+ const normalizeAttributeForComparison = (attribute) => {
227
+ const normalized = { ...attribute };
228
+ // Ignore defaults on required attributes to prevent false positives
229
+ if (normalized.required === true && "xdefault" in normalized) {
230
+ delete normalized.xdefault;
231
+ }
232
+ // Normalize min/max for numeric types
233
+ if (hasMinMaxProperties(attribute)) {
234
+ const { min, max } = normalizeMinMaxValues(attribute);
235
+ normalized.min = min;
236
+ normalized.max = max;
237
+ }
238
+ // Remove xdefault if null/undefined to ensure consistent comparison
239
+ // Appwrite sets xdefault: null for required attributes, but config files omit it
240
+ if ("xdefault" in normalized &&
241
+ (normalized.xdefault === null || normalized.xdefault === undefined)) {
242
+ delete normalized.xdefault;
243
+ }
244
+ return normalized;
245
+ };
246
+ /**
247
+ * Helper function to create an attribute using either the adapter or legacy API
248
+ */
249
+ const createAttributeViaAdapter = async (db, dbId, collectionId, attribute) => {
250
+ const startTime = Date.now();
251
+ const adapterType = isDatabaseAdapter(db) ? "adapter" : "legacy";
252
+ logger.info(`Creating attribute '${attribute.key}' via ${adapterType}`, {
253
+ type: attribute.type,
254
+ dbId,
255
+ collectionId,
256
+ adapterType,
257
+ operation: "createAttributeViaAdapter",
258
+ });
259
+ if (isDatabaseAdapter(db)) {
260
+ // Use the adapter's unified createAttribute method
261
+ const params = {
262
+ databaseId: dbId,
263
+ tableId: collectionId,
264
+ key: attribute.key,
265
+ type: attribute.type,
266
+ required: attribute.required || false,
267
+ array: attribute.array || false,
268
+ ...(attribute.size && { size: attribute.size }),
269
+ ...(attribute.xdefault !== undefined &&
270
+ !attribute.required && { default: attribute.xdefault }),
271
+ ...(attribute.encrypt && {
272
+ encrypt: attribute.encrypt,
273
+ }),
274
+ ...(attribute.min !== undefined && {
275
+ min: attribute.min,
276
+ }),
277
+ ...(attribute.max !== undefined && {
278
+ max: attribute.max,
279
+ }),
280
+ ...(attribute.elements && {
281
+ elements: attribute.elements,
282
+ }),
283
+ ...(attribute.relatedCollection && {
284
+ relatedCollection: attribute.relatedCollection,
285
+ }),
286
+ ...(attribute.relationType && {
287
+ relationType: attribute.relationType,
288
+ }),
289
+ ...(attribute.twoWay !== undefined && {
290
+ twoWay: attribute.twoWay,
291
+ }),
292
+ ...(attribute.onDelete && {
293
+ onDelete: attribute.onDelete,
294
+ }),
295
+ ...(attribute.twoWayKey && {
296
+ twoWayKey: attribute.twoWayKey,
297
+ }),
298
+ };
299
+ logger.debug(`Adapter create parameters for '${attribute.key}'`, {
300
+ params,
301
+ operation: "createAttributeViaAdapter",
302
+ });
303
+ await db.createAttribute(params);
304
+ const duration = Date.now() - startTime;
305
+ logger.info(`Successfully created attribute '${attribute.key}' via adapter`, {
306
+ duration,
307
+ operation: "createAttributeViaAdapter",
308
+ });
309
+ }
310
+ else {
311
+ // Use legacy type-specific methods
312
+ logger.debug(`Using legacy creation for attribute '${attribute.key}'`, {
313
+ operation: "createAttributeViaAdapter",
314
+ });
315
+ await createLegacyAttribute(db, dbId, collectionId, attribute);
316
+ const duration = Date.now() - startTime;
317
+ logger.info(`Successfully created attribute '${attribute.key}' via legacy`, {
318
+ duration,
319
+ operation: "createAttributeViaAdapter",
320
+ });
321
+ }
322
+ };
323
+ /**
324
+ * Helper function to update an attribute using either the adapter or legacy API
325
+ */
326
+ const updateAttributeViaAdapter = async (db, dbId, collectionId, attribute) => {
327
+ if (isDatabaseAdapter(db)) {
328
+ // Use the adapter's unified updateAttribute method
329
+ const params = {
330
+ databaseId: dbId,
331
+ tableId: collectionId,
332
+ key: attribute.key,
333
+ type: attribute.type,
334
+ required: attribute.required || false,
335
+ array: attribute.array || false,
336
+ size: attribute.size,
337
+ min: attribute.min,
338
+ max: attribute.max,
339
+ encrypt: attribute.encrypt,
340
+ elements: attribute.elements,
341
+ relatedCollection: attribute.relatedCollection,
342
+ relationType: attribute.relationType,
343
+ twoWay: attribute.twoWay,
344
+ twoWayKey: attribute.twoWayKey,
345
+ onDelete: attribute.onDelete
346
+ };
347
+ if (!attribute.required && attribute.xdefault !== undefined) {
348
+ params.default = attribute.xdefault;
349
+ }
350
+ await db.updateAttribute(params);
351
+ }
352
+ else {
353
+ // Use legacy type-specific methods
354
+ await updateLegacyAttribute(db, dbId, collectionId, attribute);
355
+ }
356
+ };
357
+ /**
358
+ * Legacy attribute creation using type-specific methods
359
+ */
360
+ const createLegacyAttribute = async (db, dbId, collectionId, attribute) => {
361
+ const startTime = Date.now();
362
+ const { min: normalizedMin, max: normalizedMax } = normalizeMinMaxValues(attribute);
363
+ logger.info(`Creating legacy attribute '${attribute.key}'`, {
364
+ type: attribute.type,
365
+ dbId,
366
+ collectionId,
367
+ normalizedMin,
368
+ normalizedMax,
369
+ operation: "createLegacyAttribute",
370
+ });
371
+ switch (attribute.type) {
372
+ case "string":
373
+ const stringParams = {
374
+ size: attribute.size || 255,
375
+ required: attribute.required || false,
376
+ defaultValue: attribute.xdefault !== undefined && !attribute.required
377
+ ? attribute.xdefault
378
+ : undefined,
379
+ array: attribute.array || false,
380
+ encrypt: attribute.encrypt,
381
+ };
382
+ logger.debug(`Creating string attribute '${attribute.key}'`, {
383
+ ...stringParams,
384
+ operation: "createLegacyAttribute",
385
+ });
386
+ await db.createStringAttribute(dbId, collectionId, attribute.key, stringParams.size, stringParams.required, stringParams.defaultValue, stringParams.array, stringParams.encrypt);
387
+ break;
388
+ case "integer":
389
+ const integerParams = {
390
+ required: attribute.required || false,
391
+ min: normalizedMin !== undefined
392
+ ? parseInt(String(normalizedMin))
393
+ : undefined,
394
+ max: normalizedMax !== undefined
395
+ ? parseInt(String(normalizedMax))
396
+ : undefined,
397
+ defaultValue: attribute.xdefault !== undefined && !attribute.required
398
+ ? attribute.xdefault
399
+ : undefined,
400
+ array: attribute.array || false,
401
+ };
402
+ logger.debug(`Creating integer attribute '${attribute.key}'`, {
403
+ ...integerParams,
404
+ operation: "createLegacyAttribute",
405
+ });
406
+ await db.createIntegerAttribute(dbId, collectionId, attribute.key, integerParams.required, integerParams.min, integerParams.max, integerParams.defaultValue, integerParams.array);
407
+ break;
408
+ case "double":
409
+ case "float":
410
+ await db.createFloatAttribute(dbId, collectionId, attribute.key, attribute.required || false, normalizedMin !== undefined ? Number(normalizedMin) : undefined, normalizedMax !== undefined ? Number(normalizedMax) : undefined, attribute.xdefault !== undefined && !attribute.required
411
+ ? attribute.xdefault
412
+ : undefined, attribute.array || false);
413
+ break;
414
+ case "boolean":
415
+ await db.createBooleanAttribute(dbId, collectionId, attribute.key, attribute.required || false, attribute.xdefault !== undefined && !attribute.required
416
+ ? attribute.xdefault
417
+ : undefined, attribute.array || false);
418
+ break;
419
+ case "datetime":
420
+ await db.createDatetimeAttribute(dbId, collectionId, attribute.key, attribute.required || false, attribute.xdefault !== undefined && !attribute.required
421
+ ? attribute.xdefault
422
+ : undefined, attribute.array || false);
423
+ break;
424
+ case "email":
425
+ await db.createEmailAttribute(dbId, collectionId, attribute.key, attribute.required || false, attribute.xdefault !== undefined && !attribute.required
426
+ ? attribute.xdefault
427
+ : undefined, attribute.array || false);
428
+ break;
429
+ case "ip":
430
+ await db.createIpAttribute(dbId, collectionId, attribute.key, attribute.required || false, attribute.xdefault !== undefined && !attribute.required
431
+ ? attribute.xdefault
432
+ : undefined, attribute.array || false);
433
+ break;
434
+ case "url":
435
+ await db.createUrlAttribute(dbId, collectionId, attribute.key, attribute.required || false, attribute.xdefault !== undefined && !attribute.required
436
+ ? attribute.xdefault
437
+ : undefined, attribute.array || false);
438
+ break;
439
+ case "enum":
440
+ await db.createEnumAttribute(dbId, collectionId, attribute.key, attribute.elements || [], attribute.required || false, attribute.xdefault !== undefined && !attribute.required
441
+ ? attribute.xdefault
442
+ : undefined, attribute.array || false);
443
+ break;
444
+ case "relationship":
445
+ await db.createRelationshipAttribute(dbId, collectionId, attribute.relatedCollection, attribute.relationType, attribute.twoWay, attribute.key, attribute.twoWayKey, attribute.onDelete);
446
+ break;
447
+ default:
448
+ const error = new Error(`Unsupported attribute type: ${attribute.type}`);
449
+ logger.error(`Unsupported attribute type for '${attribute.key}'`, {
450
+ type: attribute.type,
451
+ supportedTypes: [
452
+ "string",
453
+ "integer",
454
+ "double",
455
+ "float",
456
+ "boolean",
457
+ "datetime",
458
+ "email",
459
+ "ip",
460
+ "url",
461
+ "enum",
462
+ "relationship",
463
+ ],
464
+ operation: "createLegacyAttribute",
465
+ });
466
+ throw error;
467
+ }
468
+ const duration = Date.now() - startTime;
469
+ logger.info(`Successfully created legacy attribute '${attribute.key}'`, {
470
+ type: attribute.type,
471
+ duration,
472
+ operation: "createLegacyAttribute",
473
+ });
474
+ };
475
+ /**
476
+ * Legacy attribute update using type-specific methods
477
+ */
478
+ const updateLegacyAttribute = async (db, dbId, collectionId, attribute) => {
479
+ const { min: normalizedMin, max: normalizedMax } = normalizeMinMaxValues(attribute);
480
+ switch (attribute.type) {
481
+ case "string":
482
+ await db.updateStringAttribute(dbId, collectionId, attribute.key, attribute.required || false, !attribute.required && attribute.xdefault !== undefined
483
+ ? attribute.xdefault
484
+ : null, attribute.size);
485
+ break;
486
+ case "integer":
487
+ await db.updateIntegerAttribute(dbId, collectionId, attribute.key, attribute.required || false, !attribute.required && attribute.xdefault !== undefined
488
+ ? attribute.xdefault
489
+ : null, normalizedMin !== undefined
490
+ ? parseInt(String(normalizedMin))
491
+ : undefined, normalizedMax !== undefined
492
+ ? parseInt(String(normalizedMax))
493
+ : undefined);
494
+ break;
495
+ case "double":
496
+ case "float":
497
+ const minParam = normalizedMin !== undefined ? Number(normalizedMin) : undefined;
498
+ const maxParam = normalizedMax !== undefined ? Number(normalizedMax) : undefined;
499
+ await db.updateFloatAttribute(dbId, collectionId, attribute.key, attribute.required || false, minParam, maxParam, !attribute.required && attribute.xdefault !== undefined
500
+ ? attribute.xdefault
501
+ : null);
502
+ break;
503
+ case "boolean":
504
+ await db.updateBooleanAttribute(dbId, collectionId, attribute.key, attribute.required || false, !attribute.required && attribute.xdefault !== undefined
505
+ ? attribute.xdefault
506
+ : null);
507
+ break;
508
+ case "datetime":
509
+ await db.updateDatetimeAttribute(dbId, collectionId, attribute.key, attribute.required || false, !attribute.required && attribute.xdefault !== undefined
510
+ ? attribute.xdefault
511
+ : null);
512
+ break;
513
+ case "email":
514
+ await db.updateEmailAttribute(dbId, collectionId, attribute.key, attribute.required || false, !attribute.required && attribute.xdefault !== undefined
515
+ ? attribute.xdefault
516
+ : null);
517
+ break;
518
+ case "ip":
519
+ await db.updateIpAttribute(dbId, collectionId, attribute.key, attribute.required || false, !attribute.required && attribute.xdefault !== undefined
520
+ ? attribute.xdefault
521
+ : null);
522
+ break;
523
+ case "url":
524
+ await db.updateUrlAttribute(dbId, collectionId, attribute.key, attribute.required || false, !attribute.required && attribute.xdefault !== undefined
525
+ ? attribute.xdefault
526
+ : null);
527
+ break;
528
+ case "enum":
529
+ await db.updateEnumAttribute(dbId, collectionId, attribute.key, attribute.elements || [], attribute.required || false, !attribute.required && attribute.xdefault !== undefined
530
+ ? attribute.xdefault
531
+ : null);
532
+ break;
533
+ case "relationship":
534
+ await db.updateRelationshipAttribute(dbId, collectionId, attribute.key, attribute.onDelete);
535
+ break;
536
+ default:
537
+ throw new Error(`Unsupported attribute type for update: ${attribute.type}`);
538
+ }
539
+ };
540
+ /**
541
+ * Wait for attribute to become available, with retry logic for stuck attributes and exponential backoff
542
+ */
543
+ const waitForAttributeAvailable = async (db, dbId, collectionId, attributeKey, maxWaitTime = 60000, // 1 minute
544
+ retryCount = 0, maxRetries = 5) => {
545
+ const startTime = Date.now();
546
+ let checkInterval = 2000; // Start with 2 seconds
547
+ logger.info(`Waiting for attribute '${attributeKey}' to become available`, {
548
+ dbId,
549
+ collectionId,
550
+ maxWaitTime,
551
+ retryCount,
552
+ maxRetries,
553
+ operation: "waitForAttributeAvailable",
554
+ });
555
+ // Calculate exponential backoff: 2s, 4s, 8s, 16s, 30s (capped at 30s)
556
+ if (retryCount > 0) {
557
+ const exponentialDelay = calculateExponentialBackoff(retryCount);
558
+ await delay(exponentialDelay);
559
+ }
560
+ while (Date.now() - startTime < maxWaitTime) {
561
+ try {
562
+ const collection = isDatabaseAdapter(db)
563
+ ? (await db.getTable({ databaseId: dbId, tableId: collectionId })).data
564
+ : await db.getCollection(dbId, collectionId);
565
+ const attribute = getColumns(collection).find((attr) => attr.key === attributeKey);
566
+ if (!attribute) {
567
+ MessageFormatter.error(`Attribute '${attributeKey}' not found`);
568
+ return false;
569
+ }
570
+ const statusInfo = {
571
+ attributeKey,
572
+ status: attribute.status,
573
+ error: attribute.error,
574
+ dbId,
575
+ collectionId,
576
+ waitTime: Date.now() - startTime,
577
+ operation: "waitForAttributeAvailable",
578
+ };
579
+ switch (attribute.status) {
580
+ case "available":
581
+ logger.info(`Attribute '${attributeKey}' became available`, statusInfo);
582
+ return true;
583
+ case "failed":
584
+ logger.error(`Attribute '${attributeKey}' failed`, statusInfo);
585
+ return false;
586
+ case "stuck":
587
+ logger.warn(`Attribute '${attributeKey}' is stuck`, statusInfo);
588
+ return false;
589
+ case "processing":
590
+ // Continue waiting
591
+ logger.debug(`Attribute '${attributeKey}' still processing`, statusInfo);
592
+ break;
593
+ case "deleting":
594
+ MessageFormatter.info(chalk.yellow(`Attribute '${attributeKey}' is being deleted`));
595
+ logger.warn(`Attribute '${attributeKey}' is being deleted`, statusInfo);
596
+ break;
597
+ default:
598
+ MessageFormatter.info(chalk.yellow(`Unknown status '${attribute.status}' for attribute '${attributeKey}'`));
599
+ logger.warn(`Unknown status for attribute '${attributeKey}'`, statusInfo);
600
+ break;
601
+ }
602
+ await delay(checkInterval);
603
+ }
604
+ catch (error) {
605
+ const errorMessage = error instanceof Error ? error.message : String(error);
606
+ MessageFormatter.error(`Error checking attribute status: ${errorMessage}`);
607
+ logger.error("Error checking attribute status", {
608
+ attributeKey,
609
+ dbId,
610
+ collectionId,
611
+ error: errorMessage,
612
+ waitTime: Date.now() - startTime,
613
+ operation: "waitForAttributeAvailable",
614
+ });
615
+ return false;
616
+ }
617
+ }
618
+ // Timeout reached
619
+ MessageFormatter.info(chalk.yellow(`⏰ Timeout waiting for attribute '${attributeKey}' (${maxWaitTime}ms)`));
620
+ // If we have retries left and this isn't the last retry, try recreating
621
+ if (retryCount < maxRetries) {
622
+ MessageFormatter.info(chalk.yellow(`🔄 Retrying attribute creation (attempt ${retryCount + 1}/${maxRetries})`));
623
+ return false; // Signal that we need to retry
624
+ }
625
+ return false;
626
+ };
627
+ /**
628
+ * Wait for all attributes in a collection to become available
629
+ */
630
+ const waitForAllAttributesAvailable = async (db, dbId, collectionId, attributeKeys, maxWaitTime = 60000) => {
631
+ MessageFormatter.info(chalk.blue(`Waiting for ${attributeKeys.length} attributes to become available...`));
632
+ const failedAttributes = [];
633
+ for (const attributeKey of attributeKeys) {
634
+ const success = await waitForAttributeAvailable(db, dbId, collectionId, attributeKey, maxWaitTime);
635
+ if (!success) {
636
+ failedAttributes.push(attributeKey);
637
+ }
638
+ }
639
+ return failedAttributes;
640
+ };
641
+ /**
642
+ * Delete collection and recreate with retry logic
643
+ */
644
+ const deleteAndRecreateCollection = async (db, dbId, collection, retryCount) => {
645
+ try {
646
+ MessageFormatter.info(chalk.yellow(`🗑️ Deleting collection '${collection.name}' for retry ${retryCount}`));
647
+ // Delete the collection
648
+ if (isDatabaseAdapter(db)) {
649
+ await db.deleteTable({ databaseId: dbId, tableId: collection.$id });
650
+ }
651
+ else {
652
+ await db.deleteCollection(dbId, collection.$id);
653
+ }
654
+ MessageFormatter.warning(`Deleted collection '${collection.name}'`);
655
+ // Wait a bit before recreating
656
+ await delay(2000);
657
+ // Recreate the collection
658
+ MessageFormatter.info(`🔄 Recreating collection '${collection.name}'`);
659
+ const newCollection = isDatabaseAdapter(db)
660
+ ? (await db.createTable({
661
+ databaseId: dbId,
662
+ id: collection.$id,
663
+ name: collection.name,
664
+ permissions: collection.$permissions,
665
+ documentSecurity: collection.documentSecurity,
666
+ enabled: collection.enabled,
667
+ })).data
668
+ : await db.createCollection(dbId, collection.$id, collection.name, collection.$permissions, collection.documentSecurity, collection.enabled);
669
+ MessageFormatter.success(`✅ Recreated collection '${collection.name}'`);
670
+ return newCollection;
671
+ }
672
+ catch (error) {
673
+ MessageFormatter.info(chalk.red(`Failed to delete/recreate collection '${collection.name}': ${error}`));
674
+ return null;
675
+ }
676
+ };
677
+ /**
678
+ * Get the fields that should be compared for a specific attribute type
679
+ * Only returns fields that are valid for the given type to avoid false positives
680
+ */
681
+ const getComparableFields = (type) => {
682
+ const baseFields = ["key", "type", "array", "required", "xdefault"];
683
+ switch (type) {
684
+ case "string":
685
+ return [...baseFields, "size", "encrypt"];
686
+ case "integer":
687
+ case "double":
688
+ case "float":
689
+ return [...baseFields, "min", "max"];
690
+ case "enum":
691
+ return [...baseFields, "elements"];
692
+ case "relationship":
693
+ return [
694
+ ...baseFields,
695
+ "relationType",
696
+ "twoWay",
697
+ "twoWayKey",
698
+ "onDelete",
699
+ "relatedCollection",
700
+ ];
701
+ case "boolean":
702
+ case "datetime":
703
+ case "email":
704
+ case "ip":
705
+ case "url":
706
+ return baseFields;
707
+ default:
708
+ // Fallback to all fields for unknown types
709
+ return [
710
+ "key",
711
+ "type",
712
+ "array",
713
+ "encrypt",
714
+ "required",
715
+ "size",
716
+ "min",
717
+ "max",
718
+ "xdefault",
719
+ "elements",
720
+ "relationType",
721
+ "twoWay",
722
+ "twoWayKey",
723
+ "onDelete",
724
+ "relatedCollection",
725
+ ];
726
+ }
727
+ };
728
+ const attributesSame = (databaseAttribute, configAttribute) => {
729
+ // Normalize both attributes for comparison (handle extreme database values)
730
+ const normalizedDbAttr = normalizeAttributeForComparison(databaseAttribute);
731
+ const normalizedConfigAttr = normalizeAttributeForComparison(configAttribute);
732
+ // Use type-specific field list to avoid false positives from irrelevant fields
733
+ const attributesToCheck = getComparableFields(normalizedConfigAttr.type);
734
+ const fieldsToCheck = attributesToCheck.filter((attr) => {
735
+ if (attr !== "xdefault") {
736
+ return true;
737
+ }
738
+ const dbRequired = Boolean(normalizedDbAttr.required);
739
+ const configRequired = Boolean(normalizedConfigAttr.required);
740
+ return !(dbRequired || configRequired);
741
+ });
742
+ const differences = [];
743
+ const result = fieldsToCheck.every((attr) => {
744
+ // Check if both objects have the attribute
745
+ const dbHasAttr = attr in normalizedDbAttr;
746
+ const configHasAttr = attr in normalizedConfigAttr;
747
+ // If both have the attribute, compare values
748
+ if (dbHasAttr && configHasAttr) {
749
+ const dbValue = normalizedDbAttr[attr];
750
+ const configValue = normalizedConfigAttr[attr];
751
+ // Consider undefined and null as equivalent
752
+ if ((dbValue === undefined || dbValue === null) &&
753
+ (configValue === undefined || configValue === null)) {
754
+ return true;
755
+ }
756
+ // Normalize booleans: treat undefined and false as equivalent
757
+ if (typeof dbValue === "boolean" || typeof configValue === "boolean") {
758
+ const boolMatch = Boolean(dbValue) === Boolean(configValue);
759
+ if (!boolMatch) {
760
+ differences.push(`${attr}: db=${dbValue} config=${configValue}`);
761
+ }
762
+ return boolMatch;
763
+ }
764
+ // For numeric comparisons, compare numbers if both are numeric-like
765
+ if ((typeof dbValue === "number" ||
766
+ (typeof dbValue === "string" &&
767
+ dbValue !== "" &&
768
+ !isNaN(Number(dbValue)))) &&
769
+ (typeof configValue === "number" ||
770
+ (typeof configValue === "string" &&
771
+ configValue !== "" &&
772
+ !isNaN(Number(configValue))))) {
773
+ const numMatch = Number(dbValue) === Number(configValue);
774
+ if (!numMatch) {
775
+ differences.push(`${attr}: db=${dbValue} config=${configValue}`);
776
+ }
777
+ return numMatch;
778
+ }
779
+ // For array comparisons (e.g., enum elements), use order-independent equality
780
+ if (Array.isArray(dbValue) && Array.isArray(configValue)) {
781
+ const arrayMatch = dbValue.length === configValue.length &&
782
+ dbValue.every((val) => configValue.includes(val));
783
+ if (!arrayMatch) {
784
+ differences.push(`${attr}: db=${JSON.stringify(dbValue)} config=${JSON.stringify(configValue)}`);
785
+ }
786
+ return arrayMatch;
787
+ }
788
+ const match = dbValue === configValue;
789
+ if (!match) {
790
+ differences.push(`${attr}: db=${JSON.stringify(dbValue)} config=${JSON.stringify(configValue)}`);
791
+ }
792
+ return match;
793
+ }
794
+ // If neither has the attribute, consider it the same
795
+ if (!dbHasAttr && !configHasAttr) {
796
+ return true;
797
+ }
798
+ // If one has the attribute and the other doesn't, check if it's undefined or null
799
+ if (dbHasAttr && !configHasAttr) {
800
+ const dbValue = normalizedDbAttr[attr];
801
+ // Consider default-false booleans as equal to missing in config
802
+ if (typeof dbValue === "boolean") {
803
+ const match = dbValue === false; // missing in config equals false in db
804
+ if (!match) {
805
+ differences.push(`${attr}: db=${dbValue} config=<missing>`);
806
+ }
807
+ return match;
808
+ }
809
+ const match = dbValue === undefined || dbValue === null;
810
+ if (!match) {
811
+ differences.push(`${attr}: db=${JSON.stringify(dbValue)} config=<missing>`);
812
+ }
813
+ return match;
814
+ }
815
+ if (!dbHasAttr && configHasAttr) {
816
+ const configValue = normalizedConfigAttr[attr];
817
+ // Consider default-false booleans as equal to missing in db
818
+ if (typeof configValue === "boolean") {
819
+ const match = configValue === false; // missing in db equals false in config
820
+ if (!match) {
821
+ differences.push(`${attr}: db=<missing> config=${configValue}`);
822
+ }
823
+ return match;
824
+ }
825
+ const match = configValue === undefined || configValue === null;
826
+ if (!match) {
827
+ differences.push(`${attr}: db=<missing> config=${JSON.stringify(configValue)}`);
828
+ }
829
+ return match;
830
+ }
831
+ // If we reach here, the attributes are different
832
+ differences.push(`${attr}: unexpected comparison state`);
833
+ return false;
834
+ });
835
+ if (!result && differences.length > 0) {
836
+ logger.debug(`Attribute mismatch detected for '${normalizedConfigAttr.key}'`, {
837
+ differences,
838
+ dbAttribute: normalizedDbAttr,
839
+ configAttribute: normalizedConfigAttr,
840
+ operation: "attributesSame",
841
+ });
842
+ }
843
+ return result;
844
+ };
845
+ /**
846
+ * Enhanced attribute creation with proper status monitoring and retry logic
847
+ */
848
+ export const createOrUpdateAttributeWithStatusCheck = async (db, dbId, collection, attribute, retryCount = 0, maxRetries = 5) => {
849
+ try {
850
+ // First, try to create/update the attribute using existing logic
851
+ const result = await createOrUpdateAttribute(db, dbId, collection, attribute);
852
+ // If the attribute was queued (relationship dependency unresolved),
853
+ // skip status polling and retry logic — the queue will handle it later.
854
+ if (result === "queued") {
855
+ MessageFormatter.info(chalk.yellow(`⏭️ Deferred relationship attribute '${attribute.key}' — queued for later once dependencies are available`));
856
+ return true;
857
+ }
858
+ // If collection creation failed, return false to indicate failure
859
+ if (result === "error") {
860
+ MessageFormatter.error(`Failed to create collection for attribute '${attribute.key}'`);
861
+ return false;
862
+ }
863
+ // Now wait for the attribute to become available
864
+ const success = await waitForAttributeAvailable(db, dbId, collection.$id, attribute.key, 60000, // 1 minute timeout
865
+ retryCount, maxRetries);
866
+ if (success) {
867
+ return true;
868
+ }
869
+ // If not successful and we have retries left, delete specific attribute and try again
870
+ if (retryCount < maxRetries) {
871
+ MessageFormatter.info(chalk.yellow(`Attribute '${attribute.key}' failed/stuck, deleting and retrying...`));
872
+ // Try to delete the specific stuck attribute instead of the entire collection
873
+ try {
874
+ if (isDatabaseAdapter(db)) {
875
+ await db.deleteAttribute({
876
+ databaseId: dbId,
877
+ tableId: collection.$id,
878
+ key: attribute.key,
879
+ });
880
+ }
881
+ else {
882
+ await db.deleteAttribute(dbId, collection.$id, attribute.key);
883
+ }
884
+ MessageFormatter.info(chalk.yellow(`Deleted stuck attribute '${attribute.key}', will retry creation`));
885
+ // Wait a bit before retry
886
+ await delay(3000);
887
+ // Get fresh collection data
888
+ const freshCollection = isDatabaseAdapter(db)
889
+ ? (await db.getTable({ databaseId: dbId, tableId: collection.$id }))
890
+ .data
891
+ : await db.getCollection(dbId, collection.$id);
892
+ // Retry with the same collection (attribute should be gone now)
893
+ return await createOrUpdateAttributeWithStatusCheck(db, dbId, freshCollection, attribute, retryCount + 1, maxRetries);
894
+ }
895
+ catch (deleteError) {
896
+ MessageFormatter.info(chalk.red(`Failed to delete stuck attribute '${attribute.key}': ${deleteError}`));
897
+ // If attribute deletion fails, only then try collection recreation as last resort
898
+ if (retryCount >= maxRetries - 1) {
899
+ MessageFormatter.info(chalk.yellow(`Last resort: Recreating collection for attribute '${attribute.key}'`));
900
+ // Get fresh collection data
901
+ const freshCollection = isDatabaseAdapter(db)
902
+ ? (await db.getTable({ databaseId: dbId, tableId: collection.$id }))
903
+ .data
904
+ : await db.getCollection(dbId, collection.$id);
905
+ // Delete and recreate collection
906
+ const newCollection = await deleteAndRecreateCollection(db, dbId, freshCollection, retryCount + 1);
907
+ if (newCollection) {
908
+ // Retry with the new collection
909
+ return await createOrUpdateAttributeWithStatusCheck(db, dbId, newCollection, attribute, retryCount + 1, maxRetries);
910
+ }
911
+ }
912
+ else {
913
+ // Continue to next retry without collection recreation
914
+ return await createOrUpdateAttributeWithStatusCheck(db, dbId, collection, attribute, retryCount + 1, maxRetries);
915
+ }
916
+ }
917
+ }
918
+ MessageFormatter.info(chalk.red(`❌ Failed to create attribute '${attribute.key}' after ${maxRetries + 1} attempts`));
919
+ return false;
920
+ }
921
+ catch (error) {
922
+ MessageFormatter.info(chalk.red(`Error creating attribute '${attribute.key}': ${error}`));
923
+ if (retryCount < maxRetries) {
924
+ MessageFormatter.info(chalk.yellow(`Retrying attribute '${attribute.key}' due to error...`));
925
+ // Wait a bit before retry
926
+ await delay(2000);
927
+ return await createOrUpdateAttributeWithStatusCheck(db, dbId, collection, attribute, retryCount + 1, maxRetries);
928
+ }
929
+ return false;
930
+ }
931
+ };
932
+ export const createOrUpdateAttribute = async (db, dbId, collection, attribute) => {
933
+ let action = "create";
934
+ let foundAttribute;
935
+ const updateEnabled = true;
936
+ let finalAttribute = attribute;
937
+ try {
938
+ const collectionAttr = getColumns(collection).find((attr) => attr.key === attribute.key);
939
+ foundAttribute = parseAttribute(collectionAttr);
940
+ }
941
+ catch (error) {
942
+ foundAttribute = undefined;
943
+ }
944
+ // If attribute exists but type changed, delete it so we can recreate with new type
945
+ if (foundAttribute &&
946
+ foundAttribute.type !== attribute.type) {
947
+ MessageFormatter.info(chalk.yellow(`Attribute '${attribute.key}' type changed from '${foundAttribute.type}' to '${attribute.type}'. Recreating attribute.`));
948
+ try {
949
+ if (isDatabaseAdapter(db)) {
950
+ await db.deleteAttribute({
951
+ databaseId: dbId,
952
+ tableId: collection.$id,
953
+ key: attribute.key
954
+ });
955
+ }
956
+ else {
957
+ await db.deleteAttribute(dbId, collection.$id, attribute.key);
958
+ }
959
+ // Remove from local collection metadata so downstream logic treats it as new
960
+ const filtered = getColumns(collection).filter((attr) => attr.key !== attribute.key);
961
+ if ('columns' in collection)
962
+ collection.columns = filtered;
963
+ if ('attributes' in collection)
964
+ collection.attributes = filtered;
965
+ foundAttribute = undefined;
966
+ }
967
+ catch (deleteError) {
968
+ MessageFormatter.error(`Failed to delete attribute '${attribute.key}' before recreation: ${deleteError}`);
969
+ return "error";
970
+ }
971
+ }
972
+ if (foundAttribute &&
973
+ attributesSame(foundAttribute, attribute) &&
974
+ updateEnabled) {
975
+ // No need to do anything, they are the same
976
+ return "processed";
977
+ }
978
+ else if (foundAttribute &&
979
+ !attributesSame(foundAttribute, attribute) &&
980
+ updateEnabled) {
981
+ // MessageFormatter.info(
982
+ // `Updating attribute with same key ${attribute.key} but different values`
983
+ // );
984
+ finalAttribute = {
985
+ ...foundAttribute,
986
+ ...attribute,
987
+ };
988
+ action = "update";
989
+ }
990
+ else if (!updateEnabled &&
991
+ foundAttribute &&
992
+ !attributesSame(foundAttribute, attribute)) {
993
+ if (isDatabaseAdapter(db)) {
994
+ await db.deleteAttribute({
995
+ databaseId: dbId,
996
+ tableId: collection.$id,
997
+ key: attribute.key,
998
+ });
999
+ }
1000
+ else {
1001
+ await db.deleteAttribute(dbId, collection.$id, attribute.key);
1002
+ }
1003
+ MessageFormatter.info(`Deleted attribute: ${attribute.key} to recreate it because they diff (update disabled temporarily)`);
1004
+ return "processed";
1005
+ }
1006
+ // Relationship attribute logic with adjustments
1007
+ let collectionFoundViaRelatedCollection;
1008
+ let relatedCollectionId;
1009
+ if (finalAttribute.type === "relationship" &&
1010
+ finalAttribute.relatedCollection) {
1011
+ // First try treating relatedCollection as an ID directly
1012
+ try {
1013
+ const byIdCollection = isDatabaseAdapter(db)
1014
+ ? (await db.getTable({
1015
+ databaseId: dbId,
1016
+ tableId: finalAttribute.relatedCollection,
1017
+ })).data
1018
+ : await db.getCollection(dbId, finalAttribute.relatedCollection);
1019
+ collectionFoundViaRelatedCollection = byIdCollection;
1020
+ relatedCollectionId = byIdCollection.$id;
1021
+ // Cache by name for subsequent lookups
1022
+ nameToIdMapping.set(byIdCollection.name, byIdCollection.$id);
1023
+ }
1024
+ catch (_) {
1025
+ // Not an ID or not found — fall back to name-based resolution below
1026
+ }
1027
+ if (!collectionFoundViaRelatedCollection &&
1028
+ nameToIdMapping.has(finalAttribute.relatedCollection)) {
1029
+ relatedCollectionId = nameToIdMapping.get(finalAttribute.relatedCollection);
1030
+ try {
1031
+ collectionFoundViaRelatedCollection = isDatabaseAdapter(db)
1032
+ ? (await db.getTable({
1033
+ databaseId: dbId,
1034
+ tableId: relatedCollectionId,
1035
+ })).data
1036
+ : await db.getCollection(dbId, relatedCollectionId);
1037
+ }
1038
+ catch (e) {
1039
+ // MessageFormatter.info(
1040
+ // `Collection not found: ${finalAttribute.relatedCollection} when nameToIdMapping was set`
1041
+ // );
1042
+ collectionFoundViaRelatedCollection = undefined;
1043
+ }
1044
+ }
1045
+ else if (!collectionFoundViaRelatedCollection) {
1046
+ const collectionsPulled = isDatabaseAdapter(db)
1047
+ ? await db.listTables({
1048
+ databaseId: dbId,
1049
+ queries: [Query.equal("name", finalAttribute.relatedCollection)],
1050
+ })
1051
+ : await db.listCollections(dbId, [
1052
+ Query.equal("name", finalAttribute.relatedCollection),
1053
+ ]);
1054
+ if (collectionsPulled.total && collectionsPulled.total > 0) {
1055
+ collectionFoundViaRelatedCollection = isDatabaseAdapter(db)
1056
+ ? collectionsPulled.tables?.[0]
1057
+ : collectionsPulled.collections?.[0];
1058
+ relatedCollectionId = collectionFoundViaRelatedCollection?.$id;
1059
+ if (relatedCollectionId) {
1060
+ nameToIdMapping.set(finalAttribute.relatedCollection, relatedCollectionId);
1061
+ }
1062
+ }
1063
+ }
1064
+ // ONLY queue relationship attributes that have actual unresolved dependencies
1065
+ if (!(relatedCollectionId && collectionFoundViaRelatedCollection)) {
1066
+ MessageFormatter.info(chalk.yellow(`⏳ Queueing relationship attribute '${finalAttribute.key}' - related collection '${finalAttribute.relatedCollection}' not found yet`));
1067
+ enqueueOperation({
1068
+ type: "attribute",
1069
+ collectionId: collection.$id,
1070
+ collection: collection,
1071
+ attribute,
1072
+ dependencies: [finalAttribute.relatedCollection],
1073
+ });
1074
+ return "queued";
1075
+ }
1076
+ }
1077
+ finalAttribute = parseAttribute(finalAttribute);
1078
+ // Ensure collection/table exists - create it if it doesn't
1079
+ try {
1080
+ await (isDatabaseAdapter(db)
1081
+ ? db.getTable({ databaseId: dbId, tableId: collection.$id })
1082
+ : db.getCollection(dbId, collection.$id));
1083
+ }
1084
+ catch (error) {
1085
+ // Collection doesn't exist - create it
1086
+ if (error.code === 404 ||
1087
+ (error instanceof Error &&
1088
+ (error.message.includes("collection_not_found") ||
1089
+ error.message.includes("Collection with the requested ID could not be found")))) {
1090
+ MessageFormatter.info(`Collection '${collection.name}' doesn't exist, creating it first...`);
1091
+ try {
1092
+ if (isDatabaseAdapter(db)) {
1093
+ await db.createTable({
1094
+ databaseId: dbId,
1095
+ id: collection.$id,
1096
+ name: collection.name,
1097
+ permissions: collection.$permissions || [],
1098
+ documentSecurity: collection.documentSecurity ?? false,
1099
+ enabled: collection.enabled ?? true,
1100
+ });
1101
+ }
1102
+ else {
1103
+ await db.createCollection(dbId, collection.$id, collection.name, collection.$permissions || [], collection.documentSecurity ?? false, collection.enabled ?? true);
1104
+ }
1105
+ MessageFormatter.success(`Created collection '${collection.name}'`);
1106
+ await delay(500); // Wait for collection to be ready
1107
+ }
1108
+ catch (createError) {
1109
+ MessageFormatter.error(`Failed to create collection '${collection.name}'`, createError instanceof Error
1110
+ ? createError
1111
+ : new Error(String(createError)));
1112
+ return "error";
1113
+ }
1114
+ }
1115
+ else {
1116
+ // Other error - re-throw
1117
+ throw error;
1118
+ }
1119
+ }
1120
+ // Use adapter-based attribute creation/update
1121
+ if (action === "create") {
1122
+ await tryAwaitWithRetry(async () => await createAttributeViaAdapter(db, dbId, collection.$id, finalAttribute));
1123
+ }
1124
+ else {
1125
+ console.log(`Updating attribute '${finalAttribute.key}'...`);
1126
+ if (finalAttribute.type === "double" || finalAttribute.type === "integer") {
1127
+ console.log("finalAttribute:", finalAttribute);
1128
+ }
1129
+ await tryAwaitWithRetry(async () => await updateAttributeViaAdapter(db, dbId, collection.$id, finalAttribute));
1130
+ }
1131
+ return "processed";
1132
+ };
1133
+ /**
1134
+ * Enhanced collection attribute creation with proper status monitoring
1135
+ */
1136
+ export const createUpdateCollectionAttributesWithStatusCheck = async (db, dbId, collection, attributes) => {
1137
+ const existingAttributes = getColumns(collection).map((attr) => parseAttribute(attr)) || [];
1138
+ const attributesToRemove = existingAttributes.filter((attr) => !attributes.some((a) => a.key === attr.key));
1139
+ const indexesToRemove = collection.indexes.filter((index) => attributesToRemove.some((attr) => index.attributes.includes(attr.key)));
1140
+ // Handle attribute removal first
1141
+ if (attributesToRemove.length > 0) {
1142
+ if (indexesToRemove.length > 0) {
1143
+ MessageFormatter.info(chalk.red(`Removing indexes as they rely on an attribute that is being removed: ${indexesToRemove
1144
+ .map((index) => index.key)
1145
+ .join(", ")}`));
1146
+ for (const index of indexesToRemove) {
1147
+ await tryAwaitWithRetry(async () => {
1148
+ if (isDatabaseAdapter(db)) {
1149
+ await db.deleteIndex({
1150
+ databaseId: dbId,
1151
+ tableId: collection.$id,
1152
+ key: index.key,
1153
+ });
1154
+ }
1155
+ else {
1156
+ await db.deleteIndex(dbId, collection.$id, index.key);
1157
+ }
1158
+ });
1159
+ await delay(500); // Longer delay for deletions
1160
+ }
1161
+ }
1162
+ for (const attr of attributesToRemove) {
1163
+ MessageFormatter.info(chalk.red(`Removing attribute: ${attr.key} as it is no longer in the collection`));
1164
+ await tryAwaitWithRetry(async () => {
1165
+ if (isDatabaseAdapter(db)) {
1166
+ await db.deleteAttribute({
1167
+ databaseId: dbId,
1168
+ tableId: collection.$id,
1169
+ key: attr.key,
1170
+ });
1171
+ }
1172
+ else {
1173
+ await db.deleteAttribute(dbId, collection.$id, attr.key);
1174
+ }
1175
+ });
1176
+ await delay(500); // Longer delay for deletions
1177
+ }
1178
+ }
1179
+ // First, get fresh collection data and determine which attributes actually need processing
1180
+ let currentCollection = collection;
1181
+ try {
1182
+ currentCollection = isDatabaseAdapter(db)
1183
+ ? (await db.getTable({ databaseId: dbId, tableId: collection.$id })).data
1184
+ : await db.getCollection(dbId, collection.$id);
1185
+ }
1186
+ catch (error) {
1187
+ MessageFormatter.info(chalk.yellow(`Warning: Could not refresh collection data: ${error}`));
1188
+ }
1189
+ const existingAttributesMap = new Map();
1190
+ try {
1191
+ const parsedAttributes = currentCollection.attributes.map((attr) => parseAttribute(attr));
1192
+ parsedAttributes.forEach((attr) => existingAttributesMap.set(attr.key, attr));
1193
+ }
1194
+ catch (error) {
1195
+ MessageFormatter.info(chalk.yellow(`Warning: Could not parse existing attributes: ${error}`));
1196
+ }
1197
+ // Filter to only attributes that need processing (new, changed, or not yet processed)
1198
+ const attributesToProcess = attributes.filter((attribute) => {
1199
+ // Skip if already processed in this session
1200
+ if (isAttributeProcessed(dbId, currentCollection.$id, attribute.key)) {
1201
+ return false;
1202
+ }
1203
+ const existing = existingAttributesMap.get(attribute.key);
1204
+ if (!existing) {
1205
+ MessageFormatter.info(`➕ ${attribute.key}`);
1206
+ return true;
1207
+ }
1208
+ const needsUpdate = !attributesSame(existing, parseAttribute(attribute));
1209
+ if (needsUpdate) {
1210
+ MessageFormatter.info(`🔄 ${attribute.key}`);
1211
+ }
1212
+ else {
1213
+ MessageFormatter.info(chalk.gray(`✅ ${attribute.key}`));
1214
+ }
1215
+ return needsUpdate;
1216
+ });
1217
+ if (attributesToProcess.length === 0) {
1218
+ return true;
1219
+ }
1220
+ let remainingAttributes = [...attributesToProcess];
1221
+ let overallRetryCount = 0;
1222
+ const maxOverallRetries = 3;
1223
+ while (remainingAttributes.length > 0 &&
1224
+ overallRetryCount < maxOverallRetries) {
1225
+ const attributesToProcessThisRound = [...remainingAttributes];
1226
+ remainingAttributes = []; // Reset for next iteration
1227
+ for (const attribute of attributesToProcessThisRound) {
1228
+ const success = await createOrUpdateAttributeWithStatusCheck(db, dbId, currentCollection, attribute);
1229
+ if (success) {
1230
+ // Mark this specific attribute as processed
1231
+ markAttributeProcessed(dbId, currentCollection.$id, attribute.key);
1232
+ // Get updated collection data for next iteration
1233
+ try {
1234
+ currentCollection = isDatabaseAdapter(db)
1235
+ ? (await db.getTable({ databaseId: dbId, tableId: collection.$id })).data
1236
+ : await db.getCollection({
1237
+ databaseId: dbId,
1238
+ collectionId: collection.$id,
1239
+ });
1240
+ }
1241
+ catch (error) {
1242
+ MessageFormatter.info(chalk.yellow(`Warning: Could not refresh collection data: ${error}`));
1243
+ }
1244
+ // Add delay between successful attributes
1245
+ await delay(1000);
1246
+ }
1247
+ else {
1248
+ MessageFormatter.info(chalk.red(`❌ ${attribute.key}`));
1249
+ remainingAttributes.push(attribute); // Add back to retry list
1250
+ }
1251
+ }
1252
+ if (remainingAttributes.length === 0) {
1253
+ return true;
1254
+ }
1255
+ overallRetryCount++;
1256
+ if (overallRetryCount < maxOverallRetries) {
1257
+ MessageFormatter.info(chalk.yellow(`⏳ Retrying ${remainingAttributes.length} failed attributes...`));
1258
+ await delay(5000);
1259
+ // Refresh collection data before retry
1260
+ try {
1261
+ currentCollection = isDatabaseAdapter(db)
1262
+ ? (await db.getTable({ databaseId: dbId, tableId: collection.$id }))
1263
+ .data
1264
+ : await db.getCollection(dbId, collection.$id);
1265
+ }
1266
+ catch (error) {
1267
+ // Silently continue if refresh fails
1268
+ }
1269
+ }
1270
+ }
1271
+ // If we get here, some attributes still failed after all retries
1272
+ if (attributesToProcess.length > 0) {
1273
+ MessageFormatter.info(chalk.red(`\n❌ Failed to create ${attributesToProcess.length} attributes after ${maxOverallRetries} attempts: ${attributesToProcess
1274
+ .map((a) => a.key)
1275
+ .join(", ")}`));
1276
+ MessageFormatter.info(chalk.red(`This may indicate a fundamental issue with the attribute definitions or Appwrite instance`));
1277
+ return false;
1278
+ }
1279
+ MessageFormatter.info(chalk.green(`\n✅ Successfully created all ${attributes.length} attributes for collection: ${collection.name}`));
1280
+ return true;
1281
+ };
1282
+ export const createUpdateCollectionAttributes = async (db, dbId, collection, attributes) => {
1283
+ MessageFormatter.info(chalk.green(`Creating/Updating attributes for collection: ${collection.name}`));
1284
+ const existingAttributes = getColumns(collection).map((attr) => parseAttribute(attr)) || [];
1285
+ const attributesToRemove = existingAttributes.filter((attr) => !attributes.some((a) => a.key === attr.key));
1286
+ const indexesToRemove = collection.indexes.filter((index) => attributesToRemove.some((attr) => index.attributes.includes(attr.key)));
1287
+ if (attributesToRemove.length > 0) {
1288
+ if (indexesToRemove.length > 0) {
1289
+ MessageFormatter.info(chalk.red(`Removing indexes as they rely on an attribute that is being removed: ${indexesToRemove
1290
+ .map((index) => index.key)
1291
+ .join(", ")}`));
1292
+ for (const index of indexesToRemove) {
1293
+ await tryAwaitWithRetry(async () => {
1294
+ if (isDatabaseAdapter(db)) {
1295
+ await db.deleteIndex({
1296
+ databaseId: dbId,
1297
+ tableId: collection.$id,
1298
+ key: index.key,
1299
+ });
1300
+ }
1301
+ else {
1302
+ await db.deleteIndex(dbId, collection.$id, index.key);
1303
+ }
1304
+ });
1305
+ await delay(100);
1306
+ }
1307
+ }
1308
+ for (const attr of attributesToRemove) {
1309
+ MessageFormatter.info(chalk.red(`Removing attribute: ${attr.key} as it is no longer in the collection`));
1310
+ await tryAwaitWithRetry(async () => {
1311
+ if (isDatabaseAdapter(db)) {
1312
+ await db.deleteAttribute({
1313
+ databaseId: dbId,
1314
+ tableId: collection.$id,
1315
+ key: attr.key,
1316
+ });
1317
+ }
1318
+ else {
1319
+ await db.deleteAttribute(dbId, collection.$id, attr.key);
1320
+ }
1321
+ });
1322
+ await delay(50);
1323
+ }
1324
+ }
1325
+ const batchSize = 3;
1326
+ for (let i = 0; i < attributes.length; i += batchSize) {
1327
+ const batch = attributes.slice(i, i + batchSize);
1328
+ const attributePromises = batch.map((attribute) => tryAwaitWithRetry(async () => await createOrUpdateAttribute(db, dbId, collection, attribute)));
1329
+ const results = await Promise.allSettled(attributePromises);
1330
+ results.forEach((result) => {
1331
+ if (result.status === "rejected") {
1332
+ MessageFormatter.error("An attribute promise was rejected:", result.reason);
1333
+ }
1334
+ });
1335
+ // Add delay after each batch
1336
+ await delay(200);
1337
+ }
1338
+ MessageFormatter.info(`Finished creating/updating attributes for collection: ${collection.name}`);
1339
+ };