@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
package/lib/blueprints.js CHANGED
@@ -8,10 +8,6 @@ const readTemplate = (name) => fs.readFileSync(path.join(__dirname, '..', 'templ
8
8
  const baseBlueprints = {
9
9
  'cms/menus.json': readTemplate('menus.json'),
10
10
  'cms/mock-data.json': readTemplate('mock-data.json'),
11
- 'src/.forgewp/forgewp-config.ts': readTemplate('forgewp-config.ts'),
12
- 'src/.forgewp/wordpress.tsx': readTemplate('wordpress.tsx'),
13
- 'src/.forgewp/SEO.tsx': readTemplate('SEO.tsx'),
14
- 'src/.forgewp/PresetsStyle.tsx': readTemplate('PresetsStyle.tsx'),
15
11
  };
16
12
 
17
13
  function checkHasWooCommerce(projectRoot) {
@@ -48,99 +44,43 @@ function checkHasAuth(projectRoot) {
48
44
  return false;
49
45
  }
50
46
 
47
+ export function getSystemBlueprints(projectRoot = process.cwd()) {
48
+ const hasWooCommerce = checkHasWooCommerce(projectRoot);
49
+ const hasAuth = checkHasAuth(projectRoot);
50
+
51
+ const blueprints = { ...baseBlueprints };
52
+ if (hasWooCommerce) {
53
+ blueprints['cms/products.json'] = readTemplate('products.json');
54
+ }
55
+ if (hasAuth) {
56
+ blueprints['cms/users.json'] = readTemplate('users.json');
57
+ blueprints['cms/roles.json'] = readTemplate('roles.json');
58
+ blueprints['cms/sessions.json'] = readTemplate('sessions.json');
59
+ }
60
+
61
+ return blueprints;
62
+ }
63
+
51
64
  export const SYSTEM_BLUEPRINTS = new Proxy(baseBlueprints, {
52
- ownKeys(target) {
53
- const keys = Reflect.ownKeys(target);
54
- const extraKeys = [];
55
- if (checkHasWooCommerce(process.cwd())) {
56
- extraKeys.push('cms/products.json');
57
- }
58
- if (checkHasAuth(process.cwd())) {
59
- extraKeys.push('cms/users.json', 'cms/roles.json', 'cms/sessions.json');
60
- }
61
- return [...keys, ...extraKeys];
65
+ ownKeys() {
66
+ return Reflect.ownKeys(getSystemBlueprints(process.cwd()));
62
67
  },
63
68
  getOwnPropertyDescriptor(target, prop) {
64
- if (prop === 'cms/products.json') {
65
- if (checkHasWooCommerce(process.cwd())) {
66
- return {
67
- enumerable: true,
68
- configurable: true,
69
- writable: true,
70
- value: readTemplate('products.json')
71
- };
72
- }
73
- return undefined;
74
- }
75
- if (prop === 'cms/users.json' || prop === 'cms/roles.json' || prop === 'cms/sessions.json') {
76
- if (checkHasAuth(process.cwd())) {
77
- const templateName = prop.split('/').pop();
78
- return {
79
- enumerable: true,
80
- configurable: true,
81
- writable: true,
82
- value: readTemplate(templateName)
83
- };
84
- }
85
- return undefined;
69
+ const bps = getSystemBlueprints(process.cwd());
70
+ if (prop in bps) {
71
+ return {
72
+ enumerable: true,
73
+ configurable: true,
74
+ writable: true,
75
+ value: bps[prop]
76
+ };
86
77
  }
87
- return Reflect.getOwnPropertyDescriptor(target, prop);
78
+ return undefined;
88
79
  },
89
80
  get(target, prop) {
90
- const projectRoot = process.cwd();
91
- const hasWooCommerce = checkHasWooCommerce(projectRoot);
92
- const hasAuth = checkHasAuth(projectRoot);
93
-
94
- if (prop === 'cms/products.json') {
95
- if (hasWooCommerce) {
96
- return readTemplate('products.json');
97
- }
98
- return undefined;
99
- }
100
-
101
- if (prop === 'cms/users.json' || prop === 'cms/roles.json' || prop === 'cms/sessions.json') {
102
- if (hasAuth) {
103
- const templateName = prop.split('/').pop();
104
- return readTemplate(templateName);
105
- }
106
- return undefined;
107
- }
108
-
109
- if (prop === 'src/.forgewp/wordpress.tsx') {
110
- let content = target[prop];
111
- let importsToAdd = "";
112
- let windowMocksToAdd = "";
113
-
114
- if (hasWooCommerce) {
115
- importsToAdd += "\n// @ts-ignore\nimport productsData from '../../cms/products.json';";
116
- content = content.replace(
117
- "(window as any)._forgeWpMockPosts = mockData;",
118
- "(window as any)._forgeWpMockPosts = {\n ...mockData,\n ...productsData,\n };"
119
- );
120
- content += `\n\n// ── WooCommerce Modular Extensions ───────────────────────────────────────────\nexport * from '@forgewp/woocommerce';\n`;
121
- }
122
-
123
- if (hasAuth) {
124
- importsToAdd += "\n// @ts-ignore\nimport usersData from '../../cms/users.json';\n// @ts-ignore\nimport rolesData from '../../cms/roles.json';\n// @ts-ignore\nimport sessionsData from '../../cms/sessions.json';";
125
- windowMocksToAdd += "\n (window as any)._forgeWpMockUsers = usersData;\n (window as any)._forgeWpMockRoles = rolesData;\n (window as any)._forgeWpMockSessions = sessionsData;";
126
- content += `\n\n// ── Auth Modular Extensions ───────────────────────────────────────────\nexport * from '@forgewp/auth';\n`;
127
- }
128
-
129
- if (importsToAdd) {
130
- content = content.replace(
131
- "import translationsData from '../../cms/translations.json';",
132
- "import translationsData from '../../cms/translations.json';" + importsToAdd
133
- );
134
- }
135
-
136
- if (windowMocksToAdd) {
137
- content = content.replace(
138
- "(window as any)._forgeWpMockMenus = menusData;",
139
- "(window as any)._forgeWpMockMenus = menusData;" + windowMocksToAdd
140
- );
141
- }
142
-
143
- return content;
81
+ const bps = getSystemBlueprints(process.cwd());
82
+ if (typeof prop === 'string' && prop in bps) {
83
+ return bps[prop];
144
84
  }
145
85
  return target[prop];
146
86
  }
@@ -1,6 +1,6 @@
1
- import { existsSync, readFileSync } from "node:fs";
2
- import path from "node:path";
3
- import { spawnSync } from "node:child_process";
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { spawnSync } from 'node:child_process';
4
4
 
5
5
  /**
6
6
  * @param {string} themeRoot
@@ -9,53 +9,58 @@ import { spawnSync } from "node:child_process";
9
9
  */
10
10
  export function buildAssets(themeRoot, options = {}) {
11
11
  const pm = options.packageManager ?? detectPackageManager();
12
- const build = runPackageScript(themeRoot, pm, "build");
12
+ const build = runPackageScript(themeRoot, pm, 'build', options);
13
13
 
14
14
  if (build.status !== 0) {
15
- throw new Error("Vite build failed. Fix build errors and run export again.");
15
+ if (build.stdout) process.stdout.write(build.stdout);
16
+ if (build.stderr) process.stderr.write(build.stderr);
17
+ throw new Error(
18
+ 'Vite build failed. Fix build errors and run export again.',
19
+ );
16
20
  }
17
21
 
18
22
  return readBuildManifest(themeRoot);
19
23
  }
20
24
 
21
25
  function detectPackageManager() {
22
- const ua = process.env.npm_config_user_agent ?? "";
23
- if (ua.startsWith("pnpm/")) return "pnpm";
24
- if (ua.startsWith("yarn/")) return "yarn";
25
- if (ua.startsWith("bun/")) return "bun";
26
- return "npm";
26
+ const ua = process.env.npm_config_user_agent ?? '';
27
+ if (ua.startsWith('pnpm/')) return 'pnpm';
28
+ if (ua.startsWith('yarn/')) return 'yarn';
29
+ if (ua.startsWith('bun/')) return 'bun';
30
+ return 'npm';
27
31
  }
28
32
 
29
- function runPackageScript(cwd, pm, script) {
33
+ function runPackageScript(cwd, pm, script, options = {}) {
30
34
  const env = { ...process.env, INIT_CWD: cwd };
35
+ const stdio = options.verbose ? 'inherit' : 'pipe';
31
36
 
32
37
  switch (pm) {
33
- case "pnpm":
34
- return spawnSync("pnpm", ["run", script], {
38
+ case 'pnpm':
39
+ return spawnSync('pnpm', ['run', script], {
35
40
  cwd,
36
- stdio: "inherit",
37
- shell: process.platform === "win32",
41
+ stdio,
42
+ shell: process.platform === 'win32',
38
43
  env,
39
44
  });
40
- case "yarn":
41
- return spawnSync("yarn", ["run", script], {
45
+ case 'yarn':
46
+ return spawnSync('yarn', ['run', script], {
42
47
  cwd,
43
- stdio: "inherit",
44
- shell: process.platform === "win32",
48
+ stdio,
49
+ shell: process.platform === 'win32',
45
50
  env,
46
51
  });
47
- case "bun":
48
- return spawnSync("bun", ["run", script], {
52
+ case 'bun':
53
+ return spawnSync('bun', ['run', script], {
49
54
  cwd,
50
- stdio: "inherit",
51
- shell: process.platform === "win32",
55
+ stdio,
56
+ shell: process.platform === 'win32',
52
57
  env,
53
58
  });
54
59
  default:
55
- return spawnSync("npm", ["run", script], {
60
+ return spawnSync('npm', ['run', script], {
56
61
  cwd,
57
- stdio: "inherit",
58
- shell: process.platform === "win32",
62
+ stdio,
63
+ shell: process.platform === 'win32',
59
64
  env,
60
65
  });
61
66
  }
@@ -67,30 +72,30 @@ function runPackageScript(cwd, pm, script) {
67
72
  */
68
73
  export function readBuildManifest(themeRoot) {
69
74
  const candidates = [
70
- path.join(themeRoot, "dist", ".vite", "manifest.json"),
71
- path.join(themeRoot, "dist", "manifest.json"),
75
+ path.join(themeRoot, 'dist', '.vite', 'manifest.json'),
76
+ path.join(themeRoot, 'dist', 'manifest.json'),
72
77
  ];
73
78
 
74
79
  const manifestPath = candidates.find((candidate) => existsSync(candidate));
75
80
 
76
81
  if (!manifestPath) {
77
82
  throw new Error(
78
- "Build manifest not found. Enable build.manifest in vite.config.ts and run build first.",
83
+ 'Build manifest not found. Enable build.manifest in vite.config.ts and run build first.',
79
84
  );
80
85
  }
81
86
 
82
- const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
87
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
83
88
  const entry =
84
- manifest["index.html"] ??
89
+ manifest['index.html'] ??
85
90
  Object.values(manifest).find((chunk) => chunk?.isEntry);
86
91
 
87
92
  if (!entry?.file) {
88
- throw new Error("Could not find entry chunk in Vite manifest");
93
+ throw new Error('Could not find entry chunk in Vite manifest');
89
94
  }
90
95
 
91
96
  const cssFile = entry.css?.[0];
92
97
  if (!cssFile) {
93
- throw new Error("No CSS file in Vite build output");
98
+ throw new Error('No CSS file in Vite build output');
94
99
  }
95
100
 
96
101
  return {
@@ -0,0 +1,102 @@
1
+ function normalizePagePath(url) {
2
+ if (typeof url !== 'string' || !url.startsWith('/') || url.startsWith('//')) {
3
+ return '';
4
+ }
5
+
6
+ const path = url.split(/[?#]/, 1)[0].replace(/^\/+|\/+$/g, '');
7
+ return path;
8
+ }
9
+
10
+ function pathToTemplateSlug(path) {
11
+ return path.split('/').filter(Boolean).join('-').toLowerCase();
12
+ }
13
+
14
+ function titleToTemplateSlug(title) {
15
+ const componentName =
16
+ String(title)
17
+ .replace(/[^a-zA-Z0-9]/g, ' ')
18
+ .trim()
19
+ .split(/\s+/)
20
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
21
+ .join('') + 'Page';
22
+
23
+ return componentName.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
24
+ }
25
+
26
+ function flattenMenuItems(items, output = []) {
27
+ if (!Array.isArray(items)) return output;
28
+
29
+ for (const item of items) {
30
+ if (!item || typeof item !== 'object') continue;
31
+ output.push(item);
32
+ flattenMenuItems(item.children, output);
33
+ }
34
+
35
+ return output;
36
+ }
37
+
38
+ /**
39
+ * Maps compiled Page templates to their matching menu route and removes
40
+ * duplicate templates that describe the same WordPress page path.
41
+ */
42
+ export function collectPageTemplateRoutes(templateSlugs, menus = {}) {
43
+ const items = Object.entries(menus)
44
+ .filter(([location]) => !location.startsWith('_'))
45
+ .flatMap(([, menuItems]) => flattenMenuItems(menuItems));
46
+ const routes = new Map();
47
+
48
+ for (const templateSlug of templateSlugs) {
49
+ let matchedRoute = null;
50
+
51
+ for (const item of items) {
52
+ const path = normalizePagePath(item.url);
53
+ if (!path) continue;
54
+
55
+ if (titleToTemplateSlug(item.title) === templateSlug) {
56
+ matchedRoute = {
57
+ title: item.title,
58
+ slug: path,
59
+ score: 4,
60
+ };
61
+ break;
62
+ }
63
+
64
+ const routeSlug = pathToTemplateSlug(path);
65
+ const templateRouteSlug = templateSlug.endsWith('-page')
66
+ ? templateSlug.slice(0, -5)
67
+ : templateSlug;
68
+ if (routeSlug === templateRouteSlug) {
69
+ matchedRoute = {
70
+ title: item.title,
71
+ slug: path,
72
+ score: templateSlug.endsWith('-page') ? 3 : 2,
73
+ };
74
+ break;
75
+ }
76
+ }
77
+
78
+ const fallbackSlug = templateSlug.endsWith('-page')
79
+ ? templateSlug.slice(0, -5)
80
+ : templateSlug;
81
+ const route = matchedRoute || {
82
+ title: fallbackSlug
83
+ .split('-')
84
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
85
+ .join(' '),
86
+ slug: fallbackSlug,
87
+ score: 0,
88
+ };
89
+ const existing = routes.get(route.slug);
90
+
91
+ if (!existing || route.score > existing.score) {
92
+ routes.set(route.slug, {
93
+ title: route.title,
94
+ slug: route.slug,
95
+ template: `page-${templateSlug}.php`,
96
+ score: route.score,
97
+ });
98
+ }
99
+ }
100
+
101
+ return Array.from(routes.values(), ({ score, ...route }) => route);
102
+ }
@@ -0,0 +1,175 @@
1
+ import { parse } from '@babel/parser';
2
+
3
+ /**
4
+ * Collects local page routes that exist in the React app (menus + routes.tsx)
5
+ * but have no compiled custom template yet. These must still become WordPress
6
+ * pages — otherwise redirect_canonical() guesses a similar CPT slug
7
+ * (e.g. /about → /product/about-a-chair-aa51/).
8
+ */
9
+
10
+ const RESERVED_FIRST_SEGMENTS = new Set([
11
+ 'product',
12
+ 'products',
13
+ 'product-category',
14
+ 'product-tag',
15
+ 'shop',
16
+ 'cart',
17
+ 'checkout',
18
+ 'my-account',
19
+ 'category',
20
+ 'categories',
21
+ 'tag',
22
+ 'author',
23
+ 'feed',
24
+ 'search',
25
+ 'wp-admin',
26
+ 'wp-json',
27
+ 'wp-content',
28
+ 'wp-includes',
29
+ ]);
30
+
31
+ function titleFromSlug(slug) {
32
+ const leaf = slug.split('/').filter(Boolean).pop() || slug;
33
+ return leaf
34
+ .split('-')
35
+ .filter(Boolean)
36
+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
37
+ .join(' ');
38
+ }
39
+
40
+ function consider(url, title, description, seen, out) {
41
+ if (!url || typeof url !== 'string') return;
42
+ const trimmed = url.trim();
43
+ if (
44
+ !trimmed.startsWith('/') ||
45
+ trimmed.startsWith('//') ||
46
+ trimmed.startsWith('/http')
47
+ ) {
48
+ return;
49
+ }
50
+ const pathOnly = trimmed.split('?')[0].split('#')[0];
51
+ const slug = pathOnly.replace(/^\//, '').replace(/\/$/, '');
52
+ if (!slug || slug.includes(':') || slug.includes('*')) return;
53
+
54
+ const first = slug.split('/')[0];
55
+ if (RESERVED_FIRST_SEGMENTS.has(first)) return;
56
+ if (seen.has(slug)) return;
57
+
58
+ seen.add(slug);
59
+ const entry = {
60
+ slug,
61
+ title: (title && String(title).trim()) || titleFromSlug(slug),
62
+ template: 'page-placeholder.php',
63
+ };
64
+ if (description && String(description).trim()) {
65
+ entry.description = String(description).trim();
66
+ }
67
+ out.push(entry);
68
+ }
69
+
70
+ function walkMenuItems(items, seen, out) {
71
+ if (!Array.isArray(items)) return;
72
+ for (const item of items) {
73
+ if (!item || typeof item !== 'object') continue;
74
+ consider(item.url, null, item.description || null, seen, out);
75
+ if (item.children) walkMenuItems(item.children, seen, out);
76
+ }
77
+ }
78
+
79
+ export function collectStaticRouteDefinitions(routesSource = '') {
80
+ if (!routesSource) return [];
81
+
82
+ const routes = [];
83
+ try {
84
+ const ast = parse(routesSource, {
85
+ sourceType: 'unambiguous',
86
+ plugins: ['jsx', 'typescript'],
87
+ });
88
+
89
+ const visit = (node) => {
90
+ if (!node || typeof node !== 'object') return;
91
+
92
+ if (node.type === 'JSXElement') {
93
+ const opening = node.openingElement;
94
+ if (
95
+ opening.name.type === 'JSXIdentifier' &&
96
+ opening.name.name === 'Route'
97
+ ) {
98
+ const pathAttribute = opening.attributes.find(
99
+ (attribute) =>
100
+ attribute.type === 'JSXAttribute' &&
101
+ attribute.name.type === 'JSXIdentifier' &&
102
+ attribute.name.name === 'path',
103
+ );
104
+ const pathValue = pathAttribute?.value;
105
+ const routePath =
106
+ pathValue?.type === 'StringLiteral'
107
+ ? pathValue.value
108
+ : pathValue?.type === 'JSXExpressionContainer' &&
109
+ pathValue.expression.type === 'StringLiteral'
110
+ ? pathValue.expression.value
111
+ : '';
112
+
113
+ if (routePath.startsWith('/')) {
114
+ const block = routesSource.slice(node.start, node.end);
115
+ const titleMatch = block.match(
116
+ /\btitle\s*[:=]\s*['"`]([^'"`]+)['"`]/i,
117
+ );
118
+ const descMatch = block.match(
119
+ /\bdescription\s*[:=]\s*['"`]([^'"`]+)['"`]/i,
120
+ );
121
+ routes.push({
122
+ path: routePath,
123
+ title: titleMatch ? titleMatch[1] : null,
124
+ description: descMatch ? descMatch[1] : null,
125
+ });
126
+ }
127
+ }
128
+ }
129
+
130
+ for (const value of Object.values(node)) {
131
+ if (Array.isArray(value)) {
132
+ for (const child of value) visit(child);
133
+ } else if (value && typeof value === 'object') {
134
+ visit(value);
135
+ }
136
+ }
137
+ };
138
+
139
+ visit(ast);
140
+ } catch {
141
+ return [];
142
+ }
143
+
144
+ return routes;
145
+ }
146
+
147
+ /**
148
+ * @param {{ menus?: Record<string, any>, routesSource?: string, existingSlugs?: string[] }} opts
149
+ * @returns {Array<{ slug: string, title: string, description?: string, template: string }>}
150
+ */
151
+ export function collectFallbackPageRoutes({
152
+ menus = {},
153
+ routesSource = '',
154
+ existingSlugs = [],
155
+ } = {}) {
156
+ const seen = new Set(
157
+ (existingSlugs || [])
158
+ .map((s) => String(s).replace(/^\/+|\/+$/g, ''))
159
+ .filter(Boolean),
160
+ );
161
+ const out = [];
162
+
163
+ if (routesSource) {
164
+ for (const route of collectStaticRouteDefinitions(routesSource)) {
165
+ consider(route.path, route.title, route.description, seen, out);
166
+ }
167
+ }
168
+
169
+ for (const [location, items] of Object.entries(menus || {})) {
170
+ if (location.startsWith('_')) continue;
171
+ walkMenuItems(items, seen, out);
172
+ }
173
+
174
+ return out;
175
+ }