-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathwordpress.service.ts
More file actions
1937 lines (1679 loc) · 70.3 KB
/
wordpress.service.ts
File metadata and controls
1937 lines (1679 loc) · 70.3 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
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-unused-vars */
import fs, { existsSync } from "fs";
import path from "path";
import { fileURLToPath } from "url";
import axios from "axios";
import { MIGRATION_DATA_CONFIG, LOCALE_MAPPER } from "../constants/index.js";
import jsdom from "jsdom";
import { htmlToJson, jsonToHtml } from "@contentstack/json-rte-serializer";
import customLogger from "../utils/custom-logger.utils.js";
import { getLogMessage } from "../utils/index.js";
import { v4 as uuidv4 } from "uuid";
import { orgService } from "./org.service.js";
import * as cheerio from 'cheerio';
import { setupWordPressBlocks, stripHtmlTags } from "../utils/wordpressParseUtil.js";
import { getMimeTypeFromExtension } from "../utils/mimeTypes.js";
const { JSDOM } = jsdom;
// Get the current file's path
const __filename = fileURLToPath(import.meta.url);
// Get the current directory
const __dirname = path.dirname(__filename);
const { DATA, EXPORT_INFO_FILE } = MIGRATION_DATA_CONFIG
let assetsSave = path.join(
MIGRATION_DATA_CONFIG.DATA,
MIGRATION_DATA_CONFIG.ASSETS_DIR_NAME
);
const entrySave = path.join(
MIGRATION_DATA_CONFIG.DATA,
MIGRATION_DATA_CONFIG.ENTRIES_DIR_NAME
);
let postFolderPath = path.join(
entrySave,
MIGRATION_DATA_CONFIG.POSTS_DIR_NAME,
MIGRATION_DATA_CONFIG.POSTS_FOLDER_NAME
);
let authorsFolderPath = path.join(
entrySave,
MIGRATION_DATA_CONFIG.AUTHORS_DIR_NAME
);
let authorsFilePath = path.join(
authorsFolderPath,
MIGRATION_DATA_CONFIG.AUTHORS_FILE_NAME
);
const TaxonomiesSave = path.join(
MIGRATION_DATA_CONFIG.DATA,
MIGRATION_DATA_CONFIG.TAXONOMIES_DIR_NAME
);
let assetMasterFolderPath = path.join(
MIGRATION_DATA_CONFIG.DATA,
"logs",
MIGRATION_DATA_CONFIG.ASSETS_DIR_NAME
);
interface Asset {
"wp:post_type": string;
[key: string]: any;
}
const idCorrector = (id: any) => {
const newId = id?.replace(/[-{}]/g, (match: any) => match === '-' ? '' : '')
if (newId) {
return newId?.toLowerCase()
} else {
return id
}
}
let failedJSONFilePath = path.join(
assetMasterFolderPath,
MIGRATION_DATA_CONFIG.ASSETS_FAILED_FILE
);
const failedJSON: Record<string, any> = {};
let assetData: Record<string, any> | any = {};
// import { parse, serialize } from '@wordpress/blocks';
// import { registerCoreBlocks } from '@wordpress/block-library';
const getFieldName = (key: string ) => {
if(key?.includes('/')){
return key?.split('/')?.[1];
}
else if(key?.includes('wp:')){
const parts = key.split('_'); // e.g. ['wp', 'post', 'title']
//let displayName : string = '';
const displayName = parts
.filter(item => !item.includes('wp:'))
.join(' ');
return displayName;
}
return key;
}
const RteJsonConverter = (html: string) => {
const dom = new JSDOM(html);
const htmlDoc = dom.window.document.querySelector("body");
return htmlToJson(htmlDoc);
}
const getLocale = (master_locale: string, project: any) => {
for (const key of Object.keys(project?.master_locale || {})) {
if (key === master_locale) {
return key;
}
}
//return project?.master_locale?.[master_locale] ? project.master_locale[master_locale] : master_locale;
}
function getLastUid(uid : string) {
return uid?.split?.('.')?.[uid?.split?.('.')?.length - 1];
}
async function createSchema(fields: any, blockJson : any, title: string, uid: string, assetData: any, duplicateBlockMappings?: Record<string, string>) {
const schema : any = {
title: title,
uid: uid,
//fields: fields?.fields,
};
try {
// Ensure blockJson is an array and fields is defined
if (!Array.isArray(blockJson)) {
console.warn('blockJson is not an array:', typeof blockJson);
return schema;
}
if (!Array.isArray(fields)) {
console.warn('fields is not an array:', typeof fields);
return schema;
}
// Process modular blocks fields
for (const field of fields) {
if (field?.contentstackFieldType === 'modular_blocks') {
const modularBlocksArray: any[] = [];
const modularBlocksFieldUid = field?.contentstackFieldUid || getLastUid(field?.conteststackUid);
// Find all modular_blocks_child fields that belong to this modular_blocks field
const modularBlockChildren = fields.filter((f: any) => {
const fUid = f?.contentstackFieldUid || '';
return f?.contentstackFieldType === 'modular_blocks_child' &&
fUid?.startsWith(modularBlocksFieldUid + '.') &&
!fUid?.substring(modularBlocksFieldUid?.length + 1)?.includes('.');
});
// Process each block in blockJson to see if it matches any modular block child
for (const block of blockJson) {
try {
const blockName = (block?.attrs?.metadata?.name?.toLowerCase() || getFieldName(block?.blockName?.toLowerCase()));
// Find which modular block child this block matches
let matchingChildField = fields.find((childField: any) => {
const fieldName = childField?.otherCmsField?.toLowerCase() ;
return (childField?.contentstackFieldType !== 'modular_blocks_child') && (blockName === fieldName)
});
let matchingModularBlockChild = modularBlockChildren.find((childField: any) => {
const fieldName = childField?.otherCmsField?.toLowerCase() ;
return blockName === fieldName
});
// Fallback: if no direct match, check duplicate block mappings
if (!matchingModularBlockChild && duplicateBlockMappings) {
const mappedName = duplicateBlockMappings[blockName];
if (mappedName) {
matchingModularBlockChild = modularBlockChildren.find((childField: any) => {
const fieldName = childField?.otherCmsField?.toLowerCase();
return mappedName === fieldName;
});
//if (!matchingChildField) {
matchingChildField = fields.find((childField: any) => {
const fieldName = childField?.otherCmsField?.toLowerCase();
return (childField?.contentstackFieldType !== 'modular_blocks_child') && (mappedName === fieldName);
});
// }
}
}
//if (matchingChildField) {
// Process innerBlocks (children) if they exist
if (block?.innerBlocks?.length > 0 && Array.isArray(block?.innerBlocks) && matchingModularBlockChild?.uid) {
const childrenObject: Record<string, any> = {};
block?.innerBlocks?.forEach((child: any, childIndex: number) => {
try {
// Find the field that matches this inner block
// Look for fields that belong to this modular_blocks_child
const childFieldUid = matchingModularBlockChild?.contentstackFieldUid || getLastUid(matchingModularBlockChild?.contentstackUid);
const childField = fields.find((f: any) => {
const fUid = f?.contentstackFieldUid || '';
const fOtherCmsField = f?.otherCmsType?.toLowerCase();
const childBlockName = matchingChildField ? matchingChildField?.otherCmsField?.toLowerCase() : (child?.attrs?.metadata?.name?.toLowerCase() || getFieldName(child?.blockName?.toLowerCase()));
const childKey = getLastUid(f?.contentstackFieldUid);
const alreadyPopulated = childrenObject[childKey] !== undefined && childrenObject[childKey] !== null;
return fUid.startsWith(childFieldUid + '.') &&
(fOtherCmsField === childBlockName) && (!alreadyPopulated || f?.advanced?.multiple === true);
});
if (childField) {
const childKey = getLastUid(childField?.contentstackFieldUid);
if (childField?.contentstackFieldType === 'group') {
// Process group recursively - handles nested structures
const processedGroup = processNestedGroup(child, childField, fields);
if (childField?.advanced?.multiple === true && processedGroup) {
if (Array.isArray(childrenObject[childKey])) {
childrenObject[childKey].push(processedGroup);
} else {
childrenObject[childKey] = [processedGroup];
}
} else {
processedGroup && (childrenObject[childKey] = processedGroup);
}
} else {
const formattedChild = formatChildByType(child, childField, assetData);
if (childField?.advanced?.multiple === true && formattedChild) {
if (Array.isArray(childrenObject[childKey])) {
childrenObject[childKey].push(formattedChild);
} else {
childrenObject[childKey] = [formattedChild];
}
} else {
formattedChild && (childrenObject[childKey] = formattedChild);
}
}
}
} catch (childError) {
console.warn(`Error processing child block at index ${childIndex}:`, childError);
}
});
// Add the block to the modular blocks array with the child field's UID as the key
if (Object?.keys(childrenObject)?.length > 0) {
modularBlocksArray.push({[getLastUid(matchingModularBlockChild?.contentstackFieldUid)] : childrenObject });
} else if (getLastUid(matchingModularBlockChild?.contentstackFieldUid) && matchingChildField) {
// Fallback: inner blocks didn't match child fields (e.g., duplicate-mapped block with different inner block types)
const formattedBlock = formatChildByType(block, matchingChildField, assetData);
formattedBlock && modularBlocksArray.push({[getLastUid(matchingModularBlockChild?.contentstackFieldUid)] : { [getLastUid(matchingChildField?.contentstackFieldUid)]: formattedBlock }});
}
} else if(getLastUid(matchingModularBlockChild?.contentstackFieldUid) && matchingChildField){
// Handle blocks with no inner blocks - format the block itself
const formattedBlock = formatChildByType(block, matchingChildField, assetData);
formattedBlock && modularBlocksArray.push({[getLastUid(matchingModularBlockChild?.contentstackFieldUid)] : { [getLastUid(matchingChildField?.contentstackFieldUid)]: formattedBlock }});
}
//}
} catch (blockError) {
console.warn('Error processing block:', blockError);
}
}
// Set the modular blocks array in the schema
if (modularBlocksArray.length > 0) {
schema[field?.contentstackFieldUid] = modularBlocksArray;
}
}
}
} catch (error) {
console.error('Error in createSchema:', error);
schema.error = 'Failed to process WordPress blocks';
}
return schema;
}
// Recursive helper function to process nested group structures
function processNestedGroup(child: any, childField: any, allFields: any[]): Record<string, any> {
const nestedChildrenObject: Record<string, any> = {};
if (!child?.innerBlocks?.length || !Array.isArray(child?.innerBlocks)) {
// No nested children, return empty object for group type
return {};
}
// Find nested fields for this group by checking contentstackFieldUid
const groupFieldUid = childField?.contentstackFieldUid || getLastUid(childField?.contentstackFieldUid);
const nestedFields = allFields?.filter((field: any) => {
const fieldUid = field?.contentstackFieldUid || '';
if (!fieldUid || !groupFieldUid) return false;
// Check if field is a direct child of this group (one level deeper)
if (!fieldUid.startsWith(groupFieldUid + '.')) return false;
// Verify it's exactly one level deeper (no more dots after the prefix)
const remainder = fieldUid.substring(groupFieldUid.length + 1);
return remainder && !remainder.includes('.');
}) || [];
if (nestedFields?.length === 0) {
// No nested fields found, return empty object
return {};
}
child?.innerBlocks?.forEach((nestedChild: any, nestedIndex: number) => {
try {
const nestedChildField = nestedFields?.find((field: any) =>
field?.otherCmsType?.toLowerCase() === (nestedChild?.attrs?.metadata?.name?.toLowerCase() ?? getFieldName(nestedChild?.blockName?.toLowerCase()))?.toLowerCase() && !nestedChildrenObject[getLastUid(field?.contentstackFieldUid)]?.length
);
if (!nestedChildField) {
return;
}
const nestedChildKey = getLastUid(nestedChildField?.contentstackFieldUid);
if (nestedChildField?.contentstackFieldType === 'group') {
// Recursively process nested groups
const deeplyNestedObject = processNestedGroup(nestedChild, nestedChildField, allFields);
if (nestedChildField?.advanced?.multiple === true) {
if (Array.isArray(nestedChildrenObject[nestedChildKey])) {
nestedChildrenObject[nestedChildKey].push(deeplyNestedObject);
} else {
nestedChildrenObject[nestedChildKey] = [deeplyNestedObject];
}
} else {
nestedChildrenObject[nestedChildKey] = deeplyNestedObject;
}
} else {
// Regular field, format it
const formattedNestedChild = formatChildByType(nestedChild, nestedChildField, assetData);
if (nestedChildField?.advanced?.multiple === true) {
if (Array.isArray(nestedChildrenObject[nestedChildKey])) {
nestedChildrenObject[nestedChildKey].push(formattedNestedChild);
} else {
nestedChildrenObject[nestedChildKey] = [formattedNestedChild];
}
} else {
nestedChildrenObject[nestedChildKey] = formattedNestedChild;
}
}
} catch (nestedError) {
console.warn(`Error processing nested child block at index ${nestedIndex}:`, nestedError);
}
});
return nestedChildrenObject;
}
// Helper function to collect HTML strings from innerBlocks recursively
function collectHtmlFromInnerBlocks(block: any): string {
let html = '';
if (block?.innerHTML) {
html += block.innerHTML;
}
if (block?.innerBlocks && Array.isArray(block.innerBlocks) && block.innerBlocks.length > 0) {
block.innerBlocks.forEach((innerBlock: any) => {
html += collectHtmlFromInnerBlocks(innerBlock);
});
}
return html;
}
// Helper function to extract all HTML from innerBlocks recursively
function extractAllHtmlFromInnerBlocks(block: any): any {
const html = collectHtmlFromInnerBlocks(block);
return html ;
}
// Helper function to format child blocks based on their type and field configuration
function formatChildByType(child: any, field: any, assetData: any) {
let formatted ;
try {
// Process attributes based on field type configuration
//if (child?.attributes && typeof child.attributes === 'object') {
const attrKey = getFieldName(child?.attr?.metadata?.name?.toLowerCase() || child?.blockName?.toLowerCase());
try {
const attrValue = child?.attrs?.innerHTML;
// Check if otherCmsField is "columns" - get all HTML data
if (field?.otherCmsField?.toLowerCase() === 'columns') {
formatted = extractAllHtmlFromInnerBlocks(child);
}
// Format based on common field types
switch (field?.contentstackFieldType || 'text') {
case 'modular_blocks':
formatted = [];
break;
case 'multi_line_text':
case 'single_line_text': {
// Extract text content without HTML tags
const textContent = child?.blockName ? stripHtmlTags(child?.innerHTML) : child;
formatted = textContent;
break;
}
case 'number':
formatted = typeof attrValue === 'number' ? attrValue : Number(attrValue) || 0;
break;
case 'boolean':
formatted = Boolean(child?.attrs[attrKey]);
break;
case 'json': {
let htmlContent = formatted;
if (!htmlContent && child?.innerBlocks?.length > 0) {
htmlContent = collectHtmlFromInnerBlocks(child);
}
if (!htmlContent) {
htmlContent = child?.blockName ? child?.innerHTML : child;
}
formatted = RteJsonConverter(htmlContent);
break;
}
case 'html':
formatted = child?.blockName ? formatted ?? child?.innerHTML : `<p>${child}</p>`;
break;
case 'link':
formatted= {
"title": child?.attrs?.service,
"href": child?.attrs?.url
};
break;
case 'file': {
// Extract filename from img tag in innerHTML
let fileName = '';
let imgUrl = child?.attrs?.src;
// Check innerHTML for img tag
const innerHtml = child?.innerHTML;
if (innerHtml && typeof innerHtml === 'string') {
try {
const $ = cheerio.load(innerHtml);
const imgTag = $('img').first();
if (imgTag.length) {
const src = imgTag.attr('src');
if (src) {
imgUrl = src;
// Extract filename from URL
const urlParts = src.split('/');
const fileNameWithExt = urlParts[urlParts.length - 1].split('?')[0]; // Remove query params
fileName = fileNameWithExt.includes('.') ? fileNameWithExt.substring(0, fileNameWithExt.lastIndexOf('.')) : fileNameWithExt;
}
}
} catch (htmlError) {
console.warn('Error parsing innerHTML for img tag:', htmlError);
}
}
// If no filename extracted from innerHTML, try to get it from src URL
if (!fileName && imgUrl) {
const urlParts = imgUrl.split('/');
fileName = urlParts[urlParts.length - 1].split('?')[0];
}
const asset = assetData[fileName?.replace(/-/g, '_')?.toLowerCase()];
formatted = asset;
break;
}
default:
// Default formatting - preserve original structure with null check
formatted = attrValue;
}
} catch (attrError) {
console.warn(`Error processing attribute ${attrKey}:`, attrError);
formatted[attrKey] = null;
}
} catch (error) {
console.error('Error in formatChildByType:', error);
formatted = 'Failed to process block attributes';
}
return formatted;
}
const extractCategoryReference = (categories: any) => {
const categoryArray = Array?.isArray(categories) ? categories : [categories];
const categoryReference = categoryArray?.filter((category: any) => category?.attributes?.domain === 'category');
return categoryReference;
}
const extractTermsReference = (terms: any) => {
const termArray = Array?.isArray(terms) ? terms : [terms];
const termReference = termArray?.filter((term: any) => term?.attributes?.domain !== 'category');
return termReference;
}
async function saveEntry(fields: any, entry: any, file_path: string, assetData : any, categories: any, master_locale: string, destinationStackId: string, project: any, allTerms: any, duplicateBlockMappings?: Record<string, string>) {
const locale = getLocale(master_locale, project);
const mapperKeys = project?.mapperKeys || {};
const authorsCtName = mapperKeys[MIGRATION_DATA_CONFIG.AUTHORS_DIR_NAME] ? mapperKeys[MIGRATION_DATA_CONFIG.AUTHORS_DIR_NAME] : MIGRATION_DATA_CONFIG.AUTHORS_DIR_NAME;
const authorsSave = path.join(MIGRATION_DATA_CONFIG.DATA, destinationStackId, MIGRATION_DATA_CONFIG?.ENTRIES_DIR_NAME,authorsCtName, master_locale);
const authorsFilePath = path.join(authorsSave,`${master_locale}.json` );
const authorsData = JSON.parse(await fs.promises.readFile(authorsFilePath, "utf8")) || {};
//const Jsondata = await fs.promises.readFile(file_path, "utf8");
const xmlData = await fs.promises.readFile(file_path, "utf8");
const $ = cheerio.load(xmlData, { xmlMode: true });
const items = $('item');
const entryData: Record<string, any> = {};
const fieldList = Array.isArray(fields) ? fields : [];
const hasField = (uid: string) =>
fieldList.some(
(field: any) => field?.contentstackFieldUid === uid || field?.uid === uid
);
try {
if(entry ){
// Process each entry with its corresponding XML item
for (let i = 0; i < entry?.length; i++) {
const taxonomies: any = [];
const tags: any = [];
const item = entry[i];
const terms = [];
if(item?.['category']?.length > 0){
const category = item?.['category']?.filter((category: any) => category?.attributes?.domain === 'category');
tags.push(...item?.['category']?.filter((category: any) => category?.attributes?.domain === 'post_tag') || []);
for(const cat of category){
const parentCategoryUid = categories?.find((category: any) => category?.["wp:category_nicename"] === cat?.attributes?.nicename)?.["wp:category_parent"];
const parentCategory = parentCategoryUid ? categories?.find((category: any) => category?.["wp:category_nicename"] === parentCategoryUid)?.['wp:term_id']
: categories?.find((category: any) => category?.["wp:category_nicename"] === cat?.attributes?.nicename)?.['wp:term_id'];
const categoryName = cat?.attributes?.nicename;
taxonomies.push({
"taxonomy_uid": parentCategoryUid ? `${parentCategoryUid}_${parentCategory}` : `${categoryName}_${parentCategory}`,
"term_uid": parentCategoryUid ? categoryName : `${categoryName}_${parentCategory}`
});
}
const termCategory = item?.['category']?.filter((category: any) => category?.attributes?.domain !== 'category');
for(const term of termCategory){
const uid = allTerms?.find((item: any) => term?.attributes?.nicename === item?.["wp:term_slug"])?.["wp:term_id"];
terms.push({
"uid": `terms_${uid}`,
"_content_type_uid": 'terms'
});
}
}
const uid = idCorrector(`posts_${item?.["wp:post_id"]}`);
const author = Object?.keys(authorsData)?.find((key: any) => authorsData[key]?.title?.toLowerCase() === item?.['dc:creator']?.toLowerCase());
const authorData = [{
"uid":author,
"_content_type_uid": authorsCtName
}];
const xmlItem = items?.length > 0 ? items?.filter((i, el) => {
return $(el).find("title").text() === item["title"]
}) : [];
// const targetItem = xmlItems.filter((i, el) => {
// return $(el).find("title").text() === entry.title;
// }).first();
// Find the matching XML item for this entry
// const matchingXmlItem = xmlItems
// .filter((_: any, el: any) => {
// const xmlPostId = $(el).find("wp\\:post_id").text();
// return xmlPostId === item["wp:post_id"];
// })
// .first();
//console.info("matching xml item 1 --> ", matchingXmlItem);
if (xmlItem && xmlItem?.length > 0) {
// Extract individual content encoded for this specific item
const contentEncoded = $(xmlItem)?.find("content\\:encoded")?.text() || '';
const blocksJson = await setupWordPressBlocks(contentEncoded);
customLogger(project?.id, destinationStackId,'info', `Processed blocks for entry ${uid}`);
// Pass individual content to createSchema
entryData[uid] = await createSchema(fields, blocksJson, item?.title, uid, assetData, duplicateBlockMappings);
const categoryReference = extractCategoryReference(item?.['category']);
if (hasField("taxonomies") && categoryReference?.length > 0) {
entryData[uid]["taxonomies"] = taxonomies;
}
const termsReference = extractTermsReference(item?.['category']);
if (hasField("terms") && termsReference?.length > 0) {
entryData[uid]["terms"] = terms;
}
entryData[uid]["tags"] = tags?.map((tag: any) => tag?.text) || [];
if (hasField("author")) {
entryData[uid]["author"] =
authorData?.filter((author: any) => author?.uid) || [];
}
entryData[uid]['locale'] = locale;
entryData[uid]["publish_details"] = [];
entryData[uid]['publish_details'] = [];
console.info(`Processed entry ${uid} with individual content`);
} else {
console.warn(`No matching XML item found for entry ${uid}`);
}
}
}
} catch (err) {
if (err instanceof Error) {
console.warn(`⚠️ Failed to parse blocks for:`, err.message);
} else {
console.warn(`⚠️ Failed to parse blocks for:`, err);
}
}
return entryData;
}
async function createEntry(file_path: string, packagePath: string, destinationStackId: string, projectId: string, contentTypes: any, mapperKeys: any, master_locale: string, project: any){
const locale = getLocale(master_locale, project) || master_locale;
const Jsondata = await fs.promises.readFile(packagePath, "utf8");
const xmlData = await fs.promises.readFile(file_path, "utf8");
const $ = cheerio.load(xmlData, { xmlMode: true });
const entriesJsonData = JSON.parse(Jsondata);
const entries = entriesJsonData?.rss?.channel?.["item"];
const categories = entriesJsonData?.rss?.channel?.["wp:category"];
const allCategories = Array?.isArray(categories) ? categories : (categories ? [categories] : []);
const authorsData = entriesJsonData?.rss?.channel?.["wp:author"];
const authors = Array?.isArray(authorsData) ? authorsData : [authorsData];
const termsData = entriesJsonData?.rss?.channel?.["wp:term"];
const allTerms = Array?.isArray(termsData) ? termsData : [termsData];
assetsSave = path.join(MIGRATION_DATA_CONFIG.DATA, destinationStackId, MIGRATION_DATA_CONFIG.ASSETS_DIR_NAME);
const assetsSchemaPath = path.join(assetsSave, MIGRATION_DATA_CONFIG.ASSETS_SCHEMA_FILE);
const assetData = JSON.parse(await fs.promises.readFile(assetsSchemaPath, "utf8")) || {};
const itemsArray = Array?.isArray(entries) ? entries : (entries ? [entries] : []);
if(! existsSync(path.join(MIGRATION_DATA_CONFIG.DATA,destinationStackId,
MIGRATION_DATA_CONFIG.ENTRIES_DIR_NAME))){
await fs.promises.mkdir(path.join(MIGRATION_DATA_CONFIG.DATA,destinationStackId,
MIGRATION_DATA_CONFIG.ENTRIES_DIR_NAME), { recursive: true });
}
const authorContentTypes = contentTypes?.filter((contentType: any) => contentType?.contentstackUid === 'author');
if(authorContentTypes?.length > 0){
const postsFolderName = mapperKeys[authorContentTypes?.[0]?.contentstackUid] ? mapperKeys[authorContentTypes?.[0]?.contentstackUid] : authorContentTypes?.[0]?.contentstackUid;
// Create master locale folder and file
postFolderPath = path.join(MIGRATION_DATA_CONFIG.DATA,destinationStackId,
MIGRATION_DATA_CONFIG.ENTRIES_DIR_NAME, postsFolderName, locale);
if(! existsSync(postFolderPath)){
await fs.promises.mkdir(postFolderPath, { recursive: true });
}
const authorContent = await saveAuthors(authors, destinationStackId, projectId,authorContentTypes[0],master_locale, project?.locales, project);
const filePath = path.join(postFolderPath, `${locale}.json`);
await writeFileAsync(filePath, authorContent, 4);
await fs.promises.writeFile(path.join(postFolderPath, "index.json"),
JSON.stringify({ "1": `${locale}.json` }, null, 4), "utf-8"
);
}
const termsContentTypes = contentTypes?.filter((contentType: any) => contentType?.contentstackUid === 'terms');
if(termsContentTypes?.length > 0){
const termsFolderName = mapperKeys[termsContentTypes?.[0]?.contentstackUid] ? mapperKeys[termsContentTypes?.[0]?.contentstackUid] : termsContentTypes?.[0]?.contentstackUid;
const termsFolderPath = path.join(MIGRATION_DATA_CONFIG.DATA,destinationStackId,
MIGRATION_DATA_CONFIG.ENTRIES_DIR_NAME, termsFolderName, locale);
if(! existsSync(termsFolderPath)){
await fs.promises.mkdir(termsFolderPath, { recursive: true });
}
const termsContent = await createTerms(allTerms, destinationStackId, projectId, termsContentTypes[0],master_locale, project?.locales, project);
const filePath = path.join(termsFolderPath, `${locale}.json`);
await writeFileAsync(filePath, termsContent, 4);
await fs.promises.writeFile(path.join(termsFolderPath, "index.json"),
JSON.stringify({ "1": `${locale}.json` }, null, 4), "utf-8"
);
}
const postContentTypes = contentTypes?.filter(
(contentType: any) =>
contentType?.contentstackUid !== 'author' &&
contentType?.contentstackUid !== 'terms'
);
for(const contentType of postContentTypes){
//await startingDirPosts(contentType?.contentstackUid, master_locale, project?.locales);
const postsFolderName = mapperKeys[contentType?.contentstackUid] ? mapperKeys[contentType?.contentstackUid] : contentType?.contentstackUid;
// Create master locale folder and file
postFolderPath = path.join(MIGRATION_DATA_CONFIG.DATA,destinationStackId,
MIGRATION_DATA_CONFIG.ENTRIES_DIR_NAME, postsFolderName, locale);
if(! existsSync(postFolderPath)){
await fs.promises.mkdir(postFolderPath, { recursive: true });
}
const contentTypeUid = contentType?.contentstackTitle?.toLowerCase();
const entry = entries?.filter((entry: any) => {
return entry?.['wp:post_type']?.toLowerCase() === contentTypeUid;
});
const content = await saveEntry(contentType?.fieldMapping, entry,file_path, assetData, allCategories, master_locale, destinationStackId, project, allTerms, contentType?.duplicateBlockMappings) || {};
const filePath = path.join(postFolderPath, `${locale}.json`);
await writeFileAsync(filePath, content, 4);
await fs.promises.writeFile(path.join(postFolderPath, "index.json"),
JSON.stringify({ "1": `${locale}.json` }, null, 4), "utf-8"
);
console.info(`Processed content for ${contentType?.contentstackTitle}:`, Object?.keys(content)?.length, "items");
}
}
async function createTaxonomy(file_path: string, packagePath: string, destinationStackId: string, projectId: string, contentTypes: any, mapperKeys: any, master_locale: string, project: any){
console.info("createTaxonomy");
const taxonomiesPath = path.join(MIGRATION_DATA_CONFIG.DATA, destinationStackId, MIGRATION_DATA_CONFIG.TAXONOMIES_DIR_NAME);
await fs.promises.mkdir(taxonomiesPath, { recursive: true });
const Jsondata = await fs.promises.readFile(packagePath, "utf8");
const xmlData = await fs.promises.readFile(file_path, "utf8");
const categoriesData = JSON.parse(Jsondata)?.rss?.channel?.["wp:category"] || JSON.parse(Jsondata)?.channel?.["wp:category"];
const categoriesJsonData = Array?.isArray(categoriesData) ? categoriesData : (categoriesData ? [categoriesData] : []);
if(categoriesJsonData?.length > 0){
const allTaxonomies : any = {}
for(const category of categoriesJsonData){
if(!category?.['wp:category_parent']){
const terms = [];
const categoryName = category?.["wp:cat_name"];
const categoryUid = `${category?.["wp:category_nicename"]}_${category?.["wp:term_id"]}`;
const categoryDescription = category?.["wp:category_description"];
const childCategories = categoriesJsonData?.filter((child: any) => child?.['wp:category_parent'] === category?.["wp:category_nicename"]);
for(const childCategory of childCategories){
terms?.push({
"uid": childCategory?.["wp:category_nicename"],
"name": childCategory?.["wp:cat_name"],
"description": childCategory?.["wp:category_description"],
"parent_uid": categoryUid,
})
}
const taxonomy = {
"uid": categoryUid,
"name": categoryName,
"description": categoryDescription,
}
allTaxonomies[categoryUid] = {
"uid": categoryUid,
"name": categoryName,
"description": categoryDescription,
}
terms?.push({
"uid": categoryUid,
"name": categoryName,
"description": categoryDescription,
"parent_uid": null,
})
const taxonomyData = {taxonomy, terms};
await writeFileAsync(path.join(taxonomiesPath, `${categoryUid}.json`), JSON.stringify(taxonomyData, null, 4), 4);
customLogger(projectId, destinationStackId, 'info', `Category ${categoryName} has been successfully extracted`);
}
}
await writeFileAsync(path.join(taxonomiesPath, MIGRATION_DATA_CONFIG.TAXONOMIES_FILE_NAME), JSON.stringify(allTaxonomies, null, 4), 4);
}
else {
console.warn("No categories found to extract");
customLogger(projectId, destinationStackId, 'error', "No categories found to extract");
}
}
// helper functions
async function writeFileAsync(filePath: string, data: any, tabSpaces: number) {
filePath = path.resolve(filePath);
data =
typeof data == "object" ? JSON.stringify(data, null, tabSpaces)
: data || "{}";
await fs.promises.writeFile(filePath, data, "utf-8");
}
async function writeOneFile(indexPath: string, fileMeta: any) {
fs.writeFile(indexPath, JSON.stringify(fileMeta), (err) => {
if (err) {
console.error('Error writing file: 3', err);
}
});
}
const getKeys = (obj: Record<string, any>): string[] => { //Function to fetch all the locale codes
return Object.keys(obj);
};
/************ Locale module functions start *********/
const createLocale = async (req: any, destinationStackId: string, projectId: string, project: any) => {
const srcFunc = 'createLocale';
try {
const baseDir = path.join(MIGRATION_DATA_CONFIG.DATA, destinationStackId);
const localeSave = path.join(baseDir, MIGRATION_DATA_CONFIG.LOCALE_DIR_NAME);
const allLocalesResp = await orgService.getLocales(req)
const masterLocale = Object?.keys?.(project?.master_locale ?? LOCALE_MAPPER?.masterLocale)?.[0];
const msLocale: any = {};
const uid = uuidv4();
msLocale[uid] = {
"code": masterLocale,
"fallback_locale": null,
"uid": uid,
"name": allLocalesResp?.data?.locales?.[masterLocale] ?? ''
}
const message = getLogMessage(
srcFunc,
`Master locale ${masterLocale} has been successfully transformed.`,
{}
)
await customLogger(projectId, destinationStackId, 'info', message);
const allLocales: any = {};
for (const [key, value] of Object.entries(project?.locales ?? LOCALE_MAPPER.locales)) {
const localeUid = uuidv4();
if (key !== 'masterLocale' && typeof value === 'string') {
allLocales[localeUid] = {
"code": key,
"fallback_locale": masterLocale,
"uid": localeUid,
"name": allLocalesResp?.data?.locales?.[key] ?? ''
}
const message = getLogMessage(
srcFunc,
`locale ${value} has been successfully transformed.`,
{}
)
await customLogger(projectId, destinationStackId, 'info', message);
}
}
const masterPath = path.join(localeSave, MIGRATION_DATA_CONFIG.LOCALE_MASTER_LOCALE);
const allLocalePath = path.join(localeSave, MIGRATION_DATA_CONFIG.LOCALE_FILE_NAME);
fs.access(localeSave, async (err) => {
if (err) {
fs.mkdir(localeSave, { recursive: true }, async (err) => {
if (!err) {
await writeOneFile(masterPath, msLocale);
await writeOneFile(allLocalePath, allLocales);
}
})
} else {
await writeOneFile(masterPath, msLocale);
await writeOneFile(allLocalePath, allLocales);
}
})
} catch (err) {
const message = getLogMessage(
srcFunc,
`error while Createing the locales.`,
{},
err
)
await customLogger(projectId, destinationStackId, 'error', message);
}
}
const getTermsFieldValue = (field: any, data: any, url: string) => {
const fieldUid = field?.uid;
const otherCmsField = field?.otherCmsField;
const fieldUidLower = fieldUid?.toLowerCase();
const otherCmsFieldLower = otherCmsField?.toLowerCase();
// Field mapping for common WordPress author fields
const fieldMapping: Record<string, string> = {
'term_taxonomy': 'wp:term_taxonomy',
'term_slug': 'wp:term_slug',
'term_parent': 'wp:term_parent',
'term_name': 'wp:term_name',
'termmeta': 'wp:termmeta',
'term_description': 'wp:term_description',
};
const wpFieldKey = fieldMapping[fieldUidLower] || fieldMapping[otherCmsFieldLower];
if (wpFieldKey) {
const value = data[wpFieldKey];
// Handle special cases
if (wpFieldKey === 'wp:term_name' && !value) {
return data['wp:term_name'];
}
return value;
}
return null;
}
const createTerms = async (allTerms: any, destinationStackId: string, projectId: string, contentType: any, master_locale: string, locales: object, project: any) => {
const srcFunc = 'createTerms';
const localeKeys = getKeys(locales)
try {
const termsData:{ [key: string]: any } = {}
for (const data of allTerms) {
const uid = `terms_${data["wp:term_id"]}`;
const title = data?.["wp:term_name"];
const url = `/${title?.toLowerCase()?.replace(/ /g, "_")}`;
const customId = idCorrector(uid);
const termdataEntry: any = {
uid: uid,
title: data?.["wp:term_name"],
url: url,
};
// Process each field in the content type's field mapping
if (contentType?.fieldMapping && Array?.isArray(contentType?.fieldMapping)) {
for (const field of contentType.fieldMapping) {
const fieldValue = getTermsFieldValue(field, data, url);
// Store the field value in authordataEntry using field.uid
if (field?.uid && fieldValue !== undefined && fieldValue !== null) {
termdataEntry[field?.contentstackFieldUid] = formatChildByType(fieldValue, field, assetData);
}
}
}
termsData[customId] = termdataEntry
termsData[customId].publish_details = [];
const message = getLogMessage(
srcFunc,
`Entry title ${data["wp:term_name"]} (terms) in the ${master_locale} locale has been successfully transformed.`,
{}
);
await customLogger(projectId, destinationStackId, 'info', message);
}
for (const loc of localeKeys) {
if (loc === master_locale) continue;
const localeFolderPath = path.join(entrySave, MIGRATION_DATA_CONFIG.AUTHORS_DIR_NAME, loc);
const indexPath = path.join(localeFolderPath, "index.json");
try {
await fs.promises.writeFile(
indexPath,
JSON.stringify({ "1": `${loc}.json` }, null, 4)
);
} catch (err) {
console.error(`Error writing index.json for locale ${loc}:`, err);
}
}
const message = getLogMessage(
srcFunc,
`${allTerms?.length} Authors exported successfully`,
{}
)
await customLogger(projectId, destinationStackId, 'info', message);
return termsData;
} catch (err) {
const message = getLogMessage(
srcFunc,
`error while Createing the terms.`,
{},
err
)
await customLogger(projectId, destinationStackId, 'error', message);
}
}
/************ Assests module functions start *********/
async function startingDirAssests(destinationStackId: string) {
try {
// Check if assetsSave directory exists
assetsSave = path.join(
MIGRATION_DATA_CONFIG.DATA,
destinationStackId,
MIGRATION_DATA_CONFIG.ASSETS_DIR_NAME
);
assetMasterFolderPath = path.join(
MIGRATION_DATA_CONFIG.DATA,
destinationStackId,
"logs",
MIGRATION_DATA_CONFIG.ASSETS_DIR_NAME
);
failedJSONFilePath = path.join(
assetMasterFolderPath,
MIGRATION_DATA_CONFIG.ASSETS_FAILED_FILE
);