@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
package/bin/make-block.js CHANGED
@@ -1,8 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { existsSync, mkdirSync, writeFileSync } from "node:fs";
3
+ import { existsSync } from "node:fs";
4
4
  import path from "node:path";
5
5
  import pc from "picocolors";
6
+ import { loadConfig } from "../lib/load-config.js";
7
+ import { loadFrameworkAdapter } from "../lib/framework-adapter.js";
6
8
 
7
9
  const args = process.argv.slice(2);
8
10
  let rawBlockName = args.find(a => !a.startsWith("-"));
@@ -44,25 +46,12 @@ const readableTitle = pascalCase
44
46
 
45
47
  // Ensure we are inside a ForgeWP theme workspace
46
48
  const projectRoot = process.cwd();
47
- const blocksDir = path.join(projectRoot, "src", "blocks");
48
49
 
49
50
  if (!existsSync(path.join(projectRoot, "src"))) {
50
51
  console.error(pc.red(`\n❌ Error: "src" folder not found. Are you in your theme's root directory?\n`));
51
52
  process.exit(1);
52
53
  }
53
54
 
54
- // Ensure src/blocks directory exists
55
- if (!existsSync(blocksDir)) {
56
- mkdirSync(blocksDir, { recursive: true });
57
- }
58
-
59
- const targetFile = path.join(blocksDir, `${pascalCase}.tsx`);
60
-
61
- if (existsSync(targetFile)) {
62
- console.error(pc.red(`\n❌ Error: Block "${pascalCase}.tsx" already exists at src/blocks/\n`));
63
- process.exit(1);
64
- }
65
-
66
55
  // 2. Parse custom attributes if provided via --attributes or --attrs
67
56
  let attributesList = ["title", "description"];
68
57
  const attrsArg = args.find(a => /^-+attributes=/.test(a) || /^-+attrs=/.test(a));
@@ -78,53 +67,31 @@ if (attrsArg) {
78
67
  }
79
68
  }
80
69
 
81
- const propSignature = attributesList.map(a => `${a}: string`).join("; ");
82
- const propDestructuring = attributesList.join(", ");
83
-
84
- const layoutMarkup = attributesList.map((attr, index) => {
85
- if (index === 0) {
86
- return `<h3 className="text-2xl font-black text-zinc-950 uppercase tracking-tight leading-none mb-3">
87
- {${attr}}
88
- </h3>`;
89
- }
90
- if (attr.toLowerCase().includes("image") || attr.toLowerCase().includes("pic") || attr.toLowerCase().includes("img")) {
91
- return `<img src={${attr}} alt="Block Media" className="w-full border-2 border-zinc-950 mb-3" />`;
92
- }
93
- return `<p className="text-sm text-zinc-600 font-medium font-sans leading-relaxed mb-3">
94
- {${attr}}
95
- </p>`;
96
- }).join("\n ");
97
-
98
- const attributesRegistry = attributesList.map(a => {
99
- return ` ${a}: { type: "string", default: "Customize ${a} here" }`;
100
- }).join(",\n");
101
-
102
- // 3. Generate the beautiful Neo-Brutalist React block template
103
- const blockTemplate = `export default function ${pascalCase}({ ${propDestructuring} }: { ${propSignature} }) {
104
- return (
105
- <div className="p-8 bg-white border-4 border-zinc-950 shadow-[6px_6px_0px_0px_rgba(0,0,0,1)] rounded-none my-6 selection:bg-brand selection:text-white">
106
- <span className="inline-block bg-brand text-white text-xs font-mono font-bold uppercase tracking-wider px-2 py-0.5 mb-3 border-2 border-zinc-950">
107
- Gutenberg Custom Block
108
- </span>
109
- ${layoutMarkup}
110
- </div>
111
- );
70
+ // Load configuration and invoke adapter
71
+ let frameworkAdapter = "react";
72
+ try {
73
+ const config = await loadConfig(projectRoot);
74
+ frameworkAdapter = config.frameworkAdapter || "react";
75
+ } catch (err) {
76
+ // Use default
112
77
  }
113
78
 
114
- export const settings = {
115
- title: "Sharp ${readableTitle}",
116
- icon: "admin-post", // Choose icons from: https://developer.wordpress.org/resource/dashicons/
117
- category: "design",
118
- attributes: {
119
- ${attributesRegistry}
79
+ try {
80
+ const adapterModule = await loadFrameworkAdapter(frameworkAdapter);
81
+ const adapter = adapterModule.default || adapterModule;
82
+ if (typeof adapter.onMakeBlock === "function") {
83
+ await adapter.onMakeBlock(projectRoot, {
84
+ pascalCase,
85
+ readableTitle,
86
+ attributesList,
87
+ pc
88
+ });
89
+ } else {
90
+ console.error(pc.red(`\n❌ Error: Framework adapter "${frameworkAdapter}" does not support making Gutenberg blocks.`));
91
+ process.exit(1);
120
92
  }
121
- };
122
- `;
123
-
124
- // 4. Write template out to disk
125
- writeFileSync(targetFile, blockTemplate, "utf8");
93
+ } catch (err) {
94
+ console.error(pc.red(`\n❌ Failed to execute make:block: ${err.message}`));
95
+ process.exit(1);
96
+ }
126
97
 
127
- console.log(pc.green(`\n⚡ Block "${pascalCase}" successfully created!`));
128
- console.log(` Location: ${pc.cyan(`src/blocks/${pascalCase}.tsx`)}`);
129
- console.log(` Gutenberg Title: ${pc.yellow(`Sharp ${readableTitle}`)}`);
130
- console.log(`\n🎉 Run ${pc.cyan("pnpm export")} to automatically register it inside your WordPress theme!\n`);
@@ -0,0 +1,72 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { existsSync } from "node:fs";
4
+ import path from "node:path";
5
+ import pc from "picocolors";
6
+ import { loadConfig } from "../lib/load-config.js";
7
+ import { loadFrameworkAdapter } from "../lib/framework-adapter.js";
8
+
9
+ const args = process.argv.slice(2);
10
+ let rawIslandName = args.find(a => !a.startsWith("-"));
11
+
12
+ // Support --name CounterIsland or --name=CounterIsland
13
+ const nameIndex = args.indexOf("--name");
14
+ if (nameIndex !== -1 && args[nameIndex + 1]) {
15
+ rawIslandName = args[nameIndex + 1];
16
+ } else {
17
+ const nameEqual = args.find(a => a.startsWith("--name="));
18
+ if (nameEqual) {
19
+ rawIslandName = nameEqual.split("=")[1];
20
+ }
21
+ }
22
+
23
+ if (!rawIslandName) {
24
+ console.error(pc.red("\n❌ Error: Please specify an island name."));
25
+ console.log(pc.cyan(" Example: pnpm forgewp make:island CounterIsland"));
26
+ console.log(pc.cyan(" Or: pnpm forgewp make:island --name CounterIsland\n"));
27
+ process.exit(1);
28
+ }
29
+
30
+ // PascalCase formatting
31
+ const cleanName = rawIslandName.replace(/[^a-zA-Z0-9_-]/g, "");
32
+ const pascalCase = cleanName
33
+ .replace(/(?:^\w|[A-Z]|\b\w)/g, (word) => word.toUpperCase())
34
+ .replace(/[^a-zA-Z0-9]/g, "");
35
+
36
+ if (!pascalCase) {
37
+ console.error(pc.red("\n❌ Error: Invalid island name.\n"));
38
+ process.exit(1);
39
+ }
40
+
41
+ const projectRoot = process.cwd();
42
+
43
+ if (!existsSync(path.join(projectRoot, "src"))) {
44
+ console.error(pc.red(`\n❌ Error: "src" folder not found. Are you in your theme's root directory?\n`));
45
+ process.exit(1);
46
+ }
47
+
48
+ // Load configuration and invoke adapter
49
+ let frameworkAdapter = "react";
50
+ try {
51
+ const config = await loadConfig(projectRoot);
52
+ frameworkAdapter = config.frameworkAdapter || "react";
53
+ } catch (err) {
54
+ // Use default
55
+ }
56
+
57
+ try {
58
+ const adapterModule = await loadFrameworkAdapter(frameworkAdapter);
59
+ const adapter = adapterModule.default || adapterModule;
60
+ if (typeof adapter.onMakeIsland === "function") {
61
+ await adapter.onMakeIsland(projectRoot, {
62
+ pascalCase,
63
+ pc
64
+ });
65
+ } else {
66
+ console.error(pc.red(`\n❌ Error: Framework adapter "${frameworkAdapter}" does not support making interactive hydration islands.`));
67
+ process.exit(1);
68
+ }
69
+ } catch (err) {
70
+ console.error(pc.red(`\n❌ Failed to execute make:island: ${err.message}`));
71
+ process.exit(1);
72
+ }
@@ -33,10 +33,10 @@ if (!cleanName) {
33
33
  }
34
34
 
35
35
  const projectRoot = process.cwd();
36
- const wpDir = path.join(projectRoot, "wordpress");
36
+ const wpDir = path.join(projectRoot, "cms");
37
37
  const mockDataPath = path.join(wpDir, "mock-data.json");
38
38
 
39
- // Ensure wordpress directory exists
39
+ // Ensure cms directory exists
40
40
  if (!existsSync(wpDir)) {
41
41
  mkdirSync(wpDir, { recursive: true });
42
42
  }
@@ -47,13 +47,13 @@ if (existsSync(mockDataPath)) {
47
47
  try {
48
48
  mockData = JSON.parse(readFileSync(mockDataPath, "utf8"));
49
49
  } catch (err) {
50
- console.error(pc.red(`\n❌ Error: Failed to parse wordpress/mock-data.json. Enforcing clean file.`));
50
+ console.error(pc.red(`\n❌ Error: Failed to parse cms/mock-data.json. Enforcing clean file.`));
51
51
  mockData = {};
52
52
  }
53
53
  }
54
54
 
55
55
  if (mockData[cleanName]) {
56
- console.warn(pc.yellow(`\n⚠️ Post type "${cleanName}" already exists in wordpress/mock-data.json.`));
56
+ console.warn(pc.yellow(`\n⚠️ Post type "${cleanName}" already exists in cms/mock-data.json.`));
57
57
  console.log(` You can open the file directly to view or edit existing fields.\n`);
58
58
  process.exit(0);
59
59
  }
@@ -97,7 +97,7 @@ mockData[cleanName] = [
97
97
  id: 1,
98
98
  title: `Sample ${cleanName.charAt(0).toUpperCase() + cleanName.slice(1)} Item 1`,
99
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>`,
100
+ content: `<p>Welcome to your new custom <strong>${cleanName}</strong> post template! Edit this in cms/mock-data.json.</p>`,
101
101
  date: new Date().toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" }),
102
102
  author: "ForgeWP CLI",
103
103
  featuredImage: `https://picsum.photos/seed/${cleanName}1/1200/630`,
@@ -121,7 +121,7 @@ writeFileSync(mockDataPath, JSON.stringify(mockData, null, 2), "utf8");
121
121
  const suggestedField = customFieldsList.length > 0 ? customFieldsList[0] : "client_name";
122
122
 
123
123
  console.log(pc.green(`\n⚡ Post Type "${cleanName}" successfully registered!`));
124
- console.log(` Local DB: ${pc.cyan(`wordpress/mock-data.json`)}`);
124
+ console.log(` Local DB: ${pc.cyan(`cms/mock-data.json`)}`);
125
125
  console.log(`\n🎉 Query your seeded fields in React inside:`);
126
126
  console.log(` ${pc.yellow(`<WpQueryLoop postType="${cleanName}" postsPerPage={2}>`)}`);
127
127
  console.log(` ${pc.yellow(`<h3>{useWpTitle()}</h3>`)}`);
@@ -0,0 +1,145 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
4
+ import path from "node:path";
5
+ import pc from "picocolors";
6
+ import { loadConfig } from "../lib/load-config.js";
7
+ import { loadFrameworkAdapter } from "../lib/framework-adapter.js";
8
+
9
+ const args = process.argv.slice(2);
10
+ let rawTemplateName = args.find(a => !a.startsWith("-"));
11
+
12
+ // Support --name PortfolioTemplate or --name=PortfolioTemplate
13
+ const nameIndex = args.indexOf("--name");
14
+ if (nameIndex !== -1 && args[nameIndex + 1]) {
15
+ rawTemplateName = args[nameIndex + 1];
16
+ } else {
17
+ const nameEqual = args.find(a => a.startsWith("--name="));
18
+ if (nameEqual) {
19
+ rawTemplateName = nameEqual.split("=")[1];
20
+ }
21
+ }
22
+
23
+ // Check for legacy alias warning
24
+ if (process.env.FORGEWP_LEGACY_ALIAS === "1") {
25
+ console.log(pc.yellow(`\n⚠️ Legacy Command Warning: "make:component" is deprecated.`));
26
+ console.log(` Please use the new modern naming: ${pc.cyan("pnpm forgewp make:template <Name>")}\n`);
27
+ }
28
+
29
+ if (!rawTemplateName) {
30
+ console.error(pc.red("\n❌ Error: Please specify a template name."));
31
+ console.log(pc.cyan(" Example: pnpm forgewp make:template PortfolioTemplate --postType=portfolio"));
32
+ console.log(pc.cyan(" Or: pnpm forgewp make:template --name PortfolioTemplate --postType=portfolio\n"));
33
+ process.exit(1);
34
+ }
35
+
36
+ // PascalCase formatting
37
+ const cleanName = rawTemplateName.replace(/[^a-zA-Z0-9_-]/g, "");
38
+ const pascalCase = cleanName
39
+ .replace(/(?:^\w|[A-Z]|\b\w)/g, (word) => word.toUpperCase())
40
+ .replace(/[^a-zA-Z0-9]/g, "");
41
+
42
+ if (!pascalCase) {
43
+ console.error(pc.red("\n❌ Error: Invalid template name.\n"));
44
+ process.exit(1);
45
+ }
46
+
47
+ // Parse postType
48
+ let postType = "post";
49
+ const postTypeArg = args.find(a => a.startsWith("--postType=") || a.startsWith("--post-type="));
50
+ if (postTypeArg) {
51
+ postType = postTypeArg.split("=")[1];
52
+ } else {
53
+ const postTypeIndex = args.findIndex(a => a === "--postType" || a === "--post-type");
54
+ if (postTypeIndex !== -1 && args[postTypeIndex + 1]) {
55
+ postType = args[postTypeIndex + 1];
56
+ }
57
+ }
58
+
59
+ const projectRoot = process.cwd();
60
+ const mockDataPath = path.join(projectRoot, "cms", "mock-data.json");
61
+
62
+ if (!existsSync(path.join(projectRoot, "src"))) {
63
+ console.error(pc.red(`\n❌ Error: "src" folder not found. Are you in your theme's root directory?\n`));
64
+ process.exit(1);
65
+ }
66
+
67
+ // Try to load custom fields from mock-data.json for this post type
68
+ let customFields = [];
69
+ let automaticallySeeded = false;
70
+
71
+ if (existsSync(mockDataPath)) {
72
+ try {
73
+ const mockData = JSON.parse(readFileSync(mockDataPath, "utf8"));
74
+ if (!mockData[postType]) {
75
+ // SMART ACTION: Automatically register and seed postType records in the JSON database
76
+ mockData[postType] = [
77
+ {
78
+ id: 1,
79
+ title: `Sample ${postType.charAt(0).toUpperCase() + postType.slice(1)} Item 1`,
80
+ excerpt: `This is a custom ${postType} post seeded dynamically via ForgeWP CLI.`,
81
+ content: `<p>Welcome to your new custom <strong>${postType}</strong> post template! Edit this in cms/mock-data.json.</p>`,
82
+ date: new Date().toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" }),
83
+ author: "ForgeWP CLI",
84
+ featuredImage: `https://picsum.photos/seed/${postType}1/1200/630`,
85
+ customFields: {
86
+ client_name: "Mock Enterprise",
87
+ project_budget: "$30,000",
88
+ }
89
+ },
90
+ {
91
+ id: 2,
92
+ title: `Sample ${postType.charAt(0).toUpperCase() + postType.slice(1)} Item 2`,
93
+ excerpt: `This is another custom ${postType} post seeded dynamically via ForgeWP CLI.`,
94
+ content: `<p>This is the second custom post for the ${postType} post type.</p>`,
95
+ date: new Date().toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" }),
96
+ author: "ForgeWP CLI",
97
+ featuredImage: `https://picsum.photos/seed/${postType}2/1200/630`,
98
+ customFields: {
99
+ client_name: "Mock Organization",
100
+ project_budget: "$55,000",
101
+ }
102
+ }
103
+ ];
104
+ // Save updated JSON
105
+ writeFileSync(mockDataPath, JSON.stringify(mockData, null, 2), "utf8");
106
+ automaticallySeeded = true;
107
+ }
108
+
109
+ const records = mockData[postType] || [];
110
+ if (records.length > 0 && records[0].customFields) {
111
+ customFields = Object.keys(records[0].customFields);
112
+ }
113
+ } catch (err) {
114
+ // Ignore and fallback
115
+ }
116
+ }
117
+
118
+ // Load configuration and invoke adapter
119
+ let frameworkAdapter = "react";
120
+ try {
121
+ const config = await loadConfig(projectRoot);
122
+ frameworkAdapter = config.frameworkAdapter || "react";
123
+ } catch (err) {
124
+ // Use default
125
+ }
126
+
127
+ try {
128
+ const adapterModule = await loadFrameworkAdapter(frameworkAdapter);
129
+ const adapter = adapterModule.default || adapterModule;
130
+ if (typeof adapter.onMakeTemplate === "function") {
131
+ await adapter.onMakeTemplate(projectRoot, {
132
+ pascalCase,
133
+ postType,
134
+ customFields,
135
+ automaticallySeeded,
136
+ pc
137
+ });
138
+ } else {
139
+ console.error(pc.red(`\n❌ Error: Framework adapter "${frameworkAdapter}" does not support making custom templates.`));
140
+ process.exit(1);
141
+ }
142
+ } catch (err) {
143
+ console.error(pc.red(`\n❌ Failed to execute make:template: ${err.message}`));
144
+ process.exit(1);
145
+ }
package/bin/repair.js CHANGED
@@ -28,7 +28,7 @@ try {
28
28
  }
29
29
 
30
30
  // Ensure default mock data table is recreated if deleted
31
- const mockDataPath = path.join(projectRoot, "wordpress", "mock-data.json");
31
+ const mockDataPath = path.join(projectRoot, "cms", "mock-data.json");
32
32
  if (!existsSync(mockDataPath)) {
33
33
  const defaultJson = {
34
34
  menu: {
@@ -56,7 +56,7 @@ try {
56
56
  mkdirSync(dirPath, { recursive: true });
57
57
  }
58
58
  writeFileSync(mockDataPath, JSON.stringify(defaultJson, null, 2), "utf8");
59
- console.log(` ${pc.green("✅ Seeded Default Database")}: wordpress/mock-data.json`);
59
+ console.log(` ${pc.green("✅ Seeded Default Database")}: cms/mock-data.json`);
60
60
  repairedCount++;
61
61
  }
62
62
 
@@ -0,0 +1,221 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * forgewp sync-hooks
4
+ *
5
+ * Propagates the canonical src/.forgewp/wordpress.tsx template to every
6
+ * ForgeWP project in the workspace that contains a src/.forgewp/ directory.
7
+ *
8
+ * Usage:
9
+ * pnpm forgewp sync-hooks # sync all projects
10
+ * pnpm forgewp sync-hooks --dry-run # preview without writing
11
+ * pnpm forgewp sync-hooks --verbose # show skipped projects too
12
+ */
13
+
14
+ import {
15
+ existsSync,
16
+ readFileSync,
17
+ writeFileSync,
18
+ readdirSync,
19
+ statSync,
20
+ } from "node:fs";
21
+ import { createHash } from "node:crypto";
22
+ import path from "node:path";
23
+ import { fileURLToPath } from "node:url";
24
+ import pc from "picocolors";
25
+
26
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
27
+
28
+ // ── CLI flags ──────────────────────────────────────────────────────────────────
29
+ const argv = process.argv.slice(2);
30
+ const isDryRun = argv.includes("--dry-run") || argv.includes("-n");
31
+ const isVerbose = argv.includes("--verbose") || argv.includes("-v");
32
+
33
+ // ── Banner ─────────────────────────────────────────────────────────────────────
34
+ console.log(
35
+ `\n🔄 ${pc.bold(pc.bgCyan(pc.black(" FORGEWP SYNC-HOOKS ")))} ${
36
+ isDryRun ? pc.yellow("[DRY RUN — no files will be written]") : ""
37
+ }\n`
38
+ );
39
+
40
+ // ── Locate the canonical template (source of truth) ───────────────────────────
41
+ const canonicalTemplatePath = path.resolve(
42
+ __dirname,
43
+ "..",
44
+ "templates",
45
+ "wordpress.tsx"
46
+ );
47
+
48
+ if (!existsSync(canonicalTemplatePath)) {
49
+ console.error(
50
+ pc.red(
51
+ `\n❌ Cannot find canonical template at:\n ${canonicalTemplatePath}\n`
52
+ )
53
+ );
54
+ process.exit(1);
55
+ }
56
+
57
+ const canonicalContent = readFileSync(canonicalTemplatePath, "utf8");
58
+ const canonicalHash = md5(canonicalContent);
59
+
60
+ console.log(
61
+ ` ${pc.bold("Source:")} ${pc.cyan("packages/compiler/templates/wordpress.tsx")}`
62
+ );
63
+ console.log(` ${pc.bold("Hash:")} ${pc.dim(canonicalHash.slice(0, 12))}...\n`);
64
+
65
+ // ── Find workspace root (directory containing pnpm-workspace.yaml) ─────────────
66
+ function findWorkspaceRoot(startDir) {
67
+ let dir = startDir;
68
+ for (let i = 0; i < 10; i++) {
69
+ if (existsSync(path.join(dir, "pnpm-workspace.yaml"))) return dir;
70
+ const parent = path.dirname(dir);
71
+ if (parent === dir) break;
72
+ dir = parent;
73
+ }
74
+ return null;
75
+ }
76
+
77
+ const projectRoot = process.cwd();
78
+ const workspaceRoot = findWorkspaceRoot(projectRoot) || projectRoot;
79
+
80
+ console.log(` ${pc.bold("Workspace:")} ${pc.dim(workspaceRoot)}\n`);
81
+
82
+ // ── Collect candidate project directories ─────────────────────────────────────
83
+ function collectProjectDirs(workspaceRoot) {
84
+ const dirs = new Set();
85
+
86
+ // 1. Parse pnpm-workspace.yaml for declared packages
87
+ const workspaceYaml = path.join(workspaceRoot, "pnpm-workspace.yaml");
88
+ if (existsSync(workspaceYaml)) {
89
+ const raw = readFileSync(workspaceYaml, "utf8");
90
+ // Simple line-by-line parse — handles " - "pattern-or-glob" entries
91
+ const lines = raw.split(/\r?\n/);
92
+ for (const line of lines) {
93
+ const match = line.match(/^\s+-\s+"?([^"#\s]+)"?\s*$/);
94
+ if (!match) continue;
95
+ const pattern = match[1].trim();
96
+ if (pattern.startsWith("!")) continue; // exclusion — handled below
97
+
98
+ if (pattern.endsWith("/*")) {
99
+ // Glob: enumerate immediate children
100
+ const base = path.join(workspaceRoot, pattern.slice(0, -2));
101
+ if (existsSync(base)) {
102
+ for (const entry of readdirSync(base)) {
103
+ const full = path.join(base, entry);
104
+ if (statSync(full).isDirectory()) dirs.add(full);
105
+ }
106
+ }
107
+ } else {
108
+ // Literal path
109
+ const full = path.join(workspaceRoot, pattern);
110
+ if (existsSync(full)) dirs.add(full);
111
+ }
112
+ }
113
+ }
114
+
115
+ // 2. Always include template scaffold directories (excluded from workspace installs
116
+ // but still need to be kept in sync as they seed new projects)
117
+ const extraTemplates = [
118
+ path.join(workspaceRoot, "packages", "create-forgewp", "template"),
119
+ path.join(workspaceRoot, "packages", "create-forgewp", "template-html"),
120
+ ];
121
+ for (const t of extraTemplates) {
122
+ if (existsSync(t)) dirs.add(t);
123
+ }
124
+
125
+ return [...dirs];
126
+ }
127
+
128
+ const candidateDirs = collectProjectDirs(workspaceRoot);
129
+
130
+ // ── Sync logic ─────────────────────────────────────────────────────────────────
131
+ const TARGET_RELATIVE = path.join("src", ".forgewp", "wordpress.tsx");
132
+
133
+ let updatedCount = 0;
134
+ let alreadyCurrentCount = 0;
135
+ let skippedCount = 0;
136
+
137
+ for (const dir of candidateDirs) {
138
+ const targetPath = path.join(dir, TARGET_RELATIVE);
139
+ const relativeDir = path.relative(workspaceRoot, dir);
140
+
141
+ // Skip if this dir doesn't have a src/.forgewp/ at all — it's not a ForgeWP theme
142
+ if (!existsSync(path.dirname(targetPath))) {
143
+ if (isVerbose) {
144
+ console.log(
145
+ ` ${pc.dim("⊘ Skipped")} ${pc.dim(relativeDir)} ${pc.dim("(no src/.forgewp/)")}`
146
+ );
147
+ }
148
+ skippedCount++;
149
+ continue;
150
+ }
151
+
152
+ // Skip the compiler's own templates directory to avoid self-overwrite
153
+ if (dir === path.resolve(__dirname, "..")) {
154
+ if (isVerbose) {
155
+ console.log(` ${pc.dim("⊘ Skipped")} ${pc.dim(relativeDir)} ${pc.dim("(source package)")}`);
156
+ }
157
+ skippedCount++;
158
+ continue;
159
+ }
160
+
161
+ if (existsSync(targetPath)) {
162
+ const existingContent = readFileSync(targetPath, "utf8");
163
+ const existingHash = md5(existingContent);
164
+
165
+ if (existingHash === canonicalHash) {
166
+ if (isVerbose) {
167
+ console.log(
168
+ ` ${pc.green("✓ Up-to-date")} ${pc.cyan(relativeDir)}`
169
+ );
170
+ }
171
+ alreadyCurrentCount++;
172
+ continue;
173
+ }
174
+ }
175
+
176
+ // Write update
177
+ if (!isDryRun) {
178
+ writeFileSync(targetPath, canonicalContent, "utf8");
179
+ }
180
+
181
+ console.log(
182
+ ` ${isDryRun ? pc.yellow("~ Would update") : pc.green("✅ Updated")} ${pc.cyan(relativeDir + "/" + TARGET_RELATIVE.replace(/\\/g, "/"))}`
183
+ );
184
+ updatedCount++;
185
+ }
186
+
187
+ // ── Summary ────────────────────────────────────────────────────────────────────
188
+ console.log("\n" + "─".repeat(60));
189
+
190
+ if (updatedCount === 0 && alreadyCurrentCount > 0) {
191
+ console.log(
192
+ pc.green(
193
+ `\n✨ ${pc.bold("All projects are already up-to-date.")} (${alreadyCurrentCount} checked)\n`
194
+ )
195
+ );
196
+ } else if (isDryRun) {
197
+ console.log(
198
+ pc.yellow(
199
+ `\n🔍 ${pc.bold("Dry run complete.")} ${updatedCount} file(s) would be updated, ${alreadyCurrentCount} already current.\n`
200
+ )
201
+ );
202
+ } else {
203
+ const total = updatedCount + alreadyCurrentCount + skippedCount;
204
+ console.log(
205
+ pc.green(
206
+ `\n🎉 ${pc.bold("Sync complete!")} Updated ${pc.bold(String(updatedCount))} project(s). ${alreadyCurrentCount} already current. ${skippedCount} non-theme packages skipped.\n`
207
+ )
208
+ );
209
+ if (updatedCount > 0) {
210
+ console.log(
211
+ pc.cyan(
212
+ ` All projects now share the same wordpress.tsx hooks — zero drift.\n`
213
+ )
214
+ );
215
+ }
216
+ }
217
+
218
+ // ── Helpers ───────────────────────────────────────────────────────────────────
219
+ function md5(content) {
220
+ return createHash("md5").update(content).digest("hex");
221
+ }