@forgewp/compiler 0.1.8 → 0.1.9

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.
@@ -37,14 +37,12 @@ export function generateTheme({
37
37
  cpSync(distAssets, assetsOut, { recursive: true });
38
38
 
39
39
  // Drop unused JS from the theme ZIP
40
- import("node:fs").then(({ readdirSync, unlinkSync }) => {
41
- const files = readdirSync(assetsOut);
42
- for (const file of files) {
43
- if (file.endsWith(".js") || file.endsWith(".js.map")) {
44
- unlinkSync(path.join(assetsOut, file));
45
- }
40
+ const files = readdirSync(assetsOut);
41
+ for (const file of files) {
42
+ if ((file.endsWith(".js") || file.endsWith(".js.map")) && file !== "forgewp-editor.js") {
43
+ rmSync(path.join(assetsOut, file), { force: true });
46
44
  }
47
- });
45
+ }
48
46
 
49
47
  // Fix nav links and split markup
50
48
  const processedApp = processMarkup(appHtml);
@@ -114,10 +112,56 @@ export function generateTheme({
114
112
  // Dynamic Gutenberg blocks compilation (Phase 5)
115
113
  const compiledBlocks = compileBlocks(themeRoot, outDir);
116
114
 
115
+ const editorScriptContent = `
116
+ const { registerBlockType } = wp.blocks;
117
+ const { createElement } = wp.element;
118
+ const { InspectorControls, useBlockProps } = wp.blockEditor;
119
+ const { PanelBody, TextControl } = wp.components;
120
+ const ServerSideRender = wp.serverSideRender;
121
+
122
+ if (window.forgeWpBlocks) {
123
+ window.forgeWpBlocks.forEach(block => {
124
+ registerBlockType(block.name, {
125
+ title: block.title,
126
+ icon: block.icon,
127
+ category: block.category,
128
+ attributes: block.attributes,
129
+ edit: function(props) {
130
+ const { attributes, setAttributes } = props;
131
+ const blockProps = useBlockProps();
132
+
133
+ // Build inspector controls dynamically from attributes
134
+ const controls = Object.keys(block.attributes).map(key => {
135
+ return createElement(TextControl, {
136
+ label: key.charAt(0).toUpperCase() + key.slice(1),
137
+ value: attributes[key],
138
+ onChange: (val) => setAttributes({ [key]: val })
139
+ });
140
+ });
141
+
142
+ return createElement('div', blockProps,
143
+ createElement(InspectorControls, null,
144
+ createElement(PanelBody, { title: 'Block Settings', initialOpen: true }, controls)
145
+ ),
146
+ createElement(ServerSideRender, {
147
+ block: block.name,
148
+ attributes: attributes
149
+ })
150
+ );
151
+ },
152
+ save: function() {
153
+ return null; // Dynamic blocks return null in save
154
+ }
155
+ });
156
+ });
157
+ }
158
+ `;
159
+ writeFileSync(path.join(outDir, "assets", "forgewp-editor.js"), editorScriptContent, "utf8");
160
+
117
161
  writeFileSync(path.join(outDir, "style.css"), buildStyleCss(config), "utf8");
118
162
  writeFileSync(
119
163
  path.join(outDir, "functions.php"),
120
- buildFunctionsPhp(config, assets, compiledBlocks),
164
+ buildFunctionsPhp(config, assets, compiledBlocks, themeRoot),
121
165
  "utf8",
122
166
  );
123
167
  writeFileSync(path.join(outDir, "header.php"), buildHeaderPhp(config), "utf8");
@@ -129,6 +173,49 @@ export function generateTheme({
129
173
  writeFileSync(path.join(outDir, "archive.php"), buildArchivePhp(), "utf8");
130
174
  writeFileSync(path.join(outDir, "page.php"), buildPagePhp(), "utf8");
131
175
 
176
+ // Dynamic Custom Page Templates Compiler
177
+ const forgewpDir = path.join(themeRoot, ".forgewp");
178
+ if (existsSync(forgewpDir)) {
179
+ const templateFiles = readdirSync(forgewpDir);
180
+ for (const file of templateFiles) {
181
+ if (file.startsWith("template-") && file.endsWith(".html") && !file.includes("-head")) {
182
+ const slug = file.replace(".html", "");
183
+ const rawHtml = readFileSync(path.join(forgewpDir, file), "utf8");
184
+
185
+ let processedHtml = processMarkup(rawHtml);
186
+ if (processedHeader) processedHtml = processedHtml.replace(processedHeader, "");
187
+ if (processedFooter) processedHtml = processedHtml.replace(processedFooter, "");
188
+
189
+ writeFileSync(path.join(staticDir, file), processedHtml, "utf8");
190
+
191
+ const headFile = file.replace(".html", "-head.html");
192
+ if (existsSync(path.join(forgewpDir, headFile))) {
193
+ writeFileSync(path.join(staticDir, headFile), readFileSync(path.join(forgewpDir, headFile), "utf8"), "utf8");
194
+ }
195
+
196
+ // Generate the native WordPress PHP Custom Page Template
197
+ const templateName = slug.replace("template-", "").split("-").map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
198
+ const phpContent = `<?php
199
+ /**
200
+ * Template Name: ${templateName}
201
+ *
202
+ * @package ${config.textDomain}
203
+ */
204
+
205
+ get_header();
206
+
207
+ $markup_file = get_template_directory() . '/forgewp-static/${file}';
208
+ if (file_exists($markup_file)) {
209
+ include $markup_file;
210
+ }
211
+
212
+ get_footer();
213
+ `;
214
+ writeFileSync(path.join(outDir, `page-${slug.replace("template-", "")}.php`), phpContent, "utf8");
215
+ }
216
+ }
217
+ }
218
+
132
219
  // Dynamic theme.json compiler (Phase 5)
133
220
  const themeJsonSrc = path.join(themeRoot, "wordpress", "theme.json");
134
221
  let themeJson = {
@@ -331,11 +418,51 @@ Text Domain: ${config.textDomain}
331
418
  * @param {import('./types.js').ForgeWPThemeConfig} config
332
419
  * @param {import('./types.js').ForgeWPBuildAssets} assets
333
420
  */
334
- function buildFunctionsPhp(config, assets, blockSlugs = []) {
421
+ function buildFunctionsPhp(config, assets, blockSlugs = [], themeRoot = "") {
335
422
  const css = assets.cssFile.replace(/^assets\//, "");
336
423
  const version = config.version.replace(/'/g, "\\'");
337
424
  const googleFonts = config.settings?.typography?.googleFonts || [];
338
425
 
426
+ let cptRegistration = "";
427
+ try {
428
+ const mockDataPath = path.join(themeRoot, "wordpress", "mock-data.json");
429
+ if (existsSync(mockDataPath)) {
430
+ const mockData = JSON.parse(readFileSync(mockDataPath, "utf8"));
431
+ const postTypes = Object.keys(mockData).filter(k => k !== "posts" && k !== "pages" && k !== "post" && k !== "page" && k !== "menus");
432
+ if (postTypes.length > 0) {
433
+ cptRegistration = `
434
+ /**
435
+ * Register dynamic Custom Post Types inferred from local mock data.
436
+ */
437
+ function forgewp_register_custom_post_types() {
438
+ ${postTypes.map(pt => ` register_post_type('${pt}', array(
439
+ 'labels' => array(
440
+ 'name' => '${pt.charAt(0).toUpperCase() + pt.slice(1)}s',
441
+ 'singular_name' => '${pt.charAt(0).toUpperCase() + pt.slice(1)}',
442
+ 'menu_name' => '${pt.charAt(0).toUpperCase() + pt.slice(1)}s',
443
+ 'name_admin_bar' => '${pt.charAt(0).toUpperCase() + pt.slice(1)}',
444
+ 'add_new' => 'Add New',
445
+ 'add_new_item' => 'Add New ${pt.charAt(0).toUpperCase() + pt.slice(1)}',
446
+ 'new_item' => 'New ${pt.charAt(0).toUpperCase() + pt.slice(1)}',
447
+ 'edit_item' => 'Edit ${pt.charAt(0).toUpperCase() + pt.slice(1)}',
448
+ 'view_item' => 'View ${pt.charAt(0).toUpperCase() + pt.slice(1)}',
449
+ 'all_items' => 'All ${pt.charAt(0).toUpperCase() + pt.slice(1)}s',
450
+ 'search_items' => 'Search ${pt.charAt(0).toUpperCase() + pt.slice(1)}s',
451
+ 'not_found' => 'No ${pt.charAt(0).toUpperCase() + pt.slice(1)}s found.',
452
+ ),
453
+ 'public' => true,
454
+ 'has_archive' => true,
455
+ 'show_in_rest'=> true,
456
+ 'supports' => array('title', 'editor', 'thumbnail', 'custom-fields', 'excerpt'),
457
+ 'menu_icon' => 'dashicons-admin-post',
458
+ ));`).join("\n")}
459
+ }
460
+ add_action('init', 'forgewp_register_custom_post_types');
461
+ `;
462
+ }
463
+ }
464
+ } catch (e) {}
465
+
339
466
  let fontsEnqueue = "";
340
467
  let preconnectFilter = "";
341
468
 
@@ -379,12 +506,32 @@ add_filter('wp_resource_hints', 'forgewp_google_fonts_resource_hints', 10, 2);
379
506
  * Register dynamic Gutenberg blocks compiled by ForgeWP.
380
507
  */
381
508
  function forgewp_register_dynamic_blocks(): void {
382
- $blocks = array(${blocksArray});
509
+ $blocks = array(${blockSlugs.map(s => `'${s.name.replace("forgewp/", "")}'`).join(", ")});
383
510
  foreach ($blocks as $block) {
384
511
  register_block_type(__DIR__ . '/blocks/' . $block);
385
512
  }
386
513
  }
387
514
  add_action('init', 'forgewp_register_dynamic_blocks');
515
+
516
+ /**
517
+ * Enqueue Block Editor JavaScript to dynamically render block interfaces.
518
+ */
519
+ function forgewp_enqueue_block_editor_assets(): void {
520
+ wp_enqueue_script(
521
+ 'forgewp-editor-script',
522
+ get_template_directory_uri() . '/assets/forgewp-editor.js',
523
+ array('wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-server-side-render'),
524
+ FORGEWP_THEME_VERSION,
525
+ true
526
+ );
527
+
528
+ wp_localize_script(
529
+ 'forgewp-editor-script',
530
+ 'forgeWpBlocks',
531
+ json_decode('${JSON.stringify(blockSlugs)}')
532
+ );
533
+ }
534
+ add_action('enqueue_block_editor_assets', 'forgewp_enqueue_block_editor_assets');
388
535
  `;
389
536
  }
390
537
 
@@ -434,7 +581,7 @@ function forgewp_theme_setup(): void {
434
581
  add_editor_style('assets/${css}');
435
582
  }
436
583
  add_action('after_setup_theme', 'forgewp_theme_setup');
437
- ${preconnectFilter}${blocksRegistration}`;
584
+ ${preconnectFilter}${blocksRegistration}${cptRegistration}`;
438
585
  }
439
586
 
440
587
  function buildHeaderPhp(config) {
@@ -784,7 +931,7 @@ ${phpMarkup}
784
931
  writeFileSync(path.join(blockOutDir, "block.json"), JSON.stringify(settings, null, 2), "utf8");
785
932
  writeFileSync(path.join(blockOutDir, "render.php"), renderPhpContent, "utf8");
786
933
 
787
- blockSlugs.push(blockSlug);
934
+ blockSlugs.push(settings);
788
935
  } catch (e) {
789
936
  console.error(`[Gutenberg Block Compiler] Failed to compile block ${blockSlug}:`, e.message);
790
937
  }
@@ -43,6 +43,10 @@ export async function renderStaticMarkup(themeRoot) {
43
43
  const detail = result.stderr?.trim() || result.stdout?.trim() || "Unknown error";
44
44
  throw new Error(`Static render failed:\n${detail}`);
45
45
  }
46
+
47
+ if (result.stderr) {
48
+ console.warn(result.stderr);
49
+ }
46
50
 
47
51
  const outDir = result.stdout?.trim() || path.join(themeRoot, ".forgewp");
48
52
  const appHtmlPath = path.join(outDir, "app.html");
@@ -13,6 +13,7 @@ if (!themeRoot) {
13
13
  // Use the theme's own node_modules for ALL packages (React 19)
14
14
  const require = createRequire(path.join(themeRoot, "package.json"));
15
15
  const React = require("react");
16
+ globalThis.React = React; // Polyfill for classic JSX transform in Node.js
16
17
  const { renderToStaticMarkup } = require("react-dom/server");
17
18
 
18
19
  const appUrl = pathToFileURL(path.join(themeRoot, "src", "app", "page.tsx")).href;
@@ -197,4 +198,35 @@ if (singleHtml) writeFileSync(path.join(outDir, "single.html"), singleHtml, "utf
197
198
  if (notFoundHtml) writeFileSync(path.join(outDir, "404.html"), notFoundHtml, "utf8");
198
199
  if (archiveHtml) writeFileSync(path.join(outDir, "archive.html"), archiveHtml, "utf8");
199
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
+
200
232
  process.stdout.write(outDir);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@forgewp/compiler",
3
- "version": "0.1.8",
3
+ "version": "0.1.9",
4
4
  "description": "Compile ForgeWP React themes into installable WordPress themes",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -25,7 +25,7 @@
25
25
  "jiti": "^2.6.1",
26
26
  "picocolors": "^1.1.1",
27
27
  "react-helmet-async": "^3.0.0",
28
- "@forgewp/registry": "0.1.8"
28
+ "@forgewp/ui": "0.1.9"
29
29
  },
30
30
  "devDependencies": {
31
31
  "@types/node": "^22.19.19"