@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.
Files changed (52) hide show
  1. package/README.md +24 -5
  2. package/bin/analyze.js +158 -0
  3. package/bin/cli.js +33 -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-hooks.js +221 -0
  15. package/bin/sync-routes.js +28 -158
  16. package/define-config.d.ts +1 -0
  17. package/define-config.js +1 -0
  18. package/lib/adapters/html-adapter.js +65 -0
  19. package/lib/adapters/stub-adapter.js +49 -0
  20. package/lib/add-component.js +282 -183
  21. package/lib/asset-loader.js +27 -0
  22. package/lib/block-compiler.js +552 -0
  23. package/lib/blueprints.js +15 -501
  24. package/lib/define-config.d.ts +3 -0
  25. package/lib/define-config.js +8 -0
  26. package/lib/diagnostics.js +798 -0
  27. package/lib/export-theme.js +81 -18
  28. package/lib/framework-adapter.js +34 -0
  29. package/lib/functions-builder.js +2044 -0
  30. package/lib/generate-theme.js +1140 -1352
  31. package/lib/hydration-scanner.js +663 -21
  32. package/lib/i18n/extractor.js +60 -0
  33. package/lib/i18n/providers.js +165 -0
  34. package/lib/index.d.ts +115 -3
  35. package/lib/index.js +19 -5
  36. package/lib/load-config.js +122 -6
  37. package/lib/markup-processor.js +589 -0
  38. package/lib/php-builders.js +381 -0
  39. package/lib/react-adapter.js +1336 -0
  40. package/lib/render-static.js +9 -82
  41. package/lib/render-theme.mts +543 -232
  42. package/lib/screenshot-fallback.png +0 -0
  43. package/lib/types.js +1 -0
  44. package/lib/validate-export.js +183 -0
  45. package/package.json +15 -3
  46. package/templates/PresetsStyle.tsx +74 -0
  47. package/templates/SEO.tsx +109 -0
  48. package/templates/forgewp-config.ts +43 -0
  49. package/templates/menus.json +11 -0
  50. package/templates/mock-data.json +434 -0
  51. package/templates/wordpress.tsx +1297 -0
  52. package/bin/make-component.js +0 -200
@@ -1,1352 +1,1140 @@
1
- import { copyFileSync, cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
2
- import path from "node:path";
3
- import { scanForHydrationIslands } from "./hydration-scanner.js";
4
-
5
- /**
6
- * @param {Object} options
7
- * @param {string} options.themeRoot
8
- * @param {string} options.outDir
9
- * @param {import('./types.js').ForgeWPThemeConfig} options.config
10
- * @param {string} options.appHtml
11
- * @param {string} [options.headerHtml]
12
- * @param {string} [options.footerHtml]
13
- * @param {import('./types.js').ForgeWPBuildAssets} options.assets
14
- */
15
- export function generateTheme({
16
- themeRoot,
17
- outDir,
18
- config,
19
- appHtml,
20
- headerHtml = "",
21
- footerHtml = "",
22
- headHtml = "",
23
- singleHeadHtml = "",
24
- singleHtml = "",
25
- notFoundHtml = "",
26
- archiveHtml = "",
27
- assets,
28
- }) {
29
- if (existsSync(outDir)) {
30
- rmSync(outDir, { recursive: true, force: true });
31
- }
32
-
33
- mkdirSync(outDir, { recursive: true });
34
-
35
- // Load menus configuration for auto-registration and setup
36
- let menus = {};
37
- const menusJsonSrc = path.join(themeRoot, "wordpress", "menus.json");
38
- if (existsSync(menusJsonSrc)) {
39
- try {
40
- menus = JSON.parse(readFileSync(menusJsonSrc, "utf8"));
41
- } catch (e) {
42
- console.warn("Failed to parse menus.json:", e.message);
43
- }
44
- }
45
-
46
- // Gather compiled custom page templates for auto-creation with smart slug mapping
47
- const pagesToAutoCreate = [];
48
- const forgewpDir = path.join(themeRoot, ".forgewp");
49
- if (existsSync(forgewpDir)) {
50
- const templateFiles = readdirSync(forgewpDir);
51
- for (const file of templateFiles) {
52
- if (file.startsWith("template-") && file.endsWith(".html") && !file.includes("-head")) {
53
- const slug = file.replace(".html", "");
54
- const pageTemplateSlug = slug.replace("template-", "");
55
-
56
- let matchedSlug = null;
57
- let matchedTitle = null;
58
-
59
- const toKebabTemplateSlug = (str) => {
60
- const compName = str
61
- .replace(/[^a-zA-Z0-9]/g, " ")
62
- .trim()
63
- .split(/\s+/)
64
- .map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
65
- .join("") + "Page";
66
- return compName.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
67
- };
68
-
69
- const targetKebab = pageTemplateSlug;
70
-
71
- // Search in menus to find matching target URL slugs defined by the developer
72
- for (const [location, items] of Object.entries(menus)) {
73
- if (!Array.isArray(items)) continue;
74
- for (const item of items) {
75
- if (!item.url || !item.url.startsWith("/")) continue;
76
- const menuUrlSlug = item.url.replace(/^\//, "");
77
-
78
- if (
79
- toKebabTemplateSlug(item.title) === targetKebab ||
80
- toKebabTemplateSlug(menuUrlSlug) === targetKebab
81
- ) {
82
- matchedSlug = menuUrlSlug;
83
- matchedTitle = item.title;
84
- break;
85
- }
86
- }
87
- if (matchedSlug) break;
88
- }
89
-
90
- // Fallback 1: Strip trailing "-page" from template slug
91
- if (!matchedSlug) {
92
- matchedSlug = pageTemplateSlug.endsWith("-page")
93
- ? pageTemplateSlug.slice(0, -5)
94
- : pageTemplateSlug;
95
- }
96
-
97
- // Fallback 2: Generate clean human-readable title
98
- if (!matchedTitle) {
99
- const cleanName = pageTemplateSlug.endsWith("-page") ? pageTemplateSlug.slice(0, -5) : pageTemplateSlug;
100
- matchedTitle = cleanName.split("-").map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
101
- }
102
-
103
- pagesToAutoCreate.push({
104
- title: matchedTitle,
105
- slug: matchedSlug,
106
- template: `page-${pageTemplateSlug}.php`
107
- });
108
- }
109
- }
110
- }
111
-
112
- const hydrationIslands = scanForHydrationIslands(themeRoot);
113
- const hasHydration = hydrationIslands.length > 0;
114
-
115
- const assetsOut = path.join(outDir, "assets");
116
- const distAssets = path.join(themeRoot, "dist", "assets");
117
- mkdirSync(assetsOut, { recursive: true });
118
- cpSync(distAssets, assetsOut, { recursive: true });
119
-
120
- let hydrationManifestJson = "{}";
121
- if (hasHydration) {
122
- const manifestPath = path.join(themeRoot, "dist", ".vite", "manifest.json");
123
- let viteManifest = {};
124
- if (existsSync(manifestPath)) {
125
- try {
126
- viteManifest = JSON.parse(readFileSync(manifestPath, "utf8"));
127
- } catch (e) {
128
- console.warn("Failed to parse Vite manifest.json:", e.message);
129
- }
130
- }
131
-
132
- const mapping = {};
133
- let mainJsFile = "";
134
- const entryChunk = viteManifest["index.html"] || Object.values(viteManifest).find(c => c.isEntry);
135
- if (entryChunk) {
136
- mainJsFile = entryChunk.file;
137
- }
138
-
139
- for (const island of hydrationIslands) {
140
- const pascalName = island
141
- .split("-")
142
- .map(w => w.charAt(0).toUpperCase() + w.slice(1))
143
- .join("");
144
-
145
- let resolvedChunk = null;
146
- for (const [key, value] of Object.entries(viteManifest)) {
147
- if (
148
- key.endsWith(`${pascalName}.tsx`) ||
149
- key.endsWith(`${pascalName}.ts`) ||
150
- key.endsWith(`${island}.tsx`) ||
151
- key.endsWith(`${island}.ts`) ||
152
- (value.file && value.file.includes(island))
153
- ) {
154
- resolvedChunk = value.file;
155
- break;
156
- }
157
- }
158
-
159
- if (resolvedChunk) {
160
- mapping[island] = resolvedChunk;
161
- }
162
- }
163
-
164
- const hydratorScript = `(function () {
165
- const config = window.forgeWpHydration || { themeUri: "", manifest: {} };
166
- const islands = document.querySelectorAll("[data-forgewp-hydrate]");
167
-
168
- const observer = new IntersectionObserver((entries) => {
169
- entries.forEach((entry) => {
170
- if (entry.isIntersecting) {
171
- const hydrate = entry.target.__forgewpHydrate;
172
- if (typeof hydrate === "function") hydrate();
173
- observer.unobserve(entry.target);
174
- }
175
- });
176
- }, { rootMargin: "200px" });
177
-
178
- const StrategyRegistry = {
179
- load: (el, hydrate) => {
180
- if (document.readyState === "complete") {
181
- hydrate();
182
- } else {
183
- window.addEventListener("load", hydrate);
184
- }
185
- },
186
- visible: (el, hydrate) => {
187
- el.__forgewpHydrate = hydrate;
188
- observer.observe(el);
189
- },
190
- interaction: (el, hydrate) => {
191
- const run = () => {
192
- hydrate();
193
- el.removeEventListener("click", run);
194
- el.removeEventListener("mouseenter", run);
195
- el.removeEventListener("focusin", run);
196
- };
197
- el.addEventListener("click", run);
198
- el.addEventListener("mouseenter", run);
199
- el.addEventListener("focusin", run);
200
- },
201
- // Modern extensible triggers (e.g. idle trigger for low priority activation)
202
- idle: (el, hydrate) => {
203
- if ("requestIdleCallback" in window) {
204
- window.requestIdleCallback(hydrate);
205
- } else {
206
- setTimeout(hydrate, 200);
207
- }
208
- }
209
- };
210
-
211
- islands.forEach((el) => {
212
- const trigger = el.getAttribute("data-forgewp-trigger") || "visible";
213
- const runHydration = () => hydrateElement(el);
214
-
215
- const strategy = StrategyRegistry[trigger];
216
- if (strategy) {
217
- strategy(el, runHydration);
218
- } else {
219
- StrategyRegistry.visible(el, runHydration);
220
- }
221
- });
222
-
223
- function hydrateElement(el) {
224
- const islandName = el.getAttribute("data-forgewp-hydrate");
225
- const rawProps = el.getAttribute("data-forgewp-props") || "{}";
226
- const props = JSON.parse(rawProps);
227
-
228
- const chunkPath = config.manifest[islandName];
229
- if (!chunkPath) {
230
- console.error("[ForgeWP Hydrator] Could not find compiled chunk for island " + islandName);
231
- return;
232
- }
233
-
234
- const scriptUrl = config.themeUri + "/assets/" + chunkPath.replace(/^assets\\//, "").replace(/^assets\\/, "");
235
-
236
- import(scriptUrl)
237
- .then((module) => {
238
- const Component = module.default || Object.values(module)[0];
239
- if (typeof Component !== "function") {
240
- console.error("[ForgeWP Hydrator] Chunk for " + islandName + " does not export a valid React component");
241
- return;
242
- }
243
-
244
- if (window.ReactDOM && window.React) {
245
- const isClientOnly = el.hasAttribute("data-forgewp-client-only");
246
- if (isClientOnly) {
247
- // No SSR markup present: clean render
248
- const root = window.ReactDOM.createRoot(el);
249
- root.render(window.React.createElement(Component, props));
250
- } else {
251
- // Highly optimized hydration of server-side visual markup
252
- window.ReactDOM.hydrateRoot(el, window.React.createElement(Component, props));
253
- }
254
- } else {
255
- console.error("[ForgeWP Hydration Error] React or ReactDOM not found on window object.");
256
- }
257
- })
258
- .catch((err) => {
259
- console.error("[ForgeWP Hydrator] Failed to load chunk for " + islandName + ":", err);
260
- });
261
- }
262
- })();`;
263
-
264
- writeFileSync(path.join(assetsOut, "forgewp-hydrator.js"), hydratorScript, "utf8");
265
- hydrationManifestJson = JSON.stringify({
266
- mainJsFile,
267
- mapping
268
- });
269
- }
270
-
271
- // Drop unused JS from the theme ZIP
272
- const files = readdirSync(assetsOut);
273
- for (const file of files) {
274
- if ((file.endsWith(".js") || file.endsWith(".js.map")) && file !== "forgewp-editor.js" && file !== "forgewp-hydrator.js") {
275
- if (!hasHydration) {
276
- rmSync(path.join(assetsOut, file), { force: true });
277
- }
278
- }
279
- }
280
-
281
- // Fix nav links and split markup
282
- const processedApp = processMarkup(appHtml);
283
- const processedHeader = processMarkup(headerHtml);
284
- const processedFooter = processMarkup(footerHtml);
285
-
286
- // Extract content (App markup minus Header/Footer)
287
- let contentHtml = processedApp;
288
- if (processedHeader) {
289
- contentHtml = contentHtml.replace(processedHeader, "");
290
- }
291
- if (processedFooter) {
292
- contentHtml = contentHtml.replace(processedFooter, "");
293
- }
294
-
295
- // Process single post template if exists
296
- let processedSingle = "";
297
- if (singleHtml) {
298
- processedSingle = processMarkup(singleHtml);
299
- if (processedHeader) {
300
- processedSingle = processedSingle.replace(processedHeader, "");
301
- }
302
- if (processedFooter) {
303
- processedSingle = processedSingle.replace(processedFooter, "");
304
- }
305
- }
306
-
307
- // Process 404 template if exists
308
- let processedNotFound = "";
309
- if (notFoundHtml) {
310
- processedNotFound = processMarkup(notFoundHtml);
311
- if (processedHeader) {
312
- processedNotFound = processedNotFound.replace(processedHeader, "");
313
- }
314
- if (processedFooter) {
315
- processedNotFound = processedNotFound.replace(processedFooter, "");
316
- }
317
- }
318
-
319
- const staticDir = path.join(outDir, "forgewp-static");
320
- mkdirSync(staticDir, { recursive: true });
321
- writeFileSync(path.join(staticDir, "content.html"), contentHtml, "utf8");
322
- writeFileSync(path.join(staticDir, "header.html"), processedHeader, "utf8");
323
- writeFileSync(path.join(staticDir, "footer.html"), processedFooter, "utf8");
324
- if (headHtml) {
325
- writeFileSync(path.join(staticDir, "head.html"), headHtml, "utf8");
326
- }
327
- if (singleHeadHtml) {
328
- writeFileSync(path.join(staticDir, "single-head.html"), singleHeadHtml, "utf8");
329
- }
330
- if (processedSingle) {
331
- writeFileSync(path.join(staticDir, "single.html"), processedSingle, "utf8");
332
- }
333
- if (processedNotFound) {
334
- writeFileSync(path.join(staticDir, "404.html"), processedNotFound, "utf8");
335
- }
336
-
337
- // Archive page (category / tag / date archives)
338
- let processedArchive = "";
339
- if (archiveHtml) {
340
- processedArchive = processMarkup(archiveHtml);
341
- if (processedHeader) processedArchive = processedArchive.replace(processedHeader, "");
342
- if (processedFooter) processedArchive = processedArchive.replace(processedFooter, "");
343
- writeFileSync(path.join(staticDir, "archive.html"), processedArchive, "utf8");
344
- }
345
-
346
- // Dynamic Gutenberg blocks compilation (Phase 5)
347
- const compiledBlocks = compileBlocks(themeRoot, outDir);
348
-
349
- const editorScriptContent = `
350
- const { registerBlockType } = wp.blocks;
351
- const { createElement } = wp.element;
352
- const { InspectorControls, useBlockProps } = wp.blockEditor;
353
- const { PanelBody, TextControl } = wp.components;
354
- const ServerSideRender = wp.serverSideRender;
355
-
356
- if (window.forgeWpBlocks) {
357
- window.forgeWpBlocks.forEach(block => {
358
- registerBlockType(block.name, {
359
- title: block.title,
360
- icon: block.icon,
361
- category: block.category,
362
- attributes: block.attributes,
363
- edit: function(props) {
364
- const { attributes, setAttributes } = props;
365
- const blockProps = useBlockProps();
366
-
367
- // Build inspector controls dynamically from attributes
368
- const controls = Object.keys(block.attributes).map(key => {
369
- return createElement(TextControl, {
370
- label: key.charAt(0).toUpperCase() + key.slice(1),
371
- value: attributes[key],
372
- onChange: (val) => setAttributes({ [key]: val })
373
- });
374
- });
375
-
376
- return createElement('div', blockProps,
377
- createElement(InspectorControls, null,
378
- createElement(PanelBody, { title: 'Block Settings', initialOpen: true }, controls)
379
- ),
380
- createElement(ServerSideRender, {
381
- block: block.name,
382
- attributes: attributes
383
- })
384
- );
385
- },
386
- save: function() {
387
- return null; // Dynamic blocks return null in save
388
- }
389
- });
390
- });
391
- }
392
- `;
393
- writeFileSync(path.join(outDir, "assets", "forgewp-editor.js"), editorScriptContent, "utf8");
394
-
395
- writeFileSync(path.join(outDir, "style.css"), buildStyleCss(config), "utf8");
396
-
397
- let hydrationData = null;
398
- if (hasHydration) {
399
- try {
400
- hydrationData = JSON.parse(hydrationManifestJson);
401
- } catch {}
402
- }
403
-
404
- writeFileSync(
405
- path.join(outDir, "functions.php"),
406
- buildFunctionsPhp(config, assets, compiledBlocks, themeRoot, pagesToAutoCreate, menus, hydrationData),
407
- "utf8",
408
- );
409
- writeFileSync(path.join(outDir, "header.php"), buildHeaderPhp(config), "utf8");
410
- writeFileSync(path.join(outDir, "footer.php"), buildFooterPhp(config), "utf8");
411
- writeFileSync(path.join(outDir, "index.php"), buildIndexPhp(), "utf8");
412
- writeFileSync(path.join(outDir, "single.php"), buildSinglePhp(), "utf8");
413
- writeFileSync(path.join(outDir, "404.php"), build404Php(), "utf8");
414
- writeFileSync(path.join(outDir, "front-page.php"), buildIndexPhp(), "utf8");
415
- writeFileSync(path.join(outDir, "archive.php"), buildArchivePhp(), "utf8");
416
- writeFileSync(path.join(outDir, "page.php"), buildPagePhp(), "utf8");
417
-
418
- // Dynamic Custom Page Templates Compiler
419
- if (existsSync(forgewpDir)) {
420
- const templateFiles = readdirSync(forgewpDir);
421
- for (const file of templateFiles) {
422
- if (file.startsWith("template-") && file.endsWith(".html") && !file.includes("-head")) {
423
- const slug = file.replace(".html", "");
424
- const rawHtml = readFileSync(path.join(forgewpDir, file), "utf8");
425
-
426
- let processedHtml = processMarkup(rawHtml);
427
- if (processedHeader) processedHtml = processedHtml.replace(processedHeader, "");
428
- if (processedFooter) processedHtml = processedHtml.replace(processedFooter, "");
429
-
430
- writeFileSync(path.join(staticDir, file), processedHtml, "utf8");
431
-
432
- const headFile = file.replace(".html", "-head.html");
433
- if (existsSync(path.join(forgewpDir, headFile))) {
434
- writeFileSync(path.join(staticDir, headFile), readFileSync(path.join(forgewpDir, headFile), "utf8"), "utf8");
435
- }
436
-
437
- // Generate the native WordPress PHP Custom Page Template
438
- const templateName = slug.replace("template-", "").split("-").map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
439
- const phpContent = `<?php
440
- /**
441
- * Template Name: ${templateName}
442
- *
443
- * @package ${config.textDomain}
444
- */
445
-
446
- get_header();
447
-
448
- $markup_file = get_template_directory() . '/forgewp-static/${file}';
449
- if (file_exists($markup_file)) {
450
- include $markup_file;
451
- }
452
-
453
- get_footer();
454
- `;
455
- writeFileSync(path.join(outDir, `page-${slug.replace("template-", "")}.php`), phpContent, "utf8");
456
- }
457
- }
458
- }
459
-
460
- // Dynamic theme.json compiler (Phase 5)
461
- const themeJsonSrc = path.join(themeRoot, "wordpress", "theme.json");
462
- let themeJson = {
463
- "$schema": "https://schemas.wp.org/trunk/theme.json",
464
- "version": 3,
465
- "settings": {
466
- "appearanceTools": true,
467
- },
468
- };
469
-
470
- if (existsSync(themeJsonSrc)) {
471
- try {
472
- themeJson = JSON.parse(readFileSync(themeJsonSrc, "utf8"));
473
- } catch (e) {
474
- console.warn("Failed to parse theme.json template:", e.message);
475
- }
476
- }
477
-
478
- // Merge tokens from wp.config.ts
479
- if (config.settings) {
480
- if (!themeJson.settings) themeJson.settings = {};
481
-
482
- // Layout (contentSize, wideSize)
483
- if (config.settings.layout) {
484
- themeJson.settings.layout = {
485
- ...themeJson.settings.layout,
486
- ...config.settings.layout,
487
- };
488
- }
489
-
490
- // Colors (custom, palette)
491
- if (config.settings.color) {
492
- themeJson.settings.color = {
493
- ...themeJson.settings.color,
494
- ...config.settings.color,
495
- };
496
- }
497
-
498
- // Typography (fontSizes, fontFamilies)
499
- if (config.settings.typography) {
500
- themeJson.settings.typography = {
501
- ...themeJson.settings.typography,
502
- ...config.settings.typography,
503
- };
504
- }
505
- }
506
-
507
- writeFileSync(
508
- path.join(outDir, "theme.json"),
509
- JSON.stringify(themeJson, null, 2),
510
- "utf8"
511
- );
512
-
513
- const screenshot = path.join(themeRoot, "wordpress", "screenshot.png");
514
- if (existsSync(screenshot)) {
515
- copyFileSync(screenshot, path.join(outDir, "screenshot.png"));
516
- }
517
- }
518
-
519
- /**
520
- * Process markup: fix nav links etc.
521
- */
522
- function processMarkup(html) {
523
- if (!html) return "";
524
- // Fix nav links — # → <?php echo esc_url( home_url( '/' ) ); ?>
525
- // We use a placeholder and replace it in the PHP file generation if needed,
526
- // but for now we'll do it via string replacement in the template files.
527
- let processed = html.replace(
528
- /href="#"/g,
529
- 'href="<?php echo esc_url( home_url( \'/\' ) ); ?>"',
530
- );
531
-
532
- processed = processed.replace(
533
- /__FORGEWP_THE_TITLE__/g,
534
- '<?php the_title(); ?>'
535
- );
536
-
537
- processed = processed.replace(
538
- /__FORGEWP_THE_CONTENT__/g,
539
- '<?php the_content(); ?>'
540
- );
541
-
542
- processed = processed.replace(
543
- /__FORGEWP_THE_PERMALINK__/g,
544
- '<?php the_permalink(); ?>'
545
- );
546
-
547
- processed = processed.replace(
548
- /__FORGEWP_THE_EXCERPT__/g,
549
- '<?php the_excerpt(); ?>'
550
- );
551
-
552
- processed = processed.replace(
553
- /__FORGEWP_THE_DATE__/g,
554
- "<?php echo esc_html( get_the_date() ); ?>"
555
- );
556
-
557
- processed = processed.replace(
558
- /__FORGEWP_THE_AUTHOR__/g,
559
- "<?php echo esc_html( get_the_author() ); ?>"
560
- );
561
-
562
- processed = processed.replace(
563
- /__FORGEWP_THE_POST_THUMBNAIL_URL__/g,
564
- "<?php echo esc_url( get_the_post_thumbnail_url( null, 'large' ) ); ?>"
565
- );
566
-
567
- processed = processed.replace(
568
- /__FORGEWP_THE_CATEGORY_LIST__/g,
569
- "<?php the_category( ', ' ); ?>"
570
- );
571
-
572
- processed = processed.replace(
573
- /__FORGEWP_THE_ARCHIVE_TITLE__/g,
574
- "<?php the_archive_title(); ?>"
575
- );
576
-
577
- processed = processed.replace(
578
- /<forgewp-loop-start\s*\/?>/g,
579
- '<?php if (have_posts()) : while (have_posts()) : the_post(); ?>'
580
- );
581
-
582
- processed = processed.replace(
583
- /<\/forgewp-loop-start>/g,
584
- ''
585
- );
586
-
587
- processed = processed.replace(
588
- /<forgewp-loop-end\s*\/?>/g,
589
- '<?php endwhile; else : echo "<p>No posts found.</p>"; endif; ?>'
590
- );
591
-
592
- processed = processed.replace(
593
- /<\/forgewp-loop-end>/g,
594
- ''
595
- );
596
-
597
- // ── Custom Meta Fields (ACF / metadata support) ──
598
- processed = processed.replace(
599
- /__FORGEWP_CUSTOM_FIELD__([a-zA-Z0-9_-]+)__/g,
600
- "<?php echo esc_html( get_post_meta( get_the_ID(), '$1', true ) ); ?>"
601
- );
602
-
603
- // ── Dynamic Custom Menus ──
604
- processed = processed.replace(
605
- /<forgewp-menu\s+[^>]*location="([^"]+)"\s+[^>]*className="([^"]*)"\s+[^>]*linkClassName="([^"]*)"\s*\/?>/g,
606
- '<?php\n $locations = get_nav_menu_locations();\n $menu_id = isset($locations[\'$1\']) ? $locations[\'$1\'] : null;\n $menu_items = $menu_id ? wp_get_nav_menu_items($menu_id) : array();\n if (!empty($menu_items)) {\n echo \'<nav class="$2">\';\n foreach ($menu_items as $item) {\n echo \'<a href="\' . esc_url($item->url) . \'" class="$3">\' . esc_html($item->title) . \'</a>\';\n }\n echo \'</nav>\';\n } else {\n echo \'<nav class="$2"><a href="\' . esc_url(home_url(\'/\')) . \'" class="$3">Home</a></nav>\';\n }\n ?>'
607
- );
608
- processed = processed.replace(/<\/forgewp-menu>/g, '');
609
-
610
- // ── WordPress Shortcodes Support ──
611
- processed = processed.replace(
612
- /<forgewp-shortcode\s+[^>]*code="([^"]+)"\s*\/?>/g,
613
- (match, code) => {
614
- const decodedCode = code.replace(/&quot;/g, '"').replace(/&#39;/g, "'");
615
- return `<?php echo do_shortcode('${decodedCode}'); ?>`;
616
- }
617
- );
618
- processed = processed.replace(/<\/forgewp-shortcode>/g, '');
619
-
620
- // ── Custom WP_Query Loop Blocks ──
621
- processed = processed.replace(
622
- /<forgewp-query-loop-start\s+[^>]*post[Tt]ype="([^"]+)"\s+[^>]*posts[Pp]er[Pp]age="([^"]+)"\s*(?:[^>]*category[Nn]ame="([^"]*)")?\s*\/?>/g,
623
- '<?php\n $query_args = array(\n \'post_type\' => \'$1\',\n \'posts_per_page\' => $2,\n );\n if (\'$3\' !== \'\') {\n $query_args[\'category_name\'] = \'$3\';\n }\n $custom_query = new WP_Query($query_args);\n if ($custom_query->have_posts()) : while ($custom_query->have_posts()) : $custom_query->the_post();\n ?>'
624
- );
625
- processed = processed.replace(/<\/forgewp-query-loop-start>/g, '');
626
- processed = processed.replace(
627
- /<forgewp-query-loop-end\s*\/?>/g,
628
- '<?php\n endwhile;\n wp_reset_postdata();\n endif;\n ?>'
629
- );
630
- processed = processed.replace(/<\/forgewp-query-loop-end>/g, '');
631
-
632
- return processed;
633
- }
634
-
635
-
636
- /**
637
- * @param {import('./types.js').ForgeWPThemeConfig} config
638
- */
639
- function buildStyleCss(config) {
640
- return `/*
641
- Theme Name: ${config.name}
642
- Theme URI: https://forgewp.dev
643
- Author: ForgeWP
644
- Description: ${config.description}
645
- Version: ${config.version}
646
- Requires at least: 6.0
647
- Tested up to: 6.7
648
- Requires PHP: 7.4
649
- License: GNU General Public License v2 or later
650
- License URI: https://www.gnu.org/licenses/gpl-2.0.html
651
- Text Domain: ${config.textDomain}
652
- */
653
-
654
- /* Compiled styles are enqueued from assets/ via functions.php */
655
- `;
656
- }
657
-
658
- /**
659
- * @param {import('./types.js').ForgeWPThemeConfig} config
660
- * @param {import('./types.js').ForgeWPBuildAssets} assets
661
- */
662
- function buildFunctionsPhp(config, assets, blockSlugs = [], themeRoot = "", pagesToAutoCreate = [], menus = {}, hydrationData = null) {
663
- const css = assets.cssFile.replace(/^assets\//, "");
664
- const version = config.version.replace(/'/g, "\\'");
665
- const googleFonts = config.settings?.typography?.googleFonts || [];
666
-
667
- let cptRegistration = "";
668
- try {
669
- const mockDataPath = path.join(themeRoot, "wordpress", "mock-data.json");
670
- if (existsSync(mockDataPath)) {
671
- const mockData = JSON.parse(readFileSync(mockDataPath, "utf8"));
672
- const postTypes = Object.keys(mockData).filter(k => k !== "posts" && k !== "pages" && k !== "post" && k !== "page" && k !== "menus");
673
- if (postTypes.length > 0) {
674
- cptRegistration = `
675
- /**
676
- * Register dynamic Custom Post Types inferred from local mock data.
677
- */
678
- function forgewp_register_custom_post_types() {
679
- ${postTypes.map(pt => ` register_post_type('${pt}', array(
680
- 'labels' => array(
681
- 'name' => '${pt.charAt(0).toUpperCase() + pt.slice(1)}s',
682
- 'singular_name' => '${pt.charAt(0).toUpperCase() + pt.slice(1)}',
683
- 'menu_name' => '${pt.charAt(0).toUpperCase() + pt.slice(1)}s',
684
- 'name_admin_bar' => '${pt.charAt(0).toUpperCase() + pt.slice(1)}',
685
- 'add_new' => 'Add New',
686
- 'add_new_item' => 'Add New ${pt.charAt(0).toUpperCase() + pt.slice(1)}',
687
- 'new_item' => 'New ${pt.charAt(0).toUpperCase() + pt.slice(1)}',
688
- 'edit_item' => 'Edit ${pt.charAt(0).toUpperCase() + pt.slice(1)}',
689
- 'view_item' => 'View ${pt.charAt(0).toUpperCase() + pt.slice(1)}',
690
- 'all_items' => 'All ${pt.charAt(0).toUpperCase() + pt.slice(1)}s',
691
- 'search_items' => 'Search ${pt.charAt(0).toUpperCase() + pt.slice(1)}s',
692
- 'not_found' => 'No ${pt.charAt(0).toUpperCase() + pt.slice(1)}s found.',
693
- ),
694
- 'public' => true,
695
- 'has_archive' => true,
696
- 'show_in_rest'=> true,
697
- 'supports' => array('title', 'editor', 'thumbnail', 'custom-fields', 'excerpt'),
698
- 'menu_icon' => 'dashicons-admin-post',
699
- ));`).join("\n")}
700
- }
701
- add_action('init', 'forgewp_register_custom_post_types');
702
- `;
703
- }
704
- }
705
- } catch (e) {}
706
-
707
- let fontsEnqueue = "";
708
- let preconnectFilter = "";
709
-
710
- if (googleFonts.length > 0) {
711
- const fontsParam = googleFonts.map(f => encodeURIComponent(f)).join("&family=");
712
- fontsEnqueue = `
713
- // Enqueue Google Fonts (dynamic preset via wp.config.ts)
714
- wp_enqueue_style(
715
- '${config.textDomain}-google-fonts',
716
- 'https://fonts.googleapis.com/css2?family=${fontsParam}&display=swap',
717
- array(),
718
- null
719
- );`;
720
-
721
- preconnectFilter = `
722
- /**
723
- * Add preconnect resource hints for Google Fonts performance.
724
- */
725
- function forgewp_google_fonts_resource_hints(array $urls, string $relation_type): array {
726
- if (wp_style_is('${config.textDomain}-google-fonts', 'queue') && 'preconnect' === $relation_type) {
727
- $urls[] = array(
728
- 'href' => 'https://fonts.googleapis.com',
729
- 'crossorigin' => 'anonymous',
730
- );
731
- $urls[] = array(
732
- 'href' => 'https://fonts.gstatic.com',
733
- 'crossorigin' => 'anonymous',
734
- );
735
- }
736
- return $urls;
737
- }
738
- add_filter('wp_resource_hints', 'forgewp_google_fonts_resource_hints', 10, 2);
739
- `;
740
- }
741
-
742
- let blocksRegistration = "";
743
- if (blockSlugs.length > 0) {
744
- const blocksArray = blockSlugs.map(s => `'${s}'`).join(", ");
745
- blocksRegistration = `
746
- /**
747
- * Register dynamic Gutenberg blocks compiled by ForgeWP.
748
- */
749
- function forgewp_register_dynamic_blocks(): void {
750
- $blocks = array(${blockSlugs.map(s => `'${s.name.replace("forgewp/", "")}'`).join(", ")});
751
- foreach ($blocks as $block) {
752
- register_block_type(__DIR__ . '/blocks/' . $block);
753
- }
754
- }
755
- add_action('init', 'forgewp_register_dynamic_blocks');
756
-
757
- /**
758
- * Enqueue Block Editor JavaScript to dynamically render block interfaces.
759
- */
760
- function forgewp_enqueue_block_editor_assets(): void {
761
- wp_enqueue_script(
762
- 'forgewp-editor-script',
763
- get_template_directory_uri() . '/assets/forgewp-editor.js',
764
- array('wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-server-side-render'),
765
- FORGEWP_THEME_VERSION,
766
- true
767
- );
768
-
769
- wp_localize_script(
770
- 'forgewp-editor-script',
771
- 'forgeWpBlocks',
772
- json_decode('${JSON.stringify(blockSlugs)}')
773
- );
774
- }
775
- add_action('enqueue_block_editor_assets', 'forgewp_enqueue_block_editor_assets');
776
- `;
777
- }
778
-
779
- let registerMenusPhp = "";
780
- const menuLocations = Object.keys(menus).filter(k => !k.startsWith("_"));
781
- if (menuLocations.length > 0) {
782
- registerMenusPhp = `
783
- // Register custom navigation menus from sitemap config
784
- register_nav_menus(array(
785
- ${menuLocations.map(loc => ` '${loc}' => __('${loc.charAt(0).toUpperCase() + loc.slice(1)} Navigation', '${config.textDomain}'),`).join("\n")}
786
- ));`;
787
- }
788
-
789
- const pagesPhpArray = pagesToAutoCreate.map(p => {
790
- return ` array(
791
- 'title' => '${p.title.replace(/'/g, "\\'")}',
792
- 'slug' => '${p.slug.replace(/'/g, "\\'")}',
793
- 'template' => '${p.template.replace(/'/g, "\\'")}',
794
- )`;
795
- }).join(",\n");
796
-
797
- const menuItemsPhpArray = Object.entries(menus)
798
- .filter(([loc]) => !loc.startsWith("_"))
799
- .map(([loc, items]) => {
800
- const itemsPhp = items.map(item => {
801
- return ` array(
802
- 'title' => '${item.title.replace(/'/g, "\\'")}',
803
- 'url' => '${item.url.replace(/'/g, "\\'")}',
804
- )`;
805
- }).join(",\n");
806
- return ` '${loc}' => array(
807
- ${itemsPhp}
808
- )`;
809
- }).join(",\n");
810
-
811
- const autoCreationPhp = `
812
- /**
813
- * Automatically create routes defined in menus.json and assign custom page templates upon theme activation.
814
- */
815
- function forgewp_auto_create_pages_and_menus(): void {
816
- $activated_option = '${config.textDomain}_activated_' . str_replace('.', '_', FORGEWP_THEME_VERSION);
817
- if (get_option($activated_option) === 'yes') {
818
- return;
819
- }
820
-
821
- $pages = array(
822
- ${pagesPhpArray}
823
- );
824
-
825
- foreach ($pages as $p) {
826
- $existing_page = get_page_by_path($p['slug']);
827
- if (!$existing_page) {
828
- $page_id = wp_insert_post(array(
829
- 'post_title' => $p['title'],
830
- 'post_name' => $p['slug'],
831
- 'post_status' => 'publish',
832
- 'post_type' => 'page',
833
- ));
834
- if (!is_wp_error($page_id) && $page_id > 0) {
835
- update_post_meta($page_id, '_wp_page_template', $p['template']);
836
- }
837
- } else {
838
- update_post_meta($existing_page->ID, '_wp_page_template', $p['template']);
839
- }
840
- }
841
-
842
- $menu_structure = array(
843
- ${menuItemsPhpArray}
844
- );
845
-
846
- foreach ($menu_structure as $location => $items) {
847
- $menu_name = ucfirst($location) . ' Navigation';
848
- $menu_exists = wp_get_nav_menu_object($menu_name);
849
-
850
- if (!$menu_exists) {
851
- $menu_id = wp_create_nav_menu($menu_name);
852
- if (!is_wp_error($menu_id)) {
853
- $locations = get_theme_mod('nav_menu_locations');
854
- if (!is_array($locations)) {
855
- $locations = array();
856
- }
857
- $locations[$location] = $menu_id;
858
- set_theme_mod('nav_menu_locations', $locations);
859
-
860
- foreach ($items as $item) {
861
- $item_title = $item['title'];
862
- $item_url = $item['url'];
863
-
864
- $object_id = 0;
865
- $object_type = 'custom';
866
- $target_url = $item_url;
867
-
868
- if (strpos($item_url, '/') === 0) {
869
- $slug = trim($item_url, '/');
870
- if ($slug === '') {
871
- $target_url = home_url('/');
872
- } else {
873
- $page = get_page_by_path($slug);
874
- if ($page) {
875
- $object_id = $page->ID;
876
- $object_type = 'page';
877
- $target_url = get_permalink($page->ID);
878
- } else {
879
- $target_url = home_url($item_url);
880
- }
881
- }
882
- }
883
-
884
- wp_update_nav_menu_item($menu_id, 0, array(
885
- 'menu-item-title' => $item_title,
886
- 'menu-item-url' => $target_url,
887
- 'menu-item-object-id' => $object_id,
888
- 'menu-item-object' => $object_type === 'page' ? 'page' : '',
889
- 'menu-item-type' => $object_type === 'page' ? 'post_type' : 'custom',
890
- 'menu-item-status' => 'publish',
891
- ));
892
- }
893
- }
894
- }
895
- }
896
-
897
- update_option($activated_option, 'yes');
898
- }
899
- add_action('after_switch_theme', 'forgewp_auto_create_pages_and_menus');
900
- `;
901
-
902
- let hydrationEnqueue = "";
903
- if (hydrationData && hydrationData.mapping) {
904
- const mainJs = hydrationData.mainJsFile.replace(/^assets\//, "").replace(/^assets\\/, "");
905
- const manifestPairs = Object.entries(hydrationData.mapping).map(([key, val]) => {
906
- const cleanVal = val.replace(/^assets\//, "").replace(/^assets\\/, "");
907
- return ` '${key}' => 'assets/${cleanVal}'`;
908
- }).join(",\n");
909
-
910
- hydrationEnqueue = `
911
- // Enqueue React runtime entrypoint and dynamic Selective Hydration assets
912
- $js_path = get_template_directory() . '/assets/${mainJs}';
913
- if (file_exists($js_path)) {
914
- wp_enqueue_script(
915
- '${config.textDomain}-react-runtime',
916
- $theme_uri . '/assets/${mainJs}',
917
- array(),
918
- FORGEWP_THEME_VERSION,
919
- true
920
- );
921
-
922
- // Inject hydration manifest mappings dynamically
923
- wp_localize_script(
924
- '${config.textDomain}-react-runtime',
925
- 'forgeWpHydration',
926
- array(
927
- 'themeUri' => $theme_uri,
928
- 'manifest' => array(
929
- ${manifestPairs}
930
- )
931
- )
932
- );
933
-
934
- // Enqueue Micro-Hydrator orchestrator script
935
- wp_enqueue_script(
936
- '${config.textDomain}-hydrator',
937
- $theme_uri . '/assets/forgewp-hydrator.js',
938
- array('${config.textDomain}-react-runtime'),
939
- FORGEWP_THEME_VERSION,
940
- true
941
- );
942
- }`;
943
- }
944
-
945
- return `<?php
946
- /**
947
- * ${config.name} — generated by ForgeWP
948
- *
949
- * @package ${config.textDomain}
950
- */
951
-
952
- if (! defined('ABSPATH')) {
953
- exit;
954
- }
955
-
956
- define('FORGEWP_THEME_VERSION', '${version}');
957
-
958
- /**
959
- * Enqueue compiled theme assets.
960
- */
961
- function forgewp_enqueue_assets(): void {
962
- $theme_uri = get_template_directory_uri();
963
- $css_path = get_template_directory() . '/assets/${css}';
964
- ${fontsEnqueue}
965
-
966
- if (file_exists($css_path)) {
967
- wp_enqueue_style(
968
- '${config.textDomain}-app',
969
- $theme_uri . '/assets/${css}',
970
- array(),
971
- FORGEWP_THEME_VERSION
972
- );
973
- }
974
- ${hydrationEnqueue}
975
- }
976
- add_action('wp_enqueue_scripts', 'forgewp_enqueue_assets');
977
-
978
- /**
979
- * Theme supports.
980
- */
981
- function forgewp_theme_setup(): void {
982
- add_theme_support('title-tag');
983
- add_theme_support('post-thumbnails');
984
- add_theme_support('html5', array('search-form', 'comment-form', 'comment-list', 'gallery', 'caption', 'style', 'script'));
985
- add_theme_support('wp-block-styles');
986
- add_theme_support('editor-styles');
987
-
988
- // Load compiled theme stylesheet inside Gutenberg Block Editor
989
- add_editor_style('assets/${css}');
990
- ${registerMenusPhp}
991
- }
992
- add_action('after_setup_theme', 'forgewp_theme_setup');
993
- ${preconnectFilter}${blocksRegistration}${cptRegistration}${autoCreationPhp}`;
994
- }
995
-
996
- function buildHeaderPhp(config) {
997
- return `<?php
998
- /**
999
- * Theme header
1000
- *
1001
- * @package ${config.textDomain}
1002
- */
1003
- ?><!DOCTYPE html>
1004
- <html <?php language_attributes(); ?>>
1005
- <head>
1006
- <meta charset="<?php bloginfo('charset'); ?>">
1007
- <meta name="viewport" content="width=device-width, initial-scale=1">
1008
- <?php
1009
- $single_head = get_template_directory() . '/forgewp-static/single-head.html';
1010
- $head_file = get_template_directory() . '/forgewp-static/head.html';
1011
- if (is_single() && file_exists($single_head)) {
1012
- include $single_head;
1013
- } elseif (file_exists($head_file)) {
1014
- include $head_file;
1015
- }
1016
- ?>
1017
- <?php wp_head(); ?>
1018
- <style>
1019
- /* Reset WP link underlines to match React/Tailwind expected styling */
1020
- a { text-decoration: none !important; }
1021
- a:hover { text-decoration: none !important; }
1022
- </style>
1023
- </head>
1024
- <body <?php body_class(); ?>>
1025
- <?php wp_body_open(); ?>
1026
- <?php
1027
- $header_file = get_template_directory() . '/forgewp-static/header.html';
1028
- if (file_exists($header_file)) {
1029
- include $header_file;
1030
- }
1031
- ?>
1032
- `;
1033
- }
1034
-
1035
- function buildFooterPhp(config) {
1036
- return `<?php
1037
- /**
1038
- * Theme footer
1039
- *
1040
- * @package ${config.textDomain}
1041
- */
1042
- $footer_file = get_template_directory() . '/forgewp-static/footer.html';
1043
- if (file_exists($footer_file)) {
1044
- include $footer_file;
1045
- }
1046
- wp_footer();
1047
- ?>
1048
- </body>
1049
- </html>
1050
- `;
1051
- }
1052
-
1053
- function buildIndexPhp() {
1054
- return `<?php
1055
- /**
1056
- * Main template — displays ForgeWP compiled static markup
1057
- *
1058
- * @package forgewp
1059
- */
1060
-
1061
- get_header();
1062
-
1063
- $markup_file = get_template_directory() . '/forgewp-static/content.html';
1064
-
1065
- if (is_front_page() && file_exists($markup_file)) {
1066
- include $markup_file;
1067
- } elseif (have_posts()) {
1068
- echo '<main class="mx-auto max-w-3xl px-6 py-12">';
1069
- while (have_posts()) {
1070
- the_post();
1071
- echo '<article class="mb-12">';
1072
- echo '<h1 class="text-3xl font-bold mb-4">' . get_the_title() . '</h1>';
1073
- echo '<div class="prose prose-zinc max-w-none">';
1074
- the_content();
1075
- echo '</div>';
1076
- echo '</article>';
1077
- }
1078
- echo '</main>';
1079
- }
1080
-
1081
- get_footer();
1082
- `;
1083
- }
1084
-
1085
- function buildSinglePhp() {
1086
- return `<?php
1087
- /**
1088
- * Single post template
1089
- *
1090
- * @package forgewp
1091
- */
1092
-
1093
- get_header();
1094
-
1095
- $single_file = get_template_directory() . '/forgewp-static/single.html';
1096
- if (file_exists($single_file)) {
1097
- if (have_posts()) {
1098
- while (have_posts()) {
1099
- the_post();
1100
- include $single_file;
1101
- }
1102
- }
1103
- } else {
1104
- if (have_posts()) {
1105
- while (have_posts()) {
1106
- the_post();
1107
- echo '<main class="mx-auto max-w-3xl px-6 py-12">';
1108
- echo '<article>';
1109
- echo '<h1 class="text-4xl font-bold mb-6">' . get_the_title() . '</h1>';
1110
- echo '<div class="prose prose-zinc max-w-none">';
1111
- the_content();
1112
- echo '</div>';
1113
- echo '</article>';
1114
- echo '</main>';
1115
- }
1116
- }
1117
- }
1118
-
1119
- get_footer();
1120
- `;
1121
- }
1122
-
1123
- function build404Php() {
1124
- return `<?php
1125
- /**
1126
- * 404 template
1127
- *
1128
- * @package forgewp
1129
- */
1130
-
1131
- get_header();
1132
-
1133
- $notFound_file = get_template_directory() . '/forgewp-static/404.html';
1134
- if (file_exists($notFound_file)) {
1135
- include $notFound_file;
1136
- } else {
1137
- echo '<main class="flex min-h-[60vh] flex-col items-center justify-center text-center px-6 py-24">';
1138
- echo '<p class="text-base font-semibold text-zinc-900">404</p>';
1139
- echo '<h1 class="mt-4 text-3xl font-bold tracking-tight text-zinc-900 sm:text-5xl">Page not found</h1>';
1140
- echo '<p class="mt-6 text-base leading-7 text-zinc-600">Sorry, we couldn’t find the page you’re looking for.</p>';
1141
- echo '</main>';
1142
- }
1143
-
1144
- get_footer();
1145
- `;
1146
- }
1147
-
1148
- function buildArchivePhp() {
1149
- return `<?php
1150
- /**
1151
- * Archive template — category, tag, date, and author archives.
1152
- * Loads the ForgeWP compiled archive.html which contains the WpLoop.
1153
- *
1154
- * @package forgewp
1155
- */
1156
-
1157
- get_header();
1158
-
1159
- $archive_file = get_template_directory() . '/forgewp-static/archive.html';
1160
-
1161
- if (file_exists($archive_file)) {
1162
- include $archive_file;
1163
- } else {
1164
- echo '<main class="mx-auto max-w-3xl px-6 py-12">';
1165
- the_archive_title('<h1 class="text-3xl font-bold mb-8">', '</h1>');
1166
- if (have_posts()) {
1167
- echo '<div class="space-y-8">';
1168
- while (have_posts()) {
1169
- the_post();
1170
- echo '<article>';
1171
- echo '<h2 class="text-xl font-bold"><a href="' . get_permalink() . '">' . get_the_title() . '</a></h2>';
1172
- echo '<div class="text-sm text-zinc-500 mt-1">' . get_the_date() . ' by ' . get_the_author() . '</div>';
1173
- echo '<div class="mt-3 text-zinc-600">';
1174
- the_excerpt();
1175
- echo '</div>';
1176
- echo '</article>';
1177
- }
1178
- echo '</div>';
1179
- } else {
1180
- echo '<p>No posts found.</p>';
1181
- }
1182
- echo '</main>';
1183
- }
1184
-
1185
- get_footer();
1186
- `;
1187
- }
1188
-
1189
- function buildPagePhp() {
1190
- return `<?php
1191
- /**
1192
- * Static page template — WordPress pages (e.g. About, Contact).
1193
- * Reuses single.html since static pages share the same title+content structure.
1194
- *
1195
- * @package forgewp
1196
- */
1197
-
1198
- get_header();
1199
-
1200
- $page_file = get_template_directory() . '/forgewp-static/single.html';
1201
-
1202
- if (file_exists($page_file)) {
1203
- if (have_posts()) {
1204
- while (have_posts()) {
1205
- the_post();
1206
- include $page_file;
1207
- }
1208
- }
1209
- } else {
1210
- if (have_posts()) {
1211
- while (have_posts()) {
1212
- the_post();
1213
- echo '<main class="mx-auto max-w-3xl px-6 py-12">';
1214
- echo '<article>';
1215
- echo '<h1 class="text-4xl font-bold mb-6">' . get_the_title() . '</h1>';
1216
- echo '<div class="prose prose-zinc max-w-none">';
1217
- the_content();
1218
- echo '</div>';
1219
- echo '</article>';
1220
- echo '</main>';
1221
- }
1222
- }
1223
- }
1224
-
1225
- get_footer();
1226
- `;
1227
- }
1228
-
1229
- /**
1230
- * Scans the \`src/blocks/\` folder, parses block settings and JSX content,
1231
- * and compiles them into official, dynamic WordPress blocks.
1232
- *
1233
- * @param {string} themeRoot
1234
- * @param {string} outDir
1235
- * @returns {string[]} Compiled block slugs
1236
- */
1237
- function compileBlocks(themeRoot, outDir) {
1238
- const blocksDir = path.join(themeRoot, "src", "blocks");
1239
- const blockSlugs = [];
1240
-
1241
- if (!existsSync(blocksDir)) {
1242
- return blockSlugs;
1243
- }
1244
-
1245
- const entries = readdirSync(blocksDir);
1246
- for (const entry of entries) {
1247
- const entryPath = path.join(blocksDir, entry);
1248
- let blockFile = "";
1249
- let blockSlug = "";
1250
-
1251
- if (statSync(entryPath).isDirectory()) {
1252
- const indexPath = path.join(entryPath, "index.tsx");
1253
- if (existsSync(indexPath)) {
1254
- blockFile = indexPath;
1255
- blockSlug = entry.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase().replace(/[^a-z0-9]+/g, "-");
1256
- }
1257
- } else if (entry.endsWith(".tsx") || entry.endsWith(".jsx")) {
1258
- blockFile = entryPath;
1259
- blockSlug = entry.replace(/\.(tsx|jsx)$/, "").replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase().replace(/[^a-z0-9]+/g, "-");
1260
- }
1261
-
1262
- if (blockFile) {
1263
- try {
1264
- const code = readFileSync(blockFile, "utf8");
1265
-
1266
- // Parse human-readable title and metadata from setting exports
1267
- const settingsMatch = code.match(/export\s+const\s+settings\s*=\s*(\{[\s\S]*?\});/);
1268
- let settings = {
1269
- apiVersion: 3,
1270
- name: `forgewp/${blockSlug}`,
1271
- title: blockSlug.split("-").map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(" "),
1272
- category: "design",
1273
- icon: "admin-generic",
1274
- attributes: {},
1275
- render: "file:./render.php"
1276
- };
1277
-
1278
- if (settingsMatch) {
1279
- try {
1280
- // Evaluates settings safely without external libraries
1281
- const evalFn = new Function(`return ${settingsMatch[1]};`);
1282
- settings = { ...settings, ...evalFn() };
1283
- // Ensure schema, apiVersion, name and render path are strictly aligned
1284
- settings.name = `forgewp/${blockSlug}`;
1285
- settings.apiVersion = 3;
1286
- settings.render = "file:./render.php";
1287
- } catch (e) {
1288
- console.warn(`[Gutenberg Block Compiler] Error parsing settings for ${blockSlug}:`, e.message);
1289
- }
1290
- }
1291
-
1292
- // Parse JSX block content
1293
- let jsx = "";
1294
- const returnMatch = code.match(/return\s*\(\s*(<[\s\S]*?>)\s*\)/);
1295
- if (returnMatch) {
1296
- jsx = returnMatch[1];
1297
- } else {
1298
- const returnMatchSingle = code.match(/return\s+(<[\s\S]*?>);/);
1299
- if (returnMatchSingle) {
1300
- jsx = returnMatchSingle[1];
1301
- }
1302
- }
1303
-
1304
- if (!jsx) {
1305
- console.warn(`[Gutenberg Block Compiler] Skipping block ${blockSlug}: No returning JSX element found.`);
1306
- continue;
1307
- }
1308
-
1309
- // Translate dynamic attributes inside returning JSX into dynamic PHP echoes
1310
- let phpMarkup = jsx;
1311
-
1312
- // className="..." -> class="..."
1313
- phpMarkup = phpMarkup.replace(/className=/g, "class=");
1314
-
1315
- // src={image} or src={attributes.image}
1316
- phpMarkup = phpMarkup.replace(/(src|href|alt|title)=\{\s*(?:attributes\.|props\.)?([a-zA-Z0-9_-]+)\s*\}/gi, (match, attr, varName) => {
1317
- const escFunc = attr === "href" || attr === "src" ? "esc_url" : "esc_attr";
1318
- return `${attr}="<?php echo ${escFunc}( $attributes['${varName}'] ?? '' ); ?>"`;
1319
- });
1320
-
1321
- // {title} or {props.title}
1322
- phpMarkup = phpMarkup.replace(/\{\s*(?:attributes\.|props\.)?([a-zA-Z0-9_-]+)\s*\}/g, (match, varName) => {
1323
- return `<?php echo esc_html( $attributes['${varName}'] ?? '' ); ?>`;
1324
- });
1325
-
1326
- // Wrap the final PHP template markup in a clean block wrapper
1327
- const renderPhpContent = `<?php
1328
- /**
1329
- * Gutenberg dynamic block template — ${settings.title}
1330
- * Autogenerated by ForgeWP Theme Compiler. Do not modify manually.
1331
- */
1332
- ?>
1333
- ${phpMarkup}
1334
- `;
1335
-
1336
- const blockOutDir = path.join(outDir, "blocks", blockSlug);
1337
- mkdirSync(blockOutDir, { recursive: true });
1338
-
1339
- // Write block.json and render.php
1340
- writeFileSync(path.join(blockOutDir, "block.json"), JSON.stringify(settings, null, 2), "utf8");
1341
- writeFileSync(path.join(blockOutDir, "render.php"), renderPhpContent, "utf8");
1342
-
1343
- blockSlugs.push(settings);
1344
- } catch (e) {
1345
- console.error(`[Gutenberg Block Compiler] Failed to compile block ${blockSlug}:`, e.message);
1346
- }
1347
- }
1348
- }
1349
-
1350
- return blockSlugs;
1351
- }
1352
-
1
+ import fs, {
2
+ copyFileSync,
3
+ cpSync,
4
+ existsSync,
5
+ mkdirSync,
6
+ readFileSync,
7
+ readdirSync,
8
+ rmSync,
9
+ statSync,
10
+ writeFileSync,
11
+ } from 'node:fs';
12
+ import path from 'node:path';
13
+ import { fileURLToPath, pathToFileURL } from 'node:url';
14
+ import { scanForEditableSchemas } from './hydration-scanner.js';
15
+ import { loadFrameworkAdapter } from './framework-adapter.js';
16
+ import {
17
+ analyzeHydrationIslands,
18
+ printDiagnosticsReport,
19
+ } from './diagnostics.js';
20
+
21
+ // Import newly refactored modular helpers
22
+ import { processMarkup } from './markup-processor.js';
23
+ import {
24
+ buildStyleCss,
25
+ buildHeaderPhp,
26
+ buildFooterPhp,
27
+ buildIndexPhp,
28
+ buildSinglePhp,
29
+ build404Php,
30
+ buildArchivePhp,
31
+ buildPagePhp,
32
+ } from './php-builders.js';
33
+ import { buildFunctionsPhp } from './functions-builder.js';
34
+ import { compileBlocks } from './block-compiler.js';
35
+
36
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
37
+
38
+ /**
39
+ * Orchestrates the theme generation pipeline.
40
+ * Transpiles isomorphic React components into native WordPress theme assets.
41
+ *
42
+ * @param {Object} options
43
+ * @param {string} options.themeRoot
44
+ * @param {string} options.outDir
45
+ * @param {import('./types.js').ForgeWPThemeConfig} options.config
46
+ * @param {string} options.appHtml
47
+ * @param {string} [options.headerHtml]
48
+ * @param {string} [options.footerHtml]
49
+ * @param {import('./types.js').ForgeWPBuildAssets} options.assets
50
+ */
51
+ export async function generateTheme({
52
+ themeRoot,
53
+ outDir,
54
+ config,
55
+ appHtml,
56
+ headerHtml = '',
57
+ footerHtml = '',
58
+ headHtml = '',
59
+ singleHeadHtml = '',
60
+ singleHtml = '',
61
+ notFoundHtml = '',
62
+ archiveHtml = '',
63
+ assets,
64
+ }) {
65
+ if (existsSync(outDir)) {
66
+ rmSync(outDir, { recursive: true, force: true });
67
+ }
68
+
69
+ mkdirSync(outDir, { recursive: true });
70
+
71
+ const schemas = scanForEditableSchemas(themeRoot);
72
+ console.log(`[ForgeWP Compiler] Discovered colocated editable schemas for templates: ${Object.keys(schemas).join(', ') || '<none>'}`);
73
+
74
+ // Load project-specific compiler hooks if they exist in theme src
75
+ let projectHooks = null;
76
+ const hooksPath = path.join(themeRoot, 'src', 'compiler-hooks.js');
77
+ if (existsSync(hooksPath)) {
78
+ console.warn(
79
+ '\x1b[33m%s\x1b[0m',
80
+ '⚠️ [ForgeWP Deprecation Warning]: "compiler-hooks.js" is deprecated. Please migrate custom PHP logic to "src/server/*.php" files.'
81
+ );
82
+ try {
83
+ const fileUrl = pathToFileURL(hooksPath).href;
84
+ projectHooks = await import(fileUrl);
85
+ } catch (e) {
86
+ console.warn('[ForgeWP Compiler] Failed to import project compiler hooks:', e.message);
87
+ }
88
+ }
89
+
90
+ // Load menus configuration for auto-registration and setup
91
+ let menus = {};
92
+ const menusJsonSrc = path.join(themeRoot, 'cms', 'menus.json');
93
+ if (existsSync(menusJsonSrc)) {
94
+ try {
95
+ menus = JSON.parse(readFileSync(menusJsonSrc, 'utf8'));
96
+ } catch (e) {
97
+ console.warn('Failed to parse menus.json:', e.message);
98
+ }
99
+ }
100
+
101
+ // Merge static menu definitions from defineTheme/wp.config.ts config.menus
102
+ if (config.menus) {
103
+ for (const [key, label] of Object.entries(config.menus)) {
104
+ if (!menus[key]) {
105
+ menus[key] = []; // Initialize menu locations for auto-registration
106
+ }
107
+ }
108
+ }
109
+
110
+ // Gather compiled custom page templates for auto-creation with smart slug mapping
111
+ const pagesToAutoCreate = [];
112
+ const pageTemplateSlugs = [];
113
+ const forgewpDir = path.join(themeRoot, '.forgewp');
114
+ if (existsSync(forgewpDir)) {
115
+ const templateFiles = readdirSync(forgewpDir);
116
+ for (const file of templateFiles) {
117
+ if (
118
+ file.startsWith('template-') &&
119
+ file.endsWith('.html') &&
120
+ !file.includes('-head')
121
+ ) {
122
+ const slug = file.replace('.html', '');
123
+ const pageTemplateSlug = slug.replace('template-', '');
124
+ pageTemplateSlugs.push(pageTemplateSlug);
125
+
126
+ let matchedSlug = null;
127
+ let matchedTitle = null;
128
+
129
+ const toKebabTemplateSlug = (str) => {
130
+ const compName =
131
+ str
132
+ .replace(/[^a-zA-Z0-9]/g, ' ')
133
+ .trim()
134
+ .split(/\s+/)
135
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
136
+ .join('') + 'Page';
137
+ return compName.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
138
+ };
139
+
140
+ const targetKebab = pageTemplateSlug;
141
+
142
+ // Search in menus to find matching target URL slugs defined by the developer
143
+ for (const [location, items] of Object.entries(menus)) {
144
+ if (!Array.isArray(items)) continue;
145
+ for (const item of items) {
146
+ if (!item.url || !item.url.startsWith('/')) continue;
147
+ const menuUrlSlug = item.url.replace(/^\//, '');
148
+
149
+ if (
150
+ toKebabTemplateSlug(item.title) === targetKebab ||
151
+ toKebabTemplateSlug(menuUrlSlug) === targetKebab
152
+ ) {
153
+ matchedSlug = menuUrlSlug;
154
+ matchedTitle = item.title;
155
+ break;
156
+ }
157
+ }
158
+ if (matchedSlug) break;
159
+ }
160
+
161
+ // Fallback 1: Strip trailing "-page" from template slug
162
+ if (!matchedSlug) {
163
+ matchedSlug = pageTemplateSlug.endsWith('-page')
164
+ ? pageTemplateSlug.slice(0, -5)
165
+ : pageTemplateSlug;
166
+ }
167
+
168
+ // Fallback 2: Generate clean human-readable title
169
+ if (!matchedTitle) {
170
+ const cleanName = pageTemplateSlug.endsWith('-page')
171
+ ? pageTemplateSlug.slice(0, -5)
172
+ : pageTemplateSlug;
173
+ matchedTitle = cleanName
174
+ .split('-')
175
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
176
+ .join(' ');
177
+ }
178
+
179
+ pagesToAutoCreate.push({
180
+ title: matchedTitle,
181
+ slug: matchedSlug,
182
+ template: `page-${pageTemplateSlug}.php`,
183
+ });
184
+ }
185
+ }
186
+ }
187
+
188
+ const adapter = await loadFrameworkAdapter(config.frameworkAdapter);
189
+ const scanForHydrationIslands =
190
+ adapter.scanForHydrationIslands || adapter.default?.scanForHydrationIslands;
191
+
192
+ const hydrationIslands = scanForHydrationIslands
193
+ ? scanForHydrationIslands(themeRoot)
194
+ : [];
195
+ const hasHydration = hydrationIslands.length > 0;
196
+
197
+ const assetsOut = path.join(outDir, 'assets');
198
+ const distAssets = path.join(themeRoot, 'dist', 'assets');
199
+ mkdirSync(assetsOut, { recursive: true });
200
+ cpSync(distAssets, assetsOut, { recursive: true });
201
+
202
+ // Copy all other files/folders from dist to outDir (excluding .vite, index.html, and assets)
203
+ const distDir = path.join(themeRoot, 'dist');
204
+ if (existsSync(distDir)) {
205
+ const items = readdirSync(distDir);
206
+ for (const item of items) {
207
+ if (item !== '.vite' && item !== 'index.html' && item !== 'assets') {
208
+ const srcPath = path.join(distDir, item);
209
+ const destPath = path.join(outDir, item);
210
+ cpSync(srcPath, destPath, { recursive: true });
211
+ }
212
+ }
213
+ }
214
+
215
+ let hydrationManifestJson = '{}';
216
+ if (hasHydration) {
217
+ const manifestPath = path.join(themeRoot, 'dist', '.vite', 'manifest.json');
218
+ let viteManifest = {};
219
+ if (existsSync(manifestPath)) {
220
+ try {
221
+ viteManifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
222
+ } catch (e) {
223
+ console.warn('Failed to parse Vite manifest.json:', e.message);
224
+ }
225
+ } else {
226
+ console.warn(
227
+ 'Hydration manifest not found at dist/.vite/manifest.json. Hydration asset generation may be incomplete.',
228
+ );
229
+ }
230
+
231
+ const mapping = {};
232
+ let mainJsFile = '';
233
+ const entryChunk =
234
+ viteManifest['index.html'] ||
235
+ Object.values(viteManifest).find((c) => c.isEntry);
236
+ if (entryChunk) {
237
+ mainJsFile = entryChunk.file;
238
+ }
239
+
240
+ for (const island of hydrationIslands) {
241
+ const pascalName = island
242
+ .split('-')
243
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
244
+ .join('');
245
+
246
+ let resolvedChunk = null;
247
+ for (const [key, value] of Object.entries(viteManifest)) {
248
+ const fileBasename = path.basename(value.file || '');
249
+ const cleanName = fileBasename.replace(/-[A-Za-z0-9_-]+\.js$/, '');
250
+ if (
251
+ key.endsWith(`/${pascalName}.tsx`) ||
252
+ key.endsWith(`/${pascalName}.ts`) ||
253
+ key.endsWith(`/${island}.tsx`) ||
254
+ key.endsWith(`/${island}.ts`) ||
255
+ cleanName === island ||
256
+ cleanName === pascalName.toLowerCase()
257
+ ) {
258
+ resolvedChunk = value.file;
259
+ break;
260
+ }
261
+ }
262
+
263
+ if (resolvedChunk) {
264
+ mapping[island] = resolvedChunk;
265
+ }
266
+ }
267
+
268
+ if (!mainJsFile) {
269
+ throw new Error(
270
+ 'Hydration generation failed: could not resolve the React runtime entry chunk. Ensure Vite emitted a valid manifest and the theme entry is present.',
271
+ );
272
+ }
273
+
274
+ const missingIslands = hydrationIslands.filter(
275
+ (island) => !(island in mapping),
276
+ );
277
+ if (missingIslands.length > 0) {
278
+ throw new Error(
279
+ `Hydration generation failed: missing compiled chunk for island(s): ${missingIslands.join(', ')}. ` +
280
+ 'Verify the Hydrate component children and the corresponding Vite input files.',
281
+ );
282
+ }
283
+
284
+ const hydratorScript = `(function () {
285
+ const config = window.forgeWpHydration || { themeUri: "", manifest: {} };
286
+ const islands = document.querySelectorAll("[data-forgewp-hydrate]");
287
+
288
+ const observer = new IntersectionObserver((entries) => {
289
+ entries.forEach((entry) => {
290
+ if (entry.isIntersecting) {
291
+ const hydrate = entry.target.__forgewpHydrate;
292
+ if (typeof hydrate === "function") hydrate();
293
+ observer.unobserve(entry.target);
294
+ }
295
+ });
296
+ }, { rootMargin: "200px" });
297
+
298
+ // Predictive preloading observer with larger viewport margin (600px)
299
+ const preloadObserver = new IntersectionObserver((entries) => {
300
+ entries.forEach((entry) => {
301
+ if (entry.isIntersecting) {
302
+ const el = entry.target;
303
+ preloadElement(el);
304
+ preloadObserver.unobserve(el);
305
+ }
306
+ });
307
+ }, { rootMargin: "600px" });
308
+
309
+ const StrategyRegistry = {
310
+ load: (el, hydrate) => {
311
+ if (document.readyState === "complete") {
312
+ hydrate();
313
+ } else {
314
+ window.addEventListener("load", hydrate);
315
+ }
316
+ },
317
+ visible: (el, hydrate) => {
318
+ el.__forgewpHydrate = hydrate;
319
+ observer.observe(el);
320
+ },
321
+ interaction: (el, hydrate) => {
322
+ const run = () => {
323
+ hydrate();
324
+ el.removeEventListener("click", run);
325
+ el.removeEventListener("mouseenter", run);
326
+ el.removeEventListener("focusin", run);
327
+ };
328
+ el.addEventListener("click", run);
329
+ el.addEventListener("mouseenter", run);
330
+ el.addEventListener("focusin", run);
331
+ },
332
+ click: (el, hydrate) => {
333
+ const run = () => {
334
+ hydrate();
335
+ el.removeEventListener("click", run);
336
+ };
337
+ el.addEventListener("click", run);
338
+ },
339
+ hover: (el, hydrate) => {
340
+ const run = () => {
341
+ hydrate();
342
+ el.removeEventListener("mouseenter", run);
343
+ };
344
+ el.addEventListener("mouseenter", run);
345
+ },
346
+ idle: (el, hydrate) => {
347
+ if ("requestIdleCallback" in window) {
348
+ window.requestIdleCallback(hydrate);
349
+ } else {
350
+ setTimeout(hydrate, 200);
351
+ }
352
+ }
353
+ };
354
+
355
+ islands.forEach((el) => {
356
+ const islandName = el.getAttribute("data-forgewp-hydrate");
357
+
358
+ // 1. Network-Aware Check: Restrict/skip hydration on slow 2G/3G connections if requested
359
+ const connection = el.getAttribute("data-forgewp-connection");
360
+ if (connection === "fast") {
361
+ const conn = navigator.connection;
362
+ if (conn && (conn.saveData || /2g|3g/.test(conn.effectiveType))) {
363
+ console.warn("[ForgeWP Hydrator] Deferring hydration of island '" + islandName + "' due to slow 2G/3G network conditions.");
364
+ return;
365
+ }
366
+ }
367
+
368
+ // 2. Predictive Preloading Setup
369
+ const preload = el.getAttribute("data-forgewp-preload");
370
+ if (preload === "near-visible") {
371
+ preloadObserver.observe(el);
372
+ }
373
+
374
+ const runHydration = () => hydrateElement(el);
375
+
376
+ // 3. Media-Query Check: Gated by target device dimensions
377
+ const media = el.getAttribute("data-forgewp-media");
378
+ if (media) {
379
+ const mql = window.matchMedia(media);
380
+ const setupMediaHydration = () => {
381
+ const trigger = el.getAttribute("data-forgewp-trigger") || "visible";
382
+ const strategy = StrategyRegistry[trigger];
383
+ if (strategy) {
384
+ strategy(el, runHydration);
385
+ } else {
386
+ StrategyRegistry.visible(el, runHydration);
387
+ }
388
+ };
389
+
390
+ if (mql.matches) {
391
+ setupMediaHydration();
392
+ } else {
393
+ const listener = (e) => {
394
+ if (e.matches) {
395
+ setupMediaHydration();
396
+ mql.removeEventListener("change", listener);
397
+ }
398
+ };
399
+ mql.addEventListener("change", listener);
400
+ }
401
+ return;
402
+ }
403
+
404
+ // Standard trigger registration
405
+ const trigger = el.getAttribute("data-forgewp-trigger") || "visible";
406
+ const strategy = StrategyRegistry[trigger];
407
+ if (strategy) {
408
+ strategy(el, runHydration);
409
+ } else {
410
+ StrategyRegistry.visible(el, runHydration);
411
+ }
412
+ });
413
+
414
+ function preloadElement(el) {
415
+ const islandName = el.getAttribute("data-forgewp-hydrate");
416
+ const chunkPath = config.manifest?.[islandName];
417
+ if (!chunkPath) return;
418
+ const scriptUrl = config.themeUri + "/assets/" + chunkPath.replace("assets/", "").replace("assets\\\\", "");
419
+
420
+ // Inject link[rel=modulepreload]
421
+ if (document.querySelector("link[href='" + scriptUrl + "']")) return;
422
+ const link = document.createElement("link");
423
+ link.rel = "modulepreload";
424
+ link.href = scriptUrl;
425
+ document.head.appendChild(link);
426
+ }
427
+
428
+ function hydrateElement(el) {
429
+ const islandName = el.getAttribute("data-forgewp-hydrate");
430
+ if (!islandName) {
431
+ console.error("[ForgeWP Hydrator] Missing data-forgewp-hydrate attribute on hydration boundary.");
432
+ return;
433
+ }
434
+
435
+ const rawProps = el.getAttribute("data-forgewp-props") || "{}";
436
+ let props = {};
437
+ try {
438
+ props = JSON.parse(rawProps);
439
+ } catch (err) {
440
+ console.error("[ForgeWP Hydrator] Failed to parse props for island " + islandName + ":", err);
441
+ }
442
+
443
+ const chunkPath = config.manifest?.[islandName];
444
+ if (!chunkPath) {
445
+ const available = config.manifest ? Object.keys(config.manifest).join(", ") : "<none>";
446
+ console.error(
447
+ "[ForgeWP Hydrator] Could not find compiled chunk for island " + islandName + ". " +
448
+ "Available manifest keys: " + available
449
+ );
450
+ return;
451
+ }
452
+
453
+ const scriptUrl = config.themeUri + "/assets/" + chunkPath.replace("assets/", "").replace("assets\\\\", "");
454
+
455
+ import(scriptUrl)
456
+ .then((module) => {
457
+ let Component = module.default;
458
+ if (!Component) {
459
+ Component = Object.values(module).find((val) => typeof val === "function");
460
+ if (!Component) {
461
+ Component = Object.values(module)[0];
462
+ }
463
+ }
464
+ if (typeof Component !== "function") {
465
+ const exportsList = Object.keys(module).join(", ");
466
+ console.error(
467
+ "[ForgeWP Hydrator] Chunk for " + islandName + " does not export a valid React component. " +
468
+ "Available exports: " + exportsList
469
+ );
470
+ return;
471
+ }
472
+
473
+ // Resolve ReactDOM/React — prefer window globals set by main.tsx.
474
+ // Always use createRoot (not hydrateRoot): island chunks bundle their
475
+ // own React via Vite code-splitting, so hydrateRoot from window.ReactDOM
476
+ // (a different instance) causes a silent Fiber reconciler failure.
477
+ // createRoot takes full ownership of the container, bypassing this issue.
478
+ const ReactDOM = window.ReactDOM;
479
+ const React = window.React;
480
+
481
+ if (ReactDOM && React) {
482
+ const root = ReactDOM.createRoot(el);
483
+ root.render(React.createElement(Component, props));
484
+ } else {
485
+ console.error("[ForgeWP Hydration Error] React or ReactDOM not found on window. Ensure main.tsx exposes window.React and window.ReactDOM.");
486
+ }
487
+ })
488
+ .catch((err) => {
489
+ console.error("[ForgeWP Hydrator] Failed to load chunk for " + islandName + ":", err);
490
+ });
491
+ }
492
+ })();`;
493
+
494
+ writeFileSync(
495
+ path.join(assetsOut, 'forgewp-hydrator.js'),
496
+ hydratorScript,
497
+ 'utf8',
498
+ );
499
+ hydrationManifestJson = JSON.stringify({
500
+ mainJsFile,
501
+ mapping,
502
+ });
503
+
504
+ // Run compiler diagnostics & output detailed metrics
505
+ const analysis = analyzeHydrationIslands(themeRoot, mapping);
506
+ printDiagnosticsReport(analysis);
507
+ }
508
+
509
+ // Drop unused JS from the theme ZIP
510
+ const files = readdirSync(assetsOut);
511
+ for (const file of files) {
512
+ if (
513
+ (file.endsWith('.js') || file.endsWith('.js.map')) &&
514
+ file !== 'forgewp-editor.js' &&
515
+ file !== 'forgewp-hydrator.js'
516
+ ) {
517
+ if (!hasHydration) {
518
+ rmSync(path.join(assetsOut, file), { force: true });
519
+ }
520
+ }
521
+ }
522
+
523
+ // Scan all page templates for translations before processMarkup replaces them
524
+ const i18nKeys = new Set();
525
+ const scanForI18nKeys = (content) => {
526
+ if (!content) return;
527
+ const regex = /__FORGEWP_I18N_([^_](?:[^_]|_(?!_))*?)__/g;
528
+ let match;
529
+ while ((match = regex.exec(content)) !== null) {
530
+ const clean = match[1]
531
+ .replace(/&amp;/g, '&')
532
+ .replace(/&quot;/g, '"')
533
+ .replace(/&#39;/g, "'")
534
+ .replace(/&#x27;/g, "'")
535
+ .replace(/&lt;/g, '<')
536
+ .replace(/&gt;/g, '>');
537
+ i18nKeys.add(clean);
538
+ }
539
+ };
540
+
541
+ scanForI18nKeys(appHtml);
542
+ scanForI18nKeys(headerHtml);
543
+ scanForI18nKeys(footerHtml);
544
+ scanForI18nKeys(singleHtml);
545
+ scanForI18nKeys(notFoundHtml);
546
+ scanForI18nKeys(archiveHtml);
547
+
548
+ if (existsSync(forgewpDir)) {
549
+ const templateFiles = readdirSync(forgewpDir);
550
+ for (const file of templateFiles) {
551
+ if (file.endsWith('.html')) {
552
+ const rawHtml = readFileSync(path.join(forgewpDir, file), 'utf8');
553
+ scanForI18nKeys(rawHtml);
554
+ }
555
+ }
556
+ }
557
+
558
+ // Load and merge keys from cms/translations.json
559
+ const translationsFileSrc = path.join(themeRoot, 'cms', 'translations.json');
560
+ if (existsSync(translationsFileSrc)) {
561
+ try {
562
+ const transData = JSON.parse(readFileSync(translationsFileSrc, 'utf8'));
563
+ for (const locale of Object.keys(transData)) {
564
+ if (transData[locale] && typeof transData[locale] === 'object') {
565
+ for (const key of Object.keys(transData[locale])) {
566
+ i18nKeys.add(key);
567
+ }
568
+ }
569
+ }
570
+ } catch (e) {
571
+ // Ignore parse/read errors during build time
572
+ }
573
+ }
574
+
575
+ // Fix nav links and split markup
576
+ const processedApp = processMarkup(appHtml, config.textDomain);
577
+ const processedHeader = processMarkup(headerHtml, config.textDomain);
578
+ const processedFooter = processMarkup(footerHtml, config.textDomain);
579
+
580
+ // Extract content (App markup minus Header/Footer)
581
+ let contentHtml = processedApp;
582
+ if (processedHeader) {
583
+ const replaced = contentHtml.replace(processedHeader, '');
584
+ contentHtml = replaced !== contentHtml ? replaced : contentHtml.replace(/<header\b[^>]*>([\s\S]*?)<\/header>/i, '');
585
+ }
586
+ if (processedFooter) {
587
+ const replaced = contentHtml.replace(processedFooter, '');
588
+ contentHtml = replaced !== contentHtml ? replaced : contentHtml.replace(/<footer\b[^>]*>([\s\S]*?)<\/footer>/i, '');
589
+ }
590
+ contentHtml = contentHtml.replace(/<div\b[^>]*data-forgewp-hydrate="(navbar|site-header|site-footer)"[^>]*>\s*<\/div>/g, '');
591
+
592
+ // Process single post template if exists
593
+ let processedSingle = '';
594
+ if (singleHtml) {
595
+ processedSingle = processMarkup(singleHtml, config.textDomain);
596
+ if (processedHeader) {
597
+ const replaced = processedSingle.replace(processedHeader, '');
598
+ processedSingle = replaced !== processedSingle ? replaced : processedSingle.replace(/<header\b[^>]*>([\s\S]*?)<\/header>/i, '');
599
+ }
600
+ if (processedFooter) {
601
+ const replaced = processedSingle.replace(processedFooter, '');
602
+ processedSingle = replaced !== processedSingle ? replaced : processedSingle.replace(/<footer\b[^>]*>([\s\S]*?)<\/footer>/i, '');
603
+ }
604
+ processedSingle = processedSingle.replace(/<div\b[^>]*data-forgewp-hydrate="(navbar|site-header|site-footer)"[^>]*>\s*<\/div>/g, '');
605
+ }
606
+
607
+ // Process 404 template if exists
608
+ let processedNotFound = '';
609
+ if (notFoundHtml) {
610
+ processedNotFound = processMarkup(notFoundHtml, config.textDomain);
611
+ if (processedHeader) {
612
+ const replaced = processedNotFound.replace(processedHeader, '');
613
+ processedNotFound = replaced !== processedNotFound ? replaced : processedNotFound.replace(/<header\b[^>]*>([\s\S]*?)<\/header>/i, '');
614
+ }
615
+ if (processedFooter) {
616
+ const replaced = processedNotFound.replace(processedFooter, '');
617
+ processedNotFound = replaced !== processedNotFound ? replaced : processedNotFound.replace(/<footer\b[^>]*>([\s\S]*?)<\/footer>/i, '');
618
+ }
619
+ processedNotFound = processedNotFound.replace(/<div\b[^>]*data-forgewp-hydrate="(navbar|site-header|site-footer)"[^>]*>\s*<\/div>/g, '');
620
+ }
621
+
622
+ const staticDir = path.join(outDir, 'forgewp-static');
623
+ mkdirSync(staticDir, { recursive: true });
624
+ writeFileSync(path.join(staticDir, 'content.html'), contentHtml, 'utf8');
625
+ writeFileSync(path.join(staticDir, 'header.html'), processedHeader, 'utf8');
626
+ writeFileSync(path.join(staticDir, 'footer.html'), processedFooter, 'utf8');
627
+ if (headHtml) {
628
+ writeFileSync(path.join(staticDir, 'head.html'), headHtml, 'utf8');
629
+ }
630
+ if (singleHeadHtml) {
631
+ writeFileSync(
632
+ path.join(staticDir, 'single-head.html'),
633
+ singleHeadHtml,
634
+ 'utf8',
635
+ );
636
+ }
637
+ if (processedSingle) {
638
+ writeFileSync(path.join(staticDir, 'single.html'), processedSingle, 'utf8');
639
+ }
640
+ if (processedNotFound) {
641
+ writeFileSync(path.join(staticDir, '404.html'), processedNotFound, 'utf8');
642
+ }
643
+
644
+ // Archive page (category / tag / date archives)
645
+ let processedArchive = '';
646
+ if (archiveHtml) {
647
+ processedArchive = processMarkup(archiveHtml, config.textDomain);
648
+ if (processedHeader) {
649
+ const replaced = processedArchive.replace(processedHeader, '');
650
+ processedArchive = replaced !== processedArchive ? replaced : processedArchive.replace(/<header\b[^>]*>([\s\S]*?)<\/header>/i, '');
651
+ }
652
+ if (processedFooter) {
653
+ const replaced = processedArchive.replace(processedFooter, '');
654
+ processedArchive = replaced !== processedArchive ? replaced : processedArchive.replace(/<footer\b[^>]*>([\s\S]*?)<\/footer>/i, '');
655
+ }
656
+ processedArchive = processedArchive.replace(/<div\b[^>]*data-forgewp-hydrate="(navbar|site-header|site-footer)"[^>]*>\s*<\/div>/g, '');
657
+ writeFileSync(
658
+ path.join(staticDir, 'archive.html'),
659
+ processedArchive,
660
+ 'utf8',
661
+ );
662
+ }
663
+
664
+ // Dynamic Gutenberg blocks compilation (Phase 5)
665
+ const compiledBlocks = compileBlocks(themeRoot, outDir);
666
+
667
+ const editorScriptContent = `
668
+ const { registerBlockType } = wp.blocks;
669
+ const { createElement } = wp.element;
670
+ const { InspectorControls, useBlockProps } = wp.blockEditor;
671
+ const { PanelBody, TextControl } = wp.components;
672
+ const ServerSideRender = wp.serverSideRender;
673
+
674
+ if (window.forgeWpBlocks) {
675
+ window.forgeWpBlocks.forEach(block => {
676
+ registerBlockType(block.name, {
677
+ title: block.title,
678
+ icon: block.icon,
679
+ category: block.category,
680
+ attributes: block.attributes,
681
+ edit: function(props) {
682
+ const { attributes, setAttributes } = props;
683
+ const blockProps = useBlockProps();
684
+
685
+ if (block.customEditJsx) {
686
+ try {
687
+ const renderFn = new Function('props', 'createElement', 'useBlockProps', 'attributes', 'setAttributes', 'blockProps',
688
+ 'return ' + block.customEditJsx
689
+ );
690
+ return renderFn(props, createElement, useBlockProps, attributes, setAttributes, blockProps);
691
+ } catch (e) {
692
+ console.error("[ForgeWP Editor] Custom edit render failed for block " + block.name + ":", e);
693
+ return createElement('div', blockProps, 'Render Error: ' + e.message);
694
+ }
695
+ }
696
+
697
+ // Build inspector controls dynamically from attributes
698
+ const controls = Object.keys(block.attributes).map(key => {
699
+ return createElement(TextControl, {
700
+ label: key.charAt(0).toUpperCase() + key.slice(1),
701
+ value: attributes[key],
702
+ onChange: (val) => setAttributes({ [key]: val })
703
+ });
704
+ });
705
+
706
+ return createElement('div', blockProps,
707
+ createElement(InspectorControls, null,
708
+ createElement(PanelBody, { title: 'Block Settings', initialOpen: true }, controls)
709
+ ),
710
+ createElement(ServerSideRender, {
711
+ block: block.name,
712
+ attributes: attributes
713
+ })
714
+ );
715
+ },
716
+ save: function() {
717
+ return null; // Dynamic blocks return null in save
718
+ }
719
+ });
720
+ });
721
+ }
722
+ `;
723
+ writeFileSync(
724
+ path.join(outDir, 'assets', 'forgewp-editor.js'),
725
+ editorScriptContent,
726
+ 'utf8',
727
+ );
728
+
729
+ writeFileSync(path.join(outDir, 'style.css'), buildStyleCss(config), 'utf8');
730
+
731
+ let hydrationData = null;
732
+ if (hasHydration) {
733
+ try {
734
+ hydrationData = JSON.parse(hydrationManifestJson);
735
+ } catch {}
736
+ }
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
+
741
+ let functionsPhpContent = buildFunctionsPhp(
742
+ config,
743
+ assets,
744
+ compiledBlocks,
745
+ themeRoot,
746
+ pagesToAutoCreate,
747
+ menus,
748
+ hydrationData,
749
+ Array.from(i18nKeys),
750
+ schemas,
751
+ queries,
752
+ );
753
+
754
+ if (projectHooks && typeof projectHooks.processFunctionsPhp === 'function') {
755
+ functionsPhpContent = projectHooks.processFunctionsPhp(functionsPhpContent, config);
756
+ }
757
+
758
+ // Execute plugin functions.php transformation hooks
759
+ if (config.plugins && Array.isArray(config.plugins)) {
760
+ for (const plugin of config.plugins) {
761
+ if (typeof plugin.transformFunctionsPhp === 'function') {
762
+ functionsPhpContent = plugin.transformFunctionsPhp(functionsPhpContent, config, themeRoot, { fs, path });
763
+ }
764
+ }
765
+ }
766
+
767
+ // Append custom PHP server escape hatch files from src/server/*.php
768
+ const serverDir = path.join(themeRoot, 'src', 'server');
769
+ if (existsSync(serverDir)) {
770
+ const phpFiles = readdirSync(serverDir)
771
+ .filter((file) => file.endsWith('.php'))
772
+ .sort();
773
+ if (phpFiles.length > 0) {
774
+ let serverPhpContent = '\n\n/**\n * ── PHP Server Escape Hatch (src/server/) ──\n */';
775
+ for (const file of phpFiles) {
776
+ const filePath = path.join(serverDir, file);
777
+ let content = readFileSync(filePath, 'utf8');
778
+ // Clean leading and trailing php tags safely
779
+ content = content
780
+ .replace(/^<\?php\s*/i, '')
781
+ .replace(/^<\?\s*/i, '')
782
+ .replace(/\s*\?>\s*$/i, '');
783
+ serverPhpContent += `\n\n/**\n * Source: src/server/${file}\n */\n${content.trim()}`;
784
+ }
785
+ functionsPhpContent += serverPhpContent + '\n';
786
+ }
787
+ }
788
+
789
+ writeFileSync(
790
+ path.join(outDir, 'functions.php'),
791
+ functionsPhpContent,
792
+ 'utf8',
793
+ );
794
+
795
+ // Copy translations.json directly if it exists in the project cms/ folder
796
+ const translationsSrc = path.join(themeRoot, 'cms', 'translations.json');
797
+ if (existsSync(translationsSrc)) {
798
+ copyFileSync(translationsSrc, path.join(outDir, 'translations.json'));
799
+ }
800
+ writeFileSync(
801
+ path.join(outDir, 'header.php'),
802
+ buildHeaderPhp(config),
803
+ 'utf8',
804
+ );
805
+ writeFileSync(
806
+ path.join(outDir, 'footer.php'),
807
+ buildFooterPhp(config),
808
+ 'utf8',
809
+ );
810
+ writeFileSync(path.join(outDir, 'index.php'), buildIndexPhp(), 'utf8');
811
+ writeFileSync(path.join(outDir, 'single.php'), buildSinglePhp(), 'utf8');
812
+ writeFileSync(path.join(outDir, '404.php'), build404Php(), 'utf8');
813
+ writeFileSync(path.join(outDir, 'front-page.php'), buildIndexPhp(), 'utf8');
814
+ writeFileSync(path.join(outDir, 'archive.php'), buildArchivePhp(), 'utf8');
815
+ writeFileSync(path.join(outDir, 'page.php'), buildPagePhp(), 'utf8');
816
+
817
+ // Dynamic Custom WP hierarchy templates compiler (single-*, taxonomy-*, archive-*, etc.)
818
+ if (existsSync(forgewpDir)) {
819
+ const templateFiles = readdirSync(forgewpDir);
820
+ for (const file of templateFiles) {
821
+ const name = file.replace('.html', '');
822
+ const isHierarchyTemplate =
823
+ (name.startsWith('single-') ||
824
+ name.startsWith('archive-') ||
825
+ name.startsWith('taxonomy-') ||
826
+ name === 'taxonomy') &&
827
+ file.endsWith('.html') &&
828
+ !file.includes('-head');
829
+
830
+ if (isHierarchyTemplate) {
831
+ const rawHtml = readFileSync(path.join(forgewpDir, file), 'utf8');
832
+ let processedHtml = processMarkup(rawHtml, config.textDomain);
833
+ if (processedHeader) {
834
+ const replaced = processedHtml.replace(processedHeader, '');
835
+ processedHtml = replaced !== processedHtml ? replaced : processedHtml.replace(/<header\b[^>]*>([\s\S]*?)<\/header>/i, '');
836
+ }
837
+ if (processedFooter) {
838
+ const replaced = processedHtml.replace(processedFooter, '');
839
+ processedHtml = replaced !== processedHtml ? replaced : processedHtml.replace(/<footer\b[^>]*>([\s\S]*?)<\/footer>/i, '');
840
+ }
841
+ processedHtml = processedHtml.replace(/<div\b[^>]*data-forgewp-hydrate="(navbar|site-header|site-footer)"[^>]*>\s*<\/div>/g, '');
842
+
843
+ writeFileSync(path.join(staticDir, file), processedHtml, 'utf8');
844
+
845
+ const headFile = file.replace('.html', '-head.html');
846
+ if (existsSync(path.join(forgewpDir, headFile))) {
847
+ writeFileSync(
848
+ path.join(staticDir, headFile),
849
+ readFileSync(path.join(forgewpDir, headFile), 'utf8'),
850
+ 'utf8',
851
+ );
852
+ }
853
+
854
+ const phpLoop = name.startsWith('single-')
855
+ ? ` if (have_posts()) {
856
+ the_post();
857
+ include $markup_file;
858
+ } else {
859
+ include $markup_file;
860
+ }`
861
+ : ` if (have_posts()) {
862
+ while (have_posts()) {
863
+ the_post();
864
+ include $markup_file;
865
+ }
866
+ } else {
867
+ include $markup_file;
868
+ }`;
869
+
870
+ const phpContent = `<?php
871
+ /**
872
+ * Dynamic ${name} template
873
+ *
874
+ * @package ${config.textDomain}
875
+ */
876
+
877
+ get_header();
878
+
879
+ $markup_file = get_template_directory() . '/forgewp-static/${file}';
880
+ if (file_exists($markup_file)) {
881
+ ${phpLoop}
882
+ }
883
+
884
+ get_footer();
885
+ `;
886
+ writeFileSync(path.join(outDir, `${name}.php`), phpContent, 'utf8');
887
+ console.warn(`[ForgeWP Compiler] Wrote dynamic WP template ${name}.php`);
888
+ }
889
+ }
890
+ }
891
+
892
+ // Dynamic Custom Page Templates Compiler
893
+ if (existsSync(forgewpDir)) {
894
+ const templateFiles = readdirSync(forgewpDir);
895
+ for (const file of templateFiles) {
896
+ if (
897
+ file.startsWith('template-') &&
898
+ file.endsWith('.html') &&
899
+ !file.includes('-head')
900
+ ) {
901
+ const slug = file.replace('.html', '');
902
+ const rawHtml = readFileSync(path.join(forgewpDir, file), 'utf8');
903
+
904
+ let processedHtml = processMarkup(rawHtml, config.textDomain);
905
+ if (processedHeader) {
906
+ const replaced = processedHtml.replace(processedHeader, '');
907
+ processedHtml = replaced !== processedHtml ? replaced : processedHtml.replace(/<header\b[^>]*>([\s\S]*?)<\/header>/i, '');
908
+ }
909
+ if (processedFooter) {
910
+ const replaced = processedHtml.replace(processedFooter, '');
911
+ processedHtml = replaced !== processedHtml ? replaced : processedHtml.replace(/<footer\b[^>]*>([\s\S]*?)<\/footer>/i, '');
912
+ }
913
+ processedHtml = processedHtml.replace(/<div\b[^>]*data-forgewp-hydrate="(navbar|site-header|site-footer)"[^>]*>\s*<\/div>/g, '');
914
+
915
+ if (projectHooks && typeof projectHooks.processTemplateMarkup === 'function') {
916
+ processedHtml = projectHooks.processTemplateMarkup(slug, processedHtml, config);
917
+ }
918
+
919
+ writeFileSync(path.join(staticDir, file), processedHtml, 'utf8');
920
+
921
+ const headFile = file.replace('.html', '-head.html');
922
+ if (existsSync(path.join(forgewpDir, headFile))) {
923
+ writeFileSync(
924
+ path.join(staticDir, headFile),
925
+ readFileSync(path.join(forgewpDir, headFile), 'utf8'),
926
+ 'utf8',
927
+ );
928
+ }
929
+
930
+ // Generate the native WordPress PHP Custom Page Template
931
+ const templateName = slug
932
+ .replace('template-', '')
933
+ .split('-')
934
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
935
+ .join(' ');
936
+ const phpContent = `<?php
937
+ /**
938
+ * Template Name: ${templateName}
939
+ *
940
+ * @package ${config.textDomain}
941
+ */
942
+
943
+ get_header();
944
+
945
+ $markup_file = get_template_directory() . '/forgewp-static/${file}';
946
+ if (file_exists($markup_file)) {
947
+ include $markup_file;
948
+ }
949
+
950
+ get_footer();
951
+ `;
952
+ writeFileSync(
953
+ path.join(outDir, `page-${slug.replace('template-', '')}.php`),
954
+ phpContent,
955
+ 'utf8',
956
+ );
957
+ }
958
+ }
959
+ }
960
+
961
+ // Dynamic theme.json compiler (Phase 5)
962
+ const themeJsonSrc = path.join(themeRoot, 'cms', 'theme.json');
963
+ let themeJson = {
964
+ $schema: 'https://schemas.wp.org/trunk/theme.json',
965
+ version: 3,
966
+ settings: {
967
+ appearanceTools: true,
968
+ },
969
+ };
970
+
971
+ if (existsSync(themeJsonSrc)) {
972
+ try {
973
+ themeJson = JSON.parse(readFileSync(themeJsonSrc, 'utf8'));
974
+ } catch (e) {
975
+ console.warn('Failed to parse theme.json template:', e.message);
976
+ }
977
+ }
978
+
979
+ // Merge tokens from wp.config.ts
980
+ if (config.settings) {
981
+ if (!themeJson.settings) themeJson.settings = {};
982
+
983
+ // Layout (contentSize, wideSize)
984
+ if (config.settings.layout) {
985
+ themeJson.settings.layout = {
986
+ ...themeJson.settings.layout,
987
+ ...config.settings.layout,
988
+ };
989
+ }
990
+
991
+ // Colors (custom, palette)
992
+ if (config.settings.color) {
993
+ themeJson.settings.color = {
994
+ ...themeJson.settings.color,
995
+ ...config.settings.color,
996
+ };
997
+ }
998
+
999
+ // Typography (fontSizes, fontFamilies)
1000
+ if (config.settings.typography) {
1001
+ themeJson.settings.typography = {
1002
+ ...themeJson.settings.typography,
1003
+ ...config.settings.typography,
1004
+ };
1005
+ }
1006
+ }
1007
+
1008
+ writeFileSync(
1009
+ path.join(outDir, 'theme.json'),
1010
+ JSON.stringify(themeJson, null, 2),
1011
+ 'utf8',
1012
+ );
1013
+
1014
+ const screenshot = path.join(themeRoot, 'cms', 'screenshot.png');
1015
+ if (existsSync(screenshot)) {
1016
+ copyFileSync(screenshot, path.join(outDir, 'screenshot.png'));
1017
+ } else {
1018
+ const fallbackScreenshot = path.join(__dirname, 'screenshot-fallback.png');
1019
+ if (existsSync(fallbackScreenshot)) {
1020
+ copyFileSync(fallbackScreenshot, path.join(outDir, 'screenshot.png'));
1021
+ }
1022
+ }
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
+ }