@forgewp/compiler 0.3.0 → 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.
- package/README.md +24 -5
- package/bin/analyze.js +158 -0
- package/bin/cli.js +33 -4
- package/bin/doctor.js +125 -11
- package/bin/export.js +20 -0
- package/bin/fresh.js +32 -343
- package/bin/i18n-extract.js +121 -0
- package/bin/i18n-translate.js +112 -0
- package/bin/make-block.js +27 -60
- package/bin/make-island.js +72 -0
- package/bin/make-post-type.js +6 -6
- package/bin/make-template.js +145 -0
- package/bin/repair.js +2 -2
- package/bin/sync-hooks.js +221 -0
- package/bin/sync-routes.js +28 -158
- package/define-config.d.ts +1 -0
- package/define-config.js +1 -0
- package/lib/adapters/html-adapter.js +65 -0
- package/lib/adapters/stub-adapter.js +49 -0
- package/lib/add-component.js +282 -183
- package/lib/asset-loader.js +27 -0
- package/lib/block-compiler.js +552 -0
- package/lib/blueprints.js +15 -501
- package/lib/define-config.d.ts +3 -0
- package/lib/define-config.js +8 -0
- package/lib/diagnostics.js +798 -0
- package/lib/export-theme.js +81 -18
- package/lib/framework-adapter.js +34 -0
- package/lib/functions-builder.js +2044 -0
- package/lib/generate-theme.js +1140 -1352
- package/lib/hydration-scanner.js +663 -21
- package/lib/i18n/extractor.js +60 -0
- package/lib/i18n/providers.js +165 -0
- package/lib/index.d.ts +115 -3
- package/lib/index.js +19 -5
- package/lib/load-config.js +122 -6
- package/lib/markup-processor.js +589 -0
- package/lib/php-builders.js +381 -0
- package/lib/react-adapter.js +1336 -0
- package/lib/render-static.js +9 -82
- package/lib/render-theme.mts +543 -232
- package/lib/screenshot-fallback.png +0 -0
- package/lib/types.js +1 -0
- package/lib/validate-export.js +183 -0
- package/package.json +15 -3
- package/templates/PresetsStyle.tsx +74 -0
- package/templates/SEO.tsx +109 -0
- package/templates/forgewp-config.ts +43 -0
- package/templates/menus.json +11 -0
- package/templates/mock-data.json +434 -0
- package/templates/wordpress.tsx +1297 -0
- package/bin/make-component.js +0 -200
package/lib/render-theme.mts
CHANGED
|
@@ -1,232 +1,543 @@
|
|
|
1
|
-
import { existsSync, readFileSync, mkdirSync, writeFileSync } from "node:fs";
|
|
2
|
-
import path from "node:path";
|
|
3
|
-
import { pathToFileURL } from "node:url";
|
|
4
|
-
import { createRequire } from "node:module";
|
|
5
|
-
|
|
6
|
-
const
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
const
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
const
|
|
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
|
-
const
|
|
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
|
-
if (
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
const
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
if (
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
const
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
//
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
const
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
if (
|
|
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
|
-
|
|
1
|
+
import { existsSync, readFileSync, mkdirSync, writeFileSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { pathToFileURL, fileURLToPath } from "node:url";
|
|
4
|
+
import { createRequire, register } from "node:module";
|
|
5
|
+
|
|
6
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
7
|
+
register(pathToFileURL(path.join(__dirname, "asset-loader.js")).href);
|
|
8
|
+
|
|
9
|
+
const themeRoot = process.argv[2];
|
|
10
|
+
|
|
11
|
+
if (!themeRoot) {
|
|
12
|
+
console.error("Usage: render-theme.mts <theme-root>");
|
|
13
|
+
process.exit(1);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// Use the theme's own node_modules for ALL packages (React 19)
|
|
17
|
+
const require = createRequire(path.join(themeRoot, "package.json"));
|
|
18
|
+
const React = require("react");
|
|
19
|
+
globalThis.React = React; // Polyfill for classic JSX transform in Node.js
|
|
20
|
+
|
|
21
|
+
// Resilient browser globals polyfills for Node SSR/compile-time rendering
|
|
22
|
+
if (typeof globalThis.window === "undefined") {
|
|
23
|
+
const mockLocation = {
|
|
24
|
+
pathname: "/",
|
|
25
|
+
search: "",
|
|
26
|
+
hash: "",
|
|
27
|
+
href: "http://localhost/",
|
|
28
|
+
origin: "http://localhost",
|
|
29
|
+
assign: () => {},
|
|
30
|
+
replace: () => {},
|
|
31
|
+
reload: () => {}
|
|
32
|
+
};
|
|
33
|
+
globalThis.window = {
|
|
34
|
+
location: mockLocation,
|
|
35
|
+
navigator: { userAgent: "Node" },
|
|
36
|
+
addEventListener: () => {},
|
|
37
|
+
removeEventListener: () => {},
|
|
38
|
+
dispatchEvent: () => false,
|
|
39
|
+
_forgeWpCompileTime: true,
|
|
40
|
+
} as any;
|
|
41
|
+
globalThis.location = mockLocation as any;
|
|
42
|
+
globalThis.document = {
|
|
43
|
+
addEventListener: () => {},
|
|
44
|
+
removeEventListener: () => {},
|
|
45
|
+
querySelector: () => null,
|
|
46
|
+
querySelectorAll: () => [],
|
|
47
|
+
} as any;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const { renderToStaticMarkup } = require("react-dom/server");
|
|
51
|
+
|
|
52
|
+
const appUrl = pathToFileURL(path.join(themeRoot, "src", "app", "page.tsx")).href;
|
|
53
|
+
const headerPath = path.join(themeRoot, "src", "components", "SiteHeader.tsx");
|
|
54
|
+
const headerUrl = pathToFileURL(headerPath).href;
|
|
55
|
+
const footerUrl = pathToFileURL(path.join(themeRoot, "src", "components", "SiteFooter.tsx")).href;
|
|
56
|
+
const layoutUrl = pathToFileURL(path.join(themeRoot, "src", "app", "layout.tsx")).href;
|
|
57
|
+
const layoutPath = path.join(themeRoot, "src", "app", "layout.tsx");
|
|
58
|
+
|
|
59
|
+
// ── Load pages ────────────────────────────────────────────────────────────────
|
|
60
|
+
let App: any;
|
|
61
|
+
try {
|
|
62
|
+
const module = await import(appUrl);
|
|
63
|
+
App = module.default;
|
|
64
|
+
if (!App) {
|
|
65
|
+
throw new Error("Page component lacks a default export.");
|
|
66
|
+
}
|
|
67
|
+
} catch (err: any) {
|
|
68
|
+
console.error(`\n[ForgeWP Compiler Error] Failed to load the main Page component (src/app/page.tsx).`);
|
|
69
|
+
console.error(`Check for syntax errors, incorrect imports, or invalid references inside your page component.`);
|
|
70
|
+
console.error(`Error details: ${err.stack || err.message || err}\n`);
|
|
71
|
+
process.exit(1);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
let RootLayout: (props: any) => any = ({ children }: any) =>
|
|
75
|
+
React.createElement(React.Fragment, null, children);
|
|
76
|
+
if (existsSync(layoutPath)) {
|
|
77
|
+
try {
|
|
78
|
+
const module = await import(layoutUrl);
|
|
79
|
+
RootLayout = module.default;
|
|
80
|
+
if (!RootLayout) {
|
|
81
|
+
throw new Error("Root layout component lacks a default export.");
|
|
82
|
+
}
|
|
83
|
+
} catch (err: any) {
|
|
84
|
+
console.error(`\n[ForgeWP Compiler Error] Failed to load the Root Layout component (src/app/layout.tsx).`);
|
|
85
|
+
console.error(`Check for syntax errors, incorrect imports, or invalid references inside your layout component.`);
|
|
86
|
+
console.error(`Error details: ${err.stack || err.message || err}\n`);
|
|
87
|
+
process.exit(1);
|
|
88
|
+
}
|
|
89
|
+
} else {
|
|
90
|
+
console.warn("RootLayout (src/app/layout.tsx) not found, using Fragment fallback");
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// ── Render a page inside RootLayout ──────────────────────────────────────────
|
|
94
|
+
function renderPage(PageComponent: any): string {
|
|
95
|
+
try {
|
|
96
|
+
return renderToStaticMarkup(
|
|
97
|
+
React.createElement(RootLayout, null, React.createElement(PageComponent))
|
|
98
|
+
);
|
|
99
|
+
} catch (err: any) {
|
|
100
|
+
console.error(`\n[ForgeWP Compiler Error] Server-Side Rendering (SSR) failed for Page Component.`);
|
|
101
|
+
console.error(`This typically happens if you use browser-only globals (like 'window', 'document', 'localStorage') at render-time, or if a component throws during execution.`);
|
|
102
|
+
console.error(`Ensure browser-specific logic is placed inside useEffect() or is executed only in the client.`);
|
|
103
|
+
console.error(`Error details: ${err.stack || err.message || err}\n`);
|
|
104
|
+
process.exit(1);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
let textDomain = "forgewp";
|
|
109
|
+
try {
|
|
110
|
+
const wpConfigPath = path.join(themeRoot, "wp.config.ts");
|
|
111
|
+
if (existsSync(wpConfigPath)) {
|
|
112
|
+
const configContent = readFileSync(wpConfigPath, "utf8");
|
|
113
|
+
const domainMatch = configContent.match(/textDomain\s*:\s*['"]([^'"]+)['"]/);
|
|
114
|
+
if (domainMatch) {
|
|
115
|
+
textDomain = domainMatch[1];
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
} catch (e) {}
|
|
119
|
+
|
|
120
|
+
function translateExpressionToPhp(expression: string, propName: string): string {
|
|
121
|
+
expression = expression.trim();
|
|
122
|
+
|
|
123
|
+
// 1. Check for useWpTitle()
|
|
124
|
+
if (expression.includes("useWpTitle(")) {
|
|
125
|
+
return `<?php echo esc_attr(get_the_title()); ?>`;
|
|
126
|
+
}
|
|
127
|
+
// 2. Check for useWpExcerpt()
|
|
128
|
+
if (expression.includes("useWpExcerpt(")) {
|
|
129
|
+
return `<?php echo esc_attr(get_the_excerpt()); ?>`;
|
|
130
|
+
}
|
|
131
|
+
// 3. Check for useWpFeaturedImage()
|
|
132
|
+
if (expression.includes("useWpFeaturedImage(")) {
|
|
133
|
+
return `<?php echo esc_url(get_the_post_thumbnail_url(get_the_ID(), 'full')); ?>`;
|
|
134
|
+
}
|
|
135
|
+
// 4. Check for useWpPermalink()
|
|
136
|
+
if (expression.includes("useWpPermalink(")) {
|
|
137
|
+
return `<?php echo esc_url(get_permalink()); ?>`;
|
|
138
|
+
}
|
|
139
|
+
// 5. Check for useWpCustomField / useWpField / useWpMeta
|
|
140
|
+
const metaMatch = expression.match(/useWp(?:CustomField|Field|Meta)\s*\(\s*['"]([^'"]+)['"]/);
|
|
141
|
+
if (metaMatch) {
|
|
142
|
+
const key = metaMatch[1];
|
|
143
|
+
const isUrl = propName === "canonical" || propName === "ogImage" || key.includes("url") || key.includes("image") || key.includes("website");
|
|
144
|
+
const escFn = isUrl ? "esc_url" : "esc_attr";
|
|
145
|
+
return `<?php echo ${escFn}(get_post_meta(get_the_ID(), '${key}', true)); ?>`;
|
|
146
|
+
}
|
|
147
|
+
// 6. Check for useWpAuthor()
|
|
148
|
+
if (expression.includes("useWpAuthor(")) {
|
|
149
|
+
return `<?php echo esc_attr(get_the_author()); ?>`;
|
|
150
|
+
}
|
|
151
|
+
// 7. Check for useWpDate()
|
|
152
|
+
if (expression.includes("useWpDate(")) {
|
|
153
|
+
return `<?php echo esc_attr(get_the_date()); ?>`;
|
|
154
|
+
}
|
|
155
|
+
// 8. Check for useWpOption()
|
|
156
|
+
const optionMatch = expression.match(/useWpOption\s*\(\s*['"]([^'"]+)['"]/);
|
|
157
|
+
if (optionMatch) {
|
|
158
|
+
const key = optionMatch[1];
|
|
159
|
+
return `<?php echo esc_attr(get_option('${key}', '')); ?>`;
|
|
160
|
+
}
|
|
161
|
+
// 9. Check for useWpThemeMod()
|
|
162
|
+
const themeModMatch = expression.match(/useWpThemeMod\s*\(\s*['"]([^'"]+)['"]/);
|
|
163
|
+
if (themeModMatch) {
|
|
164
|
+
const key = themeModMatch[1];
|
|
165
|
+
return `<?php echo esc_attr(get_theme_mod('${key}', '')); ?>`;
|
|
166
|
+
}
|
|
167
|
+
// 10. Check for useWpPageLink
|
|
168
|
+
const pageLinkMatch = expression.match(/useWpPageLink\s*\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]/);
|
|
169
|
+
if (pageLinkMatch) {
|
|
170
|
+
const templateName = pageLinkMatch[1];
|
|
171
|
+
const fallbackUrl = pageLinkMatch[2];
|
|
172
|
+
return `<?php $matched = get_pages(array('meta_key' => '_wp_page_template', 'meta_value' => 'page-${templateName.replace(/-page$/, "")}.php', 'number' => 1)); echo esc_url(!empty($matched) ? get_permalink($matched[0]->ID) : home_url('${fallbackUrl}')); ?>`;
|
|
173
|
+
}
|
|
174
|
+
// 11. Check for internationalization __()
|
|
175
|
+
const i18nMatch = expression.match(/__\s*\(\s*['"]([^'"]+)['"]/);
|
|
176
|
+
if (i18nMatch) {
|
|
177
|
+
const str = i18nMatch[1];
|
|
178
|
+
return `<?php echo esc_attr(__('${str}', '${textDomain}')); ?>`;
|
|
179
|
+
}
|
|
180
|
+
// 12. Check for literal string in quotes
|
|
181
|
+
const literalMatch = expression.match(/^\s*['"]([^'"]+)['"]\s*$/);
|
|
182
|
+
if (literalMatch) {
|
|
183
|
+
return literalMatch[1];
|
|
184
|
+
}
|
|
185
|
+
return "";
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function extractBalancedJsxExpression(src: string, propName: string): string {
|
|
189
|
+
const marker = `${propName}={`;
|
|
190
|
+
const index = src.indexOf(marker);
|
|
191
|
+
if (index === -1) return "";
|
|
192
|
+
let braces = 1;
|
|
193
|
+
let start = index + marker.length;
|
|
194
|
+
let i = start;
|
|
195
|
+
while (braces > 0 && i < src.length) {
|
|
196
|
+
if (src[i] === "{") braces++;
|
|
197
|
+
else if (src[i] === "}") braces--;
|
|
198
|
+
i++;
|
|
199
|
+
}
|
|
200
|
+
return src.slice(start, i - 1).trim();
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function compileSchemaObject(schemaExpr: string, fileSrc: string): string {
|
|
204
|
+
return schemaExpr.replace(/("[\w@]+"|[\w@]+)\s*:\s*([^,\n}]+)/g, (match, key, valStr) => {
|
|
205
|
+
let val = valStr.trim();
|
|
206
|
+
if (/^["']([^"']*)["']$/.test(val)) {
|
|
207
|
+
return `${key}: ${val}`;
|
|
208
|
+
}
|
|
209
|
+
if (/^(true|false|[0-9.]+)$/i.test(val)) {
|
|
210
|
+
return `${key}: ${val}`;
|
|
211
|
+
}
|
|
212
|
+
let resolved = val;
|
|
213
|
+
if (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(val)) {
|
|
214
|
+
const declRegex = new RegExp(`(?:const|let|var)\\s+${val}\\s*=\\s*([^;\\n]+)`);
|
|
215
|
+
const declMatch = fileSrc.match(declRegex);
|
|
216
|
+
if (declMatch) {
|
|
217
|
+
resolved = declMatch[1].trim();
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
const phpVal = translateExpressionToPhp(resolved, "");
|
|
221
|
+
if (phpVal) {
|
|
222
|
+
return `${key}: "${phpVal}"`;
|
|
223
|
+
}
|
|
224
|
+
return `${key}: ${val}`;
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// ── SEO extraction from source files (React 19 SSR-safe) ─────────────────────
|
|
229
|
+
// react-helmet-async v3 disabled server-side context for React 19 —
|
|
230
|
+
// HelmetProvider is a Fragment at SSR time so helmetContext.helmet is never set.
|
|
231
|
+
// Instead we parse <SEO .../> props directly from the source TSX file.
|
|
232
|
+
|
|
233
|
+
function extractSeoPropsFromSource(filePath: string): Record<string, string> {
|
|
234
|
+
if (!filePath || !existsSync(filePath)) return {};
|
|
235
|
+
|
|
236
|
+
let src = readFileSync(filePath, "utf8");
|
|
237
|
+
|
|
238
|
+
// Strip JSX block comments so we don't match <SEO /> mentions inside them
|
|
239
|
+
src = src.replace(/\{\/\*[\s\S]*?\*\/\}/g, "");
|
|
240
|
+
|
|
241
|
+
// Find the first <SEO ... /> or <WpHead ... /> (multiline, s flag)
|
|
242
|
+
const seoMatch = src.match(/<(?:SEO|WpHead)\b([^>]*?)(?:\/>|>)/s);
|
|
243
|
+
if (!seoMatch) {
|
|
244
|
+
// If not found, let's look for local imports to follow
|
|
245
|
+
const importRegex = /import\s+.*?\s+from\s+['"](\.\.?\/[^'"]+)['"]/g;
|
|
246
|
+
let match;
|
|
247
|
+
const dir = path.dirname(filePath);
|
|
248
|
+
while ((match = importRegex.exec(src)) !== null) {
|
|
249
|
+
const relativePath = match[1];
|
|
250
|
+
// Try resolving with common extensions
|
|
251
|
+
for (const ext of [".tsx", ".ts", "/index.tsx", "/index.ts"]) {
|
|
252
|
+
const resolvedPath = path.resolve(dir, relativePath + ext);
|
|
253
|
+
if (existsSync(resolvedPath)) {
|
|
254
|
+
const importedProps = extractSeoPropsFromSource(resolvedPath);
|
|
255
|
+
if (Object.keys(importedProps).length > 0) {
|
|
256
|
+
return importedProps; // Return the first matching props we find
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
return {};
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const attribsStr = seoMatch[1];
|
|
265
|
+
const props: Record<string, string> = {};
|
|
266
|
+
|
|
267
|
+
// Double-quoted values: prop="value with & and spaces"
|
|
268
|
+
let m: RegExpExecArray | null;
|
|
269
|
+
const dqPattern = /(\w+)\s*=\s*"([^"]*)"/g;
|
|
270
|
+
while ((m = dqPattern.exec(attribsStr)) !== null) props[m[1]] = m[2];
|
|
271
|
+
|
|
272
|
+
// Single-quoted values: prop='value'
|
|
273
|
+
const sqPattern = /(\w+)\s*=\s*'([^']*)'/g;
|
|
274
|
+
while ((m = sqPattern.exec(attribsStr)) !== null) if (!props[m[1]]) props[m[1]] = m[2];
|
|
275
|
+
|
|
276
|
+
// JSX string expressions: prop={"value"} or prop={'value'}
|
|
277
|
+
const jsxPattern = /(\w+)\s*=\s*\{["']([^"']*)["']\}/g;
|
|
278
|
+
while ((m = jsxPattern.exec(attribsStr)) !== null) if (!props[m[1]]) props[m[1]] = m[2];
|
|
279
|
+
|
|
280
|
+
// JSX brace expressions: prop={expression}
|
|
281
|
+
const exprPattern = /(\w+)\s*=\s*\{([^}]*)\}/g;
|
|
282
|
+
while ((m = exprPattern.exec(attribsStr)) !== null) {
|
|
283
|
+
const propName = m[1];
|
|
284
|
+
const expression = m[2].trim();
|
|
285
|
+
if (!props[propName]) {
|
|
286
|
+
let resolvedExpression = expression;
|
|
287
|
+
|
|
288
|
+
// Trace variable name back to declaration if it is a simple identifier
|
|
289
|
+
if (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(expression)) {
|
|
290
|
+
const declRegex = new RegExp(`(?:const|let|var)\\s+${expression}\\s*=\\s*([^;\\n]+)`);
|
|
291
|
+
const declMatch = src.match(declRegex);
|
|
292
|
+
if (declMatch) {
|
|
293
|
+
resolvedExpression = declMatch[1].trim();
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
const phpVal = translateExpressionToPhp(resolvedExpression, propName);
|
|
298
|
+
if (phpVal) {
|
|
299
|
+
props[propName] = phpVal;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// Extract and compile inline schema if present
|
|
305
|
+
if (attribsStr.includes("schema=")) {
|
|
306
|
+
const rawSchema = extractBalancedJsxExpression(src, "schema");
|
|
307
|
+
if (rawSchema) {
|
|
308
|
+
const compiledSchema = compileSchemaObject(rawSchema, src);
|
|
309
|
+
if (compiledSchema) {
|
|
310
|
+
props["schema"] = compiledSchema;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
return props;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function buildHeadHtml(
|
|
319
|
+
base: Record<string, string>,
|
|
320
|
+
override: Record<string, string> = {}
|
|
321
|
+
): string {
|
|
322
|
+
// Merge: per-page overrides win over layout defaults
|
|
323
|
+
const p = { ...base, ...override };
|
|
324
|
+
|
|
325
|
+
const {
|
|
326
|
+
title,
|
|
327
|
+
description,
|
|
328
|
+
keywords,
|
|
329
|
+
ogTitle,
|
|
330
|
+
ogDescription,
|
|
331
|
+
ogImage,
|
|
332
|
+
ogType = "website",
|
|
333
|
+
twitterCard = "summary_large_image",
|
|
334
|
+
twitterCreator,
|
|
335
|
+
canonical,
|
|
336
|
+
} = p;
|
|
337
|
+
|
|
338
|
+
const tags: string[] = [];
|
|
339
|
+
|
|
340
|
+
if (title && !title.includes("FORGEWP")) tags.push(`<title>${title}</title>`);
|
|
341
|
+
if (description) tags.push(`<meta name="description" content="${description}">`);
|
|
342
|
+
if (keywords) tags.push(`<meta name="keywords" content="${keywords}">`);
|
|
343
|
+
if (canonical) tags.push(`<link rel="canonical" href="${canonical}">`);
|
|
344
|
+
|
|
345
|
+
// Open Graph
|
|
346
|
+
tags.push(`<meta property="og:type" content="${ogType}">`);
|
|
347
|
+
const ogTitleVal = ogTitle || title;
|
|
348
|
+
if (ogTitleVal && !ogTitleVal.includes("FORGEWP")) {
|
|
349
|
+
tags.push(`<meta property="og:title" content="${ogTitleVal}">`);
|
|
350
|
+
}
|
|
351
|
+
const ogDescVal = ogDescription || description;
|
|
352
|
+
if (ogDescVal) tags.push(`<meta property="og:description" content="${ogDescVal}">`);
|
|
353
|
+
if (ogImage) tags.push(`<meta property="og:image" content="${ogImage}">`);
|
|
354
|
+
|
|
355
|
+
// Twitter
|
|
356
|
+
tags.push(`<meta name="twitter:card" content="${twitterCard}">`);
|
|
357
|
+
if (ogTitleVal && !ogTitleVal.includes("FORGEWP")) {
|
|
358
|
+
tags.push(`<meta name="twitter:title" content="${ogTitleVal}">`);
|
|
359
|
+
}
|
|
360
|
+
if (ogDescVal) tags.push(`<meta name="twitter:description" content="${ogDescVal}">`);
|
|
361
|
+
if (twitterCreator) tags.push(`<meta name="twitter:creator" content="${twitterCreator}">`);
|
|
362
|
+
if (p.schema) {
|
|
363
|
+
tags.push(`<script type="application/ld+json">\n${p.schema}\n</script>`);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
return tags.join("\n");
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// ── Render header / footer fragments ─────────────────────────────────────────
|
|
370
|
+
const footerPath = path.join(themeRoot, "src", "components", "SiteFooter.tsx");
|
|
371
|
+
|
|
372
|
+
let headerHtml = "";
|
|
373
|
+
if (existsSync(headerPath)) {
|
|
374
|
+
try {
|
|
375
|
+
const module = await import(headerUrl);
|
|
376
|
+
const SiteHeader = module.SiteHeader || module.default;
|
|
377
|
+
if (!SiteHeader) {
|
|
378
|
+
throw new Error("SiteHeader component not found in export (expects named export 'SiteHeader' or default export).");
|
|
379
|
+
}
|
|
380
|
+
headerHtml = renderToStaticMarkup(React.createElement(SiteHeader));
|
|
381
|
+
} catch (err: any) {
|
|
382
|
+
console.error(`\n[ForgeWP Compiler Error] Failed to load or render the Site Header component (src/components/SiteHeader.tsx).`);
|
|
383
|
+
console.error(`Error details: ${err.stack || err.message || err}\n`);
|
|
384
|
+
process.exit(1);
|
|
385
|
+
}
|
|
386
|
+
} else {
|
|
387
|
+
console.warn("SiteHeader (src/components/SiteHeader.tsx) not found, skipping separate render");
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
let footerHtml = "";
|
|
391
|
+
if (existsSync(footerPath)) {
|
|
392
|
+
try {
|
|
393
|
+
const module = await import(footerUrl);
|
|
394
|
+
const SiteFooter = module.SiteFooter || module.default;
|
|
395
|
+
if (!SiteFooter) {
|
|
396
|
+
throw new Error("SiteFooter component not found in export (expects named export 'SiteFooter' or default export).");
|
|
397
|
+
}
|
|
398
|
+
footerHtml = renderToStaticMarkup(React.createElement(SiteFooter));
|
|
399
|
+
} catch (err: any) {
|
|
400
|
+
console.error(`\n[ForgeWP Compiler Error] Failed to load or render the Site Footer component (src/components/SiteFooter.tsx).`);
|
|
401
|
+
console.error(`Error details: ${err.stack || err.message || err}\n`);
|
|
402
|
+
process.exit(1);
|
|
403
|
+
}
|
|
404
|
+
} else {
|
|
405
|
+
console.warn("SiteFooter (src/components/SiteFooter.tsx) not found, skipping separate render");
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
// ── Render pages ──────────────────────────────────────────────────────────────
|
|
409
|
+
const appHtml = renderPage(App);
|
|
410
|
+
let layoutExtraHeadTags = "";
|
|
411
|
+
const cleanAppHtml = appHtml.replace(/<forgewp-head\b[^>]*>(.*?)<\/forgewp-head>/gs, (match, childrenHtml) => {
|
|
412
|
+
layoutExtraHeadTags += "\n" + childrenHtml;
|
|
413
|
+
return "";
|
|
414
|
+
});
|
|
415
|
+
|
|
416
|
+
// ── Compile Dynamic WordPress Template Hierarchy ──────────────────────────────
|
|
417
|
+
const layoutSeo = extractSeoPropsFromSource(layoutPath);
|
|
418
|
+
let headHtml = buildHeadHtml(layoutSeo);
|
|
419
|
+
const outDir = path.join(themeRoot, ".forgewp");
|
|
420
|
+
mkdirSync(outDir, { recursive: true });
|
|
421
|
+
|
|
422
|
+
const appDir = path.join(themeRoot, "src", "app");
|
|
423
|
+
if (existsSync(appDir)) {
|
|
424
|
+
const { readdirSync } = require("node:fs");
|
|
425
|
+
const files = readdirSync(appDir);
|
|
426
|
+
for (const file of files) {
|
|
427
|
+
if (file.endsWith(".tsx")) {
|
|
428
|
+
const name = file.replace(".tsx", "");
|
|
429
|
+
const isWpTemplate =
|
|
430
|
+
name === "single" ||
|
|
431
|
+
name === "archive" ||
|
|
432
|
+
name === "404" ||
|
|
433
|
+
name === "taxonomy" ||
|
|
434
|
+
name.startsWith("single-") ||
|
|
435
|
+
name.startsWith("taxonomy-") ||
|
|
436
|
+
name.startsWith("archive-");
|
|
437
|
+
|
|
438
|
+
if (isWpTemplate) {
|
|
439
|
+
const filePath = path.join(appDir, file);
|
|
440
|
+
console.warn(`[ForgeWP Compiler] Attempting to compile template: ${file}`);
|
|
441
|
+
try {
|
|
442
|
+
const module = await import(pathToFileURL(filePath).href);
|
|
443
|
+
const TemplateComponent = module.default;
|
|
444
|
+
if (TemplateComponent) {
|
|
445
|
+
globalThis.__forgewpSsrQueries = {};
|
|
446
|
+
const html = name === "404"
|
|
447
|
+
? renderToStaticMarkup(React.createElement(TemplateComponent))
|
|
448
|
+
: renderPage(TemplateComponent);
|
|
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
|
+
|
|
456
|
+
let extraHeadTags = "";
|
|
457
|
+
const cleanHtml = html.replace(/<forgewp-head\b[^>]*>(.*?)<\/forgewp-head>/gs, (match, childrenHtml) => {
|
|
458
|
+
extraHeadTags += "\n" + childrenHtml;
|
|
459
|
+
return "";
|
|
460
|
+
});
|
|
461
|
+
|
|
462
|
+
const finalHtml = cleanHtml + stateScript;
|
|
463
|
+
writeFileSync(path.join(outDir, `${name}.html`), finalHtml, "utf8");
|
|
464
|
+
console.warn(`[ForgeWP Compiler] WROTE ${name}.html to ${outDir}`);
|
|
465
|
+
|
|
466
|
+
const seoProps = extractSeoPropsFromSource(filePath);
|
|
467
|
+
let customHeadHtml = buildHeadHtml(layoutSeo, seoProps);
|
|
468
|
+
if (extraHeadTags) {
|
|
469
|
+
customHeadHtml += "\n" + extraHeadTags;
|
|
470
|
+
}
|
|
471
|
+
writeFileSync(path.join(outDir, `${name}-head.html`), customHeadHtml, "utf8");
|
|
472
|
+
console.warn(`[ForgeWP Compiler] WROTE ${name}-head.html to ${outDir}`);
|
|
473
|
+
}
|
|
474
|
+
} catch (e: any) {
|
|
475
|
+
console.warn(`[ForgeWP Compiler Warning] Failed to render WP template ${file}:`, e.message);
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
// ── Write outputs ─────────────────────────────────────────────────────────────
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
writeFileSync(path.join(outDir, "header.html"), headerHtml, "utf8");
|
|
486
|
+
writeFileSync(path.join(outDir, "footer.html"), footerHtml, "utf8");
|
|
487
|
+
writeFileSync(path.join(outDir, "app.html"), cleanAppHtml, "utf8");
|
|
488
|
+
let finalHeadHtml = headHtml;
|
|
489
|
+
if (layoutExtraHeadTags) {
|
|
490
|
+
finalHeadHtml += "\n" + layoutExtraHeadTags;
|
|
491
|
+
}
|
|
492
|
+
writeFileSync(path.join(outDir, "head.html"), finalHeadHtml, "utf8");
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
// ── Compile Custom Page Templates ──────────────────────────────────────────────
|
|
496
|
+
const pagesDir = path.join(themeRoot, "src", "app", "pages");
|
|
497
|
+
console.warn("CHECKING PAGES DIR: " + pagesDir + " EXISTS: " + existsSync(pagesDir));
|
|
498
|
+
if (existsSync(pagesDir)) {
|
|
499
|
+
const { readdirSync } = require("node:fs");
|
|
500
|
+
const pages = readdirSync(pagesDir).filter(f => f.endsWith(".tsx"));
|
|
501
|
+
|
|
502
|
+
for (const pageFile of pages) {
|
|
503
|
+
const pagePath = path.join(pagesDir, pageFile);
|
|
504
|
+
console.warn(`Attempting to compile template: ${pageFile}`);
|
|
505
|
+
try {
|
|
506
|
+
const module = await import(pathToFileURL(pagePath).href);
|
|
507
|
+
const CustomPage = module.default || Object.values(module)[0];
|
|
508
|
+
if (CustomPage) {
|
|
509
|
+
globalThis.__forgewpSsrQueries = {};
|
|
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
|
+
|
|
517
|
+
let customExtraHeadTags = "";
|
|
518
|
+
const cleanCustomHtml = customHtml.replace(/<forgewp-head\b[^>]*>(.*?)<\/forgewp-head>/gs, (match, childrenHtml) => {
|
|
519
|
+
customExtraHeadTags += "\n" + childrenHtml;
|
|
520
|
+
return "";
|
|
521
|
+
});
|
|
522
|
+
const pageName = pageFile.replace(".tsx", "");
|
|
523
|
+
const slug = pageName.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
|
|
524
|
+
|
|
525
|
+
const finalHtml = cleanCustomHtml + stateScript;
|
|
526
|
+
writeFileSync(path.join(outDir, `template-${slug}.html`), finalHtml, "utf8");
|
|
527
|
+
console.warn(`WROTE template-${slug}.html to ${outDir}`);
|
|
528
|
+
|
|
529
|
+
const customSeo = extractSeoPropsFromSource(pagePath);
|
|
530
|
+
let customHeadHtml = buildHeadHtml(layoutSeo, customSeo);
|
|
531
|
+
if (customExtraHeadTags) {
|
|
532
|
+
customHeadHtml += "\n" + customExtraHeadTags;
|
|
533
|
+
}
|
|
534
|
+
writeFileSync(path.join(outDir, `template-${slug}-head.html`), customHeadHtml, "utf8");
|
|
535
|
+
console.warn(`WROTE template-${slug}-head.html to ${outDir}`);
|
|
536
|
+
}
|
|
537
|
+
} catch (e) {
|
|
538
|
+
console.warn(`Failed to render custom page ${pageFile}:`, e.message);
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
process.stdout.write(outDir);
|