@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
@@ -0,0 +1,65 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ /**
5
+ * Static HTML adapter proof-of-concept.
6
+ * This adapter reads a prebuilt static HTML entrypoint and returns it as app markup.
7
+ */
8
+ export async function renderStaticMarkup(themeRoot) {
9
+ const builtHtml = path.join(themeRoot, 'dist', 'index.html');
10
+ if (!existsSync(builtHtml)) {
11
+ throw new Error(
12
+ `Static HTML adapter requires a built HTML entrypoint at ${builtHtml}. ` +
13
+ 'Run your static theme build first.',
14
+ );
15
+ }
16
+
17
+ const appHtml = readFileSync(builtHtml, 'utf8');
18
+
19
+ return {
20
+ appHtml,
21
+ headerHtml: '',
22
+ footerHtml: '',
23
+ headHtml: '',
24
+ singleHtml: '',
25
+ singleHeadHtml: '',
26
+ notFoundHtml: '',
27
+ archiveHtml: '',
28
+ };
29
+ }
30
+
31
+ export function scanForHydrationIslands(themeRoot) {
32
+ return [];
33
+ }
34
+
35
+ export function findComponentPath(themeRoot, kebabName) {
36
+ return null;
37
+ }
38
+
39
+ export function getHydrationRollupInputs(themeRoot) {
40
+ return {
41
+ index: path.resolve(themeRoot, 'index.html'),
42
+ };
43
+ }
44
+
45
+ export function getCriticalFiles(themeRoot) {
46
+ return ['src/main.tsx'];
47
+ }
48
+
49
+ export async function onFresh(themeRoot) {
50
+ // Static HTML adapter uses a single index.html and does not require routes.tsx or page.tsx setups.
51
+ }
52
+
53
+ export function onMakeBlock(themeRoot, { pascalCase, pc }) {
54
+ console.log(pc.yellow(`\n⚠️ The Static HTML framework adapter does not support custom Gutenberg blocks.`));
55
+ console.log(` Block "${pascalCase}" was not created.\n`);
56
+ }
57
+
58
+ export function onMakeComponent(themeRoot, { pascalCase, pc }) {
59
+ console.log(pc.yellow(`\n⚠️ The Static HTML framework adapter does not support custom loop components.`));
60
+ console.log(` Component "${pascalCase}" was not created.\n`);
61
+ }
62
+
63
+ export function onSyncRoutes(themeRoot, { pc }) {
64
+ console.log(pc.gray(`\nℹ️ The Static HTML framework adapter uses static HTML. Route synchronization skipped.\n`));
65
+ }
@@ -0,0 +1,49 @@
1
+ import path from 'node:path';
2
+
3
+ /**
4
+ * Example adapter stub for a non-React framework.
5
+ * Replace these methods with framework-specific rendering and hydration logic.
6
+ */
7
+
8
+ export async function renderStaticMarkup(themeRoot) {
9
+ throw new Error(
10
+ 'Stub adapter cannot render static markup. Implement renderStaticMarkup() for your framework.',
11
+ );
12
+ }
13
+
14
+ export function scanForHydrationIslands(themeRoot) {
15
+ // Return a list of kebab-case hydration island identifiers.
16
+ return [];
17
+ }
18
+
19
+ export function findComponentPath(themeRoot, kebabName) {
20
+ // Resolve a component source path for hydration input generation.
21
+ return null;
22
+ }
23
+
24
+ export function getHydrationRollupInputs(themeRoot) {
25
+ // Provide default Vite entrypoints for the theme build.
26
+ return {
27
+ index: path.resolve(themeRoot, 'index.html'),
28
+ };
29
+ }
30
+
31
+ export function getCriticalFiles(themeRoot) {
32
+ return [];
33
+ }
34
+
35
+ export async function onFresh(themeRoot) {
36
+ // Stub adapter onFresh no-op.
37
+ }
38
+
39
+ export function onMakeBlock(themeRoot, { pascalCase, pc }) {
40
+ console.log(pc.yellow(`\n⚠️ The Stub framework adapter does not support custom Gutenberg blocks.`));
41
+ }
42
+
43
+ export function onMakeComponent(themeRoot, { pascalCase, pc }) {
44
+ console.log(pc.yellow(`\n⚠️ The Stub framework adapter does not support custom loop components.`));
45
+ }
46
+
47
+ export function onSyncRoutes(themeRoot, { pc }) {
48
+ console.log(pc.gray(`\nℹ️ The Stub framework adapter route synchronization skipped.\n`));
49
+ }
@@ -1,231 +1,330 @@
1
1
  import { execSync } from "node:child_process";
2
2
  import { readFileSync, writeFileSync, readdirSync, existsSync, mkdirSync } from "node:fs";
3
+ import { createRequire } from "node:module";
4
+ import { fileURLToPath } from "node:url";
3
5
  import path from "node:path";
4
- import readline from "node:readline";
5
6
  import pc from "picocolors";
6
7
 
8
+ // ─────────────────────────────────────────────────────────────────────────────
9
+ // CONSTANTS
10
+ // ─────────────────────────────────────────────────────────────────────────────
11
+
12
+ /**
13
+ * The canonical shadcn components.json file expected at the project root.
14
+ * ForgeWP ensures this exists before delegating to the shadcn CLI.
15
+ * It points to the standard ForgeWP project layout.
16
+ */
17
+ const SHADCN_COMPONENTS_JSON = {
18
+ "$schema": "https://ui.shadcn.com/schema.json",
19
+ "style": "new-york",
20
+ "rsc": false,
21
+ "tsx": true,
22
+ "tailwind": {
23
+ "config": "tailwind.config.js",
24
+ "css": "src/app/globals.css",
25
+ "baseColor": "zinc",
26
+ "cssVariables": true,
27
+ "prefix": ""
28
+ },
29
+ "aliases": {
30
+ "components": "@/components",
31
+ "utils": "@/lib/utils",
32
+ "ui": "@/components/ui",
33
+ "lib": "@/lib",
34
+ "hooks": "@/hooks"
35
+ },
36
+ "iconLibrary": "lucide"
37
+ };
38
+
39
+ // ─────────────────────────────────────────────────────────────────────────────
40
+ // MAIN EXPORT
41
+ // ─────────────────────────────────────────────────────────────────────────────
42
+
43
+ /**
44
+ * Adds a UI component to the ForgeWP project.
45
+ *
46
+ * Flow:
47
+ * 1. Ensure shadcn's components.json is present (create if missing).
48
+ * 2. Run `shadcn add <component>` — shadcn handles all npm deps, Tailwind
49
+ * plugins, CSS vars, and globals.css registration automatically via its
50
+ * own remote registry.json for every component it knows about.
51
+ * 3. If ForgeWP has a local override (`@forgewp/ui/components/<name>/forgewp.tsx`),
52
+ * overwrite shadcn's freshly installed copy with the ForgeWP version.
53
+ * Read the component's registry.json for any additional plugin requirements
54
+ * not covered by shadcn (e.g. ForgeWP-native components that aren't in
55
+ * the shadcn remote registry).
56
+ * 4. If style === "forgewp", apply the neo-brutalist sharpening transform.
57
+ *
58
+ * @param {string} component - The component name (e.g. "sheet", "navbar").
59
+ * @param {{ style?: "shadcn" | "forgewp" }} options
60
+ */
7
61
  export async function addComponent(component, options) {
8
- const { style = "forgewp" } = options;
62
+ const { style = "shadcn" } = options;
9
63
  const projectRoot = process.cwd();
10
64
 
11
- console.log(pc.cyan(`\n ForgeWP add — ${component} (${style})\n`));
65
+ console.log(pc.cyan(`\n ForgeWP add — ${component}\n`));
66
+
67
+ // ── Step 1: Guarantee components.json exists ───────────────────────────────
68
+ ensureComponentsJson(projectRoot);
69
+
70
+ // ── Step 2: Detect package manager ────────────────────────────────────────
71
+ const { installCmd, shadcnCmd } = detectPackageManager(projectRoot);
72
+
73
+ // ── Step 3: Check for a ForgeWP local override ────────────────────────────
74
+ const localRegistry = resolveLocalRegistry(component);
75
+ const hasLocalOverride = localRegistry !== null && existsSync(localRegistry.tsxPath);
12
76
 
13
- // 1. Check local registry first
14
- let registryPath;
77
+ // ── Step 4: Run shadcn add (primary install source for everything) ─────────
78
+ console.log(pc.dim(` Installing ${component} via shadcn...`));
15
79
  try {
16
- const { createRequire } = await import("node:module");
17
- const require = createRequire(import.meta.url);
18
- registryPath = path.join(path.dirname(require.resolve("@forgewp/ui/package.json")), "components");
19
- } catch (e) {
20
- // Fallback for development/local execution
21
- registryPath = path.resolve(path.dirname(new URL(import.meta.url).pathname), "../../ui/components");
22
- }
23
-
24
- let localComponentFile = path.join(registryPath, component, `${style}.tsx`);
25
- if (!existsSync(localComponentFile)) {
26
- localComponentFile = path.join(registryPath, component, "forgewp.tsx");
80
+ execSync(`${shadcnCmd} add ${component} --yes`, {
81
+ stdio: "inherit",
82
+ cwd: projectRoot,
83
+ shell: process.platform === "win32",
84
+ });
85
+ } catch (err) {
86
+ // shadcn may fail for ForgeWP-native components not in the shadcn registry.
87
+ // If we have a local override, that's fine — we'll install it ourselves below.
88
+ if (!hasLocalOverride) {
89
+ throw new Error(
90
+ `Failed to install "${component}" via shadcn, and no ForgeWP local override exists.\n` +
91
+ `Details: ${err.message}`
92
+ );
93
+ }
94
+ console.log(pc.yellow(` ⚠ shadcn does not know "${component}" — using ForgeWP local registry instead.`));
27
95
  }
28
96
 
29
- if (existsSync(localComponentFile)) {
30
- console.log(pc.dim(` Found ${component} in ForgeWP local registry...`));
97
+ // ── Step 5: Install ForgeWP local override (if present) ───────────────────
98
+ if (hasLocalOverride) {
99
+ console.log(pc.dim(` Applying ForgeWP override for ${component}...`));
100
+
31
101
  const targetDir = path.join(projectRoot, "src", "components", "ui");
32
102
  if (!existsSync(targetDir)) mkdirSync(targetDir, { recursive: true });
33
-
103
+
34
104
  const targetFile = path.join(targetDir, `${component}.tsx`);
35
- const content = readFileSync(localComponentFile, "utf8");
105
+ const content = readFileSync(localRegistry.tsxPath, "utf8");
36
106
  writeFileSync(targetFile, content, "utf8");
37
-
38
- // Auto-detect and install missing third-party dependencies from imported component files
39
- await autoInstallMissingDependencies(targetFile, projectRoot);
40
107
 
41
- if (style === "forgewp") {
42
- sharpenFile(targetFile);
108
+ // Install any extra Tailwind plugins declared in the ForgeWP registry.json
109
+ // that shadcn's remote registry wouldn't know about (ForgeWP-native components).
110
+ if (localRegistry.meta?.tailwindPlugins?.length > 0) {
111
+ await ensureTailwindPlugins(localRegistry.meta.tailwindPlugins, installCmd, projectRoot);
43
112
  }
44
113
 
45
- console.log(pc.green(`\n Success! ${component} added to src/components/ui/\n`));
46
- return;
114
+ console.log(pc.dim(` ↳ Override written to src/components/ui/${component}.tsx`));
47
115
  }
48
116
 
49
- // 2. Run shadcn add (fallback)
50
- console.log(pc.dim(` Fetching ${component} from shadcn/ui...`));
51
- try {
52
- // Auto-detect the package manager being used by the developer
53
- const userAgent = process.env.npm_config_user_agent || "";
54
- let shadcnCmd = "npx shadcn@latest"; // Default fallback
55
-
56
- if (userAgent.includes("pnpm")) {
57
- shadcnCmd = "pnpm dlx shadcn@latest";
58
- } else if (userAgent.includes("bun")) {
59
- shadcnCmd = "bunx --bun shadcn@latest";
60
- } else if (userAgent.includes("yarn")) {
61
- shadcnCmd = "yarn dlx shadcn@latest";
117
+ // ── Step 6: Apply ForgeWP sharpening (when style === "forgewp") ────────────
118
+ if (style === "forgewp") {
119
+ const uiDir = path.join(projectRoot, "src", "components", "ui");
120
+ if (existsSync(uiDir)) {
121
+ const files = readdirSync(uiDir).filter(f =>
122
+ f.toLowerCase().includes(component.toLowerCase().replace(/-/g, "")) ||
123
+ f.toLowerCase().includes(component.toLowerCase())
124
+ );
125
+ const targets = files.length > 0 ? files : readdirSync(uiDir);
126
+ targets.forEach(f => {
127
+ if (f.endsWith(".tsx")) sharpenFile(path.join(uiDir, f));
128
+ });
62
129
  }
130
+ }
63
131
 
64
- // We use --yes to skip prompts
65
- execSync(`${shadcnCmd} add ${component} --yes`, {
66
- stdio: "inherit",
67
- cwd: projectRoot,
68
- shell: process.platform === "win32",
69
- });
132
+ console.log(pc.green(`\n ✅ ${component} ready in src/components/ui/\n`));
133
+ }
134
+
135
+ // ─────────────────────────────────────────────────────────────────────────────
136
+ // HELPERS
137
+ // ─────────────────────────────────────────────────────────────────────────────
138
+
139
+ /**
140
+ * Ensures shadcn's components.json exists at the project root.
141
+ * If missing, writes the standard ForgeWP default so `shadcn add` works
142
+ * without requiring the developer to run `shadcn init` manually.
143
+ */
144
+ function ensureComponentsJson(projectRoot) {
145
+ const targetPath = path.join(projectRoot, "components.json");
146
+ if (existsSync(targetPath)) return;
147
+
148
+ try {
149
+ writeFileSync(targetPath, JSON.stringify(SHADCN_COMPONENTS_JSON, null, 2), "utf8");
150
+ console.log(pc.green(` ✅ Created components.json (shadcn configuration)`));
70
151
  } catch (err) {
71
- throw new Error(`Failed to add component via shadcn: ${err.message}`);
152
+ console.log(pc.yellow(` ⚠ Could not create components.json: ${err.message}`));
153
+ console.log(pc.yellow(` Run "pnpm dlx shadcn@latest init" to initialize shadcn manually.`));
72
154
  }
155
+ }
73
156
 
74
- // 2. If style is forgewp, sharpen the components
75
- if (style === "forgewp") {
76
- console.log(pc.dim(" Applying ForgeWP Sharp aesthetics..."));
77
- const uiDir = path.join(projectRoot, "src", "components", "ui");
78
-
79
- if (!existsSync(uiDir)) return;
80
-
81
- const files = readdirSync(uiDir);
82
- // Find files related to the component
83
- const relevantFiles = files.filter(f =>
84
- f.toLowerCase().includes(component.toLowerCase().replace(/-/g, "")) ||
85
- f.toLowerCase().includes(component.toLowerCase())
86
- );
157
+ /**
158
+ * Detects the project's package manager from lockfiles and returns
159
+ * the appropriate install and shadcn CLI commands.
160
+ */
161
+ function detectPackageManager(projectRoot) {
162
+ let installCmd = "npm install --save-dev";
163
+ let shadcnCmd = "npx shadcn@latest";
87
164
 
88
- if (relevantFiles.length > 0) {
89
- relevantFiles.forEach(f => {
90
- if (f.endsWith(".tsx")) sharpenFile(path.join(uiDir, f));
91
- });
92
- } else {
93
- // Fallback: sharpen everything in the UI dir to be safe
94
- files.forEach(f => {
95
- if (f.endsWith(".tsx")) sharpenFile(path.join(uiDir, f));
96
- });
165
+ let current = projectRoot;
166
+ while (current) {
167
+ if (existsSync(path.join(current, "pnpm-lock.yaml"))) {
168
+ installCmd = "pnpm add -D";
169
+ shadcnCmd = "pnpm dlx shadcn@latest";
170
+ break;
97
171
  }
172
+ if (existsSync(path.join(current, "yarn.lock"))) {
173
+ installCmd = "yarn add -D";
174
+ shadcnCmd = "yarn dlx shadcn@latest";
175
+ break;
176
+ }
177
+ if (existsSync(path.join(current, "bun.lockb"))) {
178
+ installCmd = "bun add -d";
179
+ shadcnCmd = "bunx --bun shadcn@latest";
180
+ break;
181
+ }
182
+ const parent = path.dirname(current);
183
+ if (parent === current) break;
184
+ current = parent;
98
185
  }
99
186
 
100
- console.log(pc.green(`\n Success! ${component} added to src/components/ui/\n`));
187
+ return { installCmd, shadcnCmd };
101
188
  }
102
189
 
103
- function sharpenFile(filePath) {
104
- let content = readFileSync(filePath, "utf8");
105
-
106
- // Regex to find and replace rounding classes, including variants (e.g., focus:rounded-md)
107
- const sharpened = content.replace(/(?:\b|['"\s])([a-z0-9-:]+)?rounded(-[a-z0-9\[\]]+)?(?=["'\s])/g, (match, prefix, suffix) => {
108
- // If it's just 'rounded' or 'rounded-*', replace it
109
- if (match.includes("rounded")) {
110
- // Preserve prefixes like 'focus:'
111
- const cleanPrefix = match.split("rounded")[0];
112
- return `${cleanPrefix}rounded-none`;
190
+ /**
191
+ * Checks the `@forgewp/ui` local registry for a component override.
192
+ * Returns an object with the tsx path and parsed registry.json metadata,
193
+ * or null if no override exists for this component.
194
+ *
195
+ * @returns {{ tsxPath: string, meta: object } | null}
196
+ */
197
+ function resolveLocalRegistry(component) {
198
+ let registryBase;
199
+ try {
200
+ const req = createRequire(import.meta.url);
201
+ registryBase = path.join(
202
+ path.dirname(req.resolve("@forgewp/ui/package.json")),
203
+ "components"
204
+ );
205
+ } catch {
206
+ // Fallback for local monorepo development
207
+ registryBase = path.resolve(
208
+ path.dirname(fileURLToPath(import.meta.url)),
209
+ "../../ui/components"
210
+ );
211
+ }
212
+
213
+ const componentDir = path.join(registryBase, component);
214
+ const tsxPath = path.join(componentDir, "forgewp.tsx");
215
+ const registryPath = path.join(componentDir, "registry.json");
216
+
217
+ if (!existsSync(tsxPath) && !existsSync(registryPath)) return null;
218
+
219
+ let meta = {};
220
+ if (existsSync(registryPath)) {
221
+ try {
222
+ meta = JSON.parse(readFileSync(registryPath, "utf8"));
223
+ } catch {
224
+ // Malformed registry.json — proceed with empty meta
113
225
  }
114
- return match;
115
- });
116
-
117
- if (content !== sharpened) {
118
- writeFileSync(filePath, sharpened, "utf8");
119
- console.log(pc.dim(` Sharpened ${path.basename(filePath)}`));
120
226
  }
227
+
228
+ return { tsxPath, meta };
121
229
  }
122
230
 
123
- function autoInstallMissingDependencies(filePath, projectRoot) {
124
- return new Promise((resolve) => {
125
- const content = readFileSync(filePath, "utf8");
126
-
127
- // Find all import statements
128
- const importRegex = /import\s+(?:[a-zA-Z0-9_*$,{}\s]+from\s+)?['"]([^'"]+)['"]/g;
129
- const foundImports = new Set();
130
- let match;
131
-
132
- while ((match = importRegex.exec(content)) !== null) {
133
- const importPath = match[1];
134
- // Filter out local imports, React, and standard framework packages
135
- if (
136
- !importPath.startsWith(".") &&
137
- !importPath.startsWith("/") &&
138
- importPath !== "react" &&
139
- importPath !== "react-dom" &&
140
- importPath !== "@forgewp/react"
141
- ) {
142
- // Extract the base package name (e.g. framer-motion or @radix-ui/react-slot)
143
- let basePkg = importPath;
144
- if (importPath.startsWith("@")) {
145
- const parts = importPath.split("/");
146
- basePkg = `${parts[0]}/${parts[1]}`;
147
- } else {
148
- basePkg = importPath.split("/")[0];
149
- }
150
- foundImports.add(basePkg);
231
+ /**
232
+ * Ensures the given Tailwind CSS plugins are installed and registered
233
+ * via `@plugin` in the project's globals.css file.
234
+ *
235
+ * This is used only for ForgeWP-native components whose Tailwind plugin
236
+ * requirements are declared in their local registry.json — since shadcn's
237
+ * remote registry handles this automatically for shadcn-sourced components.
238
+ *
239
+ * @param {string[]} plugins - Plugin package names (e.g. ["tailwindcss-animate"])
240
+ * @param {string} installCmd - The detected package manager install command
241
+ * @param {string} projectRoot
242
+ */
243
+ async function ensureTailwindPlugins(plugins, installCmd, projectRoot) {
244
+ const pkgJsonPath = path.join(projectRoot, "package.json");
245
+ if (!existsSync(pkgJsonPath)) return;
246
+
247
+ const pkg = JSON.parse(readFileSync(pkgJsonPath, "utf8"));
248
+ const currentDeps = { ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}) };
249
+
250
+ for (const plugin of plugins) {
251
+ // Install if missing
252
+ if (!currentDeps[plugin]) {
253
+ console.log(pc.yellow(`\n ⚡ Requires Tailwind plugin: ${pc.bold(plugin)}`));
254
+ try {
255
+ execSync(`${installCmd} ${plugin}`, {
256
+ stdio: "inherit",
257
+ cwd: projectRoot,
258
+ shell: process.platform === "win32",
259
+ });
260
+ console.log(pc.green(` ✅ Installed ${plugin}`));
261
+ } catch (err) {
262
+ console.log(pc.red(` ❌ Failed to install ${plugin}: ${err.message}`));
263
+ console.log(pc.yellow(` Please manually run: ${installCmd} ${plugin}\n`));
264
+ continue;
151
265
  }
152
266
  }
153
267
 
154
- if (foundImports.size === 0) {
155
- resolve();
156
- return;
157
- }
268
+ // Register @plugin in globals.css if not already present
269
+ const cssSearchPaths = [
270
+ path.join(projectRoot, "src", "app", "globals.css"),
271
+ path.join(projectRoot, "src", "styles", "globals.css"),
272
+ path.join(projectRoot, "src", "index.css"),
273
+ path.join(projectRoot, "src", "global.css"),
274
+ ];
158
275
 
159
- const pkgJsonPath = path.join(projectRoot, "package.json");
160
- if (!existsSync(pkgJsonPath)) {
161
- resolve();
162
- return;
276
+ const globalsPath = cssSearchPaths.find(p => existsSync(p));
277
+ if (!globalsPath) {
278
+ console.log(pc.yellow(` ⚠ Could not find globals.css. Add manually: @plugin "${plugin}";`));
279
+ continue;
163
280
  }
164
281
 
165
- const pkg = JSON.parse(readFileSync(pkgJsonPath, "utf8"));
166
- const currentDeps = {
167
- ...(pkg.dependencies || {}),
168
- ...(pkg.devDependencies || {})
169
- };
170
-
171
- const missingDeps = Array.from(foundImports).filter(dep => !currentDeps[dep]);
172
-
173
- if (missingDeps.length > 0) {
174
- console.log(pc.yellow(`\n ⚡ Detected missing dependencies: ${missingDeps.join(", ")}`));
175
-
176
- // Detect Package Manager
177
- let installCmd = "npm install --save";
178
- let managerName = "npm";
179
- if (existsSync(path.join(projectRoot, "pnpm-lock.yaml"))) {
180
- installCmd = "pnpm add";
181
- managerName = "pnpm";
182
- } else if (existsSync(path.join(projectRoot, "yarn.lock"))) {
183
- installCmd = "yarn add";
184
- managerName = "yarn";
185
- } else if (existsSync(path.join(projectRoot, "bun.lockb"))) {
186
- installCmd = "bun add";
187
- managerName = "bun";
188
- }
189
-
190
- // Check if environment is interactive
191
- if (!process.stdin.isTTY) {
192
- console.log(pc.dim(` Non-interactive environment detected. Skipping auto-install.`));
193
- console.log(pc.yellow(` Please manually install: ${installCmd} ${missingDeps.join(" ")}\n`));
194
- resolve();
195
- return;
196
- }
282
+ let css = readFileSync(globalsPath, "utf8");
283
+ const directive = `@plugin "${plugin}";`;
284
+ if (css.includes(directive)) {
285
+ console.log(pc.dim(` ↳ ${plugin} already registered in ${path.basename(globalsPath)}`));
286
+ continue;
287
+ }
197
288
 
198
- const rl = readline.createInterface({
199
- input: process.stdin,
200
- output: process.stdout
201
- });
289
+ // Insert after the last @import line
290
+ const lines = css.split("\n");
291
+ let lastImportIdx = -1;
292
+ lines.forEach((line, i) => {
293
+ if (line.trimStart().startsWith("@import")) lastImportIdx = i;
294
+ });
202
295
 
203
- rl.question(` ? Would you like to install them via ${pc.bold(managerName)}? (Y/n): `, (answer) => {
204
- rl.close();
205
- const confirmed = answer.trim().toLowerCase() !== "n";
206
-
207
- if (confirmed) {
208
- console.log(pc.dim(" Automatically installing dependencies..."));
209
- try {
210
- execSync(`${installCmd} ${missingDeps.join(" ")}`, {
211
- stdio: "inherit",
212
- cwd: projectRoot,
213
- shell: process.platform === "win32"
214
- });
215
- console.log(pc.green(` ✅ Successfully installed: ${missingDeps.join(", ")}\n`));
216
- } catch (err) {
217
- console.log(pc.red(` ❌ Auto-installation failed: ${err.message}`));
218
- console.log(pc.yellow(` Please manually install: ${installCmd} ${missingDeps.join(" ")}\n`));
219
- }
220
- } else {
221
- console.log(pc.blue(" Skipped installation."));
222
- console.log(pc.yellow(` Please manually install: ${installCmd} ${missingDeps.join(" ")}\n`));
223
- }
224
- resolve();
225
- });
296
+ if (lastImportIdx !== -1) {
297
+ lines.splice(lastImportIdx + 1, 0, directive);
226
298
  } else {
227
- resolve();
299
+ lines.unshift(directive);
228
300
  }
229
- });
301
+
302
+ writeFileSync(globalsPath, lines.join("\n"), "utf8");
303
+ console.log(pc.green(` ✅ Registered @plugin "${plugin}" in ${path.basename(globalsPath)}`));
304
+ }
230
305
  }
231
306
 
307
+ /**
308
+ * Applies the ForgeWP "sharp" neo-brutalist aesthetic transform to a component file.
309
+ * Replaces all Tailwind rounding utilities with `rounded-none`.
310
+ * Used only when the project's wp.config.ts sets style: "forgewp".
311
+ */
312
+ function sharpenFile(filePath) {
313
+ let content = readFileSync(filePath, "utf8");
314
+
315
+ const sharpened = content.replace(
316
+ /(?:\b|['"\s])([a-z0-9-:]+)?rounded(-[a-z0-9\[\]]+)?(?=["'\s])/g,
317
+ (match) => {
318
+ if (match.includes("rounded")) {
319
+ const cleanPrefix = match.split("rounded")[0];
320
+ return `${cleanPrefix}rounded-none`;
321
+ }
322
+ return match;
323
+ }
324
+ );
325
+
326
+ if (content !== sharpened) {
327
+ writeFileSync(filePath, sharpened, "utf8");
328
+ console.log(pc.dim(` Sharpened ${path.basename(filePath)}`));
329
+ }
330
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Node.js ESM Loader hook to intercept and mock static asset imports (images, styles, fonts)
3
+ * during server-side theme compilation.
4
+ */
5
+ export async function load(url, context, defaultLoad) {
6
+ const cleanUrl = url.split('?')[0].split('#')[0];
7
+ if (
8
+ cleanUrl.endsWith('.css') ||
9
+ cleanUrl.endsWith('.png') ||
10
+ cleanUrl.endsWith('.jpg') ||
11
+ cleanUrl.endsWith('.jpeg') ||
12
+ cleanUrl.endsWith('.webp') ||
13
+ cleanUrl.endsWith('.svg') ||
14
+ cleanUrl.endsWith('.gif') ||
15
+ cleanUrl.endsWith('.woff') ||
16
+ cleanUrl.endsWith('.woff2') ||
17
+ cleanUrl.endsWith('.ttf') ||
18
+ cleanUrl.endsWith('.eot')
19
+ ) {
20
+ return {
21
+ format: 'module',
22
+ source: 'export default "";',
23
+ shortCircuit: true,
24
+ };
25
+ }
26
+ return defaultLoad(url, context, defaultLoad);
27
+ }