@forgewp/compiler 0.2.0 → 0.3.0
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.
- package/lib/add-component.js +118 -0
- package/lib/generate-theme.js +213 -4
- package/lib/hydration-scanner.js +179 -0
- package/lib/index.d.ts +6 -0
- package/lib/index.js +3 -0
- package/package.json +2 -2
package/lib/add-component.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { execSync } from "node:child_process";
|
|
2
2
|
import { readFileSync, writeFileSync, readdirSync, existsSync, mkdirSync } from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
|
+
import readline from "node:readline";
|
|
4
5
|
import pc from "picocolors";
|
|
5
6
|
|
|
6
7
|
export async function addComponent(component, options) {
|
|
@@ -34,6 +35,13 @@ export async function addComponent(component, options) {
|
|
|
34
35
|
const content = readFileSync(localComponentFile, "utf8");
|
|
35
36
|
writeFileSync(targetFile, content, "utf8");
|
|
36
37
|
|
|
38
|
+
// Auto-detect and install missing third-party dependencies from imported component files
|
|
39
|
+
await autoInstallMissingDependencies(targetFile, projectRoot);
|
|
40
|
+
|
|
41
|
+
if (style === "forgewp") {
|
|
42
|
+
sharpenFile(targetFile);
|
|
43
|
+
}
|
|
44
|
+
|
|
37
45
|
console.log(pc.green(`\n Success! ${component} added to src/components/ui/\n`));
|
|
38
46
|
return;
|
|
39
47
|
}
|
|
@@ -111,3 +119,113 @@ function sharpenFile(filePath) {
|
|
|
111
119
|
console.log(pc.dim(` Sharpened ${path.basename(filePath)}`));
|
|
112
120
|
}
|
|
113
121
|
}
|
|
122
|
+
|
|
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);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
if (foundImports.size === 0) {
|
|
155
|
+
resolve();
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const pkgJsonPath = path.join(projectRoot, "package.json");
|
|
160
|
+
if (!existsSync(pkgJsonPath)) {
|
|
161
|
+
resolve();
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
|
|
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
|
+
}
|
|
197
|
+
|
|
198
|
+
const rl = readline.createInterface({
|
|
199
|
+
input: process.stdin,
|
|
200
|
+
output: process.stdout
|
|
201
|
+
});
|
|
202
|
+
|
|
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
|
+
});
|
|
226
|
+
} else {
|
|
227
|
+
resolve();
|
|
228
|
+
}
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
|
package/lib/generate-theme.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { copyFileSync, cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
|
+
import { scanForHydrationIslands } from "./hydration-scanner.js";
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* @param {Object} options
|
|
@@ -108,16 +109,172 @@ export function generateTheme({
|
|
|
108
109
|
}
|
|
109
110
|
}
|
|
110
111
|
|
|
112
|
+
const hydrationIslands = scanForHydrationIslands(themeRoot);
|
|
113
|
+
const hasHydration = hydrationIslands.length > 0;
|
|
114
|
+
|
|
111
115
|
const assetsOut = path.join(outDir, "assets");
|
|
112
116
|
const distAssets = path.join(themeRoot, "dist", "assets");
|
|
113
117
|
mkdirSync(assetsOut, { recursive: true });
|
|
114
118
|
cpSync(distAssets, assetsOut, { recursive: true });
|
|
115
119
|
|
|
120
|
+
let hydrationManifestJson = "{}";
|
|
121
|
+
if (hasHydration) {
|
|
122
|
+
const manifestPath = path.join(themeRoot, "dist", ".vite", "manifest.json");
|
|
123
|
+
let viteManifest = {};
|
|
124
|
+
if (existsSync(manifestPath)) {
|
|
125
|
+
try {
|
|
126
|
+
viteManifest = JSON.parse(readFileSync(manifestPath, "utf8"));
|
|
127
|
+
} catch (e) {
|
|
128
|
+
console.warn("Failed to parse Vite manifest.json:", e.message);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const mapping = {};
|
|
133
|
+
let mainJsFile = "";
|
|
134
|
+
const entryChunk = viteManifest["index.html"] || Object.values(viteManifest).find(c => c.isEntry);
|
|
135
|
+
if (entryChunk) {
|
|
136
|
+
mainJsFile = entryChunk.file;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
for (const island of hydrationIslands) {
|
|
140
|
+
const pascalName = island
|
|
141
|
+
.split("-")
|
|
142
|
+
.map(w => w.charAt(0).toUpperCase() + w.slice(1))
|
|
143
|
+
.join("");
|
|
144
|
+
|
|
145
|
+
let resolvedChunk = null;
|
|
146
|
+
for (const [key, value] of Object.entries(viteManifest)) {
|
|
147
|
+
if (
|
|
148
|
+
key.endsWith(`${pascalName}.tsx`) ||
|
|
149
|
+
key.endsWith(`${pascalName}.ts`) ||
|
|
150
|
+
key.endsWith(`${island}.tsx`) ||
|
|
151
|
+
key.endsWith(`${island}.ts`) ||
|
|
152
|
+
(value.file && value.file.includes(island))
|
|
153
|
+
) {
|
|
154
|
+
resolvedChunk = value.file;
|
|
155
|
+
break;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
if (resolvedChunk) {
|
|
160
|
+
mapping[island] = resolvedChunk;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const hydratorScript = `(function () {
|
|
165
|
+
const config = window.forgeWpHydration || { themeUri: "", manifest: {} };
|
|
166
|
+
const islands = document.querySelectorAll("[data-forgewp-hydrate]");
|
|
167
|
+
|
|
168
|
+
const observer = new IntersectionObserver((entries) => {
|
|
169
|
+
entries.forEach((entry) => {
|
|
170
|
+
if (entry.isIntersecting) {
|
|
171
|
+
const hydrate = entry.target.__forgewpHydrate;
|
|
172
|
+
if (typeof hydrate === "function") hydrate();
|
|
173
|
+
observer.unobserve(entry.target);
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
}, { rootMargin: "200px" });
|
|
177
|
+
|
|
178
|
+
const StrategyRegistry = {
|
|
179
|
+
load: (el, hydrate) => {
|
|
180
|
+
if (document.readyState === "complete") {
|
|
181
|
+
hydrate();
|
|
182
|
+
} else {
|
|
183
|
+
window.addEventListener("load", hydrate);
|
|
184
|
+
}
|
|
185
|
+
},
|
|
186
|
+
visible: (el, hydrate) => {
|
|
187
|
+
el.__forgewpHydrate = hydrate;
|
|
188
|
+
observer.observe(el);
|
|
189
|
+
},
|
|
190
|
+
interaction: (el, hydrate) => {
|
|
191
|
+
const run = () => {
|
|
192
|
+
hydrate();
|
|
193
|
+
el.removeEventListener("click", run);
|
|
194
|
+
el.removeEventListener("mouseenter", run);
|
|
195
|
+
el.removeEventListener("focusin", run);
|
|
196
|
+
};
|
|
197
|
+
el.addEventListener("click", run);
|
|
198
|
+
el.addEventListener("mouseenter", run);
|
|
199
|
+
el.addEventListener("focusin", run);
|
|
200
|
+
},
|
|
201
|
+
// Modern extensible triggers (e.g. idle trigger for low priority activation)
|
|
202
|
+
idle: (el, hydrate) => {
|
|
203
|
+
if ("requestIdleCallback" in window) {
|
|
204
|
+
window.requestIdleCallback(hydrate);
|
|
205
|
+
} else {
|
|
206
|
+
setTimeout(hydrate, 200);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
|
|
211
|
+
islands.forEach((el) => {
|
|
212
|
+
const trigger = el.getAttribute("data-forgewp-trigger") || "visible";
|
|
213
|
+
const runHydration = () => hydrateElement(el);
|
|
214
|
+
|
|
215
|
+
const strategy = StrategyRegistry[trigger];
|
|
216
|
+
if (strategy) {
|
|
217
|
+
strategy(el, runHydration);
|
|
218
|
+
} else {
|
|
219
|
+
StrategyRegistry.visible(el, runHydration);
|
|
220
|
+
}
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
function hydrateElement(el) {
|
|
224
|
+
const islandName = el.getAttribute("data-forgewp-hydrate");
|
|
225
|
+
const rawProps = el.getAttribute("data-forgewp-props") || "{}";
|
|
226
|
+
const props = JSON.parse(rawProps);
|
|
227
|
+
|
|
228
|
+
const chunkPath = config.manifest[islandName];
|
|
229
|
+
if (!chunkPath) {
|
|
230
|
+
console.error("[ForgeWP Hydrator] Could not find compiled chunk for island " + islandName);
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const scriptUrl = config.themeUri + "/assets/" + chunkPath.replace(/^assets\\//, "").replace(/^assets\\/, "");
|
|
235
|
+
|
|
236
|
+
import(scriptUrl)
|
|
237
|
+
.then((module) => {
|
|
238
|
+
const Component = module.default || Object.values(module)[0];
|
|
239
|
+
if (typeof Component !== "function") {
|
|
240
|
+
console.error("[ForgeWP Hydrator] Chunk for " + islandName + " does not export a valid React component");
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
if (window.ReactDOM && window.React) {
|
|
245
|
+
const isClientOnly = el.hasAttribute("data-forgewp-client-only");
|
|
246
|
+
if (isClientOnly) {
|
|
247
|
+
// No SSR markup present: clean render
|
|
248
|
+
const root = window.ReactDOM.createRoot(el);
|
|
249
|
+
root.render(window.React.createElement(Component, props));
|
|
250
|
+
} else {
|
|
251
|
+
// Highly optimized hydration of server-side visual markup
|
|
252
|
+
window.ReactDOM.hydrateRoot(el, window.React.createElement(Component, props));
|
|
253
|
+
}
|
|
254
|
+
} else {
|
|
255
|
+
console.error("[ForgeWP Hydration Error] React or ReactDOM not found on window object.");
|
|
256
|
+
}
|
|
257
|
+
})
|
|
258
|
+
.catch((err) => {
|
|
259
|
+
console.error("[ForgeWP Hydrator] Failed to load chunk for " + islandName + ":", err);
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
})();`;
|
|
263
|
+
|
|
264
|
+
writeFileSync(path.join(assetsOut, "forgewp-hydrator.js"), hydratorScript, "utf8");
|
|
265
|
+
hydrationManifestJson = JSON.stringify({
|
|
266
|
+
mainJsFile,
|
|
267
|
+
mapping
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
|
|
116
271
|
// Drop unused JS from the theme ZIP
|
|
117
272
|
const files = readdirSync(assetsOut);
|
|
118
273
|
for (const file of files) {
|
|
119
|
-
if ((file.endsWith(".js") || file.endsWith(".js.map")) && file !== "forgewp-editor.js") {
|
|
120
|
-
|
|
274
|
+
if ((file.endsWith(".js") || file.endsWith(".js.map")) && file !== "forgewp-editor.js" && file !== "forgewp-hydrator.js") {
|
|
275
|
+
if (!hasHydration) {
|
|
276
|
+
rmSync(path.join(assetsOut, file), { force: true });
|
|
277
|
+
}
|
|
121
278
|
}
|
|
122
279
|
}
|
|
123
280
|
|
|
@@ -236,9 +393,17 @@ if (window.forgeWpBlocks) {
|
|
|
236
393
|
writeFileSync(path.join(outDir, "assets", "forgewp-editor.js"), editorScriptContent, "utf8");
|
|
237
394
|
|
|
238
395
|
writeFileSync(path.join(outDir, "style.css"), buildStyleCss(config), "utf8");
|
|
396
|
+
|
|
397
|
+
let hydrationData = null;
|
|
398
|
+
if (hasHydration) {
|
|
399
|
+
try {
|
|
400
|
+
hydrationData = JSON.parse(hydrationManifestJson);
|
|
401
|
+
} catch {}
|
|
402
|
+
}
|
|
403
|
+
|
|
239
404
|
writeFileSync(
|
|
240
405
|
path.join(outDir, "functions.php"),
|
|
241
|
-
buildFunctionsPhp(config, assets, compiledBlocks, themeRoot, pagesToAutoCreate, menus),
|
|
406
|
+
buildFunctionsPhp(config, assets, compiledBlocks, themeRoot, pagesToAutoCreate, menus, hydrationData),
|
|
242
407
|
"utf8",
|
|
243
408
|
);
|
|
244
409
|
writeFileSync(path.join(outDir, "header.php"), buildHeaderPhp(config), "utf8");
|
|
@@ -494,7 +659,7 @@ Text Domain: ${config.textDomain}
|
|
|
494
659
|
* @param {import('./types.js').ForgeWPThemeConfig} config
|
|
495
660
|
* @param {import('./types.js').ForgeWPBuildAssets} assets
|
|
496
661
|
*/
|
|
497
|
-
function buildFunctionsPhp(config, assets, blockSlugs = [], themeRoot = "", pagesToAutoCreate = [], menus = {}) {
|
|
662
|
+
function buildFunctionsPhp(config, assets, blockSlugs = [], themeRoot = "", pagesToAutoCreate = [], menus = {}, hydrationData = null) {
|
|
498
663
|
const css = assets.cssFile.replace(/^assets\//, "");
|
|
499
664
|
const version = config.version.replace(/'/g, "\\'");
|
|
500
665
|
const googleFonts = config.settings?.typography?.googleFonts || [];
|
|
@@ -734,6 +899,49 @@ ${menuItemsPhpArray}
|
|
|
734
899
|
add_action('after_switch_theme', 'forgewp_auto_create_pages_and_menus');
|
|
735
900
|
`;
|
|
736
901
|
|
|
902
|
+
let hydrationEnqueue = "";
|
|
903
|
+
if (hydrationData && hydrationData.mapping) {
|
|
904
|
+
const mainJs = hydrationData.mainJsFile.replace(/^assets\//, "").replace(/^assets\\/, "");
|
|
905
|
+
const manifestPairs = Object.entries(hydrationData.mapping).map(([key, val]) => {
|
|
906
|
+
const cleanVal = val.replace(/^assets\//, "").replace(/^assets\\/, "");
|
|
907
|
+
return ` '${key}' => 'assets/${cleanVal}'`;
|
|
908
|
+
}).join(",\n");
|
|
909
|
+
|
|
910
|
+
hydrationEnqueue = `
|
|
911
|
+
// Enqueue React runtime entrypoint and dynamic Selective Hydration assets
|
|
912
|
+
$js_path = get_template_directory() . '/assets/${mainJs}';
|
|
913
|
+
if (file_exists($js_path)) {
|
|
914
|
+
wp_enqueue_script(
|
|
915
|
+
'${config.textDomain}-react-runtime',
|
|
916
|
+
$theme_uri . '/assets/${mainJs}',
|
|
917
|
+
array(),
|
|
918
|
+
FORGEWP_THEME_VERSION,
|
|
919
|
+
true
|
|
920
|
+
);
|
|
921
|
+
|
|
922
|
+
// Inject hydration manifest mappings dynamically
|
|
923
|
+
wp_localize_script(
|
|
924
|
+
'${config.textDomain}-react-runtime',
|
|
925
|
+
'forgeWpHydration',
|
|
926
|
+
array(
|
|
927
|
+
'themeUri' => $theme_uri,
|
|
928
|
+
'manifest' => array(
|
|
929
|
+
${manifestPairs}
|
|
930
|
+
)
|
|
931
|
+
)
|
|
932
|
+
);
|
|
933
|
+
|
|
934
|
+
// Enqueue Micro-Hydrator orchestrator script
|
|
935
|
+
wp_enqueue_script(
|
|
936
|
+
'${config.textDomain}-hydrator',
|
|
937
|
+
$theme_uri . '/assets/forgewp-hydrator.js',
|
|
938
|
+
array('${config.textDomain}-react-runtime'),
|
|
939
|
+
FORGEWP_THEME_VERSION,
|
|
940
|
+
true
|
|
941
|
+
);
|
|
942
|
+
}`;
|
|
943
|
+
}
|
|
944
|
+
|
|
737
945
|
return `<?php
|
|
738
946
|
/**
|
|
739
947
|
* ${config.name} — generated by ForgeWP
|
|
@@ -763,6 +971,7 @@ ${fontsEnqueue}
|
|
|
763
971
|
FORGEWP_THEME_VERSION
|
|
764
972
|
);
|
|
765
973
|
}
|
|
974
|
+
${hydrationEnqueue}
|
|
766
975
|
}
|
|
767
976
|
add_action('wp_enqueue_scripts', 'forgewp_enqueue_assets');
|
|
768
977
|
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { readFileSync, readdirSync, existsSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Scans the theme's page files (page.tsx, layout.tsx, pages/*.tsx)
|
|
6
|
+
* for <Hydrate> boundaries and extracts their resolved kebab-case component names.
|
|
7
|
+
*
|
|
8
|
+
* @param {string} themeRoot - The absolute path of the theme's root directory.
|
|
9
|
+
* @returns {string[]} An array of discovered kebab-case hydration chunk identifiers.
|
|
10
|
+
*/
|
|
11
|
+
export function scanForHydrationIslands(themeRoot) {
|
|
12
|
+
const islands = new Set();
|
|
13
|
+
const filesToScan = [];
|
|
14
|
+
|
|
15
|
+
const appDir = path.join(themeRoot, "src", "app");
|
|
16
|
+
if (existsSync(appDir)) {
|
|
17
|
+
// Scan page.tsx
|
|
18
|
+
const mainPage = path.join(appDir, "page.tsx");
|
|
19
|
+
if (existsSync(mainPage)) filesToScan.push(mainPage);
|
|
20
|
+
|
|
21
|
+
// Scan layout.tsx
|
|
22
|
+
const mainLayout = path.join(appDir, "layout.tsx");
|
|
23
|
+
if (existsSync(mainLayout)) filesToScan.push(mainLayout);
|
|
24
|
+
|
|
25
|
+
// Scan pages/ directory
|
|
26
|
+
const pagesDir = path.join(appDir, "pages");
|
|
27
|
+
if (existsSync(pagesDir)) {
|
|
28
|
+
try {
|
|
29
|
+
const pages = readdirSync(pagesDir).filter((f) => f.endsWith(".tsx"));
|
|
30
|
+
for (const file of pages) {
|
|
31
|
+
filesToScan.push(path.join(pagesDir, file));
|
|
32
|
+
}
|
|
33
|
+
} catch {}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Scan each file for <Hydrate> occurrences
|
|
38
|
+
for (const filePath of filesToScan) {
|
|
39
|
+
try {
|
|
40
|
+
const content = readFileSync(filePath, "utf8");
|
|
41
|
+
|
|
42
|
+
// Matches <Hydrate ...> ... </Hydrate>
|
|
43
|
+
const hydrateRegex = /<Hydrate\b([\s\S]*?)>([\s\S]*?)<\/Hydrate>/g;
|
|
44
|
+
let match;
|
|
45
|
+
while ((match = hydrateRegex.exec(content)) !== null) {
|
|
46
|
+
const propsStr = match[1];
|
|
47
|
+
const childrenStr = match[2].trim();
|
|
48
|
+
|
|
49
|
+
// 1. Try to parse explicit 'id' attribute
|
|
50
|
+
const idMatch = propsStr.match(/id\s*=\s*["']([^"']*)["']/);
|
|
51
|
+
if (idMatch) {
|
|
52
|
+
islands.add(idMatch[1]);
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// 2. Fallback: Parse Component Tag name from children (e.g. <FadeUpSection />)
|
|
57
|
+
const componentTagMatch = childrenStr.match(/<([A-Z][a-zA-Z0-9]*)\b/);
|
|
58
|
+
if (componentTagMatch) {
|
|
59
|
+
const compName = componentTagMatch[1];
|
|
60
|
+
const kebabName = compName
|
|
61
|
+
.replace(/([a-z0-9])([A-Z])/g, "$1-$2")
|
|
62
|
+
.toLowerCase();
|
|
63
|
+
islands.add(kebabName);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
} catch (err) {
|
|
67
|
+
console.warn(`[Hydration Scanner] Failed to scan file ${filePath}:`, err.message);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// 3. Smart Component Discovery: scan src/components/ for interactive/animated components
|
|
72
|
+
const compDir = path.join(themeRoot, "src", "components");
|
|
73
|
+
const interactiveComponents = new Set();
|
|
74
|
+
|
|
75
|
+
function scanComponentsRecursive(dir) {
|
|
76
|
+
if (!existsSync(dir)) return;
|
|
77
|
+
try {
|
|
78
|
+
const items = readdirSync(dir, { withFileTypes: true });
|
|
79
|
+
for (const item of items) {
|
|
80
|
+
const fullPath = path.join(dir, item.name);
|
|
81
|
+
if (item.isDirectory()) {
|
|
82
|
+
scanComponentsRecursive(fullPath);
|
|
83
|
+
} else if (item.isFile() && (item.name.endsWith(".tsx") || item.name.endsWith(".ts"))) {
|
|
84
|
+
try {
|
|
85
|
+
const fileContent = readFileSync(fullPath, "utf8");
|
|
86
|
+
const hasState = fileContent.includes("useState") || fileContent.includes("useEffect") || fileContent.includes("useRef");
|
|
87
|
+
const hasMotion = fileContent.includes("framer-motion") || fileContent.includes("gsap") || fileContent.includes("animate") || fileContent.includes("motion.");
|
|
88
|
+
if (hasState || hasMotion) {
|
|
89
|
+
const compName = path.basename(item.name, path.extname(item.name));
|
|
90
|
+
interactiveComponents.add(compName);
|
|
91
|
+
}
|
|
92
|
+
} catch {}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
} catch {}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
scanComponentsRecursive(compDir);
|
|
99
|
+
|
|
100
|
+
for (const filePath of filesToScan) {
|
|
101
|
+
try {
|
|
102
|
+
const content = readFileSync(filePath, "utf8");
|
|
103
|
+
for (const compName of interactiveComponents) {
|
|
104
|
+
if (content.includes(`<${compName}`)) {
|
|
105
|
+
const kebabName = compName.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
|
|
106
|
+
if (!islands.has(kebabName)) {
|
|
107
|
+
islands.add(kebabName);
|
|
108
|
+
console.log(`\x1b[33m[ForgeWP Optimizer] Smart Discovery: Detected "${compName}" uses interactive hooks/animations. Auto-enforcing code-splitting chunk. Wrap it in <Hydrate> in page markup for dynamic browser activation!\x1b[0m`);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
} catch {}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return Array.from(islands);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Searches components directories for a file matching the kebab-case component name.
|
|
120
|
+
*
|
|
121
|
+
* @param {string} themeRoot - The absolute path of the theme's root directory.
|
|
122
|
+
* @param {string} kebabName - The target component's kebab-case identifier.
|
|
123
|
+
* @returns {string|null} The absolute path to the component file, or null if not found.
|
|
124
|
+
*/
|
|
125
|
+
export function findComponentPath(themeRoot, kebabName) {
|
|
126
|
+
const compDirs = [
|
|
127
|
+
path.join(themeRoot, "src", "components"),
|
|
128
|
+
path.join(themeRoot, "src", "components", "ui"),
|
|
129
|
+
];
|
|
130
|
+
|
|
131
|
+
// Convert kebab-case back to PascalCase and check candidates
|
|
132
|
+
const pascalName = kebabName
|
|
133
|
+
.split("-")
|
|
134
|
+
.map((w) => w.charAt(0).toUpperCase() + w.slice(1))
|
|
135
|
+
.join("");
|
|
136
|
+
|
|
137
|
+
const candidates = [
|
|
138
|
+
`${pascalName}.tsx`,
|
|
139
|
+
`${pascalName}.ts`,
|
|
140
|
+
`${kebabName}.tsx`,
|
|
141
|
+
`${kebabName}.ts`,
|
|
142
|
+
];
|
|
143
|
+
|
|
144
|
+
for (const dir of compDirs) {
|
|
145
|
+
if (!existsSync(dir)) continue;
|
|
146
|
+
try {
|
|
147
|
+
const files = readdirSync(dir);
|
|
148
|
+
for (const file of files) {
|
|
149
|
+
if (candidates.includes(file)) {
|
|
150
|
+
return path.join(dir, file);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
} catch {}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
return null;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Resolves Rollup's multi-entry input mapping for Vite based on discovered hydration islands.
|
|
161
|
+
*
|
|
162
|
+
* @param {string} themeRoot - The absolute path of the theme's root directory.
|
|
163
|
+
* @returns {Record<string, string>} Rollup input object.
|
|
164
|
+
*/
|
|
165
|
+
export function getHydrationRollupInputs(themeRoot) {
|
|
166
|
+
const inputs = {
|
|
167
|
+
index: path.resolve(themeRoot, "index.html"),
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
const islands = scanForHydrationIslands(themeRoot);
|
|
171
|
+
for (const island of islands) {
|
|
172
|
+
const compPath = findComponentPath(themeRoot, island);
|
|
173
|
+
if (compPath) {
|
|
174
|
+
inputs[island] = compPath;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
return inputs;
|
|
179
|
+
}
|
package/lib/index.d.ts
CHANGED
|
@@ -59,3 +59,9 @@ export function exportTheme(options: {
|
|
|
59
59
|
export function loadConfig(themeRoot: string): Promise<ForgeWPThemeConfig>;
|
|
60
60
|
|
|
61
61
|
export function validateCriticalFiles(themeRoot: string): void;
|
|
62
|
+
|
|
63
|
+
export function scanForHydrationIslands(themeRoot: string): string[];
|
|
64
|
+
|
|
65
|
+
export function findComponentPath(themeRoot: string, kebabName: string): string | null;
|
|
66
|
+
|
|
67
|
+
export function getHydrationRollupInputs(themeRoot: string): Record<string, string>;
|
package/lib/index.js
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
1
|
export { exportTheme } from "./export-theme.js";
|
|
2
2
|
export { loadConfig } from "./load-config.js";
|
|
3
3
|
export { validateCriticalFiles } from "./validate.js";
|
|
4
|
+
export { scanForHydrationIslands, findComponentPath, getHydrationRollupInputs } from "./hydration-scanner.js";
|
|
5
|
+
|
|
6
|
+
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@forgewp/compiler",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Compile ForgeWP React themes into installable WordPress themes",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
"jiti": "^2.6.1",
|
|
26
26
|
"picocolors": "^1.1.1",
|
|
27
27
|
"react-helmet-async": "^3.0.0",
|
|
28
|
-
"@forgewp/ui": "0.
|
|
28
|
+
"@forgewp/ui": "0.3.0"
|
|
29
29
|
},
|
|
30
30
|
"devDependencies": {
|
|
31
31
|
"@types/node": "^22.19.19"
|