@forgewp/compiler 0.4.3 → 0.4.4

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 (133) hide show
  1. package/README.md +59 -0
  2. package/bin/add.js +20 -14
  3. package/bin/cli.js +145 -70
  4. package/bin/doctor.js +21 -12
  5. package/bin/export.js +69 -20
  6. package/bin/fresh.js +5 -0
  7. package/bin/i18n-extract.js +3 -10
  8. package/bin/i18n-translate.js +15 -24
  9. package/bin/make-block.js +13 -0
  10. package/bin/make-editable.js +166 -0
  11. package/bin/make-form.js +131 -0
  12. package/bin/make-loop.js +40 -43
  13. package/bin/make-mail.js +27 -0
  14. package/bin/make-post-type.js +57 -29
  15. package/bin/make-sandbox.js +62 -11
  16. package/bin/make-section.js +221 -0
  17. package/bin/make-shell.js +375 -0
  18. package/bin/repair.js +14 -26
  19. package/bin/seed.js +119 -0
  20. package/bin/sync-routes.js +107 -85
  21. package/lib/adapters/html-adapter.js +5 -0
  22. package/lib/adapters/stub-adapter.js +4 -0
  23. package/lib/add-component.js +153 -92
  24. package/lib/asset-loader.js +313 -3
  25. package/lib/assets/asset-graph.js +432 -0
  26. package/lib/assets/asset-pipeline.js +125 -0
  27. package/lib/assets/diagnostics-report.js +345 -0
  28. package/lib/assets/external-fetcher.js +173 -0
  29. package/lib/assets/font-orchestrator.js +348 -0
  30. package/lib/assets/font-usage-scanner.js +242 -0
  31. package/lib/assets/image-optimizer.js +229 -0
  32. package/lib/assets/index.js +51 -0
  33. package/lib/assets/preload-generator.js +70 -0
  34. package/lib/assets/public-url.js +153 -0
  35. package/lib/block-authoring-help.js +11 -0
  36. package/lib/blocks/ast-parser.js +67 -0
  37. package/lib/blocks/discover-blocks.js +146 -0
  38. package/lib/blocks/editor-scope.js +733 -0
  39. package/lib/blocks/editor-transpiler.js +1229 -0
  40. package/lib/blocks/index.js +2838 -0
  41. package/lib/blocks/php-transpiler.js +4928 -0
  42. package/lib/blocks/scanner.js +1487 -0
  43. package/lib/blocks/shared-utils.js +290 -0
  44. package/lib/blocks/source-sanitize.js +1449 -0
  45. package/lib/blueprints.js +31 -91
  46. package/lib/build-assets.js +38 -33
  47. package/lib/collect-page-template-routes.js +102 -0
  48. package/lib/collect-static-routes.js +175 -0
  49. package/lib/diagnostics.js +58 -33
  50. package/lib/export-theme.js +84 -5
  51. package/lib/extract-template-content.js +90 -0
  52. package/lib/forms-preview.js +42 -0
  53. package/lib/functions/cpt-routing.js +69 -0
  54. package/lib/functions/forms.js +2461 -0
  55. package/lib/functions/hydration-enqueuer.js +400 -0
  56. package/lib/functions/index.js +1623 -0
  57. package/lib/functions/load-menus.js +112 -0
  58. package/lib/functions/load-translations.js +148 -0
  59. package/lib/functions/rest-endpoints.js +2923 -0
  60. package/lib/functions/routing.js +765 -0
  61. package/lib/functions/seed-mock-data.js +392 -0
  62. package/lib/functions/seed-products.js +481 -0
  63. package/lib/functions/settings-page.js +273 -0
  64. package/lib/functions/theme-setup.js +494 -0
  65. package/lib/generate-theme.js +1916 -339
  66. package/lib/hydration/editable-schemas.js +332 -0
  67. package/lib/hydration/enter-hidden-initial.js +65 -0
  68. package/lib/hydration/form-schemas.js +227 -0
  69. package/lib/hydration/index.js +12 -0
  70. package/lib/hydration/is-interactive.js +951 -0
  71. package/lib/hydration/island-split.js +1231 -0
  72. package/lib/hydration/islands-scanner.js +599 -0
  73. package/lib/hydration/resolve-island-chunk.js +103 -0
  74. package/lib/hydration/resolve-island-component.js +52 -0
  75. package/lib/hydration/rollup-inputs.js +81 -0
  76. package/lib/hydration/root-class-extractor.js +220 -0
  77. package/lib/hydration/scan-app-providers.js +154 -0
  78. package/lib/hydration/static-lint.js +382 -0
  79. package/lib/hydration/transform.js +257 -0
  80. package/lib/hydration/uses-block-area.js +49 -0
  81. package/lib/hydration/utils.js +119 -0
  82. package/lib/i18n/translation-cache.js +141 -0
  83. package/lib/icon-registry.js +72 -0
  84. package/lib/index.d.ts +287 -8
  85. package/lib/index.js +2 -1
  86. package/lib/load-config.js +338 -242
  87. package/lib/mail-templates.js +37 -0
  88. package/lib/markup-processor.js +388 -102
  89. package/lib/node-runtime.js +7 -0
  90. package/lib/page-config-plugin.js +64 -20
  91. package/lib/php-builders.js +383 -44
  92. package/lib/react-adapter.js +983 -235
  93. package/lib/registration-metadata.js +11 -0
  94. package/lib/render-theme.mts +1410 -616
  95. package/lib/route-layout.js +76 -0
  96. package/lib/template-discovery.js +58 -0
  97. package/lib/theme-compatibility.js +32 -0
  98. package/lib/validate-export.js +2 -2
  99. package/lib/validate.js +27 -5
  100. package/lib/virtual-plugin.js +319 -0
  101. package/lib/walkthrough.md +26 -0
  102. package/package.json +16 -5
  103. package/templates/auth/cms/email-logs.json +9 -0
  104. package/templates/auth/cms/menus.json +11 -0
  105. package/templates/auth/cms/mock-data.json +123 -0
  106. package/templates/auth/cms/roles.json +7 -0
  107. package/templates/auth/cms/sessions.json +1 -0
  108. package/templates/auth/cms/site-settings.json +28 -0
  109. package/templates/auth/cms/translations.json +4 -0
  110. package/templates/auth/cms/users.json +46 -0
  111. package/templates/auth/components/forgot-password-form-wrapper.tsx +10 -2
  112. package/templates/auth/components/login-form-wrapper.tsx +118 -21
  113. package/templates/auth/components/reset-password-form-wrapper.tsx +10 -2
  114. package/templates/auth/components/signup-form-wrapper.tsx +2 -2
  115. package/templates/auth/components/verify-email-view-wrapper.tsx +5 -5
  116. package/templates/auth/pages/DashboardPage.tsx +1 -4
  117. package/templates/auth/pages/ForgotPasswordPage.tsx +1 -4
  118. package/templates/auth/pages/LoginPage.tsx +1 -4
  119. package/templates/auth/pages/ResetPasswordPage.tsx +1 -4
  120. package/templates/auth/pages/SignUpPage.tsx +1 -4
  121. package/templates/auth/pages/VerifyEmailPage.tsx +1 -4
  122. package/templates/auth/ui/button.tsx +57 -0
  123. package/templates/auth/ui/card.tsx +76 -0
  124. package/templates/auth/ui/field.tsx +242 -0
  125. package/templates/auth/ui/input.tsx +22 -0
  126. package/templates/auth/ui/label.tsx +24 -0
  127. package/templates/auth/ui/separator.tsx +31 -0
  128. package/templates/menus.json +12 -10
  129. package/templates/users.json +8 -4
  130. package/templates/wordpress.tsx +690 -245
  131. package/lib/block-compiler.js +0 -552
  132. package/lib/functions-builder.js +0 -2970
  133. package/lib/hydration-scanner.js +0 -833
@@ -44,11 +44,16 @@ export function analyzeHydrationIslands(themeRoot, mapping) {
44
44
  * @param {{ heavyCount: number, results: any[] }} analysis
45
45
  */
46
46
  export function printDiagnosticsReport(analysis) {
47
- console.log(`\n🩺 ${pc.bold(pc.bgCyan(pc.black(" FORGEWP HYDRATION DIAGNOSTICS ")))}`);
48
-
47
+ if (process.env.FORGEWP_VERBOSE !== '1') return;
48
+ console.log(
49
+ `\n🩺 ${pc.bold(pc.bgCyan(pc.black(' FORGEWP HYDRATION DIAGNOSTICS ')))}`,
50
+ );
51
+
49
52
  if (analysis.results.length === 0) {
50
- console.log(` ${pc.dim("No active hydration islands detected in this project.")}`);
51
- console.log("─".repeat(60) + "\n");
53
+ console.log(
54
+ ` ${pc.dim('No active hydration islands detected in this project.')}`,
55
+ );
56
+ console.log('─'.repeat(60) + '\n');
52
57
  return;
53
58
  }
54
59
 
@@ -57,23 +62,37 @@ export function printDiagnosticsReport(analysis) {
57
62
  const formattedSize = `${item.sizeKb.toFixed(1)} kB`;
58
63
 
59
64
  if (item.isHeavy) {
60
- console.log(` ⚠️ ${pc.yellow(pc.bold(paddedName))} ${pc.red(pc.bold(formattedSize))} ${pc.bgRed(pc.black(" HEAVY "))}`);
61
- console.log(` ${pc.dim("👉 Chunk Path:")} dist/${item.chunkPath}`);
62
- console.log(` ${pc.dim("👉 Recommendations:")}`);
63
- console.log(` 1. Split static markup sections out of the component into static wrappers.`);
64
- console.log(` 2. Avoid heavy external packages inside the island (or lazy load them inside React).`);
65
- console.log(` 3. Switch to a non-blocking trigger strategy (e.g. trigger="interaction" or trigger="idle").`);
65
+ console.log(
66
+ ` ⚠️ ${pc.yellow(pc.bold(paddedName))} ${pc.red(pc.bold(formattedSize))} ${pc.bgRed(pc.black(' HEAVY '))}`,
67
+ );
68
+ console.log(` ${pc.dim('👉 Chunk Path:')} dist/${item.chunkPath}`);
69
+ console.log(` ${pc.dim('👉 Recommendations:')}`);
70
+ console.log(
71
+ ` 1. Split static markup sections out of the component into static wrappers.`,
72
+ );
73
+ console.log(
74
+ ` 2. Avoid heavy external packages inside the island (or lazy load them inside React).`,
75
+ );
76
+ console.log(
77
+ ` 3. Switch to a non-blocking trigger strategy (e.g. trigger="interaction" or trigger="idle").`,
78
+ );
66
79
  } else {
67
80
  console.log(` ✅ ${pc.green(paddedName)} ${pc.green(formattedSize)}`);
68
81
  }
69
82
  }
70
83
 
71
- console.log("─".repeat(60));
84
+ console.log('─'.repeat(60));
72
85
  if (analysis.heavyCount > 0) {
73
- console.log(` ${pc.red(pc.bold("WARNING:"))} Found ${analysis.heavyCount} heavy interactive hydration island(s).`);
74
- console.log(` 💡 Keep JS bundles light. Modern Web Vitals rewards minimal runtime overhead!\n`);
86
+ console.log(
87
+ ` ${pc.red(pc.bold('WARNING:'))} Found ${analysis.heavyCount} heavy interactive hydration island(s).`,
88
+ );
89
+ console.log(
90
+ ` 💡 Keep JS bundles light. Modern Web Vitals rewards minimal runtime overhead!\n`,
91
+ );
75
92
  } else {
76
- console.log(` ${pc.green(pc.bold("SYSTEM OPTIMIZED:"))} All interactive hydration islands are within healthy thresholds (<100 kB).\n`);
93
+ console.log(
94
+ ` ${pc.green(pc.bold('SYSTEM OPTIMIZED:'))} All interactive hydration islands are within healthy thresholds (<100 kB).\n`,
95
+ );
77
96
  }
78
97
  }
79
98
 
@@ -85,7 +104,12 @@ export function printDiagnosticsReport(analysis) {
85
104
  * @param {any} config
86
105
  * @returns {string} Path to the generated report
87
106
  */
88
- export function generateVisualReport(themeRoot, analysis, islandsWithProps, config) {
107
+ export function generateVisualReport(
108
+ themeRoot,
109
+ analysis,
110
+ islandsWithProps,
111
+ config,
112
+ ) {
89
113
  const islands = islandsWithProps.map((item) => {
90
114
  const analysisMatch = analysis.results.find((a) => a.name === item.name);
91
115
  return {
@@ -100,13 +124,13 @@ export function generateVisualReport(themeRoot, analysis, islandsWithProps, conf
100
124
  // Calculate dynamic performance score
101
125
  let score = 100;
102
126
  let totalJsKb = 0;
103
-
127
+
104
128
  for (const island of islands) {
105
129
  totalJsKb += island.sizeKb;
106
130
  if (island.isHeavy) {
107
131
  score -= 15;
108
132
  }
109
- if (island.trigger === "load") {
133
+ if (island.trigger === 'load') {
110
134
  score -= 10;
111
135
  }
112
136
  if (island.smartDiscovered) {
@@ -116,25 +140,25 @@ export function generateVisualReport(themeRoot, analysis, islandsWithProps, conf
116
140
 
117
141
  const violations = analysis.violations || [];
118
142
  for (const v of violations) {
119
- if (v.type === "metadata") score -= 5;
120
- else if (v.type === "loop") score -= 15;
121
- else if (v.type === "url") score -= 3;
143
+ if (v.type === 'metadata') score -= 5;
144
+ else if (v.type === 'loop') score -= 15;
145
+ else if (v.type === 'url') score -= 3;
122
146
  }
123
147
 
124
148
  score -= Math.floor(totalJsKb / 10);
125
149
  score = Math.max(10, Math.min(100, score));
126
150
 
127
- let grade = "F";
128
- if (score >= 90) grade = "A";
129
- else if (score >= 80) grade = "B";
130
- else if (score >= 70) grade = "C";
131
- else if (score >= 60) grade = "D";
151
+ let grade = 'F';
152
+ if (score >= 90) grade = 'A';
153
+ else if (score >= 80) grade = 'B';
154
+ else if (score >= 70) grade = 'C';
155
+ else if (score >= 60) grade = 'D';
132
156
 
133
157
  const payload = {
134
158
  config: {
135
- name: config.name || "Unknown Theme",
136
- slug: config.slug || "unknown",
137
- version: config.version || "1.0.0",
159
+ name: config.name || 'Unknown Theme',
160
+ slug: config.slug || 'unknown',
161
+ version: config.version || '1.0.0',
138
162
  },
139
163
  score,
140
164
  grade,
@@ -142,15 +166,17 @@ export function generateVisualReport(themeRoot, analysis, islandsWithProps, conf
142
166
  violations,
143
167
  };
144
168
 
145
- const outDir = path.join(themeRoot, ".forgewp", "analyzer");
169
+ const outDir = path.join(themeRoot, '.forgewp', 'analyzer');
146
170
  if (!fs.existsSync(outDir)) {
147
171
  fs.mkdirSync(outDir, { recursive: true });
148
172
  }
149
173
 
150
- const htmlContent = ANALYZER_TEMPLATE.replace("__DATA_PLACEHOLDER__", () => JSON.stringify(payload));
174
+ const htmlContent = ANALYZER_TEMPLATE.replace('__DATA_PLACEHOLDER__', () =>
175
+ JSON.stringify(payload),
176
+ );
151
177
 
152
- const reportPath = path.join(outDir, "index.html");
153
- fs.writeFileSync(reportPath, htmlContent, "utf8");
178
+ const reportPath = path.join(outDir, 'index.html');
179
+ fs.writeFileSync(reportPath, htmlContent, 'utf8');
154
180
 
155
181
  return reportPath;
156
182
  }
@@ -795,4 +821,3 @@ const ANALYZER_TEMPLATE = `<!DOCTYPE html>
795
821
  </script>
796
822
  </body>
797
823
  </html>`;
798
-
@@ -1,4 +1,5 @@
1
1
  import path from 'node:path';
2
+ import { existsSync, mkdirSync, rmSync } from 'node:fs';
2
3
  import pc from 'picocolors';
3
4
  import { buildAssets } from './build-assets.js';
4
5
  import { generateTheme } from './generate-theme.js';
@@ -8,20 +9,48 @@ import { assertZipCreated, zipTheme } from './zip-theme.js';
8
9
 
9
10
  import { validateCriticalFiles } from './validate.js';
10
11
  import { validateExport } from './validate-export.js';
12
+ import { scanAndGenerateBlocks } from './blocks/index.js';
13
+ import { splitInteractiveIslands } from './hydration/island-split.js';
14
+ import {
15
+ scanAssetGraph,
16
+ runAssetPipeline,
17
+ orchestrateFonts,
18
+ generateAssetManifest,
19
+ printAssetDiagnosticsReport,
20
+ } from './assets/index.js';
11
21
 
12
22
  /**
13
23
  * @param {Object} options
14
24
  * @param {string} options.themeRoot
15
25
  * @param {boolean} [options.skipBuild]
16
26
  * @param {boolean} [options.zip]
27
+ * @param {boolean} [options.validate]
28
+ * @param {boolean} [options.strict] Treat editable from/pick issues (and --validate warnings) as failures
17
29
  * @param {string} [options.packageManager]
30
+ * @param {(progress: { stage: string, message: string }) => void} [options.onProgress]
18
31
  */
19
32
  export async function exportTheme(options) {
20
33
  const themeRoot = path.resolve(options.themeRoot);
34
+ const strict = !!options.strict;
35
+ const verbose = process.env.FORGEWP_VERBOSE === '1';
21
36
 
22
37
  // Run Preflight Safeguards and Self-Healing checks
23
38
  validateCriticalFiles(themeRoot);
24
39
 
40
+ // Auto-split components mixing static/attribute-driven content with genuine
41
+ // interactivity into a static shell + extracted islands, before anything
42
+ // below (block wrapper generation, Vite's Rollup entry resolution) reads
43
+ // component source or decides what needs a hydration bundle.
44
+ splitInteractiveIslands(themeRoot);
45
+
46
+ // Pre-scaffold block wrappers so Vite receives them in Rollup inputs.
47
+ // Defer editable-issue flush to compileBlocks (generateTheme) so --strict applies once.
48
+ scanAndGenerateBlocks(themeRoot, {
49
+ strict: false,
50
+ resetIssues: true,
51
+ flush: false,
52
+ });
53
+
25
54
  const config = await loadConfig(themeRoot);
26
55
 
27
56
  function report(stage, message, level = 'dim') {
@@ -42,7 +71,9 @@ export async function exportTheme(options) {
42
71
  : level === 'green'
43
72
  ? pc.green
44
73
  : pc.white;
45
- console.log(fn(` ${message}`));
74
+ if (!options.onProgress) {
75
+ console.log(fn(` ${message}`));
76
+ }
46
77
  }
47
78
 
48
79
  console.log(pc.cyan(`\n ForgeWP export — ${config.name}\n`));
@@ -55,13 +86,50 @@ export async function exportTheme(options) {
55
86
  );
56
87
  const assets = options.skipBuild
57
88
  ? (await import('./build-assets.js')).readBuildManifest(themeRoot)
58
- : buildAssets(themeRoot, { packageManager: options.packageManager });
89
+ : buildAssets(themeRoot, {
90
+ packageManager: options.packageManager,
91
+ verbose,
92
+ });
59
93
 
60
- report('render', `Rendering ${config.frameworkAdapter || 'React'} app to static HTML…`);
94
+ report(
95
+ 'render',
96
+ `Rendering ${config.frameworkAdapter || 'React'} app to static HTML…`,
97
+ );
61
98
  const markup = await renderStaticMarkup(themeRoot, config.frameworkAdapter);
62
99
 
63
100
  const outDir = path.join(themeRoot, '.forgewp', 'out', config.slug);
64
101
  const zipPath = path.join(themeRoot, '.forgewp', `${config.slug}.zip`);
102
+ if (existsSync(outDir)) {
103
+ rmSync(outDir, { recursive: true, force: true });
104
+ }
105
+ mkdirSync(outDir, { recursive: true });
106
+
107
+ // Generate image variants before rendering markup so srcset and preload URLs match.
108
+ report('assets', 'Optimizing static image assets with Sharp…');
109
+ const assetGraph = scanAssetGraph(themeRoot);
110
+ const assetResults = await runAssetPipeline(themeRoot, assetGraph, {
111
+ outDir,
112
+ quality: config.assets?.images?.quality || 80,
113
+ });
114
+ if (assetResults.processedCount > 0) {
115
+ report(
116
+ 'assets-done',
117
+ `Optimized ${assetResults.processedCount} image(s) (${assetResults.totalVariants} responsive WebP variants generated, ${assetResults.cachedCount} cached)`,
118
+ 'green',
119
+ );
120
+ }
121
+
122
+ // Web Font Orchestration (self-host WOFF2 with local @font-face)
123
+ const fontResults = await orchestrateFonts(themeRoot, config, assetGraph, {
124
+ outDir,
125
+ });
126
+ if (fontResults.strategy === 'self-host' && fontResults.downloadedCount > 0) {
127
+ report(
128
+ 'fonts-done',
129
+ `Self-hosted ${fontResults.downloadedCount} WOFF2 font file(s) in assets/fonts/ with local @font-face`,
130
+ 'green',
131
+ );
132
+ }
65
133
 
66
134
  report('generate', 'Generating WordPress theme files…');
67
135
  await generateTheme({
@@ -73,11 +141,22 @@ export async function exportTheme(options) {
73
141
  footerHtml: markup.footerHtml,
74
142
  headHtml: markup.headHtml,
75
143
  singleHeadHtml: markup.singleHeadHtml,
76
- singleHtml: markup.singleHtml,
77
144
  notFoundHtml: markup.notFoundHtml,
78
145
  archiveHtml: markup.archiveHtml,
146
+ singleHtml: markup.singleHtml,
79
147
  assets,
148
+ assetGraph,
149
+ preserveOutDir: true,
150
+ strict,
151
+ });
152
+
153
+ // Asset Manifest & Performance Diagnostics CLI Report
154
+ const assetManifest = generateAssetManifest(themeRoot, assetGraph, {
155
+ outDir,
156
+ config,
157
+ fontRules: fontResults.enrichedRules || [],
80
158
  });
159
+ printAssetDiagnosticsReport(assetManifest);
81
160
 
82
161
  // Optional export validation
83
162
  if (options.validate) {
@@ -87,7 +166,7 @@ export async function exportTheme(options) {
87
166
  outDir,
88
167
  assets,
89
168
  config,
90
- strict: !!options.strict,
169
+ strict,
91
170
  });
92
171
 
93
172
  if (validation.warnings && validation.warnings.length > 0) {
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Pull the page body out of an SSR document.
3
+ *
4
+ * Default layouts contribute a shared header/footer, so the template keeps
5
+ * the layout `<main>`'s children. A page that owns its document (blank
6
+ * layout) rendered the shell itself — splitting it drops the client tree
7
+ * that ties the shell to the page (scroll state, enter animations, refs).
8
+ *
9
+ * A page component may itself root at `<main>`. A non-greedy match stops at
10
+ * that inner closer, leaves the page island unclosed, and the shared footer
11
+ * is then parsed as a child of the island. Hydration replaces the island's
12
+ * children with the page component, which does not render the layout footer.
13
+ *
14
+ * @param {string} markup
15
+ * @param {string} [header]
16
+ * @param {string} [footer]
17
+ * @param {{ ownsShell?: boolean }} [options]
18
+ * @returns {string}
19
+ */
20
+ export function extractTemplateContent(markup, header, footer, options = {}) {
21
+ if (!markup) return '';
22
+ const ownsShell =
23
+ options.ownsShell === true ||
24
+ /<forgewp-content-boundary\b[^>]*\bdata-forgewp-owns-shell="true"/.test(
25
+ markup,
26
+ );
27
+ const boundaryMatch = markup.match(
28
+ /<forgewp-content-boundary\b[^>]*>([\s\S]*?)<\/forgewp-content-boundary>/i,
29
+ );
30
+ let res = boundaryMatch ? boundaryMatch[1] : markup;
31
+
32
+ if (ownsShell) return res;
33
+
34
+ const main = findBalancedElement(res, 'main');
35
+ if (main) {
36
+ const outside = res.slice(0, main.openIndex) + res.slice(main.closeEnd);
37
+ // Header/footer beside <main> are the shared layout shell. Take the
38
+ // balanced children so a nested page <main> stays closed. A <main> with
39
+ // no shell beside it is the page itself — keep its island wrapper.
40
+ if (/<(header|footer)\b/i.test(outside)) return main.inner;
41
+ return res;
42
+ }
43
+
44
+ if (header) {
45
+ const replaced = res.replace(header, '');
46
+ res =
47
+ replaced !== res
48
+ ? replaced
49
+ : res.replace(/<header\b[^>]*>([\s\S]*?)<\/header>/i, '');
50
+ }
51
+ if (footer) {
52
+ const replaced = res.replace(footer, '');
53
+ res =
54
+ replaced !== res
55
+ ? replaced
56
+ : res.replace(/<footer\b[^>]*>([\s\S]*?)<\/footer>/i, '');
57
+ }
58
+ return res;
59
+ }
60
+
61
+ /**
62
+ * First balanced element named `tag`, including nested copies of that tag.
63
+ * @param {string} html
64
+ * @param {string} tag
65
+ * @returns {{ openIndex: number, openEnd: number, closeIndex: number, closeEnd: number, inner: string } | null}
66
+ */
67
+ function findBalancedElement(html, tag) {
68
+ const openRe = new RegExp(`<${tag}\\b[^>]*>`, 'i');
69
+ const open = openRe.exec(html);
70
+ if (!open) return null;
71
+ const tokenRe = new RegExp(`<(/?)${tag}\\b[^>]*>`, 'gi');
72
+ tokenRe.lastIndex = open.index;
73
+ let depth = 0;
74
+ let match;
75
+ while ((match = tokenRe.exec(html))) {
76
+ if (match[0].endsWith('/>')) continue;
77
+ depth += match[1] === '/' ? -1 : 1;
78
+ if (depth === 0) {
79
+ const openEnd = open.index + open[0].length;
80
+ return {
81
+ openIndex: open.index,
82
+ openEnd,
83
+ closeIndex: match.index,
84
+ closeEnd: match.index + match[0].length,
85
+ inner: html.slice(openEnd, match.index),
86
+ };
87
+ }
88
+ }
89
+ return null;
90
+ }
@@ -0,0 +1,42 @@
1
+ // Only public field descriptors cross into the local browser runtime.
2
+ export function buildFormsPreviewData(config) {
3
+ const types = new Set(['text', 'email', 'tel', 'number', 'textarea', 'select', 'checkbox']);
4
+ const fields = (seed) => Array.isArray(seed) ? seed.filter((field) => field && typeof field.name === 'string' && types.has(field.type)).map((field) => ({
5
+ name: field.name,
6
+ label: typeof field.label === 'string' ? field.label : field.name,
7
+ type: field.type,
8
+ required: field.required === true,
9
+ ...(Array.isArray(field.options) ? { options: field.options.filter((option) => typeof option === 'string') } : {}),
10
+ ...(typeof field.placeholder === 'string' ? { placeholder: field.placeholder } : {}),
11
+ })) : [];
12
+ const forms = Object.create(null);
13
+ const validation = Object.create(null);
14
+ for (const [name, form] of Object.entries(config.forms || {})) {
15
+ const seed = form?.clientFields?.enabled ? form.clientFields.seed : [];
16
+ forms[name] = Array.isArray(seed) ? fields(seed) : Object.fromEntries(Object.entries(seed || {}).map(([locale, entries]) => [locale, fields(entries)]));
17
+ if (form.mode !== 'shortcode') {
18
+ validation[name] = fields(Object.entries(form.fields || {}).map(([fieldName, field]) => ({ ...field, name: fieldName })));
19
+ }
20
+ }
21
+ return { forms, validation, locales: config.i18n?.locales || [], defaultLocale: config.i18n?.defaultLocale || config.i18n?.locales?.[0] || '' };
22
+ }
23
+
24
+ // Kept self-contained so its exact source can be installed by the virtual module.
25
+ function installFormsPreview(win, data) {
26
+ const forms = Object.create(null);
27
+ for (const [name, seed] of Object.entries(data.forms)) {
28
+ forms[name] = { get fields() {
29
+ if (Array.isArray(seed)) return seed;
30
+ const segment = win.location?.pathname?.split('/')[1] || '';
31
+ const locale = data.locales.includes(segment) ? segment : data.defaultLocale;
32
+ return seed[locale] || [];
33
+ }, get validationFields() {
34
+ return Object.prototype.hasOwnProperty.call(data.validation, name) ? [...data.validation[name], ...this.fields] : undefined;
35
+ } };
36
+ }
37
+ win._forgeWpMockForms = forms;
38
+ }
39
+
40
+ export function formsPreviewScript(data) {
41
+ return `(${installFormsPreview.toString()})(window, ${JSON.stringify(data)});`;
42
+ }
@@ -0,0 +1,69 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ export function validateCptRewrite(value, key) {
4
+ if (value === undefined || value === false) return;
5
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
6
+ throw new Error(`postTypes.${key}.rewrite must be false or an object`);
7
+ }
8
+ if (value.slug !== undefined && (typeof value.slug !== 'string' || !value.slug.trim() || /[?#\\\r\n]/.test(value.slug) || value.slug.includes('://'))) {
9
+ throw new Error(`postTypes.${key}.rewrite.slug must be a nonempty path without a query, fragment, or URL origin`);
10
+ }
11
+ if (value.withFront !== undefined && typeof value.withFront !== 'boolean') {
12
+ throw new Error(`postTypes.${key}.rewrite.withFront must be a boolean`);
13
+ }
14
+ }
15
+
16
+ export function effectiveCptRouting(config, postTypes) {
17
+ return [...new Set(postTypes)].sort().map((postType) => {
18
+ const entry = config.postTypes?.[postType] || {};
19
+ validateCptRewrite(entry.rewrite, postType);
20
+ return {
21
+ postType,
22
+ public: entry.public !== false,
23
+ hasArchive: entry.hasArchive !== false,
24
+ rewrite: entry.rewrite === false ? false : {
25
+ slug: entry.rewrite?.slug || postType,
26
+ withFront: entry.rewrite?.withFront !== false,
27
+ },
28
+ };
29
+ });
30
+ }
31
+
32
+ export function collectCptRouteDiagnostics(config, postTypes, pages = []) {
33
+ const normalize = (value) => String(value).replace(/^\/+|\/+$/g, '').replace(/\/+/g, '/');
34
+ const pagePaths = new Set(pages.map((page) => normalize(page.slug)).filter(Boolean));
35
+ const diagnostics = [];
36
+ for (const rule of effectiveCptRouting(config, postTypes)) {
37
+ const configured = config.postTypes?.[rule.postType];
38
+ if (configured?.rewrite !== undefined || configured?.hasArchive !== undefined) {
39
+ diagnostics.push({ level: 'info', postType: rule.postType, message:
40
+ `CPT "${rule.postType}": ${rule.rewrite === false ? 'pretty rewrites disabled' : `base /${normalize(rule.rewrite.slug)}; archive ${rule.hasArchive ? 'enabled' : 'disabled'}${rule.rewrite.withFront ? ' (site permalink front may prepend this base)' : ''}`}. If this changes installed URLs, review redirects; export does not create redirects or delete saved Pages.` });
41
+ }
42
+ // WordPress can add archive rewrite rules even for a non-public type.
43
+ if (!rule.hasArchive || rule.rewrite === false) continue;
44
+ const archive = normalize(rule.rewrite.slug);
45
+ if (pagePaths.has(archive)) diagnostics.push({ level: 'warning', postType: rule.postType, message:
46
+ `Potential route collision: CPT "${rule.postType}" archive /${archive} also names a configured Page route. Give them separate paths, or set postTypes.${rule.postType}.hasArchive: false if the Page should own that path. Check the site's permalink front and any plugin-owned registration on WordPress; the exporter cannot inspect them.` });
47
+ }
48
+ return diagnostics;
49
+ }
50
+
51
+ export function buildCptRewriteRefreshPhp(config, postTypes) {
52
+ const signature = createHash('sha256').update(JSON.stringify(effectiveCptRouting(config, postTypes))).digest('hex');
53
+ const domain = String(config.textDomain || 'theme').replace(/[^a-zA-Z0-9_]/g, '_');
54
+ const option = `forgewp_${domain}_cpt_rewrite_signature`;
55
+ const fn = `forgewp_flush_${domain}_cpt_rewrite_rules`;
56
+ // Always keep the comparison hook: removing the final CPT/rewrite setting must
57
+ // invalidate the previous signature too. An unchanged signature is a no-op.
58
+ return `
59
+ function ${fn}() {
60
+ $signature = '${signature}';
61
+ if (get_option('${option}') === $signature) {
62
+ return;
63
+ }
64
+ flush_rewrite_rules(false);
65
+ update_option('${option}', $signature, false);
66
+ }
67
+ add_action('init', '${fn}', 99);
68
+ `;
69
+ }