@forgewp/compiler 0.1.7 → 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.
@@ -0,0 +1,200 @@
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`);
@@ -0,0 +1,129 @@
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 rawName = args.find(a => !a.startsWith("-"));
9
+
10
+ // Support --name portfolio or --name=portfolio
11
+ const nameIndex = args.indexOf("--name");
12
+ if (nameIndex !== -1 && args[nameIndex + 1]) {
13
+ rawName = args[nameIndex + 1];
14
+ } else {
15
+ const nameEqual = args.find(a => a.startsWith("--name="));
16
+ if (nameEqual) {
17
+ rawName = nameEqual.split("=")[1];
18
+ }
19
+ }
20
+
21
+ if (!rawName) {
22
+ console.error(pc.red("\n❌ Error: Please specify a post type name."));
23
+ console.log(pc.cyan(" Example: pnpm forgewp make:post-type portfolio"));
24
+ console.log(pc.cyan(" Or: pnpm forgewp make:post-type --name portfolio\n"));
25
+ process.exit(1);
26
+ }
27
+
28
+ // WordPress slugs should be lowercase alphanumeric with dashes or underscores
29
+ const cleanName = rawName.toLowerCase().replace(/[^a-z0-9_-]/g, "");
30
+ if (!cleanName) {
31
+ console.error(pc.red("\n❌ Error: Invalid post type name. Use letters, numbers, dashes, and underscores.\n"));
32
+ process.exit(1);
33
+ }
34
+
35
+ const projectRoot = process.cwd();
36
+ const wpDir = path.join(projectRoot, "wordpress");
37
+ const mockDataPath = path.join(wpDir, "mock-data.json");
38
+
39
+ // Ensure wordpress directory exists
40
+ if (!existsSync(wpDir)) {
41
+ mkdirSync(wpDir, { recursive: true });
42
+ }
43
+
44
+ let mockData = {};
45
+
46
+ if (existsSync(mockDataPath)) {
47
+ try {
48
+ mockData = JSON.parse(readFileSync(mockDataPath, "utf8"));
49
+ } catch (err) {
50
+ console.error(pc.red(`\n❌ Error: Failed to parse wordpress/mock-data.json. Enforcing clean file.`));
51
+ mockData = {};
52
+ }
53
+ }
54
+
55
+ if (mockData[cleanName]) {
56
+ console.warn(pc.yellow(`\n⚠️ Post type "${cleanName}" already exists in wordpress/mock-data.json.`));
57
+ console.log(` You can open the file directly to view or edit existing fields.\n`);
58
+ process.exit(0);
59
+ }
60
+
61
+ // Parse custom fields if provided via --customFields, -customFields, --custom-fields, etc.
62
+ let customFieldsList = [];
63
+ const fieldsArg = args.find(a => /^-+custom[Ff]ields=/.test(a) || /^-+custom-fields=/.test(a));
64
+ if (fieldsArg) {
65
+ const rawFields = fieldsArg.split("=")[1];
66
+ if (rawFields) {
67
+ customFieldsList = rawFields.split(",").map(f => f.trim()).filter(Boolean);
68
+ }
69
+ } else {
70
+ const fieldsIndex = args.findIndex(a => /^-+custom[Ff]ields$/.test(a) || /^-+custom-fields$/.test(a));
71
+ if (fieldsIndex !== -1 && args[fieldsIndex + 1]) {
72
+ customFieldsList = args[fieldsIndex + 1].split(",").map(f => f.trim()).filter(Boolean);
73
+ }
74
+ }
75
+
76
+ // Generate seeded customFields object
77
+ const seededCustomFields1 = {};
78
+ const seededCustomFields2 = {};
79
+
80
+ if (customFieldsList.length > 0) {
81
+ for (const field of customFieldsList) {
82
+ seededCustomFields1[field] = `[Seeded ${field} 1]`;
83
+ seededCustomFields2[field] = `[Seeded ${field} 2]`;
84
+ }
85
+ } else {
86
+ // Default fallbacks if no flag is provided
87
+ seededCustomFields1["client_name"] = "Mock Enterprise";
88
+ seededCustomFields1["project_budget"] = "$30,000";
89
+
90
+ seededCustomFields2["client_name"] = "Mock Organization";
91
+ seededCustomFields2["project_budget"] = "$55,000";
92
+ }
93
+
94
+ // Generate template seed items for this custom post type
95
+ mockData[cleanName] = [
96
+ {
97
+ id: 1,
98
+ title: `Sample ${cleanName.charAt(0).toUpperCase() + cleanName.slice(1)} Item 1`,
99
+ excerpt: `This is a custom ${cleanName} post seeded dynamically via ForgeWP CLI.`,
100
+ content: `<p>Welcome to your new custom <strong>${cleanName}</strong> post template! Edit this in wordpress/mock-data.json.</p>`,
101
+ date: new Date().toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" }),
102
+ author: "ForgeWP CLI",
103
+ featuredImage: `https://picsum.photos/seed/${cleanName}1/1200/630`,
104
+ customFields: seededCustomFields1
105
+ },
106
+ {
107
+ id: 2,
108
+ title: `Sample ${cleanName.charAt(0).toUpperCase() + cleanName.slice(1)} Item 2`,
109
+ excerpt: `This is another custom ${cleanName} post seeded dynamically via ForgeWP CLI.`,
110
+ content: `<p>This is the second custom post for the ${cleanName} post type.</p>`,
111
+ date: new Date().toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" }),
112
+ author: "ForgeWP CLI",
113
+ featuredImage: `https://picsum.photos/seed/${cleanName}2/1200/630`,
114
+ customFields: seededCustomFields2
115
+ }
116
+ ];
117
+
118
+ // Write update JSON back to file
119
+ writeFileSync(mockDataPath, JSON.stringify(mockData, null, 2), "utf8");
120
+
121
+ const suggestedField = customFieldsList.length > 0 ? customFieldsList[0] : "client_name";
122
+
123
+ console.log(pc.green(`\n⚡ Post Type "${cleanName}" successfully registered!`));
124
+ console.log(` Local DB: ${pc.cyan(`wordpress/mock-data.json`)}`);
125
+ console.log(`\n🎉 Query your seeded fields in React inside:`);
126
+ console.log(` ${pc.yellow(`<WpQueryLoop postType="${cleanName}" postsPerPage={2}>`)}`);
127
+ console.log(` ${pc.yellow(`<h3>{useWpTitle()}</h3>`)}`);
128
+ console.log(` ${pc.yellow(`<p>${suggestedField.charAt(0).toUpperCase() + suggestedField.slice(1)}: {useWpCustomField("${suggestedField}")}</p>`)}`);
129
+ console.log(` ${pc.yellow(`</WpQueryLoop>`)}\n`);
package/bin/repair.js ADDED
@@ -0,0 +1,69 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { existsSync, writeFileSync, mkdirSync } from "node:fs";
4
+ import path from "node:path";
5
+ import pc from "picocolors";
6
+ import { SYSTEM_BLUEPRINTS } from "../lib/blueprints.js";
7
+
8
+ console.log(`\n🔧 ${pc.bold(pc.bgYellow(pc.black(" FORGEWP SYSTEM REPAIR TOOL ")))}\n`);
9
+
10
+ const projectRoot = process.cwd();
11
+ let repairedCount = 0;
12
+
13
+ try {
14
+ // Re-heal every system blueprint
15
+ for (const [relativePath, blueprintContent] of Object.entries(SYSTEM_BLUEPRINTS)) {
16
+ const fullPath = path.join(projectRoot, relativePath);
17
+
18
+ // Ensure the folder exists
19
+ const dirPath = path.dirname(fullPath);
20
+ if (!existsSync(dirPath)) {
21
+ mkdirSync(dirPath, { recursive: true });
22
+ }
23
+
24
+ // Force overwrite to restore pure internals
25
+ writeFileSync(fullPath, blueprintContent, "utf8");
26
+ console.log(` ${pc.green("✅ Restored/Healed")}: ${pc.cyan(relativePath)}`);
27
+ repairedCount++;
28
+ }
29
+
30
+ // Ensure default mock data table is recreated if deleted
31
+ const mockDataPath = path.join(projectRoot, "wordpress", "mock-data.json");
32
+ if (!existsSync(mockDataPath)) {
33
+ const defaultJson = {
34
+ menu: {
35
+ primary: [
36
+ { title: "Home", url: "/" },
37
+ { title: "Blog", url: "/post" },
38
+ { title: "Archive", url: "/archive" }
39
+ ]
40
+ },
41
+ post: [
42
+ {
43
+ id: 1,
44
+ title: "Welcome to ForgeWP: The Headless Revolution",
45
+ excerpt: "Discover how ForgeWP bridges standard WordPress themes with React.",
46
+ content: "<p>Welcome to ForgeWP! Modify this in mock-data.json.</p>",
47
+ date: "May 10, 2026",
48
+ author: "Antigravity",
49
+ featuredImage: "https://picsum.photos/seed/forgewp/1200/630",
50
+ customFields: {}
51
+ }
52
+ ]
53
+ };
54
+ const dirPath = path.dirname(mockDataPath);
55
+ if (!existsSync(dirPath)) {
56
+ mkdirSync(dirPath, { recursive: true });
57
+ }
58
+ writeFileSync(mockDataPath, JSON.stringify(defaultJson, null, 2), "utf8");
59
+ console.log(` ${pc.green("✅ Seeded Default Database")}: wordpress/mock-data.json`);
60
+ repairedCount++;
61
+ }
62
+
63
+ console.log("\n" + "─".repeat(60));
64
+ console.log(pc.green(`\n🎉 ${pc.bold("REPAIR COMPLETE:")} Successfully repaired/synced ${repairedCount} core framework elements.`));
65
+ console.log(pc.cyan(" All protected boundaries have been restored back to defaults. Build safe!\n"));
66
+ } catch (err) {
67
+ console.error(pc.red(`\n❌ Error: Failed to perform system repair.\nReason: ${err.message}\n`));
68
+ process.exit(1);
69
+ }
@@ -0,0 +1,260 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
4
+ import path from "node:path";
5
+ import pc from "picocolors";
6
+
7
+ console.log(`\n⚡ ${pc.bold(pc.bgCyan(pc.black(" FORGEWP SITEMAP COMPILER (SYNC:ROUTES) ")))}\n`);
8
+
9
+ const projectRoot = process.cwd();
10
+ const args = process.argv.slice(2);
11
+ const isForce = args.includes("--force") || args.includes("--override");
12
+
13
+ // 1. Locate menus configuration file
14
+ let menusPath = path.join(projectRoot, "wordpress", "menus.json");
15
+ let menus = null;
16
+
17
+ if (!existsSync(menusPath)) {
18
+ // Try fallback in mock-data.json
19
+ const mockDataPath = path.join(projectRoot, "wordpress", "mock-data.json");
20
+ if (existsSync(mockDataPath)) {
21
+ try {
22
+ const mockData = JSON.parse(readFileSync(mockDataPath, "utf8"));
23
+ if (mockData.menu) {
24
+ menus = mockData.menu;
25
+ console.log(` ℹ️ Using legacy menus block inside: wordpress/mock-data.json`);
26
+ }
27
+ } catch (e) {
28
+ // Ignored
29
+ }
30
+ }
31
+ if (!menus) {
32
+ menus = {
33
+ _comment: "⚡ ForgeWP Navigation Menus — Edit this file to add/remove links in local dev. Run 'pnpm forgewp sync:routes' to auto-scaffold corresponding React pages!",
34
+ primary: [
35
+ { title: "Home", url: "/" },
36
+ { title: "New", url: "/new" },
37
+ { title: "Men", url: "/men" },
38
+ { title: "Women", url: "/women" }
39
+ ],
40
+ utility: [
41
+ { title: "Help", url: "/help" },
42
+ { title: "Sign In", url: "/login" }
43
+ ]
44
+ };
45
+
46
+ const dir = path.dirname(menusPath);
47
+ if (!existsSync(dir)) {
48
+ mkdirSync(dir, { recursive: true });
49
+ }
50
+ writeFileSync(menusPath, JSON.stringify(menus, null, 2), "utf8");
51
+ console.log(` 🎉 ${pc.green("Created dedicated sitemap source")}: wordpress/menus.json`);
52
+ }
53
+ } else {
54
+ try {
55
+ menus = JSON.parse(readFileSync(menusPath, "utf8"));
56
+ console.log(` 📖 ${pc.green("Loaded sitemap source")}: wordpress/menus.json`);
57
+ } catch (err) {
58
+ console.error(pc.red(`\n❌ Error: Failed to parse wordpress/menus.json.\nReason: ${err.message}`));
59
+ process.exit(1);
60
+ }
61
+ }
62
+
63
+ // 2. Extract unique local paths and sanitize them
64
+ const routesToScaffold = [];
65
+ const seenUrls = new Set(["/", ""]);
66
+
67
+ for (const [location, items] of Object.entries(menus)) {
68
+ if (!Array.isArray(items)) continue;
69
+ for (const item of items) {
70
+ if (!item.url || typeof item.url !== "string") continue;
71
+ let url = item.url.trim();
72
+
73
+ // Skip external, anchors, mailto, etc.
74
+ if (
75
+ url.startsWith("http://") ||
76
+ url.startsWith("https://") ||
77
+ url.startsWith("#") ||
78
+ url.startsWith("mailto:") ||
79
+ url.startsWith("tel:")
80
+ ) {
81
+ continue;
82
+ }
83
+
84
+ // Normalize starting slash
85
+ if (!url.startsWith("/")) {
86
+ url = "/" + url;
87
+ }
88
+
89
+ if (seenUrls.has(url)) continue;
90
+ seenUrls.add(url);
91
+
92
+ routesToScaffold.push({
93
+ path: url,
94
+ title: item.title || url.replace("/", "")
95
+ });
96
+ }
97
+ }
98
+
99
+ if (routesToScaffold.length === 0) {
100
+ console.log(pc.yellow(`\nℹ️ No local pages to synchronize inside your sitemap menu config.`));
101
+ process.exit(0);
102
+ }
103
+
104
+ // Helper to convert path / slug to PascalCase ComponentName
105
+ function toPascalCase(str) {
106
+ return str
107
+ .replace(/[^a-zA-Z0-9]/g, " ")
108
+ .trim()
109
+ .split(/\s+/)
110
+ .map(w => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
111
+ .join("") + "Page";
112
+ }
113
+
114
+ // 3. Ensure Pages output directory exists
115
+ const pagesDir = path.join(projectRoot, "src", "app", "pages");
116
+ if (!existsSync(pagesDir)) {
117
+ mkdirSync(pagesDir, { recursive: true });
118
+ }
119
+
120
+ // 4. Scaffold components non-destructively
121
+ let scaffoldedCount = 0;
122
+ let skippedCount = 0;
123
+
124
+ for (const route of routesToScaffold) {
125
+ const componentName = toPascalCase(route.title);
126
+ const componentPath = path.join(pagesDir, `${componentName}.tsx`);
127
+
128
+ const componentContent = `/**
129
+ * ⚡ Auto-Generated Page Component by ForgeWP
130
+ *
131
+ * This file was generated automatically from your sitemap configuration (wordpress/menus.json).
132
+ * You can safely edit this file to customize the visual layout, styles, and logic.
133
+ * Subsequent runs of 'pnpm forgewp sync:routes' will NOT overwrite your changes.
134
+ *
135
+ * To force reset this page back to boilerplate defaults, run:
136
+ * 'pnpm forgewp sync:routes --force'
137
+ */
138
+ import { SEO } from "../../.forgewp/SEO";
139
+ import { WpQueryLoop, useWpTitle, useWpExcerpt, useWpFeaturedImage } from "../../.forgewp/wordpress";
140
+
141
+ export function ${componentName}() {
142
+ return (
143
+ <main className="container mx-auto px-6 py-12">
144
+ {/* Dynamic SEO Injector */}
145
+ <SEO
146
+ title="${route.title}"
147
+ description="Explore our exclusive ${route.title} section, dynamically loaded in Headless React."
148
+ />
149
+
150
+ {/* Hero Header Area */}
151
+ <header className="border-b-4 border-black pb-6 mb-12">
152
+ <h1 className="text-5xl font-black tracking-tight uppercase">${route.title}</h1>
153
+ <p className="text-zinc-500 mt-2 text-lg">
154
+ Auto-generated template. Edit <code className="bg-zinc-100 px-1 py-0.5 rounded text-sm text-red-600 font-mono">src/app/pages/${componentName}.tsx</code> to customize this page.
155
+ </p>
156
+ </header>
157
+
158
+ {/* Grid Starter - WordPress Mock Loop */}
159
+ <section className="grid grid-cols-1 md:grid-cols-3 gap-8">
160
+ <WpQueryLoop postType="post" postsPerPage={3}>
161
+ <article className="border-2 border-black p-6 bg-white shadow-[4px_4px_0px_0px_rgba(0,0,0,1)] hover:translate-y-[-2px] hover:shadow-[6px_6px_0px_0px_rgba(0,0,0,1)] transition-all">
162
+ <div className="w-full h-48 bg-zinc-100 mb-4 border border-zinc-200 overflow-hidden">
163
+ <img
164
+ src={useWpFeaturedImage()}
165
+ alt={useWpTitle()}
166
+ className="w-full h-full object-cover"
167
+ />
168
+ </div>
169
+ <h2 className="text-xl font-bold uppercase tracking-tight mb-2">
170
+ {useWpTitle()}
171
+ </h2>
172
+ <p className="text-zinc-600 text-sm mb-4">
173
+ {useWpExcerpt()}
174
+ </p>
175
+ <a
176
+ href="#"
177
+ className="inline-block px-4 py-2 border-2 border-black bg-zinc-100 font-bold uppercase text-xs hover:bg-black hover:text-white transition-colors"
178
+ >
179
+ Read More
180
+ </a>
181
+ </article>
182
+ </WpQueryLoop>
183
+ </section>
184
+ </main>
185
+ );
186
+ }
187
+ `;
188
+
189
+ if (existsSync(componentPath) && !isForce) {
190
+ console.log(` ${pc.gray("ℹ️ [Skip] Component already exists:")} src/app/pages/${componentName}.tsx`);
191
+ skippedCount++;
192
+ } else {
193
+ writeFileSync(componentPath, componentContent, "utf8");
194
+ console.log(` ${pc.green("✅ Scaffolded component")}: src/app/pages/${componentName}.tsx`);
195
+ scaffoldedCount++;
196
+ }
197
+ }
198
+
199
+ // 5. Inject pages into src/app/routes.tsx
200
+ const routesFilePath = path.join(projectRoot, "src/app/routes.tsx");
201
+ if (existsSync(routesFilePath)) {
202
+ let routesContent = readFileSync(routesFilePath, "utf8");
203
+ let modified = false;
204
+
205
+ for (const route of routesToScaffold) {
206
+ const componentName = toPascalCase(route.title);
207
+
208
+ // Check if the component is imported
209
+ const importRegex = new RegExp(`import\\s+\\{\\s*${componentName}\\s*\\}\\s+from\\s+["']\\./pages/${componentName}["']`);
210
+ if (!importRegex.test(routesContent)) {
211
+ // Find a clean place to inject imports
212
+ // Right above "export default function" or under other imports
213
+ const defaultExportIndex = routesContent.indexOf("export default function");
214
+ if (defaultExportIndex !== -1) {
215
+ routesContent =
216
+ routesContent.slice(0, defaultExportIndex) +
217
+ `import { ${componentName} } from "./pages/${componentName}";\n` +
218
+ routesContent.slice(defaultExportIndex);
219
+ modified = true;
220
+ }
221
+ }
222
+
223
+ // Check if the Route path is registered
224
+ const routeRegex = new RegExp(`path\\s*=\\s*["']${route.path}["']`);
225
+ if (!routeRegex.test(routesContent)) {
226
+ // Find the fallback route or closing Switch tag to inject
227
+ const fallbackMarker = "{/* Fallback route */}";
228
+ const fallbackIndex = routesContent.indexOf(fallbackMarker);
229
+ if (fallbackIndex !== -1) {
230
+ routesContent =
231
+ routesContent.slice(0, fallbackIndex) +
232
+ `<Route path="${route.path}" component={${componentName}} />\n\n ` +
233
+ routesContent.slice(fallbackIndex);
234
+ modified = true;
235
+ } else {
236
+ // Fallback to closing Switch tag
237
+ const switchCloseIndex = routesContent.indexOf("</Switch>");
238
+ if (switchCloseIndex !== -1) {
239
+ routesContent =
240
+ routesContent.slice(0, switchCloseIndex) +
241
+ ` <Route path="${route.path}" component={${componentName}} />\n ` +
242
+ routesContent.slice(switchCloseIndex);
243
+ modified = true;
244
+ }
245
+ }
246
+ }
247
+ }
248
+
249
+ if (modified) {
250
+ writeFileSync(routesFilePath, routesContent, "utf8");
251
+ console.log(` ${pc.green("✅ Synced routing paths in")}: src/app/routes.tsx`);
252
+ } else {
253
+ console.log(` ${pc.gray("ℹ️ Routes are already fully up to date in")}: src/app/routes.tsx`);
254
+ }
255
+ } else {
256
+ console.log(pc.yellow(` ⚠️ Warning: routes.tsx not found. Skipped route linking.`));
257
+ }
258
+
259
+ console.log("\n" + "─".repeat(60));
260
+ console.log(pc.green(`\n🎉 ${pc.bold("SITEMAP SYNC COMPLETE:")} Generated ${scaffoldedCount} new pages (skipped ${skippedCount}).\n`));