@forgewp/compiler 0.3.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +24 -5
  2. package/bin/analyze.js +158 -0
  3. package/bin/cli.js +33 -4
  4. package/bin/doctor.js +125 -11
  5. package/bin/export.js +20 -0
  6. package/bin/fresh.js +32 -343
  7. package/bin/i18n-extract.js +121 -0
  8. package/bin/i18n-translate.js +112 -0
  9. package/bin/make-block.js +27 -60
  10. package/bin/make-island.js +72 -0
  11. package/bin/make-post-type.js +6 -6
  12. package/bin/make-template.js +145 -0
  13. package/bin/repair.js +2 -2
  14. package/bin/sync-hooks.js +221 -0
  15. package/bin/sync-routes.js +28 -158
  16. package/define-config.d.ts +1 -0
  17. package/define-config.js +1 -0
  18. package/lib/adapters/html-adapter.js +65 -0
  19. package/lib/adapters/stub-adapter.js +49 -0
  20. package/lib/add-component.js +282 -183
  21. package/lib/asset-loader.js +27 -0
  22. package/lib/block-compiler.js +552 -0
  23. package/lib/blueprints.js +15 -501
  24. package/lib/define-config.d.ts +3 -0
  25. package/lib/define-config.js +8 -0
  26. package/lib/diagnostics.js +798 -0
  27. package/lib/export-theme.js +81 -18
  28. package/lib/framework-adapter.js +34 -0
  29. package/lib/functions-builder.js +2044 -0
  30. package/lib/generate-theme.js +1140 -1352
  31. package/lib/hydration-scanner.js +663 -21
  32. package/lib/i18n/extractor.js +60 -0
  33. package/lib/i18n/providers.js +165 -0
  34. package/lib/index.d.ts +115 -3
  35. package/lib/index.js +19 -5
  36. package/lib/load-config.js +122 -6
  37. package/lib/markup-processor.js +589 -0
  38. package/lib/php-builders.js +381 -0
  39. package/lib/react-adapter.js +1336 -0
  40. package/lib/render-static.js +9 -82
  41. package/lib/render-theme.mts +543 -232
  42. package/lib/screenshot-fallback.png +0 -0
  43. package/lib/types.js +1 -0
  44. package/lib/validate-export.js +183 -0
  45. package/package.json +15 -3
  46. package/templates/PresetsStyle.tsx +74 -0
  47. package/templates/SEO.tsx +109 -0
  48. package/templates/forgewp-config.ts +43 -0
  49. package/templates/menus.json +11 -0
  50. package/templates/mock-data.json +434 -0
  51. package/templates/wordpress.tsx +1297 -0
  52. package/bin/make-component.js +0 -200
@@ -1,4 +1,4 @@
1
- import { readFileSync, readdirSync, existsSync } from "node:fs";
1
+ import { readFileSync, readdirSync, existsSync, statSync } from "node:fs";
2
2
  import path from "node:path";
3
3
 
4
4
  /**
@@ -12,26 +12,29 @@ export function scanForHydrationIslands(themeRoot) {
12
12
  const islands = new Set();
13
13
  const filesToScan = [];
14
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
- }
15
+ const dirsToScan = [
16
+ path.join(themeRoot, "src", "app"),
17
+ path.join(themeRoot, "src", "components"),
18
+ path.join(themeRoot, "src", "blocks"),
19
+ ];
20
+
21
+ function collectFilesRecursive(dir) {
22
+ if (!existsSync(dir)) return;
23
+ try {
24
+ const items = readdirSync(dir, { withFileTypes: true });
25
+ for (const item of items) {
26
+ const fullPath = path.join(dir, item.name);
27
+ if (item.isDirectory()) {
28
+ collectFilesRecursive(fullPath);
29
+ } else if (item.isFile() && (item.name.endsWith(".tsx") || item.name.endsWith(".ts"))) {
30
+ filesToScan.push(fullPath);
31
+ }
32
+ }
33
+ } catch {}
34
+ }
35
+
36
+ for (const dir of dirsToScan) {
37
+ collectFilesRecursive(dir);
35
38
  }
36
39
 
37
40
  // Scan each file for <Hydrate> occurrences
@@ -175,5 +178,644 @@ export function getHydrationRollupInputs(themeRoot) {
175
178
  }
176
179
  }
177
180
 
181
+ // Scan and inject custom blocks from src/blocks/
182
+ const blocksDir = path.join(themeRoot, "src", "blocks");
183
+ if (existsSync(blocksDir)) {
184
+ try {
185
+ const items = readdirSync(blocksDir);
186
+ for (const item of items) {
187
+ const fullPath = path.join(blocksDir, item);
188
+ const isDir = statSync(fullPath).isDirectory();
189
+ if (isDir) {
190
+ const indexPath = path.join(fullPath, "index.tsx");
191
+ if (existsSync(indexPath)) {
192
+ const blockName = item
193
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
194
+ .toLowerCase()
195
+ .replace(/[^a-z0-9]+/g, "-");
196
+ inputs[`block-${blockName}`] = indexPath;
197
+ }
198
+ } else if (item.endsWith(".tsx") || item.endsWith(".jsx")) {
199
+ const blockName = item
200
+ .replace(/\.(tsx|jsx)$/, "")
201
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
202
+ .toLowerCase()
203
+ .replace(/[^a-z0-9]+/g, "-");
204
+ inputs[`block-${blockName}`] = fullPath;
205
+ }
206
+ }
207
+ } catch (err) {
208
+ console.warn("[Hydration Scanner] Failed to scan src/blocks/:", err.message);
209
+ }
210
+ }
211
+
178
212
  return inputs;
179
213
  }
214
+
215
+ /**
216
+ * Scans theme pages and layout files for <Hydrate> boundaries and extracts their kebab-case names,
217
+ * source files, and defined properties.
218
+ *
219
+ * @param {string} themeRoot - The absolute path of the theme's root directory.
220
+ * @returns {Array<{ name: string, file: string, trigger: string, preload: string, media: string|null, connection: string|null, clientOnly: boolean, smartDiscovered?: boolean }>}
221
+ */
222
+ export function scanForHydrationIslandsWithProps(themeRoot) {
223
+ const discovered = [];
224
+ const namesFound = new Set();
225
+ const filesToScan = [];
226
+
227
+ const dirsToScan = [
228
+ path.join(themeRoot, "src", "app"),
229
+ path.join(themeRoot, "src", "components"),
230
+ path.join(themeRoot, "src", "blocks"),
231
+ ];
232
+
233
+ function collectFilesRecursive(dir) {
234
+ if (!existsSync(dir)) return;
235
+ try {
236
+ const items = readdirSync(dir, { withFileTypes: true });
237
+ for (const item of items) {
238
+ const fullPath = path.join(dir, item.name);
239
+ if (item.isDirectory()) {
240
+ collectFilesRecursive(fullPath);
241
+ } else if (item.isFile() && (item.name.endsWith(".tsx") || item.name.endsWith(".ts"))) {
242
+ filesToScan.push(fullPath);
243
+ }
244
+ }
245
+ } catch {}
246
+ }
247
+
248
+ for (const dir of dirsToScan) {
249
+ collectFilesRecursive(dir);
250
+ }
251
+
252
+ // Helper to extract attribute values
253
+ const getAttr = (str, attr) => {
254
+ const regex1 = new RegExp(`${attr}\\s*=\\s*["']([^"']*)["']`);
255
+ const regex2 = new RegExp(`${attr}\\s*=\\s*\\{["']([^"']*)["']\\}`);
256
+ const regex3 = new RegExp(`${attr}\\s*=\\s*\\{([^\\}]*)\\}`);
257
+
258
+ const m1 = str.match(regex1);
259
+ if (m1) return m1[1];
260
+ const m2 = str.match(regex2);
261
+ if (m2) return m2[1];
262
+ const m3 = str.match(regex3);
263
+ if (m3) return m3[1].trim();
264
+
265
+ return null;
266
+ };
267
+
268
+ for (const filePath of filesToScan) {
269
+ const relFile = path.relative(themeRoot, filePath).replace(/\\/g, "/");
270
+ try {
271
+ const content = readFileSync(filePath, "utf8");
272
+ const hydrateRegex = /<Hydrate\b([\s\S]*?)>([\s\S]*?)<\/Hydrate>/g;
273
+ let match;
274
+ while ((match = hydrateRegex.exec(content)) !== null) {
275
+ const propsStr = match[1];
276
+ const childrenStr = match[2].trim();
277
+
278
+ // Resolve component identifier name
279
+ let islandName = null;
280
+ const idMatch = propsStr.match(/id\s*=\s*["']([^"']*)["']/);
281
+ if (idMatch) {
282
+ islandName = idMatch[1];
283
+ } else {
284
+ const componentTagMatch = childrenStr.match(/<([A-Z][a-zA-Z0-9]*)\b/);
285
+ if (componentTagMatch) {
286
+ const compName = componentTagMatch[1];
287
+ islandName = compName.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
288
+ }
289
+ }
290
+
291
+ if (islandName) {
292
+ namesFound.add(islandName);
293
+ const trigger = getAttr(propsStr, "trigger") || "visible";
294
+ const preload = getAttr(propsStr, "preload") || "none";
295
+ const media = getAttr(propsStr, "media");
296
+ const connection = getAttr(propsStr, "connection") || "any";
297
+ const clientOnly = propsStr.includes("clientOnly") && !propsStr.includes("clientOnly={false}");
298
+
299
+ discovered.push({
300
+ name: islandName,
301
+ file: relFile,
302
+ trigger,
303
+ preload,
304
+ media,
305
+ connection,
306
+ clientOnly,
307
+ });
308
+ }
309
+ }
310
+ } catch (err) {
311
+ console.warn(`[Hydration Scanner] Failed to scan file ${filePath}:`, err.message);
312
+ }
313
+ }
314
+
315
+ // Smart Discovery matching
316
+ const compDir = path.join(themeRoot, "src", "components");
317
+ const interactiveComponents = new Set();
318
+
319
+ function scanComponentsRecursive(dir) {
320
+ if (!existsSync(dir)) return;
321
+ try {
322
+ const items = readdirSync(dir, { withFileTypes: true });
323
+ for (const item of items) {
324
+ const fullPath = path.join(dir, item.name);
325
+ if (item.isDirectory()) {
326
+ scanComponentsRecursive(fullPath);
327
+ } else if (item.isFile() && (item.name.endsWith(".tsx") || item.name.endsWith(".ts"))) {
328
+ try {
329
+ const fileContent = readFileSync(fullPath, "utf8");
330
+ const hasState = fileContent.includes("useState") || fileContent.includes("useEffect") || fileContent.includes("useRef");
331
+ const hasMotion = fileContent.includes("framer-motion") || fileContent.includes("gsap") || fileContent.includes("animate") || fileContent.includes("motion.");
332
+ if (hasState || hasMotion) {
333
+ const compName = path.basename(item.name, path.extname(item.name));
334
+ interactiveComponents.add(compName);
335
+ }
336
+ } catch {}
337
+ }
338
+ }
339
+ } catch {}
340
+ }
341
+
342
+ scanComponentsRecursive(compDir);
343
+
344
+ for (const filePath of filesToScan) {
345
+ const relFile = path.relative(themeRoot, filePath).replace(/\\/g, "/");
346
+ try {
347
+ const content = readFileSync(filePath, "utf8");
348
+ for (const compName of interactiveComponents) {
349
+ if (content.includes(`<${compName}`)) {
350
+ const kebabName = compName.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
351
+ if (!namesFound.has(kebabName)) {
352
+ namesFound.add(kebabName);
353
+ discovered.push({
354
+ name: kebabName,
355
+ file: relFile,
356
+ trigger: "visible",
357
+ preload: "none",
358
+ media: null,
359
+ connection: "any",
360
+ clientOnly: false,
361
+ smartDiscovered: true,
362
+ });
363
+ }
364
+ }
365
+ }
366
+ } catch {}
367
+ }
368
+
369
+ return discovered;
370
+ }
371
+
372
+ /**
373
+ * Statically analyzes theme templates to detect missing metadata,
374
+ * dynamic event handlers in static WpQueryLoop scopes, and hardcoded relative URLs.
375
+ *
376
+ * @param {string} themeRoot
377
+ * @returns {Array<{ type: 'metadata' | 'loop' | 'url', file: string, message: string, severity: 'warning' | 'error', lineContent?: string }>}
378
+ */
379
+ export function runStaticLintChecks(themeRoot) {
380
+ const violations = [];
381
+ const filesToScan = [];
382
+
383
+ // Load CPTs, Taxonomies, and Custom Fields from wp.config.ts and cms/mock-data.json
384
+ const validPostTypes = new Set(["post", "page"]);
385
+ const postTypeTaxonomies = {
386
+ "post": new Set(["category", "post_tag"]),
387
+ "page": new Set()
388
+ };
389
+ const postTypeCustomFields = {
390
+ "post": new Set(),
391
+ "page": new Set()
392
+ };
393
+
394
+ // 1. Scan CPTs from wp.config.ts
395
+ const configPath = path.join(themeRoot, "wp.config.ts");
396
+ if (existsSync(configPath)) {
397
+ try {
398
+ const configContent = readFileSync(configPath, "utf8");
399
+ const postTypesMatch = configContent.match(/postTypes\s*:\s*\{([\s\S]*?)\}/);
400
+ if (postTypesMatch) {
401
+ const block = postTypesMatch[1];
402
+ const keyRegex = /\b([a-zA-Z0-9_-]+)\s*:/g;
403
+ let m;
404
+ while ((m = keyRegex.exec(block)) !== null) {
405
+ const pt = m[1];
406
+ if (pt !== 'labels' && pt !== 'singular' && pt !== 'plural' && pt !== 'translatable') {
407
+ validPostTypes.add(pt);
408
+ if (!postTypeTaxonomies[pt]) {
409
+ postTypeTaxonomies[pt] = new Set(["category", "post_tag"]);
410
+ }
411
+ if (!postTypeCustomFields[pt]) {
412
+ postTypeCustomFields[pt] = new Set();
413
+ }
414
+ }
415
+ }
416
+ }
417
+ } catch {}
418
+ }
419
+
420
+ // 2. Scan CPTs, Taxonomies, and Custom Fields from cms/mock-data.json
421
+ const mockDataPath = path.join(themeRoot, "cms", "mock-data.json");
422
+ if (existsSync(mockDataPath)) {
423
+ try {
424
+ const mockData = JSON.parse(readFileSync(mockDataPath, "utf8"));
425
+ for (const pt of Object.keys(mockData)) {
426
+ if (
427
+ pt !== 'posts' &&
428
+ pt !== 'pages' &&
429
+ pt !== 'post' &&
430
+ pt !== 'page' &&
431
+ pt !== 'menus' &&
432
+ pt !== 'attachment' &&
433
+ !pt.startsWith('_')
434
+ ) {
435
+ validPostTypes.add(pt);
436
+ if (!postTypeTaxonomies[pt]) {
437
+ postTypeTaxonomies[pt] = new Set(["category", "post_tag"]);
438
+ }
439
+ if (!postTypeCustomFields[pt]) {
440
+ postTypeCustomFields[pt] = new Set();
441
+ }
442
+
443
+ const items = mockData[pt];
444
+ if (Array.isArray(items)) {
445
+ for (const item of items) {
446
+ if (item._terms && typeof item._terms === 'object') {
447
+ for (const tax of Object.keys(item._terms)) {
448
+ postTypeTaxonomies[pt].add(tax);
449
+ }
450
+ }
451
+ if (item.customFields && typeof item.customFields === 'object') {
452
+ for (const key of Object.keys(item.customFields)) {
453
+ postTypeCustomFields[pt].add(key);
454
+ }
455
+ }
456
+ }
457
+ }
458
+ } else if (pt === 'post' || pt === 'page') {
459
+ const items = mockData[pt];
460
+ if (Array.isArray(items)) {
461
+ for (const item of items) {
462
+ if (item._terms && typeof item._terms === 'object') {
463
+ for (const tax of Object.keys(item._terms)) {
464
+ postTypeTaxonomies[pt].add(tax);
465
+ }
466
+ }
467
+ if (item.customFields && typeof item.customFields === 'object') {
468
+ for (const key of Object.keys(item.customFields)) {
469
+ postTypeCustomFields[pt].add(key);
470
+ }
471
+ }
472
+ }
473
+ }
474
+ }
475
+ }
476
+ } catch {}
477
+ }
478
+
479
+ const validSlugs = new Set(["page"]);
480
+ const pagesDir = path.join(themeRoot, "src", "app", "pages");
481
+ if (existsSync(pagesDir)) {
482
+ try {
483
+ const pageFiles = readdirSync(pagesDir).filter(f => f.endsWith(".tsx"));
484
+ for (const pf of pageFiles) {
485
+ const pageName = pf.replace(".tsx", "");
486
+ if (pageName.startsWith("Single")) {
487
+ continue;
488
+ }
489
+ const slug = pageName.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
490
+ validSlugs.add(slug);
491
+ }
492
+ } catch {}
493
+ }
494
+
495
+ const dirsToScan = [
496
+ path.join(themeRoot, "src", "app"),
497
+ path.join(themeRoot, "src", "components"),
498
+ path.join(themeRoot, "src", "blocks"),
499
+ ];
500
+
501
+ function collectFilesRecursive(dir) {
502
+ if (!existsSync(dir)) return;
503
+ try {
504
+ const items = readdirSync(dir, { withFileTypes: true });
505
+ for (const item of items) {
506
+ const fullPath = path.join(dir, item.name);
507
+ if (item.isDirectory()) {
508
+ collectFilesRecursive(fullPath);
509
+ } else if (item.isFile() && (item.name.endsWith(".tsx") || item.name.endsWith(".ts"))) {
510
+ filesToScan.push(fullPath);
511
+ }
512
+ }
513
+ } catch {}
514
+ }
515
+
516
+ for (const dir of dirsToScan) {
517
+ collectFilesRecursive(dir);
518
+ }
519
+
520
+ for (const filePath of filesToScan) {
521
+ const relFile = path.relative(themeRoot, filePath).replace(/\\/g, "/");
522
+ try {
523
+ const content = readFileSync(filePath, "utf8");
524
+ const lines = content.split("\n");
525
+
526
+ // 1. Metadata Checks (Only for page files)
527
+ const isPage = path.basename(filePath).startsWith("page.tsx") || filePath.includes("pages/");
528
+ if (isPage) {
529
+ const hasWpHead = content.includes("<WpHead") || content.includes("<WpHead\b");
530
+ if (!hasWpHead) {
531
+ violations.push({
532
+ type: "metadata",
533
+ file: relFile,
534
+ message: "Missing SEO <WpHead> component on this major page template.",
535
+ severity: "warning"
536
+ });
537
+ } else {
538
+ const wpHeadRegex = /<WpHead\b([\s\S]*?)\/?>/g;
539
+ let headMatch;
540
+ while ((headMatch = wpHeadRegex.exec(content)) !== null) {
541
+ const headProps = headMatch[1];
542
+ const hasTitle = /title\s*=\s*(?:["']|\{)/.test(headProps);
543
+ const hasDescription = /description\s*=\s*(?:["']|\{)/.test(headProps);
544
+
545
+ if (!hasTitle) {
546
+ violations.push({
547
+ type: "metadata",
548
+ file: relFile,
549
+ message: "SEO <WpHead> is missing the required 'title' attribute.",
550
+ severity: "warning"
551
+ });
552
+ }
553
+ if (!hasDescription) {
554
+ violations.push({
555
+ type: "metadata",
556
+ file: relFile,
557
+ message: "SEO <WpHead> is missing the required 'description' attribute.",
558
+ severity: "warning"
559
+ });
560
+ }
561
+ }
562
+ }
563
+ }
564
+
565
+ // 2. WpQueryLoop without Hydration check
566
+ const hydrateBlocks = [];
567
+ const hydrateRegex = /<Hydrate\b([\s\S]*?)>([\s\S]*?)<\/Hydrate>/g;
568
+ let hydMatch;
569
+ while ((hydMatch = hydrateRegex.exec(content)) !== null) {
570
+ hydrateBlocks.push({
571
+ start: hydMatch.index,
572
+ end: hydMatch.index + hydMatch[0].length
573
+ });
574
+ }
575
+
576
+ const loopRegex = /<WpQueryLoop\b([\s\S]*?)>([\s\S]*?)<\/WpQueryLoop>/g;
577
+ let loopMatch;
578
+ while ((loopMatch = loopRegex.exec(content)) !== null) {
579
+ const loopBody = loopMatch[2];
580
+ const loopStart = loopMatch.index;
581
+
582
+ const isHydrated = hydrateBlocks.some(hb => loopStart >= hb.start && loopStart <= hb.end);
583
+
584
+ if (!isHydrated) {
585
+ const hasEventHandlers = /\bon[A-Z][a-zA-Z]*\s*=\s*\{/.test(loopBody);
586
+ if (hasEventHandlers) {
587
+ const eventMatch = loopBody.match(/\b(on[A-Z][a-zA-Z]*)\s*=\s*\{/);
588
+ const eventName = eventMatch ? eventMatch[1] : "event handler";
589
+ violations.push({
590
+ type: "loop",
591
+ file: relFile,
592
+ message: `WpQueryLoop contains active interactive handler (${eventName}) but is not wrapped inside a <Hydrate> boundary. It will render static and non-interactive in production WordPress.`,
593
+ severity: "error"
594
+ });
595
+ }
596
+ }
597
+ }
598
+
599
+ // 3. Hardcoded relative internal links check
600
+ for (let i = 0; i < lines.length; i++) {
601
+ const line = lines[i];
602
+ const hrefRegex = /href\s*=\s*["']([^"']*)["']/g;
603
+ let hrefMatch;
604
+ while ((hrefMatch = hrefRegex.exec(line)) !== null) {
605
+ const val = hrefMatch[1];
606
+ const isRelative = val.startsWith("/") &&
607
+ !val.startsWith("//") &&
608
+ !val.startsWith("/wp-") &&
609
+ !val.startsWith("/feed");
610
+ if (isRelative) {
611
+ violations.push({
612
+ type: "url",
613
+ file: relFile,
614
+ message: `Hardcoded relative URL "${val}" found. Use useWpPermalink() to resolve dynamically from WordPress.`,
615
+ severity: "warning",
616
+ lineContent: line.trim() + ` (line ${i + 1})`
617
+ });
618
+ }
619
+ }
620
+
621
+ const jsxHrefRegex = /href\s*=\s*\{\s*["']([^"']*)["']\s*\}/g;
622
+ let jsxHrefMatch;
623
+ while ((jsxHrefMatch = jsxHrefRegex.exec(line)) !== null) {
624
+ const val = jsxHrefMatch[1];
625
+ const isRelative = val.startsWith("/") &&
626
+ !val.startsWith("//") &&
627
+ !val.startsWith("/wp-") &&
628
+ !val.startsWith("/feed");
629
+ if (isRelative) {
630
+ violations.push({
631
+ type: "url",
632
+ file: relFile,
633
+ message: `Hardcoded relative URL "${val}" found. Use useWpPermalink() to resolve dynamically from WordPress.`,
634
+ severity: "warning",
635
+ lineContent: line.trim() + ` (line ${i + 1})`
636
+ });
637
+ }
638
+ }
639
+ }
640
+
641
+ // 4. useWpPageLink template slug typo check
642
+ const pageLinkRegex = /useWpPageLink\s*\(\s*["']([^"']+)["']/g;
643
+ let pageLinkMatch;
644
+ while ((pageLinkMatch = pageLinkRegex.exec(content)) !== null) {
645
+ const slugUsed = pageLinkMatch[1];
646
+ if (!validSlugs.has(slugUsed)) {
647
+ violations.push({
648
+ type: "pagelink",
649
+ file: relFile,
650
+ message: `useWpPageLink references non-existent page template slug "${slugUsed}". Valid slugs: ${Array.from(validSlugs).join(", ")}`,
651
+ severity: "warning"
652
+ });
653
+ }
654
+ }
655
+
656
+ // 5. useWpQuery arguments audit
657
+ const useWpQueryRegex = /useWpQuery\s*\(\s*(\{[\s\S]*?\})\s*\)/g;
658
+ let queryMatch;
659
+ while ((queryMatch = useWpQueryRegex.exec(content)) !== null) {
660
+ const argsStr = queryMatch[1];
661
+
662
+ const postTypeMatch = argsStr.match(/postType\s*:\s*['"]([^'"]+)['"]/);
663
+ const postType = postTypeMatch ? postTypeMatch[1] : 'post';
664
+
665
+ if (!validPostTypes.has(postType)) {
666
+ violations.push({
667
+ type: "query",
668
+ file: relFile,
669
+ message: `useWpQuery references unregistered postType "${postType}".`,
670
+ severity: "warning"
671
+ });
672
+ } else {
673
+ // Validate Taxonomies inside taxQuery
674
+ const taxRegex = /\btaxonomy\s*:\s*['"]([^'"]+)['"]/g;
675
+ let taxMatch;
676
+ const allowedTaxonomies = postTypeTaxonomies[postType] || new Set();
677
+ while ((taxMatch = taxRegex.exec(argsStr)) !== null) {
678
+ const taxSlug = taxMatch[1];
679
+ if (!allowedTaxonomies.has(taxSlug)) {
680
+ violations.push({
681
+ type: "query",
682
+ file: relFile,
683
+ message: `useWpQuery in ${path.basename(filePath)} queries taxonomy "${taxSlug}", which is not registered for postType "${postType}" in wp.config.ts.`,
684
+ severity: "warning"
685
+ });
686
+ }
687
+ }
688
+
689
+ // Validate Custom Fields inside metaQuery
690
+ const keyRegex = /\bkey\s*:\s*['"]([^'"]+)['"]/g;
691
+ let keyMatch;
692
+ const allowedFields = postTypeCustomFields[postType] || new Set();
693
+ while ((keyMatch = keyRegex.exec(argsStr)) !== null) {
694
+ const fieldKey = keyMatch[1];
695
+ if (!allowedFields.has(fieldKey)) {
696
+ violations.push({
697
+ type: "query",
698
+ file: relFile,
699
+ message: `useWpQuery in ${path.basename(filePath)} queries custom field "${fieldKey}", which is not defined for postType "${postType}" in wp.config.ts.`,
700
+ severity: "warning"
701
+ });
702
+ }
703
+ }
704
+ }
705
+ }
706
+
707
+ } catch (err) {
708
+ console.warn(`[Static Lint] Failed to scan file ${filePath}:`, err.message);
709
+ }
710
+ }
711
+
712
+ return violations;
713
+ }
714
+
715
+ /**
716
+ * Scans theme template page files for colocated `defineEditable` exports
717
+ * and parses them into a unified schema dictionary.
718
+ *
719
+ * @param {string} themeRoot
720
+ * @returns {Record<string, Record<string, any>>} A map of template/page slug -> parsed schema
721
+ */
722
+ export function scanForEditableSchemas(themeRoot) {
723
+ const schemas = {};
724
+ const filesToScan = [];
725
+
726
+ const dirsToScan = [
727
+ path.join(themeRoot, "src", "app"),
728
+ ];
729
+
730
+ function collectFilesRecursive(dir) {
731
+ if (!existsSync(dir)) return;
732
+ try {
733
+ const items = readdirSync(dir, { withFileTypes: true });
734
+ for (const item of items) {
735
+ const fullPath = path.join(dir, item.name);
736
+ if (item.isDirectory()) {
737
+ collectFilesRecursive(fullPath);
738
+ } else if (item.isFile() && (item.name.endsWith(".tsx") || item.name.endsWith(".ts"))) {
739
+ filesToScan.push(fullPath);
740
+ }
741
+ }
742
+ } catch {}
743
+ }
744
+
745
+ for (const dir of dirsToScan) {
746
+ collectFilesRecursive(dir);
747
+ }
748
+
749
+ for (const filePath of filesToScan) {
750
+ try {
751
+ const content = readFileSync(filePath, "utf8");
752
+ if (!content.includes("defineEditable")) continue;
753
+
754
+ const schemaStr = extractDefineEditableContent(content);
755
+ if (schemaStr) {
756
+ const parsed = parseEditableSchema(schemaStr);
757
+ if (parsed) {
758
+ // Resolve template slug based on file name or path
759
+ // e.g. "SingleHotelPage.tsx" -> "single-hotel-page"
760
+ // or "page.tsx" -> "front-page" or similar
761
+ const baseName = path.basename(filePath, path.extname(filePath));
762
+ let slug = baseName
763
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
764
+ .toLowerCase();
765
+
766
+ if (slug === 'page') {
767
+ slug = 'front-page';
768
+ }
769
+
770
+ schemas[slug] = parsed;
771
+ }
772
+ }
773
+ } catch (err) {
774
+ console.warn(`[Schema Scanner] Failed to scan file ${filePath}:`, err.message);
775
+ }
776
+ }
777
+
778
+ return schemas;
779
+ }
780
+
781
+ function extractDefineEditableContent(fileContent) {
782
+ const match = fileContent.match(/export\s+const\s+editable\s*=\s*defineEditable\s*\(/);
783
+ if (!match) return null;
784
+
785
+ const startIndex = match.index + match[0].length;
786
+ let parenCount = 1;
787
+ let currentIndex = startIndex;
788
+
789
+ while (parenCount > 0 && currentIndex < fileContent.length) {
790
+ const char = fileContent[currentIndex];
791
+ if (char === '(') {
792
+ parenCount++;
793
+ } else if (char === ')') {
794
+ parenCount--;
795
+ }
796
+ currentIndex++;
797
+ }
798
+
799
+ if (parenCount === 0) {
800
+ return fileContent.substring(startIndex, currentIndex - 1);
801
+ }
802
+ return null;
803
+ }
804
+
805
+ function parseEditableSchema(schemaStr) {
806
+ const text = (opts) => ({ type: 'text', ...opts });
807
+ const richText = (opts) => ({ type: 'richText', ...opts });
808
+ const image = (opts) => ({ type: 'image', ...opts });
809
+ const boolean = (opts) => ({ type: 'boolean', ...opts });
810
+ const repeater = (opts) => ({ type: 'repeater', ...opts });
811
+
812
+ try {
813
+ const fn = new Function('text', 'richText', 'image', 'boolean', 'repeater', `return (${schemaStr})`);
814
+ return fn(text, richText, image, boolean, repeater);
815
+ } catch (e) {
816
+ console.error('[Schema Parser] Failed to evaluate schema literal:', e.message);
817
+ return null;
818
+ }
819
+ }
820
+
821
+