@forgewp/compiler 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +24 -5
  2. package/bin/analyze.js +158 -0
  3. package/bin/cli.js +29 -4
  4. package/bin/doctor.js +125 -11
  5. package/bin/export.js +20 -0
  6. package/bin/fresh.js +32 -343
  7. package/bin/i18n-extract.js +121 -0
  8. package/bin/i18n-translate.js +112 -0
  9. package/bin/make-block.js +27 -60
  10. package/bin/make-island.js +72 -0
  11. package/bin/make-post-type.js +6 -6
  12. package/bin/make-template.js +145 -0
  13. package/bin/repair.js +2 -2
  14. package/bin/sync-routes.js +28 -158
  15. package/define-config.d.ts +1 -0
  16. package/define-config.js +1 -0
  17. package/lib/adapters/html-adapter.js +65 -0
  18. package/lib/adapters/stub-adapter.js +49 -0
  19. package/lib/add-component.js +282 -183
  20. package/lib/asset-loader.js +27 -0
  21. package/lib/block-compiler.js +552 -0
  22. package/lib/blueprints.js +1459 -501
  23. package/lib/define-config.d.ts +3 -0
  24. package/lib/define-config.js +8 -0
  25. package/lib/diagnostics.js +798 -0
  26. package/lib/export-theme.js +81 -18
  27. package/lib/framework-adapter.js +34 -0
  28. package/lib/functions-builder.js +1801 -0
  29. package/lib/generate-theme.js +1019 -1352
  30. package/lib/hydration-scanner.js +516 -21
  31. package/lib/i18n/extractor.js +60 -0
  32. package/lib/i18n/providers.js +165 -0
  33. package/lib/index.d.ts +115 -3
  34. package/lib/index.js +19 -5
  35. package/lib/load-config.js +122 -6
  36. package/lib/markup-processor.js +584 -0
  37. package/lib/php-builders.js +381 -0
  38. package/lib/react-adapter.js +1336 -0
  39. package/lib/render-static.js +9 -82
  40. package/lib/render-theme.mts +526 -232
  41. package/lib/screenshot-fallback.png +0 -0
  42. package/lib/types.js +1 -0
  43. package/lib/validate-export.js +183 -0
  44. package/package.json +14 -3
  45. package/bin/make-component.js +0 -200
Binary file
package/lib/types.js CHANGED
@@ -5,6 +5,7 @@
5
5
  * @property {string} version
6
6
  * @property {string} description
7
7
  * @property {string} textDomain
8
+ * @property {'react'|'html'|'stub'} [frameworkAdapter]
8
9
  */
9
10
 
10
11
  /**
@@ -0,0 +1,183 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { scanForHydrationIslands } from './hydration-scanner.js';
4
+
5
+ /**
6
+ * Validate exported theme package output.
7
+ * @param {{ themeRoot: string, outDir: string, assets: any, config: any, strict?: boolean }} opts
8
+ */
9
+ export async function validateExport({ themeRoot, outDir, assets, config, strict = false }) {
10
+ const summary = { missing: [], warnings: [] };
11
+ const staticDir = path.join(outDir, 'forgewp-static');
12
+
13
+ const requiredThemeFiles = [
14
+ path.join(outDir, 'functions.php'),
15
+ path.join(outDir, 'style.css'),
16
+ path.join(outDir, 'header.php'),
17
+ path.join(outDir, 'footer.php'),
18
+ path.join(outDir, 'index.php'),
19
+ path.join(outDir, 'single.php'),
20
+ path.join(outDir, '404.php'),
21
+ path.join(outDir, 'front-page.php'),
22
+ path.join(outDir, 'archive.php'),
23
+ path.join(outDir, 'page.php'),
24
+ path.join(outDir, 'theme.json'),
25
+ ];
26
+
27
+ for (const p of requiredThemeFiles) {
28
+ if (!fs.existsSync(p)) summary.missing.push(p.replace(process.cwd() + path.sep, ''));
29
+ }
30
+
31
+ const staticFiles = [
32
+ path.join(staticDir, 'content.html'),
33
+ path.join(staticDir, 'header.html'),
34
+ path.join(staticDir, 'footer.html'),
35
+ ];
36
+
37
+ for (const p of staticFiles) {
38
+ if (!fs.existsSync(p)) {
39
+ summary.missing.push(p.replace(process.cwd() + path.sep, ''));
40
+ } else if (fs.readFileSync(p, 'utf8').trim().length === 0) {
41
+ const relative = p.replace(process.cwd() + path.sep, '');
42
+ if (p.endsWith('content.html')) summary.missing.push(relative);
43
+ else summary.warnings.push(relative);
44
+ }
45
+ }
46
+
47
+ const assetsDir = path.join(outDir, 'assets');
48
+ if (!fs.existsSync(assetsDir) || fs.readdirSync(assetsDir).length === 0) {
49
+ summary.missing.push(assetsDir.replace(process.cwd() + path.sep, ''));
50
+ } else {
51
+ const expectedAssets = [path.join(assetsDir, 'forgewp-editor.js')];
52
+ if (assets?.cssFile) expectedAssets.push(path.join(assetsDir, path.basename(assets.cssFile)));
53
+
54
+ // Hydration-related expectations
55
+ const islands = scanForHydrationIslands(themeRoot);
56
+
57
+ if (islands.length > 0 && assets?.jsFile) {
58
+ expectedAssets.push(path.join(assetsDir, path.basename(assets.jsFile)));
59
+ expectedAssets.push(path.join(assetsDir, 'forgewp-hydrator.js'));
60
+ }
61
+
62
+ for (const assetPath of expectedAssets) {
63
+ if (!fs.existsSync(assetPath)) summary.missing.push(assetPath.replace(process.cwd() + path.sep, ''));
64
+ }
65
+
66
+ const hydrationManifestCandidates = [
67
+ path.join(themeRoot, 'dist', '.vite', 'manifest.json'),
68
+ path.join(themeRoot, 'dist', 'manifest.json'),
69
+ ];
70
+ const hydrationManifestPath = hydrationManifestCandidates.find((candidate) => fs.existsSync(candidate));
71
+ let viteManifest = null;
72
+
73
+ if (islands.length > 0) {
74
+ if (!hydrationManifestPath) {
75
+ summary.missing.push('dist/.vite/manifest.json');
76
+ } else {
77
+ try {
78
+ viteManifest = JSON.parse(fs.readFileSync(hydrationManifestPath, 'utf8'));
79
+ } catch (err) {
80
+ summary.missing.push(`${hydrationManifestPath.replace(process.cwd() + path.sep, '')} (invalid JSON)`);
81
+ }
82
+ }
83
+ }
84
+
85
+ if (viteManifest && islands.length > 0) {
86
+ for (const island of islands) {
87
+ const pascalName = island
88
+ .split('-')
89
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
90
+ .join('');
91
+
92
+ let resolvedChunk = null;
93
+ for (const [key, value] of Object.entries(viteManifest)) {
94
+ const fileBasename = path.basename(value.file || '');
95
+ const cleanName = fileBasename.replace(/-[A-Za-z0-9_-]+\.js$/, '');
96
+ if (
97
+ key.endsWith(`/${pascalName}.tsx`) ||
98
+ key.endsWith(`/${pascalName}.ts`) ||
99
+ key.endsWith(`/${island}.tsx`) ||
100
+ key.endsWith(`/${island}.ts`) ||
101
+ cleanName === island ||
102
+ cleanName === pascalName.toLowerCase()
103
+ ) {
104
+ resolvedChunk = value.file;
105
+ break;
106
+ }
107
+ }
108
+
109
+ if (!resolvedChunk) {
110
+ summary.missing.push(`hydration asset for ${island}`);
111
+ continue;
112
+ }
113
+
114
+ const assetFile = path.join(assetsDir, path.basename(resolvedChunk));
115
+ if (!fs.existsSync(assetFile)) {
116
+ summary.missing.push(assetFile.replace(process.cwd() + path.sep, ''));
117
+ }
118
+ }
119
+ }
120
+
121
+ // functions.php should reference compiled assets when present
122
+ const functionsPhpPath = path.join(outDir, 'functions.php');
123
+ if (fs.existsSync(functionsPhpPath)) {
124
+ const functionsPhp = fs.readFileSync(functionsPhpPath, 'utf8');
125
+ if (assets?.cssFile && !functionsPhp.includes(path.basename(assets.cssFile))) summary.warnings.push(`${functionsPhpPath.replace(process.cwd() + path.sep, '')} (missing CSS asset reference)`);
126
+ if (islands.length > 0 && assets?.jsFile && !functionsPhp.includes(path.basename(assets.jsFile))) summary.warnings.push(`${functionsPhpPath.replace(process.cwd() + path.sep, '')} (missing JS asset reference)`);
127
+ if (islands.length > 0 && !functionsPhp.includes('forgewp-hydrator.js')) summary.warnings.push(`${functionsPhpPath.replace(process.cwd() + path.sep, '')} (missing forgewp-hydrator enqueue)`);
128
+ if (islands.length > 0 && !functionsPhp.includes('forgeWpHydration')) summary.warnings.push(`${functionsPhpPath.replace(process.cwd() + path.sep, '')} (missing hydration manifest localization)`);
129
+ }
130
+ }
131
+
132
+ // Validate style.css metadata
133
+ const styleCssPath = path.join(outDir, 'style.css');
134
+ if (fs.existsSync(styleCssPath)) {
135
+ const styleCss = fs.readFileSync(styleCssPath, 'utf8');
136
+ if (!/Theme Name:/i.test(styleCss)) summary.warnings.push(styleCssPath.replace(process.cwd() + path.sep, ''));
137
+ if (!/Text Domain:/i.test(styleCss)) summary.warnings.push(`${styleCssPath.replace(process.cwd() + path.sep, '')} (missing Text Domain)`);
138
+ }
139
+
140
+ // Validate theme.json
141
+ try {
142
+ const themeJsonPath = path.join(outDir, 'theme.json');
143
+ if (fs.existsSync(themeJsonPath)) {
144
+ const json = JSON.parse(fs.readFileSync(themeJsonPath, 'utf8'));
145
+ if (!json.version) summary.warnings.push('theme.json (missing version)');
146
+ }
147
+ } catch (err) {
148
+ summary.missing.push('theme.json');
149
+ }
150
+
151
+ // Validate generated page templates from .forgewp/template-*.html
152
+ const templateDir = path.join(themeRoot, '.forgewp');
153
+ if (fs.existsSync(templateDir)) {
154
+ const templateFiles = fs.readdirSync(templateDir).filter((file) => /^template-.*\.html$/.test(file));
155
+ for (const templateFile of templateFiles) {
156
+ const slug = templateFile.replace(/^template-(.*)\.html$/, '$1');
157
+ const templatePhp = path.join(outDir, `page-${slug}.php`);
158
+ if (!fs.existsSync(templatePhp)) summary.missing.push(templatePhp.replace(process.cwd() + path.sep, ''));
159
+
160
+ const expectedStaticTemplate = path.join(staticDir, templateFile);
161
+ if (!fs.existsSync(expectedStaticTemplate)) summary.missing.push(expectedStaticTemplate.replace(process.cwd() + path.sep, ''));
162
+
163
+ const headSource = path.join(templateDir, `template-${slug}-head.html`);
164
+ const headOutput = path.join(staticDir, `template-${slug}-head.html`);
165
+ if (fs.existsSync(headSource) && !fs.existsSync(headOutput)) summary.missing.push(headOutput.replace(process.cwd() + path.sep, ''));
166
+ }
167
+ }
168
+
169
+ // Screenshot copy
170
+ const screenshotSrc = path.join(themeRoot, 'cms', 'screenshot.png');
171
+ if (fs.existsSync(screenshotSrc)) {
172
+ const screenshotOut = path.join(outDir, 'screenshot.png');
173
+ if (!fs.existsSync(screenshotOut)) summary.missing.push(screenshotOut.replace(process.cwd() + path.sep, ''));
174
+ }
175
+
176
+ // If strict, treat warnings as missing
177
+ if (strict && summary.warnings.length > 0) {
178
+ summary.missing.push(...summary.warnings);
179
+ summary.warnings = [];
180
+ }
181
+
182
+ return summary;
183
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@forgewp/compiler",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "description": "Compile ForgeWP React themes into installable WordPress themes",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -11,11 +11,17 @@
11
11
  ".": {
12
12
  "types": "./lib/index.d.ts",
13
13
  "default": "./lib/index.js"
14
+ },
15
+ "./define-config": {
16
+ "types": "./define-config.d.ts",
17
+ "default": "./define-config.js"
14
18
  }
15
19
  },
16
20
  "files": [
17
21
  "bin",
18
- "lib"
22
+ "lib",
23
+ "define-config.js",
24
+ "define-config.d.ts"
19
25
  ],
20
26
  "engines": {
21
27
  "node": ">=18"
@@ -25,9 +31,14 @@
25
31
  "jiti": "^2.6.1",
26
32
  "picocolors": "^1.1.1",
27
33
  "react-helmet-async": "^3.0.0",
28
- "@forgewp/ui": "0.3.0"
34
+ "@forgewp/ui": "0.4.1"
29
35
  },
30
36
  "devDependencies": {
31
37
  "@types/node": "^22.19.19"
38
+ },
39
+ "scripts": {
40
+ "test:export-fixture": "node test/export-fixture/run-export-fixture.js",
41
+ "test:adapter-runtime": "node test/adapter-loader.js",
42
+ "test:adapter-types": "pnpm exec tsc --noEmit -p tsconfig.test.json"
32
43
  }
33
44
  }
@@ -1,200 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- import { existsSync, mkdirSync, writeFileSync, readFileSync } from "node:fs";
4
- import path from "node:path";
5
- import pc from "picocolors";
6
-
7
- const args = process.argv.slice(2);
8
- let rawComponentName = args.find(a => !a.startsWith("-"));
9
-
10
- // Support --name PortfolioGrid or --name=PortfolioGrid
11
- const nameIndex = args.indexOf("--name");
12
- if (nameIndex !== -1 && args[nameIndex + 1]) {
13
- rawComponentName = args[nameIndex + 1];
14
- } else {
15
- const nameEqual = args.find(a => a.startsWith("--name="));
16
- if (nameEqual) {
17
- rawComponentName = nameEqual.split("=")[1];
18
- }
19
- }
20
-
21
- if (!rawComponentName) {
22
- console.error(pc.red("\n❌ Error: Please specify a component name."));
23
- console.log(pc.cyan(" Example: pnpm forgewp make:component PortfolioGrid --postType=portfolio"));
24
- console.log(pc.cyan(" Or: pnpm forgewp make:component --name PortfolioGrid --postType=portfolio\n"));
25
- process.exit(1);
26
- }
27
-
28
- // PascalCase formatting
29
- const cleanName = rawComponentName.replace(/[^a-zA-Z0-9_-]/g, "");
30
- const pascalCase = cleanName
31
- .replace(/(?:^\w|[A-Z]|\b\w)/g, (word) => word.toUpperCase())
32
- .replace(/[^a-zA-Z0-9]/g, "");
33
-
34
- if (!pascalCase) {
35
- console.error(pc.red("\n❌ Error: Invalid component name.\n"));
36
- process.exit(1);
37
- }
38
-
39
- // Parse postType
40
- let postType = "post";
41
- const postTypeArg = args.find(a => a.startsWith("--postType=") || a.startsWith("--post-type="));
42
- if (postTypeArg) {
43
- postType = postTypeArg.split("=")[1];
44
- } else {
45
- const postTypeIndex = args.findIndex(a => a === "--postType" || a === "--post-type");
46
- if (postTypeIndex !== -1 && args[postTypeIndex + 1]) {
47
- postType = args[postTypeIndex + 1];
48
- }
49
- }
50
-
51
- const projectRoot = process.cwd();
52
- const componentsDir = path.join(projectRoot, "src", "components");
53
- const mockDataPath = path.join(projectRoot, "wordpress", "mock-data.json");
54
-
55
- if (!existsSync(path.join(projectRoot, "src"))) {
56
- console.error(pc.red(`\n❌ Error: "src" folder not found. Are you in your theme's root directory?\n`));
57
- process.exit(1);
58
- }
59
-
60
- // Ensure src/components directory exists
61
- if (!existsSync(componentsDir)) {
62
- mkdirSync(componentsDir, { recursive: true });
63
- }
64
-
65
- const targetFile = path.join(componentsDir, `${pascalCase}.tsx`);
66
-
67
- if (existsSync(targetFile)) {
68
- console.error(pc.red(`\n❌ Error: Component "${pascalCase}.tsx" already exists at src/components/\n`));
69
- process.exit(1);
70
- }
71
-
72
- // Try to load custom fields from mock-data.json for this post type
73
- let customFields = [];
74
- let automaticallySeeded = false;
75
-
76
- if (existsSync(mockDataPath)) {
77
- try {
78
- const mockData = JSON.parse(readFileSync(mockDataPath, "utf8"));
79
- if (!mockData[postType]) {
80
- // SMART ACTION: Automatically register and seed postType records in the JSON database
81
- mockData[postType] = [
82
- {
83
- id: 1,
84
- title: `Sample ${postType.charAt(0).toUpperCase() + postType.slice(1)} Item 1`,
85
- excerpt: `This is a custom ${postType} post seeded dynamically via ForgeWP CLI.`,
86
- content: `<p>Welcome to your new custom <strong>${postType}</strong> post template! Edit this in wordpress/mock-data.json.</p>`,
87
- date: new Date().toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" }),
88
- author: "ForgeWP CLI",
89
- featuredImage: `https://picsum.photos/seed/${postType}1/1200/630`,
90
- customFields: {
91
- client_name: "Mock Enterprise",
92
- project_budget: "$30,000",
93
- }
94
- },
95
- {
96
- id: 2,
97
- title: `Sample ${postType.charAt(0).toUpperCase() + postType.slice(1)} Item 2`,
98
- excerpt: `This is another custom ${postType} post seeded dynamically via ForgeWP CLI.`,
99
- content: `<p>This is the second custom post for the ${postType} post type.</p>`,
100
- date: new Date().toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" }),
101
- author: "ForgeWP CLI",
102
- featuredImage: `https://picsum.photos/seed/${postType}2/1200/630`,
103
- customFields: {
104
- client_name: "Mock Organization",
105
- project_budget: "$55,000",
106
- }
107
- }
108
- ];
109
- // Save updated JSON
110
- writeFileSync(mockDataPath, JSON.stringify(mockData, null, 2), "utf8");
111
- automaticallySeeded = true;
112
- }
113
-
114
- const records = mockData[postType] || [];
115
- if (records.length > 0 && records[0].customFields) {
116
- customFields = Object.keys(records[0].customFields);
117
- }
118
- } catch (err) {
119
- // Ignore and fallback
120
- }
121
- }
122
-
123
- // Generate dynamic JSX elements for custom fields
124
- let customFieldsMarkup = "";
125
- if (customFields.length > 0) {
126
- customFieldsMarkup = customFields.map(f => {
127
- const cleanLabel = f.replace(/_/g, " ").replace(/(?:^\w|[A-Z]|\b\w)/g, (word) => word.toUpperCase());
128
- return `<div className="flex justify-between border-t border-zinc-950 pt-2 text-xs font-mono text-zinc-700">
129
- <span>${cleanLabel}:</span>
130
- <span className="font-bold">{useWpCustomField("${f}")}</span>
131
- </div>`;
132
- }).join("\n ");
133
- } else {
134
- customFieldsMarkup = `{/* No custom fields registered in mock-data.json. Add fields by running forgewp make:post-type */}
135
- <p className="text-xs text-zinc-500 font-mono italic">No custom fields configured for post type: ${postType}</p>`;
136
- }
137
-
138
- // Generate beautiful Brutalist post loop grid template
139
- const componentTemplate = `import { WpQueryLoop, useWpTitle, useWpFeaturedImage, useWpExcerpt, useWpPermalink, useWpCustomField } from "@/lib/wordpress";
140
-
141
- export default function ${pascalCase}() {
142
- return (
143
- <section className="py-12 bg-zinc-50">
144
- <div className="max-w-6xl mx-auto px-4">
145
- <div className="mb-8 border-b-4 border-zinc-950 pb-4">
146
- <h2 className="text-4xl font-black uppercase tracking-tight text-zinc-950">
147
- Latest ${postType.charAt(0).toUpperCase() + postType.slice(1)} Items
148
- </h2>
149
- <p className="text-sm font-mono font-medium text-zinc-600 mt-1">
150
- Dynamic Post Type Loop Component — Querying "${postType}"
151
- </p>
152
- </div>
153
-
154
- <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
155
- <WpQueryLoop postType="${postType}" postsPerPage={3}>
156
- <article className="bg-white border-4 border-zinc-950 p-6 shadow-[6px_6px_0px_0px_rgba(0,0,0,1)] rounded-none flex flex-col justify-between hover:translate-x-[-2px] hover:translate-y-[-2px] hover:shadow-[8px_8px_0px_0px_rgba(0,0,0,1)] transition-all">
157
- <div>
158
- <div className="relative aspect-video w-full border-2 border-zinc-950 overflow-hidden mb-4 bg-zinc-100">
159
- <img
160
- src={useWpFeaturedImage()}
161
- alt={useWpTitle()}
162
- className="object-cover w-full h-full"
163
- />
164
- </div>
165
- <h3 className="text-2xl font-black text-zinc-950 uppercase tracking-tight leading-none mb-3 hover:text-brand transition-colors">
166
- <a href={useWpPermalink()}>{useWpTitle()}</a>
167
- </h3>
168
- <p className="text-sm text-zinc-600 font-sans leading-relaxed mb-6">
169
- {useWpExcerpt()}
170
- </p>
171
- </div>
172
-
173
- <div className="space-y-2 mt-auto">
174
- ${customFieldsMarkup}
175
- </div>
176
- </article>
177
- </WpQueryLoop>
178
- </div>
179
- </div>
180
- </section>
181
- );
182
- }
183
- `;
184
-
185
- // Write template to file
186
- writeFileSync(targetFile, componentTemplate, "utf8");
187
-
188
- if (automaticallySeeded) {
189
- console.log(pc.yellow(`\n⚠️ Post type "${postType}" was missing from local database (mock-data.json).`));
190
- console.log(` We have automatically registered it and seeded default custom fields for you!`);
191
- }
192
-
193
- console.log(pc.green(`\n⚡ Loop Component "${pascalCase}" successfully created!`));
194
- console.log(` Location: ${pc.cyan(`src/components/${pascalCase}.tsx`)}`);
195
- console.log(` Target Post Type: ${pc.yellow(postType)}`);
196
- if (customFields.length > 0) {
197
- console.log(` Seeded Custom Fields: ${pc.yellow(customFields.join(", "))}`);
198
- }
199
- console.log(`\n🎉 You can now import it directly inside your pages:`);
200
- console.log(` ${pc.cyan(`import ${pascalCase} from "@/components/${pascalCase}";`)}\n`);