-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
2560 lines (2239 loc) · 86.2 KB
/
index.js
File metadata and controls
2560 lines (2239 loc) · 86.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/**
* xyOps File Export Action Plugin (c) 2026 Tim Alderweireldt
*
* Exports job input data to CSV, HTML, or JSON file format.
* Supports optional timestamp and unique identifier in filename.
* Cross-platform compatible (Linux, Windows, macOS).
*/
const fs = require('fs');
const path = require('path');
// Dependencies (installed via npm)
const exceljs = require('exceljs');
const PDFDocument = require('pdfkit');
const jsYaml = require('js-yaml');
// Read JSON from STDIN
async function readStdin() {
const chunks = [];
for await (const chunk of process.stdin) {
chunks.push(chunk);
}
return JSON.parse(chunks.join(''));
}
// Generate 8-character unique ID
function generateUID() {
const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
let uid = '';
for (let i = 0; i < 8; i++) {
uid += chars.charAt(Math.floor(Math.random() * chars.length));
}
return uid;
}
// Generate timestamp in YYYYMMDD_HHmmss format
function generateTimestamp() {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
const seconds = String(now.getSeconds()).padStart(2, '0');
return `${year}${month}${day}_${hours}${minutes}${seconds}`;
}
// Flatten nested object into dot-notation keys
function flattenObject(obj, prefix = '', result = {}) {
if (obj === null || obj === undefined) {
result[prefix] = '';
return result;
}
if (typeof obj !== 'object') {
result[prefix] = obj;
return result;
}
if (Array.isArray(obj)) {
if (obj.length === 0) {
result[prefix] = '';
} else {
// Check if array contains objects or primitives
const hasObjects = obj.some(item => typeof item === 'object' && item !== null);
if (hasObjects) {
obj.forEach((item, index) => {
flattenObject(item, prefix ? `${prefix}[${index}]` : `[${index}]`, result);
});
} else {
result[prefix] = obj.join(', ');
}
}
return result;
}
for (const key of Object.keys(obj)) {
const newKey = prefix ? `${prefix}.${key}` : key;
flattenObject(obj[key], newKey, result);
}
return result;
}
// ============================================
// DATA TRANSFORM ENGINE
// ============================================
/**
* Parse YAML transforms configuration
* @param {string} yamlString - YAML configuration string
* @returns {Array} Array of transform steps
*/
function parseTransformsYaml(yamlString) {
if (!yamlString || typeof yamlString !== 'string' || yamlString.trim() === '') {
return [];
}
const config = jsYaml.load(yamlString);
if (!config || !config.transforms) {
return [];
}
if (!Array.isArray(config.transforms)) {
throw new Error('transforms must be an array of transform steps');
}
return config.transforms;
}
/**
* Get nested value from object using dot notation
* @param {Object} obj - Source object
* @param {string} path - Dot-notation path (e.g., 'user.address.city')
* @returns {*} Value at path or undefined
*/
function getNestedValue(obj, path) {
const parts = path.split('.');
let current = obj;
for (const part of parts) {
if (current === null || current === undefined) return undefined;
current = current[part];
}
return current;
}
/**
* Evaluate a simple filter condition
* Supports: ==, !=, >, <, >=, <=, contains, startswith, endswith
* @param {Object} row - Data row to evaluate
* @param {string} condition - Filter condition string
* @returns {boolean} Whether row matches condition
*/
function evaluateCondition(row, condition) {
// Parse condition: "field operator value" or "field operator 'value'"
const operators = ['==', '!=', '>=', '<=', '>', '<', ' contains ', ' startswith ', ' endswith '];
let field, operator, value;
for (const op of operators) {
const idx = condition.indexOf(op);
if (idx !== -1) {
field = condition.substring(0, idx).trim();
operator = op.trim();
value = condition.substring(idx + op.length).trim();
break;
}
}
if (!field || !operator) {
throw new Error(`Invalid filter condition: ${condition}. Expected format: "field operator value"`);
}
// Remove quotes from value if present
if ((value.startsWith("'") && value.endsWith("'")) ||
(value.startsWith('"') && value.endsWith('"'))) {
value = value.slice(1, -1);
}
// Get field value from row (support nested paths)
const fieldValue = getNestedValue(row, field);
// Convert value to appropriate type for comparison
let compareValue = value;
if (value === 'null') compareValue = null;
else if (value === 'true') compareValue = true;
else if (value === 'false') compareValue = false;
else if (!isNaN(Number(value)) && value !== '') compareValue = Number(value);
// Perform comparison
switch (operator) {
case '==':
return fieldValue == compareValue;
case '!=':
return fieldValue != compareValue;
case '>':
return fieldValue > compareValue;
case '<':
return fieldValue < compareValue;
case '>=':
return fieldValue >= compareValue;
case '<=':
return fieldValue <= compareValue;
case 'contains':
return String(fieldValue || '').toLowerCase().includes(String(compareValue).toLowerCase());
case 'startswith':
return String(fieldValue || '').toLowerCase().startsWith(String(compareValue).toLowerCase());
case 'endswith':
return String(fieldValue || '').toLowerCase().endsWith(String(compareValue).toLowerCase());
default:
throw new Error(`Unknown operator: ${operator}`);
}
}
/**
* Apply filter transform - keep rows matching condition
* @param {Array} data - Input data array
* @param {string} condition - Filter condition
* @returns {Array} Filtered data
*/
function transformFilter(data, condition) {
if (!Array.isArray(data)) {
console.error('File Export: filter requires array data, skipping');
return data;
}
const before = data.length;
const result = data.filter(row => {
try {
return evaluateCondition(row, condition);
} catch (e) {
throw new Error(`Filter error: ${e.message}`);
}
});
console.error(`File Export: filter '${condition}' - ${before} rows → ${result.length} rows`);
return result;
}
/**
* Apply select transform - keep only specified fields
* @param {Array|Object} data - Input data
* @param {Array} fields - Fields to keep
* @returns {Array|Object} Data with only selected fields
*/
function transformSelect(data, fields) {
if (!Array.isArray(fields) || fields.length === 0) {
throw new Error('select requires a non-empty array of field names');
}
const selectFields = (obj) => {
const result = {};
for (const field of fields) {
const value = getNestedValue(obj, field);
if (value !== undefined) {
result[field] = value;
}
}
return result;
};
if (Array.isArray(data)) {
console.error(`File Export: select fields [${fields.join(', ')}]`);
return data.map(selectFields);
} else if (typeof data === 'object' && data !== null) {
console.error(`File Export: select fields [${fields.join(', ')}]`);
return selectFields(data);
}
return data;
}
/**
* Apply exclude transform - remove specified fields
* @param {Array|Object} data - Input data
* @param {Array} fields - Fields to remove
* @returns {Array|Object} Data without excluded fields
*/
function transformExclude(data, fields) {
if (!Array.isArray(fields) || fields.length === 0) {
throw new Error('exclude requires a non-empty array of field names');
}
const excludeFields = (obj) => {
const result = { ...obj };
for (const field of fields) {
delete result[field];
}
return result;
};
if (Array.isArray(data)) {
console.error(`File Export: exclude fields [${fields.join(', ')}]`);
return data.map(excludeFields);
} else if (typeof data === 'object' && data !== null) {
console.error(`File Export: exclude fields [${fields.join(', ')}]`);
return excludeFields(data);
}
return data;
}
/**
* Apply rename transform - rename field names
* @param {Array|Object} data - Input data
* @param {Object} mapping - Object with oldName: newName pairs
* @returns {Array|Object} Data with renamed fields
*/
function transformRename(data, mapping) {
if (!mapping || typeof mapping !== 'object') {
throw new Error('rename requires an object with field mappings');
}
const renameFields = (obj) => {
const result = {};
for (const [key, value] of Object.entries(obj)) {
const newKey = mapping[key] || key;
result[newKey] = value;
}
return result;
};
const renames = Object.entries(mapping).map(([k, v]) => `${k}→${v}`).join(', ');
console.error(`File Export: rename fields [${renames}]`);
if (Array.isArray(data)) {
return data.map(renameFields);
} else if (typeof data === 'object' && data !== null) {
return renameFields(data);
}
return data;
}
/**
* Apply sort transform - sort data by field
* @param {Array} data - Input data array
* @param {Object|string} sortConfig - Sort configuration {field, order} or "field desc"
* @returns {Array} Sorted data
*/
function transformSort(data, sortConfig) {
if (!Array.isArray(data)) {
console.error('File Export: sort requires array data, skipping');
return data;
}
let field, order = 'asc';
if (typeof sortConfig === 'string') {
// Parse "field desc" or "field asc" or just "field"
const parts = sortConfig.trim().split(/\s+/);
field = parts[0];
if (parts[1] && ['desc', 'asc'].includes(parts[1].toLowerCase())) {
order = parts[1].toLowerCase();
}
} else if (typeof sortConfig === 'object') {
field = sortConfig.field;
order = sortConfig.order || 'asc';
}
if (!field) {
throw new Error('sort requires a field name');
}
console.error(`File Export: sort by '${field}' ${order}`);
return [...data].sort((a, b) => {
const aVal = getNestedValue(a, field);
const bVal = getNestedValue(b, field);
// Handle nulls/undefined
if (aVal === null || aVal === undefined) return order === 'asc' ? 1 : -1;
if (bVal === null || bVal === undefined) return order === 'asc' ? -1 : 1;
// Compare
let result;
if (typeof aVal === 'number' && typeof bVal === 'number') {
result = aVal - bVal;
} else {
result = String(aVal).localeCompare(String(bVal));
}
return order === 'desc' ? -result : result;
});
}
/**
* Apply format transform - format field values
* @param {Array|Object} data - Input data
* @param {Object} formatConfig - Format configuration {fieldName: {type, pattern}}
* @returns {Array|Object} Data with formatted fields
*/
function transformFormat(data, formatConfig) {
if (!formatConfig || typeof formatConfig !== 'object') {
throw new Error('format requires a configuration object');
}
const formatValue = (value, config) => {
if (value === null || value === undefined) return value;
const type = config.type || 'string';
switch (type) {
case 'date': {
// Format date according to pattern
const pattern = config.pattern || 'YYYY-MM-DD';
let date;
if (value instanceof Date) {
date = value;
} else if (typeof value === 'string' || typeof value === 'number') {
date = new Date(value);
} else {
return value;
}
if (isNaN(date.getTime())) return value;
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
return pattern
.replace('YYYY', year)
.replace('MM', month)
.replace('DD', day)
.replace('HH', hours)
.replace('mm', minutes)
.replace('ss', seconds);
}
case 'number': {
const num = Number(value);
if (isNaN(num)) return value;
const decimals = config.decimals !== undefined ? config.decimals : 2;
const thousands = config.thousands !== false;
let formatted = num.toFixed(decimals);
if (thousands) {
const parts = formatted.split('.');
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
formatted = parts.join('.');
}
if (config.prefix) formatted = config.prefix + formatted;
if (config.suffix) formatted = formatted + config.suffix;
return formatted;
}
case 'uppercase':
return String(value).toUpperCase();
case 'lowercase':
return String(value).toLowerCase();
case 'trim':
return String(value).trim();
case 'boolean': {
const trueVal = config.true || 'Yes';
const falseVal = config.false || 'No';
return value ? trueVal : falseVal;
}
case 'replace': {
if (!config.search) return value;
const search = new RegExp(config.search, config.flags || 'g');
return String(value).replace(search, config.replacement || '');
}
case 'default': {
// Replace null/empty with default value
if (value === null || value === undefined || value === '') {
return config.value || 'N/A';
}
return value;
}
default:
return value;
}
};
const formatFields = (obj) => {
const result = { ...obj };
for (const [field, config] of Object.entries(formatConfig)) {
if (field in result) {
result[field] = formatValue(result[field], config);
}
}
return result;
};
const fields = Object.keys(formatConfig).join(', ');
console.error(`File Export: format fields [${fields}]`);
if (Array.isArray(data)) {
return data.map(formatFields);
} else if (typeof data === 'object' && data !== null) {
return formatFields(data);
}
return data;
}
/**
* Apply limit transform - keep only first N rows
* @param {Array} data - Input data array
* @param {number} count - Number of rows to keep
* @returns {Array} Limited data
*/
function transformLimit(data, count) {
if (!Array.isArray(data)) {
console.error('File Export: limit requires array data, skipping');
return data;
}
const n = parseInt(count, 10);
if (isNaN(n) || n < 0) {
throw new Error('limit requires a positive number');
}
console.error(`File Export: limit to ${n} rows (was ${data.length})`);
return data.slice(0, n);
}
/**
* Apply skip transform - skip first N rows
* @param {Array} data - Input data array
* @param {number} count - Number of rows to skip
* @returns {Array} Data with skipped rows
*/
function transformSkip(data, count) {
if (!Array.isArray(data)) {
console.error('File Export: skip requires array data, skipping');
return data;
}
const n = parseInt(count, 10);
if (isNaN(n) || n < 0) {
throw new Error('skip requires a positive number');
}
console.error(`File Export: skip ${n} rows (was ${data.length}, now ${Math.max(0, data.length - n)})`);
return data.slice(n);
}
/**
* Apply reverse transform - reverse row order
* @param {Array} data - Input data array
* @returns {Array} Reversed data
*/
function transformReverse(data) {
if (!Array.isArray(data)) {
console.error('File Export: reverse requires array data, skipping');
return data;
}
console.error(`File Export: reverse ${data.length} rows`);
return [...data].reverse();
}
/**
* Apply distinct transform - remove duplicate rows
* @param {Array} data - Input data array
* @param {string|Array} fields - Field(s) to check for uniqueness, or null for entire row
* @returns {Array} Deduplicated data
*/
function transformDistinct(data, fields) {
if (!Array.isArray(data)) {
console.error('File Export: distinct requires array data, skipping');
return data;
}
const before = data.length;
const seen = new Set();
const result = data.filter(row => {
let key;
if (fields) {
// Distinct by specific field(s)
const fieldList = Array.isArray(fields) ? fields : [fields];
key = fieldList.map(f => JSON.stringify(getNestedValue(row, f))).join('|');
} else {
// Distinct by entire row
key = JSON.stringify(row);
}
if (seen.has(key)) {
return false;
}
seen.add(key);
return true;
});
const fieldDesc = fields ? (Array.isArray(fields) ? fields.join(', ') : fields) : 'all fields';
console.error(`File Export: distinct by [${fieldDesc}] - ${before} rows → ${result.length} rows`);
return result;
}
/**
* Apply flatten transform - flatten nested objects to dot-notation
* @param {Array|Object} data - Input data
* @param {string} separator - Separator for nested keys (default: '.')
* @returns {Array|Object} Flattened data
*/
function transformFlatten(data, config) {
const separator = (typeof config === 'object' ? config.separator : config) || '.';
const flattenObj = (obj, prefix = '', result = {}) => {
if (obj === null || obj === undefined) {
if (prefix) result[prefix] = obj;
return result;
}
if (typeof obj !== 'object' || obj instanceof Date) {
if (prefix) result[prefix] = obj;
return result;
}
if (Array.isArray(obj)) {
if (prefix) result[prefix] = obj;
return result;
}
for (const [key, value] of Object.entries(obj)) {
const newKey = prefix ? `${prefix}${separator}${key}` : key;
if (typeof value === 'object' && value !== null && !Array.isArray(value) && !(value instanceof Date)) {
flattenObj(value, newKey, result);
} else {
result[newKey] = value;
}
}
return result;
};
console.error(`File Export: flatten with separator '${separator}'`);
if (Array.isArray(data)) {
return data.map(row => flattenObj(row));
} else if (typeof data === 'object' && data !== null) {
return flattenObj(data);
}
return data;
}
/**
* Apply compute transform - add calculated fields
* @param {Array|Object} data - Input data
* @param {Object} computations - Field definitions {newField: expression}
* @returns {Array|Object} Data with computed fields
*/
function transformCompute(data, computations) {
if (!computations || typeof computations !== 'object') {
throw new Error('compute requires an object with field definitions');
}
const computeValue = (row, expression) => {
// Replace field references with actual values
// Support: field names, basic math (+, -, *, /), string concat
let expr = expression;
// Find all field references (words that aren't numbers or operators)
const fieldRefs = expr.match(/[a-zA-Z_][a-zA-Z0-9_.]*(?![\(])/g) || [];
const uniqueFields = [...new Set(fieldRefs)];
// Create a safe evaluation context
const context = {};
for (const field of uniqueFields) {
const value = getNestedValue(row, field);
// Sanitize field name for use as variable
const safeField = field.replace(/\./g, '_');
context[safeField] = value;
// Replace in expression
expr = expr.replace(new RegExp(`\\b${field.replace('.', '\\.')}\\b`, 'g'), safeField);
}
try {
// Build function with context variables
const vars = Object.keys(context);
const vals = Object.values(context);
// eslint-disable-next-line no-new-func
const fn = new Function(...vars, `return ${expr}`);
return fn(...vals);
} catch (e) {
console.error(`File Export: compute error for '${expression}': ${e.message}`);
return null;
}
};
const addComputed = (row) => {
const result = { ...row };
for (const [newField, expression] of Object.entries(computations)) {
result[newField] = computeValue(row, expression);
}
return result;
};
const fields = Object.keys(computations).join(', ');
console.error(`File Export: compute fields [${fields}]`);
if (Array.isArray(data)) {
return data.map(addComputed);
} else if (typeof data === 'object' && data !== null) {
return addComputed(data);
}
return data;
}
/**
* Apply concat transform - combine fields into new field
* @param {Array|Object} data - Input data
* @param {Object} config - {field: "newFieldName", fields: [...], separator: " "}
* @returns {Array|Object} Data with concatenated field
*/
function transformConcat(data, config) {
if (!config || !config.field || !config.fields) {
throw new Error('concat requires {field: "name", fields: [...]}');
}
const { field, fields, separator = ' ' } = config;
const concatFields = (row) => {
const result = { ...row };
const values = fields.map(f => {
const val = getNestedValue(row, f);
return val !== null && val !== undefined ? String(val) : '';
});
result[field] = values.filter(v => v !== '').join(separator);
return result;
};
console.error(`File Export: concat [${fields.join(', ')}] → '${field}'`);
if (Array.isArray(data)) {
return data.map(concatFields);
} else if (typeof data === 'object' && data !== null) {
return concatFields(data);
}
return data;
}
/**
* Apply split transform - split field into multiple fields
* @param {Array|Object} data - Input data
* @param {Object} config - {field: "source", separator: ",", into: ["field1", "field2"]}
* @returns {Array|Object} Data with split fields
*/
function transformSplit(data, config) {
if (!config || !config.field || !config.into) {
throw new Error('split requires {field: "source", into: [...]}');
}
const { field, separator = ',', into } = config;
const splitField = (row) => {
const result = { ...row };
const value = getNestedValue(row, field);
const parts = value ? String(value).split(separator) : [];
into.forEach((newField, index) => {
result[newField] = parts[index] !== undefined ? parts[index].trim() : '';
});
return result;
};
console.error(`File Export: split '${field}' by '${separator}' → [${into.join(', ')}]`);
if (Array.isArray(data)) {
return data.map(splitField);
} else if (typeof data === 'object' && data !== null) {
return splitField(data);
}
return data;
}
/**
* Apply lookup transform - map values using a lookup table
* @param {Array|Object} data - Input data
* @param {Object} config - {field: "fieldName", map: {value: label}, default: "Unknown"}
* @returns {Array|Object} Data with mapped values
*/
function transformLookup(data, config) {
if (!config || !config.field || !config.map) {
throw new Error('lookup requires {field: "name", map: {...}}');
}
const { field, map, default: defaultValue = null, target } = config;
const targetField = target || field; // Can map to a different field
const lookupValue = (row) => {
const result = { ...row };
const value = getNestedValue(row, field);
const key = String(value);
if (key in map) {
result[targetField] = map[key];
} else if (defaultValue !== null) {
result[targetField] = defaultValue;
}
return result;
};
const mapCount = Object.keys(map).length;
console.error(`File Export: lookup '${field}' with ${mapCount} mappings`);
if (Array.isArray(data)) {
return data.map(lookupValue);
} else if (typeof data === 'object' && data !== null) {
return lookupValue(data);
}
return data;
}
/**
* Apply group transform - group by field with aggregations
* @param {Array} data - Input data array
* @param {Object} config - {by: "field", aggregations: {newField: {op: "sum", field: "amount"}}}
* @returns {Array} Grouped and aggregated data
*/
function transformGroup(data, config) {
if (!Array.isArray(data)) {
console.error('File Export: group requires array data, skipping');
return data;
}
if (!config || !config.by) {
throw new Error('group requires {by: "field", aggregations: {...}}');
}
const { by, aggregations = {} } = config;
const groupFields = Array.isArray(by) ? by : [by];
// Group data
const groups = new Map();
data.forEach(row => {
const key = groupFields.map(f => JSON.stringify(getNestedValue(row, f))).join('|');
if (!groups.has(key)) {
groups.set(key, { key: {}, rows: [] });
groupFields.forEach(f => {
groups.get(key).key[f] = getNestedValue(row, f);
});
}
groups.get(key).rows.push(row);
});
// Apply aggregations
const result = [];
groups.forEach(group => {
const row = { ...group.key };
// Add count by default
row._count = group.rows.length;
// Apply custom aggregations
for (const [newField, aggConfig] of Object.entries(aggregations)) {
const { op, field } = aggConfig;
const values = group.rows.map(r => getNestedValue(r, field)).filter(v => v !== null && v !== undefined);
const numValues = values.map(Number).filter(n => !isNaN(n));
switch (op) {
case 'sum':
row[newField] = numValues.reduce((a, b) => a + b, 0);
break;
case 'avg':
case 'average':
row[newField] = numValues.length > 0 ? numValues.reduce((a, b) => a + b, 0) / numValues.length : 0;
break;
case 'min':
row[newField] = numValues.length > 0 ? Math.min(...numValues) : null;
break;
case 'max':
row[newField] = numValues.length > 0 ? Math.max(...numValues) : null;
break;
case 'count':
row[newField] = values.length;
break;
case 'first':
row[newField] = values[0];
break;
case 'last':
row[newField] = values[values.length - 1];
break;
case 'list':
row[newField] = values.join(', ');
break;
default:
console.error(`File Export: unknown aggregation '${op}'`);
}
}
result.push(row);
});
const aggCount = Object.keys(aggregations).length;
console.error(`File Export: group by [${groupFields.join(', ')}] with ${aggCount} aggregations - ${data.length} rows → ${result.length} groups`);
return result;
}
/**
* Apply summarize transform - add summary row with totals
* @param {Array} data - Input data array
* @param {Object} config - {fields: {fieldName: "sum|avg|count|min|max"}, label: {field: "value"}}
* @returns {Array} Data with summary row appended
*/
function transformSummarize(data, config) {
if (!Array.isArray(data)) {
console.error('File Export: summarize requires array data, skipping');
return data;
}
if (!config || !config.fields) {
throw new Error('summarize requires {fields: {fieldName: "operation"}}');
}
const { fields, label = {} } = config;
const summary = {};
// Set label field(s)
for (const [field, value] of Object.entries(label)) {
summary[field] = value;
}
// Calculate summaries
for (const [field, op] of Object.entries(fields)) {
const values = data.map(r => getNestedValue(r, field)).filter(v => v !== null && v !== undefined);
const numValues = values.map(Number).filter(n => !isNaN(n));
switch (op) {
case 'sum':
summary[field] = numValues.reduce((a, b) => a + b, 0);
break;
case 'avg':
case 'average':
summary[field] = numValues.length > 0 ? numValues.reduce((a, b) => a + b, 0) / numValues.length : 0;
break;
case 'min':
summary[field] = numValues.length > 0 ? Math.min(...numValues) : null;
break;
case 'max':
summary[field] = numValues.length > 0 ? Math.max(...numValues) : null;
break;
case 'count':
summary[field] = values.length;
break;
default:
console.error(`File Export: unknown summary operation '${op}'`);
}
}
console.error(`File Export: summarize ${Object.keys(fields).length} fields`);
return [...data, summary];
}
/**
* Apply truncate transform - limit string length
* @param {Array|Object} data - Input data
* @param {Object} config - {field: length} or {field: {length: N, suffix: "..."}}
* @returns {Array|Object} Data with truncated strings
*/
function transformTruncate(data, config) {
if (!config || typeof config !== 'object') {
throw new Error('truncate requires {field: length} or {field: {length: N}}');
}
const truncateFields = (row) => {
const result = { ...row };
for (const [field, settings] of Object.entries(config)) {
if (!(field in result)) continue;
let length, suffix;
if (typeof settings === 'number') {
length = settings;
suffix = '...';
} else {
length = settings.length || 50;
suffix = settings.suffix !== undefined ? settings.suffix : '...';
}
const value = result[field];
if (typeof value === 'string' && value.length > length) {
result[field] = value.substring(0, length - suffix.length) + suffix;
}
}
return result;
};
const fields = Object.keys(config).join(', ');
console.error(`File Export: truncate fields [${fields}]`);
if (Array.isArray(data)) {
return data.map(truncateFields);
} else if (typeof data === 'object' && data !== null) {
return truncateFields(data);
}
return data;
}
/**
* Apply pad transform - pad strings to fixed width
* @param {Array|Object} data - Input data
* @param {Object} config - {field: {length: N, char: " ", side: "left|right"}}
* @returns {Array|Object} Data with padded strings
*/
function transformPad(data, config) {
if (!config || typeof config !== 'object') {
throw new Error('pad requires {field: {length: N}}');
}
const padFields = (row) => {
const result = { ...row };
for (const [field, settings] of Object.entries(config)) {
if (!(field in result)) continue;
const length = settings.length || 10;
const char = settings.char || ' ';
const side = settings.side || 'left';
let value = String(result[field] ?? '');
if (side === 'left') {
value = value.padStart(length, char);