@getchomp/mcp 0.0.0-stage → 0.2.42

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 (56) hide show
  1. package/README.md +15 -2
  2. package/dist/conventionsReference.d.ts +84 -0
  3. package/dist/conventionsReference.js +313 -0
  4. package/dist/designSystem/astScanner.d.ts +153 -0
  5. package/dist/designSystem/astScanner.js +2014 -0
  6. package/dist/designSystem/baseline.d.ts +65 -0
  7. package/dist/designSystem/baseline.js +136 -0
  8. package/dist/designSystem/color.d.ts +35 -0
  9. package/dist/designSystem/color.js +265 -0
  10. package/dist/designSystem/config.d.ts +183 -0
  11. package/dist/designSystem/config.js +469 -0
  12. package/dist/designSystem/contrast.d.ts +55 -0
  13. package/dist/designSystem/contrast.js +377 -0
  14. package/dist/designSystem/cssParser.d.ts +63 -0
  15. package/dist/designSystem/cssParser.js +469 -0
  16. package/dist/designSystem/merges.d.ts +57 -0
  17. package/dist/designSystem/merges.js +94 -0
  18. package/dist/designSystem/preprocessors.d.ts +46 -0
  19. package/dist/designSystem/preprocessors.js +1108 -0
  20. package/dist/designSystem/presentation.d.ts +45 -0
  21. package/dist/designSystem/presentation.js +796 -0
  22. package/dist/designSystem/styleVectors.d.ts +27 -0
  23. package/dist/designSystem/styleVectors.js +484 -0
  24. package/dist/designSystem/tokens.d.ts +39 -0
  25. package/dist/designSystem/tokens.js +409 -0
  26. package/dist/designSystem/topology.d.ts +64 -0
  27. package/dist/designSystem/topology.js +254 -0
  28. package/dist/designSystem/types.d.ts +857 -0
  29. package/dist/designSystem/types.js +113 -0
  30. package/dist/designSystem/typography.d.ts +25 -0
  31. package/dist/designSystem/typography.js +244 -0
  32. package/dist/designSystem/uiShapes.d.ts +74 -0
  33. package/dist/designSystem/uiShapes.js +285 -0
  34. package/dist/designSystem/valueClusters.d.ts +76 -0
  35. package/dist/designSystem/valueClusters.js +281 -0
  36. package/dist/designSystemPlugin.d.ts +321 -0
  37. package/dist/designSystemPlugin.js +4730 -0
  38. package/dist/enrichNodesPlugin.d.ts +160 -0
  39. package/dist/enrichNodesPlugin.js +957 -0
  40. package/dist/index.d.ts +65 -0
  41. package/dist/index.js +1298 -0
  42. package/dist/intelligence.d.ts +502 -0
  43. package/dist/intelligence.js +3058 -0
  44. package/dist/pluginRunner.d.ts +364 -0
  45. package/dist/pluginRunner.js +1096 -0
  46. package/dist/plugins/design-system/index.d.ts +14 -0
  47. package/dist/plugins/design-system/index.js +241 -0
  48. package/dist/plugins/enrich-nodes/index.d.ts +388 -0
  49. package/dist/plugins/enrich-nodes/index.js +697 -0
  50. package/dist/plugins/index.d.ts +15 -0
  51. package/dist/plugins/index.js +20 -0
  52. package/dist/plugins/local-shims/index.d.ts +121 -0
  53. package/dist/plugins/local-shims/index.js +237 -0
  54. package/dist/shimsPlugin.d.ts +134 -0
  55. package/dist/shimsPlugin.js +1392 -0
  56. package/package.json +38 -3
@@ -0,0 +1,1108 @@
1
+ /**
2
+ * packages/mcp/src/designSystem/preprocessors.ts
3
+ *
4
+ * Line-preserving preprocessors for non-TSX/CSS frontend formats:
5
+ * - Stylesheets: `.scss`, `.less` (single-line `//` comments outside `url(...)`/strings, `$var` / `@var` tokens)
6
+ * - Single-File & Content Components: `.vue`, `.svelte`, `.astro`, `.mdx`
7
+ * - Extracts embedded `<style>` blocks with exact 1-based line padding for `parseCssStylesheet`
8
+ * - Transforms `<script>` + `<template>` / Astro frontmatter+markup / MDX JSX into valid,
9
+ * line-preserving TSX so `scanTsxOrTsFile` inventories DOM primitives, Tailwind utilities,
10
+ * inline style literals, prop contracts, JSX skeletons, and component call sites accurately.
11
+ */
12
+ import { basename, dirname } from "node:path";
13
+ export const LESS_AT_RULE_KEYWORDS = new Set([
14
+ "import",
15
+ "media",
16
+ "supports",
17
+ "keyframes",
18
+ "-webkit-keyframes",
19
+ "-moz-keyframes",
20
+ "font-face",
21
+ "layer",
22
+ "container",
23
+ "scope",
24
+ "starting-style",
25
+ "document",
26
+ "property",
27
+ "theme",
28
+ "charset",
29
+ "namespace",
30
+ "page",
31
+ "plugin",
32
+ "use",
33
+ "forward",
34
+ "mixin",
35
+ "include",
36
+ "extend",
37
+ "function",
38
+ "return",
39
+ "if",
40
+ "else",
41
+ "each",
42
+ "for",
43
+ "while",
44
+ "warn",
45
+ "error",
46
+ "debug",
47
+ "at-root",
48
+ "content",
49
+ ]);
50
+ const HTML_VOID_TAGS = new Set([
51
+ "area",
52
+ "base",
53
+ "br",
54
+ "col",
55
+ "embed",
56
+ "hr",
57
+ "img",
58
+ "input",
59
+ "link",
60
+ "meta",
61
+ "param",
62
+ "source",
63
+ "track",
64
+ "wbr",
65
+ ]);
66
+ export function detectStylesheetSyntax(filePath) {
67
+ const lower = filePath.toLowerCase();
68
+ if (lower.endsWith(".scss") || lower.endsWith(".sass"))
69
+ return "scss";
70
+ if (lower.endsWith(".less"))
71
+ return "less";
72
+ return "css";
73
+ }
74
+ export function isSupportedStylesheetFile(filePath) {
75
+ const lower = filePath.toLowerCase();
76
+ return lower.endsWith(".css") || lower.endsWith(".scss") || lower.endsWith(".less");
77
+ }
78
+ export function isPreprocessedUiComponentFile(filePath) {
79
+ const lower = filePath.toLowerCase();
80
+ return (lower.endsWith(".vue") ||
81
+ lower.endsWith(".svelte") ||
82
+ lower.endsWith(".astro") ||
83
+ lower.endsWith(".mdx"));
84
+ }
85
+ /**
86
+ * Strips `/* ... * /` block comments and (when `allowLineComments` is true for `.scss`/`.less`)
87
+ * `// ...` single-line comments outside string literals and `(...)` (e.g. `url(https://...)`),
88
+ * replacing stripped characters with spaces while preserving every `\n`.
89
+ */
90
+ export function stripStylesheetCommentsPreservingLines(rawText, allowLineComments = false) {
91
+ const chars = Array.from(rawText);
92
+ const len = chars.length;
93
+ let quote = null;
94
+ let parenDepth = 0;
95
+ let i = 0;
96
+ while (i < len) {
97
+ const ch = chars[i];
98
+ const next = i + 1 < len ? chars[i + 1] : "";
99
+ if (quote) {
100
+ if (ch === "\\" && i + 1 < len) {
101
+ i += 2;
102
+ continue;
103
+ }
104
+ if (ch === quote) {
105
+ quote = null;
106
+ }
107
+ i++;
108
+ continue;
109
+ }
110
+ if (ch === "'" || ch === '"') {
111
+ quote = ch;
112
+ i++;
113
+ continue;
114
+ }
115
+ if (ch === "(") {
116
+ parenDepth++;
117
+ i++;
118
+ continue;
119
+ }
120
+ if (ch === ")" && parenDepth > 0) {
121
+ parenDepth--;
122
+ i++;
123
+ continue;
124
+ }
125
+ if (ch === "/" && next === "*") {
126
+ chars[i] = " ";
127
+ chars[i + 1] = " ";
128
+ i += 2;
129
+ while (i < len) {
130
+ if (chars[i] === "*" && i + 1 < len && chars[i + 1] === "/") {
131
+ chars[i] = " ";
132
+ chars[i + 1] = " ";
133
+ i += 2;
134
+ break;
135
+ }
136
+ if (chars[i] !== "\n" && chars[i] !== "\r") {
137
+ chars[i] = " ";
138
+ }
139
+ i++;
140
+ }
141
+ continue;
142
+ }
143
+ if (allowLineComments && parenDepth === 0 && ch === "/" && next === "/") {
144
+ const prev = i > 0 ? chars[i - 1] : "";
145
+ if (prev !== ":") {
146
+ while (i < len && chars[i] !== "\n") {
147
+ if (chars[i] !== "\r")
148
+ chars[i] = " ";
149
+ i++;
150
+ }
151
+ continue;
152
+ }
153
+ }
154
+ i++;
155
+ }
156
+ return chars.join("");
157
+ }
158
+ /**
159
+ * Extracts `$var` (SCSS) or `@var` (Less) token references from a CSS declaration value.
160
+ */
161
+ export function extractPreprocessorVarReferences(value, syntax) {
162
+ if (syntax === "css")
163
+ return [];
164
+ const scrubbed = value.replace(/(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')/g, " ");
165
+ const refs = [];
166
+ if (syntax === "scss") {
167
+ for (const m of scrubbed.matchAll(/(\$[a-zA-Z_][a-zA-Z0-9_-]*)/g)) {
168
+ const name = m[1];
169
+ if (!refs.includes(name))
170
+ refs.push(name);
171
+ }
172
+ }
173
+ else if (syntax === "less") {
174
+ for (const m of scrubbed.matchAll(/(@[a-zA-Z_][a-zA-Z0-9_-]*)/g)) {
175
+ const name = m[1];
176
+ const bare = name.slice(1).toLowerCase();
177
+ if (LESS_AT_RULE_KEYWORDS.has(bare))
178
+ continue;
179
+ if (!refs.includes(name))
180
+ refs.push(name);
181
+ }
182
+ }
183
+ return refs;
184
+ }
185
+ /**
186
+ * Extracts `<style>` blocks from `.vue`, `.svelte`, and `.astro` files, padding leading lines
187
+ * with `\n` so 1-based line numbers reported by `parseCssStylesheet` match the original file.
188
+ */
189
+ export function extractEmbeddedStyleBlocks(filePath, rawText) {
190
+ const lower = filePath.toLowerCase();
191
+ if (!lower.endsWith(".vue") &&
192
+ !lower.endsWith(".svelte") &&
193
+ !lower.endsWith(".astro")) {
194
+ return [];
195
+ }
196
+ // Blank out `<script>...</script>` and `<!-- ... -->` first so `<style>` strings inside JS/comments are ignored
197
+ let masked = rawText.replace(/<!--[\s\S]*?-->/g, (m) => m.replace(/[^\n]/g, " "));
198
+ masked = masked.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, (m) => m.replace(/[^\n]/g, " "));
199
+ if (lower.endsWith(".astro")) {
200
+ masked = masked.replace(/^\s*---[\s\S]*?---/, (m) => m.replace(/[^\n]/g, " "));
201
+ }
202
+ const blocks = [];
203
+ const styleRe = /<style\b([^>]*)>([\s\S]*?)<\/style>/gi;
204
+ let match;
205
+ while ((match = styleRe.exec(masked)) !== null) {
206
+ const attrs = match[1] ?? "";
207
+ const openTagLen = match[0].indexOf(">") + 1;
208
+ const bodyStart = match.index + openTagLen;
209
+ const bodyEnd = bodyStart + (match[2]?.length ?? 0);
210
+ const rawBody = rawText.slice(bodyStart, bodyEnd);
211
+ let lineBreaksBefore = 0;
212
+ let lastNewlineIdx = -1;
213
+ for (let k = 0; k < bodyStart; k++) {
214
+ if (rawText.charCodeAt(k) === 10) {
215
+ lineBreaksBefore++;
216
+ lastNewlineIdx = k;
217
+ }
218
+ }
219
+ const colOffset = Math.max(0, bodyStart - (lastNewlineIdx + 1));
220
+ const paddedCssText = `${"\n".repeat(lineBreaksBefore)}${" ".repeat(colOffset)}${rawBody}`;
221
+ const langMatch = attrs.match(/\blang\s*=\s*["']?([a-zA-Z0-9_-]+)["']?/i);
222
+ const lang = (langMatch?.[1] ?? "css").toLowerCase();
223
+ const syntax = lang === "scss" || lang === "sass" ? "scss" : lang === "less" ? "less" : "css";
224
+ let defaultScoped = false;
225
+ if (lower.endsWith(".vue")) {
226
+ defaultScoped = /\bscoped\b/i.test(attrs);
227
+ }
228
+ else if (lower.endsWith(".svelte")) {
229
+ defaultScoped = !/\bglobal\b/i.test(attrs);
230
+ }
231
+ else if (lower.endsWith(".astro")) {
232
+ defaultScoped = !/\bis:global\b/i.test(attrs);
233
+ }
234
+ blocks.push({
235
+ filePath,
236
+ paddedCssText,
237
+ syntax,
238
+ defaultScoped,
239
+ });
240
+ }
241
+ return blocks;
242
+ }
243
+ function toPascalIdentifier(raw) {
244
+ const cleaned = raw
245
+ .replace(/^\+/, "")
246
+ .replace(/^\[+|\]+$/g, "")
247
+ .replace(/\.[^.]+$/, "");
248
+ const parts = cleaned.split(/[^a-zA-Z0-9]+/).filter(Boolean);
249
+ if (parts.length === 0)
250
+ return "UiComponent";
251
+ const joined = parts
252
+ .map((p) => p.charAt(0).toUpperCase() + p.slice(1))
253
+ .join("");
254
+ return /^[A-Za-z_$]/.test(joined) ? joined : `Comp${joined}`;
255
+ }
256
+ export function deriveComponentNameFromPath(filePath) {
257
+ const posix = filePath.replace(/\\/g, "/");
258
+ const base = basename(posix).replace(/\.[^.]+$/, "");
259
+ const parent = basename(dirname(posix));
260
+ if ((base === "+page" || base === "+layout" || base === "index" || base === "page" || base === "layout") &&
261
+ parent &&
262
+ parent !== "." &&
263
+ parent !== "src" &&
264
+ parent !== "pages" &&
265
+ parent !== "routes") {
266
+ return toPascalIdentifier(`${parent}-${base.replace(/^\+/, "")}`);
267
+ }
268
+ return toPascalIdentifier(base);
269
+ }
270
+ function kebabToPascal(tag) {
271
+ return tag
272
+ .split("-")
273
+ .filter(Boolean)
274
+ .map((p) => p.charAt(0).toUpperCase() + p.slice(1))
275
+ .join("");
276
+ }
277
+ function cssPropertyToCamelCase(prop) {
278
+ const trimmed = prop.trim();
279
+ if (trimmed.startsWith("--"))
280
+ return JSON.stringify(trimmed);
281
+ const camel = trimmed.replace(/-([a-zA-Z])/g, (_, ch) => ch.toUpperCase());
282
+ return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(camel) ? camel : JSON.stringify(trimmed);
283
+ }
284
+ function convertInlineStyleAttrToJsx(cssStyleText) {
285
+ const entries = [];
286
+ for (const part of cssStyleText.split(";")) {
287
+ const idx = part.indexOf(":");
288
+ if (idx <= 0)
289
+ continue;
290
+ const rawProp = part.slice(0, idx).trim();
291
+ const rawVal = part.slice(idx + 1).trim();
292
+ if (!rawProp || !rawVal)
293
+ continue;
294
+ entries.push(`${cssPropertyToCamelCase(rawProp)}: ${JSON.stringify(rawVal)}`);
295
+ }
296
+ return entries.length > 0 ? `style={{ ${entries.join(", ")} }}` : "";
297
+ }
298
+ function extractStaticStringsFromExpr(expr) {
299
+ const out = [];
300
+ for (const m of expr.matchAll(/(?:"([^"\\]*)"|'([^'\\]*)')/g)) {
301
+ const val = (m[1] ?? m[2] ?? "").trim();
302
+ if (val)
303
+ out.push(val);
304
+ }
305
+ return out;
306
+ }
307
+ /**
308
+ * Converts raw HTML / Vue / Svelte / Astro tag attributes (potentially spanning multiple lines)
309
+ * into valid JSX attributes mapped to their relative line offsets inside the opening tag.
310
+ */
311
+ function convertTagAttributesByLine(attrsRaw) {
312
+ const rawLines = attrsRaw.split("\n");
313
+ const lineStarts = [0];
314
+ for (let i = 0; i < attrsRaw.length; i++) {
315
+ if (attrsRaw.charCodeAt(i) === 10)
316
+ lineStarts.push(i + 1);
317
+ }
318
+ const lineOf = (offset) => {
319
+ let lo = 0;
320
+ let hi = lineStarts.length - 1;
321
+ while (lo <= hi) {
322
+ const mid = (lo + hi) >> 1;
323
+ if (lineStarts[mid] <= offset)
324
+ lo = mid + 1;
325
+ else
326
+ hi = mid - 1;
327
+ }
328
+ return Math.max(0, hi);
329
+ };
330
+ const parsed = [];
331
+ const staticClasses = [];
332
+ let hasDynamicClass = false;
333
+ let firstClassLine = 0;
334
+ const seenPropNames = new Set();
335
+ const len = attrsRaw.length;
336
+ let i = 0;
337
+ while (i < len) {
338
+ while (i < len && /\s/.test(attrsRaw[i]))
339
+ i++;
340
+ if (i >= len)
341
+ break;
342
+ // Skip JSX/Svelte spread `{...props}`
343
+ if (attrsRaw[i] === "{") {
344
+ let depth = 1;
345
+ i++;
346
+ while (i < len && depth > 0) {
347
+ if (attrsRaw[i] === "{")
348
+ depth++;
349
+ else if (attrsRaw[i] === "}")
350
+ depth--;
351
+ i++;
352
+ }
353
+ continue;
354
+ }
355
+ const attrStart = i;
356
+ while (i < len && !/[\s=/>"'{}]/.test(attrsRaw[i]))
357
+ i++;
358
+ const rawName = attrsRaw.slice(attrStart, i);
359
+ if (!rawName) {
360
+ i++;
361
+ continue;
362
+ }
363
+ const attrLine = lineOf(attrStart);
364
+ while (i < len && /[ \t\r]/.test(attrsRaw[i]))
365
+ i++;
366
+ let valKind = "none";
367
+ let rawVal = "";
368
+ if (i < len && attrsRaw[i] === "=") {
369
+ i++;
370
+ while (i < len && /\s/.test(attrsRaw[i]))
371
+ i++;
372
+ if (i < len && (attrsRaw[i] === '"' || attrsRaw[i] === "'")) {
373
+ const q = attrsRaw[i];
374
+ const vStart = i + 1;
375
+ i++;
376
+ while (i < len && attrsRaw[i] !== q) {
377
+ if (attrsRaw[i] === "\\" && i + 1 < len)
378
+ i += 2;
379
+ else
380
+ i++;
381
+ }
382
+ rawVal = attrsRaw.slice(vStart, i);
383
+ if (i < len && attrsRaw[i] === q)
384
+ i++;
385
+ valKind = "string";
386
+ }
387
+ else if (i < len && attrsRaw[i] === "{") {
388
+ const vStart = i + 1;
389
+ let depth = 1;
390
+ i++;
391
+ while (i < len && depth > 0) {
392
+ if (attrsRaw[i] === "{")
393
+ depth++;
394
+ else if (attrsRaw[i] === "}")
395
+ depth--;
396
+ i++;
397
+ }
398
+ rawVal = attrsRaw.slice(vStart, Math.max(vStart, i - 1));
399
+ valKind = "expr";
400
+ }
401
+ else {
402
+ const vStart = i;
403
+ while (i < len && !/[\s/>]/.test(attrsRaw[i]))
404
+ i++;
405
+ rawVal = attrsRaw.slice(vStart, i);
406
+ valKind = "string";
407
+ }
408
+ }
409
+ // Skip Vue/Svelte directives & event handlers (`v-*`, `@click`, `on:click`, `bind:*`, `use:*`, `#slot`)
410
+ if (rawName.startsWith("@") ||
411
+ rawName.startsWith("#") ||
412
+ rawName.startsWith("v-if") ||
413
+ rawName.startsWith("v-else") ||
414
+ rawName.startsWith("v-for") ||
415
+ rawName.startsWith("v-show") ||
416
+ rawName.startsWith("v-model") ||
417
+ rawName.startsWith("v-html") ||
418
+ rawName.startsWith("v-text") ||
419
+ rawName.startsWith("v-slot") ||
420
+ rawName.startsWith("v-on:") ||
421
+ rawName.startsWith("on:") ||
422
+ rawName.startsWith("bind:") ||
423
+ rawName.startsWith("use:") ||
424
+ rawName.startsWith("transition:") ||
425
+ rawName.startsWith("in:") ||
426
+ rawName.startsWith("out:") ||
427
+ rawName.startsWith("animate:")) {
428
+ continue;
429
+ }
430
+ // Svelte `class:active={cond}` directive (excluding Astro's `class:list={...}`)
431
+ if (rawName.startsWith("class:") && rawName !== "class:list") {
432
+ const cls = rawName.slice("class:".length).trim();
433
+ if (cls) {
434
+ if (staticClasses.length === 0 && !hasDynamicClass)
435
+ firstClassLine = attrLine;
436
+ staticClasses.push({ line: attrLine, value: cls });
437
+ hasDynamicClass = true;
438
+ }
439
+ continue;
440
+ }
441
+ const isBound = rawName.startsWith(":") || rawName.startsWith("v-bind:");
442
+ const cleanName = rawName
443
+ .replace(/^(?::|v-bind:)/, "")
444
+ .replace(/\.[a-zA-Z0-9_-]+$/, "");
445
+ if (cleanName === "class" || cleanName === "className" || cleanName === "class:list") {
446
+ if (staticClasses.length === 0 && !hasDynamicClass)
447
+ firstClassLine = attrLine;
448
+ if (!isBound && valKind === "string") {
449
+ if (rawVal.trim()) {
450
+ staticClasses.push({ line: attrLine, value: rawVal.replace(/\s+/g, " ").trim() });
451
+ }
452
+ }
453
+ else {
454
+ hasDynamicClass = true;
455
+ for (const s of extractStaticStringsFromExpr(rawVal)) {
456
+ staticClasses.push({ line: attrLine, value: s });
457
+ }
458
+ }
459
+ continue;
460
+ }
461
+ if (cleanName === "style") {
462
+ if (!isBound && valKind === "string") {
463
+ const styleJsx = convertInlineStyleAttrToJsx(rawVal);
464
+ if (styleJsx && !seenPropNames.has("style")) {
465
+ seenPropNames.add("style");
466
+ parsed.push({ lineOffset: attrLine, jsxAttr: styleJsx });
467
+ }
468
+ }
469
+ else if (valKind === "expr" && /^\s*\{[\s\S]*\}\s*$/.test(`{${rawVal}}`)) {
470
+ // Keep object-literal inline styles (`style={{ margin: "12px" }}`) when single-line valid
471
+ const trimmedExpr = rawVal.trim();
472
+ if (trimmedExpr.startsWith("{") && trimmedExpr.endsWith("}") && !trimmedExpr.includes("\n")) {
473
+ if (!seenPropNames.has("style")) {
474
+ seenPropNames.add("style");
475
+ parsed.push({ lineOffset: attrLine, jsxAttr: `style={${trimmedExpr}}` });
476
+ }
477
+ }
478
+ }
479
+ continue;
480
+ }
481
+ if (!/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(cleanName))
482
+ continue;
483
+ if (seenPropNames.has(cleanName))
484
+ continue;
485
+ seenPropNames.add(cleanName);
486
+ if (!isBound && valKind === "string") {
487
+ parsed.push({
488
+ lineOffset: attrLine,
489
+ jsxAttr: `${cleanName}=${JSON.stringify(rawVal.replace(/\r?\n/g, " "))}`,
490
+ });
491
+ }
492
+ else if (!isBound && valKind === "none") {
493
+ parsed.push({ lineOffset: attrLine, jsxAttr: cleanName });
494
+ }
495
+ else {
496
+ parsed.push({ lineOffset: attrLine, jsxAttr: `${cleanName}={undefined as any}` });
497
+ }
498
+ }
499
+ if (staticClasses.length > 0 || hasDynamicClass) {
500
+ const joinedClasses = staticClasses.map((c) => c.value).join(" ").trim();
501
+ const targetLine = staticClasses[0]?.line ?? firstClassLine;
502
+ const classJsx = hasDynamicClass
503
+ ? `className={\`${joinedClasses.replace(/[`$\\]/g, "")}\${""}\`}`
504
+ : `className=${JSON.stringify(joinedClasses)}`;
505
+ parsed.unshift({ lineOffset: targetLine, jsxAttr: classJsx });
506
+ }
507
+ const byLine = new Map();
508
+ for (const item of parsed) {
509
+ let arr = byLine.get(item.lineOffset);
510
+ if (!arr) {
511
+ arr = [];
512
+ byLine.set(item.lineOffset, arr);
513
+ }
514
+ arr.push(item.jsxAttr);
515
+ }
516
+ return { byLine, lineCount: rawLines.length };
517
+ }
518
+ /**
519
+ * Converts a slice of HTML/Vue/Svelte/Astro template lines (`lines[startLine..endLine]`)
520
+ * into balanced, line-preserving JSX inside `outLines[startLine..endLine]`.
521
+ */
522
+ function emitTemplateRegionAsJsx(lines, startLine, endLine, outLines, importedNames, options = {}) {
523
+ if (startLine < 0 || endLine < startLine || startLine >= lines.length)
524
+ return;
525
+ const regionLines = lines.slice(startLine, endLine + 1).map((l, idx) => {
526
+ if (options.stripOuterTemplateTag) {
527
+ if (idx === 0)
528
+ l = l.replace(/<template\b[^>]*>/i, (m) => " ".repeat(m.length));
529
+ if (idx === endLine - startLine) {
530
+ l = l.replace(/<\/template>/i, (m) => " ".repeat(m.length));
531
+ }
532
+ }
533
+ return l;
534
+ });
535
+ // Mask fenced code blocks in MDX so markdown examples are never treated as JSX
536
+ if (options.mdxMode) {
537
+ let inFence = false;
538
+ for (let i = 0; i < regionLines.length; i++) {
539
+ if (/^\s*```/.test(regionLines[i])) {
540
+ regionLines[i] = "";
541
+ inFence = !inFence;
542
+ continue;
543
+ }
544
+ if (inFence) {
545
+ regionLines[i] = "";
546
+ }
547
+ else if (/^\s*(?:import|export)\b/.test(regionLines[i])) {
548
+ // Handled at module top-level
549
+ regionLines[i] = "";
550
+ }
551
+ }
552
+ }
553
+ const regionText = regionLines.join("\n");
554
+ const lineStarts = [0];
555
+ for (let i = 0; i < regionText.length; i++) {
556
+ if (regionText.charCodeAt(i) === 10)
557
+ lineStarts.push(i + 1);
558
+ }
559
+ const lineOf = (offset) => {
560
+ let lo = 0;
561
+ let hi = lineStarts.length - 1;
562
+ while (lo <= hi) {
563
+ const mid = (lo + hi) >> 1;
564
+ if (lineStarts[mid] <= offset)
565
+ lo = mid + 1;
566
+ else
567
+ hi = mid - 1;
568
+ }
569
+ return Math.max(0, hi);
570
+ };
571
+ const perLineSegments = Array.from({ length: regionLines.length }, () => []);
572
+ const pushSeg = (relLine, text) => {
573
+ const bounded = Math.max(0, Math.min(regionLines.length - 1, relLine));
574
+ perLineSegments[bounded].push(text);
575
+ };
576
+ const openStack = [];
577
+ const len = regionText.length;
578
+ let i = 0;
579
+ while (i < len) {
580
+ const lt = regionText.indexOf("<", i);
581
+ if (lt === -1)
582
+ break;
583
+ // HTML comment `<!-- ... -->`
584
+ if (regionText.startsWith("<!--", lt)) {
585
+ const closeComment = regionText.indexOf("-->", lt + 4);
586
+ i = closeComment === -1 ? len : closeComment + 3;
587
+ continue;
588
+ }
589
+ const afterLt = regionText[lt + 1] ?? "";
590
+ // Closing tag `</tag>`
591
+ if (afterLt === "/") {
592
+ const gt = regionText.indexOf(">", lt + 2);
593
+ if (gt === -1)
594
+ break;
595
+ const rawClose = regionText.slice(lt + 2, gt).trim();
596
+ i = gt + 1;
597
+ if (!/^[A-Za-z][A-Za-z0-9_.:-]*$/.test(rawClose))
598
+ continue;
599
+ let resolvedClose = rawClose;
600
+ if (rawClose === "slot" || rawClose === "template" || rawClose.startsWith("svelte:")) {
601
+ resolvedClose = "div";
602
+ }
603
+ else if (!/^[A-Z]/.test(rawClose) && rawClose.includes("-")) {
604
+ const pascal = kebabToPascal(rawClose);
605
+ resolvedClose = importedNames.has(pascal) ? pascal : "div";
606
+ }
607
+ if (HTML_VOID_TAGS.has(resolvedClose.toLowerCase()))
608
+ continue;
609
+ // Pop matching tag from stack (closing any unclosed inner HTML tags cleanly)
610
+ let matchIdx = -1;
611
+ for (let s = openStack.length - 1; s >= 0; s--) {
612
+ if (openStack[s].jsxTag === resolvedClose) {
613
+ matchIdx = s;
614
+ break;
615
+ }
616
+ }
617
+ const closeLine = lineOf(gt);
618
+ if (matchIdx !== -1) {
619
+ while (openStack.length > matchIdx) {
620
+ const popped = openStack.pop();
621
+ pushSeg(closeLine, `</${popped.jsxTag}>`);
622
+ }
623
+ }
624
+ continue;
625
+ }
626
+ // Must start a valid tag name `<Tag` or `<div`
627
+ if (!/[A-Za-z]/.test(afterLt)) {
628
+ i = lt + 1;
629
+ continue;
630
+ }
631
+ // Scan tag name
632
+ let p = lt + 1;
633
+ while (p < len && /[A-Za-z0-9_.:-]/.test(regionText[p]))
634
+ p++;
635
+ const rawTagName = regionText.slice(lt + 1, p);
636
+ const nextCh = regionText[p] ?? "";
637
+ if (nextCh && !/[\s/>]/.test(nextCh)) {
638
+ i = lt + 1;
639
+ continue;
640
+ }
641
+ // Scan until matching `>` outside quotes and `{...}` braces
642
+ let quote = null;
643
+ let braceDepth = 0;
644
+ let q = p;
645
+ while (q < len) {
646
+ const c = regionText[q];
647
+ if (quote) {
648
+ if (c === "\\" && q + 1 < len) {
649
+ q += 2;
650
+ continue;
651
+ }
652
+ if (c === quote)
653
+ quote = null;
654
+ q++;
655
+ continue;
656
+ }
657
+ if (c === "'" || c === '"') {
658
+ quote = c;
659
+ q++;
660
+ continue;
661
+ }
662
+ if (c === "{") {
663
+ braceDepth++;
664
+ q++;
665
+ continue;
666
+ }
667
+ if (c === "}" && braceDepth > 0) {
668
+ braceDepth--;
669
+ q++;
670
+ continue;
671
+ }
672
+ if (c === ">" && braceDepth === 0) {
673
+ break;
674
+ }
675
+ q++;
676
+ }
677
+ if (q >= len)
678
+ break;
679
+ let attrsSlice = regionText.slice(p, q);
680
+ let selfClosing = false;
681
+ if (/\s*\/\s*$/.test(attrsSlice)) {
682
+ selfClosing = true;
683
+ attrsSlice = attrsSlice.replace(/\/\s*$/, "");
684
+ }
685
+ const openStartLine = lineOf(lt);
686
+ const openEndLine = lineOf(q);
687
+ i = q + 1;
688
+ // Resolve JSX tag identifier
689
+ let jsxTag = rawTagName;
690
+ if (rawTagName === "slot" || rawTagName === "template" || rawTagName.startsWith("svelte:")) {
691
+ jsxTag = "div";
692
+ }
693
+ else if (rawTagName === "component") {
694
+ const isMatch = attrsSlice.match(/(?::is|v-bind:is)\s*=\s*(?:"([^"]*)"|'([^']*)')/);
695
+ const exprIdent = isMatch ? (isMatch[1] ?? isMatch[2] ?? "").trim() : "";
696
+ jsxTag = /^[A-Z][A-Za-z0-9_]*$/.test(exprIdent) ? exprIdent : "div";
697
+ }
698
+ else if (!/^[A-Z]/.test(rawTagName)) {
699
+ if (rawTagName.includes("-")) {
700
+ const pascal = kebabToPascal(rawTagName);
701
+ jsxTag = importedNames.has(pascal) ? pascal : "div";
702
+ }
703
+ else if (rawTagName.includes(":")) {
704
+ jsxTag = "div";
705
+ }
706
+ else {
707
+ jsxTag = rawTagName.toLowerCase();
708
+ }
709
+ }
710
+ if (HTML_VOID_TAGS.has(jsxTag.toLowerCase())) {
711
+ selfClosing = true;
712
+ }
713
+ const { byLine, lineCount } = convertTagAttributesByLine(attrsSlice);
714
+ const closeToken = selfClosing ? " />" : ">";
715
+ if (lineCount <= 1 || openStartLine === openEndLine) {
716
+ const inlineAttrs = byLine.get(0) ?? [];
717
+ const attrStr = inlineAttrs.length > 0 ? ` ${inlineAttrs.join(" ")}` : "";
718
+ pushSeg(openStartLine, `<${jsxTag}${attrStr}${closeToken}`);
719
+ }
720
+ else {
721
+ const firstAttrs = byLine.get(0) ?? [];
722
+ pushSeg(openStartLine, `<${jsxTag}${firstAttrs.length > 0 ? ` ${firstAttrs.join(" ")}` : ""}`);
723
+ for (let off = 1; off < lineCount - 1; off++) {
724
+ const midAttrs = byLine.get(off) ?? [];
725
+ if (midAttrs.length > 0) {
726
+ pushSeg(openStartLine + off, midAttrs.join(" "));
727
+ }
728
+ }
729
+ const lastOff = lineCount - 1;
730
+ const lastAttrs = byLine.get(lastOff) ?? [];
731
+ pushSeg(openEndLine, `${lastAttrs.length > 0 ? `${lastAttrs.join(" ")}` : ""}${closeToken}`);
732
+ }
733
+ if (!selfClosing) {
734
+ openStack.push({ jsxTag, relLine: openEndLine });
735
+ }
736
+ }
737
+ // Close any unclosed tags at the end of the template region so TSX is 100% balanced
738
+ const finalRelLine = Math.max(0, regionLines.length - 1);
739
+ while (openStack.length > 0) {
740
+ const unclosed = openStack.pop();
741
+ pushSeg(finalRelLine, `</${unclosed.jsxTag}>`);
742
+ }
743
+ for (let r = 0; r < regionLines.length; r++) {
744
+ const segs = perLineSegments[r];
745
+ if (segs.length > 0) {
746
+ outLines[startLine + r] = segs.join(" ");
747
+ }
748
+ }
749
+ }
750
+ function collectImportedIdentifiers(scriptLines) {
751
+ const names = new Set();
752
+ const joined = scriptLines.join("\n");
753
+ for (const m of joined.matchAll(/import\s+([\s\S]*?)\s+from\s+["'][^"']+["']/g)) {
754
+ const clause = m[1] ?? "";
755
+ for (const id of clause.matchAll(/\b([A-Za-z_$][A-Za-z0-9_$]*)\b/g)) {
756
+ const tok = id[1];
757
+ if (tok !== "type" && tok !== "as")
758
+ names.add(tok);
759
+ }
760
+ }
761
+ return names;
762
+ }
763
+ /**
764
+ * Preprocesses `.vue`, `.svelte`, `.astro`, and `.mdx` source text into valid,
765
+ * line-preserving TSX source text for `scanTsxOrTsFile`.
766
+ */
767
+ export function preprocessUiComponentToTsx(filePath, rawText) {
768
+ const lower = filePath.toLowerCase();
769
+ if (!isPreprocessedUiComponentFile(filePath))
770
+ return rawText;
771
+ const lines = rawText.split(/\r?\n/);
772
+ const totalLines = Math.max(1, lines.length);
773
+ const out = new Array(totalLines).fill("");
774
+ const compName = deriveComponentNameFromPath(filePath);
775
+ // -------------------------------------------------------------------------
776
+ // 1. Vue Single-File Component (`.vue`)
777
+ // -------------------------------------------------------------------------
778
+ if (lower.endsWith(".vue")) {
779
+ let inScript = false;
780
+ let hasExportDefault = false;
781
+ const scriptLines = [];
782
+ for (let i = 0; i < lines.length; i++) {
783
+ const line = lines[i];
784
+ if (!inScript) {
785
+ const openMatch = line.match(/<script\b([^>]*)>/i);
786
+ if (openMatch) {
787
+ const afterOpen = line.slice((openMatch.index ?? 0) + openMatch[0].length);
788
+ const closeMatch = afterOpen.match(/<\/script>/i);
789
+ if (closeMatch) {
790
+ const inner = afterOpen.slice(0, closeMatch.index ?? 0);
791
+ out[i] = inner;
792
+ scriptLines.push(inner);
793
+ if (/\bexport\s+default\b/.test(inner))
794
+ hasExportDefault = true;
795
+ }
796
+ else {
797
+ inScript = true;
798
+ out[i] = afterOpen.trim() ? afterOpen : "";
799
+ scriptLines.push(afterOpen);
800
+ if (/\bexport\s+default\b/.test(afterOpen))
801
+ hasExportDefault = true;
802
+ }
803
+ }
804
+ }
805
+ else {
806
+ const closeMatch = line.match(/<\/script>/i);
807
+ if (closeMatch) {
808
+ const beforeClose = line.slice(0, closeMatch.index ?? 0);
809
+ out[i] = beforeClose.trim() ? beforeClose : "";
810
+ scriptLines.push(beforeClose);
811
+ if (/\bexport\s+default\b/.test(beforeClose))
812
+ hasExportDefault = true;
813
+ inScript = false;
814
+ }
815
+ else {
816
+ out[i] = line;
817
+ scriptLines.push(line);
818
+ if (/\bexport\s+default\b/.test(line))
819
+ hasExportDefault = true;
820
+ }
821
+ }
822
+ }
823
+ // Extract single-line or multi-line `defineProps<PropsType>()` type parameter if present
824
+ const fullScript = scriptLines.join("\n");
825
+ const definePropsMatch = fullScript.match(/\bdefineProps\s*<([\s\S]*?)>\s*\(/);
826
+ const propsTypeRef = definePropsMatch && !definePropsMatch[1].includes("\n")
827
+ ? definePropsMatch[1].trim()
828
+ : undefined;
829
+ const importedNames = collectImportedIdentifiers(scriptLines);
830
+ let tplStart = -1;
831
+ let tplEnd = -1;
832
+ let tplDepth = 0;
833
+ for (let i = 0; i < lines.length; i++) {
834
+ if (out[i] !== "")
835
+ continue;
836
+ const line = lines[i];
837
+ const opens = (line.match(/<template\b[^>]*>/gi) ?? []).length;
838
+ const closes = (line.match(/<\/template>/gi) ?? []).length;
839
+ if (opens > 0 && tplDepth === 0 && tplStart === -1)
840
+ tplStart = i;
841
+ tplDepth += opens - closes;
842
+ if (tplStart !== -1 && tplDepth <= 0 && closes > 0) {
843
+ tplEnd = i;
844
+ break;
845
+ }
846
+ }
847
+ const paramSig = propsTypeRef ? `_props: ${propsTypeRef}` : "";
848
+ const fnOpen = `${hasExportDefault ? "" : "export "}function ${compName}(${paramSig}) { return (<>`;
849
+ if (tplStart !== -1 && tplEnd !== -1 && tplEnd >= tplStart) {
850
+ emitTemplateRegionAsJsx(lines, tplStart, tplEnd, out, importedNames, {
851
+ stripOuterTemplateTag: true,
852
+ });
853
+ out[tplStart] = `${fnOpen}${out[tplStart] ? ` ${out[tplStart]}` : ""}`;
854
+ out[tplEnd] = `${out[tplEnd] ? `${out[tplEnd]} ` : ""}</>); }`;
855
+ }
856
+ else {
857
+ const last = totalLines - 1;
858
+ out[last] = `${out[last] ? `${out[last]}; ` : ""}${fnOpen}</>); }`;
859
+ }
860
+ return out.join("\n");
861
+ }
862
+ // -------------------------------------------------------------------------
863
+ // 2. Svelte Component (`.svelte`)
864
+ // -------------------------------------------------------------------------
865
+ if (lower.endsWith(".svelte")) {
866
+ let inScript = false;
867
+ let inStyle = false;
868
+ const isMarkupLine = new Array(totalLines).fill(true);
869
+ const scriptLines = [];
870
+ const svelteExportProps = [];
871
+ for (let i = 0; i < lines.length; i++) {
872
+ const line = lines[i];
873
+ if (inStyle) {
874
+ isMarkupLine[i] = false;
875
+ if (/<\/style>/i.test(line))
876
+ inStyle = false;
877
+ continue;
878
+ }
879
+ if (!inScript && /<style\b[^>]*>/i.test(line)) {
880
+ isMarkupLine[i] = false;
881
+ if (!/<\/style>/i.test(line))
882
+ inStyle = true;
883
+ continue;
884
+ }
885
+ if (!inScript) {
886
+ const openMatch = line.match(/<script\b([^>]*)>/i);
887
+ if (openMatch) {
888
+ isMarkupLine[i] = false;
889
+ const afterOpen = line.slice((openMatch.index ?? 0) + openMatch[0].length);
890
+ const closeMatch = afterOpen.match(/<\/script>/i);
891
+ if (closeMatch) {
892
+ const inner = afterOpen.slice(0, closeMatch.index ?? 0);
893
+ out[i] = inner;
894
+ scriptLines.push(inner);
895
+ }
896
+ else {
897
+ inScript = true;
898
+ out[i] = afterOpen.trim() ? afterOpen : "";
899
+ scriptLines.push(afterOpen);
900
+ }
901
+ continue;
902
+ }
903
+ }
904
+ else {
905
+ isMarkupLine[i] = false;
906
+ const closeMatch = line.match(/<\/script>/i);
907
+ if (closeMatch) {
908
+ const beforeClose = line.slice(0, closeMatch.index ?? 0);
909
+ out[i] = beforeClose.trim() ? beforeClose : "";
910
+ scriptLines.push(beforeClose);
911
+ inScript = false;
912
+ }
913
+ else {
914
+ // Capture Svelte 4 `export let propName: PropType = default;`
915
+ const expLet = line.match(/^\s*export\s+let\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*(?::\s*([^=;]+?))?\s*(?:=\s*([^;]+))?;?\s*$/);
916
+ if (expLet) {
917
+ svelteExportProps.push({
918
+ name: expLet[1],
919
+ type: (expLet[2] ?? "unknown").trim(),
920
+ optional: expLet[3] !== undefined,
921
+ });
922
+ out[i] = line.replace(/^\s*export\s+let\b/, "let");
923
+ }
924
+ else if (/^\s*\$:\s*/.test(line)) {
925
+ // Strip Svelte reactive label `$:` so TS parses cleanly
926
+ out[i] = line.replace(/^\s*\$:\s*/, "");
927
+ }
928
+ else {
929
+ out[i] = line;
930
+ }
931
+ scriptLines.push(line);
932
+ }
933
+ }
934
+ }
935
+ const fullScript = scriptLines.join("\n");
936
+ const runesPropsMatch = fullScript.match(/:\s*([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*\$props\s*\(/);
937
+ let propsSig = "";
938
+ if (runesPropsMatch) {
939
+ propsSig = `_props: ${runesPropsMatch[1]}`;
940
+ }
941
+ else if (svelteExportProps.length > 0) {
942
+ const inlineMembers = svelteExportProps
943
+ .map((p) => `${p.name}${p.optional ? "?" : ""}: ${p.type}`)
944
+ .join("; ");
945
+ propsSig = `_props: { ${inlineMembers} }`;
946
+ }
947
+ const importedNames = collectImportedIdentifiers(scriptLines);
948
+ // Collect markup lines into a masked array keeping non-markup lines blank
949
+ const maskedLines = lines.map((l, idx) => (isMarkupLine[idx] ? l : ""));
950
+ let firstMarkup = isMarkupLine.indexOf(true);
951
+ let lastMarkup = isMarkupLine.lastIndexOf(true);
952
+ if (firstMarkup === -1) {
953
+ firstMarkup = totalLines - 1;
954
+ lastMarkup = totalLines - 1;
955
+ }
956
+ const jsxOut = new Array(totalLines).fill("");
957
+ emitTemplateRegionAsJsx(maskedLines, firstMarkup, lastMarkup, jsxOut, importedNames);
958
+ for (let i = firstMarkup; i <= lastMarkup; i++) {
959
+ if (isMarkupLine[i] && jsxOut[i]) {
960
+ out[i] = jsxOut[i];
961
+ }
962
+ }
963
+ const fnOpen = `export function ${compName}(${propsSig}) { return (<>`;
964
+ out[firstMarkup] = `${out[firstMarkup] && !isMarkupLine[firstMarkup] ? `${out[firstMarkup]}; ` : ""}${fnOpen}${isMarkupLine[firstMarkup] && out[firstMarkup] ? ` ${out[firstMarkup]}` : ""}`;
965
+ out[lastMarkup] = `${out[lastMarkup] ? `${out[lastMarkup]} ` : ""}</>); }`;
966
+ return out.join("\n");
967
+ }
968
+ // -------------------------------------------------------------------------
969
+ // 3. Astro Component / Page (`.astro`)
970
+ // -------------------------------------------------------------------------
971
+ if (lower.endsWith(".astro")) {
972
+ let firstIdx = -1;
973
+ for (let i = 0; i < lines.length; i++) {
974
+ if (lines[i].trim() !== "") {
975
+ firstIdx = i;
976
+ break;
977
+ }
978
+ }
979
+ let closeIdx = -1;
980
+ if (firstIdx !== -1 && lines[firstIdx].trim() === "---") {
981
+ for (let i = firstIdx + 1; i < lines.length; i++) {
982
+ if (lines[i].trim() === "---") {
983
+ closeIdx = i;
984
+ break;
985
+ }
986
+ }
987
+ }
988
+ const scriptLines = [];
989
+ let hasPropsInterface = false;
990
+ let markupStart = 0;
991
+ if (closeIdx !== -1) {
992
+ for (let i = firstIdx + 1; i < closeIdx; i++) {
993
+ out[i] = lines[i];
994
+ scriptLines.push(lines[i]);
995
+ if (/\b(?:interface|type)\s+Props\b/.test(lines[i])) {
996
+ hasPropsInterface = true;
997
+ }
998
+ }
999
+ markupStart = closeIdx;
1000
+ }
1001
+ // Blank out `<style>` and `<script>` blocks inside the Astro template body
1002
+ const maskedMarkup = [...lines];
1003
+ let inTagBlock = null;
1004
+ for (let i = markupStart; i < maskedMarkup.length; i++) {
1005
+ if (i === closeIdx) {
1006
+ maskedMarkup[i] = "";
1007
+ continue;
1008
+ }
1009
+ const l = maskedMarkup[i];
1010
+ if (inTagBlock) {
1011
+ maskedMarkup[i] = "";
1012
+ if (new RegExp(`</${inTagBlock}>`, "i").test(l))
1013
+ inTagBlock = null;
1014
+ continue;
1015
+ }
1016
+ if (/<style\b[^>]*>/i.test(l)) {
1017
+ maskedMarkup[i] = "";
1018
+ if (!/<\/style>/i.test(l))
1019
+ inTagBlock = "style";
1020
+ continue;
1021
+ }
1022
+ if (/<script\b[^>]*>/i.test(l)) {
1023
+ maskedMarkup[i] = "";
1024
+ if (!/<\/script>/i.test(l))
1025
+ inTagBlock = "script";
1026
+ }
1027
+ }
1028
+ const importedNames = collectImportedIdentifiers(scriptLines);
1029
+ const endLine = totalLines - 1;
1030
+ emitTemplateRegionAsJsx(maskedMarkup, markupStart, endLine, out, importedNames);
1031
+ const propsSig = hasPropsInterface ? "_props: Props" : "";
1032
+ const fnOpen = `export function ${compName}(${propsSig}) { return (<>`;
1033
+ out[markupStart] = `${fnOpen}${out[markupStart] ? ` ${out[markupStart]}` : ""}`;
1034
+ out[endLine] = `${out[endLine] ? `${out[endLine]} ` : ""}</>); }`;
1035
+ return out.join("\n");
1036
+ }
1037
+ // -------------------------------------------------------------------------
1038
+ // 4. MDX Document (`.mdx`)
1039
+ // -------------------------------------------------------------------------
1040
+ let bodyStart = 0;
1041
+ if (lines[0]?.trim() === "---") {
1042
+ for (let i = 1; i < lines.length; i++) {
1043
+ if (lines[i].trim() === "---") {
1044
+ bodyStart = i + 1;
1045
+ break;
1046
+ }
1047
+ }
1048
+ }
1049
+ const scriptLines = [];
1050
+ const moduleStmtLines = new Set();
1051
+ let inFence = false;
1052
+ for (let i = bodyStart; i < lines.length; i++) {
1053
+ const trimmed = lines[i].trim();
1054
+ if (trimmed.startsWith("```")) {
1055
+ inFence = !inFence;
1056
+ continue;
1057
+ }
1058
+ if (inFence)
1059
+ continue;
1060
+ if (/^(?:import|export)\s/.test(trimmed)) {
1061
+ out[i] = lines[i];
1062
+ scriptLines.push(lines[i]);
1063
+ moduleStmtLines.add(i);
1064
+ }
1065
+ }
1066
+ const importedNames = collectImportedIdentifiers(scriptLines);
1067
+ const jsxOut = new Array(totalLines).fill("");
1068
+ emitTemplateRegionAsJsx(lines, bodyStart, totalLines - 1, jsxOut, importedNames, {
1069
+ mdxMode: true,
1070
+ });
1071
+ // Partition [bodyStart..totalLines-1] into contiguous non-module spans so top-level `import`/`export`
1072
+ // statements never end up nested inside JSX fragments.
1073
+ const spans = [];
1074
+ let spanStart = -1;
1075
+ for (let i = bodyStart; i < totalLines; i++) {
1076
+ if (moduleStmtLines.has(i)) {
1077
+ if (spanStart !== -1) {
1078
+ spans.push({ start: spanStart, end: i - 1 });
1079
+ spanStart = -1;
1080
+ }
1081
+ }
1082
+ else if (spanStart === -1) {
1083
+ spanStart = i;
1084
+ }
1085
+ }
1086
+ if (spanStart !== -1) {
1087
+ spans.push({ start: spanStart, end: totalLines - 1 });
1088
+ }
1089
+ for (let i = bodyStart; i < totalLines; i++) {
1090
+ if (!moduleStmtLines.has(i) && jsxOut[i]) {
1091
+ out[i] = jsxOut[i];
1092
+ }
1093
+ }
1094
+ if (spans.length === 0) {
1095
+ const last = totalLines - 1;
1096
+ out[last] = `${out[last] ? `${out[last]}; ` : ""}export function ${compName}() { return (<></>); }`;
1097
+ }
1098
+ else {
1099
+ spans.forEach((sp, idx) => {
1100
+ const fnOpen = idx === 0
1101
+ ? `export function ${compName}() { return (<>`
1102
+ : `function __${compName}Part${idx}__() { return (<>`;
1103
+ out[sp.start] = `${fnOpen}${out[sp.start] ? ` ${out[sp.start]}` : ""}`;
1104
+ out[sp.end] = `${out[sp.end] ? `${out[sp.end]} ` : ""}</>); }`;
1105
+ });
1106
+ }
1107
+ return out.join("\n");
1108
+ }