@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,552 +0,0 @@
1
- import {
2
- existsSync,
3
- mkdirSync,
4
- readFileSync,
5
- readdirSync,
6
- statSync,
7
- writeFileSync,
8
- } from 'node:fs';
9
- import path from 'node:path';
10
-
11
- function parseAttributes(attrStr) {
12
- const attrs = {};
13
- const regex = /([a-zA-Z0-9_-]+)(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|(?:\{([\s\S]*?)\}))|(?=\s|$))/gi;
14
- let match;
15
- while ((match = regex.exec(attrStr)) !== null) {
16
- const key = match[1];
17
- const val = match[2] || match[3] || match[4] || true;
18
- attrs[key] = val;
19
- }
20
- return attrs;
21
- }
22
-
23
- function parseJsxToAst(jsx) {
24
- const tokens = [];
25
- let index = 0;
26
-
27
- while (index < jsx.length) {
28
- const char = jsx[index];
29
-
30
- if (char === '<') {
31
- let tagEnd = jsx.indexOf('>', index);
32
- if (tagEnd === -1) break;
33
-
34
- let tagStr = jsx.substring(index, tagEnd + 1);
35
- const isClosing = tagStr.startsWith('</');
36
- const isSelfClosing = tagStr.endsWith('/>');
37
-
38
- const tagNameMatch = tagStr.match(/<\/?([a-zA-Z0-9_-]+)/);
39
- const tagName = tagNameMatch ? tagNameMatch[1] : '';
40
-
41
- tokens.push({
42
- type: 'tag',
43
- name: tagName,
44
- raw: tagStr,
45
- isClosing,
46
- isSelfClosing
47
- });
48
-
49
- index = tagEnd + 1;
50
- } else {
51
- let nextTag = jsx.indexOf('<', index);
52
- let text = nextTag === -1 ? jsx.substring(index) : jsx.substring(index, nextTag);
53
-
54
- if (text.trim()) {
55
- tokens.push({
56
- type: 'text',
57
- value: text
58
- });
59
- }
60
-
61
- index = nextTag === -1 ? jsx.length : nextTag;
62
- }
63
- }
64
-
65
- const root = { type: 'root', children: [] };
66
- const stack = [root];
67
-
68
- for (const token of tokens) {
69
- if (token.type === 'tag') {
70
- if (token.isClosing) {
71
- if (stack.length > 1) {
72
- stack.pop();
73
- }
74
- } else {
75
- const node = {
76
- type: 'element',
77
- name: token.name,
78
- attributes: parseAttributes(token.raw.substring(token.name.length + 1, token.raw.length - (token.isSelfClosing ? 2 : 1))),
79
- children: []
80
- };
81
-
82
- stack[stack.length - 1].children.push(node);
83
-
84
- if (!token.isSelfClosing && token.name !== 'img' && token.name !== 'input' && token.name !== 'br' && token.name !== 'hr') {
85
- stack.push(node);
86
- }
87
- }
88
- } else {
89
- stack[stack.length - 1].children.push({
90
- type: 'text',
91
- value: token.value
92
- });
93
- }
94
- }
95
-
96
- return root;
97
- }
98
-
99
- function generateReactCreateElement(node) {
100
- if (!node) return 'null';
101
-
102
- if (node.type === 'root') {
103
- if (node.children.length === 1) {
104
- return generateReactCreateElement(node.children[0]);
105
- }
106
- return `[${node.children.map(generateReactCreateElement).join(', ')}]`;
107
- }
108
-
109
- if (node.type === 'text') {
110
- const val = node.value.trim();
111
- if (val.startsWith('{') && val.endsWith('}')) {
112
- return val.slice(1, -1).trim();
113
- }
114
- return JSON.stringify(val);
115
- }
116
-
117
- if (node.type === 'element') {
118
- if (node.name === 'WpEditable') {
119
- const tag = String(node.attributes.tagName || 'div').replace(/['"]/g, '').trim();
120
- const valStr = String(node.attributes.value || '').trim();
121
-
122
- let varName = 'value';
123
- const varMatch = valStr.match(/(?:attributes|props)?\.?([a-zA-Z0-9_-]+)$/);
124
- if (varMatch) {
125
- varName = varMatch[1];
126
- }
127
-
128
- const className = node.attributes.className
129
- ? (node.attributes.className.startsWith('{')
130
- ? node.attributes.className.slice(1, -1)
131
- : JSON.stringify(node.attributes.className))
132
- : '""';
133
-
134
- return `createElement(wp.blockEditor.RichText, {
135
- tagName: ${JSON.stringify(tag)},
136
- value: attributes.${varName} || '',
137
- onChange: function(val) { setAttributes({ ${varName}: val }); },
138
- className: ${className}
139
- })`;
140
- }
141
-
142
- const props = {};
143
- for (const [key, val] of Object.entries(node.attributes)) {
144
- const propKey = key === 'className' ? 'className' : key;
145
- if (typeof val === 'string' && val.startsWith('{') && val.endsWith('}')) {
146
- props[propKey] = val.slice(1, -1).trim();
147
- } else {
148
- props[propKey] = JSON.stringify(val);
149
- }
150
- }
151
-
152
- const propsStr = Object.keys(props).length > 0
153
- ? `{ ${Object.entries(props).map(([k, v]) => `${k}: ${v}`).join(', ')} }`
154
- : 'null';
155
-
156
- const childrenStr = node.children.map(generateReactCreateElement).filter(Boolean).join(', ');
157
-
158
- return `createElement(${JSON.stringify(node.name)}, ${propsStr}${childrenStr ? `, ${childrenStr}` : ''})`;
159
- }
160
- return 'null';
161
- }
162
-
163
- function parseDefineBlock(code, blockSlug) {
164
- const startIndex = code.indexOf('defineBlock(');
165
- if (startIndex === -1) return null;
166
-
167
- let depth = 1;
168
- let i = startIndex + 'defineBlock('.length;
169
- let blockContent = '';
170
-
171
- while (i < code.length && depth > 0) {
172
- const char = code[i];
173
- if (char === '(') depth++;
174
- else if (char === ')') depth--;
175
-
176
- if (depth > 0) {
177
- blockContent += char;
178
- }
179
- i++;
180
- }
181
-
182
- let cleanBlockContent = blockContent;
183
-
184
- cleanBlockContent = cleanBlockContent.replace(
185
- /edit\s*:\s*([\s\S]*?)(?=,\s*(?:save|name|title|category|icon|attributes)\s*:|\s*\}$)/,
186
- 'edit: null'
187
- );
188
- cleanBlockContent = cleanBlockContent.replace(
189
- /save\s*:\s*([\s\S]*?)(?=,\s*(?:edit|name|title|category|icon|attributes)\s*:|\s*\}$)/,
190
- 'save: null'
191
- );
192
-
193
- try {
194
- const evalFn = new Function(`return ${cleanBlockContent};`);
195
- return evalFn();
196
- } catch (e) {
197
- console.warn(`[Gutenberg Block Compiler] parseDefineBlock eval failed:`, e.message);
198
-
199
- const nameMatch = blockContent.match(/name\s*:\s*["']([^"']+)["']/);
200
- const titleMatch = blockContent.match(/title\s*:\s*["']([^"']+)["']/);
201
- const categoryMatch = blockContent.match(/category\s*:\s*["']([^"']+)["']/);
202
- const iconMatch = blockContent.match(/icon\s*:\s*["']([^"']+)["']/);
203
-
204
- let attributes = {};
205
- const attrMatch = blockContent.match(/attributes\s*:\s*(\{[\s\S]*?\})(?:\s*,\s*(?:edit|save)|\s*\})/);
206
- if (attrMatch) {
207
- try {
208
- const attrEval = new Function(`return ${attrMatch[1]};`);
209
- attributes = attrEval();
210
- } catch {}
211
- }
212
-
213
- return {
214
- name: nameMatch ? nameMatch[1] : blockSlug,
215
- title: titleMatch ? titleMatch[1] : blockSlug,
216
- category: categoryMatch ? categoryMatch[1] : 'design',
217
- icon: iconMatch ? iconMatch[1] : 'info',
218
- attributes
219
- };
220
- }
221
- }
222
-
223
- function extractJsx(code, propertyName) {
224
- const propIndex = code.indexOf(`${propertyName}:`);
225
- if (propIndex === -1) return null;
226
-
227
- const subCode = code.substring(propIndex);
228
- const returnIndex = subCode.indexOf('return (');
229
- if (returnIndex !== -1) {
230
- let depth = 1;
231
- let j = returnIndex + 'return ('.length;
232
- let jsxContent = '';
233
- while (j < subCode.length && depth > 0) {
234
- const c = subCode[j];
235
- if (c === '(') depth++;
236
- else if (c === ')') depth--;
237
-
238
- if (depth > 0) {
239
- jsxContent += c;
240
- }
241
- j++;
242
- }
243
- return jsxContent.trim();
244
- }
245
-
246
- const returnSingleIndex = subCode.indexOf('return ');
247
- if (returnSingleIndex !== -1) {
248
- const afterReturn = subCode.substring(returnSingleIndex + 'return '.length).trim();
249
- if (afterReturn.startsWith('<')) {
250
- const match = afterReturn.match(/^(<[\s\S]*?>)(?:\s*[,;\}]|\s*$)/);
251
- if (match) {
252
- return match[1].trim();
253
- }
254
- }
255
- }
256
-
257
- const arrowIndex = subCode.indexOf('=>');
258
- if (arrowIndex !== -1 && arrowIndex < 80) {
259
- const afterArrow = subCode.substring(arrowIndex + 2).trim();
260
- if (afterArrow.startsWith('(')) {
261
- let depth = 1;
262
- let j = 1;
263
- let jsxContent = '';
264
- while (j < afterArrow.length && depth > 0) {
265
- const c = afterArrow[j];
266
- if (c === '(') depth++;
267
- else if (c === ')') depth--;
268
- if (depth > 0) jsxContent += c;
269
- j++;
270
- }
271
- return jsxContent.trim();
272
- } else if (afterArrow.startsWith('<')) {
273
- const match = afterArrow.match(/^(<[\s\S]*?>)(?:\s*[,;\}]|\s*$)/);
274
- if (match) {
275
- return match[1].trim();
276
- }
277
- }
278
- }
279
-
280
- return null;
281
- }
282
-
283
- function parenthesizeTernaryExpression(expr) {
284
- const questionCount = (expr.match(/\?/g) || []).length;
285
- if (questionCount <= 1) return expr;
286
-
287
- let depth = 0;
288
- let firstQuestionIdx = -1;
289
- let firstColonIdx = -1;
290
-
291
- for (let i = 0; i < expr.length; i++) {
292
- const char = expr[i];
293
- if (char === '(' || char === '{' || char === '[') depth++;
294
- else if (char === ')' || char === '}' || char === ']') depth--;
295
- else if (depth === 0) {
296
- if (char === '?' && firstQuestionIdx === -1) {
297
- firstQuestionIdx = i;
298
- } else if (char === ':' && firstQuestionIdx !== -1 && firstColonIdx === -1) {
299
- firstColonIdx = i;
300
- break;
301
- }
302
- }
303
- }
304
-
305
- if (firstQuestionIdx === -1 || firstColonIdx === -1) {
306
- return expr;
307
- }
308
-
309
- const cond = expr.substring(0, firstQuestionIdx).trim();
310
- const truthy = expr.substring(firstQuestionIdx + 1, firstColonIdx).trim();
311
- const falsy = expr.substring(firstColonIdx + 1).trim();
312
-
313
- const newTruthy = parenthesizeTernaryExpression(truthy);
314
- const newFalsy = parenthesizeTernaryExpression(falsy);
315
-
316
- const wrapTruthy = (truthy.includes('?') && !truthy.startsWith('(')) ? `(${newTruthy})` : newTruthy;
317
- const wrapFalsy = (falsy.includes('?') && !falsy.startsWith('(')) ? `(${newFalsy})` : newFalsy;
318
-
319
- return `${cond} ? ${wrapTruthy} : ${wrapFalsy}`;
320
- }
321
-
322
- function translateJsExpressionToPhp(jsExpr) {
323
- const phpExpr = jsExpr
324
- .replace(/(?:attributes|props)\.([a-zA-Z0-9_-]+)/g, "$attributes['$1']")
325
- .replace(/\b([a-zA-Z0-9_-]+)\b/g, (name) => {
326
- return name;
327
- });
328
- return parenthesizeTernaryExpression(phpExpr);
329
- }
330
-
331
- /**
332
- * Scans the `src/blocks/` folder, parses block settings and JSX content,
333
- * and compiles them into official, dynamic WordPress blocks.
334
- *
335
- * @param {string} themeRoot
336
- * @param {string} outDir
337
- * @returns {string[]} Compiled block slugs
338
- */
339
- export function compileBlocks(themeRoot, outDir) {
340
- const blocksDir = path.join(themeRoot, 'src', 'blocks');
341
- const blockSlugs = [];
342
-
343
- if (!existsSync(blocksDir)) {
344
- return blockSlugs;
345
- }
346
-
347
- const entries = readdirSync(blocksDir);
348
- for (const entry of entries) {
349
- const entryPath = path.join(blocksDir, entry);
350
- let blockFile = '';
351
- let blockSlug = '';
352
-
353
- if (statSync(entryPath).isDirectory()) {
354
- const indexPath = path.join(entryPath, 'index.tsx');
355
- if (existsSync(indexPath)) {
356
- blockFile = indexPath;
357
- blockSlug = entry
358
- .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
359
- .toLowerCase()
360
- .replace(/[^a-z0-9]+/g, '-');
361
- }
362
- } else if (entry.endsWith('.tsx') || entry.endsWith('.jsx')) {
363
- blockFile = entryPath;
364
- blockSlug = entry
365
- .replace(/\.(tsx|jsx)$/, '')
366
- .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
367
- .toLowerCase()
368
- .replace(/[^a-z0-9]+/g, '-');
369
- }
370
-
371
- if (blockFile) {
372
- try {
373
- const code = readFileSync(blockFile, 'utf8');
374
-
375
- const settingsMatch = code.match(
376
- /export\s+const\s+settings\s*=\s*(\{[\s\S]*?\});/,
377
- );
378
- let settings = {
379
- apiVersion: 3,
380
- name: `forgewp/${blockSlug}`,
381
- title: blockSlug
382
- .split('-')
383
- .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
384
- .join(' '),
385
- category: 'design',
386
- icon: 'admin-generic',
387
- attributes: {},
388
- render: 'file:./render.php',
389
- };
390
-
391
- let parsedSettings = null;
392
- if (code.includes('defineBlock(')) {
393
- parsedSettings = parseDefineBlock(code, blockSlug);
394
- } else if (settingsMatch) {
395
- try {
396
- const evalFn = new Function(`return ${settingsMatch[1]};`);
397
- parsedSettings = evalFn();
398
- } catch (e) {
399
- console.warn(
400
- `[Gutenberg Block Compiler] Error parsing legacy settings for ${blockSlug}:`,
401
- e.message,
402
- );
403
- }
404
- }
405
-
406
- if (parsedSettings) {
407
- settings = { ...settings, ...parsedSettings };
408
- settings.name = settings.name ? (settings.name.includes('/') ? settings.name : `forgewp/${settings.name}`) : `forgewp/${blockSlug}`;
409
- settings.apiVersion = 3;
410
- settings.render = 'file:./render.php';
411
- }
412
-
413
- // Extract JSX from save first, then edit as fallback
414
- let jsx = '';
415
- if (code.includes('save:')) {
416
- jsx = extractJsx(code, 'save');
417
- }
418
- if (!jsx && code.includes('edit:')) {
419
- jsx = extractJsx(code, 'edit');
420
- }
421
-
422
- if (!jsx) {
423
- const returnMatch = code.match(/return\s*\(\s*(<[\s\S]*?>)\s*\)/);
424
- if (returnMatch) {
425
- jsx = returnMatch[1];
426
- } else {
427
- const returnMatchSingle = code.match(/return\s+(<[\s\S]*?>);/);
428
- if (returnMatchSingle) {
429
- jsx = returnMatchSingle[1];
430
- }
431
- }
432
- }
433
-
434
- if (!jsx) {
435
- console.warn(
436
- `[Gutenberg Block Compiler] Skipping block ${blockSlug}: No returning JSX element found.`,
437
- );
438
- continue;
439
- }
440
-
441
- // Extract custom edit JSX for block-canvas high-fidelity controls using AST parser
442
- let editJsx = '';
443
- if (code.includes('edit:')) {
444
- editJsx = extractJsx(code, 'edit');
445
- }
446
- if (editJsx) {
447
- try {
448
- const ast = parseJsxToAst(editJsx);
449
- const customEditJsx = generateReactCreateElement(ast);
450
- settings.customEditJsx = customEditJsx;
451
- } catch (e) {
452
- console.warn(`[Gutenberg Block Compiler] Failed to parse custom edit JSX for ${blockSlug}:`, e.message);
453
- }
454
- }
455
-
456
- let phpMarkup = jsx;
457
-
458
- // Transpile <WpEditable> into standard JSX element so subsequent regexes can process it
459
- phpMarkup = phpMarkup.replace(
460
- /<WpEditable\s+([^>]*?)(?:\/>|>([\s\S]*?)<\/WpEditable>)/g,
461
- (match, attrsStr, children) => {
462
- const getAttr = (name) => {
463
- const regex = new RegExp(
464
- `${name}=(?:"([^"]*)"|'([^']*)'|\\{\\s*(?:attributes\\.|props\\.)?([a-zA-Z0-9_-]+)\\s*\\})`
465
- );
466
- const m = attrsStr.match(regex);
467
- return m ? m[1] || m[2] || m[3] || '' : '';
468
- };
469
-
470
- const tag = getAttr('tagName') || 'div';
471
- const valueVar = getAttr('value');
472
-
473
- let cleanAttrs = attrsStr
474
- .replace(/tagName=(?:"[^"]*"|'[^']*'|\{[^\}]*\})/g, '')
475
- .replace(/value=(?:"[^"]*"|'[^']*'|\{[^\}]*\})/g, '')
476
- .replace(/onChange=(?:"[^"]*"|'[^']*'|\{[^\}]*\})/g, '')
477
- .trim();
478
-
479
- if (cleanAttrs) cleanAttrs = ' ' + cleanAttrs;
480
-
481
- const content = valueVar ? `{attributes.${valueVar}}` : (children || '');
482
-
483
- return `<${tag}${cleanAttrs}>${content}</${tag}>`;
484
- }
485
- );
486
-
487
- // className="..." -> class="..."
488
- phpMarkup = phpMarkup.replace(/className=/g, 'class=');
489
-
490
- // Transpile ES6 template literal conditional classes class={`...`}
491
- phpMarkup = phpMarkup.replace(/class=\{\`([\s\S]*?)\`\}/g, (match, templateLiteralContent) => {
492
- const processed = templateLiteralContent.replace(/\$\{\s*([\s\S]*?)\s*\}/g, (m, jsExpr) => {
493
- const phpExpr = translateJsExpressionToPhp(jsExpr);
494
- return `<?php echo esc_attr( ${phpExpr} ); ?>`;
495
- });
496
- return `class="${processed}"`;
497
- });
498
-
499
- // src={image} or src={attributes.image}
500
- phpMarkup = phpMarkup.replace(
501
- /(src|href|alt|title)=\{\s*(?:attributes\.|props\.)?([a-zA-Z0-9_-]+)\s*\}/gi,
502
- (match, attr, varName) => {
503
- const escFunc =
504
- attr === 'href' || attr === 'src' ? 'esc_url' : 'esc_attr';
505
- return `${attr}="<?php echo ${escFunc}( $attributes['${varName}'] ?? '' ); ?>"`;
506
- },
507
- );
508
-
509
- // {title} or {props.title}
510
- phpMarkup = phpMarkup.replace(
511
- /\{\s*(?:attributes\.|props\.)?([a-zA-Z0-9_-]+)\s*\}/g,
512
- (match, varName) => {
513
- return `<?php echo esc_html( $attributes['${varName}'] ?? '' ); ?>`;
514
- },
515
- );
516
-
517
- const renderPhpContent = `<?php
518
- /**
519
- * Gutenberg dynamic block template — ${settings.title}
520
- * Autogenerated by ForgeWP Theme Compiler. Do not modify manually.
521
- */
522
- ?>
523
- ${phpMarkup}
524
- `;
525
-
526
- const blockOutDir = path.join(outDir, 'blocks', blockSlug);
527
- mkdirSync(blockOutDir, { recursive: true });
528
-
529
- // Write block.json and render.php
530
- writeFileSync(
531
- path.join(blockOutDir, 'block.json'),
532
- JSON.stringify(settings, null, 2),
533
- 'utf8',
534
- );
535
- writeFileSync(
536
- path.join(blockOutDir, 'render.php'),
537
- renderPhpContent,
538
- 'utf8',
539
- );
540
-
541
- blockSlugs.push(settings);
542
- } catch (e) {
543
- console.error(
544
- `[Gutenberg Block Compiler] Failed to compile block ${blockSlug}:`,
545
- e.message,
546
- );
547
- }
548
- }
549
- }
550
-
551
- return blockSlugs;
552
- }