@forgewp/compiler 0.4.2 → 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 (144) hide show
  1. package/README.md +70 -3
  2. package/bin/add.js +30 -15
  3. package/bin/analyze.js +66 -1
  4. package/bin/cli.js +149 -70
  5. package/bin/doctor.js +21 -12
  6. package/bin/export.js +69 -20
  7. package/bin/fresh.js +6 -1
  8. package/bin/i18n-extract.js +3 -10
  9. package/bin/i18n-translate.js +15 -24
  10. package/bin/make-block.js +24 -0
  11. package/bin/make-editable.js +166 -0
  12. package/bin/make-form.js +131 -0
  13. package/bin/make-island.js +11 -0
  14. package/bin/make-loop.js +147 -0
  15. package/bin/make-mail.js +27 -0
  16. package/bin/make-page.js +83 -0
  17. package/bin/make-post-type.js +68 -29
  18. package/bin/make-sandbox.js +609 -0
  19. package/bin/make-section.js +221 -0
  20. package/bin/make-shell.js +375 -0
  21. package/bin/repair.js +14 -26
  22. package/bin/seed.js +119 -0
  23. package/bin/sync-routes.js +107 -85
  24. package/lib/adapters/html-adapter.js +13 -3
  25. package/lib/adapters/stub-adapter.js +10 -2
  26. package/lib/add-component.js +153 -92
  27. package/lib/asset-loader.js +333 -1
  28. package/lib/assets/asset-graph.js +432 -0
  29. package/lib/assets/asset-pipeline.js +125 -0
  30. package/lib/assets/diagnostics-report.js +345 -0
  31. package/lib/assets/external-fetcher.js +173 -0
  32. package/lib/assets/font-orchestrator.js +348 -0
  33. package/lib/assets/font-usage-scanner.js +242 -0
  34. package/lib/assets/image-optimizer.js +229 -0
  35. package/lib/assets/index.js +51 -0
  36. package/lib/assets/preload-generator.js +70 -0
  37. package/lib/assets/public-url.js +153 -0
  38. package/lib/block-authoring-help.js +11 -0
  39. package/lib/blocks/ast-parser.js +67 -0
  40. package/lib/blocks/discover-blocks.js +146 -0
  41. package/lib/blocks/editor-scope.js +733 -0
  42. package/lib/blocks/editor-transpiler.js +1229 -0
  43. package/lib/blocks/index.js +2838 -0
  44. package/lib/blocks/php-transpiler.js +4928 -0
  45. package/lib/blocks/scanner.js +1487 -0
  46. package/lib/blocks/shared-utils.js +290 -0
  47. package/lib/blocks/source-sanitize.js +1449 -0
  48. package/lib/blueprints.js +77 -5
  49. package/lib/build-assets.js +38 -33
  50. package/lib/collect-page-template-routes.js +102 -0
  51. package/lib/collect-static-routes.js +175 -0
  52. package/lib/diagnostics.js +58 -33
  53. package/lib/export-theme.js +84 -5
  54. package/lib/extract-template-content.js +90 -0
  55. package/lib/forms-preview.js +42 -0
  56. package/lib/functions/cpt-routing.js +69 -0
  57. package/lib/functions/forms.js +2461 -0
  58. package/lib/functions/hydration-enqueuer.js +400 -0
  59. package/lib/functions/index.js +1623 -0
  60. package/lib/functions/load-menus.js +112 -0
  61. package/lib/functions/load-translations.js +148 -0
  62. package/lib/functions/rest-endpoints.js +2923 -0
  63. package/lib/functions/routing.js +765 -0
  64. package/lib/functions/seed-mock-data.js +392 -0
  65. package/lib/functions/seed-products.js +481 -0
  66. package/lib/functions/settings-page.js +273 -0
  67. package/lib/functions/theme-setup.js +494 -0
  68. package/lib/generate-theme.js +2076 -303
  69. package/lib/hydration/editable-schemas.js +332 -0
  70. package/lib/hydration/enter-hidden-initial.js +65 -0
  71. package/lib/hydration/form-schemas.js +227 -0
  72. package/lib/hydration/index.js +12 -0
  73. package/lib/hydration/is-interactive.js +951 -0
  74. package/lib/hydration/island-split.js +1231 -0
  75. package/lib/hydration/islands-scanner.js +599 -0
  76. package/lib/hydration/resolve-island-chunk.js +103 -0
  77. package/lib/hydration/resolve-island-component.js +52 -0
  78. package/lib/hydration/rollup-inputs.js +81 -0
  79. package/lib/hydration/root-class-extractor.js +220 -0
  80. package/lib/hydration/scan-app-providers.js +154 -0
  81. package/lib/hydration/static-lint.js +382 -0
  82. package/lib/hydration/transform.js +257 -0
  83. package/lib/hydration/uses-block-area.js +49 -0
  84. package/lib/hydration/utils.js +119 -0
  85. package/lib/i18n/translation-cache.js +141 -0
  86. package/lib/icon-registry.js +72 -0
  87. package/lib/index.d.ts +324 -8
  88. package/lib/index.js +3 -2
  89. package/lib/load-config.js +338 -144
  90. package/lib/mail-templates.js +37 -0
  91. package/lib/markup-processor.js +483 -92
  92. package/lib/node-runtime.js +7 -0
  93. package/lib/page-config-plugin.js +84 -0
  94. package/lib/php-builders.js +383 -42
  95. package/lib/react-adapter.js +1053 -246
  96. package/lib/registration-metadata.js +11 -0
  97. package/lib/render-theme.mts +1410 -543
  98. package/lib/route-layout.js +76 -0
  99. package/lib/template-discovery.js +58 -0
  100. package/lib/theme-compatibility.js +32 -0
  101. package/lib/validate-export.js +51 -2
  102. package/lib/validate.js +27 -5
  103. package/lib/virtual-plugin.js +319 -0
  104. package/lib/walkthrough.md +26 -0
  105. package/package.json +17 -5
  106. package/templates/PresetsStyle.tsx +1 -1
  107. package/templates/auth/cms/email-logs.json +9 -0
  108. package/templates/auth/cms/menus.json +11 -0
  109. package/templates/auth/cms/mock-data.json +123 -0
  110. package/templates/auth/cms/roles.json +7 -0
  111. package/templates/auth/cms/sessions.json +1 -0
  112. package/templates/auth/cms/site-settings.json +28 -0
  113. package/templates/auth/cms/translations.json +4 -0
  114. package/templates/auth/cms/users.json +46 -0
  115. package/templates/auth/components/dashboard-view-wrapper.tsx +168 -0
  116. package/templates/auth/components/forgot-password-form-wrapper.tsx +141 -0
  117. package/templates/auth/components/login-form-wrapper.tsx +300 -0
  118. package/templates/auth/components/reset-password-form-wrapper.tsx +190 -0
  119. package/templates/auth/components/signup-form-wrapper.tsx +257 -0
  120. package/templates/auth/components/verify-email-view-wrapper.tsx +265 -0
  121. package/templates/auth/pages/DashboardPage.tsx +12 -0
  122. package/templates/auth/pages/ForgotPasswordPage.tsx +11 -0
  123. package/templates/auth/pages/LoginPage.tsx +11 -0
  124. package/templates/auth/pages/ResetPasswordPage.tsx +11 -0
  125. package/templates/auth/pages/SignUpPage.tsx +11 -0
  126. package/templates/auth/pages/VerifyEmailPage.tsx +11 -0
  127. package/templates/auth/ui/button.tsx +57 -0
  128. package/templates/auth/ui/card.tsx +76 -0
  129. package/templates/auth/ui/field.tsx +242 -0
  130. package/templates/auth/ui/input.tsx +22 -0
  131. package/templates/auth/ui/label.tsx +24 -0
  132. package/templates/auth/ui/separator.tsx +31 -0
  133. package/templates/forgewp-config.ts +70 -3
  134. package/templates/menus.json +12 -10
  135. package/templates/mock-data.json +122 -433
  136. package/templates/products.json +5 -0
  137. package/templates/roles.json +7 -0
  138. package/templates/sessions.json +1 -0
  139. package/templates/users.json +38 -0
  140. package/templates/wordpress.tsx +1835 -1297
  141. package/bin/make-template.js +0 -145
  142. package/lib/block-compiler.js +0 -552
  143. package/lib/functions-builder.js +0 -2044
  144. package/lib/hydration-scanner.js +0 -821
@@ -0,0 +1,1449 @@
1
+ /**
2
+ * TypeScript cleanup + same-file helper extraction for the block compiler.
3
+ *
4
+ * The Gutenberg editor runs plain JS (customEditJsx via new Function), not the
5
+ * original TSX module. Developers still write normal TypeScript — casts, typed
6
+ * params, and module-level helpers — so we sanitize and hoist what the editor
7
+ * (and best-effort PHP render) need.
8
+ */
9
+
10
+ import { translateReplaceTrim } from "./php-transpiler.js";
11
+ import { tryParseSource, traverse, markLegacyFallback } from "./ast-parser.js";
12
+
13
+ const JS_KEYWORDS = new Set([
14
+ 'if', 'else', 'for', 'while', 'do', 'switch', 'case', 'break', 'continue',
15
+ 'return', 'function', 'const', 'let', 'var', 'new', 'typeof', 'instanceof',
16
+ 'void', 'delete', 'throw', 'try', 'catch', 'finally', 'class', 'extends',
17
+ 'super', 'import', 'export', 'default', 'from', 'as', 'of', 'in', 'await',
18
+ 'async', 'yield', 'this', 'true', 'false', 'null', 'undefined', 'NaN',
19
+ 'Infinity', 'debugger', 'with', 'enum', 'implements', 'interface', 'package',
20
+ 'private', 'protected', 'public', 'static', 'readonly', 'keyof', 'infer',
21
+ 'satisfies', 'asserts', 'is', 'never', 'unknown', 'any', 'string', 'number',
22
+ 'boolean', 'object', 'symbol', 'bigint',
23
+ ]);
24
+
25
+ /**
26
+ * Strip TypeScript syntax so the remaining text is valid plain JS.
27
+ *
28
+ * AST-based (see ast-parser.js): parses `code` with @babel/parser once,
29
+ * walks it for TS-only node types (type annotations, `as`/`satisfies` casts,
30
+ * non-null assertions, generic call type args, interface/type declarations),
31
+ * and deletes exactly those byte ranges from the original text — offsets
32
+ * come straight from the AST, so nested generics/casts can never be
33
+ * misidentified the way a regex boundary can (the bug class this replaces:
34
+ * cast-stripping corrupting an adjacent computed property, a ternary branch
35
+ * read as a typed param list, etc.).
36
+ *
37
+ * Many callers still pass text fragments produced by older brace-balancing
38
+ * extraction (a function body's statements up to `return`, a bare JSX
39
+ * subtree) rather than standalone-parseable source — `code` is parsed with
40
+ * `allowReturnOutsideFunction` to cover the common fragment shapes, but
41
+ * anything that still fails to parse falls back to the legacy regex/text-
42
+ * scanning implementation so behavior never regresses on those cases.
43
+ */
44
+ export function stripTypeScriptSyntax(code) {
45
+ if (!code || typeof code !== 'string') return code;
46
+
47
+ const ast = tryParseSource(code);
48
+ if (ast) {
49
+ try {
50
+ return spliceRanges(code, collectTsStripRanges(ast, code));
51
+ } catch {
52
+ // Fall through to the legacy text-based stripper below.
53
+ }
54
+ }
55
+ markLegacyFallback('source-sanitize:stripTypeScriptSyntax');
56
+ return stripTypeScriptSyntaxLegacy(code);
57
+ }
58
+
59
+ /**
60
+ * Collect [start, end) byte ranges of TS-only syntax to delete from `code`,
61
+ * per the AST produced by ast-parser.js's parseSource.
62
+ */
63
+ function collectTsStripRanges(ast, code) {
64
+ const ranges = [];
65
+
66
+ function addTypeParamsRange(node) {
67
+ if (node.typeParameters) {
68
+ ranges.push([node.typeParameters.start, node.typeParameters.end]);
69
+ }
70
+ }
71
+
72
+ traverse(ast, {
73
+ ImportDeclaration(path) {
74
+ if (path.node.importKind === 'type') ranges.push([path.node.start, path.node.end]);
75
+ },
76
+ ExportNamedDeclaration(path) {
77
+ if (path.node.exportKind === 'type') ranges.push([path.node.start, path.node.end]);
78
+ },
79
+ TSInterfaceDeclaration(path) {
80
+ ranges.push([path.node.start, path.node.end]);
81
+ },
82
+ TSTypeAliasDeclaration(path) {
83
+ ranges.push([path.node.start, path.node.end]);
84
+ },
85
+ TSTypeAnnotation(path) {
86
+ // `name?: Type` — the `?` optional marker isn't part of this node's own
87
+ // range (it belongs to the owning Identifier/pattern), so extend the
88
+ // deletion left across it when present.
89
+ let start = path.node.start;
90
+ const parent = path.parent;
91
+ if (parent && parent.optional) {
92
+ let i = start - 1;
93
+ while (i >= 0 && /\s/.test(code[i])) i--;
94
+ if (i >= 0 && code[i] === '?') start = i;
95
+ }
96
+ ranges.push([start, path.node.end]);
97
+ },
98
+ TSAsExpression(path) {
99
+ ranges.push([path.node.expression.end, path.node.end]);
100
+ },
101
+ TSSatisfiesExpression(path) {
102
+ ranges.push([path.node.expression.end, path.node.end]);
103
+ },
104
+ TSNonNullExpression(path) {
105
+ ranges.push([path.node.expression.end, path.node.end]);
106
+ },
107
+ CallExpression(path) {
108
+ addTypeParamsRange(path.node);
109
+ },
110
+ NewExpression(path) {
111
+ addTypeParamsRange(path.node);
112
+ },
113
+ FunctionDeclaration(path) {
114
+ addTypeParamsRange(path.node);
115
+ },
116
+ FunctionExpression(path) {
117
+ addTypeParamsRange(path.node);
118
+ },
119
+ ArrowFunctionExpression(path) {
120
+ addTypeParamsRange(path.node);
121
+ },
122
+ });
123
+
124
+ return ranges;
125
+ }
126
+
127
+ /** Delete a set of (possibly overlapping/nested) [start, end) ranges from `code`. */
128
+ function spliceRanges(code, ranges) {
129
+ if (ranges.length === 0) return code;
130
+ const sorted = ranges.slice().sort((a, b) => a[0] - b[0]);
131
+ const merged = [];
132
+ for (const [start, end] of sorted) {
133
+ const last = merged[merged.length - 1];
134
+ if (last && start <= last[1]) {
135
+ last[1] = Math.max(last[1], end);
136
+ } else {
137
+ merged.push([start, end]);
138
+ }
139
+ }
140
+ let out = '';
141
+ let cursor = 0;
142
+ for (const [start, end] of merged) {
143
+ if (start > cursor) out += code.slice(cursor, start);
144
+ cursor = Math.max(cursor, end);
145
+ }
146
+ out += code.slice(cursor);
147
+ return out;
148
+ }
149
+
150
+ /**
151
+ * Legacy regex/text-scanning TS stripper — fallback for text fragments that
152
+ * don't parse standalone (see stripTypeScriptSyntax above). Not a full TS
153
+ * parser — covers the patterns that show up in component JSX, helpers, and
154
+ * local const initializers.
155
+ */
156
+ function stripTypeScriptSyntaxLegacy(code) {
157
+ let s = code;
158
+
159
+ // Remove multi-line and single-line type-only import/export noise if present
160
+ s = s.replace(/^import\s+type\s+[\s\S]*?;\s*/gm, '');
161
+ s = s.replace(/^export\s+type\s+[\s\S]*?;\s*/gm, '');
162
+
163
+ // `as const` / `as any` / `as Type` / `as { ... }` / `as (...)` casts
164
+ s = stripAsCasts(s);
165
+
166
+ // Non-null assertions: value! / foo!.bar (not != or !==)
167
+ s = s.replace(/(\w|\))!(?!=)/g, '$1');
168
+
169
+ // Optional generic on calls: foo<string>( → foo(
170
+ s = s.replace(/\b([A-Za-z_$][\w$]*)\s*<\s*[A-Za-z_$][\w$.,\s|&[\]<>]*\s*>\s*\(/g, '$1(');
171
+
172
+ // Parameter / property type annotations inside (...): (val: string, n?: number)
173
+ // and destructured props: ({ a, b }: Props)
174
+ s = stripParamTypeAnnotations(s);
175
+
176
+ // Variable annotations: const x: string = / let y: Foo =
177
+ s = s.replace(
178
+ /\b(const|let|var)\s+([A-Za-z_$][\w$]*)\s*:\s*[^=;\n]+?(\s*=)/g,
179
+ '$1 $2$3',
180
+ );
181
+
182
+ // Return type annotations: ): string { / ): Promise<void> =>
183
+ // Do NOT use a bare `=` terminator — that matches query strings in ternary
184
+ // branches: `) : 'https://...?auto=format&...'` → corrupted `)=format`.
185
+ s = s.replace(
186
+ /\)\s*:\s*(?:[A-Za-z_$]|Promise\b)[A-Za-z0-9_$.<>\[\]|&,\s]*?\s*(\{|=>)/g,
187
+ ')$1',
188
+ );
189
+
190
+ // Angle-bracket type assertions leftover: <string>x (rare in TSX)
191
+ // Avoid matching JSX — only when preceded by = ( or ,
192
+ s = s.replace(/(=|\(|,)\s*<\s*[A-Za-z_$][\w$.,\s|&[\]]*\s*>\s*(?=[A-Za-z_$('"`])/g, '$1');
193
+
194
+ // satisfies Type
195
+ s = s.replace(/\s+satisfies\s+[A-Za-z_$][\w$<>[\]|&.,\s]*/g, '');
196
+
197
+ return s;
198
+ }
199
+
200
+ function stripAsCasts(code) {
201
+ let result = '';
202
+ let i = 0;
203
+ while (i < code.length) {
204
+ // `expr as Type` — including property access: event.target as Node
205
+ // Do NOT require a non-word char before the space (that skipped real casts).
206
+ // Distinguish from import renames (`foo as bar`) via type-like RHS heuristics.
207
+ if (/\s/.test(code[i]) && /^\s+as\s+/.test(code.slice(i))) {
208
+ const m = code.slice(i).match(/^\s+as\s+/);
209
+ const afterAs = i + m[0].length;
210
+ const next = code.slice(afterAs);
211
+ const isTypeLike =
212
+ /^(const|any|unknown|never|string|number|boolean|object|null|undefined|keyof|typeof|readonly|Partial|Pick|Omit|Record|Required|Readonly)\b/.test(
213
+ next,
214
+ ) ||
215
+ /^[A-Z(]/.test(next) ||
216
+ next.startsWith('{') ||
217
+ next.startsWith('[') ||
218
+ /^[A-Za-z_$][\w$]*\s*[<.\[]/.test(next);
219
+
220
+ if (isTypeLike) {
221
+ i = afterAs;
222
+ i = skipTypeToken(code, i);
223
+ continue;
224
+ }
225
+ // lowercase bare identifier after `as` → likely import rename; keep
226
+ }
227
+ result += code[i];
228
+ i++;
229
+ }
230
+ return result;
231
+ }
232
+
233
+ function skipTypeToken(code, start) {
234
+ let i = start;
235
+ while (i < code.length && /\s/.test(code[i])) i++;
236
+ if (i >= code.length) return i;
237
+
238
+ // String / template literal types: 'span' | "foo" | `bar`
239
+ if (code[i] === '"' || code[i] === "'" || code[i] === '`') {
240
+ const q = code[i];
241
+ i++;
242
+ while (i < code.length && code[i] !== q) {
243
+ if (code[i] === '\\') {
244
+ i += 2;
245
+ continue;
246
+ }
247
+ if (q === '`' && code[i] === '$' && code[i + 1] === '{') {
248
+ i += 2;
249
+ let d = 1;
250
+ while (i < code.length && d > 0) {
251
+ if (code[i] === '{') d++;
252
+ else if (code[i] === '}') d--;
253
+ i++;
254
+ }
255
+ continue;
256
+ }
257
+ i++;
258
+ }
259
+ if (i < code.length) i++; // closing quote
260
+ while (i < code.length && /\s/.test(code[i])) i++;
261
+ if ((code[i] === '|' || code[i] === '&') && code[i + 1] !== code[i]) {
262
+ i++;
263
+ while (i < code.length && /\s/.test(code[i])) i++;
264
+ return skipTypeToken(code, i);
265
+ }
266
+ return i;
267
+ }
268
+
269
+ // Numeric literal types: 0 | 1
270
+ if (/[0-9]/.test(code[i])) {
271
+ while (i < code.length && /[0-9._]/.test(code[i])) i++;
272
+ while (i < code.length && /\s/.test(code[i])) i++;
273
+ if ((code[i] === '|' || code[i] === '&') && code[i + 1] !== code[i]) {
274
+ i++;
275
+ while (i < code.length && /\s/.test(code[i])) i++;
276
+ return skipTypeToken(code, i);
277
+ }
278
+ return i;
279
+ }
280
+
281
+ if (code[i] === '{' || code[i] === '(' || code[i] === '[') {
282
+ const open = code[i];
283
+ const close = open === '{' ? '}' : open === '(' ? ')' : ']';
284
+ let depth = 0;
285
+ while (i < code.length) {
286
+ if (code[i] === open) depth++;
287
+ else if (code[i] === close) {
288
+ depth--;
289
+ if (depth === 0) {
290
+ i++;
291
+ break;
292
+ }
293
+ }
294
+ i++;
295
+ }
296
+ // trailing [] or | Other
297
+ while (code[i] === '[' || code[i] === '|' || code[i] === '&' || code[i] === '<' || /\s/.test(code[i])) {
298
+ if (code[i] === '[') {
299
+ while (i < code.length && code[i] !== ']') i++;
300
+ if (code[i] === ']') i++;
301
+ } else if (code[i] === '<') {
302
+ let d = 0;
303
+ while (i < code.length) {
304
+ if (code[i] === '<') d++;
305
+ else if (code[i] === '>') {
306
+ d--;
307
+ if (d === 0) {
308
+ i++;
309
+ break;
310
+ }
311
+ }
312
+ i++;
313
+ }
314
+ } else if (code[i] === '|' || code[i] === '&') {
315
+ i++;
316
+ while (i < code.length && /\s/.test(code[i])) i++;
317
+ i = skipTypeToken(code, i);
318
+ break;
319
+ } else {
320
+ i++;
321
+ }
322
+ }
323
+ return i;
324
+ }
325
+
326
+ // keyof T / typeof x / readonly T
327
+ const prefixKw = code.slice(i).match(/^(keyof|typeof|readonly)\b/);
328
+ if (prefixKw) {
329
+ i += prefixKw[0].length;
330
+ while (i < code.length && /\s/.test(code[i])) i++;
331
+ return skipTypeToken(code, i);
332
+ }
333
+
334
+ // Identifier / qualified / generic / indexed type: Foo, Foo.Bar, Foo<T>, Foo['bar']
335
+ while (i < code.length && /[A-Za-z0-9_$.]/.test(code[i])) i++;
336
+ while (i < code.length) {
337
+ while (i < code.length && /\s/.test(code[i])) i++;
338
+ if (i >= code.length) break;
339
+
340
+ if (code[i] === '<') {
341
+ let d = 0;
342
+ while (i < code.length) {
343
+ if (code[i] === '<') d++;
344
+ else if (code[i] === '>') {
345
+ d--;
346
+ if (d === 0) {
347
+ i++;
348
+ break;
349
+ }
350
+ }
351
+ i++;
352
+ }
353
+ continue;
354
+ }
355
+ // Foo[] or Foo['key'] / Foo["key"]
356
+ if (code[i] === '[') {
357
+ let d = 0;
358
+ while (i < code.length) {
359
+ if (code[i] === '[') d++;
360
+ else if (code[i] === ']') {
361
+ d--;
362
+ if (d === 0) {
363
+ i++;
364
+ break;
365
+ }
366
+ }
367
+ i++;
368
+ }
369
+ continue;
370
+ }
371
+ if ((code[i] === '|' || code[i] === '&') && code[i + 1] !== code[i]) {
372
+ i++;
373
+ while (i < code.length && /\s/.test(code[i])) i++;
374
+ return skipTypeToken(code, i);
375
+ }
376
+ break;
377
+ }
378
+ return i;
379
+ }
380
+
381
+ function stripParamTypeAnnotations(code) {
382
+ // Walk and inside parentheses that look like parameter lists, drop `: type`
383
+ let result = '';
384
+ let i = 0;
385
+ while (i < code.length) {
386
+ if (code[i] === '(') {
387
+ // Find matching close, then peek if followed by function-ish tail.
388
+ // IMPORTANT: do NOT treat `) : value` (ternary) as a typed param list —
389
+ // that used to strip ternary branches like `: String(x)` inside
390
+ // `cond ? (a ? b : c) : 'url'`.
391
+ const close = findMatching(code, i, '(', ')');
392
+ if (close !== -1) {
393
+ const afterStr = code.slice(close + 1);
394
+ // Function-like tails only — NOT ternary `) : (` (true-branch paren of
395
+ // `cond ? (…jsx…) : (…)` was misread as typed params and stripped
396
+ // object fields like `{ [key]: val }` inside the branch).
397
+ const isFunctionLike =
398
+ /^\s*=>/.test(afterStr) ||
399
+ /^\s*\{/.test(afterStr) ||
400
+ // ): Type => / ): Type { — type must start with ident, never `(`
401
+ /^\s*:\s*(?:[A-Za-z_$]|Promise\b)[A-Za-z0-9_$.<>\[\]|&,\s]*?\s*(=>|\{)/.test(
402
+ afterStr,
403
+ );
404
+ const inner = code.slice(i + 1, close);
405
+ // Match ident types AND string-literal param types: tagName: 'span' | 'p'
406
+ if (isFunctionLike && /:\s*(?:[A-Za-z_{$'"0-9]|Promise\b)/.test(inner)) {
407
+ const cleaned = stripTypesInsideParams(inner);
408
+ result += '(' + cleaned + ')';
409
+ i = close + 1;
410
+ continue;
411
+ }
412
+ }
413
+ }
414
+ result += code[i];
415
+ i++;
416
+ }
417
+ return result;
418
+ }
419
+
420
+ /** TS primitive / keyword types — never valid as destructure rename bindings. */
421
+ const TS_TYPE_KEYWORDS = new Set([
422
+ 'string',
423
+ 'number',
424
+ 'boolean',
425
+ 'any',
426
+ 'unknown',
427
+ 'never',
428
+ 'object',
429
+ 'void',
430
+ 'null',
431
+ 'undefined',
432
+ 'bigint',
433
+ 'symbol',
434
+ 'true',
435
+ 'false',
436
+ 'keyof',
437
+ 'typeof',
438
+ 'readonly',
439
+ 'infer',
440
+ 'Partial',
441
+ 'Pick',
442
+ 'Omit',
443
+ 'Record',
444
+ 'Required',
445
+ 'Readonly',
446
+ 'Promise',
447
+ 'Array',
448
+ 'Map',
449
+ 'Set',
450
+ ]);
451
+
452
+ /**
453
+ * Inside object destructure patterns `{ icon: Icon }`, `icon: Icon` is a
454
+ * rename binding — NOT a type annotation. Only treat as type when the RHS
455
+ * looks like a real type (primitive keyword, union, generic, string literal…).
456
+ */
457
+ function isObjectPatternRename(afterColon) {
458
+ const rest = afterColon.replace(/^\s+/, '');
459
+ if (!rest || /^['"`0-9({[<]/.test(rest)) return false;
460
+ if (/^(keyof|typeof|readonly|infer)\b/.test(rest)) return false;
461
+ const m = rest.match(/^([A-Za-z_$][\w$]*)\s*(?=[,}=]|$)/);
462
+ if (!m) return false;
463
+ if (TS_TYPE_KEYWORDS.has(m[1])) return false;
464
+ const afterId = rest.slice(m[1].length).replace(/^\s+/, '');
465
+ if (
466
+ afterId.startsWith('<') ||
467
+ afterId.startsWith('[') ||
468
+ afterId.startsWith('|') ||
469
+ afterId.startsWith('&') ||
470
+ afterId.startsWith('.')
471
+ ) {
472
+ return false;
473
+ }
474
+ return true;
475
+ }
476
+
477
+ function stripTypesInsideParams(inner) {
478
+ // Remove `: Type` after identifiers / } in param lists.
479
+ // Preserve object-pattern renames: `{ icon: Icon, label }` stays intact.
480
+ let s = '';
481
+ let i = 0;
482
+ let braceDepth = 0;
483
+ while (i < inner.length) {
484
+ // Skip strings
485
+ if (inner[i] === '"' || inner[i] === "'" || inner[i] === '`') {
486
+ const q = inner[i];
487
+ s += q;
488
+ i++;
489
+ while (i < inner.length && inner[i] !== q) {
490
+ if (inner[i] === '\\') {
491
+ s += inner[i] + (inner[i + 1] || '');
492
+ i += 2;
493
+ continue;
494
+ }
495
+ s += inner[i++];
496
+ }
497
+ if (i < inner.length) s += inner[i++];
498
+ continue;
499
+ }
500
+
501
+ if (inner[i] === '{') braceDepth++;
502
+ if (inner[i] === '}') braceDepth = Math.max(0, braceDepth - 1);
503
+
504
+ // Type annotation colon: after ident, `)`, `]`, `}`, `?`, or whitespace.
505
+ // Must include `}` so destructured params with a type work:
506
+ // ({ name, className }: { name?: string }) — colon sits right after `}`
507
+ if (
508
+ inner[i] === ':' &&
509
+ (i === 0 ||
510
+ /[\w$?)\]}]/.test(inner[i - 1]) ||
511
+ /\s/.test(inner[i - 1]))
512
+ ) {
513
+ const after = inner.slice(i + 1);
514
+ // Inside `{ … }` → keep renames like `icon: Icon`
515
+ if (braceDepth > 0 && isObjectPatternRename(after)) {
516
+ s += ':';
517
+ i++;
518
+ continue;
519
+ }
520
+ // Type annotation — skip until , or ) or = (default)
521
+ i++;
522
+ while (i < inner.length && /\s/.test(inner[i])) i++;
523
+ i = skipTypeToken(inner, i);
524
+ continue;
525
+ }
526
+ // Optional `?` before type on params: name?:
527
+ s += inner[i];
528
+ i++;
529
+ }
530
+ // Clean `name?` leftover optional markers on params (incl. last param)
531
+ s = s.replace(/([A-Za-z_$][\w$]*)\?(?=\s*[,)=]|$)/g, '$1');
532
+ return s;
533
+ }
534
+
535
+ function findMatching(code, openIdx, openChar, closeChar) {
536
+ let depth = 0;
537
+ let inS = false;
538
+ let inD = false;
539
+ let inB = false;
540
+ for (let i = openIdx; i < code.length; i++) {
541
+ const c = code[i];
542
+ if (inS) {
543
+ if (c === '\\') {
544
+ i++;
545
+ continue;
546
+ }
547
+ if (c === "'") inS = false;
548
+ continue;
549
+ }
550
+ if (inD) {
551
+ if (c === '\\') {
552
+ i++;
553
+ continue;
554
+ }
555
+ if (c === '"') inD = false;
556
+ continue;
557
+ }
558
+ if (inB) {
559
+ if (c === '\\') {
560
+ i++;
561
+ continue;
562
+ }
563
+ if (c === '`') inB = false;
564
+ continue;
565
+ }
566
+ if (c === "'") inS = true;
567
+ else if (c === '"') inD = true;
568
+ else if (c === '`') inB = true;
569
+ else if (c === openChar) depth++;
570
+ else if (c === closeChar) {
571
+ depth--;
572
+ if (depth === 0) return i;
573
+ }
574
+ }
575
+ return -1;
576
+ }
577
+
578
+ /**
579
+ * Built-ins / framework identifiers that look like PascalCase helpers but
580
+ * must never be hoisted from the component file.
581
+ */
582
+ const PASCAL_HELPER_SKIP = new Set([
583
+ 'React',
584
+ 'Fragment',
585
+ 'Component',
586
+ 'PureComponent',
587
+ 'Suspense',
588
+ 'StrictMode',
589
+ 'WpEditable',
590
+ 'WpLink',
591
+ 'WpIcon',
592
+ 'WpRepeater',
593
+ 'WpHead',
594
+ 'WpImage',
595
+ 'Hydrate',
596
+ 'Button',
597
+ 'InspectorControls',
598
+ 'RichText',
599
+ 'InnerBlocks',
600
+ 'ServerSideRender',
601
+ 'JSON',
602
+ 'Math',
603
+ 'Array',
604
+ 'Object',
605
+ 'String',
606
+ 'Number',
607
+ 'Boolean',
608
+ 'Date',
609
+ 'Error',
610
+ 'Promise',
611
+ 'Map',
612
+ 'Set',
613
+ 'Symbol',
614
+ 'RegExp',
615
+ 'URL',
616
+ 'URLSearchParams',
617
+ 'FormData',
618
+ 'File',
619
+ 'Blob',
620
+ 'Image',
621
+ 'Element',
622
+ 'Node',
623
+ 'Document',
624
+ 'Window',
625
+ ]);
626
+
627
+ /**
628
+ * Find helper names referenced in code:
629
+ * - lowercase call sites: getSocialHandle(
630
+ * - PascalCase free refs / tags: TiktokIcon, icon: PinterestIcon, <MyIcon />
631
+ *
632
+ * PascalCase values are how local SVG/icon components are usually passed around
633
+ * (e.g. `icon: TiktokIcon` in a social list). Those are never "called" with `(`,
634
+ * so a call-only scan would miss them and leave "X is not defined" in the editor.
635
+ */
636
+ export function findCalledHelperNames(code) {
637
+ const names = new Set();
638
+ if (!code) return names;
639
+
640
+ // camelCase / lowercase calls: helper(
641
+ const callRx = /\b([a-z][A-Za-z0-9_$]*)\s*\(/g;
642
+ let m;
643
+ while ((m = callRx.exec(code)) !== null) {
644
+ const name = m[1];
645
+ if (!JS_KEYWORDS.has(name)) {
646
+ names.add(name);
647
+ }
648
+ }
649
+
650
+ // PascalCase identifiers used as values or JSX tags (not after `.`)
651
+ const pascalRx = /(?<![.\w$])([A-Z][A-Za-z0-9_$]*)\b/g;
652
+ while ((m = pascalRx.exec(code)) !== null) {
653
+ const name = m[1];
654
+ if (PASCAL_HELPER_SKIP.has(name)) continue;
655
+ if (JS_KEYWORDS.has(name)) continue;
656
+ // Skip ALL_CAPS constants (BAKED_PADDING is handled separately)
657
+ if (/^[A-Z][A-Z0-9_]+$/.test(name)) continue;
658
+ names.add(name);
659
+ }
660
+
661
+ return names;
662
+ }
663
+
664
+ /**
665
+ * Extract a top-level function or const-arrow helper by name from a source file.
666
+ * Returns the full declaration string (function / const), or null.
667
+ */
668
+ /**
669
+ * AST-first extraction: parse the whole module (clean TSX — virtually always
670
+ * parseable) and take the top-level declaration's exact byte range off
671
+ * program.body. Replaces the legacy scanner's two genuinely fragile jobs —
672
+ * finding where a single-expression arrow body ENDS (depth-counted scan for
673
+ * `;`) and telling a param-destructure `{` apart from the body `{` — with
674
+ * parser facts (scratch categories E/F).
675
+ */
676
+ // extractSameFileHelpers' BFS probes extractTopLevelHelper once per candidate
677
+ // name (dozens per block) against the same module source — parse each unique
678
+ // source once, not once per probe, or the whole-theme compile time explodes.
679
+ const helperAstCache = new Map();
680
+
681
+ function parseModuleCached(sourceCode) {
682
+ if (helperAstCache.has(sourceCode)) return helperAstCache.get(sourceCode);
683
+ if (helperAstCache.size > 64) helperAstCache.clear();
684
+ const ast = tryParseSource(sourceCode);
685
+ helperAstCache.set(sourceCode, ast);
686
+ return ast;
687
+ }
688
+
689
+ function extractTopLevelHelperAst(sourceCode, name) {
690
+ const ast = parseModuleCached(sourceCode);
691
+ if (!ast) return null;
692
+ for (const stmt of ast.program.body) {
693
+ let decl = stmt;
694
+ if (decl.type === 'ExportNamedDeclaration' && decl.declaration) decl = decl.declaration;
695
+ if (decl.type === 'FunctionDeclaration' && decl.id && decl.id.name === name) {
696
+ return sourceCode.slice(stmt.start, stmt.end).trim();
697
+ }
698
+ // Single-declarator const/let only — a multi-declarator statement
699
+ // (`const a = 1, cell = …;`) has no clean per-declarator slice, and the
700
+ // legacy regex never matched those either.
701
+ if (decl.type === 'VariableDeclaration' && decl.declarations.length === 1) {
702
+ const d = decl.declarations[0];
703
+ if (
704
+ d.id.type === 'Identifier' && d.id.name === name && d.init &&
705
+ (d.init.type === 'ArrowFunctionExpression' || d.init.type === 'FunctionExpression')
706
+ ) {
707
+ return sourceCode.slice(stmt.start, stmt.end).trim();
708
+ }
709
+ }
710
+ }
711
+ return null;
712
+ }
713
+
714
+ export function extractTopLevelHelper(sourceCode, name) {
715
+ if (!sourceCode || !name) return null;
716
+
717
+ const fromAst = extractTopLevelHelperAst(sourceCode, name);
718
+ if (fromAst) return fromAst;
719
+ const legacy = extractTopLevelHelperLegacy(sourceCode, name);
720
+ // Only a legacy result the AST path MISSED proves the fallback matters —
721
+ // most probes are speculative names that exist in neither.
722
+ if (legacy) markLegacyFallback('source-sanitize:extractTopLevelHelper-legacy-contributed');
723
+ return legacy;
724
+ }
725
+
726
+ function extractTopLevelHelperLegacy(sourceCode, name) {
727
+ const patterns = [
728
+ // function name(
729
+ new RegExp(`(?:export\\s+)?function\\s+${name}\\s*\\(`, 'm'),
730
+ // const name = (
731
+ new RegExp(`(?:export\\s+)?const\\s+${name}\\s*=\\s*(?:async\\s*)?(?:function\\s*)?\\(`, 'm'),
732
+ // const name = async (
733
+ new RegExp(`(?:export\\s+)?const\\s+${name}\\s*=\\s*async\\s*\\(`, 'm'),
734
+ ];
735
+
736
+ for (const re of patterns) {
737
+ const match = re.exec(sourceCode);
738
+ if (!match) continue;
739
+ const start = match.index;
740
+ // Find end of declaration
741
+ const from = sourceCode.slice(start);
742
+ // Arrow single-expression: const name = (a) => expr;
743
+ const arrowExpr = from.match(
744
+ new RegExp(
745
+ `^(?:export\\s+)?const\\s+${name}\\s*=\\s*(?:async\\s*)?\\([^)]*\\)\\s*=>\\s*(?!\\{)`,
746
+ ),
747
+ );
748
+ if (arrowExpr) {
749
+ // Read until semicolon at depth 0
750
+ let i = arrowExpr[0].length;
751
+ let depth = 0;
752
+ let inS = false;
753
+ let inD = false;
754
+ let inB = false;
755
+ while (i < from.length) {
756
+ const c = from[i];
757
+ if (inS) {
758
+ if (c === '\\') {
759
+ i += 2;
760
+ continue;
761
+ }
762
+ if (c === "'") inS = false;
763
+ i++;
764
+ continue;
765
+ }
766
+ if (inD) {
767
+ if (c === '\\') {
768
+ i += 2;
769
+ continue;
770
+ }
771
+ if (c === '"') inD = false;
772
+ i++;
773
+ continue;
774
+ }
775
+ if (inB) {
776
+ if (c === '\\') {
777
+ i += 2;
778
+ continue;
779
+ }
780
+ if (c === '`') inB = false;
781
+ i++;
782
+ continue;
783
+ }
784
+ if (c === "'") inS = true;
785
+ else if (c === '"') inD = true;
786
+ else if (c === '`') inB = true;
787
+ else if (c === '(' || c === '{' || c === '[') depth++;
788
+ else if (c === ')' || c === '}' || c === ']') depth--;
789
+ else if (c === ';' && depth <= 0) {
790
+ i++;
791
+ break;
792
+ }
793
+ i++;
794
+ }
795
+ return from.slice(0, i).trim();
796
+ }
797
+
798
+ // Block body: find `{` that opens the function/arrow body — NOT a
799
+ // destructure brace inside params, e.g.
800
+ // function ValueIcon({ name, className }: Props) { … }
801
+ // const fn = ({ a }: T) => { … }
802
+ const bodyBrace = findFunctionBodyOpenBrace(from);
803
+ if (bodyBrace === -1) continue;
804
+ const bodyEnd = findMatching(from, bodyBrace, '{', '}');
805
+ if (bodyEnd === -1) continue;
806
+ let end = bodyEnd + 1;
807
+ if (from[end] === ';') end++;
808
+ return from.slice(0, end).trim();
809
+ }
810
+
811
+ return null;
812
+ }
813
+
814
+ /**
815
+ * Locate the `{` that opens a function/arrow block body, skipping braces that
816
+ * belong to parameter destructuring or TypeScript param/return type literals.
817
+ *
818
+ * @param {string} from Declaration starting at `function name` / `const name =`
819
+ * @returns {number} index of body `{`, or -1
820
+ */
821
+ function findFunctionBodyOpenBrace(from) {
822
+ const isFunctionKeyword = /^\s*(?:export\s+)?function\b/.test(from);
823
+
824
+ if (!isFunctionKeyword) {
825
+ // const name = (…) => { … } — only scan the signature, not later arrows
826
+ // in the rest of the file. Cap search to the first statement-ish region.
827
+ const sigEnd = Math.min(from.length, 500);
828
+ const head = from.slice(0, sigEnd);
829
+ const arrowIdx = head.search(/=>/);
830
+ if (arrowIdx !== -1) {
831
+ let i = arrowIdx + 2;
832
+ while (i < from.length && /\s/.test(from[i])) i++;
833
+ if (from[i] === '{') return i;
834
+ // Expression-body arrow — no block brace on this declaration
835
+ return -1;
836
+ }
837
+ }
838
+
839
+ // function name(params) { or function name(params): Type {
840
+ // (also const name = function(params) { … })
841
+ const parenOpen = from.indexOf('(');
842
+ if (parenOpen === -1) return -1;
843
+ const parenClose = findMatching(from, parenOpen, '(', ')');
844
+ if (parenClose === -1) return -1;
845
+ let i = parenClose + 1;
846
+ while (i < from.length && /\s/.test(from[i])) i++;
847
+ // Optional return type: ): Type {
848
+ if (from[i] === ':') {
849
+ i++;
850
+ while (i < from.length && /\s/.test(from[i])) i++;
851
+ i = skipTypeToken(from, i);
852
+ while (i < from.length && /\s/.test(from[i])) i++;
853
+ }
854
+ if (from[i] === '{') return i;
855
+ return -1;
856
+ }
857
+
858
+ /**
859
+ * Collect same-file helpers referenced by `code`, including transitive callees.
860
+ * @returns {{ name: string, code: string }[]}
861
+ */
862
+ /**
863
+ * Helpers that are full React data islands (useWpQuery / useState / …) must not
864
+ * be hoisted into the editor IIFE — they leave free vars like `terms` and raw
865
+ * JSX early-returns. Nested tags already become placeholders via expandNested.
866
+ */
867
+ function isUnsafeEditorHelper(code) {
868
+ if (!code) return false;
869
+ return (
870
+ /\buse(State|Effect|Reducer|LayoutEffect|ImperativeHandle)\b/.test(code) ||
871
+ /\bReact\.use(State|Effect|Reducer)\b/.test(code) ||
872
+ /\buseWp(Query|Terms|SearchParams|Location|Search)\b/.test(code) ||
873
+ /\buseIsEditorPreview\b/.test(code)
874
+ );
875
+ }
876
+
877
+ export function extractSameFileHelpers(sourceCode, codeThatUsesThem, excludeNames = new Set()) {
878
+ const result = [];
879
+ const seen = new Set(excludeNames);
880
+ let pending = [...findCalledHelperNames(codeThatUsesThem)];
881
+
882
+ while (pending.length > 0) {
883
+ const name = pending.shift();
884
+ if (seen.has(name)) continue;
885
+ seen.add(name);
886
+
887
+ const raw = extractTopLevelHelper(sourceCode, name);
888
+ if (!raw) continue;
889
+
890
+ // Skip live-data / hook components (e.g. DestinationsGrid, FeaturedHotelsGrid)
891
+ // even if their name appears in a placeholder string.
892
+ if (isUnsafeEditorHelper(raw)) continue;
893
+
894
+ const cleaned = stripTypeScriptSyntax(raw);
895
+ result.push({ name, code: cleaned });
896
+
897
+ // Transitive helpers used inside this helper
898
+ for (const inner of findCalledHelperNames(cleaned)) {
899
+ if (!seen.has(inner)) pending.push(inner);
900
+ }
901
+ }
902
+
903
+ return result;
904
+ }
905
+
906
+ /** Brace-balanced scan for the `}` matching the `{` at openIdx (string/backtick-aware). */
907
+ function findMatchingBraceClose(str, openIdx) {
908
+ let depth = 0;
909
+ let inStr = null;
910
+ let esc = false;
911
+ for (let i = openIdx; i < str.length; i++) {
912
+ const c = str[i];
913
+ if (inStr) {
914
+ if (esc) esc = false;
915
+ else if (c === '\\') esc = true;
916
+ else if (c === inStr) inStr = null;
917
+ continue;
918
+ }
919
+ if (c === "'" || c === '"' || c === '`') {
920
+ inStr = c;
921
+ continue;
922
+ }
923
+ if (c === '{') depth++;
924
+ else if (c === '}') {
925
+ depth--;
926
+ if (depth === 0) return i;
927
+ }
928
+ }
929
+ return -1;
930
+ }
931
+
932
+ /**
933
+ * `try { A } catch (e) { B }` / `try { A } catch { B }` → PHP's own
934
+ * `try { A } catch (\Throwable $e) { B }`. PHP requires a catch variable
935
+ * (JS's parameterless `catch {}` doesn't have one), so `$e` is added when
936
+ * missing. Brace-balanced rather than a lazy regex so a nested `if { }`
937
+ * inside either block doesn't get treated as the block's own closing brace.
938
+ */
939
+ function translateTryCatch(code) {
940
+ const tryRegex = /\btry\s*\{/g;
941
+ let result = '';
942
+ let lastIndex = 0;
943
+ let match;
944
+ while ((match = tryRegex.exec(code)) !== null) {
945
+ const tryBraceOpen = match.index + match[0].length - 1;
946
+ const tryBraceClose = findMatchingBraceClose(code, tryBraceOpen);
947
+ if (tryBraceClose === -1) continue;
948
+
949
+ const afterTry = code.slice(tryBraceClose + 1);
950
+ const catchMatch = afterTry.match(/^\s*catch\s*(?:\(\s*([A-Za-z_$][\w$]*)\s*\))?\s*\{/);
951
+ if (!catchMatch) continue;
952
+
953
+ const catchBraceOpenAbs = tryBraceClose + 1 + catchMatch[0].length - 1;
954
+ const catchBraceClose = findMatchingBraceClose(code, catchBraceOpenAbs);
955
+ if (catchBraceClose === -1) continue;
956
+
957
+ const catchVar = catchMatch[1] || 'e';
958
+ const tryBody = code.slice(tryBraceOpen + 1, tryBraceClose);
959
+ const catchBody = code.slice(catchBraceOpenAbs + 1, catchBraceClose);
960
+
961
+ result += code.slice(lastIndex, match.index);
962
+ result += `try {${tryBody}} catch (\\Throwable $${catchVar}) {${catchBody}}`;
963
+ lastIndex = catchBraceClose + 1;
964
+ tryRegex.lastIndex = catchBraceClose + 1;
965
+ }
966
+ result += code.slice(lastIndex);
967
+ return result;
968
+ }
969
+
970
+ /**
971
+ * Best-effort convert a small pure JS helper to a PHP function.
972
+ * Returns PHP source or null if conversion looks unsafe.
973
+ */
974
+ export function jsHelperToPhpFunction(phpName, jsHelperCode) {
975
+ try {
976
+ let code = stripTypeScriptSyntax(jsHelperCode).trim();
977
+
978
+ let params = [];
979
+ let body = '';
980
+
981
+ const fnMatch = code.match(/^(?:export\s+)?function\s+[A-Za-z_$][\w$]*\s*\(([^)]*)\)\s*\{([\s\S]*)\}\s*;?$/);
982
+ if (fnMatch) {
983
+ params = splitParams(fnMatch[1]);
984
+ body = fnMatch[2];
985
+ } else {
986
+ const arrowBlock = code.match(
987
+ /^(?:export\s+)?const\s+[A-Za-z_$][\w$]*\s*=\s*(?:async\s*)?\(([^)]*)\)\s*=>\s*\{([\s\S]*)\}\s*;?$/,
988
+ );
989
+ if (arrowBlock) {
990
+ params = splitParams(arrowBlock[1]);
991
+ body = arrowBlock[2];
992
+ } else {
993
+ const arrowExpr = code.match(
994
+ /^(?:export\s+)?const\s+[A-Za-z_$][\w$]*\s*=\s*(?:async\s*)?\(([^)]*)\)\s*=>\s*([\s\S]+?)\s*;?\s*$/,
995
+ );
996
+ if (arrowExpr) {
997
+ params = splitParams(arrowExpr[1]);
998
+ body = `return ${arrowExpr[2].replace(/;?\s*$/, '')};`;
999
+ } else {
1000
+ return null;
1001
+ }
1002
+ }
1003
+ }
1004
+
1005
+ // Reject helpers that clearly need a JS runtime / DOM / React event model.
1006
+ // (Emitting them as PHP causes fatals like "Value of type null is not callable".)
1007
+ if (
1008
+ /\?\./.test(body) ||
1009
+ /=>/.test(body) ||
1010
+ /\.\.\./.test(body) ||
1011
+ /use[A-Z]|window\.|document\.|React\.|fetch\s*\(|await\s|import\s|require\s*\(/.test(body) ||
1012
+ /\.contains\b|addEventListener|removeEventListener|preventDefault|stopPropagation/.test(body) ||
1013
+ /\bset[A-Z][A-Za-z0-9_]*\s*\(/.test(body) || // setCategoryOpen(false)
1014
+ /\bcreateElement\b|wp\.blockEditor|wp\.element/.test(body)
1015
+ ) {
1016
+ return null;
1017
+ }
1018
+
1019
+ // Reject helpers that return raw JSX (icon components, render-prop cells,
1020
+ // etc.) — these are presentational React components, not translatable
1021
+ // logic, and naive brace extraction would dump untranspiled JSX straight
1022
+ // into a PHP function body ("unexpected token '<'"). The rendering of any
1023
+ // JSX these return is handled elsewhere (icon registry, island placeholder);
1024
+ // a missing PHP function here just means the call site degrades to nothing.
1025
+ if (/<\/?[A-Za-z][\w.]*[\s/>]/.test(body)) {
1026
+ return null;
1027
+ }
1028
+
1029
+ // .replace(/pattern/flags, 'str') → preg_replace(...) (optionally .trim()
1030
+ // chained → trim(preg_replace(...))). Reuses the same translation the JSX
1031
+ // expression pipeline uses, so a helper like getSocialHandle (which strips
1032
+ // a trailing slash via .replace before .split('/')) gets a real PHP twin
1033
+ // instead of being rejected outright.
1034
+ let preprocessedBody = translateReplaceTrim(body);
1035
+
1036
+ // X.split('sep') → explode('sep', X) — single string-literal separator,
1037
+ // the only shape these helpers actually use.
1038
+ preprocessedBody = preprocessedBody.replace(
1039
+ /([A-Za-z_$][\w$.\[\]'"]*)\.split\(\s*('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")\s*\)/g,
1040
+ (full, subject, sep) => `explode(${sep}, ${subject})`,
1041
+ );
1042
+
1043
+ // X.length → count((array)(X)), matching the same PHP 8-safe cast used
1044
+ // elsewhere in this pipeline (translateJsExpressionToPhp) so e.g.
1045
+ // `parts.length > 0 ? parts[parts.length - 1] : …` translates correctly.
1046
+ preprocessedBody = preprocessedBody.replace(
1047
+ /([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\[[^\]]+\])*)\.length\b/g,
1048
+ 'count((array)($1))',
1049
+ );
1050
+
1051
+ // try { A } catch (e) { B } / try { A } catch { B } → PHP's own try/catch.
1052
+ // PHP requires a catch variable (JS's parameterless `catch {}` doesn't
1053
+ // have one), so one is added when missing. Brace-balanced (not a lazy
1054
+ // regex) so a nested `if { }` inside either block doesn't truncate early.
1055
+ preprocessedBody = translateTryCatch(preprocessedBody);
1056
+
1057
+ // Reject helpers using JS String/Array/RegExp prototype methods this
1058
+ // function still can't safely rewrite — this remains a regex-based
1059
+ // translator, not a real parser. Falling back to no PHP function is safe:
1060
+ // the call site is neutralized to an empty string by neutralizeUnknownJsCalls.
1061
+ //
1062
+ // Note: `try {`/`catch (\Throwable $e) {` are NOT rejected here — that's
1063
+ // exactly what a successfully-translated try/catch now looks like (PHP's
1064
+ // own syntax), so checking for that text would reject every helper this
1065
+ // function just correctly translated. Only a bare `catch {` proves
1066
+ // translateTryCatch didn't run/match — PHP has no parameterless catch.
1067
+ if (
1068
+ /\.(map|slice|trim|includes|indexOf|lastIndexOf|join|push|pop|shift|unshift|concat|toLowerCase|toUpperCase|charAt|charCodeAt|substring|substr|padStart|padEnd|repeat|startsWith|endsWith|match|matchAll|search|test|exec|toFixed|filter|reduce|some|every|find|findIndex|flat|flatMap|sort|reverse)\s*\(/.test(preprocessedBody) ||
1069
+ /\.length\b/.test(preprocessedBody) ||
1070
+ /\bcatch\s*\{/.test(preprocessedBody)
1071
+ ) {
1072
+ return null;
1073
+ }
1074
+
1075
+ let phpBody = preprocessedBody;
1076
+
1077
+ // typeof x === 'string' etc. before $ prefixing
1078
+ phpBody = phpBody.replace(/typeof\s+([A-Za-z_$][\w$]*)\s*===\s*(['"])string\2/g, 'is_string($1)');
1079
+ phpBody = phpBody.replace(/typeof\s+([A-Za-z_$][\w$]*)\s*!==\s*(['"])string\2/g, '!is_string($1)');
1080
+ phpBody = phpBody.replace(/typeof\s+([A-Za-z_$][\w$]*)\s*===\s*(['"])number\2/g, 'is_numeric($1)');
1081
+ phpBody = phpBody.replace(/typeof\s+([A-Za-z_$][\w$]*)\s*===\s*(['"])object\2/g, '(is_array($1) || is_object($1))');
1082
+ phpBody = phpBody.replace(/typeof\s+([A-Za-z_$][\w$]*)\s*===\s*(['"])undefined\2/g, '!isset($1)');
1083
+ phpBody = phpBody.replace(/typeof\s+([A-Za-z_$][\w$]*)\s*!==\s*(['"])undefined\2/g, 'isset($1)');
1084
+
1085
+ // !x → empty($x) before $ prefixing
1086
+ phpBody = phpBody.replace(/!\s*([A-Za-z_$][\w$]*)\b/g, (_, n) => `empty($${n})`);
1087
+
1088
+ // 'key' in obj → safe array/object key-existence check (JS `in` has no PHP
1089
+ // equivalent). Must run before $ prefixing so we can emit $obj directly.
1090
+ phpBody = phpBody.replace(
1091
+ /(['"])([A-Za-z_$][\w$]*)\1\s+in\s+([A-Za-z_$][\w$]*)\b/g,
1092
+ (full, q, key, obj) =>
1093
+ `(is_array($${obj}) ? array_key_exists('${key}', $${obj}) : (is_object($${obj}) ? property_exists($${obj}, '${key}') : false))`,
1094
+ );
1095
+
1096
+ // String(x) → strval(x) — JS's String() cast has no direct PHP equivalent.
1097
+ phpBody = phpBody.replace(/\bString\(/g, 'strval(');
1098
+
1099
+ // Collapse a redundant single-identifier paren left behind by TS cast
1100
+ // stripping (e.g. `(val as { url?: string }).url` → `(val).url`) so the
1101
+ // property-access rule below still recognizes it as `val.url`.
1102
+ phpBody = phpBody.replace(/\(\s*([A-Za-z_$][\w$]*)\s*\)(?=\s*\.)/g, '$1');
1103
+
1104
+ // Prefix identifiers with $ (params + locals), skip keywords
1105
+ const localNames = new Set(params);
1106
+ const declRx = /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)/g;
1107
+ let dm;
1108
+ while ((dm = declRx.exec(phpBody)) !== null) localNames.add(dm[1]);
1109
+
1110
+ phpBody = phpBody.replace(/\b(?:const|let|var)\s+/g, '');
1111
+
1112
+ // Property access: x.y → array/object safe (before bare $ prefix)
1113
+ phpBody = phpBody.replace(
1114
+ /\b([A-Za-z_$][\w$]*)\s*\.\s*([A-Za-z_$][\w$]*)/g,
1115
+ (full, obj, prop) => {
1116
+ if (JS_KEYWORDS.has(obj) || obj.startsWith('$')) return full;
1117
+ return `(is_array($${obj}) ? ($${obj}['${prop}'] ?? null) : (is_object($${obj}) ? ($${obj}->${prop} ?? null) : null))`;
1118
+ },
1119
+ );
1120
+
1121
+ // Bare params / locals → $name (skip keywords and already-prefixed)
1122
+ for (const p of localNames) {
1123
+ phpBody = phpBody.replace(new RegExp(`(?<![\\w$])${p}(?![\\w$])`, 'g'), `$${p}`);
1124
+ }
1125
+
1126
+ // Fix double $$
1127
+ phpBody = phpBody.replace(/\$\$+/g, '$');
1128
+
1129
+ // empty($x) may have been written empty($$1) incorrectly — normalize empty($var)
1130
+ phpBody = phpBody.replace(/empty\(\$\$+/g, 'empty($');
1131
+
1132
+ phpBody = phpBody
1133
+ .replace(/\bundefined\b/g, 'null')
1134
+ .replace(/===/g, '==')
1135
+ .replace(/!==/g, '!=')
1136
+ .replace(/\|\|/g, '?:');
1137
+
1138
+ // Reject if params still look like TS leftovers
1139
+ if (params.some((p) => /[^A-Za-z0-9_$]/.test(p))) {
1140
+ return null;
1141
+ }
1142
+
1143
+ const phpParams = params.map((p) => `$${p}`).join(', ');
1144
+ return `if (!function_exists('${phpName}')) {\n function ${phpName}(${phpParams}) {\n${indentPhp(phpBody, 4)}\n }\n}\n`;
1145
+ } catch {
1146
+ return null;
1147
+ }
1148
+ }
1149
+
1150
+ /**
1151
+ * Best-effort convert a small JSX-returning helper (the common local
1152
+ * render-prop pattern — `const cell = (a, b) => (<div>…</div>)`, including
1153
+ * the dual-host ternary-chain shape —
1154
+ * `(v, k, cls, tag) => setAttributes ? <WpEditable/> : tag === 'p' ? <p/> : …`
1155
+ * — into an inlinable JSX template: its params plus the raw body text.
1156
+ *
1157
+ * jsHelperToPhpFunction rejects these (JSX can't become a PHP function body),
1158
+ * but leaving the call site untouched means the literal JS text
1159
+ * (`{cell(a, b)}`) ends up in render.php verbatim — the caller is expected to
1160
+ * inline this template at each call site instead, after which the body's
1161
+ * ternaries/JSX flow through the same transpileTernaries/transpileConditionals
1162
+ * pipeline that already handles this exact pattern when written inline.
1163
+ *
1164
+ * Only the simple arrow-expression-body shape is handled (no intermediate
1165
+ * statements before the returned expression), and only when the body
1166
+ * contains JSX and none of the JS-runtime-only constructs the regex-based
1167
+ * transpiler can't safely rewrite (mirrors jsHelperToPhpFunction's own
1168
+ * reject list). Anything else returns null so the caller's neutralization
1169
+ * safety net can take over instead of leaking broken text into the page.
1170
+ */
1171
+ export function jsxHelperToTemplate(jsHelperCode) {
1172
+ try {
1173
+ const code = stripTypeScriptSyntax(jsHelperCode).trim();
1174
+ const arrowExpr = code.match(
1175
+ /^(?:export\s+)?const\s+[A-Za-z_$][\w$]*\s*=\s*(?:async\s*)?\(([^)]*)\)\s*=>\s*([\s\S]+?)\s*;?\s*$/,
1176
+ );
1177
+ if (!arrowExpr) return null;
1178
+
1179
+ const params = splitParams(arrowExpr[1]);
1180
+ if (params.some((p) => /[^A-Za-z0-9_$]/.test(p))) return null;
1181
+
1182
+ let jsxBody = arrowExpr[2].trim();
1183
+ if (jsxBody.startsWith('(') && jsxBody.endsWith(')') && isBalancedParenWrap(jsxBody)) {
1184
+ jsxBody = jsxBody.slice(1, -1).trim();
1185
+ }
1186
+
1187
+ // Must actually contain JSX somewhere (a bare JS value/ternary with no
1188
+ // JSX belongs to jsHelperToPhpFunction's real-PHP-function path instead;
1189
+ // reaching here for JSX-less code means it was rejected for a different,
1190
+ // unsafe reason and shouldn't be inlined as markup either).
1191
+ if (!/<[A-Za-z/]|<>/.test(jsxBody)) return null;
1192
+
1193
+ if (
1194
+ /use[A-Z]|window\.|document\.|React\.|fetch\s*\(|await\s|import\s|require\s*\(/.test(jsxBody) ||
1195
+ /\.contains\b|addEventListener|removeEventListener/.test(jsxBody) ||
1196
+ // setAttributes(...) is exempt: it's the WordPress dual-host prop, not a
1197
+ // React state setter, and `setAttributes ? A : B` (its universal usage
1198
+ // shape here) already resolves safely to B in render.php — translateJsExpressionToPhp
1199
+ // turns the unknown bare identifier into `($setAttributes ?? null)`,
1200
+ // which is falsy since that PHP variable is never defined server-side.
1201
+ /\bset(?!Attributes\b)[A-Z][A-Za-z0-9_]*\s*\(/.test(jsxBody) ||
1202
+ /\btry\s*\{|\bcatch\s*[({]/.test(jsxBody) ||
1203
+ /\.(replace|split|slice|trim|includes|indexOf|lastIndexOf|join|push|pop|shift|unshift|concat|toLowerCase|toUpperCase|charAt|charCodeAt|substring|substr|padStart|padEnd|repeat|startsWith|endsWith|match|matchAll|search|exec|toFixed|filter|reduce|some|every|find|findIndex|flat|flatMap|sort|reverse)\s*\(/.test(jsxBody) ||
1204
+ /\.length\b/.test(jsxBody)
1205
+ ) {
1206
+ return null;
1207
+ }
1208
+
1209
+ return { params, jsxBody };
1210
+ } catch {
1211
+ return null;
1212
+ }
1213
+ }
1214
+
1215
+ function isBalancedParenWrap(s) {
1216
+ if (s[0] !== '(' || s[s.length - 1] !== ')') return false;
1217
+ let depth = 0;
1218
+ for (let i = 0; i < s.length; i++) {
1219
+ if (s[i] === '(') depth++;
1220
+ else if (s[i] === ')') {
1221
+ depth--;
1222
+ if (depth === 0) return i === s.length - 1;
1223
+ }
1224
+ }
1225
+ return false;
1226
+ }
1227
+
1228
+ function splitParams(paramStr) {
1229
+ if (!paramStr || !paramStr.trim()) return [];
1230
+ // After TS strip, params are plain names or defaults
1231
+ return paramStr
1232
+ .split(',')
1233
+ .map((p) => p.trim())
1234
+ .filter(Boolean)
1235
+ .map((p) => {
1236
+ const name = p.replace(/=.*$/, '').trim();
1237
+ // destructuring not supported
1238
+ if (name.startsWith('{') || name.startsWith('[')) return null;
1239
+ return name.replace(/^\.\.\./, '');
1240
+ })
1241
+ .filter(Boolean);
1242
+ }
1243
+
1244
+ function indentPhp(body, spaces) {
1245
+ const pad = ' '.repeat(spaces);
1246
+ return body
1247
+ .split('\n')
1248
+ .map((line) => (line.trim() ? pad + line.trimEnd() : ''))
1249
+ .join('\n');
1250
+ }
1251
+
1252
+ /**
1253
+ * Remove a top-level `const name = …` / `function name…` declaration from a
1254
+ * preamble string (balanced scan). Used so hoisted helpers aren't also left
1255
+ * inline — avoids "Identifier has already been declared" in the editor IIFE.
1256
+ */
1257
+ export function stripTopLevelHelperDecl(code, name) {
1258
+ if (!code || !name) return code;
1259
+ const patterns = [
1260
+ new RegExp(`(?:export\\s+)?const\\s+${name}\\s*=`),
1261
+ new RegExp(`(?:export\\s+)?function\\s+${name}\\b`),
1262
+ ];
1263
+ for (const re of patterns) {
1264
+ const m = code.match(re);
1265
+ if (!m || m.index === undefined) continue;
1266
+ const start = m.index;
1267
+ let i = start + m[0].length;
1268
+ // Skip to end of statement: for const, find expression end at top-level `;`
1269
+ // or for function, find matching body `}`
1270
+ if (m[0].includes('function')) {
1271
+ while (i < code.length && code[i] !== '{') i++;
1272
+ if (code[i] === '{') {
1273
+ let depth = 0;
1274
+ for (; i < code.length; i++) {
1275
+ if (code[i] === '{') depth++;
1276
+ else if (code[i] === '}') {
1277
+ depth--;
1278
+ if (depth === 0) {
1279
+ i++;
1280
+ break;
1281
+ }
1282
+ }
1283
+ }
1284
+ }
1285
+ } else {
1286
+ // const name = <expr> ;
1287
+ let depthParen = 0;
1288
+ let depthBrace = 0;
1289
+ let depthBracket = 0;
1290
+ let inStr = null;
1291
+ let escape = false;
1292
+ for (; i < code.length; i++) {
1293
+ const c = code[i];
1294
+ if (inStr) {
1295
+ if (escape) escape = false;
1296
+ else if (c === '\\') escape = true;
1297
+ else if (c === inStr) inStr = null;
1298
+ continue;
1299
+ }
1300
+ if (c === '"' || c === "'" || c === '`') {
1301
+ inStr = c;
1302
+ continue;
1303
+ }
1304
+ if (c === '(') depthParen++;
1305
+ else if (c === ')') depthParen--;
1306
+ else if (c === '{') depthBrace++;
1307
+ else if (c === '}') depthBrace--;
1308
+ else if (c === '[') depthBracket++;
1309
+ else if (c === ']') depthBracket--;
1310
+ else if (
1311
+ c === ';' &&
1312
+ depthParen === 0 &&
1313
+ depthBrace === 0 &&
1314
+ depthBracket === 0
1315
+ ) {
1316
+ i++;
1317
+ break;
1318
+ }
1319
+ }
1320
+ }
1321
+ while (i < code.length && /\s/.test(code[i])) i++;
1322
+ return code.slice(0, start) + code.slice(i);
1323
+ }
1324
+ return code;
1325
+ }
1326
+
1327
+ /**
1328
+ * Build a unique PHP function name for a block helper.
1329
+ */
1330
+ export function phpHelperName(blockSlug, helperName) {
1331
+ const safeSlug = String(blockSlug).replace(/[^a-zA-Z0-9_]/g, '_');
1332
+ const safeHelper = String(helperName).replace(/[^a-zA-Z0-9_]/g, '_');
1333
+ return `forgewp_blk_${safeSlug}_${safeHelper}`;
1334
+ }
1335
+
1336
+ /**
1337
+ * Rewrite bare attribute identifiers to `attributes.key` for the Gutenberg
1338
+ * customEditJsx IIFE — without breaking declarations.
1339
+ *
1340
+ * Unsafe (old): `const title = …` → `const attributes.title = …`
1341
+ * → SyntaxError: missing initializer in const declaration
1342
+ *
1343
+ * Safe: skip binding names after const/let/var; skip object keys (`title:`);
1344
+ * skip property access already under `attributes.` / `props.`.
1345
+ *
1346
+ * Style-agnostic: works with any local aliasing pattern the developer chooses.
1347
+ *
1348
+ * @param {string} code
1349
+ * @param {string[]} attrKeys
1350
+ * @returns {string}
1351
+ */
1352
+ /**
1353
+ * True when `offset` sits inside a string / template literal in `code`.
1354
+ * Prevents rewriting `'authority'` → `'attributes.authority'`.
1355
+ */
1356
+ function isInsideStringLiteral(code, offset) {
1357
+ let inSingle = false;
1358
+ let inDouble = false;
1359
+ let inBacktick = false;
1360
+ for (let i = 0; i < offset && i < code.length; i++) {
1361
+ const c = code[i];
1362
+ if (inSingle) {
1363
+ if (c === '\\') {
1364
+ i++;
1365
+ continue;
1366
+ }
1367
+ if (c === "'") inSingle = false;
1368
+ continue;
1369
+ }
1370
+ if (inDouble) {
1371
+ if (c === '\\') {
1372
+ i++;
1373
+ continue;
1374
+ }
1375
+ if (c === '"') inDouble = false;
1376
+ continue;
1377
+ }
1378
+ if (inBacktick) {
1379
+ if (c === '\\') {
1380
+ i++;
1381
+ continue;
1382
+ }
1383
+ if (c === '`') inBacktick = false;
1384
+ // template ${…} re-enters code mode for the expression
1385
+ else if (c === '$' && code[i + 1] === '{') {
1386
+ i += 2;
1387
+ let d = 1;
1388
+ while (i < offset && i < code.length && d > 0) {
1389
+ if (code[i] === '{') d++;
1390
+ else if (code[i] === '}') d--;
1391
+ i++;
1392
+ }
1393
+ i--; // for-loop will ++
1394
+ }
1395
+ continue;
1396
+ }
1397
+ if (c === "'") inSingle = true;
1398
+ else if (c === '"') inDouble = true;
1399
+ else if (c === '`') inBacktick = true;
1400
+ }
1401
+ return inSingle || inDouble || inBacktick;
1402
+ }
1403
+
1404
+ export function rewriteAttrRefsSafely(code, attrKeys) {
1405
+ if (!code || !attrKeys || attrKeys.length === 0) return code;
1406
+
1407
+ let out = code;
1408
+ for (const key of attrKeys) {
1409
+ if (!key || !/^[A-Za-z_$][\w$]*$/.test(key)) continue;
1410
+
1411
+ // 1. Shorthand object properties: { listicleId } -> { listicleId: attributes.listicleId }
1412
+ const shorthandRegex = new RegExp(`(?<=[{,]\\s*)${key}(?=\\s*[,}])`, 'g');
1413
+ out = out.replace(shorthandRegex, (match, offset, full) => {
1414
+ if (isInsideStringLiteral(full, offset)) return match;
1415
+ return `${key}: attributes.${key}`;
1416
+ });
1417
+
1418
+ // 2. Spreads: ...team → ...attributes.team (not inside strings)
1419
+ out = out.replace(new RegExp(`\\.\\.\\.${key}\\b`, 'g'), (match, offset) => {
1420
+ if (isInsideStringLiteral(out, offset)) return match;
1421
+ return `...attributes.${key}`;
1422
+ });
1423
+
1424
+ // 3. Normal references
1425
+ out = out.replace(
1426
+ new RegExp(`(?<![.\\w$])${key}(?![\\w$])(?!\\s*:)`, 'g'),
1427
+ (match, offset, full) => {
1428
+ if (isInsideStringLiteral(full, offset)) return match;
1429
+
1430
+ // Look behind (skip whitespace) for declaration keywords
1431
+ let i = offset - 1;
1432
+ while (i >= 0 && /\s/.test(full[i])) i--;
1433
+ // End of previous token
1434
+ let end = i;
1435
+ while (i >= 0 && /[A-Za-z0-9_$]/.test(full[i])) i--;
1436
+ const prevWord = full.slice(i + 1, end + 1);
1437
+ if (prevWord === 'const' || prevWord === 'let' || prevWord === 'var') {
1438
+ return match; // binding name — keep
1439
+ }
1440
+ // Already attributes.key / props.key (lookbehind for .)
1441
+ if (end >= 0 && full[end] === '.') {
1442
+ return match;
1443
+ }
1444
+ return `attributes.${key}`;
1445
+ },
1446
+ );
1447
+ }
1448
+ return out;
1449
+ }