@forgewp/compiler 0.2.0 → 0.4.1

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.
Files changed (45) hide show
  1. package/README.md +24 -5
  2. package/bin/analyze.js +158 -0
  3. package/bin/cli.js +29 -4
  4. package/bin/doctor.js +125 -11
  5. package/bin/export.js +20 -0
  6. package/bin/fresh.js +32 -343
  7. package/bin/i18n-extract.js +121 -0
  8. package/bin/i18n-translate.js +112 -0
  9. package/bin/make-block.js +27 -60
  10. package/bin/make-island.js +72 -0
  11. package/bin/make-post-type.js +6 -6
  12. package/bin/make-template.js +145 -0
  13. package/bin/repair.js +2 -2
  14. package/bin/sync-routes.js +28 -158
  15. package/define-config.d.ts +1 -0
  16. package/define-config.js +1 -0
  17. package/lib/adapters/html-adapter.js +65 -0
  18. package/lib/adapters/stub-adapter.js +49 -0
  19. package/lib/add-component.js +290 -73
  20. package/lib/asset-loader.js +27 -0
  21. package/lib/block-compiler.js +552 -0
  22. package/lib/blueprints.js +1459 -501
  23. package/lib/define-config.d.ts +3 -0
  24. package/lib/define-config.js +8 -0
  25. package/lib/diagnostics.js +798 -0
  26. package/lib/export-theme.js +81 -18
  27. package/lib/framework-adapter.js +34 -0
  28. package/lib/functions-builder.js +1801 -0
  29. package/lib/generate-theme.js +1019 -1143
  30. package/lib/hydration-scanner.js +674 -0
  31. package/lib/i18n/extractor.js +60 -0
  32. package/lib/i18n/providers.js +165 -0
  33. package/lib/index.d.ts +119 -1
  34. package/lib/index.js +20 -3
  35. package/lib/load-config.js +122 -6
  36. package/lib/markup-processor.js +584 -0
  37. package/lib/php-builders.js +381 -0
  38. package/lib/react-adapter.js +1336 -0
  39. package/lib/render-static.js +9 -82
  40. package/lib/render-theme.mts +526 -232
  41. package/lib/screenshot-fallback.png +0 -0
  42. package/lib/types.js +1 -0
  43. package/lib/validate-export.js +183 -0
  44. package/package.json +14 -3
  45. package/bin/make-component.js +0 -200
@@ -1,232 +1,526 @@
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 themeRoot = process.argv[2];
7
-
8
- if (!themeRoot) {
9
- console.error("Usage: render-theme.mts <theme-root>");
10
- process.exit(1);
11
- }
12
-
13
- // Use the theme's own node_modules for ALL packages (React 19)
14
- const require = createRequire(path.join(themeRoot, "package.json"));
15
- const React = require("react");
16
- globalThis.React = React; // Polyfill for classic JSX transform in Node.js
17
- const { renderToStaticMarkup } = require("react-dom/server");
18
-
19
- const appUrl = pathToFileURL(path.join(themeRoot, "src", "app", "page.tsx")).href;
20
- const headerUrl = pathToFileURL(path.join(themeRoot, "src", "components", "SiteHeader.tsx")).href;
21
- const footerUrl = pathToFileURL(path.join(themeRoot, "src", "components", "SiteFooter.tsx")).href;
22
- const layoutUrl = pathToFileURL(path.join(themeRoot, "src", "app", "layout.tsx")).href;
23
- const layoutPath = path.join(themeRoot, "src", "app", "layout.tsx");
24
-
25
- // ── Load pages ────────────────────────────────────────────────────────────────
26
- const { default: App } = await import(appUrl);
27
-
28
- let RootLayout: (props: any) => any = ({ children }: any) =>
29
- React.createElement(React.Fragment, null, children);
30
- try {
31
- const { default: LoadedLayout } = await import(layoutUrl);
32
- RootLayout = LoadedLayout;
33
- } catch {
34
- console.warn("RootLayout not found, using Fragment fallback");
35
- }
36
-
37
- // ── Render a page inside RootLayout ──────────────────────────────────────────
38
- function renderPage(PageComponent: any): string {
39
- return renderToStaticMarkup(
40
- React.createElement(RootLayout, null, React.createElement(PageComponent))
41
- );
42
- }
43
-
44
- // ── SEO extraction from source files (React 19 SSR-safe) ─────────────────────
45
- // react-helmet-async v3 disabled server-side context for React 19 —
46
- // HelmetProvider is a Fragment at SSR time so helmetContext.helmet is never set.
47
- // Instead we parse <SEO .../> props directly from the source TSX file.
48
-
49
- function extractSeoPropsFromSource(filePath: string): Record<string, string> {
50
- if (!existsSync(filePath)) return {};
51
-
52
- let src = readFileSync(filePath, "utf8");
53
-
54
- // Strip JSX block comments so we don't match <SEO /> mentions inside them
55
- src = src.replace(/\{\/\*[\s\S]*?\*\/\}/g, "");
56
-
57
- // Find the first <SEO ... /> (multiline, s flag)
58
- const seoMatch = src.match(/<SEO\b([\s\S]*?)\/>/s);
59
- if (!seoMatch) return {};
60
-
61
- const attribsStr = seoMatch[1];
62
- const props: Record<string, string> = {};
63
-
64
- // Double-quoted values: prop="value with & and spaces"
65
- let m: RegExpExecArray | null;
66
- const dqPattern = /(\w+)\s*=\s*"([^"]*)"/g;
67
- while ((m = dqPattern.exec(attribsStr)) !== null) props[m[1]] = m[2];
68
-
69
- // Single-quoted values: prop='value'
70
- const sqPattern = /(\w+)\s*=\s*'([^']*)'/g;
71
- while ((m = sqPattern.exec(attribsStr)) !== null) if (!props[m[1]]) props[m[1]] = m[2];
72
-
73
- // JSX string expressions: prop={"value"} or prop={'value'}
74
- const jsxPattern = /(\w+)\s*=\s*\{["']([^"']*)["']\}/g;
75
- while ((m = jsxPattern.exec(attribsStr)) !== null) if (!props[m[1]]) props[m[1]] = m[2];
76
-
77
- return props;
78
- }
79
-
80
- function buildHeadHtml(
81
- base: Record<string, string>,
82
- override: Record<string, string> = {}
83
- ): string {
84
- // Merge: per-page overrides win over layout defaults
85
- const p = { ...base, ...override };
86
-
87
- const {
88
- title,
89
- description,
90
- keywords,
91
- ogTitle,
92
- ogDescription,
93
- ogImage,
94
- ogType = "website",
95
- twitterCard = "summary_large_image",
96
- twitterCreator,
97
- canonical,
98
- } = p;
99
-
100
- const tags: string[] = [];
101
-
102
- if (title && !title.includes("FORGEWP")) tags.push(`<title>${title}</title>`);
103
- if (description) tags.push(`<meta name="description" content="${description}">`);
104
- if (keywords) tags.push(`<meta name="keywords" content="${keywords}">`);
105
- if (canonical) tags.push(`<link rel="canonical" href="${canonical}">`);
106
-
107
- // Open Graph
108
- tags.push(`<meta property="og:type" content="${ogType}">`);
109
- const ogTitleVal = ogTitle || title;
110
- if (ogTitleVal && !ogTitleVal.includes("FORGEWP")) {
111
- tags.push(`<meta property="og:title" content="${ogTitleVal}">`);
112
- }
113
- const ogDescVal = ogDescription || description;
114
- if (ogDescVal) tags.push(`<meta property="og:description" content="${ogDescVal}">`);
115
- if (ogImage) tags.push(`<meta property="og:image" content="${ogImage}">`);
116
-
117
- // Twitter
118
- tags.push(`<meta name="twitter:card" content="${twitterCard}">`);
119
- if (ogTitleVal && !ogTitleVal.includes("FORGEWP")) {
120
- tags.push(`<meta name="twitter:title" content="${ogTitleVal}">`);
121
- }
122
- if (ogDescVal) tags.push(`<meta name="twitter:description" content="${ogDescVal}">`);
123
- if (ogImage) tags.push(`<meta name="twitter:image" content="${ogImage}">`);
124
- if (twitterCreator) tags.push(`<meta name="twitter:creator" content="${twitterCreator}">`);
125
-
126
- return tags.join("\n");
127
- }
128
-
129
- // ── Render header / footer fragments ─────────────────────────────────────────
130
- let headerHtml = "";
131
- try {
132
- const { SiteHeader } = await import(headerUrl);
133
- headerHtml = renderToStaticMarkup(React.createElement(SiteHeader));
134
- } catch {
135
- console.warn("SiteHeader not found, skipping separate render");
136
- }
137
-
138
- let footerHtml = "";
139
- try {
140
- const { SiteFooter } = await import(footerUrl);
141
- footerHtml = renderToStaticMarkup(React.createElement(SiteFooter));
142
- } catch {
143
- console.warn("SiteFooter not found, skipping separate render");
144
- }
145
-
146
- // ── Render pages ──────────────────────────────────────────────────────────────
147
- const appHtml = renderPage(App);
148
-
149
- // single.tsx
150
- const singlePath = path.join(themeRoot, "src", "app", "single.tsx");
151
- let singleHtml = "";
152
- if (existsSync(singlePath)) {
153
- const { default: SinglePage } = await import(pathToFileURL(singlePath).href);
154
- singleHtml = renderPage(SinglePage);
155
- }
156
-
157
- // 404.tsx — rendered bare, no RootLayout (WP 404.php calls get_header/get_footer)
158
- const notFoundPath = path.join(themeRoot, "src", "app", "404.tsx");
159
- let notFoundHtml = "";
160
- if (existsSync(notFoundPath)) {
161
- const { default: NotFoundPage } = await import(pathToFileURL(notFoundPath).href);
162
- notFoundHtml = renderToStaticMarkup(React.createElement(NotFoundPage));
163
- }
164
-
165
- // archive.tsx
166
- const archivePath = path.join(themeRoot, "src", "app", "archive.tsx");
167
- let archiveHtml = "";
168
- if (existsSync(archivePath)) {
169
- const { default: ArchivePage } = await import(pathToFileURL(archivePath).href);
170
- archiveHtml = renderPage(ArchivePage);
171
- }
172
-
173
- // ── Extract SEO from source files ─────────────────────────────────────────────
174
- // Global defaults come from layout.tsx <SEO> props.
175
- // Per-page overrides come from the individual page file's <SEO> props.
176
- const layoutSeo = extractSeoPropsFromSource(layoutPath);
177
- const singleSeo = existsSync(singlePath)
178
- ? extractSeoPropsFromSource(singlePath)
179
- : {};
180
-
181
- // Global head.html (used on all pages that don't have a per-page override)
182
- const headHtml = buildHeadHtml(layoutSeo);
183
-
184
- // Per-page head HTML for single.html (merged: layout defaults + single overrides)
185
- const singleHeadHtml = buildHeadHtml(layoutSeo, singleSeo);
186
-
187
- // ── Write outputs ─────────────────────────────────────────────────────────────
188
- const outDir = path.join(themeRoot, ".forgewp");
189
- mkdirSync(outDir, { recursive: true });
190
-
191
- writeFileSync(path.join(outDir, "header.html"), headerHtml, "utf8");
192
- writeFileSync(path.join(outDir, "footer.html"), footerHtml, "utf8");
193
- writeFileSync(path.join(outDir, "app.html"), appHtml, "utf8");
194
- writeFileSync(path.join(outDir, "head.html"), headHtml, "utf8");
195
- writeFileSync(path.join(outDir, "single-head.html"), singleHeadHtml, "utf8");
196
-
197
- if (singleHtml) writeFileSync(path.join(outDir, "single.html"), singleHtml, "utf8");
198
- if (notFoundHtml) writeFileSync(path.join(outDir, "404.html"), notFoundHtml, "utf8");
199
- if (archiveHtml) writeFileSync(path.join(outDir, "archive.html"), archiveHtml, "utf8");
200
-
201
- // ── Compile Custom Page Templates ──────────────────────────────────────────────
202
- const pagesDir = path.join(themeRoot, "src", "app", "pages");
203
- console.warn("CHECKING PAGES DIR: " + pagesDir + " EXISTS: " + existsSync(pagesDir));
204
- if (existsSync(pagesDir)) {
205
- const { readdirSync } = require("node:fs");
206
- const pages = readdirSync(pagesDir).filter(f => f.endsWith(".tsx"));
207
-
208
- for (const pageFile of pages) {
209
- const pagePath = path.join(pagesDir, pageFile);
210
- console.warn(`Attempting to compile template: ${pageFile}`);
211
- try {
212
- const module = await import(pathToFileURL(pagePath).href);
213
- const CustomPage = module.default || Object.values(module)[0];
214
- if (CustomPage) {
215
- const customHtml = renderPage(CustomPage);
216
- const pageName = pageFile.replace(".tsx", "");
217
- const slug = pageName.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
218
- writeFileSync(path.join(outDir, `template-${slug}.html`), customHtml, "utf8");
219
- console.warn(`WROTE template-${slug}.html to ${outDir}`);
220
-
221
- const customSeo = extractSeoPropsFromSource(pagePath);
222
- const customHeadHtml = buildHeadHtml(layoutSeo, customSeo);
223
- writeFileSync(path.join(outDir, `template-${slug}-head.html`), customHeadHtml, "utf8");
224
- console.warn(`WROTE template-${slug}-head.html to ${outDir}`);
225
- }
226
- } catch (e) {
227
- console.warn(`Failed to render custom page ${pageFile}:`, e.message);
228
- }
229
- }
230
- }
231
-
232
- process.stdout.write(outDir);
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
+ const html = name === "404"
446
+ ? renderToStaticMarkup(React.createElement(TemplateComponent))
447
+ : renderPage(TemplateComponent);
448
+
449
+ let extraHeadTags = "";
450
+ const cleanHtml = html.replace(/<forgewp-head\b[^>]*>(.*?)<\/forgewp-head>/gs, (match, childrenHtml) => {
451
+ extraHeadTags += "\n" + childrenHtml;
452
+ return "";
453
+ });
454
+
455
+ writeFileSync(path.join(outDir, `${name}.html`), cleanHtml, "utf8");
456
+ console.warn(`[ForgeWP Compiler] WROTE ${name}.html to ${outDir}`);
457
+
458
+ const seoProps = extractSeoPropsFromSource(filePath);
459
+ let customHeadHtml = buildHeadHtml(layoutSeo, seoProps);
460
+ if (extraHeadTags) {
461
+ customHeadHtml += "\n" + extraHeadTags;
462
+ }
463
+ writeFileSync(path.join(outDir, `${name}-head.html`), customHeadHtml, "utf8");
464
+ console.warn(`[ForgeWP Compiler] WROTE ${name}-head.html to ${outDir}`);
465
+ }
466
+ } catch (e: any) {
467
+ console.warn(`[ForgeWP Compiler Warning] Failed to render WP template ${file}:`, e.message);
468
+ }
469
+ }
470
+ }
471
+ }
472
+ }
473
+
474
+ // ── Write outputs ─────────────────────────────────────────────────────────────
475
+
476
+
477
+ writeFileSync(path.join(outDir, "header.html"), headerHtml, "utf8");
478
+ writeFileSync(path.join(outDir, "footer.html"), footerHtml, "utf8");
479
+ writeFileSync(path.join(outDir, "app.html"), cleanAppHtml, "utf8");
480
+ let finalHeadHtml = headHtml;
481
+ if (layoutExtraHeadTags) {
482
+ finalHeadHtml += "\n" + layoutExtraHeadTags;
483
+ }
484
+ writeFileSync(path.join(outDir, "head.html"), finalHeadHtml, "utf8");
485
+
486
+
487
+ // ── Compile Custom Page Templates ──────────────────────────────────────────────
488
+ const pagesDir = path.join(themeRoot, "src", "app", "pages");
489
+ console.warn("CHECKING PAGES DIR: " + pagesDir + " EXISTS: " + existsSync(pagesDir));
490
+ if (existsSync(pagesDir)) {
491
+ const { readdirSync } = require("node:fs");
492
+ const pages = readdirSync(pagesDir).filter(f => f.endsWith(".tsx"));
493
+
494
+ for (const pageFile of pages) {
495
+ const pagePath = path.join(pagesDir, pageFile);
496
+ console.warn(`Attempting to compile template: ${pageFile}`);
497
+ try {
498
+ const module = await import(pathToFileURL(pagePath).href);
499
+ const CustomPage = module.default || Object.values(module)[0];
500
+ if (CustomPage) {
501
+ const customHtml = renderPage(CustomPage);
502
+ let customExtraHeadTags = "";
503
+ const cleanCustomHtml = customHtml.replace(/<forgewp-head\b[^>]*>(.*?)<\/forgewp-head>/gs, (match, childrenHtml) => {
504
+ customExtraHeadTags += "\n" + childrenHtml;
505
+ return "";
506
+ });
507
+ const pageName = pageFile.replace(".tsx", "");
508
+ const slug = pageName.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
509
+ writeFileSync(path.join(outDir, `template-${slug}.html`), cleanCustomHtml, "utf8");
510
+ console.warn(`WROTE template-${slug}.html to ${outDir}`);
511
+
512
+ const customSeo = extractSeoPropsFromSource(pagePath);
513
+ let customHeadHtml = buildHeadHtml(layoutSeo, customSeo);
514
+ if (customExtraHeadTags) {
515
+ customHeadHtml += "\n" + customExtraHeadTags;
516
+ }
517
+ writeFileSync(path.join(outDir, `template-${slug}-head.html`), customHeadHtml, "utf8");
518
+ console.warn(`WROTE template-${slug}-head.html to ${outDir}`);
519
+ }
520
+ } catch (e) {
521
+ console.warn(`Failed to render custom page ${pageFile}:`, e.message);
522
+ }
523
+ }
524
+ }
525
+
526
+ process.stdout.write(outDir);