@monoes/monodesign 1.2.20 → 1.2.23

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 (95) hide show
  1. package/README.md +2 -2
  2. package/cli/engine/cli/main.mjs +21 -1
  3. package/cli/engine/design-system-checks.mjs +381 -0
  4. package/cli/engine/design-system-parse.mjs +433 -0
  5. package/cli/engine/design-system.mjs +20 -736
  6. package/cli/engine/detect-antipatterns-browser.js +28 -5
  7. package/cli/engine/detect-antipatterns.mjs +1 -0
  8. package/cli/engine/engines/regex/detect-text-matchers.mjs +371 -0
  9. package/cli/engine/engines/regex/detect-text-run.mjs +186 -0
  10. package/cli/engine/engines/regex/detect-text.mjs +11 -523
  11. package/cli/engine/engines/static-html/css-cascade-color.mjs +219 -0
  12. package/cli/engine/engines/static-html/css-cascade-static-data.mjs +138 -0
  13. package/cli/engine/engines/static-html/css-cascade-static-dom.mjs +132 -0
  14. package/cli/engine/engines/static-html/css-cascade-static-parse.mjs +393 -0
  15. package/cli/engine/engines/static-html/css-cascade.mjs +24 -837
  16. package/cli/engine/engines/static-html/detect-html.mjs +6 -1
  17. package/cli/engine/findings-group.mjs +94 -0
  18. package/cli/engine/fix/index.mjs +1 -26
  19. package/cli/engine/fix/unified-diff.mjs +107 -0
  20. package/cli/engine/rules/checks-background.mjs +17 -3
  21. package/cli/engine/rules/checks-element.mjs +2 -0
  22. package/cli/engine/rules/checks-pure.mjs +9 -2
  23. package/cli/lib/monodesign-config-consent.mjs +93 -0
  24. package/cli/lib/monodesign-config-core.mjs +37 -0
  25. package/cli/lib/monodesign-config-detection.mjs +133 -0
  26. package/cli/lib/monodesign-config-filter.mjs +198 -0
  27. package/cli/lib/monodesign-config-ignore-value.mjs +212 -0
  28. package/cli/lib/monodesign-config.mjs +21 -623
  29. package/package.json +2 -2
  30. package/skill/scripts/context-fields.mjs +65 -0
  31. package/skill/scripts/context-resolve.mjs +425 -0
  32. package/skill/scripts/context-update.mjs +151 -0
  33. package/skill/scripts/context-utils.mjs +68 -0
  34. package/skill/scripts/context-workspace.mjs +245 -0
  35. package/skill/scripts/context.mjs +17 -891
  36. package/skill/scripts/hook-admin-config.mjs +152 -0
  37. package/skill/scripts/hook-admin-ignore.mjs +131 -0
  38. package/skill/scripts/hook-admin-manifest.mjs +292 -0
  39. package/skill/scripts/hook-admin.mjs +8 -541
  40. package/skill/scripts/hook-lib-cache.mjs +145 -0
  41. package/skill/scripts/hook-lib-config.mjs +292 -0
  42. package/skill/scripts/hook-lib-detector.mjs +72 -0
  43. package/skill/scripts/hook-lib-events.mjs +182 -0
  44. package/skill/scripts/hook-lib-findings.mjs +201 -0
  45. package/skill/scripts/hook-lib-ignore.mjs +205 -0
  46. package/skill/scripts/hook-lib-render.mjs +273 -0
  47. package/skill/scripts/hook-lib-run.mjs +281 -0
  48. package/skill/scripts/hook-lib-scan-targets.mjs +128 -0
  49. package/skill/scripts/hook-lib.mjs +71 -1747
  50. package/skill/scripts/lib/design-parser-colors.mjs +182 -0
  51. package/skill/scripts/lib/design-parser-extract.mjs +333 -0
  52. package/skill/scripts/lib/design-parser-sections.mjs +214 -0
  53. package/skill/scripts/lib/design-parser-yaml.mjs +135 -0
  54. package/skill/scripts/lib/design-parser.mjs +10 -783
  55. package/skill/scripts/live/manual-apply-chunk.mjs +151 -0
  56. package/skill/scripts/live/manual-apply-compact.mjs +122 -0
  57. package/skill/scripts/live/manual-apply-evidence.mjs +115 -0
  58. package/skill/scripts/live/manual-apply-log.mjs +179 -0
  59. package/skill/scripts/live/manual-apply-transaction.mjs +122 -0
  60. package/skill/scripts/live/manual-apply.mjs +65 -640
  61. package/skill/scripts/live/svelte-component-accept.mjs +248 -0
  62. package/skill/scripts/live/svelte-component-css.mjs +230 -0
  63. package/skill/scripts/live/svelte-component-markup.mjs +104 -0
  64. package/skill/scripts/live/svelte-component-scaffold.mjs +118 -0
  65. package/skill/scripts/live/svelte-component-session.mjs +158 -0
  66. package/skill/scripts/live/svelte-component.mjs +32 -792
  67. package/skill/scripts/live-accept-mutate.mjs +152 -0
  68. package/skill/scripts/live-accept-parse.mjs +370 -0
  69. package/skill/scripts/live-accept-scrub.mjs +59 -0
  70. package/skill/scripts/live-accept-search.mjs +58 -0
  71. package/skill/scripts/live-accept.mjs +15 -631
  72. package/skill/scripts/live-commit-manual-edits-paths.mjs +27 -0
  73. package/skill/scripts/live-commit-manual-edits-repair.mjs +166 -0
  74. package/skill/scripts/live-commit-manual-edits-rollback.mjs +231 -0
  75. package/skill/scripts/live-commit-manual-edits-utils.mjs +167 -0
  76. package/skill/scripts/live-commit-manual-edits-verify.mjs +356 -0
  77. package/skill/scripts/live-commit-manual-edits.mjs +24 -881
  78. package/skill/scripts/live-copy-edit-agent.mjs +16 -551
  79. package/skill/scripts/live-copy-edit-compact.mjs +137 -0
  80. package/skill/scripts/live-copy-edit-post-apply.mjs +175 -0
  81. package/skill/scripts/live-copy-edit-runners.mjs +297 -0
  82. package/skill/scripts/live-inject-csp.mjs +132 -0
  83. package/skill/scripts/live-inject-files.mjs +229 -0
  84. package/skill/scripts/live-inject-tag.mjs +114 -0
  85. package/skill/scripts/live-inject.mjs +13 -440
  86. package/skill/scripts/live-server-poll.mjs +232 -0
  87. package/skill/scripts/live-server-routes.mjs +449 -0
  88. package/skill/scripts/live-server-state.mjs +361 -0
  89. package/skill/scripts/live-server.mjs +10 -946
  90. package/skill/scripts/live-wrap-css.mjs +132 -0
  91. package/skill/scripts/live-wrap-manual-edit.mjs +153 -0
  92. package/skill/scripts/live-wrap-search.mjs +247 -0
  93. package/skill/scripts/live-wrap.mjs +21 -484
  94. package/skill/scripts/palette-seeds.mjs +401 -0
  95. package/skill/scripts/palette.mjs +1 -395
@@ -0,0 +1,152 @@
1
+ /**
2
+ * Discard/accept source rewrites for live-accept.mjs: restoring the original
3
+ * element (discard) or splicing in the chosen variant with a carbonize
4
+ * wrapper for any colocated CSS (accept).
5
+ *
6
+ * Split out of live-accept.mjs. See that file for context.
7
+ */
8
+ import fs from 'node:fs';
9
+ import {
10
+ deindentContent,
11
+ detectCommentSyntax,
12
+ expandReplaceRange,
13
+ extractCss,
14
+ extractOriginal,
15
+ extractVariant,
16
+ findMarkerBlock,
17
+ } from './live-accept-parse.mjs';
18
+
19
+ export function handleDiscard(id, lines, targetFile) {
20
+ const block = findMarkerBlock(id, lines);
21
+ if (!block) return { handled: false, error: 'Markers not found' };
22
+
23
+ const original = extractOriginal(lines, block);
24
+ const isJsx = detectCommentSyntax(targetFile).open === '{/*';
25
+ const replaceRange = expandReplaceRange(block, lines, isJsx);
26
+
27
+ // Restore at the line we're actually replacing FROM, not the marker line.
28
+ // For JSX wrappers the marker comments live INSIDE the outer `<div>`, so
29
+ // `block.start` sits 2 spaces deeper than the original element. Using that
30
+ // as the deindent base would push the restored content 2 spaces too far
31
+ // right on every JSX/TSX session. `replaceRange.start` is the outer wrapper
32
+ // line, which is at the original element's indent for both HTML and JSX.
33
+ const indent = lines[replaceRange.start].match(/^(\s*)/)[1];
34
+ const restored = deindentContent(original, indent);
35
+
36
+ const newLines = [
37
+ ...lines.slice(0, replaceRange.start),
38
+ ...restored,
39
+ ...lines.slice(replaceRange.end + 1),
40
+ ];
41
+ fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
42
+ return {};
43
+ }
44
+
45
+ function buildCarbonizeReplacement({
46
+ indent,
47
+ commentSyntax,
48
+ isJsx,
49
+ id,
50
+ variantNum,
51
+ cssContent,
52
+ paramValues,
53
+ restored,
54
+ }) {
55
+ const lines = [];
56
+ if (!cssContent) {
57
+ lines.push(...restored);
58
+ return lines;
59
+ }
60
+
61
+ const variantStyleAttr = isJsx
62
+ ? "style={{ display: 'contents' }}"
63
+ : 'style="display: contents"';
64
+
65
+ const pushCarbonizeBody = (bodyIndent) => {
66
+ const bodyRestored = reindentContent(restored, indent, `${bodyIndent} `);
67
+ lines.push(`${bodyIndent + commentSyntax.open} monodesign-carbonize-start ${id} ${commentSyntax.close}`);
68
+ lines.push(`${bodyIndent}<style data-monodesign-css="${id}">${isJsx ? '{`' : ''}`);
69
+ for (const cssLine of cssContent) {
70
+ lines.push(bodyIndent + cssLine.trimStart());
71
+ }
72
+ lines.push(bodyIndent + (isJsx ? '`}</style>' : '</style>'));
73
+ if (paramValues && Object.keys(paramValues).length > 0) {
74
+ lines.push(
75
+ `${bodyIndent + commentSyntax.open} monodesign-param-values ${id}: ${JSON.stringify(paramValues)} ${commentSyntax.close}`,
76
+ );
77
+ }
78
+ lines.push(`${bodyIndent + commentSyntax.open} monodesign-carbonize-end ${id} ${commentSyntax.close}`);
79
+ lines.push(`${bodyIndent}<div data-monodesign-variant="${variantNum}" ${variantStyleAttr}>`);
80
+ lines.push(...bodyRestored);
81
+ lines.push(`${bodyIndent}</div>`);
82
+ };
83
+
84
+ if (isJsx) {
85
+ const wrapperStyle = 'style={{ display: "contents" }}';
86
+ lines.push(`${indent}<div data-monodesign-carbonize="${id}" ${wrapperStyle}>`);
87
+ pushCarbonizeBody(`${indent} `);
88
+ lines.push(`${indent}</div>`);
89
+ } else {
90
+ pushCarbonizeBody(indent);
91
+ }
92
+
93
+ return lines;
94
+ }
95
+
96
+ function reindentContent(contentLines, fromIndent, toIndent) {
97
+ return contentLines.map((line) => {
98
+ if (line.trim() === '') return '';
99
+ if (line.startsWith(fromIndent)) return toIndent + line.slice(fromIndent.length);
100
+ return toIndent + line.trimStart();
101
+ });
102
+ }
103
+
104
+ export function handleAccept(id, variantNum, lines, targetFile, paramValues) {
105
+ const block = findMarkerBlock(id, lines);
106
+ if (!block) return { handled: false, error: 'Markers not found' };
107
+
108
+ const commentSyntax = detectCommentSyntax(targetFile);
109
+ const isJsx = commentSyntax.open === '{/*';
110
+ // Anchor indent on the line we're replacing FROM (the outer wrapper),
111
+ // not on `block.start` — for JSX that's the marker comment 2 spaces
112
+ // deeper than the original element. See handleDiscard for the full
113
+ // rationale.
114
+ const replaceRange = expandReplaceRange(block, lines, isJsx);
115
+ const indent = lines[replaceRange.start].match(/^(\s*)/)[1];
116
+
117
+ // Extract the chosen variant's inner content
118
+ const variantContent = extractVariant(lines, block, variantNum);
119
+ if (!variantContent) return { handled: false, error: `Variant ${variantNum} not found` };
120
+ const originalContent = extractOriginal(lines, block);
121
+
122
+ // Extract CSS block if present
123
+ const cssContent = extractCss(lines, block, id);
124
+
125
+ // Check if carbonizing is needed:
126
+ // - CSS block exists, OR
127
+ // - variant HTML contains helper classes/attributes that need cleanup
128
+ const variantText = variantContent.join('\n');
129
+ const hasHelperAttrs = variantText.includes('data-monodesign-variant');
130
+ const needsCarbonize = !!(cssContent || hasHelperAttrs);
131
+
132
+ const restored = deindentContent(variantContent, indent);
133
+ const replacement = buildCarbonizeReplacement({
134
+ indent,
135
+ commentSyntax,
136
+ isJsx,
137
+ id,
138
+ variantNum,
139
+ cssContent,
140
+ paramValues,
141
+ restored,
142
+ });
143
+
144
+ const newLines = [
145
+ ...lines.slice(0, replaceRange.start),
146
+ ...replacement,
147
+ ...lines.slice(replaceRange.end + 1),
148
+ ];
149
+ fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
150
+
151
+ return { carbonize: needsCarbonize, acceptedOriginalText: originalContent.join('\n') };
152
+ }
@@ -0,0 +1,370 @@
1
+ /**
2
+ * Marker-block and content-extraction helpers for live-accept.mjs: locating
3
+ * a session's variant-wrapper markers in source, extracting the original or
4
+ * a chosen variant's content, and the legacy source-shadow-preview detector.
5
+ *
6
+ * Split out of live-accept.mjs. See that file for context.
7
+ */
8
+ import path from 'node:path';
9
+
10
+ export function readSourceShadowPreviewMeta(content, id) {
11
+ const escaped = escapeRegExp(id);
12
+ const wrapperRe = new RegExp(`<[^>]+data-monodesign-variants=(["'])${escaped}\\1[^>]*>`);
13
+ const match = String(content || '').match(wrapperRe);
14
+ if (!match) return null;
15
+ const tag = match[0];
16
+ if (readHtmlAttr(tag, 'data-monodesign-preview') !== 'source-shadow') return null;
17
+ const sourceFile = readHtmlAttr(tag, 'data-monodesign-source-file');
18
+ const sourceStartLine = Number(readHtmlAttr(tag, 'data-monodesign-source-start'));
19
+ const sourceEndLine = Number(readHtmlAttr(tag, 'data-monodesign-source-end'));
20
+ if (!sourceFile || !Number.isFinite(sourceStartLine) || !Number.isFinite(sourceEndLine)) return null;
21
+ return { sourceFile, sourceStartLine, sourceEndLine };
22
+ }
23
+
24
+ function readHtmlAttr(tag, name) {
25
+ const match = String(tag || '').match(new RegExp(`\\s${escapeRegExp(name)}\\s*=\\s*(["'])(.*?)\\1`));
26
+ if (!match) return null;
27
+ return decodeHtmlAttr(match[2]);
28
+ }
29
+
30
+ function decodeHtmlAttr(value) {
31
+ return String(value || '')
32
+ .replace(/&quot;/g, '"')
33
+ .replace(/&lt;/g, '<')
34
+ .replace(/&gt;/g, '>')
35
+ .replace(/&amp;/g, '&');
36
+ }
37
+
38
+ // ---------------------------------------------------------------------------
39
+ // Parsing helpers
40
+ // ---------------------------------------------------------------------------
41
+
42
+ /**
43
+ * Find the start/end marker lines for a session.
44
+ * Returns { start, end } (0-indexed line numbers) or null.
45
+ */
46
+ export function findMarkerBlock(id, lines) {
47
+ let start = -1;
48
+ let end = -1;
49
+ const startPattern = `monodesign-variants-start ${id}`;
50
+ const endPattern = `monodesign-variants-end ${id}`;
51
+
52
+ for (let i = 0; i < lines.length; i++) {
53
+ if (start === -1 && lines[i].includes(startPattern)) start = i;
54
+ if (lines[i].includes(endPattern)) { end = i; break; }
55
+ }
56
+
57
+ return (start !== -1 && end !== -1) ? { start, end, id } : null;
58
+ }
59
+
60
+ /**
61
+ * Compute the line range to REPLACE (vs. just the marker range to extract
62
+ * from). For JSX/TSX wrappers, live-wrap places the marker comments INSIDE
63
+ * the `<div data-monodesign-variants="ID">` outer wrapper so the picked
64
+ * element's JSX slot keeps a single child — a Fragment `<></>` would have
65
+ * solved the multi-sibling case but failed inside `asChild` / cloneElement
66
+ * parents with "Invalid prop supplied to React.Fragment".
67
+ *
68
+ * That means the marker block is enclosed by the wrapper `<div>` opener
69
+ * (with `data-monodesign-variants="ID"`) and its matching `</div>`. We
70
+ * walk back to the opener and forward to the closer so accept/discard
71
+ * remove the entire scaffold, not just the inner markers.
72
+ *
73
+ * Marker lines themselves stay where they were so extractOriginal /
74
+ * extractVariant / extractCss continue to walk the same range.
75
+ */
76
+ export function expandReplaceRange(block, lines, isJsx) {
77
+ if (!isJsx) return { start: block.start, end: block.end };
78
+
79
+ let { start, end } = block;
80
+
81
+ // Walk back for the wrapper `<div data-monodesign-variants="..."` opener.
82
+ // The attr may sit on a continuation line of a multi-line opening tag, so
83
+ // also walk to the line that actually contains `<div`.
84
+ for (let i = start - 1; i >= 0; i--) {
85
+ if (isVariantEndMarkerLine(lines[i], block.id)) break;
86
+ if (hasVariantWrapperAttr(lines[i], block.id)) {
87
+ let opener = i;
88
+ while (opener > 0 && !/<div\b/.test(lines[opener]) && !isVariantEndMarkerLine(lines[opener], block.id)) {
89
+ opener--;
90
+ }
91
+ if (/<div\b/.test(lines[opener])) start = opener;
92
+ break;
93
+ }
94
+ }
95
+
96
+ // Walk forward to the matching `</div>` by div-depth tracking from the
97
+ // wrapper opener. Operate on JOINED text instead of per-line: a
98
+ // multi-line self-closing JSX `<div\n className="spacer"\n/>` would
99
+ // fool per-line regex tracking (the `<div` line matches openRe but the
100
+ // `/>` line never matches selfCloseRe since it needs `<div` on the same
101
+ // line). That left depth permanently over-counted and the wrapper's
102
+ // outer `</div>` orphaned after accept/discard. Single regex with
103
+ // `[^>]*?` (which spans newlines in JS) handles either form correctly.
104
+ const joined = lines.slice(start).join('\n');
105
+ // Match either `<div … />` (self-close, group 1 is `/`), `<div … >`
106
+ // (open, group 1 is empty), or `</div>`.
107
+ const tagRe = /<div\b[^>]*?(\/?)>|<\/div\s*>/g;
108
+ let depth = 0;
109
+ let m;
110
+ while ((m = tagRe.exec(joined)) !== null) {
111
+ const isClose = m[0].startsWith('</');
112
+ const isSelfClose = !isClose && m[1] === '/';
113
+ if (isClose) depth--;
114
+ else if (!isSelfClose) depth++;
115
+ if (depth <= 0) {
116
+ // m.index is offset within `joined`; convert back to a file line.
117
+ const linesBefore = joined.slice(0, m.index + m[0].length).split('\n').length - 1;
118
+ const candidateEnd = start + linesBefore;
119
+ if (candidateEnd >= end) {
120
+ end = candidateEnd;
121
+ break;
122
+ }
123
+ }
124
+ }
125
+
126
+ return { start, end };
127
+ }
128
+
129
+ function escapeRegExp(value) {
130
+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
131
+ }
132
+
133
+ function isVariantEndMarkerLine(line, id) {
134
+ return new RegExp(`monodesign-variants-end\\s+${escapeRegExp(id)}(?:\\s|--|\\*/|$)`).test(line);
135
+ }
136
+
137
+ function hasVariantWrapperAttr(line, id) {
138
+ const escaped = escapeRegExp(id);
139
+ return new RegExp(`data-monodesign-variants\\s*=\\s*(?:"${escaped}"|'${escaped}'|\\{["']${escaped}["']\\})`).test(line);
140
+ }
141
+
142
+ /**
143
+ * Join wrapper lines into a single string with `<style>` elements removed so
144
+ * marker matching and div-depth tracking aren't confused by:
145
+ * - CSS `@scope ([data-monodesign-variant="N"])` strings that look like the
146
+ * HTML marker we're searching for
147
+ * - JSX self-closing `<style ... />` (no separate `</style>` to close on)
148
+ * - Same-line `<style>…</style>` blocks
149
+ * - Multi-line `<style>\n…\n</style>` blocks
150
+ */
151
+ function stripStyleAndJoin(lines, block) {
152
+ const out = [];
153
+ let inStyle = false;
154
+ for (let i = block.start; i <= block.end; i++) {
155
+ let line = lines[i];
156
+
157
+ if (!inStyle) {
158
+ // Strip any complete <style> elements on this line (self-closed or
159
+ // same-line-closed), including their body content.
160
+ line = line
161
+ .replace(/<style\b[^>]*>[\s\S]*?<\/style\s*>/g, '')
162
+ .replace(/<style\b[^>]*\/\s*>/g, '');
163
+
164
+ // If a <style> opener remains (multi-line body starts here), strip from
165
+ // the opener to end-of-line and flip into skip mode.
166
+ const openerIdx = line.search(/<style\b/);
167
+ if (openerIdx !== -1) {
168
+ line = line.slice(0, openerIdx);
169
+ inStyle = true;
170
+ }
171
+ out.push(line);
172
+ } else {
173
+ // In multi-line style body; drop everything until we see </style>.
174
+ const closeIdx = line.search(/<\/style\s*>/);
175
+ if (closeIdx !== -1) {
176
+ inStyle = false;
177
+ out.push(line.slice(closeIdx).replace(/<\/style\s*>/, ''));
178
+ }
179
+ // else: skip line entirely
180
+ }
181
+ }
182
+ return out.join('\n');
183
+ }
184
+
185
+ /**
186
+ * Find the inner content of `<TAG ...attrMatch...>…</TAG>` inside `text`,
187
+ * handling nested same-tag elements via depth counting. `attrMatch` is a
188
+ * regex source fragment that must appear inside the opener tag.
189
+ * Returns the inner string (may be empty), or null if not found.
190
+ */
191
+ function extractInnerByAttr(text, attrMatch) {
192
+ const openerRe = new RegExp(`<([A-Za-z][A-Za-z0-9]*)\\b[^>]*${attrMatch}[^>]*>`);
193
+ const openMatch = text.match(openerRe);
194
+ if (!openMatch) return null;
195
+
196
+ const tagName = openMatch[1];
197
+ const innerStart = openMatch.index + openMatch[0].length;
198
+
199
+ // Match any opener or closer of this tag name after innerStart.
200
+ // (Does not match self-closing <TAG … />, which doesn't contribute to depth.)
201
+ const tagRe = new RegExp(`<(?:/)?${tagName}\\b[^>]*>`, 'g');
202
+ tagRe.lastIndex = innerStart;
203
+
204
+ let depth = 1;
205
+ let m;
206
+ while ((m = tagRe.exec(text))) {
207
+ const isClose = m[0].startsWith('</');
208
+ const isSelfClose = !isClose && /\/\s*>$/.test(m[0]);
209
+ if (isClose) {
210
+ depth--;
211
+ if (depth === 0) return text.slice(innerStart, m.index);
212
+ } else if (!isSelfClose) {
213
+ depth++;
214
+ }
215
+ }
216
+ return null;
217
+ }
218
+
219
+ /**
220
+ * Extract the original element content from within the variant wrapper.
221
+ * Returns an array of lines.
222
+ */
223
+ export function extractOriginal(lines, block) {
224
+ const text = stripStyleAndJoin(lines, block);
225
+ const inner = extractInnerByAttr(text, 'data-monodesign-variant="original"');
226
+ if (inner === null) return [];
227
+ return inner.split('\n');
228
+ }
229
+
230
+ /**
231
+ * Extract a specific variant's inner content (stripping the wrapper div).
232
+ * Returns an array of lines, or null if not found.
233
+ */
234
+ export function extractVariant(lines, block, variantNum) {
235
+ const text = stripStyleAndJoin(lines, block);
236
+ const inner = extractInnerByAttr(text, `data-monodesign-variant="${variantNum}"`);
237
+ if (inner === null) return null;
238
+ const result = inner.split('\n');
239
+ // Collapse a lone empty leading/trailing line (common after string splice).
240
+ while (result.length > 1 && result[0].trim() === '') result.shift();
241
+ while (result.length > 1 && result[result.length - 1].trim() === '') result.pop();
242
+ return result.length > 0 ? result : null;
243
+ }
244
+
245
+ /**
246
+ * Extract the colocated <style> block content (between the style tags).
247
+ * Returns an array of CSS lines, or null if no style block found.
248
+ *
249
+ * Handles three shapes of `<style data-monodesign-css="ID" ...>`:
250
+ * 1. Self-closing: `<style ... />` — no body; return null (nothing to carbonize).
251
+ * 2. Same-line open+close: `<style>...</style>` — return the inner content.
252
+ * 3. Multi-line: `<style>` on one line, `</style>` on a later line — return
253
+ * the lines between them.
254
+ */
255
+ export function extractCss(lines, block, id) {
256
+ const styleAttr = `data-monodesign-css="${id}"`;
257
+ let inStyle = false;
258
+ const content = [];
259
+
260
+ for (let i = block.start; i <= block.end; i++) {
261
+ const line = lines[i];
262
+
263
+ if (!inStyle && line.includes(styleAttr)) {
264
+ // Self-closing: nothing to carbonize.
265
+ if (/<style\b[^>]*\/\s*>/.test(line)) return null;
266
+ // Same-line open + close: extract inner text.
267
+ const sameLine = line.match(/<style\b[^>]*>([\s\S]*?)<\/style\s*>/);
268
+ if (sameLine) {
269
+ const inner = stripJsxTemplateWrap(sameLine[1]);
270
+ return inner.length > 0 ? inner.split('\n') : null;
271
+ }
272
+ inStyle = true;
273
+ continue; // skip the <style> opening tag
274
+ }
275
+
276
+ if (inStyle) {
277
+ // Detect </style> anywhere on the line — JSX template-literal closes
278
+ // (`}</style>`) put the close mid-line, and we don't want to absorb the
279
+ // template-literal punctuation as CSS content.
280
+ const closeIdx = line.indexOf('</style>');
281
+ if (closeIdx !== -1) break;
282
+ content.push(line);
283
+ }
284
+ }
285
+
286
+ if (content.length === 0) return null;
287
+ return stripJsxTemplateLines(content);
288
+ }
289
+
290
+ /**
291
+ * Strip a JSX template-literal wrap (`{` … `}`) from CSS extracted out of a
292
+ * `<style>` element in a JSX/TSX file. The agent may write the wrap with
293
+ * `{` and `}` directly attached to the `<style>` tags, on their own lines,
294
+ * or attached to the first/last CSS lines — all three are JSX-legal.
295
+ *
296
+ * Stripping is required because handleAccept re-wraps the CSS itself when
297
+ * carbonizing. Without this, two consecutive accepts (or a previously-
298
+ * accepted variants block being carbonized) would produce nested
299
+ * `{` `{` … `}` `}`, which oxc rejects with "Expected `}` but found `@`".
300
+ */
301
+ function stripJsxTemplateLines(content) {
302
+ const out = content.slice();
303
+
304
+ // Drop any leading blank lines so we don't miss a `{` line buried below
305
+ // them; same for trailing.
306
+ while (out.length > 0 && out[0].trim() === '') out.shift();
307
+ while (out.length > 0 && out[out.length - 1].trim() === '') out.pop();
308
+ if (out.length === 0) return null;
309
+
310
+ // Leading `{`: own line, or attached to the first CSS line.
311
+ const firstTrim = out[0].trimStart();
312
+ if (firstTrim === '{`') {
313
+ out.shift();
314
+ } else if (firstTrim.startsWith('{`')) {
315
+ const idx = out[0].indexOf('{`');
316
+ out[0] = out[0].slice(0, idx) + out[0].slice(idx + 2);
317
+ if (out[0].trim() === '') out.shift();
318
+ }
319
+ if (out.length === 0) return null;
320
+
321
+ // Trailing `` ` `` `}`: own line, or attached to the last CSS line.
322
+ const lastIdx = out.length - 1;
323
+ const lastTrim = out[lastIdx].trimEnd();
324
+ if (lastTrim === '`}') {
325
+ out.pop();
326
+ } else if (lastTrim.endsWith('`}')) {
327
+ const text = out[lastIdx];
328
+ const idx = text.lastIndexOf('`}');
329
+ out[lastIdx] = text.slice(0, idx) + text.slice(idx + 2);
330
+ if (out[lastIdx].trim() === '') out.pop();
331
+ }
332
+
333
+ return out.length > 0 ? out : null;
334
+ }
335
+
336
+ function stripJsxTemplateWrap(text) {
337
+ const lines = text.split('\n');
338
+ const stripped = stripJsxTemplateLines(lines);
339
+ return stripped ? stripped.join('\n') : '';
340
+ }
341
+
342
+ /**
343
+ * De-indent content that was indented by live-wrap.mjs.
344
+ * The wrap script adds `indent + ' '` (4 extra spaces) to each line.
345
+ * We restore to just `indent` level.
346
+ */
347
+ export function deindentContent(contentLines, baseIndent) {
348
+ // Find the minimum indentation in the content to determine how much was added
349
+ let minIndent = Infinity;
350
+ for (const line of contentLines) {
351
+ if (line.trim() === '') continue;
352
+ const leadingSpaces = line.match(/^(\s*)/)[1].length;
353
+ minIndent = Math.min(minIndent, leadingSpaces);
354
+ }
355
+ if (minIndent === Infinity) minIndent = 0;
356
+
357
+ // Strip the extra indentation and re-add base indent
358
+ return contentLines.map(line => {
359
+ if (line.trim() === '') return '';
360
+ return baseIndent + line.slice(minIndent);
361
+ });
362
+ }
363
+
364
+ export function detectCommentSyntax(filePath) {
365
+ const ext = path.extname(filePath).toLowerCase();
366
+ if (ext === '.jsx' || ext === '.tsx') {
367
+ return { open: '{/*', close: '*/}' };
368
+ }
369
+ return { open: '<!--', close: '-->' };
370
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Scoped manual-edit-buffer cleanup for live-accept.mjs: after a variant
3
+ * accept rewrites a wrapper, drop only staged copy-edit ops whose text
4
+ * appeared inside that wrapper's original block.
5
+ *
6
+ * Split out of live-accept.mjs. See that file for context.
7
+ */
8
+ import { readBuffer as readManualEditsBuffer, writeBuffer as writeManualEditsBuffer } from './live/manual-edits-buffer.mjs';
9
+
10
+ export function scrubManualEditsAgainstOriginalBlock(originalBlockText, cwd = process.cwd(), pageUrl = null) {
11
+ const originalBlock = String(originalBlockText || '');
12
+ if (!originalBlock) return;
13
+ if (!pageUrl) return;
14
+ const buffer = readManualEditsBuffer(cwd);
15
+ if (buffer.entries.length === 0) return;
16
+ let mutated = false;
17
+ for (const entry of buffer.entries) {
18
+ if (entry.pageUrl !== pageUrl) continue;
19
+ const before = entry.ops.length;
20
+ entry.ops = entry.ops.filter((op) => {
21
+ return !manualEditOpAppearsInBlock(op, originalBlock);
22
+ });
23
+ if (entry.ops.length !== before) mutated = true;
24
+ }
25
+ buffer.entries = buffer.entries.filter((entry) => entry.ops.length > 0);
26
+ if (mutated) writeManualEditsBuffer(cwd, buffer);
27
+ }
28
+
29
+ function manualEditOpAppearsInBlock(op, originalBlock) {
30
+ const candidates = [op?.newText, op?.originalText]
31
+ .filter((text) => typeof text === 'string' && text.length > 0);
32
+ return candidates.some((text) => originalBlockHasExactManualText(originalBlock, text));
33
+ }
34
+
35
+ function originalBlockHasExactManualText(originalBlock, text) {
36
+ const needle = normalizeManualEditText(text);
37
+ if (!needle) return false;
38
+ return manualEditTextSegments(originalBlock).some((segment) => segment === needle);
39
+ }
40
+
41
+ function manualEditTextSegments(source) {
42
+ return String(source || '')
43
+ .replace(/<[^>]*>/g, '\n')
44
+ .replace(/\{\/\*[\s\S]*?\*\/\}/g, '\n')
45
+ .replace(/<!--[\s\S]*?-->/g, '\n')
46
+ .split(/\n+/)
47
+ .map(normalizeManualEditText)
48
+ .filter(Boolean);
49
+ }
50
+
51
+ function normalizeManualEditText(text) {
52
+ return String(text || '').replace(/\s+/g, ' ').trim();
53
+ }
54
+
55
+ // Compatibility export for older tests/callers. The unsafe file-wide scrub was
56
+ // removed; callers must pass accepted original-block text for scoped cleanup.
57
+ export function scrubManualEditsAgainstFile(_targetFile, cwd = process.cwd(), originalBlockText = '', pageUrl = null) {
58
+ return scrubManualEditsAgainstOriginalBlock(originalBlockText, cwd, pageUrl);
59
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Session-marker file search for live-accept.mjs: walking common source
3
+ * directories to find the file containing a given session's markers.
4
+ *
5
+ * Split out of live-accept.mjs. See that file for context.
6
+ */
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+
10
+ const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
11
+
12
+ export function findSessionFile(id, cwd) {
13
+ const marker = `monodesign-variants-start ${id}`;
14
+ const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
15
+ const seen = new Set();
16
+
17
+ for (const dir of searchDirs) {
18
+ const absDir = path.join(cwd, dir);
19
+ if (!fs.existsSync(absDir)) continue;
20
+ const result = searchDir(absDir, marker, seen, 0);
21
+ if (result) {
22
+ const content = fs.readFileSync(result, 'utf-8');
23
+ return { file: result, content, lines: content.split('\n') };
24
+ }
25
+ }
26
+ return null;
27
+ }
28
+
29
+ function searchDir(dir, query, seen, depth) {
30
+ if (depth > 5) return null;
31
+ let realDir;
32
+ try { realDir = fs.realpathSync(dir); } catch { return null; }
33
+ if (seen.has(realDir)) return null;
34
+ seen.add(realDir);
35
+
36
+ let entries;
37
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
38
+ catch { return null; }
39
+
40
+ for (const entry of entries) {
41
+ if (!entry.isFile()) continue;
42
+ if (!EXTENSIONS.includes(path.extname(entry.name).toLowerCase())) continue;
43
+ const filePath = path.join(dir, entry.name);
44
+ try {
45
+ const content = fs.readFileSync(filePath, 'utf-8');
46
+ if (content.includes(query)) return filePath;
47
+ } catch { /* skip */ }
48
+ }
49
+
50
+ for (const entry of entries) {
51
+ if (!entry.isDirectory()) continue;
52
+ if (['node_modules', '.git', 'dist', 'build'].includes(entry.name)) continue;
53
+ const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);
54
+ if (result) return result;
55
+ }
56
+
57
+ return null;
58
+ }