@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,733 @@
1
+ /**
2
+ * Build editor-IIFE scope injections for identifiers that components import
3
+ * (e.g. `defaults` from cms/editables, layout helpers, module-level consts).
4
+ *
5
+ * The Gutenberg customEditJsx runs via `new Function(...)` and does not have
6
+ * ESM imports — anything the inlined body references must be injected here.
7
+ *
8
+ * Also builds a serializable `editorScope` object that the editor runtime can
9
+ * pass as Function parameters — a second line of defense if string injection
10
+ * is missing or stripped.
11
+ */
12
+ import { existsSync, readFileSync } from "node:fs";
13
+ import path from "node:path";
14
+ import { parseDefineEditable } from "./scanner.js";
15
+ import { stripTypeScriptSyntax } from "./source-sanitize.js";
16
+
17
+ /**
18
+ * @param {string} sourceCode Component source
19
+ * @param {string} filePath Absolute path to component
20
+ * @param {string} themeRoot
21
+ * @param {string} iifeBody customEditJsx body (to know which symbols are used)
22
+ * @returns {{ injections: string, scope: Record<string, unknown> }}
23
+ */
24
+ export function buildEditorScopeInjections(sourceCode, filePath, themeRoot, iifeBody) {
25
+ if (!sourceCode || !iifeBody) return { injections: "", scope: {} };
26
+
27
+ const chunks = [];
28
+ /** @type {Record<string, unknown>} */
29
+ const scope = {};
30
+ const used = (name) => new RegExp(`\\b${name}\\b`).test(iifeBody);
31
+
32
+ // ── defaults from cms/editables (or any defineEditable module) ───────────
33
+ // Supports aliased imports such as `import { defaults as heroDefaults }`.
34
+ const importedDefaults = resolveImportedDefaults(sourceCode, filePath, themeRoot);
35
+ for (const [local, obj] of Object.entries(importedDefaults)) {
36
+ if (local === "defaults" || !used(local)) continue;
37
+ scope[local] = obj;
38
+ chunks.push(`var ${local} = ${JSON.stringify(obj)};`);
39
+ }
40
+ if (used("defaults")) {
41
+ // Always define — empty bag still prevents "defaults is not defined"
42
+ const bag = importedDefaults.defaults || {};
43
+ scope.defaults = bag;
44
+ chunks.push(`var defaults = ${JSON.stringify(bag)};`);
45
+ }
46
+
47
+ // ── Module-level string/number/boolean consts (e.g. BAKED_PADDING = 'lg') ─
48
+ const moduleConsts = extractModuleLevelLiterals(sourceCode);
49
+ for (const [name, value] of Object.entries(moduleConsts)) {
50
+ if (used(name)) {
51
+ scope[name] = value;
52
+ chunks.push(`var ${name} = ${JSON.stringify(value)};`);
53
+ }
54
+ }
55
+
56
+ // ── Module-level object consts (e.g. SECTION_PADDING_Y = { ... }) ───────
57
+ // Prefer resolving from imports; also scan local source.
58
+ const objectConsts = extractModuleLevelObjectConsts(sourceCode);
59
+ for (const [name, value] of Object.entries(objectConsts)) {
60
+ if (used(name) && !(name in scope)) {
61
+ scope[name] = value;
62
+ chunks.push(`var ${name} = ${JSON.stringify(value)};`);
63
+ }
64
+ }
65
+
66
+ // ── Relative helper imports (sectionPaddingY, resolveBlockPaddingY, …) ───
67
+ const helperResult = resolveImportedHelpers(sourceCode, filePath, iifeBody, scope);
68
+ if (helperResult.code) chunks.push(helperResult.code);
69
+
70
+ // ── i18n free function: __( '…' ) ────────────────────────────────────────
71
+ // Components often do `const { __ } = useWpI18n()`. Nested expansions and
72
+ // some preambles omit that destructure, leaving bare `__(…)` references.
73
+ // Identity stub is correct for the editor canvas (no real gettext needed).
74
+ if (/\b__\s*\(/.test(iifeBody) && !/\bconst\s*\{\s*__\s*\}/.test(iifeBody)) {
75
+ chunks.push(`var __ = function(s) { return s; };`);
76
+ }
77
+
78
+ // ── Lucide / icon package free components ───────────────────────────────
79
+ // Data rows often store icon: Phone and render <Icon />. Without ESM, inject
80
+ // thin wrappers around forgeWpRenderIcon for every used PascalCase import
81
+ // from lucide-react (and similar) that appears in the IIFE body.
82
+ const iconStubs = buildIconComponentStubs(sourceCode, iifeBody);
83
+ if (iconStubs) chunks.push(iconStubs);
84
+
85
+ // ── String→icon maps: const VALUE_ICONS = { award: Award, … } ────────────
86
+ // Helpers like ValueIcon close over these maps. Values are components — inject
87
+ // slug→forgeWpRenderIcon wrappers so the helper body can resolve Static icons.
88
+ const iconMaps = buildIconMapInjections(sourceCode, iifeBody);
89
+ if (iconMaps) chunks.push(iconMaps);
90
+
91
+ // ── Dual-host prop aliases ──────────────────────────────────────────────
92
+ // 1) *Prop names (titleProp ← attributes.title)
93
+ // 2) Destructuring renames (stat1Value: v1p ← attributes.stat1Value)
94
+ const propAliasCode = buildPropAliasInjections(sourceCode, iifeBody);
95
+ if (propAliasCode) chunks.push(propAliasCode);
96
+
97
+ return {
98
+ injections: chunks.filter(Boolean).join("\n"),
99
+ scope,
100
+ };
101
+ }
102
+
103
+ /**
104
+ * Inject `var Phone = (p) => forgeWpRenderIcon('phone', …)` style stubs for
105
+ * lucide-react (etc.) imports referenced in the editor IIFE.
106
+ */
107
+ function buildIconComponentStubs(sourceCode, iifeBody) {
108
+ if (!sourceCode || !iifeBody) return "";
109
+ const importRe =
110
+ /import\s+\{([^}]+)\}\s+from\s+['"](lucide-react|@lucide\/react|react-icons\/[\w-]+)['"]/g;
111
+ const names = [];
112
+ let m;
113
+ while ((m = importRe.exec(sourceCode)) !== null) {
114
+ for (const part of m[1].split(",")) {
115
+ const bits = part.trim().split(/\s+as\s+/);
116
+ const local = (bits[1] || bits[0] || "").trim();
117
+ if (local && /^[A-Z]/.test(local) && new RegExp(`\\b${local}\\b`).test(iifeBody)) {
118
+ names.push(local);
119
+ }
120
+ }
121
+ }
122
+ if (names.length === 0) return "";
123
+
124
+ const lines = [
125
+ `// Icon component stubs (lucide etc. → forgeWpRenderIcon)`,
126
+ ];
127
+ for (const name of names) {
128
+ // PascalCase → likely registry slug (Phone → phone, MapPin → map-pin)
129
+ const slug = name
130
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
131
+ .replace(/([A-Z])([A-Z][a-z])/g, "$1-$2")
132
+ .toLowerCase();
133
+ lines.push(
134
+ `var ${name} = function(p) {` +
135
+ ` return (typeof forgeWpRenderIcon === 'function')` +
136
+ ` ? forgeWpRenderIcon(${JSON.stringify(slug)}, p && (p.className || p.class) || '', 'lucide')` +
137
+ ` : null; };`,
138
+ );
139
+ }
140
+ return lines.join("\n");
141
+ }
142
+
143
+ /**
144
+ * Inject `var VALUE_ICONS = { award: fn, … }` for maps used by helpers like ValueIcon.
145
+ * Source shape: `const VALUE_ICONS = { award: Award, shield: Shield, … }`
146
+ */
147
+ function buildIconMapInjections(sourceCode, iifeBody) {
148
+ if (!sourceCode || !iifeBody) return "";
149
+ // const NAME = { key: Ident, … } (optional TS type annotation)
150
+ const re =
151
+ /(?:export\s+)?const\s+([A-Z][A-Z0-9_]*)\s*(?::[^=]+)?=\s*\{/g;
152
+ const chunks = [];
153
+ let m;
154
+ while ((m = re.exec(sourceCode)) !== null) {
155
+ const mapName = m[1];
156
+ if (!new RegExp(`\\b${mapName}\\b`).test(iifeBody)) continue;
157
+
158
+ const braceStart = m.index + m[0].length - 1;
159
+ let depth = 0;
160
+ let end = -1;
161
+ for (let i = braceStart; i < sourceCode.length; i++) {
162
+ if (sourceCode[i] === "{") depth++;
163
+ else if (sourceCode[i] === "}") {
164
+ depth--;
165
+ if (depth === 0) {
166
+ end = i;
167
+ break;
168
+ }
169
+ }
170
+ }
171
+ if (end < 0) continue;
172
+ const body = sourceCode.slice(braceStart + 1, end);
173
+ // key: PascalCaseIdent pairs
174
+ const pairRe = /([A-Za-z_$][\w$]*)\s*:\s*([A-Z][A-Za-z0-9_$]*)/g;
175
+ const entries = [];
176
+ let p;
177
+ while ((p = pairRe.exec(body)) !== null) {
178
+ const key = p[1];
179
+ const slug = key
180
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
181
+ .replace(/([A-Z])([A-Z][a-z])/g, "$1-$2")
182
+ .toLowerCase();
183
+ entries.push(
184
+ `${JSON.stringify(key)}: function(pr) {` +
185
+ ` return (typeof forgeWpRenderIcon === 'function')` +
186
+ ` ? forgeWpRenderIcon(${JSON.stringify(slug)}, pr && (pr.className || pr.class) || '', 'lucide')` +
187
+ ` : null; }`,
188
+ );
189
+ }
190
+ if (entries.length === 0) continue;
191
+ chunks.push(
192
+ `// Icon map stub for ${mapName}`,
193
+ `var ${mapName} = { ${entries.join(", ")} };`,
194
+ );
195
+ }
196
+ return chunks.join("\n");
197
+ }
198
+
199
+ /**
200
+ * Resolve `import { defaults } from '…'` / `import { defaults as X }` to plain objects.
201
+ * @returns {Record<string, Record<string, unknown>>} local binding name → defaults bag
202
+ */
203
+ function resolveImportedDefaults(sourceCode, filePath, themeRoot) {
204
+ // import { editable as frontPageEditable, defaults } from '…'
205
+ // import { defaults as heroDefaults } from '…'
206
+ const importRe =
207
+ /import\s+\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/g;
208
+ /** @type {Record<string, Record<string, unknown>>} */
209
+ const out = {};
210
+ let im;
211
+ while ((im = importRe.exec(sourceCode)) !== null) {
212
+ const names = im[1].split(",").map((p) => p.trim());
213
+ let localDefaultsName = null;
214
+ for (const part of names) {
215
+ const bits = part.split(/\s+as\s+/);
216
+ const orig = bits[0].trim();
217
+ const local = (bits[1] || bits[0]).trim();
218
+ if (orig === "defaults" || local === "defaults") {
219
+ localDefaultsName = local;
220
+ break;
221
+ }
222
+ }
223
+ if (!localDefaultsName || localDefaultsName in out) continue;
224
+
225
+ const resolved = resolveModuleFile(path.dirname(filePath), im[2], themeRoot);
226
+ if (!resolved) continue;
227
+
228
+ const schemaCode = readFileSync(resolved, "utf8");
229
+ const schema = parseDefineEditable(schemaCode);
230
+ if (!schema) continue;
231
+
232
+ const defaultsObj = {};
233
+ for (const [key, field] of Object.entries(schema)) {
234
+ if (field && typeof field === "object" && "default" in field) {
235
+ defaultsObj[key] = field.default;
236
+ }
237
+ }
238
+ out[localDefaultsName] = defaultsObj;
239
+ }
240
+ return out;
241
+ }
242
+
243
+ /**
244
+ * Top-level `const NAME = 'literal' | number | boolean` (after strip).
245
+ */
246
+ function extractModuleLevelLiterals(sourceCode) {
247
+ const stripped = stripTypeScriptSyntax(sourceCode);
248
+ const out = {};
249
+ // Only consider declarations before the first export function/component-ish line
250
+ const firstExportFn = stripped.search(
251
+ /export\s+(?:default\s+)?(?:function|const)\s+[A-Z]/,
252
+ );
253
+ const head =
254
+ firstExportFn === -1 ? stripped : stripped.slice(0, firstExportFn);
255
+
256
+ const re =
257
+ /(?:export\s+)?const\s+([A-Za-z_$][\w$]*)\s*=\s*(['"])((?:\\.|[^\\])*?)\2\s*;/g;
258
+ let m;
259
+ while ((m = re.exec(head)) !== null) {
260
+ out[m[1]] = m[3].replace(/\\(['"])/g, "$1");
261
+ }
262
+ const reNum =
263
+ /(?:export\s+)?const\s+([A-Za-z_$][\w$]*)\s*=\s*(-?\d+(?:\.\d+)?)\s*;/g;
264
+ while ((m = reNum.exec(head)) !== null) {
265
+ out[m[1]] = Number(m[2]);
266
+ }
267
+ const reBool =
268
+ /(?:export\s+)?const\s+([A-Za-z_$][\w$]*)\s*=\s*(true|false)\s*;/g;
269
+ while ((m = reBool.exec(head)) !== null) {
270
+ out[m[1]] = m[2] === "true";
271
+ }
272
+ return out;
273
+ }
274
+
275
+ /**
276
+ * Top-level `const NAME = { ... }` with JSON-ish object literals (no functions).
277
+ */
278
+ function extractModuleLevelObjectConsts(sourceCode) {
279
+ const stripped = stripTypeScriptSyntax(sourceCode);
280
+ const out = {};
281
+ const re =
282
+ /(?:export\s+)?const\s+([A-Za-z_$][\w$]*)\s*=\s*(\{)/g;
283
+ let m;
284
+ while ((m = re.exec(stripped)) !== null) {
285
+ const name = m[1];
286
+ const braceStart = m.index + m[0].length - 1;
287
+ const objStr = extractBalanced(stripped, braceStart, "{", "}");
288
+ if (!objStr) continue;
289
+ // Skip if looks like it contains functions / spreads we can't JSON.parse
290
+ if (/\bfunction\b|=>|\.\.\./.test(objStr)) continue;
291
+ try {
292
+ // Quote bare keys: { none: '' } → { "none": '' } then normalize quotes
293
+ const jsonish = objStr
294
+ .replace(/'/g, '"')
295
+ .replace(/([{,]\s*)([A-Za-z_$][\w$]*)\s*:/g, '$1"$2":')
296
+ .replace(/,\s*}/g, "}");
297
+ out[name] = JSON.parse(jsonish);
298
+ } catch {
299
+ // ignore non-JSON objects
300
+ }
301
+ }
302
+ return out;
303
+ }
304
+
305
+ /**
306
+ * Inline simple exported helpers from relative imports when referenced in the IIFE.
307
+ * Falls back to no-op stubs if the module can't be inlined safely.
308
+ * Also pulls object consts (SECTION_PADDING_Y) from those modules into scope.
309
+ */
310
+ function resolveImportedHelpers(sourceCode, filePath, iifeBody, scope) {
311
+ const chunks = [];
312
+ const importRe =
313
+ /import\s+\{([^}]+)\}\s+from\s+['"](\.[^'"]+|@\/[^'"]+)['"]/g;
314
+ let im;
315
+ while ((im = importRe.exec(sourceCode)) !== null) {
316
+ const from = im[2];
317
+ // Skip editables (handled as defaults) and wordpress bridge
318
+ if (from.includes("editables") || from.includes("wordpress")) continue;
319
+
320
+ const names = im[1].split(",").map((p) => p.trim());
321
+ const resolved = resolveModuleFile(path.dirname(filePath), from);
322
+ let modCode = null;
323
+ /** @type {Record<string, unknown>} */
324
+ let modObjects = {};
325
+ /** @type {Record<string, unknown>} */
326
+ let modLiterals = {};
327
+ if (resolved) {
328
+ modCode = stripTypeScriptSyntax(readFileSync(resolved, "utf8"));
329
+ modObjects = extractModuleLevelObjectConsts(modCode);
330
+ modLiterals = extractModuleLevelLiterals(modCode);
331
+ }
332
+
333
+ // Collect inlined helper source so we can pull free object consts they need
334
+ // (e.g. sectionPaddingY body references SECTION_PADDING_Y even when the
335
+ // component source never mentions that name).
336
+ const inlinedHelperCode = [];
337
+
338
+ for (const part of names) {
339
+ const bits = part.split(/\s+as\s+/);
340
+ const orig = bits[0].trim();
341
+ const local = (bits[1] || bits[0]).trim();
342
+ if (!local || local === "defaults" || local === "editable") continue;
343
+ // Skip type-only names
344
+ if (orig === "type" || local.startsWith("type ")) continue;
345
+ if (!new RegExp(`\\b${local}\\b`).test(iifeBody)) continue;
346
+
347
+ // Already injected as object/literal const
348
+ if (local in scope) continue;
349
+
350
+ if (!resolved || !modCode) {
351
+ chunks.push(stubHelper(local));
352
+ continue;
353
+ }
354
+
355
+ // Imported name is a module-level object/literal const
356
+ if (orig in modObjects) {
357
+ scope[local] = modObjects[orig];
358
+ chunks.push(`var ${local} = ${JSON.stringify(modObjects[orig])};`);
359
+ continue;
360
+ }
361
+ if (orig in modLiterals) {
362
+ scope[local] = modLiterals[orig];
363
+ chunks.push(`var ${local} = ${JSON.stringify(modLiterals[orig])};`);
364
+ continue;
365
+ }
366
+
367
+ const fn = extractExportedFunction(modCode, orig);
368
+ if (fn && looksLikeJsxComponent(fn)) {
369
+ // A React component (contains raw JSX), not a plain helper — naive brace
370
+ // extraction would dump its untranspiled JSX straight into the editor IIFE,
371
+ // producing invalid JS ("Unexpected token '<'"). Its actual rendering is
372
+ // already handled at the JSX-tag level (island placeholder for live-data
373
+ // components); it's never *called* like a function, so a safe no-op stub
374
+ // is enough to satisfy stray references (e.g. its name appearing inside a
375
+ // placeholder string like "DestinationsGrid - interactive preview").
376
+ chunks.push(stubHelper(local));
377
+ continue;
378
+ }
379
+ if (fn) {
380
+ let code = fn;
381
+ if (orig !== local) {
382
+ code = code
383
+ .replace(
384
+ new RegExp(
385
+ `^(export\\s+)?(function\\s+|const\\s+)${orig}\\b`,
386
+ ),
387
+ `$1$2${local}`,
388
+ )
389
+ .replace(
390
+ new RegExp(`^export\\s+function\\s+${orig}\\b`),
391
+ `function ${local}`,
392
+ )
393
+ .replace(
394
+ new RegExp(`^export\\s+const\\s+${orig}\\b`),
395
+ `const ${local}`,
396
+ );
397
+ } else {
398
+ code = code.replace(/^export\s+/, "");
399
+ }
400
+ chunks.push(code);
401
+ inlinedHelperCode.push(code);
402
+ } else {
403
+ chunks.push(stubHelper(local));
404
+ }
405
+ }
406
+
407
+ // After inlining helpers, inject any module consts those helpers reference
408
+ const helperBlob = inlinedHelperCode.join("\n");
409
+ if (helperBlob) {
410
+ for (const [name, value] of Object.entries(modObjects)) {
411
+ if (
412
+ new RegExp(`\\b${name}\\b`).test(helperBlob) &&
413
+ !(name in scope)
414
+ ) {
415
+ scope[name] = value;
416
+ // Prepend so helpers can close over it — push to front of chunks
417
+ chunks.unshift(`var ${name} = ${JSON.stringify(value)};`);
418
+ }
419
+ }
420
+ for (const [name, value] of Object.entries(modLiterals)) {
421
+ if (
422
+ new RegExp(`\\b${name}\\b`).test(helperBlob) &&
423
+ !(name in scope)
424
+ ) {
425
+ scope[name] = value;
426
+ chunks.unshift(`var ${name} = ${JSON.stringify(value)};`);
427
+ }
428
+ }
429
+ }
430
+ }
431
+ return { code: chunks.join("\n\n") };
432
+ }
433
+
434
+ /**
435
+ * Names that must NEVER be redeclared inside customEditJsx.
436
+ * Shadowing `setAttributes` / `attributes` breaks RichText onChange and
437
+ * turns `setAttributes ? <WpEditable/> : static` into permanent static text
438
+ * (sidebar still works because InspectorControls uses the outer callback).
439
+ */
440
+ const EDITOR_RESERVED_LOCALS = new Set([
441
+ "setAttributes",
442
+ "attributes",
443
+ "clientId",
444
+ "isSelected",
445
+ "context",
446
+ "className",
447
+ "name",
448
+ "props",
449
+ "createElement",
450
+ "React",
451
+ "useBlockProps",
452
+ "blockProps",
453
+ "children",
454
+ "ref",
455
+ "key",
456
+ "__attr",
457
+ ]);
458
+
459
+ /**
460
+ * Build const aliases for dual-host props:
461
+ * - titleProp ← attributes.title
462
+ * - v1p ← attributes.stat1Value (from `stat1Value: v1p` destructure)
463
+ *
464
+ * Never alias reserved editor bindings (especially setAttributes).
465
+ */
466
+ function buildPropAliasInjections(sourceCode, iifeBody) {
467
+ const chunks = [];
468
+ const aliases = new Map(); // localName → attrKey
469
+
470
+ // From component destructuring: { title: titleProp, stat1Value: v1p, paddingY: paddingYProp }
471
+ const destructureAliases = extractDestructureAliases(sourceCode);
472
+ for (const [local, attrKey] of Object.entries(destructureAliases)) {
473
+ if (EDITOR_RESERVED_LOCALS.has(local) || EDITOR_RESERVED_LOCALS.has(attrKey)) {
474
+ continue;
475
+ }
476
+ if (new RegExp(`\\b${local}\\b`).test(iifeBody)) {
477
+ aliases.set(local, attrKey);
478
+ }
479
+ }
480
+
481
+ // Also catch *Prop convention even without destructure map
482
+ const re = /\b([A-Za-z_$][\w$]*)Prop\b/g;
483
+ let m;
484
+ while ((m = re.exec(iifeBody)) !== null) {
485
+ const local = m[0]; // e.g. titleProp
486
+ const base = m[1]; // e.g. title
487
+ if (EDITOR_RESERVED_LOCALS.has(local) || EDITOR_RESERVED_LOCALS.has(base)) {
488
+ continue;
489
+ }
490
+ if (!aliases.has(local)) {
491
+ aliases.set(local, base);
492
+ }
493
+ }
494
+
495
+ if (aliases.size === 0) return "";
496
+
497
+ chunks.push(`// Dual-host prop aliases (block attributes → local names used in components)`);
498
+ chunks.push(
499
+ `var __attr = (typeof attributes === 'object' && attributes) ? attributes : {};`,
500
+ );
501
+
502
+ for (const [local, attrKey] of aliases) {
503
+ if (EDITOR_RESERVED_LOCALS.has(local)) continue;
504
+ // Prefer attributes[attrKey], then attributes[local], else undefined
505
+ chunks.push(
506
+ `var ${local} = (typeof __attr[${JSON.stringify(attrKey)}] !== 'undefined')` +
507
+ ` ? __attr[${JSON.stringify(attrKey)}]` +
508
+ ` : (typeof __attr[${JSON.stringify(local)}] !== 'undefined' ? __attr[${JSON.stringify(local)}] : undefined);`,
509
+ );
510
+ }
511
+
512
+ return chunks.join("\n");
513
+ }
514
+
515
+ /**
516
+ * Parse `export function Foo({ a: aLocal, b: bLocal, c }: Props)` renames.
517
+ * Returns { aLocal: 'a', bLocal: 'b', c: 'c' } for names used as locals.
518
+ *
519
+ * IMPORTANT: run on the original source — stripTypeScriptSyntax treats
520
+ * `stat1Value: v1p` as a type annotation and deletes the rename.
521
+ */
522
+ function extractDestructureAliases(sourceCode) {
523
+ // Find first component-like function with object destructure props.
524
+ // Match up to the closing `}` of the destructure, then optional `}: Type`.
525
+ const fnMatch = sourceCode.match(
526
+ /(?:export\s+)?(?:default\s+)?function\s+[A-Z][A-Za-z0-9_]*\s*\(\s*\{/,
527
+ );
528
+ const arrowMatch = !fnMatch
529
+ ? sourceCode.match(
530
+ /(?:export\s+)?const\s+[A-Z][A-Za-z0-9_]*\s*=\s*\(\s*\{/,
531
+ )
532
+ : null;
533
+ const startMatch = fnMatch || arrowMatch;
534
+ if (!startMatch) return {};
535
+
536
+ const openIdx = startMatch.index + startMatch[0].length - 1; // points at `{`
537
+ const destructure = extractBalanced(sourceCode, openIdx, "{", "}");
538
+ if (!destructure || destructure.length < 2) return {};
539
+ const body = destructure.slice(1, -1); // inside braces
540
+
541
+ const out = {};
542
+ // Split on commas at depth 0 (simple — props are flat)
543
+ const parts = splitTopLevel(body, ",");
544
+ for (const part of parts) {
545
+ const p = part.trim();
546
+ if (!p || p.startsWith("...")) continue;
547
+ // name: rename OR name = default OR name
548
+ // Prefer rename: `stat1Value: v1p` / `title: titleProp`
549
+ const renameMatch = p.match(
550
+ /^([A-Za-z_$][\w$]*)\s*:\s*([A-Za-z_$][\w$]*)\s*(?:=|$)/,
551
+ );
552
+ if (renameMatch) {
553
+ out[renameMatch[2]] = renameMatch[1];
554
+ continue;
555
+ }
556
+ const plainMatch = p.match(/^([A-Za-z_$][\w$]*)/);
557
+ if (plainMatch) {
558
+ out[plainMatch[1]] = plainMatch[1];
559
+ }
560
+ }
561
+ return out;
562
+ }
563
+
564
+ function splitTopLevel(s, sep) {
565
+ const parts = [];
566
+ let depth = 0;
567
+ let cur = "";
568
+ for (let i = 0; i < s.length; i++) {
569
+ const c = s[i];
570
+ if (c === "{" || c === "(" || c === "[") depth++;
571
+ else if (c === "}" || c === ")" || c === "]") depth--;
572
+ if (c === sep && depth === 0) {
573
+ parts.push(cur);
574
+ cur = "";
575
+ continue;
576
+ }
577
+ cur += c;
578
+ }
579
+ if (cur.trim()) parts.push(cur);
580
+ return parts;
581
+ }
582
+
583
+ function extractBalanced(s, startIdx, open, close) {
584
+ if (s[startIdx] !== open) return null;
585
+ let depth = 0;
586
+ for (let i = startIdx; i < s.length; i++) {
587
+ if (s[i] === open) depth++;
588
+ else if (s[i] === close) {
589
+ depth--;
590
+ if (depth === 0) return s.slice(startIdx, i + 1);
591
+ }
592
+ }
593
+ return null;
594
+ }
595
+
596
+ /**
597
+ * Heuristic: does this extracted function body contain raw JSX? Real plain-JS
598
+ * helpers (padding resolvers, formatters, className builders, etc.) never emit
599
+ * a `<Tag`, `<tag-name`, `</Tag>` or self-closing `<Tag .../>` sequence — those
600
+ * only appear in component render bodies.
601
+ */
602
+ function looksLikeJsxComponent(code) {
603
+ return /<\/?[A-Za-z][\w.]*[\s/>]/.test(code);
604
+ }
605
+
606
+ function stubHelper(name) {
607
+ // Safe no-op stubs for editor preview — must not throw.
608
+ if (/padding|Padding|className|Class/.test(name)) {
609
+ return `function ${name}() { var a = arguments; if (a.length === 0) return ''; var v = a[0]; return (typeof v === 'string' ? v : ''); }`;
610
+ }
611
+ if (/resolve|Resolve/.test(name)) {
612
+ return `function ${name}() { var a = arguments; return a[a.length - 1]; }`;
613
+ }
614
+ return `function ${name}() { return undefined; }`;
615
+ }
616
+
617
+ function extractExportedFunction(modCode, name) {
618
+ // function name(...) { ... }
619
+ const start = modCode.search(
620
+ new RegExp(`(?:export\\s+)?function\\s+${name}\\s*\\(`),
621
+ );
622
+ if (start !== -1) {
623
+ // Balance the parameter list's own parens first — a destructured param
624
+ // (`function X({ a, b }: Props) { ... }`) contains a `{`/`}` pair of its
625
+ // own that a naive "find the first {" would mistake for the function
626
+ // body's opening brace, truncating the extraction right after the
627
+ // parameter list and silently dropping the entire body.
628
+ const parenStart = modCode.indexOf("(", start);
629
+ let parenDepth = 0;
630
+ let parenEnd = -1;
631
+ for (let i = parenStart; i < modCode.length; i++) {
632
+ if (modCode[i] === "(") parenDepth++;
633
+ else if (modCode[i] === ")") {
634
+ parenDepth--;
635
+ if (parenDepth === 0) {
636
+ parenEnd = i;
637
+ break;
638
+ }
639
+ }
640
+ }
641
+ const brace =
642
+ parenEnd !== -1
643
+ ? modCode.indexOf("{", parenEnd)
644
+ : modCode.indexOf("{", start);
645
+ if (brace !== -1) {
646
+ let depth = 0;
647
+ for (let i = brace; i < modCode.length; i++) {
648
+ if (modCode[i] === "{") depth++;
649
+ else if (modCode[i] === "}") {
650
+ depth--;
651
+ if (depth === 0) {
652
+ return modCode.slice(start, i + 1).replace(/^export\s+/, "");
653
+ }
654
+ }
655
+ }
656
+ }
657
+ }
658
+
659
+ // const name = (...) => { ... } or (...) => expr;
660
+ const constStart = modCode.search(
661
+ new RegExp(`(?:export\\s+)?const\\s+${name}\\s*=`),
662
+ );
663
+ if (constStart !== -1) {
664
+ let i = modCode.indexOf("=", constStart) + 1;
665
+ while (i < modCode.length && /\s/.test(modCode[i])) i++;
666
+ // scan to top-level semicolon
667
+ let depthParen = 0;
668
+ let depthBrace = 0;
669
+ let inStr = null;
670
+ let esc = false;
671
+ const exprStart = constStart;
672
+ for (; i < modCode.length; i++) {
673
+ const c = modCode[i];
674
+ if (inStr) {
675
+ if (esc) esc = false;
676
+ else if (c === "\\") esc = true;
677
+ else if (c === inStr) inStr = null;
678
+ continue;
679
+ }
680
+ if (c === '"' || c === "'" || c === "`") {
681
+ inStr = c;
682
+ continue;
683
+ }
684
+ if (c === "(") depthParen++;
685
+ else if (c === ")") depthParen--;
686
+ else if (c === "{") depthBrace++;
687
+ else if (c === "}") depthBrace--;
688
+ else if (c === ";" && depthParen === 0 && depthBrace === 0) {
689
+ return modCode
690
+ .slice(exprStart, i + 1)
691
+ .replace(/^export\s+/, "");
692
+ }
693
+ }
694
+ }
695
+
696
+ return null;
697
+ }
698
+
699
+ function resolveModuleFile(fromDir, importPath, themeRoot) {
700
+ let base = importPath;
701
+ if (base.startsWith("@/") && themeRoot) {
702
+ base = path.resolve(themeRoot, base.replace("@/", "src/"));
703
+ // treat as absolute-ish path from here
704
+ const extensions = [".ts", ".tsx", ".js", ".jsx", ""];
705
+ for (const ext of extensions) {
706
+ const p = base + ext;
707
+ if (existsSync(p) && !requiresDir(p)) return p;
708
+ const idx = path.join(base, "index" + (ext || ".ts"));
709
+ if (existsSync(idx)) return idx;
710
+ }
711
+ return null;
712
+ }
713
+
714
+ const extensions = [".ts", ".tsx", ".js", ".jsx"];
715
+ for (const ext of extensions) {
716
+ let p = path.resolve(fromDir, importPath + ext);
717
+ if (existsSync(p)) return p;
718
+ p = path.resolve(fromDir, importPath, "index" + ext);
719
+ if (existsSync(p)) return p;
720
+ }
721
+ // bare path with extension already
722
+ const direct = path.resolve(fromDir, importPath);
723
+ if (existsSync(direct)) return direct;
724
+ return null;
725
+ }
726
+
727
+ function requiresDir(p) {
728
+ try {
729
+ return existsSync(p) && !p.match(/\.\w+$/);
730
+ } catch {
731
+ return false;
732
+ }
733
+ }