@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
@@ -0,0 +1,599 @@
1
+ import { readFileSync, readdirSync, existsSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import {
4
+ isComponentInteractive,
5
+ getInteractiveExportNames,
6
+ readComponentSource,
7
+ } from './is-interactive.js';
8
+ import { getComponentRootClassName } from './root-class-extractor.js';
9
+
10
+ /** True when `content` contains a JSX opening/self-closing tag for `tagName`. */
11
+ function sourceUsesJsxTag(content, tagName) {
12
+ if (!content || !tagName) return false;
13
+ return new RegExp(`<${tagName}(?=[\\s/>])`).test(content);
14
+ }
15
+
16
+ function toKebabName(exportName) {
17
+ return exportName
18
+ .replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')
19
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
20
+ .toLowerCase();
21
+ }
22
+
23
+ // scanForHydrationIslands/scanForHydrationIslandsWithProps both run from
24
+ // several integration points within one `forgewp export` (vite.config.ts's
25
+ // config-load-time getHydrationRollupInputs call, the Vite plugin's
26
+ // buildStart, etc.) — without deduping, the same "detected X" line would
27
+ // print once per integration point. Tracked per-process (not per-call) so
28
+ // each discovery is announced once no matter how many call sites trigger it;
29
+ // full per-item detail is behind FORGEWP_VERBOSE=1, matching island-split.js's
30
+ // convention.
31
+ const smartDiscoveryReportedOnce = new Set();
32
+
33
+ function reportSmartDiscovery(key, verboseMessage) {
34
+ if (smartDiscoveryReportedOnce.has(key)) return false;
35
+ smartDiscoveryReportedOnce.add(key);
36
+ if (process.env.FORGEWP_VERBOSE) {
37
+ console.warn(verboseMessage);
38
+ }
39
+ return true;
40
+ }
41
+
42
+ /**
43
+ * Searches components directories for a file matching the kebab-case component name.
44
+ *
45
+ * @param {string} themeRoot - The absolute path of the theme's root directory.
46
+ * @param {string} kebabName - The target component's kebab-case identifier.
47
+ * @returns {string|null} The absolute path to the component file, or null if not found.
48
+ */
49
+ export function findComponentPath(themeRoot, kebabName) {
50
+ const compDir = path.join(themeRoot, 'src', 'components');
51
+ const appDir = path.join(themeRoot, 'src', 'app');
52
+ const blocksDir = path.join(themeRoot, 'src', 'blocks');
53
+
54
+ // Convert kebab-case back to PascalCase and check candidates
55
+ const pascalName = kebabName
56
+ .split('-')
57
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
58
+ .join('');
59
+
60
+ const candidates = [
61
+ `${pascalName}.tsx`,
62
+ `${pascalName}.ts`,
63
+ `${kebabName}.tsx`,
64
+ `${kebabName}.ts`,
65
+ ];
66
+
67
+ const cleanKebab = kebabName.replace(/[-_]/g, '').toLowerCase();
68
+ const fileExtRegex = /\.(tsx|ts|jsx|js)$/;
69
+
70
+ let result = null;
71
+
72
+ function searchRecursive(dir) {
73
+ if (result || !existsSync(dir)) return;
74
+ try {
75
+ const items = readdirSync(dir, { withFileTypes: true });
76
+ for (const item of items) {
77
+ const fullPath = path.join(dir, item.name);
78
+ if (item.isDirectory()) {
79
+ searchRecursive(fullPath);
80
+ } else if (item.isFile()) {
81
+ if (candidates.includes(item.name)) {
82
+ result = fullPath;
83
+ return;
84
+ }
85
+ if (fileExtRegex.test(item.name)) {
86
+ const base = item.name
87
+ .replace(fileExtRegex, '')
88
+ .replace(/[-_]/g, '')
89
+ .toLowerCase();
90
+ if (base === cleanKebab) {
91
+ result = fullPath;
92
+ return;
93
+ }
94
+ }
95
+ }
96
+ }
97
+ } catch {}
98
+ }
99
+
100
+ searchRecursive(compDir);
101
+ if (result) return result;
102
+
103
+ // Special cases for page templates
104
+ if (
105
+ kebabName === 'page' ||
106
+ kebabName === 'layout' ||
107
+ kebabName === '404' ||
108
+ kebabName === 'single' ||
109
+ kebabName === 'archive'
110
+ ) {
111
+ const pagePath = path.join(appDir, `${kebabName}.tsx`);
112
+ if (existsSync(pagePath)) return pagePath;
113
+ const tsPath = path.join(appDir, `${kebabName}.ts`);
114
+ if (existsSync(tsPath)) return tsPath;
115
+ }
116
+
117
+ searchRecursive(appDir);
118
+ if (result) return result;
119
+
120
+ searchRecursive(blocksDir);
121
+ if (result) return result;
122
+
123
+ // Pass 2: Search for named exports if no matching filename was found
124
+ function searchNamedExports(dir) {
125
+ if (result || !existsSync(dir)) return;
126
+ try {
127
+ const items = readdirSync(dir, { withFileTypes: true });
128
+ for (const item of items) {
129
+ const fullPath = path.join(dir, item.name);
130
+ if (item.isDirectory()) {
131
+ searchNamedExports(fullPath);
132
+ } else if (
133
+ item.isFile() &&
134
+ (item.name.endsWith('.tsx') || item.name.endsWith('.ts'))
135
+ ) {
136
+ try {
137
+ const content = readFileSync(fullPath, 'utf8');
138
+ const hasExport =
139
+ content.includes(`export function ${pascalName}`) ||
140
+ content.includes(`export const ${pascalName}`) ||
141
+ new RegExp(`\\bexport\\s*\\{[^}]*\\b${pascalName}\\b`).test(
142
+ content,
143
+ );
144
+ if (hasExport) {
145
+ result = fullPath;
146
+ return;
147
+ }
148
+ } catch {}
149
+ }
150
+ }
151
+ } catch {}
152
+ }
153
+
154
+ searchNamedExports(compDir);
155
+ if (result) return result;
156
+
157
+ searchNamedExports(appDir);
158
+ if (result) return result;
159
+
160
+ searchNamedExports(blocksDir);
161
+ return result;
162
+ }
163
+
164
+ /**
165
+ * Scans the theme's page files (page.tsx, layout.tsx, pages/*.tsx)
166
+ * for <Hydrate> boundaries and extracts their resolved kebab-case component names.
167
+ *
168
+ * @param {string} themeRoot - The absolute path of the theme's root directory.
169
+ * @returns {string[]} An array of discovered kebab-case hydration chunk identifiers.
170
+ */
171
+ export function scanForHydrationIslands(themeRoot) {
172
+ const islands = new Set();
173
+ const filesToScan = [];
174
+ let newDiscoveries = 0;
175
+
176
+ const dirsToScan = [
177
+ path.join(themeRoot, 'src', 'app'),
178
+ path.join(themeRoot, 'src', 'components'),
179
+ path.join(themeRoot, 'src', 'blocks'),
180
+ ];
181
+
182
+ function collectFilesRecursive(dir) {
183
+ if (!existsSync(dir)) return;
184
+ try {
185
+ const items = readdirSync(dir, { withFileTypes: true });
186
+ for (const item of items) {
187
+ const fullPath = path.join(dir, item.name);
188
+ if (item.isDirectory()) {
189
+ collectFilesRecursive(fullPath);
190
+ } else if (
191
+ item.isFile() &&
192
+ (item.name.endsWith('.tsx') || item.name.endsWith('.ts'))
193
+ ) {
194
+ filesToScan.push(fullPath);
195
+ }
196
+ }
197
+ } catch {}
198
+ }
199
+
200
+ for (const dir of dirsToScan) {
201
+ collectFilesRecursive(dir);
202
+ }
203
+
204
+ // Scan each file for <Hydrate> occurrences
205
+ for (const filePath of filesToScan) {
206
+ try {
207
+ // readComponentSource (not raw readFileSync): a file's on-disk content
208
+ // may have been auto-split, in which case the shell's rewritten source
209
+ // (referencing the extracted island components by tag name) — not the
210
+ // dev's original, unmodified content — is what actually determines
211
+ // which components need their own hydration bundle.
212
+ const content = readComponentSource(filePath);
213
+
214
+ // Matches <Hydrate ...> ... </Hydrate>
215
+ const hydrateRegex = /<Hydrate\b([\s\S]*?)>([\s\S]*?)<\/Hydrate>/g;
216
+ let match;
217
+ while ((match = hydrateRegex.exec(content)) !== null) {
218
+ const propsStr = match[1];
219
+ const childrenStr = match[2].trim();
220
+
221
+ // 1. Try to parse explicit 'id' attribute
222
+ const idMatch = propsStr.match(/id\s*=\s*["']([^"']*)["']/);
223
+ if (idMatch) {
224
+ islands.add(idMatch[1]);
225
+ continue;
226
+ }
227
+
228
+ // 2. Fallback: Parse Component Tag name from children (e.g. <FadeUpSection />)
229
+ const componentTagMatch = childrenStr.match(/<([A-Z][a-zA-Z0-9]*)\b/);
230
+ if (componentTagMatch) {
231
+ const compName = componentTagMatch[1];
232
+ const kebabName = compName
233
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
234
+ .toLowerCase();
235
+ islands.add(kebabName);
236
+ }
237
+ }
238
+ } catch (err) {
239
+ console.warn(
240
+ `[Hydration Scanner] Failed to scan file ${filePath}:`,
241
+ err.message,
242
+ );
243
+ }
244
+ }
245
+
246
+ // 3. Smart Component Discovery: scan src/components/ for interactive exports
247
+ // (per-export, not per-file — a file that also exports a static helper must
248
+ // not force that helper into a client island).
249
+ const interactiveExports = new Map(); // PascalCase export name -> file path
250
+
251
+ function scanComponentsRecursive(dir) {
252
+ if (!existsSync(dir)) return;
253
+ try {
254
+ const items = readdirSync(dir, { withFileTypes: true });
255
+ for (const item of items) {
256
+ const fullPath = path.join(dir, item.name);
257
+ if (item.isDirectory()) {
258
+ scanComponentsRecursive(fullPath);
259
+ } else if (
260
+ item.isFile() &&
261
+ (item.name.endsWith('.tsx') || item.name.endsWith('.ts'))
262
+ ) {
263
+ try {
264
+ for (const exportName of getInteractiveExportNames(fullPath)) {
265
+ interactiveExports.set(exportName, fullPath);
266
+ }
267
+ } catch {}
268
+ }
269
+ }
270
+ } catch {}
271
+ }
272
+
273
+ const componentDirs = [
274
+ path.join(themeRoot, 'src', 'components'),
275
+ path.join(themeRoot, 'src', 'app', 'components'),
276
+ ];
277
+ for (const componentDir of componentDirs) {
278
+ scanComponentsRecursive(componentDir);
279
+ }
280
+
281
+ for (const filePath of filesToScan) {
282
+ try {
283
+ // readComponentSource (not raw readFileSync): a file's on-disk content
284
+ // may have been auto-split, in which case the shell's rewritten source
285
+ // (referencing the extracted island components by tag name) — not the
286
+ // dev's original, unmodified content — is what actually determines
287
+ // which components need their own hydration bundle.
288
+ const content = readComponentSource(filePath);
289
+ for (const exportName of interactiveExports.keys()) {
290
+ if (sourceUsesJsxTag(content, exportName)) {
291
+ const kebabName = toKebabName(exportName);
292
+ if (!islands.has(kebabName)) {
293
+ islands.add(kebabName);
294
+ if (
295
+ reportSmartDiscovery(
296
+ `component:${kebabName}`,
297
+ `\x1b[33m[ForgeWP Optimizer] Smart Discovery: Detected "${exportName}" uses interactive hooks/animations. Auto-enforcing code-splitting chunk. Wrap it in <Hydrate> in page markup for dynamic browser activation!\x1b[0m`,
298
+ )
299
+ )
300
+ newDiscoveries++;
301
+ }
302
+ }
303
+ }
304
+ } catch {}
305
+ }
306
+
307
+ // 4. Smart Page Hydration: if a page file itself is interactive, register it directly
308
+ const pageDirs = [
309
+ path.join(themeRoot, 'src', 'app'),
310
+ path.join(themeRoot, 'src', 'app', 'pages'),
311
+ ];
312
+ for (const pDir of pageDirs) {
313
+ if (existsSync(pDir)) {
314
+ try {
315
+ const items = readdirSync(pDir, { withFileTypes: true });
316
+ for (const item of items) {
317
+ if (
318
+ item.isFile() &&
319
+ (item.name.endsWith('.tsx') || item.name.endsWith('.ts'))
320
+ ) {
321
+ const fullPath = path.join(pDir, item.name);
322
+ if (isComponentInteractive(fullPath)) {
323
+ const compName = path.basename(
324
+ item.name,
325
+ path.extname(item.name),
326
+ );
327
+ const kebabName = compName
328
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
329
+ .toLowerCase();
330
+ if (!islands.has(kebabName)) {
331
+ islands.add(kebabName);
332
+ if (
333
+ reportSmartDiscovery(
334
+ `page:${kebabName}`,
335
+ `\x1b[33m[ForgeWP Optimizer] Smart Discovery: Detected interactive page file "${compName}". Auto-enforcing page hydration island!\x1b[0m`,
336
+ )
337
+ )
338
+ newDiscoveries++;
339
+ }
340
+ }
341
+ }
342
+ }
343
+ } catch {}
344
+ }
345
+ }
346
+
347
+ if (newDiscoveries > 0 && process.env.FORGEWP_VERBOSE === '1') {
348
+ console.warn(
349
+ `\x1b[33m[ForgeWP Optimizer] Smart Discovery: auto-enforced code-splitting for ${newDiscoveries} interactive component(s)/page(s) — set FORGEWP_VERBOSE=1 to see which.\x1b[0m`,
350
+ );
351
+ }
352
+
353
+ return Array.from(islands);
354
+ }
355
+
356
+ /**
357
+ * Scans theme pages and layout files for <Hydrate> boundaries and extracts their kebab-case names,
358
+ * source files, and defined properties.
359
+ *
360
+ * @param {string} themeRoot - The absolute path of the theme's root directory.
361
+ * @returns {Array<{ name: string, file: string, trigger: string, preload: string, media: string|null, connection: string|null, clientOnly: boolean, smartDiscovered?: boolean, rootClassName?: string|null, rootClassNameUnresolved?: boolean }>}
362
+ */
363
+ export function scanForHydrationIslandsWithProps(themeRoot) {
364
+ const discovered = [];
365
+ const namesFound = new Set();
366
+ const filesToScan = [];
367
+ let newDiscoveries = 0;
368
+
369
+ const dirsToScan = [
370
+ path.join(themeRoot, 'src', 'app'),
371
+ path.join(themeRoot, 'src', 'components'),
372
+ path.join(themeRoot, 'src', 'blocks'),
373
+ ];
374
+
375
+ function collectFilesRecursive(dir) {
376
+ if (!existsSync(dir)) return;
377
+ try {
378
+ const items = readdirSync(dir, { withFileTypes: true });
379
+ for (const item of items) {
380
+ const fullPath = path.join(dir, item.name);
381
+ if (item.isDirectory()) {
382
+ collectFilesRecursive(fullPath);
383
+ } else if (
384
+ item.isFile() &&
385
+ (item.name.endsWith('.tsx') || item.name.endsWith('.ts'))
386
+ ) {
387
+ filesToScan.push(fullPath);
388
+ }
389
+ }
390
+ } catch {}
391
+ }
392
+
393
+ for (const dir of dirsToScan) {
394
+ collectFilesRecursive(dir);
395
+ }
396
+
397
+ // Helper to extract attribute values
398
+ const getAttr = (str, attr) => {
399
+ const regex1 = new RegExp(`${attr}\\s*=\\s*["']([^"']*)["']`);
400
+ const regex2 = new RegExp(`${attr}\\s*=\\s*\\{["']([^"']*)["']\\}`);
401
+ const regex3 = new RegExp(`${attr}\\s*=\\s*\\{([^\\}]*)\\}`);
402
+
403
+ const m1 = str.match(regex1);
404
+ if (m1) return m1[1];
405
+ const m2 = str.match(regex2);
406
+ if (m2) return m2[1];
407
+ const m3 = str.match(regex3);
408
+ if (m3) return m3[1].trim();
409
+
410
+ return null;
411
+ };
412
+
413
+ for (const filePath of filesToScan) {
414
+ const relFile = path.relative(themeRoot, filePath).replace(/\\/g, '/');
415
+ try {
416
+ // readComponentSource (not raw readFileSync): a file's on-disk content
417
+ // may have been auto-split, in which case the shell's rewritten source
418
+ // (referencing the extracted island components by tag name) — not the
419
+ // dev's original, unmodified content — is what actually determines
420
+ // which components need their own hydration bundle.
421
+ const content = readComponentSource(filePath);
422
+ const hydrateRegex = /<Hydrate\b([\s\S]*?)>([\s\S]*?)<\/Hydrate>/g;
423
+ let match;
424
+ while ((match = hydrateRegex.exec(content)) !== null) {
425
+ const propsStr = match[1];
426
+ const childrenStr = match[2].trim();
427
+
428
+ // Resolve component identifier name
429
+ let islandName = null;
430
+ const idMatch = propsStr.match(/id\s*=\s*["']([^"']*)["']/);
431
+ if (idMatch) {
432
+ islandName = idMatch[1];
433
+ } else {
434
+ const componentTagMatch = childrenStr.match(/<([A-Z][a-zA-Z0-9]*)\b/);
435
+ if (componentTagMatch) {
436
+ const compName = componentTagMatch[1];
437
+ islandName = compName
438
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
439
+ .toLowerCase();
440
+ }
441
+ }
442
+
443
+ if (islandName) {
444
+ namesFound.add(islandName);
445
+ const trigger = getAttr(propsStr, 'trigger') || 'visible';
446
+ const preload = getAttr(propsStr, 'preload') || 'none';
447
+ const media = getAttr(propsStr, 'media');
448
+ const connection = getAttr(propsStr, 'connection') || 'any';
449
+ const clientOnly =
450
+ propsStr.includes('clientOnly') &&
451
+ !propsStr.includes('clientOnly={false}');
452
+
453
+ discovered.push({
454
+ name: islandName,
455
+ file: relFile,
456
+ trigger,
457
+ preload,
458
+ media,
459
+ connection,
460
+ clientOnly,
461
+ });
462
+ }
463
+ }
464
+ } catch (err) {
465
+ console.warn(
466
+ `[Hydration Scanner] Failed to scan file ${filePath}:`,
467
+ err.message,
468
+ );
469
+ }
470
+ }
471
+
472
+ // Smart Discovery matching — per interactive *export*, not per file.
473
+ const compDir = path.join(themeRoot, 'src', 'components');
474
+ const interactiveExports = new Map(); // PascalCase export name -> absolute file path
475
+
476
+ function scanComponentsRecursive(dir) {
477
+ if (!existsSync(dir)) return;
478
+ try {
479
+ const items = readdirSync(dir, { withFileTypes: true });
480
+ for (const item of items) {
481
+ const fullPath = path.join(dir, item.name);
482
+ if (item.isDirectory()) {
483
+ scanComponentsRecursive(fullPath);
484
+ } else if (
485
+ item.isFile() &&
486
+ (item.name.endsWith('.tsx') || item.name.endsWith('.ts'))
487
+ ) {
488
+ try {
489
+ for (const exportName of getInteractiveExportNames(fullPath)) {
490
+ interactiveExports.set(exportName, fullPath);
491
+ }
492
+ } catch {}
493
+ }
494
+ }
495
+ } catch {}
496
+ }
497
+
498
+ scanComponentsRecursive(compDir);
499
+
500
+ for (const filePath of filesToScan) {
501
+ const relFile = path.relative(themeRoot, filePath).replace(/\\/g, '/');
502
+ try {
503
+ // readComponentSource (not raw readFileSync): a file's on-disk content
504
+ // may have been auto-split, in which case the shell's rewritten source
505
+ // (referencing the extracted island components by tag name) — not the
506
+ // dev's original, unmodified content — is what actually determines
507
+ // which components need their own hydration bundle.
508
+ const content = readComponentSource(filePath);
509
+ for (const [exportName, compFullPath] of interactiveExports) {
510
+ if (sourceUsesJsxTag(content, exportName)) {
511
+ const kebabName = toKebabName(exportName);
512
+ if (!namesFound.has(kebabName)) {
513
+ namesFound.add(kebabName);
514
+ // Resolve the *component's own* root className (not the referencing page's),
515
+ // so the auto-generated <Hydrate> wrapper can inherit its layout classes
516
+ // instead of defaulting to an unstyled display:block box.
517
+ const rootInfo = getComponentRootClassName(compFullPath);
518
+ discovered.push({
519
+ name: kebabName,
520
+ file: relFile,
521
+ trigger: 'load',
522
+ preload: 'none',
523
+ media: null,
524
+ connection: 'any',
525
+ clientOnly: false,
526
+ smartDiscovered: true,
527
+ rootClassName: rootInfo.resolvable ? rootInfo.className : null,
528
+ rootClassNameUnresolved: rootInfo.reason === 'dynamic-classname',
529
+ });
530
+ }
531
+ }
532
+ }
533
+ } catch {}
534
+ }
535
+
536
+ // Smart Page Hydration: if a page file itself is interactive, register it directly
537
+ const pageDirs2 = [
538
+ path.join(themeRoot, 'src', 'app'),
539
+ path.join(themeRoot, 'src', 'app', 'pages'),
540
+ ];
541
+ for (const pDir of pageDirs2) {
542
+ if (existsSync(pDir)) {
543
+ try {
544
+ const items = readdirSync(pDir, { withFileTypes: true });
545
+ for (const item of items) {
546
+ if (
547
+ item.isFile() &&
548
+ (item.name.endsWith('.tsx') || item.name.endsWith('.ts'))
549
+ ) {
550
+ const fullPath = path.join(pDir, item.name);
551
+ if (isComponentInteractive(fullPath)) {
552
+ const compName = path.basename(
553
+ item.name,
554
+ path.extname(item.name),
555
+ );
556
+ const kebabName = compName
557
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
558
+ .toLowerCase();
559
+ if (!namesFound.has(kebabName)) {
560
+ namesFound.add(kebabName);
561
+ const rootInfo = getComponentRootClassName(fullPath);
562
+ discovered.push({
563
+ name: kebabName,
564
+ file: path.relative(themeRoot, fullPath).replace(/\\/g, '/'),
565
+ trigger: 'load', // Pages should default to load trigger for immediate responsiveness
566
+ preload: 'none',
567
+ media: null,
568
+ connection: 'any',
569
+ clientOnly: false,
570
+ smartDiscovered: true,
571
+ rootClassName: rootInfo.resolvable
572
+ ? rootInfo.className
573
+ : null,
574
+ rootClassNameUnresolved:
575
+ rootInfo.reason === 'dynamic-classname',
576
+ });
577
+ if (
578
+ reportSmartDiscovery(
579
+ `page:${kebabName}`,
580
+ `\x1b[33m[ForgeWP Optimizer] Smart Discovery: Detected interactive page file "${compName}". Auto-enforcing page hydration island!\x1b[0m`,
581
+ )
582
+ )
583
+ newDiscoveries++;
584
+ }
585
+ }
586
+ }
587
+ }
588
+ } catch {}
589
+ }
590
+ }
591
+
592
+ if (newDiscoveries > 0 && process.env.FORGEWP_VERBOSE === '1') {
593
+ console.warn(
594
+ `\x1b[33m[ForgeWP Optimizer] Smart Discovery: auto-enforced page hydration for ${newDiscoveries} interactive page file(s) — set FORGEWP_VERBOSE=1 to see which.\x1b[0m`,
595
+ );
596
+ }
597
+
598
+ return discovered;
599
+ }
@@ -0,0 +1,103 @@
1
+ import path from "node:path";
2
+ import { findComponentPath } from "./islands-scanner.js";
3
+
4
+ /**
5
+ * Map a kebab-case hydration island id to its Vite-emitted JS file.
6
+ *
7
+ * Vite's manifest `name` is the Rollup input key (the island id). That is the
8
+ * only reliable match for named exports that do not live in a same-named file
9
+ * (a named export compiled from a differently-named source file).
10
+ *
11
+ * Filename fallbacks still exist for older manifests, but they must not treat
12
+ * hyphens inside the island name as the start of the content hash —
13
+ * `count-up-Dtfp7iNm.js`.replace(/-[A-Za-z0-9_-]+\.js$/, '') === "count".
14
+ *
15
+ * @param {Record<string, { file?: string, name?: string, src?: string }>} viteManifest
16
+ * @param {string} island
17
+ * @param {string} [themeRoot]
18
+ * @returns {string|null} manifest `file` path (e.g. "assets/count-up-abc.js")
19
+ */
20
+ export function resolveIslandChunk(viteManifest, island, themeRoot = process.cwd()) {
21
+ if (!viteManifest || !island) return null;
22
+
23
+ const pascalName = island
24
+ .split("-")
25
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
26
+ .join("");
27
+
28
+ // Pass 1: Prioritize explicit entry chunks (isEntry === true) created by getHydrationRollupInputs
29
+ for (const [key, value] of Object.entries(viteManifest)) {
30
+ if (!value || !value.file || !value.isEntry) continue;
31
+
32
+ if (value.name === island || key === island) {
33
+ return value.file;
34
+ }
35
+
36
+ const src = value.src || key;
37
+ const srcNorm = String(src).replace(/\\/g, "/");
38
+ if (
39
+ srcNorm.endsWith(`/${pascalName}.tsx`) ||
40
+ srcNorm.endsWith(`/${pascalName}.ts`) ||
41
+ srcNorm.endsWith(`/${island}.tsx`) ||
42
+ srcNorm.endsWith(`/${island}.ts`)
43
+ ) {
44
+ return value.file;
45
+ }
46
+
47
+ const fileBasename = path.basename(value.file);
48
+ if (
49
+ fileBasename === `${island}.js` ||
50
+ (fileBasename.startsWith(`${island}-`) && fileBasename.endsWith(".js"))
51
+ ) {
52
+ return value.file;
53
+ }
54
+ }
55
+
56
+ // Pass 2: Fallback to non-entry chunks if no entry chunk matched
57
+ for (const [key, value] of Object.entries(viteManifest)) {
58
+ if (!value || !value.file) continue;
59
+
60
+ if (value.name === island || key === island) {
61
+ return value.file;
62
+ }
63
+
64
+ const src = value.src || key;
65
+ const srcNorm = String(src).replace(/\\/g, "/");
66
+ if (
67
+ srcNorm.endsWith(`/${pascalName}.tsx`) ||
68
+ srcNorm.endsWith(`/${pascalName}.ts`) ||
69
+ srcNorm.endsWith(`/${island}.tsx`) ||
70
+ srcNorm.endsWith(`/${island}.ts`)
71
+ ) {
72
+ return value.file;
73
+ }
74
+
75
+ const fileBasename = path.basename(value.file);
76
+ if (
77
+ fileBasename === `${island}.js` ||
78
+ (fileBasename.startsWith(`${island}-`) && fileBasename.endsWith(".js"))
79
+ ) {
80
+ return value.file;
81
+ }
82
+ }
83
+
84
+ // Pass 3: Resolve via findComponentPath if island is a named export from a multi-export source file
85
+ try {
86
+ const compPath = findComponentPath(themeRoot, island);
87
+ if (compPath) {
88
+ const compNorm = compPath.replace(/\\/g, "/");
89
+ for (const [key, value] of Object.entries(viteManifest)) {
90
+ if (!value || !value.file) continue;
91
+ const src = value.src || key;
92
+ const srcNorm = String(src).replace(/\\/g, "/");
93
+ if (compNorm.endsWith(srcNorm) || srcNorm.endsWith(path.basename(compNorm))) {
94
+ return value.file;
95
+ }
96
+ }
97
+ }
98
+ } catch {}
99
+
100
+ return null;
101
+ }
102
+
103
+