-
Notifications
You must be signed in to change notification settings - Fork 36
/
Asset.js
2291 lines (2187 loc) · 96.5 KB
/
Asset.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 MetadataType from './MetadataType.js';
import { Util } from '../util/util.js';
import File from '../util/file.js';
import pLimit from 'p-limit';
import cliProgress from 'cli-progress';
import cache from '../util/cache.js';
import TriggeredSend from './TriggeredSend.js';
import Folder from './Folder.js';
import ReplaceCbReference from '../util/replaceContentBlockReference.js';
/**
* @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').MetadataTypeItem} MetadataTypeItem
* @typedef {import('../../types/mcdev.d.js').MetadataTypeItemDiff} MetadataTypeItemDiff
* @typedef {import('../../types/mcdev.d.js').MetadataTypeMap} MetadataTypeMap
* @typedef {import('../../types/mcdev.d.js').SoapRequestParams} SoapRequestParams
* @typedef {import('../../types/mcdev.d.js').TemplateMap} TemplateMap
*/
/**
* @typedef {import('../../types/mcdev.d.js').AssetSubType} AssetSubType
* @typedef {import('../../types/mcdev.d.js').AssetMap} AssetMap
* @typedef {import('../../types/mcdev.d.js').AssetItem} AssetItem
* @typedef {import('../../types/mcdev.d.js').AssetRequestParams} AssetRequestParams
*/
/**
* FileTransfer MetadataType
*
* @augments MetadataType
*/
class Asset extends MetadataType {
/**
* Retrieves Metadata of Asset
*
* @param {string} retrieveDir Directory where retrieved metadata directory will be saved
* @param {void | string[]} _ unused parameter
* @param {string[]} [subTypeArr] optionally limit to a single AssetSubType
* @param {string} [key] customer key
* @param {boolean} [loadShared] optionally retrieve assets from other BUs that were shared with the current
* @returns {Promise.<{metadata: AssetMap, type: string}>} Promise
*/
static async retrieve(retrieveDir, _, subTypeArr, key, loadShared = false) {
const items = [];
if (subTypeArr) {
// check if elements in subTypeArr exist in this.definition.subTypes
const invalidSubTypes = subTypeArr.filter(
(subType) => !this.definition.subTypes.includes(subType)
);
if (invalidSubTypes.length) {
throw new Error(`Invalid subType(s) found: ${invalidSubTypes.join(', ')}`);
}
}
subTypeArr ||= this._getSubTypes();
if (retrieveDir) {
await File.initPrettier();
}
// loop through subtypes and return results of each subType for caching (saving is handled per subtype)
for (const subType of subTypeArr) {
// each subtype contains multiple different specific types (images contains jpg and png for example)
// we use await here to limit the risk of too many concurrent api requests at time
items.push(...(await this.requestSubType(subType, retrieveDir, key, null, loadShared)));
}
const metadata = this.parseResponseBody({ items: items });
if (retrieveDir) {
Util.logger.info(
`Downloaded: ${this.definition.type} (${Object.keys(metadata).length})` +
Util.getKeysString(key)
);
}
return { metadata: metadata, type: this.definition.type };
}
/**
* Helper for writing Metadata to disk, used for Retrieve and deploy
*
* @param {MetadataTypeMap} results metadata results from deploy
* @param {string} retrieveDir directory where metadata should be stored after deploy/retrieve
* @param {string} [overrideType] for use when there is a subtype (such as folder-queries)
* @param {TemplateMap} [templateVariables] variables to be replaced in the metadata
* @returns {Promise.<MetadataTypeMap>} Promise of saved metadata
*/
static async saveResults(results, retrieveDir, overrideType, templateVariables) {
if (Object.keys(results).length) {
// only execute the following if records were found
await this._postRetrieveTasksBulk(results);
}
return super.saveResults(results, retrieveDir, overrideType, templateVariables);
}
/**
* helper for Journey's {@link Asset.saveResults}. Gets executed after retreive of metadata type and
*
* @param {MetadataTypeMap} metadataMap key=customer key, value=metadata
*/
static async _postRetrieveTasksBulk(metadataMap) {
// Template-Based Email
let needTemplates = false;
for (const key in metadataMap) {
if (metadataMap[key].assetType.name == 'templatebasedemail') {
needTemplates = true;
break;
}
}
if (needTemplates && !cache.getCache()?.asset) {
// for
Util.logger.info(' - Caching dependent Metadata: asset-template');
const result = await this.retrieveForCache(undefined, ['template']);
cache.setMetadata('asset', result.metadata);
}
}
/**
* Retrieves asset metadata for caching
*
* @param {void | string[]} [_] parameter not used
* @param {string[]} [subTypeArr] optionally limit to a single subtype
* @param {boolean} [loadShared] optionally retrieve assets from other BUs that were shared with the current
* @returns {Promise.<{metadata: AssetMap, type: string}>} Promise
*/
static retrieveForCache(_, subTypeArr, loadShared = false) {
return this.retrieve(null, null, subTypeArr, undefined, loadShared);
}
/**
* Retrieves asset metadata for templating
*
* @param {string} templateDir Directory where retrieved metadata directory will be saved
* @param {string} name name of the metadata file
* @param {TemplateMap} templateVariables variables to be replaced in the metadata
* @param {AssetSubType} [selectedSubType] optionally limit to a single subtype
* @returns {Promise.<{metadata: AssetItem, type: string}>} Promise
*/
static async retrieveAsTemplate(templateDir, name, templateVariables, selectedSubType) {
const items = [];
const subTypes = selectedSubType ? [selectedSubType] : this._getSubTypes();
await File.initPrettier();
// loop through subtypes and return results of each subType for caching (saving is handled per subtype)
for (const subType of subTypes) {
// each subtype contains multiple different specific types (images contains jpg and png for example)
// we use await here to limit the risk of too many concurrent api requests at time
items.push(
...(await this.requestSubType(
subType,
templateDir,
'name:' + name,
templateVariables
))
);
}
const metadata = this.parseResponseBody({ items: items });
if (!Object.keys(metadata).length) {
Util.logger.error(`${this.definition.type} '${name}' not found on server.`);
}
Util.logger.info(`Downloaded: ${this.definition.type} (${Object.keys(metadata).length})`);
return { metadata: Object.values(metadata)[0], type: this.definition.type };
}
/**
* helper for {@link Asset.retrieve} + {@link Asset.retrieveAsTemplate}
*
* @private
* @returns {string[]} AssetSubType array
*/
static _getSubTypes() {
const selectedSubTypeArr = this.properties.metaDataTypes.retrieve.filter((type) =>
type.startsWith('asset-')
);
/* eslint-disable unicorn/prefer-ternary */
if (
this.properties.metaDataTypes.retrieve.includes('asset') ||
!selectedSubTypeArr.length
) {
// if "asset" is found in config assume to download the default subtypes only
return this.definition.typeRetrieveByDefault;
} else {
return selectedSubTypeArr.map((type) => type.replace('asset-', ''));
}
/* eslint-enable unicorn/prefer-ternary */
}
/**
* Creates a single asset
*
* @param {AssetItem} metadata a single asset
* @returns {Promise} Promise
*/
static create(metadata) {
delete metadata.businessUnitAvailability;
const uri = '/asset/v1/content/assets/';
return super.createREST(metadata, uri);
}
/**
* Updates a single asset
*
* @param {AssetItem} metadata a single asset
* @returns {Promise} Promise
*/
static update(metadata) {
const uri = '/asset/v1/content/assets/' + metadata.id;
return super.updateREST(metadata, uri);
}
/**
* Retrieves Metadata of a specific asset type
*
* @param {string} subType group of similar assets to put in a folder (ie. images)
* @param {string} [retrieveDir] target directory for saving assets
* @param {string} [key] key/id/name to filter by
* @param {TemplateMap} [templateVariables] variables to be replaced in the metadata
* @param {boolean} [loadShared] optionally retrieve assets from other BUs that were shared with the current
* @returns {Promise.<object[]>} Promise
*/
static async requestSubType(subType, retrieveDir, key, templateVariables, loadShared = false) {
if (retrieveDir) {
Util.logger.info(`- Retrieving Subtype: ${subType}`);
} else {
Util.logger.info(` - Caching Subtype: ${subType}`);
}
/** @type {AssetSubType[]} */
const extendedSubTypeArr = this.definition.extendedSubTypes[subType];
const subtypeIds = extendedSubTypeArr?.map(
(subTypeItemName) => Asset.definition.typeMapping[subTypeItemName]
);
const uri = '/asset/v1/content/assets/query' + (loadShared ? '?scope=shared' : '');
/** @type {AssetRequestParams} */
const payload = {
page: {
page: 1,
pageSize: 50,
},
query: null,
fields: ['category', 'createdDate', 'createdBy', 'modifiedDate', 'modifiedBy'], // get folder to allow duplicate name check against cache
};
if (key) {
payload.query = {
leftOperand: {
property: 'assetType.id',
simpleOperator: 'in',
value: subtypeIds,
},
logicalOperator: 'AND',
};
if (key.startsWith('id:')) {
payload.query.rightOperand = {
property: this.definition.idField,
simpleOperator: 'equal',
value: key.slice(3),
};
} else if (key.startsWith('name:')) {
payload.query.rightOperand = {
property: this.definition.nameField,
simpleOperator: 'equal',
value: key.slice(5),
};
} else {
payload.query.rightOperand = {
property: this.definition.keyField,
simpleOperator: 'equal',
value: key,
};
}
} else {
payload.query = {
property: 'assetType.id',
simpleOperator: 'in',
value: subtypeIds,
};
payload.sort = [{ property: 'id', direction: 'ASC' }];
}
// for caching we do not need these fields
if (retrieveDir) {
payload.fields = [
'fileProperties',
'status',
'category',
'createdDate',
'createdBy',
'modifiedDate',
'modifiedBy',
'availableViews',
'data',
'tags',
];
}
let moreResults = false;
let lastPage = 0;
let items = [];
do {
payload.page.page = lastPage + 1;
const response = await this.client.rest.post(uri, payload);
if (response?.items?.length) {
// sometimes the api will return a payload without items
// --> ensure we only add proper items-arrays here
items = items.concat(response.items);
}
// check if any more records
if (response?.message?.includes('all shards failed')) {
// When running certain filters, there is a limit of 10k on ElastiCache.
// Since we sort by ID, we can get the last ID then run new requests from there
payload.query = {
leftOperand: {
property: 'assetType.id',
simpleOperator: 'in',
value: subtypeIds,
},
logicalOperator: 'AND',
rightOperand: {
property: 'id',
simpleOperator: 'greaterThan',
value: items.at(-1).id,
},
};
lastPage = 0;
moreResults = true;
} else if (response.page * response.pageSize < response.count) {
moreResults = true;
lastPage = Number(response.page);
} else {
moreResults = false;
}
} while (moreResults);
// only when we save results do we need the complete metadata or files. caching can skip these
if (retrieveDir) {
if (items.length > 0) {
for (const item of items) {
if (item.customerKey.trim() !== item.customerKey) {
Util.logger.warn(
` - ${this.definition.type} ${item[this.definition.nameField]} (${
item[this.definition.keyField]
}) has leading or trailing spaces in customerKey. Please remove them in SFMC.`
);
}
}
// we have to wait on execution or it potentially causes memory reference issues when changing between BUs
await this.requestAndSaveExtended(items, subType, retrieveDir, templateVariables);
}
// always show the summary even if we already had the progress bar in the console
Util.logger.info(` Downloaded asset-${subType}: ${items.length}`);
}
return items.map((item) => {
item._subType = subType;
return item;
});
}
/**
* Retrieves extended metadata (files or extended content) of asset
*
* @param {Array} items array of items to retrieve
* @param {string} subType group of similar assets to put in a folder (ie. images)
* @param {string} retrieveDir target directory for saving assets
* @param {TemplateMap} [templateVariables] variables to be replaced in the metadata
* @returns {Promise.<MetadataTypeMap>} Promise
*/
static async requestAndSaveExtended(items, subType, retrieveDir, templateVariables) {
// disable CLI logs other than error while retrieving subtype
const loggerLevelBak = Util.logger.level;
if (loggerLevelBak !== 'error') {
// disable logging to cli other than Errors
Util.setLoggingLevel({ silent: true });
}
const extendedBar = new cliProgress.SingleBar(
{
format:
' Downloading [{bar}] {percentage}% | {value}/{total} | asset-' +
subType,
},
cliProgress.Presets.shades_classic
);
const completed = [];
const failed = [];
const metadataMap = {};
// put in do loop to manage issues with connection timeout
do {
// use promise execution limiting to avoid rate limits on api, but speed up execution
// start the progress bar with a total value of 200 and start value of 0
extendedBar.start(items.length - completed.length, 0);
try {
const rateLimit = pLimit(5);
const promiseMap = await Promise.all(
items.map((item, index) =>
rateLimit(async () => {
// this is a file so extended is at another endpoint
if (item?.fileProperties?.extension && !completed.includes(item.id)) {
try {
// retrieving the extended file does not need to be awaited
await this._retrieveExtendedFile(item, subType, retrieveDir);
} catch (ex) {
failed.push({ item: item, error: ex });
}
// even if the extended file failed, still save the metadata
metadataMap[item.customerKey] = item;
}
// this is a complex type which stores data in the asset itself
else if (!completed.includes(item.id)) {
try {
const extendedItem = await this.client.rest.get(
'asset/v1/content/assets/' + item.id
);
// only save the metadata if we have extended content
metadataMap[item.customerKey] = extendedItem;
// overwrite the original item with the extended content to ensure retrieve() returns it
items[index] = extendedItem;
} catch (ex) {
failed.push({ item: item, error: ex });
}
}
completed.push(item.id);
if (metadataMap[item.customerKey]) {
await this.saveResults(
metadataMap,
retrieveDir,
'asset-' + subType,
templateVariables
);
}
// update the current value in your application..
extendedBar.increment();
})
)
);
// stop the progress bar
extendedBar.stop();
Asset._resetLogLevel(loggerLevelBak, failed);
return promiseMap;
} catch (ex) {
extendedBar.stop();
Asset._resetLogLevel(loggerLevelBak, failed);
// timeouts should be retried, others can be exited
if (ex.code !== 'ETIMEDOUT') {
throw ex;
}
}
} while (completed.length === items.length);
return metadataMap;
}
/**
* helper that reset the log level and prints errors
*
* @private
* @param {'info'|'verbose'|'debug'|'error'} loggerLevelBak original logger level
* @param {object[]} failed array of failed items
*/
static _resetLogLevel(loggerLevelBak, failed) {
// re-enable CLI logs
// reset logging level
let obj;
switch (loggerLevelBak) {
case 'info': {
obj = {};
break;
}
case 'verbose': {
obj = { verbose: true };
break;
}
case 'debug': {
obj = { debug: true };
break;
}
case 'error': {
obj = { silent: true };
}
}
Util.setLoggingLevel(obj);
if (failed.length) {
Util.logger.warn(
` - Failed to download ${failed.length} extended file${
failed.length > 1 ? 's' : ''
}:`
);
for (const fail of failed) {
Util.logger.warn(
` - "${fail.item.name}" (${fail.item.customerKey}): ${fail.error.message} (${
fail.error.code
})${
fail.error.endpoint
? Util.getGrayMsg(
' - ' +
fail.error.endpoint.split('rest.marketingcloudapis.com')[1]
)
: ''
}`
);
}
Util.logger.info(
' - You will still find a JSON file for each of these in the download directory.'
);
}
}
/**
* Some metadata types store their actual content as a separate file, e.g. images
* This method retrieves these and saves them alongside the metadata json
*
* @param {AssetItem} metadata a single asset
* @param {string} subType group of similar assets to put in a folder (ie. images)
* @param {string} retrieveDir target directory for saving assets
* @returns {Promise.<void>} -
*/
static async _retrieveExtendedFile(metadata, subType, retrieveDir) {
const file = await this.client.rest.get('asset/v1/content/assets/' + metadata.id + '/file');
// to handle uploaded files that bear the same name, SFMC engineers decided to add a number after the fileName
// however, their solution was not following standards: fileName="header.png (4) " and then extension="png (4) "
const fileExt = metadata.fileProperties.extension.split(' ')[0];
File.writeToFile(
[retrieveDir, this.definition.type, subType],
metadata.customerKey,
fileExt,
file,
'base64'
);
}
/**
* helper for {@link Asset.preDeployTasks}
* Some metadata types store their actual content as a separate file, e.g. images
* This method reads these from the local FS stores them in the metadata object allowing to deploy it
*
* @param {AssetItem} metadata a single asset
* @param {string} subType group of similar assets to put in a folder (ie. images)
* @param {string} deployDir directory of deploy files
* @param {boolean} [pathOnly] used by getFilesToCommit which does not need the binary file to be actually read
* @returns {Promise.<string>} if found will return the path of the binary file
*/
static async _readExtendedFileFromFS(metadata, subType, deployDir, pathOnly = false) {
// to handle uploaded files that bear the same name, SFMC engineers decided to add a number after the fileName
// however, their solution was not following standards: fileName="header.png (4) " and then extension="png (4) "
if (!metadata?.fileProperties?.extension) {
return;
}
const fileExt = metadata.fileProperties.extension.split(' ')[0];
const path = File.normalizePath([
deployDir,
this.definition.type,
subType,
`${metadata.customerKey}.${fileExt}`,
]);
if (await File.pathExists(path)) {
if (!pathOnly) {
metadata.file = await File.readFilteredFilename(
[deployDir, this.definition.type, subType],
metadata.customerKey,
fileExt,
'base64'
);
}
return path;
}
}
/**
* manages post retrieve steps
*
* @param {AssetItem} metadata a single asset
* @returns {CodeExtractItem} metadata
*/
static postRetrieveTasks(metadata) {
// folder
this.setFolderPath(metadata);
// template-based emails
if (metadata.assetType.name === 'templatebasedemail') {
// get template
try {
if (metadata.views?.html?.template?.id) {
metadata.views.html.template.r__asset_key = cache.searchForField(
'asset',
metadata.views?.html?.template?.id,
'id',
'customerKey'
);
delete metadata.views.html.template.id;
delete metadata.views.html.template.name;
delete metadata.views.html.template.assetType;
delete metadata.views.html.template.availableViews;
delete metadata.views.html.template.data;
delete metadata.views.html.template.modelVersion;
}
} catch {
Util.logger.warn(
` - ${this.definition.type} '${metadata[this.definition.nameField]}' (${
metadata[this.definition.keyField]
}): Could not find email template with id (${metadata.views.html.template.id})`
);
}
}
// extract HTML for selected subtypes and convert payload for easier processing in MetadataType.saveResults()
return this._extractCode(metadata);
}
/**
* Gets executed after deployment of metadata type
*
* @param {MetadataTypeMap} metadata metadata mapped by their keyField
* @param {MetadataTypeMap} _ originalMetadata to be updated (contains additioanl fields)
* @param {{created: number, updated: number}} createdUpdated counter representing successful creates/updates
* @returns {Promise.<void>} -
*/
static async postDeployTasks(metadata, _, createdUpdated) {
if (Util.OPTIONS.refresh) {
if (createdUpdated.updated) {
// only run this if assets were updated. for created assets we do not expect
this._refreshTriggeredSend(metadata);
} else {
Util.logger.warn(
'You set the --refresh flag but no updated assets found. Skipping refresh of triggeredSendDefinitions.'
);
}
}
}
/**
* helper for {@link Asset.postDeployTasks}. triggers a refresh of active triggerredSendDefinitions associated with the updated asset-message items. Gets executed if refresh option has been set.
*
* @private
* @param {MetadataTypeMap} metadata metadata mapped by their keyField
* @returns {Promise.<void>} -
*/
static async _refreshTriggeredSend(metadata) {
// get legacyData.legacyId from assets to compare to TSD's metadata.Email.ID to
const legacyIdArr = Object.keys(metadata)
.map((key) => metadata[key]?.legacyData?.legacyId)
.filter(Boolean);
if (!legacyIdArr.length) {
Util.logger.warn(
'No legacyId found in updated emails. Skipping refresh of triggeredSendDefinitions.'
);
return;
}
// prep triggeredSendDefinition class
TriggeredSend.properties = this.properties;
TriggeredSend.buObject = this.buObject;
TriggeredSend.client = this.client;
try {
// find refreshable TSDs
const tsdObj = (await TriggeredSend.findRefreshableItems(true)).metadata;
const tsdCountInitial = Object.keys(tsdObj).length;
const emailCount = legacyIdArr.length;
// filter TSDs by legacyId
for (const key in tsdObj) {
if (!legacyIdArr.includes(tsdObj[key].Email.ID)) {
delete tsdObj[key];
}
}
const tsdCountFiltered = Object.keys(tsdObj).length;
Util.logger.info(
`Found ${tsdCountFiltered} out of ${tsdCountInitial} total triggeredSendDefinitions for ${emailCount} deployed emails. Commencing validation...`
);
// get keys of TSDs to refresh
const keyArr = await TriggeredSend.getKeysForValidTSDs(tsdObj);
await TriggeredSend.refresh(keyArr);
} catch {
Util.logger.warn('Failed to refresh triggeredSendDefinition');
}
}
/**
* prepares an asset definition for deployment
*
* @param {AssetItem} metadata a single asset
* @param {string} deployDir directory of deploy files
* @returns {Promise.<AssetItem>} Promise
*/
static async preDeployTasks(metadata, deployDir) {
// additonalattributes fail where the value is "" so we need to remove them from deploy
if (metadata?.data?.email?.attributes?.length > 0) {
metadata.data.email.attributes = metadata.data.email.attributes.filter(
(attr) => attr.value
);
}
// folder
this.setFolderId(metadata);
// template-based emails
if (
metadata.assetType.name === 'templatebasedemail' &&
metadata.views?.html?.template?.r__asset_key
) {
// template
metadata.views.html.template.id = cache.searchForField(
'asset',
metadata.views.html.template.r__asset_key,
'customerKey',
'id'
);
metadata.views.html.template.name = cache.searchForField(
'asset',
metadata.views.html.template.r__asset_key,
'customerKey',
'name'
);
metadata.views.html.template.assetType = {
id: 4,
name: 'template',
displayName: 'Template',
};
metadata.views.html.template.data = {
email: { options: { generateFrom: null } },
};
metadata.views.html.template.availableViews = [];
metadata.views.html.template.modelVersion = 2;
delete metadata.views.html.template.r__asset_key;
}
// restore asset type id which is needed for deploy
metadata.assetType.id = this.definition.typeMapping[metadata.assetType.name];
// define asset's subtype
const subType = this._getSubtype(metadata);
// #1 get text extracts back into the JSON
await this._mergeCode(metadata, deployDir, subType);
// #2 get file from local disk and insert as base64
await this._readExtendedFileFromFS(metadata, subType, deployDir);
// only execute #3 if we are deploying / copying from one BU to another, not while using mcdev as a developer tool
if (
!Util.OPTIONS.noMidSuffix &&
this.buObject.mid &&
metadata.memberId != this.buObject.mid && // soft comparison to accomodate for string-version of mid
!metadata[this.definition.keyField].endsWith(this.buObject.mid)
) {
// #3 make sure customer key is unique by suffixing it with target MID (unless we are deploying to the same MID)
// check if this suffixed with the source MID
const suffix = '-' + this.buObject.mid;
// for customer key max is 36 chars
metadata[this.definition.keyField] =
metadata[this.definition.keyField].slice(0, Math.max(0, 36 - suffix.length)) +
suffix;
}
// #4 make sure the name is unique
const assetCache = cache.getCache()[this.definition.type];
const namesInFolder = Object.keys(assetCache)
.filter((key) => assetCache[key].category.id === metadata.category.id)
.map((key) => ({
type: this.#getMainSubtype(assetCache[key].assetType.name),
key: key,
name: assetCache[key].name,
}));
// if the name is already in the folder for a different key, add a number to the end
metadata[this.definition.nameField] = this._findUniqueName(
metadata[this.definition.keyField],
metadata[this.definition.nameField],
this.#getMainSubtype(metadata.assetType.name),
namesInFolder
);
return metadata;
}
/**
* find the subType matching the extendedSubType
*
* @param {string} extendedSubType webpage, htmlblock, etc
* @returns {string} subType: block, message, other, etc
*/
static #getMainSubtype(extendedSubType) {
return Object.keys(this.definition.extendedSubTypes).find((subType) =>
this.definition.extendedSubTypes[subType].includes(extendedSubType)
);
}
/**
* helper to find a new unique name during asset creation
*
* @private
* @param {string} key key of the asset
* @param {string} name name of the asset
* @param {string} type assetType-name
* @param {{ type: string; key: string; name: any; }[]} namesInFolder names of the assets in the same folder
* @returns {string} new name
*/
static _findUniqueName(key, name, type, namesInFolder) {
let newName = name;
let suffix;
let i = 1;
while (
namesInFolder.find(
(item) => item.name === newName && item.type === type && item.key !== key
)
) {
suffix = ' (' + i + ')';
// for customer key max is 100 chars
newName = name.slice(0, Math.max(0, 100 - suffix.length)) + suffix;
i++;
}
return newName;
}
/**
* determines the subtype of the current asset
*
* @private
* @param {AssetItem} metadata a single asset
* @returns {string} subtype
*/
static _getSubtype(metadata) {
for (const sub in this.definition.extendedSubTypes) {
if (this.definition.extendedSubTypes[sub].includes(metadata.assetType.name)) {
return sub;
}
}
return;
}
/**
* helper for {@link MetadataType.buildDefinition}
* handles extracted code if any are found for complex types
*
* @param {string} templateDir Directory where metadata templates are stored
* @param {string} targetDir Directory where built definitions will be saved
* @param {AssetItem} metadata main JSON file that was read from file system
* @param {TemplateMap} templateVariables variables to be replaced in the metadata
* @param {string} templateName name of the template to be built
* @returns {Promise.<string[][]>} list of extracted files with path-parts provided as an array
*/
static buildDefinitionForNested(
templateDir,
targetDir,
metadata,
templateVariables,
templateName
) {
return this._buildForNested(
templateDir,
targetDir,
metadata,
templateVariables,
templateName,
'definition'
);
}
/**
* helper for {@link MetadataType.buildTemplate}
* handles extracted code if any are found for complex types
*
* @example assets of type codesnippetblock will result in 1 json and 1 amp/html file. both files need to be run through templating
* @param {string} templateDir Directory where metadata templates are stored
* @param {string|string[]} targetDir (List of) Directory where built definitions will be saved
* @param {AssetItem} metadata main JSON file that was read from file system
* @param {TemplateMap} templateVariables variables to be replaced in the metadata
* @param {string} templateName name of the template to be built
* @returns {Promise.<string[][]>} list of extracted files with path-parts provided as an array
*/
static buildTemplateForNested(
templateDir,
targetDir,
metadata,
templateVariables,
templateName
) {
return this._buildForNested(
templateDir,
targetDir,
metadata,
templateVariables,
templateName,
'template'
);
}
/**
* helper for {@link MetadataType.buildDefinition}
* handles extracted code if any are found for complex types
*
* @param {string} templateDir Directory where metadata templates are stored
* @param {string|string[]} targetDir (List of) Directory where built definitions will be saved
* @param {AssetItem} metadata main JSON file that was read from file system
* @param {TemplateMap} templateVariables variables to be replaced in the metadata
* @param {string} templateName name of the template to be built
* @param {'definition'|'template'} mode defines what we use this helper for
* @returns {Promise.<string[][]>} list of extracted files with path-parts provided as an array
*/
static async _buildForNested(
templateDir,
targetDir,
metadata,
templateVariables,
templateName,
mode
) {
// * because asset's _mergeCode() is overwriting 'metadata', clone it to ensure the main file is not modified by what we do in here
metadata = structuredClone(metadata);
// #1 text extracts
// define asset's subtype
const subType = this._getSubtype(metadata);
// get HTML from filesystem
const fileList = await this._mergeCode(metadata, templateDir, subType, templateName);
// replace template variables with their values
for (const extractedFile of fileList) {
try {
if (mode === 'definition') {
// replace template variables with their values
extractedFile.content = this.applyTemplateValues(
extractedFile.content,
templateVariables
);
} else if (mode === 'template') {
// replace template values with corresponding variable names
extractedFile.content = this.applyTemplateNames(
extractedFile.content,
templateVariables
);
}
} catch {
throw new Error(
`${this.definition.type}:: Error applying template variables on ${
metadata[this.definition.keyField]
}: ${extractedFile.fileName}.${extractedFile.fileExt}.`
);
}
extractedFile.subFolder = extractedFile.subFolder
.map((el) => (el === templateName ? metadata[this.definition.keyField] : el))
.map((el) => this.applyTemplateValues(el, templateVariables));
}
// #2 binary extracts
if (metadata?.fileProperties?.extension) {
// to handle uploaded files that bear the same name, SFMC engineers decided to add a number after the fileName
// however, their solution was not following standards: fileName="header.png (4) " and then extension="png (4) "
const fileExt = metadata.fileProperties.extension.split(' ')[0];
const filecontent = await File.readFilteredFilename(
[templateDir, this.definition.type, subType],
templateName,
fileExt,
'base64'
);
// keep old name if creating templates, otherwise use new name
const fileName =
mode === 'definition' ? metadata[this.definition.keyField] : templateName;
fileList.push({
subFolder: [this.definition.type, subType],
fileName: fileName,
fileExt: fileExt,
content: filecontent,
encoding: 'base64',
});
}
const nestedFilePaths = [];
// write to file (#1 + #2)
const targetDirArr = Array.isArray(targetDir) ? targetDir : [targetDir];
for (const targetDir of targetDirArr) {
for (const extractedFile of fileList) {
File.writeToFile(
[targetDir, ...extractedFile.subFolder],
extractedFile.fileName,
extractedFile.fileExt,
extractedFile.content,
extractedFile.encoding || null
);
nestedFilePaths.push([
File.normalizePath([targetDir, ...extractedFile.subFolder]),
extractedFile.fileName +
'.' +
this.definition.type +
'-meta.' +
extractedFile.fileExt,
]);
}
}
return nestedFilePaths;
}
/**
* generic script that retrieves the folder path from cache and updates the given metadata with it after retrieve
*
* @param {MetadataTypeItem} metadata a single script activity definition
*/
static setFolderPath(metadata) {
try {
metadata.r__folder_Path = cache.searchForField(
'folder',
metadata.category.id,
'ID',
'Path'
);
delete metadata.category;
} catch (ex) {
Util.logger.warn(