@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
@@ -1,12 +1,296 @@
1
- import { fileURLToPath } from 'node:url';
1
+ import { fileURLToPath, pathToFileURL } from 'node:url';
2
2
  import path from 'node:path';
3
+ import { readFileSync, existsSync, readdirSync } from 'node:fs';
4
+ import { createRequire } from 'node:module';
5
+ import { transformThemeFile } from './hydration/index.js';
6
+
7
+ function polyfillImportMetaGlob(code, filePath) {
8
+ if (!code.includes('import.meta.glob')) return code;
9
+ // The options object must not use [\s\S]* — a trailing comma after
10
+ // `{ eager: true },` is normal, and a greedy scan then eats the rest
11
+ // of the module until some later `}` `)` (the first <Route />).
12
+ const replaced = code.replace(
13
+ /import\.meta\.glob(?:\s*<[^()]*>)?\s*\(\s*(['"])([^'"]+)\1(?:\s*,\s*\{(?:[^{}]|\{[^{}]*\})*\})?\s*,?\s*\)/g,
14
+ (match, _quote, globPattern) => {
15
+ try {
16
+ const fileDir = path.dirname(filePath);
17
+ const cleanGlob = globPattern.replace(/^\.\//, '');
18
+ const globDir = path.join(fileDir, path.dirname(cleanGlob));
19
+ if (existsSync(globDir)) {
20
+ const extRegex = /\.(tsx|jsx|ts|js)$/;
21
+ const entries = readdirSync(globDir)
22
+ .filter((f) => extRegex.test(f) && !f.endsWith('.d.ts'))
23
+ .map((f) => {
24
+ const relKey =
25
+ './' +
26
+ path
27
+ .relative(fileDir, path.join(globDir, f))
28
+ .replace(/\\/g, '/');
29
+ const href = pathToFileURL(path.join(globDir, f)).href;
30
+ // Dynamic import, not require(): the SSR loader only
31
+ // transpiles TypeScript on the ESM load hook.
32
+ return `"${relKey}": await import(${JSON.stringify(href)})`;
33
+ });
34
+ return `{ ${entries.join(', ')} }`;
35
+ }
36
+ } catch (e) {}
37
+ return '({})';
38
+ },
39
+ );
40
+ return replaced;
41
+ }
42
+
43
+ const require = createRequire(import.meta.url);
44
+ let ts = null;
45
+ try {
46
+ ts = require('typescript');
47
+ } catch (e) {
48
+ let currentDir = process.cwd();
49
+ while (true) {
50
+ const tsPath = path.join(currentDir, 'node_modules', 'typescript');
51
+ if (existsSync(tsPath)) {
52
+ try {
53
+ const rootRequire = createRequire(
54
+ path.join(currentDir, 'package.json'),
55
+ );
56
+ ts = rootRequire('typescript');
57
+ break;
58
+ } catch (e2) {}
59
+ }
60
+ const parentDir = path.dirname(currentDir);
61
+ if (parentDir === currentDir) break;
62
+ currentDir = parentDir;
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Vite/esbuild synthesize a named export for `export { Foo as default }`
68
+ * (and `export default Foo`). Node native ESM does not, so
69
+ * `import { ScrollTrigger } from 'gsap/ScrollTrigger'` works in `vite dev`
70
+ * and fails during compile-time SSR. Mirror that interop here.
71
+ *
72
+ * @param {string} source
73
+ * @returns {string|null} patched source, or null if no change is needed
74
+ */
75
+ export function synthesizeNamedExportsFromDefault(source) {
76
+ if (typeof source !== 'string' || source.length === 0) return null;
77
+
78
+ const names = new Set();
79
+
80
+ for (const block of source.matchAll(/export\s*\{([^}]+)\}/g)) {
81
+ for (const part of block[1].split(',')) {
82
+ const trimmed = part.trim();
83
+ if (!trimmed) continue;
84
+ const asDefault = trimmed.match(/^([A-Za-z_$][\w$]*)\s+as\s+default$/);
85
+ if (asDefault) names.add(asDefault[1]);
86
+ }
87
+ }
88
+
89
+ const identDefault = source.match(
90
+ /export\s+default\s+([A-Za-z_$][\w$]*)\s*;/,
91
+ );
92
+ if (identDefault) names.add(identDefault[1]);
93
+
94
+ const fnDefault = source.match(
95
+ /export\s+default\s+(?:async\s+)?function\s+([A-Za-z_$][\w$]*)/,
96
+ );
97
+ if (fnDefault) names.add(fnDefault[1]);
98
+
99
+ const classDefault = source.match(
100
+ /export\s+default\s+class\s+([A-Za-z_$][\w$]*)/,
101
+ );
102
+ if (classDefault) names.add(classDefault[1]);
103
+
104
+ const missing = [...names].filter(
105
+ (name) => !hasExplicitNamedExport(source, name),
106
+ );
107
+ if (missing.length === 0) return null;
108
+
109
+ return `${source}\n${missing.map((n) => `export { ${n} };`).join('\n')}\n`;
110
+ }
111
+
112
+ function hasExplicitNamedExport(source, name) {
113
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
114
+ if (
115
+ new RegExp(
116
+ `export\\s+(?:async\\s+)?(?:function|class|const|let|var)\\s+${escaped}\\b`,
117
+ ).test(source)
118
+ ) {
119
+ return true;
120
+ }
121
+
122
+ for (const block of source.matchAll(/export\s*\{([^}]+)\}/g)) {
123
+ for (const part of block[1].split(',')) {
124
+ const trimmed = part.trim();
125
+ if (!trimmed) continue;
126
+ const pieces = trimmed.split(/\s+as\s+/).map((s) => s.trim());
127
+ const local = pieces[0];
128
+ const alias = pieces[1];
129
+ if (alias === 'default') continue;
130
+ if (alias === name || (!alias && local === name)) return true;
131
+ }
132
+ }
133
+
134
+ return false;
135
+ }
136
+
137
+ /** True when a .js file is authored as ESM (import/export) rather than CJS. */
138
+ export function sourceLooksLikeEsm(source) {
139
+ return (
140
+ typeof source === 'string' &&
141
+ (/(^|\n)\s*export\s/.test(source) ||
142
+ /(^|\n)\s*import\s/.test(source) ||
143
+ /(^|\n)\s*import\s*\(/.test(source))
144
+ );
145
+ }
146
+
147
+ /**
148
+ * Node.js ESM resolve hook to resolve alias paths (@/*) and extensionless TypeScript files.
149
+ */
150
+ export async function resolve(specifier, context, defaultResolve) {
151
+ // 1. Resolve @/* alias to <themeRoot>/src/*
152
+ if (specifier.startsWith('@/')) {
153
+ let themeRoot = process.env.INIT_CWD || process.cwd();
154
+ if (context.parentURL) {
155
+ try {
156
+ const parentPath = fileURLToPath(context.parentURL);
157
+ const norm = parentPath.replace(/\\/g, '/');
158
+ if (norm.includes('/src/')) {
159
+ themeRoot = parentPath.substring(0, norm.indexOf('/src/'));
160
+ }
161
+ } catch (e) {}
162
+ }
163
+ const target = path.join(themeRoot, 'src', specifier.slice(2));
164
+ const extensions = [
165
+ '.tsx',
166
+ '.ts',
167
+ '.jsx',
168
+ '.js',
169
+ '/index.tsx',
170
+ '/index.ts',
171
+ '/index.jsx',
172
+ '/index.js',
173
+ ];
174
+ for (const ext of extensions) {
175
+ const full = target + ext;
176
+ if (existsSync(full)) {
177
+ return {
178
+ url: pathToFileURL(full).href,
179
+ format: 'module',
180
+ shortCircuit: true,
181
+ };
182
+ }
183
+ }
184
+ if (existsSync(target)) {
185
+ return {
186
+ url: pathToFileURL(target).href,
187
+ format: 'module',
188
+ shortCircuit: true,
189
+ };
190
+ }
191
+ }
192
+
193
+ // 2. Resolve relative imports without extensions.
194
+ if (specifier.startsWith('.') && context.parentURL) {
195
+ try {
196
+ const parentPath = fileURLToPath(context.parentURL);
197
+ const target = path.resolve(path.dirname(parentPath), specifier);
198
+ const extensions = [
199
+ '.tsx',
200
+ '.ts',
201
+ '.jsx',
202
+ '.js',
203
+ '/index.tsx',
204
+ '/index.ts',
205
+ '/index.jsx',
206
+ '/index.js',
207
+ ];
208
+ for (const ext of extensions) {
209
+ const full = target + ext;
210
+ if (existsSync(full)) {
211
+ return {
212
+ url: pathToFileURL(full).href,
213
+ format: 'module',
214
+ shortCircuit: true,
215
+ };
216
+ }
217
+ }
218
+ } catch (e) {}
219
+ }
220
+
221
+ return defaultResolve(specifier, context, defaultResolve);
222
+ }
3
223
 
4
224
  /**
5
225
  * Node.js ESM Loader hook to intercept and mock static asset imports (images, styles, fonts)
6
- * during server-side theme compilation.
226
+ * and compile TypeScript/TSX on the fly during server-side theme compilation.
7
227
  */
8
228
  export async function load(url, context, defaultLoad) {
9
229
  const cleanUrl = url.split('?')[0].split('#')[0];
230
+
231
+ // 1. Intercept TSX/TS file imports to compile with AST transforms
232
+ if (
233
+ (cleanUrl.endsWith('.tsx') ||
234
+ (cleanUrl.endsWith('.ts') && !cleanUrl.endsWith('.d.ts'))) &&
235
+ !cleanUrl.includes('/node_modules/') &&
236
+ (!cleanUrl.includes('/.forgewp/') || cleanUrl.includes('/src/.forgewp/'))
237
+ ) {
238
+ try {
239
+ const filePath = fileURLToPath(cleanUrl);
240
+ const code = readFileSync(filePath, 'utf8');
241
+
242
+ const themeRoot = cleanUrl.includes('/src/')
243
+ ? filePath.substring(0, filePath.replace(/\\/g, '/').indexOf('/src/'))
244
+ : process.cwd();
245
+
246
+ // Apply the JSX wrapper transformations
247
+ let transformedCode = transformThemeFile(code, filePath, themeRoot);
248
+ transformedCode = polyfillImportMetaGlob(transformedCode, filePath);
249
+
250
+ if (ts) {
251
+ const transpileResult = ts.transpileModule(transformedCode, {
252
+ compilerOptions: {
253
+ target: ts.ScriptTarget.ES2022,
254
+ module: ts.ModuleKind.ESNext,
255
+ jsx: ts.JsxEmit.React,
256
+ allowJs: true,
257
+ },
258
+ });
259
+ return {
260
+ format: 'module',
261
+ source: transpileResult.outputText,
262
+ shortCircuit: true,
263
+ };
264
+ }
265
+ } catch (e) {
266
+ console.error(
267
+ `[ForgeWP SSR Loader Error] Failed to load/transpile ${url}:`,
268
+ e,
269
+ );
270
+ }
271
+ }
272
+
273
+ // 2. Intercept JSON files to return valid JS modules
274
+ if (cleanUrl.endsWith('.json')) {
275
+ try {
276
+ const filePath = fileURLToPath(cleanUrl);
277
+ const jsonContent = readFileSync(filePath, 'utf8');
278
+ return {
279
+ format: 'module',
280
+ source: `export default ${jsonContent};`,
281
+ shortCircuit: true,
282
+ };
283
+ } catch (e) {
284
+ console.error(`[ForgeWP SSR Loader] Failed to load JSON ${url}:`, e);
285
+ return {
286
+ format: 'module',
287
+ source: 'export default {};',
288
+ shortCircuit: true,
289
+ };
290
+ }
291
+ }
292
+
293
+ // 3. Intercept static assets to return mock values
10
294
  if (
11
295
  cleanUrl.endsWith('.css') ||
12
296
  cleanUrl.endsWith('.png') ||
@@ -44,6 +328,32 @@ export async function load(url, context, defaultLoad) {
44
328
  shortCircuit: true,
45
329
  };
46
330
  }
331
+
332
+ // Serve node_modules ESM ourselves. Downstream loaders (tsx) re-bundle some
333
+ // packages (gsap plugins) into `export default` only, so
334
+ // `import { ScrollTrigger } from 'gsap/ScrollTrigger'` — valid in Vite and
335
+ // in Node native ESM — fails during compile-time SSR.
336
+ if (
337
+ /\/node_modules\//.test(cleanUrl) &&
338
+ (cleanUrl.endsWith('.js') || cleanUrl.endsWith('.mjs'))
339
+ ) {
340
+ try {
341
+ const filePath = fileURLToPath(cleanUrl);
342
+ if (existsSync(filePath)) {
343
+ const source = readFileSync(filePath, 'utf8');
344
+ if (cleanUrl.endsWith('.mjs') || sourceLooksLikeEsm(source)) {
345
+ const patched = synthesizeNamedExportsFromDefault(source) || source;
346
+ return {
347
+ format: 'module',
348
+ source: patched,
349
+ shortCircuit: true,
350
+ };
351
+ }
352
+ }
353
+ } catch {
354
+ // Fall through to the next loader.
355
+ }
356
+ }
357
+
47
358
  return defaultLoad(url, context, defaultLoad);
48
359
  }
49
-