-
Notifications
You must be signed in to change notification settings - Fork 36
/
index.js
2301 lines (2186 loc) · 91.6 KB
/
index.js
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
'use strict';
import { Util } from './util/util.js';
import auth from './util/auth.js';
import File from './util/file.js';
import config from './util/config.js';
import Init from './util/init.js';
import InitGit from './util/init.git.js';
import Cli from './util/cli.js';
import DevOps from './util/devops.js';
import BuHelper from './util/businessUnit.js';
import Builder from './Builder.js';
import Deployer from './Deployer.js';
import MetadataTypeInfo from './MetadataTypeInfo.js';
import MetadataTypeDefinitions from './MetadataTypeDefinitions.js';
import Retriever from './Retriever.js';
import cache from './util/cache.js';
import ReplaceContentBlockReference from './util/replaceContentBlockReference.js';
import pLimit from 'p-limit';
import path from 'node:path';
import { confirm } from '@inquirer/prompts';
/**
* @typedef {import('../types/mcdev.d.js').BuObject} BuObject
* @typedef {import('../types/mcdev.d.js').CodeExtract} CodeExtract
* @typedef {import('../types/mcdev.d.js').CodeExtractItem} CodeExtractItem
* @typedef {import('../types/mcdev.d.js').DeltaPkgItem} DeltaPkgItem
* @typedef {import('../types/mcdev.d.js').Mcdevrc} Mcdevrc
* @typedef {import('../types/mcdev.d.js').MetadataTypeItem} MetadataTypeItem
* @typedef {import('../types/mcdev.d.js').MetadataTypeItemDiff} MetadataTypeItemDiff
* @typedef {import('../types/mcdev.d.js').MetadataTypeItemObj} MetadataTypeItemObj
* @typedef {import('../types/mcdev.d.js').MetadataTypeMap} MetadataTypeMap
* @typedef {import('../types/mcdev.d.js').MetadataTypeMapObj} MetadataTypeMapObj
* @typedef {import('../types/mcdev.d.js').MultiMetadataTypeList} MultiMetadataTypeList
* @typedef {import('../types/mcdev.d.js').MultiMetadataTypeMap} MultiMetadataTypeMap
* @typedef {import('../types/mcdev.d.js').SkipInteraction} SkipInteraction
* @typedef {import('../types/mcdev.d.js').SoapRequestParams} SoapRequestParams
* @typedef {import('../types/mcdev.d.js').TemplateMap} TemplateMap
* @typedef {import('../types/mcdev.d.js').TypeKeyCombo} TypeKeyCombo
* @typedef {import('../types/mcdev.d.js').ExplainType} ExplainType
* @typedef {import('../types/mcdev.d.js').ContentBlockConversionTypes} ContentBlockConversionTypes
*/
/**
* main class
*/
class Mcdev {
/**
* @returns {string} current version of mcdev
*/
static version() {
console.log('mcdev v' + Util.packageJsonMcdev.version); // eslint-disable-line no-console
return Util.packageJsonMcdev.version;
}
/**
* helper method to use unattended mode when including mcdev as a package
*
* @param {SkipInteraction} [skipInteraction] signals what to insert automatically for things usually asked via wizard
* @returns {void}
*/
static setSkipInteraction(skipInteraction) {
Util.skipInteraction = skipInteraction;
}
/**
* configures what is displayed in the console
*
* @param {object} argv list of command line parameters given by user
* @param {boolean} [argv.silent] only errors printed to CLI
* @param {boolean} [argv.verbose] chatty user CLI output
* @param {boolean} [argv.debug] enables developer output & features
* @returns {void}
*/
static setLoggingLevel(argv) {
Util.setLoggingLevel(argv);
}
/**
* allows setting system wide / command related options
*
* @param {object} argv list of command line parameters given by user
* @returns {void}
*/
static setOptions(argv) {
const knownOptions = [
'api',
'changeKeyField',
'changeKeyValue',
'commitHistory',
'dependencies',
'errorLog',
'execute',
'filter',
'fixShared',
'format',
'fromRetrieve',
'ignoreFolder',
'ignoreSfFields',
'json',
'keySuffix',
'like',
'matchName',
'noLogColors',
'noLogFile',
'noUpdate',
'autoMidSuffix',
'publish',
'referenceFrom',
'referenceTo',
'refresh',
'retrieve',
'schedule',
'skipDeploy',
'skipInteraction',
'skipRetrieve',
'skipStatusCheck',
'skipValidation',
'validate',
'_runningTest',
'_welcomeMessageShown',
];
for (const option of knownOptions) {
if (argv[option] !== undefined) {
Util.OPTIONS[option] = argv[option];
}
}
// set logging level
const loggingOptions = ['silent', 'verbose', 'debug'];
for (const option of loggingOptions) {
if (argv[option] !== undefined) {
this.setLoggingLevel(argv);
break;
}
}
// set skip interaction
if (argv.skipInteraction !== undefined) {
this.setSkipInteraction(argv.skipInteraction);
}
}
/**
* handler for 'mcdev createDeltaPkg
*
* @param {object} argv yargs parameters
* @param {string} [argv.range] git commit range
into deploy directory
* @param {string} [argv.filter] filter file paths that start with any
* @param {number} [argv.commitHistory] filter file paths that start with any
* @param {DeltaPkgItem[]} [argv.diffArr] list of files to include in delta package (skips git diff when provided)
* @returns {Promise.<DeltaPkgItem[]>} list of changed items
*/
static async createDeltaPkg(argv) {
Util.startLogger();
Util.logger.info('Create Delta Package ::');
const properties = await config.getProperties();
if (!(await config.checkProperties(properties))) {
return null;
}
try {
return await (argv.filter
? // get source market and source BU from config
DevOps.getDeltaList(properties, argv.range, true, argv.filter, argv.commitHistory)
: // If no custom filter was provided, use deployment marketLists & templating
DevOps.buildDeltaDefinitions(
properties,
argv.range,
argv.diffArr,
argv.commitHistory
));
} catch (ex) {
Util.logger.error(ex.message);
}
}
/**
* @returns {Promise} .
*/
static async selectTypes() {
Util.startLogger();
const properties = await config.getProperties();
if (!(await config.checkProperties(properties))) {
return null;
}
await Cli.selectTypes(properties);
}
/**
* @returns {ExplainType[]} list of supported types with their apiNames
*/
static explainTypes() {
return Cli.explainTypes();
}
/**
* @returns {Promise.<boolean>} success flag
*/
static async upgrade() {
Util.startLogger();
const properties = await config.getProperties();
if (!properties) {
Util.logger.error('No config found. Please run mcdev init');
return false;
}
if ((await InitGit.initGitRepo()).status === 'error') {
return false;
}
return Init.upgradeProject(properties, false);
}
/**
* helper to show an off-the-logs message to users
*/
static #welcomeMessage() {
if (Util.OPTIONS._welcomeMessageShown) {
// ensure we don't spam the user in case methods are called multiple times
return;
}
Util.OPTIONS._welcomeMessageShown = true;
const color = Util.isRunViaVSCodeExtension
? { reset: '', bgWhite: '', fgBlue: '' }
: Util.color;
/* eslint-disable no-console */
if (process.env['USERDNSDOMAIN'] === 'DIR.SVC.ACCENTURE.COM') {
// Accenture internal message
console.log(
`\n` +
` Thank you for using Accenture SFMC DevTools on your Accenture laptop!\n` +
` We are trying to understand who is using mcdev across the globe and would therefore appreciate it if you left a message\n` +
` in our Accenture Teams channel ${color.bgWhite}telling us about your journey with mcdev${color.reset}: ${color.fgBlue}https://go.accenture.com/mcdevTeams${color.reset}.\n` +
`\n` +
` For any questions or concerns, please feel free to create a ticket in GitHub: ${color.fgBlue}https://bit.ly/mcdev-support${color.reset}.\n`
);
} else {
// external message
console.log(
`\n` +
` Thank you for using Accenture SFMC DevTools!\n` +
`\n` +
` For any questions or concerns, please feel free to create a ticket in GitHub: ${color.fgBlue}https://bit.ly/mcdev-support${color.reset}.\n`
);
}
/* eslint-enable no-console */
}
/**
* Retrieve all metadata from the specified business unit into the local file system.
*
* @param {string} businessUnit references credentials from properties.json
* @param {string[] | TypeKeyCombo} [selectedTypesArr] limit retrieval to given metadata type
* @param {string[]} [keys] limit retrieval to given metadata key
* @param {boolean} [changelogOnly] skip saving, only create json in memory
* @returns {Promise.<object>} -
*/
static async retrieve(businessUnit, selectedTypesArr, keys, changelogOnly) {
this.#welcomeMessage();
console.time('Time'); // eslint-disable-line no-console
Util.startLogger();
Util.logger.info('mcdev:: Retrieve');
const properties = await config.getProperties();
if (!(await config.checkProperties(properties))) {
// return null here to avoid seeing 2 error messages for the same issue
return null;
}
// assume a list was passed in and check each entry's validity
if (selectedTypesArr) {
for (const selectedType of Array.isArray(selectedTypesArr)
? selectedTypesArr
: Object.keys(selectedTypesArr)) {
if (!Util._isValidType(selectedType)) {
return;
}
}
}
const resultsObj = {};
if (businessUnit === '*') {
Util.logger.info(':: Retrieving all BUs for all credentials');
let counter_credTotal = 0;
for (const cred in properties.credentials) {
Util.logger.info(`:: Retrieving all BUs for ${cred}`);
let counter_credBu = 0;
for (const bu in properties.credentials[cred].businessUnits) {
resultsObj[`${cred}/${bu}`] = await this.#retrieveBU(
cred,
bu,
selectedTypesArr,
keys
);
counter_credBu++;
Util.startLogger(true);
}
counter_credTotal += counter_credBu;
Util.logger.info(`:: ${counter_credBu} BUs of ${cred}\n`);
}
const credentialCount = Object.keys(properties.credentials).length;
Util.logger.info(
`:: Done for ${counter_credTotal} BUs of ${credentialCount} credential${
credentialCount === 1 ? '' : 's'
} in total\n`
);
} else {
let [cred, bu] = businessUnit ? businessUnit.split('/') : [null, null];
// to allow all-BU via user selection we need to run this here already
if (
properties.credentials &&
(!properties.credentials[cred] ||
(bu !== '*' && !properties.credentials[cred].businessUnits[bu]))
) {
const buObject = await Cli.getCredentialObject(
properties,
cred === null ? null : cred + '/' + bu,
null,
true
);
if (buObject === null) {
return;
} else {
cred = buObject.credential;
bu = buObject.businessUnit;
}
}
if (bu === '*' && properties.credentials && properties.credentials[cred]) {
Util.logger.info(`:: Retrieving all BUs for ${cred}`);
let counter_credBu = 0;
for (const bu in properties.credentials[cred].businessUnits) {
resultsObj[`${cred}/${bu}`] = await this.#retrieveBU(
cred,
bu,
selectedTypesArr,
keys
);
counter_credBu++;
Util.startLogger(true);
}
Util.logger.info(`:: Done for ${counter_credBu} BUs of ${cred}\n`);
} else {
// retrieve a single BU; return
const retrieveChangelog = await this.#retrieveBU(
cred,
bu,
selectedTypesArr,
keys,
changelogOnly
);
if (changelogOnly) {
console.timeEnd('Time'); // eslint-disable-line no-console
return retrieveChangelog;
} else {
resultsObj[`${cred}/${bu}`] = retrieveChangelog;
}
Util.logger.info(`:: Done\n`);
}
}
// merge all results into one object
for (const credBu in resultsObj) {
for (const type in resultsObj[credBu]) {
const base = resultsObj[credBu][type][0];
for (let i = 1; i < resultsObj[credBu][type].length; i++) {
// merge all items into the first array
Object.assign(base, resultsObj[credBu][type][i]);
}
resultsObj[credBu][type] = resultsObj[credBu][type][0];
}
}
console.timeEnd('Time'); // eslint-disable-line no-console
return resultsObj;
}
/**
* helper for {@link Mcdev.retrieve}
*
* @param {string} cred name of Credential
* @param {string} bu name of BU
* @param {string[] | TypeKeyCombo} [selectedTypesArr] limit retrieval to given metadata type/subtype
* @param {string[]} [keys] limit retrieval to given metadata key
* @param {boolean} [changelogOnly] skip saving, only create json in memory
* @returns {Promise.<object>} ensure that BUs are worked on sequentially
*/
static async #retrieveBU(cred, bu, selectedTypesArr, keys, changelogOnly) {
// ensure changes to the selectedTypesArr on one BU do not affect other BUs called in the same go
selectedTypesArr = structuredClone(selectedTypesArr);
const properties = await config.getProperties();
if (!(await config.checkProperties(properties))) {
return null;
}
const buObject = await Cli.getCredentialObject(
properties,
cred === null ? null : cred + '/' + bu,
null,
true
);
if (buObject !== null) {
cache.initCache(buObject);
cred = buObject.credential;
bu = buObject.businessUnit;
// clean up old folders after types were renamed
// TODO: Remove renamedTypes-logic 6 months after version 5 release
const renamedTypes = {
attributeSet: 'setDefinition',
emailSend: 'emailSendDefinition',
event: 'eventDefinition',
fileLocation: 'ftpLocation',
journey: 'interaction',
triggeredSend: 'triggeredSendDefinition',
user: 'accountUser',
};
Util.logger.info('');
Util.logger.info(`:: Retrieving ${cred}/${bu}`);
const retrieveTypesArr = [];
if (selectedTypesArr) {
for (const selectedType of Array.isArray(selectedTypesArr)
? selectedTypesArr
: Object.keys(selectedTypesArr)) {
const { type, subType } = Util.getTypeAndSubType(selectedType);
const removePathArr = [properties.directories.retrieve, cred, bu, type];
if (
type &&
subType &&
MetadataTypeInfo[type] &&
MetadataTypeDefinitions[type].subTypes.includes(subType)
) {
// Clear output folder structure for selected sub-type
removePathArr.push(subType);
retrieveTypesArr.push(selectedType);
} else if (type && MetadataTypeInfo[type]) {
// Clear output folder structure for selected type
retrieveTypesArr.push(type);
}
const areKeySet = Array.isArray(selectedTypesArr)
? keys
: Object.values(selectedTypesArr).filter(Boolean).length;
if (!areKeySet) {
// dont delete directories if we are just re-retrieving a single file
await File.remove(File.normalizePath(removePathArr));
// clean up old folders after types were renamed
// TODO: Remove this with version 5.0.0
if (renamedTypes[type]) {
await File.remove(
File.normalizePath([
properties.directories.retrieve,
cred,
bu,
renamedTypes[type],
])
);
}
}
}
}
if (!retrieveTypesArr.length) {
// assume no type was given and config settings are used instead:
// Clear output folder structure
await File.remove(File.normalizePath([properties.directories.retrieve, cred, bu]));
// removes subtypes and removes duplicates
retrieveTypesArr.push(
...new Set(properties.metaDataTypes.retrieve.map((type) => type.split('-')[0]))
);
for (const selectedType of retrieveTypesArr) {
const test = Util._isValidType(selectedType);
if (!test) {
Util.logger.error(
`Please remove the type ${selectedType} from your ${Util.configFileName}`
);
return;
}
}
}
const retriever = new Retriever(properties, buObject);
try {
// await is required or the calls end up conflicting
const retrieveChangelog = await retriever.retrieve(
retrieveTypesArr,
Array.isArray(selectedTypesArr) ? keys : selectedTypesArr,
null,
changelogOnly
);
return retrieveChangelog;
} catch (ex) {
Util.logger.errorStack(ex, 'mcdev.retrieve failed');
}
}
}
/**
* Deploys all metadata located in the 'deploy' directory to the specified business unit
*
* @param {string} businessUnit references credentials from properties.json
* @param {string[] | TypeKeyCombo} [selectedTypesArr] limit deployment to given metadata type
* @param {string[]} [keyArr] limit deployment to given metadata keys
* @returns {Promise.<Object.<string, MultiMetadataTypeMap>>} deployed metadata per BU (first key: bu name, second key: metadata type)
*/
static async deploy(businessUnit, selectedTypesArr, keyArr) {
this.#welcomeMessage();
console.time('Time'); // eslint-disable-line no-console
Util.startLogger();
const deployResult = await Deployer.deploy(businessUnit, selectedTypesArr, keyArr);
console.timeEnd('Time'); // eslint-disable-line no-console
return deployResult;
}
/**
* Creates template file for properties.json
*
* @param {string} [credentialsName] identifying name of the installed package / project
* @returns {Promise.<void>} -
*/
static async initProject(credentialsName) {
Util.startLogger();
Util.logger.info('mcdev:: Setting up project');
const properties = await config.getProperties(!!credentialsName, true);
try {
await Init.initProject(properties, credentialsName);
} catch (ex) {
Util.logger.error(ex.message);
}
}
/**
* Clones an existing project from git repository and installs it
*
* @returns {Promise.<void>} -
*/
static async joinProject() {
Util.startLogger();
Util.logger.info('mcdev:: Joining an existing project');
try {
await Init.joinProject();
} catch (ex) {
Util.logger.error(ex.message);
}
}
/**
* Refreshes BU names and ID's from MC instance
*
* @param {string} credentialsName identifying name of the installed package / project
* @returns {Promise.<void>} -
*/
static async findBUs(credentialsName) {
Util.startLogger();
Util.logger.info('mcdev:: Load BUs');
const properties = await config.getProperties();
if (!(await config.checkProperties(properties))) {
return null;
}
const buObject = await Cli.getCredentialObject(properties, credentialsName, true);
if (buObject !== null) {
BuHelper.refreshBUProperties(properties, buObject.credential);
}
}
/**
* Creates docs for supported metadata types in Markdown and/or HTML format
*
* @param {string} businessUnit references credentials from properties.json
* @param {string} type metadata type
* @returns {Promise.<void>} -
*/
static async document(businessUnit, type) {
Util.startLogger();
Util.logger.info('mcdev:: Document');
const properties = await config.getProperties();
if (!(await config.checkProperties(properties))) {
return null;
}
if (type && !MetadataTypeInfo[type]) {
Util.logger.error(`:: '${type}' is not a valid metadata type`);
return;
}
try {
const parentBUOnlyTypes = ['user', 'role'];
const buObject = await Cli.getCredentialObject(
properties,
parentBUOnlyTypes.includes(type) ? businessUnit.split('/')[0] : businessUnit,
parentBUOnlyTypes.includes(type) ? Util.parentBuName : null
);
if (buObject !== null) {
MetadataTypeInfo[type].properties = properties;
MetadataTypeInfo[type].buObject = buObject;
MetadataTypeInfo[type].document();
}
} catch (ex) {
Util.logger.error('mcdev.document ' + ex.message);
Util.logger.debug(ex.stack);
Util.logger.info(
'If the directoy does not exist, you may need to retrieve this BU first.'
);
}
}
/**
* deletes metadata from MC instance by key
*
* @param {string} businessUnit references credentials from properties.json
* @param {string | TypeKeyCombo} selectedTypes supported metadata type (single) or complex object
* @param {string[] | string} [keys] Identifier of metadata
* @returns {Promise.<boolean>} true if successful, false otherwise
*/
static async deleteByKey(businessUnit, selectedTypes, keys) {
Util.startLogger();
Util.logger.info('mcdev:: delete');
/** @typedef {string[]} */
let selectedTypesArr;
/** @typedef {TypeKeyCombo} */
let selectedTypesObj;
let keyArr;
keyArr = 'string' === typeof keys ? [keys] : keys;
if ('string' === typeof selectedTypes) {
selectedTypesArr = [selectedTypes];
} else {
selectedTypesObj = selectedTypes;
// reset keys array because it will be overriden by values from selectedTypesObj
keyArr = null;
}
// check if types are valid
for (const selectedType of selectedTypesArr || Object.keys(selectedTypesObj)) {
if (!Util._isValidType(selectedType)) {
return;
}
}
const properties = await config.getProperties();
if (!(await config.checkProperties(properties))) {
return null;
}
const buObject = await Cli.getCredentialObject(properties, businessUnit);
if (!buObject) {
return;
}
let client;
try {
client = auth.getSDK(buObject);
} catch (ex) {
Util.logger.error(ex.message);
return;
}
let status = true;
for (const type of selectedTypesArr || Object.keys(selectedTypesObj)) {
keyArr = selectedTypesArr ? keyArr : selectedTypesObj[type];
if (!keyArr) {
Util.logger.error(`No keys set for ${type}`);
return;
}
MetadataTypeInfo[type].client = client;
MetadataTypeInfo[type].properties = properties;
MetadataTypeInfo[type].buObject = buObject;
const deleteLimit = pLimit(20);
await Promise.allSettled(
keyArr.map((key) =>
deleteLimit(async () => {
// Util.logger.info(
// Util.getGrayMsg(` - Deleting ${type} ${key} on BU ${businessUnit}`)
// );
try {
const result = await MetadataTypeInfo[type].deleteByKey(key);
status &&= result;
} catch (ex) {
Util.logger.errorStack(
ex,
` - Deleting ${type} ${key} on BU ${businessUnit} failed`
);
status = false;
}
return status;
})
)
);
}
return status;
}
/**
* get name & key for provided id
*
* @param {string} businessUnit references credentials from properties.json
* @param {string} type supported metadata type
* @param {string} id Identifier of metadata
* @returns {Promise.<{key:string, name:string, path:string}>} key, name and path of metadata; null if not found
*/
static async resolveId(businessUnit, type, id) {
Util.startLogger();
if (!Util.OPTIONS.json) {
Util.logger.info('mcdev:: resolveId');
}
if (!Util._isValidType(type)) {
return;
}
const properties = await config.getProperties();
if (!(await config.checkProperties(properties))) {
return null;
}
const buObject = await Cli.getCredentialObject(properties, businessUnit);
if (buObject !== null) {
try {
MetadataTypeInfo[type].client = auth.getSDK(buObject);
} catch (ex) {
Util.logger.error(ex.message);
return;
}
if (!Util.OPTIONS.json) {
Util.logger.info(
Util.getGrayMsg(` - Searching ${type} with id ${id} on BU ${businessUnit}`)
);
}
try {
MetadataTypeInfo[type].properties = properties;
MetadataTypeInfo[type].buObject = buObject;
return await MetadataTypeInfo[type].resolveId(id);
} catch (ex) {
Util.logger.errorStack(ex, ` - Could not resolve ID of ${type} ${id}`);
}
}
}
/**
* ensures triggered sends are restarted to ensure they pick up on changes of the underlying emails
*
* @param {string} businessUnit references credentials from properties.json
* @param {string} type references credentials from properties.json
* @param {string[]} [keyArr] metadata keys
* @returns {Promise.<void>} -
*/
static async refresh(businessUnit, type, keyArr) {
Util.startLogger();
Util.logger.info('mcdev:: refresh');
if (!type || !Util._isValidType(type, true)) {
type = 'triggeredSend';
Util.logger.info(' - setting type to ' + type);
}
const properties = await config.getProperties();
if (!(await config.checkProperties(properties))) {
return null;
}
const buObject = await Cli.getCredentialObject(properties, businessUnit);
if (buObject !== null) {
try {
MetadataTypeInfo[type].client = auth.getSDK(buObject);
} catch (ex) {
Util.logger.error(ex.message);
return;
}
try {
cache.initCache(buObject);
MetadataTypeInfo[type].properties = properties;
MetadataTypeInfo[type].buObject = buObject;
await MetadataTypeInfo[type].refresh(keyArr);
} catch (ex) {
Util.logger.errorStack(ex, 'mcdev.refresh');
}
}
}
/**
* method for contributors to get details on SOAP objects
*
* @param {string} type references credentials from properties.json
* @param {string} [businessUnit] defaults to first credential's ParentBU
* @returns {Promise.<void>} -
*/
static async describeSoap(type, businessUnit) {
Util.startLogger();
Util.logger.info('mcdev:: describe SOAP');
const properties = await config.getProperties();
if (!(await config.checkProperties(properties))) {
return null;
}
const credential = Object.keys(properties.credentials)[0];
businessUnit ||=
credential + '/' + Object.keys(properties.credentials[credential].businessUnits)[0];
const buObject = await Cli.getCredentialObject(properties, businessUnit);
if (!buObject) {
return;
}
try {
const client = auth.getSDK(buObject);
const response = await client.soap.describe(type);
if (response?.ObjectDefinition?.Properties) {
Util.logger.info(
`Properties for SOAP object ${response.ObjectDefinition.ObjectType}:`
);
const properties = response.ObjectDefinition.Properties.map((prop) => {
delete prop.PartnerKey;
delete prop.ObjectID;
return prop;
});
if (Util.OPTIONS.json) {
console.log(JSON.stringify(properties, null, 2)); // eslint-disable-line no-console
} else {
console.table(properties); // eslint-disable-line no-console
}
return properties;
} else {
throw new Error(
`Soap object ${type} not found. Please check the spelling and retry`
);
}
} catch (ex) {
Util.logger.error(ex.message);
}
}
/**
* Converts metadata to legacy format. Output is saved in 'converted' directory
*
* @param {string} businessUnit references credentials from properties.json
* @returns {Promise.<void>} -
*/
static async badKeys(businessUnit) {
Util.startLogger();
const properties = await config.getProperties();
if (!(await config.checkProperties(properties))) {
return null;
}
const buObject = await Cli.getCredentialObject(properties, businessUnit);
if (buObject !== null) {
Util.logger.info('Gathering list of Name<>External Key mismatches (bad keys)');
const retrieveDir = File.filterIllegalPathChars(
File.normalizePath([
properties.directories.retrieve,
buObject.credential,
buObject.businessUnit,
])
);
const docPath = File.normalizePath([
properties.directories.docs,
'badKeys',
buObject.credential,
]);
const filename = File.normalizePath([
docPath,
File.filterIllegalFilenames(buObject.businessUnit) + '.badKeys.md',
]);
await File.ensureDir(docPath);
if (await File.pathExists(filename)) {
await File.remove(filename);
}
const regex = new RegExp(String.raw`(\w+-){4}\w+`);
await File.ensureDir(retrieveDir);
const metadata = await Deployer.readBUMetadata(retrieveDir, null, true);
let output = '# List of Metadata with Name-Key mismatches\n';
for (const metadataType in metadata) {
let listEntries = '';
for (const entry in metadata[metadataType]) {
const metadataEntry = metadata[metadataType][entry];
if (regex.test(entry)) {
if (metadataType === 'query' && metadataEntry.Status === 'Inactive') {
continue;
}
listEntries +=
'- ' +
entry +
(metadataEntry.name || metadataEntry.Name
? ' => ' + (metadataEntry.name || metadataEntry.Name)
: '') +
'\n';
}
}
if (listEntries !== '') {
output += '\n## ' + metadataType + '\n\n' + listEntries;
}
}
await File.writeToFile(
docPath,
File.filterIllegalFilenames(buObject.businessUnit) + '.badKeys',
'md',
output
);
Util.logger.info('Bad keys documented in ' + filename);
}
}
/**
* Retrieve a specific metadata file and templatise.
*
* @param {string} businessUnit references credentials from properties.json
* @param {string} selectedType supported metadata type
* @param {string[]} name name of the metadata
* @param {string} market market which should be used to revert template
* @returns {Promise.<MultiMetadataTypeList>} -
*/
static async retrieveAsTemplate(businessUnit, selectedType, name, market) {
Util.startLogger();
Util.logger.warn(
'mcdev:: [DEPRECATED] Retrieve as Template [DEPRECATED] - use "retrieve" + "buildTemplate" instead'
);
const properties = await config.getProperties();
if (!(await config.checkProperties(properties))) {
return null;
}
if (!Util._isValidType(selectedType)) {
return;
}
const { type, subType } = Util.getTypeAndSubType(selectedType);
let retrieveTypesArr;
if (
type &&
subType &&
MetadataTypeInfo[type] &&
MetadataTypeDefinitions[type].subTypes.includes(subType)
) {
retrieveTypesArr = [selectedType];
} else if (type && MetadataTypeInfo[type]) {
retrieveTypesArr = [type];
}
const buObject = await Cli.getCredentialObject(properties, businessUnit);
if (buObject !== null) {
cache.initCache(buObject);
const retriever = new Retriever(properties, buObject);
if (Util.checkMarket(market, properties)) {
return retriever.retrieve(retrieveTypesArr, name, properties.markets[market]);
}
}
}
/**
* @param {string} businessUnit references credentials from properties.json
* @param {TypeKeyCombo} selectedTypes limit retrieval to given metadata type
* @returns {Promise.<TypeKeyCombo>} selected types including dependencies
*/
static async addDependentCbReferences(businessUnit, selectedTypes) {
if (!Util.OPTIONS.dependencies) {
return;
}
const initialAssetNumber = selectedTypes['asset']?.length || 0;
const properties = await config.getProperties();
const buObject = await Cli.getCredentialObject(properties, businessUnit);
Util.logger.info(
'Searching for additional dependencies that were linked via ContentBlockByKey, ContentBlockByName and ContentBlockById'
);
await ReplaceContentBlockReference.createCache(properties, buObject, true);
// because we re-use the replaceReference logic here we need to manually set this value
/** @type {ContentBlockConversionTypes[]} */
Util.OPTIONS.referenceFrom = ['key', 'name', 'id'];
/** @type {ContentBlockConversionTypes} */
Util.OPTIONS.referenceTo = 'key';
/** @type {Set.<string>} */
const assetDependencies = new Set();
const retrieveDir = File.filterIllegalPathChars(
File.normalizePath([
properties.directories.retrieve,
buObject.credential,
buObject.businessUnit,
])
);
// check all non-asset types for dependencies
for (const depType in selectedTypes) {
if (
!Object.prototype.hasOwnProperty.call(
MetadataTypeInfo[depType],
'replaceCbReference'
) ||
depType === 'asset'
) {
continue;
}
MetadataTypeInfo[depType].properties = properties;
MetadataTypeInfo[depType].buObject = buObject;
await MetadataTypeInfo[depType].getCbReferenceKeys(
selectedTypes[depType],
retrieveDir,
assetDependencies
);
}
// add dependencies to selectedTypes
if (assetDependencies.size) {
const depType = 'asset';
if (selectedTypes[depType]) {
selectedTypes[depType].push(...assetDependencies);
} else {
selectedTypes[depType] = [...assetDependencies];
}
// remove duplicates in main object after adding dependencies
selectedTypes[depType] = [...new Set(selectedTypes[depType])];
}
// check all assets for dependencies recursively
if (selectedTypes.asset?.length) {
const depType = 'asset';
const Asset = MetadataTypeInfo[depType];
Asset.properties = properties;
Asset.buObject = buObject;