appwrite-utils-cli 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/README.md +80 -0
  2. package/dist/main.d.ts +2 -0
  3. package/dist/main.js +74 -0
  4. package/dist/migrations/afterImportActions.d.ts +12 -0
  5. package/dist/migrations/afterImportActions.js +196 -0
  6. package/dist/migrations/attributes.d.ts +4 -0
  7. package/dist/migrations/attributes.js +158 -0
  8. package/dist/migrations/backup.d.ts +621 -0
  9. package/dist/migrations/backup.js +159 -0
  10. package/dist/migrations/collections.d.ts +16 -0
  11. package/dist/migrations/collections.js +207 -0
  12. package/dist/migrations/converters.d.ts +179 -0
  13. package/dist/migrations/converters.js +575 -0
  14. package/dist/migrations/dbHelpers.d.ts +5 -0
  15. package/dist/migrations/dbHelpers.js +54 -0
  16. package/dist/migrations/importController.d.ts +44 -0
  17. package/dist/migrations/importController.js +312 -0
  18. package/dist/migrations/importDataActions.d.ts +44 -0
  19. package/dist/migrations/importDataActions.js +219 -0
  20. package/dist/migrations/indexes.d.ts +4 -0
  21. package/dist/migrations/indexes.js +18 -0
  22. package/dist/migrations/logging.d.ts +2 -0
  23. package/dist/migrations/logging.js +14 -0
  24. package/dist/migrations/migrationHelper.d.ts +18 -0
  25. package/dist/migrations/migrationHelper.js +66 -0
  26. package/dist/migrations/queue.d.ts +13 -0
  27. package/dist/migrations/queue.js +79 -0
  28. package/dist/migrations/relationships.d.ts +90 -0
  29. package/dist/migrations/relationships.js +209 -0
  30. package/dist/migrations/schema.d.ts +3142 -0
  31. package/dist/migrations/schema.js +485 -0
  32. package/dist/migrations/schemaStrings.d.ts +12 -0
  33. package/dist/migrations/schemaStrings.js +261 -0
  34. package/dist/migrations/setupDatabase.d.ts +7 -0
  35. package/dist/migrations/setupDatabase.js +151 -0
  36. package/dist/migrations/storage.d.ts +8 -0
  37. package/dist/migrations/storage.js +241 -0
  38. package/dist/migrations/users.d.ts +11 -0
  39. package/dist/migrations/users.js +114 -0
  40. package/dist/migrations/validationRules.d.ts +43 -0
  41. package/dist/migrations/validationRules.js +42 -0
  42. package/dist/schemas/authUser.d.ts +62 -0
  43. package/dist/schemas/authUser.js +17 -0
  44. package/dist/setup.d.ts +2 -0
  45. package/dist/setup.js +5 -0
  46. package/dist/types.d.ts +9 -0
  47. package/dist/types.js +5 -0
  48. package/dist/utils/configSchema.json +742 -0
  49. package/dist/utils/helperFunctions.d.ts +34 -0
  50. package/dist/utils/helperFunctions.js +72 -0
  51. package/dist/utils/index.d.ts +2 -0
  52. package/dist/utils/index.js +2 -0
  53. package/dist/utils/setupFiles.d.ts +2 -0
  54. package/dist/utils/setupFiles.js +276 -0
  55. package/dist/utilsController.d.ts +30 -0
  56. package/dist/utilsController.js +106 -0
  57. package/package.json +34 -0
  58. package/src/main.ts +77 -0
  59. package/src/migrations/afterImportActions.ts +300 -0
  60. package/src/migrations/attributes.ts +315 -0
  61. package/src/migrations/backup.ts +189 -0
  62. package/src/migrations/collections.ts +303 -0
  63. package/src/migrations/converters.ts +628 -0
  64. package/src/migrations/dbHelpers.ts +89 -0
  65. package/src/migrations/importController.ts +509 -0
  66. package/src/migrations/importDataActions.ts +313 -0
  67. package/src/migrations/indexes.ts +37 -0
  68. package/src/migrations/logging.ts +15 -0
  69. package/src/migrations/migrationHelper.ts +100 -0
  70. package/src/migrations/queue.ts +119 -0
  71. package/src/migrations/relationships.ts +336 -0
  72. package/src/migrations/schema.ts +590 -0
  73. package/src/migrations/schemaStrings.ts +310 -0
  74. package/src/migrations/setupDatabase.ts +219 -0
  75. package/src/migrations/storage.ts +351 -0
  76. package/src/migrations/users.ts +148 -0
  77. package/src/migrations/validationRules.ts +63 -0
  78. package/src/schemas/authUser.ts +23 -0
  79. package/src/setup.ts +8 -0
  80. package/src/types.ts +14 -0
  81. package/src/utils/configSchema.json +742 -0
  82. package/src/utils/helperFunctions.ts +111 -0
  83. package/src/utils/index.ts +2 -0
  84. package/src/utils/setupFiles.ts +295 -0
  85. package/src/utilsController.ts +173 -0
  86. package/tsconfig.json +37 -0
@@ -0,0 +1,628 @@
1
+ import { DateTime } from "luxon";
2
+ import _ from "lodash";
3
+ import type { AppwriteConfig } from "./schema.js";
4
+
5
+ const { cloneDeep, isObject } = _;
6
+
7
+ export interface ConverterFunctions {
8
+ [key: string]: (value: any) => any;
9
+ }
10
+
11
+ export const converterFunctions = {
12
+ /**
13
+ * Converts any value to a string. Handles null and undefined explicitly.
14
+ * @param {any} value The value to convert.
15
+ * @return {string | null} The converted string or null if the value is null or undefined.
16
+ */
17
+ anyToString(value: any): string | null {
18
+ if (value == null) return null;
19
+ return typeof value === "string" ? value : JSON.stringify(value);
20
+ },
21
+
22
+ /**
23
+ * Converts any value to a number. Returns null for non-numeric values, null, or undefined.
24
+ * @param {any} value The value to convert.
25
+ * @return {number | null} The converted number or null.
26
+ */
27
+ anyToNumber(value: any): number | null {
28
+ if (value == null) return null;
29
+ const number = Number(value);
30
+ return isNaN(number) ? null : number;
31
+ },
32
+
33
+ /**
34
+ * Converts any value to a boolean. Specifically handles string representations.
35
+ * @param {any} value The value to convert.
36
+ * @return {boolean | null} The converted boolean or null if conversion is not possible.
37
+ */
38
+ anyToBoolean(value: any): boolean | null {
39
+ if (value == null) return null;
40
+ if (typeof value === "string") {
41
+ const trimmedValue = value.trim().toLowerCase();
42
+ if (["true", "yes", "1"].includes(trimmedValue)) return true;
43
+ if (["false", "no", "0"].includes(trimmedValue)) return false;
44
+ return null; // Return null for strings that don't explicitly match
45
+ }
46
+ return Boolean(value);
47
+ },
48
+
49
+ /**
50
+ * Converts any value to an array, attempting to split strings by a specified separator.
51
+ * @param {any} value The value to convert.
52
+ * @param {string | undefined} separator The separator to use when splitting strings.
53
+ * @return {any[]} The resulting array after conversion.
54
+ */
55
+ anyToAnyArray(value: any): any[] {
56
+ if (Array.isArray(value)) {
57
+ return value;
58
+ } else if (typeof value === "string") {
59
+ // Let's try a few
60
+ return converterFunctions.trySplitByDifferentSeparators(value);
61
+ }
62
+ return [value];
63
+ },
64
+
65
+ /**
66
+ * Converts any value to an array of strings. If the input is already an array, returns it as is.
67
+ * Otherwise, if the input is a string, returns an array with the string as the only element.
68
+ * Otherwise, returns an empty array.
69
+ * @param {any} value The value to convert.
70
+ * @return {string[]} The resulting array after conversion.
71
+ */
72
+ anyToStringArray(value: any): string[] {
73
+ if (Array.isArray(value)) {
74
+ return value.map((item) => String(item));
75
+ } else if (typeof value === "string" && value.length > 0) {
76
+ return [value];
77
+ }
78
+ return [];
79
+ },
80
+
81
+ /**
82
+ * A function that converts any type of value to an array of numbers.
83
+ *
84
+ * @param {any} value - the value to be converted
85
+ * @return {number[]} an array of numbers
86
+ */
87
+ anyToNumberArray(value: any): number[] {
88
+ if (Array.isArray(value)) {
89
+ return value.map((item) => Number(item));
90
+ } else if (typeof value === "string") {
91
+ return [Number(value)];
92
+ }
93
+ return [];
94
+ },
95
+
96
+ trim(value: string): string {
97
+ try {
98
+ return value.trim();
99
+ } catch (error) {
100
+ return value;
101
+ }
102
+ },
103
+
104
+ /**
105
+ * Removes the start and end quotes from a string.
106
+ * @param value The string to remove quotes from.
107
+ * @return The string with quotes removed.
108
+ **/
109
+ removeStartEndQuotes(value: string): string {
110
+ return value.replace(/^["']|["']$/g, "");
111
+ },
112
+
113
+ /**
114
+ * Tries to split a string by different separators and returns the split that has the most uniform segment lengths.
115
+ * This can be particularly useful for structured data like phone numbers.
116
+ * @param value The string to split.
117
+ * @return The split string array that has the most uniform segment lengths.
118
+ */
119
+ trySplitByDifferentSeparators(value: string): string[] {
120
+ const separators = [",", ";", "|", ":", "/", "\\"];
121
+ let bestSplit: string[] = [];
122
+ let bestScore = -Infinity;
123
+
124
+ for (const separator of separators) {
125
+ const split = value.split(separator).map((s) => s.trim()); // Ensure we trim spaces
126
+ if (split.length <= 1) continue; // Skip if no actual splitting occurred
127
+
128
+ // Calculate uniformity in segment length
129
+ const lengths = split.map((segment) => segment.length);
130
+ const averageLength = lengths.reduce((a, b) => a + b, 0) / lengths.length;
131
+ const lengthVariance =
132
+ lengths.reduce(
133
+ (total, length) => total + Math.pow(length - averageLength, 2),
134
+ 0
135
+ ) / lengths.length;
136
+
137
+ // Adjust scoring to prioritize splits with lower variance and/or specific segment count if needed
138
+ const score = split.length / (1 + lengthVariance); // Adjusted to prioritize lower variance
139
+
140
+ // Update bestSplit if this split has a better score
141
+ if (score > bestScore) {
142
+ bestSplit = split;
143
+ bestScore = score;
144
+ }
145
+ }
146
+
147
+ // If no suitable split was found, return the original value as a single-element array
148
+ if (bestSplit.length === 0) {
149
+ return [value];
150
+ }
151
+
152
+ return bestSplit;
153
+ },
154
+
155
+ joinValues(values: any[]): any {
156
+ try {
157
+ return values.join("");
158
+ } catch (error) {
159
+ return values;
160
+ }
161
+ },
162
+
163
+ joinBySpace(values: any[]): any {
164
+ try {
165
+ return values.join(" ");
166
+ } catch (error) {
167
+ return values;
168
+ }
169
+ },
170
+
171
+ joinByComma(values: any[]): any {
172
+ try {
173
+ return values.join(",");
174
+ } catch (error) {
175
+ return values;
176
+ }
177
+ },
178
+
179
+ joinByPipe(values: any[]): any {
180
+ try {
181
+ return values.join("|");
182
+ } catch (error) {
183
+ return values;
184
+ }
185
+ },
186
+
187
+ joinBySemicolon(values: any[]): any {
188
+ try {
189
+ return values.join(";");
190
+ } catch (error) {
191
+ return values;
192
+ }
193
+ },
194
+
195
+ joinByColon(values: any[]): any {
196
+ try {
197
+ return values.join(":");
198
+ } catch (error) {
199
+ return values;
200
+ }
201
+ },
202
+
203
+ joinBySlash(values: any[]): any {
204
+ try {
205
+ return values.join("/");
206
+ } catch (error) {
207
+ return values;
208
+ }
209
+ },
210
+
211
+ joinByHyphen(values: any[]): any {
212
+ try {
213
+ return values.join("-");
214
+ } catch (error) {
215
+ return values;
216
+ }
217
+ },
218
+
219
+ splitByComma(value: string): any {
220
+ try {
221
+ return value.split(",");
222
+ } catch (error) {
223
+ return value;
224
+ }
225
+ },
226
+
227
+ splitByPipe(value: string): any {
228
+ try {
229
+ return value.split("|");
230
+ } catch (error) {
231
+ return value;
232
+ }
233
+ },
234
+
235
+ splitBySemicolon(value: string): any {
236
+ try {
237
+ return value.split(";");
238
+ } catch (error) {
239
+ return value;
240
+ }
241
+ },
242
+
243
+ splitByColon(value: string): any {
244
+ try {
245
+ return value.split(":");
246
+ } catch (error) {
247
+ return value;
248
+ }
249
+ },
250
+
251
+ splitBySlash(value: string): any {
252
+ try {
253
+ return value.split("/");
254
+ } catch (error) {
255
+ return value;
256
+ }
257
+ },
258
+
259
+ splitByBackslash(value: string): any {
260
+ try {
261
+ return value.split("\\");
262
+ } catch (error) {
263
+ return value;
264
+ }
265
+ },
266
+
267
+ splitBySpace(value: string): any {
268
+ try {
269
+ return value.split(" ");
270
+ } catch (error) {
271
+ return value;
272
+ }
273
+ },
274
+
275
+ splitByDot(value: string): any {
276
+ try {
277
+ return value.split(".");
278
+ } catch (error) {
279
+ return value;
280
+ }
281
+ },
282
+
283
+ splitByUnderscore(value: string): any {
284
+ try {
285
+ return value.split("_");
286
+ } catch (error) {
287
+ return value;
288
+ }
289
+ },
290
+
291
+ splitByHyphen(value: string): any {
292
+ try {
293
+ return value.split("-");
294
+ } catch (error) {
295
+ return value;
296
+ }
297
+ },
298
+
299
+ /**
300
+ * Takes the first element of an array and returns it.
301
+ * @param {any[]} value The array to take the first element from.
302
+ * @return {any} The first element of the array.
303
+ */
304
+ pickFirstElement(value: any[]): any {
305
+ try {
306
+ return value[0];
307
+ } catch (error) {
308
+ return value;
309
+ }
310
+ },
311
+
312
+ /**
313
+ * Takes the last element of an array and returns it.
314
+ * @param {any[]} value The array to take the last element from.
315
+ * @return {any} The last element of the array.
316
+ */
317
+ pickLastElement(value: any[]): any {
318
+ try {
319
+ return value[value.length - 1];
320
+ } catch (error) {
321
+ return value;
322
+ }
323
+ },
324
+
325
+ /**
326
+ * Converts an object to a JSON string.
327
+ * @param {any} object The object to convert.
328
+ * @return {string} The JSON string representation of the object.
329
+ */
330
+ stringifyObject(object: any): string {
331
+ return JSON.stringify(object);
332
+ },
333
+
334
+ /**
335
+ * Converts a JSON string to an object.
336
+ * @param {string} jsonString The JSON string to convert.
337
+ * @return {any} The object representation of the JSON string.
338
+ */
339
+ parseObject(jsonString: string): any {
340
+ return JSON.parse(jsonString);
341
+ },
342
+
343
+ convertPhoneStringToUSInternational(value: string): string {
344
+ // Normalize input: Remove all non-digit characters except the leading +
345
+ const normalizedValue = value.startsWith("+")
346
+ ? "+" + value.slice(1).replace(/\D/g, "")
347
+ : value.replace(/\D/g, "");
348
+
349
+ // Check if the value is not a string or doesn't contain digits, return as is
350
+ if (typeof normalizedValue !== "string" || !/\d/.test(normalizedValue))
351
+ return value;
352
+
353
+ // Handle numbers with a leading + (indicating an international format)
354
+ if (normalizedValue.startsWith("+")) {
355
+ // If the number is already in a valid international format, return as is
356
+ if (normalizedValue.length > 11 && normalizedValue.length <= 15) {
357
+ return normalizedValue;
358
+ }
359
+ } else {
360
+ // For numbers without a leading +, check the length and format
361
+ if (normalizedValue.length === 10) {
362
+ // US numbers without country code, prepend +1
363
+ return `+1${normalizedValue}`;
364
+ } else if (
365
+ normalizedValue.length === 11 &&
366
+ normalizedValue.startsWith("1")
367
+ ) {
368
+ // US numbers with country code but missing +, prepend +
369
+ return `+${normalizedValue}`;
370
+ }
371
+ }
372
+
373
+ // For numbers that don't fit expected formats, return the original value
374
+ return value;
375
+ },
376
+
377
+ convertEmptyToNull(value: any): any {
378
+ if (Array.isArray(value)) {
379
+ return value.map((item) => this.convertEmptyToNull(item));
380
+ }
381
+ if (_.isEmpty(value)) return null;
382
+ return value;
383
+ },
384
+
385
+ /**
386
+ * A function that removes invalid elements from an array
387
+ *
388
+ * @param {any[]} array - the input array
389
+ * @return {any[]} the filtered array without invalid elements
390
+ */
391
+ removeInvalidElements(array: any[]): any[] {
392
+ if (!Array.isArray(array)) return array;
393
+ return _.filter(
394
+ array,
395
+ (element) =>
396
+ element !== null &&
397
+ element !== undefined &&
398
+ element !== "" &&
399
+ element !== "undefined" &&
400
+ element !== "null" &&
401
+ !_.isEmpty(element)
402
+ );
403
+ },
404
+
405
+ validateOrNullEmail(email: string): string | null {
406
+ if (!email) return null;
407
+ const emailRegex = /^[\w\-\.]+@([\w-]+\.)+[\w-]{2,}$/;
408
+ return emailRegex.test(email) ? email : null;
409
+ },
410
+
411
+ /**
412
+ * Tries to parse a date from various formats using Luxon with enhanced error reporting.
413
+ * @param {string | number} input The input date as a string or timestamp.
414
+ * @return {string | null} The parsed date in ISO 8601 format or null if parsing failed.
415
+ */
416
+ safeParseDate(input: string | number): string | null {
417
+ const formats = [
418
+ "M/d/yyyy HH:mm:ss", // U.S. style with time
419
+ "d/M/yyyy HH:mm:ss", // Rest of the world style with time
420
+ "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", // ISO 8601 format
421
+ "yyyy-MM-dd'T'HH:mm:ss", // ISO 8601 without milliseconds
422
+ "yyyy-MM-dd HH:mm:ss", // SQL datetime format (common log format)
423
+ "M/d/yyyy", // U.S. style without time
424
+ "d/M/yyyy", // Rest of the world style without time
425
+ "yyyy-MM-dd", // ISO date format
426
+ "dd-MM-yyyy",
427
+ "MM-dd-yyyy",
428
+ "dd/MM/yyyy",
429
+ "MM/dd/yyyy",
430
+ "dd.MM.yyyy",
431
+ "MM.dd.yyyy",
432
+ "yyyy.MM.dd",
433
+ "yyyy/MM/dd",
434
+ "yyyy/MM/dd HH:mm",
435
+ "yyyy-MM-dd HH:mm",
436
+ "M/d/yyyy h:mm:ss tt", // U.S. style with 12-hour clock
437
+ "d/M/yyyy h:mm:ss tt", // Rest of the world style with 12-hour clock
438
+ "h:mm tt", // Time only with 12-hour clock
439
+ "HH:mm:ss", // Time only with 24-hour clock
440
+ "HH:mm", // Time only without seconds, 24-hour clock
441
+ "h:mm tt M/d/yyyy", // 12-hour clock time followed by U.S. style date
442
+ "h:mm tt d/M/yyyy", // 12-hour clock time followed by Rest of the world style date
443
+ "yyyy-MM-dd'T'HH:mm:ss.SSSZ", // ISO 8601 with timezone offset
444
+ "yyyy-MM-dd'T'HH:mm:ssZ", // ISO 8601 without milliseconds but with timezone offset
445
+ "E, dd MMM yyyy HH:mm:ss z", // RFC 2822 format
446
+ "EEEE, MMMM d, yyyy", // Full textual date
447
+ "yyyy-MM-dd'T'HH:mm:ss.SSSXXX", // ISO 8601 with extended timezone offset
448
+ "yyyy-MM-dd'T'HH:mm:ssXXX", // ISO 8601 without milliseconds but with extended timezone offset
449
+ "dd-MMM-yyyy", // Textual month with day and year
450
+ ];
451
+
452
+ // Attempt to parse as a timestamp first if input is a number
453
+ if (typeof input === "number") {
454
+ const dateFromMillis = DateTime.fromMillis(input);
455
+ if (dateFromMillis.isValid) {
456
+ return dateFromMillis.toISO();
457
+ }
458
+ }
459
+
460
+ // Attempt to parse as an ISO string or SQL string
461
+ let date = DateTime.fromISO(String(input));
462
+ if (!date.isValid) date = DateTime.fromSQL(String(input));
463
+
464
+ // Try each custom format if still not valid
465
+ for (const format of formats) {
466
+ if (!date.isValid) {
467
+ date = DateTime.fromFormat(String(input), format);
468
+ }
469
+ }
470
+
471
+ // Return null if no valid date could be parsed
472
+ if (!date.isValid) {
473
+ return null;
474
+ }
475
+
476
+ return date.toISO();
477
+ },
478
+ };
479
+
480
+ /**
481
+ * Deeply converts all properties of an object (or array) to strings.
482
+ * @param data The input data to convert.
483
+ * @returns The data with all its properties converted to strings.
484
+ */
485
+ export const deepAnyToString = (data: any): any => {
486
+ if (Array.isArray(data)) {
487
+ return data.map((item) => deepAnyToString(item));
488
+ } else if (isObject(data)) {
489
+ return Object.keys(data).reduce((acc, key) => {
490
+ acc[key] = deepAnyToString(data[key as keyof typeof data]);
491
+ return acc;
492
+ }, {} as Record<string, any>);
493
+ } else {
494
+ return converterFunctions.anyToString(data);
495
+ }
496
+ };
497
+
498
+ /**
499
+ * Performs a deep conversion of all values in a nested structure to the specified type.
500
+ * Uses a conversion function like anyToString, anyToNumber, etc.
501
+ * @param data The data to convert.
502
+ * @param convertFn The conversion function to apply.
503
+ * @returns The converted data.
504
+ */
505
+ export const deepConvert = <T>(
506
+ data: any,
507
+ convertFn: (value: any) => T
508
+ ): any => {
509
+ if (Array.isArray(data)) {
510
+ return data.map((item) => deepConvert(item, convertFn));
511
+ } else if (isObject(data)) {
512
+ return Object.keys(data).reduce((acc: Record<string, T>, key: string) => {
513
+ acc[key] = deepConvert(data[key as keyof typeof data], convertFn);
514
+ return acc;
515
+ }, {});
516
+ } else {
517
+ return convertFn(data);
518
+ }
519
+ };
520
+
521
+ /**
522
+ * Converts an entire object's properties to different types based on a provided schema.
523
+ * @param obj The object to convert.
524
+ * @param schema A mapping of object keys to conversion functions.
525
+ * @returns The converted object.
526
+ */
527
+ export const convertObjectBySchema = (
528
+ obj: Record<string, any>,
529
+ schema: Record<string, (value: any) => any>
530
+ ): Record<string, any> => {
531
+ return Object.keys(obj).reduce((acc: Record<string, any>, key: string) => {
532
+ const convertFn = schema[key];
533
+ acc[key] = convertFn ? convertFn(obj[key]) : obj[key];
534
+ return acc;
535
+ }, {});
536
+ };
537
+
538
+ type AttributeMappings =
539
+ AppwriteConfig["collections"][number]["importDefs"][number]["attributeMappings"];
540
+
541
+ /**
542
+ * Converts the keys of an object based on a provided attributeMappings.
543
+ * Each key in the object is checked against attributeMappings; if a matching entry is found,
544
+ * the key is renamed to the targetKey specified in attributeMappings.
545
+ *
546
+ * @param obj The object to convert.
547
+ * @param attributeMappings The attributeMappings defining how keys in the object should be converted.
548
+ * @returns The converted object with keys renamed according to attributeMappings.
549
+ */
550
+ export const convertObjectByAttributeMappings = (
551
+ obj: Record<string, any>,
552
+ attributeMappings: AttributeMappings
553
+ ): Record<string, any> => {
554
+ const result: Record<string, any> = {};
555
+
556
+ // Correctly handle [any] notation by mapping or aggregating over all elements or keys
557
+ const resolveValue = (obj: Record<string, any>, path: string): any => {
558
+ const parts = path.split(".");
559
+ let current = obj;
560
+
561
+ for (let i = 0; i < parts.length; i++) {
562
+ if (parts[i] === "[any]") {
563
+ if (Array.isArray(current)) {
564
+ // If current is an array, apply resolution to each item
565
+ return current.map((item) =>
566
+ resolveValue(item, parts.slice(i + 1).join("."))
567
+ );
568
+ } else if (typeof current === "object" && current !== null) {
569
+ // If current is an object, aggregate values from all keys
570
+ return Object.values(current).map((value) =>
571
+ resolveValue(value, parts.slice(i + 1).join("."))
572
+ );
573
+ }
574
+ } else {
575
+ current = current[parts[i]];
576
+ if (current === undefined) return undefined;
577
+ }
578
+ }
579
+ return current;
580
+ };
581
+
582
+ for (const mapping of attributeMappings) {
583
+ if (Array.isArray(mapping.oldKeys)) {
584
+ // Collect and flatten values from multiple oldKeys
585
+ const values = mapping.oldKeys
586
+ .map((oldKey) => resolveValue(obj, oldKey))
587
+ .flat(Infinity);
588
+ result[mapping.targetKey] = values.filter((value) => value !== undefined);
589
+ } else if (mapping.oldKey) {
590
+ // Resolve single oldKey
591
+ const value = resolveValue(obj, mapping.oldKey);
592
+ if (value !== undefined) {
593
+ result[mapping.targetKey] = Array.isArray(value)
594
+ ? value.flat(Infinity)
595
+ : value;
596
+ }
597
+ }
598
+ }
599
+ console.log("Resolved object:", result);
600
+ return result;
601
+ };
602
+
603
+ /**
604
+ * Ensures data conversion without mutating the original input.
605
+ * @param data The data to convert.
606
+ * @param convertFn The conversion function to apply.
607
+ * @returns The converted data.
608
+ */
609
+ export const immutableConvert = <T>(
610
+ data: any,
611
+ convertFn: (value: any) => T
612
+ ): T => {
613
+ const clonedData = cloneDeep(data);
614
+ return convertFn(clonedData);
615
+ };
616
+
617
+ /**
618
+ * Validates a string against a regular expression and returns the string if valid, or null.
619
+ * @param value The string to validate.
620
+ * @param pattern The regex pattern to validate against.
621
+ * @returns The original string if valid, otherwise null.
622
+ */
623
+ export const validateString = (
624
+ value: string,
625
+ pattern: RegExp
626
+ ): string | null => {
627
+ return pattern.test(value) ? value : null;
628
+ };
@@ -0,0 +1,89 @@
1
+ import type {
2
+ AppwriteConfig,
3
+ Attribute,
4
+ RelationshipAttribute,
5
+ } from "./schema.js";
6
+
7
+ // Helper function to categorize collections based on relationship sides
8
+ export const categorizeCollectionByRelationshipSide = (
9
+ attributes: Attribute[]
10
+ ): "parent" | "mixed" | "child" => {
11
+ let hasParent = false;
12
+ let hasChild = false;
13
+
14
+ for (const attr of attributes) {
15
+ if (attr.type === "relationship") {
16
+ if (attr.side === "parent") {
17
+ hasParent = true;
18
+ } else if (attr.side === "child") {
19
+ hasChild = true;
20
+ }
21
+ }
22
+ }
23
+
24
+ if (hasParent && hasChild) return "mixed";
25
+ if (hasParent) return "parent";
26
+ return "child";
27
+ };
28
+
29
+ // Helper function to get all dependencies of a collection
30
+ export const getDependencies = (attributes: Attribute[]): string[] => {
31
+ return attributes
32
+ .filter(
33
+ (attr) =>
34
+ attr.type === "relationship" && attr.relatedCollection !== undefined
35
+ )
36
+ .map((attr) => (attr as RelationshipAttribute).relatedCollection);
37
+ };
38
+
39
+ // Function to sort collections based on dependencies and relationship sides
40
+ export const sortCollections = (
41
+ configCollections: AppwriteConfig["collections"]
42
+ ): AppwriteConfig["collections"] => {
43
+ // Categorize collections based on their relationship sides
44
+ const parentCollections = configCollections.filter(
45
+ ({ attributes }) =>
46
+ categorizeCollectionByRelationshipSide(attributes) === "parent"
47
+ );
48
+ const mixedCollections = configCollections.filter(
49
+ ({ attributes }) =>
50
+ categorizeCollectionByRelationshipSide(attributes) === "mixed"
51
+ );
52
+ const childCollections = configCollections.filter(
53
+ ({ attributes }) =>
54
+ categorizeCollectionByRelationshipSide(attributes) === "child"
55
+ );
56
+
57
+ // Sort mixedCollections to ensure parents are processed before children within the mixed category
58
+ // This might involve more sophisticated logic if you need to order mixed collections based on specific parent-child relationships
59
+ mixedCollections.sort((a, b) => {
60
+ // Example sorting logic for mixed collections; adjust based on your specific needs
61
+ const aDependencies = getDependencies(a.attributes).length;
62
+ const bDependencies = getDependencies(b.attributes).length;
63
+ return aDependencies - bDependencies;
64
+ });
65
+
66
+ // Combine them back into a single array with the desired order
67
+ // Children first because they have no dependencies and parents will create the relationship if it's twoWay
68
+ return [...childCollections, ...parentCollections, ...mixedCollections];
69
+ };
70
+
71
+ // Function to sort attributes within a collection based on relationship sides
72
+ export const sortAttributesByRelationshipSide = (
73
+ attributes: Attribute[]
74
+ ): Attribute[] => {
75
+ // Separate attributes into parent and child based on their relationship side
76
+ const parentAttributes = attributes.filter(
77
+ (attr) => attr.type === "relationship" && attr.side === "parent"
78
+ );
79
+ const childAttributes = attributes.filter(
80
+ (attr) => attr.type === "relationship" && attr.side === "child"
81
+ );
82
+ const otherAttributes = attributes.filter(
83
+ (attr) => attr.type !== "relationship"
84
+ );
85
+
86
+ // Combine them back into a single array with child attributes first, then other attributes, and parent attributes last
87
+ // as parent attributes will create the relationship with the child if needed
88
+ return [...childAttributes, ...otherAttributes, ...parentAttributes];
89
+ };