impeccable project-wide
This commit is contained in:
@@ -0,0 +1,842 @@
|
||||
// Parse a DESIGN.md (Stitch-spec format) into a structured JSON model that
|
||||
// the live-mode design-system panel can render. Deterministic, dependency-free.
|
||||
//
|
||||
// Two-layer: YAML frontmatter (machine-readable tokens) + markdown body
|
||||
// (prose with six canonical H2 sections). When frontmatter is present, it's
|
||||
// exposed on `model.frontmatter` alongside the prose-scraped sections;
|
||||
// consumers can prefer frontmatter values and fall back to prose.
|
||||
|
||||
const CANONICAL_SECTIONS = [
|
||||
'Overview',
|
||||
'Colors',
|
||||
'Typography',
|
||||
'Elevation',
|
||||
'Components',
|
||||
"Do's and Don'ts",
|
||||
];
|
||||
|
||||
// ---------- Frontmatter (Stitch YAML subset) ----------
|
||||
|
||||
function parseFrontmatter(md) {
|
||||
const lines = md.split(/\r?\n/);
|
||||
if (lines[0]?.trim() !== '---') return { frontmatter: null, body: md };
|
||||
|
||||
let end = -1;
|
||||
for (let i = 1; i < lines.length; i++) {
|
||||
if (lines[i].trim() === '---') { end = i; break; }
|
||||
}
|
||||
if (end === -1) return { frontmatter: null, body: md };
|
||||
|
||||
const yaml = lines.slice(1, end).join('\n');
|
||||
const body = lines.slice(end + 1).join('\n');
|
||||
try {
|
||||
return { frontmatter: parseYamlSubset(yaml), body };
|
||||
} catch {
|
||||
return { frontmatter: null, body: md };
|
||||
}
|
||||
}
|
||||
|
||||
// Minimal YAML reader for the Stitch frontmatter subset: scalar maps with
|
||||
// one level of nested objects (typography roles, components). Indent-based,
|
||||
// 2-space convention. No arrays, no anchors, no multi-line scalars — Stitch's
|
||||
// schema doesn't need them and accepting them would require a real YAML
|
||||
// dependency we don't want to vendor.
|
||||
function parseYamlSubset(yaml) {
|
||||
const lines = yaml.split(/\r?\n/);
|
||||
const root = {};
|
||||
const stack = [{ indent: -1, obj: root }];
|
||||
|
||||
for (const raw of lines) {
|
||||
// Skip blanks and line-only comments. Don't strip inline comments:
|
||||
// unquoted hex values start with `#` and can't be safely distinguished
|
||||
// from a comment after whitespace.
|
||||
if (!raw.trim() || /^\s*#/.test(raw)) continue;
|
||||
|
||||
const indent = raw.match(/^\s*/)[0].length;
|
||||
const content = raw.slice(indent);
|
||||
|
||||
const colonIdx = findTopLevelColon(content);
|
||||
if (colonIdx === -1) continue;
|
||||
|
||||
while (stack.length > 1 && stack[stack.length - 1].indent >= indent) {
|
||||
stack.pop();
|
||||
}
|
||||
|
||||
const key = unquoteYamlKey(content.slice(0, colonIdx).trim());
|
||||
const rest = stripInlineYamlComment(content.slice(colonIdx + 1).trim());
|
||||
const parent = stack[stack.length - 1].obj;
|
||||
|
||||
if (rest === '') {
|
||||
const obj = {};
|
||||
parent[key] = obj;
|
||||
stack.push({ indent, obj });
|
||||
} else {
|
||||
parent[key] = parseScalar(rest);
|
||||
}
|
||||
}
|
||||
|
||||
return root;
|
||||
}
|
||||
|
||||
function findTopLevelColon(s) {
|
||||
let inQuote = null;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const ch = s[i];
|
||||
if (inQuote) {
|
||||
if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
|
||||
} else if (ch === '"' || ch === "'") {
|
||||
inQuote = ch;
|
||||
} else if (ch === ':') {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function unquoteYamlKey(key) {
|
||||
if ((key.startsWith('"') && key.endsWith('"')) || (key.startsWith("'") && key.endsWith("'"))) {
|
||||
return key.slice(1, -1);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
function stripInlineYamlComment(s) {
|
||||
let inQuote = null;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const ch = s[i];
|
||||
if (inQuote) {
|
||||
if (ch === inQuote && s[i - 1] !== '\\') inQuote = null;
|
||||
} else if (ch === '"' || ch === "'") {
|
||||
inQuote = ch;
|
||||
} else if (ch === '#' && i > 0 && /\s/.test(s[i - 1])) {
|
||||
return s.slice(0, i).trimEnd();
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
function parseScalar(raw) {
|
||||
const s = raw.trim();
|
||||
if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
|
||||
return s.slice(1, -1);
|
||||
}
|
||||
if (s === 'true') return true;
|
||||
if (s === 'false') return false;
|
||||
if (s === 'null' || s === '~') return null;
|
||||
if (/^-?\d+$/.test(s)) return Number(s);
|
||||
if (/^-?\d*\.\d+$/.test(s)) return Number(s);
|
||||
return s;
|
||||
}
|
||||
|
||||
const HEX_RE = /#[0-9a-fA-F]{3,8}\b/g;
|
||||
const OKLCH_RE = /oklch\([^)]+\)/gi;
|
||||
const RGBA_RE = /rgba?\([^)]+\)/gi;
|
||||
const BOX_SHADOW_RE = /(?:box-shadow:\s*)?((?:-?\d[\w\d\s\-.,/()#%]*)+)/;
|
||||
const NAMED_RULE_RE = /\*\*(The [^*]+?Rule)\.\*\*\s*(.+)/;
|
||||
|
||||
// ---------- Section splitting ----------
|
||||
|
||||
function splitSections(md) {
|
||||
const lines = md.split(/\r?\n/);
|
||||
let title = null;
|
||||
const sections = {};
|
||||
let current = null;
|
||||
|
||||
for (const raw of lines) {
|
||||
const line = raw.trimEnd();
|
||||
|
||||
if (!title && line.startsWith('# ') && !line.startsWith('## ')) {
|
||||
title = line.replace(/^#\s+/, '').trim();
|
||||
continue;
|
||||
}
|
||||
|
||||
const h2 = line.match(/^##\s+(?:\d+\.\s*)?([^:\n]+?)(?::\s*(.+))?$/);
|
||||
if (h2) {
|
||||
const rawName = normalizeApostrophes(h2[1].trim());
|
||||
const subtitle = h2[2] ? h2[2].trim() : null;
|
||||
const canonical = matchCanonicalSection(rawName);
|
||||
if (canonical) {
|
||||
current = { name: canonical, subtitle, lines: [] };
|
||||
sections[canonical] = current;
|
||||
continue;
|
||||
}
|
||||
// non-canonical H2 — ignore but stop feeding into current
|
||||
current = null;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (current) current.lines.push(raw);
|
||||
}
|
||||
|
||||
return { title, sections };
|
||||
}
|
||||
|
||||
function normalizeApostrophes(s) {
|
||||
return s.replace(/[\u2018\u2019]/g, "'");
|
||||
}
|
||||
|
||||
function matchCanonicalSection(name) {
|
||||
const normalized = normalizeApostrophes(name).toLowerCase();
|
||||
// Exact match first
|
||||
for (const c of CANONICAL_SECTIONS) {
|
||||
if (normalizeApostrophes(c).toLowerCase() === normalized) return c;
|
||||
}
|
||||
// Keyword-contained match: "Overview & Creative North Star" -> "Overview",
|
||||
// "Elevation & Depth" -> "Elevation", etc.
|
||||
for (const c of CANONICAL_SECTIONS) {
|
||||
const key = normalizeApostrophes(c).toLowerCase();
|
||||
const pattern = new RegExp(`\\b${key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`);
|
||||
if (pattern.test(normalized)) return c;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ---------- Subsection splitting (inside a canonical section) ----------
|
||||
|
||||
function splitSubsections(lines) {
|
||||
const subs = [];
|
||||
let current = { name: null, lines: [] };
|
||||
subs.push(current);
|
||||
|
||||
for (const raw of lines) {
|
||||
const h3 = raw.match(/^###\s+(.+?)\s*$/);
|
||||
if (h3) {
|
||||
current = { name: h3[1].trim(), lines: [] };
|
||||
subs.push(current);
|
||||
continue;
|
||||
}
|
||||
current.lines.push(raw);
|
||||
}
|
||||
|
||||
return subs;
|
||||
}
|
||||
|
||||
// ---------- Generic helpers ----------
|
||||
|
||||
function collectParagraphs(lines) {
|
||||
const paragraphs = [];
|
||||
let buf = [];
|
||||
const flush = () => {
|
||||
if (buf.length) {
|
||||
paragraphs.push(buf.join(' ').trim());
|
||||
buf = [];
|
||||
}
|
||||
};
|
||||
for (const raw of lines) {
|
||||
const trimmed = raw.trim();
|
||||
if (trimmed === '') { flush(); continue; }
|
||||
// Horizontal rules (---, ***) and headings/bullets end a paragraph.
|
||||
if (/^(?:-{3,}|\*{3,}|_{3,})$/.test(trimmed)) { flush(); continue; }
|
||||
if (raw.startsWith('#') || raw.match(/^[-*]\s/)) { flush(); continue; }
|
||||
buf.push(trimmed);
|
||||
}
|
||||
flush();
|
||||
return paragraphs.filter(Boolean);
|
||||
}
|
||||
|
||||
function collectBullets(lines) {
|
||||
const bullets = [];
|
||||
let current = null;
|
||||
for (const raw of lines) {
|
||||
const m = raw.match(/^\s*[-*]\s+(.+)$/);
|
||||
if (m) {
|
||||
if (current) bullets.push(current);
|
||||
current = m[1];
|
||||
continue;
|
||||
}
|
||||
// continuation of a bullet (indented line)
|
||||
if (current && raw.match(/^\s{2,}\S/)) {
|
||||
current += ' ' + raw.trim();
|
||||
continue;
|
||||
}
|
||||
// blank line ends a bullet
|
||||
if (raw.trim() === '' && current) {
|
||||
bullets.push(current);
|
||||
current = null;
|
||||
}
|
||||
}
|
||||
if (current) bullets.push(current);
|
||||
return bullets;
|
||||
}
|
||||
|
||||
function stripBold(s) {
|
||||
return s.replace(/\*\*(.+?)\*\*/g, '$1');
|
||||
}
|
||||
|
||||
function extractNamedRules(lines) {
|
||||
const rules = [];
|
||||
const seen = new Set();
|
||||
|
||||
// Style A (Impeccable): "**The X Rule.** body body body" — can span lines.
|
||||
const joined = lines.join('\n');
|
||||
const inlineStart = /\*\*(The [^*]+?Rule)\.\*\*/g;
|
||||
const inlineMatches = [];
|
||||
let m;
|
||||
while ((m = inlineStart.exec(joined)) !== null) {
|
||||
inlineMatches.push({ name: m[1], start: m.index, end: inlineStart.lastIndex });
|
||||
}
|
||||
for (let i = 0; i < inlineMatches.length; i++) {
|
||||
const mm = inlineMatches[i];
|
||||
const bodyEnd = i + 1 < inlineMatches.length ? inlineMatches[i + 1].start : joined.length;
|
||||
const body = joined
|
||||
.slice(mm.end, bodyEnd)
|
||||
.replace(/\n##[^\n]*$/s, '')
|
||||
.replace(/\n###[^\n]*$/s, '')
|
||||
.trim();
|
||||
const name = stripBold(mm.name).trim();
|
||||
seen.add(name.toLowerCase());
|
||||
rules.push({ name, body: stripBold(body) });
|
||||
}
|
||||
|
||||
// Style B (Stitch): `### The "X" Rule` or `### The X Fallback`, body is the
|
||||
// bullets/paragraphs until the next heading. Accept Rule / Fallback / Principle.
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const h3 = lines[i].match(/^###\s+(.+?)\s*$/);
|
||||
if (!h3) continue;
|
||||
const headerName = stripBold(h3[1]).replace(/["“”]/g, '').trim();
|
||||
if (!/^The\b.*\b(Rule|Fallback|Principle)\b/i.test(headerName)) continue;
|
||||
if (seen.has(headerName.toLowerCase())) continue;
|
||||
|
||||
const bodyLines = [];
|
||||
for (let j = i + 1; j < lines.length; j++) {
|
||||
if (/^##\s|^###\s/.test(lines[j])) break;
|
||||
bodyLines.push(lines[j]);
|
||||
}
|
||||
const body = stripBold(bodyLines.join('\n').replace(/\n+/g, ' ')).trim();
|
||||
if (body) {
|
||||
seen.add(headerName.toLowerCase());
|
||||
rules.push({ name: headerName, body });
|
||||
}
|
||||
}
|
||||
|
||||
// Style C (Stitch bullet form): "* **The Layering Principle:** body"
|
||||
// Colon/period lives inside the bold, so match "**...**" then inspect.
|
||||
for (const b of collectBullets(lines)) {
|
||||
const mm = b.match(/^\*\*([^*]+?)\*\*\s*(.+)$/);
|
||||
if (!mm) continue;
|
||||
const nameRaw = mm[1].replace(/[.:]\s*$/, '').replace(/["“”]/g, '').trim();
|
||||
if (!/^The\b.+\b(Rule|Fallback|Principle)$/i.test(nameRaw)) continue;
|
||||
if (seen.has(nameRaw.toLowerCase())) continue;
|
||||
seen.add(nameRaw.toLowerCase());
|
||||
rules.push({ name: nameRaw, body: stripBold(mm[2]).trim() });
|
||||
}
|
||||
|
||||
return rules;
|
||||
}
|
||||
|
||||
// ---------- Per-section extractors ----------
|
||||
|
||||
function extractOverview(section) {
|
||||
if (!section) return null;
|
||||
const text = section.lines.join('\n');
|
||||
const northStar = text.match(/\*\*Creative North Star:\s*"([^"]+)"\*\*/);
|
||||
const keyChars = [];
|
||||
const keyCharMatch = text.match(/\*\*Key Characteristics:\*\*\s*\n([\s\S]+?)(?:\n##|\n###|$)/);
|
||||
if (keyCharMatch) {
|
||||
for (const line of keyCharMatch[1].split('\n')) {
|
||||
const m = line.match(/^\s*[-*]\s+(.+)$/);
|
||||
if (m) keyChars.push(stripBold(m[1].trim()));
|
||||
}
|
||||
}
|
||||
|
||||
// Philosophy paragraphs: everything that isn't a rule header or key-char block
|
||||
const paragraphs = collectParagraphs(section.lines).filter(
|
||||
(p) =>
|
||||
!p.startsWith('**Creative North Star') &&
|
||||
!p.startsWith('**Key Characteristics')
|
||||
);
|
||||
|
||||
return {
|
||||
subtitle: section.subtitle,
|
||||
creativeNorthStar: northStar ? northStar[1] : null,
|
||||
philosophy: paragraphs,
|
||||
keyCharacteristics: keyChars,
|
||||
};
|
||||
}
|
||||
|
||||
function extractColors(section) {
|
||||
if (!section) return null;
|
||||
const subs = splitSubsections(section.lines);
|
||||
|
||||
const description = collectParagraphs(subs[0].lines).join(' ');
|
||||
const groups = [];
|
||||
const ROLE_KEYWORDS = /^(primary|secondary|tertiary|neutral|accent)\b/i;
|
||||
|
||||
for (const sub of subs.slice(1)) {
|
||||
if (!sub.name || /Named Rules?/i.test(sub.name) || /^The\s/i.test(sub.name)) continue;
|
||||
|
||||
const bullets = collectBullets(sub.lines);
|
||||
const parsed = bullets.map((b) => parseColorBullet(b)).filter(Boolean);
|
||||
if (parsed.length === 0) continue;
|
||||
|
||||
// If every bullet starts with a role keyword (Primary/Secondary/...), promote
|
||||
// each bullet to its own group. Otherwise keep the subsection as the group.
|
||||
const allRoleBullets =
|
||||
parsed.length > 0 && parsed.every((p) => p.name && ROLE_KEYWORDS.test(p.name));
|
||||
|
||||
if (allRoleBullets) {
|
||||
for (const p of parsed) {
|
||||
groups.push({ role: p.name, colors: [p] });
|
||||
}
|
||||
} else {
|
||||
groups.push({ role: sub.name, colors: parsed });
|
||||
}
|
||||
}
|
||||
|
||||
// If the Colors section has no subsections at all (unlikely), fall back to
|
||||
// scanning the whole section as a flat bullet list.
|
||||
if (groups.length === 0) {
|
||||
const flat = collectBullets(section.lines)
|
||||
.map((b) => parseColorBullet(b))
|
||||
.filter(Boolean);
|
||||
if (flat.length) {
|
||||
for (const p of flat) {
|
||||
if (p.name && ROLE_KEYWORDS.test(p.name)) {
|
||||
groups.push({ role: p.name, colors: [p] });
|
||||
} else {
|
||||
const fallback = groups.find((g) => g.role === 'Palette');
|
||||
if (fallback) fallback.colors.push(p);
|
||||
else groups.push({ role: 'Palette', colors: [p] });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
subtitle: section.subtitle,
|
||||
description: description || null,
|
||||
groups,
|
||||
rules: extractNamedRules(section.lines),
|
||||
};
|
||||
}
|
||||
|
||||
function parseColorBullet(bullet) {
|
||||
const text = bullet.trim();
|
||||
|
||||
// Case 1 (Impeccable): **Name** (value-with-maybe-nested-parens): description
|
||||
const bold = text.match(/^\*\*(.+?)\*\*\s*(.*)$/);
|
||||
if (bold && bold[2].startsWith('(')) {
|
||||
const value = extractParenGroup(bold[2]);
|
||||
if (value !== null) {
|
||||
const after = bold[2].slice(value.length + 2).trimStart();
|
||||
if (after.startsWith(':')) {
|
||||
return buildColor(bold[1], value, after.slice(1).trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Case 2 (Stitch): **Name (values):** description — value embedded in bold.
|
||||
const stitch = text.match(/^\*\*([^*]+?)\s*\(([^)]+)\):\*\*\s*(.*)$/);
|
||||
if (stitch) {
|
||||
return buildColor(stitch[1].trim(), stitch[2], stitch[3]);
|
||||
}
|
||||
|
||||
// Case 3: bullet without bold, just hex/oklch inside.
|
||||
const values = collectColorValues(text);
|
||||
if (values.length) {
|
||||
return buildColor(null, values.join(' to '), text);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function extractParenGroup(s) {
|
||||
if (s[0] !== '(') return null;
|
||||
let depth = 0;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
if (s[i] === '(') depth++;
|
||||
else if (s[i] === ')') {
|
||||
depth--;
|
||||
if (depth === 0) return s.slice(1, i);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildColor(name, rawValue, description) {
|
||||
const values = collectColorValues(rawValue);
|
||||
const primary = values[0] ?? rawValue.trim();
|
||||
return {
|
||||
name: name ? stripBold(name).trim() : null,
|
||||
value: primary,
|
||||
valueRange: values.length > 1 ? values : null,
|
||||
format: detectFormat(primary),
|
||||
description: stripBold(description || '').trim() || null,
|
||||
};
|
||||
}
|
||||
|
||||
function collectColorValues(s) {
|
||||
const out = [];
|
||||
s.replace(HEX_RE, (v) => {
|
||||
out.push(v);
|
||||
return v;
|
||||
});
|
||||
s.replace(OKLCH_RE, (v) => {
|
||||
out.push(v);
|
||||
return v;
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
function detectFormat(v) {
|
||||
if (!v) return 'unknown';
|
||||
if (v.startsWith('#')) return 'hex';
|
||||
if (/^oklch/i.test(v)) return 'oklch';
|
||||
if (/^rgb/i.test(v)) return 'rgb';
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
function scanInlineColors(lines) {
|
||||
const out = [];
|
||||
for (const line of lines) {
|
||||
if (!/^\s*[-*]\s/.test(line)) continue;
|
||||
const trimmed = line.replace(/^\s*[-*]\s+/, '');
|
||||
const color = parseColorBullet(trimmed);
|
||||
if (color) out.push(color);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function parseStitchInlineGroups(lines) {
|
||||
// Stitch writes: `* **Primary (`#00478d` to `#005eb8`):** Use for "..."`
|
||||
// Each bullet IS its own role. Group them under the spoken role name.
|
||||
const out = [];
|
||||
for (const line of lines) {
|
||||
if (!/^\s*[-*]\s/.test(line)) continue;
|
||||
const trimmed = line.replace(/^\s*[-*]\s+/, '').trim();
|
||||
const m = trimmed.match(
|
||||
/^\*\*([A-Z][a-zA-Z]+)\s*\(([^)]+)\):\*\*\s*(.*)$/
|
||||
);
|
||||
if (m) {
|
||||
const role = m[1];
|
||||
const color = buildColor(role, m[2], m[3]);
|
||||
out.push({ role, colors: [color] });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function extractTypography(section) {
|
||||
if (!section) return null;
|
||||
const text = section.lines.join('\n');
|
||||
|
||||
const fonts = {};
|
||||
// Pattern A: **Display Font:** Family (with fallback)
|
||||
const fontLineRe = /\*\*([\w\s/]+?)Font:\*\*\s*([^\n(]+?)(?:\s*\(with\s+([^)]+)\))?\s*$/gm;
|
||||
let fm;
|
||||
while ((fm = fontLineRe.exec(text)) !== null) {
|
||||
const rawRole = fm[1].trim().toLowerCase().replace(/\s+/g, '-');
|
||||
const role = normalizeFontRole(rawRole) || 'display';
|
||||
fonts[role] = {
|
||||
family: fm[2].trim(),
|
||||
fallback: fm[3] ? fm[3].trim() : null,
|
||||
};
|
||||
}
|
||||
|
||||
// Pattern B (Stitch): * **Display & Headlines (Noto Serif):** description
|
||||
if (Object.keys(fonts).length === 0) {
|
||||
const stitchRe = /\*\*([\w\s&/]+?)\s*\(([^)]+)\):\*\*\s*(.+)/g;
|
||||
let sm;
|
||||
while ((sm = stitchRe.exec(text)) !== null) {
|
||||
const rawRole = sm[1]
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/\s*&\s*/g, '-')
|
||||
.replace(/\s+/g, '-');
|
||||
const role = normalizeFontRole(rawRole) || rawRole;
|
||||
fonts[role] = { family: sm[2].trim(), fallback: null, purpose: sm[3].trim() };
|
||||
}
|
||||
}
|
||||
|
||||
// Character paragraph — either a **Character:** label, or fall back to the
|
||||
// first free paragraph under the section header (Stitch style).
|
||||
const characterMatch = text.match(/\*\*Character:\*\*\s*([^\n]+(?:\n[^\n]+)*?)(?=\n\n|\n###|\n##|$)/);
|
||||
let character = characterMatch ? characterMatch[1].replace(/\n/g, ' ').trim() : null;
|
||||
if (!character) {
|
||||
const paragraphs = collectParagraphs(section.lines).filter(
|
||||
(p) => !/^\*\*[\w\s/&]+Font/i.test(p) && !/^\*\*[\w\s/&]+\([^)]+\)/.test(p)
|
||||
);
|
||||
if (paragraphs.length) character = paragraphs[0];
|
||||
}
|
||||
|
||||
// Hierarchy bullets under ### Hierarchy
|
||||
const subs = splitSubsections(section.lines);
|
||||
let hierarchy = [];
|
||||
const hierSub = subs.find((s) => s.name && /hierarch/i.test(s.name));
|
||||
if (hierSub) {
|
||||
const bullets = collectBullets(hierSub.lines);
|
||||
hierarchy = bullets.map(parseTypeBullet).filter(Boolean);
|
||||
}
|
||||
|
||||
return {
|
||||
subtitle: section.subtitle,
|
||||
fonts,
|
||||
character,
|
||||
hierarchy,
|
||||
rules: extractNamedRules(section.lines),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeFontRole(raw) {
|
||||
// Canonical roles the panel cares about: display, body, label, mono.
|
||||
// Stitch often writes compound roles like "display-&-headlines" or "ui-&-body"
|
||||
// — collapse them to the first canonical role present.
|
||||
const tokens = raw.split(/[-/&\s]+/).filter(Boolean);
|
||||
const priority = ['display', 'headline', 'body', 'ui', 'label', 'mono'];
|
||||
const canonical = { headline: 'display', ui: 'body' };
|
||||
for (const p of priority) {
|
||||
if (tokens.includes(p)) return canonical[p] || p;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseTypeBullet(bullet) {
|
||||
// - **Display** (family, weight 300, italic, clamp(...), line-height 1): purpose
|
||||
const m = bullet.match(/^\*\*(.+?)\*\*\s*\(([^)]+)\):\s*(.*)$/);
|
||||
if (!m) return null;
|
||||
const name = m[1].trim();
|
||||
const specs = m[2].split(',').map((s) => s.trim());
|
||||
return {
|
||||
name,
|
||||
specs,
|
||||
purpose: stripBold(m[3] || '').trim() || null,
|
||||
};
|
||||
}
|
||||
|
||||
function extractElevation(section) {
|
||||
if (!section) return null;
|
||||
const subs = splitSubsections(section.lines);
|
||||
|
||||
const description = collectParagraphs(subs[0].lines).join(' ') || null;
|
||||
|
||||
const shadows = [];
|
||||
const seen = new Set();
|
||||
const dedupe = (entry) => {
|
||||
const key = (entry.name || '') + '::' + entry.value;
|
||||
if (seen.has(key)) return;
|
||||
seen.add(key);
|
||||
shadows.push(entry);
|
||||
};
|
||||
|
||||
for (const b of collectBullets(section.lines)) {
|
||||
const parsed = parseShadowBullet(b);
|
||||
if (parsed) dedupe(parsed);
|
||||
}
|
||||
|
||||
// Fallback: extract shadows written inline in prose. Stitch style is
|
||||
// "...use an extra-diffused shadow: `box-shadow: 0 12px 40px rgba(...)`."
|
||||
for (const p of collectParagraphs(section.lines)) {
|
||||
for (const inline of extractInlineShadows(p)) dedupe(inline);
|
||||
}
|
||||
for (const b of collectBullets(section.lines)) {
|
||||
for (const inline of extractInlineShadows(b)) dedupe(inline);
|
||||
}
|
||||
|
||||
return {
|
||||
subtitle: section.subtitle,
|
||||
description,
|
||||
shadows,
|
||||
rules: extractNamedRules(section.lines),
|
||||
};
|
||||
}
|
||||
|
||||
function extractInlineShadows(text) {
|
||||
// Find `box-shadow: ...` anywhere in prose and capture the value. Work on the
|
||||
// raw string so it handles both backtick-fenced and unfenced variants.
|
||||
const out = [];
|
||||
const re = /box-shadow\s*:\s*([^`;\n]+)/gi;
|
||||
let m;
|
||||
while ((m = re.exec(text)) !== null) {
|
||||
const value = m[1].replace(/[`.)]+$/, '').trim();
|
||||
if (!value) continue;
|
||||
// Name heuristic: the noun immediately before the shadow phrase.
|
||||
// e.g. "an extra-diffused shadow: ..." -> "extra-diffused shadow"
|
||||
const before = text.slice(0, m.index);
|
||||
const nameMatch = before.match(/\b([A-Za-z][A-Za-z\- ]{2,40})\s+shadow\b[^A-Za-z0-9]*$/i);
|
||||
let name = null;
|
||||
if (nameMatch) {
|
||||
const stripped = nameMatch[1]
|
||||
.replace(/^(?:use|using|apply|applying|is|are|looks? like)\s+/i, '')
|
||||
.replace(/^(?:a|an|the)\s+/i, '')
|
||||
.trim();
|
||||
if (stripped) {
|
||||
name =
|
||||
stripped.charAt(0).toUpperCase() + stripped.slice(1) + ' shadow';
|
||||
}
|
||||
}
|
||||
out.push({
|
||||
name,
|
||||
value,
|
||||
purpose: null,
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function parseShadowBullet(bullet) {
|
||||
// - **Name** (`box-shadow: value`): purpose
|
||||
// - **Name** (`value`): purpose
|
||||
// Only accept if the paren content looks like a shadow value (contains px,
|
||||
// rem, rgba, or box-shadow). This filters out `**Rule Name:**` bullets.
|
||||
const m = bullet.match(/^\*\*(.+?)\*\*\s*\(`?([^`]+?)`?\):\s*(.*)$/);
|
||||
if (!m) return null;
|
||||
const rawValue = m[2].replace(/^box-shadow:\s*/i, '').trim();
|
||||
const looksLikeShadow =
|
||||
/box-shadow|rgba?\(|\bpx\b|\brem\b|^-?\d+\s/i.test(rawValue) &&
|
||||
/\d/.test(rawValue);
|
||||
if (!looksLikeShadow) return null;
|
||||
const name = stripBold(m[1]).trim();
|
||||
return {
|
||||
name,
|
||||
value: rawValue,
|
||||
purpose: stripBold(m[3] || '').trim() || null,
|
||||
};
|
||||
}
|
||||
|
||||
function extractComponents(section) {
|
||||
if (!section) return null;
|
||||
const subs = splitSubsections(section.lines);
|
||||
const components = [];
|
||||
|
||||
for (const sub of subs.slice(1)) {
|
||||
if (!sub.name) continue;
|
||||
|
||||
const bullets = collectBullets(sub.lines);
|
||||
const paragraphs = collectParagraphs(sub.lines);
|
||||
|
||||
const variants = [];
|
||||
const properties = {};
|
||||
|
||||
for (const b of bullets) {
|
||||
// - **Key:** value
|
||||
const m = b.match(/^\*\*(.+?):?\*\*:?\s*(.+)$/);
|
||||
if (m) {
|
||||
const key = stripBold(m[1]).trim();
|
||||
const value = stripBold(m[2]).trim();
|
||||
// Heuristic: "Primary", "Secondary", "Hover", "Focus" etc are variants;
|
||||
// "Shape", "Background", "Padding" are properties.
|
||||
if (/^(primary|secondary|tertiary|ghost|hover|focus|active|disabled|default|error|selected|unselected|state)$/i.test(key.split(/[\s/]/)[0])) {
|
||||
variants.push({ name: key, description: value });
|
||||
} else {
|
||||
properties[key.toLowerCase()] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
components.push({
|
||||
name: sub.name,
|
||||
description: paragraphs.join(' ') || null,
|
||||
properties,
|
||||
variants,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
subtitle: section.subtitle,
|
||||
components,
|
||||
};
|
||||
}
|
||||
|
||||
function extractDosDonts(section) {
|
||||
if (!section) return null;
|
||||
const subs = splitSubsections(section.lines);
|
||||
const dos = [];
|
||||
const donts = [];
|
||||
|
||||
for (const sub of subs.slice(1)) {
|
||||
if (!sub.name) continue;
|
||||
const subName = normalizeApostrophes(sub.name);
|
||||
const bullets = collectBullets(sub.lines).map((b) => stripBold(b).trim());
|
||||
if (/^do'?t?:?$/i.test(subName) || /^do:?$/i.test(subName)) {
|
||||
dos.push(...bullets);
|
||||
} else if (/^don'?t:?$/i.test(subName)) {
|
||||
donts.push(...bullets);
|
||||
}
|
||||
}
|
||||
|
||||
// Classify by bullet prefix as a backup (catches loose bullets outside H3 wrappers)
|
||||
for (const b of collectBullets(section.lines)) {
|
||||
const stripped = normalizeApostrophes(stripBold(b).trim());
|
||||
if (/^don'?t\b/i.test(stripped)) {
|
||||
if (!donts.some((d) => normalizeApostrophes(d) === stripped)) donts.push(stripped);
|
||||
} else if (/^do\b/i.test(stripped)) {
|
||||
if (!dos.some((d) => normalizeApostrophes(d) === stripped)) dos.push(stripped);
|
||||
}
|
||||
}
|
||||
|
||||
return { dos, donts };
|
||||
}
|
||||
|
||||
// ---------- Coverage assessment ----------
|
||||
|
||||
function assessCoverage(model) {
|
||||
const report = {};
|
||||
|
||||
report.overview = model.overview
|
||||
? {
|
||||
northStar: Boolean(model.overview.creativeNorthStar),
|
||||
philosophy: model.overview.philosophy.length > 0,
|
||||
keyCharacteristics: model.overview.keyCharacteristics.length,
|
||||
}
|
||||
: 'missing';
|
||||
|
||||
report.colors = model.colors
|
||||
? {
|
||||
groups: model.colors.groups.length,
|
||||
totalColors: model.colors.groups.reduce((n, g) => n + g.colors.length, 0),
|
||||
rules: model.colors.rules.length,
|
||||
}
|
||||
: 'missing';
|
||||
|
||||
report.typography = model.typography
|
||||
? {
|
||||
fonts: Object.keys(model.typography.fonts).length,
|
||||
hierarchyEntries: model.typography.hierarchy.length,
|
||||
character: Boolean(model.typography.character),
|
||||
rules: model.typography.rules.length,
|
||||
}
|
||||
: 'missing';
|
||||
|
||||
report.elevation = model.elevation
|
||||
? {
|
||||
shadows: model.elevation.shadows.length,
|
||||
rules: model.elevation.rules.length,
|
||||
description: Boolean(model.elevation.description),
|
||||
}
|
||||
: 'missing';
|
||||
|
||||
report.components = model.components
|
||||
? {
|
||||
count: model.components.components.length,
|
||||
variantTotal: model.components.components.reduce((n, c) => n + c.variants.length, 0),
|
||||
}
|
||||
: 'missing';
|
||||
|
||||
report.dosDonts = model.dosDonts
|
||||
? {
|
||||
dos: model.dosDonts.dos.length,
|
||||
donts: model.dosDonts.donts.length,
|
||||
}
|
||||
: 'missing';
|
||||
|
||||
return report;
|
||||
}
|
||||
|
||||
// ---------- Main ----------
|
||||
|
||||
export function parseDesignMd(md) {
|
||||
const { frontmatter, body } = parseFrontmatter(md);
|
||||
const { title, sections } = splitSections(body);
|
||||
return {
|
||||
schemaVersion: 2,
|
||||
title,
|
||||
frontmatter,
|
||||
overview: extractOverview(sections['Overview']),
|
||||
colors: extractColors(sections['Colors']),
|
||||
typography: extractTypography(sections['Typography']),
|
||||
elevation: extractElevation(sections['Elevation']),
|
||||
components: extractComponents(sections['Components']),
|
||||
dosDonts: extractDosDonts(sections["Do's and Don'ts"]),
|
||||
};
|
||||
}
|
||||
|
||||
export { assessCoverage };
|
||||
@@ -0,0 +1,640 @@
|
||||
/**
|
||||
* CLI-side reader/writer for the unified `.impeccable` config.
|
||||
*
|
||||
* The CLI (published to npm) and the skill scripts (bundled into the install)
|
||||
* live in separate trees and cannot share runtime code, so this duplicates a
|
||||
* small slice of skill/scripts/hook-lib.mjs — the config-path layout, detector
|
||||
* ignore semantics, and the `.git/info/exclude` handling. Keep the schema,
|
||||
* ignore filtering, and exclude marker in sync if either side changes.
|
||||
*
|
||||
* Schema (config.json shared / config.local.json gitignored, per-developer):
|
||||
* {
|
||||
* "detector": { "ignoreRules": [], "ignoreFiles": [], "ignoreValues": [], "designSystem": { "enabled": true } },
|
||||
* "hook": { "consent": "accepted" | "declined", ... },
|
||||
* "updateCheck": bool
|
||||
* }
|
||||
*/
|
||||
|
||||
import { existsSync, readFileSync, writeFileSync, mkdirSync, statSync } from 'node:fs';
|
||||
import { join, dirname, isAbsolute, relative, resolve, sep } from 'node:path';
|
||||
|
||||
export function getConfigPath(root) {
|
||||
return join(root, '.impeccable', 'config.json');
|
||||
}
|
||||
|
||||
export function getLocalConfigPath(root) {
|
||||
return join(root, '.impeccable', 'config.local.json');
|
||||
}
|
||||
|
||||
function safeReadJson(filePath) {
|
||||
try {
|
||||
const raw = JSON.parse(readFileSync(filePath, 'utf-8'));
|
||||
return raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function hookSection(raw) {
|
||||
return raw && raw.hook && typeof raw.hook === 'object' && !Array.isArray(raw.hook) ? raw.hook : null;
|
||||
}
|
||||
|
||||
function detectorSection(raw) {
|
||||
return raw && raw.detector && typeof raw.detector === 'object' && !Array.isArray(raw.detector) ? raw.detector : null;
|
||||
}
|
||||
|
||||
const DETECTOR_CONFIG_KEYS = new Set(['ignoreRules', 'ignoreFiles', 'ignoreValues', 'designSystem']);
|
||||
|
||||
const DEFAULT_DETECTION_CONFIG = Object.freeze({
|
||||
ignoreRules: [],
|
||||
ignoreFiles: [],
|
||||
ignoreValues: [],
|
||||
designSystem: { enabled: true },
|
||||
});
|
||||
|
||||
function cloneDetectionConfig() {
|
||||
return {
|
||||
ignoreRules: [],
|
||||
ignoreFiles: [],
|
||||
ignoreValues: [],
|
||||
designSystem: { ...DEFAULT_DETECTION_CONFIG.designSystem },
|
||||
};
|
||||
}
|
||||
|
||||
function cloneRawDetectionConfig() {
|
||||
return {
|
||||
ignoreRules: [],
|
||||
ignoreFiles: [],
|
||||
ignoreValues: [],
|
||||
};
|
||||
}
|
||||
|
||||
function applyDetectionConfigSource(config, raw) {
|
||||
if (!raw || typeof raw !== 'object') return config;
|
||||
if (raw.designSystem && typeof raw.designSystem === 'object' && !Array.isArray(raw.designSystem)) {
|
||||
config.designSystem = {
|
||||
...config.designSystem,
|
||||
enabled: raw.designSystem.enabled === false ? false : true,
|
||||
};
|
||||
}
|
||||
if (Array.isArray(raw.ignoreRules)) {
|
||||
config.ignoreRules = uniqueStrings([...config.ignoreRules, ...raw.ignoreRules]);
|
||||
}
|
||||
if (Array.isArray(raw.ignoreFiles)) {
|
||||
config.ignoreFiles = uniqueStrings([...config.ignoreFiles, ...raw.ignoreFiles]);
|
||||
}
|
||||
if (Array.isArray(raw.ignoreValues)) {
|
||||
config.ignoreValues = mergeIgnoreValues(config.ignoreValues, raw.ignoreValues);
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
function uniqueStrings(values) {
|
||||
return Array.from(new Set(values.map(String)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Detector filters shared by `npx impeccable detect` and the design hook.
|
||||
* `hook.enabled` remains hook lifecycle state; manual CLI scans still run when
|
||||
* the hook is disabled, but they honor the same ignore rules and design-system
|
||||
* toggle.
|
||||
*/
|
||||
export function readDetectionConfig(root) {
|
||||
const config = cloneDetectionConfig();
|
||||
for (const filePath of [getConfigPath(root), getLocalConfigPath(root)]) {
|
||||
const raw = safeReadJson(filePath);
|
||||
// Back-compat: old builds stored detector filters under hook.*.
|
||||
applyDetectionConfigSource(config, hookSection(raw));
|
||||
applyDetectionConfigSource(config, detectorSection(raw));
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
export function readRawDetectionConfig(root, opts = {}) {
|
||||
const raw = safeReadJson(opts.local ? getLocalConfigPath(root) : getConfigPath(root));
|
||||
const config = cloneRawDetectionConfig();
|
||||
applyDetectionConfigSource(config, hookSection(raw));
|
||||
applyDetectionConfigSource(config, detectorSection(raw));
|
||||
return config;
|
||||
}
|
||||
|
||||
export function writeDetectionConfig(root, detectorConfig, opts = {}) {
|
||||
const filePath = opts.local ? getLocalConfigPath(root) : getConfigPath(root);
|
||||
if (opts.local) ensureConfigGitExclude(root);
|
||||
const existing = safeReadJson(filePath) || {};
|
||||
const existingHook = hookSection(existing);
|
||||
const nextHook = stripDetectorKeys(existingHook);
|
||||
const nextDetector = {
|
||||
...(detectorSection(existing) || {}),
|
||||
...normalizeDetectionConfigForWrite(detectorConfig),
|
||||
};
|
||||
const next = {
|
||||
...existing,
|
||||
detector: nextDetector,
|
||||
};
|
||||
if (nextHook && Object.keys(nextHook).length > 0) {
|
||||
next.hook = nextHook;
|
||||
} else {
|
||||
delete next.hook;
|
||||
}
|
||||
mkdirSync(dirname(filePath), { recursive: true });
|
||||
writeFileSync(filePath, `${JSON.stringify(next, null, 2)}\n`);
|
||||
return filePath;
|
||||
}
|
||||
|
||||
function normalizeDetectionConfigForWrite(config) {
|
||||
const out = {};
|
||||
if (Array.isArray(config?.ignoreRules)) {
|
||||
out.ignoreRules = uniqueStrings(config.ignoreRules.map((rule) => normalizeIgnoreRule(rule)).filter(Boolean));
|
||||
}
|
||||
if (Array.isArray(config?.ignoreFiles)) {
|
||||
out.ignoreFiles = uniqueStrings(config.ignoreFiles.filter(v => typeof v === 'string' && v.trim()).map(v => v.trim()));
|
||||
}
|
||||
out.ignoreValues = normalizeIgnoreValueEntries(config?.ignoreValues || []);
|
||||
if (config?.designSystem && typeof config.designSystem === 'object' && !Array.isArray(config.designSystem)) {
|
||||
out.designSystem = {
|
||||
enabled: config.designSystem.enabled === false ? false : true,
|
||||
};
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function stripDetectorKeys(raw) {
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
|
||||
const out = {};
|
||||
for (const [key, value] of Object.entries(raw)) {
|
||||
if (!DETECTOR_CONFIG_KEYS.has(key)) out[key] = value;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function normalizeIgnoreValue(value) {
|
||||
return String(value || '')
|
||||
.trim()
|
||||
.replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function normalizeIgnoreRule(rule) {
|
||||
return String(rule || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function colorIgnoreKey(value) {
|
||||
const color = parseIgnoreColor(value);
|
||||
if (!color) return '';
|
||||
return `${color.r},${color.g},${color.b},${Math.round(color.a * 255)}`;
|
||||
}
|
||||
|
||||
function parseIgnoreColor(value) {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
if (!text) return null;
|
||||
|
||||
const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i);
|
||||
if (hex) return parseHexIgnoreColor(hex[1]);
|
||||
|
||||
const rgb = text.match(/^rgba?\((.*)\)$/i);
|
||||
if (rgb) {
|
||||
const parts = splitColorArgs(rgb[1]);
|
||||
if (parts.length < 3 || parts.length > 4) return null;
|
||||
const r = parseRgbChannel(parts[0]);
|
||||
const g = parseRgbChannel(parts[1]);
|
||||
const b = parseRgbChannel(parts[2]);
|
||||
const a = parts[3] === undefined ? 1 : parseAlphaChannel(parts[3]);
|
||||
if ([r, g, b, a].some((v) => v === null)) return null;
|
||||
return { r, g, b, a };
|
||||
}
|
||||
|
||||
const hsl = text.match(/^hsla?\((.*)\)$/i);
|
||||
if (hsl) {
|
||||
const parts = splitColorArgs(hsl[1]);
|
||||
if (parts.length < 3 || parts.length > 4) return null;
|
||||
const h = parseHueChannel(parts[0]);
|
||||
const s = parsePercentChannel(parts[1]);
|
||||
const l = parsePercentChannel(parts[2]);
|
||||
const a = parts[3] === undefined ? 1 : parseAlphaChannel(parts[3]);
|
||||
if ([h, s, l, a].some((v) => v === null)) return null;
|
||||
return hslToRgb(h, s, l, a);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseHexIgnoreColor(hex) {
|
||||
if (hex.length === 3 || hex.length === 4) {
|
||||
const r = parseInt(hex[0] + hex[0], 16);
|
||||
const g = parseInt(hex[1] + hex[1], 16);
|
||||
const b = parseInt(hex[2] + hex[2], 16);
|
||||
const a = hex.length === 4 ? parseInt(hex[3] + hex[3], 16) / 255 : 1;
|
||||
return { r, g, b, a };
|
||||
}
|
||||
const r = parseInt(hex.slice(0, 2), 16);
|
||||
const g = parseInt(hex.slice(2, 4), 16);
|
||||
const b = parseInt(hex.slice(4, 6), 16);
|
||||
const a = hex.length === 8 ? parseInt(hex.slice(6, 8), 16) / 255 : 1;
|
||||
return { r, g, b, a };
|
||||
}
|
||||
|
||||
function splitColorArgs(body) {
|
||||
const text = String(body || '').trim();
|
||||
if (!text) return [];
|
||||
if (text.includes(',')) {
|
||||
const parts = text.split(',').map((part) => part.trim()).filter(Boolean);
|
||||
const last = parts[parts.length - 1];
|
||||
if (last && last.includes('/')) {
|
||||
const split = last.split('/').map((part) => part.trim()).filter(Boolean);
|
||||
return [...parts.slice(0, -1), ...split];
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
return text.replace(/\s*\/\s*/g, ' / ').split(/\s+/).filter((part) => part && part !== '/');
|
||||
}
|
||||
|
||||
function parseRgbChannel(raw) {
|
||||
const text = String(raw || '').trim();
|
||||
const match = text.match(/^(-?\d*\.?\d+)(%)?$/);
|
||||
if (!match) return null;
|
||||
const value = Number.parseFloat(match[1]);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
const scaled = match[2] ? value * 2.55 : value;
|
||||
if (scaled < 0 || scaled > 255) return null;
|
||||
return Math.round(scaled);
|
||||
}
|
||||
|
||||
function parseAlphaChannel(raw) {
|
||||
const text = String(raw || '').trim();
|
||||
const match = text.match(/^(-?\d*\.?\d+)(%)?$/);
|
||||
if (!match) return null;
|
||||
const value = Number.parseFloat(match[1]);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
const alpha = match[2] ? value / 100 : value;
|
||||
return alpha >= 0 && alpha <= 1 ? alpha : null;
|
||||
}
|
||||
|
||||
function parseHueChannel(raw) {
|
||||
const text = String(raw || '').trim();
|
||||
const match = text.match(/^(-?\d*\.?\d+)(deg|rad|turn|grad)?$/);
|
||||
if (!match) return null;
|
||||
const value = Number.parseFloat(match[1]);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
const unit = match[2] || 'deg';
|
||||
if (unit === 'turn') return value * 360;
|
||||
if (unit === 'rad') return value * (180 / Math.PI);
|
||||
if (unit === 'grad') return value * 0.9;
|
||||
return value;
|
||||
}
|
||||
|
||||
function parsePercentChannel(raw) {
|
||||
const text = String(raw || '').trim();
|
||||
const match = text.match(/^(-?\d*\.?\d+)%$/);
|
||||
if (!match) return null;
|
||||
const value = Number.parseFloat(match[1]);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
return value >= 0 && value <= 100 ? value / 100 : null;
|
||||
}
|
||||
|
||||
function hslToRgb(hue, saturation, lightness, alpha) {
|
||||
const h = (((hue % 360) + 360) % 360) / 360;
|
||||
if (saturation === 0) {
|
||||
const gray = clampByte(Math.round(lightness * 255));
|
||||
return { r: gray, g: gray, b: gray, a: alpha };
|
||||
}
|
||||
const q = lightness < 0.5
|
||||
? lightness * (1 + saturation)
|
||||
: lightness + saturation - lightness * saturation;
|
||||
const p = 2 * lightness - q;
|
||||
const toRgb = (t) => {
|
||||
let channel = t;
|
||||
if (channel < 0) channel += 1;
|
||||
if (channel > 1) channel -= 1;
|
||||
if (channel < 1 / 6) return p + (q - p) * 6 * channel;
|
||||
if (channel < 1 / 2) return q;
|
||||
if (channel < 2 / 3) return p + (q - p) * (2 / 3 - channel) * 6;
|
||||
return p;
|
||||
};
|
||||
return {
|
||||
r: clampByte(Math.round(toRgb(h + 1 / 3) * 255)),
|
||||
g: clampByte(Math.round(toRgb(h) * 255)),
|
||||
b: clampByte(Math.round(toRgb(h - 1 / 3) * 255)),
|
||||
a: alpha,
|
||||
};
|
||||
}
|
||||
|
||||
function clampByte(value) {
|
||||
return Math.min(255, Math.max(0, value));
|
||||
}
|
||||
|
||||
function ignoreValueMatches(rule, entryValue, findingValue) {
|
||||
if (entryValue === findingValue) return true;
|
||||
if (rule !== 'design-system-color') return false;
|
||||
const entryColor = colorIgnoreKey(entryValue);
|
||||
return Boolean(entryColor && entryColor === colorIgnoreKey(findingValue));
|
||||
}
|
||||
|
||||
export function normalizeIgnoreValueEntries(entries) {
|
||||
if (!Array.isArray(entries)) return [];
|
||||
const out = [];
|
||||
for (const entry of entries) {
|
||||
if (!entry || typeof entry !== 'object') continue;
|
||||
const rule = normalizeIgnoreRule(entry.rule);
|
||||
const value = normalizeIgnoreValue(entry.value);
|
||||
if (!rule || !value) continue;
|
||||
const normalized = { rule, value };
|
||||
const files = uniqueStrings([
|
||||
...(typeof entry.file === 'string' && entry.file.trim() ? [entry.file.trim()] : []),
|
||||
...(Array.isArray(entry.files) ? entry.files.filter(v => typeof v === 'string' && v.trim()).map(v => v.trim()) : []),
|
||||
]);
|
||||
if (files.length > 0) normalized.files = files;
|
||||
if (typeof entry.reason === 'string' && entry.reason.trim()) {
|
||||
normalized.reason = entry.reason.trim();
|
||||
}
|
||||
if (typeof entry.createdAt === 'string' && entry.createdAt.trim()) {
|
||||
normalized.createdAt = entry.createdAt.trim();
|
||||
}
|
||||
out.push(normalized);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function mergeIgnoreValues(existing, incoming) {
|
||||
const map = new Map();
|
||||
for (const entry of normalizeIgnoreValueEntries(existing)) {
|
||||
map.set(`${entry.rule}\0${entry.value}\0${ignoreValueFilesKey(entry.files)}`, entry);
|
||||
}
|
||||
for (const entry of normalizeIgnoreValueEntries(incoming)) {
|
||||
map.set(`${entry.rule}\0${entry.value}\0${ignoreValueFilesKey(entry.files)}`, entry);
|
||||
}
|
||||
return Array.from(map.values());
|
||||
}
|
||||
|
||||
function ignoreValueFilesKey(files) {
|
||||
return Array.isArray(files) && files.length > 0 ? files.join('\x1f') : '';
|
||||
}
|
||||
|
||||
// Glob -> RegExp. Supports `**`, `*`, `?`, and `{a,b}` alternation.
|
||||
function globToRegex(glob) {
|
||||
let re = '^';
|
||||
let i = 0;
|
||||
while (i < glob.length) {
|
||||
const c = glob[i];
|
||||
if (c === '*') {
|
||||
if (glob[i + 1] === '*') {
|
||||
re += '.*';
|
||||
i += 2;
|
||||
if (glob[i] === '/') i += 1;
|
||||
} else {
|
||||
re += '[^/]*';
|
||||
i += 1;
|
||||
}
|
||||
} else if (c === '?') {
|
||||
re += '[^/]';
|
||||
i += 1;
|
||||
} else if (c === '{') {
|
||||
const end = glob.indexOf('}', i);
|
||||
if (end === -1) { re += '\\{'; i += 1; continue; }
|
||||
const parts = glob.slice(i + 1, end).split(',').map((p) => p.replace(/[.+^$()|[\]\\]/g, '\\$&'));
|
||||
re += `(?:${parts.join('|')})`;
|
||||
i = end + 1;
|
||||
} else if (/[.+^$()|[\]\\]/.test(c)) {
|
||||
re += `\\${c}`;
|
||||
i += 1;
|
||||
} else {
|
||||
re += c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
re += '$';
|
||||
return new RegExp(re);
|
||||
}
|
||||
|
||||
export function matchesAnyGlob(filePath, globs) {
|
||||
if (!Array.isArray(globs) || globs.length === 0) return false;
|
||||
const normalized = String(filePath || '').split(sep).join('/');
|
||||
for (const glob of globs) {
|
||||
try {
|
||||
const re = globToRegex(String(glob));
|
||||
if (re.test(normalized)) return true;
|
||||
const base = normalized.split('/').pop();
|
||||
if (re.test(base)) return true;
|
||||
} catch {
|
||||
/* malformed glob, skip */
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function shouldIgnoreDetectionFile(filePath, root, config) {
|
||||
const globs = config?.ignoreFiles || [];
|
||||
if (!Array.isArray(globs) || globs.length === 0) return false;
|
||||
const raw = String(filePath || '').trim();
|
||||
if (!raw) return false;
|
||||
if (matchesAnyGlob(raw, globs)) return true;
|
||||
|
||||
try {
|
||||
const abs = isAbsolute(raw) ? raw : resolve(root, raw);
|
||||
if (matchesAnyGlob(abs, globs)) return true;
|
||||
const rel = relative(root, abs);
|
||||
if (rel && !rel.startsWith('..') && !isAbsolute(rel)) {
|
||||
return matchesAnyGlob(rel, globs);
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function filterDetectionFindings(findings, config) {
|
||||
if (!Array.isArray(findings) || findings.length === 0) return [];
|
||||
const ignoreRules = new Set((config?.ignoreRules || []).map((rule) => normalizeIgnoreRule(rule)));
|
||||
const ignoreValues = normalizeIgnoreValueEntries(config?.ignoreValues || []);
|
||||
return findings.filter((finding) => {
|
||||
if (!finding || typeof finding !== 'object') return false;
|
||||
if (ignoreRules.has(normalizeIgnoreRule(finding.antipattern))) return false;
|
||||
if (isIgnoredFindingValue(finding, ignoreValues)) return false;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
function isIgnoredFindingValue(finding, ignoreValues) {
|
||||
if (!Array.isArray(ignoreValues) || ignoreValues.length === 0) return false;
|
||||
const rule = normalizeIgnoreRule(finding.antipattern);
|
||||
if (!rule) return false;
|
||||
// File-scoped wildcards suppress rules with no extractable value, such as side-tab.
|
||||
const value = extractFindingIgnoreValue(finding);
|
||||
return ignoreValues.some((entry) => {
|
||||
if (entry.rule !== rule) return false;
|
||||
const wildcardValue = entry.value === '*';
|
||||
if (!wildcardValue && (!value || !ignoreValueMatches(rule, entry.value, value))) return false;
|
||||
if (!Array.isArray(entry.files) || entry.files.length === 0) return !wildcardValue;
|
||||
return findingMatchesScopedIgnoreFile(finding, entry.files);
|
||||
});
|
||||
}
|
||||
|
||||
function findingMatchesScopedIgnoreFile(finding, globs) {
|
||||
const filePath = String(finding?.file || '').trim();
|
||||
if (!filePath) return false;
|
||||
if (matchesAnyGlob(filePath, globs)) return true;
|
||||
|
||||
const normalized = filePath.split(sep).join('/');
|
||||
const parts = normalized.split('/').filter(Boolean);
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const suffix = parts.slice(i).join('/');
|
||||
if (matchesAnyGlob(suffix, globs)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function extractFindingIgnoreValue(finding) {
|
||||
if (!finding || typeof finding !== 'object') return '';
|
||||
const rule = normalizeIgnoreRule(finding.antipattern);
|
||||
const directValueRules = new Set([
|
||||
'overused-font',
|
||||
'bounce-easing',
|
||||
'design-system-font',
|
||||
'design-system-color',
|
||||
'design-system-radius',
|
||||
]);
|
||||
if (!directValueRules.has(rule)) return '';
|
||||
return normalizeIgnoreValue(extractFindingIgnoreValueRaw(finding, rule));
|
||||
}
|
||||
|
||||
function extractFindingIgnoreValueRaw(finding, rule = normalizeIgnoreRule(finding?.antipattern)) {
|
||||
const direct = cleanIgnoreValueDisplay(finding.ignoreValue || finding.value || '');
|
||||
if (direct) return direct;
|
||||
|
||||
const candidates = [finding.detail, finding.snippet].filter((v) => typeof v === 'string' && v);
|
||||
for (const text of candidates) {
|
||||
if (rule === 'bounce-easing') {
|
||||
const motion = extractMotionIgnoreValue(text);
|
||||
if (motion) return motion;
|
||||
continue;
|
||||
}
|
||||
|
||||
const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
|
||||
if (primary) return cleanIgnoreValueDisplay(primary[1]);
|
||||
|
||||
const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
|
||||
if (family) return cleanIgnoreValueDisplay(family[1]);
|
||||
|
||||
const google = text.match(/[?&]family=([^&:;\n]+)/i);
|
||||
if (google) {
|
||||
try {
|
||||
return cleanIgnoreValueDisplay(decodeURIComponent(google[1]));
|
||||
} catch {
|
||||
return cleanIgnoreValueDisplay(google[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
function extractMotionIgnoreValue(text) {
|
||||
const tailwind = text.match(/\banimate-bounce\b/i);
|
||||
if (tailwind) return cleanIgnoreValueDisplay(tailwind[0]);
|
||||
|
||||
const bezier = text.match(/cubic-bezier\([^)]+\)/i);
|
||||
if (bezier) return cleanIgnoreValueDisplay(bezier[0]);
|
||||
|
||||
const animation = text.match(/animation(?:-name)?\s*:\s*([^;\n]+)/i);
|
||||
if (animation) {
|
||||
const token = animation[1]
|
||||
.split(/[,\s]+/)
|
||||
.find((part) => /bounce|elastic|wobble|jiggle|spring/i.test(part));
|
||||
if (token) return cleanIgnoreValueDisplay(token);
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
function cleanIgnoreValueDisplay(value) {
|
||||
return String(value || '')
|
||||
.trim()
|
||||
.replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ')
|
||||
.replace(/\s+/g, ' ');
|
||||
}
|
||||
|
||||
/**
|
||||
* The recorded design-hook decision: 'accepted' | 'declined' | undefined.
|
||||
* config.local.json (per-developer) overrides config.json.
|
||||
*/
|
||||
export function getHookConsent(root) {
|
||||
let consent;
|
||||
for (const filePath of [getConfigPath(root), getLocalConfigPath(root)]) {
|
||||
const hook = hookSection(safeReadJson(filePath));
|
||||
if (hook && (hook.consent === 'accepted' || hook.consent === 'declined')) consent = hook.consent;
|
||||
}
|
||||
return consent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist the per-developer decision to config.local.json, preserving any
|
||||
* sibling keys, and ensure the file is gitignored.
|
||||
*/
|
||||
export function setHookConsent(root, value) {
|
||||
const filePath = getLocalConfigPath(root);
|
||||
const existing = safeReadJson(filePath) || {};
|
||||
const hook = hookSection(existing) || {};
|
||||
const next = { ...existing, hook: { ...hook, consent: value } };
|
||||
mkdirSync(dirname(filePath), { recursive: true });
|
||||
writeFileSync(filePath, `${JSON.stringify(next, null, 2)}\n`);
|
||||
ensureConfigGitExclude(root);
|
||||
return filePath;
|
||||
}
|
||||
|
||||
const EXCLUDE_OPEN = '# impeccable-config-ignore-start';
|
||||
const EXCLUDE_CLOSE = '# impeccable-config-ignore-end';
|
||||
const EXCLUDE_PATTERNS = ['.impeccable/config.local.json'];
|
||||
|
||||
/**
|
||||
* Add config.local.json to `.git/info/exclude` so a developer's decision is
|
||||
* never committed. Idempotent via marker comments. Best-effort; returns false
|
||||
* when there is no resolvable git dir.
|
||||
*/
|
||||
export function ensureConfigGitExclude(root) {
|
||||
try {
|
||||
const gitDir = resolveGitDir(root);
|
||||
if (!gitDir) return false;
|
||||
const target = join(gitDir, 'info', 'exclude');
|
||||
const existing = existsSync(target) ? readFileSync(target, 'utf-8') : '';
|
||||
const block = [EXCLUDE_OPEN, ...EXCLUDE_PATTERNS, EXCLUDE_CLOSE].join('\n');
|
||||
const markerRe = new RegExp(`${escapeRegExp(EXCLUDE_OPEN)}[\\s\\S]*?${escapeRegExp(EXCLUDE_CLOSE)}`);
|
||||
let updated;
|
||||
if (markerRe.test(existing)) {
|
||||
updated = existing.replace(markerRe, block);
|
||||
} else {
|
||||
const prefix = existing.length === 0 ? '' : existing.endsWith('\n') ? existing : `${existing}\n`;
|
||||
updated = `${prefix}${block}\n`;
|
||||
}
|
||||
if (updated !== existing) {
|
||||
mkdirSync(dirname(target), { recursive: true });
|
||||
writeFileSync(target, updated);
|
||||
}
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function resolveGitDir(root) {
|
||||
const dotGit = join(root, '.git');
|
||||
if (!existsSync(dotGit)) return null;
|
||||
try {
|
||||
if (statSync(dotGit).isDirectory()) return dotGit;
|
||||
// A `.git` file (worktree/submodule) points elsewhere: "gitdir: <path>".
|
||||
const match = readFileSync(dotGit, 'utf-8').match(/gitdir:\s*(.+)/);
|
||||
if (match) {
|
||||
const resolved = match[1].trim();
|
||||
return isAbsolute(resolved) ? resolved : join(root, resolved);
|
||||
}
|
||||
} catch {
|
||||
/* fall through */
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function escapeRegExp(value) {
|
||||
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { resolveProjectRoot } from '../context.mjs';
|
||||
export { IMPECCABLE_COMMAND_PREFIX } from './provider.mjs';
|
||||
|
||||
export const IMPECCABLE_DIR = '.impeccable';
|
||||
export const LIVE_DIR = 'live';
|
||||
export const CRITIQUE_DIR = 'critique';
|
||||
|
||||
export function getImpeccableDir(cwd = process.cwd(), options = {}) {
|
||||
return path.join(resolveProjectRoot(cwd, options), IMPECCABLE_DIR);
|
||||
}
|
||||
|
||||
export function getDesignSidecarPath(cwd = process.cwd(), options = {}) {
|
||||
return path.join(getImpeccableDir(cwd, options), 'design.json');
|
||||
}
|
||||
|
||||
export function getDesignSidecarCandidates(cwd = process.cwd(), contextDir = cwd, options = {}) {
|
||||
const projectRoot = resolveProjectRoot(cwd, options);
|
||||
const candidates = [
|
||||
getDesignSidecarPath(cwd, options),
|
||||
path.join(projectRoot, 'DESIGN.json'),
|
||||
];
|
||||
const contextLegacy = path.join(contextDir, 'DESIGN.json');
|
||||
if (!candidates.includes(contextLegacy)) candidates.push(contextLegacy);
|
||||
return candidates;
|
||||
}
|
||||
|
||||
export function resolveDesignSidecarPath(cwd = process.cwd(), contextDir = cwd, options = {}) {
|
||||
return firstExisting(getDesignSidecarCandidates(cwd, contextDir, options));
|
||||
}
|
||||
|
||||
export function getLiveDir(cwd = process.cwd(), options = {}) {
|
||||
return path.join(getImpeccableDir(cwd, options), LIVE_DIR);
|
||||
}
|
||||
|
||||
export function getLiveConfigPath(cwd = process.cwd(), options = {}) {
|
||||
return path.join(getLiveDir(cwd, options), 'config.json');
|
||||
}
|
||||
|
||||
export function getLegacyLiveConfigPath(scriptsDir) {
|
||||
return path.join(scriptsDir, 'config.json');
|
||||
}
|
||||
|
||||
export function resolveLiveConfigPath({ cwd = process.cwd(), scriptsDir, env = process.env, targetPath } = {}) {
|
||||
if (env.IMPECCABLE_LIVE_CONFIG && env.IMPECCABLE_LIVE_CONFIG.trim()) {
|
||||
const configured = env.IMPECCABLE_LIVE_CONFIG.trim();
|
||||
return path.isAbsolute(configured) ? configured : path.resolve(cwd, configured);
|
||||
}
|
||||
const primary = getLiveConfigPath(cwd, { targetPath });
|
||||
if (fs.existsSync(primary)) return primary;
|
||||
if (scriptsDir) {
|
||||
const legacy = getLegacyLiveConfigPath(scriptsDir);
|
||||
if (fs.existsSync(legacy)) return legacy;
|
||||
}
|
||||
return primary;
|
||||
}
|
||||
|
||||
export function getLiveServerPath(cwd = process.cwd(), options = {}) {
|
||||
return path.join(getLiveDir(cwd, options), 'server.json');
|
||||
}
|
||||
|
||||
export function getLegacyLiveServerPath(cwd = process.cwd(), options = {}) {
|
||||
return path.join(resolveProjectRoot(cwd, options), '.impeccable-live.json');
|
||||
}
|
||||
|
||||
export function readLiveServerInfo(cwd = process.cwd(), options = {}) {
|
||||
for (const filePath of [getLiveServerPath(cwd, options), getLegacyLiveServerPath(cwd, options)]) {
|
||||
try {
|
||||
const info = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
|
||||
if (info && typeof info.pid === 'number' && !isLiveServerPidReachable(info.pid)) {
|
||||
try { fs.unlinkSync(filePath); } catch {}
|
||||
continue;
|
||||
}
|
||||
return { info, path: filePath };
|
||||
} catch {
|
||||
/* try next */
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function isLiveServerPidReachable(pid) {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (err) {
|
||||
// ESRCH means "no such process". EPERM means the process exists but this
|
||||
// user cannot signal it, so the live server info is still valid.
|
||||
return err?.code !== 'ESRCH';
|
||||
}
|
||||
}
|
||||
|
||||
export function writeLiveServerInfo(cwd = process.cwd(), info, options = {}) {
|
||||
const filePath = getLiveServerPath(cwd, options);
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
fs.writeFileSync(filePath, JSON.stringify(info));
|
||||
return filePath;
|
||||
}
|
||||
|
||||
export function removeLiveServerInfo(cwd = process.cwd(), options = {}) {
|
||||
for (const filePath of [getLiveServerPath(cwd, options), getLegacyLiveServerPath(cwd, options)]) {
|
||||
try { fs.unlinkSync(filePath); } catch {}
|
||||
}
|
||||
}
|
||||
|
||||
export function getLiveSessionsDir(cwd = process.cwd(), options = {}) {
|
||||
return path.join(getLiveDir(cwd, options), 'sessions');
|
||||
}
|
||||
|
||||
export function getLegacyLiveSessionsDir(cwd = process.cwd(), options = {}) {
|
||||
return path.join(resolveProjectRoot(cwd, options), '.impeccable-live', 'sessions');
|
||||
}
|
||||
|
||||
export function getLiveAnnotationsDir(cwd = process.cwd(), options = {}) {
|
||||
return path.join(getLiveDir(cwd, options), 'annotations');
|
||||
}
|
||||
|
||||
export function getCritiqueDir(cwd = process.cwd(), options = {}) {
|
||||
return path.join(getImpeccableDir(cwd, options), CRITIQUE_DIR);
|
||||
}
|
||||
|
||||
export function getLegacyLiveAnnotationsDir(cwd = process.cwd(), options = {}) {
|
||||
return path.join(resolveProjectRoot(cwd, options), '.impeccable-live', 'annotations');
|
||||
}
|
||||
|
||||
function firstExisting(paths) {
|
||||
return paths.find((filePath) => fs.existsSync(filePath)) || null;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* Decide whether a given file is "generated" (regenerated by a build step,
|
||||
* unsafe to write variants into) or "source" (safe to edit, changes persist).
|
||||
*
|
||||
* Why this matters: when the user picks an element on a page whose underlying
|
||||
* file is regenerated by a build step (e.g. `scripts/build-sub-pages.js`
|
||||
* rewriting `public/docs/*.html`), writing variants or accepted changes into
|
||||
* that file is silent data loss — the next build wipes them.
|
||||
*
|
||||
* Signals, in order of reliability:
|
||||
* 1. Git check-ignore: gitignored files are assumed generated.
|
||||
* 2. File-header markers ("GENERATED", "DO NOT EDIT", "AUTO-GENERATED")
|
||||
* within the first ~300 characters — catches non-git projects.
|
||||
*/
|
||||
|
||||
import { execSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const HEADER_SCAN_BYTES = 300;
|
||||
const HEADER_MARKERS = [
|
||||
/@generated\b/i,
|
||||
/\bGENERATED\s+FILE\b/,
|
||||
/\bAUTO-?GENERATED\b/i,
|
||||
/\bDO\s+NOT\s+EDIT\b/i,
|
||||
];
|
||||
|
||||
/**
|
||||
* @param {string} filePath - absolute or cwd-relative path
|
||||
* @param {object} [options]
|
||||
* @param {string} [options.cwd] - project root (defaults to process.cwd())
|
||||
*/
|
||||
export function isGeneratedFile(filePath, options = {}) {
|
||||
const cwd = options.cwd || process.cwd();
|
||||
const absPath = path.isAbsolute(filePath) ? filePath : path.resolve(cwd, filePath);
|
||||
|
||||
if (isGitIgnored(absPath, cwd)) return true;
|
||||
if (hasGeneratedHeader(absPath)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
function isGitIgnored(absPath, cwd) {
|
||||
try {
|
||||
execSync(`git check-ignore --quiet ${JSON.stringify(absPath)}`, {
|
||||
cwd,
|
||||
stdio: 'ignore',
|
||||
});
|
||||
return true; // exit 0 = ignored
|
||||
} catch (err) {
|
||||
// Exit code 1 = not ignored. Exit code 128 = not a git repo or other error.
|
||||
// In both cases, treat as "not known to be ignored."
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function hasGeneratedHeader(absPath) {
|
||||
let fd;
|
||||
try {
|
||||
fd = fs.openSync(absPath, 'r');
|
||||
const buf = Buffer.alloc(HEADER_SCAN_BYTES);
|
||||
const bytesRead = fs.readSync(fd, buf, 0, HEADER_SCAN_BYTES, 0);
|
||||
const head = buf.slice(0, bytesRead).toString('utf-8');
|
||||
return HEADER_MARKERS.some((re) => re.test(head));
|
||||
} catch {
|
||||
return false;
|
||||
} finally {
|
||||
if (fd !== undefined) { try { fs.closeSync(fd); } catch {} }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
// Source scripts default to slash commands. The provider build replaces only
|
||||
// this exact declaration, avoiding heuristic rewrites across executable code.
|
||||
export const IMPECCABLE_COMMAND_PREFIX = "$";
|
||||
export const IMPECCABLE_COMMAND = `${IMPECCABLE_COMMAND_PREFIX}impeccable`;
|
||||
@@ -0,0 +1,42 @@
|
||||
class TargetArgError extends Error {
|
||||
constructor(message, code) {
|
||||
super(message);
|
||||
this.name = 'TargetArgError';
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
export function parseTargetPath(args = [], { strict = false } = {}) {
|
||||
let targetPath = null;
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const arg = String(args[i]);
|
||||
if (arg === '--target' || arg === '-t') {
|
||||
const next = args[i + 1];
|
||||
if (next && !String(next).startsWith('-')) {
|
||||
targetPath = String(next);
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (strict) {
|
||||
throw new TargetArgError('--target requires a path value.', 'TARGET_VALUE_MISSING');
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (arg.startsWith('--target=')) {
|
||||
const value = arg.slice('--target='.length);
|
||||
if (value) {
|
||||
targetPath = value;
|
||||
continue;
|
||||
}
|
||||
if (strict) {
|
||||
throw new TargetArgError('--target requires a path value.', 'TARGET_VALUE_MISSING');
|
||||
}
|
||||
}
|
||||
}
|
||||
return targetPath;
|
||||
}
|
||||
|
||||
export function parseTargetOptions(args = [], options = {}) {
|
||||
const targetPath = parseTargetPath(args, options);
|
||||
return targetPath ? { targetPath } : {};
|
||||
}
|
||||
Reference in New Issue
Block a user