@forgewp/compiler 0.4.1 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,6 +5,96 @@ import {
5
5
  generateDynamicAcfFieldPhp,
6
6
  } from './php-builders.js';
7
7
 
8
+ function generatePhpArgs(queryObj) {
9
+ const phpLines = [];
10
+ phpLines.push(`$args = array(`);
11
+
12
+ if (queryObj.postType && typeof queryObj.postType === 'string') {
13
+ phpLines.push(` 'post_type' => '${queryObj.postType}',`);
14
+ } else {
15
+ phpLines.push(` 'post_type' => 'post',`);
16
+ }
17
+
18
+ if (queryObj.postsPerPage !== undefined) {
19
+ const ppp = parseInt(queryObj.postsPerPage, 10);
20
+ phpLines.push(` 'posts_per_page' => ${isNaN(ppp) ? 10 : ppp},`);
21
+ } else {
22
+ phpLines.push(` 'posts_per_page' => 10,`);
23
+ }
24
+
25
+ if (queryObj.orderby) {
26
+ phpLines.push(` 'orderby' => '${queryObj.orderby}',`);
27
+ }
28
+ if (queryObj.order) {
29
+ phpLines.push(` 'order' => '${queryObj.order}',`);
30
+ }
31
+
32
+ if (queryObj.categoryName) {
33
+ if (String(queryObj.categoryName).startsWith('__DYNAMIC_')) {
34
+ const varName = String(queryObj.categoryName).replace(/^__DYNAMIC_/, '').replace(/__$/, '');
35
+ phpLines.push(` 'category_name' => $request->get_param('${varName}') ? sanitize_text_field($request->get_param('${varName}')) : '',`);
36
+ } else {
37
+ phpLines.push(` 'category_name' => '${queryObj.categoryName}',`);
38
+ }
39
+ }
40
+
41
+ phpLines.push(` 'paged' => $paged,`);
42
+
43
+ if (queryObj.taxQuery && Array.isArray(queryObj.taxQuery) && queryObj.taxQuery.length > 0) {
44
+ phpLines.push(` 'tax_query' => array(`);
45
+ for (const taxQ of queryObj.taxQuery) {
46
+ phpLines.push(` array(`);
47
+ phpLines.push(` 'taxonomy' => '${taxQ.taxonomy}',`);
48
+ phpLines.push(` 'field' => '${taxQ.field || 'slug'}',`);
49
+
50
+ const termsVal = taxQ.terms;
51
+ if (typeof termsVal === 'string' && termsVal.startsWith('__DYNAMIC_')) {
52
+ const varName = termsVal.replace(/^__DYNAMIC_/, '').replace(/__$/, '');
53
+ phpLines.push(` 'terms' => $request->get_param('${varName}') ? sanitize_text_field($request->get_param('${varName}')) : '',`);
54
+ } else if (Array.isArray(termsVal)) {
55
+ const termsPhp = termsVal.map(t => typeof t === 'string' ? `'${t}'` : t).join(', ');
56
+ phpLines.push(` 'terms' => array(${termsPhp}),`);
57
+ } else if (typeof termsVal === 'string') {
58
+ phpLines.push(` 'terms' => '${termsVal}',`);
59
+ } else {
60
+ phpLines.push(` 'terms' => ${termsVal},`);
61
+ }
62
+ phpLines.push(` ),`);
63
+ }
64
+ phpLines.push(` ),`);
65
+ }
66
+
67
+ if (queryObj.metaQuery && Array.isArray(queryObj.metaQuery) && queryObj.metaQuery.length > 0) {
68
+ phpLines.push(` 'meta_query' => array(`);
69
+ if (queryObj.metaRelation) {
70
+ phpLines.push(` 'relation' => '${queryObj.metaRelation}',`);
71
+ }
72
+ for (const metaQ of queryObj.metaQuery) {
73
+ phpLines.push(` array(`);
74
+ phpLines.push(` 'key' => '${metaQ.key}',`);
75
+ if (metaQ.compare) {
76
+ phpLines.push(` 'compare' => '${metaQ.compare}',`);
77
+ }
78
+ if (metaQ.value !== undefined) {
79
+ const val = metaQ.value;
80
+ if (typeof val === 'string' && val.startsWith('__DYNAMIC_')) {
81
+ const varName = val.replace(/^__DYNAMIC_/, '').replace(/__$/, '');
82
+ phpLines.push(` 'value' => $request->get_param('${varName}') ? sanitize_text_field($request->get_param('${varName}')) : '',`);
83
+ } else if (typeof val === 'string') {
84
+ phpLines.push(` 'value' => '${val}',`);
85
+ } else {
86
+ phpLines.push(` 'value' => ${val},`);
87
+ }
88
+ }
89
+ phpLines.push(` ),`);
90
+ }
91
+ phpLines.push(` ),`);
92
+ }
93
+
94
+ phpLines.push(` );`);
95
+ return phpLines.join('\n');
96
+ }
97
+
8
98
  /**
9
99
  * Generate functions.php template string
10
100
  *
@@ -21,6 +111,7 @@ export function buildFunctionsPhp(
21
111
  hydrationData = null,
22
112
  i18nKeys = [],
23
113
  schemas = {},
114
+ queries = [],
24
115
  ) {
25
116
  const css = assets.cssFile.replace(/^assets\//, '');
26
117
 
@@ -1398,6 +1489,142 @@ add_action('acf/init', 'forgewp_register_acf_field_groups');
1398
1489
  `;
1399
1490
  }
1400
1491
 
1492
+ let queryEndpointsPhp = '';
1493
+ if (queries && queries.length > 0) {
1494
+ queryEndpointsPhp += `\n\n/**\n * ── Compiled REST Query Endpoints (Milestone 2) ──\n */\n`;
1495
+ queryEndpointsPhp += `
1496
+ if (!function_exists('forgewp_format_rest_post')) {
1497
+ function forgewp_format_rest_post(\$post) {
1498
+ \$id = \$post->ID;
1499
+ \$title = get_the_title(\$post);
1500
+ \$excerpt = get_the_excerpt(\$post);
1501
+
1502
+ \$content = apply_filters('the_content', \$post->post_content);
1503
+ \$date = get_the_date('', \$post);
1504
+ \$author = get_the_author_meta('display_name', \$post->post_author);
1505
+
1506
+ \$featured_image = 'https://picsum.photos/seed/forgewp/1200/630';
1507
+ if (has_post_thumbnail(\$post)) {
1508
+ \$thumbnail_url = get_the_post_thumbnail_url(\$post, 'full');
1509
+ if (\$thumbnail_url) {
1510
+ \$featured_image = \$thumbnail_url;
1511
+ }
1512
+ }
1513
+
1514
+ \$permalink = get_permalink(\$post);
1515
+
1516
+ \$custom_fields = array();
1517
+ \$meta = get_post_meta(\$id);
1518
+ if (is_array(\$meta)) {
1519
+ foreach (\$meta as \$key => \$values) {
1520
+ \$val = isset(\$values[0]) ? maybe_unserialize(\$values[0]) : '';
1521
+ \$custom_fields[\$key] = \$val;
1522
+ }
1523
+ }
1524
+
1525
+ if (function_exists('get_fields')) {
1526
+ \$acf_fields = get_fields(\$id);
1527
+ if (is_array(\$acf_fields)) {
1528
+ \$custom_fields = array_merge(\$custom_fields, \$acf_fields);
1529
+ }
1530
+ }
1531
+
1532
+ \$terms_data = array();
1533
+ \$taxonomies = get_object_taxonomies(\$post->post_type);
1534
+ if (is_array(\$taxonomies)) {
1535
+ foreach (\$taxonomies as \$taxonomy) {
1536
+ \$terms = get_the_terms(\$post, \$taxonomy);
1537
+ if (is_array(\$terms)) {
1538
+ \$terms_data[\$taxonomy] = array();
1539
+ foreach (\$terms as \$t) {
1540
+ \$terms_data[\$taxonomy][] = array(
1541
+ 'id' => \$t->term_id,
1542
+ 'slug' => \$t->slug,
1543
+ 'name' => html_entity_decode(\$t->name, ENT_QUOTES, 'UTF-8'),
1544
+ );
1545
+ }
1546
+ }
1547
+ }
1548
+ }
1549
+
1550
+ return array(
1551
+ 'ID' => \$id,
1552
+ 'title' => \$title,
1553
+ 'excerpt' => \$excerpt,
1554
+ 'content' => \$content,
1555
+ 'date' => \$date,
1556
+ 'author' => \$author,
1557
+ 'featuredImage' => \$featured_image,
1558
+ 'permalink' => \$permalink,
1559
+ 'customFields' => \$custom_fields,
1560
+ '_terms' => \$terms_data,
1561
+ 'post_type' => \$post->post_type,
1562
+ );
1563
+ }
1564
+ }
1565
+ `;
1566
+
1567
+ queryEndpointsPhp += `
1568
+ add_action('rest_api_init', function() {`;
1569
+ for (const q of queries) {
1570
+ const cleanId = q.queryId.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
1571
+ const querySlug = 'query-' + cleanId;
1572
+ const callbackName = 'forgewp_rest_query_' + cleanId.replace(/-/g, '_');
1573
+ queryEndpointsPhp += `
1574
+ register_rest_route('forgewp/v1', '/${querySlug}', array(
1575
+ 'methods' => 'GET',
1576
+ 'callback' => '${callbackName}',
1577
+ 'permission_callback' => '__return_true',
1578
+ ));`;
1579
+ }
1580
+ queryEndpointsPhp += `
1581
+ });
1582
+ `;
1583
+
1584
+ for (const q of queries) {
1585
+ const cleanId = q.queryId.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
1586
+ const callbackName = 'forgewp_rest_query_' + cleanId.replace(/-/g, '_');
1587
+ const phpArgs = generatePhpArgs(q);
1588
+
1589
+ queryEndpointsPhp += `
1590
+ function ${callbackName}(WP_REST_Request \$request) {
1591
+ \$paged = \$request->get_param('page') ? intval(\$request->get_param('page')) : 1;
1592
+ \$s = \$request->get_param('search');
1593
+ if (empty(\$s)) {
1594
+ \$s = \$request->get_param('s');
1595
+ }
1596
+
1597
+ ${phpArgs}
1598
+
1599
+ if (!empty(\$s)) {
1600
+ \$args['s'] = sanitize_text_field(\$s);
1601
+ }
1602
+
1603
+ \$lang = \$request->get_param('lang');
1604
+ if (!empty(\$lang)) {
1605
+ \$args['lang'] = sanitize_text_field(\$lang);
1606
+ }
1607
+
1608
+ \$query = new WP_Query(\$args);
1609
+ \$posts = array();
1610
+ if (\$query->have_posts()) {
1611
+ while (\$query->have_posts()) {
1612
+ \$query->the_post();
1613
+ \$posts[] = forgewp_format_rest_post(\$query->post);
1614
+ }
1615
+ wp_reset_postdata();
1616
+ }
1617
+
1618
+ return new WP_REST_Response(array(
1619
+ 'posts' => \$posts,
1620
+ 'total' => intval(\$query->found_posts),
1621
+ 'totalPages' => intval(\$query->max_num_pages),
1622
+ ), 200);
1623
+ }
1624
+ `;
1625
+ }
1626
+ }
1627
+
1401
1628
  return `<?php
1402
1629
  /**
1403
1630
  * ${config.name} — generated by ForgeWP
@@ -1795,7 +2022,23 @@ function forgewp_render_theme_icon($icon_slug, $class_name = '', $provider = 'lu
1795
2022
  echo $svg;
1796
2023
  }
1797
2024
  }
1798
- ${faviconPhp}${sitemapsPhp}
2025
+ ${faviconPhp}${sitemapsPhp}${queryEndpointsPhp}
2026
+
2027
+ /**
2028
+ * Prevent TinyMCE Classic Editor auto-resize height expansion feedback loop.
2029
+ */
2030
+ function forgewp_disable_editor_autoresize($init_array) {
2031
+ if (isset($init_array['plugins'])) {
2032
+ $plugins = explode(',', $init_array['plugins']);
2033
+ $key = array_search('wpautoresize', $plugins);
2034
+ if ($key !== false) {
2035
+ unset($plugins[$key]);
2036
+ $init_array['plugins'] = implode(',', $plugins);
2037
+ }
2038
+ }
2039
+ return $init_array;
2040
+ }
2041
+ add_filter('tiny_mce_before_init', 'forgewp_disable_editor_autoresize');
1799
2042
  `;
1800
2043
  }
1801
2044
 
@@ -735,6 +735,9 @@ if (window.forgeWpBlocks) {
735
735
  } catch {}
736
736
  }
737
737
 
738
+ const queries = scanForQueries(themeRoot);
739
+ console.log(`[ForgeWP Compiler] Scanned and compiled ${queries.length} REST endpoints: ${queries.map(q => q.queryId).join(', ') || '<none>'}`);
740
+
738
741
  let functionsPhpContent = buildFunctionsPhp(
739
742
  config,
740
743
  assets,
@@ -745,6 +748,7 @@ if (window.forgeWpBlocks) {
745
748
  hydrationData,
746
749
  Array.from(i18nKeys),
747
750
  schemas,
751
+ queries,
748
752
  );
749
753
 
750
754
  if (projectHooks && typeof projectHooks.processFunctionsPhp === 'function') {
@@ -1017,3 +1021,120 @@ get_footer();
1017
1021
  }
1018
1022
  }
1019
1023
  }
1024
+
1025
+ function extractUseWpQueryArgs(fileContent) {
1026
+ const queries = [];
1027
+ const regex = /useWpQuery\s*\(/g;
1028
+ let match;
1029
+ while ((match = regex.exec(fileContent)) !== null) {
1030
+ const startIdx = regex.lastIndex; // index right after the '('
1031
+ let parenCount = 1;
1032
+ let endIdx = startIdx;
1033
+ let inString = false;
1034
+ let stringChar = null;
1035
+
1036
+ for (let i = startIdx; i < fileContent.length; i++) {
1037
+ const char = fileContent[i];
1038
+
1039
+ if (inString) {
1040
+ if (char === stringChar && fileContent[i - 1] !== '\\') {
1041
+ inString = false;
1042
+ }
1043
+ continue;
1044
+ }
1045
+ if (char === '"' || char === "'" || char === '`') {
1046
+ inString = true;
1047
+ stringChar = char;
1048
+ continue;
1049
+ }
1050
+
1051
+ if (char === '(') parenCount++;
1052
+ if (char === ')') {
1053
+ parenCount--;
1054
+ if (parenCount === 0) {
1055
+ endIdx = i;
1056
+ break;
1057
+ }
1058
+ }
1059
+ }
1060
+
1061
+ if (endIdx > startIdx) {
1062
+ const argText = fileContent.slice(startIdx, endIdx).trim();
1063
+ queries.push(argText);
1064
+ }
1065
+ }
1066
+ return queries;
1067
+ }
1068
+
1069
+ function safeEvalObject(objText) {
1070
+ if (!objText) return null;
1071
+ if (!objText.startsWith('{') || !objText.endsWith('}')) {
1072
+ return null;
1073
+ }
1074
+ try {
1075
+ const sandbox = new Proxy({}, {
1076
+ has() { return true; },
1077
+ get(target, prop) {
1078
+ if (prop === 'Symbol(Symbol.toPrimitive)') return undefined;
1079
+ return `__DYNAMIC_${String(prop)}__`;
1080
+ }
1081
+ });
1082
+ const fn = new Function('sandbox', `with(sandbox) { return (${objText}); }`);
1083
+ return fn(sandbox);
1084
+ } catch (e) {
1085
+ console.warn('[ForgeWP Query Parser] safeEvalObject failed for:', objText, e.message);
1086
+ return null;
1087
+ }
1088
+ }
1089
+
1090
+ function scanForQueries(themeRoot) {
1091
+ const srcDir = path.join(themeRoot, 'src');
1092
+ if (!existsSync(srcDir)) return [];
1093
+
1094
+ const queries = [];
1095
+ const walk = (dir) => {
1096
+ if (!existsSync(dir)) return;
1097
+ const files = readdirSync(dir);
1098
+ for (const file of files) {
1099
+ const fullPath = path.join(dir, file);
1100
+ const stat = statSync(fullPath);
1101
+ if (stat.isDirectory()) {
1102
+ walk(fullPath);
1103
+ } else if (/\.(js|jsx|ts|tsx)$/.test(file)) {
1104
+ const content = readFileSync(fullPath, 'utf8');
1105
+ if (content.includes('useWpQuery')) {
1106
+ const rawArgsList = extractUseWpQueryArgs(content);
1107
+ for (const rawArgs of rawArgsList) {
1108
+ if (!rawArgs) continue;
1109
+ const parsed = safeEvalObject(rawArgs);
1110
+ if (parsed && typeof parsed === 'object') {
1111
+ if (!parsed.postType) {
1112
+ parsed.postType = 'post';
1113
+ }
1114
+ if (!parsed.queryId) {
1115
+ const baseName = path.basename(file, path.extname(file));
1116
+ const postTypePart = String(parsed.postType).toLowerCase();
1117
+ const cleanBase = baseName.toLowerCase().replace(/[^a-z0-9]+/g, '-');
1118
+ parsed.queryId = cleanBase + '-' + postTypePart;
1119
+ }
1120
+ queries.push(parsed);
1121
+ }
1122
+ }
1123
+ }
1124
+ }
1125
+ }
1126
+ };
1127
+
1128
+ walk(srcDir);
1129
+
1130
+ const uniqueQueries = [];
1131
+ const seenIds = new Set();
1132
+ for (const q of queries) {
1133
+ const cleanId = q.queryId.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');
1134
+ if (!seenIds.has(cleanId)) {
1135
+ seenIds.add(cleanId);
1136
+ uniqueQueries.push(q);
1137
+ }
1138
+ }
1139
+ return uniqueQueries;
1140
+ }
@@ -380,6 +380,102 @@ export function runStaticLintChecks(themeRoot) {
380
380
  const violations = [];
381
381
  const filesToScan = [];
382
382
 
383
+ // Load CPTs, Taxonomies, and Custom Fields from wp.config.ts and cms/mock-data.json
384
+ const validPostTypes = new Set(["post", "page"]);
385
+ const postTypeTaxonomies = {
386
+ "post": new Set(["category", "post_tag"]),
387
+ "page": new Set()
388
+ };
389
+ const postTypeCustomFields = {
390
+ "post": new Set(),
391
+ "page": new Set()
392
+ };
393
+
394
+ // 1. Scan CPTs from wp.config.ts
395
+ const configPath = path.join(themeRoot, "wp.config.ts");
396
+ if (existsSync(configPath)) {
397
+ try {
398
+ const configContent = readFileSync(configPath, "utf8");
399
+ const postTypesMatch = configContent.match(/postTypes\s*:\s*\{([\s\S]*?)\}/);
400
+ if (postTypesMatch) {
401
+ const block = postTypesMatch[1];
402
+ const keyRegex = /\b([a-zA-Z0-9_-]+)\s*:/g;
403
+ let m;
404
+ while ((m = keyRegex.exec(block)) !== null) {
405
+ const pt = m[1];
406
+ if (pt !== 'labels' && pt !== 'singular' && pt !== 'plural' && pt !== 'translatable') {
407
+ validPostTypes.add(pt);
408
+ if (!postTypeTaxonomies[pt]) {
409
+ postTypeTaxonomies[pt] = new Set(["category", "post_tag"]);
410
+ }
411
+ if (!postTypeCustomFields[pt]) {
412
+ postTypeCustomFields[pt] = new Set();
413
+ }
414
+ }
415
+ }
416
+ }
417
+ } catch {}
418
+ }
419
+
420
+ // 2. Scan CPTs, Taxonomies, and Custom Fields from cms/mock-data.json
421
+ const mockDataPath = path.join(themeRoot, "cms", "mock-data.json");
422
+ if (existsSync(mockDataPath)) {
423
+ try {
424
+ const mockData = JSON.parse(readFileSync(mockDataPath, "utf8"));
425
+ for (const pt of Object.keys(mockData)) {
426
+ if (
427
+ pt !== 'posts' &&
428
+ pt !== 'pages' &&
429
+ pt !== 'post' &&
430
+ pt !== 'page' &&
431
+ pt !== 'menus' &&
432
+ pt !== 'attachment' &&
433
+ !pt.startsWith('_')
434
+ ) {
435
+ validPostTypes.add(pt);
436
+ if (!postTypeTaxonomies[pt]) {
437
+ postTypeTaxonomies[pt] = new Set(["category", "post_tag"]);
438
+ }
439
+ if (!postTypeCustomFields[pt]) {
440
+ postTypeCustomFields[pt] = new Set();
441
+ }
442
+
443
+ const items = mockData[pt];
444
+ if (Array.isArray(items)) {
445
+ for (const item of items) {
446
+ if (item._terms && typeof item._terms === 'object') {
447
+ for (const tax of Object.keys(item._terms)) {
448
+ postTypeTaxonomies[pt].add(tax);
449
+ }
450
+ }
451
+ if (item.customFields && typeof item.customFields === 'object') {
452
+ for (const key of Object.keys(item.customFields)) {
453
+ postTypeCustomFields[pt].add(key);
454
+ }
455
+ }
456
+ }
457
+ }
458
+ } else if (pt === 'post' || pt === 'page') {
459
+ const items = mockData[pt];
460
+ if (Array.isArray(items)) {
461
+ for (const item of items) {
462
+ if (item._terms && typeof item._terms === 'object') {
463
+ for (const tax of Object.keys(item._terms)) {
464
+ postTypeTaxonomies[pt].add(tax);
465
+ }
466
+ }
467
+ if (item.customFields && typeof item.customFields === 'object') {
468
+ for (const key of Object.keys(item.customFields)) {
469
+ postTypeCustomFields[pt].add(key);
470
+ }
471
+ }
472
+ }
473
+ }
474
+ }
475
+ }
476
+ } catch {}
477
+ }
478
+
383
479
  const validSlugs = new Set(["page"]);
384
480
  const pagesDir = path.join(themeRoot, "src", "app", "pages");
385
481
  if (existsSync(pagesDir)) {
@@ -557,6 +653,57 @@ export function runStaticLintChecks(themeRoot) {
557
653
  }
558
654
  }
559
655
 
656
+ // 5. useWpQuery arguments audit
657
+ const useWpQueryRegex = /useWpQuery\s*\(\s*(\{[\s\S]*?\})\s*\)/g;
658
+ let queryMatch;
659
+ while ((queryMatch = useWpQueryRegex.exec(content)) !== null) {
660
+ const argsStr = queryMatch[1];
661
+
662
+ const postTypeMatch = argsStr.match(/postType\s*:\s*['"]([^'"]+)['"]/);
663
+ const postType = postTypeMatch ? postTypeMatch[1] : 'post';
664
+
665
+ if (!validPostTypes.has(postType)) {
666
+ violations.push({
667
+ type: "query",
668
+ file: relFile,
669
+ message: `useWpQuery references unregistered postType "${postType}".`,
670
+ severity: "warning"
671
+ });
672
+ } else {
673
+ // Validate Taxonomies inside taxQuery
674
+ const taxRegex = /\btaxonomy\s*:\s*['"]([^'"]+)['"]/g;
675
+ let taxMatch;
676
+ const allowedTaxonomies = postTypeTaxonomies[postType] || new Set();
677
+ while ((taxMatch = taxRegex.exec(argsStr)) !== null) {
678
+ const taxSlug = taxMatch[1];
679
+ if (!allowedTaxonomies.has(taxSlug)) {
680
+ violations.push({
681
+ type: "query",
682
+ file: relFile,
683
+ message: `useWpQuery in ${path.basename(filePath)} queries taxonomy "${taxSlug}", which is not registered for postType "${postType}" in wp.config.ts.`,
684
+ severity: "warning"
685
+ });
686
+ }
687
+ }
688
+
689
+ // Validate Custom Fields inside metaQuery
690
+ const keyRegex = /\bkey\s*:\s*['"]([^'"]+)['"]/g;
691
+ let keyMatch;
692
+ const allowedFields = postTypeCustomFields[postType] || new Set();
693
+ while ((keyMatch = keyRegex.exec(argsStr)) !== null) {
694
+ const fieldKey = keyMatch[1];
695
+ if (!allowedFields.has(fieldKey)) {
696
+ violations.push({
697
+ type: "query",
698
+ file: relFile,
699
+ message: `useWpQuery in ${path.basename(filePath)} queries custom field "${fieldKey}", which is not defined for postType "${postType}" in wp.config.ts.`,
700
+ severity: "warning"
701
+ });
702
+ }
703
+ }
704
+ }
705
+ }
706
+
560
707
  } catch (err) {
561
708
  console.warn(`[Static Lint] Failed to scan file ${filePath}:`, err.message);
562
709
  }
@@ -46,6 +46,11 @@ export function processMarkup(html, textDomain = 'theme') {
46
46
  '<?php echo esc_html( get_the_date() ); ?>',
47
47
  );
48
48
 
49
+ processed = processed.replace(
50
+ /__FORGEWP_THE_MODIFIED_DATE__/g,
51
+ '<?php echo esc_html( get_the_modified_date() ); ?>',
52
+ );
53
+
49
54
  processed = processed.replace(
50
55
  /__FORGEWP_THE_AUTHOR__/g,
51
56
  '<?php echo esc_html( get_the_author() ); ?>',
@@ -442,17 +442,25 @@ if (existsSync(appDir)) {
442
442
  const module = await import(pathToFileURL(filePath).href);
443
443
  const TemplateComponent = module.default;
444
444
  if (TemplateComponent) {
445
+ globalThis.__forgewpSsrQueries = {};
445
446
  const html = name === "404"
446
447
  ? renderToStaticMarkup(React.createElement(TemplateComponent))
447
448
  : renderPage(TemplateComponent);
448
449
 
450
+ const ssrState = globalThis.__forgewpSsrQueries || {};
451
+ let stateScript = "";
452
+ if (Object.keys(ssrState).length > 0) {
453
+ stateScript = `\n<script id="forgewp-initial-state" type="application/json">${JSON.stringify({ queries: ssrState })}</script>`;
454
+ }
455
+
449
456
  let extraHeadTags = "";
450
457
  const cleanHtml = html.replace(/<forgewp-head\b[^>]*>(.*?)<\/forgewp-head>/gs, (match, childrenHtml) => {
451
458
  extraHeadTags += "\n" + childrenHtml;
452
459
  return "";
453
460
  });
454
461
 
455
- writeFileSync(path.join(outDir, `${name}.html`), cleanHtml, "utf8");
462
+ const finalHtml = cleanHtml + stateScript;
463
+ writeFileSync(path.join(outDir, `${name}.html`), finalHtml, "utf8");
456
464
  console.warn(`[ForgeWP Compiler] WROTE ${name}.html to ${outDir}`);
457
465
 
458
466
  const seoProps = extractSeoPropsFromSource(filePath);
@@ -498,7 +506,14 @@ if (existsSync(pagesDir)) {
498
506
  const module = await import(pathToFileURL(pagePath).href);
499
507
  const CustomPage = module.default || Object.values(module)[0];
500
508
  if (CustomPage) {
509
+ globalThis.__forgewpSsrQueries = {};
501
510
  const customHtml = renderPage(CustomPage);
511
+ const ssrState = globalThis.__forgewpSsrQueries || {};
512
+ let stateScript = "";
513
+ if (Object.keys(ssrState).length > 0) {
514
+ stateScript = `\n<script id="forgewp-initial-state" type="application/json">${JSON.stringify({ queries: ssrState })}</script>`;
515
+ }
516
+
502
517
  let customExtraHeadTags = "";
503
518
  const cleanCustomHtml = customHtml.replace(/<forgewp-head\b[^>]*>(.*?)<\/forgewp-head>/gs, (match, childrenHtml) => {
504
519
  customExtraHeadTags += "\n" + childrenHtml;
@@ -506,7 +521,9 @@ if (existsSync(pagesDir)) {
506
521
  });
507
522
  const pageName = pageFile.replace(".tsx", "");
508
523
  const slug = pageName.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
509
- writeFileSync(path.join(outDir, `template-${slug}.html`), cleanCustomHtml, "utf8");
524
+
525
+ const finalHtml = cleanCustomHtml + stateScript;
526
+ writeFileSync(path.join(outDir, `template-${slug}.html`), finalHtml, "utf8");
510
527
  console.warn(`WROTE template-${slug}.html to ${outDir}`);
511
528
 
512
529
  const customSeo = extractSeoPropsFromSource(pagePath);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@forgewp/compiler",
3
- "version": "0.4.1",
3
+ "version": "0.4.2",
4
4
  "description": "Compile ForgeWP React themes into installable WordPress themes",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -20,6 +20,7 @@
20
20
  "files": [
21
21
  "bin",
22
22
  "lib",
23
+ "templates",
23
24
  "define-config.js",
24
25
  "define-config.d.ts"
25
26
  ],
@@ -31,7 +32,7 @@
31
32
  "jiti": "^2.6.1",
32
33
  "picocolors": "^1.1.1",
33
34
  "react-helmet-async": "^3.0.0",
34
- "@forgewp/ui": "0.4.1"
35
+ "@forgewp/ui": "0.4.2"
35
36
  },
36
37
  "devDependencies": {
37
38
  "@types/node": "^22.19.19"