mirror of
https://github.com/pbakaus/impeccable.git
synced 2026-09-12 22:26:38 +03:00
* feat(live): manual text-edit panel + Astro inject + stale-lockfile reap Adds a manual text-edit popover under the live-mode bar so users can retype copy directly without going through generate. The footer's "Apply edits" button fires a manual_edits event; the server writes the changes back to source via the new live-edit.mjs deterministic file mutator. Mirrors the wrap+accept flow but skips variant generation. New scripts: - skill/scripts/live-edit.mjs: writes manual_edits back to source - skill/scripts/live-text-rows.js: browser walker that surfaces every pure-text descendant of the picked element as an editable row Touched scripts: - skill/scripts/live-browser.js: text panel UI, CONFIGURING state hook - skill/scripts/live-poll.mjs: manual_edits routing - skill/scripts/live-server.mjs: manual_edits endpoint + handler - skill/scripts/live-wrap.mjs: small adjustments to support the flow Docs + tests: - skill/reference/live.md: manual-edit section - tests/live-edit.test.mjs, tests/live-text-rows.test.mjs Also bundles two live-mode reliability fixes that surfaced during manual testing of the feature: 1. live-inject now emits is:inline when the inject target is a .astro file. Astro otherwise processes the <script> tag and rewrites src to its own bundled URL, so the literal live.js never loads. 2. readLiveServerInfo now probes the lockfile PID with kill(pid, 0) and unlinks the stale lock if dead. Previously a crashed helper left server.json with a dead PID and live-poll reported "Live server not running" forever. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(live): inline contenteditable text editing Replace the text-edit popover panel with inline contenteditable activation. When an element is picked in CONFIGURING, every pure-text descendant becomes contenteditable="true" directly on the page. Each blur-event fires a single-op manual_edits save to source. Esc restores original text and stays in CONFIGURING; successful save exits to PICKING. If Go is clicked while a save is in-flight, the save completes before generate fires. Deleted ~340 lines of panel UI (initTextPanel, openTextPanel, closeTextPanel, renderTextRow, buildTextFooter, etc.). Added enableInlineEdit, disableInlineEdit, onInlineBlur. Server contract unchanged; live-edit.mjs handles per-op saves as before. Tests: 186 pass. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(live): hide annotation overlay during inline edit Annotation overlay's click handler was intercepting clicks on contenteditable text elements. Hide the overlay when inline-edit is enabled to allow text selection and editing. Restore it when exiting inline-edit (if still in CONFIGURING). Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * feat(live): edit content badge mode with batched saves Replace automatic inline contenteditable on element pick with an explicit "Edit content" badge. The badge appears at the element's top-right corner when an element is picked. Clicking the badge enters a new EDITING state where: - The contextual bar hides - The annotation overlay hides - The badge morphs to show Cancel + Apply buttons - Text descendants become contenteditable inline Edits are held in memory (input event tracking) until Apply is clicked, which fires a single batched manual_edits event with all ops. Cancel discards drafts without saving. This eliminates the annotation overlay interference that prevented clicking on text elements. The EDITING state integrates with the main state machine and handles all exits (Esc, click-outside, teardown) cleanly. All 186 tests pass. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(live): use row.el.tagName for tag in applyEditing op The applyEditing function was trying to use row.tag which doesn't exist on the row object. The tag should be the tagName of the text element itself (row.el.tagName.toLowerCase()). Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * feat(live): Edit content badge styling + auto-focus + separate buttons - Edit content button now matches Go button styling (BP.accent background, BP.mark text, FONT, transitions, hover effects) - Auto-focus first editable element when entering editing mode (50ms timeout) - Separate Cancel and Apply buttons with 8px gap (no divider) - Cancel uses muted styling (BP.hairline background, BP.textDim text) - Apply keeps brand accent styling - Remove all focus rings and outlines on edit badge buttons (no blue ring/outline in EDITING mode) Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com> * feat(live): Subtle button UI + cursor positioning + better copy - Change badge buttons to use impeccable-button aesthetic (ink background, surface text, hover to accent) - Removes aggressive styling conflict with Go button - No animations; simple 150ms background transition - Matches site design language (padding 0.625rem 1.5rem, 0.8125rem font, letter-spacing 0.03em) - Shorter, clearer button copy: "Edit" instead of "Edit content", "Save" instead of "Apply" - Fix cursor positioning: cursor now appears at END of text, not beginning - Use Selection API to collapse cursor to end of contenteditable element - Improves UX for immediate continuation of text - Update live.md documentation to reflect new button labels Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com> * fix(live): Use site design system colors for edit badge buttons - Edit/Save buttons: oklch(10% 0 0) background → oklch(60% 0.25 350) on hover - Cancel button: oklch(55% 0 0) background → oklch(65% 0 0) on hover - All buttons: 6px border-radius (matches Go button), oklch(98% 0 0) text - Smooth transition: 0.3s cubic-bezier(0.16, 1, 0.3, 1) (--ease-out) - Uses site color palette instead of live-overlay constants Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com> * fix(live): Match slop-callout style for edit badge buttons - Use exact .slop-callout aesthetic: paper background, accent border + text, uppercase 10px (0.625rem) - 600 weight, 0.06em letter-spacing, 4px 8px padding, 6px border-radius - Box-shadow: 0 2px 8px rgba(0,0,0,0.1) matches site callouts - Hover: inverts to filled background (accent fill, paper text) - Cancel uses ash color variant for muted state, Save uses accent - Smooth 0.3s cubic-bezier(0.16, 1, 0.3, 1) transition on background and color Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(live): Pill-shaped edit badge buttons, 2px padding, no uppercase - Border-radius: 999px (pill shape) - Padding: 2px 8px (more compact) - Removed text-transform: uppercase Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(live): Cancel button uses mist border + ash text - Border: 1px solid oklch(92% 0 0) (--color-mist) - Color: oklch(55% 0 0) (--color-ash) - Hover: inverts to ash background with paper text Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(live): Remove blue focus outline from contenteditable elements in EDITING mode - Add inline outline: none on each row's element when contenteditable activates - Inject [data-impeccable-editable] CSS rule to override browser default focus ring - Use !important to win against site styles that re-apply focus outlines - Cleanup restores outline/data-attribute on disable Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(live): Decouple manual edits from agent/poll pipeline Manual text edits now POST directly to a new /manual-edit endpoint that runs live-edit.mjs synchronously and returns the result. The event is never enqueued, never reaches the poll loop, never reaches the agent. Why: every Save was costing an LLM turn. The poll script would dequeue the manual_edits event, run live-edit.mjs deterministically, post a completion ack, then print the event JSON to stdout. The Claude agent would read that output and decide "loop and re-poll". Zero real work for the agent but every Save burned context. Changes: - live-server.mjs: new POST /manual-edit handler that runs live-edit.mjs synchronously and returns the result. Does not enqueue, does not log to session store. Defense-in-depth: /events rejects manual_edits. - live-browser.js: applyEditing() POSTs to /manual-edit instead of sendEvent({type: 'manual_edits'}). - live-poll.mjs: removed manual_edits handler branch (dead code now). - reference/live.md: removed "Handle manual_edits" section; replaced with a one-line note that manual edits are server-direct. The HMR-triggered page reload remains (dev server detects source file change) but that is a separate dev-server behavior, not our pipeline. resumeSession() already restores variants and selection after reload. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(live): Stash manual edits server-side; commit via AI on request Decouples manual-edit Save from source file writes. Save now stashes to .impeccable/live/pending-manual-edits.json with no HMR refresh. The user explicitly asks the AI to commit when ready. Why: even with the prior /manual-edit fix, every Save still wrote to source and triggered the dev server's HMR/full reload. The page flash was the actual user pain. Now there's zero source touch on Save, and the user controls when the dev server reloads. Server (live-server.mjs): - /manual-edit-stash POST: append to buffer file. Returns {ok, pendingCount, totalCount, perPage}. - /manual-edit-stash GET: query counts by page for counter UI. - /manual-edit-discard POST: drop entries (all if no pageUrl). - Old /manual-edit returns 410 Gone (defense in depth). - Buffer ops merge by (pageUrl, ref): keep first originalText, update newText. CLIs: - live-commit-manual-edits.mjs: read buffer, shell out to live-edit.mjs per entry, truncate succeeded entries, surface failures. - live-discard-manual-edits.mjs: truncate buffer (optionally scoped by page). - Both take optional --page-url=<url>. Browser (live-browser.js): - applyEditing() POSTs to /manual-edit-stash, no source write. - Pending pill (• N staged) + trash icon next to Exit in global bar. - One-time onboarding toast on first Save: "Saved. Tell the AI to commit when ready." - Counter persists across reloads via GET /manual-edit-stash on init. - Trash icon: confirm dialog scoped to current page, then POST /manual-edit-discard. Variant pipeline interaction: - live-wrap.mjs: when wrapping an element, apply pending manual edits to the source range so the wrap block's "original" variant reflects the user's edited DOM (their pre-Go view), not the raw source. - live-accept.mjs: after accept writes the variant to source, scrub buffer ops whose originalText no longer appears in that file. The accept embodies the manual edit; the pending op is consumed. - Variant discard does NOT touch the buffer. Reference docs: - reference/live.md: full commit/discard contract, trigger guidance (narrow action-verb intent), do-not-auto-commit rule. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * feat(live): Staged-edits pill becomes an "Apply" button Click the "• N staged" pill → confirm dialog "Apply N staged edits to source? The page will reload." → POST /manual-edit-commit on the server, which shells out to live-commit-manual-edits.mjs. Same path the AI uses, just triggered from the overlay. Trash icon stays for discard. The AI-driven commit path also stays (useful for inspecting failures or scripting). The pill is now the primary apply affordance because it removes the chat-context-switch for the common case. Pill styling: pointer cursor, accent border + text at rest, fills on hover (accent bg, paper text). Tooltip: "Click to apply staged edits to source". First-save toast updated: "Saved. Click the 'staged' badge to apply, or ask the AI." Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * chore(live): gitignore pending-manual-edits.json runtime buffer Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore: drop stray site/ test edits from PR Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(live): Pill label reads "Apply N staged" Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(live): Manual edit ops use the leaf element's locator, not parent's Multi-row inline editing captures each contenteditable leaf (row.el) but the op was being built with selectedElement.id / classList — i.e. the parent card, not the editable text node. live-edit.mjs then searched source for the parent's class on the leaf's tag (e.g. <span class= "foundation-card">), found nothing, and silently failed. Use row.el's own id / classList instead. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(live): Climb to nearest classed ancestor when leaf has no locator A bare <em>/<strong>/etc. with no id or class produced ops the CLI rejected with insufficient_locator. Prefer the leaf's own id/class; if neither exists, walk up to the nearest ancestor with one and adopt its tag + locator. Text-replace still works because the CLI narrows by originalText inside the matched element's source range. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(live): Make mixed-content paragraphs editable The text-rows walker skips elements with mixed children (text + element + text), so paragraphs like "Some text <code>x</code> more text" or "Body text · <a>link</a>" exposed zero rows for the surrounding copy. At edit time, wrap each non-whitespace direct text-node child in a marker span so the walker emits a row for it. Unwrap on save/cancel. The locator climbs to the parent's class as before, and live-edit narrows by originalText inside that parent's source range. hasTextRows now uses a lightweight subtree check that matches the new wrap+walk path so the edit affordance shows up on mixed-content elements. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(live): Address Cursor Bugbot findings (CB-2 through CB-6) CB-2 - Escape reverted DOM text but inlineEditDrafts retained the pre-revert value; clicking Apply afterwards committed the undone edit. Clear the draft entry when restoring innerText. CB-3 - The scrub gate !result.handled || result.handled !== false was a tautology that ran the scrub regardless of accept outcome. Use the intended result.handled !== false. CB-4 - The buffer-aware "original" content step in live-wrap iterated every entry in the buffer with no pageUrl filter, so an edit on /a could leak into a wrap call on /b. Add --page-url to the CLI; filter by it; skip the buffer-aware step entirely when omitted. live.md updated. CB-5 - removeEntries returned entry count while truncateBuffer returned op count, causing the discard CLI and HTTP endpoint to report mixed units. Make removeEntries return ops removed. CB-6 - applyTextReplace used string truthiness to gate prepending content above the edit, which silently dropped a leading empty line when the file started with '\n'. Gate on the line index instead, and mirror the fix on the trailing-empty-line side. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(live): A3+A4 data-integrity guards, A6 test coverage A3 — applyTextReplace refuses with text_ambiguous_in_block when originalText appears more than once in the matched element block. Refusing is safer than picking the first indexOf hit when we can't tell which leaf the user edited; user can rephrase one occurrence. A4 — newText is rejected if it contains <, >, {, }, or a backtick. Two layers: server-side validator in /manual-edit-stash returns 400, CLI-side guard in applyTextReplace returns invalid_chars_in_newText. Browser surfaces the specific reason via toast. The shared char list lives in live-edit.mjs (validateNewTextChars). reference/live.md documents the rule. A6 — New test files cover the orchestration gap: - live-manual-edits-buffer.test.mjs (17 tests across read/stage/ remove/find/count/truncate; pins removeEntries returns OPS count) - live-wrap-buffer-aware.test.mjs (3 tests; CB-4 regression test) - live-commit-manual-edits.test.mjs (4 tests; partial-failure, --page-url scope, no_pending_edits) - live-discard-manual-edits.test.mjs (3 tests; CB-5 unit consistency) - live-accept-scrub.test.mjs (4 tests; keep/drop/prune) Plus 2 new cases in live-edit.test.mjs for A3 and A4. Side-effect refactors: - scrubManualEditsAgainstFile accepts cwd for unit-testing and is exported. - Failed-op entries in live-edit.mjs now propagate forbidden and occurrences fields so callers can surface specifics. 41 tests across the 6 affected files pass; full suite green at 186/186. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore: drop .claude/pr-review.md from PR Local review notes belong in the working tree, not the PR diff. Kept in the file system; just untracked. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore: drop stray site/ test edits from PR (round 2) Live-inject script tag and the "Impeccable Works!" / "WHAT'S INCLUDED IN THE BOX" / "Wow Impeccable. ---- " strings were test edits that slipped back into the branch. Restore both files to match main. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(live): Disable Edit badge while variants are generating Clicking Edit during GENERATING would open inline text editing on the same DOM region the variant wrapper is about to land in, racing the HMR and the mutation observer. The badge now switches to an 'idle-disabled' rendering (ash + mist, not-allowed cursor, disabled attribute, tooltip) the moment state transitions into GENERATING. Returns to 'idle' on the normal CONFIGURING re-entry paths. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(live): live-wrap refuses without --page-url when buffer has pending edits When a manual edit is staged ("Impeccable Works!") but not yet committed, the buffer holds the user's edited DOM while source still has the un- edited text ("Impeccable"). live-wrap's buffer-aware step exists to rewrite the wrap block's <div data-impeccable-variant="original"> to match the staged DOM, but per CB-4 it is gated by --page-url. When the agent invoking live-wrap omits --page-url, the buffer-aware step silently no-op'd and the variant authoring saw stale source — the user's manual edit appeared lost. Make the silent no-op a loud error: when buffer.entries.length > 0 and --page-url is missing, exit 1 with { error: 'missing_page_url_with_pending_edits', pendingEntries, hint }. Empty buffer = no risk = no requirement, so existing flows without pending edits keep working. Updated reference/live.md to flag --page-url as required when the buffer has entries. Added regression test in live-wrap-buffer-aware.test.mjs. live-wrap.test.mjs gained a buffer- clear hook so any leftover .impeccable/live/pending-manual-edits.json from local dev doesn't trip the new check. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * change back * chore: drop stray site/ test edits from PR (round 3) Live-inject script tag in Base.astro slipped back in via git add -A while a local live server was running. Restore both site/ files to main. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * Fix live manual edit staging * Rename live edit copy badge * Use sentence case for live edit copy badge * Move copy edit apply control outside live bar * Improve live copy edit apply flow * Clean up live copy edit AI apply flow * Polish live copy edit docs and toast * Fix staged copy edit review issues * Fix CI jsdom dependency * Fix Cursor Bot live edit findings * Fix remaining live edit review issues * Fix Bugbot staged edit edge cases * Fix latest Bugbot live edit edges * Fix remaining Bugbot wrap and discard issues * Fix live copy edit safety contracts * Fix copy edit rollback coverage * Fix live manual copy edit apply flow * Adjust live pending dock offset * feat(live): route manual-edit Apply through the chat agent Make the staged copy-edit Apply work when no CLI AI runner is authenticated by routing the batch through the active chat session, and surface runner failures clearly instead of opaque exit codes. - live-poll: add --reply --data '<json>' so the chat agent can return a structured manual_edit_apply result (the documented flag was missing, so the server resolved with an empty object) - live-server: manual_edit_apply event + deferred map, chat-vs-subprocess dispatch in /manual-edit-commit, resolve the deferred from the ack - live-copy-edit-agent: chat provider, extractRunnerErrorMessage and commandAuthed pre-flight, diagnostic describeNoProviderError; drop the stale CLAUDE_CODE_SIMPLE and --no-session-persistence flags so headless CLAUDE_CODE_OAUTH_TOKEN auth works - live-browser: clear pendingApplyInFlight on commit_done and add a watchdog so a missed signal can no longer freeze element picking - reference/live.md: tight Handle manual_edit_apply handler plus a separate diagnostics reference section; advertise the event in the opening contract and dispatch table Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * Add live manual edit apply coverage * Fix manual edit apply review issues * Fix manual edit review follow-ups * Fix manual apply poll acknowledgements * Fix manual apply failed-entry rollback * Clarify manual apply LLM prompt * Fix stale manual apply discard events * Fix manual apply dynamic source edits * Fix large manual apply chunks * Clarify manual edit apply is first-class work * Clarify manual apply resume flow * Compact live manual apply evidence * Reject malformed manual apply replies * Recover legacy manual apply summaries * Fix Astro live script injection * Add live manual edit apply coverage * Slim live manual apply flow * Slim manual edit test dependencies * Stabilize real browser LLM smoke * Generalize manual edit LLM prompt examples * Remove retired live edit wrapper * Inline live text row walker * Slim manual edit prompts * Drop AGENTS doc churn * Stabilize live manual apply prompts * Stabilize manual apply visible Haiku flow * Add hard framework manual edit coverage * Stabilize manual edit LLM retries * Fix manual apply transaction rollback * Fix live shader text capture * Clean up manual apply runtime artifacts * Fix live manual edit apply reliability * Clean up manual apply coverage * Slim manual apply test cleanup * Fix manual edit prompt contract test * Align manual edit cancel hover * Fix live loading shader capture * Fix manual apply review findings * Restore live e2e tests for CI * Fix live loading shader halftone * Tune live loading shader dots * Restore main live shader behavior * Fix manual apply review findings * Fix manual apply bot follow-ups * Clarify manual apply rollback changes * Fix manual apply state naming * Address PR review cleanup * Fix manual apply review follow-ups * Fix multiline manual apply verification * Restore inline drafts when hiding live bar --------- Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
690 lines
26 KiB
JavaScript
690 lines
26 KiB
JavaScript
/**
|
|
* CLI helper: deterministic accept/discard of variant sessions.
|
|
*
|
|
* Usage:
|
|
* node live-accept.mjs --id SESSION_ID --discard
|
|
* node live-accept.mjs --id SESSION_ID --variant N
|
|
*
|
|
* For discard: removes the entire variant wrapper and restores the original.
|
|
* For accept: replaces the wrapper with the chosen variant's content. If the
|
|
* session had a colocated <style> block, it's preserved with carbonize markers
|
|
* for a background agent to integrate into the project's CSS.
|
|
*
|
|
* Output: JSON to stdout.
|
|
*/
|
|
|
|
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import { isGeneratedFile } from './is-generated.mjs';
|
|
import { readBuffer as readManualEditsBuffer, writeBuffer as writeManualEditsBuffer } from './live-manual-edits-buffer.mjs';
|
|
|
|
const EXTENSIONS = ['.html', '.jsx', '.tsx', '.vue', '.svelte', '.astro'];
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// CLI
|
|
// ---------------------------------------------------------------------------
|
|
|
|
export async function acceptCli() {
|
|
const args = process.argv.slice(2);
|
|
|
|
if (args.includes('--help') || args.includes('-h')) {
|
|
console.log(`Usage: node live-accept.mjs [options]
|
|
|
|
Deterministic accept/discard for live variant sessions.
|
|
|
|
Modes:
|
|
--discard Remove variants, restore original
|
|
--variant N Accept variant N, discard the rest
|
|
|
|
Required:
|
|
--id SESSION_ID Session ID of the variant wrapper
|
|
|
|
Options:
|
|
--page-url URL Current browser page URL; scopes staged copy-edit cleanup
|
|
|
|
Output (JSON):
|
|
{ handled, file, carbonize }`);
|
|
process.exit(0);
|
|
}
|
|
|
|
const id = argVal(args, '--id');
|
|
const variantNum = argVal(args, '--variant');
|
|
const paramValuesRaw = argVal(args, '--param-values');
|
|
const pageUrl = argVal(args, '--page-url');
|
|
const isDiscard = args.includes('--discard');
|
|
|
|
if (!id) { console.error('Missing --id'); process.exit(1); }
|
|
if (!isDiscard && !variantNum) { console.error('Need --discard or --variant N'); process.exit(1); }
|
|
|
|
let paramValues = null;
|
|
if (paramValuesRaw) {
|
|
try { paramValues = JSON.parse(paramValuesRaw); }
|
|
catch { paramValues = null; } // malformed blob: skip the comment rather than failing the accept
|
|
}
|
|
|
|
// Find the file containing this session's markers
|
|
const found = findSessionFile(id, process.cwd());
|
|
if (!found) {
|
|
console.log(JSON.stringify({ handled: false, error: 'Session markers not found for id: ' + id }));
|
|
process.exit(0);
|
|
}
|
|
|
|
const { file: targetFile, content, lines } = found;
|
|
const relFile = path.relative(process.cwd(), targetFile);
|
|
|
|
// Bail if the session lives in a generated file. The agent manually wrote
|
|
// the wrapper there for preview, and is responsible for writing the
|
|
// accepted variant to true source (or cleaning up on discard). See
|
|
// "Handle fallback" in live.md.
|
|
if (isGeneratedFile(targetFile, { cwd: process.cwd() })) {
|
|
console.log(JSON.stringify({
|
|
handled: false,
|
|
mode: 'fallback',
|
|
file: relFile,
|
|
hint: 'Session is in a generated file. Persist the accepted variant in source; do not rely on this script.',
|
|
}));
|
|
process.exit(0);
|
|
}
|
|
|
|
if (isDiscard) {
|
|
const result = handleDiscard(id, lines, targetFile);
|
|
console.log(JSON.stringify({ handled: true, file: relFile, carbonize: false, ...result }));
|
|
} else {
|
|
const result = handleAccept(id, variantNum, lines, targetFile, paramValues);
|
|
const acceptedOriginalText = result.acceptedOriginalText || '';
|
|
delete result.acceptedOriginalText;
|
|
// Single-line attention-grabber when cleanup is required. The full
|
|
// five-step checklist lives in reference/live.md (loaded once per
|
|
// session); repeating it per-event would waste tokens.
|
|
if (result.carbonize) {
|
|
result.todo = 'REQUIRED before next poll: carbonize cleanup in ' + relFile + '. See reference/live.md "Required after accept".';
|
|
}
|
|
// Scrub stash entries whose text appeared inside the just-replaced
|
|
// original wrap block. The accept embodies those manual edits (wrap was
|
|
// buffer-aware), so only those scoped ops are redundant.
|
|
if (result.handled !== false) {
|
|
try {
|
|
scrubManualEditsAgainstOriginalBlock(acceptedOriginalText, process.cwd(), pageUrl);
|
|
} catch {
|
|
// Non-fatal; the buffer stays as-is and the user can discard later.
|
|
}
|
|
}
|
|
console.log(JSON.stringify({ handled: true, file: relFile, ...result }));
|
|
}
|
|
}
|
|
|
|
/**
|
|
* After a variant accept rewrites one wrapper, drop only buffer ops whose
|
|
* text appeared inside that wrapper's original block. The previous file-wide
|
|
* scrub dropped unrelated staged edits from other components/files whenever
|
|
* their originalText wasn't present in the just-accepted file.
|
|
*
|
|
* Match both originalText and newText because live-wrap rewrites the original
|
|
* preview block to reflect pending manual edits before variants are generated.
|
|
*/
|
|
function scrubManualEditsAgainstOriginalBlock(originalBlockText, cwd = process.cwd(), pageUrl = null) {
|
|
const originalBlock = String(originalBlockText || '');
|
|
if (!originalBlock) return;
|
|
if (!pageUrl) return;
|
|
const buffer = readManualEditsBuffer(cwd);
|
|
if (buffer.entries.length === 0) return;
|
|
let mutated = false;
|
|
for (const entry of buffer.entries) {
|
|
if (entry.pageUrl !== pageUrl) continue;
|
|
const before = entry.ops.length;
|
|
entry.ops = entry.ops.filter((op) => {
|
|
return !manualEditOpAppearsInBlock(op, originalBlock);
|
|
});
|
|
if (entry.ops.length !== before) mutated = true;
|
|
}
|
|
buffer.entries = buffer.entries.filter((entry) => entry.ops.length > 0);
|
|
if (mutated) writeManualEditsBuffer(cwd, buffer);
|
|
}
|
|
|
|
function manualEditOpAppearsInBlock(op, originalBlock) {
|
|
const candidates = [op?.newText, op?.originalText]
|
|
.filter((text) => typeof text === 'string' && text.length > 0);
|
|
return candidates.some((text) => originalBlockHasExactManualText(originalBlock, text));
|
|
}
|
|
|
|
function originalBlockHasExactManualText(originalBlock, text) {
|
|
const needle = normalizeManualEditText(text);
|
|
if (!needle) return false;
|
|
return manualEditTextSegments(originalBlock).some((segment) => segment === needle);
|
|
}
|
|
|
|
function manualEditTextSegments(source) {
|
|
return String(source || '')
|
|
.replace(/<[^>]*>/g, '\n')
|
|
.replace(/\{\/\*[\s\S]*?\*\/\}/g, '\n')
|
|
.replace(/<!--[\s\S]*?-->/g, '\n')
|
|
.split(/\n+/)
|
|
.map(normalizeManualEditText)
|
|
.filter(Boolean);
|
|
}
|
|
|
|
function normalizeManualEditText(text) {
|
|
return String(text || '').replace(/\s+/g, ' ').trim();
|
|
}
|
|
|
|
// Compatibility export for older tests/callers. The unsafe file-wide scrub was
|
|
// removed; callers must pass accepted original-block text for scoped cleanup.
|
|
function scrubManualEditsAgainstFile(_targetFile, cwd = process.cwd(), originalBlockText = '', pageUrl = null) {
|
|
return scrubManualEditsAgainstOriginalBlock(originalBlockText, cwd, pageUrl);
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Discard
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function handleDiscard(id, lines, targetFile) {
|
|
const block = findMarkerBlock(id, lines);
|
|
if (!block) return { handled: false, error: 'Markers not found' };
|
|
|
|
const original = extractOriginal(lines, block);
|
|
const isJsx = detectCommentSyntax(targetFile).open === '{/*';
|
|
const replaceRange = expandReplaceRange(block, lines, isJsx);
|
|
|
|
// Restore at the line we're actually replacing FROM, not the marker line.
|
|
// For JSX wrappers the marker comments live INSIDE the outer `<div>`, so
|
|
// `block.start` sits 2 spaces deeper than the original element. Using that
|
|
// as the deindent base would push the restored content 2 spaces too far
|
|
// right on every JSX/TSX session. `replaceRange.start` is the outer wrapper
|
|
// line, which is at the original element's indent for both HTML and JSX.
|
|
const indent = lines[replaceRange.start].match(/^(\s*)/)[1];
|
|
const restored = deindentContent(original, indent);
|
|
|
|
const newLines = [
|
|
...lines.slice(0, replaceRange.start),
|
|
...restored,
|
|
...lines.slice(replaceRange.end + 1),
|
|
];
|
|
fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
|
|
return {};
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Accept
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function handleAccept(id, variantNum, lines, targetFile, paramValues) {
|
|
const block = findMarkerBlock(id, lines);
|
|
if (!block) return { handled: false, error: 'Markers not found' };
|
|
|
|
const commentSyntax = detectCommentSyntax(targetFile);
|
|
const isJsx = commentSyntax.open === '{/*';
|
|
// Anchor indent on the line we're replacing FROM (the outer wrapper),
|
|
// not on `block.start` — for JSX that's the marker comment 2 spaces
|
|
// deeper than the original element. See handleDiscard for the full
|
|
// rationale.
|
|
const replaceRange = expandReplaceRange(block, lines, isJsx);
|
|
const indent = lines[replaceRange.start].match(/^(\s*)/)[1];
|
|
|
|
// Extract the chosen variant's inner content
|
|
const variantContent = extractVariant(lines, block, variantNum);
|
|
if (!variantContent) return { handled: false, error: 'Variant ' + variantNum + ' not found' };
|
|
const originalContent = extractOriginal(lines, block);
|
|
|
|
// Extract CSS block if present
|
|
const cssContent = extractCss(lines, block, id);
|
|
|
|
// Check if carbonizing is needed:
|
|
// - CSS block exists, OR
|
|
// - variant HTML contains helper classes/attributes that need cleanup
|
|
const variantText = variantContent.join('\n');
|
|
const hasHelperAttrs = variantText.includes('data-impeccable-variant');
|
|
const needsCarbonize = !!(cssContent || hasHelperAttrs);
|
|
|
|
// Build the replacement
|
|
const restored = deindentContent(variantContent, indent);
|
|
const replacement = [];
|
|
|
|
if (cssContent) {
|
|
replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-start ' + id + ' ' + commentSyntax.close);
|
|
// JSX targets need the CSS body wrapped in a template literal so that the
|
|
// `{` and `}` in CSS rules don't get parsed as JSX expressions.
|
|
replacement.push(indent + '<style data-impeccable-css="' + id + '">' + (isJsx ? '{`' : ''));
|
|
// Re-indent CSS content to match
|
|
for (const cssLine of cssContent) {
|
|
replacement.push(indent + cssLine.trimStart());
|
|
}
|
|
replacement.push(indent + (isJsx ? '`}</style>' : '</style>'));
|
|
if (paramValues && Object.keys(paramValues).length > 0) {
|
|
// Preserve the user's knob positions for the carbonize-cleanup agent
|
|
// to bake into the final CSS when it collapses scoped rules.
|
|
replacement.push(indent + commentSyntax.open + ' impeccable-param-values ' + id + ': ' + JSON.stringify(paramValues) + ' ' + commentSyntax.close);
|
|
}
|
|
replacement.push(indent + commentSyntax.open + ' impeccable-carbonize-end ' + id + ' ' + commentSyntax.close);
|
|
}
|
|
|
|
// Keep the `@scope ([data-impeccable-variant="N"])` selectors in the
|
|
// carbonize CSS block working visually by re-wrapping the accepted content
|
|
// in a data-impeccable-variant="N" div with `display: contents` (so layout
|
|
// isn't affected). The carbonize agent strips this attribute + wrapper when
|
|
// it moves the CSS to a proper stylesheet.
|
|
//
|
|
// Style attribute syntax has to follow the host file's flavor — JSX files
|
|
// need the object form, otherwise React 19 throws "Failed to set indexed
|
|
// property [0] on CSSStyleDeclaration" while parsing the string char-by-char.
|
|
if (cssContent) {
|
|
const styleAttr = isJsx ? "style={{ display: 'contents' }}" : 'style="display: contents"';
|
|
replacement.push(indent + '<div data-impeccable-variant="' + variantNum + '" ' + styleAttr + '>');
|
|
replacement.push(...restored);
|
|
replacement.push(indent + '</div>');
|
|
} else {
|
|
replacement.push(...restored);
|
|
}
|
|
|
|
const newLines = [
|
|
...lines.slice(0, replaceRange.start),
|
|
...replacement,
|
|
...lines.slice(replaceRange.end + 1),
|
|
];
|
|
fs.writeFileSync(targetFile, newLines.join('\n'), 'utf-8');
|
|
|
|
return { carbonize: needsCarbonize, acceptedOriginalText: originalContent.join('\n') };
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Parsing helpers
|
|
// ---------------------------------------------------------------------------
|
|
|
|
/**
|
|
* Find the start/end marker lines for a session.
|
|
* Returns { start, end } (0-indexed line numbers) or null.
|
|
*/
|
|
function findMarkerBlock(id, lines) {
|
|
let start = -1;
|
|
let end = -1;
|
|
const startPattern = 'impeccable-variants-start ' + id;
|
|
const endPattern = 'impeccable-variants-end ' + id;
|
|
|
|
for (let i = 0; i < lines.length; i++) {
|
|
if (start === -1 && lines[i].includes(startPattern)) start = i;
|
|
if (lines[i].includes(endPattern)) { end = i; break; }
|
|
}
|
|
|
|
return (start !== -1 && end !== -1) ? { start, end, id } : null;
|
|
}
|
|
|
|
/**
|
|
* Compute the line range to REPLACE (vs. just the marker range to extract
|
|
* from). For JSX/TSX wrappers, live-wrap places the marker comments INSIDE
|
|
* the `<div data-impeccable-variants="ID">` outer wrapper so the picked
|
|
* element's JSX slot keeps a single child — a Fragment `<></>` would have
|
|
* solved the multi-sibling case but failed inside `asChild` / cloneElement
|
|
* parents with "Invalid prop supplied to React.Fragment".
|
|
*
|
|
* That means the marker block is enclosed by the wrapper `<div>` opener
|
|
* (with `data-impeccable-variants="ID"`) and its matching `</div>`. We
|
|
* walk back to the opener and forward to the closer so accept/discard
|
|
* remove the entire scaffold, not just the inner markers.
|
|
*
|
|
* Marker lines themselves stay where they were so extractOriginal /
|
|
* extractVariant / extractCss continue to walk the same range.
|
|
*/
|
|
function expandReplaceRange(block, lines, isJsx) {
|
|
if (!isJsx) return { start: block.start, end: block.end };
|
|
|
|
let { start, end } = block;
|
|
|
|
// Walk back for the wrapper `<div data-impeccable-variants="..."` opener.
|
|
// The attr may sit on a continuation line of a multi-line opening tag, so
|
|
// also walk to the line that actually contains `<div`.
|
|
for (let i = start - 1; i >= 0; i--) {
|
|
if (isVariantEndMarkerLine(lines[i], block.id)) break;
|
|
if (hasVariantWrapperAttr(lines[i], block.id)) {
|
|
let opener = i;
|
|
while (opener > 0 && !/<div\b/.test(lines[opener]) && !isVariantEndMarkerLine(lines[opener], block.id)) {
|
|
opener--;
|
|
}
|
|
if (/<div\b/.test(lines[opener])) start = opener;
|
|
break;
|
|
}
|
|
}
|
|
|
|
// Walk forward to the matching `</div>` by div-depth tracking from the
|
|
// wrapper opener. Operate on JOINED text instead of per-line: a
|
|
// multi-line self-closing JSX `<div\n className="spacer"\n/>` would
|
|
// fool per-line regex tracking (the `<div` line matches openRe but the
|
|
// `/>` line never matches selfCloseRe since it needs `<div` on the same
|
|
// line). That left depth permanently over-counted and the wrapper's
|
|
// outer `</div>` orphaned after accept/discard. Single regex with
|
|
// `[^>]*?` (which spans newlines in JS) handles either form correctly.
|
|
const joined = lines.slice(start).join('\n');
|
|
// Match either `<div … />` (self-close, group 1 is `/`), `<div … >`
|
|
// (open, group 1 is empty), or `</div>`.
|
|
const tagRe = /<div\b[^>]*?(\/?)>|<\/div\s*>/g;
|
|
let depth = 0;
|
|
let m;
|
|
while ((m = tagRe.exec(joined)) !== null) {
|
|
const isClose = m[0].startsWith('</');
|
|
const isSelfClose = !isClose && m[1] === '/';
|
|
if (isClose) depth--;
|
|
else if (!isSelfClose) depth++;
|
|
if (depth <= 0) {
|
|
// m.index is offset within `joined`; convert back to a file line.
|
|
const linesBefore = joined.slice(0, m.index + m[0].length).split('\n').length - 1;
|
|
const candidateEnd = start + linesBefore;
|
|
if (candidateEnd >= end) {
|
|
end = candidateEnd;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
return { start, end };
|
|
}
|
|
|
|
function escapeRegExp(value) {
|
|
return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
}
|
|
|
|
function isVariantEndMarkerLine(line, id) {
|
|
return new RegExp('impeccable-variants-end\\s+' + escapeRegExp(id) + '(?:\\s|--|\\*/|$)').test(line);
|
|
}
|
|
|
|
function hasVariantWrapperAttr(line, id) {
|
|
const escaped = escapeRegExp(id);
|
|
return new RegExp(`data-impeccable-variants\\s*=\\s*(?:"${escaped}"|'${escaped}'|\\{["']${escaped}["']\\})`).test(line);
|
|
}
|
|
|
|
/**
|
|
* Join wrapper lines into a single string with `<style>` elements removed so
|
|
* marker matching and div-depth tracking aren't confused by:
|
|
* - CSS `@scope ([data-impeccable-variant="N"])` strings that look like the
|
|
* HTML marker we're searching for
|
|
* - JSX self-closing `<style ... />` (no separate `</style>` to close on)
|
|
* - Same-line `<style>…</style>` blocks
|
|
* - Multi-line `<style>\n…\n</style>` blocks
|
|
*/
|
|
function stripStyleAndJoin(lines, block) {
|
|
const out = [];
|
|
let inStyle = false;
|
|
for (let i = block.start; i <= block.end; i++) {
|
|
let line = lines[i];
|
|
|
|
if (!inStyle) {
|
|
// Strip any complete <style> elements on this line (self-closed or
|
|
// same-line-closed), including their body content.
|
|
line = line
|
|
.replace(/<style\b[^>]*>[\s\S]*?<\/style\s*>/g, '')
|
|
.replace(/<style\b[^>]*\/\s*>/g, '');
|
|
|
|
// If a <style> opener remains (multi-line body starts here), strip from
|
|
// the opener to end-of-line and flip into skip mode.
|
|
const openerIdx = line.search(/<style\b/);
|
|
if (openerIdx !== -1) {
|
|
line = line.slice(0, openerIdx);
|
|
inStyle = true;
|
|
}
|
|
out.push(line);
|
|
} else {
|
|
// In multi-line style body; drop everything until we see </style>.
|
|
const closeIdx = line.search(/<\/style\s*>/);
|
|
if (closeIdx !== -1) {
|
|
inStyle = false;
|
|
out.push(line.slice(closeIdx).replace(/<\/style\s*>/, ''));
|
|
}
|
|
// else: skip line entirely
|
|
}
|
|
}
|
|
return out.join('\n');
|
|
}
|
|
|
|
/**
|
|
* Find the inner content of `<TAG ...attrMatch...>…</TAG>` inside `text`,
|
|
* handling nested same-tag elements via depth counting. `attrMatch` is a
|
|
* regex source fragment that must appear inside the opener tag.
|
|
* Returns the inner string (may be empty), or null if not found.
|
|
*/
|
|
function extractInnerByAttr(text, attrMatch) {
|
|
const openerRe = new RegExp('<([A-Za-z][A-Za-z0-9]*)\\b[^>]*' + attrMatch + '[^>]*>');
|
|
const openMatch = text.match(openerRe);
|
|
if (!openMatch) return null;
|
|
|
|
const tagName = openMatch[1];
|
|
const innerStart = openMatch.index + openMatch[0].length;
|
|
|
|
// Match any opener or closer of this tag name after innerStart.
|
|
// (Does not match self-closing <TAG … />, which doesn't contribute to depth.)
|
|
const tagRe = new RegExp('<(?:/)?' + tagName + '\\b[^>]*>', 'g');
|
|
tagRe.lastIndex = innerStart;
|
|
|
|
let depth = 1;
|
|
let m;
|
|
while ((m = tagRe.exec(text))) {
|
|
const isClose = m[0].startsWith('</');
|
|
const isSelfClose = !isClose && /\/\s*>$/.test(m[0]);
|
|
if (isClose) {
|
|
depth--;
|
|
if (depth === 0) return text.slice(innerStart, m.index);
|
|
} else if (!isSelfClose) {
|
|
depth++;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* Extract the original element content from within the variant wrapper.
|
|
* Returns an array of lines.
|
|
*/
|
|
function extractOriginal(lines, block) {
|
|
const text = stripStyleAndJoin(lines, block);
|
|
const inner = extractInnerByAttr(text, 'data-impeccable-variant="original"');
|
|
if (inner === null) return [];
|
|
return inner.split('\n');
|
|
}
|
|
|
|
/**
|
|
* Extract a specific variant's inner content (stripping the wrapper div).
|
|
* Returns an array of lines, or null if not found.
|
|
*/
|
|
function extractVariant(lines, block, variantNum) {
|
|
const text = stripStyleAndJoin(lines, block);
|
|
const inner = extractInnerByAttr(text, 'data-impeccable-variant="' + variantNum + '"');
|
|
if (inner === null) return null;
|
|
const result = inner.split('\n');
|
|
// Collapse a lone empty leading/trailing line (common after string splice).
|
|
while (result.length > 1 && result[0].trim() === '') result.shift();
|
|
while (result.length > 1 && result[result.length - 1].trim() === '') result.pop();
|
|
return result.length > 0 ? result : null;
|
|
}
|
|
|
|
/**
|
|
* Extract the colocated <style> block content (between the style tags).
|
|
* Returns an array of CSS lines, or null if no style block found.
|
|
*
|
|
* Handles three shapes of `<style data-impeccable-css="ID" ...>`:
|
|
* 1. Self-closing: `<style ... />` — no body; return null (nothing to carbonize).
|
|
* 2. Same-line open+close: `<style>...</style>` — return the inner content.
|
|
* 3. Multi-line: `<style>` on one line, `</style>` on a later line — return
|
|
* the lines between them.
|
|
*/
|
|
function extractCss(lines, block, id) {
|
|
const styleAttr = 'data-impeccable-css="' + id + '"';
|
|
let inStyle = false;
|
|
const content = [];
|
|
|
|
for (let i = block.start; i <= block.end; i++) {
|
|
const line = lines[i];
|
|
|
|
if (!inStyle && line.includes(styleAttr)) {
|
|
// Self-closing: nothing to carbonize.
|
|
if (/<style\b[^>]*\/\s*>/.test(line)) return null;
|
|
// Same-line open + close: extract inner text.
|
|
const sameLine = line.match(/<style\b[^>]*>([\s\S]*?)<\/style\s*>/);
|
|
if (sameLine) {
|
|
const inner = stripJsxTemplateWrap(sameLine[1]);
|
|
return inner.length > 0 ? inner.split('\n') : null;
|
|
}
|
|
inStyle = true;
|
|
continue; // skip the <style> opening tag
|
|
}
|
|
|
|
if (inStyle) {
|
|
// Detect </style> anywhere on the line — JSX template-literal closes
|
|
// (`}</style>`) put the close mid-line, and we don't want to absorb the
|
|
// template-literal punctuation as CSS content.
|
|
const closeIdx = line.indexOf('</style>');
|
|
if (closeIdx !== -1) break;
|
|
content.push(line);
|
|
}
|
|
}
|
|
|
|
if (content.length === 0) return null;
|
|
return stripJsxTemplateLines(content);
|
|
}
|
|
|
|
/**
|
|
* Strip a JSX template-literal wrap (`{` … `}`) from CSS extracted out of a
|
|
* `<style>` element in a JSX/TSX file. The agent may write the wrap with
|
|
* `{` and `}` directly attached to the `<style>` tags, on their own lines,
|
|
* or attached to the first/last CSS lines — all three are JSX-legal.
|
|
*
|
|
* Stripping is required because handleAccept re-wraps the CSS itself when
|
|
* carbonizing. Without this, two consecutive accepts (or a previously-
|
|
* accepted variants block being carbonized) would produce nested
|
|
* `{` `{` … `}` `}`, which oxc rejects with "Expected `}` but found `@`".
|
|
*/
|
|
function stripJsxTemplateLines(content) {
|
|
const out = content.slice();
|
|
|
|
// Drop any leading blank lines so we don't miss a `{` line buried below
|
|
// them; same for trailing.
|
|
while (out.length > 0 && out[0].trim() === '') out.shift();
|
|
while (out.length > 0 && out[out.length - 1].trim() === '') out.pop();
|
|
if (out.length === 0) return null;
|
|
|
|
// Leading `{`: own line, or attached to the first CSS line.
|
|
const firstTrim = out[0].trimStart();
|
|
if (firstTrim === '{`') {
|
|
out.shift();
|
|
} else if (firstTrim.startsWith('{`')) {
|
|
const idx = out[0].indexOf('{`');
|
|
out[0] = out[0].slice(0, idx) + out[0].slice(idx + 2);
|
|
if (out[0].trim() === '') out.shift();
|
|
}
|
|
if (out.length === 0) return null;
|
|
|
|
// Trailing `` ` `` `}`: own line, or attached to the last CSS line.
|
|
const lastIdx = out.length - 1;
|
|
const lastTrim = out[lastIdx].trimEnd();
|
|
if (lastTrim === '`}') {
|
|
out.pop();
|
|
} else if (lastTrim.endsWith('`}')) {
|
|
const text = out[lastIdx];
|
|
const idx = text.lastIndexOf('`}');
|
|
out[lastIdx] = text.slice(0, idx) + text.slice(idx + 2);
|
|
if (out[lastIdx].trim() === '') out.pop();
|
|
}
|
|
|
|
return out.length > 0 ? out : null;
|
|
}
|
|
|
|
function stripJsxTemplateWrap(text) {
|
|
const lines = text.split('\n');
|
|
const stripped = stripJsxTemplateLines(lines);
|
|
return stripped ? stripped.join('\n') : '';
|
|
}
|
|
|
|
/**
|
|
* De-indent content that was indented by live-wrap.mjs.
|
|
* The wrap script adds `indent + ' '` (4 extra spaces) to each line.
|
|
* We restore to just `indent` level.
|
|
*/
|
|
function deindentContent(contentLines, baseIndent) {
|
|
// Find the minimum indentation in the content to determine how much was added
|
|
let minIndent = Infinity;
|
|
for (const line of contentLines) {
|
|
if (line.trim() === '') continue;
|
|
const leadingSpaces = line.match(/^(\s*)/)[1].length;
|
|
minIndent = Math.min(minIndent, leadingSpaces);
|
|
}
|
|
if (minIndent === Infinity) minIndent = 0;
|
|
|
|
// Strip the extra indentation and re-add base indent
|
|
return contentLines.map(line => {
|
|
if (line.trim() === '') return '';
|
|
return baseIndent + line.slice(minIndent);
|
|
});
|
|
}
|
|
|
|
function detectCommentSyntax(filePath) {
|
|
const ext = path.extname(filePath).toLowerCase();
|
|
if (ext === '.jsx' || ext === '.tsx') {
|
|
return { open: '{/*', close: '*/}' };
|
|
}
|
|
return { open: '<!--', close: '-->' };
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// File search (find the file containing session markers)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function findSessionFile(id, cwd) {
|
|
const marker = 'impeccable-variants-start ' + id;
|
|
const searchDirs = ['src', 'app', 'pages', 'components', 'public', 'views', 'templates', '.'];
|
|
const seen = new Set();
|
|
|
|
for (const dir of searchDirs) {
|
|
const absDir = path.join(cwd, dir);
|
|
if (!fs.existsSync(absDir)) continue;
|
|
const result = searchDir(absDir, marker, seen, 0);
|
|
if (result) {
|
|
const content = fs.readFileSync(result, 'utf-8');
|
|
return { file: result, content, lines: content.split('\n') };
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function searchDir(dir, query, seen, depth) {
|
|
if (depth > 5) return null;
|
|
let realDir;
|
|
try { realDir = fs.realpathSync(dir); } catch { return null; }
|
|
if (seen.has(realDir)) return null;
|
|
seen.add(realDir);
|
|
|
|
let entries;
|
|
try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
|
|
catch { return null; }
|
|
|
|
for (const entry of entries) {
|
|
if (!entry.isFile()) continue;
|
|
if (!EXTENSIONS.includes(path.extname(entry.name).toLowerCase())) continue;
|
|
const filePath = path.join(dir, entry.name);
|
|
try {
|
|
const content = fs.readFileSync(filePath, 'utf-8');
|
|
if (content.includes(query)) return filePath;
|
|
} catch { /* skip */ }
|
|
}
|
|
|
|
for (const entry of entries) {
|
|
if (!entry.isDirectory()) continue;
|
|
if (['node_modules', '.git', 'dist', 'build'].includes(entry.name)) continue;
|
|
const result = searchDir(path.join(dir, entry.name), query, seen, depth + 1);
|
|
if (result) return result;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Utilities
|
|
// ---------------------------------------------------------------------------
|
|
|
|
function argVal(args, flag) {
|
|
const idx = args.indexOf(flag);
|
|
return idx !== -1 && idx + 1 < args.length ? args[idx + 1] : null;
|
|
}
|
|
|
|
// Auto-execute when run directly
|
|
const _running = process.argv[1];
|
|
if (_running?.endsWith('live-accept.mjs') || _running?.endsWith('live-accept.mjs/')) {
|
|
acceptCli();
|
|
}
|
|
|
|
export { findMarkerBlock, extractOriginal, extractVariant, extractCss, deindentContent, detectCommentSyntax, scrubManualEditsAgainstFile, scrubManualEditsAgainstOriginalBlock };
|