@bridge-ds/core 0.15.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../src/validators.ts","../src/id-map.ts","../src/token-merge.ts","../src/token-combine.ts","../src/css-overrides.ts","../src/compose.ts","../src/protection.ts","../src/protection-github.ts","../src/usage.ts","../src/history-github.ts","../src/history-demo.ts","../src/previews-github.ts","../src/ramps.js","../src/brand.ts","../src/docs-ai.ts","../src/draft-exchange.ts","../src/explorations-github.ts","../src/fidelity.ts","../src/fidelity-references.ts","../src/library-update.ts","../src/branch-actions.ts","../src/share-branch.ts","../src/try-in-product.ts","../src/combine-branches.ts","../src/prod-branch-github.ts","../src/token-proposal.ts","../src/figma-push-github.ts","../src/storybook.ts","../src/token-rows.ts","../src/contrast-model.ts","../src/component-scan.ts","../src/repo-model.ts","../src/repo-source-github.ts","../src/repo-access.ts","../src/snapshot.ts"],"sourcesContent":["// Guardrails checked before a PR can be opened. They mirror the repo rules (AGENTS.md,\n// docs/ARCHITECTURE.md \"Token tiers\", docs/GOVERNANCE.md) so designers get the answer in Figma\n// instead of a red CI run later.\n//\n// Tier rules (what each tier may alias):\n// primitive literal values, or another primitive\n// brand an alias to a primitive (palette, radius and font roles re-point raw scales)\n// base a literal or a primitive (motion, layers, icon sizes)\n// semantic an alias, never a literal. Colors alias a Brand palette role (palette.*); translucent\n// primitives (color.alpha.*) are the only raw colors allowed. Non-color semantic tokens\n// (focus ring width, elevation) may alias a primitive or a brand role.\n// density an alias to a primitive (space and size scales)\n// component an alias to a semantic, base, density or brand role token, or a primitive scale step\n// (space, type). Never a raw color ramp or a palette role.\n// Brand x theme overrides follow the semantic rule and must override an existing semantic token.\n\nimport { findReferenceProblems } from './resolver';\nimport { type TokenSet, modesOf } from './token-set';\nimport { type LogicalToken, SINGLE_MODE, TIER_AXIS, TIER_NAMES, type Tier, isMultiMode, modeDisplayName } from './types';\nimport { aliasTarget, collectRefs, isAlias } from './values';\nimport { type ContrastPair, type ContrastResult, contextLabel, contrastScope, evaluatePairs } from './wcag';\n\nexport type IssueCode =\n | 'file-problem'\n | 'raw-value'\n | 'alias-tier'\n | 'broken-reference'\n | 'alias-cycle'\n | 'all-scopes'\n | 'missing-mode'\n | 'override-orphan'\n | 'override-shadowed'\n | 'contrast'\n | 'contrast-unresolved'\n | 'type-change';\n\nexport interface Issue {\n code: IssueCode;\n severity: 'error' | 'warning';\n message: string;\n path?: string | undefined;\n mode?: string | undefined;\n}\n\nconst issueKey = (i: Issue) => `${i.code}|${i.path ?? ''}|${i.mode ?? ''}|${i.code === 'file-problem' ? i.message : ''}`;\nconst modeName = (mode: string) => (mode === SINGLE_MODE ? 'all modes' : modeDisplayName(mode));\n\nconst isPalette = (t: LogicalToken) => t.tier === 'brand' && t.path.startsWith('palette.');\nconst isRawColor = (t: LogicalToken) => t.tier === 'primitive' && t.type === 'color';\n\n/** Why `owner` (in `tier`) may not alias `target`, or undefined when the alias is allowed. */\nfunction aliasRule(owner: { tier: Tier; type: string }, target: LogicalToken): string | undefined {\n switch (owner.tier) {\n case 'primitive':\n case 'base':\n case 'brand':\n case 'density':\n return target.tier === 'primitive' ? undefined : `${TIER_NAMES[owner.tier]} tokens point to primitives only`;\n case 'semantic':\n if (owner.type === 'color') {\n if (isPalette(target)) return undefined;\n if (target.tier === 'primitive' && target.path.startsWith('color.alpha.')) return undefined;\n return 'Semantic colors point to a Brand palette role (palette.*) so every brand can re-map them';\n }\n return target.tier === 'primitive' || target.tier === 'brand' ? undefined : 'Semantic tokens point to a Brand role or a primitive';\n case 'component':\n if (isPalette(target) || isRawColor(target)) return 'Component tokens point to semantic tokens, never to a palette role or a raw color';\n return target.tier === 'component' ? 'Component tokens point to semantic tokens, not to other component tokens' : undefined;\n }\n}\n\n/** Tiers whose values must be aliases. */\nconst MUST_ALIAS: Tier[] = ['brand', 'semantic', 'density', 'component'];\n\nfunction checkValue(set: TokenSet, owner: { path: string; tier: Tier; type: string }, value: unknown, mode: string, where: string, issues: Issue[]): void {\n if (!isAlias(value)) {\n if (MUST_ALIAS.includes(owner.tier) && value !== undefined) {\n issues.push({\n code: 'raw-value',\n severity: 'error',\n path: owner.path,\n mode,\n message: `${owner.path} uses a raw value in ${where}. ${TIER_NAMES[owner.tier]} tokens must point to another variable (pick one instead of typing a value).`,\n });\n }\n return;\n }\n const target = set.byPath.get(aliasTarget(value));\n if (!target) return; // reported as a broken reference\n const why = aliasRule(owner, target);\n if (why) {\n issues.push({\n code: 'alias-tier',\n severity: 'error',\n path: owner.path,\n mode,\n message: `${owner.path} points to ${target.path} (${TIER_NAMES[target.tier]}) in ${where}. ${why}.`,\n });\n }\n}\n\n/** All rule violations in a token set. */\nexport function validateSet(set: TokenSet, pairs: ContrastPair[]): { issues: Issue[]; contrast: ContrastResult[] } {\n const issues: Issue[] = [];\n for (const p of set.problems) issues.push({ code: 'file-problem', severity: 'error', message: p });\n\n for (const t of set.tokens.values()) {\n if (t.scopes?.includes('ALL_SCOPES')) {\n issues.push({\n code: 'all-scopes',\n severity: 'error',\n path: t.path,\n message: `${t.path} is offered in every Figma picker (\"All supported properties\"). Pick the specific properties it is meant for in the variable's scoping settings.`,\n });\n }\n const modes = modesOf(set.layout, t.tier);\n for (const mode of modes) {\n const v = t.values[mode];\n if (v === undefined) {\n if (isMultiMode(t.tier)) {\n issues.push({\n code: 'missing-mode',\n severity: 'error',\n path: t.path,\n mode,\n message: `${t.path} has no value in ${modeName(mode)}. ${TIER_NAMES[t.tier]} tokens must exist in every ${TIER_AXIS[t.tier]}.`,\n });\n }\n continue;\n }\n checkValue(set, t, v, mode, modeName(mode), issues);\n }\n }\n\n for (const o of set.overrides) {\n const mode = `${o.brand}.${o.theme}`;\n const where = `${modeDisplayName(o.brand)} ${o.theme} (${o.file})`;\n const base = set.byPath.get(o.path);\n if (!base || base.tier !== 'semantic') {\n issues.push({\n code: 'override-orphan',\n severity: 'error',\n path: o.path,\n mode,\n message: `${o.file} overrides ${o.path}, which is not a semantic token. Remove the override or restore the token.`,\n });\n continue;\n }\n checkValue(set, { path: o.path, tier: 'semantic', type: base.type }, o.value, mode, where, issues);\n for (const ref of collectRefs(o.value)) {\n if (!set.byPath.has(ref)) issues.push({ code: 'broken-reference', severity: 'error', path: o.path, mode, message: `${o.path} points to ${ref}, which does not exist (${where}).` });\n }\n }\n\n const axes = { brand: modesOf(set.layout, 'brand'), theme: modesOf(set.layout, 'semantic'), density: modesOf(set.layout, 'density') };\n for (const p of findReferenceProblems(set.byPath, axes)) {\n issues.push(\n p.kind === 'broken'\n ? {\n code: 'broken-reference',\n severity: 'error',\n path: p.path,\n mode: p.mode,\n message: `${p.path} points to ${p.target}, which does not exist (${modeName(p.mode)}).`,\n }\n : {\n code: 'alias-cycle',\n severity: 'error',\n path: p.path,\n mode: p.mode,\n message: `${p.path} is part of a loop of references: ${p.chain.join(' -> ')} (${modeName(p.mode)}).`,\n },\n );\n }\n\n const contrast = evaluatePairs(set.byPath, pairs, contrastScope(set));\n for (const r of contrast) {\n const path = `${r.pair.foreground} on ${r.pair.background}`;\n const mode = `${r.brand ?? ''}.${r.theme}`;\n if (r.error) {\n issues.push({ code: 'contrast-unresolved', severity: 'warning', path, mode, message: `Contrast of ${path} in ${contextLabel(r)} cannot be checked: ${r.error}.` });\n } else if (r.level === 'fail') {\n issues.push({\n code: 'contrast',\n severity: 'error',\n path,\n mode,\n message: `${path} is ${r.ratio}:1 in ${contextLabel(r)}; contrast.checks.json needs ${r.pair.min}:1 (WCAG AA ${r.pair.kind === 'ui' ? 'for interface elements' : 'for text'}).`,\n });\n }\n }\n return { issues, contrast };\n}\n\nexport interface TypeChange {\n path: string;\n from: string;\n to: string;\n}\n\nexport interface ProposalValidation {\n /** Problems this change introduces. They disable the PR button. */\n blocking: Issue[];\n /** Problems that already exist on main, or soft checks. Shown, not blocking. */\n warnings: Issue[];\n contrastBefore: ContrastResult[];\n contrastAfter: ContrastResult[];\n}\n\n/**\n * Semantic edits that some brand does not see because it overrides that token for the theme\n * (brands/<brand>.<theme>.tokens.json). Not an error: a heads-up that the edit is partial.\n */\nexport function shadowedEdits(set: TokenSet, edits: { path: string; tier: Tier; modes: string[] }[]): Issue[] {\n const out: Issue[] = [];\n for (const e of edits) {\n if (e.tier !== 'semantic') continue;\n for (const o of set.overrides) {\n if (o.path !== e.path || !e.modes.includes(o.theme)) continue;\n out.push({\n code: 'override-shadowed',\n severity: 'warning',\n path: e.path,\n mode: `${o.brand}.${o.theme}`,\n message: `${e.path} is overridden for ${modeDisplayName(o.brand)} in ${o.theme} (${o.file}), so this edit does not change ${modeDisplayName(o.brand)} ${o.theme}. Brand overrides stay code-only.`,\n });\n }\n }\n return out;\n}\n\n/**\n * Validate the files a PR would produce. Errors already present on main are reported as warnings\n * so an unrelated, pre-existing problem does not block a designer's change; everything the change\n * introduces blocks.\n */\nexport function validateProposal(proposed: TokenSet, head: TokenSet, pairs: ContrastPair[], typeChanges: TypeChange[] = []): ProposalValidation {\n const after = validateSet(proposed, pairs);\n const before = validateSet(head, pairs);\n const existing = new Set(before.issues.map(issueKey));\n const blocking: Issue[] = [];\n const warnings: Issue[] = [];\n for (const i of after.issues) {\n if (i.severity === 'warning') warnings.push(i);\n else if (existing.has(issueKey(i))) warnings.push({ ...i, severity: 'warning', message: `Already on main: ${i.message}` });\n else blocking.push(i);\n }\n for (const c of typeChanges) {\n blocking.push({\n code: 'type-change',\n severity: 'error',\n path: c.path,\n message: `${c.path} changed type from ${c.from} to ${c.to}. Type changes are not allowed; create a new token instead.`,\n });\n }\n return { blocking, warnings, contrastBefore: before.contrast, contrastAfter: after.contrast };\n}\n","// Stable identity of tokens across renames.\n//\n// Every variable DS Bridge writes carries a token id in its plugin data. The id is the token's\n// `$extensions[\"com.dsbridge.id\"]` when the file declares one, otherwise \"path:<path>\". Matching is\n// by id first, so renaming a variable in Figma is a rename, not a delete plus an add. Only renamed\n// (or re-identified) tokens get the extension written into Git, which keeps the files lean.\n//\n// Variables created in Figma have no id. They are matched by name, then, as a last resort, a\n// heuristic proposes \"this looks like a rename\" (same type, same values, similar path). Heuristic\n// matches are suggestions only: the user confirms each one.\n\nimport { pathId } from './token-set';\nimport type { LogicalToken } from './types';\nimport { valuesEqual } from './values';\n\nexport interface RenameSuggestion {\n /** Id the Figma variable currently has (derived from its new name). */\n figmaId: string;\n /** Id of the Git token it probably is. */\n gitId: string;\n fromPath: string;\n toPath: string;\n similarity: number;\n}\n\nexport interface ReconcileResult {\n tokens: LogicalToken[];\n /** Figma tokens that adopted a Git id because their names matched (no plugin data yet). */\n adoptedByName: string[];\n suggestions: RenameSuggestion[];\n}\n\nexport function levenshtein(a: string, b: string): number {\n const prev = Array.from({ length: b.length + 1 }, (_, i) => i);\n for (let i = 1; i <= a.length; i++) {\n let diag = prev[0]!;\n prev[0] = i;\n for (let j = 1; j <= b.length; j++) {\n const tmp = prev[j]!;\n prev[j] = Math.min(prev[j]! + 1, prev[j - 1]! + 1, diag + (a[i - 1] === b[j - 1] ? 0 : 1));\n diag = tmp;\n }\n }\n return prev[b.length]!;\n}\n\nexport function pathSimilarity(a: string, b: string): number {\n const ratio = 1 - levenshtein(a, b) / Math.max(a.length, b.length, 1);\n const leafA = a.slice(a.lastIndexOf('.') + 1);\n const leafB = b.slice(b.lastIndexOf('.') + 1);\n return leafA === leafB ? Math.max(ratio, 0.75) : ratio;\n}\n\nexport const SIMILARITY_THRESHOLD = 0.5;\n\nfunction sameContent(a: LogicalToken, b: LogicalToken): boolean {\n if (a.type !== b.type || a.tier !== b.tier) return false;\n const modes = new Set([...Object.keys(a.values), ...Object.keys(b.values)]);\n for (const m of modes) if (!valuesEqual(a.type, a.values[m], b.values[m])) return false;\n return true;\n}\n\n/**\n * Align Figma token ids with Git ids. `git` is every token known on the Git side (base and head).\n * Heuristic candidates are restricted to Git tokens that no Figma variable claims.\n */\nexport function reconcileIds(figma: LogicalToken[], git: LogicalToken[]): ReconcileResult {\n const gitById = new Map<string, LogicalToken>();\n const gitByPath = new Map<string, LogicalToken>();\n for (const t of git) {\n if (!gitById.has(t.id)) gitById.set(t.id, t);\n if (!gitByPath.has(t.path)) gitByPath.set(t.path, t);\n }\n const claimed = new Set(figma.filter((t) => gitById.has(t.id)).map((t) => t.id));\n const adoptedByName: string[] = [];\n const tokens = figma.map((t) => ({ ...t }));\n\n for (const t of tokens) {\n if (gitById.has(t.id)) continue;\n const byName = gitByPath.get(t.path);\n if (byName && !claimed.has(byName.id) && byName.type === t.type) {\n t.id = byName.id;\n claimed.add(byName.id);\n adoptedByName.push(t.id);\n }\n }\n\n const suggestions: RenameSuggestion[] = [];\n const unclaimedGit = [...gitById.values()].filter((g) => !claimed.has(g.id));\n for (const t of tokens) {\n if (gitById.has(t.id)) continue;\n let best: RenameSuggestion | undefined;\n for (const g of unclaimedGit) {\n if (!sameContent(t, g)) continue;\n const similarity = pathSimilarity(t.path, g.path);\n if (similarity < SIMILARITY_THRESHOLD) continue;\n if (!best || similarity > best.similarity) {\n best = { figmaId: t.id, gitId: g.id, fromPath: g.path, toPath: t.path, similarity: Math.round(similarity * 100) / 100 };\n }\n }\n if (best) suggestions.push(best);\n }\n // One suggestion per Git token: keep the most similar.\n const byGit = new Map<string, RenameSuggestion>();\n for (const s of suggestions) {\n const prev = byGit.get(s.gitId);\n if (!prev || s.similarity > prev.similarity) byGit.set(s.gitId, s);\n }\n return { tokens, adoptedByName, suggestions: [...byGit.values()] };\n}\n\n/** Apply the rename suggestions the user confirmed: the Figma token takes the Git id. */\nexport function applyConfirmedRenames(tokens: LogicalToken[], confirmed: RenameSuggestion[]): LogicalToken[] {\n const map = new Map(confirmed.map((s) => [s.figmaId, s.gitId]));\n return tokens.map((t) => (map.has(t.id) ? { ...t, id: map.get(t.id)! } : t));\n}\n\n/**\n * Id to write into `$extensions[\"com.dsbridge.id\"]`: only needed when the id no longer matches\n * the default derived from the path (after a rename). Undefined means \"do not write\".\n */\nexport function idExtensionFor(t: LogicalToken): string | undefined {\n return t.id === pathId(t.path) ? undefined : t.id;\n}\n","// Three-way merge of token files: a change (mine) against the latest library (theirs), from the commit they share\n// (base). Same rules as the Figma sync (diff-engine threeWayDiff): a token changed on one side only takes that side,\n// a token changed on both sides the same way is unchanged, and a token changed on both sides differently is a\n// conflict the designer decides (\"Keep mine\" or \"Use the library's\"). A token removed on one side and changed on the\n// other has no default: the designer must pick.\n//\n// Works file by file on the DTCG text, so each mode (semantic/light, semantic/dark, a brand override file) is merged\n// on its own, and edits go through the format-preserving codec: untouched tokens stay byte for byte as the library\n// has them. Pure: no fetch, no DOM.\n\nimport { emptyTokenFile, flattenTokens, parseTokenFile, removeToken, serializeTokenFile, upsertToken, type TokenDocument } from './dtcg-codec';\nimport { threeWayDiff, type DiffEntry } from './diff-engine';\nimport { pathId } from './token-set';\nimport { EXT_ID, EXT_SCOPES, SINGLE_MODE, type FlatToken, type LogicalToken } from './types';\n\n/** Which side a conflict keeps: this change (\"Keep mine\") or the latest library (\"Use the library's\"). */\nexport type MergeSide = 'mine' | 'theirs';\n\nexport interface TokenMergeConflict {\n /** Stable key for the choice: `<file>#<token id>`. */\n key: string;\n /** Token file, relative to the tokens root. */\n file: string;\n /** Display path: this change's name, else the library's, else the shared one. */\n path: string;\n base?: FlatToken | undefined;\n mine?: FlatToken | undefined;\n theirs?: FlatToken | undefined;\n /** The side that removed the token while the other changed it. Null when both sides kept it. */\n removedOn: MergeSide | null;\n /** \"Keep mine\" by default; null when the token was removed on one side and changed on the other. */\n defaultChoice: MergeSide | null;\n}\n\nexport interface TokenMergePlan {\n /** Token files both sides changed, relative to the tokens root. */\n files: string[];\n conflicts: TokenMergeConflict[];\n /** Tokens only this change touched: applied on top of the library as they are. */\n mineOnly: number;\n /** Tokens only the library touched: kept as the library has them. */\n theirsOnly: number;\n /** Files that could not be read (not JSON): nothing can be merged while there is one. */\n problems: string[];\n}\n\nexport interface TokenMergeInput {\n /** File texts at the commit both sides share. Undefined: the file did not exist there. */\n base: Record<string, string | undefined>;\n /** File texts in the change. */\n mine: Record<string, string | undefined>;\n /** File texts in the latest library. */\n theirs: Record<string, string | undefined>;\n /** Token files both sides changed (the others need no merge). */\n files: string[];\n}\n\nexport type MergeChoices = Record<string, MergeSide | undefined>;\n\ninterface Side {\n doc: TokenDocument | undefined;\n flat: Map<string, FlatToken>;\n logical: Map<string, LogicalToken>;\n}\n\nconst idOf = (f: FlatToken) => {\n const id = f.extensions?.[EXT_ID];\n return typeof id === 'string' && id ? id : pathId(f.path);\n};\n\n/** One flat token as a single-mode logical token, so threeWayDiff compares path, type, value, description and scopes. */\nfunction logical(f: FlatToken): LogicalToken {\n const scopes = f.extensions?.[EXT_SCOPES];\n return {\n id: idOf(f),\n path: f.path,\n type: f.type ?? 'unknown',\n // One file holds one tier: the tier only feeds default scopes, the same on every side.\n tier: 'primitive',\n values: { [SINGLE_MODE]: f.value },\n description: f.description,\n scopes: Array.isArray(scopes) ? scopes.map(String) : undefined,\n files: { [SINGLE_MODE]: f.file },\n };\n}\n\nfunction readSide(file: string, text: string | undefined, problems: string[], label: string): Side {\n const side: Side = { doc: undefined, flat: new Map(), logical: new Map() };\n if (text === undefined) return side;\n try {\n side.doc = parseTokenFile(file, text);\n } catch (err) {\n problems.push(`${file} (${label}) is not valid JSON: ${(err as Error).message}`);\n return side;\n }\n for (const f of flattenTokens(side.doc)) {\n const id = idOf(f);\n side.flat.set(id, f);\n side.logical.set(id, logical(f));\n }\n return side;\n}\n\ninterface FileDiff {\n file: string;\n base: Side;\n mine: Side;\n theirs: Side;\n local: DiffEntry[];\n remote: DiffEntry[];\n conflicts: DiffEntry[];\n}\n\nfunction diffFile(input: TokenMergeInput, file: string, problems: string[]): FileDiff {\n const base = readSide(file, input.base[file], problems, 'shared start');\n const mine = readSide(file, input.mine[file], problems, 'this change');\n const theirs = readSide(file, input.theirs[file], problems, 'latest library');\n const r = threeWayDiff(base.logical, mine.logical, theirs.logical);\n return { file, base, mine, theirs, local: r.local, remote: r.remote, conflicts: r.conflicts };\n}\n\n/** The side that removed a token the other side changed, or null. */\nexport function removedSide(c: { base?: unknown; mine?: unknown; theirs?: unknown }): MergeSide | null {\n if (!c.base) return null;\n if (!c.mine && c.theirs) return 'mine';\n if (!c.theirs && c.mine) return 'theirs';\n return null;\n}\n\n/** \"Keep mine\" by default, except for a token removed on one side and changed on the other: no default there. */\nexport const defaultChoiceFor = (c: { base?: unknown; mine?: unknown; theirs?: unknown }): MergeSide | null => (removedSide(c) ? null : 'mine');\n\n/** What both sides did to the token files they both changed, and which tokens need a decision. */\nexport function planTokenMerge(input: TokenMergeInput): TokenMergePlan {\n const problems: string[] = [];\n const files = [...new Set(input.files)].sort();\n const conflicts: TokenMergeConflict[] = [];\n let mineOnly = 0;\n let theirsOnly = 0;\n for (const file of files) {\n const d = diffFile(input, file, problems);\n mineOnly += d.local.length;\n theirsOnly += d.remote.length;\n for (const e of d.conflicts) {\n const c = { base: d.base.flat.get(e.id), mine: d.mine.flat.get(e.id), theirs: d.theirs.flat.get(e.id) };\n conflicts.push({ key: `${file}#${e.id}`, file, path: (c.mine ?? c.theirs ?? c.base)!.path, ...c, removedOn: removedSide(c), defaultChoice: defaultChoiceFor(c) });\n }\n }\n return { files, conflicts, mineOnly, theirsOnly, problems };\n}\n\n/** The side a conflict keeps: the designer's pick, else its default (null: still to pick). */\nexport const choiceFor = (c: TokenMergeConflict, choices: MergeChoices): MergeSide | null => choices[c.key] ?? c.defaultChoice;\n\n/** Conflicts that still need a pick: removed on one side, changed on the other, and not decided yet. */\nexport function missingChoices(plan: Pick<TokenMergePlan, 'conflicts'>, choices: MergeChoices): TokenMergeConflict[] {\n return plan.conflicts.filter((c) => choiceFor(c, choices) === null);\n}\n\n/** Puts this change's version of a token into the library's file: its value, type, description and extensions. Also used by token-combine. */\nexport function takeMine(doc: TokenDocument, mine: FlatToken | undefined, existing: FlatToken | undefined): boolean {\n if (!mine) return existing ? removeToken(doc, existing.path) : false;\n let changed = false;\n if (existing && existing.path !== mine.path) changed = removeToken(doc, existing.path) || changed;\n // Extension keys the library has and this change does not are removed, so the token reads as in the change.\n const extensions: Record<string, unknown> = {};\n for (const k of Object.keys(existing?.path === mine.path ? (existing.extensions ?? {}) : {})) extensions[k] = undefined;\n Object.assign(extensions, mine.extensions ?? {});\n return upsertToken(doc, mine.path, { type: mine.type, value: mine.value, description: mine.description, extensions }) || changed;\n}\n\nexport interface TokenMergeResult {\n /** Merged text per file (relative to the tokens root); null when the merged file holds no token and is removed. */\n files: Record<string, string | null>;\n /** How many conflicts kept each side. */\n kept: Record<MergeSide, number>;\n}\n\n/**\n * The merged token files: the latest library's text, plus every token only this change touched, plus each conflict\n * as chosen. Throws when a file could not be read or a conflict still needs a pick.\n */\nexport function applyTokenMerge(input: TokenMergeInput, choices: MergeChoices): TokenMergeResult {\n const plan = planTokenMerge(input);\n if (plan.problems.length) throw new Error(plan.problems[0]);\n const missing = missingChoices(plan, choices);\n if (missing.length) throw new Error(`Pick a value for ${missing.map((c) => c.path).join(', ')} first.`);\n const byKey = new Map(plan.conflicts.map((c) => [c.key, c]));\n const kept: Record<MergeSide, number> = { mine: 0, theirs: 0 };\n const files: Record<string, string | null> = {};\n for (const file of plan.files) {\n const d = diffFile(input, file, []);\n const doc = d.theirs.doc ?? emptyTokenFile(file);\n for (const e of d.local) takeMine(doc, d.mine.flat.get(e.id), d.theirs.flat.get(e.id) ?? d.base.flat.get(e.id));\n for (const e of d.conflicts) {\n const side = choiceFor(byKey.get(`${file}#${e.id}`)!, choices)!;\n kept[side]++;\n if (side === 'mine') takeMine(doc, d.mine.flat.get(e.id), d.theirs.flat.get(e.id));\n }\n const empty = flattenTokens(doc).length === 0;\n files[file] = empty && (input.theirs[file] === undefined || input.mine[file] === undefined) ? null : serializeTokenFile(doc);\n }\n return { files, kept };\n}\n","// Try several changes together: the latest library plus the token edits of 2 to 4 open changes, combined in the\n// browser. Nothing is written anywhere: no branch, no commit. Each change's own edits are what it did to its token\n// files since it started (its start against its current version), so a change that is behind the library never\n// undoes the library's newer values. Edits to the same token that agree are applied once; edits that disagree are a\n// conflict the designer settles (\"Use <change>'s\"). Pure: no fetch, no DOM. Studio (Changes, the library views) and\n// the admin's Bridge toolbar both run it.\n\nimport { emptyTokenFile, flattenTokens, parseTokenFile, serializeTokenFile, type TokenDocument } from './dtcg-codec';\nimport { takeMine } from './token-merge';\nimport { pathId } from './token-set';\nimport { EXT_ID, type FlatToken } from './types';\n\n/** What one change brings: its token files where it started and now, and the token files it edits. */\nexport interface CombineSource {\n number: number;\n /** Token file texts where the change started (relative to the tokens root). Undefined: the file did not exist. */\n base: Record<string, string | undefined>;\n /** Token file texts in the change now. Undefined: the change removes the file. */\n head: Record<string, string | undefined>;\n /** Token files the change edits, relative to the tokens root. */\n files: string[];\n}\n\nexport interface CombineEdit {\n /** `<file>#<token id>`: the same token in the same file across changes. */\n key: string;\n file: string;\n /** The token's path in the change (its old path when the change removes it). */\n path: string;\n change: number;\n /** The change's version of the token; undefined when the change removes it. */\n token: FlatToken | undefined;\n}\n\nexport interface ChangeEdits {\n number: number;\n edits: CombineEdit[];\n /** Files that could not be read (not JSON). */\n problems: string[];\n}\n\nconst idOf = (f: FlatToken) => {\n const id = f.extensions?.[EXT_ID];\n return typeof id === 'string' && id ? id : pathId(f.path);\n};\n\nfunction tokensOf(file: string, text: string | undefined, problems: string[], label: string): Map<string, FlatToken> {\n const out = new Map<string, FlatToken>();\n if (text === undefined) return out;\n try {\n for (const t of flattenTokens(parseTokenFile(file, text))) out.set(idOf(t), t);\n } catch (err) {\n problems.push(`${file} (${label}) is not valid JSON: ${(err as Error).message}`);\n }\n return out;\n}\n\n/** What a token is, for comparing two versions of it: its path, type, value and description. */\nconst shape = (t: FlatToken | undefined) => (t ? JSON.stringify([t.path, t.type ?? null, t.value, t.description ?? null]) : 'removed');\n/** What a token shows, for comparing two changes' edits: removed, or its type and value. */\nconst look = (t: FlatToken | undefined) => (t ? JSON.stringify([t.path, t.type ?? null, t.value]) : 'removed');\n\n/** The token edits of one change: every token whose version differs between where the change started and now. */\nexport function changeEdits(src: CombineSource): ChangeEdits {\n const problems: string[] = [];\n const edits: CombineEdit[] = [];\n for (const file of [...new Set(src.files)].sort()) {\n const before = tokensOf(file, src.base[file], problems, 'start');\n const after = tokensOf(file, src.head[file], problems, `change ${src.number}`);\n for (const id of new Set([...before.keys(), ...after.keys()])) {\n const a = before.get(id);\n const b = after.get(id);\n if (shape(a) === shape(b)) continue;\n edits.push({ key: `${file}#${id}`, file, path: (b ?? a)!.path, change: src.number, token: b });\n }\n }\n return { number: src.number, edits, problems };\n}\n\n/** One value a conflicting token can take, and the changes that set it. */\nexport interface CombineOption {\n changes: number[];\n token: FlatToken | undefined;\n}\n\n/** A token two or more changes set differently: the designer picks one change's value. */\nexport interface CombineConflict {\n key: string;\n file: string;\n path: string;\n /** Distinct values, in the order of the changes. */\n options: CombineOption[];\n}\n\n/** The pick of each conflict: the change whose value the combination uses. */\nexport type CombinePicks = Record<string, number>;\n\nexport interface Combination {\n /** Every token file of the latest library, with the combined edits applied (unchanged files as they are). */\n files: Record<string, string>;\n /** The changes combined, in order. */\n included: number[];\n /** Token values the combination edits (one per token and file: a token edited in light and dark counts twice). */\n edits: number;\n /** Tokens the combination edits, by name. */\n tokens: number;\n conflicts: CombineConflict[];\n /** Conflicts without a pick that counts: left at the library's value ('skip') or given the first change's ('first'). */\n missing: CombineConflict[];\n /** Token path -> the changes whose value the combination uses for it. */\n from: Record<string, number[]>;\n problems: string[];\n}\n\n/** Edits grouped by token, in the order of the changes. */\nfunction byToken(changes: ChangeEdits[]): Map<string, CombineEdit[]> {\n const out = new Map<string, CombineEdit[]>();\n for (const c of changes) for (const e of c.edits) out.set(e.key, [...(out.get(e.key) ?? []), e]);\n return out;\n}\n\nfunction optionsOf(edits: CombineEdit[]): CombineOption[] {\n const out: { look: string; option: CombineOption }[] = [];\n for (const e of edits) {\n const l = look(e.token);\n const hit = out.find((o) => o.look === l);\n if (hit) hit.option.changes.push(e.change);\n else out.push({ look: l, option: { changes: [e.change], token: e.token } });\n }\n return out.map((o) => o.option);\n}\n\n/** Tokens that two or more of these changes set differently. */\nexport function combineConflicts(changes: ChangeEdits[]): CombineConflict[] {\n const out: CombineConflict[] = [];\n for (const [key, edits] of byToken(changes)) {\n const options = optionsOf(edits);\n if (options.length > 1) out.push({ key, file: edits[0]!.file, path: edits[0]!.path, options });\n }\n return out;\n}\n\n/** The option a pick selects, or null when the picked change is not among them (not picked, or switched off). */\nexport function pickedOption(c: CombineConflict, picks: CombinePicks): CombineOption | null {\n const n = picks[c.key];\n return n === undefined ? null : (c.options.find((o) => o.changes.includes(n)) ?? null);\n}\n\n/** Conflicts that still need a pick. */\nexport const unpicked = (conflicts: CombineConflict[], picks: CombinePicks) => conflicts.filter((c) => !pickedOption(c, picks));\n\n/**\n * The latest library plus the edits of the included changes (all of them by default, in their order). A conflict\n * uses the picked change's value. Without a pick that counts, `unpicked: 'skip'` (Studio, before opening) leaves the\n * token at the library's value and lists it in `missing`; `'first'` (the toolbar, when a picked change is switched\n * off) uses the first included change's value and still lists it.\n */\nexport function combineChanges(latest: Record<string, string>, changes: ChangeEdits[], picks: CombinePicks = {}, opts: { include?: number[]; unpicked?: 'skip' | 'first' } = {}): Combination {\n const on = opts.include ? changes.filter((c) => opts.include!.includes(c.number)) : changes;\n const problems = on.flatMap((c) => c.problems);\n const groups = byToken(on);\n const conflicts: CombineConflict[] = [];\n const missing: CombineConflict[] = [];\n const from: Record<string, number[]> = {};\n const docs = new Map<string, TokenDocument>();\n const docOf = (file: string): TokenDocument | null => {\n if (docs.has(file)) return docs.get(file)!;\n const text = latest[file];\n let doc: TokenDocument;\n try {\n doc = text === undefined ? emptyTokenFile(file) : parseTokenFile(file, text);\n } catch (err) {\n problems.push(`${file} (latest library) is not valid JSON: ${(err as Error).message}`);\n return null;\n }\n docs.set(file, doc);\n return doc;\n };\n for (const [key, edits] of groups) {\n const options = optionsOf(edits);\n let use: CombineOption | null = options[0]!;\n if (options.length > 1) {\n const conflict: CombineConflict = { key, file: edits[0]!.file, path: edits[0]!.path, options };\n conflicts.push(conflict);\n use = pickedOption(conflict, picks);\n if (!use) {\n missing.push(conflict);\n use = opts.unpicked === 'first' ? options[0]! : null;\n }\n }\n if (!use) continue;\n const doc = docOf(edits[0]!.file);\n if (!doc) continue;\n const existing = flattenTokens(doc).find((t) => idOf(t) === key.slice(key.indexOf('#') + 1));\n // A removal removes the library's token; an edit replaces it (or adds it when the library does not have it).\n takeMine(doc, use.token, existing);\n const path = use.token?.path ?? edits[0]!.path;\n from[path] = [...new Set([...(from[path] ?? []), ...use.changes])];\n }\n const files: Record<string, string> = { ...latest };\n for (const [file, doc] of docs) {\n if (latest[file] === undefined && flattenTokens(doc).length === 0) continue;\n files[file] = serializeTokenFile(doc);\n }\n const tokens = new Set([...groups.values()].map((e) => e[0]!.path)).size;\n return { files, included: on.map((c) => c.number), edits: groups.size, tokens, conflicts, missing, from, problems };\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// Picks in an address: `118:semantic/light.tokens.json#path:color.bg.default~120:...`. The change number first, then\n// the conflict key; entries joined by \"~\" (keys hold \":\" and \"#\", never \"~\").\n\nexport function encodePicks(picks: CombinePicks): string {\n return Object.entries(picks)\n .filter(([, n]) => Number.isSafeInteger(n) && n > 0)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([key, n]) => `${n}:${key}`)\n .join('~');\n}\n\nexport function decodePicks(raw: string | null | undefined): CombinePicks {\n const out: CombinePicks = {};\n for (const part of (raw ?? '').split('~')) {\n const i = part.indexOf(':');\n if (i < 1) continue;\n const n = Number(part.slice(0, i));\n const key = part.slice(i + 1);\n if (/^\\d{1,7}$/.test(part.slice(0, i)) && n > 0 && key.includes('#')) out[key] = n;\n }\n return out;\n}\n","// CSS custom properties that paint a token set over another one: the live preview of a token draft (Studio Tokens),\n// a change shown in Studio Components, and several changes tried together in the admin's Bridge toolbar. Pure.\nimport { resolve, type ResolveContext } from './resolver';\nimport type { TokenSet } from './token-set';\nimport { formatValue, parseColor, rgbaToHex } from './values';\n\n/** CSS value of a resolved DTCG value, the way tokens.css writes it. */\nexport function cssOf(type: string, value: unknown): string | undefined {\n if (value === undefined) return undefined;\n if (type === 'color') {\n const hex = value && typeof value === 'object' ? (value as { hex?: unknown }).hex : undefined;\n const c = parseColor(value);\n if (!c) return undefined;\n if (c.a < 1) return `rgb(${Math.round(c.r * 255)} ${Math.round(c.g * 255)} ${Math.round(c.b * 255)} / ${c.a})`;\n return typeof hex === 'string' ? hex.toLowerCase() : rgbaToHex(c);\n }\n return formatValue(type, value);\n}\n\nexport const cssVarOf = (path: string) => `--${path.replace(/\\./g, '-')}`;\n\n/**\n * CSS custom properties to set on a scope so it renders `proposed` instead of `head`: every token whose resolved value\n * differs in that context. Setting resolved values (not var() references) keeps chains correct even when the original\n * variable is declared on an ancestor.\n */\nexport function previewOverrides(head: TokenSet, proposed: TokenSet, ctx: ResolveContext): Record<string, string> {\n const out: Record<string, string> = {};\n const hctx = { ...ctx, overrides: head.overrideIndex };\n const pctx = { ...ctx, overrides: proposed.overrideIndex };\n for (const t of proposed.byPath.values()) {\n const a = resolve(head.byPath, t.path, hctx);\n const b = resolve(proposed.byPath, t.path, pctx);\n const css = cssOf(t.type, b.value);\n if (css !== undefined && JSON.stringify(a.value) !== JSON.stringify(b.value)) out[cssVarOf(t.path)] = css;\n }\n return out;\n}\n","// Apply accepted token changes onto main's files. Only files whose text actually changes are\n// returned, and inside them only the edited tokens change (layout, key order, other tools'\n// $extensions and untouched values are preserved byte for byte).\n\nimport {\n type TokenDocument,\n emptyTokenFile,\n moveToken,\n parseTokenFile,\n readTokenAt,\n removeToken,\n serializeTokenFile,\n upsertToken,\n} from './dtcg-codec';\nimport { idExtensionFor } from './id-map';\nimport { defaultScopes, effectiveScopes, sameScopes } from './scopes';\nimport { type TokenSet, defaultFile, modeFile } from './token-set';\nimport { EXT_ID, EXT_SCOPES, type LogicalToken, isMultiMode } from './types';\nimport { valuesEqual } from './values';\n\nexport interface AcceptedChange {\n /** Desired state; undefined removes the token. */\n target: LogicalToken | undefined;\n /** State on main (head) before the change; undefined for additions. */\n current: LogicalToken | undefined;\n}\n\nexport interface ComposeResult {\n /** Changed files only: path relative to the tokens directory -> new text. */\n files: Record<string, string>;\n /** Every token file after the change (changed and unchanged), for validation. */\n allFiles: Record<string, string>;\n}\n\nconst modesOf = (t: LogicalToken) => Object.keys(t.values);\n\nexport function composeFiles(head: TokenSet, originals: Record<string, string>, changes: AcceptedChange[]): ComposeResult {\n const docs = new Map<string, TokenDocument>();\n const doc = (file: string): TokenDocument => {\n let d = docs.get(file);\n if (!d) {\n const text = originals[file];\n d = text === undefined ? emptyTokenFile(file) : parseTokenFile(file, text);\n docs.set(file, d);\n }\n return d;\n };\n // Each value goes back to the file of its tier and mode: brands/<brand>, semantic/<theme>,\n // density/<density>, or the single file of a primitive, base or component token.\n const fileFor = (t: LogicalToken, mode: string, current?: LogicalToken) =>\n current?.files[mode] ??\n t.files[mode] ??\n (isMultiMode(t.tier) ? modeFile(head.layout, t.tier, mode) : undefined) ??\n defaultFile(t.tier, t.path, head.options.dirs);\n\n for (const { target, current } of changes) {\n if (!target) {\n if (current) for (const mode of modesOf(current)) removeToken(doc(fileFor(current, mode)), current.path);\n continue;\n }\n const renamed = !!current && current.path !== target.path;\n if (current) {\n for (const mode of modesOf(current)) {\n const d = doc(fileFor(current, mode));\n if (target.values[mode] === undefined) removeToken(d, current.path);\n else if (renamed) moveToken(d, current.path, target.path);\n }\n }\n\n const targetScopes = effectiveScopes(target);\n const scopesExt = sameScopes(targetScopes, defaultScopes(target.path, target.type, target.tier)) ? undefined : targetScopes;\n const scopesChanged = !current || !sameScopes(targetScopes, effectiveScopes(current));\n const descChanged = (target.description ?? '').trim() !== (current?.description ?? '').trim();\n\n for (const mode of modesOf(target)) {\n const d = doc(fileFor(target, mode, current));\n const existing = readTokenAt(d, target.path);\n const currentValue = current?.values[mode];\n // Keep main's exact spelling when the value is equal (Figma returns float noise).\n const value = currentValue !== undefined && valuesEqual(target.type, target.values[mode], currentValue) ? currentValue : target.values[mode];\n const extensions: Record<string, unknown> = {};\n if (scopesChanged) extensions[EXT_SCOPES] = scopesExt;\n if (renamed || !existing) extensions[EXT_ID] = idExtensionFor(target);\n upsertToken(d, target.path, {\n type: target.type,\n value,\n description: descChanged || !existing ? target.description : existing.description,\n extensions,\n });\n }\n }\n\n const files: Record<string, string> = {};\n const allFiles: Record<string, string> = { ...originals };\n for (const [file, d] of docs) {\n const text = serializeTokenFile(d);\n allFiles[file] = text;\n if (text !== originals[file]) files[file] = text;\n }\n return { files, allFiles };\n}\n","// Library protection: Bridge is the only way into the default branch. Whatever writes (Claude Code, Claude Design,\n// a developer, the MCP server), the change lands on a branch and reaches the default branch through a reviewed pull\n// request. GitHub enforces it with a repository ruleset on the default branch; this module builds that ruleset and\n// reads whether the default branch is protected, from rulesets and from classic branch protection.\n//\n// Pure: no fetch, no DOM. The GitHub reads live in github-client.ts (listRulesets, getRuleset, getBranchProtection,\n// listCheckRuns); Studio, the CLI and the MCP server share these functions.\n\n/** A ruleset rule as GitHub returns and accepts it. */\nexport interface RulesetRule {\n type: string;\n parameters?: Record<string, unknown>;\n}\n\nexport interface RulesetBypassActor {\n actor_id: number | null;\n actor_type: 'RepositoryRole' | 'Team' | 'Integration' | 'OrganizationAdmin' | 'DeployKey';\n bypass_mode: 'always' | 'pull_request';\n}\n\n/** A repository ruleset (GET /repos/{o}/{r}/rulesets/{id}). The list endpoint leaves out `rules`. */\nexport interface Ruleset {\n id?: number;\n name: string;\n target?: 'branch' | 'tag' | 'push' | string;\n enforcement: 'active' | 'evaluate' | 'disabled' | string;\n conditions?: { ref_name?: { include?: string[]; exclude?: string[] } } | null;\n rules?: RulesetRule[];\n bypass_actors?: RulesetBypassActor[];\n /** Where the ruleset is edited on GitHub. */\n html_url?: string;\n _links?: { html?: { href?: string } };\n}\n\n/** The body of POST /repos/{o}/{r}/rulesets. */\nexport interface RulesetPayload {\n name: string;\n target: 'branch';\n enforcement: 'active';\n conditions: { ref_name: { include: string[]; exclude: string[] } };\n rules: RulesetRule[];\n bypass_actors: RulesetBypassActor[];\n}\n\n/**\n * Classic branch protection (GET /repos/{o}/{r}/branches/{b}/protection), the fields Bridge reads.\n * `null` means the branch has none; `undefined` means it could not be read (no token, no admin access).\n */\nexport interface ClassicProtection {\n required_pull_request_reviews?: { required_approving_review_count?: number } | null;\n required_status_checks?: { contexts?: string[]; checks?: { context: string }[] } | null;\n allow_force_pushes?: { enabled: boolean } | null;\n allow_deletions?: { enabled: boolean } | null;\n}\n\n/** What protecting the library takes, in the order Studio names them. */\nexport type ProtectionPart = 'review' | 'checks' | 'history' | 'deletion';\nexport const PROTECTION_PARTS: readonly ProtectionPart[] = ['review', 'checks', 'history', 'deletion'];\n\nexport type ProtectionKind = 'protected' | 'partial' | 'unprotected' | 'unknown';\n\nexport interface ProtectionState {\n kind: ProtectionKind;\n /** Parts not enforced on the default branch (empty when protected; every part when unprotected or unknown). */\n missing: ProtectionPart[];\n /** The Bridge ruleset (by name), when one exists, active or not: \"Complete protection\" updates it in place. */\n bridgeRulesetId?: number;\n /** Where to see the rule that protects the branch on GitHub, when one does. */\n url?: string;\n}\n\n/** The name Bridge gives its ruleset. Bridge finds it again by this name. */\nexport const protectionRulesetName = (defaultBranch: string) => `Protect the library (${defaultBranch})`;\n\n/** GitHub's built-in repository role id for \"Admin\", used in bypass_actors. */\nexport const ADMIN_ROLE_ID = 5;\n\nexport interface ProtectionOptions {\n /** Check names that must pass before a merge (see requiredCheckNames). Empty: no checks rule. */\n checks: string[];\n /** Approvals a pull request needs. Never below 1. */\n approvals: number;\n /** Let repository admins merge a pull request without its approvals (the owner override). */\n adminBypass: boolean;\n}\n\n/**\n * The ruleset that protects the library. Choices:\n * - Target `~DEFAULT_BRANCH`, not a branch name: it follows a rename of the default branch.\n * - `deletion` and `non_fast_forward`: nobody deletes the default branch or rewrites its history.\n * - `pull_request` with at least 1 approval: every change goes through a reviewed pull request, direct pushes are\n * refused whoever pushes. Stale approvals are dismissed on a new push, so what was approved is what merges.\n * Code owner review and \"approval of the most recent push\" stay off: CODEOWNERS often holds placeholders, and a\n * team of two must still be able to ship.\n * - `required_status_checks`: the CI jobs that ran on recent pull requests must pass. Not strict (the branch does\n * not have to be up to date), which keeps merges from queueing behind each other.\n * - Bypass: repository admins in `pull_request` mode only. They keep the owner override (merge a pull request\n * whose approvals are missing) but cannot push to the default branch either.\n */\nexport function protectionRuleset(config: { repo?: { defaultBranch?: string } | undefined } | null | undefined, opts: ProtectionOptions): RulesetPayload {\n const branch = config?.repo?.defaultBranch ?? 'main';\n const approvals = Math.max(1, Math.floor(Number.isFinite(opts.approvals) ? opts.approvals : 1));\n const checks = [...new Set(opts.checks.map((c) => c.trim()).filter(Boolean))];\n const rules: RulesetRule[] = [\n { type: 'deletion' },\n { type: 'non_fast_forward' },\n {\n type: 'pull_request',\n parameters: {\n required_approving_review_count: approvals,\n dismiss_stale_reviews_on_push: true,\n require_code_owner_review: false,\n require_last_push_approval: false,\n required_review_thread_resolution: false,\n },\n },\n ];\n if (checks.length) {\n rules.push({\n type: 'required_status_checks',\n parameters: {\n strict_required_status_checks_policy: false,\n required_status_checks: checks.map((context) => ({ context })),\n },\n });\n }\n return {\n name: protectionRulesetName(branch),\n target: 'branch',\n enforcement: 'active',\n conditions: { ref_name: { include: ['~DEFAULT_BRANCH'], exclude: [] } },\n rules,\n bypass_actors: opts.adminBypass ? [{ actor_id: ADMIN_ROLE_ID, actor_type: 'RepositoryRole', bypass_mode: 'pull_request' }] : [],\n };\n}\n\n/** Minimal check run shape (github-client CheckRun fits). `app` is the GitHub App slug when known. */\nexport interface CheckRunLike {\n name: string;\n status?: string;\n conclusion: string | null;\n app?: string | undefined;\n}\n\nconst isVercel = (r: CheckRunLike) => /vercel/i.test(r.app ?? '') || /^vercel\\b/i.test(r.name);\nconst ran = (r: CheckRunLike) => r.conclusion !== 'skipped' && r.conclusion !== 'cancelled' && r.conclusion !== 'stale';\n\n/**\n * The check names to require, read from the repository's own CI, never hardcoded: the check runs of the default\n * branch's latest commit, without Vercel (deploy previews, not tests) and without skipped ones. When the head of a\n * recent pull request is given, only checks that also ran there are kept: a job that runs on pushes to the default\n * branch only (a release job) never reports on a pull request, and requiring it would block every merge.\n */\nexport function requiredCheckNames(defaultBranchRuns: CheckRunLike[], pullRequestRuns?: CheckRunLike[]): string[] {\n const names = [...new Set(defaultBranchRuns.filter((r) => !isVercel(r) && ran(r)).map((r) => r.name))];\n if (!pullRequestRuns?.length) return names;\n const onPulls = new Set(pullRequestRuns.filter((r) => !isVercel(r)).map((r) => r.name));\n return names.filter((n) => onPulls.has(n));\n}\n\n/** Converts a ref pattern (fnmatch: `*` within a segment, `**` across) to a RegExp. */\nfunction refPattern(pattern: string): RegExp {\n const src = pattern\n .replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\*\\*/g, '\\u0000')\n .replace(/\\*/g, '[^/]*')\n .replace(/\\?/g, '[^/]')\n .replace(/\\u0000/g, '.*');\n return new RegExp(`^${src}$`);\n}\n\n/** True when a branch ruleset's conditions cover the default branch. */\nexport function rulesetTargetsDefault(ruleset: Ruleset, defaultBranch: string): boolean {\n if (ruleset.target && ruleset.target !== 'branch') return false;\n const ref = `refs/heads/${defaultBranch}`;\n const hit = (p: string) => p === '~ALL' || p === '~DEFAULT_BRANCH' || p === ref || p === defaultBranch || refPattern(p.startsWith('refs/') ? p : `refs/heads/${p}`).test(ref);\n const cond = ruleset.conditions?.ref_name;\n // A repository ruleset with no ref condition applies to nothing; GitHub requires one.\n if (!cond) return false;\n if ((cond.exclude ?? []).some(hit)) return false;\n return (cond.include ?? []).some(hit);\n}\n\nconst count = (v: unknown) => (typeof v === 'number' ? v : 0);\n\n/** The parts one ruleset enforces (active rulesets only; \"evaluate\" only reports). */\nfunction rulesetParts(ruleset: Ruleset): Set<ProtectionPart> {\n const parts = new Set<ProtectionPart>();\n if (ruleset.enforcement !== 'active') return parts;\n for (const rule of ruleset.rules ?? []) {\n if (rule.type === 'deletion') parts.add('deletion');\n if (rule.type === 'non_fast_forward') parts.add('history');\n if (rule.type === 'pull_request' && count(rule.parameters?.required_approving_review_count) >= 1) parts.add('review');\n if (rule.type === 'required_status_checks' && Array.isArray(rule.parameters?.required_status_checks) && (rule.parameters.required_status_checks as unknown[]).length > 0) parts.add('checks');\n }\n return parts;\n}\n\n/** The parts classic branch protection enforces. Force pushes and deletions are refused unless allowed. */\nfunction classicParts(p: ClassicProtection): Set<ProtectionPart> {\n const parts = new Set<ProtectionPart>();\n if (count(p.required_pull_request_reviews?.required_approving_review_count) >= 1) parts.add('review');\n if (((p.required_status_checks?.contexts?.length ?? 0) || (p.required_status_checks?.checks?.length ?? 0)) > 0) parts.add('checks');\n if (!p.allow_force_pushes?.enabled) parts.add('history');\n if (!p.allow_deletions?.enabled) parts.add('deletion');\n return parts;\n}\n\nconst rulesetUrl = (r: Ruleset) => r.html_url ?? r._links?.html?.href;\n\n/**\n * Whether the default branch is protected, from full rulesets (with `rules`; null when they could not be read) and\n * classic branch protection (null when the branch has none, undefined when it could not be read).\n * - protected: review, checks, no history rewrite and no deletion are all enforced.\n * - partial: some of them are.\n * - unprotected: none of them, and both sources were read.\n * - unknown: nothing could be read, or nothing was found in one source while the other could not be read.\n */\nexport function protectionState(rulesets: Ruleset[] | null | undefined, branchProtection: ClassicProtection | null | undefined, defaultBranch: string): ProtectionState {\n const bridge = rulesets?.find((r) => r.name === protectionRulesetName(defaultBranch));\n const extra = bridge?.id !== undefined ? { bridgeRulesetId: bridge.id } : {};\n const covered = new Set<ProtectionPart>();\n let url: string | undefined;\n for (const r of rulesets ?? []) {\n if (!rulesetTargetsDefault(r, defaultBranch)) continue;\n const parts = rulesetParts(r);\n if (parts.size && !url) url = rulesetUrl(r);\n parts.forEach((p) => covered.add(p));\n }\n if (branchProtection) classicParts(branchProtection).forEach((p) => covered.add(p));\n const missing = PROTECTION_PARTS.filter((p) => !covered.has(p));\n const withUrl = url ? { url } : {};\n if (!missing.length) return { kind: 'protected', missing, ...extra, ...withUrl };\n const unreadable = rulesets == null || branchProtection === undefined;\n if (covered.size === 0) return { kind: unreadable ? 'unknown' : 'unprotected', missing, ...extra };\n return { kind: 'partial', missing, ...extra, ...withUrl };\n}\n\n/** Plain words for each part, for designers: no \"ruleset\", \"branch\" or \"force push\". */\nexport const PROTECTION_PART_PHRASE: Record<ProtectionPart, string> = {\n review: 'changes can skip review',\n checks: 'checks do not have to pass',\n history: 'past changes can be rewritten',\n deletion: 'the library can be deleted',\n};\n\nconst joinAnd = (xs: string[]) => (xs.length <= 1 ? (xs[0] ?? '') : `${xs.slice(0, -1).join(', ')} and ${xs[xs.length - 1]}`);\n\n/** The one sentence Studio, the CLI and the MCP server show for a protection state. */\nexport function protectionSentence(state: ProtectionState): string {\n switch (state.kind) {\n case 'protected':\n return 'Protected: every change goes through review.';\n case 'unprotected':\n return 'Your library can be changed without review.';\n case 'partial': {\n const s = joinAnd(state.missing.map((p) => PROTECTION_PART_PHRASE[p]));\n return `Partly protected: ${s}.`;\n }\n default:\n return 'Protection status unknown: GitHub did not let this token read it.';\n }\n}\n","// Library protection over the GitHub client: read the state of the default branch, read the checks to require,\n// and create (or complete) the Bridge ruleset. Studio, the CLI and the MCP server call these.\n\nimport { GitHubError, type GitHubClient } from './github-client';\nimport { type ProtectionOptions, protectionRuleset, type ProtectionState, protectionState, requiredCheckNames, type Ruleset } from './protection';\n\n/**\n * The protection of `defaultBranch`. Rulesets are listed (read access is enough), then read one by one for their\n * rules; classic branch protection is read too. Whatever cannot be read counts as unknown, never as unprotected.\n */\nexport async function loadProtection(client: GitHubClient, defaultBranch: string): Promise<ProtectionState> {\n const rulesets = await client\n .listRulesets()\n // Disabled rulesets enforce nothing: kept as listed (the Bridge one is still found by name, to update it).\n .then((list) => Promise.all(list.map((r) => (r.enforcement === 'disabled' || r.id === undefined ? r : client.getRuleset(r.id)))))\n // Any failure (no access, a repo GitHub hides behind a 404, rate limit) leaves the state unknown.\n .catch((): Ruleset[] | null => null);\n const classic = await client.getBranchProtection(defaultBranch).catch(() => undefined);\n return protectionState(rulesets, classic, defaultBranch);\n}\n\n/** The checks to require: the default branch's latest check runs, kept to those the last merged pull request ran. */\nexport async function loadRequiredChecks(client: GitHubClient, defaultBranch: string): Promise<string[]> {\n const onDefault = await client.listCheckRuns(defaultBranch).catch(() => []);\n const merged = await client\n .listPullRequests('closed')\n .then((prs) => prs.find((p) => p.state === 'merged' && p.baseRef === defaultBranch))\n .catch(() => undefined);\n const onPull = merged?.headSha ? await client.listCheckRuns(merged.headSha).catch(() => []) : [];\n return requiredCheckNames(onDefault, onPull);\n}\n\n/**\n * Turns protection on: creates the Bridge ruleset, or replaces it when one with its name exists (Complete\n * protection). Needs a token with admin on the repository; GitHub's refusal is thrown as a GitHubError.\n */\nexport async function protectLibrary(\n client: GitHubClient,\n defaultBranch: string,\n opts: Partial<ProtectionOptions> & { state?: ProtectionState } = {},\n): Promise<Ruleset> {\n const checks = opts.checks ?? (await loadRequiredChecks(client, defaultBranch));\n const payload = protectionRuleset({ repo: { defaultBranch } }, { checks, approvals: opts.approvals ?? 1, adminBypass: opts.adminBypass ?? true });\n const id = opts.state?.bridgeRulesetId;\n return id !== undefined ? client.updateRuleset(id, payload) : client.createRuleset(payload);\n}\n\n/** GitHub's message when the plan does not allow rulesets on a private repository. */\nconst PLAN_REFUSED = /upgrade to github (pro|team)|make this repository public|not available for private repositories/i;\n\n/** True when GitHub refused the ruleset because of the repository's plan, not the token. */\nexport const isPlanRefusal = (err: unknown) => err instanceof GitHubError && (err.status === 403 || err.status === 422) && PLAN_REFUSED.test(`${err.detail ?? ''} ${err.message}`);\n\n/** Where rulesets are managed on GitHub. */\nexport const rulesSettingsUrl = (owner: string, repo: string) => `https://github.com/${owner}/${repo}/settings/rules`;\n\n/**\n * The one sentence for a refused \"Protect the library\": the plan, the token's permission, or admin access.\n * Null for any other failure (the caller shows GitHub's message).\n */\nexport function protectRefusal(err: unknown): string | null {\n if (!(err instanceof GitHubError)) return null;\n if (isPlanRefusal(err)) return \"GitHub's plan for this private repository does not include protection rules. Upgrade the plan or make the repository public, then try again.\";\n // \"Must have admin rights\": the person is not an admin, whatever the token allows.\n if (/admin rights/i.test(`${err.detail ?? ''}`)) return 'Only a repository admin can protect the library. Ask an admin, or set it up in GitHub settings.';\n if (err.auth === 'missing-permission') return 'This token cannot change the protection. Add Administration: Read and write to the token on GitHub, then try again.';\n if (err.status === 403 || err.status === 404) return 'Only a repository admin can protect the library. Ask an admin, or set it up in GitHub settings.';\n return null;\n}\n","// Usage index: which CSS custom properties each component module reads, and which other components it renders.\n// Pure text scanning (no CSS or TypeScript parser), so it runs in Node, the browser and the Figma sandbox alike.\n// Used by visual impact analysis to go from changed tokens and files to the components (and stories) to look at.\n\nexport interface UsageFile {\n /** Repo-relative path with forward slashes. */\n path: string;\n text: string;\n}\n\nexport interface UsageModule {\n /** Component folder name, e.g. \"Button\". */\n id: string;\n dir: string;\n files: string[];\n /** CSS custom properties read with var(), sorted. Includes locally defined ones. */\n vars: string[];\n /** Other components this one imports from its source (stories and tests excluded), sorted. */\n imports: string[];\n /** Components that only its stories import (e.g. a Button inside an Alert story), sorted. */\n storyImports: string[];\n}\n\nexport interface UsageIndex {\n componentsDir: string;\n modules: Record<string, UsageModule>;\n /** CSS custom property -> modules that read it. */\n byVar: Record<string, string[]>;\n /** CSS custom properties read by files outside the component folders (global styles, theme). */\n globalVars: Record<string, string[]>;\n}\n\nconst VAR_RE = /var\\(\\s*(--[A-Za-z0-9_-]+)/g;\nconst IMPORT_RE = /(?:import|export)\\s[^'\"]*?from\\s*['\"]([^'\"]+)['\"]|import\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g;\n\n/** CSS custom properties read with `var(--x)` in a stylesheet or a style string, in order of first use. */\nexport function cssVarsIn(text: string): string[] {\n const out = new Set<string>();\n for (const m of text.matchAll(VAR_RE)) out.add(m[1]!);\n return [...out];\n}\n\n/** Module specifiers a TS/JS file imports or re-exports. */\nexport function importsIn(text: string): string[] {\n const out = new Set<string>();\n for (const m of text.matchAll(IMPORT_RE)) out.add((m[1] ?? m[2])!);\n return [...out];\n}\n\nconst norm = (p: string) => p.replace(/\\\\/g, '/').replace(/\\/+$/, '');\nconst isStory = (p: string) => /\\.stories\\.[cm]?[jt]sx?$/.test(p);\nconst isTest = (p: string) => /\\.(test|spec)\\.[cm]?[jt]sx?$/.test(p);\nconst isCss = (p: string) => /\\.(css|scss|less)$/.test(p);\nconst isScript = (p: string) => /\\.[cm]?[jt]sx?$/.test(p);\n\n/** Resolves a relative specifier from a file to the component folder it lands in, if any. */\nfunction componentOf(from: string, spec: string, componentsDir: string): string | null {\n if (!spec.startsWith('.')) return null;\n const parts = from.split('/').slice(0, -1);\n for (const seg of spec.split('/')) {\n if (seg === '.' || seg === '') continue;\n if (seg === '..') parts.pop();\n else parts.push(seg);\n }\n const abs = parts.join('/');\n if (!abs.startsWith(`${componentsDir}/`)) return null;\n return abs.slice(componentsDir.length + 1).split('/')[0] || null;\n}\n\n/** The component folder a repo path belongs to, or null when it is outside `componentsDir`. */\nexport function componentForPath(path: string, componentsDir: string): string | null {\n const dir = norm(componentsDir);\n const p = norm(path);\n if (!p.startsWith(`${dir}/`)) return null;\n const rest = p.slice(dir.length + 1).split('/');\n return rest.length >= 2 ? rest[0]! : null;\n}\n\n/**\n * Builds the index from the files of a component library. `componentsDir` holds one folder per component\n * (`<dir>/<Name>/...`); every other file is \"global\" (styles, theme, story helpers) and only its CSS\n * variables are recorded.\n */\nexport function buildUsageIndex(files: UsageFile[], componentsDir: string): UsageIndex {\n const dir = norm(componentsDir);\n const modules: Record<string, UsageModule> = {};\n const vars = new Map<string, Set<string>>();\n const imports = new Map<string, Set<string>>();\n const storyImports = new Map<string, Set<string>>();\n const globalVars: Record<string, string[]> = {};\n const get = (m: Map<string, Set<string>>, k: string) => m.get(k) ?? m.set(k, new Set()).get(k)!;\n\n for (const f of files) {\n const path = norm(f.path);\n const id = componentForPath(path, dir);\n if (!id) {\n if (isCss(path)) {\n const v = cssVarsIn(f.text);\n if (v.length) globalVars[path] = v.sort();\n }\n continue;\n }\n const mod = (modules[id] ??= { id, dir: `${dir}/${id}`, files: [], vars: [], imports: [], storyImports: [] });\n mod.files.push(path);\n if (isTest(path)) continue;\n // Inline styles in TSX can read variables too (style={{ color: 'var(--x)' }}).\n for (const v of cssVarsIn(f.text)) get(vars, id).add(v);\n if (!isScript(path)) continue;\n for (const spec of importsIn(f.text)) {\n const dep = componentOf(path, spec, dir);\n if (!dep || dep === id) continue;\n get(isStory(path) ? storyImports : imports, id).add(dep);\n }\n }\n\n const byVar: Record<string, string[]> = {};\n for (const mod of Object.values(modules)) {\n mod.files.sort();\n mod.vars = [...(vars.get(mod.id) ?? [])].sort();\n mod.imports = [...(imports.get(mod.id) ?? [])].sort();\n mod.storyImports = [...(storyImports.get(mod.id) ?? [])].filter((d) => !mod.imports.includes(d)).sort();\n for (const v of mod.vars) (byVar[v] ??= []).push(mod.id);\n }\n for (const k of Object.keys(byVar)) byVar[k]!.sort();\n return { componentsDir: dir, modules, byVar, globalVars };\n}\n\nexport interface ImpactedModule {\n id: string;\n /** Why: \"uses --color-feedback-danger-solid\", \"file changed: ...\", \"renders Button\". */\n reasons: string[];\n /** True when reached only through another component it renders. */\n indirect: boolean;\n}\n\nexport interface ModuleImpact {\n modules: ImpactedModule[];\n /** Global stylesheets that read a changed variable. */\n globalHits: { file: string; vars: string[] }[];\n}\n\n/**\n * Components affected by changed CSS variables and changed files, closed over \"renders\": when Button changes,\n * every component that imports Button changes too.\n */\nexport function impactedModules(index: UsageIndex, input: { vars?: string[]; files?: string[] }): ModuleImpact {\n const reasons = new Map<string, { reasons: string[]; indirect: boolean }>();\n const add = (id: string, reason: string, indirect: boolean) => {\n const r = reasons.get(id);\n if (r) {\n if (!r.reasons.includes(reason)) r.reasons.push(reason);\n r.indirect &&= indirect;\n } else reasons.set(id, { reasons: [reason], indirect });\n };\n const changedVars = new Set(input.vars ?? []);\n for (const v of changedVars) for (const id of index.byVar[v] ?? []) add(id, `uses ${v}`, false);\n for (const f of input.files ?? []) {\n const id = componentForPath(f, index.componentsDir);\n if (id && index.modules[id]) add(id, `file changed: ${norm(f)}`, false);\n }\n // Reverse \"renders\" edges, breadth first so the closest reason is listed first.\n const renderedBy = new Map<string, string[]>();\n for (const m of Object.values(index.modules)) for (const d of m.imports) (renderedBy.get(d) ?? renderedBy.set(d, []).get(d)!).push(m.id);\n const queue = [...reasons.keys()];\n while (queue.length) {\n const id = queue.shift()!;\n for (const parent of renderedBy.get(id) ?? []) {\n const known = reasons.has(parent);\n add(parent, `renders ${id}`, true);\n if (!known) queue.push(parent);\n }\n }\n const globalHits = Object.entries(index.globalVars)\n .map(([file, vs]) => ({ file, vars: vs.filter((v) => changedVars.has(v)) }))\n .filter((g) => g.vars.length > 0);\n const modules = [...reasons.entries()].map(([id, r]) => ({ id, reasons: r.reasons, indirect: r.indirect })).sort((a, b) => Number(a.indirect) - Number(b.indirect) || a.id.localeCompare(b.id));\n return { modules, globalHits };\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// Token usage: which tokens are in use. One definition for every surface (Overview, Checks, the token explorer).\n\nexport interface UsageToken {\n path: string;\n /** CSS custom property the token builds to, e.g. \"--color-bg-default\". */\n cssVar: string;\n /** Token paths this token resolves through, in any mode (its alias chains). May include the token itself. */\n refs: readonly string[];\n}\n\nexport interface TokenReads {\n /** CSS custom property -> components that read it (UsageIndex.byVar). */\n byVar?: Record<string, readonly string[]>;\n /** Global stylesheet -> CSS custom properties it reads (UsageIndex.globalVars): base styles, app shell, theme. */\n globalVars?: Record<string, readonly string[]>;\n}\n\nexport interface TokenUsage {\n /** Paths of every token in use. */\n used: Set<string>;\n /** Paths read directly with var(), by a component or a global stylesheet. */\n direct: Set<string>;\n}\n\n/**\n * A token is in use when a component stylesheet or a global stylesheet (base styles, the app shell) reads its\n * variable, or when a token in use aliases it, at any depth and in any mode. Everything else is unused.\n */\nexport function tokenUsage(tokens: readonly UsageToken[], reads: TokenReads): TokenUsage {\n const readVars = new Set<string>();\n for (const [v, mods] of Object.entries(reads.byVar ?? {})) if (mods.length) readVars.add(v);\n for (const vars of Object.values(reads.globalVars ?? {})) for (const v of vars) readVars.add(v);\n const byPath = new Map(tokens.map((t) => [t.path, t]));\n const direct = new Set(tokens.filter((t) => readVars.has(t.cssVar)).map((t) => t.path));\n const used = new Set<string>();\n const queue = [...direct];\n while (queue.length) {\n const p = queue.pop()!;\n if (used.has(p)) continue;\n used.add(p);\n for (const r of byPath.get(p)?.refs ?? []) if (!used.has(r) && byPath.has(r)) queue.push(r);\n }\n return { used, direct };\n}\n","// History from GitHub over REST, in the browser or Node: commits that touched the tokens root on a ref,\n// the pull request each one belongs to, token files at each side of the change (blobs cached by sha, so\n// files that did not change are read once), changesets the change added, tags and the CHANGELOG.\n\nimport type { BridgeConfig } from './config';\nimport type { GitHubClient, TreeEntry } from './github-client';\nimport { type HistoryBackend, type HistoryCommit, type HistoryReport, buildReport, collectHistory, mergeReleases, packageDirCandidates, parseChangelog, releasesFromTags } from './history';\nimport { selectTokenFiles } from './layered';\n\nexport function gitHubHistoryBackend(client: GitHubClient, config: BridgeConfig, opts: { concurrency?: number } = {}): HistoryBackend & { tree(sha: string): Promise<TreeEntry[]> } {\n const trees = new Map<string, Promise<TreeEntry[]>>();\n const tree = (sha: string) => {\n let t = trees.get(sha);\n if (!t) {\n t = client.getCommitTree(sha).then((ts) => client.getTree(ts, true)).then((r) => r.entries);\n trees.set(sha, t);\n }\n return t;\n };\n const root = config.tokens.root.replace(/\\/$/, '');\n const prefix = root === '.' || !root ? '' : `${root}/`;\n const limit = Math.max(1, opts.concurrency ?? 4);\n const pool = async <T, R>(items: T[], fn: (x: T) => Promise<R>): Promise<R[]> => {\n const out: R[] = new Array(items.length);\n let i = 0;\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {\n for (let k = i++; k < items.length; k = i++) out[k] = await fn(items[k]!);\n }));\n return out;\n };\n\n return {\n tree,\n async listCommits({ ref, paths, limit: max }) {\n const commits: HistoryCommit[] = [];\n for (let page = 1; commits.length < max && page <= 10; page++) {\n const batch = await client.listCommits({ sha: ref, path: paths[0], perPage: Math.min(100, max), page });\n for (const c of batch) {\n const [subject, ...rest] = c.message.split('\\n');\n commits.push({ sha: c.sha, parents: c.parents, date: c.date, author: c.author, subject: subject ?? '', body: rest.join('\\n').trim() });\n }\n if (batch.length < Math.min(100, max)) break;\n }\n const list = commits.slice(0, max);\n // The pull request of each commit. A branch commit of a merged PR is replaced by the PR's merge commit,\n // so the entry diffs the whole PR as it landed.\n const merges = new Map<string, Promise<HistoryCommit | undefined>>();\n const enriched = await pool(list, async (c) => {\n const prs = await client.listPullRequestsForCommit(c.sha).catch(() => []);\n const pr = prs.find((p) => p.mergedAt && p.baseRef === ref) ?? prs.find((p) => p.mergedAt);\n if (!pr) return c;\n const prInfo = { number: pr.number, title: pr.title, url: pr.url, author: pr.author, ...(pr.mergedAt ? { mergedAt: pr.mergedAt } : {}), body: pr.body };\n if (pr.mergeCommitSha && pr.mergeCommitSha !== c.sha) {\n let m = merges.get(pr.mergeCommitSha);\n if (!m) {\n m = client.getCommitInfo(pr.mergeCommitSha).then(\n (info) => {\n const [subject, ...rest] = info.message.split('\\n');\n return { sha: info.sha, parents: info.parents, date: pr.mergedAt ?? info.date, author: info.author, subject: subject ?? '', body: rest.join('\\n').trim() };\n },\n () => undefined,\n );\n merges.set(pr.mergeCommitSha, m);\n }\n const merge = await m;\n if (merge) return { ...merge, pr: prInfo };\n }\n return { ...c, ...(pr.mergedAt ? { date: pr.mergedAt } : {}), pr: prInfo };\n });\n return enriched;\n },\n async tokenFiles(sha) {\n const entries = await tree(sha);\n const blobs = entries.filter((e) => e.type === 'blob' && e.path.startsWith(prefix));\n const picked = new Set(selectTokenFiles(config, blobs.map((e) => e.path)));\n const wanted = blobs.filter((e) => picked.has(prefix ? e.path.slice(prefix.length) : e.path));\n const texts = await pool(wanted, async (e) => [prefix ? e.path.slice(prefix.length) : e.path, await client.getBlobText(e.sha)] as const);\n return new Map(texts);\n },\n async changesetPaths(sha) {\n const dir = config.changesets?.dir.replace(/\\/$/, '');\n if (!dir) return [];\n return (await tree(sha)).filter((e) => e.type === 'blob' && e.path.startsWith(`${dir}/`)).map((e) => e.path);\n },\n async readFile(sha, path) {\n const e = (await tree(sha)).find((x) => x.type === 'blob' && x.path === path);\n return e ? client.getBlobText(e.sha) : null;\n },\n };\n}\n\n/** The whole history report for a GitHub repo: entries, releases (tags and CHANGELOG), timeline. */\nexport async function loadGitHubHistory(client: GitHubClient, config: BridgeConfig, opts: { ref?: string; limit?: number; onProgress?: (done: number, total: number) => void } = {}): Promise<HistoryReport> {\n const ref = opts.ref ?? config.repo?.defaultBranch ?? (await client.getDefaultBranch());\n const limit = opts.limit ?? 30;\n const backend = gitHubHistoryBackend(client, config);\n let listed = 0;\n const counted: HistoryBackend = { ...backend, listCommits: async (o) => {\n const r = await backend.listCommits(o);\n listed = r.length;\n return r;\n } };\n const entries = await collectHistory(config, counted, { ref, limit, ...(opts.onProgress ? { onProgress: opts.onProgress } : {}) });\n const head = await client.getBranchSha(ref).catch(() => undefined);\n let changelog: ReturnType<typeof parseChangelog> = [];\n let currentVersion: string | undefined;\n if (head) {\n const files = await backend.tree(head).catch(() => [] as TreeEntry[]);\n for (const dir of packageDirCandidates(config)) {\n const p = (f: string) => (dir ? `${dir}/${f}` : f);\n const cl = files.find((e) => e.path === p('CHANGELOG.md'));\n const pkg = files.find((e) => e.path === p('package.json'));\n if (!cl && !pkg) continue;\n if (cl) changelog = parseChangelog(await client.getBlobText(cl.sha));\n if (pkg) {\n try {\n const json = JSON.parse(await client.getBlobText(pkg.sha)) as { name?: string; version?: string };\n if (!config.changesets || json.name === config.changesets.package) currentVersion = json.version;\n } catch {\n /* not JSON: no version */\n }\n }\n break;\n }\n }\n const tagList = await client.listTags(30).catch(() => []);\n const tagReleases = releasesFromTags(tagList, config.changesets?.package);\n // Tag dates cost one request each: only the ten newest.\n await Promise.all(\n tagReleases.slice(0, 10).map(async (r) => {\n if (!r.sha) return;\n const info = await client.getCommitInfo(r.sha).catch(() => undefined);\n if (info?.date) r.date = info.date;\n }),\n );\n const releases = mergeReleases(changelog, tagReleases);\n return buildReport({ source: 'github', label: `${client.fullName}@${ref}`, ref, entries, releases, ...(currentVersion ? { currentVersion } : {}), truncated: listed >= limit });\n}\n","// Demo history: fixture entries built backwards from the CURRENT token files, so a revert or a restore\n// planned on them runs against the real base branch. For showing the History UI on a repo with little\n// history. Every entry is flagged `demo`, has no PR link, and the report says `demo: true`: surfaces show\n// it only behind an explicit, labelled toggle and never as real history.\n\nimport type { BridgeConfig } from './config';\nimport { type HistoryEntry, type HistoryReport, buildHistoryEntry, buildReport } from './history';\nimport { LayeredTokenSet } from './layered';\nimport { type TokenEdit, applyTokenEdits } from './token-edits';\n\ninterface DemoStep {\n pr: number;\n title: string;\n why: string;\n author: string;\n date: string;\n /** The values BEFORE this step; the values after it are whatever the next state holds. */\n before: TokenEdit[];\n}\n\nconst STEPS: DemoStep[] = [\n { pr: 101, title: 'Darken muted text for small sizes', why: 'Muted captions at 12px read too light on subtle surfaces in usability tests.', author: 'demo-designer', date: '2026-07-08T09:30:00Z', before: [{ op: 'set', path: 'color.text.muted', file: 'semantic/light.tokens.json', value: '{palette.neutral.500}' }] },\n { pr: 102, title: 'Rounder buttons', why: 'Buttons move to the control radius so they match inputs and selects.', author: 'demo-engineer', date: '2026-07-21T14:10:00Z', before: [{ op: 'set', path: 'button.radius', file: 'components/button.tokens.json', value: '{radius.inset}' }] },\n { pr: 104, title: 'Clarify the alert radius description', why: 'The description now says why alerts use the container radius.', author: 'demo-engineer', date: '2026-08-19T08:00:00Z', before: [{ op: 'set', path: 'alert.radius', file: 'components/feedback.tokens.json', description: 'Alert corner radius.' }] },\n { pr: 106, title: 'Muted text one step lighter', why: 'Muted text competed with body text in dense tables; one step lighter still passes 4.5:1.', author: 'demo-designer', date: '2026-09-30T16:45:00Z', before: [{ op: 'set', path: 'color.text.muted', file: 'semantic/light.tokens.json', value: '{palette.neutral.700}' }] },\n];\n\nexport const DEMO_RELEASES = [\n { version: '1.1.0', date: '2026-07-25T12:00:00Z' },\n { version: '1.2.0', date: '2026-08-25T12:00:00Z' },\n];\n\n/** Demo history over the current files. Steps whose tokens this repo does not have are left out. */\nexport function demoHistory(config: BridgeConfig, current: Map<string, string>): HistoryReport {\n const states: Map<string, string>[] = [current];\n const kept: DemoStep[] = [];\n for (const step of [...STEPS].reverse()) {\n try {\n const prev = applyTokenEdits(new LayeredTokenSet(config, states[0]!), step.before).files;\n states.unshift(prev);\n kept.unshift(step);\n } catch {\n /* this repo has no such token: skip the step */\n }\n }\n const entries: HistoryEntry[] = [];\n kept.forEach((step, i) => {\n const e = buildHistoryEntry({\n config,\n commit: { sha: `demo${String(step.pr).padStart(36, '0')}`, parents: [`demo${String(step.pr - 1).padStart(36, '0')}`], date: step.date, author: step.author, subject: step.title, body: step.why, pr: { number: step.pr, title: step.title, author: step.author, mergedAt: step.date, body: step.why } },\n before: states[i]!,\n after: states[i + 1]!,\n demo: true,\n });\n if (e) entries.push(e);\n });\n return { ...buildReport({ source: 'demo', label: 'Demo history (fixture data)', ref: 'demo', entries, releases: DEMO_RELEASES, truncated: false }), demo: true };\n}\n","// Real branch preview URLs read from GitHub: the deployments and commit statuses of the head commit and the Vercel\n// bot comment on the pull request, resolved by `resolveBranchPreviews` (previews.ts). Shared by the plugin, Studio,\n// the MCP server and the CLI, so none of them shows a guessed URL. See docs/PREVIEWS.md.\n\nimport type { BridgeConfig } from './config';\nimport type { GitHubClient } from './github-client';\nimport { resolveBranchPreviews, type BranchPreview, type PreviewApps } from './previews';\n\nexport interface BranchPreviewOptions {\n /** Branch and head commit when the caller knows them (skips reading the pull request). */\n branch?: string | undefined;\n sha?: string | undefined;\n /** The pull request's comments when the caller already read them (skips one read). */\n comments?: { body?: string | null | undefined }[] | undefined;\n}\n\n/**\n * The preview of each app configured in `previews.apps` for a pull request (by number) or a commit (by sha): the URL\n * Vercel reports (deployments, then commit statuses, then its PR comment), the template only when Vercel cannot have\n * shortened it, and whether the build of that commit is ready. A failed read leaves that source out, never throws for it.\n */\nexport async function branchPreviewUrls(gh: GitHubClient, ref: number | string, config: Pick<BridgeConfig, 'previews'> | { previews?: { apps?: PreviewApps | undefined } | undefined } | undefined, opts: BranchPreviewOptions = {}): Promise<BranchPreview[]> {\n const apps: PreviewApps = config?.previews?.apps ?? {};\n if (!Object.values(apps).some(Boolean)) return [];\n let pr: number | undefined;\n let branch = opts.branch;\n let sha = opts.sha;\n if (typeof ref === 'number') {\n pr = ref;\n if (!branch || !sha) {\n const p = await gh.getPullRequest(ref);\n branch ??= p.headRef;\n sha ??= p.headSha;\n }\n } else {\n sha = ref;\n if (!branch || !opts.comments) {\n const open = (await gh.listPullRequestsForCommit(ref).catch(() => [])).find((p) => p.state === 'open');\n if (open) {\n pr = open.number;\n branch ??= open.headRef;\n }\n }\n }\n const [comments, statuses, deployments] = await Promise.all([\n opts.comments ? Promise.resolve(opts.comments) : pr !== undefined ? gh.listIssueComments(pr).catch(() => []) : Promise.resolve([]),\n sha ? gh.listCommitStatuses(sha).catch(() => []) : Promise.resolve([]),\n sha ? gh.listDeployments(sha).catch(() => []) : Promise.resolve([]),\n ]);\n return resolveBranchPreviews(apps, { branch: branch ?? '', ...(pr !== undefined ? { pr } : {}), ...(sha ? { sha } : {}) }, { comments, statuses, deployments });\n}\n","// The Bridge ramp engine: OKLCH color ramps on one shared lightness ladder (docs/DESIGN-LANGUAGE.md, section 4).\n// Pure and dependency-free, written as plain JavaScript so two very different callers run the same code:\n// packages/tokens/scripts/ramps.mjs regenerates src/primitives/color.tokens.json (plain Node, no build)\n// @bridge-ds/core planNewBrand generates the palette of a new brand (plugin, docs site, CLI, MCP)\n// Types live next to it in ramps.d.ts. Change the algorithm here and both stay in step.\n\n/** Ramp steps, lightest first. */\nexport const STEPS = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950];\n\n/** OKLCH lightness of every step: the same step has the same perceived lightness whatever the hue. */\nexport const LIGHTNESS = { 50: 0.975, 100: 0.952, 200: 0.912, 300: 0.85, 400: 0.735, 500: 0.63, 600: 0.53, 700: 0.445, 800: 0.36, 900: 0.27, 950: 0.205 };\n\n/** Chroma bell: share of the peak chroma per step, peaking around 500 and 600. */\nexport const BELL = { 50: 0.12, 100: 0.22, 200: 0.4, 300: 0.62, 400: 0.85, 500: 1, 600: 1, 700: 0.92, 800: 0.8, 900: 0.62, 950: 0.5 };\n\n/** Bridge's ink anchors (Line, Ink secondary, Ink): pinned in the bridge neutral by scripts/ramps.mjs. */\nexport const NEUTRAL_ANCHORS = { 200: '#E3E8EE', 600: '#5B6672', 900: '#15202B' };\n\n/** How far a pinned brand hex may sit from its ladder step before the ramp stops reading as one family. */\nexport const PIN_TOLERANCE = 0.04;\n\n/** Chroma curve of a colored ramp (primary, status, accents). */\nexport const bellChroma = (peak) => (s) => peak * BELL[s];\n\n/** Chroma curve of a neutral ramp (ink, slate): nearly grey at the light end, a visible hue at the dark end. */\nexport const neutralChroma =\n (scale = 1, low = 0.004, base = 0.01, slope = 0.022) =>\n (s) =>\n (s <= 100 ? low : base + slope * (s / 950)) * scale;\n\nexport function oklchToLinear(L, C, h) {\n const hr = (h * Math.PI) / 180;\n const a = C * Math.cos(hr);\n const b = C * Math.sin(hr);\n const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3;\n const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3;\n const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3;\n return [\n 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,\n -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,\n -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,\n ];\n}\n\nconst encode = (x) => {\n const c = Math.min(1, Math.max(0, x));\n return c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055;\n};\nconst decode = (x) => (x <= 0.04045 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4);\n\n/** sRGB (0..1 components) of an OKLCH color, gamut-mapped by lowering chroma until it fits. */\nexport function oklch(L, C, h) {\n let c = C;\n let lin = oklchToLinear(L, c, h);\n for (let i = 0; i < 60 && !lin.every((x) => x >= -0.0005 && x <= 1.0005); i++) {\n c *= 0.95;\n lin = oklchToLinear(L, c, h);\n }\n return lin.map(encode);\n}\n\n/** OKLCH of an sRGB color (0..1 components). Hue is 0 for greys. */\nexport function toOklch(rgb) {\n const [r, g, b] = rgb.map(decode);\n const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);\n const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);\n const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);\n const L = 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s;\n const A = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s;\n const B = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s;\n const C = Math.sqrt(A * A + B * B);\n const h = C < 1e-6 ? 0 : ((Math.atan2(B, A) * 180) / Math.PI + 360) % 360;\n return { L, C, h };\n}\n\nexport const isHex = (s) => typeof s === 'string' && /^#[0-9a-f]{6}$/i.test(s.trim());\nexport const fromHex = (hex) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255);\nexport const round3 = (x) => Math.round(x * 1000) / 1000;\nexport const toHex = (rgb) => '#' + rgb.map((x) => Math.round(x * 255).toString(16).padStart(2, '0')).join('');\n\n/** DTCG 2025.10 color value in the house form: { colorSpace, components, hex, alpha? }. */\nexport function dtcgColor(rgb, alpha) {\n const v = { colorSpace: 'srgb', components: rgb.map(round3), hex: toHex(rgb) };\n if (alpha !== undefined) v.alpha = alpha;\n return v;\n}\n\n/**\n * One ramp: step -> sRGB. `chroma(step)` and `offset(step)` shape it; `pins` replace steps with exact brand hexes,\n * so named brand colors survive regeneration.\n */\nexport function generateRamp({ hue, chroma, offset = () => 0, pins = {} }) {\n const out = {};\n for (const s of STEPS) {\n const pin = pins[s];\n out[s] = pin ? fromHex(pin) : oklch(LIGHTNESS[s] + offset(s), chroma(s), hue);\n }\n return out;\n}\n\n/** Ladder step whose lightness is closest to an sRGB color. */\nexport function nearestStep(rgb) {\n const { L } = toOklch(rgb);\n let best = STEPS[0];\n for (const s of STEPS) if (Math.abs(LIGHTNESS[s] - L) < Math.abs(LIGHTNESS[best] - L)) best = s;\n return best;\n}\n\n/**\n * A colored ramp anchored on a brand hex: hue from the hex, peak chroma so the curve passes through it, and the\n * hex pinned at `pinStep` (or at its nearest step). `distance` is how far the hex sits from the ladder lightness\n * of the pinned step; above PIN_TOLERANCE the ramp is no longer monotonic around the pin.\n */\nexport function anchoredRamp(hex, pinStep) {\n const rgb = fromHex(hex);\n const { L, C, h } = toOklch(rgb);\n const step = pinStep ?? nearestStep(rgb);\n const peak = Math.min(0.24, Math.max(0.02, C / BELL[step]));\n return { hue: h, peak, step, distance: Math.abs(L - LIGHTNESS[step]), ramp: generateRamp({ hue: h, chroma: bellChroma(peak), pins: { [step]: hex.toUpperCase() } }) };\n}\n\n/**\n * Lightness offsets of a generated neutral: the steps text and lines use sit exactly where Bridge's ink anchors\n * sit, so muted text (600) keeps its contrast on zones and subtle backgrounds in every new brand.\n */\nexport function neutralOffset() {\n const off = {};\n for (const [s, hex] of Object.entries(NEUTRAL_ANCHORS)) off[s] = toOklch(fromHex(hex)).L - LIGHTNESS[s];\n return (s) => off[s] ?? 0;\n}\n\n/** A neutral ramp tinted by a hex: hue from the hex, chroma scaled by how tinted it is (0 for a pure grey). */\nexport function tintedNeutral(hex) {\n const rgb = fromHex(hex);\n const { C, h } = toOklch(rgb);\n const ref = neutralChroma()(nearestStep(rgb));\n const scale = C < 0.004 ? 0 : Math.min(2.5, C / ref);\n return { hue: h, scale, ramp: generateRamp({ hue: h, chroma: neutralChroma(scale), offset: neutralOffset() }) };\n}\n","// New brands: one planner shared by the CLI (`bridge brand create`), the MCP server (bridge_plan_brand,\n// bridge_propose_brand), the Figma plugin (a new mode in the Brand collection) and the docs site Studio.\n//\n// A brand only re-points palette roles, radius roles, font roles and typography families (docs/DESIGN-LANGUAGE.md,\n// \"Second brand\"). planNewBrand copies a starting brand (or the default brand's structure for \"blank\"), fills\n// the primary, accent, link and neutral palette roles with ramps from the shared ramp engine (ramps.js, the\n// code packages/tokens/scripts/ramps.mjs runs), copies the starting brand's theme overrides when it has any,\n// adds the slug to modes.brand in bridge.config.json and runs the contrast gate for the new brand in every theme.\n// Nothing is written: the result lists files, contrast, validation, risk tier and a PR body; each surface decides\n// where the files go (a local branch, a remote pull request), never to the default branch.\n\nimport { CONFIG_FILE, type BridgeConfig, loadConfig, tokensPath, toConfigJson } from './config';\nimport { formatChangeset } from './changeset';\nimport { type Combo, type LayerIssue, LayeredTokenSet, validateLayered } from './layered';\nimport { type LayeredContrastResult, checkLayeredPair } from './layered-review';\nimport { RISK_LABELS, type RiskResult, classifyRisk } from './risk';\nimport { type Step, LIGHTNESS, PIN_TOLERANCE, STEPS, anchoredRamp, bellChroma, dtcgColor, fromHex, generateRamp, isHex, neutralChroma, neutralOffset, tintedNeutral, toOklch } from './ramps';\nimport { coerceValue } from './token-edits';\nimport { type ContrastPair, parseContrastChecks } from './wcag';\n\n// --- inputs -----------------------------------------------------------------------------------------------\n\n/** A ramp anchor: a \"#rrggbb\" brand color (pinned in the ramp) or an OKLCH hue in degrees (0..360). */\nexport type HueInput = string | number;\n\nexport interface BrandRadiusInput {\n /** px, on the radius scale (0, 2, 4, 6, 10, 12, 16, 20). */\n inset?: number;\n control?: number;\n container?: number;\n overlay?: number;\n}\n\nexport interface BrandFontsInput {\n /** Display and headings (typography display, h1, h2). A curated font id, see BRAND_FONTS. */\n heading?: string;\n /** Body, UI and captions (typography h3, body, ui, caption). */\n text?: string;\n}\n\nexport interface NewBrandInput {\n /** Lowercase letters, digits and single dashes, 2 to 24 characters: \"acme\", \"north-star\". */\n slug: string;\n /** Display name. Default: the slug in title case. */\n name?: string;\n /** Existing brand to start from, or \"blank\" (the default brand's structure, neutral type and no overrides). */\n from: string;\n /** Primary ramp (also accent and link unless set in `colors`). A hex is pinned at the step primary actions use. */\n primaryHue?: HueInput;\n /** Neutral ramp: text, lines, canvases. A hex tints it with its hue; a pure grey gives a pure grey ramp. */\n neutralHue?: HueInput;\n /** \"More colors\": separate ramps for accent (signal, focus ring) and link. */\n colors?: { accent?: HueInput; link?: HueInput };\n radius?: BrandRadiusInput;\n fonts?: BrandFontsInput;\n /** Exact values for brand tokens, by path (palette.primary.600, radius.control...): hex, \"12px\", \"{alias}\" or DTCG. */\n overrides?: Record<string, unknown>;\n}\n\n/** What the planner reads: the repo's config, its token files (relative to tokens.root) and contrast pairs. */\nexport interface BrandSource {\n config: BridgeConfig;\n /** bridge.config.json as written; edited with a minimal diff. Without it the canonical form is written. */\n configText?: string | undefined;\n files: Map<string, string> | Record<string, string>;\n /** contrast.checks.json text. */\n contrastText?: string | undefined;\n}\n\n// --- curated choices --------------------------------------------------------------------------------------\n\nexport interface BrandFont {\n id: string;\n label: string;\n /** Primitive token the role aliases. */\n token: string;\n /** Where it reads well: headings only (a display serif) or both. */\n use: 'heading' | 'both';\n}\n\n/** The short list the Studio offers. Every font here is self-hosted by @bridge-ds/tokens/fonts.css. */\nexport const BRAND_FONTS: BrandFont[] = [\n { id: 'fraunces', label: 'Fraunces', token: 'font.family.fraunces', use: 'heading' },\n { id: 'instrument-sans', label: 'Instrument Sans', token: 'font.family.instrument-sans', use: 'both' },\n { id: 'plex-sans', label: 'IBM Plex Sans', token: 'font.family.plex-sans', use: 'both' },\n { id: 'system', label: 'System UI', token: 'font.family.system', use: 'both' },\n];\n\nexport interface RadiusPreset {\n id: string;\n label: string;\n hint: string;\n radius: Required<BrandRadiusInput>;\n}\n\nexport const RADIUS_PRESETS: RadiusPreset[] = [\n { id: 'soft', label: 'Soft', hint: 'Rounded, like Bridge', radius: { inset: 6, control: 12, container: 20, overlay: 20 } },\n { id: 'balanced', label: 'Balanced', hint: 'Tighter, like Ocean', radius: { inset: 4, control: 10, container: 16, overlay: 20 } },\n { id: 'crisp', label: 'Crisp', hint: 'Near square corners', radius: { inset: 2, control: 4, container: 6, overlay: 10 } },\n];\n\nconst HEADING_ROLES = ['display', 'h1', 'h2'];\nconst TEXT_ROLES = ['h3', 'body', 'ui', 'caption'];\nconst RADIUS_ROLES = ['inset', 'control', 'container', 'overlay'] as const;\nconst RESERVED = new Set(['default', 'base', 'all', 'none', 'new', 'blank', 'primitives', 'semantic', 'components', 'density']);\nexport const BRAND_SLUG_RE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;\nconst DEFAULT_PRIMARY_CHROMA = 0.14;\n\n// --- outputs ----------------------------------------------------------------------------------------------\n\nexport interface PlannedFile {\n /** Repo-relative path. */\n path: string;\n action: 'create' | 'modify';\n content: string;\n}\n\nexport interface BrandIssue {\n level: 'error' | 'warning';\n code: string;\n message: string;\n path?: string;\n file?: string;\n}\n\nexport interface BrandSwatch {\n step: number;\n hex: string;\n}\n\nexport interface BrandContrastSummary {\n /** Pairs checked for the new brand, every theme. */\n checks: number;\n passing: number;\n failing: LayeredContrastResult[];\n /** Every result for the new brand, for tables. */\n results: LayeredContrastResult[];\n themes: string[];\n}\n\nexport interface NewBrandPlan {\n ok: boolean;\n slug: string;\n name: string;\n from: string;\n title: string;\n /** Suggested branch name (governance.branchPrefix + brand-<slug>). */\n branch: string;\n files: PlannedFile[];\n /** Token files after the change, relative to tokens.root (feed it to brandPreviewVariables or a LayeredTokenSet). */\n tokenFiles: Record<string, string>;\n /** bridge.config.json after the change, as text. */\n configText: string;\n /** Primary, neutral (and accent, link when they differ) ramps of the new brand, resolved. */\n ramps: Record<string, BrandSwatch[]>;\n /** Step of the primary ramp that primary actions use in the light theme (where a hex primary is pinned). */\n actionStep: number;\n contrast: BrandContrastSummary;\n /** Slug, input and DTCG problems. Errors block a proposal. */\n issues: BrandIssue[];\n risk: RiskResult & { bump: 'minor' };\n changeset?: { path: string; content: string } | undefined;\n}\n\n// --- helpers ----------------------------------------------------------------------------------------------\n\ntype Json = Record<string, unknown>;\nconst isObj = (x: unknown): x is Json => !!x && typeof x === 'object' && !Array.isArray(x);\nconst fileMap = (f: BrandSource['files']) => (f instanceof Map ? new Map(f) : new Map(Object.entries(f)));\nexport const brandDisplayName = (slug: string) => slug.split('-').filter(Boolean).map((w) => w[0]!.toUpperCase() + w.slice(1)).join(' ');\n\n/** The layer patterns brands use: the brand file and the optional brand x theme overrides. */\nfunction brandLayers(config: BridgeConfig): { brand?: string; override?: string; overrideAxis?: string } {\n const out: { brand?: string; override?: string; overrideAxis?: string } = {};\n for (const l of config.tokens.layers) {\n const ph = (l.files.match(/\\{([^}]+)\\}/g) ?? []).map((p) => p.slice(1, -1));\n if (!ph.includes('brand')) continue;\n if (ph.length === 1 && !out.brand) out.brand = l.files;\n else if (ph.length === 2 && !out.override) {\n out.override = l.files;\n out.overrideAxis = ph.find((p) => p !== 'brand');\n }\n }\n return out;\n}\nconst fill = (pattern: string, combo: Combo) => pattern.replace(/\\{([^}]+)\\}/g, (_, k: string) => combo[k] ?? `{${k}}`);\n\nfunction setAt(doc: Json, path: string, node: Json) {\n const keys = path.split('.');\n let cur = doc;\n for (const k of keys.slice(0, -1)) {\n if (!isObj(cur[k])) cur[k] = {};\n cur = cur[k] as Json;\n }\n const last = keys[keys.length - 1]!;\n const prev = isObj(cur[last]) ? (cur[last] as Json) : {};\n cur[last] = { ...prev, ...node };\n}\nfunction getAt(doc: Json, path: string): Json | undefined {\n let cur: unknown = doc;\n for (const k of path.split('.')) cur = isObj(cur) ? cur[k] : undefined;\n return isObj(cur) ? cur : undefined;\n}\n/** $type of a token in a doc, inherited from its groups. */\nfunction typeAt(doc: Json, path: string): string | undefined {\n let cur: unknown = doc;\n let type: string | undefined;\n for (const k of path.split('.')) {\n if (!isObj(cur)) return type;\n if (typeof cur.$type === 'string') type = cur.$type;\n cur = cur[k];\n }\n return isObj(cur) && typeof cur.$type === 'string' ? cur.$type : type;\n}\n\n/** Ramp for a hue input: a hex is pinned (at `pinStep`), a number is generated with the default chroma. */\nfunction rampFor(input: HueInput, pinStep: Step | undefined, kind: 'color' | 'neutral'): { ramp: Record<number, number[]>; issue?: BrandIssue; anchor: string } {\n if (typeof input === 'number' || (typeof input === 'string' && /^\\d+(\\.\\d+)?$/.test(input.trim()))) {\n const hue = ((Number(input) % 360) + 360) % 360;\n const ramp = kind === 'neutral' ? generateRamp({ hue, chroma: neutralChroma(), offset: neutralOffset() }) : generateRamp({ hue, chroma: bellChroma(DEFAULT_PRIMARY_CHROMA) });\n return { ramp, anchor: `OKLCH hue ${Math.round(hue)}` };\n }\n const hex = String(input).trim();\n if (!isHex(hex)) throw new Error(`\"${hex}\" is not a color. Use #rrggbb or a hue in degrees (0 to 360).`);\n if (kind === 'neutral') {\n const n = tintedNeutral(hex);\n return { ramp: n.ramp, anchor: `${hex.toUpperCase()} (hue ${Math.round(n.hue)})` };\n }\n const a = anchoredRamp(hex, pinStep);\n const issue: BrandIssue | undefined =\n a.distance > PIN_TOLERANCE\n ? {\n level: 'warning',\n code: 'pin-off-ladder',\n message: `${hex.toUpperCase()} is ${a.distance > 0.12 ? 'much ' : ''}${toOklch(fromHex(hex)).L > LIGHTNESS[a.step] ? 'lighter' : 'darker'} than the ${a.step} step it is pinned to, so the ramp around it will not read as one family. Primary actions use this step: pick a ${a.step >= 600 ? 'deeper' : 'lighter'} color.`,\n }\n : undefined;\n return { ramp: a.ramp, anchor: `${hex.toUpperCase()} pinned at ${a.step}`, ...(issue ? { issue } : {}) };\n}\n\n/** Points a palette role at a primitive ramp: palette.<role>.<step> -> {color.<ramp>.<step>} (two tiers, never literals). */\nfunction aliasRamp(doc: Json, role: string, ramp: string, description: string) {\n const group = getAt(doc, `palette.${role}`);\n if (!group) return;\n for (const s of STEPS) {\n if (!(String(s) in group)) continue;\n setAt(doc, `palette.${role}.${s}`, { $value: `{color.${ramp}.${s}}` });\n }\n group.$description = description;\n}\n\n/** Primitive ramps a new brand adds: ramp name -> description and DTCG color per step. */\ntype PrimitiveRamps = Map<string, { description: string; steps: Map<number, unknown> }>;\n\n/** Inserts `slug` into modes.brand.values (or modes.brands) with a minimal text change. */\nexport function addBrandToConfigText(text: string, slug: string): string {\n const canonical = /(\"brand\"\\s*:\\s*\\{\\s*\"values\"\\s*:\\s*\\[)([^\\]]*)(\\])/;\n const flat = /(\"brands\"\\s*:\\s*\\[)([^\\]]*)(\\])/;\n for (const re of [canonical, flat]) {\n const m = re.exec(text);\n if (!m) continue;\n const items = m[2]!.trim();\n const sep = items.includes('\\n') ? `,${/\\n(\\s*)\"/.exec(m[2]!)?.[0]?.replace(/\"$/, '') ?? ' '}` : ', ';\n return text.slice(0, m.index) + m[1] + (items ? `${m[2]!.replace(/\\s*$/, '')}${sep}\"${slug}\"` : `\"${slug}\"`) + (m[2]!.match(/\\s*$/)?.[0] ?? '') + m[3] + text.slice(m.index + m[0].length);\n }\n throw new Error('bridge.config.json has no modes.brand.values list to add the brand to.');\n}\n\n// --- listing ----------------------------------------------------------------------------------------------\n\nexport interface BrandSummary {\n slug: string;\n name: string;\n default: boolean;\n file: string;\n description?: string;\n /** Resolved color.action.primary.bg in the default theme, when the repo has it. */\n primary?: string;\n /** Theme override files the brand has. */\n overrides: string[];\n}\n\nexport function listBrands(source: BrandSource): BrandSummary[] {\n const { config } = source;\n const files = fileMap(source.files);\n const set = new LayeredTokenSet(config, files);\n const layers = brandLayers(config);\n const brandAxis = config.axes.brand;\n if (!brandAxis || !layers.brand) return [];\n return brandAxis.values.map((slug) => {\n const file = fill(layers.brand!, { brand: slug });\n let doc: Json = {};\n try {\n doc = JSON.parse(files.get(file) ?? '{}') as Json;\n } catch {\n /* reported by validation */\n }\n const meta = isObj(doc.$extensions) && isObj(doc.$extensions['dev.bridge.brand']) ? (doc.$extensions['dev.bridge.brand'] as Json) : {};\n const combo = set.normalizeCombo({ brand: slug });\n const primary = set.resolve('color.action.primary.bg', combo);\n const overrides = layers.override ? (config.axes[layers.overrideAxis!]?.values ?? []).map((v) => fill(layers.override!, { brand: slug, [layers.overrideAxis!]: v })).filter((f) => files.has(f)) : [];\n return {\n slug,\n name: typeof meta.name === 'string' ? meta.name : brandDisplayName(slug),\n default: slug === brandAxis.default,\n file: tokensPath(config, file),\n ...(typeof doc.$description === 'string' ? { description: doc.$description } : {}),\n ...(primary.css && !primary.error ? { primary: primary.css } : {}),\n overrides: overrides.map((f) => tokensPath(config, f)),\n };\n });\n}\n\n// --- planning ---------------------------------------------------------------------------------------------\n\n/** Problems with a slug before anything is generated (the Studio uses it as you type). */\nexport function checkBrandSlug(config: BridgeConfig, files: BrandSource['files'], slug: string): BrandIssue[] {\n const out: BrandIssue[] = [];\n const s = slug.trim();\n if (!s) return [{ level: 'error', code: 'slug-empty', message: 'Give the brand a name.' }];\n if (s.length < 2 || s.length > 24 || !BRAND_SLUG_RE.test(s)) out.push({ level: 'error', code: 'slug-format', message: 'Use 2 to 24 lowercase letters, digits and single dashes, starting with a letter: \"acme\" or \"north-star\".' });\n const taken = Object.values(config.axes).flatMap((a) => a.values);\n if (config.axes.brand?.values.includes(s)) out.push({ level: 'error', code: 'slug-taken', message: `A brand called \"${s}\" already exists. Pick another name or edit that brand.` });\n else if (taken.includes(s) || RESERVED.has(s)) out.push({ level: 'error', code: 'slug-reserved', message: `\"${s}\" is a reserved mode name. Pick another name.` });\n const layer = brandLayers(config).brand;\n const map = fileMap(files);\n if (layer && !config.axes.brand?.values.includes(s) && map.has(fill(layer, { brand: s }))) out.push({ level: 'error', code: 'slug-file-exists', message: `${tokensPath(config, fill(layer, { brand: s }))} already exists. Pick another name or add it to bridge.config.json.` });\n return out;\n}\n\nexport function planNewBrand(source: BrandSource, input: NewBrandInput): NewBrandPlan {\n const { config } = source;\n const files = fileMap(source.files);\n const issues: BrandIssue[] = [];\n const slug = input.slug.trim();\n const name = input.name?.trim() || brandDisplayName(slug);\n const layers = brandLayers(config);\n const brandAxis = config.axes.brand;\n if (!brandAxis || !layers.brand) throw new Error('This repo has no brand mode: bridge.config.json needs modes.brand and a tokens layer with {brand}.');\n issues.push(...checkBrandSlug(config, files, slug));\n\n const from = input.from?.trim() || brandAxis.default;\n const blank = from === 'blank';\n if (!blank && !brandAxis.values.includes(from)) throw new Error(`Unknown brand \"${from}\" to start from. Brands: ${brandAxis.values.join(', ')} (or \"blank\").`);\n const template = blank ? brandAxis.default : from;\n const templateFile = fill(layers.brand, { brand: template });\n const templateText = files.get(templateFile);\n if (!templateText) throw new Error(`${tokensPath(config, templateFile)} is missing.`);\n const doc = JSON.parse(templateText) as Json;\n const before = new LayeredTokenSet(config, files);\n\n // Step that primary actions use in the light (default) theme of the starting brand: a hex primary is pinned there.\n const chain = before.resolve('color.action.primary.bg', before.normalizeCombo({ brand: template })).chain;\n const actionStep = Number(/^palette\\.primary\\.(\\d+)$/.exec(chain.find((c) => /^palette\\.primary\\.\\d+$/.test(c)) ?? '')?.[1] ?? 600) as Step;\n\n const anchors: Record<string, string> = {};\n const safeRamp = (role: string, hue: HueInput, kind: 'color' | 'neutral', pin?: Step) => {\n try {\n const r = rampFor(hue, pin, kind);\n if (r.issue) issues.push({ ...r.issue, path: `palette.${role}` });\n anchors[role] = r.anchor;\n return r.ramp;\n } catch (e) {\n issues.push({ level: 'error', code: 'invalid-color', message: (e as Error).message, path: `palette.${role}` });\n return undefined;\n }\n };\n // Generated ramps become primitives (color.<slug>-<role>.<step>); the brand file only aliases them.\n const prims: PrimitiveRamps = new Map();\n const addRamp = (role: string, ramp: Record<number, number[]>, description: string) => {\n const steps = new Map<number, unknown>(STEPS.map((st) => [st, dtcgColor(ramp[st]!)]));\n prims.set(`${slug}-${role}`, { description, steps });\n return `${slug}-${role}`;\n };\n if (input.primaryHue !== undefined && input.primaryHue !== '') {\n const ramp = safeRamp('primary', input.primaryHue, 'color', actionStep);\n if (ramp) {\n const r = addRamp('primary', ramp, `${name} primary. Generated by Bridge from ${anchors.primary}.`);\n aliasRamp(doc, 'primary', r, `${name} primary.`);\n if (input.colors?.accent === undefined) aliasRamp(doc, 'accent', r, `${name} accent: the primary ramp.`);\n if (input.colors?.link === undefined) aliasRamp(doc, 'link', r, `${name} links: the primary ramp.`);\n }\n }\n for (const role of ['accent', 'link'] as const) {\n const hue = input.colors?.[role];\n if (hue === undefined || hue === '') continue;\n const ramp = safeRamp(role, hue, 'color');\n if (ramp) aliasRamp(doc, role, addRamp(role, ramp, `${name} ${role}. Generated by Bridge from ${anchors[role]}.`), `${name} ${role}.`);\n }\n if (input.neutralHue !== undefined && input.neutralHue !== '') {\n const ramp = safeRamp('neutral', input.neutralHue, 'neutral');\n if (ramp) aliasRamp(doc, 'neutral', addRamp('neutral', ramp, `${name} neutral. Generated by Bridge from ${anchors.neutral}.`), `${name} neutral.`);\n }\n\n // Radius roles: aliases of the radius scale.\n const scale = new Map<number, string>();\n for (const [path, defs] of before.view(before.defaultCombo)) {\n const m = /^radius\\.([\\w-]+)$/.exec(path);\n const v = defs[defs.length - 1]!.value;\n if (m && isObj(v) && typeof v.value === 'number' && v.unit === 'px' && !getAt(doc, path)) scale.set(v.value, m[1]!);\n }\n const radius = input.radius ?? (blank ? RADIUS_PRESETS[0]!.radius : undefined);\n if (radius) {\n for (const role of RADIUS_ROLES) {\n const px = radius[role];\n if (px === undefined) continue;\n const step = scale.get(px);\n if (!step) issues.push({ level: 'error', code: 'radius-off-scale', message: `radius.${role} ${px}px is not on the radius scale (${[...scale.keys()].filter((x) => x < 9999).sort((a, b) => a - b).join(', ')} px).`, path: `radius.${role}` });\n else if (getAt(doc, `radius.${role}`)) setAt(doc, `radius.${role}`, { $value: `{radius.${step}}` });\n }\n }\n\n // Font roles and typography families.\n const fonts = input.fonts ?? (blank ? { heading: 'instrument-sans', text: 'instrument-sans' } : undefined);\n const fontToken = (id: string | undefined, role: string) => {\n if (!id) return undefined;\n const f = BRAND_FONTS.find((x) => x.id === id || x.token === id);\n const token = f?.token ?? (id.startsWith('font.family.') ? id : `font.family.${id}`);\n if (!before.view(before.defaultCombo).has(token) || ['font.family.sans', 'font.family.display', 'font.family.mono'].includes(token)) {\n issues.push({ level: 'error', code: 'unknown-font', message: `\"${id}\" is not a font this repo self-hosts. Pick one of: ${BRAND_FONTS.map((x) => x.label).join(', ')}.`, path: `font.family.${role}` });\n return undefined;\n }\n return token;\n };\n const heading = fontToken(fonts?.heading, 'display');\n const text = fontToken(fonts?.text, 'sans');\n if (heading && getAt(doc, 'font.family.display')) setAt(doc, 'font.family.display', { $value: `{${heading}}` });\n if (text && getAt(doc, 'font.family.sans')) setAt(doc, 'font.family.sans', { $value: `{${text}}` });\n for (const r of HEADING_ROLES) if (heading && getAt(doc, `typography.${r}.family`)) setAt(doc, `typography.${r}.family`, { $value: `{${heading}}` });\n for (const r of TEXT_ROLES) if (text && getAt(doc, `typography.${r}.family`)) setAt(doc, `typography.${r}.family`, { $value: `{${text}}` });\n\n // Exact values (the Figma plugin sends every variable of the new mode).\n for (const [path, raw] of Object.entries(input.overrides ?? {})) {\n const node = getAt(doc, path);\n if (!node || !('$value' in node)) {\n issues.push({ level: 'error', code: 'unknown-token', message: `${path} is not a token of the ${template} brand file, so a new brand cannot set it.`, path });\n continue;\n }\n setAt(doc, path, { $value: coerceValue(raw, typeAt(doc, path), node.$value) });\n }\n\n // Exact colors (Figma values, overrides) are hoisted too: a literal palette color becomes the primitive\n // color.<slug>-<role>.<step> and the role aliases it, so brand files never hold literal values.\n const palette = getAt(doc, 'palette');\n for (const [role, group] of Object.entries(palette ?? {})) {\n if (role.startsWith('$') || !isObj(group)) continue;\n for (const [step, node] of Object.entries(group)) {\n if (step.startsWith('$') || !isObj(node) || !('$value' in node) || typeof node.$value === 'string') continue;\n const ramp = `${slug}-${role}`;\n const entry = prims.get(ramp) ?? { description: `${name} ${role}. Exact values set when the brand was created.`, steps: new Map<number, unknown>() };\n entry.steps.set(Number(step), node.$value);\n prims.set(ramp, entry);\n setAt(doc, `palette.${role}.${step}`, { $value: `{color.${ramp}.${step}}` });\n }\n }\n const primDir = config.tokens.tiers.primitive?.[0]?.replace(/\\/$/, '') ?? config.tokens.primitives;\n const primFile = `${primDir}/${slug}.tokens.json`;\n if (prims.size && files.has(primFile)) issues.push({ level: 'error', code: 'slug-file-exists', message: `${tokensPath(config, primFile)} already exists. Pick another name.` });\n for (const r of prims.keys()) if (before.allPaths().some((p) => p.startsWith(`color.${r}.`))) issues.push({ level: 'error', code: 'ramp-exists', message: `A primitive ramp color.${r} already exists. Pick another name.` });\n\n doc.$description = `${name}: created with Bridge, started from ${blank ? 'a blank brand' : brandDisplayName(from)}.`;\n doc.$extensions = { ...(isObj(doc.$extensions) ? doc.$extensions : {}), 'dev.bridge.brand': { name, from, ...(Object.keys(anchors).length ? { anchors } : {}) } };\n // Keep $description and $extensions on top, like the hand-written brand files.\n const { $description, $extensions, ...rest } = doc;\n const brandFile = fill(layers.brand, { brand: slug });\n const nextFiles = new Map(files);\n const created: string[] = [];\n if (prims.size) {\n const color: Json = { $type: 'color' };\n for (const [r, { description, steps }] of prims) {\n const ramp: Json = { $description: description };\n for (const st of [...steps.keys()].sort((a, b) => a - b)) ramp[String(st)] = { $value: steps.get(st) };\n color[r] = ramp;\n }\n const prim = { $description: `${name} brand ramps, generated by Bridge (@bridge-ds/core ramp engine). Never used by components directly: brands/${slug}.tokens.json maps them to palette roles.`, color };\n nextFiles.set(primFile, `${JSON.stringify(prim, null, 2)}\\n`);\n created.push(primFile);\n }\n created.push(brandFile);\n nextFiles.set(brandFile, `${JSON.stringify({ $description, $extensions, ...rest }, null, 2)}\\n`);\n\n // Theme overrides of the starting brand come along: they point at palette roles, so they follow the new ramps.\n if (!blank && layers.override && layers.overrideAxis) {\n for (const v of config.axes[layers.overrideAxis]?.values ?? []) {\n const src = fill(layers.override, { brand: from, [layers.overrideAxis]: v });\n const text = files.get(src);\n if (!text) continue;\n const o = JSON.parse(text) as Json;\n const out = { ...o, $description: `${name} overrides on top of semantic/${v}, copied from ${brandDisplayName(from)}.` };\n const dst = fill(layers.override, { brand: slug, [layers.overrideAxis]: v });\n nextFiles.set(dst, `${JSON.stringify(out, null, 2)}\\n`);\n created.push(dst);\n }\n }\n\n // bridge.config.json: modes.brand += slug.\n const baseConfigText = source.configText ?? `${JSON.stringify(toConfigJson(config), null, 2)}\\n`;\n let configText = baseConfigText;\n let nextConfig = config;\n try {\n configText = addBrandToConfigText(baseConfigText, slug);\n nextConfig = issues.some((i) => i.code.startsWith('slug-')) ? config : loadConfig(configText);\n } catch (e) {\n issues.push({ level: 'error', code: 'config', message: (e as Error).message });\n }\n\n // Validation (only problems the new brand brings) and the contrast gate for the new brand in every theme.\n const after = new LayeredTokenSet(nextConfig, nextFiles);\n const key = (i: LayerIssue) => `${i.code}|${i.path ?? ''}|${i.message}`;\n const known = new Set(validateLayered(before).map(key));\n const brandKey = `brand=${slug}`;\n for (const i of validateLayered(after)) {\n if (known.has(key(i))) continue;\n if (i.modes && !i.modes.some((m) => m.split(',').includes(brandKey)) && !created.includes(i.file ?? '')) continue;\n issues.push({ level: i.level, code: i.code, message: i.message, ...(i.path ? { path: i.path } : {}), ...(i.file ? { file: tokensPath(config, i.file) } : {}) });\n }\n const pairs: ContrastPair[] = parseContrastChecks(source.contrastText);\n const inGate = nextConfig.axes.brand?.values.includes(slug);\n const combos = inGate ? after.combos(nextConfig.contrast?.modes).filter((c) => c.brand === slug) : [];\n const results = combos.flatMap((c) => pairs.map((p) => checkLayeredPair(after, p, c)));\n const failing = results.filter((r) => !r.pass);\n const themes = [...new Set(combos.map((c) => c.theme).filter((t): t is string => !!t))];\n\n // Ramps, resolved (so Figma values and overrides show as they will ship).\n const ramps: Record<string, BrandSwatch[]> = {};\n if (inGate) {\n const combo = after.normalizeCombo({ brand: slug });\n const read = (role: string) =>\n STEPS.map((s) => ({ step: s, hex: after.resolve(`palette.${role}.${s}`, combo).css })).filter((x) => /^#[0-9a-f]{6}$/i.test(x.hex));\n ramps.primary = read('primary');\n ramps.neutral = read('neutral');\n for (const role of ['accent', 'link']) {\n const r = read(role);\n if (JSON.stringify(r) !== JSON.stringify(ramps.primary)) ramps[role] = r;\n }\n }\n\n // Tier: every token of the new files is an addition, bridge.config.json is a guardrail. Tier 3, minor.\n const addedTokens = after.defs.filter((d) => created.includes(d.file)).map((d) => ({ kind: 'added' as const, path: d.path }));\n const risk = classifyRisk({ tokenChanges: addedTokens, files: [{ path: CONFIG_FILE, status: 'modified' }], config });\n const planned: PlannedFile[] = [\n ...created.map((f) => ({ path: tokensPath(config, f), action: 'create' as const, content: nextFiles.get(f)! })),\n { path: CONFIG_FILE, action: 'modify', content: configText },\n ];\n const cs = config.changesets ?? (config.changeset ? { dir: '.changeset', package: config.changeset.package } : undefined);\n const changeset = cs\n ? {\n path: `${cs.dir}/bridge-brand-${slug}.md`,\n content: formatChangeset(cs.package, 'minor', `Add the ${name} brand (\\`${slug}\\`), started from ${blank ? 'a blank brand' : brandDisplayName(from)}.`, `- ${created.map((f) => `\\`${tokensPath(config, f)}\\``).join('\\n- ')}\\n- \\`${CONFIG_FILE}\\`: modes.brand gains \"${slug}\", so the token build and the contrast gate cover it.`),\n }\n : undefined;\n if (changeset) planned.push({ path: changeset.path, action: 'create', content: changeset.content });\n\n const errors = issues.filter((i) => i.level === 'error');\n return {\n ok: errors.length === 0 && failing.length === 0 && results.length > 0,\n slug,\n name,\n from,\n title: `Add the ${name} brand`,\n branch: `${config.governance.branchPrefix}brand-${slug || 'new'}`,\n files: planned,\n tokenFiles: Object.fromEntries(nextFiles),\n configText,\n ramps,\n actionStep,\n contrast: { checks: results.length, passing: results.length - failing.length, failing, results, themes },\n issues,\n risk: { ...risk, bump: 'minor' },\n changeset,\n };\n}\n\n/** CSS variables of a planned brand in one theme (every semantic and component token), for live previews. */\nexport function brandPreviewVariables(source: BrandSource, plan: Pick<NewBrandPlan, 'slug' | 'tokenFiles' | 'configText'>, theme?: string): Record<string, string> {\n let config = source.config;\n try {\n config = loadConfig(plan.configText);\n } catch {\n /* keep the old config: the preview falls back to the default brand */\n }\n const set = new LayeredTokenSet(config, new Map(Object.entries(plan.tokenFiles)));\n let combo: Combo;\n try {\n combo = set.normalizeCombo({ brand: plan.slug, ...(theme ? { theme } : {}) });\n } catch {\n combo = set.normalizeCombo(theme ? { theme } : {});\n }\n const out: Record<string, string> = {};\n for (const path of set.view(combo).keys()) {\n const tier = set.tierOf(path);\n if (tier === 'primitive') continue;\n const r = set.resolve(path, combo);\n if (!r.error && r.css) out[set.cssVarName(path)] = r.css;\n }\n return out;\n}\n\n// --- PR body ----------------------------------------------------------------------------------------------\n\nconst code = (s: string) => `\\`${s}\\``;\n\n/** The \"New brand\" section: swatch ramps and the contrast summary. GitHub shows a chip next to `#rrggbb`. */\nexport function newBrandSection(plan: NewBrandPlan): string {\n const roles = Object.keys(plan.ramps);\n const rampTable = roles.length\n ? [\n `| Step | ${roles.map((r) => r[0]!.toUpperCase() + r.slice(1)).join(' | ')} |`,\n `| --- | ${roles.map(() => '---').join(' | ')} |`,\n ...STEPS.map((s) => `| ${s}${s === plan.actionStep ? ' (actions)' : ''} | ${roles.map((r) => code(plan.ramps[r]!.find((x) => x.step === s)?.hex ?? '')).join(' | ')} |`),\n ].join('\\n')\n : '_No ramps resolved._';\n const c = plan.contrast;\n const contrastLine = c.failing.length\n ? `**${c.failing.length} of ${c.checks} pairs fail** for ${plan.name} (${c.themes.join(' and ')}).`\n : `All ${c.checks} contrast checks pass for ${plan.name} in ${c.themes.join(' and ')}.`;\n const failRows = c.failing.slice(0, 20).map((r) => `| ${code(r.fg)} on ${code(r.bg)} | ${r.modes.split(',').find((m) => m.startsWith('theme='))?.slice(6) ?? r.modes} | ${r.ratio ?? 'n/a'} | ${r.min} |`);\n const tightest = [...c.results].filter((r) => r.pass && r.ratio !== null).sort((a, b) => a.ratio! - a.min - (b.ratio! - b.min)).slice(0, 3);\n return [\n '## New brand',\n '',\n `- Name: **${plan.name}** (${code(plan.slug)})`,\n `- Started from: ${plan.from === 'blank' ? 'a blank brand' : brandDisplayName(plan.from)}`,\n `- Primary actions use step ${plan.actionStep} of the primary ramp in the light theme.`,\n '',\n rampTable,\n '',\n '### Contrast',\n '',\n contrastLine,\n ...(failRows.length ? ['', '| Pair | Theme | Ratio | Min |', '| --- | --- | --- | --- |', ...failRows] : []),\n ...(tightest.length ? ['', `Tightest passing pairs: ${tightest.map((r) => `${code(r.fg)} on ${code(r.bg)} ${r.ratio}:1 (min ${r.min})`).join('; ')}.`] : []),\n ].join('\\n');\n}\n\nexport interface NewBrandBodyOptions {\n /** \"the bridge CLI\", \"Bridge MCP\", \"the Bridge Studio\", \"the DS Bridge Figma plugin\". */\n tool: string;\n author?: string;\n /** true when an AI agent proposed it. */\n agent?: boolean;\n /** Free text from the person proposing. */\n notes?: string;\n}\n\nexport function composeNewBrandBody(plan: NewBrandPlan, opts: NewBrandBodyOptions): string {\n const t = plan.risk.tier;\n const box = (n: 1 | 2 | 3) => `- ${n === t ? '[x]' : '[ ]'} ${RISK_LABELS[n]}`;\n const errors = plan.issues.filter((i) => i.level === 'error');\n const warnings = plan.issues.filter((i) => i.level === 'warning');\n return [\n '## What changed and why',\n '',\n `Adds the ${plan.name} brand. Components do not change: the brand re-points palette, radius and font roles, and the token build, the contrast gate and the docs pick it up from ${code('bridge.config.json')}.`,\n ...(opts.notes?.trim() ? ['', opts.notes.trim()] : []),\n '',\n `Proposed through ${opts.tool}${opts.author ? ` by ${opts.author}` : ''}.${opts.agent ? ' Agent-authored: a human design owner and tech owner review and merge.' : ''}`,\n '',\n newBrandSection(plan),\n '',\n '## Files',\n '',\n ...plan.files.map((f) => `- ${f.action === 'create' ? 'Create' : 'Modify'} ${code(f.path)}`),\n '',\n '## Risk tier',\n '',\n box(1),\n box(2),\n box(3),\n '',\n `- Brand added: ${plan.files.filter((f) => f.action === 'create' && f.path.endsWith('.tokens.json')).length} token file(s), every token new`,\n `- ${code('bridge.config.json')} is a guardrail file`,\n `- Semver bump: ${code(plan.risk.bump)} for ${code('@bridge-ds/tokens')}`,\n '',\n '## Checks',\n '',\n `- Token validation: ${errors.length ? `**${errors.length} error(s)**` : 'no errors'} (DTCG shapes, aliases, every mode)${warnings.length ? `, ${warnings.length} warning(s): ${warnings.map((w) => w.message).join(' ')}` : ''}`,\n `- Contrast gate for ${plan.name}: ${plan.contrast.failing.length ? `**${plan.contrast.failing.length} failing pair(s)**` : `all ${plan.contrast.checks} pairs pass`}`,\n '',\n '## Authored by',\n '',\n opts.agent ? '- [ ] Human' : '- [x] Human',\n opts.agent ? '- [x] AI agent (Claude), reviewed by a human before merge' : '- [ ] AI agent',\n '',\n '## Design review checklist',\n '',\n '- [ ] Checked in light and dark, with real components (Studio preview or Storybook brand switch)',\n '- [ ] Primary, zone and link colors read as one family',\n '- [ ] Changeset bump matches the tier',\n '',\n ].join('\\n');\n}\n","// Component docs drafted with Claude: the task (which sections, or a selected passage), the prompt, the answer\n// parsing and sanitizing, the merge into a docs.json, and the Messages API request. Shared by the docs-draft GitHub\n// Action (scripts/docs-draft.mjs), the in-place drafting of the Library page (apps/docs-site docs-ai) and the draft\n// exchange (the user's own Claude through the Bridge MCP server), so an answer is cleaned the same way everywhere.\n// Pure: no DOM, no Node-only API. The callers do the fetch.\n\nimport { cleanDraftText } from './change-drafts';\nimport {\n type ComponentDocsJson,\n type DocsConventions,\n type DocsExampleNode,\n type DocsGuidance,\n type DocsPrefill,\n PROSE_KEYS,\n type ProseKey,\n docsPrompt,\n markClaudeDraft,\n} from './docs-draft';\n\nexport const DOCS_DRAFT_MODEL = 'claude-sonnet-5-5';\nexport const ANTHROPIC_MESSAGES_URL = 'https://api.anthropic.com/v1/messages';\n\n/** How a selected passage is rewritten. */\nexport type DocsSelectionMode = 'clearer' | 'shorter' | 'voice';\nexport const DOCS_SELECTION_MODES: Record<DocsSelectionMode, string> = {\n clearer: 'Make it clearer: plain words, one idea per sentence, the most useful fact first.',\n shorter: 'Make it shorter: keep every fact, drop filler, aim for half the words or fewer.',\n voice: 'Put it in the Bridge voice: sentence case, verbs first, calm and precise, no marketing words, no em dash.',\n};\nexport const isDocsSelectionMode = (m: unknown): m is DocsSelectionMode => typeof m === 'string' && m in DOCS_SELECTION_MODES;\nexport const isProseKey = (k: unknown): k is ProseKey => typeof k === 'string' && (PROSE_KEYS as readonly string[]).includes(k);\n\n/**\n * One drafting job on a component's docs. \"sections\": write these prose sections (rewrite: even when they hold text;\n * check: written sections older than the code, returned only when no longer true for it, so an absent one is still\n * accurate). \"selection\": rewrite one passage of a section, nothing else.\n */\nexport type DocsDraftTask =\n | { kind: 'sections'; keys: ProseKey[]; rewrite?: boolean | undefined; check?: ProseKey[] | undefined }\n | { kind: 'selection'; key: ProseKey; text: string; mode: DocsSelectionMode };\n\n/** Problems in a task, as sentences. Empty when valid. */\nexport function validateDocsTask(x: unknown): string[] {\n if (!x || typeof x !== 'object') return ['The docs task is missing.'];\n const t = x as Partial<Record<string, unknown>>;\n if (t.kind === 'sections') {\n const keys = t.keys;\n if (!Array.isArray(keys) || !keys.length || !keys.every(isProseKey)) return [`The docs task lists no sections: use ${PROSE_KEYS.join(', ')}.`];\n if (t.check !== undefined && (!Array.isArray(t.check) || !t.check.every(isProseKey))) return ['check must list prose sections.'];\n return [];\n }\n if (t.kind === 'selection') {\n const out: string[] = [];\n if (!isProseKey(t.key)) out.push(`The selection needs a section: ${PROSE_KEYS.join(', ')}.`);\n if (typeof t.text !== 'string' || !t.text.trim()) out.push('The selection has no text.');\n if (!isDocsSelectionMode(t.mode)) out.push('The selection mode must be clearer, shorter or voice.');\n return out;\n }\n return ['The docs task kind must be \"sections\" or \"selection\".'];\n}\n\n/** The keys a task writes. */\nexport const docsTaskKeys = (t: DocsDraftTask): ProseKey[] => (t.kind === 'sections' ? t.keys : [t.key]);\n\n/** The prompt to rewrite a selected passage of a section: the facts and the conventions, the passage, one rule. */\nexport function docsSelectionPrompt(prefill: DocsPrefill, conventions: DocsConventions, sel: { key: ProseKey; text: string; mode: DocsSelectionMode }): string {\n const base = docsPrompt(prefill, conventions, { keys: [sel.key] });\n // Reuse the facts and conventions of the sections prompt, with the selection task and contract on top.\n const facts = base.slice(base.indexOf('Facts computed from the code:'));\n return [\n `Rewrite one passage of the \"${sel.key}\" section of ${prefill.component}.docs.json for the Bridge design system.`,\n DOCS_SELECTION_MODES[sel.mode],\n '',\n 'Rules:',\n '- Keep its meaning and every fact that the code supports. Never add props, variants, keyboard behavior or tokens that are not in the facts or the source below.',\n '- Bridge voice: sentence case, plain words, verbs first, no em dashes, no marketing words, no Markdown.',\n '- Rewrite only the passage: it is pasted back in place of the selection, inside the rest of the section.',\n '- Answer with one JSON object, nothing else: { \"replacement\": \"the rewritten passage\" }.',\n '',\n `<passage>\\n${sel.text.trim()}\\n</passage>`,\n '',\n facts,\n ].join('\\n');\n}\n\n/** The prompt of a task: docsPrompt for sections (only those keys), docsSelectionPrompt for a selection. */\nexport function docsTaskPrompt(prefill: DocsPrefill, conventions: DocsConventions, task: DocsDraftTask): string {\n if (task.kind === 'selection') return docsSelectionPrompt(prefill, conventions, task);\n return docsPrompt(prefill, conventions, { keys: task.keys, ...(task.rewrite ? { rewrite: true } : {}), ...(task.check?.length ? { check: task.check } : {}) });\n}\n\n// ---------------------------------------------------------------------------------------------\n// Answers: parse and sanitize\n\n/** The first JSON object in a model reply (plain, or inside a ```json fence). Throws when there is none. */\nexport function parseDocsReply(text: string): Record<string, unknown> {\n const fenced = /```(?:json)?\\s*([\\s\\S]*?)```/i.exec(text);\n const body = fenced ? fenced[1]! : text;\n const start = body.indexOf('{');\n const end = body.lastIndexOf('}');\n if (start < 0 || end <= start) throw new Error('The reply holds no JSON object.');\n const json = JSON.parse(body.slice(start, end + 1)) as unknown;\n if (!json || typeof json !== 'object' || Array.isArray(json)) throw new Error('The reply is not a docs.json object.');\n return json as Record<string, unknown>;\n}\n\n/** One line of docs prose: em dashes out, whitespace folded, trimmed. */\nexport const cleanDocsText = (s: string): string => cleanDraftText(s.replace(/[\\r\\n]+/g, ' '));\n\nconst isExample = (x: unknown): x is DocsExampleNode => {\n if (typeof x === 'string') return true;\n if (!x || typeof x !== 'object' || Array.isArray(x)) return false;\n const n = x as { c?: unknown; p?: unknown; children?: unknown };\n if (typeof n.c !== 'string' || !n.c) return false;\n if (n.p !== undefined && (!n.p || typeof n.p !== 'object' || Array.isArray(n.p))) return false;\n return n.children === undefined || (Array.isArray(n.children) && n.children.every(isExample));\n};\n\nconst textList = (x: unknown): string[] | undefined => {\n if (typeof x === 'string') x = [x];\n if (!Array.isArray(x)) return undefined;\n const out = x.filter((s): s is string => typeof s === 'string').map(cleanDocsText).filter(Boolean);\n return out.length ? out : undefined;\n};\n\nconst guidanceList = (x: unknown, examples: boolean): DocsGuidance[] | undefined => {\n if (!Array.isArray(x)) return undefined;\n const out: DocsGuidance[] = [];\n for (const g of x as unknown[]) {\n if (!g || typeof g !== 'object') continue;\n const r = g as { title?: unknown; text?: unknown; example?: unknown };\n const title = typeof r.title === 'string' ? cleanDocsText(r.title) : '';\n const text = typeof r.text === 'string' ? cleanDocsText(r.text) : '';\n if (!title || !text) continue;\n out.push({ title, text, ...(examples && r.example !== undefined && isExample(r.example) ? { example: r.example } : {}) });\n }\n return out.length ? out : undefined;\n};\n\nexport type DocsSections = Partial<Pick<ComponentDocsJson, ProseKey>>;\n\n/**\n * The prose sections of an answer, kept to the docs.json shapes: only `keys`, summary one cleaned paragraph, lists of\n * non-empty cleaned strings, dos and donts as {title, text} (an example only when `examples` and well formed). Em\n * dashes removed everywhere. Sections that come back empty or in the wrong shape are left out.\n */\nexport function sanitizeDocsSections(raw: unknown, keys: readonly ProseKey[] = PROSE_KEYS, opts: { examples?: boolean } = {}): DocsSections {\n const out: DocsSections = {};\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out;\n const r = raw as Record<string, unknown>;\n for (const k of keys) {\n const v = r[k];\n if (k === 'summary') {\n const s = typeof v === 'string' ? cleanDocsText(v) : '';\n if (s) out.summary = s;\n } else if (k === 'dos' || k === 'donts') {\n const g = guidanceList(v, opts.examples ?? false);\n if (g) out[k] = g;\n } else {\n const l = textList(v);\n if (l) out[k] = l;\n }\n }\n return out;\n}\n\n/** A rewritten passage: one cleaned paragraph without wrapping quotes, or '' when there is none. */\nexport function sanitizeDocsReplacement(raw: unknown): string {\n if (typeof raw !== 'string') return '';\n return cleanDocsText(raw.trim().replace(/^[\"'“]+|[\"'”]+$/g, ''));\n}\n\n/**\n * A task's answer. Sections tasks: `sections` drafted or fixed, and `checked`, the checked sections Claude verified and\n * left unchanged (still accurate). Selection: `replacement` only.\n */\nexport type DocsTaskAnswer = { sections: DocsSections; checked: ProseKey[]; replacement?: undefined } | { sections: DocsSections; checked?: undefined; replacement: string };\n\n/**\n * A task's answer from Claude's reply text. Sections: the requested keys, sanitized; throws when none came back.\n * Selection: `replacement` only (sections stay empty); a reply that is plain text counts as the passage.\n */\nexport function parseDocsTaskAnswer(task: DocsDraftTask, text: string): DocsTaskAnswer {\n if (task.kind === 'selection') {\n let raw: unknown = text;\n try {\n const json = parseDocsReply(text);\n raw = json.replacement ?? json.text ?? json[task.key];\n } catch {\n raw = text.replace(/```[a-z]*\\s*|```/gi, '');\n }\n const replacement = sanitizeDocsReplacement(raw);\n if (!replacement) throw new Error('Claude sent no rewritten passage. Try again.');\n return { sections: {}, replacement };\n }\n return docsSectionsAnswer(task, parseDocsReply(text));\n}\n\n/**\n * Sections and checked of a sections task from an answer object: absent checked keys are still accurate. Throws only\n * when the task checks nothing and none of its keys came back.\n */\nexport function docsSectionsAnswer(task: Extract<DocsDraftTask, { kind: 'sections' }>, raw: unknown): { sections: DocsSections; checked: ProseKey[] } {\n const check = (task.check ?? []).filter((k) => task.keys.includes(k));\n const sections = check.length ? sanitizeDocsSections(raw, task.keys) : docsSectionsResult(task, raw);\n return { sections, checked: check.filter((k) => sections[k] === undefined) };\n}\n\n/** The sections of a task from an answer object (API reply or the exchange). Throws when none of the keys came back. */\nexport function docsSectionsResult(task: Extract<DocsDraftTask, { kind: 'sections' }>, raw: unknown): DocsSections {\n const sections = sanitizeDocsSections(raw, task.keys);\n if (!Object.keys(sections).length) throw new Error(`Claude's answer holds none of the sections asked for (${task.keys.join(', ')}). Try again.`);\n return sections;\n}\n\n/**\n * Drafted sections applied to a docs.json, marked for review: the sections replace the ones there, the rest stays as\n * is (anatomy and preview are code-decided and never come from a draft), and draftedSections lists what waits.\n */\nexport function applyDocsSections<T extends Partial<ComponentDocsJson>>(docs: T, sections: DocsSections): T {\n const keys = PROSE_KEYS.filter((k) => sections[k] !== undefined);\n if (!keys.length) return docs;\n return markClaudeDraft({ ...docs, ...sections }, keys);\n}\n\n/**\n * The docs-draft Action's merge: Claude's prose on top of the pre-fill draft, only where the pre-fill is empty (a\n * written section is never overwritten), anatomy kept from the code, the drafted sections marked for review.\n */\nexport function mergeDocsDraft(prefillDraft: Partial<ComponentDocsJson>, reply: Record<string, unknown>): Partial<ComponentDocsJson> {\n const empty = PROSE_KEYS.filter((k) => {\n const v = prefillDraft[k];\n return v === undefined || (typeof v === 'string' ? !v.trim() : Array.isArray(v) && !v.length);\n });\n const sections = sanitizeDocsSections(reply, empty, { examples: true });\n const merged: Partial<ComponentDocsJson> = { ...prefillDraft, ...sections };\n if (reply.preview && !prefillDraft.preview && isExample(reply.preview)) merged.preview = reply.preview;\n merged.anatomy = prefillDraft.anatomy;\n const drafted = PROSE_KEYS.filter((k) => sections[k] !== undefined);\n return markClaudeDraft(merged, drafted.length && drafted.length < PROSE_KEYS.length ? drafted : undefined);\n}\n\n// ---------------------------------------------------------------------------------------------\n// The Messages API call (raw HTTP: no SDK dependency for one call)\n\nexport interface AnthropicHttpRequest {\n url: string;\n init: { method: 'POST'; headers: Record<string, string>; body: string };\n}\n\nexport interface AnthropicRequestInput {\n apiKey: string;\n prompt: string;\n model?: string | undefined;\n system?: string | undefined;\n maxTokens?: number | undefined;\n /** A direct call from a browser page (the user's own key): adds the header the API asks for. */\n browser?: boolean | undefined;\n /** Re-run a declined request on a fallback model inside the same call (server-side fallback beta). */\n fallback?: boolean | undefined;\n}\n\n/** The Messages API request for one prompt. The key goes in x-api-key, to api.anthropic.com only. */\nexport function anthropicRequest(input: AnthropicRequestInput): AnthropicHttpRequest {\n const headers: Record<string, string> = { 'x-api-key': input.apiKey, 'anthropic-version': '2023-06-01', 'content-type': 'application/json' };\n if (input.fallback) headers['anthropic-beta'] = 'server-side-fallback-2026-07-01';\n if (input.browser) headers['anthropic-dangerous-direct-browser-access'] = 'true';\n const body: Record<string, unknown> = {\n model: input.model || DOCS_DRAFT_MODEL,\n max_tokens: input.maxTokens ?? 16000,\n ...(input.fallback ? { fallbacks: 'default' } : {}),\n ...(input.system ? { system: input.system } : {}),\n messages: [{ role: 'user', content: input.prompt }],\n };\n return { url: ANTHROPIC_MESSAGES_URL, init: { method: 'POST', headers, body: JSON.stringify(body) } };\n}\n\n/** The text of a Messages API reply. Throws when Claude declined or the reply was cut off. */\nexport function anthropicReplyText(msg: unknown): string {\n const m = (msg ?? {}) as { stop_reason?: string; content?: { type?: string; text?: unknown }[] };\n if (m.stop_reason === 'refusal') throw new Error('Claude declined to draft this one.');\n if (m.stop_reason === 'max_tokens') throw new Error('The reply was cut off (max_tokens).');\n return (m.content ?? [])\n .filter((b) => b?.type === 'text' && typeof b.text === 'string')\n .map((b) => b.text as string)\n .join('');\n}\n","// Draft exchange: designers draft their change texts with their own Claude (Claude Desktop or Claude Code on their own\n// plan) through the Bridge MCP server, from the DS Bridge Figma plugin. Third-party apps cannot use a Claude plan, and\n// Bridge has no backend, so the channel is the GitHub repo both already reach with the designer's own token:\n//\n// 1. The plugin writes `.bridge/drafts/<sessionId>.json` (status \"pending\") on the requests branch, with the detected\n// changes, the deterministic draft and links to before and after PNGs uploaded next to it.\n// 2. The designer tells their Claude \"Draft my Bridge changes\". The MCP tool bridge_pending_drafts returns the pending\n// items (and the images, so Claude can see them), bridge_write_drafts writes the results back (status \"drafted\").\n// 3. The plugin polls the file, fills the fields it may fill, then deletes the file once the request or push is sent\n// (or cancelled).\n//\n// Bridge Studio uses the same exchange for component docs (a \"docs\" item, from the Library page): the item carries the\n// task (which prose sections, or a selected passage) and the full prompt with the facts from the code; the result\n// carries the sections (or the rewritten passage), sanitized to the docs.json shapes.\n//\n// Writers update with the file sha (optimistic concurrency) and retry on 409. Pure helpers plus a few GitHubClient\n// helpers: no DOM, no figma.*, no Node-only API.\n\nimport { DRAFT_LINE_MAX, cleanDraftText, sanitizeDraftLine, type DraftText } from './change-drafts';\nimport { type DocsDraftTask, type DocsSections, docsSectionsAnswer, docsTaskKeys, sanitizeDocsReplacement, validateDocsTask } from './docs-ai';\nimport type { ProseKey } from './docs-draft';\nimport { GitHubError, type GitHubClient } from './github-client';\nimport { REQUESTS_BRANCH, type RequestChange, type RequestKind, REQUEST_KINDS } from './requests';\n\nexport const DRAFT_EXCHANGE_VERSION = 1;\n/** Folder of pending draft sessions on the requests branch. */\nexport const DRAFTS_DIR = '.bridge/drafts';\n/** What the designer says to their Claude. */\nexport const DRAFT_PHRASE = 'Draft my Bridge changes';\nexport const DRAFT_TITLE_MAX = 70;\nexport const DRAFT_SUMMARY_SENTENCES = 3;\nexport { DRAFT_LINE_MAX };\nconst SUMMARY_MAX = 600;\n\nexport type DraftScope = 'request' | 'push' | 'docs';\n/** Who wrote the session: the DS Bridge Figma plugin, or Bridge Studio (component docs on the Library page). */\nexport type DraftSource = 'figma' | 'studio';\nexport type DraftSessionStatus = 'pending' | 'drafted';\n\nexport interface DraftImage {\n label: 'before' | 'after';\n /** Public URL on the requests branch (github.com/<repo>/blob/bridge-requests/<path>?raw=true). */\n url: string;\n /** Repo path on the requests branch, so tools can read it with the token. */\n path?: string | undefined;\n /** The change line (DraftLine id) this image shows, when an item has several components (a push). */\n line?: string | undefined;\n}\n\n/**\n * One detected component change to describe in one sentence (its \"change line\"): the main line of its row in the\n * plugin and the first line of its request. A request item has one, a push item one per component it requests.\n */\nexport interface DraftLine {\n /** Stable id to answer with (the plugin uses the component's node id). */\n id: string;\n component?: string | undefined;\n kind?: RequestKind | undefined;\n changes: RequestChange[];\n /** The deterministic line, from the changes only, as a starting point. */\n line: string;\n /** The deterministic request title of this component change, as a starting point. Missing from older plugins. */\n title?: string | undefined;\n}\n\nexport interface DraftVariableRow {\n path: string;\n before?: string | undefined;\n after?: string | undefined;\n}\n\nexport interface DraftItem {\n id: string;\n /** \"request\": one component change request. \"push\": the pull request description of variable edits. */\n scope: DraftScope;\n component?: string | undefined;\n kind?: RequestKind | undefined;\n changes: RequestChange[];\n /** Push only: the variable edits (token path, value now, value in Figma). */\n variables?: DraftVariableRow[] | undefined;\n /** Push only: components the push also sends a request for. */\n components?: string[] | undefined;\n /** What the designer already typed: their intent, kept in the answer. */\n notes?: string | undefined;\n images?: DraftImage[] | undefined;\n /** The deterministic draft (from the detected changes only), as a starting point. */\n draft: DraftText;\n /** Component changes to write one line each for. Missing in sessions from older plugins. */\n lines?: DraftLine[] | undefined;\n /** Docs only: the component docs to write. */\n docs?: DraftDocsItem | undefined;\n}\n\n/** A docs item: prose sections of one component's docs.json (or one selected passage), from Bridge Studio. */\nexport interface DraftDocsItem {\n /** Component slug on the Library page (button, icon-button). */\n slug: string;\n /** docs.json path in the repo. */\n path?: string | undefined;\n task: DocsDraftTask;\n /** The full prompt: the task, the rules, the facts from the code (props, CSS module classes, JSDoc, tokens), the voice. */\n prompt: string;\n}\n\nexport interface DraftResult {\n id: string;\n title: string;\n summary: string;\n /**\n * One sentence per change line of the item (by DraftLine id), and the title of the request it becomes. Optional:\n * older writers send none, or lines without a title.\n */\n lines?: DraftResultLine[] | undefined;\n /** Docs items (sections task): the sections Claude wrote, sanitized to the docs.json shapes. */\n docs?: DocsSections | undefined;\n /** Docs items (selection task): the rewritten passage. */\n replacement?: string | undefined;\n /** Docs items (sections task): checked sections Claude verified and left unchanged (still accurate). */\n checked?: ProseKey[] | undefined;\n by: 'claude';\n at: string;\n}\n\nexport interface DraftResultLine {\n id: string;\n /** May be empty when only the title was written. */\n line: string;\n /** The request title of this component change: short, sentence case, at most 70 characters (\"Add an icon after the label\"). */\n title?: string | undefined;\n}\n\nexport interface PendingDrafts {\n version: 1;\n sessionId: string;\n createdAt: string;\n status: DraftSessionStatus;\n source: DraftSource;\n items: DraftItem[];\n results?: DraftResult[] | undefined;\n}\n\n// ---------------------------------------------------------------------------------------------\n// The words Claude gets: the Bridge voice and the exact output contract.\n\nexport const DRAFT_VOICE_RULES = [\n 'Write like a calm, precise colleague. Sentence case. Start the title with a verb.',\n 'Look at the before and after images first, then the change table: say what changes for developers (props, variants, tokens, the look) and why it matters for people who use the component.',\n 'Use only facts from the changes, the images and the designer\\'s notes. Never invent numbers, names, usage or reasons. If the reason is unknown, say what changes and leave the reason out.',\n 'Keep the designer\\'s intent from their notes.',\n 'Never use an em dash: use a colon, a comma or parentheses. No exclamation marks, no emoji, no Markdown.',\n 'A request title never repeats the component name: the issue title already starts with it.',\n `For each change line, write one short sentence (at most ${DRAFT_LINE_MAX} characters, no trailing period) of what changed for developers, read from the before and after images: the part, the variant and the values when you can see them, for example \"Icon added after the label in primary sm: Pencil, 16px\". Never guess a value you cannot read.`,\n `For each change line, also write the title of the request it becomes: short, sentence case, starts with a verb, at most ${DRAFT_TITLE_MAX} characters, no trailing period, never the component name, for example \"Add an icon after the label\".`,\n];\n\nexport const DRAFT_OUTPUT_CONTRACT = [\n `Call bridge_write_drafts once per session with {\"sessionId\": \"...\", \"results\": [{\"id\": \"<item id>\", \"title\": \"...\", \"summary\": \"...\", \"lines\": [{\"id\": \"<line id>\", \"line\": \"...\", \"title\": \"...\"}]}]}, one result per item.`,\n `title: one line, at most ${DRAFT_TITLE_MAX} characters, no trailing period.`,\n `summary: at most ${DRAFT_SUMMARY_SENTENCES} sentences, plain text.`,\n `lines: one per change line the item lists (its \"lines\"), by line id: line is one sentence, at most ${DRAFT_LINE_MAX} characters, no trailing period; title is the request title for that component change, at most ${DRAFT_TITLE_MAX} characters, no trailing period. Leave lines out when the item lists none.`,\n 'Docs items (scope \"docs\", from Bridge Studio): follow the item\\'s prompt and send {\"id\": \"<item id>\", \"docs\": {<only the sections it asks for>}} for a sections task (a section to check goes in only when something in it is no longer true for the code: leave accurate ones out, {\"docs\": {}} when all are), or {\"id\": \"<item id>\", \"replacement\": \"...\"} for a selection task. No title or summary. The designer reviews them on the Library page.',\n 'The designer reviews the text in Figma before anything is sent.',\n];\n\n// ---------------------------------------------------------------------------------------------\n// Pure helpers\n\n/** A random session id: 16 lowercase base-36 characters, safe in a file name. */\nexport function newDraftSessionId(random: () => number = Math.random): string {\n let out = '';\n while (out.length < 16) out += Math.floor(random() * 36).toString(36);\n return out;\n}\n\nconst SESSION_RE = /^[a-z0-9-]{6,64}$/;\nexport const isDraftSessionId = (s: unknown): s is string => typeof s === 'string' && SESSION_RE.test(s);\n\n/** Path of a session file on the requests branch. */\nexport function draftSessionPath(sessionId: string): string {\n if (!isDraftSessionId(sessionId)) throw new Error(`\"${sessionId}\" is not a draft session id.`);\n return `${DRAFTS_DIR}/${sessionId}.json`;\n}\n\n/** Path of an image of a session item on the requests branch: `.bridge/drafts/<sessionId>/<itemId>-<label>.png`. */\nexport function draftImagePath(sessionId: string, itemId: string, label: DraftImage['label']): string {\n const item = itemId.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'item';\n draftSessionPath(sessionId);\n return `${DRAFTS_DIR}/${sessionId}/${item}-${label}.png`;\n}\n\nexport interface ComposeDraftsInput {\n items: DraftItem[];\n source?: DraftSource | undefined;\n sessionId?: string | undefined;\n now?: Date | undefined;\n random?: (() => number) | undefined;\n}\n\n/** A new pending session. Throws when it has no item or an item is invalid. */\nexport function composePendingDrafts(input: ComposeDraftsInput): PendingDrafts {\n const p: PendingDrafts = {\n version: DRAFT_EXCHANGE_VERSION,\n sessionId: input.sessionId ?? newDraftSessionId(input.random),\n createdAt: (input.now ?? new Date()).toISOString(),\n status: 'pending',\n source: input.source ?? 'figma',\n items: input.items.map((i) => ({ ...i, changes: i.changes ?? [] })),\n };\n const problems = validatePendingDrafts(p);\n if (problems.length) throw new Error(problems.join(' '));\n return p;\n}\n\nconst KINDS = new Set<string>(REQUEST_KINDS.map((k) => k.value));\nconst str = (x: unknown) => typeof x === 'string';\nconst optStr = (x: unknown) => x === undefined || typeof x === 'string';\n\n/** Problems in a session, as sentences. Empty when valid. */\nexport function validatePendingDrafts(x: unknown): string[] {\n const out: string[] = [];\n if (!x || typeof x !== 'object' || Array.isArray(x)) return ['A draft session is a JSON object.'];\n const p = x as Partial<PendingDrafts>;\n if (p.version !== DRAFT_EXCHANGE_VERSION) out.push(`Unsupported draft session version ${String(p.version)}: update Bridge.`);\n if (!isDraftSessionId(p.sessionId)) out.push('The session id is missing or invalid.');\n if (!str(p.createdAt) || Number.isNaN(Date.parse(p.createdAt!))) out.push('createdAt must be an ISO date.');\n if (p.status !== 'pending' && p.status !== 'drafted') out.push('status must be \"pending\" or \"drafted\".');\n if (p.source !== 'figma' && p.source !== 'studio') out.push('source must be \"figma\" or \"studio\".');\n if (!Array.isArray(p.items) || !p.items.length) out.push('A draft session needs at least one item.');\n const ids = new Set<string>();\n for (const [n, i] of (Array.isArray(p.items) ? p.items : []).entries()) {\n const at = `Item ${n + 1}`;\n if (!i || typeof i !== 'object') {\n out.push(`${at} is not an object.`);\n continue;\n }\n if (!str(i.id) || !i.id) out.push(`${at} has no id.`);\n else if (ids.has(i.id)) out.push(`${at} repeats the id \"${i.id}\".`);\n else ids.add(i.id);\n if (i.scope !== 'request' && i.scope !== 'push' && i.scope !== 'docs') out.push(`${at}: scope must be \"request\", \"push\" or \"docs\".`);\n if (i.scope === 'docs') {\n const d = i.docs;\n if (!d || typeof d !== 'object' || !str(d.slug) || !d.slug || !str(d.prompt) || !d.prompt || !optStr(d.path)) out.push(`${at}: a docs item needs docs {slug, task, prompt}.`);\n else out.push(...validateDocsTask(d.task).map((m) => `${at}: ${m}`));\n } else if (i.docs !== undefined) out.push(`${at}: only a docs item has docs.`);\n if (!optStr(i.component)) out.push(`${at}: component must be text.`);\n if (i.kind !== undefined && !KINDS.has(i.kind)) out.push(`${at}: unknown kind \"${String(i.kind)}\".`);\n if (!Array.isArray(i.changes) || i.changes.some((c) => !c || !str(c.field) || !optStr(c.before) || !optStr(c.after))) out.push(`${at}: changes must be a list of {field, before, after}.`);\n if (i.variables !== undefined && (!Array.isArray(i.variables) || i.variables.some((v) => !v || !str(v.path)))) out.push(`${at}: variables must be a list of {path, before, after}.`);\n if (i.variables !== undefined && i.scope !== 'push') out.push(`${at}: only a push item has variables.`);\n if (i.images !== undefined && (!Array.isArray(i.images) || i.images.some((m) => !m || (m.label !== 'before' && m.label !== 'after') || !str(m.url)))) out.push(`${at}: images must be a list of {label: before or after, url}.`);\n if (!i.draft || !str(i.draft.title) || !str(i.draft.summary)) out.push(`${at}: draft must hold a title and a summary.`);\n if (i.lines !== undefined && (!Array.isArray(i.lines) || i.lines.some((l) => !l || !str(l.id) || !l.id || !str(l.line) || !optStr(l.title) || !Array.isArray(l.changes)))) out.push(`${at}: lines must be a list of {id, changes, line, title}.`);\n }\n if (p.results !== undefined) {\n if (!Array.isArray(p.results)) out.push('results must be a list.');\n else\n for (const r of p.results) {\n if (!r || !str(r.id) || !str(r.title) || !str(r.summary)) out.push('Each result needs an id, a title and a summary.');\n else if (r.docs !== undefined && (!r.docs || typeof r.docs !== 'object' || Array.isArray(r.docs))) out.push('Result docs must be an object of sections.');\n else if (!optStr(r.replacement)) out.push('A result replacement must be text.');\n else if (r.lines !== undefined && (!Array.isArray(r.lines) || r.lines.some((l) => !l || !str(l.id) || !str(l.line) || !optStr(l.title)))) out.push('Result lines must be a list of {id, line, title}.');\n }\n }\n return out;\n}\n\n/** The session in a file's text, or undefined when it is not a valid session. */\nexport function parsePendingDrafts(text: string | null | undefined): PendingDrafts | undefined {\n if (!text) return undefined;\n let json: unknown;\n try {\n json = JSON.parse(text);\n } catch {\n return undefined;\n }\n return validatePendingDrafts(json).length ? undefined : (json as PendingDrafts);\n}\n\nexport function serializePendingDrafts(p: PendingDrafts): string {\n return `${JSON.stringify(p, null, 2)}\\n`;\n}\n\n/** Shortens to `max` characters at a word boundary, without a trailing period. */\nfunction clip(text: string, max: number): string {\n const t = text.replace(/\\s+/g, ' ').trim().replace(/\\.$/, '');\n if (t.length <= max) return t;\n const cut = t.slice(0, max + 1);\n const at = cut.lastIndexOf(' ');\n return (at > max * 0.5 ? cut.slice(0, at) : t.slice(0, max)).replace(/[\\s,;:]+$/, '');\n}\n\n/** At most 3 sentences and 600 characters. */\nfunction sentences(text: string): string {\n const t = text.replace(/\\s+/g, ' ').trim();\n const parts = t.match(/[^.!?]+(?:[.!?]+(?=\\s|$)|$)/g) ?? [t];\n let out = parts.slice(0, DRAFT_SUMMARY_SENTENCES).map((s) => s.trim()).join(' ');\n if (out.length > SUMMARY_MAX) out = `${clip(out, SUMMARY_MAX)}.`;\n return out;\n}\n\n/**\n * Title and summary kept to the contract: em dashes removed, title one line of at most 70 characters with no\n * trailing period, summary at most 3 sentences. Both may come back empty.\n */\nexport function sanitizeDraftText(raw: { title?: unknown; summary?: unknown }): DraftText {\n const title = typeof raw.title === 'string' ? clip(cleanDraftText(raw.title), DRAFT_TITLE_MAX) : '';\n const summary = typeof raw.summary === 'string' ? sentences(cleanDraftText(raw.summary)) : '';\n return { title, summary };\n}\n\n/** What a writer (bridge_write_drafts) sends for one item, before sanitizing. */\nexport interface DraftResultInput {\n id: string;\n title?: unknown;\n summary?: unknown;\n lines?: unknown;\n /** Docs items: the sections written (sections task). */\n docs?: unknown;\n /** Docs items: the rewritten passage (selection task). */\n replacement?: unknown;\n}\n\n/** The docs part of a result for a docs item, sanitized to its task. Throws when it holds nothing the task asked for. */\nexport function sanitizeDocsResult(item: DraftItem, r: DraftResultInput): Pick<DraftResult, 'docs' | 'replacement' | 'checked'> {\n const task = item.docs!.task;\n if (task.kind === 'selection') {\n const raw = r.replacement ?? (r.docs && typeof r.docs === 'object' ? (r.docs as Record<string, unknown>)[task.key] : undefined);\n const replacement = sanitizeDocsReplacement(raw);\n if (!replacement) throw new Error(`Item \"${item.id}\" asks to rewrite a passage of ${task.key}: send {\"id\": \"${item.id}\", \"replacement\": \"...\"}.`);\n return { replacement };\n }\n try {\n const { sections, checked } = docsSectionsAnswer(task, r.docs ?? {});\n return { docs: sections, checked };\n } catch {\n throw new Error(`Item \"${item.id}\" asks for the sections ${docsTaskKeys(task).join(', ')}: send {\"id\": \"${item.id}\", \"docs\": {${task.keys.map((k) => `\"${k}\": ...`).join(', ')}}} in the shapes of its prompt.`);\n }\n}\n\n/**\n * The change lines of a result kept to the contract: known line ids only (throws on an unknown one), one sentence of\n * at most 120 characters each, empty ones dropped, the last one per id kept.\n */\nexport function sanitizeResultLines(item: Pick<DraftItem, 'id' | 'lines'>, raw: unknown): DraftResultLine[] {\n if (raw === undefined || raw === null) return [];\n if (!Array.isArray(raw)) throw new Error(`lines for \"${item.id}\" must be a list of {\"id\", \"line\", \"title\"}.`);\n const known = new Set((item.lines ?? []).map((l) => l.id));\n const out = new Map<string, DraftResultLine>();\n for (const l of raw as { id?: unknown; line?: unknown; title?: unknown }[]) {\n const id = typeof l?.id === 'string' ? l.id : '';\n if (!known.has(id)) throw new Error(`Item \"${item.id}\" has no change line \"${id}\".${known.size ? ` Use the line ids from bridge_pending_drafts: ${[...known].join(', ')}.` : ' It lists no lines: leave lines out.'}`);\n const line = sanitizeDraftLine(l.line);\n const title = sanitizeDraftTitle(l.title);\n if (line || title) out.set(id, { id, line, ...(title ? { title } : {}) });\n }\n return [...out.values()];\n}\n\n/** A request title kept to the contract: one line, no em dash, sentence case, at most 70 characters, no trailing period. */\nexport function sanitizeDraftTitle(raw: unknown): string {\n if (typeof raw !== 'string') return '';\n const t = clip(cleanDraftText(raw.replace(/[\\r\\n]+/g, ' ')), DRAFT_TITLE_MAX);\n return t.charAt(0).toUpperCase() + t.slice(1);\n}\n\n/**\n * The session with these results added (a result for the same item replaces the earlier one). Results are sanitized.\n * Throws on an unknown item id or an empty result. Status is \"drafted\" once every item has a result.\n */\nexport function mergeDraftResults(p: PendingDrafts, results: DraftResultInput[], at: Date = new Date()): PendingDrafts {\n const ids = new Set(p.items.map((i) => i.id));\n const next = new Map((p.results ?? []).map((r) => [r.id, r]));\n for (const r of results) {\n if (!ids.has(r.id)) throw new Error(`Session ${p.sessionId} has no item \"${r.id}\". Use the ids from bridge_pending_drafts: ${[...ids].join(', ')}.`);\n const item = p.items.find((i) => i.id === r.id)!;\n if (item.scope === 'docs') {\n next.set(r.id, { id: r.id, title: '', summary: '', ...sanitizeDocsResult(item, r), by: 'claude', at: at.toISOString() });\n continue;\n }\n const clean = sanitizeDraftText(r);\n const lines = sanitizeResultLines(item, r.lines);\n if (!clean.title && !clean.summary && !lines.length) throw new Error(`The result for \"${r.id}\" has no title and no summary, and no line.`);\n next.set(r.id, { id: r.id, title: clean.title, summary: clean.summary, ...(lines.length ? { lines } : {}), by: 'claude', at: at.toISOString() });\n }\n const merged = p.items.map((i) => next.get(i.id)).filter((r): r is DraftResult => !!r);\n return { ...p, results: merged, status: merged.length === p.items.length ? 'drafted' : 'pending' };\n}\n\n/** The Markdown brief of one item, for Claude: what to write, the facts, the starting draft. */\nexport function draftItemBrief(i: DraftItem): string {\n if (i.scope === 'docs' && i.docs) {\n const t = i.docs.task;\n const check = t.kind === 'sections' ? (t.check ?? []).filter((k) => t.keys.includes(k)) : [];\n const write = t.kind === 'sections' ? t.keys.filter((k) => !check.includes(k)) : [];\n const what =\n t.kind === 'selection'\n ? `rewrite one passage of the ${t.key} section (${t.mode}), answer with \"replacement\"`\n : [\n write.length ? `${t.rewrite ? 'rewrite' : 'write'} the sections ${write.join(', ')}` : '',\n check.length ? `check the sections ${check.join(', ')} against the code and return one only when something in it is no longer true (leave accurate ones out)` : '',\n ]\n .filter(Boolean)\n .join('; ') + ', answer with \"docs\"';\n return [`Item ${i.id}: component docs${i.component ? ` of ${i.component}` : ''} from Bridge Studio (${i.docs.path ?? i.docs.slug}): ${what}.`, '', i.docs.prompt].join('\\n');\n }\n const kind = i.kind ? REQUEST_KINDS.find((k) => k.value === i.kind)?.label : undefined;\n const cell = (s: string | undefined) => (s ?? '').replace(/\\|/g, '\\\\|').replace(/\\n/g, ' ');\n const lines: string[] = [`Item ${i.id}: ${i.scope === 'request' ? 'a component change request (a GitHub issue developers implement)' : 'the description of a pull request with design token (variable) edits from Figma'}.`];\n if (i.component) lines.push(`Component: ${i.component}`);\n if (kind) lines.push(`Kind: ${kind}`);\n if (i.components?.length) lines.push(`Components with a change request: ${i.components.join(', ')}`);\n if (i.changes.length) lines.push('', '| What | Now | In Figma |', '| --- | --- | --- |', ...i.changes.map((c) => `| ${cell(c.field)} | ${cell(c.before) || 'none'} | ${cell(c.after) || 'removed'} |`));\n if (i.variables?.length) lines.push('', '| Token | Now | In Figma |', '| --- | --- | --- |', ...i.variables.map((v) => `| ${cell(v.path)} | ${cell(v.before) || 'none'} | ${cell(v.after) || 'removed'} |`));\n if (!i.changes.length && !i.variables?.length && !i.lines?.length) lines.push('', 'No change detected: rely on the notes and the images.');\n if (i.draft.title || i.draft.summary) lines.push('', 'Starting draft, written from the changes only:', `Title: ${i.draft.title}`, `Summary: ${i.draft.summary}`);\n if (i.notes?.trim()) lines.push('', 'The designer\\'s notes (keep their intent):', i.notes.trim());\n if (i.lines?.length) {\n lines.push('', `Change lines to write (one sentence each, at most ${DRAFT_LINE_MAX} characters, from the before and after images), each with the title of its request (at most ${DRAFT_TITLE_MAX} characters):`);\n for (const l of i.lines) {\n lines.push(`- Line ${l.id}${l.component ? `, ${l.component}` : ''}${l.kind ? ` (${REQUEST_KINDS.find((k) => k.value === l.kind)?.label ?? l.kind})` : ''}. Starting line: ${l.line || '(none)'}${l.title ? `. Starting title: ${l.title}` : ''}`);\n for (const c of l.changes) lines.push(` - ${c.field}: ${c.before || 'none'} -> ${c.after || 'removed'}`);\n }\n }\n if (i.images?.length) lines.push('', `Images: ${i.images.map((m) => `${m.label}${m.line ? ` (line ${m.line})` : ''} ${m.url}`).join(', ')}`);\n return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------------------------\n// GitHub: read and write sessions on the requests branch\n\ntype DraftClient = Pick<GitHubClient, 'getFile' | 'putFile' | 'deleteFile' | 'listDirectory'>;\n\nconst isConflict = (err: unknown) => err instanceof GitHubError ? err.status === 409 || (err.status === 422 && /sha/i.test(`${err.detail ?? ''} ${err.message}`)) : (err as { status?: number })?.status === 409;\n\n/** Writes a new session file on the requests branch (the branch must exist). Returns the session. */\nexport async function createPendingDrafts(client: DraftClient, p: PendingDrafts, branch = REQUESTS_BRANCH): Promise<PendingDrafts> {\n const problems = validatePendingDrafts(p);\n if (problems.length) throw new Error(problems.join(' '));\n await client.putFile({ path: draftSessionPath(p.sessionId), content: serializePendingDrafts(p), branch, message: `Bridge drafts: ${p.items.length === 1 ? '1 item' : `${p.items.length} items`} waiting for Claude` });\n return p;\n}\n\n/** One session and its file sha, or undefined when the file is gone (sent, cancelled) or not a session. */\nexport async function readPendingDrafts(client: Pick<GitHubClient, 'getFile'>, sessionId: string, branch = REQUESTS_BRANCH): Promise<{ drafts: PendingDrafts; sha: string } | undefined> {\n const f = await client.getFile(draftSessionPath(sessionId), branch);\n const drafts = parsePendingDrafts(f?.text);\n return f && drafts ? { drafts, sha: f.sha } : undefined;\n}\n\n/** Every valid session on the requests branch, newest first. Unreadable files are skipped. */\nexport async function listPendingDrafts(client: Pick<GitHubClient, 'getFile' | 'listDirectory'>, opts: { status?: DraftSessionStatus | 'all'; branch?: string } = {}): Promise<PendingDrafts[]> {\n const branch = opts.branch ?? REQUESTS_BRANCH;\n const entries = (await client.listDirectory(DRAFTS_DIR, branch)).filter((e) => e.type === 'file' && /\\.json$/.test(e.name));\n const out: PendingDrafts[] = [];\n for (const e of entries) {\n const id = e.name.replace(/\\.json$/, '');\n if (!isDraftSessionId(id)) continue;\n const r = await readPendingDrafts(client, id, branch).catch(() => undefined);\n if (r && r.drafts.sessionId === id) out.push(r.drafts);\n }\n const status = opts.status ?? 'all';\n return out.filter((p) => status === 'all' || p.status === status).sort((a, b) => b.createdAt.localeCompare(a.createdAt));\n}\n\n/**\n * Read, change and write a session with its sha; when someone else wrote it in between (409), read it again and\n * retry, up to `attempts` times. Throws when the session does not exist.\n */\nexport async function updatePendingDrafts(\n client: DraftClient,\n sessionId: string,\n change: (p: PendingDrafts) => PendingDrafts,\n opts: { branch?: string; attempts?: number; message?: string } = {},\n): Promise<PendingDrafts> {\n const branch = opts.branch ?? REQUESTS_BRANCH;\n const attempts = Math.max(1, opts.attempts ?? 3);\n for (let attempt = 1; ; attempt++) {\n const cur = await readPendingDrafts(client, sessionId, branch);\n if (!cur) throw new Error(`No pending drafts for session ${sessionId}: it was sent or cancelled in Figma. Call bridge_pending_drafts for the current ones.`);\n const next = change(cur.drafts);\n try {\n await client.putFile({ path: draftSessionPath(sessionId), content: serializePendingDrafts(next), branch, message: opts.message ?? 'Bridge drafts: update', sha: cur.sha });\n return next;\n } catch (err) {\n if (attempt >= attempts || !isConflict(err)) throw err;\n }\n }\n}\n\n/** Writes Claude's results into a session (sanitized, merged, status \"drafted\" when complete), retrying on 409. */\nexport function writeDraftResults(client: DraftClient, sessionId: string, results: DraftResultInput[], opts: { branch?: string; now?: Date; attempts?: number } = {}): Promise<PendingDrafts> {\n return updatePendingDrafts(client, sessionId, (p) => mergeDraftResults(p, results, opts.now), {\n ...opts,\n message: `Bridge drafts: ${results.length === 1 ? '1 text' : `${results.length} texts`} drafted by Claude`,\n });\n}\n\n/**\n * Removes a session once it was sent or cancelled: its file, then its images (best effort). Returns false when it was\n * already gone.\n */\nexport async function deletePendingDrafts(client: DraftClient, sessionId: string, opts: { branch?: string } = {}): Promise<boolean> {\n const branch = opts.branch ?? REQUESTS_BRANCH;\n const path = draftSessionPath(sessionId);\n const f = await client.getFile(path, branch);\n if (!f) return false;\n await client.deleteFile({ path, branch, message: 'Bridge drafts: done', sha: f.sha });\n const images = await client.listDirectory(`${DRAFTS_DIR}/${sessionId}`, branch).catch(() => []);\n for (const img of images.filter((e) => e.type === 'file')) {\n await client.deleteFile({ path: img.path, branch, message: 'Bridge drafts: done', sha: img.sha }).catch(() => undefined);\n }\n return true;\n}\n\n/** Creates the requests branch from the head of `baseBranch` when it is missing. Never moves an existing branch. */\nexport async function ensureRequestsBranch(client: Pick<GitHubClient, 'getBranchSha' | 'createBranch'>, baseBranch: string): Promise<void> {\n if (await client.getBranchSha(REQUESTS_BRANCH)) return;\n const head = await client.getBranchSha(baseBranch);\n if (!head) throw new Error(`Branch \"${baseBranch}\" was not found, so the ${REQUESTS_BRANCH} branch cannot start from it.`);\n await client.createBranch(REQUESTS_BRANCH, head);\n}\n\nexport interface DocsDraftSessionInput {\n component: string;\n slug: string;\n path?: string | undefined;\n task: DocsDraftTask;\n prompt: string;\n /** Branch the requests branch starts from when it does not exist yet. */\n baseBranch: string;\n now?: Date | undefined;\n random?: (() => number) | undefined;\n}\n\n/**\n * Bridge Studio asks the user's own Claude for component docs: one docs item in a new session (source \"studio\") on\n * the requests branch, created from `baseBranch` when missing. Returns the session to poll.\n */\nexport async function createDocsDraftSession(\n client: Pick<GitHubClient, 'getBranchSha' | 'createBranch' | 'getFile' | 'putFile' | 'deleteFile' | 'listDirectory'>,\n input: DocsDraftSessionInput,\n): Promise<PendingDrafts> {\n await ensureRequestsBranch(client, input.baseBranch);\n const what = input.task.kind === 'selection' ? `Rewrite a passage of ${input.task.key}` : `${input.task.rewrite ? 'Rewrite' : 'Write'} ${input.task.keys.join(', ')}`;\n const item: DraftItem = {\n id: 'docs-1',\n scope: 'docs',\n component: input.component,\n changes: [],\n draft: { title: `${input.component} docs`, summary: what },\n docs: { slug: input.slug, ...(input.path ? { path: input.path } : {}), task: input.task, prompt: input.prompt },\n };\n return createPendingDrafts(client, composePendingDrafts({ items: [item], source: 'studio', now: input.now, random: input.random }));\n}\n\n// ---------------------------------------------------------------------------------------------\n// Polling: the plugin and Studio read the session until Claude answers\n\nexport const DRAFT_POLL_INTERVAL_MS = 5_000;\nexport const DRAFT_POLL_TIMEOUT_MS = 10 * 60_000;\n\nexport interface DraftPollerOptions {\n client: Pick<GitHubClient, 'getFile'>;\n sessionId: string;\n intervalMs?: number | undefined;\n timeoutMs?: number | undefined;\n now?: (() => number) | undefined;\n setTimer?: ((fn: () => void, ms: number) => unknown) | undefined;\n clearTimer?: ((handle: unknown) => void) | undefined;\n /** Claude answered every item. Polling has stopped. */\n onResults: (results: DraftResult[], drafts: PendingDrafts) => void;\n /** No answer within the timeout. Polling has stopped; start() polls again. */\n onTimeout: () => void;\n /** The file is gone (sent or cancelled elsewhere). Polling has stopped. */\n onGone?: (() => void) | undefined;\n /** A read failed; polling goes on. */\n onError?: ((message: string) => void) | undefined;\n}\n\n/** Reads the session every 5 seconds until Claude answers, the file goes away, or 10 minutes pass. */\nexport class DraftPoller {\n private handle: unknown;\n private startedAt = 0;\n private running = false;\n private busy = false;\n\n constructor(private readonly o: DraftPollerOptions) {}\n\n get active(): boolean {\n return this.running;\n }\n\n private now(): number {\n return (this.o.now ?? Date.now)();\n }\n\n private schedule(): void {\n const set = this.o.setTimer ?? ((fn: () => void, ms: number) => setTimeout(fn, ms));\n this.handle = set(() => void this.tick(), this.o.intervalMs ?? DRAFT_POLL_INTERVAL_MS);\n }\n\n /** Starts (or restarts, after a timeout) polling; the timeout counts from now. */\n start(): void {\n this.stop();\n this.running = true;\n this.startedAt = this.now();\n this.schedule();\n }\n\n stop(): void {\n if (this.handle !== undefined) (this.o.clearTimer ?? ((h: unknown) => clearTimeout(h as ReturnType<typeof setTimeout>)))(this.handle);\n this.handle = undefined;\n this.running = false;\n }\n\n private async tick(): Promise<void> {\n if (!this.running) return;\n this.handle = undefined;\n const done = await this.check();\n if (done || !this.running) return;\n if (this.now() - this.startedAt >= (this.o.timeoutMs ?? DRAFT_POLL_TIMEOUT_MS)) {\n this.stop();\n this.o.onTimeout();\n return;\n }\n this.schedule();\n }\n\n /** Reads the file once. True when polling is over (answered or gone). */\n async check(): Promise<boolean> {\n if (this.busy) return false;\n this.busy = true;\n try {\n const cur = await readPendingDrafts(this.o.client, this.o.sessionId);\n if (!cur) {\n this.stop();\n this.o.onGone?.();\n return true;\n }\n if (cur.drafts.status === 'drafted' && cur.drafts.results?.length) {\n this.stop();\n this.o.onResults(cur.drafts.results, cur.drafts);\n return true;\n }\n return false;\n } catch (err) {\n this.o.onError?.(err instanceof Error ? err.message : String(err));\n return false;\n } finally {\n this.busy = false;\n }\n }\n}\n","// Explorations on GitHub: start one (branch from the base with the exploration note, a draft pull request labeled\n// `exploration`), list them, promote one to review, close one. Shared by Studio (in the browser, with the viewer's\n// token), the MCP server and the CLI. The pure rules are in explorations.ts.\n\nimport type { BridgeConfig } from './config';\nimport {\n EXPLORATION_LABEL,\n EXPLORATION_PREFIX,\n explorationNote,\n explorationNotePath,\n explorationPrBody,\n explorationPrTitle,\n explorationProblems,\n explorationSlug,\n explorationStatus,\n explorationTryIt,\n isExplorationPull,\n parseExplorationBody,\n promotionPlan,\n type Exploration,\n type ExplorationSource,\n type ExplorationStatus,\n type ExplorationTryIt,\n type PromotionPlan,\n} from './explorations';\nimport { GitHubError, type GitHubClient, type PullRequestSummary } from './github-client';\nimport { findPreviewComment, previewLinks, previewsSettled, type BranchPreview, type PreviewApps } from './previews';\nimport { branchPreviewUrls } from './previews-github';\n\nexport interface ExplorationSettings {\n /** Branch explorations start from and pull requests target (the default branch). */\n base: string;\n /** Snapshot packages (bridge.config.json previews.packages). */\n packages: string[];\n /** Per-branch preview URL templates (bridge.config.json previews.apps). */\n apps: PreviewApps;\n /** Requests the exploration answers, listed in its draft pull request body. */\n requests?: { number: number; title: string }[] | undefined;\n /** More labels for the draft pull request, such as the product ones (productMarks). */\n labels?: string[] | undefined;\n}\n\nexport interface ExplorationSummary {\n number: number;\n url: string;\n branch: string;\n slug: string;\n name: string;\n purpose: string;\n useCase?: string | undefined;\n status: ExplorationStatus;\n draft: boolean;\n author: string;\n /** Where it was started and the AI agent that started it, when the exploration block says so. */\n source?: ExplorationSource | undefined;\n agent?: string | undefined;\n updatedAt: string;\n /** Head commit of the branch. */\n headSha: string;\n /**\n * Template previews Vercel cannot have shortened (a host label of 63 characters or less), without a round trip. The\n * URLs Vercel reports, with their build state, come from `explorationTestBuildOnGitHub`.\n */\n previews: { app: string; label: string; url: string }[];\n}\n\n/** One exploration from a pull request summary. */\nexport function explorationSummary(p: PullRequestSummary, _owner: string, _repo: string, s: Pick<ExplorationSettings, 'packages' | 'apps'>): ExplorationSummary {\n const e = parseExplorationBody(p.body);\n const slug = p.headRef?.startsWith(EXPLORATION_PREFIX) ? p.headRef.slice(EXPLORATION_PREFIX.length) : (e?.slug ?? explorationSlug(p.title));\n return {\n number: p.number,\n url: p.url,\n branch: p.headRef,\n slug,\n name: e?.name ?? p.title.replace(/^[A-Z][A-Z0-9_]*-\\d+\\s+/, '').replace(/^Exploration:\\s*/i, ''),\n purpose: e?.purpose ?? '',\n ...(e?.useCase ? { useCase: e.useCase } : {}),\n status: explorationStatus({ state: p.state, labels: p.labels, headRef: p.headRef, body: p.body }),\n draft: p.draft,\n author: e?.author ?? p.author,\n ...(e?.source ? { source: e.source } : {}),\n ...(e?.agent ? { agent: e.agent } : {}),\n updatedAt: p.updatedAt,\n headSha: p.headSha,\n previews: previewLinks(s.apps, { branch: p.headRef, pr: p.number, sha: p.headSha }),\n };\n}\n\n/** Explorations of the repo, newest activity first. `state: 'open'` lists the running ones and the promoted open ones. */\nexport async function listExplorationsOnGitHub(gh: GitHubClient, s: Pick<ExplorationSettings, 'packages' | 'apps'>, opts: { state?: 'open' | 'closed' | 'all' } = {}): Promise<ExplorationSummary[]> {\n const pulls = await gh.listPullRequests(opts.state ?? 'open');\n return pulls.filter((p) => isExplorationPull({ state: p.state, labels: p.labels, headRef: p.headRef, body: p.body })).map((p) => explorationSummary(p, gh.owner, gh.name, s));\n}\n\nexport interface StartedExploration {\n branch: string;\n slug: string;\n pr: number;\n url: string;\n commit: string;\n /** Just started: the snapshot is not built yet. `explorationTestBuildOnGitHub` reads the command once it is. */\n tryIt: ExplorationTryIt;\n previews: { app: string; label: string; url: string }[];\n}\n\n/**\n * Starts an exploration: the branch `explore/<slug>` from the base with one commit (the exploration note), a draft\n * pull request labeled `exploration`, then the body rewritten with the pull request number so it carries the\n * install command. Refuses an exploration whose branch already exists.\n */\nexport async function startExplorationOnGitHub(gh: GitHubClient, e: Exploration, s: ExplorationSettings): Promise<StartedExploration> {\n const problems = explorationProblems(e);\n if (problems.length) throw new GitHubError(422, problems.join(' '));\n if (!gh.canWrite) throw new GitHubError(401, 'Starting an exploration needs a GitHub token (contents and pull requests, read and write, on this repository only).');\n const slug = e.slug || explorationSlug(e.name);\n const branch = `${EXPLORATION_PREFIX}${slug}`;\n const x = gh.withBranchPrefix(EXPLORATION_PREFIX);\n if (await x.getBranchSha(branch)) throw new GitHubError(422, `An exploration named \"${slug}\" already exists (${branch}). Pick another name, or continue that one.`);\n const full: Exploration = { ...e, slug, startedAt: e.startedAt ?? new Date().toISOString() };\n const commit = await x.commitToNewBranch({\n base: s.base,\n branch,\n message: `chore(explore): start ${full.name.trim()}\\n\\n${full.purpose.trim()}\\n\\nExploration: never merged as is. Promote it to review or close it.`,\n files: [{ path: explorationNotePath(slug), content: explorationNote(full) }],\n });\n const ctx = { owner: gh.owner, repo: gh.name, packages: s.packages, apps: s.apps, ...(s.requests?.length ? { requests: s.requests } : {}) };\n const title = full.jira ? `${full.jira.trim().toUpperCase()} ${explorationPrTitle(full)}` : explorationPrTitle(full);\n const pr = await x.createPullRequest({ title, head: branch, base: s.base, body: explorationPrBody(full, ctx), draft: true });\n await x.addLabels(pr.number, [EXPLORATION_LABEL, ...(s.labels ?? [])]);\n // The number exists now: the body gets the install command.\n await x.updatePullRequest(pr.number, { body: explorationPrBody(full, { ...ctx, pr: pr.number }) }).catch(() => undefined);\n return {\n branch,\n slug,\n pr: pr.number,\n url: pr.url,\n commit: commit.sha,\n tryIt: { state: 'building' },\n previews: previewLinks(s.apps, { branch, pr: pr.number, sha: commit.sha }),\n };\n}\n\n/**\n * Where the test build of an exploration stands: the install command from its sticky preview comment when it matches\n * the branch head, \"building\" while the workflow has not caught up, \"failed\" when the publish failed. Two reads.\n */\nexport async function explorationTryItOnGitHub(gh: GitHubClient, e: { number: number; branch: string }): Promise<ExplorationTryIt> {\n const [comments, head] = await Promise.all([gh.listIssueComments(e.number), gh.getBranchSha(e.branch).catch(() => undefined)]);\n return explorationTryIt({ comment: findPreviewComment(comments)?.body, headSha: head });\n}\n\nexport interface ExplorationTestBuild {\n /** The install command from the sticky preview comment, or building/failed. Never a guessed command. */\n tryIt: ExplorationTryIt;\n /** Every configured app with the URL Vercel reports (null while unknown) and its build state. */\n previews: BranchPreview[];\n /** True when the command is ready (or the publish failed) and every preview is built: polling can stop. */\n settled: boolean;\n}\n\n/**\n * Everything \"Try it\" shows for an exploration, read in one go: the command from the preview comment and the real\n * preview URLs (deployments, Vercel statuses, the Vercel comment). Comments and the branch head are read once.\n */\nexport async function explorationTestBuildOnGitHub(gh: GitHubClient, e: { number: number; branch: string }, config: Pick<BridgeConfig, 'previews'> | undefined): Promise<ExplorationTestBuild> {\n const [comments, head] = await Promise.all([gh.listIssueComments(e.number), gh.getBranchSha(e.branch).catch(() => undefined)]);\n const tryIt = explorationTryIt({ comment: findPreviewComment(comments)?.body, headSha: head });\n const previews = await branchPreviewUrls(gh, e.number, config, { branch: e.branch, sha: head, comments }).catch(() => [] as BranchPreview[]);\n return { tryIt, previews, settled: tryIt.state !== 'building' && previewsSettled(previews) };\n}\n\n/** The open exploration pull request of a branch, slug or number. */\nexport async function findExplorationOnGitHub(gh: GitHubClient, ref: string | number): Promise<PullRequestSummary & { body: string }> {\n if (typeof ref === 'number' || /^#?\\d+$/.test(String(ref))) {\n const p = await gh.getPullRequest(Number(String(ref).replace(/^#/, '')));\n if (!isExplorationPull({ state: p.state, labels: p.labels, headRef: p.headRef, body: p.body })) throw new GitHubError(422, `Pull request #${p.number} is not an exploration.`);\n return p;\n }\n const branch = `${EXPLORATION_PREFIX}${explorationSlug(String(ref))}`;\n const open = await gh.findOpenPullRequest(branch);\n if (!open) throw new GitHubError(404, `No open exploration on ${branch}. \\`bridge explore list\\` shows the running ones.`);\n return gh.getPullRequest(open.number);\n}\n\nexport interface PromotedExploration extends PromotionPlan {\n number: number;\n url: string;\n branch: string;\n /** Steps that did not go through, with what to do on GitHub instead. */\n warnings: string[];\n}\n\n/**\n * Promotes an exploration to a normal pull request for review: the exploration note removed from the branch, the\n * tier labels from the shared classifier, the `exploration` label removed, the body for review (closing the\n * requests implemented on it), and the draft marked ready for review (GraphQL). Never merges.\n */\nexport async function promoteExplorationOnGitHub(\n gh: GitHubClient,\n ref: string | number,\n opts: { config?: BridgeConfig | undefined; requests?: number[] | undefined; date?: Date | undefined; dryRun?: boolean | undefined } = {},\n): Promise<PromotedExploration> {\n const p = await findExplorationOnGitHub(gh, ref);\n const status = explorationStatus({ state: p.state, labels: p.labels, headRef: p.headRef, body: p.body });\n if (status !== 'active') throw new GitHubError(422, status === 'closed' ? `Exploration #${p.number} is closed. Reopen it on GitHub first.` : `#${p.number} is already promoted to review.`);\n const files = await gh.listPullRequestFiles(p.number);\n const plan = promotionPlan({ title: p.title, body: p.body, labels: p.labels, files: files.map((f) => ({ path: f.filename, status: f.status })), config: opts.config, requests: opts.requests, date: opts.date });\n const out: PromotedExploration = { ...plan, number: p.number, url: p.url, branch: p.headRef, warnings: [] };\n if (opts.dryRun) return out;\n if (!gh.canWrite) throw new GitHubError(401, 'Promoting an exploration needs a GitHub token (contents and pull requests, read and write).');\n const x = gh.withBranchPrefix(EXPLORATION_PREFIX);\n if (plan.removeFiles.length) {\n await x.commitToBranch({ branch: p.headRef, message: 'chore(explore): promote to review, remove the exploration note', files: plan.removeFiles.map((path) => ({ path, content: null })) }).catch((e: Error) => {\n // A refused token is not a partial success: nothing else would go through either.\n if (e instanceof GitHubError && e.auth === 'rejected') throw e;\n out.warnings.push(`The exploration note stays on the branch (${e.message}). Delete ${plan.removeFiles.join(', ')} before merging.`);\n });\n }\n await x.addLabels(p.number, plan.addLabels);\n await x.removeLabel(p.number, EXPLORATION_LABEL).catch((e: Error) => {\n if (!(e instanceof GitHubError && e.status === 404)) out.warnings.push(`The exploration label is still on (${e.message}). Remove it on GitHub.`);\n });\n await x.updatePullRequest(p.number, { title: plan.title, body: plan.body });\n await x.markReadyForReview(p.number).catch((e: Error) => {\n out.warnings.push(`Still a draft: ${e.message}`);\n });\n return out;\n}\n\n/** Closes an exploration without merging. The branch stays for reference; the workflow removes the prerelease. */\nexport async function closeExplorationOnGitHub(gh: GitHubClient, ref: string | number): Promise<{ number: number; url: string; branch: string }> {\n if (!gh.canWrite) throw new GitHubError(401, 'Closing an exploration needs a GitHub token (pull requests: write).');\n const p = await findExplorationOnGitHub(gh, ref);\n await gh.updatePullRequest(p.number, { state: 'closed' });\n return { number: p.number, url: p.url, branch: p.headRef };\n}\n","// Fidelity check: does a component built in Figma look like the code? Compares a Figma export of one variant with\n// an image of the same variant rendered from code (the Storybook reference images, see fidelity-references.ts).\n// Pure and dependency free: images are plain RGBA buffers, decoded by the caller (a canvas in the plugin, pngjs in\n// Node). The result shapes are JSON so a report can be stored and shown later (Studio Quality, follow-up).\n\n/** An RGBA image, 4 bytes per pixel, row by row (ImageData, pngjs and canvas all use this layout). */\nexport interface RgbaImage {\n width: number;\n height: number;\n data: Uint8Array | Uint8ClampedArray;\n}\n\nexport interface Size {\n width: number;\n height: number;\n}\n\nexport interface CompareOptions {\n /** Export scale of both images (device pixels per CSS pixel). Sizes are reported in CSS pixels. Default 2. */\n scale?: number;\n /**\n * Color distance under which two pixels are the same, 0 to 1 (YIQ, as pixelmatch). Default 0.1: absorbs gamma\n * and antialiasing ramps, catches a token swap (a gray one step away is about 0.12).\n */\n threshold?: number;\n /**\n * Neighborhood, in device pixels, searched for a matching pixel before one counts as different. Figma and Chrome\n * rasterize text and curves differently (glyph hinting, subpixel positions, corner antialiasing): a pixel that has\n * its twin within this distance is the same shape drawn half a pixel away. Default: one CSS pixel (= scale).\n */\n radius?: number;\n /** Largest share of different pixels, in percent, that still matches. Default 3. */\n maxPercent?: number;\n /** Largest size difference per side, in CSS pixels, that still matches. Default 1. */\n sizeTolerance?: number;\n /** Also return the diff overlay. Default true. */\n diffImage?: boolean;\n}\n\nexport interface ImageCompareResult {\n matches: boolean;\n /** Different pixels in percent of the larger canvas, two decimals. */\n percent: number;\n differentPixels: number;\n totalPixels: number;\n /** CSS pixel sizes (image size divided by the scale, rounded). */\n size: { figma: Size; code: Size };\n sizeMatches: boolean;\n /** The code image faded to gray with different pixels in red, on the larger canvas. */\n diff?: RgbaImage | undefined;\n}\n\nexport const FIDELITY_DEFAULTS = { scale: 2, threshold: 0.1, maxPercent: 3, sizeTolerance: 1 } as const;\n\n// Largest YIQ squared distance (black vs white), as in pixelmatch.\nconst MAX_DELTA = 35215;\n// Outside the overlap of two sizes: only near-white (transparent) pixels are the same.\nconst STRICT_THRESHOLD = 0.02;\n\n/** Pixel `i` of an image composited over white, or white outside the image. */\nfunction rgbAt(img: RgbaImage, x: number, y: number): [number, number, number] {\n if (x < 0 || y < 0 || x >= img.width || y >= img.height) return [255, 255, 255];\n const i = (y * img.width + x) * 4;\n const a = img.data[i + 3]! / 255;\n return [255 + (img.data[i]! - 255) * a, 255 + (img.data[i + 1]! - 255) * a, 255 + (img.data[i + 2]! - 255) * a];\n}\n\n/** YIQ squared distance between two opaque colors (pixelmatch's perceptual metric). */\nexport function colorDelta(a: [number, number, number], b: [number, number, number]): number {\n const dr = a[0] - b[0];\n const dg = a[1] - b[1];\n const db = a[2] - b[2];\n const y = dr * 0.29889531 + dg * 0.58662247 + db * 0.11448223;\n const i = dr * 0.59597799 - dg * 0.2741761 - db * 0.32180189;\n const q = dr * 0.21147017 - dg * 0.52261711 + db * 0.31114694;\n return 0.5053 * y * y + 0.299 * i * i + 0.1957 * q * q;\n}\n\n/** Whether color `c` appears in `img` within `radius` pixels of (x, y). */\nfunction foundNear(img: RgbaImage, x: number, y: number, c: [number, number, number], radius: number, max: number): boolean {\n for (let dy = -radius; dy <= radius; dy++) for (let dx = -radius; dx <= radius; dx++) if (colorDelta(c, rgbAt(img, x + dx, y + dy)) <= max) return true;\n return false;\n}\n\n/**\n * Compares a Figma export with the code reference of the same variant. A pixel differs when its color is not found\n * near the same place in the other image, in either direction: a shape drawn half a pixel away, or text rasterized\n * a little differently, matches; a missing border, another color, other padding or a different size does not.\n * Pixels outside the smaller image count as transparent: there, any visible color differs (a missing footer is a\n * difference even when its gray is light).\n */\nexport function compareImages(figma: RgbaImage, code: RgbaImage, options: CompareOptions = {}): ImageCompareResult {\n const scale = options.scale ?? FIDELITY_DEFAULTS.scale;\n const radius = Math.max(0, Math.round(options.radius ?? scale));\n const max = MAX_DELTA * (options.threshold ?? FIDELITY_DEFAULTS.threshold) ** 2;\n const strict = MAX_DELTA * STRICT_THRESHOLD ** 2;\n const width = Math.max(figma.width, code.width);\n const height = Math.max(figma.height, code.height);\n const total = width * height;\n const wantDiff = options.diffImage !== false;\n const out = wantDiff ? new Uint8ClampedArray(total * 4) : undefined;\n let different = 0;\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const a = rgbAt(figma, x, y);\n const b = rgbAt(code, x, y);\n // Where only one image has pixels (a size difference), any visible color counts: a light surface on white is\n // a missing part, not antialiasing.\n const m = x < Math.min(figma.width, code.width) && y < Math.min(figma.height, code.height) ? max : strict;\n const same = colorDelta(a, b) <= m || (foundNear(code, x, y, a, radius, m) && foundNear(figma, x, y, b, radius, m));\n if (!same) different++;\n if (out) {\n const o = (y * width + x) * 4;\n if (same) {\n // The code image, faded: light gray context for the red marks.\n const gray = 255 + ((b[0] * 0.299 + b[1] * 0.587 + b[2] * 0.114) - 255) * 0.1;\n out[o] = out[o + 1] = out[o + 2] = gray;\n } else {\n out[o] = 220;\n out[o + 1] = 38;\n out[o + 2] = 38;\n }\n out[o + 3] = 255;\n }\n }\n }\n const css = (img: RgbaImage): Size => ({ width: Math.round(img.width / scale), height: Math.round(img.height / scale) });\n const size = { figma: css(figma), code: css(code) };\n const tol = options.sizeTolerance ?? FIDELITY_DEFAULTS.sizeTolerance;\n const sizeMatches = Math.abs(size.figma.width - size.code.width) <= tol && Math.abs(size.figma.height - size.code.height) <= tol;\n const percent = total ? Math.round((different / total) * 10000) / 100 : 0;\n return {\n matches: sizeMatches && percent <= (options.maxPercent ?? FIDELITY_DEFAULTS.maxPercent),\n percent,\n differentPixels: different,\n totalPixels: total,\n size,\n sizeMatches,\n ...(out ? { diff: { width, height, data: out } } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------------------------\n// Report: what a check found, per component and variant. JSON, storable as is.\n\nexport type FidelityVariantStatus = 'matches' | 'differs' | 'skipped';\n\nexport interface FidelityVariantResult {\n /** Variant key, as the plugin stores it (\"Size=md, State=Default, Variant=primary\"). */\n key: string;\n status: FidelityVariantStatus;\n percent?: number | undefined;\n size?: { figma: Size; code: Size } | undefined;\n /** Skipped variants: why there is nothing to compare, in designer words. */\n reason?: string | undefined;\n}\n\nexport type FidelityComponentStatus = 'matches' | 'differs' | 'not-checked';\n\nexport interface FidelityComponentResult {\n component: string;\n status: FidelityComponentStatus;\n checked: number;\n differing: number;\n skipped: number;\n /** The variant that differs most (or matches least well). */\n worst?: { key: string; percent: number; size: { figma: Size; code: Size } } | undefined;\n /** Not checked at all: why. */\n reason?: string | undefined;\n variants: FidelityVariantResult[];\n}\n\nexport interface FidelityReport {\n version: 1;\n checkedAt: string;\n /** Figma file the sets were exported from. */\n file?: string | undefined;\n /** Commit the code images were made from. */\n reference: { sha: string; createdAt: string };\n options: { scale: number; threshold: number; radius: number; maxPercent: number; sizeTolerance: number };\n components: FidelityComponentResult[];\n summary: { components: number; matches: number; differs: number; notChecked: number; variantsChecked: number; variantsSkipped: number };\n}\n\n/** Rolls variant results up into one component result. */\nexport function summarizeComponent(component: string, variants: FidelityVariantResult[], reason?: string): FidelityComponentResult {\n const compared = variants.filter((v) => v.status !== 'skipped');\n const differing = compared.filter((v) => v.status === 'differs');\n const rank = (v: FidelityVariantResult) => (v.status === 'differs' ? 1000 : 0) + (v.percent ?? 0) + (v.size && !sameSize(v.size) ? 500 : 0);\n const worst = [...compared].sort((a, b) => rank(b) - rank(a))[0];\n return {\n component,\n status: compared.length === 0 ? 'not-checked' : differing.length ? 'differs' : 'matches',\n checked: compared.length,\n differing: differing.length,\n skipped: variants.length - compared.length,\n ...(worst && worst.size ? { worst: { key: worst.key, percent: worst.percent ?? 0, size: worst.size } } : {}),\n ...(compared.length === 0 ? { reason: reason ?? variants.find((v) => v.reason)?.reason } : {}),\n variants,\n };\n}\n\nconst sameSize = (s: { figma: Size; code: Size }) => s.figma.width === s.code.width && s.figma.height === s.code.height;\n\nexport function buildFidelityReport(input: {\n components: FidelityComponentResult[];\n reference: { sha: string; createdAt: string };\n options?: CompareOptions;\n file?: string;\n now?: Date;\n}): FidelityReport {\n const o = input.options ?? {};\n const scale = o.scale ?? FIDELITY_DEFAULTS.scale;\n const c = input.components;\n return {\n version: 1,\n checkedAt: (input.now ?? new Date()).toISOString(),\n ...(input.file ? { file: input.file } : {}),\n reference: input.reference,\n options: {\n scale,\n threshold: o.threshold ?? FIDELITY_DEFAULTS.threshold,\n radius: Math.round(o.radius ?? scale),\n maxPercent: o.maxPercent ?? FIDELITY_DEFAULTS.maxPercent,\n sizeTolerance: o.sizeTolerance ?? FIDELITY_DEFAULTS.sizeTolerance,\n },\n components: c,\n summary: {\n components: c.length,\n matches: c.filter((x) => x.status === 'matches').length,\n differs: c.filter((x) => x.status === 'differs').length,\n notChecked: c.filter((x) => x.status === 'not-checked').length,\n variantsChecked: c.reduce((n, x) => n + x.checked, 0),\n variantsSkipped: c.reduce((n, x) => n + x.skipped, 0),\n },\n };\n}\n\nconst fmtPercent = (p: number) => (p >= 10 ? `${Math.round(p)}%` : p >= 1 ? `${Math.round(p * 10) / 10}%` : p > 0 ? 'under 1%' : '0%');\nconst fmtSize = (s: Size) => `${s.width}x${s.height}`;\n\n/** One variant's verdict: \"Matches the code\" or \"Differs from the code: 12% of pixels, size 120x40 vs 118x40\". */\nexport function fidelityVerdict(v: Pick<FidelityVariantResult, 'status' | 'percent' | 'size' | 'reason'>): string {\n if (v.status === 'skipped') return `Not compared: ${v.reason ?? 'no image of the code'}`;\n if (v.status === 'matches') return 'Matches the code';\n const parts = [`${fmtPercent(v.percent ?? 0)} of pixels`];\n if (v.size && !sameSize(v.size)) parts.push(`size ${fmtSize(v.size.figma)} vs ${fmtSize(v.size.code)}`);\n return `Differs from the code: ${parts.join(', ')}`;\n}\n\n/** One component's line, from its worst variant. */\nexport function fidelityComponentLine(c: FidelityComponentResult): string {\n if (c.status === 'not-checked') return `Not compared: ${c.reason ?? 'no image of the code'}`;\n if (c.status === 'matches') return c.checked === 1 ? 'Matches the code' : `Matches the code (${c.checked} variants)`;\n const w = c.worst!;\n const head = fidelityVerdict({ status: 'differs', percent: w.percent, size: w.size });\n return c.checked > 1 ? `${head} (${c.differing} of ${c.checked} variants)` : head;\n}\n","// Code images for the fidelity check: which code render matches each generated Figma variant, and where the images\n// live. The generator (component-specs.ts) draws one Figma variant per axis combination; this module turns that same\n// spec back into props, content and a pseudo state, so the hidden Storybook story \"Internal/Figma reference\" renders\n// what the Figma variant should look like (same texts, icons and width). A variant that cannot be rendered the same\n// way is skipped with a reason, never guessed.\n//\n// Images are made on main by .github/workflows/figma-references.yml (bridge figma-references) and published to the\n// `bridge-visual` branch, the one Visual impact already publishes to, under figma-references/: manifest.json plus one\n// PNG per variant. The plugin reads them through the GitHub contents API with the token it already has.\n\nimport { variantKeyOf, type ComponentSpec, type ComponentSpecsFile, type SpecExample, type SpecPart, type SpecVariant } from './component-spec';\n\nexport const FIGMA_REFERENCES_BRANCH = 'bridge-visual';\nexport const FIGMA_REFERENCES_DIR = 'figma-references';\nexport const FIGMA_REFERENCES_MANIFEST = `${FIGMA_REFERENCES_DIR}/manifest.json`;\n/** Story id of packages/react/src/stories/FigmaReference.stories.tsx. */\nexport const FIGMA_REFERENCE_STORY = 'internal-figma-reference--variant';\n/** Width token of a block-level root in Figma (the plugin draws fill roots at this width: FILL_WIDTH_TOKEN). */\nexport const FIGMA_FILL_WIDTH_TOKEN = 'size.80';\n\nexport type ReferencePseudo = 'hover' | 'active' | 'focus-visible';\n\n/** What the reference story renders for one variant. JSON, passed to the story as a string arg. */\nexport interface ReferenceRender {\n /** Export name of the component (\"Button\", \"Card\"). */\n component: string;\n /** Props from the variant axes and the default property values (\"variant\": \"primary\", \"disabled\": true). */\n props: Record<string, unknown>;\n /** Text children (the Label property) of a simple component. */\n text?: string | undefined;\n /** Compound parts, in order: export name and text (\"CardHeader\", \"Header\"). */\n parts?: { component: string; text: string }[] | undefined;\n /** Icon props -> Lucide icon name (\"icon\": \"Pencil\"). */\n icons?: Record<string, string> | undefined;\n /** Hover, pressed or focus, forced with the pseudo-states addon classes. */\n pseudo?: ReferencePseudo | undefined;\n /** Width token path of the frame the component sits in, for roots that fill their container. */\n width?: string | undefined;\n /**\n * Children from the code example the set was drawn with (a table's rows, a form's fields): texts and design system\n * elements with their props, icons by name. Replaces `text` and `parts`.\n */\n children?: (string | SpecExample)[] | undefined;\n}\n\nexport type ReferencePlan = { ok: true; render: ReferenceRender } | { ok: false; reason: string };\n\nconst STATE_PSEUDO: Record<string, ReferencePseudo | 'rest' | 'disabled'> = {\n default: 'rest',\n rest: 'rest',\n enabled: 'rest',\n hover: 'hover',\n hovered: 'hover',\n pressed: 'active',\n active: 'active',\n focus: 'focus-visible',\n focused: 'focus-visible',\n 'focus visible': 'focus-visible',\n disabled: 'disabled',\n};\n\nconst iconName = (component: string) => component.replace(/^Icon\\//, '');\nconst exportName = (name: string) => name.replace(/[^A-Za-z0-9]+/g, '');\n\n/** How to render one generated variant from code, or why it cannot be compared. */\nexport function planReference(spec: ComponentSpec, variant: SpecVariant, file?: Pick<ComponentSpecsFile, 'slots'>): ReferencePlan {\n // A popup drawn open: the code image shows the component closed, so there is nothing to compare it with.\n if (spec.view === 'popup') return { ok: false, reason: 'drawn open in Figma; the code image shows it closed' };\n const props: Record<string, unknown> = { ...(spec.fixed ?? {}) };\n let pseudo: ReferencePseudo | undefined;\n for (const axis of spec.axes) {\n const value = variant.props[axis.name];\n if (value === undefined) return { ok: false, reason: `the variant has no ${axis.name} value` };\n if (axis.prop) {\n props[axis.prop] = value === 'true' ? true : value === 'false' ? false : value;\n continue;\n }\n // The Checked axis the generator draws from Base UI's checked state: the checked and indeterminate props.\n if (axis.name === 'Checked') {\n props.checked = value === 'true';\n if (value === 'mixed') props.indeterminate = true;\n continue;\n }\n if (axis.name.toLowerCase() !== 'state') return { ok: false, reason: `${axis.name} has no matching option in code` };\n const s = STATE_PSEUDO[value.toLowerCase()];\n if (!s) return { ok: false, reason: `the ${value} state has no code equivalent to render` };\n if (s === 'disabled') props.disabled = true;\n else if (s !== 'rest') pseudo = s;\n }\n\n const root = spec.parts.find((p) => !p.parent);\n if (!root) return { ok: false, reason: 'the spec has no root layer' };\n const children = (id: string) => spec.parts.filter((p) => p.parent === id);\n const textOf = (part: SpecPart): string | { reason: string } => {\n const swapTo = variant.slots?.[part.id] ?? part.swap?.default;\n if (part.swap && swapTo) {\n const slot = file?.slots?.find((s) => s.name === swapTo);\n if (!slot) return { reason: `${swapTo} is not in the specs` };\n if (slot.kind !== 'text' || !slot.text) return { reason: `Figma shows a placeholder (${swapTo}) that code has no example of` };\n return slot.text.default;\n }\n const prop = spec.properties.find((p) => p.name === part.text && p.type === 'TEXT');\n return typeof prop?.default === 'string' ? prop.default : part.name;\n };\n\n let text: string | undefined;\n const icons: Record<string, string> = {};\n for (const prop of spec.properties) {\n if (prop.type === 'TEXT') {\n // Optional content hidden by default (an input's prefix, a description): not passed, as Figma does not show it.\n const hidden = spec.properties.some((b) => b.type === 'BOOLEAN' && b.prop === prop.prop && b.default === false);\n if (hidden && prop.prop) continue;\n if (prop.prop === 'children') text = String(prop.default);\n else if (prop.prop) props[prop.prop] = String(prop.default);\n continue;\n }\n // BOOLEAN: an optional icon shown by default gets its icon below; any other default-on flag is a prop, unless the\n // content it shows is already passed (a description's text, an example's token name).\n const iconPart = spec.parts.find((p) => p.kind === 'icon' && p.visible === prop.name);\n if (prop.default === true && !iconPart && prop.prop && props[prop.prop] === undefined && spec.example?.p?.[prop.prop] === undefined) props[prop.prop] = true;\n }\n\n for (const part of spec.parts) {\n if (part.kind !== 'icon' || !part.swap) continue;\n const shown = part.visible ? spec.properties.find((p) => p.name === part.visible)?.default === true : true;\n if (!shown) continue;\n if (!part.swap.prop) return { ok: false, reason: `the ${part.name} icon has no matching option in code` };\n icons[part.swap.prop] = iconName(variant.slots?.[part.id] ?? part.swap.default);\n }\n\n // Texts that no prop carries: an input's placeholder, or a compound component's parts (CardHeader...).\n let parts: { component: string; text: string }[] | undefined;\n const loose = spec.properties.filter((p) => p.type === 'TEXT' && !p.prop);\n const frames = children(root.id).filter((p) => p.kind === 'frame');\n // Compound parts are frames named like their text (CardHeader's \"Header\") or holding a slot, not a field's box.\n const compound = text === undefined && frames.length > 0 && frames.every((f) => spec.parts.some((p) => p.parent === f.id && p.kind === 'text' && (p.swap || p.text === f.name)));\n if (compound) {\n parts = [];\n for (const f of frames) {\n const t = spec.parts.find((p) => p.parent === f.id && p.kind === 'text')!;\n const value = textOf(t);\n if (typeof value !== 'string') return { ok: false, reason: value.reason };\n parts.push({ component: `${exportName(spec.name)}${exportName(f.name)}`, text: value });\n }\n }\n for (const p of loose) {\n // A value display Base UI writes from the component's value (a progress percentage): code writes it too.\n if (p.name === 'Value') continue;\n const part = spec.parts.find((x) => x.text === p.name);\n if (compound && part && part.parent !== root.id) continue;\n if (part && /placeholder$/.test(part.id)) {\n props.placeholder = String(p.default);\n continue;\n }\n return { ok: false, reason: `the ${p.name} text has no matching option in code` };\n }\n\n // The code example the content came from: its props (the variant's own win) and children.\n const example = spec.example;\n const exampleChildren = example?.children?.length ? example.children : undefined;\n return {\n ok: true,\n render: {\n component: exportName(spec.view || spec.fixed || example ? (example?.c ?? spec.component ?? spec.name) : spec.name),\n props: { ...(example?.p ?? {}), ...props },\n ...(exampleChildren ? { children: exampleChildren } : {}),\n ...(text !== undefined && !exampleChildren ? { text } : {}),\n ...(parts && !exampleChildren ? { parts } : {}),\n ...(Object.keys(icons).length ? { icons } : {}),\n ...(pseudo ? { pseudo } : {}),\n ...(root.fill ? { width: FIGMA_FILL_WIDTH_TOKEN } : {}),\n },\n };\n}\n\n/** File name of a variant's image, stable and file safe: \"button/size-md__state-default__variant-primary.png\". */\nexport function referenceImagePath(component: string, key: string): string {\n const slug = (s: string) => s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');\n const file = key\n .split(',')\n .map((kv) => slug(kv))\n .filter(Boolean)\n .join('__');\n return `${slug(component)}/${file || 'default'}.png`;\n}\n\nexport type FigmaReferenceEntry = { file: string; width: number; height: number } | { skipped: string };\n\nexport interface FigmaReferenceManifest {\n version: 1;\n tool: '@bridge-ds/visual';\n createdAt: string;\n /** Commit of the code the images were made from. */\n sha: string;\n /** Device pixels per CSS pixel, the scale the plugin exports Figma variants at. */\n scale: number;\n mode: { brand: string; theme: string; density: string };\n storyId: string;\n components: Record<string, { specHash: string; variants: Record<string, FigmaReferenceEntry> }>;\n}\n\n/** Every variant of every spec with its render plan (the capture's to-do list). */\nexport function planReferences(file: ComponentSpecsFile): { component: string; specHash: string; key: string; plan: ReferencePlan }[] {\n return file.components.flatMap((spec) =>\n spec.variants.map((v) => ({ component: spec.name, specHash: spec.hash, key: variantKeyOf(v.props), plan: planReference(spec, v, file) })),\n );\n}\n","// Update a branch from main (\"bring in the latest library\"), shared by Bridge Studio, the MCP server and the CLI.\n// Reads how far a branch is behind and what both sides touched since they parted; when nothing conflicts, GitHub's\n// update-branch; when only token files conflict, a merge commit with the person's token choices (\"keep mine\" or\n// \"use main's\", core token-merge); anything in code stays with a developer. One implementation over the core\n// GitHub client: Studio passes its own client (studioClient), the MCP server and the CLI theirs.\nimport { loadConfig, DEFAULT_TOKEN_PATHS, type BridgeConfig } from './config';\nimport type { GitHubClient, TreeEntry } from './github-client';\nimport { buildTokenSet, layoutOptions, type LayoutOptions, type TokenSet } from './token-set';\nimport { parseContrastChecks, type ContrastPair } from './wcag';\nimport { applyTokenMerge, choiceFor, planTokenMerge, type MergeChoices, type TokenMergeConflict, type TokenMergeInput, type TokenMergePlan } from './token-merge';\n\nconst plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;\n\n/** A file of a compare (GET /repos/{o}/{r}/compare/{base}...{head}). */\nexport interface CompareFile {\n filename: string;\n status: string;\n previous_filename?: string | undefined;\n sha?: string | null | undefined;\n}\n\n/** Every path a compare file names: a renamed file counts under its old name too. */\nconst names = (files: CompareFile[]) => files.flatMap((f) => (f.previous_filename ? [f.filename, f.previous_filename] : [f.filename]));\n\n/** Files both the branch and main changed since they parted, split into token files and the rest (code). */\nexport function overlap(changeFiles: CompareFile[], libraryFiles: CompareFile[], isTokenFile: (path: string) => boolean): { tokenFiles: string[]; codeFiles: string[] } {\n const lib = new Set(names(libraryFiles));\n const both = [...new Set(names(changeFiles).filter((f) => lib.has(f)))].sort();\n return { tokenFiles: both.filter(isTokenFile), codeFiles: both.filter((f) => !isTokenFile(f)) };\n}\n\n/** GitHub lists at most 300 files per compare: past that, Bridge cannot know what both sides touched. */\nexport const COMPARE_FILE_LIMIT = 300;\n\nexport type ConflictRoute = { kind: 'tokens'; files: string[] } | { kind: 'code'; alsoTokens: boolean; files: string[] };\n\n/**\n * Who resolves the conflict. Only token files on both sides: the designer, in Bridge. Any code file on both sides, a\n * file list GitHub cut short, or no shared file at all (GitHub saw a conflict Bridge cannot explain): a developer.\n */\nexport function conflictRoute(o: { tokenFiles: string[]; codeFiles: string[] }, opts: { truncated?: boolean } = {}): ConflictRoute {\n if (opts.truncated || (!o.tokenFiles.length && !o.codeFiles.length)) return { kind: 'code', alsoTokens: false, files: [] };\n if (o.codeFiles.length) return { kind: 'code', alsoTokens: o.tokenFiles.length > 0, files: o.codeFiles };\n return { kind: 'tokens', files: o.tokenFiles };\n}\n\n/** A rule from GET /repos/{o}/{r}/rules/branches/{branch}. */\nexport interface BranchRuleLike {\n type: string;\n parameters?: { dismiss_stale_reviews_on_push?: boolean } | null;\n}\n\n/**\n * Whether GitHub dismisses approvals when new commits arrive, from the rules that apply to the library branch. True\n * or false when a pull request rule says so; null when no rule says (classic branch protection is not readable\n * without admin rights).\n */\nexport function dismissStaleFrom(rules: BranchRuleLike[] | null | undefined): boolean | null {\n const pr = (rules ?? []).filter((r) => r.type === 'pull_request');\n if (!pr.length) return null;\n return pr.some((r) => r.parameters?.dismiss_stale_reviews_on_push === true);\n}\n\n/** The commit message of the resolution, so History and the branch say what the person chose. */\nexport function resolutionMessage(input: { library: string; conflicts: TokenMergeConflict[]; choices: MergeChoices; who?: string | null | undefined }): string {\n const lines = input.conflicts.map((c) => `- ${c.path} (${c.file}): ${choiceFor(c, input.choices) === 'theirs' ? `used the ${input.library} value` : 'kept this change'}`);\n const title = input.conflicts.length ? `Bring in the latest ${input.library} and resolve ${plural(input.conflicts.length, 'token conflict')}` : `Bring in the latest ${input.library}`;\n const by = input.who ? `\\n\\nResolved in Bridge by @${input.who.replace(/^@/, '')}.` : '\\n\\nResolved in Bridge.';\n return `${title}${lines.length ? `\\n\\n${lines.join('\\n')}` : ''}${by}`;\n}\n\nexport type LibraryState = 'current' | 'behind' | 'conflict' | 'unknown';\n\nexport interface Freshness {\n state: LibraryState;\n /** Library updates (commits on the library branch) since the change started; null when not read. */\n behindBy: number | null;\n /** The commit the change and the library share. */\n mergeBase: string | null;\n}\n\n/**\n * How the change stands against the latest library. A conflict (mergeable false) wins: GitHub cannot combine them.\n * Otherwise it is behind when the library has commits the change has not. A shipped or closed change has nothing to\n * bring in. A compare that could not be read says unknown, never \"up to date\".\n */\nexport function freshness<C extends { behind_by?: number | undefined; merge_base_commit?: { sha: string } | null | undefined }>(input: { compare: C | null | undefined; mergeable: boolean | null | undefined; open: boolean }): Freshness {\n const behindBy = typeof input.compare?.behind_by === 'number' ? input.compare.behind_by : null;\n const mergeBase = input.compare?.merge_base_commit?.sha ?? null;\n if (!input.open) return { state: 'current', behindBy, mergeBase };\n if (input.mergeable === false) return { state: 'conflict', behindBy, mergeBase };\n if (behindBy === null) return { state: 'unknown', behindBy, mergeBase };\n return { state: behindBy > 0 ? 'behind' : 'current', behindBy, mergeBase };\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// Reads and writes over the core GitHub client\n\n/** The compare of main and a branch head, in the shape the conflict reader needs (client.compareDetailed). */\nexport interface LibraryCompare {\n mergeBase: string | null;\n baseSha: string | null;\n baseTree: string | null;\n files: CompareFile[];\n}\n\nexport interface LibraryConflicts {\n route: ConflictRoute;\n /** Present for a pure token-file conflict. */\n tokens?: {\n root: string;\n plan: TokenMergePlan;\n input: TokenMergeInput;\n sets: { base: TokenSet; mine: TokenSet; theirs: TokenSet };\n /** Every token file of each side, relative to the tokens root. */\n mineFiles: Record<string, string>;\n theirsFiles: Record<string, string>;\n pairs: ContrastPair[];\n options: LayoutOptions;\n };\n /** What the commit needs: main's tip and its tree, the branch head tree and its own files. */\n write?: { mainSha: string; mainTree: string; headSha: string; headTree: Map<string, TreeEntry>; changeFiles: CompareFile[] };\n}\n\nconst withoutRoot = (root: string, p: string) => (root && p.startsWith(`${root}/`) ? p.slice(root.length + 1) : p);\n\nasync function treeAt(gh: GitHubClient, sha: string): Promise<Map<string, TreeEntry>> {\n const t = await gh.getTree(await gh.getCommitTree(sha));\n if (t.truncated) throw new Error('This repository is too big for Bridge to read in one go. A developer resolves the conflict on GitHub.');\n return new Map(t.entries.filter((e) => e.type === 'blob').map((e) => [e.path, e]));\n}\n\nasync function textAt(gh: GitHubClient, sha: string, path: string): Promise<string> {\n return (await gh.readFile(path, sha)) ?? '';\n}\n\nasync function tokenFilesAt(gh: GitHubClient, sha: string, root: string, tree: Map<string, TreeEntry>): Promise<Record<string, string>> {\n const prefix = root ? `${root}/` : '';\n const paths = [...tree.keys()].filter((p) => p.startsWith(prefix) && p.endsWith('.tokens.json'));\n return Object.fromEntries(await Promise.all(paths.map(async (p) => [withoutRoot(root, p), await textAt(gh, sha, p)] as const)));\n}\n\nasync function configAt(gh: GitHubClient, sha: string, tree: Map<string, TreeEntry>): Promise<BridgeConfig | null> {\n if (!tree.has('bridge.config.json')) return null;\n try {\n return loadConfig(await textAt(gh, sha, 'bridge.config.json'));\n } catch {\n return null;\n }\n}\n\n/**\n * What conflicts and who resolves it. Reads the files main changed since the branch started (one compare), then, for\n * a pure token-file conflict, the token files at the shared start, in the branch and in main. `tokensRoot` is the\n * best guess before the config is read (Studio: its site config); `contrastFallback` the contrast checks to use when\n * main has none.\n */\nexport async function readLibraryConflicts(\n gh: GitHubClient,\n compare: LibraryCompare,\n headSha: string,\n opts: { tokensRoot?: string | undefined; contrastFallback?: string | undefined } = {},\n): Promise<LibraryConflicts> {\n const { mergeBase, baseSha: mainSha, baseTree: mainTree } = compare;\n const changeFiles = compare.files;\n if (!mergeBase || !mainSha || !mainTree) return { route: conflictRoute({ tokenFiles: [], codeFiles: [] }) };\n const library = (await gh.compareDetailed(mergeBase, mainSha)).files;\n const truncated = changeFiles.length >= COMPARE_FILE_LIMIT || library.length >= COMPARE_FILE_LIMIT;\n // The tokens root guess first: the config of main confirms it before anything is written.\n const guess = opts.tokensRoot ?? DEFAULT_TOKEN_PATHS.root;\n const route = conflictRoute(\n overlap(changeFiles, library, (p) => p.endsWith('.tokens.json') && p.startsWith(`${guess}/`)),\n { truncated },\n );\n if (route.kind !== 'tokens') return { route };\n\n const [baseTree, headTree, theirsTree] = await Promise.all([treeAt(gh, mergeBase), treeAt(gh, headSha), treeAt(gh, mainSha)]);\n const config = (await configAt(gh, mainSha, theirsTree)) ?? (await configAt(gh, mergeBase, baseTree));\n const root = config?.tokens.root ?? guess;\n const options = config ? layoutOptions(config) : {};\n const checksPath = `${root}/${config?.tokens.contrastChecks ?? DEFAULT_TOKEN_PATHS.contrastChecks}`;\n const [baseFiles, mineFiles, theirsFiles, checks] = await Promise.all([\n tokenFilesAt(gh, mergeBase, root, baseTree),\n tokenFilesAt(gh, headSha, root, headTree),\n tokenFilesAt(gh, mainSha, root, theirsTree),\n theirsTree.has(checksPath) ? textAt(gh, mainSha, checksPath) : Promise.resolve(''),\n ]);\n const input: TokenMergeInput = { base: baseFiles, mine: mineFiles, theirs: theirsFiles, files: route.files.map((f) => withoutRoot(root, f)) };\n return {\n route,\n tokens: {\n root,\n plan: planTokenMerge(input),\n input,\n sets: { base: buildTokenSet(baseFiles, options), mine: buildTokenSet(mineFiles, options), theirs: buildTokenSet(theirsFiles, options) },\n mineFiles,\n theirsFiles,\n pairs: parseContrastChecks(checks || opts.contrastFallback),\n options,\n },\n write: { mainSha, mainTree, headSha, headTree, changeFiles },\n };\n}\n\n/**\n * Every token file once resolved, relative to the tokens root: main's files, the branch's own token files where only\n * the branch touched them, and the merged files where both did.\n */\nexport function resolvedTokenFiles(data: LibraryConflicts, choices: MergeChoices): { all: Record<string, string>; merged: Record<string, string | null> } {\n const t = data.tokens!;\n const merged = applyTokenMerge(t.input, choices).files;\n const all: Record<string, string> = { ...t.theirsFiles };\n for (const f of data.write!.changeFiles) {\n for (const p of [f.previous_filename, f.filename]) {\n if (!p || !p.endsWith('.tokens.json') || !p.startsWith(`${t.root}/`)) continue;\n const rel = withoutRoot(t.root, p);\n if (rel in merged) continue;\n if (t.mineFiles[rel] === undefined) delete all[rel];\n else all[rel] = t.mineFiles[rel]!;\n }\n }\n for (const [rel, text] of Object.entries(merged)) {\n if (text === null) delete all[rel];\n else all[rel] = text;\n }\n return { all, merged };\n}\n\n/**\n * Commits the resolution to the branch: a merge commit of main and the branch, whose tree is main plus the branch's\n * own files plus the merged token files. Fast-forward only: when the branch moved meanwhile, GitHub refuses and\n * nothing is lost.\n */\nexport async function commitLibraryResolution(\n gh: GitHubClient,\n pull: { head: { ref: string; sha: string }; base: { ref: string } },\n data: LibraryConflicts,\n choices: MergeChoices,\n who: string | null | undefined,\n): Promise<string> {\n const t = data.tokens;\n const w = data.write;\n if (!t || !w) throw new Error('Only a token conflict can be resolved in Bridge. A developer resolves code conflicts on GitHub.');\n if (w.headSha !== pull.head.sha) throw new Error('The branch moved while you were choosing. Read it again and resolve again.');\n const { merged } = resolvedTokenFiles(data, choices);\n const shared = new Set(data.route.files);\n type Entry = { path: string; mode: string; sha: string | null } | { path: string; mode: string; content: string };\n const tree: Entry[] = [];\n for (const f of w.changeFiles) {\n if (shared.has(f.filename)) continue;\n if (f.previous_filename && !shared.has(f.previous_filename)) tree.push({ path: f.previous_filename, mode: '100644', sha: null });\n if (f.status === 'removed') {\n tree.push({ path: f.filename, mode: '100644', sha: null });\n continue;\n }\n const e = w.headTree.get(f.filename);\n if (!e) throw new Error(`Bridge could not read ${f.filename} in the branch. Read it again and try again.`);\n tree.push({ path: e.path, mode: e.mode, sha: e.sha });\n }\n for (const [rel, text] of Object.entries(merged)) {\n const path = t.root ? `${t.root}/${rel}` : rel;\n const mode = w.headTree.get(path)?.mode ?? '100644';\n tree.push(text === null ? { path, mode, sha: null } : { path, mode, content: text });\n }\n const newTree = await gh.createTreeEntries(w.mainTree, tree);\n const message = resolutionMessage({ library: pull.base.ref, conflicts: t.plan.conflicts, choices, who });\n const commit = await gh.createCommit(message, newTree, [w.headSha, w.mainSha]);\n await gh.updateBranch(pull.head.ref, commit);\n return commit;\n}\n","// The writes behind the actions on a branch in review, shared by Bridge Studio (scripts/reviews.ts), the MCP server\n// and the CLI: merge, merge as owner override (reason posted first, marked \"not merged\" when GitHub refuses), review,\n// close and reopen. The rules that decide whether they are allowed live in review-gate.ts; these only write, through\n// the core GitHub client, so every surface sends GitHub the same requests.\nimport type { GitHubClient, Review } from './github-client';\nimport { OVERRIDE_HEADING, overrideComment, overrideRefusedComment, type MergeMethod, type MissingApproval } from './review-gate';\n\n/** Merges a branch at the head the person saw (GitHub refuses when it moved meanwhile). Studio's Merge button: squash. */\nexport async function mergeOnGitHub(gh: GitHubClient, input: { number: number; headSha: string; method?: MergeMethod | undefined }): Promise<{ sha: string }> {\n const r = await gh.mergePullRequest(input.number, { method: input.method ?? 'squash', sha: input.headSha });\n return { sha: r.sha };\n}\n\n/** Where an owner override stopped: GitHub refused the reason comment (nothing merged), or the merge itself. */\nexport class OverrideMergeError extends Error {\n constructor(\n readonly stage: 'comment' | 'merge',\n message: string,\n readonly cause?: unknown,\n readonly commentUrl?: string | undefined,\n ) {\n super(message);\n this.name = 'OverrideMergeError';\n }\n}\n\n/**\n * Merge as owner override: posts the reason on the branch first (the audit trail History reads back), then merges\n * with the first merge method the repository allows. When GitHub refuses the merge, the comment is edited to say\n * \"Merge refused by GitHub ... Not merged\", so the trail never claims a merge that did not happen. The caller checks\n * the gate first (mergeGate: overridable) and the reason (overrideReasonProblem).\n */\nexport async function overrideMergeOnGitHub(\n gh: GitHubClient,\n input: { number: number; headSha: string; login: string; reason: string; missing: MissingApproval[]; method: MergeMethod },\n): Promise<{ sha: string; commentUrl: string; comment: string }> {\n const body = overrideComment(input.login, input.reason, input.missing);\n let comment: { id: number; url: string };\n try {\n comment = await gh.createIssueComment(input.number, body);\n } catch (err) {\n throw new OverrideMergeError('comment', `GitHub did not take the comment, so nothing merged: ${(err as Error).message}`, err);\n }\n try {\n const r = await gh.mergePullRequest(input.number, { method: input.method, sha: input.headSha, commitMessage: body.replace(OVERRIDE_HEADING, '').trim() });\n return { sha: r.sha, commentUrl: comment.url, comment: body };\n } catch (err) {\n const msg = (err as Error).message.trim().replace(/[.\\s]+$/, '');\n await gh.updateIssueComment(comment.id, overrideRefusedComment(body, msg)).catch(() => undefined);\n throw new OverrideMergeError(\n 'merge',\n `GitHub refused to merge it: ${msg}. Your reason stays on the branch, marked not merged. The protection of main may need an approving review or an admin bypass.`,\n err,\n comment.url,\n );\n }\n}\n\nexport type ReviewEvent = 'APPROVE' | 'REQUEST_CHANGES' | 'COMMENT';\n\n/** Approve, request changes or comment, on the head the reviewer saw. Changes and comments need a text. */\nexport async function reviewOnGitHub(gh: GitHubClient, input: { number: number; event: ReviewEvent; body?: string | undefined; headSha?: string | undefined }): Promise<Review> {\n const text = input.body?.trim() ?? '';\n if (input.event === 'REQUEST_CHANGES' && !text) throw new Error('Add a comment that says what to change.');\n if (input.event === 'COMMENT' && !text) throw new Error('Write a comment first.');\n return gh.submitReview(input.number, { event: input.event, body: text || undefined, commitId: input.headSha });\n}\n\n/** A comment on the branch's conversation. */\nexport async function commentOnGitHub(gh: GitHubClient, n: number, body: string): Promise<{ id: number; url: string }> {\n const text = body.trim();\n if (!text) throw new Error('Write the comment first.');\n return gh.createIssueComment(n, text);\n}\n\n/**\n * \"Ask someone else to review\": requests the review from `others` (core reviewersToAsk) and takes the viewer off the\n * requested reviewers when GitHub had them on it. Throws how to fix it when nobody else can.\n */\nexport async function askOthersToReviewOnGitHub(gh: GitHubClient, input: { number: number; others: string[]; viewer?: string | null | undefined; viewerRequested?: boolean | undefined }): Promise<string[]> {\n if (!input.others.length) throw new Error('Nobody else can give the missing approval. Review it, or ask an owner in Settings to add a reviewer.');\n await gh.requestReviewers(input.number, input.others);\n if (input.viewer && input.viewerRequested) await gh.removeRequestedReviewers(input.number, [input.viewer]).catch(() => undefined);\n return input.others;\n}\n\n/** Closes a branch without merging it. Its work stays on GitHub and it can be reopened. */\nexport async function closeOnGitHub(gh: GitHubClient, n: number): Promise<void> {\n await gh.updatePullRequest(n, { state: 'closed' });\n}\n\n/** Reopens a closed branch (GitHub refuses when its branch was deleted). */\nexport async function reopenOnGitHub(gh: GitHubClient, n: number): Promise<void> {\n await gh.updatePullRequest(n, { state: 'open' });\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// Adding edits to a branch already in review\n\nconst sameLogin = (a: string | null | undefined, b: string | null | undefined) => Boolean(a && b && a.toLowerCase().replace(/^@/, '') === b.toLowerCase().replace(/^@/, ''));\n\n/** Only the author or someone with write access to the repository adds to a branch. */\nexport function canAddTo(p: { user: { login: string } | null }, viewer: string | null | undefined, write: boolean): boolean {\n if (!viewer) return false;\n return write || sameLogin(p.user?.login, viewer);\n}\n\n/** The comment posted on the branch, so reviewers see what was added and from where. */\nexport function addedComment(paths: string[], viewer: string | null | undefined, from = 'the Bridge token editor'): string {\n const lines = paths.slice(0, 20).map((p) => `- \\`${p}\\``);\n if (paths.length > 20) lines.push(`- and ${paths.length - 20} more`);\n return `${viewer ? `@${viewer} added` : 'Added'} token edits from ${from}:\\n\\n${lines.join('\\n')}`;\n}\n","// \"Share with a product team\" on a branch, shared by Bridge Studio, the MCP server and the CLI: a product team installs the change in its own app before it ships, the\n// designer's release candidate. Everything comes from what the Preview packages workflow\n// (.github/workflows/preview-packages.yml) really does:\n// - every update to an open or draft change builds the library packages (previews.packages in bridge.config.json)\n// and posts the install command in its sticky comment (`<!-- bridge-branch-preview -->`), about two minutes\n// after the update, whether or not the checks pass;\n// - with pkg.pr.new, one snapshot per update, kept after the change ships or closes;\n// - without it (this repository today), tarballs on a `preview-pr-<n>` GitHub prerelease: only the latest update\n// is kept, and the \"Remove the preview prerelease\" job deletes it when the change ships or closes.\n// Nothing is published to the npm registry per change: there is no dist-tag, the command installs by URL.\nimport { readPreviewComment } from './previews';\n\n/** The dialog's explanation, in designer words. */\nexport const SHARE_EXPLAIN = 'Product teams can install this branch in their app before it is merged, and remove it any time.';\n\nexport type ChangeLifecycle = 'open' | 'draft' | 'merged' | 'closed';\ntype Source = 'pkg.pr.new' | 'release' | 'other';\n\nexport type ShareState =\n /** The command for the latest update is posted. */\n | { kind: 'ready'; command: string; source: Source }\n /** No command for the latest update yet. */\n | { kind: 'building' }\n /** The workflow posted for the latest update but could not publish. */\n | { kind: 'failed' }\n /** The change touches none of the preview packages: there is nothing to install. */\n | { kind: 'no-packages' }\n /** Shipped or closed. `stillWorks` from where the preview lived; null when no preview was ever posted. */\n | { kind: 'shipped' | 'closed'; stillWorks: boolean | null; command: string | null };\n\n/** `@bridge-ds/react` -> `packages/react/`, the folder the workflow builds it from (PACKAGE_DIRS). */\nexport const packageDir = (name: string): string => `packages/${name.replace(/^@[^/]+\\//, '')}/`;\n\n/** True when a changed file is inside one of the preview packages. */\nexport function touchesPackages(files: readonly string[], packages: readonly string[]): boolean {\n const dirs = packages.map(packageDir);\n return files.some((f) => dirs.some((d) => f.startsWith(d)));\n}\n\n/**\n * Whether a change offers sharing at all: never from a fork (the workflow cannot publish from one) or when the\n * repository has no preview packages configured.\n */\nexport const canShare = (x: { fromFork: boolean; packages: readonly string[] }): boolean => !x.fromFork && x.packages.length > 0;\n\n/**\n * Where the preview of a change stands, from its lifecycle, its changed files and the sticky preview comment. A\n * comment about an older update than the head means the new one is still being prepared: its command is never shown.\n */\nexport function shareState(x: { lifecycle: ChangeLifecycle; files: readonly string[]; packages: readonly string[]; comment: string | null | undefined; headSha: string }): ShareState {\n // Checked first: a change outside the packages never has anything to install, before or after it ships.\n if (!touchesPackages(x.files, x.packages)) return { kind: 'no-packages' };\n const c = readPreviewComment(x.comment);\n if (x.lifecycle === 'merged' || x.lifecycle === 'closed') {\n const kind = x.lifecycle === 'merged' ? 'shipped' : 'closed';\n if (!c || !c.command || c.source === 'none') return { kind, stillWorks: null, command: null };\n // pkg.pr.new keeps every snapshot; the prerelease is deleted when the change ships or closes.\n return { kind, stillWorks: c.source === 'pkg.pr.new' ? true : c.source === 'release' ? false : null, command: c.command };\n }\n if (!c) return { kind: 'building' };\n if (c.sha7 && !x.headSha.startsWith(c.sha7)) return { kind: 'building' };\n if (!c.command || c.source === 'none') return { kind: 'failed' };\n return { kind: 'ready', command: c.command, source: c.source };\n}\n\n/**\n * Whether the change page shows the action: always while the change is open or a draft (the dialog says why there is\n * nothing to install yet), and after it ships or closes only when a preview was posted that a team may have installed.\n */\nexport const showShare = (lifecycle: ChangeLifecycle, s: ShareState): boolean =>\n lifecycle === 'open' || lifecycle === 'draft' || ((s.kind === 'shipped' || s.kind === 'closed') && !!s.command);\n\n/** The dialog's description: the explanation while the change can still be tried, where it stands once finished. */\nexport const shareDescription = (s: ShareState): string =>\n s.kind === 'shipped' || s.kind === 'closed' ? (stateSentence(s) ?? SHARE_EXPLAIN) : SHARE_EXPLAIN;\n\n/** How a product goes back to the released packages. */\nexport const stableCommand = (packages: readonly string[]): string => `npm i ${packages.map((p) => `${p}@latest`).join(' ')}`;\n\n/** The one sentence the dialog shows under its explanation, in designer words. Null when the message says it all. */\nexport function stateSentence(s: ShareState): string | null {\n switch (s.kind) {\n case 'ready':\n return null;\n case 'building':\n return 'The preview version is being prepared. It is usually ready a couple of minutes after each update to the branch.';\n case 'failed':\n return 'The preview version could not be prepared for the latest update. Update the branch to try again, or ask a developer to run it again on GitHub.';\n case 'no-packages':\n return 'This branch does not touch the library tokens or components, so there is no preview version to install.';\n case 'shipped':\n return s.stillWorks === true\n ? 'This branch was merged. Its preview version still installs, and products get it with the next library release.'\n : s.stillWorks === false\n ? 'This branch was merged, so its preview version was removed. Products get it with the next library release.'\n : 'This branch was merged. Products get it with the next library release.';\n case 'closed':\n return s.stillWorks === true\n ? 'This branch was closed without merging. Its preview version still installs, but it will not reach the library.'\n : s.stillWorks === false\n ? 'This branch was closed without merging, so its preview version was removed.'\n : 'This branch was closed without merging.';\n }\n}\n\nexport interface ShareMessageInput {\n title: string;\n state: ShareState;\n packages: readonly string[];\n /** \"Try it in the product\": the admin preview with this change, when GitHub reports one. */\n tryUrl?: string | null | undefined;\n /** The change on GitHub, for the developer. */\n url: string;\n}\n\nexport interface ShareMessage {\n subject: string;\n body: string;\n}\n\nconst quote = (t: string) => `\"${t.trim().replace(/\"/g, \"'\")}\"`;\n\n/**\n * The ready-to-paste message for a developer of a product team: the change, the preview install command, where to\n * see it first, how long the preview lasts and how to go back. Plain text, for a chat or an email. Null when there is\n * nothing to install and nothing to undo (still building, failed, no packages, or never posted).\n */\nexport function shareMessage(x: ShareMessageInput): ShareMessage | null {\n const back = stableCommand(x.packages);\n const s = x.state;\n if (s.kind === 'ready') {\n const lasts =\n s.source === 'pkg.pr.new'\n ? 'This preview stays available. Each update to the change makes a new one: ask me for the latest command.'\n : 'This preview is replaced on each update to the change and removed when it ships or closes: ask me for the latest command if the install fails.';\n return {\n subject: `Try the design system change ${quote(x.title)} before it ships`,\n body: [\n 'Hi,',\n '',\n `Could you try the design system change ${quote(x.title)} in our product before it ships?`,\n ...(x.tryUrl ? ['', `See it in the demo product first: ${x.tryUrl}`] : []),\n '',\n 'Install the preview version in a staging branch (not production):',\n s.command,\n '',\n lasts,\n '',\n 'To go back to the stable version:',\n back,\n '',\n `Details for developers: ${x.url}`,\n ].join('\\n'),\n };\n }\n if ((s.kind === 'shipped' || s.kind === 'closed') && s.command) {\n const what = s.kind === 'shipped' ? `The design system change ${quote(x.title)} has shipped. You get it with the next library release.` : `The design system change ${quote(x.title)} was closed without shipping.`;\n const preview = s.stillWorks === false ? 'Its preview version was removed, so reinstalling it fails.' : s.stillWorks === true ? 'Its preview version still installs, but it is not the released version.' : '';\n return {\n subject: `Design system change ${quote(x.title)} ${s.kind === 'shipped' ? 'has shipped' : 'was closed'}`,\n body: ['Hi,', '', [what, preview].filter(Boolean).join(' '), '', 'If you installed its preview, go back to the stable version:', back, '', `Details for developers: ${x.url}`].join('\\n'),\n };\n }\n return null;\n}\n\n/** \"Open in email\": a mailto link with the subject and body. Nothing is sent by Studio. */\nexport const mailtoHref = (m: ShareMessage): string => `mailto:?subject=${encodeURIComponent(m.subject)}&body=${encodeURIComponent(m.body.replace(/\\r?\\n/g, '\\r\\n'))}`;\n","// \"Try it in the product\" on a branch, shared by Bridge Studio, the MCP server and the CLI: the product preview Vercel\n// built for the branch, opened with the Bridge toolbar (`?bridge=<number>`, apps/admin/src/bridge) on a given screen.\n// The URL is only one GitHub reported (Vercel commit status, deployment or bot comment), never the config template:\n// Vercel shortens long branch aliases, so a template URL can point nowhere.\nimport { resolveBranchPreviews, type BranchPreviewSources, type PreviewApps } from './previews';\n\nexport interface ProductScreen {\n label: string;\n route: string;\n tenant: string;\n theme: string;\n}\n\n/** The admin preview of a change, or null when GitHub reports none (or the build failed, or it comes from a fork). */\nexport function productPreview(apps: PreviewApps, ctx: { branch: string; pr: number; sha: string; fromFork?: boolean }, sources: BranchPreviewSources): string | null {\n if (!apps.admin || ctx.fromFork) return null;\n const admin = resolveBranchPreviews(apps, { branch: ctx.branch, pr: ctx.pr, sha: ctx.sha }, sources).find((p) => p.app === 'admin');\n if (!admin?.url || admin.source === 'template' || admin.state === 'failed') return null;\n return admin.url;\n}\n\n/**\n * The preview with the toolbar on, at that screen (shop and theme in the query, the hash route ra-core reads), else home.\n * Only http(s) previews: anything else (a javascript: or data: URL in a hostile comment) gives ''.\n */\nexport function tryInProductUrl(preview: string, pr: number, screen: ProductScreen | null): string {\n const url = new URL(preview);\n if (url.protocol !== 'https:' && url.protocol !== 'http:') return '';\n url.pathname = '/';\n url.search = '';\n url.searchParams.set('bridge', String(pr));\n if (screen) {\n url.searchParams.set('tenant', screen.tenant);\n url.searchParams.set('theme', screen.theme);\n }\n url.hash = screen ? screen.route : '';\n return url.href;\n}\n","// Try 2 to 4 token branches together, the reads and the rules shared by Bridge Studio, the MCP server and the CLI:\n// which branches can be combined (token files only: code would need a real combined build), each branch's own token\n// edits read from GitHub (its start against its current version, token-combine changeEdits), and where the\n// combination opens (the admin demo with the Bridge toolbar, `?bridge=101,118`). Nothing is written anywhere.\nimport type { GitHubClient } from './github-client';\nimport { changeEdits, encodePicks, type ChangeEdits, type CombinePicks, type CombineSource } from './token-combine';\n\nexport const MIN_TOGETHER = 2;\n\nexport const MAX_TOGETHER = 4;\n\n/**\n * Whether a change only edits tokens: token files under the tokens root, the contrast gate and release notes\n * (changesets). Anything else is code. No file read yet (or none) is not a token change.\n */\nexport function onlyTokens(files: string[], tokensRoot: string): boolean {\n const root = `${tokensRoot.replace(/^\\/+|\\/+$/g, '')}/`;\n return files.length > 0 && files.every((f) => (f.startsWith(root) && f.endsWith('.tokens.json')) || /contrast\\.checks\\.json$/.test(f) || f.startsWith('.changeset/'));\n}\n\n/** Token files a change edits, relative to the tokens root. */\nexport function tokenFilesOf(files: string[], tokensRoot: string): string[] {\n const root = `${tokensRoot.replace(/^\\/+|\\/+$/g, '')}/`;\n return files.filter((f) => f.startsWith(root) && f.endsWith('.tokens.json')).map((f) => f.slice(root.length));\n}\n\n/** A list of changes in an address: \"101,118,120\" (commas stay readable). */\nexport const changeList = (numbers: number[]) => numbers.join(',');\n\n/**\n * The admin demo with the Bridge toolbar on the combination: production (no preview holds all of them), the tokens\n * applied live. `bridge-use` carries the picks.\n */\nexport function tryTogetherUrl(admin: string, numbers: number[], picks: CombinePicks): string {\n const url = new URL(admin);\n url.pathname = '/';\n url.hash = '';\n const use = encodePicks(picks);\n url.search = `?bridge=${changeList(numbers)}${use ? `&bridge-use=${encodeURIComponent(use)}` : ''}`;\n return url.href;\n}\n\n/** GitHub lists at most 300 files per compare: past that, a branch cannot be read whole, so it is not combined. */\nexport const COMBINE_COMPARE_LIMIT = 300;\n\nexport interface CombineBranch {\n number: number;\n title: string;\n /** Only token files (and release notes): it can be combined. */\n tokens: boolean;\n /** Its own token edits; null for a code change. */\n edits: ChangeEdits | null;\n}\n\n/**\n * One branch as the combination needs it: one compare against the default branch (the files it edits since it\n * started, and where it started), then its token files at its start and now. Without a token the client reads the\n * public raw host, so visitors spend no API read on file contents.\n */\nexport async function readCombineBranch(gh: GitHubClient, pull: { number: number; title: string; headSha: string }, opts: { base: string; tokensRoot: string }): Promise<CombineBranch> {\n const compare = await gh.compareDetailed(opts.base, pull.headSha);\n const files = compare.files;\n const names = files.flatMap((f) => (f.previous_filename ? [f.filename, f.previous_filename] : [f.filename]));\n const start = compare.mergeBase;\n if (!start || files.length >= COMBINE_COMPARE_LIMIT || !onlyTokens(names, opts.tokensRoot)) return { number: pull.number, title: pull.title, tokens: false, edits: null };\n const root = opts.tokensRoot.replace(/^\\/+|\\/+$/g, '');\n const tokenFiles = files.filter((f) => tokenFilesOf([f.filename], root).length);\n const source: CombineSource = { number: pull.number, base: {}, head: {}, files: tokenFiles.map((f) => tokenFilesOf([f.filename], root)[0]!) };\n await Promise.all(\n tokenFiles.map(async (f) => {\n const rel = tokenFilesOf([f.filename], root)[0]!;\n source.base[rel] = f.status === 'added' ? undefined : await gh.readFile(f.previous_filename ?? f.filename, start);\n source.head[rel] = f.status === 'removed' ? undefined : await gh.readFile(f.filename, pull.headSha);\n }),\n );\n return { number: pull.number, title: pull.title, tokens: true, edits: changeEdits(source) };\n}\n","// Product branches and their library branches on GitHub, shared by Bridge Studio (in the browser, with the viewer's\n// token), the MCP server and the CLI: read what a product branch changes, record its missing pieces, open the library\n// branch of a piece and link both ways, let the product branch use the library branch's preview (Bridge merges the\n// library branch in), read where each linked library branch stands, and switch to the published version once it\n// ships. In suggest mode the library side is an issue (a suggestion or a request), never a branch. The pure rules are\n// in prod-branch.ts; finding the pieces (the audit) is in audit/missing-pieces.ts.\n\nimport type { ChangesMode } from './config';\nimport { EXPLORATION_NOTES_DIR, EXPLORATION_PREFIX, isExplorationBranch } from './explorations';\nimport { startExplorationOnGitHub, type ExplorationSettings } from './explorations-github';\nimport { GitHubError, type GitHubClient, type PullRequestSummary } from './github-client';\nimport { defaultProduct, productOfBranch, type ProductConfig } from './products';\nimport {\n libraryBranchPlan,\n linkStatus,\n mergePiecesRecord,\n NEEDED_BY_LABEL,\n parsePiecesRecord,\n libraryPreviewState,\n productBranchSentence,\n withLink,\n withNeededBy,\n withPiecesRecord,\n type LibraryBranchPlan,\n type LibraryLink,\n type LinkStatus,\n type MissingPiece,\n type PiecesRecord,\n type LibraryPreviewState,\n type ProductBranchRef,\n} from './prod-branch';\nimport { composeRequestIssue, type RequestSource } from './requests';\nimport { suggestionStateFromLabels, suggestionStatus } from './suggestions';\n\n/** Files the audit reads (styles, scripts, markup). Kept here so this module never loads the audit. */\nconst PRODUCT_FILE = /\\.(css|scss|sass|less|tsx|jsx|ts|js|mjs|cjs|mts|cts|astro|vue|svelte)$/;\nconst SKIP_FILE = /\\.d\\.[cm]?ts$|\\.(test|spec|stories|story)\\.[cm]?[jt]sx?$|\\.min\\.(css|js)$/;\n/** At most this many product files are read per check (two reads each). */\nexport const PIECES_FILE_LIMIT = 40;\n\ntype Pull = PullRequestSummary & { body: string; mergeable: boolean | null; requestedReviewers: string[] };\n\nexport interface ProductBranchRead {\n pull: Pull;\n product: ProductConfig;\n /** The product's changed files, their texts at the branch start (merge base with main) and at its head. */\n files: { path: string; before: string | null; after: string | null }[];\n /** Product files left unread past the limit. */\n skipped: number;\n record: PiecesRecord | undefined;\n}\n\nconst cleanPath = (p: string) => p.trim().replace(/^\\.?\\/+|\\/+$/g, '');\n\n/** The product of a branch, refusing the library itself: missing pieces are about a product built on the library. */\nfunction productOf(products: readonly ProductConfig[], pull: Pick<Pull, 'labels'>, files: string[]): ProductConfig {\n const product = productOfBranch(products, { labels: pull.labels, files });\n if (product.key === defaultProduct(products).key) throw new GitHubError(422, `This branch is a library branch (${product.name}), not a product branch: missing pieces are checked on a branch started for a product.`);\n return product;\n}\n\n/**\n * Reads a product branch for the check: the pull request, its product, and the product files it changes with their\n * text before and after (two reads per file, up to PIECES_FILE_LIMIT files).\n */\nexport async function readProductBranchOnGitHub(gh: GitHubClient, pr: number, opts: { products: readonly ProductConfig[] }): Promise<ProductBranchRead> {\n const pull = await gh.getPullRequest(pr);\n const cmp = await gh.compareDetailed(pull.baseRef, pull.headSha);\n const product = productOf(opts.products, pull, cmp.files.map((f) => f.filename));\n const dir = product.path ? `${cleanPath(product.path)}/` : '';\n const changed = cmp.files.filter((f) => f.status !== 'removed' && (!dir || f.filename.startsWith(dir)) && PRODUCT_FILE.test(f.filename) && !SKIP_FILE.test(f.filename) && !f.filename.split('/').includes('node_modules'));\n const read = changed.slice(0, PIECES_FILE_LIMIT);\n const start = cmp.mergeBase ?? pull.baseRef;\n const files = await Promise.all(\n read.map(async (f) => {\n const [before, after] = await Promise.all([f.status === 'added' ? Promise.resolve(undefined) : gh.getFileText(f.previous_filename ?? f.filename, start), gh.getFileText(f.filename, pull.headSha)]);\n return { path: f.filename, before: before ?? null, after: after ?? null };\n }),\n );\n return { pull, product, files, skipped: changed.length - read.length, record: parsePiecesRecord(pull.body) };\n}\n\n/** Saves a check in the product branch body, keeping the library branches already opened for its pieces. */\nexport async function recordPiecesOnGitHub(gh: GitHubClient, pr: number, check: { pieces: MissingPiece[]; fixes: number; headSha?: string | undefined; checkedAt?: string | undefined }): Promise<PiecesRecord> {\n const pull = await gh.getPullRequest(pr);\n const record = mergePiecesRecord(parsePiecesRecord(pull.body), { checkedAt: check.checkedAt ?? new Date().toISOString(), headSha: check.headSha ?? pull.headSha, pieces: check.pieces, fixes: check.fixes });\n await gh.updatePullRequest(pr, { body: withPiecesRecord(pull.body, record) });\n return record;\n}\n\n/** The client that may write a product branch: explorations need the `explore/` prefix. */\nconst productWriter = (gh: GitHubClient, branch: string) => (isExplorationBranch(branch) ? gh.withBranchPrefix(EXPLORATION_PREFIX) : gh);\n\nexport interface PreviewMerge {\n status: 'merged' | 'up-to-date' | 'conflict';\n sha: string | null;\n said: string;\n}\n\n/**\n * The product branch uses the library branch's preview: Bridge merges the library branch into it, so the product\n * preview deploy and anyone working on the branch get the real library change. A conflict is left to a developer.\n */\nexport async function useLibraryPreviewOnGitHub(gh: GitHubClient, input: { productBranch: string; libraryBranch: string; libraryNumber: number }): Promise<PreviewMerge> {\n const message = `chore(bridge): use the preview of ${input.libraryBranch} (#${input.libraryNumber})\\n\\nThe product branch takes the library branch before it ships. Switch to the published version once it does.`;\n try {\n const r = await productWriter(gh, input.productBranch).mergeIntoBranch(input.productBranch, input.libraryBranch, message);\n return { ...r, said: r.status === 'merged' ? 'Your branch now uses the preview of the library branch.' : 'Your branch already has the latest preview.' };\n } catch (err) {\n if (err instanceof GitHubError && err.status === 409) return { status: 'conflict', sha: null, said: `Your branch and the library branch change the same lines. A developer merges ${input.libraryBranch} into ${input.productBranch} by hand.` };\n throw err;\n }\n}\n\nexport interface OpenLibraryBranchInput {\n /** The product branch (pull request number). */\n pr: number;\n /** The piece id, from the recorded check. */\n piece: string;\n /** Branch library work starts from (the default branch). */\n base: string;\n products: readonly ProductConfig[];\n /** Previews and snapshot packages for a library exploration. */\n exploration: Pick<ExplorationSettings, 'packages' | 'apps'>;\n /**\n * Opens the token change of a token piece (planTokenProposal + writeTokenProposalOnGitHub where the caller has the\n * token files and contrast pairs). Without it a token piece is refused. In suggest mode (`ctx.mode`), it files a\n * suggestion instead (suggestTokenProposalOnGitHub with `neededBy: plan.neededBy`) and returns its result: a result\n * with `status: 'suggested'` is linked as a suggestion, anything else as a token change pull request.\n */\n writeTokens?: ((plan: Extract<LibraryBranchPlan, { kind: 'token-change' }>, ctx: { mode: ChangesMode }) => Promise<LibraryTokenWrite>) | undefined;\n /** Who opens it, and the AI agent behind it (\"claude\"). */\n openedBy?: string | undefined;\n agent?: string | undefined;\n source?: RequestSource | undefined;\n /** Merge the new library branch into the product branch when it already changes something (default true). */\n usePreview?: boolean | undefined;\n dryRun?: boolean | undefined;\n /**\n * \"direct\" (default here, so existing callers keep their behaviour): a token piece opens a pull request, a variant\n * an exploration branch. \"suggest\": a token piece is filed as a suggestion and a variant as a component request, so\n * the token only needs Issues write. Callers pass changesMode(config), or an explicit choice.\n */\n mode?: ChangesMode | undefined;\n}\n\n/** What writeTokens returns: the pull request it opened, or the suggestion it filed. */\nexport type LibraryTokenWrite = { number: number; url: string; branch: string; status?: undefined } | { status: 'suggested'; number: number; url: string };\n\nexport interface OpenedLibraryBranch {\n /** \"suggested\": the library side is a suggestion (`link.kind` 'suggestion', `link.number` its issue). */\n status: 'opened' | 'suggested' | 'already-linked' | 'dry-run';\n plan: LibraryBranchPlan;\n link: LibraryLink | null;\n preview: PreviewMerge | null;\n warnings: string[];\n}\n\n/** The product branch as the library side names it. */\nexport function productBranchRef(pull: Pick<Pull, 'number' | 'title' | 'headRef' | 'url' | 'author' | 'body'>, product: ProductConfig): ProductBranchRef {\n const name = /<!-- bridge-exploration (\\{[\\s\\S]*?\\}) -->/.exec(pull.body ?? '');\n let title = pull.title.replace(/^[A-Z][A-Z0-9_]*-\\d+\\s+/, '').replace(/^Exploration:\\s*/i, '');\n let author = pull.author;\n if (name) {\n try {\n const e = JSON.parse(name[1]!) as { name?: string; author?: string };\n if (e.name) title = e.name;\n if (e.author) author = e.author;\n } catch {\n // The pull request title is enough.\n }\n }\n return { pr: pull.number, title: title.charAt(0).toUpperCase() + title.slice(1), branch: pull.headRef, url: pull.url, productKey: product.key, productName: product.name, ...(author ? { author } : {}) };\n}\n\n/**\n * Opens the library side of a missing piece and links both ways: the library branch (or request) says \"Needed by\" the\n * product branch and carries the `needed-by-product` label; the product branch records the link. A token piece opens a\n * token change (through `writeTokens`), a variant a library exploration, a new component a request. When the new\n * library branch already changes something (a token change), the product branch takes its preview.\n * In suggest mode nothing is a branch: a token piece is a suggestion (through `writeTokens`), a variant and a new\n * component are requests; recording the link on the product branch is best effort (a warning when refused).\n */\nexport async function openLibraryBranchOnGitHub(gh: GitHubClient, input: OpenLibraryBranchInput): Promise<OpenedLibraryBranch> {\n const pull = await gh.getPullRequest(input.pr);\n const record = parsePiecesRecord(pull.body);\n const piece = record?.pieces.find((p) => p.id === input.piece);\n if (!record || !piece) throw new GitHubError(404, record ? `No piece \"${input.piece}\" on #${input.pr}. Pieces: ${record.pieces.map((p) => p.id).join(', ') || 'none'}.` : `#${input.pr} was not checked yet: find its missing pieces first (bridge_missing_pieces with record, or \\`bridge pieces ${input.pr} --record\\`).`);\n const product = productOf(input.products, pull, await gh.listPullRequestFiles(input.pr).then((f) => f.map((x) => x.filename), () => []));\n const mode: ChangesMode = input.mode ?? 'direct';\n const plan = libraryBranchPlan(piece, productBranchRef(pull, product), { source: input.source, requestedBy: input.openedBy, mode });\n const existing = record.links.find((l) => l.piece === piece.id);\n if (existing) return { status: 'already-linked', plan, link: existing, preview: null, warnings: [] };\n if (input.dryRun) return { status: 'dry-run', plan, link: null, preview: null, warnings: [] };\n if (!gh.canWrite) throw new GitHubError(401, mode === 'suggest' ? 'Suggesting a library change needs a GitHub token (issues: write).' : 'Opening a library branch needs a GitHub token (contents, pull requests and issues: write).');\n const warnings: string[] = [];\n const at = new Date().toISOString();\n const who = { ...(input.openedBy ? { openedBy: input.openedBy } : {}), ...(input.agent ? { agent: input.agent } : {}) };\n let link: LibraryLink;\n if (plan.kind === 'token-change') {\n if (!input.writeTokens) throw new GitHubError(422, 'This piece is a token: open it where the token files are read (Bridge Studio, bridge_open_library_branch or `bridge pieces open`).');\n const r = await input.writeTokens(plan, { mode });\n link = r.status === 'suggested' ? { piece: piece.id, kind: 'suggestion', number: r.number, url: r.url, title: plan.title, at, ...who } : { piece: piece.id, kind: 'token-change', number: r.number, url: r.url, title: plan.title, branch: r.branch, at, ...who };\n } else if (plan.kind === 'exploration') {\n const r = await startExplorationOnGitHub(gh, { ...plan.exploration, ...(input.openedBy ? { author: input.openedBy } : {}), ...(input.agent ? { agent: input.agent } : {}) }, { base: input.base, ...input.exploration, labels: [NEEDED_BY_LABEL] });\n link = { piece: piece.id, kind: 'exploration', number: r.pr, url: r.url, title: plan.title, branch: r.branch, at, ...who };\n } else {\n const issue = composeRequestIssue(plan.request, { labels: [NEEDED_BY_LABEL] });\n const r = await gh.createIssue(issue);\n link = { piece: piece.id, kind: 'request', number: r.number, url: r.url, title: plan.title, at, ...who };\n }\n // The library side says who needs it; the product side records the link.\n try {\n if (link.kind === 'request' || link.kind === 'suggestion') {\n const issue = await gh.getIssue(link.number);\n await gh.updateIssue(link.number, { body: withNeededBy(issue.body, plan.neededBy) });\n if (link.kind === 'suggestion' && !issue.labels.includes(NEEDED_BY_LABEL)) await gh.addLabels(link.number, [NEEDED_BY_LABEL]);\n } else {\n const lib = await gh.getPullRequest(link.number);\n await gh.updatePullRequest(link.number, { body: withNeededBy(lib.body, plan.neededBy) });\n await gh.addLabels(link.number, [NEEDED_BY_LABEL]);\n }\n } catch (err) {\n if (err instanceof GitHubError && err.auth === 'rejected') throw err;\n warnings.push(`The library side does not say who needs it yet (${(err as Error).message}). Add \"Needed by #${input.pr}\" to #${link.number} on GitHub.`);\n }\n try {\n const fresh = await gh.getPullRequest(input.pr);\n const next = withLink(parsePiecesRecord(fresh.body) ?? record, link);\n await gh.updatePullRequest(input.pr, { body: withPiecesRecord(fresh.body, next) });\n } catch (err) {\n // Direct mode needs the record (the token can write pull requests); a suggest-mode token may not.\n if (mode !== 'suggest') throw err;\n warnings.push(`#${input.pr} does not list #${link.number} yet (${(err as Error).message}). Add \"Library: #${link.number}\" to #${input.pr} on GitHub, so this piece is not sent twice.`);\n }\n let preview: PreviewMerge | null = null;\n if ((input.usePreview ?? true) && link.kind === 'token-change' && link.branch) {\n preview = await useLibraryPreviewOnGitHub(gh, { productBranch: pull.headRef, libraryBranch: link.branch, libraryNumber: link.number }).catch((err: Error) => {\n warnings.push(`Your branch does not use the preview yet: ${err.message}`);\n return null;\n });\n }\n return { status: link.kind === 'suggestion' ? 'suggested' : 'opened', plan, link, preview, warnings };\n}\n\nexport interface LinkedLibraryBranch {\n link: LibraryLink;\n piece: MissingPiece | undefined;\n status: LinkStatus;\n preview: LibraryPreviewState;\n /** Requested reviewers of a library pull request, or assignees of a request. */\n people: string[];\n}\n\nexport interface ProductBranchView {\n pull: Pull;\n product: ProductConfig;\n record: PiecesRecord | undefined;\n sentence: ReturnType<typeof productBranchSentence>;\n linked: LinkedLibraryBranch[];\n /** Pieces with no library branch yet. */\n open: MissingPiece[];\n}\n\nconst isNote = (path: string) => path.startsWith(`${EXPLORATION_NOTES_DIR}/`);\n\n/** Where one linked library branch stands, and what its preview means for the product branch. */\nexport async function linkedLibraryBranchOnGitHub(gh: GitHubClient, link: LibraryLink, product: { headSha: string; baseRef: string }, piece?: MissingPiece): Promise<LinkedLibraryBranch> {\n const nearest = piece?.nearest?.label;\n if (link.kind === 'suggestion') {\n const issue = await gh.getIssue(link.number);\n // Status from the issue and its state label (a cache): the review comments are read on the suggestion itself.\n const cached = suggestionStateFromLabels(issue.labels);\n const s = suggestionStatus({ state: issue.state, stateReason: issue.stateReason, applied: cached === 'applying', review: cached === 'applying' ? undefined : cached });\n const status = linkStatus({ kind: 'suggestion', status: s });\n const lifecycle = s === 'applied' ? 'merged' : issue.state === 'closed' ? 'closed' : 'open';\n const behindMain = lifecycle === 'merged' ? await gh.compare(product.baseRef, product.headSha).then((c) => c.behindBy, () => null) : null;\n const preview = libraryPreviewState({ kind: 'suggestion', lifecycle, hasChanges: false, missing: null, total: null, behindMain, nearest });\n return { link, piece, status, preview, people: status.people };\n }\n if (link.kind === 'request') {\n const issue = await gh.getIssue(link.number);\n const status = linkStatus({ kind: 'request', state: issue.state, stateReason: issue.stateReason });\n const lifecycle = issue.state === 'closed' ? (issue.stateReason === 'not_planned' ? 'closed' : 'merged') : 'open';\n const behindMain = lifecycle === 'merged' ? await gh.compare(product.baseRef, product.headSha).then((c) => c.behindBy, () => null) : null;\n const preview = libraryPreviewState({ kind: 'request', lifecycle, hasChanges: false, missing: null, total: null, behindMain, nearest });\n return { link, piece, status, preview, people: status.people };\n }\n const lib = await gh.getPullRequest(link.number);\n const reviews = await gh.listReviews(link.number).catch(() => []);\n const status = linkStatus({ kind: link.kind, state: lib.state, draft: lib.draft, labels: lib.labels, requestedReviewers: lib.requestedReviewers, reviews: reviews.map((r) => ({ user: r.user, state: r.state })) });\n const lifecycle = lib.state === 'merged' ? 'merged' : lib.state === 'open' ? 'open' : 'closed';\n let missing: number | null = null;\n let total: number | null = null;\n let behindMain: number | null = null;\n let hasChanges = true;\n if (lifecycle === 'open') {\n const [files, own, inProduct] = await Promise.all([\n gh.listPullRequestFiles(link.number).catch(() => null),\n gh.compare(lib.baseRef, lib.headSha).catch(() => null),\n gh.compare(product.headSha, lib.headSha).catch(() => null),\n ]);\n hasChanges = files ? files.some((f) => !isNote(f.filename)) : true;\n total = own?.aheadBy ?? null;\n missing = inProduct?.aheadBy ?? null;\n } else if (lifecycle === 'merged') {\n behindMain = await gh.compare(product.baseRef, product.headSha).then((c) => c.behindBy, () => null);\n }\n const preview = libraryPreviewState({ kind: link.kind, lifecycle, hasChanges, missing, total, behindMain, nearest });\n return { link, piece, status, preview, people: status.people };\n}\n\n/**\n * Everything a product branch page shows: the record, the sentence, and each linked library branch with its status,\n * its reviewers and what its preview means for the product branch. A few reads per linked branch.\n */\nexport async function productBranchViewOnGitHub(gh: GitHubClient, pr: number, opts: { products: readonly ProductConfig[]; viewer?: string | null | undefined; agentName?: string | undefined }): Promise<ProductBranchView> {\n const pull = await gh.getPullRequest(pr);\n const files = await gh.listPullRequestFiles(pr).then((f) => f.map((x) => x.filename), () => []);\n const product = productOf(opts.products, pull, files);\n const record = parsePiecesRecord(pull.body);\n const linked = await Promise.all(\n (record?.links ?? []).map((l) => linkedLibraryBranchOnGitHub(gh, l, { headSha: pull.headSha, baseRef: pull.baseRef }, record?.pieces.find((p) => p.id === l.piece))),\n );\n const open = (record?.pieces ?? []).filter((p) => !record!.links.some((l) => l.piece === p.id));\n return { pull, product, record, sentence: productBranchSentence(record, { viewer: opts.viewer, agentName: opts.agentName }), linked, open };\n}\n\n/**\n * \"Switch to the published version\": once the library branch shipped, main comes into the product branch (GitHub's\n * update branch), so the product branch stops carrying the library change and uses the shipped one. Conflicts are\n * left to bridge_update_from_main or a developer.\n */\nexport async function switchToPublishedOnGitHub(gh: GitHubClient, pr: number): Promise<{ status: 'switched' | 'up-to-date'; said: string }> {\n if (!gh.canWrite) throw new GitHubError(401, 'Switching needs a GitHub token (contents and pull requests: write).');\n const pull = await gh.getPullRequest(pr);\n if (pull.state !== 'open') throw new GitHubError(422, `#${pr} is ${pull.state}: only an open branch switches.`);\n const cmp = await gh.compare(pull.baseRef, pull.headSha);\n if (cmp.behindBy === 0) return { status: 'up-to-date', said: 'Your branch already uses the published version.' };\n try {\n await gh.updatePullRequestBranch(pr, pull.headSha);\n } catch (err) {\n if (err instanceof GitHubError && err.status === 422) throw new GitHubError(422, `Your branch and ${pull.baseRef} change the same lines, so Bridge cannot switch it alone. Use \"Update from main\" to pick the token values, or ask a developer.`, err.detail);\n throw err;\n }\n return { status: 'switched', said: `Your branch now uses the published version from ${pull.baseRef}.` };\n}\n","// A token change proposal: token edits checked like every Bridge write (no new validation error, no contrast pair that\n// starts failing), tiered by the shared classifier, with the designer-friendly body and a changeset; then, on GitHub,\n// either a new branch with one commit and a pull request (a draft from tier 2), labelled (\"direct\" mode), or a\n// suggestion: an issue holding the exact edits that owners approve and a developer applies (\"suggest\" mode, see\n// suggestions.ts). The MCP server (bridge_propose_token_change), the CLI (`bridge propose`) and Studio (a library\n// branch for a product branch's missing token) all write it through these functions.\nimport type { BridgeConfig } from './config';\nimport type { GitHubClient } from './github-client';\nimport type { NeededBy } from './prod-branch';\nimport type { RequestSource } from './requests';\nimport { createSuggestionOnGitHub } from './suggestions-github';\nimport { gitBlobSha, SUGGESTION_SCHEMA, type SuggestionPayloadV1 } from './suggestions';\nimport { branchWithJiraKey, titleWithJiraKey } from './jira';\nimport { LayeredTokenSet, validateLayered, type LayerIssue } from './layered';\nimport { classifyLayered, composeProposalBody, contrastDelta, diffLayered, layeredImpact, runLayeredContrast, type ChangeTier, type ContrastDelta, type ImpactEntry, type LayeredChange } from './layered-review';\nimport { slugify } from './pr-composer';\nimport { applyTokenEdits, type TokenEdit } from './token-edits';\nimport type { ContrastPair } from './wcag';\nimport { formatChangeset } from './changeset';\n\nexport interface TokenProposalPlan {\n title: string;\n summary: string;\n /** The token edits the plan applied: what a suggestion stores and re-applies on the current tokens. */\n edits: TokenEdit[];\n before: LayeredTokenSet;\n after: LayeredTokenSet;\n changes: LayeredChange[];\n tier: ChangeTier;\n contrast: ContrastDelta[];\n newFailures: ContrastDelta[];\n newErrors: LayerIssue[];\n impact: { total: number; entries: ImpactEntry[] };\n notes: string[];\n /** Token files edited, as repo paths. */\n touched: string[];\n /** Every file the commit writes: the token files and the changeset. */\n files: { path: string; content: string | null }[];\n body: string;\n /** Branch slug from the title. */\n slug: string;\n /** Why it cannot be opened (new validation errors, failing contrast pairs), or null. */\n blocked: string | null;\n}\n\nconst issueKey = (i: LayerIssue) => `${i.code}|${i.path ?? ''}|${i.file ?? ''}|${i.message}`;\n\n/**\n * What a token change would do, without writing: the token diff, validation and contrast against `before`, the tier,\n * the body and the files. `blocked` says why it must not be opened. Null when the edits change nothing.\n */\nexport function planTokenProposal(input: {\n before: LayeredTokenSet;\n pairs: ContrastPair[];\n edits: TokenEdit[];\n title: string;\n summary?: string | undefined;\n config: BridgeConfig;\n /** \"Bridge MCP\", \"Bridge Studio\". */\n tool?: string | undefined;\n /** More body paragraphs, after the generated body (the product line, \"Needed by\"). */\n bodyExtra?: string[] | undefined;\n}): TokenProposalPlan | null {\n const { before, config } = input;\n const r = applyTokenEdits(before, input.edits);\n const after = new LayeredTokenSet(before.config, r.files);\n const changes = diffLayered(before, after);\n if (!changes.length) return null;\n const prevErrors = new Set(validateLayered(before).map(issueKey));\n const newErrors = validateLayered(after).filter((i) => i.level === 'error' && !prevErrors.has(issueKey(i)));\n const modes = config.contrast?.modes;\n const contrast = input.pairs.length ? contrastDelta(runLayeredContrast(before, input.pairs, modes), runLayeredContrast(after, input.pairs, modes)) : [];\n const newFailures = contrast.filter((d) => d.passBefore && !d.passAfter);\n const impact = layeredImpact(before, after, changes);\n const tier = classifyLayered(changes, [], config);\n const summary = input.summary?.trim() || input.title;\n const body = [composeProposalBody({ summary, changes, contrast, impact, tier, validationErrors: newErrors.length, tool: input.tool ?? 'Bridge MCP' }), ...(input.bodyExtra ?? [])].filter(Boolean).join('\\n\\n');\n const slug = slugify(input.title, 48) || 'change';\n const changesetPath = `${config.changesets?.dir ?? '.changeset'}/bridge-${slug}.md`;\n const touched = r.touched.map((f) => after.repoPath(f));\n const files = [\n ...r.touched.map((f) => ({ path: after.repoPath(f), content: after.files.get(f)! as string | null })),\n ...(config.changesets ? [{ path: changesetPath, content: formatChangeset(config.changesets.package, tier.bump, summary) as string | null }] : []),\n ];\n const blocked = newErrors.length || newFailures.length ? [newErrors.length ? `${newErrors.length} new validation error(s)` : '', newFailures.length ? `${newFailures.length} contrast pair(s) would fail` : ''].filter(Boolean).join(' and ') : null;\n return { title: input.title, summary, edits: input.edits, before, after, changes, tier, contrast, newFailures, newErrors, impact, notes: r.notes, touched, files, body, slug, blocked };\n}\n\nexport interface OpenedTokenProposal {\n branch: string;\n commit: string;\n pr: number;\n url: string;\n labels: string[];\n draft: boolean;\n}\n\n/**\n * Opens a planned token change on GitHub: a new branch from `base` (the agent prefix, the Jira key, -2, -3 when the name\n * is taken), one commit, a pull request (a draft from tier 2, until design review) and its labels. Refuses a blocked plan.\n */\nexport async function writeTokenProposalOnGitHub(\n gh: GitHubClient,\n plan: TokenProposalPlan,\n opts: {\n base: string;\n branchPrefix: string;\n jira?: string | null | undefined;\n /** Labels before the tier ones (governance.labels), and after them (the product label). */\n labels?: string[] | undefined;\n labelsAfter?: string[] | undefined;\n /** Who proposes it, in the commit message: \"Bridge MCP (source: mcp)\". */\n tool?: string | undefined;\n },\n): Promise<OpenedTokenProposal> {\n if (plan.blocked) throw new Error(`Not opened: ${plan.blocked}. Bridge never opens a branch that breaks the gate.`);\n const jira = opts.jira ?? null;\n let branch = branchWithJiraKey(`${opts.branchPrefix}${plan.slug}`, jira);\n for (let i = 2; await gh.getBranchSha(branch).then(Boolean, () => false); i++) branch = branchWithJiraKey(`${opts.branchPrefix}${plan.slug}-${i}`, jira);\n const commit = await gh.commitToNewBranch({ base: opts.base, branch, message: `feat(tokens): ${plan.title}\\n\\nProposed through ${opts.tool ?? 'Bridge MCP'}. Tier ${plan.tier.tier}.`, files: plan.files });\n const labels = tokenLabels(plan, opts.labels, opts.labelsAfter);\n const draft = plan.tier.tier >= 2;\n const pr = await gh.createPullRequest({ base: opts.base, head: branch, title: titleWithJiraKey(`feat(tokens): ${plan.title}`, jira), body: plan.body, draft });\n await gh.addLabels(pr.number, labels);\n return { branch, commit: commit.sha, pr: pr.number, url: pr.url, labels, draft };\n}\n\nexport interface SuggestedTokenProposal {\n status: 'suggested';\n /** The suggestion issue. */\n number: number;\n url: string;\n /** sha256 of the payload: what approvals bind to. */\n sha: string;\n labels: string[];\n /** Sentences about parts that did not go through (labels refused). The suggestion itself holds. */\n warnings: string[];\n}\n\n/** The labels of a token change, before and after the tier ones: the same on a pull request and a suggestion. */\nconst tokenLabels = (plan: Pick<TokenProposalPlan, 'tier'>, before: string[] = [], after: string[] = []) => [\n ...new Set([...before, `tier: ${plan.tier.tier}`, ...(plan.tier.tier === 3 ? ['tokens'] : []), ...(plan.tier.bump === 'major' ? ['breaking'] : []), ...after]),\n];\n\n/** The suggestion payload (bridge.suggestion/1) of a planned token change, computed on `base`. Pure. */\nexport function tokenSuggestionPayload(\n plan: TokenProposalPlan,\n ctx: {\n base: { ref: string; sha: string };\n source: RequestSource;\n suggestedBy?: string | undefined;\n createdAt?: string | undefined;\n links?: SuggestionPayloadV1['links'];\n previews?: SuggestionPayloadV1['previews'];\n },\n): SuggestionPayloadV1 {\n // Token files are re-derived from the edits at apply time; only the other files (the changeset) are stored whole.\n const tokenFiles = new Set(plan.touched);\n const files = plan.files.filter((f) => !tokenFiles.has(f.path)).map((f) => ({ path: f.path, beforeSha: null, afterSha: f.content === null ? null : gitBlobSha(f.content), content: f.content }));\n return {\n schema: SUGGESTION_SCHEMA,\n kind: 'token-change',\n title: plan.title,\n summary: plan.summary,\n source: ctx.source,\n ...(ctx.suggestedBy ? { suggestedBy: ctx.suggestedBy.replace(/^@/, '') } : {}),\n createdAt: ctx.createdAt ?? new Date().toISOString(),\n base: ctx.base,\n tier: { tier: plan.tier.tier, bump: plan.tier.bump },\n tokens: {\n edits: plan.edits,\n changes: plan.changes.map((c) => ({ kind: c.kind, path: c.path, from: c.from, file: c.file, before: c.before, after: c.after, beforeCss: c.beforeCss, afterCss: c.afterCss })),\n },\n ...(files.length ? { files } : {}),\n checks: {\n newErrors: plan.newErrors.length,\n contrast: plan.contrast.map((d) => ({ pair: `${d.fg} on ${d.bg}`, mode: d.modes || undefined, before: d.before ?? 0, after: d.after ?? 0, min: d.min, pass: d.passAfter })),\n blocked: plan.blocked,\n impact: plan.impact.total,\n },\n ...(ctx.links ? { links: ctx.links } : {}),\n ...(ctx.previews?.length ? { previews: ctx.previews } : {}),\n };\n}\n\n/**\n * Files a planned token change as a suggestion (suggest mode): one issue with the readable change, the checks and the\n * exact edits, labelled like the pull request would be (tier, tokens, breaking), plus the suggestion labels. Needs\n * Issues write only: no branch, no commit, no pull request. Refuses a blocked plan, like writeTokenProposalOnGitHub.\n */\nexport async function suggestTokenProposalOnGitHub(\n gh: GitHubClient,\n plan: TokenProposalPlan,\n opts: {\n /** Default branch the plan was computed on. Its head commit is recorded as the suggestion's base. */\n base: string;\n source: RequestSource;\n /** GitHub login of who suggests it. */\n suggestedBy?: string | undefined;\n /** Labels before the tier ones (governance.labels), and after them (the product label). */\n labels?: string[] | undefined;\n labelsAfter?: string[] | undefined;\n /** The product branch that needs it (a missing piece). */\n neededBy?: NeededBy | undefined;\n /** The Figma origin, a suggestion it replaces. */\n links?: SuggestionPayloadV1['links'];\n previews?: SuggestionPayloadV1['previews'];\n assignees?: string[] | undefined;\n /** Commit sha of `base`, when the caller already read it (saves a call). */\n baseSha?: string | undefined;\n },\n): Promise<SuggestedTokenProposal> {\n if (plan.blocked) throw new Error(`Not suggested: ${plan.blocked}. Bridge never suggests a change that breaks the gate.`);\n const sha = opts.baseSha ?? (await gh.getBranchSha(opts.base));\n if (!sha) throw new Error(`Branch ${opts.base} not found. Check the default branch in bridge.config.json.`);\n const links = opts.neededBy || opts.links ? { ...opts.links, ...(opts.neededBy ? { neededBy: opts.neededBy } : {}) } : undefined;\n const payload = tokenSuggestionPayload(plan, { base: { ref: opts.base, sha }, source: opts.source, suggestedBy: opts.suggestedBy, links, previews: opts.previews });\n const labels = tokenLabels(plan, opts.labels, opts.labelsAfter);\n const created = await createSuggestionOnGitHub(gh, payload, { labels, assignees: opts.assignees, details: plan.body });\n return { status: 'suggested', number: created.number, url: created.url, sha: created.sha, labels, warnings: created.warnings };\n}\n","// Components pushed from Figma, on GitHub: open the library branch a component change goes to (a token change through\n// the shared token proposal write, or a Claude draft branch carrying the spec), list them with where each stands, read\n// one back as Claude's brief, and say when Claude has drafted the code. Shared by the DS Bridge Figma plugin, the MCP\n// server and the CLI. In suggest mode the same change is filed as a suggestion (an issue) instead of a branch. The\n// routing rules are in figma-push.ts.\n\nimport type { ChangesMode } from './config';\nimport { GitHubError, type GitHubClient } from './github-client';\nimport { REQUEST_LABEL, type RequestSource } from './requests';\nimport { createSuggestionOnGitHub } from './suggestions-github';\nimport { figmaNodeUrl, SUGGESTION_SCHEMA, type SuggestionFigmaNode, type SuggestionPayloadV1 } from './suggestions';\nimport type { TokenEdit } from './token-edits';\nimport {\n DRAFTED_BY_CLAUDE_LABEL,\n FIGMA_SPEC_DIR,\n FROM_FIGMA_LABEL,\n WAITING_FOR_CLAUDE_LABEL,\n figmaBranchTitle,\n figmaDraftBody,\n figmaDraftBrief,\n figmaOriginSection,\n figmaPushStatus,\n figmaSpecPath,\n figmaSpecSlug,\n formatFigmaSpec,\n parseFigmaOrigin,\n parseFigmaSpec,\n planComponentPush,\n withFigmaOrigin,\n type ComponentPushDiff,\n type ComponentPushPlan,\n type FigmaOrigin,\n type FigmaPushStatus,\n type PushTokenContext,\n} from './figma-push';\n\n/**\n * Opens the token change of an exact push: the caller plans it on the library's token files (planTokenProposal). In\n * suggest mode (`mode`), it files a suggestion instead (suggestTokenProposalOnGitHub with `links: { figma }`) and\n * returns its result: a result with `status: 'suggested'` is reported as a suggestion.\n */\nexport type FigmaTokenWriter = (input: {\n edits: TokenEdit[];\n title: string;\n summary: string;\n bodyExtra: string[];\n mode: ChangesMode;\n /** The Figma component, for the suggestion's links. */\n figma: { fileKey?: string | undefined; nodeId?: string | undefined; url?: string | undefined; nodes?: SuggestionFigmaNode[] | undefined };\n}) => Promise<{ number: number; url: string; branch: string; status?: undefined } | { status: 'suggested'; number: number; url: string }>;\n\nexport interface OpenComponentPushInput {\n diff: ComponentPushDiff;\n /** Token facts to route it (planComponentPush), or the route already planned with every component of the file. */\n tokens?: PushTokenContext | undefined;\n plan?: ComponentPushPlan | undefined;\n /** Branch library work starts from (the default branch). */\n base: string;\n /** governance.branchPrefix (\"bridge/\"). */\n branchPrefix: string;\n /** Labels the repo adds to every Bridge branch (governance.labels), before the Figma ones. */\n labels?: string[] | undefined;\n /** The token change of an exact push (planTokenProposal + writeTokenProposalOnGitHub where the token files are read). */\n writeTokens?: FigmaTokenWriter | undefined;\n /** \"the DS Bridge Figma plugin\", \"Bridge MCP\". */\n tool?: string | undefined;\n dryRun?: boolean | undefined;\n /**\n * \"direct\" (default here, so existing callers keep their behaviour): a branch and a pull request. \"suggest\": a\n * suggestion issue (a token change, or a component spec for Claude), no branch. Callers pass changesMode(config).\n */\n mode?: ChangesMode | undefined;\n /** Who sends it (a GitHub login), recorded on a suggestion. Defaults to the diff's requestedBy. */\n suggestedBy?: string | undefined;\n /** Commit sha of `base`, when the caller already read it (a component spec suggestion records it). */\n baseSha?: string | undefined;\n}\n\nexport interface OpenedComponentPush {\n status: 'opened' | 'suggested' | 'dry-run' | 'not-sent';\n plan: ComponentPushPlan;\n /** The library branch: a token change or a Claude draft branch (a draft pull request). Null when suggested. */\n link: { route: 'token-change' | 'claude-draft'; number: number; url: string; branch: string } | null;\n /** The suggestion issue (status 'suggested'): a token change, or a component spec Claude drafts the code from. */\n suggestion?: { route: 'token-change' | 'claude-draft'; number: number; url: string } | undefined;\n}\n\n/** The source of a push, as suggestions name it: the diff's own when it is one, else Figma. */\nconst pushSource = (d: ComponentPushDiff): RequestSource => (['figma', 'studio', 'cli', 'mcp'].includes(d.source as string) ? (d.source as RequestSource) : 'figma');\n\n/** Tier of a component spec: new parts of the API are tier 2 minor, other code changes tier 2 patch. */\nconst specTier = (d: ComponentPushDiff): SuggestionPayloadV1['tier'] => ({ tier: 2, bump: d.kind === 'new-component' || d.kind === 'new-variant' || d.kind === 'prop-change' ? 'minor' : 'patch' });\n\n/** The suggestion payload (bridge.suggestion/1, kind component-spec) of a push that needs code. Pure. */\nexport function componentSpecSuggestionPayload(\n d: ComponentPushDiff,\n plan: Pick<ComponentPushPlan, 'edits' | 'reasons' | 'issues'>,\n ctx: { base: { ref: string; sha: string }; suggestedBy?: string | undefined; createdAt?: string | undefined; componentsDir?: string | undefined },\n): SuggestionPayloadV1 {\n const specPath = figmaSpecPath(d);\n const spec = JSON.parse(formatFigmaSpec(d, plan)) as unknown;\n const brief = figmaDraftBrief({ ...d, tokenEdits: plan.edits, reasons: plan.reasons }, { suggestion: true, specPath, componentsDir: ctx.componentsDir });\n const by = (ctx.suggestedBy ?? d.requestedBy)?.replace(/^@/, '');\n const figma = d.figma?.fileKey || d.figma?.nodeId || d.figma?.url ? { ...(d.figma.fileKey ? { fileKey: d.figma.fileKey } : {}), ...(d.figma.nodeId ? { nodeId: d.figma.nodeId } : {}), ...(d.figma.url ? { url: d.figma.url } : {}), ...figmaNodes(d) } : undefined;\n // Screenshots, when the sender could store them (a token with contents write): links next to the Figma nodes.\n const previews = (d.images ?? []).map((url, i) => ({ label: `${d.component} in Figma${(d.images?.length ?? 0) > 1 ? ` ${i + 1}` : ''}`, url }));\n return {\n schema: SUGGESTION_SCHEMA,\n kind: 'component-spec',\n title: d.title,\n summary: d.summary.trim() || d.title,\n source: pushSource(d),\n ...(by ? { suggestedBy: by } : {}),\n createdAt: ctx.createdAt ?? new Date().toISOString(),\n base: ctx.base,\n tier: specTier(d),\n componentSpec: { component: d.component, specPath, spec, brief },\n checks: { newErrors: 0, contrast: [], blocked: null, impact: 0 },\n ...(figma ? { links: { figma } } : {}),\n ...(previews.length ? { previews } : {}),\n };\n}\n\n/** The Figma nodes of a push for a suggestion's links: the component as it is now (after), and before when known. */\nexport function figmaNodes(d: Pick<ComponentPushDiff, 'figma'>): { nodes?: SuggestionFigmaNode[] } {\n const f = d.figma;\n if (!f) return {};\n const url = (id: string, given?: string) => given ?? (f.fileKey ? figmaNodeUrl(f.fileKey, id) : undefined);\n const nodes: SuggestionFigmaNode[] = [];\n if (f.before?.nodeId) nodes.push({ nodeId: f.before.nodeId, state: 'before', ...(url(f.before.nodeId, f.before.url) ? { url: url(f.before.nodeId, f.before.url) } : {}), ...(f.before.nodeName ? { name: f.before.nodeName } : {}) });\n if (f.nodeId) nodes.push({ nodeId: f.nodeId, state: 'after', ...(url(f.nodeId, f.url) ? { url: url(f.nodeId, f.url) } : {}), ...(f.nodeName ? { name: f.nodeName } : {}) });\n return nodes.length ? { nodes } : {};\n}\n\n/**\n * Opens the library branch of a component change from Figma, linked to its origin (the Figma component): an exact token\n * swap opens a token change (the shared proposal write: contrast gate, tier, changeset); anything that needs code opens\n * a draft pull request carrying the spec (`.bridge/figma/<slug>.json`), labelled waiting for Claude. A manual change\n * opens nothing: its issues say what to do in Figma.\n * In suggest mode: the token swap is a token suggestion (through `writeTokens`), the code change a component spec\n * suggestion (the spec inside the payload, labelled from Figma and waiting for Claude). Issues write only.\n */\nexport async function openComponentPushOnGitHub(gh: GitHubClient, input: OpenComponentPushInput): Promise<OpenedComponentPush> {\n const d = input.diff;\n if (!input.plan && !input.tokens) throw new Error('Route the change first: pass the token facts or the plan.');\n const plan = input.plan ?? planComponentPush(d, input.tokens!);\n if (plan.route === 'manual') return { status: 'not-sent', plan, link: null };\n if (input.dryRun) return { status: 'dry-run', plan, link: null };\n const mode: ChangesMode = input.mode ?? 'direct';\n if (!gh.canWrite) throw new GitHubError(401, mode === 'suggest' ? 'Suggesting a component change needs a GitHub token (issues: write).' : 'Sending a component change needs a GitHub token (contents and pull requests: write).');\n const origin: FigmaOrigin = {\n component: d.component,\n figmaName: d.figmaName,\n route: plan.route,\n kind: d.kind,\n ...(d.figma?.nodeId ? { nodeId: d.figma.nodeId } : {}),\n ...(d.figma?.fileKey ? { fileKey: d.figma.fileKey } : {}),\n ...(d.figma?.url ? { url: d.figma.url } : {}),\n ...(d.requestedBy ? { requestedBy: d.requestedBy } : {}),\n };\n if (plan.route === 'token-change') {\n if (!input.writeTokens) throw new GitHubError(422, 'This change is a token change: send it where the token files are read (the DS Bridge plugin, bridge_push_figma_component or `bridge figma push`).');\n const figma = { ...(origin.fileKey ? { fileKey: origin.fileKey } : {}), ...(origin.nodeId ? { nodeId: origin.nodeId } : {}), ...(origin.url ? { url: origin.url } : {}), ...figmaNodes(d) };\n const r = await input.writeTokens({ edits: plan.edits, title: figmaBranchTitle(d), summary: d.summary.trim() || d.title, bodyExtra: [figmaOriginSection(origin)], mode, figma });\n await gh.addLabels(r.number, [FROM_FIGMA_LABEL]);\n if (r.status === 'suggested') return { status: 'suggested', plan, link: null, suggestion: { route: 'token-change', number: r.number, url: r.url } };\n return { status: 'opened', plan, link: { route: 'token-change', number: r.number, url: r.url, branch: r.branch } };\n }\n if (mode === 'suggest') {\n const sha = input.baseSha ?? (await gh.getBranchSha(input.base));\n if (!sha) throw new GitHubError(404, `Branch ${input.base} not found. Check the default branch in bridge.config.json.`);\n const payload = componentSpecSuggestionPayload(d, plan, { base: { ref: input.base, sha }, suggestedBy: input.suggestedBy });\n const created = await createSuggestionOnGitHub(gh, payload, { labels: [...(input.labels ?? []), WAITING_FOR_CLAUDE_LABEL] });\n return { status: 'suggested', plan, link: null, suggestion: { route: 'claude-draft', number: created.number, url: created.url } };\n }\n const spec = figmaSpecPath(d);\n const o: FigmaOrigin = { ...origin, spec, status: 'spec' };\n let branch = `${input.branchPrefix}figma-${figmaSpecSlug(d)}`;\n for (let i = 2; await gh.getBranchSha(branch).then(Boolean, () => false); i++) branch = `${input.branchPrefix}figma-${figmaSpecSlug(d)}-${i}`;\n await gh.commitToNewBranch({\n base: input.base,\n branch,\n message: `chore(figma): spec for ${figmaBranchTitle(d)}\\n\\nSent from Figma with ${input.tool ?? 'the DS Bridge Figma plugin'}. Claude AI drafts the code on this branch; a person reviews it.`,\n files: [{ path: spec, content: formatFigmaSpec(d, plan) }],\n });\n const pr = await gh.createPullRequest({ base: input.base, head: branch, title: figmaBranchTitle(d), body: figmaDraftBody(d, plan, o), draft: true });\n await gh.addLabels(pr.number, [...new Set([...(input.labels ?? []), FROM_FIGMA_LABEL, REQUEST_LABEL, WAITING_FOR_CLAUDE_LABEL])]);\n return { status: 'opened', plan, link: { route: 'claude-draft', number: pr.number, url: pr.url, branch } };\n}\n\nexport interface FigmaChangeRow {\n number: number;\n title: string;\n url: string;\n branch: string;\n origin: FigmaOrigin;\n status: FigmaPushStatus;\n}\n\n/** Library branches opened from Figma components (label from-figma), newest first, with where each stands. */\nexport async function listFigmaChangesOnGitHub(gh: GitHubClient, opts: { state?: 'open' | 'closed' | 'all' } = {}): Promise<FigmaChangeRow[]> {\n const pulls = await gh.listPullRequests(opts.state ?? 'open');\n const out: FigmaChangeRow[] = [];\n for (const p of pulls) {\n if (!p.labels.includes(FROM_FIGMA_LABEL)) continue;\n const origin = parseFigmaOrigin(p.body);\n if (!origin) continue;\n out.push({ number: p.number, title: p.title, url: p.url, branch: p.headRef, origin, status: figmaPushStatus({ state: p.state, draft: p.draft, labels: p.labels, route: origin.route }) });\n }\n return out;\n}\n\n/** One library branch from Figma, its spec and Claude's brief to draft the code. */\nexport async function figmaChangeOnGitHub(gh: GitHubClient, n: number, opts: { componentsDir?: string | undefined } = {}) {\n const pull = await gh.getPullRequest(n);\n const origin = parseFigmaOrigin(pull.body);\n if (!origin) throw new GitHubError(404, `#${n} was not sent from Figma (no \"From Figma\" block in its description).`);\n const status = figmaPushStatus({ state: pull.state, draft: pull.draft, labels: pull.labels, route: origin.route });\n if (origin.route === 'token-change') return { pull, origin, status, spec: undefined, brief: undefined };\n const text = origin.spec ? await gh.getFileText(origin.spec, pull.headSha).catch(() => undefined) : undefined;\n const spec = parseFigmaSpec(text);\n if (!spec) throw new GitHubError(404, `The spec ${origin.spec ?? FIGMA_SPEC_DIR} is missing from ${pull.headRef}. Send the component from Figma again.`);\n const brief = figmaDraftBrief(spec, { pr: n, branch: pull.headRef, specPath: origin.spec!, componentsDir: opts.componentsDir });\n return { pull, origin, status, spec, brief };\n}\n\n/**\n * Claude wrote the code: the branch is labelled drafted by Claude AI (no longer waiting) and its description says so.\n * Refused while the branch only carries the spec, so the label never claims code that is not there.\n */\nexport async function markFigmaChangeDraftedOnGitHub(gh: GitHubClient, n: number): Promise<{ status: FigmaPushStatus; files: string[] }> {\n if (!gh.canWrite) throw new GitHubError(401, 'Marking a branch drafted needs a GitHub token (pull requests: write).');\n const pull = await gh.getPullRequest(n);\n const origin = parseFigmaOrigin(pull.body);\n if (!origin || origin.route !== 'claude-draft') throw new GitHubError(422, `#${n} is not a Claude draft branch from Figma.`);\n if (pull.state !== 'open') throw new GitHubError(422, `#${n} is ${pull.state}: only an open branch is marked drafted.`);\n const files = (await gh.listPullRequestFiles(n)).map((f) => f.filename).filter((f) => !f.startsWith(`${FIGMA_SPEC_DIR}/`));\n if (!files.length) throw new GitHubError(422, `${pull.headRef} only carries the spec: write the component code there first, push it, then mark it drafted.`);\n await gh.updatePullRequest(n, { body: withFigmaOrigin(pull.body, { ...origin, status: 'drafted' }) });\n await gh.removeLabel(n, WAITING_FOR_CLAUDE_LABEL).catch(() => undefined);\n await gh.addLabels(n, [DRAFTED_BY_CLAUDE_LABEL]);\n const labels = [...pull.labels.filter((l) => l !== WAITING_FOR_CLAUDE_LABEL), DRAFTED_BY_CLAUDE_LABEL];\n return { status: figmaPushStatus({ state: pull.state, labels, route: origin.route }), files };\n}\n\n/** Where each pushed Figma component's library branch stands (by pull request number), for the plugin's Pull. */\nexport async function figmaPushStatusesOnGitHub(gh: GitHubClient, numbers: number[]): Promise<Map<number, FigmaPushStatus>> {\n const out = new Map<number, FigmaPushStatus>();\n await Promise.all(\n [...new Set(numbers)].map(async (n) => {\n try {\n const p = await gh.getPullRequest(n);\n out.set(n, figmaPushStatus({ state: p.state, draft: p.draft, labels: p.labels, route: parseFigmaOrigin(p.body)?.route }));\n } catch {\n // Unreadable: the component keeps its Figma version until the next pull reads it.\n }\n }),\n );\n return out;\n}\n","// Reading a deployed (or built) Storybook: its index, grouped into components, and the URLs that show a story.\n// Pure parsing plus one fetch helper over an injected fetch. No DOM, no Node APIs.\n//\n// Index formats:\n// index.json, v4 (Storybook 7) and v5 (8+): { v, entries: { [id]: { id, title, name, type, importPath, tags?, subtype?, exportName?, componentPath? } } }\n// stories.json, v3 (6.4/6.5 with buildStoriesJson, still emitted by some 7 builds):\n// { v, stories: { [id]: { id, title?, kind, name?, story, importPath, parameters?: { docsOnly? } } } }\n\n/** One index entry, normalised across versions. */\nexport interface StorybookEntry {\n id: string;\n /** Sidebar path, `/`-separated (\"Forms/Button\"). */\n title: string;\n /** Story or docs page name (\"Primary\", \"Docs\"). */\n name: string;\n type: 'story' | 'docs';\n /** Storybook 9+ marks test entries `test`; stories are `story`. Absent before. */\n subtype?: string;\n importPath: string;\n tags: string[];\n exportName?: string;\n componentPath?: string;\n}\n\n/** Entries that share a title: one component (or one docs-only page such as \"Intro\"). */\nexport interface StorybookComponent {\n title: string;\n /** Last segment of the title (\"Button\" for \"Forms/Button\"). */\n name: string;\n /** Segments before the name ([\"Forms\"]); empty at the root. */\n group: string[];\n /** Story entries in index order (test entries excluded). */\n stories: StorybookEntry[];\n docs: StorybookEntry[];\n /** Union of the entries' tags, sorted. */\n tags: string[];\n}\n\nexport type StorybookIndexSource = 'index.json' | 'stories.json';\n\nexport interface StorybookIndex {\n /** The index's `v` field. */\n version: number;\n source: StorybookIndexSource;\n entries: StorybookEntry[];\n /** Grouped by title, sorted by title. */\n components: StorybookComponent[];\n}\n\nexport type StorybookErrorCode = 'invalid-url' | 'not-found' | 'not-json' | 'private' | 'empty' | 'http' | 'network';\n\nexport class StorybookIndexError extends Error {\n constructor(\n readonly code: StorybookErrorCode,\n message: string,\n readonly status?: number,\n ) {\n super(message);\n this.name = 'StorybookIndexError';\n }\n}\n\nconst isObj = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);\nconst str = (v: unknown): string | undefined => (typeof v === 'string' && v.trim() ? v : undefined);\n\nfunction entryFrom(key: string, raw: unknown, v3: boolean): StorybookEntry | null {\n if (!isObj(raw)) return null;\n const id = str(raw.id) ?? key;\n const title = str(raw.title) ?? str(raw.kind);\n const name = str(raw.name) ?? str(raw.story);\n if (!id || !title || !name) return null;\n const params = isObj(raw.parameters) ? raw.parameters : {};\n const type: 'story' | 'docs' = raw.type === 'docs' || raw.type === 'story' ? raw.type : v3 && params.docsOnly === true ? 'docs' : 'story';\n const e: StorybookEntry = {\n id,\n title,\n name,\n type,\n importPath: str(raw.importPath) ?? str(params.fileName) ?? '',\n tags: Array.isArray(raw.tags) ? raw.tags.filter((t): t is string => typeof t === 'string') : [],\n };\n const subtype = str(raw.subtype);\n if (subtype) e.subtype = subtype;\n const exportName = str(raw.exportName);\n if (exportName) e.exportName = exportName;\n const componentPath = str(raw.componentPath);\n if (componentPath) e.componentPath = componentPath;\n return e;\n}\n\n/** Groups entries by title. Test entries (subtype `test`) stay out of `stories`. */\nexport function groupStorybookComponents(entries: StorybookEntry[]): StorybookComponent[] {\n const byTitle = new Map<string, StorybookComponent>();\n for (const e of entries) {\n let c = byTitle.get(e.title);\n if (!c) {\n const parts = e.title.split('/').map((p) => p.trim()).filter(Boolean);\n c = { title: e.title, name: parts[parts.length - 1] ?? e.title, group: parts.slice(0, -1), stories: [], docs: [], tags: [] };\n byTitle.set(e.title, c);\n }\n if (e.type === 'docs') c.docs.push(e);\n else if (e.subtype !== 'test') c.stories.push(e);\n for (const t of e.tags) if (!c.tags.includes(t)) c.tags.push(t);\n }\n const out = [...byTitle.values()].filter((c) => c.stories.length || c.docs.length);\n for (const c of out) c.tags.sort();\n return out.sort((a, b) => a.title.localeCompare(b.title));\n}\n\n/**\n * Parses an `index.json` (v4, v5) or `stories.json` (v3) body. Throws StorybookIndexError: `private` for a\n * Chromatic login answer, `empty` when the body has no readable entries.\n */\nexport function parseStorybookIndex(json: unknown, source?: StorybookIndexSource): StorybookIndex {\n if (!isObj(json)) throw new StorybookIndexError('not-json', 'The Storybook index is not a JSON object.');\n if (typeof json.loginUrl === 'string' && !('entries' in json) && !('stories' in json)) {\n throw new StorybookIndexError('private', 'This Storybook is private: it asks for a sign-in before showing its index.');\n }\n const map = isObj(json.entries) ? json.entries : isObj(json.stories) ? json.stories : null;\n if (!map) throw new StorybookIndexError('empty', 'This file has no Storybook entries.');\n const v3 = !isObj(json.entries);\n const entries = Object.entries(map)\n .map(([k, raw]) => entryFrom(k, raw, v3))\n .filter((e): e is StorybookEntry => e !== null);\n if (!entries.length) throw new StorybookIndexError('empty', 'This Storybook index lists no stories or docs.');\n const version = typeof json.v === 'number' ? json.v : v3 ? 3 : 4;\n return { version, source: source ?? (v3 ? 'stories.json' : 'index.json'), entries, components: groupStorybookComponents(entries) };\n}\n\n/**\n * The base address of a Storybook from what a person pastes: trims, drops the query and hash\n * (`?path=/story/...`), a trailing `index.html` / `iframe.html` / `index.json` / `stories.json`, and trailing slashes.\n * Throws `invalid-url` unless it is http(s); https is required except on localhost.\n */\nexport function normalizeStorybookUrl(input: string): string {\n let u: URL;\n try {\n u = new URL(input.trim());\n } catch {\n throw new StorybookIndexError('invalid-url', 'Enter the full Storybook address, for example https://storybook.example.com');\n }\n const local = u.hostname === 'localhost' || u.hostname === '127.0.0.1' || u.hostname === '[::1]';\n if (u.protocol !== 'https:' && !(u.protocol === 'http:' && local)) {\n throw new StorybookIndexError('invalid-url', 'The Storybook address must start with https://');\n }\n if (u.username || u.password) throw new StorybookIndexError('invalid-url', 'Remove the user name and password from the address.');\n const path = u.pathname.replace(/\\/(index\\.html|iframe\\.html|index\\.json|stories\\.json)$/i, '/').replace(/\\/+$/, '');\n return `${u.protocol}//${u.host}${path}`;\n}\n\n/** The index files to try, in order. */\nexport const storybookIndexUrls = (base: string): { url: string; source: StorybookIndexSource }[] => {\n const b = base.replace(/\\/+$/, '');\n return [\n { url: `${b}/index.json`, source: 'index.json' },\n { url: `${b}/stories.json`, source: 'stories.json' },\n ];\n};\n\nexport interface StorybookIframeOptions {\n /** `story` (default) or `docs`. */\n viewMode?: 'story' | 'docs';\n /** Toolbar globals (`globals=brand:ocean;theme:dark`), in insertion order. */\n globals?: Record<string, string>;\n /** Story args (`args=label:Save`). */\n args?: Record<string, string>;\n}\n\n// Storybook reads `key:value;key:value`; keep the separators literal and encode the rest.\nconst pairs = (o: Record<string, string>) =>\n Object.entries(o)\n .map(([k, v]) => `${encodeURIComponent(k)}:${encodeURIComponent(v)}`)\n .join(';');\n\n/** URL of one story (or docs page) rendered alone: `<base>/iframe.html?id=<id>&viewMode=story[&globals=..][&args=..]`. */\nexport function storybookIframeUrl(base: string, id: string, o: StorybookIframeOptions = {}): string {\n let url = `${base.replace(/\\/+$/, '')}/iframe.html?id=${encodeURIComponent(id)}&viewMode=${o.viewMode ?? 'story'}`;\n if (o.globals && Object.keys(o.globals).length) url += `&globals=${pairs(o.globals)}`;\n if (o.args && Object.keys(o.args).length) url += `&args=${pairs(o.args)}`;\n return url;\n}\n\n/** URL of a story or docs page in the full Storybook UI (sidebar and toolbar). */\nexport function storybookManagerUrl(base: string, id: string, viewMode: 'story' | 'docs' = 'story'): string {\n return `${base.replace(/\\/+$/, '')}/?path=/${viewMode}/${encodeURIComponent(id)}`;\n}\n\nexport type StorybookFetch = (url: string, init?: { headers?: Record<string, string>; signal?: AbortSignal }) => Promise<{\n ok: boolean;\n status: number;\n headers: { get(name: string): string | null };\n text(): Promise<string>;\n}>;\n\nexport interface FetchStorybookIndexOptions {\n fetch?: StorybookFetch;\n signal?: AbortSignal;\n}\n\n/**\n * Reads a Storybook's index: `index.json`, then `stories.json`. A 404, an HTML answer (static hosts that fall back\n * to index.html) or a body without entries moves on to the next file; the first readable index wins. Throws\n * StorybookIndexError with the most telling failure (`private` before `not-json` before `not-found`).\n */\nexport async function fetchStorybookIndex(base: string, o: FetchStorybookIndexOptions = {}): Promise<StorybookIndex> {\n const doFetch: StorybookFetch = o.fetch ?? ((url, init) => fetch(url, init));\n const rank: Record<StorybookErrorCode, number> = { private: 6, http: 5, network: 4, empty: 3, 'not-json': 2, 'not-found': 1, 'invalid-url': 0 };\n let worst: StorybookIndexError | null = null;\n const keep = (e: StorybookIndexError) => {\n if (!worst || rank[e.code] > rank[worst.code]) worst = e;\n };\n for (const { url, source } of storybookIndexUrls(base)) {\n let res: Awaited<ReturnType<StorybookFetch>>;\n try {\n res = await doFetch(url, { headers: { accept: 'application/json' }, ...(o.signal ? { signal: o.signal } : {}) });\n } catch (err) {\n if (o.signal?.aborted) throw err;\n keep(new StorybookIndexError('network', `Could not reach ${url}. The host may be down or may not allow reading from another site.`));\n continue;\n }\n if (res.status === 404 || res.status === 410) {\n keep(new StorybookIndexError('not-found', `No Storybook index at ${base}: neither index.json nor stories.json was found.`, res.status));\n continue;\n }\n if (res.status === 401 || res.status === 403) {\n keep(new StorybookIndexError('private', 'This Storybook is private: it asks for a sign-in before showing its index.', res.status));\n continue;\n }\n if (!res.ok) {\n keep(new StorybookIndexError('http', `The Storybook host answered ${res.status} for ${url}.`, res.status));\n continue;\n }\n const text = await res.text();\n let json: unknown;\n try {\n json = JSON.parse(text);\n } catch {\n keep(new StorybookIndexError('not-json', `${url} is not a Storybook index (the host answered with a web page).`));\n continue;\n }\n try {\n return parseStorybookIndex(json, source);\n } catch (err) {\n if (err instanceof StorybookIndexError) keep(err);\n else throw err;\n }\n }\n throw worst ?? new StorybookIndexError('not-found', `No Storybook index at ${base}.`);\n}\n","// Token rows for documentation pages: one record per token with the full alias chain\n// (component -> semantic -> brand palette role -> primitive -> resolved value), per brand x theme (and density).\n// Moved from the docs site (apps/docs-site/src/lib/tokens.ts) so the build and the browser share one reader.\n// Every folder comes from bridge.config.json (tokens.root and the tier folders), never from a hardcoded path.\n// Resolution order mirrors packages/tokens/build.mjs. Pure: takes file bodies, reads nothing itself.\n\nimport { tokensPath, type BridgeConfig } from './config';\n\n/** Token tiers of the rows, in resolution order: primitive <- brand <- semantic <- component. Density sits beside semantic. */\nexport type TokenRowTier = 'primitive' | 'brand' | 'semantic' | 'density' | 'component';\n\ntype Json = Record<string, unknown>;\n\nexport interface RawTokenEntry {\n path: string[];\n type: string;\n value: unknown;\n description?: string;\n /** DTCG $deprecated: true, or a string explaining what to use instead. */\n deprecated?: boolean | string;\n /** Repo-relative file the token is declared in. */\n file: string;\n}\n\nexport interface PrimitiveRow {\n path: string;\n segments: string[];\n type: string;\n /** Resolved CSS value. */\n css: string;\n hex?: string;\n cssVar: string;\n figma: string;\n description?: string;\n deprecated?: boolean | string;\n raw: unknown;\n file: string;\n}\n\nexport interface TokenRowMode {\n /** First alias target, or null when the value is literal. */\n alias: string | null;\n /** Every alias hop, from the token to the final primitive (palette roles included). */\n chain: string[];\n css: string;\n hex?: string;\n}\n\nexport interface TokenRow {\n path: string;\n segments: string[];\n type: string;\n cssVar: string;\n figma: string;\n description?: string;\n /** e.g. \"color.action\" or \"elevation\". */\n group: string;\n deprecated?: boolean | string;\n tier: Exclude<TokenRowTier, 'primitive'>;\n /** Source file(s) the token is declared in, repo-relative. */\n file: string;\n /** Values per theme in the default brand and default density. */\n modes: Record<string, TokenRowMode>;\n /** Values per brand x theme (default density). */\n brands: Record<string, Record<string, TokenRowMode>>;\n /** Density tokens only: value per density. */\n densities?: Record<string, TokenRowMode>;\n /** True when the brand x theme values differ from the default brand. */\n brandSpecific: boolean;\n}\n\n/** Brand, theme and density lists the rows are computed for, with their defaults and display names. */\nexport interface TokenRowAxes {\n brands: string[];\n defaultBrand: string;\n /** Display name per brand: the name a brand file records ($extensions dev.bridge.brand.name), else the slug in title case. */\n brandLabels: Record<string, string>;\n themes: string[];\n densities: string[];\n defaultDensity: string;\n}\n\n/** Repo-relative token files the rows read, from the tier folders of the config. */\nexport interface TokenRowFiles {\n primitivesDir: string;\n semanticDir: string;\n brandsDir: string;\n densityDir: string;\n componentsDir: string;\n baseFile: string;\n semanticFile(theme: string): string;\n brandFile(brand: string): string;\n overrideFile(brand: string, theme: string): string;\n densityFile(density: string): string;\n}\n\nexport interface TokenRows extends TokenRowAxes {\n primitives: PrimitiveRow[];\n /** Semantic tier: themed (one file per theme) and theme-independent (base). */\n semantic: TokenRow[];\n /** Brand tier: palette, radius and font roles per brand. */\n brand: TokenRow[];\n density: TokenRow[];\n component: TokenRow[];\n /** Every non-primitive token: brand, semantic, density, component. */\n all: TokenRow[];\n /** Repo-relative paths of every token source file, in tier order (what the \"last updated\" line watches). */\n sources: string[];\n}\n\n// Today's values, used when bridge.config.json names no axis (the docs site's fallbacks).\nconst FALLBACK_BRANDS = ['bridge', 'ocean'];\nconst FALLBACK_THEMES = ['light', 'dark'];\nconst FALLBACK_DENSITIES = ['comfortable', 'compact'];\n\n/** Brand, theme and density lists from bridge.config.json, as the docs pages iterate them. */\nexport function tokenRowAxes(config: BridgeConfig, readText: (path: string) => string | undefined = () => undefined): TokenRowAxes {\n const brandAxis = config.axes.brand;\n const brands = brandAxis?.values.length ? [...brandAxis.values] : [...FALLBACK_BRANDS];\n const defaultBrand = brandAxis?.default ?? brands[0]!;\n const themes = config.modes.themes.length ? [...config.modes.themes] : [...FALLBACK_THEMES];\n const densities = config.modes.densities.length ? [...config.modes.densities] : [...FALLBACK_DENSITIES];\n const files = tokenRowFiles(config);\n const brandName = (b: string): string => {\n try {\n const text = readText(files.brandFile(b));\n const name = text ? (JSON.parse(text) as { $extensions?: Record<string, { name?: unknown }> }).$extensions?.['dev.bridge.brand']?.name : undefined;\n if (typeof name === 'string' && name) return name;\n } catch {\n /* unreadable brand file: fall back to the slug */\n }\n return b\n .split('-')\n .map((w) => w.charAt(0).toUpperCase() + w.slice(1))\n .join(' ');\n };\n return {\n brands,\n defaultBrand,\n brandLabels: Object.fromEntries(brands.map((b) => [b, brandName(b)])),\n themes,\n densities,\n defaultDensity: config.modes.defaults.density ?? densities[0]!,\n };\n}\n\n/** The token files of each tier, repo-relative, from the config's tokens.root and tier folders. */\nexport function tokenRowFiles(config: BridgeConfig): TokenRowFiles {\n const t = config.tokens;\n const at = (rel: string) => tokensPath(config, rel);\n return {\n primitivesDir: at(t.primitives),\n semanticDir: at(t.semantic),\n brandsDir: at(t.brands),\n densityDir: at(t.density),\n componentsDir: at(t.components),\n baseFile: at(`${t.semantic}/${t.base}.tokens.json`),\n semanticFile: (theme) => at(`${t.semantic}/${theme}.tokens.json`),\n brandFile: (brand) => at(`${t.brands}/${brand}.tokens.json`),\n overrideFile: (brand, theme) => at(`${t.brands}/${brand}.${theme}.tokens.json`),\n densityFile: (density) => at(`${t.density}/${density}.tokens.json`),\n };\n}\n\n/** Flattens one DTCG document into raw tokens, inheriting $type from groups. */\nexport function flattenTokenFile(node: Json, file: string, path: string[] = [], inheritedType = ''): RawTokenEntry[] {\n const type = (node.$type as string) ?? inheritedType;\n if ('$value' in node) {\n return [\n {\n path,\n type,\n value: node.$value,\n description: node.$description as string | undefined,\n deprecated: node.$deprecated as boolean | string | undefined,\n file,\n },\n ];\n }\n const out: RawTokenEntry[] = [];\n for (const [key, child] of Object.entries(node)) {\n if (key.startsWith('$') || typeof child !== 'object' || child === null) continue;\n out.push(...flattenTokenFile(child as Json, file, [...path, key], type));\n }\n return out;\n}\n\nconst toHex2 = (n: number) =>\n Math.round(n * 255)\n .toString(16)\n .padStart(2, '0');\n\nfunction colorCss(c: unknown): { css: string; hex?: string } {\n if (typeof c === 'string') return { css: c, hex: /^#[0-9a-f]{6}$/i.test(c) ? c.toLowerCase() : undefined };\n const v = c as { components: number[]; alpha?: number; hex?: string };\n const [r = 0, g = 0, b = 0] = v.components;\n const hex = (v.hex ?? `#${[r, g, b].map(toHex2).join('')}`).toLowerCase();\n const alpha = v.alpha ?? 1;\n if (alpha < 1) return { css: `rgb(${[r, g, b].map((x) => Math.round(x * 255)).join(' ')} / ${alpha})`, hex };\n return { css: hex, hex };\n}\n\nconst dimCss = (d: unknown) => (typeof d === 'object' && d !== null ? `${(d as { value: number }).value}${(d as { unit: string }).unit}` : String(d));\n\nfunction shadowCss(s: unknown): string {\n if (typeof s === 'string') return s;\n const layers = (Array.isArray(s) ? s : [s]) as Array<Record<string, unknown>>;\n return layers\n .map((l) => [l.inset ? 'inset' : '', dimCss(l.offsetX), dimCss(l.offsetY), dimCss(l.blur), dimCss(l.spread), colorCss(l.color).css].filter(Boolean).join(' '))\n .join(', ');\n}\n\n/** CSS text (and hex for colors) of a literal DTCG value. */\nexport function tokenValueCss(type: string, value: unknown): { css: string; hex?: string } {\n switch (type) {\n case 'color':\n return colorCss(value);\n case 'dimension':\n case 'duration':\n return { css: dimCss(value) };\n case 'shadow':\n return { css: shadowCss(value) };\n case 'cubicBezier':\n return { css: Array.isArray(value) ? `cubic-bezier(${value.join(', ')})` : String(value) };\n case 'fontFamily':\n return { css: Array.isArray(value) ? value.map((n) => (/\\s/.test(n) ? `\"${n}\"` : n)).join(', ') : String(value) };\n default:\n return { css: String(value) };\n }\n}\n\n/** CSS variable of a token path (\"color.bg.default\" segments -> \"--color-bg-default\"). */\nexport const tokenRowCssVar = (segments: string[]) => `--${segments.join('-')}`;\n/** Figma variable name of a token path. */\nexport const tokenRowFigmaName = (segments: string[]) => segments.join('/');\n\nconst isAlias = (v: unknown): v is string => typeof v === 'string' && /^\\{[^}]+\\}$/.test(v);\n\n/**\n * Builds the rows from the token files of a repo. `readText` returns a repo-relative file body (undefined when\n * missing); `listFiles` returns the repo-relative files directly inside a directory. Throws on an alias that does not\n * resolve and on a themed token missing from another theme, as the token build does.\n */\nexport function buildTokenRows(config: BridgeConfig, readText: (path: string) => string | undefined, listFiles: (dir: string) => string[]): TokenRows {\n const axes = tokenRowAxes(config, readText);\n const { brands: BRANDS, defaultBrand: DEFAULT_BRAND, themes: MODES, densities: DENSITIES, defaultDensity: DEFAULT_DENSITY } = axes;\n const files = tokenRowFiles(config);\n const REF_THEME = MODES[0]!;\n\n const jsonFiles = (dir: string) =>\n listFiles(dir)\n .filter((f) => f.endsWith('.tokens.json'))\n .sort();\n const flatCache = new Map<string, RawTokenEntry[]>();\n const flatFile = (f: string): RawTokenEntry[] => {\n if (!flatCache.has(f)) {\n const text = readText(f);\n flatCache.set(f, text === undefined ? [] : flattenTokenFile(JSON.parse(text) as Json, f));\n }\n return flatCache.get(f)!;\n };\n const byPathOf = (tokens: RawTokenEntry[]) => new Map(tokens.map((t) => [t.path.join('.'), t]));\n\n const primitiveFiles = jsonFiles(files.primitivesDir);\n const componentFiles = jsonFiles(files.componentsDir);\n const sources = [\n ...primitiveFiles,\n ...jsonFiles(files.brandsDir),\n ...MODES.map(files.semanticFile),\n files.baseFile,\n ...jsonFiles(files.densityDir),\n ...componentFiles,\n ];\n\n const primitives: PrimitiveRow[] = primitiveFiles\n .flatMap((f) => flatFile(f))\n .map((t) => {\n const { css, hex } = tokenValueCss(t.type, t.value);\n return {\n path: t.path.join('.'),\n segments: t.path,\n type: t.type,\n css,\n hex,\n cssVar: tokenRowCssVar(t.path),\n figma: tokenRowFigmaName(t.path),\n description: t.description,\n deprecated: t.deprecated,\n raw: t.value,\n file: t.file,\n };\n });\n const primByPath = new Map(primitives.map((p) => [p.path, p]));\n\n const brandRaw = Object.fromEntries(BRANDS.map((b) => [b, flatFile(files.brandFile(b))]));\n const themeRaw = Object.fromEntries(MODES.map((m) => [m, flatFile(files.semanticFile(m))]));\n const baseRaw = flatFile(files.baseFile);\n const densityRaw = Object.fromEntries(DENSITIES.map((d) => [d, flatFile(files.densityFile(d))]));\n const componentRaw = componentFiles.flatMap((f) => flatFile(f));\n\n // Lookup layers for one combination, highest priority first (mirrors packages/tokens/build.mjs).\n const layerCache = new Map<string, Map<string, RawTokenEntry>[]>();\n const layers = (b: string, m: string, d: string) => {\n const k = `${b}.${m}.${d}`;\n if (!layerCache.has(k))\n layerCache.set(k, [\n byPathOf(flatFile(files.overrideFile(b, m))),\n byPathOf(themeRaw[m] ?? []),\n byPathOf(baseRaw),\n byPathOf(densityRaw[d] ?? []),\n byPathOf(componentRaw),\n byPathOf(brandRaw[b] ?? []),\n ]);\n return layerCache.get(k)!;\n };\n\n const resolve = (b: string, m: string, d: string, value: unknown, type: string): TokenRowMode => {\n const chain: string[] = [];\n let current = value;\n let currentType = type;\n let guard = 0;\n while (isAlias(current) && guard++ < 30) {\n const target = current.slice(1, -1);\n chain.push(target);\n const prim = primByPath.get(target);\n if (prim) return { alias: chain[0] ?? null, chain, css: prim.css, hex: prim.hex };\n const hit = layers(b, m, d)\n .map((l) => l.get(target))\n .find(Boolean);\n if (!hit) throw new Error(`tokens: alias {${target}} does not resolve in ${b} ${m} ${d}`);\n current = hit.value;\n currentType = hit.type || currentType;\n }\n const { css, hex } = tokenValueCss(currentType, current);\n return { alias: chain[0] ?? null, chain, css, hex };\n };\n\n const same = (a: TokenRowMode, c: TokenRowMode) => a.css === c.css && a.chain.join() === c.chain.join();\n\n /** Builds one documented token. `valueFor` returns the raw token for a brand x theme (x density). */\n const build = (t: RawTokenEntry, tier: TokenRow['tier'], valueFor: (b: string, m: string, d: string) => RawTokenEntry | undefined): TokenRow => {\n const at = (b: string, m: string, d: string = DEFAULT_DENSITY) => {\n const raw = valueFor(b, m, d) ?? t;\n return resolve(b, m, d, raw.value, raw.type || t.type);\n };\n const brands = Object.fromEntries(BRANDS.map((b) => [b, Object.fromEntries(MODES.map((m) => [m, at(b, m)]))])) as Record<string, Record<string, TokenRowMode>>;\n return {\n path: t.path.join('.'),\n segments: t.path,\n type: t.type,\n cssVar: tokenRowCssVar(t.path),\n figma: tokenRowFigmaName(t.path),\n description: t.description,\n group: t.path[0] === 'color' ? t.path.slice(0, 2).join('.') : t.path[0]!,\n deprecated: t.deprecated,\n tier,\n file: t.file,\n modes: brands[DEFAULT_BRAND]!,\n brands,\n densities: tier === 'density' ? Object.fromEntries(DENSITIES.map((d) => [d, at(DEFAULT_BRAND, REF_THEME, d)])) : undefined,\n brandSpecific: BRANDS.some((b) => MODES.some((m) => !same(brands[b]![m]!, brands[DEFAULT_BRAND]![m]!))),\n };\n };\n\n const brand = (brandRaw[DEFAULT_BRAND] ?? []).map((t) => build(t, 'brand', (b) => byPathOf(brandRaw[b] ?? []).get(t.path.join('.'))));\n\n // Themed semantic tokens: the first theme is the reference, every other theme must define the same paths.\n const themedBy = Object.fromEntries(MODES.map((m) => [m, byPathOf(themeRaw[m] ?? [])]));\n const themed = (themeRaw[REF_THEME] ?? []).map((t) => {\n const path = t.path.join('.');\n const others = MODES.slice(1).map((m) => {\n const hit = themedBy[m]!.get(path);\n if (!hit) throw new Error(`tokens: semantic token ${path} is missing in ${files.semanticFile(m)}`);\n return hit;\n });\n const s = build(t, 'semantic', (b, m) => byPathOf(flatFile(files.overrideFile(b, m))).get(path) ?? (m === REF_THEME ? t : themedBy[m]!.get(path)));\n s.description = [t, ...others].map((x) => x.description).find((x) => x !== undefined);\n s.deprecated = [t, ...others].map((x) => x.deprecated).find((x) => x !== undefined);\n s.file = MODES.map(files.semanticFile).join(', ');\n return s;\n });\n const base = baseRaw.map((t) => build(t, 'semantic', () => t));\n const semantic = [...themed, ...base];\n\n const density = (densityRaw[DEFAULT_DENSITY] ?? []).map((t) => build(t, 'density', (_b, _m, d) => byPathOf(densityRaw[d] ?? []).get(t.path.join('.'))));\n const component = componentRaw.map((t) => build(t, 'component', () => t));\n\n return { ...axes, primitives, semantic, brand, density, component, all: [...brand, ...semantic, ...density, ...component], sources };\n}\n\n/** Every CSS variable the rows define: cssVar -> token path, tier and type. */\nexport function tokenRowIndex(rows: Pick<TokenRows, 'primitives' | 'all'>): Map<string, { path: string; kind: TokenRowTier; type: string }> {\n const map = new Map<string, { path: string; kind: TokenRowTier; type: string }>();\n for (const p of rows.primitives) map.set(p.cssVar, { path: p.path, kind: 'primitive', type: p.type });\n for (const s of rows.all) map.set(s.cssVar, { path: s.path, kind: s.tier, type: s.type });\n return map;\n}\n","// WCAG 2.2 contrast of the foreground/background pairs the token build gates on (bridge.config.json contrast.path),\n// for every brand x theme of the token rows, so pages show exactly what the build enforces. Moved from the docs site\n// (apps/docs-site/src/lib/contrast.ts). Pure: takes the checks file text and the rows.\n\nimport type { TokenRow, TokenRows } from './token-rows';\n\nexport interface ContrastPairSpec {\n fg: string;\n bg: string;\n usage: 'text' | 'ui';\n /** Minimum ratio the build enforces for this pair. */\n min: number;\n}\n\nexport interface ContrastModeResult {\n fgHex: string;\n bgHex: string;\n /** Rounded down to 2 decimals, so 4.496 never displays as a passing 4.50. */\n ratio: number;\n aa: boolean;\n /** null when AAA is not defined (non-text UI). */\n aaa: boolean | null;\n}\n\nexport interface ContrastPairResult extends ContrastPairSpec {\n fgToken: TokenRow;\n bgToken: TokenRow;\n /** Default brand, per theme. */\n modes: Record<string, ContrastModeResult>;\n brands: Record<string, Record<string, ContrastModeResult>>;\n}\n\n/** WCAG thresholds: body text 4.5:1 (AA) and 7:1 (AAA); UI parts and graphics 3:1 (AA, 1.4.11). */\nexport const CONTRAST_THRESHOLDS = { text: { aa: 4.5, aaa: 7 }, ui: { aa: 3, aaa: null } } as const;\n\nconst channel = (c: number) => {\n const s = c / 255;\n return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;\n};\n\n/** Relative luminance of a #rrggbb color. */\nexport function hexLuminance(hex: string): number {\n const n = parseInt(hex.slice(1), 16);\n return 0.2126 * channel((n >> 16) & 255) + 0.7152 * channel((n >> 8) & 255) + 0.0722 * channel(n & 255);\n}\n\n/** Contrast ratio of two opaque #rrggbb colors. */\nexport function hexContrastRatio(a: string, b: string): number {\n const [hi, lo] = [hexLuminance(a), hexLuminance(b)].sort((x, y) => y - x) as [number, number];\n return (hi + 0.05) / (lo + 0.05);\n}\n\n/** The pairs of a contrast checks file ({ \"pairs\": [[fg, bg, min] | { fg, bg, min }] }). Empty when there is no file. */\nexport function parseContrastSpecs(text: string | null | undefined): ContrastPairSpec[] {\n if (!text) return [];\n const data = JSON.parse(text) as { pairs?: Array<[string, string, number] | { fg: string; bg: string; min: number }> };\n return (data.pairs ?? []).map((p) => {\n const [fg, bg, min] = Array.isArray(p) ? p : [p.fg, p.bg, p.min];\n return { fg, bg, min, usage: min >= CONTRAST_THRESHOLDS.text.aa ? 'text' : 'ui' };\n });\n}\n\n/** Resolves pair specs against the token rows in every brand and theme. Throws on a pair naming a missing token. */\nexport function evaluateContrastPairs(specs: ContrastPairSpec[], rows: Pick<TokenRows, 'all' | 'brands' | 'themes' | 'defaultBrand'>): ContrastPairResult[] {\n const byPath = new Map(rows.all.map((s) => [s.path, s]));\n return specs.map((spec) => {\n const fgToken = byPath.get(spec.fg);\n const bgToken = byPath.get(spec.bg);\n if (!fgToken || !bgToken) throw new Error(`contrast: pair ${spec.fg} on ${spec.bg} references a token that does not exist`);\n const t = CONTRAST_THRESHOLDS[spec.usage];\n const result = (b: string, m: string): ContrastModeResult => {\n const fgHex = fgToken.brands[b]![m]!.hex!;\n const bgHex = bgToken.brands[b]![m]!.hex!;\n const r = hexContrastRatio(fgHex, bgHex);\n return { fgHex, bgHex, ratio: Math.floor(r * 100) / 100, aa: r >= spec.min, aaa: t.aaa === null ? null : r >= t.aaa };\n };\n const brands = Object.fromEntries(rows.brands.map((b) => [b, Object.fromEntries(rows.themes.map((m) => [m, result(b, m)]))])) as Record<string, Record<string, ContrastModeResult>>;\n return { ...spec, fgToken, bgToken, modes: brands[rows.defaultBrand]!, brands };\n });\n}\n","// Component data for docs, from the files that already sit next to each component (moved from the docs site,\n// apps/docs-site/src/lib/components.ts):\n// <Name>.tsx props, defaults, JSDoc, sub-components (regex parsers: React + TypeScript only)\n// <Name><styleSuffix> which tokens each part and state uses\n// <Name>.stories.tsx Storybook story ids for the live preview\n// <Name><docsSuffix> usage guidance a parser cannot know (written by designers)\n// The components folder, the suffixes and the barrel file come from bridge.config.json (components.*).\n// Pure: takes file bodies, reads nothing itself.\n\nimport type { ProseKey } from './docs-draft';\nimport type { TokenRowTier } from './token-rows';\n\nexport type ExampleNode = string | { c: string; p?: Record<string, unknown>; children?: ExampleNode[] };\n\nexport interface GuidanceItem {\n title: string;\n text: string;\n example?: ExampleNode;\n}\n\n/** <Name>.docs.json. */\nexport interface ComponentDocs {\n summary: string;\n /** Navigation group. Optional; components without one are listed under \"Core\". */\n category?: string;\n /** Lifecycle shown on the component page and in the nav: stable (default), beta, deprecated. */\n status?: 'stable' | 'beta' | 'deprecated';\n preview?: ExampleNode;\n whenToUse: string[];\n whenNotToUse: string[];\n dos: GuidanceItem[];\n donts: GuidanceItem[];\n accessibility: string[];\n contentGuidelines?: string[];\n anatomy?: Record<string, string>;\n /** \"claude\" when an AI drafted the prose (docs-draft Action, bridge_draft_docs). */\n draftedBy?: string;\n /** Prose sections Claude drafted that wait for review, when a draft covered only some (missing: the whole file). */\n draftedSections?: ProseKey[];\n /** True while drafted prose waits for a reviewer. */\n needsReview?: boolean;\n}\n\nexport interface ComponentProp {\n name: string;\n type: string;\n required: boolean;\n defaultValue?: string;\n description?: string;\n}\n\n/** What the scan knows about a CSS variable: the token it is, and an optional docs link (the caller's routing). */\nexport interface ComponentVar {\n name: string;\n href?: string;\n known: boolean;\n path?: string;\n kind?: TokenRowTier;\n}\n\nexport interface ComponentCssRule {\n selector: string;\n /** First class in the selector, used for the anatomy label. */\n className: string;\n label: string;\n vars: ComponentVar[];\n}\n\nexport interface ScannedComponent {\n name: string;\n slug: string;\n /** Repo-relative folder. */\n dir: string;\n /** Repo-relative files (they may not all exist). */\n files: { tsx: string; css: string; stories: string; docs: string };\n description?: string;\n props: ComponentProp[];\n inherits?: string;\n omitted: string[];\n subcomponents: string[];\n rules: ComponentCssRule[];\n tokensUsed: { name: string; href?: string; known: boolean; kind?: string }[];\n /** Paths of the tokens its own stylesheet reads, in every tier. */\n tokenPaths: string[];\n /**\n * Tokens it reads through another component's stylesheet it imports (IconButton imports Button.module.css), by\n * that component, without the ones its own stylesheet already reads. Followed transitively.\n */\n inherited: { from: string; slug: string; paths: string[] }[];\n /** Own and inherited token paths: what the component actually paints with. */\n allTokenPaths: string[];\n stories: { name: string; id: string }[];\n docs: ComponentDocs | null;\n /** Family from docs.json `category`, else from the grouped exports of the barrel file. */\n category: string;\n}\n\n/** \"IconButton\" -> \"icon-button\". */\nexport const componentSlug = (s: string) =>\n s\n .replace(/([a-z0-9])([A-Z])/g, '$1-$2')\n .replace(/([A-Z])([A-Z][a-z])/g, '$1-$2')\n .toLowerCase();\n\nconst escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n/**\n * Families in the order the barrel file lists them (\"// Actions\" then its exports). `componentsRel` is the components\n * folder relative to the barrel's folder (\"components\"); exports from elsewhere are not members.\n */\nexport function parseComponentFamilies(indexSrc: string, componentsRel = 'components'): { name: string; members: string[] }[] {\n const out: { name: string; members: string[] }[] = [];\n const exportRe = new RegExp(`export \\\\* from '\\\\./${escapeRe(componentsRel)}/(\\\\w+)'`);\n for (const line of indexSrc.split('\\n')) {\n const head = line.match(/^\\/\\/\\s*([A-Z][\\w ]+)$/);\n if (head) out.push({ name: head[1]!.trim(), members: [] });\n const exp = line.match(exportRe);\n if (exp && out.length) out[out.length - 1]!.members.push(exp[1]!);\n }\n return out.filter((f) => f.members.length);\n}\n\nconst NATIVE: Record<string, string> = {\n HTMLButtonElement: 'button',\n HTMLInputElement: 'input',\n HTMLSpanElement: 'span',\n HTMLDivElement: 'div',\n HTMLAnchorElement: 'a',\n};\n\nfunction parseExtends(clause: string) {\n const el = clause.match(/<(HTML\\w+Element)>/)?.[1];\n const omitted = [...(clause.match(/Omit<[^,]+,\\s*([^>]+)>/)?.[1] ?? '').matchAll(/'([^']+)'/g)].map((m) => m[1]!);\n return { inherits: el ? (NATIVE[el] ?? el) : undefined, omitted };\n}\n\n/** Props (with defaults and JSDoc), the native element it extends, its description and sub-components, from <Name>.tsx. */\nexport function parseComponentTsx(\n name: string,\n src: string,\n): { props: ComponentProp[]; inherits: string | undefined; omitted: string[]; description: string | undefined; subcomponents: string[] } {\n const aliases = new Map<string, string>();\n for (const m of src.matchAll(/export type (\\w+)\\s*=\\s*([^;]+);/g)) aliases.set(m[1]!, m[2]!.trim());\n\n let props: ComponentProp[] = [];\n let inherits: string | undefined;\n let omitted: string[] = [];\n\n const iface = src.match(new RegExp(`export interface ${name}Props(?:\\\\s+extends\\\\s+([^{]+))?\\\\s*\\\\{([\\\\s\\\\S]*?)\\\\n\\\\}`));\n if (iface) {\n ({ inherits, omitted } = parseExtends(iface[1] ?? ''));\n for (const m of iface[2]!.matchAll(/(?:\\/\\*\\*([\\s\\S]*?)\\*\\/\\s*)?(\\w+)(\\?)?:\\s*([^;]+);/g)) {\n const rawType = m[4]!.trim();\n props.push({\n name: m[2]!,\n type: aliases.get(rawType) ?? rawType,\n required: !m[3],\n description:\n m[1]\n ?.replace(/^\\s*\\*\\s?/gm, '')\n .replace(/\\s+/g, ' ')\n .trim() || undefined,\n });\n }\n } else {\n const alias = aliases.get(`${name}Props`);\n if (alias) ({ inherits, omitted } = parseExtends(alias));\n }\n\n // Defaults come from the destructuring in the component signature: `{ variant = 'primary', ... }`.\n const sig = src.match(new RegExp(`function ${name}\\\\(\\\\s*\\\\{([^}]*)\\\\}`));\n if (sig) {\n for (const m of sig[1]!.matchAll(/(\\w+)\\s*=\\s*('[^']*'|[\\w.]+)/g)) {\n const p = props.find((x) => x.name === m[1]);\n if (p) p.defaultValue = m[2];\n }\n }\n\n // The JSDoc block that ends right before the match: the last comment of what precedes it, only when it opens with\n // \"/**\". Matching the whole prefix used to start at the first JSDoc of the file, so the JSDoc of a props interface\n // and the code after it leaked into the component description.\n const docBefore = (re: RegExp) => {\n const idx = src.search(re);\n if (idx < 0) return undefined;\n const before = src.slice(0, idx).trimEnd();\n if (!before.endsWith('*/')) return undefined;\n const start = before.lastIndexOf('/*', before.length - 2);\n if (start < 0 || before[start + 2] !== '*') return undefined;\n return before\n .slice(start + 3, -2)\n .replace(/^\\s*\\*\\s?/gm, '')\n .replace(/\\s+/g, ' ')\n .trim();\n };\n const description = docBefore(new RegExp(`export (?:function|const) ${name}\\\\b`));\n const subcomponents = [...src.matchAll(/export function (\\w+)/g)].map((m) => m[1]!).filter((n) => n !== name);\n props = props.sort((a, b) => Number(b.required) - Number(a.required));\n return { props, inherits, omitted, description, subcomponents };\n}\n\nconst stateOf = (selector: string) => {\n const states = [\n [/:focus-visible/, 'focus'],\n [/:hover/, 'hover'],\n [/:disabled(?!,)|^[^(]*:disabled/, 'disabled'],\n [/\\[data-loading\\]/, 'loading'],\n [/::placeholder/, 'placeholder'],\n ] as const;\n const hit = states.filter(([re]) => re.test(selector)).map(([, s]) => s);\n return hit.length ? `, ${hit.join(' + ')}` : '';\n};\n\n/** CSS variables Base UI sets at runtime (positioning, measured heights, swipe) and private --_* locals. Not tokens. */\nconst BASE_UI_RUNTIME = /^--(_|accordion-panel-|collapsible-panel-|active-tab-|anchor-|available-|drawer-swipe-|toast-(frontmost-height|height|index|offset-y|swipe-)|transform-origin)/;\n\n/**\n * Minimal CSS reader: selector -> var(--*) list, labelled with the docs.json anatomy. Skips @keyframes, flattens\n * @media. `describe` says what a variable is (token path, tier, docs link); undefined: not a token.\n */\nexport function parseComponentCss(src: string, labels: Record<string, string>, describe: (cssVar: string) => Omit<ComponentVar, 'name' | 'known'> | undefined): ComponentCssRule[] {\n const clean = src.replace(/\\/\\*[\\s\\S]*?\\*\\//g, '');\n const rules: ComponentCssRule[] = [];\n const walk = (text: string, prefix = ''): void => {\n let i = 0;\n let buf = '';\n while (i < text.length) {\n const ch = text[i]!;\n if (ch === '{') {\n const head = buf.trim();\n buf = '';\n let depth = 1;\n const start = ++i;\n while (i < text.length && depth > 0) {\n if (text[i] === '{') depth++;\n else if (text[i] === '}') depth--;\n i++;\n }\n const inner = text.slice(start, i - 1);\n if (head.startsWith('@keyframes')) continue;\n if (head.startsWith('@')) {\n walk(inner, `${head} `);\n continue;\n }\n const names = [...new Set([...inner.matchAll(/var\\((--[\\w-]+)/g)].map((m) => m[1]!))].filter((n) => !BASE_UI_RUNTIME.test(n));\n if (!names.length) continue;\n const className = head.match(/\\.([\\w-]+)/)?.[1] ?? head;\n rules.push({\n selector: prefix + head.replace(/\\s+/g, ' '),\n className,\n label: (labels[className] ?? className) + stateOf(head),\n vars: names.map((n) => {\n const d = describe(n);\n return { name: n, href: d?.href, known: !!d, path: d?.path, kind: d?.kind };\n }),\n });\n } else {\n buf += ch;\n i++;\n }\n }\n };\n walk(clean);\n return rules;\n}\n\n/** Story names and Storybook ids of a <Name>.stories.tsx (CSF with a `title`). */\nexport function parseComponentStories(src: string): { name: string; id: string }[] {\n const title = src.match(/title:\\s*'([^']+)'/)?.[1];\n if (!title) return [];\n const base = title\n .split('/')\n .map((s) => componentSlug(s.trim()).replace(/\\s+/g, '-'))\n .join('-');\n return [...src.matchAll(/export const (\\w+):\\s*Story/g)].map((m) => ({ name: m[1]!, id: `${base}--${componentSlug(m[1]!)}` }));\n}\n\n/**\n * Fills `inherited` and `allTokenPaths` from the stylesheets each component imports from another component,\n * transitively (A imports B's stylesheet, B imports C's: A inherits from B and C). Removes `reuses`.\n */\nexport function resolveInheritedTokens(list: (Pick<ScannedComponent, 'name' | 'slug' | 'tokenPaths' | 'inherited' | 'allTokenPaths'> & { reuses?: string[] })[]): void {\n const byName = new Map(list.map((c) => [c.name, c]));\n for (const c of list) {\n const seen = new Set<string>([c.name]);\n const queue = [...(c.reuses ?? [])];\n const inherited: ScannedComponent['inherited'] = [];\n const taken = new Set(c.tokenPaths);\n while (queue.length) {\n const from = byName.get(queue.shift()!);\n if (!from || seen.has(from.name)) continue;\n seen.add(from.name);\n const paths = from.tokenPaths.filter((p) => !taken.has(p));\n paths.forEach((p) => taken.add(p));\n inherited.push({ from: from.name, slug: from.slug, paths });\n queue.push(...(from.reuses ?? []));\n }\n c.inherited = inherited;\n c.allTokenPaths = [...taken].sort();\n }\n for (const c of list) delete c.reuses;\n}\n\nexport interface ComponentScanInput {\n /** Components folder, repo-relative (bridge.config.json components.dir). */\n dir: string;\n /** Every repo-relative file under `dir` (RepoSource.list(dir)). */\n files: string[];\n /** Body of a repo-relative file, undefined when missing. */\n readText: (path: string) => string | undefined;\n /** Barrel file body (components.index), for families. Undefined: no families. */\n indexText?: string | undefined;\n /** Components folder relative to the barrel's folder. Default \"components\". */\n indexRel?: string;\n docsSuffix?: string;\n styleSuffix?: string;\n /** What a CSS variable is (token path, tier, docs link). Undefined: not a token. */\n describeVar: (cssVar: string) => Omit<ComponentVar, 'name' | 'known'> | undefined;\n /** Problems found (a docs.json that does not parse) are reported here instead of failing the scan. */\n problems?: string[];\n}\n\n/**\n * Every component of the folder: a sub-folder <Name> holding <Name>.tsx. Sorted by family (barrel order), then name.\n */\nexport function scanComponents(input: ComponentScanInput): ScannedComponent[] {\n const { dir, readText, describeVar } = input;\n const docsSuffix = input.docsSuffix ?? '.docs.json';\n const styleSuffix = input.styleSuffix ?? '.module.css';\n const fileSet = new Set(input.files);\n const has = (p: string) => fileSet.has(p);\n const fam = input.indexText === undefined ? [] : parseComponentFamilies(input.indexText, input.indexRel ?? 'components');\n const familyOf = (name: string) => fam.find((f) => f.members.includes(name))?.name;\n const names = [\n ...new Set(\n input.files\n .map((f) => (f.startsWith(`${dir}/`) ? f.slice(dir.length + 1).split('/') : []))\n .filter((parts) => parts.length === 2 && parts[1] === `${parts[0]}.tsx`)\n .map((parts) => parts[0]!),\n ),\n ].sort();\n const reuseRe = new RegExp(`from\\\\s+'\\\\.\\\\.\\\\/(\\\\w+)\\\\/(\\\\w+)${escapeRe(styleSuffix)}'`, 'g');\n\n const result = names.map((name) => {\n const folder = `${dir}/${name}`;\n const files = { tsx: `${folder}/${name}.tsx`, css: `${folder}/${name}${styleSuffix}`, stories: `${folder}/${name}.stories.tsx`, docs: `${folder}/${name}${docsSuffix}` };\n let docs: ComponentDocs | null = null;\n if (has(files.docs)) {\n try {\n docs = JSON.parse(readText(files.docs) ?? '') as ComponentDocs;\n } catch (err) {\n input.problems?.push(`${files.docs}: ${(err as Error).message}`);\n }\n }\n const tsxSrc = readText(files.tsx) ?? '';\n const tsx = parseComponentTsx(name, tsxSrc);\n // Another component's stylesheet imported as is: import buttonStyles from '../Button/Button.module.css'.\n const reuses = [...tsxSrc.matchAll(reuseRe)].filter((m) => m[1] === m[2] && m[1] !== name).map((m) => m[1]!);\n const cssText = has(files.css) ? readText(files.css) : undefined;\n const rules = cssText === undefined ? [] : parseComponentCss(cssText, docs?.anatomy ?? {}, describeVar);\n const used = [...new Set(rules.flatMap((r) => r.vars.map((v) => v.name)))].sort();\n const storiesText = has(files.stories) ? readText(files.stories) : undefined;\n return {\n name,\n slug: componentSlug(name),\n dir: folder,\n files,\n ...tsx,\n rules,\n tokensUsed: used.map((n) => {\n const d = describeVar(n);\n return { name: n, href: d?.href, known: !!d, kind: d?.kind };\n }),\n tokenPaths: [...new Set(used.flatMap((n) => describeVar(n)?.path ?? []))].sort(),\n inherited: [] as ScannedComponent['inherited'],\n allTokenPaths: [] as string[],\n reuses,\n stories: storiesText === undefined ? [] : parseComponentStories(storiesText),\n docs,\n category: docs?.category ?? familyOf(name) ?? 'Core',\n };\n });\n const order = (c: { category: string }) => {\n const i = fam.findIndex((f) => f.name === c.category);\n return i < 0 ? fam.length : i;\n };\n result.sort((a, b) => order(a) - order(b) || a.name.localeCompare(b.name));\n resolveInheritedTokens(result);\n return result as ScannedComponent[];\n}\n","// The repo model: everything the docs site and Studio read from a design system repo, computed from a RepoSource.\n// One function for the build (fsSource over the checkout) and the browser (a GitHub source over any team's repo):\n// bridge.config.json parsed once, the token rows, contrast results, the component scan (props, CSS tokens, stories,\n// docs.json) and the Figma coverage of component-specs.json. Every path comes from the config; the defaults are\n// the paths this repo used before the config named them. Pure: no Node, no DOM.\n\nimport { ConfigError, defineConfig, loadConfig, tokensPath, CONFIG_FILE, DEFAULT_CHANGES_MODE, DEFAULT_OVERRIDE, type BridgeConfig, type BridgeConfigInput, type ChangesMode } from './config';\nimport { scanComponents, parseComponentFamilies, type ScannedComponent } from './component-scan';\nimport { parseComponentSpecs, type ComponentSpecsFile, type SpecCoverage } from './component-spec';\nimport { evaluateContrastPairs, parseContrastSpecs, type ContrastPairResult, type ContrastPairSpec } from './contrast-model';\nimport { selectTokenFiles } from './layered';\nimport { DEFAULT_PRODUCTS, type ProductConfig } from './products';\nimport { readRepoTexts, parentDir, type RepoSource, type RepoSourceRef } from './repo-source';\nimport type { IntegrationsConfig } from './requests';\nimport type { Rights, VisualImpactMode } from './rights';\nimport { buildTokenRows, tokenRowAxes, tokenRowIndex, type TokenRows, type TokenRowTier } from './token-rows';\n\n/** Paths used when bridge.config.json does not name them: where this repo kept them before the config did. */\nexport const REPO_MODEL_DEFAULTS = {\n tokensRoot: 'packages/tokens/src',\n componentsDir: 'packages/react/src/components',\n componentSpecs: 'packages/react/component-specs.json',\n /** Optional token usage notes (group -> sentence), relative to tokens.root, when tokens.usage is not set. */\n tokensUsage: 'usage.json',\n repo: { owner: 'peterbono', repo: 'ai-design-system-demo', defaultBranch: 'main' },\n} as const;\n\n/** The repository settings the site and Studio act on (roles, owners, mode), derived from bridge.config.json. */\nexport interface SiteRepo {\n owner: string;\n repo: string;\n defaultBranch: string;\n /** GitHub logins that count as design and tech owners for Tier 3 approvals. Empty: any two distinct approvers. */\n owners: { design: string[]; tech: string[] };\n /** Who may merge past missing approvals from Reviews, with a reason. `allowed` empty: no override. */\n override: { allowed: string[]; requireReason: boolean; minReasonLength: number };\n /** Which owner group approves design, approves tech and ships. null: not set. */\n rights: Rights | null;\n /** governance.soloOwnerCanApproveBoth: the only owner's approval covers design and tech. Default false. */\n soloOwnerCanApproveBoth: boolean;\n /** Visual before and after: on every pull request (auto) or when someone asks (on-demand, label visual-check). */\n visualImpact: { mode: VisualImpactMode };\n /** Token root in the repo. */\n tokensRoot: string;\n /** Where component change requests go besides the GitHub issue. Empty: GitHub only. */\n integrations: IntegrationsConfig;\n /** The apps that consume the design system, the library being the default. */\n products: ProductConfig[];\n /** How changes reach the code: \"suggest\" (default) or \"direct\". */\n changes: ChangesMode;\n}\n\ntype LegacyRaw = { owner?: unknown; defaultBranch?: unknown; owners?: { design?: string[]; tech?: string[] }; governance?: { owners?: unknown } } | null | undefined;\n\n/**\n * SiteRepo from a parsed config. `raw` (the file as parsed JSON) carries the older top-level keys loadConfig does not\n * keep (`owner`, `defaultBranch`, `owners`); `fallback` names the repo when the config does not.\n */\nexport function siteRepoFromConfig(\n config: BridgeConfig,\n raw?: unknown,\n fallback: { owner: string; repo: string; defaultBranch: string } = REPO_MODEL_DEFAULTS.repo,\n): SiteRepo {\n const legacy = (raw && typeof raw === 'object' ? raw : undefined) as LegacyRaw;\n const g = config.governance;\n const legacyOwners = legacy?.governance?.owners === undefined ? legacy?.owners : undefined;\n return {\n owner: typeof legacy?.owner === 'string' && legacy.owner ? legacy.owner : (config.repo?.owner ?? fallback.owner),\n repo: config.repo?.name ?? fallback.repo,\n defaultBranch: typeof legacy?.defaultBranch === 'string' && legacy.defaultBranch ? legacy.defaultBranch : (config.repo?.defaultBranch ?? fallback.defaultBranch),\n owners: legacyOwners ? { design: legacyOwners.design ?? [], tech: legacyOwners.tech ?? [] } : { design: [...g.owners.design], tech: [...g.owners.tech] },\n override: g.override ? { ...g.override } : { ...DEFAULT_OVERRIDE },\n rights: g.rights ?? null,\n soloOwnerCanApproveBoth: g.soloOwnerCanApproveBoth === true,\n visualImpact: { mode: config.visualImpact?.mode === 'on-demand' ? 'on-demand' : 'auto' },\n tokensRoot: config.tokens.root,\n integrations: config.integrations ?? {},\n products: config.products.length ? config.products : DEFAULT_PRODUCTS.map((p) => ({ ...p })),\n changes: config.changes ?? DEFAULT_CHANGES_MODE,\n };\n}\n\n/** Fills the paths a config leaves out with REPO_MODEL_DEFAULTS (tokens.root, components.dir). */\nfunction withModelDefaults(raw: Record<string, unknown>): Record<string, unknown> {\n const tokens = (raw.tokens && typeof raw.tokens === 'object' ? raw.tokens : {}) as Record<string, unknown>;\n return {\n ...raw,\n tokens: { ...tokens, root: tokens.root ?? REPO_MODEL_DEFAULTS.tokensRoot },\n components: raw.components ?? { dir: REPO_MODEL_DEFAULTS.componentsDir },\n };\n}\n\n/** The config the model uses when the repo has no bridge.config.json (or an invalid one): the defaults above. */\nexport const defaultModelConfig = (): BridgeConfig => defineConfig(withModelDefaults({}) as BridgeConfigInput);\n\n/** bridge.config.json text -> config, parsed once. Never throws: problems are returned and the defaults stand in. */\nexport function parseModelConfig(text: string | null): { config: BridgeConfig; raw: unknown; problems: string[] } {\n if (text === null) return { config: defaultModelConfig(), raw: undefined, problems: [] };\n let raw: unknown;\n try {\n raw = JSON.parse(text);\n } catch (err) {\n return { config: defaultModelConfig(), raw: undefined, problems: [`${CONFIG_FILE} is not valid JSON (${(err as Error).message})`] };\n }\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return { config: defaultModelConfig(), raw, problems: [`${CONFIG_FILE}: top level must be an object`] };\n try {\n return { config: loadConfig(withModelDefaults(raw as Record<string, unknown>)), raw, problems: [] };\n } catch (err) {\n const problems = err instanceof ConfigError ? err.problems.map((p) => `${CONFIG_FILE}: ${p}`) : [`${CONFIG_FILE}: ${(err as Error).message}`];\n return { config: defaultModelConfig(), raw, problems };\n }\n}\n\nexport interface RepoModel {\n ref: RepoSourceRef;\n /** bridge.config.json as read, null when the repo has none. */\n configText: string | null;\n config: BridgeConfig;\n site: SiteRepo;\n /** What could not be read (invalid config, a docs.json that does not parse, an alias that does not resolve). */\n problems: string[];\n tokens: {\n /** tokens.root, repo-relative. */\n root: string;\n /** Token file bodies keyed by path relative to tokens.root, as buildTokenSet and the token explorer read them. */\n files: Record<string, string>;\n rows: TokenRows;\n /** Notes per token group (tokens.usage), null when the repo has none. */\n usage: Record<string, string> | null;\n };\n contrast: {\n /** Repo-relative checks file, undefined when the config names none. */\n path: string | undefined;\n specs: ContrastPairSpec[];\n pairs: ContrastPairResult[];\n };\n /** Null when the scan was skipped (options.components false). */\n components: {\n dir: string;\n /** Barrel file the families come from, when it exists. */\n index: string | undefined;\n families: { name: string; members: string[] }[];\n list: ScannedComponent[];\n } | null;\n specs: {\n path: string;\n /** Parsed component-specs.json, null when missing or of another version. */\n file: ComponentSpecsFile | null;\n /** Figma coverage entries, read even from an older file. */\n coverage: SpecCoverage[];\n };\n}\n\nexport interface RepoModelOptions {\n /** Scan components (3-4 files per component). Default true. */\n components?: boolean;\n /** Docs link of a token's CSS variable (the caller's routing), given its type, tier and token path. Default: none. */\n href?: (cssVar: string, type: string, tier: TokenRowTier, path: string) => string | undefined;\n /** Requests in flight. Default 8. */\n concurrency?: number;\n /**\n * Hears how far the read has gone, in real file counts: once with every phase's total before the first body is\n * read, then once per file settled. Phases run in order: tokens (token files, contrast checks, usage notes), then\n * components (code, styles, stories, the index and the Figma specs), then docs (each component's docs file).\n */\n onProgress?: (progress: RepoModelProgress) => void;\n}\n\n/** The three reads of loadRepoModel, in the order they run. */\nexport type RepoModelPhase = 'tokens' | 'components' | 'docs';\n\nexport interface RepoModelProgress {\n /** The phase being read. */\n phase: RepoModelPhase;\n /** Files of this phase settled so far, and in all (a phase with nothing to read reports 0 of 0). */\n done: number;\n total: number;\n /** Across every phase: the bar of the whole read. `filesTotal` is known from the first report and never moves. */\n filesDone: number;\n filesTotal: number;\n}\n\nconst emptyRows = (config: BridgeConfig): TokenRows => ({ ...tokenRowAxes(config), primitives: [], semantic: [], brand: [], density: [], component: [], all: [], sources: [] });\n\n/** Reads a repo through `source` and computes its model. Never throws on repo content: see `problems`. */\nexport async function loadRepoModel(source: RepoSource, options: RepoModelOptions = {}): Promise<RepoModel> {\n const concurrency = options.concurrency ?? 8;\n const problems: string[] = [];\n // A file the source refuses as too large (status 413) is a problem of the repo, not a failure of the read.\n // Anything else (rate limit, network) still throws, so the caller can retry.\n const tooLarge = (path: string, err: unknown): null => {\n if ((err as { status?: unknown } | null)?.status !== 413) throw err;\n problems.push(`${path}: ${(err as Error).message}`);\n return null;\n };\n const configText = await source.text(CONFIG_FILE);\n const parsed = parseModelConfig(configText);\n const { config } = parsed;\n problems.push(...parsed.problems);\n const fallbackRepo = source.ref.owner && source.ref.repo ? { owner: source.ref.owner, repo: source.ref.repo, defaultBranch: REPO_MODEL_DEFAULTS.repo.defaultBranch } : REPO_MODEL_DEFAULTS.repo;\n const site = siteRepoFromConfig(config, parsed.raw, fallbackRepo);\n\n // Token files, the contrast checks and the usage notes.\n const root = config.tokens.root;\n const underRoot = await source.list(root === '.' ? '' : root);\n const tokenRel = selectTokenFiles(config, underRoot);\n const contrastPath = config.contrast?.path;\n const usagePath = tokensPath(config, config.tokens.usage ?? REPO_MODEL_DEFAULTS.tokensUsage);\n const tokenPaths = tokenRel.map((f) => tokensPath(config, f));\n const tokenRead = [...new Set([...tokenPaths, ...(contrastPath ? [contrastPath] : []), usagePath])];\n\n // Every path of the components and docs phases is known from the listing, before any body: the progress total is\n // exact from the first report.\n const comps = config.components ?? { dir: REPO_MODEL_DEFAULTS.componentsDir, docsSuffix: '.docs.json', styleSuffix: '.module.css' };\n const specsPath = comps.specs ?? REPO_MODEL_DEFAULTS.componentSpecs;\n const indexPath = comps.index ?? (parentDir(comps.dir) ? `${parentDir(comps.dir)}/index.ts` : 'index.ts');\n let compFiles: string[] = [];\n const codeRead: string[] = [specsPath];\n const docsRead: string[] = [];\n if (options.components !== false) {\n compFiles = await source.list(comps.dir);\n for (const f of compFiles) {\n const parts = f.slice(comps.dir.length + 1).split('/');\n if (parts.length !== 2) continue;\n const [n, file] = parts as [string, string];\n if (file === `${n}${comps.docsSuffix}`) docsRead.push(f);\n else if ([`${n}.tsx`, `${n}${comps.styleSuffix}`, `${n}.stories.tsx`].includes(file)) codeRead.push(f);\n }\n codeRead.push(indexPath);\n }\n // A path is read once, in the first phase that asks for it.\n const seen = new Set<string>();\n const fresh = (paths: string[]) =>\n paths.filter((p) => {\n if (seen.has(p)) return false;\n seen.add(p);\n return true;\n });\n const phases: [RepoModelPhase, string[]][] = [\n ['tokens', fresh(tokenRead)],\n ['components', fresh(codeRead)],\n ['docs', fresh(docsRead)],\n ];\n const filesTotal = phases.reduce((n, [, paths]) => n + paths.length, 0);\n let before = 0;\n const readPhase = async (phase: RepoModelPhase, paths: string[]) => {\n const offset = before;\n const out = await readRepoTexts(source, paths, concurrency, tooLarge, (done, total) => options.onProgress?.({ phase, done, total, filesDone: offset + done, filesTotal }));\n before += paths.length;\n return out;\n };\n const bodies = await readPhase('tokens', phases[0]![1]);\n const read = (p: string) => bodies.get(p) ?? undefined;\n const files: Record<string, string> = {};\n tokenRel.forEach((rel, i) => {\n const body = read(tokenPaths[i]!);\n if (body !== undefined) files[rel] = body;\n });\n const listFiles = (dir: string) => underRoot.filter((p) => parentDir(p) === dir);\n\n let rows: TokenRows;\n try {\n rows = buildTokenRows(config, read, listFiles);\n } catch (err) {\n problems.push((err as Error).message);\n rows = emptyRows(config);\n }\n\n let usage: Record<string, string> | null = null;\n const usageText = read(usagePath);\n if (usageText !== undefined) {\n try {\n usage = JSON.parse(usageText) as Record<string, string>;\n } catch (err) {\n problems.push(`${usagePath}: ${(err as Error).message}`);\n }\n }\n\n let specs: ContrastPairSpec[] = [];\n let pairs: ContrastPairResult[] = [];\n try {\n specs = parseContrastSpecs(contrastPath ? read(contrastPath) : undefined);\n pairs = evaluateContrastPairs(specs, rows);\n } catch (err) {\n problems.push((err as Error).message);\n }\n\n // Components and the Figma coverage.\n const index = tokenRowIndex(rows);\n const describeVar = (cssVar: string) => {\n const hit = index.get(cssVar);\n return hit ? { path: hit.path, kind: hit.kind, href: options.href?.(cssVar, hit.type, hit.kind, hit.path) } : undefined;\n };\n let components: RepoModel['components'] = null;\n const code = await readPhase('components', phases[1]![1]);\n const docs = await readPhase('docs', phases[2]![1]);\n const readMore = (p: string) => code.get(p) ?? docs.get(p) ?? bodies.get(p) ?? undefined;\n if (options.components !== false) {\n const indexText = readMore(indexPath);\n const indexDir = parentDir(indexPath);\n const indexRel = indexDir && comps.dir.startsWith(`${indexDir}/`) ? comps.dir.slice(indexDir.length + 1) : comps.dir;\n const list = scanComponents({ dir: comps.dir, files: compFiles, readText: readMore, indexText, indexRel, docsSuffix: comps.docsSuffix, styleSuffix: comps.styleSuffix, describeVar, problems });\n components = { dir: comps.dir, index: indexText === undefined ? undefined : indexPath, families: indexText === undefined ? [] : parseComponentFamilies(indexText, indexRel), list };\n }\n\n const specsText = readMore(specsPath);\n let specsFile: ComponentSpecsFile | null = null;\n let coverage: SpecCoverage[] = [];\n if (specsText !== undefined) {\n try {\n specsFile = parseComponentSpecs(specsText);\n } catch {\n /* another version: coverage below may still read */\n }\n try {\n coverage = (JSON.parse(specsText) as { coverage?: SpecCoverage[] }).coverage ?? [];\n } catch (err) {\n problems.push(`${specsPath}: ${(err as Error).message}`);\n }\n }\n\n return {\n ref: source.ref,\n configText,\n config,\n site,\n problems,\n tokens: { root, files, rows, usage },\n contrast: { path: contrastPath, specs, pairs },\n components,\n specs: { path: specsPath, file: specsFile, coverage },\n };\n}\n","// A RepoSource over GitHub, pinned to one commit sha: one recursive tree call lists every file with its blob sha,\n// then each body is read by that blob sha. Signed in, bodies come from the git blobs API with the raw media type\n// (the raw host refuses any request that carries a token: its CORS preflight answers 403). Anonymous, bodies of a\n// public repository come from raw.githubusercontent.com at the commit sha, sent without headers (a simple CORS\n// request, no API quota). Blobs are content-addressed: cached forever, never revalidated.\n\nimport { GitHubClient, GitHubError } from './github-client';\nimport { isUnder, normalizeRepoPath, type RepoSource } from './repo-source';\n\n/** Where blob bodies are kept between sources (IndexedDB in the browser). Keyed by blob sha; may be async. */\nexport interface BlobCache {\n get(sha: string): string | undefined | Promise<string | undefined>;\n set(sha: string, text: string): void | Promise<void>;\n}\n\nexport interface GitHubSourceOptions {\n /** Files larger than this are refused (status 413) instead of read. Default 1 MB. */\n maxFileBytes?: number;\n /** Body reads in flight at once. Default 4 (friendly to GitHub's secondary limits). */\n concurrency?: number;\n /**\n * A cache that outlives the source, keyed by blob sha. Bodies of private repositories land in it, so the caller\n * scopes it per repository and account and clears it on sign-out (plan 6.8).\n */\n blobCache?: BlobCache;\n /**\n * Hears what the source does: the tree once it is read (how many files the commit holds), then each body as it\n * lands, saying whether it came from the blob cache (no request) or from GitHub.\n */\n onProgress?: (event: GitHubSourceProgress) => void;\n}\n\n/** What a GitHub source reports through `onProgress`. */\nexport type GitHubSourceProgress = { kind: 'tree'; files: number } | { kind: 'file'; path: string; cached: boolean };\n\n/** How bodies are read: the blobs API with the token, or the raw host without one. */\nexport type GitHubSourceMode = 'api' | 'raw';\n\nexport interface GitHubSource extends RepoSource {\n /** Where body reads go: 'api' when the client has a token, 'raw' otherwise. */\n readonly mode: GitHubSourceMode;\n}\n\nconst FULL_SHA = /^[0-9a-f]{40}$/i;\n\n/** A concurrency limiter: at most `n` tasks run at once, the rest wait in order. */\nfunction limiter(n: number) {\n let active = 0;\n const waiting: (() => void)[] = [];\n return async <T>(task: () => Promise<T>): Promise<T> => {\n if (active >= n) await new Promise<void>((resolve) => waiting.push(resolve));\n active++;\n try {\n return await task();\n } finally {\n active--;\n waiting.shift()?.();\n }\n };\n}\n\n/**\n * A source over `client`'s repository at commit `sha` (a full 40-character sha: a branch name would move under the\n * cache). The first `list` or `text` call reads the tree; `text` of a path the tree does not list costs no request.\n */\nexport function gitHubSource(client: GitHubClient, sha: string, opts: GitHubSourceOptions = {}): GitHubSource {\n if (!FULL_SHA.test(sha)) throw new Error(`gitHubSource needs a full commit sha, got \"${sha}\". Resolve the branch head first.`);\n const maxBytes = opts.maxFileBytes ?? 1_000_000;\n const run = limiter(Math.max(1, opts.concurrency ?? 4));\n const mode: GitHubSourceMode = client.canWrite ? 'api' : 'raw';\n\n let tree: Promise<Map<string, { sha: string; size: number | undefined }>> | undefined;\n const readTree = () => {\n tree ??= client.getTree(sha, true).then(\n ({ entries, truncated }) => {\n if (truncated) throw new GitHubError(413, 'The repository tree is too large to read in one request.');\n const files = new Map<string, { sha: string; size: number | undefined }>();\n for (const e of entries) if (e.type === 'blob') files.set(e.path, { sha: e.sha, size: e.size });\n opts.onProgress?.({ kind: 'tree', files: files.size });\n return files;\n },\n (err: unknown) => {\n tree = undefined; // A failed read (rate limit, network) is retried by the next call.\n throw err;\n },\n );\n return tree;\n };\n\n const bodies = new Map<string, Promise<string>>();\n\n const readBody = async (path: string, blobSha: string): Promise<string> => {\n const kept = await opts.blobCache?.get(blobSha);\n if (kept !== undefined) {\n opts.onProgress?.({ kind: 'file', path, cached: true });\n return kept;\n }\n const text = mode === 'api' ? await client.getBlobRaw(blobSha) : await client.readRawFile(path, sha);\n if (text === undefined) {\n const hint = mode === 'raw' ? ' Sign in with GitHub to read a private repository.' : '';\n throw new GitHubError(404, `${path} is listed at ${sha.slice(0, 7)} but GitHub did not return it.${hint}`);\n }\n try {\n await opts.blobCache?.set(blobSha, text);\n } catch {\n // A full or blocked cache only costs a read next time.\n }\n opts.onProgress?.({ kind: 'file', path, cached: false });\n return text;\n };\n\n return {\n ref: { owner: client.owner, repo: client.name, sha },\n mode,\n async list(prefix?: string) {\n // Sorted, like every RepoSource.\n return [...(await readTree()).keys()].filter((f) => isUnder(f, prefix)).sort();\n },\n async text(path: string) {\n const p = normalizeRepoPath(path);\n const entry = (await readTree()).get(p);\n if (!entry) return null;\n if (entry.size !== undefined && entry.size > maxBytes) {\n throw new GitHubError(413, `${p} is ${Math.round(entry.size / 1000)} KB; Bridge reads files up to ${Math.round(maxBytes / 1000)} KB.`);\n }\n let body = bodies.get(entry.sha);\n if (!body) {\n body = run(() => readBody(p, entry.sha));\n bodies.set(entry.sha, body);\n body.catch(() => bodies.delete(entry.sha));\n }\n return body;\n },\n };\n}\n","// What one visitor can do in one repository, from GitHub alone (multi-team plan, section 3.3). Pure: the facts come\n// from GET /repos/{owner}/{repo} (visibility and the viewer's permissions) and, for a GitHub App sign-in, from the\n// user's installations. Roles from bridge.config.json (owners, rights) are evaluated on top by the caller, as today.\n\nimport { GitHubClient, GitHubError, type RepoInfo } from './github-client';\n\n/**\n * - anonymous-public: not signed in, the repository is public (read-only Studio).\n * - anonymous-unknown: not signed in, GitHub answers 404 (private or missing: GitHub does not say which).\n * - no-access: signed in, GitHub answers 404 (no such repo, not a collaborator, or the App is not installed on it).\n * - not-installed: signed in with explicit permission (triage or more) on a public repository, and the App's\n * installations do not cover it: it is not installed there.\n * - outside-contributor: signed in, public repository, read access only, and no App installation lists it. GitHub\n * lists installations only where the user has explicit permission, so this may be a non-collaborator of a repo\n * where Bridge is installed: never say \"not installed\" here. Browse only; ask an admin for access.\n * - reader: pull or triage. Browse, comment, file suggestions.\n * - writer: push or maintain. Plus direct changes.\n * - admin: admin. Plus settings and protection.\n */\nexport type RepoAccessState = 'anonymous-public' | 'anonymous-unknown' | 'no-access' | 'not-installed' | 'outside-contributor' | 'reader' | 'writer' | 'admin';\n\n/** The viewer's permissions on a repository, as GET /repos returns them. */\nexport type RepoPermissions = NonNullable<RepoInfo['permissions']>;\n\nexport interface AccessFacts {\n /** A token was sent. */\n signedIn: boolean;\n /** GET /repos answered 200 (false on 404). */\n visible: boolean;\n /**\n * An installation of the App the user can reach covers the repository; null or undefined when not checked\n * (personal token) or GitHub would not say.\n */\n installed?: boolean | null | undefined;\n /** GET /repos said the repository is private. */\n private?: boolean | undefined;\n permissions?: RepoPermissions | undefined;\n}\n\n/** The access state from the facts (section 3.3 table). */\nexport function accessState(f: AccessFacts): RepoAccessState {\n if (!f.visible) return f.signedIn ? 'no-access' : 'anonymous-unknown';\n if (!f.signedIn) return 'anonymous-public';\n const p = f.permissions ?? {};\n // A private repository an App token can see is one the App is installed on, whatever the listing said.\n if (f.installed === false && !f.private) return p.admin || p.maintain || p.push || p.triage ? 'not-installed' : 'outside-contributor';\n if (p.admin) return 'admin';\n if (p.push || p.maintain) return 'writer';\n return 'reader';\n}\n\nconst RANK: Record<RepoAccessState, number> = {\n 'anonymous-unknown': 0,\n 'no-access': 0,\n 'anonymous-public': 1,\n 'not-installed': 1,\n 'outside-contributor': 1,\n reader: 2,\n writer: 3,\n admin: 4,\n};\n\n/**\n * True when `state` grants at least what `min` grants: 'reader' (suggest, comment), 'writer' (direct changes),\n * 'admin' (settings). The read-only states rank as 'anonymous-public'; the closed ones rank lowest.\n */\nexport function accessAtLeast(state: RepoAccessState, min: 'anonymous-public' | 'reader' | 'writer' | 'admin'): boolean {\n return RANK[state] >= RANK[min];\n}\n\nexport interface RepoAccess {\n state: RepoAccessState;\n owner: string;\n repo: string;\n /** Undefined when GitHub did not show the repository. */\n private: boolean | undefined;\n defaultBranch: string | undefined;\n permissions: RepoPermissions | undefined;\n /** The App installation that gives the user this repository, when checked and found. */\n installationId?: number | undefined;\n /** With a Direct App client: whether that App is installed for the user on the repository (null when unknown). */\n directInstalled?: boolean | null | undefined;\n}\n\nexport interface ResolveAccessOptions {\n /**\n * The client's token is a GitHub App user-to-server token: check its installations (2 or 3 calls). Leave off for a\n * personal token or anonymous reads; the state then comes from GET /repos alone.\n */\n app?: boolean;\n /** A client with the Direct App's token, to learn whether that App is installed too (changes: \"direct\"). */\n direct?: GitHubClient;\n}\n\n/** Installed, not installed, or null when GitHub would not say (personal token, missing permission, network). */\nasync function installed(client: GitHubClient, owner: string, repo: string): Promise<{ installed: boolean | null; id?: number }> {\n try {\n const found = await client.findInstallation(owner, repo);\n return found ? { installed: true, id: found.id } : { installed: false };\n } catch (err) {\n if (err instanceof GitHubError && (err.status === 401 || err.status === 429)) throw err;\n return { installed: null };\n }\n}\n\n/**\n * Reads what the client's token (or no token) can do on the client's repository. With `app`, the client's token must\n * be a user token of the signing-in App (each App lists only its own installations). A 404 is a state, not an error;\n * a rejected token (401) and an exhausted rate limit (429) are thrown for the caller to handle as today.\n */\nexport async function resolveRepoAccess(client: GitHubClient, opts: ResolveAccessOptions = {}): Promise<RepoAccess> {\n const signedIn = client.canWrite;\n const base = { owner: client.owner, repo: client.name };\n let info: RepoInfo;\n try {\n info = await client.getRepo();\n } catch (err) {\n if (err instanceof GitHubError && err.status === 404) {\n return { ...base, state: accessState({ signedIn, visible: false }), private: undefined, defaultBranch: undefined, permissions: undefined };\n }\n throw err;\n }\n const inst = signedIn && opts.app ? await installed(client, client.owner, client.name) : { installed: null };\n const direct = signedIn && opts.direct ? (await installed(opts.direct, client.owner, client.name)).installed : undefined;\n return {\n ...base,\n state: accessState({ signedIn, visible: true, installed: inst.installed, private: info.private, permissions: info.permissions }),\n private: info.private,\n defaultBranch: info.defaultBranch,\n permissions: info.permissions,\n ...(inst.id !== undefined ? { installationId: inst.id } : {}),\n ...(direct !== undefined ? { directInstalled: direct } : {}),\n };\n}\n","// Repo snapshot: the files the repo model reads, written by `bridge snapshot` in a team's CI and published to the\n// `bridge-data` branch (.github/workflows/bridge-data.yml), plus what only Node can compute (adoption audits run on\n// product code) and a compact Figma coverage list. Hosted Studio and Library read it from the raw host with no API\n// quota: snapshotSource() serves it as a RepoSource, so loadRepoModel() gives the same model as a live read.\n// Pure: no Node, no DOM.\n\nimport type { AuditMetrics, AuditReport } from './audit/types';\nimport type { ContrastPairResult } from './contrast-model';\nimport type { SpecCoverage } from './component-spec';\nimport { isUnder, normalizeRepoPath, type RepoSource } from './repo-source';\nimport type { RepoModel } from './repo-model';\n\nexport const SNAPSHOT_SCHEMA_VERSION = 1;\n/** Branch the bridge-data workflow publishes to, and the files on it. */\nexport const SNAPSHOT_BRANCH = 'bridge-data';\nexport const SNAPSHOT_FILE = 'snapshot.json';\nexport const SNAPSHOT_AUDITS_DIR = 'audits';\n/** Above this, a snapshot is refused (a published file the browser downloads whole). */\nexport const SNAPSHOT_MAX_BYTES = 5_000_000;\n\n/** One adoption audit: the summary lives in snapshot.json, the full report in audits/<id>.json next to it. */\nexport interface SnapshotAudit {\n id: string;\n /** Path of the full report on the bridge-data branch (\"audits/admin.json\"). */\n path: string;\n label?: string;\n generatedAt: string;\n target: { path: string; files: number };\n metrics: AuditMetrics;\n}\n\n/** A contrast pair as computed when the snapshot was written, without the token rows (the model has them). */\nexport type SnapshotContrastPair = Omit<ContrastPairResult, 'fgToken' | 'bgToken'>;\n\n/** Counts for a header or a card, readable without loading the model. */\nexport interface SnapshotSummary {\n tokens: number;\n /** Null when the component scan was skipped. */\n components: number | null;\n contrast: { pairs: number; checks: number; failing: number };\n /** Components in Figma (generated or drafted) out of the visual ones, null without a specs file. */\n figma: { inFigma: number; visual: number } | null;\n}\n\nexport interface RepoSnapshot {\n kind: 'bridge-snapshot';\n schemaVersion: typeof SNAPSHOT_SCHEMA_VERSION;\n tool: { name: 'bridge'; version: string };\n generatedAt: string;\n repo: { owner: string; name: string; branch: string };\n /** Commit the snapshot was computed from. Fresh when it equals the default branch head. */\n sourceSha: string;\n /** Commit date of sourceSha (ISO), when known. */\n committedAt?: string;\n /** Every path the model listed (token root, components dir), so list() answers as the repository did. */\n paths: string[];\n /** Bodies of the files the model read, keyed by repo-relative path. */\n files: Record<string, string>;\n /**\n * Figma coverage of component-specs.json without the specs themselves (the file is over 1 MB here, too big for\n * the GitHub contents source). Null when the repository has no specs file.\n */\n figma: { path: string; generated?: string; coverage: SpecCoverage[] } | null;\n summary: SnapshotSummary;\n /** Contrast results as computed when the snapshot was written (the model recomputes the same from files). */\n contrast: { path?: string; pairs: SnapshotContrastPair[] };\n audits: SnapshotAudit[];\n /** What could not be read when the snapshot was written. */\n problems: string[];\n}\n\nexport class SnapshotError extends Error {}\n\nconst isObj = (x: unknown): x is Record<string, unknown> => !!x && typeof x === 'object' && !Array.isArray(x);\nconst isStr = (x: unknown): x is string => typeof x === 'string';\n\n/** Validates a snapshot (text or parsed JSON). Throws SnapshotError naming the first problem. */\nexport function parseSnapshot(input: string | unknown): RepoSnapshot {\n let data: unknown = input;\n if (typeof input === 'string') {\n try {\n data = JSON.parse(input);\n } catch (err) {\n throw new SnapshotError(`${SNAPSHOT_FILE} is not valid JSON (${(err as Error).message})`);\n }\n }\n if (!isObj(data) || data.kind !== 'bridge-snapshot') throw new SnapshotError(`${SNAPSHOT_FILE} is not a Bridge snapshot`);\n if (data.schemaVersion !== SNAPSHOT_SCHEMA_VERSION) throw new SnapshotError(`${SNAPSHOT_FILE} is schema version ${String(data.schemaVersion)}; this version of Bridge reads ${SNAPSHOT_SCHEMA_VERSION}`);\n const repo = data.repo;\n if (!isObj(repo) || !isStr(repo.owner) || !isStr(repo.name) || !isStr(repo.branch)) throw new SnapshotError(`${SNAPSHOT_FILE}: repo needs owner, name and branch`);\n if (!isStr(data.sourceSha) || !data.sourceSha) throw new SnapshotError(`${SNAPSHOT_FILE}: sourceSha is missing`);\n if (!isStr(data.generatedAt)) throw new SnapshotError(`${SNAPSHOT_FILE}: generatedAt is missing`);\n if (!Array.isArray(data.paths) || !data.paths.every(isStr)) throw new SnapshotError(`${SNAPSHOT_FILE}: paths must be a list of strings`);\n if (!isObj(data.files) || !Object.values(data.files).every(isStr)) throw new SnapshotError(`${SNAPSHOT_FILE}: files must map paths to text`);\n if (data.figma !== null && (!isObj(data.figma) || !isStr(data.figma.path) || !Array.isArray(data.figma.coverage))) throw new SnapshotError(`${SNAPSHOT_FILE}: figma must be null or { path, coverage }`);\n if (!isObj(data.summary) || typeof data.summary.tokens !== 'number') throw new SnapshotError(`${SNAPSHOT_FILE}: summary is missing`);\n if (!isObj(data.contrast) || !Array.isArray(data.contrast.pairs)) throw new SnapshotError(`${SNAPSHOT_FILE}: contrast needs pairs`);\n if (!Array.isArray(data.audits) || !data.audits.every((a) => isObj(a) && isStr(a.id) && isStr(a.path) && isObj(a.metrics))) throw new SnapshotError(`${SNAPSHOT_FILE}: audits must be a list of { id, path, metrics }`);\n if (!Array.isArray(data.problems)) throw new SnapshotError(`${SNAPSHOT_FILE}: problems must be a list`);\n return data as unknown as RepoSnapshot;\n}\n\n/** True when the snapshot was computed from `headSha` (the default branch head): use it instead of a live read. */\nexport const snapshotIsFresh = (snapshot: Pick<RepoSnapshot, 'sourceSha'>, headSha: string | undefined): boolean => !!headSha && snapshot.sourceSha === headSha;\n\n/**\n * A RepoSource over a snapshot. The Figma specs path serves a compact file with the coverage only (no component\n * specs), so the model reads the coverage and leaves `specs.file` null.\n */\nexport function snapshotSource(snapshot: RepoSnapshot): RepoSource {\n const files = new Map(Object.entries(snapshot.files).map(([k, v]) => [normalizeRepoPath(k), v]));\n const figmaPath = snapshot.figma ? normalizeRepoPath(snapshot.figma.path) : undefined;\n if (snapshot.figma && figmaPath && !files.has(figmaPath)) {\n files.set(figmaPath, JSON.stringify({ ...(snapshot.figma.generated ? { generated: snapshot.figma.generated } : {}), coverage: snapshot.figma.coverage }));\n }\n const paths = [...new Set([...snapshot.paths.map(normalizeRepoPath), ...files.keys()])].sort();\n return {\n ref: { owner: snapshot.repo.owner, repo: snapshot.repo.name, sha: snapshot.sourceSha },\n list: async (prefix) => paths.filter((p) => isUnder(p, prefix)),\n text: async (path) => files.get(normalizeRepoPath(path)) ?? null,\n };\n}\n\n/**\n * Wraps a source and records what it lists and reads, so a snapshot carries exactly the files the model needs and\n * nothing else of the repository.\n */\nexport function recordingSource(source: RepoSource): { source: RepoSource; paths: Set<string>; files: Map<string, string> } {\n const paths = new Set<string>();\n const files = new Map<string, string>();\n return {\n paths,\n files,\n source: {\n get ref() {\n return source.ref;\n },\n async list(prefix) {\n const out = await source.list(prefix);\n for (const p of out) paths.add(p);\n return out;\n },\n async text(path) {\n const body = await source.text(path);\n if (body !== null) files.set(normalizeRepoPath(path), body);\n return body;\n },\n },\n };\n}\n\n/** Summary of an audit report for snapshot.json; the full report is written to `path`. */\nexport function snapshotAudit(id: string, report: AuditReport): SnapshotAudit {\n return {\n id,\n path: `${SNAPSHOT_AUDITS_DIR}/${id}.json`,\n ...(report.label ? { label: report.label } : {}),\n generatedAt: report.generatedAt,\n target: { path: report.target.path, files: report.target.files },\n metrics: report.metrics,\n };\n}\n\n/** A safe audit id from a label or path (\"apps/admin/src\" -> \"apps-admin-src\"). */\nexport const auditId = (s: string): string =>\n s\n .toLowerCase()\n .replace(/\\.json$/, '')\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '') || 'audit';\n\nexport interface BuildSnapshotInput {\n model: RepoModel;\n /** From recordingSource(): what loadRepoModel listed and read. */\n paths: Iterable<string>;\n files: Map<string, string> | Record<string, string>;\n version: string;\n branch?: string;\n committedAt?: string;\n generatedAt?: string;\n audits?: SnapshotAudit[];\n}\n\n/** Every brand x theme result of a pair (the default brand per theme when the rows have no brands). */\nconst pairResults = (p: SnapshotContrastPair) => {\n const brands = Object.values(p.brands);\n return brands.length ? brands.flatMap((b) => Object.values(b)) : Object.values(p.modes);\n};\n\n/** Counts of a model for the snapshot summary. */\nexport function snapshotSummary(model: RepoModel): SnapshotSummary {\n const results = model.contrast.pairs.flatMap((p) => pairResults(p).map((r) => r.ratio >= p.min));\n const coverage = model.specs.coverage;\n const visual = coverage.filter((c) => c.status !== 'layout').length;\n const inFigma = coverage.filter((c) => c.status === 'generated' || c.status === 'drafted').length;\n return {\n tokens: model.tokens.rows.all.length + model.tokens.rows.primitives.length,\n components: model.components ? model.components.list.length : null,\n contrast: { pairs: model.contrast.pairs.length, checks: results.length, failing: results.filter((ok) => !ok).length },\n figma: coverage.length ? { inFigma, visual } : null,\n };\n}\n\n/** Assembles the snapshot from a model and the files it was read from. The specs file becomes the coverage list. */\nexport function buildSnapshot(input: BuildSnapshotInput): RepoSnapshot {\n const { model } = input;\n const files: Record<string, string> = {};\n const entries = input.files instanceof Map ? [...input.files] : Object.entries(input.files);\n const specsPath = normalizeRepoPath(model.specs.path);\n for (const [k, v] of entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {\n const p = normalizeRepoPath(k);\n if (p !== specsPath) files[p] = v;\n }\n const hasSpecs = entries.some(([k]) => normalizeRepoPath(k) === specsPath);\n return {\n kind: 'bridge-snapshot',\n schemaVersion: SNAPSHOT_SCHEMA_VERSION,\n tool: { name: 'bridge', version: input.version },\n generatedAt: input.generatedAt ?? new Date().toISOString(),\n repo: { owner: model.ref.owner || model.site.owner, name: model.ref.repo || model.site.repo, branch: input.branch ?? model.site.defaultBranch },\n sourceSha: model.ref.sha,\n ...(input.committedAt ? { committedAt: input.committedAt } : {}),\n paths: [...new Set([...input.paths].map(normalizeRepoPath))].filter((p) => p !== specsPath).sort(),\n files,\n figma: hasSpecs ? { path: specsPath, ...(model.specs.file?.generated ? { generated: model.specs.file.generated } : {}), coverage: model.specs.coverage } : null,\n summary: snapshotSummary(model),\n contrast: { ...(model.contrast.path ? { path: model.contrast.path } : {}), pairs: model.contrast.pairs.map(({ fgToken: _fg, bgToken: _bg, ...rest }) => rest) },\n audits: input.audits ?? [],\n problems: [...model.problems],\n };\n}\n\n/** llms.txt next to snapshot.json on the bridge-data branch: the published design system in plain text, for agents. */\nexport const SNAPSHOT_LLMS_FILE = 'llms.txt';\n\n/** Above this many tokens, llms.txt lists the first ones and points at snapshot.json for the rest. */\nexport const LLMS_MAX_TOKENS = 600;\n\n/** One line of repo text: whitespace collapsed, so a value cannot open a heading or a list of its own. */\nconst line = (text: unknown): string => (typeof text === 'string' ? text.replace(/\\s+/g, ' ').trim() : '');\nconst strings = (list: unknown): string[] => (Array.isArray(list) ? list.map(line).filter(Boolean) : []);\n\n/**\n * The design system of a snapshot as llms.txt (https://llmstxt.org): what it is, every token with its CSS variable and\n * values per theme, and every component with its usage guidance. Written by `bridge snapshot`; the hosted Library\n * links to it. Pure: the model the snapshot was computed from goes in, text comes out.\n */\nexport function snapshotLlmsTxt(model: RepoModel, snapshot: Pick<RepoSnapshot, 'repo' | 'sourceSha' | 'committedAt' | 'generatedAt'>): string {\n const { owner, name, branch } = snapshot.repo;\n const date = (snapshot.committedAt ?? snapshot.generatedAt).slice(0, 10);\n const rows = model.tokens.rows;\n const tokens = rows.all.filter((t) => !t.deprecated);\n const shown = tokens.slice(0, LLMS_MAX_TOKENS);\n const comps = model.components?.list ?? [];\n const out: string[] = [\n `# ${owner}/${name} design system`,\n '',\n `> Tokens, components and usage guidance of the design system in github.com/${owner}/${name}, read at ${snapshot.sourceSha.slice(0, 7)} on ${branch} (${date}). Published by Bridge for AI agents and people.`,\n '',\n `- Source: https://github.com/${owner}/${name}/tree/${snapshot.sourceSha}`,\n `- Every file Bridge read, as JSON: ${SNAPSHOT_FILE}, next to this file on the ${SNAPSHOT_BRANCH} branch.`,\n `- Themes: ${rows.themes.join(', ') || 'none'}. Brands: ${rows.brands.join(', ') || 'none'}. Densities: ${rows.densities.join(', ') || 'none'}.`,\n '',\n '## Tokens',\n '',\n `${tokens.length} tokens (brand, semantic, density and component tiers) on top of ${rows.primitives.length} primitives. Use the semantic tokens in product code, never the primitives. Values are for the default brand${rows.defaultBrand ? ` (${rows.defaultBrand})` : ''}.`,\n '',\n ];\n for (const t of shown) {\n const values = Object.entries(t.modes)\n .map(([theme, v]) => `${theme} ${line(v.css)}`)\n .join(', ');\n const note = line(t.description);\n out.push(`- \\`${t.path}\\` (\\`${t.cssVar}\\`, ${t.tier} ${t.type}): ${values || 'no value'}${note ? `. ${note}` : ''}`);\n }\n if (tokens.length > shown.length) out.push('', `${tokens.length - shown.length} more tokens are in ${SNAPSHOT_FILE}.`);\n out.push('', '## Components', '');\n if (!comps.length) out.push('No components were read (components.dir in bridge.config.json names the folder).');\n for (const c of comps) {\n const d = c.docs;\n out.push(`### ${line(c.name)}`, '');\n const summary = line(d?.summary) || line(c.description);\n if (summary) out.push(summary, '');\n out.push(`- Family: ${line(c.category)}${c.docs?.status && c.docs.status !== 'stable' ? `, ${c.docs.status}` : ''}`);\n if (c.allTokenPaths.length) out.push(`- Tokens: ${c.allTokenPaths.slice(0, 40).join(', ')}${c.allTokenPaths.length > 40 ? ', ...' : ''}`);\n for (const [label, list] of [\n ['Use it for', strings(d?.whenToUse)],\n ['Not for', strings(d?.whenNotToUse)],\n ['Accessibility', strings(d?.accessibility)],\n ] as const) {\n if (list.length) out.push(`- ${label}:`, ...list.map((x) => ` - ${x}`));\n }\n const dos = Array.isArray(d?.dos) ? d!.dos : [];\n const donts = Array.isArray(d?.donts) ? d!.donts : [];\n for (const g of dos) if (line(g?.title)) out.push(`- Do: ${line(g.title)}${line(g.text) ? `. ${line(g.text)}` : ''}`);\n for (const g of donts) if (line(g?.title)) out.push(`- Don't: ${line(g.title)}${line(g.text) ? `. ${line(g.text)}` : ''}`);\n out.push('');\n }\n return `${out.join('\\n').replace(/\\n{3,}/g, '\\n\\n').trim()}\\n`;\n}\n"],"names":["issueKey","t","isAlias","pairs","p","modesOf","a","idOf","names","cl","STEPS","isObj","text","cs","str","at","line","dr","dg","db","code","by","status","lifecycle","behindMain","preview","exportName","resolve","bg","ch"],"mappings":";;;;AA4CA,MAAMA,aAAW,CAAC,MAAa,GAAG,EAAE,IAAI,IAAI,EAAE,QAAQ,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,QAAI,KAAK,EAAE;AAAA,EACb;AACA,SAAO,GAAG,IAAI,KAAK,IAAI,EAAE,QAAQ,WAAW,MAAM,EAAE,KAAA,CAAM;AAAA;AAC5D;"}
1
+ {"version":3,"file":"index.js","sources":["../src/validators.ts","../src/id-map.ts","../src/token-merge.ts","../src/token-combine.ts","../src/css-overrides.ts","../src/compose.ts","../src/protection.ts","../src/protection-github.ts","../src/usage.ts","../src/history-github.ts","../src/history-demo.ts","../src/previews-github.ts","../src/ramps.js","../src/brand.ts","../src/docs-ai.ts","../src/draft-exchange.ts","../src/explorations-github.ts","../src/fidelity.ts","../src/fidelity-references.ts","../src/library-update.ts","../src/branch-actions.ts","../src/share-branch.ts","../src/try-in-product.ts","../src/combine-branches.ts","../src/prod-branch-github.ts","../src/token-proposal.ts","../src/figma-push-github.ts","../src/storybook.ts","../src/token-rows.ts","../src/contrast-model.ts","../src/component-scan.ts","../src/repo-model.ts","../src/repo-source-github.ts","../src/repo-access.ts","../src/snapshot.ts"],"sourcesContent":["// Guardrails checked before a PR can be opened. They mirror the repo rules (AGENTS.md,\n// docs/ARCHITECTURE.md \"Token tiers\", docs/GOVERNANCE.md) so designers get the answer in Figma\n// instead of a red CI run later.\n//\n// Tier rules (what each tier may alias):\n// primitive literal values, or another primitive\n// brand an alias to a primitive (palette, radius and font roles re-point raw scales)\n// base a literal or a primitive (motion, layers, icon sizes)\n// semantic an alias, never a literal. Colors alias a Brand palette role (palette.*); translucent\n// primitives (color.alpha.*) are the only raw colors allowed. Non-color semantic tokens\n// (focus ring width, elevation) may alias a primitive or a brand role.\n// density an alias to a primitive (space and size scales)\n// component an alias to a semantic, base, density or brand role token, or a primitive scale step\n// (space, type). Never a raw color ramp or a palette role.\n// Brand x theme overrides follow the semantic rule and must override an existing semantic token.\n\nimport { findReferenceProblems } from './resolver';\nimport { type TokenSet, modesOf } from './token-set';\nimport { type LogicalToken, SINGLE_MODE, TIER_AXIS, TIER_NAMES, type Tier, isMultiMode, modeDisplayName } from './types';\nimport { aliasTarget, collectRefs, isAlias } from './values';\nimport { type ContrastPair, type ContrastResult, contextLabel, contrastScope, evaluatePairs } from './wcag';\n\nexport type IssueCode =\n | 'file-problem'\n | 'raw-value'\n | 'alias-tier'\n | 'broken-reference'\n | 'alias-cycle'\n | 'all-scopes'\n | 'missing-mode'\n | 'override-orphan'\n | 'override-shadowed'\n | 'contrast'\n | 'contrast-unresolved'\n | 'type-change';\n\nexport interface Issue {\n code: IssueCode;\n severity: 'error' | 'warning';\n message: string;\n path?: string | undefined;\n mode?: string | undefined;\n}\n\nconst issueKey = (i: Issue) => `${i.code}|${i.path ?? ''}|${i.mode ?? ''}|${i.code === 'file-problem' ? i.message : ''}`;\nconst modeName = (mode: string) => (mode === SINGLE_MODE ? 'all modes' : modeDisplayName(mode));\n\nconst isPalette = (t: LogicalToken) => t.tier === 'brand' && t.path.startsWith('palette.');\nconst isRawColor = (t: LogicalToken) => t.tier === 'primitive' && t.type === 'color';\n\n/** Why `owner` (in `tier`) may not alias `target`, or undefined when the alias is allowed. */\nfunction aliasRule(owner: { tier: Tier; type: string }, target: LogicalToken): string | undefined {\n switch (owner.tier) {\n case 'primitive':\n case 'base':\n case 'brand':\n case 'density':\n return target.tier === 'primitive' ? undefined : `${TIER_NAMES[owner.tier]} tokens point to primitives only`;\n case 'semantic':\n if (owner.type === 'color') {\n if (isPalette(target)) return undefined;\n if (target.tier === 'primitive' && target.path.startsWith('color.alpha.')) return undefined;\n return 'Semantic colors point to a Brand palette role (palette.*) so every brand can re-map them';\n }\n return target.tier === 'primitive' || target.tier === 'brand' ? undefined : 'Semantic tokens point to a Brand role or a primitive';\n case 'component':\n if (isPalette(target) || isRawColor(target)) return 'Component tokens point to semantic tokens, never to a palette role or a raw color';\n return target.tier === 'component' ? 'Component tokens point to semantic tokens, not to other component tokens' : undefined;\n }\n}\n\n/** Tiers whose values must be aliases. */\nconst MUST_ALIAS: Tier[] = ['brand', 'semantic', 'density', 'component'];\n\nfunction checkValue(set: TokenSet, owner: { path: string; tier: Tier; type: string }, value: unknown, mode: string, where: string, issues: Issue[]): void {\n if (!isAlias(value)) {\n if (MUST_ALIAS.includes(owner.tier) && value !== undefined) {\n issues.push({\n code: 'raw-value',\n severity: 'error',\n path: owner.path,\n mode,\n message: `${owner.path} uses a raw value in ${where}. ${TIER_NAMES[owner.tier]} tokens must point to another variable (pick one instead of typing a value).`,\n });\n }\n return;\n }\n const target = set.byPath.get(aliasTarget(value));\n if (!target) return; // reported as a broken reference\n const why = aliasRule(owner, target);\n if (why) {\n issues.push({\n code: 'alias-tier',\n severity: 'error',\n path: owner.path,\n mode,\n message: `${owner.path} points to ${target.path} (${TIER_NAMES[target.tier]}) in ${where}. ${why}.`,\n });\n }\n}\n\n/** All rule violations in a token set. */\nexport function validateSet(set: TokenSet, pairs: ContrastPair[]): { issues: Issue[]; contrast: ContrastResult[] } {\n const issues: Issue[] = [];\n for (const p of set.problems) issues.push({ code: 'file-problem', severity: 'error', message: p });\n\n for (const t of set.tokens.values()) {\n if (t.scopes?.includes('ALL_SCOPES')) {\n issues.push({\n code: 'all-scopes',\n severity: 'error',\n path: t.path,\n message: `${t.path} is offered in every Figma picker (\"All supported properties\"). Pick the specific properties it is meant for in the variable's scoping settings.`,\n });\n }\n const modes = modesOf(set.layout, t.tier);\n for (const mode of modes) {\n const v = t.values[mode];\n if (v === undefined) {\n if (isMultiMode(t.tier)) {\n issues.push({\n code: 'missing-mode',\n severity: 'error',\n path: t.path,\n mode,\n message: `${t.path} has no value in ${modeName(mode)}. ${TIER_NAMES[t.tier]} tokens must exist in every ${TIER_AXIS[t.tier]}.`,\n });\n }\n continue;\n }\n checkValue(set, t, v, mode, modeName(mode), issues);\n }\n }\n\n for (const o of set.overrides) {\n const mode = `${o.brand}.${o.theme}`;\n const where = `${modeDisplayName(o.brand)} ${o.theme} (${o.file})`;\n const base = set.byPath.get(o.path);\n if (!base || base.tier !== 'semantic') {\n issues.push({\n code: 'override-orphan',\n severity: 'error',\n path: o.path,\n mode,\n message: `${o.file} overrides ${o.path}, which is not a semantic token. Remove the override or restore the token.`,\n });\n continue;\n }\n checkValue(set, { path: o.path, tier: 'semantic', type: base.type }, o.value, mode, where, issues);\n for (const ref of collectRefs(o.value)) {\n if (!set.byPath.has(ref)) issues.push({ code: 'broken-reference', severity: 'error', path: o.path, mode, message: `${o.path} points to ${ref}, which does not exist (${where}).` });\n }\n }\n\n const axes = { brand: modesOf(set.layout, 'brand'), theme: modesOf(set.layout, 'semantic'), density: modesOf(set.layout, 'density') };\n for (const p of findReferenceProblems(set.byPath, axes)) {\n issues.push(\n p.kind === 'broken'\n ? {\n code: 'broken-reference',\n severity: 'error',\n path: p.path,\n mode: p.mode,\n message: `${p.path} points to ${p.target}, which does not exist (${modeName(p.mode)}).`,\n }\n : {\n code: 'alias-cycle',\n severity: 'error',\n path: p.path,\n mode: p.mode,\n message: `${p.path} is part of a loop of references: ${p.chain.join(' -> ')} (${modeName(p.mode)}).`,\n },\n );\n }\n\n const contrast = evaluatePairs(set.byPath, pairs, contrastScope(set));\n for (const r of contrast) {\n const path = `${r.pair.foreground} on ${r.pair.background}`;\n const mode = `${r.brand ?? ''}.${r.theme}`;\n if (r.error) {\n issues.push({ code: 'contrast-unresolved', severity: 'warning', path, mode, message: `Contrast of ${path} in ${contextLabel(r)} cannot be checked: ${r.error}.` });\n } else if (r.level === 'fail') {\n issues.push({\n code: 'contrast',\n severity: 'error',\n path,\n mode,\n message: `${path} is ${r.ratio}:1 in ${contextLabel(r)}; contrast.checks.json needs ${r.pair.min}:1 (WCAG AA ${r.pair.kind === 'ui' ? 'for interface elements' : 'for text'}).`,\n });\n }\n }\n return { issues, contrast };\n}\n\nexport interface TypeChange {\n path: string;\n from: string;\n to: string;\n}\n\nexport interface ProposalValidation {\n /** Problems this change introduces. They disable the PR button. */\n blocking: Issue[];\n /** Problems that already exist on main, or soft checks. Shown, not blocking. */\n warnings: Issue[];\n contrastBefore: ContrastResult[];\n contrastAfter: ContrastResult[];\n}\n\n/**\n * Semantic edits that some brand does not see because it overrides that token for the theme\n * (brands/<brand>.<theme>.tokens.json). Not an error: a heads-up that the edit is partial.\n */\nexport function shadowedEdits(set: TokenSet, edits: { path: string; tier: Tier; modes: string[] }[]): Issue[] {\n const out: Issue[] = [];\n for (const e of edits) {\n if (e.tier !== 'semantic') continue;\n for (const o of set.overrides) {\n if (o.path !== e.path || !e.modes.includes(o.theme)) continue;\n out.push({\n code: 'override-shadowed',\n severity: 'warning',\n path: e.path,\n mode: `${o.brand}.${o.theme}`,\n message: `${e.path} is overridden for ${modeDisplayName(o.brand)} in ${o.theme} (${o.file}), so this edit does not change ${modeDisplayName(o.brand)} ${o.theme}. Brand overrides stay code-only.`,\n });\n }\n }\n return out;\n}\n\n/**\n * Validate the files a PR would produce. Errors already present on main are reported as warnings\n * so an unrelated, pre-existing problem does not block a designer's change; everything the change\n * introduces blocks.\n */\nexport function validateProposal(proposed: TokenSet, head: TokenSet, pairs: ContrastPair[], typeChanges: TypeChange[] = []): ProposalValidation {\n const after = validateSet(proposed, pairs);\n const before = validateSet(head, pairs);\n const existing = new Set(before.issues.map(issueKey));\n const blocking: Issue[] = [];\n const warnings: Issue[] = [];\n for (const i of after.issues) {\n if (i.severity === 'warning') warnings.push(i);\n else if (existing.has(issueKey(i))) warnings.push({ ...i, severity: 'warning', message: `Already on main: ${i.message}` });\n else blocking.push(i);\n }\n for (const c of typeChanges) {\n blocking.push({\n code: 'type-change',\n severity: 'error',\n path: c.path,\n message: `${c.path} changed type from ${c.from} to ${c.to}. Type changes are not allowed; create a new token instead.`,\n });\n }\n return { blocking, warnings, contrastBefore: before.contrast, contrastAfter: after.contrast };\n}\n","// Stable identity of tokens across renames.\n//\n// Every variable DS Bridge writes carries a token id in its plugin data. The id is the token's\n// `$extensions[\"com.dsbridge.id\"]` when the file declares one, otherwise \"path:<path>\". Matching is\n// by id first, so renaming a variable in Figma is a rename, not a delete plus an add. Only renamed\n// (or re-identified) tokens get the extension written into Git, which keeps the files lean.\n//\n// Variables created in Figma have no id. They are matched by name, then, as a last resort, a\n// heuristic proposes \"this looks like a rename\" (same type, same values, similar path). Heuristic\n// matches are suggestions only: the user confirms each one.\n\nimport { pathId } from './token-set';\nimport type { LogicalToken } from './types';\nimport { valuesEqual } from './values';\n\nexport interface RenameSuggestion {\n /** Id the Figma variable currently has (derived from its new name). */\n figmaId: string;\n /** Id of the Git token it probably is. */\n gitId: string;\n fromPath: string;\n toPath: string;\n similarity: number;\n}\n\nexport interface ReconcileResult {\n tokens: LogicalToken[];\n /** Figma tokens that adopted a Git id because their names matched (no plugin data yet). */\n adoptedByName: string[];\n suggestions: RenameSuggestion[];\n}\n\nexport function levenshtein(a: string, b: string): number {\n const prev = Array.from({ length: b.length + 1 }, (_, i) => i);\n for (let i = 1; i <= a.length; i++) {\n let diag = prev[0]!;\n prev[0] = i;\n for (let j = 1; j <= b.length; j++) {\n const tmp = prev[j]!;\n prev[j] = Math.min(prev[j]! + 1, prev[j - 1]! + 1, diag + (a[i - 1] === b[j - 1] ? 0 : 1));\n diag = tmp;\n }\n }\n return prev[b.length]!;\n}\n\nexport function pathSimilarity(a: string, b: string): number {\n const ratio = 1 - levenshtein(a, b) / Math.max(a.length, b.length, 1);\n const leafA = a.slice(a.lastIndexOf('.') + 1);\n const leafB = b.slice(b.lastIndexOf('.') + 1);\n return leafA === leafB ? Math.max(ratio, 0.75) : ratio;\n}\n\nexport const SIMILARITY_THRESHOLD = 0.5;\n\nfunction sameContent(a: LogicalToken, b: LogicalToken): boolean {\n if (a.type !== b.type || a.tier !== b.tier) return false;\n const modes = new Set([...Object.keys(a.values), ...Object.keys(b.values)]);\n for (const m of modes) if (!valuesEqual(a.type, a.values[m], b.values[m])) return false;\n return true;\n}\n\n/**\n * Align Figma token ids with Git ids. `git` is every token known on the Git side (base and head).\n * Heuristic candidates are restricted to Git tokens that no Figma variable claims.\n */\nexport function reconcileIds(figma: LogicalToken[], git: LogicalToken[]): ReconcileResult {\n const gitById = new Map<string, LogicalToken>();\n const gitByPath = new Map<string, LogicalToken>();\n for (const t of git) {\n if (!gitById.has(t.id)) gitById.set(t.id, t);\n if (!gitByPath.has(t.path)) gitByPath.set(t.path, t);\n }\n const claimed = new Set(figma.filter((t) => gitById.has(t.id)).map((t) => t.id));\n const adoptedByName: string[] = [];\n const tokens = figma.map((t) => ({ ...t }));\n\n for (const t of tokens) {\n if (gitById.has(t.id)) continue;\n const byName = gitByPath.get(t.path);\n if (byName && !claimed.has(byName.id) && byName.type === t.type) {\n t.id = byName.id;\n claimed.add(byName.id);\n adoptedByName.push(t.id);\n }\n }\n\n const suggestions: RenameSuggestion[] = [];\n const unclaimedGit = [...gitById.values()].filter((g) => !claimed.has(g.id));\n for (const t of tokens) {\n if (gitById.has(t.id)) continue;\n let best: RenameSuggestion | undefined;\n for (const g of unclaimedGit) {\n if (!sameContent(t, g)) continue;\n const similarity = pathSimilarity(t.path, g.path);\n if (similarity < SIMILARITY_THRESHOLD) continue;\n if (!best || similarity > best.similarity) {\n best = { figmaId: t.id, gitId: g.id, fromPath: g.path, toPath: t.path, similarity: Math.round(similarity * 100) / 100 };\n }\n }\n if (best) suggestions.push(best);\n }\n // One suggestion per Git token: keep the most similar.\n const byGit = new Map<string, RenameSuggestion>();\n for (const s of suggestions) {\n const prev = byGit.get(s.gitId);\n if (!prev || s.similarity > prev.similarity) byGit.set(s.gitId, s);\n }\n return { tokens, adoptedByName, suggestions: [...byGit.values()] };\n}\n\n/** Apply the rename suggestions the user confirmed: the Figma token takes the Git id. */\nexport function applyConfirmedRenames(tokens: LogicalToken[], confirmed: RenameSuggestion[]): LogicalToken[] {\n const map = new Map(confirmed.map((s) => [s.figmaId, s.gitId]));\n return tokens.map((t) => (map.has(t.id) ? { ...t, id: map.get(t.id)! } : t));\n}\n\n/**\n * Id to write into `$extensions[\"com.dsbridge.id\"]`: only needed when the id no longer matches\n * the default derived from the path (after a rename). Undefined means \"do not write\".\n */\nexport function idExtensionFor(t: LogicalToken): string | undefined {\n return t.id === pathId(t.path) ? undefined : t.id;\n}\n","// Three-way merge of token files: a change (mine) against the latest library (theirs), from the commit they share\n// (base). Same rules as the Figma sync (diff-engine threeWayDiff): a token changed on one side only takes that side,\n// a token changed on both sides the same way is unchanged, and a token changed on both sides differently is a\n// conflict the designer decides (\"Keep mine\" or \"Use the library's\"). A token removed on one side and changed on the\n// other has no default: the designer must pick.\n//\n// Works file by file on the DTCG text, so each mode (semantic/light, semantic/dark, a brand override file) is merged\n// on its own, and edits go through the format-preserving codec: untouched tokens stay byte for byte as the library\n// has them. Pure: no fetch, no DOM.\n\nimport { emptyTokenFile, flattenTokens, parseTokenFile, removeToken, serializeTokenFile, upsertToken, type TokenDocument } from './dtcg-codec';\nimport { threeWayDiff, type DiffEntry } from './diff-engine';\nimport { pathId } from './token-set';\nimport { EXT_ID, EXT_SCOPES, SINGLE_MODE, type FlatToken, type LogicalToken } from './types';\n\n/** Which side a conflict keeps: this change (\"Keep mine\") or the latest library (\"Use the library's\"). */\nexport type MergeSide = 'mine' | 'theirs';\n\nexport interface TokenMergeConflict {\n /** Stable key for the choice: `<file>#<token id>`. */\n key: string;\n /** Token file, relative to the tokens root. */\n file: string;\n /** Display path: this change's name, else the library's, else the shared one. */\n path: string;\n base?: FlatToken | undefined;\n mine?: FlatToken | undefined;\n theirs?: FlatToken | undefined;\n /** The side that removed the token while the other changed it. Null when both sides kept it. */\n removedOn: MergeSide | null;\n /** \"Keep mine\" by default; null when the token was removed on one side and changed on the other. */\n defaultChoice: MergeSide | null;\n}\n\nexport interface TokenMergePlan {\n /** Token files both sides changed, relative to the tokens root. */\n files: string[];\n conflicts: TokenMergeConflict[];\n /** Tokens only this change touched: applied on top of the library as they are. */\n mineOnly: number;\n /** Tokens only the library touched: kept as the library has them. */\n theirsOnly: number;\n /** Files that could not be read (not JSON): nothing can be merged while there is one. */\n problems: string[];\n}\n\nexport interface TokenMergeInput {\n /** File texts at the commit both sides share. Undefined: the file did not exist there. */\n base: Record<string, string | undefined>;\n /** File texts in the change. */\n mine: Record<string, string | undefined>;\n /** File texts in the latest library. */\n theirs: Record<string, string | undefined>;\n /** Token files both sides changed (the others need no merge). */\n files: string[];\n}\n\nexport type MergeChoices = Record<string, MergeSide | undefined>;\n\ninterface Side {\n doc: TokenDocument | undefined;\n flat: Map<string, FlatToken>;\n logical: Map<string, LogicalToken>;\n}\n\nconst idOf = (f: FlatToken) => {\n const id = f.extensions?.[EXT_ID];\n return typeof id === 'string' && id ? id : pathId(f.path);\n};\n\n/** One flat token as a single-mode logical token, so threeWayDiff compares path, type, value, description and scopes. */\nfunction logical(f: FlatToken): LogicalToken {\n const scopes = f.extensions?.[EXT_SCOPES];\n return {\n id: idOf(f),\n path: f.path,\n type: f.type ?? 'unknown',\n // One file holds one tier: the tier only feeds default scopes, the same on every side.\n tier: 'primitive',\n values: { [SINGLE_MODE]: f.value },\n description: f.description,\n scopes: Array.isArray(scopes) ? scopes.map(String) : undefined,\n files: { [SINGLE_MODE]: f.file },\n };\n}\n\nfunction readSide(file: string, text: string | undefined, problems: string[], label: string): Side {\n const side: Side = { doc: undefined, flat: new Map(), logical: new Map() };\n if (text === undefined) return side;\n try {\n side.doc = parseTokenFile(file, text);\n } catch (err) {\n problems.push(`${file} (${label}) is not valid JSON: ${(err as Error).message}`);\n return side;\n }\n for (const f of flattenTokens(side.doc)) {\n const id = idOf(f);\n side.flat.set(id, f);\n side.logical.set(id, logical(f));\n }\n return side;\n}\n\ninterface FileDiff {\n file: string;\n base: Side;\n mine: Side;\n theirs: Side;\n local: DiffEntry[];\n remote: DiffEntry[];\n conflicts: DiffEntry[];\n}\n\nfunction diffFile(input: TokenMergeInput, file: string, problems: string[]): FileDiff {\n const base = readSide(file, input.base[file], problems, 'shared start');\n const mine = readSide(file, input.mine[file], problems, 'this change');\n const theirs = readSide(file, input.theirs[file], problems, 'latest library');\n const r = threeWayDiff(base.logical, mine.logical, theirs.logical);\n return { file, base, mine, theirs, local: r.local, remote: r.remote, conflicts: r.conflicts };\n}\n\n/** The side that removed a token the other side changed, or null. */\nexport function removedSide(c: { base?: unknown; mine?: unknown; theirs?: unknown }): MergeSide | null {\n if (!c.base) return null;\n if (!c.mine && c.theirs) return 'mine';\n if (!c.theirs && c.mine) return 'theirs';\n return null;\n}\n\n/** \"Keep mine\" by default, except for a token removed on one side and changed on the other: no default there. */\nexport const defaultChoiceFor = (c: { base?: unknown; mine?: unknown; theirs?: unknown }): MergeSide | null => (removedSide(c) ? null : 'mine');\n\n/** What both sides did to the token files they both changed, and which tokens need a decision. */\nexport function planTokenMerge(input: TokenMergeInput): TokenMergePlan {\n const problems: string[] = [];\n const files = [...new Set(input.files)].sort();\n const conflicts: TokenMergeConflict[] = [];\n let mineOnly = 0;\n let theirsOnly = 0;\n for (const file of files) {\n const d = diffFile(input, file, problems);\n mineOnly += d.local.length;\n theirsOnly += d.remote.length;\n for (const e of d.conflicts) {\n const c = { base: d.base.flat.get(e.id), mine: d.mine.flat.get(e.id), theirs: d.theirs.flat.get(e.id) };\n conflicts.push({ key: `${file}#${e.id}`, file, path: (c.mine ?? c.theirs ?? c.base)!.path, ...c, removedOn: removedSide(c), defaultChoice: defaultChoiceFor(c) });\n }\n }\n return { files, conflicts, mineOnly, theirsOnly, problems };\n}\n\n/** The side a conflict keeps: the designer's pick, else its default (null: still to pick). */\nexport const choiceFor = (c: TokenMergeConflict, choices: MergeChoices): MergeSide | null => choices[c.key] ?? c.defaultChoice;\n\n/** Conflicts that still need a pick: removed on one side, changed on the other, and not decided yet. */\nexport function missingChoices(plan: Pick<TokenMergePlan, 'conflicts'>, choices: MergeChoices): TokenMergeConflict[] {\n return plan.conflicts.filter((c) => choiceFor(c, choices) === null);\n}\n\n/** Puts this change's version of a token into the library's file: its value, type, description and extensions. Also used by token-combine. */\nexport function takeMine(doc: TokenDocument, mine: FlatToken | undefined, existing: FlatToken | undefined): boolean {\n if (!mine) return existing ? removeToken(doc, existing.path) : false;\n let changed = false;\n if (existing && existing.path !== mine.path) changed = removeToken(doc, existing.path) || changed;\n // Extension keys the library has and this change does not are removed, so the token reads as in the change.\n const extensions: Record<string, unknown> = {};\n for (const k of Object.keys(existing?.path === mine.path ? (existing.extensions ?? {}) : {})) extensions[k] = undefined;\n Object.assign(extensions, mine.extensions ?? {});\n return upsertToken(doc, mine.path, { type: mine.type, value: mine.value, description: mine.description, extensions }) || changed;\n}\n\nexport interface TokenMergeResult {\n /** Merged text per file (relative to the tokens root); null when the merged file holds no token and is removed. */\n files: Record<string, string | null>;\n /** How many conflicts kept each side. */\n kept: Record<MergeSide, number>;\n}\n\n/**\n * The merged token files: the latest library's text, plus every token only this change touched, plus each conflict\n * as chosen. Throws when a file could not be read or a conflict still needs a pick.\n */\nexport function applyTokenMerge(input: TokenMergeInput, choices: MergeChoices): TokenMergeResult {\n const plan = planTokenMerge(input);\n if (plan.problems.length) throw new Error(plan.problems[0]);\n const missing = missingChoices(plan, choices);\n if (missing.length) throw new Error(`Pick a value for ${missing.map((c) => c.path).join(', ')} first.`);\n const byKey = new Map(plan.conflicts.map((c) => [c.key, c]));\n const kept: Record<MergeSide, number> = { mine: 0, theirs: 0 };\n const files: Record<string, string | null> = {};\n for (const file of plan.files) {\n const d = diffFile(input, file, []);\n const doc = d.theirs.doc ?? emptyTokenFile(file);\n for (const e of d.local) takeMine(doc, d.mine.flat.get(e.id), d.theirs.flat.get(e.id) ?? d.base.flat.get(e.id));\n for (const e of d.conflicts) {\n const side = choiceFor(byKey.get(`${file}#${e.id}`)!, choices)!;\n kept[side]++;\n if (side === 'mine') takeMine(doc, d.mine.flat.get(e.id), d.theirs.flat.get(e.id));\n }\n const empty = flattenTokens(doc).length === 0;\n files[file] = empty && (input.theirs[file] === undefined || input.mine[file] === undefined) ? null : serializeTokenFile(doc);\n }\n return { files, kept };\n}\n","// Try several changes together: the latest library plus the token edits of 2 to 4 open changes, combined in the\n// browser. Nothing is written anywhere: no branch, no commit. Each change's own edits are what it did to its token\n// files since it started (its start against its current version), so a change that is behind the library never\n// undoes the library's newer values. Edits to the same token that agree are applied once; edits that disagree are a\n// conflict the designer settles (\"Use <change>'s\"). Pure: no fetch, no DOM. Studio (Changes, the library views) and\n// the admin's Bridge toolbar both run it.\n\nimport { emptyTokenFile, flattenTokens, parseTokenFile, serializeTokenFile, type TokenDocument } from './dtcg-codec';\nimport { takeMine } from './token-merge';\nimport { pathId } from './token-set';\nimport { EXT_ID, type FlatToken } from './types';\n\n/** What one change brings: its token files where it started and now, and the token files it edits. */\nexport interface CombineSource {\n number: number;\n /** Token file texts where the change started (relative to the tokens root). Undefined: the file did not exist. */\n base: Record<string, string | undefined>;\n /** Token file texts in the change now. Undefined: the change removes the file. */\n head: Record<string, string | undefined>;\n /** Token files the change edits, relative to the tokens root. */\n files: string[];\n}\n\nexport interface CombineEdit {\n /** `<file>#<token id>`: the same token in the same file across changes. */\n key: string;\n file: string;\n /** The token's path in the change (its old path when the change removes it). */\n path: string;\n change: number;\n /** The change's version of the token; undefined when the change removes it. */\n token: FlatToken | undefined;\n}\n\nexport interface ChangeEdits {\n number: number;\n edits: CombineEdit[];\n /** Files that could not be read (not JSON). */\n problems: string[];\n}\n\nconst idOf = (f: FlatToken) => {\n const id = f.extensions?.[EXT_ID];\n return typeof id === 'string' && id ? id : pathId(f.path);\n};\n\nfunction tokensOf(file: string, text: string | undefined, problems: string[], label: string): Map<string, FlatToken> {\n const out = new Map<string, FlatToken>();\n if (text === undefined) return out;\n try {\n for (const t of flattenTokens(parseTokenFile(file, text))) out.set(idOf(t), t);\n } catch (err) {\n problems.push(`${file} (${label}) is not valid JSON: ${(err as Error).message}`);\n }\n return out;\n}\n\n/** What a token is, for comparing two versions of it: its path, type, value and description. */\nconst shape = (t: FlatToken | undefined) => (t ? JSON.stringify([t.path, t.type ?? null, t.value, t.description ?? null]) : 'removed');\n/** What a token shows, for comparing two changes' edits: removed, or its type and value. */\nconst look = (t: FlatToken | undefined) => (t ? JSON.stringify([t.path, t.type ?? null, t.value]) : 'removed');\n\n/** The token edits of one change: every token whose version differs between where the change started and now. */\nexport function changeEdits(src: CombineSource): ChangeEdits {\n const problems: string[] = [];\n const edits: CombineEdit[] = [];\n for (const file of [...new Set(src.files)].sort()) {\n const before = tokensOf(file, src.base[file], problems, 'start');\n const after = tokensOf(file, src.head[file], problems, `change ${src.number}`);\n for (const id of new Set([...before.keys(), ...after.keys()])) {\n const a = before.get(id);\n const b = after.get(id);\n if (shape(a) === shape(b)) continue;\n edits.push({ key: `${file}#${id}`, file, path: (b ?? a)!.path, change: src.number, token: b });\n }\n }\n return { number: src.number, edits, problems };\n}\n\n/** One value a conflicting token can take, and the changes that set it. */\nexport interface CombineOption {\n changes: number[];\n token: FlatToken | undefined;\n}\n\n/** A token two or more changes set differently: the designer picks one change's value. */\nexport interface CombineConflict {\n key: string;\n file: string;\n path: string;\n /** Distinct values, in the order of the changes. */\n options: CombineOption[];\n}\n\n/** The pick of each conflict: the change whose value the combination uses. */\nexport type CombinePicks = Record<string, number>;\n\nexport interface Combination {\n /** Every token file of the latest library, with the combined edits applied (unchanged files as they are). */\n files: Record<string, string>;\n /** The changes combined, in order. */\n included: number[];\n /** Token values the combination edits (one per token and file: a token edited in light and dark counts twice). */\n edits: number;\n /** Tokens the combination edits, by name. */\n tokens: number;\n conflicts: CombineConflict[];\n /** Conflicts without a pick that counts: left at the library's value ('skip') or given the first change's ('first'). */\n missing: CombineConflict[];\n /** Token path -> the changes whose value the combination uses for it. */\n from: Record<string, number[]>;\n problems: string[];\n}\n\n/** Edits grouped by token, in the order of the changes. */\nfunction byToken(changes: ChangeEdits[]): Map<string, CombineEdit[]> {\n const out = new Map<string, CombineEdit[]>();\n for (const c of changes) for (const e of c.edits) out.set(e.key, [...(out.get(e.key) ?? []), e]);\n return out;\n}\n\nfunction optionsOf(edits: CombineEdit[]): CombineOption[] {\n const out: { look: string; option: CombineOption }[] = [];\n for (const e of edits) {\n const l = look(e.token);\n const hit = out.find((o) => o.look === l);\n if (hit) hit.option.changes.push(e.change);\n else out.push({ look: l, option: { changes: [e.change], token: e.token } });\n }\n return out.map((o) => o.option);\n}\n\n/** Tokens that two or more of these changes set differently. */\nexport function combineConflicts(changes: ChangeEdits[]): CombineConflict[] {\n const out: CombineConflict[] = [];\n for (const [key, edits] of byToken(changes)) {\n const options = optionsOf(edits);\n if (options.length > 1) out.push({ key, file: edits[0]!.file, path: edits[0]!.path, options });\n }\n return out;\n}\n\n/** The option a pick selects, or null when the picked change is not among them (not picked, or switched off). */\nexport function pickedOption(c: CombineConflict, picks: CombinePicks): CombineOption | null {\n const n = picks[c.key];\n return n === undefined ? null : (c.options.find((o) => o.changes.includes(n)) ?? null);\n}\n\n/** Conflicts that still need a pick. */\nexport const unpicked = (conflicts: CombineConflict[], picks: CombinePicks) => conflicts.filter((c) => !pickedOption(c, picks));\n\n/**\n * The latest library plus the edits of the included changes (all of them by default, in their order). A conflict\n * uses the picked change's value. Without a pick that counts, `unpicked: 'skip'` (Studio, before opening) leaves the\n * token at the library's value and lists it in `missing`; `'first'` (the toolbar, when a picked change is switched\n * off) uses the first included change's value and still lists it.\n */\nexport function combineChanges(latest: Record<string, string>, changes: ChangeEdits[], picks: CombinePicks = {}, opts: { include?: number[]; unpicked?: 'skip' | 'first' } = {}): Combination {\n const on = opts.include ? changes.filter((c) => opts.include!.includes(c.number)) : changes;\n const problems = on.flatMap((c) => c.problems);\n const groups = byToken(on);\n const conflicts: CombineConflict[] = [];\n const missing: CombineConflict[] = [];\n const from: Record<string, number[]> = {};\n const docs = new Map<string, TokenDocument>();\n const docOf = (file: string): TokenDocument | null => {\n if (docs.has(file)) return docs.get(file)!;\n const text = latest[file];\n let doc: TokenDocument;\n try {\n doc = text === undefined ? emptyTokenFile(file) : parseTokenFile(file, text);\n } catch (err) {\n problems.push(`${file} (latest library) is not valid JSON: ${(err as Error).message}`);\n return null;\n }\n docs.set(file, doc);\n return doc;\n };\n for (const [key, edits] of groups) {\n const options = optionsOf(edits);\n let use: CombineOption | null = options[0]!;\n if (options.length > 1) {\n const conflict: CombineConflict = { key, file: edits[0]!.file, path: edits[0]!.path, options };\n conflicts.push(conflict);\n use = pickedOption(conflict, picks);\n if (!use) {\n missing.push(conflict);\n use = opts.unpicked === 'first' ? options[0]! : null;\n }\n }\n if (!use) continue;\n const doc = docOf(edits[0]!.file);\n if (!doc) continue;\n const existing = flattenTokens(doc).find((t) => idOf(t) === key.slice(key.indexOf('#') + 1));\n // A removal removes the library's token; an edit replaces it (or adds it when the library does not have it).\n takeMine(doc, use.token, existing);\n const path = use.token?.path ?? edits[0]!.path;\n from[path] = [...new Set([...(from[path] ?? []), ...use.changes])];\n }\n const files: Record<string, string> = { ...latest };\n for (const [file, doc] of docs) {\n if (latest[file] === undefined && flattenTokens(doc).length === 0) continue;\n files[file] = serializeTokenFile(doc);\n }\n const tokens = new Set([...groups.values()].map((e) => e[0]!.path)).size;\n return { files, included: on.map((c) => c.number), edits: groups.size, tokens, conflicts, missing, from, problems };\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// Picks in an address: `118:semantic/light.tokens.json#path:color.bg.default~120:...`. The change number first, then\n// the conflict key; entries joined by \"~\" (keys hold \":\" and \"#\", never \"~\").\n\nexport function encodePicks(picks: CombinePicks): string {\n return Object.entries(picks)\n .filter(([, n]) => Number.isSafeInteger(n) && n > 0)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([key, n]) => `${n}:${key}`)\n .join('~');\n}\n\nexport function decodePicks(raw: string | null | undefined): CombinePicks {\n const out: CombinePicks = {};\n for (const part of (raw ?? '').split('~')) {\n const i = part.indexOf(':');\n if (i < 1) continue;\n const n = Number(part.slice(0, i));\n const key = part.slice(i + 1);\n if (/^\\d{1,7}$/.test(part.slice(0, i)) && n > 0 && key.includes('#')) out[key] = n;\n }\n return out;\n}\n","// CSS custom properties that paint a token set over another one: the live preview of a token draft (Studio Tokens),\n// a change shown in Studio Components, and several changes tried together in the admin's Bridge toolbar. Pure.\nimport { resolve, type ResolveContext } from './resolver';\nimport type { TokenSet } from './token-set';\nimport { formatValue, parseColor, rgbaToHex } from './values';\n\n/** CSS value of a resolved DTCG value, the way tokens.css writes it. */\nexport function cssOf(type: string, value: unknown): string | undefined {\n if (value === undefined) return undefined;\n if (type === 'color') {\n const hex = value && typeof value === 'object' ? (value as { hex?: unknown }).hex : undefined;\n const c = parseColor(value);\n if (!c) return undefined;\n if (c.a < 1) return `rgb(${Math.round(c.r * 255)} ${Math.round(c.g * 255)} ${Math.round(c.b * 255)} / ${c.a})`;\n return typeof hex === 'string' ? hex.toLowerCase() : rgbaToHex(c);\n }\n return formatValue(type, value);\n}\n\nexport const cssVarOf = (path: string) => `--${path.replace(/\\./g, '-')}`;\n\n/**\n * CSS custom properties to set on a scope so it renders `proposed` instead of `head`: every token whose resolved value\n * differs in that context. Setting resolved values (not var() references) keeps chains correct even when the original\n * variable is declared on an ancestor.\n */\nexport function previewOverrides(head: TokenSet, proposed: TokenSet, ctx: ResolveContext): Record<string, string> {\n const out: Record<string, string> = {};\n const hctx = { ...ctx, overrides: head.overrideIndex };\n const pctx = { ...ctx, overrides: proposed.overrideIndex };\n for (const t of proposed.byPath.values()) {\n const a = resolve(head.byPath, t.path, hctx);\n const b = resolve(proposed.byPath, t.path, pctx);\n const css = cssOf(t.type, b.value);\n if (css !== undefined && JSON.stringify(a.value) !== JSON.stringify(b.value)) out[cssVarOf(t.path)] = css;\n }\n return out;\n}\n","// Apply accepted token changes onto main's files. Only files whose text actually changes are\n// returned, and inside them only the edited tokens change (layout, key order, other tools'\n// $extensions and untouched values are preserved byte for byte).\n\nimport {\n type TokenDocument,\n emptyTokenFile,\n moveToken,\n parseTokenFile,\n readTokenAt,\n removeToken,\n serializeTokenFile,\n upsertToken,\n} from './dtcg-codec';\nimport { idExtensionFor } from './id-map';\nimport { defaultScopes, effectiveScopes, sameScopes } from './scopes';\nimport { type TokenSet, defaultFile, modeFile } from './token-set';\nimport { EXT_ID, EXT_SCOPES, type LogicalToken, isMultiMode } from './types';\nimport { valuesEqual } from './values';\n\nexport interface AcceptedChange {\n /** Desired state; undefined removes the token. */\n target: LogicalToken | undefined;\n /** State on main (head) before the change; undefined for additions. */\n current: LogicalToken | undefined;\n}\n\nexport interface ComposeResult {\n /** Changed files only: path relative to the tokens directory -> new text. */\n files: Record<string, string>;\n /** Every token file after the change (changed and unchanged), for validation. */\n allFiles: Record<string, string>;\n}\n\nconst modesOf = (t: LogicalToken) => Object.keys(t.values);\n\nexport function composeFiles(head: TokenSet, originals: Record<string, string>, changes: AcceptedChange[]): ComposeResult {\n const docs = new Map<string, TokenDocument>();\n const doc = (file: string): TokenDocument => {\n let d = docs.get(file);\n if (!d) {\n const text = originals[file];\n d = text === undefined ? emptyTokenFile(file) : parseTokenFile(file, text);\n docs.set(file, d);\n }\n return d;\n };\n // Each value goes back to the file of its tier and mode: brands/<brand>, semantic/<theme>,\n // density/<density>, or the single file of a primitive, base or component token.\n const fileFor = (t: LogicalToken, mode: string, current?: LogicalToken) =>\n current?.files[mode] ??\n t.files[mode] ??\n (isMultiMode(t.tier) ? modeFile(head.layout, t.tier, mode) : undefined) ??\n defaultFile(t.tier, t.path, head.options.dirs);\n\n for (const { target, current } of changes) {\n if (!target) {\n if (current) for (const mode of modesOf(current)) removeToken(doc(fileFor(current, mode)), current.path);\n continue;\n }\n const renamed = !!current && current.path !== target.path;\n if (current) {\n for (const mode of modesOf(current)) {\n const d = doc(fileFor(current, mode));\n if (target.values[mode] === undefined) removeToken(d, current.path);\n else if (renamed) moveToken(d, current.path, target.path);\n }\n }\n\n const targetScopes = effectiveScopes(target);\n const scopesExt = sameScopes(targetScopes, defaultScopes(target.path, target.type, target.tier)) ? undefined : targetScopes;\n const scopesChanged = !current || !sameScopes(targetScopes, effectiveScopes(current));\n const descChanged = (target.description ?? '').trim() !== (current?.description ?? '').trim();\n\n for (const mode of modesOf(target)) {\n const d = doc(fileFor(target, mode, current));\n const existing = readTokenAt(d, target.path);\n const currentValue = current?.values[mode];\n // Keep main's exact spelling when the value is equal (Figma returns float noise).\n const value = currentValue !== undefined && valuesEqual(target.type, target.values[mode], currentValue) ? currentValue : target.values[mode];\n const extensions: Record<string, unknown> = {};\n if (scopesChanged) extensions[EXT_SCOPES] = scopesExt;\n if (renamed || !existing) extensions[EXT_ID] = idExtensionFor(target);\n upsertToken(d, target.path, {\n type: target.type,\n value,\n description: descChanged || !existing ? target.description : existing.description,\n extensions,\n });\n }\n }\n\n const files: Record<string, string> = {};\n const allFiles: Record<string, string> = { ...originals };\n for (const [file, d] of docs) {\n const text = serializeTokenFile(d);\n allFiles[file] = text;\n if (text !== originals[file]) files[file] = text;\n }\n return { files, allFiles };\n}\n","// Library protection: Bridge is the only way into the default branch. Whatever writes (Claude Code, Claude Design,\n// a developer, the MCP server), the change lands on a branch and reaches the default branch through a reviewed pull\n// request. GitHub enforces it with a repository ruleset on the default branch; this module builds that ruleset and\n// reads whether the default branch is protected, from rulesets and from classic branch protection.\n//\n// Pure: no fetch, no DOM. The GitHub reads live in github-client.ts (listRulesets, getRuleset, getBranchProtection,\n// listCheckRuns); Studio, the CLI and the MCP server share these functions.\n\n/** A ruleset rule as GitHub returns and accepts it. */\nexport interface RulesetRule {\n type: string;\n parameters?: Record<string, unknown>;\n}\n\nexport interface RulesetBypassActor {\n actor_id: number | null;\n actor_type: 'RepositoryRole' | 'Team' | 'Integration' | 'OrganizationAdmin' | 'DeployKey';\n bypass_mode: 'always' | 'pull_request';\n}\n\n/** A repository ruleset (GET /repos/{o}/{r}/rulesets/{id}). The list endpoint leaves out `rules`. */\nexport interface Ruleset {\n id?: number;\n name: string;\n target?: 'branch' | 'tag' | 'push' | string;\n enforcement: 'active' | 'evaluate' | 'disabled' | string;\n conditions?: { ref_name?: { include?: string[]; exclude?: string[] } } | null;\n rules?: RulesetRule[];\n bypass_actors?: RulesetBypassActor[];\n /** Where the ruleset is edited on GitHub. */\n html_url?: string;\n _links?: { html?: { href?: string } };\n}\n\n/** The body of POST /repos/{o}/{r}/rulesets. */\nexport interface RulesetPayload {\n name: string;\n target: 'branch';\n enforcement: 'active';\n conditions: { ref_name: { include: string[]; exclude: string[] } };\n rules: RulesetRule[];\n bypass_actors: RulesetBypassActor[];\n}\n\n/**\n * Classic branch protection (GET /repos/{o}/{r}/branches/{b}/protection), the fields Bridge reads.\n * `null` means the branch has none; `undefined` means it could not be read (no token, no admin access).\n */\nexport interface ClassicProtection {\n required_pull_request_reviews?: { required_approving_review_count?: number } | null;\n required_status_checks?: { contexts?: string[]; checks?: { context: string }[] } | null;\n allow_force_pushes?: { enabled: boolean } | null;\n allow_deletions?: { enabled: boolean } | null;\n}\n\n/** What protecting the library takes, in the order Studio names them. */\nexport type ProtectionPart = 'review' | 'checks' | 'history' | 'deletion';\nexport const PROTECTION_PARTS: readonly ProtectionPart[] = ['review', 'checks', 'history', 'deletion'];\n\nexport type ProtectionKind = 'protected' | 'partial' | 'unprotected' | 'unknown';\n\nexport interface ProtectionState {\n kind: ProtectionKind;\n /** Parts not enforced on the default branch (empty when protected; every part when unprotected or unknown). */\n missing: ProtectionPart[];\n /** The Bridge ruleset (by name), when one exists, active or not: \"Complete protection\" updates it in place. */\n bridgeRulesetId?: number;\n /** Where to see the rule that protects the branch on GitHub, when one does. */\n url?: string;\n}\n\n/** The name Bridge gives its ruleset. Bridge finds it again by this name. */\nexport const protectionRulesetName = (defaultBranch: string) => `Protect the library (${defaultBranch})`;\n\n/** GitHub's built-in repository role id for \"Admin\", used in bypass_actors. */\nexport const ADMIN_ROLE_ID = 5;\n\nexport interface ProtectionOptions {\n /** Check names that must pass before a merge (see requiredCheckNames). Empty: no checks rule. */\n checks: string[];\n /** Approvals a pull request needs. Never below 1. */\n approvals: number;\n /** Let repository admins merge a pull request without its approvals (the owner override). */\n adminBypass: boolean;\n}\n\n/**\n * The ruleset that protects the library. Choices:\n * - Target `~DEFAULT_BRANCH`, not a branch name: it follows a rename of the default branch.\n * - `deletion` and `non_fast_forward`: nobody deletes the default branch or rewrites its history.\n * - `pull_request` with at least 1 approval: every change goes through a reviewed pull request, direct pushes are\n * refused whoever pushes. Stale approvals are dismissed on a new push, so what was approved is what merges.\n * Code owner review and \"approval of the most recent push\" stay off: CODEOWNERS often holds placeholders, and a\n * team of two must still be able to ship.\n * - `required_status_checks`: the CI jobs that ran on recent pull requests must pass. Not strict (the branch does\n * not have to be up to date), which keeps merges from queueing behind each other.\n * - Bypass: repository admins in `pull_request` mode only. They keep the owner override (merge a pull request\n * whose approvals are missing) but cannot push to the default branch either.\n */\nexport function protectionRuleset(config: { repo?: { defaultBranch?: string } | undefined } | null | undefined, opts: ProtectionOptions): RulesetPayload {\n const branch = config?.repo?.defaultBranch ?? 'main';\n const approvals = Math.max(1, Math.floor(Number.isFinite(opts.approvals) ? opts.approvals : 1));\n const checks = [...new Set(opts.checks.map((c) => c.trim()).filter(Boolean))];\n const rules: RulesetRule[] = [\n { type: 'deletion' },\n { type: 'non_fast_forward' },\n {\n type: 'pull_request',\n parameters: {\n required_approving_review_count: approvals,\n dismiss_stale_reviews_on_push: true,\n require_code_owner_review: false,\n require_last_push_approval: false,\n required_review_thread_resolution: false,\n },\n },\n ];\n if (checks.length) {\n rules.push({\n type: 'required_status_checks',\n parameters: {\n strict_required_status_checks_policy: false,\n required_status_checks: checks.map((context) => ({ context })),\n },\n });\n }\n return {\n name: protectionRulesetName(branch),\n target: 'branch',\n enforcement: 'active',\n conditions: { ref_name: { include: ['~DEFAULT_BRANCH'], exclude: [] } },\n rules,\n bypass_actors: opts.adminBypass ? [{ actor_id: ADMIN_ROLE_ID, actor_type: 'RepositoryRole', bypass_mode: 'pull_request' }] : [],\n };\n}\n\n/** Minimal check run shape (github-client CheckRun fits). `app` is the GitHub App slug when known. */\nexport interface CheckRunLike {\n name: string;\n status?: string;\n conclusion: string | null;\n app?: string | undefined;\n}\n\nconst isVercel = (r: CheckRunLike) => /vercel/i.test(r.app ?? '') || /^vercel\\b/i.test(r.name);\nconst ran = (r: CheckRunLike) => r.conclusion !== 'skipped' && r.conclusion !== 'cancelled' && r.conclusion !== 'stale';\n\n/**\n * The check names to require, read from the repository's own CI, never hardcoded: the check runs of the default\n * branch's latest commit, without Vercel (deploy previews, not tests) and without skipped ones. When the head of a\n * recent pull request is given, only checks that also ran there are kept: a job that runs on pushes to the default\n * branch only (a release job) never reports on a pull request, and requiring it would block every merge.\n */\nexport function requiredCheckNames(defaultBranchRuns: CheckRunLike[], pullRequestRuns?: CheckRunLike[]): string[] {\n const names = [...new Set(defaultBranchRuns.filter((r) => !isVercel(r) && ran(r)).map((r) => r.name))];\n if (!pullRequestRuns?.length) return names;\n const onPulls = new Set(pullRequestRuns.filter((r) => !isVercel(r)).map((r) => r.name));\n return names.filter((n) => onPulls.has(n));\n}\n\n/** Converts a ref pattern (fnmatch: `*` within a segment, `**` across) to a RegExp. */\nfunction refPattern(pattern: string): RegExp {\n const src = pattern\n .replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\*\\*/g, '\\u0000')\n .replace(/\\*/g, '[^/]*')\n .replace(/\\?/g, '[^/]')\n .replace(/\\u0000/g, '.*');\n return new RegExp(`^${src}$`);\n}\n\n/** True when a branch ruleset's conditions cover the default branch. */\nexport function rulesetTargetsDefault(ruleset: Ruleset, defaultBranch: string): boolean {\n if (ruleset.target && ruleset.target !== 'branch') return false;\n const ref = `refs/heads/${defaultBranch}`;\n const hit = (p: string) => p === '~ALL' || p === '~DEFAULT_BRANCH' || p === ref || p === defaultBranch || refPattern(p.startsWith('refs/') ? p : `refs/heads/${p}`).test(ref);\n const cond = ruleset.conditions?.ref_name;\n // A repository ruleset with no ref condition applies to nothing; GitHub requires one.\n if (!cond) return false;\n if ((cond.exclude ?? []).some(hit)) return false;\n return (cond.include ?? []).some(hit);\n}\n\nconst count = (v: unknown) => (typeof v === 'number' ? v : 0);\n\n/** The parts one ruleset enforces (active rulesets only; \"evaluate\" only reports). */\nfunction rulesetParts(ruleset: Ruleset): Set<ProtectionPart> {\n const parts = new Set<ProtectionPart>();\n if (ruleset.enforcement !== 'active') return parts;\n for (const rule of ruleset.rules ?? []) {\n if (rule.type === 'deletion') parts.add('deletion');\n if (rule.type === 'non_fast_forward') parts.add('history');\n if (rule.type === 'pull_request' && count(rule.parameters?.required_approving_review_count) >= 1) parts.add('review');\n if (rule.type === 'required_status_checks' && Array.isArray(rule.parameters?.required_status_checks) && (rule.parameters.required_status_checks as unknown[]).length > 0) parts.add('checks');\n }\n return parts;\n}\n\n/** The parts classic branch protection enforces. Force pushes and deletions are refused unless allowed. */\nfunction classicParts(p: ClassicProtection): Set<ProtectionPart> {\n const parts = new Set<ProtectionPart>();\n if (count(p.required_pull_request_reviews?.required_approving_review_count) >= 1) parts.add('review');\n if (((p.required_status_checks?.contexts?.length ?? 0) || (p.required_status_checks?.checks?.length ?? 0)) > 0) parts.add('checks');\n if (!p.allow_force_pushes?.enabled) parts.add('history');\n if (!p.allow_deletions?.enabled) parts.add('deletion');\n return parts;\n}\n\nconst rulesetUrl = (r: Ruleset) => r.html_url ?? r._links?.html?.href;\n\n/**\n * Whether the default branch is protected, from full rulesets (with `rules`; null when they could not be read) and\n * classic branch protection (null when the branch has none, undefined when it could not be read).\n * - protected: review, checks, no history rewrite and no deletion are all enforced.\n * - partial: some of them are.\n * - unprotected: none of them, and both sources were read.\n * - unknown: nothing could be read, or nothing was found in one source while the other could not be read.\n */\nexport function protectionState(rulesets: Ruleset[] | null | undefined, branchProtection: ClassicProtection | null | undefined, defaultBranch: string): ProtectionState {\n const bridge = rulesets?.find((r) => r.name === protectionRulesetName(defaultBranch));\n const extra = bridge?.id !== undefined ? { bridgeRulesetId: bridge.id } : {};\n const covered = new Set<ProtectionPart>();\n let url: string | undefined;\n for (const r of rulesets ?? []) {\n if (!rulesetTargetsDefault(r, defaultBranch)) continue;\n const parts = rulesetParts(r);\n if (parts.size && !url) url = rulesetUrl(r);\n parts.forEach((p) => covered.add(p));\n }\n if (branchProtection) classicParts(branchProtection).forEach((p) => covered.add(p));\n const missing = PROTECTION_PARTS.filter((p) => !covered.has(p));\n const withUrl = url ? { url } : {};\n if (!missing.length) return { kind: 'protected', missing, ...extra, ...withUrl };\n const unreadable = rulesets == null || branchProtection === undefined;\n if (covered.size === 0) return { kind: unreadable ? 'unknown' : 'unprotected', missing, ...extra };\n return { kind: 'partial', missing, ...extra, ...withUrl };\n}\n\n/** Plain words for each part, for designers: no \"ruleset\", \"branch\" or \"force push\". */\nexport const PROTECTION_PART_PHRASE: Record<ProtectionPart, string> = {\n review: 'changes can skip review',\n checks: 'checks do not have to pass',\n history: 'past changes can be rewritten',\n deletion: 'the library can be deleted',\n};\n\nconst joinAnd = (xs: string[]) => (xs.length <= 1 ? (xs[0] ?? '') : `${xs.slice(0, -1).join(', ')} and ${xs[xs.length - 1]}`);\n\n/** The one sentence Studio, the CLI and the MCP server show for a protection state. */\nexport function protectionSentence(state: ProtectionState): string {\n switch (state.kind) {\n case 'protected':\n return 'Protected: every change goes through review.';\n case 'unprotected':\n return 'Your library can be changed without review.';\n case 'partial': {\n const s = joinAnd(state.missing.map((p) => PROTECTION_PART_PHRASE[p]));\n return `Partly protected: ${s}.`;\n }\n default:\n return 'Protection status unknown: GitHub did not let this token read it.';\n }\n}\n","// Library protection over the GitHub client: read the state of the default branch, read the checks to require,\n// and create (or complete) the Bridge ruleset. Studio, the CLI and the MCP server call these.\n\nimport { GitHubError, type GitHubClient } from './github-client';\nimport { type ProtectionOptions, protectionRuleset, type ProtectionState, protectionState, requiredCheckNames, type Ruleset } from './protection';\n\n/**\n * The protection of `defaultBranch`. Rulesets are listed (read access is enough), then read one by one for their\n * rules; classic branch protection is read too. Whatever cannot be read counts as unknown, never as unprotected.\n */\nexport async function loadProtection(client: GitHubClient, defaultBranch: string): Promise<ProtectionState> {\n const rulesets = await client\n .listRulesets()\n // Disabled rulesets enforce nothing: kept as listed (the Bridge one is still found by name, to update it).\n .then((list) => Promise.all(list.map((r) => (r.enforcement === 'disabled' || r.id === undefined ? r : client.getRuleset(r.id)))))\n // Any failure (no access, a repo GitHub hides behind a 404, rate limit) leaves the state unknown.\n .catch((): Ruleset[] | null => null);\n const classic = await client.getBranchProtection(defaultBranch).catch(() => undefined);\n return protectionState(rulesets, classic, defaultBranch);\n}\n\n/** The checks to require: the default branch's latest check runs, kept to those the last merged pull request ran. */\nexport async function loadRequiredChecks(client: GitHubClient, defaultBranch: string): Promise<string[]> {\n const onDefault = await client.listCheckRuns(defaultBranch).catch(() => []);\n const merged = await client\n .listPullRequests('closed')\n .then((prs) => prs.find((p) => p.state === 'merged' && p.baseRef === defaultBranch))\n .catch(() => undefined);\n const onPull = merged?.headSha ? await client.listCheckRuns(merged.headSha).catch(() => []) : [];\n return requiredCheckNames(onDefault, onPull);\n}\n\n/**\n * Turns protection on: creates the Bridge ruleset, or replaces it when one with its name exists (Complete\n * protection). Needs a token with admin on the repository; GitHub's refusal is thrown as a GitHubError.\n */\nexport async function protectLibrary(\n client: GitHubClient,\n defaultBranch: string,\n opts: Partial<ProtectionOptions> & { state?: ProtectionState } = {},\n): Promise<Ruleset> {\n const checks = opts.checks ?? (await loadRequiredChecks(client, defaultBranch));\n const payload = protectionRuleset({ repo: { defaultBranch } }, { checks, approvals: opts.approvals ?? 1, adminBypass: opts.adminBypass ?? true });\n const id = opts.state?.bridgeRulesetId;\n return id !== undefined ? client.updateRuleset(id, payload) : client.createRuleset(payload);\n}\n\n/** GitHub's message when the plan does not allow rulesets on a private repository. */\nconst PLAN_REFUSED = /upgrade to github (pro|team)|make this repository public|not available for private repositories/i;\n\n/** True when GitHub refused the ruleset because of the repository's plan, not the token. */\nexport const isPlanRefusal = (err: unknown) => err instanceof GitHubError && (err.status === 403 || err.status === 422) && PLAN_REFUSED.test(`${err.detail ?? ''} ${err.message}`);\n\n/** Where rulesets are managed on GitHub. */\nexport const rulesSettingsUrl = (owner: string, repo: string) => `https://github.com/${owner}/${repo}/settings/rules`;\n\n/**\n * The one sentence for a refused \"Protect the library\": the plan, the token's permission, or admin access.\n * Null for any other failure (the caller shows GitHub's message).\n */\nexport function protectRefusal(err: unknown): string | null {\n if (!(err instanceof GitHubError)) return null;\n if (isPlanRefusal(err)) return \"GitHub's plan for this private repository does not include protection rules. Upgrade the plan or make the repository public, then try again.\";\n // \"Must have admin rights\": the person is not an admin, whatever the token allows.\n if (/admin rights/i.test(`${err.detail ?? ''}`)) return 'Only a repository admin can protect the library. Ask an admin, or set it up in GitHub settings.';\n if (err.auth === 'missing-permission') return 'This token cannot change the protection. Add Administration: Read and write to the token on GitHub, then try again.';\n if (err.status === 403 || err.status === 404) return 'Only a repository admin can protect the library. Ask an admin, or set it up in GitHub settings.';\n return null;\n}\n","// Usage index: which CSS custom properties each component module reads, and which other components it renders.\n// Pure text scanning (no CSS or TypeScript parser), so it runs in Node, the browser and the Figma sandbox alike.\n// Used by visual impact analysis to go from changed tokens and files to the components (and stories) to look at.\n\nexport interface UsageFile {\n /** Repo-relative path with forward slashes. */\n path: string;\n text: string;\n}\n\nexport interface UsageModule {\n /** Component folder name, e.g. \"Button\". */\n id: string;\n dir: string;\n files: string[];\n /** CSS custom properties read with var(), sorted. Includes locally defined ones. */\n vars: string[];\n /** Other components this one imports from its source (stories and tests excluded), sorted. */\n imports: string[];\n /** Components that only its stories import (e.g. a Button inside an Alert story), sorted. */\n storyImports: string[];\n}\n\nexport interface UsageIndex {\n componentsDir: string;\n modules: Record<string, UsageModule>;\n /** CSS custom property -> modules that read it. */\n byVar: Record<string, string[]>;\n /** CSS custom properties read by files outside the component folders (global styles, theme). */\n globalVars: Record<string, string[]>;\n}\n\nconst VAR_RE = /var\\(\\s*(--[A-Za-z0-9_-]+)/g;\nconst IMPORT_RE = /(?:import|export)\\s[^'\"]*?from\\s*['\"]([^'\"]+)['\"]|import\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g;\n\n/** CSS custom properties read with `var(--x)` in a stylesheet or a style string, in order of first use. */\nexport function cssVarsIn(text: string): string[] {\n const out = new Set<string>();\n for (const m of text.matchAll(VAR_RE)) out.add(m[1]!);\n return [...out];\n}\n\n/** Module specifiers a TS/JS file imports or re-exports. */\nexport function importsIn(text: string): string[] {\n const out = new Set<string>();\n for (const m of text.matchAll(IMPORT_RE)) out.add((m[1] ?? m[2])!);\n return [...out];\n}\n\nconst norm = (p: string) => p.replace(/\\\\/g, '/').replace(/\\/+$/, '');\nconst isStory = (p: string) => /\\.stories\\.[cm]?[jt]sx?$/.test(p);\nconst isTest = (p: string) => /\\.(test|spec)\\.[cm]?[jt]sx?$/.test(p);\nconst isCss = (p: string) => /\\.(css|scss|less)$/.test(p);\nconst isScript = (p: string) => /\\.[cm]?[jt]sx?$/.test(p);\n\n/** Resolves a relative specifier from a file to the component folder it lands in, if any. */\nfunction componentOf(from: string, spec: string, componentsDir: string): string | null {\n if (!spec.startsWith('.')) return null;\n const parts = from.split('/').slice(0, -1);\n for (const seg of spec.split('/')) {\n if (seg === '.' || seg === '') continue;\n if (seg === '..') parts.pop();\n else parts.push(seg);\n }\n const abs = parts.join('/');\n if (!abs.startsWith(`${componentsDir}/`)) return null;\n return abs.slice(componentsDir.length + 1).split('/')[0] || null;\n}\n\n/** The component folder a repo path belongs to, or null when it is outside `componentsDir`. */\nexport function componentForPath(path: string, componentsDir: string): string | null {\n const dir = norm(componentsDir);\n const p = norm(path);\n if (!p.startsWith(`${dir}/`)) return null;\n const rest = p.slice(dir.length + 1).split('/');\n return rest.length >= 2 ? rest[0]! : null;\n}\n\n/**\n * Builds the index from the files of a component library. `componentsDir` holds one folder per component\n * (`<dir>/<Name>/...`); every other file is \"global\" (styles, theme, story helpers) and only its CSS\n * variables are recorded.\n */\nexport function buildUsageIndex(files: UsageFile[], componentsDir: string): UsageIndex {\n const dir = norm(componentsDir);\n const modules: Record<string, UsageModule> = {};\n const vars = new Map<string, Set<string>>();\n const imports = new Map<string, Set<string>>();\n const storyImports = new Map<string, Set<string>>();\n const globalVars: Record<string, string[]> = {};\n const get = (m: Map<string, Set<string>>, k: string) => m.get(k) ?? m.set(k, new Set()).get(k)!;\n\n for (const f of files) {\n const path = norm(f.path);\n const id = componentForPath(path, dir);\n if (!id) {\n if (isCss(path)) {\n const v = cssVarsIn(f.text);\n if (v.length) globalVars[path] = v.sort();\n }\n continue;\n }\n const mod = (modules[id] ??= { id, dir: `${dir}/${id}`, files: [], vars: [], imports: [], storyImports: [] });\n mod.files.push(path);\n if (isTest(path)) continue;\n // Inline styles in TSX can read variables too (style={{ color: 'var(--x)' }}).\n for (const v of cssVarsIn(f.text)) get(vars, id).add(v);\n if (!isScript(path)) continue;\n for (const spec of importsIn(f.text)) {\n const dep = componentOf(path, spec, dir);\n if (!dep || dep === id) continue;\n get(isStory(path) ? storyImports : imports, id).add(dep);\n }\n }\n\n const byVar: Record<string, string[]> = {};\n for (const mod of Object.values(modules)) {\n mod.files.sort();\n mod.vars = [...(vars.get(mod.id) ?? [])].sort();\n mod.imports = [...(imports.get(mod.id) ?? [])].sort();\n mod.storyImports = [...(storyImports.get(mod.id) ?? [])].filter((d) => !mod.imports.includes(d)).sort();\n for (const v of mod.vars) (byVar[v] ??= []).push(mod.id);\n }\n for (const k of Object.keys(byVar)) byVar[k]!.sort();\n return { componentsDir: dir, modules, byVar, globalVars };\n}\n\nexport interface ImpactedModule {\n id: string;\n /** Why: \"uses --color-feedback-danger-solid\", \"file changed: ...\", \"renders Button\". */\n reasons: string[];\n /** True when reached only through another component it renders. */\n indirect: boolean;\n}\n\nexport interface ModuleImpact {\n modules: ImpactedModule[];\n /** Global stylesheets that read a changed variable. */\n globalHits: { file: string; vars: string[] }[];\n}\n\n/**\n * Components affected by changed CSS variables and changed files, closed over \"renders\": when Button changes,\n * every component that imports Button changes too.\n */\nexport function impactedModules(index: UsageIndex, input: { vars?: string[]; files?: string[] }): ModuleImpact {\n const reasons = new Map<string, { reasons: string[]; indirect: boolean }>();\n const add = (id: string, reason: string, indirect: boolean) => {\n const r = reasons.get(id);\n if (r) {\n if (!r.reasons.includes(reason)) r.reasons.push(reason);\n r.indirect &&= indirect;\n } else reasons.set(id, { reasons: [reason], indirect });\n };\n const changedVars = new Set(input.vars ?? []);\n for (const v of changedVars) for (const id of index.byVar[v] ?? []) add(id, `uses ${v}`, false);\n for (const f of input.files ?? []) {\n const id = componentForPath(f, index.componentsDir);\n if (id && index.modules[id]) add(id, `file changed: ${norm(f)}`, false);\n }\n // Reverse \"renders\" edges, breadth first so the closest reason is listed first.\n const renderedBy = new Map<string, string[]>();\n for (const m of Object.values(index.modules)) for (const d of m.imports) (renderedBy.get(d) ?? renderedBy.set(d, []).get(d)!).push(m.id);\n const queue = [...reasons.keys()];\n while (queue.length) {\n const id = queue.shift()!;\n for (const parent of renderedBy.get(id) ?? []) {\n const known = reasons.has(parent);\n add(parent, `renders ${id}`, true);\n if (!known) queue.push(parent);\n }\n }\n const globalHits = Object.entries(index.globalVars)\n .map(([file, vs]) => ({ file, vars: vs.filter((v) => changedVars.has(v)) }))\n .filter((g) => g.vars.length > 0);\n const modules = [...reasons.entries()].map(([id, r]) => ({ id, reasons: r.reasons, indirect: r.indirect })).sort((a, b) => Number(a.indirect) - Number(b.indirect) || a.id.localeCompare(b.id));\n return { modules, globalHits };\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// Token usage: which tokens are in use. One definition for every surface (Overview, Checks, the token explorer).\n\nexport interface UsageToken {\n path: string;\n /** CSS custom property the token builds to, e.g. \"--color-bg-default\". */\n cssVar: string;\n /** Token paths this token resolves through, in any mode (its alias chains). May include the token itself. */\n refs: readonly string[];\n}\n\nexport interface TokenReads {\n /** CSS custom property -> components that read it (UsageIndex.byVar). */\n byVar?: Record<string, readonly string[]>;\n /** Global stylesheet -> CSS custom properties it reads (UsageIndex.globalVars): base styles, app shell, theme. */\n globalVars?: Record<string, readonly string[]>;\n}\n\nexport interface TokenUsage {\n /** Paths of every token in use. */\n used: Set<string>;\n /** Paths read directly with var(), by a component or a global stylesheet. */\n direct: Set<string>;\n}\n\n/**\n * A token is in use when a component stylesheet or a global stylesheet (base styles, the app shell) reads its\n * variable, or when a token in use aliases it, at any depth and in any mode. Everything else is unused.\n */\nexport function tokenUsage(tokens: readonly UsageToken[], reads: TokenReads): TokenUsage {\n const readVars = new Set<string>();\n for (const [v, mods] of Object.entries(reads.byVar ?? {})) if (mods.length) readVars.add(v);\n for (const vars of Object.values(reads.globalVars ?? {})) for (const v of vars) readVars.add(v);\n const byPath = new Map(tokens.map((t) => [t.path, t]));\n const direct = new Set(tokens.filter((t) => readVars.has(t.cssVar)).map((t) => t.path));\n const used = new Set<string>();\n const queue = [...direct];\n while (queue.length) {\n const p = queue.pop()!;\n if (used.has(p)) continue;\n used.add(p);\n for (const r of byPath.get(p)?.refs ?? []) if (!used.has(r) && byPath.has(r)) queue.push(r);\n }\n return { used, direct };\n}\n","// History from GitHub over REST, in the browser or Node: commits that touched the tokens root on a ref,\n// the pull request each one belongs to, token files at each side of the change (blobs cached by sha, so\n// files that did not change are read once), changesets the change added, tags and the CHANGELOG.\n\nimport type { BridgeConfig } from './config';\nimport type { GitHubClient, TreeEntry } from './github-client';\nimport { type HistoryBackend, type HistoryCommit, type HistoryReport, buildReport, collectHistory, mergeReleases, packageDirCandidates, parseChangelog, releasesFromTags } from './history';\nimport { selectTokenFiles } from './layered';\n\nexport function gitHubHistoryBackend(client: GitHubClient, config: BridgeConfig, opts: { concurrency?: number } = {}): HistoryBackend & { tree(sha: string): Promise<TreeEntry[]> } {\n const trees = new Map<string, Promise<TreeEntry[]>>();\n const tree = (sha: string) => {\n let t = trees.get(sha);\n if (!t) {\n t = client.getCommitTree(sha).then((ts) => client.getTree(ts, true)).then((r) => r.entries);\n trees.set(sha, t);\n }\n return t;\n };\n const root = config.tokens.root.replace(/\\/$/, '');\n const prefix = root === '.' || !root ? '' : `${root}/`;\n const limit = Math.max(1, opts.concurrency ?? 4);\n const pool = async <T, R>(items: T[], fn: (x: T) => Promise<R>): Promise<R[]> => {\n const out: R[] = new Array(items.length);\n let i = 0;\n await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {\n for (let k = i++; k < items.length; k = i++) out[k] = await fn(items[k]!);\n }));\n return out;\n };\n\n return {\n tree,\n async listCommits({ ref, paths, limit: max }) {\n const commits: HistoryCommit[] = [];\n for (let page = 1; commits.length < max && page <= 10; page++) {\n const batch = await client.listCommits({ sha: ref, path: paths[0], perPage: Math.min(100, max), page });\n for (const c of batch) {\n const [subject, ...rest] = c.message.split('\\n');\n commits.push({ sha: c.sha, parents: c.parents, date: c.date, author: c.author, subject: subject ?? '', body: rest.join('\\n').trim() });\n }\n if (batch.length < Math.min(100, max)) break;\n }\n const list = commits.slice(0, max);\n // The pull request of each commit. A branch commit of a merged PR is replaced by the PR's merge commit,\n // so the entry diffs the whole PR as it landed.\n const merges = new Map<string, Promise<HistoryCommit | undefined>>();\n const enriched = await pool(list, async (c) => {\n const prs = await client.listPullRequestsForCommit(c.sha).catch(() => []);\n const pr = prs.find((p) => p.mergedAt && p.baseRef === ref) ?? prs.find((p) => p.mergedAt);\n if (!pr) return c;\n const prInfo = { number: pr.number, title: pr.title, url: pr.url, author: pr.author, ...(pr.mergedAt ? { mergedAt: pr.mergedAt } : {}), body: pr.body };\n if (pr.mergeCommitSha && pr.mergeCommitSha !== c.sha) {\n let m = merges.get(pr.mergeCommitSha);\n if (!m) {\n m = client.getCommitInfo(pr.mergeCommitSha).then(\n (info) => {\n const [subject, ...rest] = info.message.split('\\n');\n return { sha: info.sha, parents: info.parents, date: pr.mergedAt ?? info.date, author: info.author, subject: subject ?? '', body: rest.join('\\n').trim() };\n },\n () => undefined,\n );\n merges.set(pr.mergeCommitSha, m);\n }\n const merge = await m;\n if (merge) return { ...merge, pr: prInfo };\n }\n return { ...c, ...(pr.mergedAt ? { date: pr.mergedAt } : {}), pr: prInfo };\n });\n return enriched;\n },\n async tokenFiles(sha) {\n const entries = await tree(sha);\n const blobs = entries.filter((e) => e.type === 'blob' && e.path.startsWith(prefix));\n const picked = new Set(selectTokenFiles(config, blobs.map((e) => e.path)));\n const wanted = blobs.filter((e) => picked.has(prefix ? e.path.slice(prefix.length) : e.path));\n const texts = await pool(wanted, async (e) => [prefix ? e.path.slice(prefix.length) : e.path, await client.getBlobText(e.sha)] as const);\n return new Map(texts);\n },\n async changesetPaths(sha) {\n const dir = config.changesets?.dir.replace(/\\/$/, '');\n if (!dir) return [];\n return (await tree(sha)).filter((e) => e.type === 'blob' && e.path.startsWith(`${dir}/`)).map((e) => e.path);\n },\n async readFile(sha, path) {\n const e = (await tree(sha)).find((x) => x.type === 'blob' && x.path === path);\n return e ? client.getBlobText(e.sha) : null;\n },\n };\n}\n\n/** The whole history report for a GitHub repo: entries, releases (tags and CHANGELOG), timeline. */\nexport async function loadGitHubHistory(client: GitHubClient, config: BridgeConfig, opts: { ref?: string; limit?: number; onProgress?: (done: number, total: number) => void } = {}): Promise<HistoryReport> {\n const ref = opts.ref ?? config.repo?.defaultBranch ?? (await client.getDefaultBranch());\n const limit = opts.limit ?? 30;\n const backend = gitHubHistoryBackend(client, config);\n let listed = 0;\n const counted: HistoryBackend = { ...backend, listCommits: async (o) => {\n const r = await backend.listCommits(o);\n listed = r.length;\n return r;\n } };\n const entries = await collectHistory(config, counted, { ref, limit, ...(opts.onProgress ? { onProgress: opts.onProgress } : {}) });\n const head = await client.getBranchSha(ref).catch(() => undefined);\n let changelog: ReturnType<typeof parseChangelog> = [];\n let currentVersion: string | undefined;\n if (head) {\n const files = await backend.tree(head).catch(() => [] as TreeEntry[]);\n for (const dir of packageDirCandidates(config)) {\n const p = (f: string) => (dir ? `${dir}/${f}` : f);\n const cl = files.find((e) => e.path === p('CHANGELOG.md'));\n const pkg = files.find((e) => e.path === p('package.json'));\n if (!cl && !pkg) continue;\n if (cl) changelog = parseChangelog(await client.getBlobText(cl.sha));\n if (pkg) {\n try {\n const json = JSON.parse(await client.getBlobText(pkg.sha)) as { name?: string; version?: string };\n if (!config.changesets || json.name === config.changesets.package) currentVersion = json.version;\n } catch {\n /* not JSON: no version */\n }\n }\n break;\n }\n }\n const tagList = await client.listTags(30).catch(() => []);\n const tagReleases = releasesFromTags(tagList, config.changesets?.package);\n // Tag dates cost one request each: only the ten newest.\n await Promise.all(\n tagReleases.slice(0, 10).map(async (r) => {\n if (!r.sha) return;\n const info = await client.getCommitInfo(r.sha).catch(() => undefined);\n if (info?.date) r.date = info.date;\n }),\n );\n const releases = mergeReleases(changelog, tagReleases);\n return buildReport({ source: 'github', label: `${client.fullName}@${ref}`, ref, entries, releases, ...(currentVersion ? { currentVersion } : {}), truncated: listed >= limit });\n}\n","// Demo history: fixture entries built backwards from the CURRENT token files, so a revert or a restore\n// planned on them runs against the real base branch. For showing the History UI on a repo with little\n// history. Every entry is flagged `demo`, has no PR link, and the report says `demo: true`: surfaces show\n// it only behind an explicit, labelled toggle and never as real history.\n\nimport type { BridgeConfig } from './config';\nimport { type HistoryEntry, type HistoryReport, buildHistoryEntry, buildReport } from './history';\nimport { LayeredTokenSet } from './layered';\nimport { type TokenEdit, applyTokenEdits } from './token-edits';\n\ninterface DemoStep {\n pr: number;\n title: string;\n why: string;\n author: string;\n date: string;\n /** The values BEFORE this step; the values after it are whatever the next state holds. */\n before: TokenEdit[];\n}\n\nconst STEPS: DemoStep[] = [\n { pr: 101, title: 'Darken muted text for small sizes', why: 'Muted captions at 12px read too light on subtle surfaces in usability tests.', author: 'demo-designer', date: '2026-07-08T09:30:00Z', before: [{ op: 'set', path: 'color.text.muted', file: 'semantic/light.tokens.json', value: '{palette.neutral.500}' }] },\n { pr: 102, title: 'Rounder buttons', why: 'Buttons move to the control radius so they match inputs and selects.', author: 'demo-engineer', date: '2026-07-21T14:10:00Z', before: [{ op: 'set', path: 'button.radius', file: 'components/button.tokens.json', value: '{radius.inset}' }] },\n { pr: 104, title: 'Clarify the alert radius description', why: 'The description now says why alerts use the container radius.', author: 'demo-engineer', date: '2026-08-19T08:00:00Z', before: [{ op: 'set', path: 'alert.radius', file: 'components/feedback.tokens.json', description: 'Alert corner radius.' }] },\n { pr: 106, title: 'Muted text one step lighter', why: 'Muted text competed with body text in dense tables; one step lighter still passes 4.5:1.', author: 'demo-designer', date: '2026-09-30T16:45:00Z', before: [{ op: 'set', path: 'color.text.muted', file: 'semantic/light.tokens.json', value: '{palette.neutral.700}' }] },\n];\n\nexport const DEMO_RELEASES = [\n { version: '1.1.0', date: '2026-07-25T12:00:00Z' },\n { version: '1.2.0', date: '2026-08-25T12:00:00Z' },\n];\n\n/** Demo history over the current files. Steps whose tokens this repo does not have are left out. */\nexport function demoHistory(config: BridgeConfig, current: Map<string, string>): HistoryReport {\n const states: Map<string, string>[] = [current];\n const kept: DemoStep[] = [];\n for (const step of [...STEPS].reverse()) {\n try {\n const prev = applyTokenEdits(new LayeredTokenSet(config, states[0]!), step.before).files;\n states.unshift(prev);\n kept.unshift(step);\n } catch {\n /* this repo has no such token: skip the step */\n }\n }\n const entries: HistoryEntry[] = [];\n kept.forEach((step, i) => {\n const e = buildHistoryEntry({\n config,\n commit: { sha: `demo${String(step.pr).padStart(36, '0')}`, parents: [`demo${String(step.pr - 1).padStart(36, '0')}`], date: step.date, author: step.author, subject: step.title, body: step.why, pr: { number: step.pr, title: step.title, author: step.author, mergedAt: step.date, body: step.why } },\n before: states[i]!,\n after: states[i + 1]!,\n demo: true,\n });\n if (e) entries.push(e);\n });\n return { ...buildReport({ source: 'demo', label: 'Demo history (fixture data)', ref: 'demo', entries, releases: DEMO_RELEASES, truncated: false }), demo: true };\n}\n","// Real branch preview URLs read from GitHub: the deployments and commit statuses of the head commit and the Vercel\n// bot comment on the pull request, resolved by `resolveBranchPreviews` (previews.ts). Shared by the plugin, Studio,\n// the MCP server and the CLI, so none of them shows a guessed URL. See docs/PREVIEWS.md.\n\nimport type { BridgeConfig } from './config';\nimport type { GitHubClient } from './github-client';\nimport { resolveBranchPreviews, type BranchPreview, type PreviewApps } from './previews';\n\nexport interface BranchPreviewOptions {\n /** Branch and head commit when the caller knows them (skips reading the pull request). */\n branch?: string | undefined;\n sha?: string | undefined;\n /** The pull request's comments when the caller already read them (skips one read). */\n comments?: { body?: string | null | undefined }[] | undefined;\n}\n\n/**\n * The preview of each app configured in `previews.apps` for a pull request (by number) or a commit (by sha): the URL\n * Vercel reports (deployments, then commit statuses, then its PR comment), the template only when Vercel cannot have\n * shortened it, and whether the build of that commit is ready. A failed read leaves that source out, never throws for it.\n */\nexport async function branchPreviewUrls(gh: GitHubClient, ref: number | string, config: Pick<BridgeConfig, 'previews'> | { previews?: { apps?: PreviewApps | undefined } | undefined } | undefined, opts: BranchPreviewOptions = {}): Promise<BranchPreview[]> {\n const apps: PreviewApps = config?.previews?.apps ?? {};\n if (!Object.values(apps).some(Boolean)) return [];\n let pr: number | undefined;\n let branch = opts.branch;\n let sha = opts.sha;\n if (typeof ref === 'number') {\n pr = ref;\n if (!branch || !sha) {\n const p = await gh.getPullRequest(ref);\n branch ??= p.headRef;\n sha ??= p.headSha;\n }\n } else {\n sha = ref;\n if (!branch || !opts.comments) {\n const open = (await gh.listPullRequestsForCommit(ref).catch(() => [])).find((p) => p.state === 'open');\n if (open) {\n pr = open.number;\n branch ??= open.headRef;\n }\n }\n }\n const [comments, statuses, deployments] = await Promise.all([\n opts.comments ? Promise.resolve(opts.comments) : pr !== undefined ? gh.listIssueComments(pr).catch(() => []) : Promise.resolve([]),\n sha ? gh.listCommitStatuses(sha).catch(() => []) : Promise.resolve([]),\n sha ? gh.listDeployments(sha).catch(() => []) : Promise.resolve([]),\n ]);\n return resolveBranchPreviews(apps, { branch: branch ?? '', ...(pr !== undefined ? { pr } : {}), ...(sha ? { sha } : {}) }, { comments, statuses, deployments });\n}\n","// The Bridge ramp engine: OKLCH color ramps on one shared lightness ladder (docs/DESIGN-LANGUAGE.md, section 4).\n// Pure and dependency-free, written as plain JavaScript so two very different callers run the same code:\n// packages/tokens/scripts/ramps.mjs regenerates src/primitives/color.tokens.json (plain Node, no build)\n// @bridge-ds/core planNewBrand generates the palette of a new brand (plugin, docs site, CLI, MCP)\n// Types live next to it in ramps.d.ts. Change the algorithm here and both stay in step.\n\n/** Ramp steps, lightest first. */\nexport const STEPS = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950];\n\n/** OKLCH lightness of every step: the same step has the same perceived lightness whatever the hue. */\nexport const LIGHTNESS = { 50: 0.975, 100: 0.952, 200: 0.912, 300: 0.85, 400: 0.735, 500: 0.63, 600: 0.53, 700: 0.445, 800: 0.36, 900: 0.27, 950: 0.205 };\n\n/** Chroma bell: share of the peak chroma per step, peaking around 500 and 600. */\nexport const BELL = { 50: 0.12, 100: 0.22, 200: 0.4, 300: 0.62, 400: 0.85, 500: 1, 600: 1, 700: 0.92, 800: 0.8, 900: 0.62, 950: 0.5 };\n\n/** Bridge's ink anchors (Line, Ink secondary, Ink): pinned in the bridge neutral by scripts/ramps.mjs. */\nexport const NEUTRAL_ANCHORS = { 200: '#E3E8EE', 600: '#5B6672', 900: '#15202B' };\n\n/** How far a pinned brand hex may sit from its ladder step before the ramp stops reading as one family. */\nexport const PIN_TOLERANCE = 0.04;\n\n/** Chroma curve of a colored ramp (primary, status, accents). */\nexport const bellChroma = (peak) => (s) => peak * BELL[s];\n\n/** Chroma curve of a neutral ramp (ink, slate): nearly grey at the light end, a visible hue at the dark end. */\nexport const neutralChroma =\n (scale = 1, low = 0.004, base = 0.01, slope = 0.022) =>\n (s) =>\n (s <= 100 ? low : base + slope * (s / 950)) * scale;\n\nexport function oklchToLinear(L, C, h) {\n const hr = (h * Math.PI) / 180;\n const a = C * Math.cos(hr);\n const b = C * Math.sin(hr);\n const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3;\n const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3;\n const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3;\n return [\n 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,\n -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,\n -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s,\n ];\n}\n\nconst encode = (x) => {\n const c = Math.min(1, Math.max(0, x));\n return c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055;\n};\nconst decode = (x) => (x <= 0.04045 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4);\n\n/** sRGB (0..1 components) of an OKLCH color, gamut-mapped by lowering chroma until it fits. */\nexport function oklch(L, C, h) {\n let c = C;\n let lin = oklchToLinear(L, c, h);\n for (let i = 0; i < 60 && !lin.every((x) => x >= -0.0005 && x <= 1.0005); i++) {\n c *= 0.95;\n lin = oklchToLinear(L, c, h);\n }\n return lin.map(encode);\n}\n\n/** OKLCH of an sRGB color (0..1 components). Hue is 0 for greys. */\nexport function toOklch(rgb) {\n const [r, g, b] = rgb.map(decode);\n const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);\n const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);\n const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);\n const L = 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s;\n const A = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s;\n const B = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s;\n const C = Math.sqrt(A * A + B * B);\n const h = C < 1e-6 ? 0 : ((Math.atan2(B, A) * 180) / Math.PI + 360) % 360;\n return { L, C, h };\n}\n\nexport const isHex = (s) => typeof s === 'string' && /^#[0-9a-f]{6}$/i.test(s.trim());\nexport const fromHex = (hex) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255);\nexport const round3 = (x) => Math.round(x * 1000) / 1000;\nexport const toHex = (rgb) => '#' + rgb.map((x) => Math.round(x * 255).toString(16).padStart(2, '0')).join('');\n\n/** DTCG 2025.10 color value in the house form: { colorSpace, components, hex, alpha? }. */\nexport function dtcgColor(rgb, alpha) {\n const v = { colorSpace: 'srgb', components: rgb.map(round3), hex: toHex(rgb) };\n if (alpha !== undefined) v.alpha = alpha;\n return v;\n}\n\n/**\n * One ramp: step -> sRGB. `chroma(step)` and `offset(step)` shape it; `pins` replace steps with exact brand hexes,\n * so named brand colors survive regeneration.\n */\nexport function generateRamp({ hue, chroma, offset = () => 0, pins = {} }) {\n const out = {};\n for (const s of STEPS) {\n const pin = pins[s];\n out[s] = pin ? fromHex(pin) : oklch(LIGHTNESS[s] + offset(s), chroma(s), hue);\n }\n return out;\n}\n\n/** Ladder step whose lightness is closest to an sRGB color. */\nexport function nearestStep(rgb) {\n const { L } = toOklch(rgb);\n let best = STEPS[0];\n for (const s of STEPS) if (Math.abs(LIGHTNESS[s] - L) < Math.abs(LIGHTNESS[best] - L)) best = s;\n return best;\n}\n\n/**\n * A colored ramp anchored on a brand hex: hue from the hex, peak chroma so the curve passes through it, and the\n * hex pinned at `pinStep` (or at its nearest step). `distance` is how far the hex sits from the ladder lightness\n * of the pinned step; above PIN_TOLERANCE the ramp is no longer monotonic around the pin.\n */\nexport function anchoredRamp(hex, pinStep) {\n const rgb = fromHex(hex);\n const { L, C, h } = toOklch(rgb);\n const step = pinStep ?? nearestStep(rgb);\n const peak = Math.min(0.24, Math.max(0.02, C / BELL[step]));\n return { hue: h, peak, step, distance: Math.abs(L - LIGHTNESS[step]), ramp: generateRamp({ hue: h, chroma: bellChroma(peak), pins: { [step]: hex.toUpperCase() } }) };\n}\n\n/**\n * Lightness offsets of a generated neutral: the steps text and lines use sit exactly where Bridge's ink anchors\n * sit, so muted text (600) keeps its contrast on zones and subtle backgrounds in every new brand.\n */\nexport function neutralOffset() {\n const off = {};\n for (const [s, hex] of Object.entries(NEUTRAL_ANCHORS)) off[s] = toOklch(fromHex(hex)).L - LIGHTNESS[s];\n return (s) => off[s] ?? 0;\n}\n\n/** A neutral ramp tinted by a hex: hue from the hex, chroma scaled by how tinted it is (0 for a pure grey). */\nexport function tintedNeutral(hex) {\n const rgb = fromHex(hex);\n const { C, h } = toOklch(rgb);\n const ref = neutralChroma()(nearestStep(rgb));\n const scale = C < 0.004 ? 0 : Math.min(2.5, C / ref);\n return { hue: h, scale, ramp: generateRamp({ hue: h, chroma: neutralChroma(scale), offset: neutralOffset() }) };\n}\n","// New brands: one planner shared by the CLI (`bridge brand create`), the MCP server (bridge_plan_brand,\n// bridge_propose_brand), the Figma plugin (a new mode in the Brand collection) and the docs site Studio.\n//\n// A brand only re-points palette roles, radius roles, font roles and typography families (docs/DESIGN-LANGUAGE.md,\n// \"Second brand\"). planNewBrand copies a starting brand (or the default brand's structure for \"blank\"), fills\n// the primary, accent, link and neutral palette roles with ramps from the shared ramp engine (ramps.js, the\n// code packages/tokens/scripts/ramps.mjs runs), copies the starting brand's theme overrides when it has any,\n// adds the slug to modes.brand in bridge.config.json and runs the contrast gate for the new brand in every theme.\n// Nothing is written: the result lists files, contrast, validation, risk tier and a PR body; each surface decides\n// where the files go (a local branch, a remote pull request), never to the default branch.\n\nimport { CONFIG_FILE, type BridgeConfig, loadConfig, tokensPath, toConfigJson } from './config';\nimport { formatChangeset } from './changeset';\nimport { type Combo, type LayerIssue, LayeredTokenSet, validateLayered } from './layered';\nimport { type LayeredContrastResult, checkLayeredPair } from './layered-review';\nimport { RISK_LABELS, type RiskResult, classifyRisk } from './risk';\nimport { type Step, LIGHTNESS, PIN_TOLERANCE, STEPS, anchoredRamp, bellChroma, dtcgColor, fromHex, generateRamp, isHex, neutralChroma, neutralOffset, tintedNeutral, toOklch } from './ramps';\nimport { coerceValue } from './token-edits';\nimport { type ContrastPair, parseContrastChecks } from './wcag';\n\n// --- inputs -----------------------------------------------------------------------------------------------\n\n/** A ramp anchor: a \"#rrggbb\" brand color (pinned in the ramp) or an OKLCH hue in degrees (0..360). */\nexport type HueInput = string | number;\n\nexport interface BrandRadiusInput {\n /** px, on the radius scale (0, 2, 4, 6, 10, 12, 16, 20). */\n inset?: number;\n control?: number;\n container?: number;\n overlay?: number;\n}\n\nexport interface BrandFontsInput {\n /** Display and headings (typography display, h1, h2). A curated font id, see BRAND_FONTS. */\n heading?: string;\n /** Body, UI and captions (typography h3, body, ui, caption). */\n text?: string;\n}\n\nexport interface NewBrandInput {\n /** Lowercase letters, digits and single dashes, 2 to 24 characters: \"acme\", \"north-star\". */\n slug: string;\n /** Display name. Default: the slug in title case. */\n name?: string;\n /** Existing brand to start from, or \"blank\" (the default brand's structure, neutral type and no overrides). */\n from: string;\n /** Primary ramp (also accent and link unless set in `colors`). A hex is pinned at the step primary actions use. */\n primaryHue?: HueInput;\n /** Neutral ramp: text, lines, canvases. A hex tints it with its hue; a pure grey gives a pure grey ramp. */\n neutralHue?: HueInput;\n /** \"More colors\": separate ramps for accent (signal, focus ring) and link. */\n colors?: { accent?: HueInput; link?: HueInput };\n radius?: BrandRadiusInput;\n fonts?: BrandFontsInput;\n /** Exact values for brand tokens, by path (palette.primary.600, radius.control...): hex, \"12px\", \"{alias}\" or DTCG. */\n overrides?: Record<string, unknown>;\n}\n\n/** What the planner reads: the repo's config, its token files (relative to tokens.root) and contrast pairs. */\nexport interface BrandSource {\n config: BridgeConfig;\n /** bridge.config.json as written; edited with a minimal diff. Without it the canonical form is written. */\n configText?: string | undefined;\n files: Map<string, string> | Record<string, string>;\n /** contrast.checks.json text. */\n contrastText?: string | undefined;\n}\n\n// --- curated choices --------------------------------------------------------------------------------------\n\nexport interface BrandFont {\n id: string;\n label: string;\n /** Primitive token the role aliases. */\n token: string;\n /** Where it reads well: headings only (a display serif) or both. */\n use: 'heading' | 'both';\n}\n\n/** The short list the Studio offers. Every font here is self-hosted by @bridge-ds/tokens/fonts.css. */\nexport const BRAND_FONTS: BrandFont[] = [\n { id: 'fraunces', label: 'Fraunces', token: 'font.family.fraunces', use: 'heading' },\n { id: 'instrument-sans', label: 'Instrument Sans', token: 'font.family.instrument-sans', use: 'both' },\n { id: 'plex-sans', label: 'IBM Plex Sans', token: 'font.family.plex-sans', use: 'both' },\n { id: 'system', label: 'System UI', token: 'font.family.system', use: 'both' },\n];\n\nexport interface RadiusPreset {\n id: string;\n label: string;\n hint: string;\n radius: Required<BrandRadiusInput>;\n}\n\nexport const RADIUS_PRESETS: RadiusPreset[] = [\n { id: 'soft', label: 'Soft', hint: 'Rounded, like Bridge', radius: { inset: 6, control: 12, container: 20, overlay: 20 } },\n { id: 'balanced', label: 'Balanced', hint: 'Tighter, like Ocean', radius: { inset: 4, control: 10, container: 16, overlay: 20 } },\n { id: 'crisp', label: 'Crisp', hint: 'Near square corners', radius: { inset: 2, control: 4, container: 6, overlay: 10 } },\n];\n\nconst HEADING_ROLES = ['display', 'h1', 'h2'];\nconst TEXT_ROLES = ['h3', 'body', 'ui', 'caption'];\nconst RADIUS_ROLES = ['inset', 'control', 'container', 'overlay'] as const;\nconst RESERVED = new Set(['default', 'base', 'all', 'none', 'new', 'blank', 'primitives', 'semantic', 'components', 'density']);\nexport const BRAND_SLUG_RE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;\nconst DEFAULT_PRIMARY_CHROMA = 0.14;\n\n// --- outputs ----------------------------------------------------------------------------------------------\n\nexport interface PlannedFile {\n /** Repo-relative path. */\n path: string;\n action: 'create' | 'modify';\n content: string;\n}\n\nexport interface BrandIssue {\n level: 'error' | 'warning';\n code: string;\n message: string;\n path?: string;\n file?: string;\n}\n\nexport interface BrandSwatch {\n step: number;\n hex: string;\n}\n\nexport interface BrandContrastSummary {\n /** Pairs checked for the new brand, every theme. */\n checks: number;\n passing: number;\n failing: LayeredContrastResult[];\n /** Every result for the new brand, for tables. */\n results: LayeredContrastResult[];\n themes: string[];\n}\n\nexport interface NewBrandPlan {\n ok: boolean;\n slug: string;\n name: string;\n from: string;\n title: string;\n /** Suggested branch name (governance.branchPrefix + brand-<slug>). */\n branch: string;\n files: PlannedFile[];\n /** Token files after the change, relative to tokens.root (feed it to brandPreviewVariables or a LayeredTokenSet). */\n tokenFiles: Record<string, string>;\n /** bridge.config.json after the change, as text. */\n configText: string;\n /** Primary, neutral (and accent, link when they differ) ramps of the new brand, resolved. */\n ramps: Record<string, BrandSwatch[]>;\n /** Step of the primary ramp that primary actions use in the light theme (where a hex primary is pinned). */\n actionStep: number;\n contrast: BrandContrastSummary;\n /** Slug, input and DTCG problems. Errors block a proposal. */\n issues: BrandIssue[];\n risk: RiskResult & { bump: 'minor' };\n changeset?: { path: string; content: string } | undefined;\n}\n\n// --- helpers ----------------------------------------------------------------------------------------------\n\ntype Json = Record<string, unknown>;\nconst isObj = (x: unknown): x is Json => !!x && typeof x === 'object' && !Array.isArray(x);\nconst fileMap = (f: BrandSource['files']) => (f instanceof Map ? new Map(f) : new Map(Object.entries(f)));\nexport const brandDisplayName = (slug: string) => slug.split('-').filter(Boolean).map((w) => w[0]!.toUpperCase() + w.slice(1)).join(' ');\n\n/** The layer patterns brands use: the brand file and the optional brand x theme overrides. */\nfunction brandLayers(config: BridgeConfig): { brand?: string; override?: string; overrideAxis?: string } {\n const out: { brand?: string; override?: string; overrideAxis?: string } = {};\n for (const l of config.tokens.layers) {\n const ph = (l.files.match(/\\{([^}]+)\\}/g) ?? []).map((p) => p.slice(1, -1));\n if (!ph.includes('brand')) continue;\n if (ph.length === 1 && !out.brand) out.brand = l.files;\n else if (ph.length === 2 && !out.override) {\n out.override = l.files;\n out.overrideAxis = ph.find((p) => p !== 'brand');\n }\n }\n return out;\n}\nconst fill = (pattern: string, combo: Combo) => pattern.replace(/\\{([^}]+)\\}/g, (_, k: string) => combo[k] ?? `{${k}}`);\n\nfunction setAt(doc: Json, path: string, node: Json) {\n const keys = path.split('.');\n let cur = doc;\n for (const k of keys.slice(0, -1)) {\n if (!isObj(cur[k])) cur[k] = {};\n cur = cur[k] as Json;\n }\n const last = keys[keys.length - 1]!;\n const prev = isObj(cur[last]) ? (cur[last] as Json) : {};\n cur[last] = { ...prev, ...node };\n}\nfunction getAt(doc: Json, path: string): Json | undefined {\n let cur: unknown = doc;\n for (const k of path.split('.')) cur = isObj(cur) ? cur[k] : undefined;\n return isObj(cur) ? cur : undefined;\n}\n/** $type of a token in a doc, inherited from its groups. */\nfunction typeAt(doc: Json, path: string): string | undefined {\n let cur: unknown = doc;\n let type: string | undefined;\n for (const k of path.split('.')) {\n if (!isObj(cur)) return type;\n if (typeof cur.$type === 'string') type = cur.$type;\n cur = cur[k];\n }\n return isObj(cur) && typeof cur.$type === 'string' ? cur.$type : type;\n}\n\n/** Ramp for a hue input: a hex is pinned (at `pinStep`), a number is generated with the default chroma. */\nfunction rampFor(input: HueInput, pinStep: Step | undefined, kind: 'color' | 'neutral'): { ramp: Record<number, number[]>; issue?: BrandIssue; anchor: string } {\n if (typeof input === 'number' || (typeof input === 'string' && /^\\d+(\\.\\d+)?$/.test(input.trim()))) {\n const hue = ((Number(input) % 360) + 360) % 360;\n const ramp = kind === 'neutral' ? generateRamp({ hue, chroma: neutralChroma(), offset: neutralOffset() }) : generateRamp({ hue, chroma: bellChroma(DEFAULT_PRIMARY_CHROMA) });\n return { ramp, anchor: `OKLCH hue ${Math.round(hue)}` };\n }\n const hex = String(input).trim();\n if (!isHex(hex)) throw new Error(`\"${hex}\" is not a color. Use #rrggbb or a hue in degrees (0 to 360).`);\n if (kind === 'neutral') {\n const n = tintedNeutral(hex);\n return { ramp: n.ramp, anchor: `${hex.toUpperCase()} (hue ${Math.round(n.hue)})` };\n }\n const a = anchoredRamp(hex, pinStep);\n const issue: BrandIssue | undefined =\n a.distance > PIN_TOLERANCE\n ? {\n level: 'warning',\n code: 'pin-off-ladder',\n message: `${hex.toUpperCase()} is ${a.distance > 0.12 ? 'much ' : ''}${toOklch(fromHex(hex)).L > LIGHTNESS[a.step] ? 'lighter' : 'darker'} than the ${a.step} step it is pinned to, so the ramp around it will not read as one family. Primary actions use this step: pick a ${a.step >= 600 ? 'deeper' : 'lighter'} color.`,\n }\n : undefined;\n return { ramp: a.ramp, anchor: `${hex.toUpperCase()} pinned at ${a.step}`, ...(issue ? { issue } : {}) };\n}\n\n/** Points a palette role at a primitive ramp: palette.<role>.<step> -> {color.<ramp>.<step>} (two tiers, never literals). */\nfunction aliasRamp(doc: Json, role: string, ramp: string, description: string) {\n const group = getAt(doc, `palette.${role}`);\n if (!group) return;\n for (const s of STEPS) {\n if (!(String(s) in group)) continue;\n setAt(doc, `palette.${role}.${s}`, { $value: `{color.${ramp}.${s}}` });\n }\n group.$description = description;\n}\n\n/** Primitive ramps a new brand adds: ramp name -> description and DTCG color per step. */\ntype PrimitiveRamps = Map<string, { description: string; steps: Map<number, unknown> }>;\n\n/** Inserts `slug` into modes.brand.values (or modes.brands) with a minimal text change. */\nexport function addBrandToConfigText(text: string, slug: string): string {\n const canonical = /(\"brand\"\\s*:\\s*\\{\\s*\"values\"\\s*:\\s*\\[)([^\\]]*)(\\])/;\n const flat = /(\"brands\"\\s*:\\s*\\[)([^\\]]*)(\\])/;\n for (const re of [canonical, flat]) {\n const m = re.exec(text);\n if (!m) continue;\n const items = m[2]!.trim();\n const sep = items.includes('\\n') ? `,${/\\n(\\s*)\"/.exec(m[2]!)?.[0]?.replace(/\"$/, '') ?? ' '}` : ', ';\n return text.slice(0, m.index) + m[1] + (items ? `${m[2]!.replace(/\\s*$/, '')}${sep}\"${slug}\"` : `\"${slug}\"`) + (m[2]!.match(/\\s*$/)?.[0] ?? '') + m[3] + text.slice(m.index + m[0].length);\n }\n throw new Error('bridge.config.json has no modes.brand.values list to add the brand to.');\n}\n\n// --- listing ----------------------------------------------------------------------------------------------\n\nexport interface BrandSummary {\n slug: string;\n name: string;\n default: boolean;\n file: string;\n description?: string;\n /** Resolved color.action.primary.bg in the default theme, when the repo has it. */\n primary?: string;\n /** Theme override files the brand has. */\n overrides: string[];\n}\n\nexport function listBrands(source: BrandSource): BrandSummary[] {\n const { config } = source;\n const files = fileMap(source.files);\n const set = new LayeredTokenSet(config, files);\n const layers = brandLayers(config);\n const brandAxis = config.axes.brand;\n if (!brandAxis || !layers.brand) return [];\n return brandAxis.values.map((slug) => {\n const file = fill(layers.brand!, { brand: slug });\n let doc: Json = {};\n try {\n doc = JSON.parse(files.get(file) ?? '{}') as Json;\n } catch {\n /* reported by validation */\n }\n const meta = isObj(doc.$extensions) && isObj(doc.$extensions['dev.bridge.brand']) ? (doc.$extensions['dev.bridge.brand'] as Json) : {};\n const combo = set.normalizeCombo({ brand: slug });\n const primary = set.resolve('color.action.primary.bg', combo);\n const overrides = layers.override ? (config.axes[layers.overrideAxis!]?.values ?? []).map((v) => fill(layers.override!, { brand: slug, [layers.overrideAxis!]: v })).filter((f) => files.has(f)) : [];\n return {\n slug,\n name: typeof meta.name === 'string' ? meta.name : brandDisplayName(slug),\n default: slug === brandAxis.default,\n file: tokensPath(config, file),\n ...(typeof doc.$description === 'string' ? { description: doc.$description } : {}),\n ...(primary.css && !primary.error ? { primary: primary.css } : {}),\n overrides: overrides.map((f) => tokensPath(config, f)),\n };\n });\n}\n\n// --- planning ---------------------------------------------------------------------------------------------\n\n/** Problems with a slug before anything is generated (the Studio uses it as you type). */\nexport function checkBrandSlug(config: BridgeConfig, files: BrandSource['files'], slug: string): BrandIssue[] {\n const out: BrandIssue[] = [];\n const s = slug.trim();\n if (!s) return [{ level: 'error', code: 'slug-empty', message: 'Give the brand a name.' }];\n if (s.length < 2 || s.length > 24 || !BRAND_SLUG_RE.test(s)) out.push({ level: 'error', code: 'slug-format', message: 'Use 2 to 24 lowercase letters, digits and single dashes, starting with a letter: \"acme\" or \"north-star\".' });\n const taken = Object.values(config.axes).flatMap((a) => a.values);\n if (config.axes.brand?.values.includes(s)) out.push({ level: 'error', code: 'slug-taken', message: `A brand called \"${s}\" already exists. Pick another name or edit that brand.` });\n else if (taken.includes(s) || RESERVED.has(s)) out.push({ level: 'error', code: 'slug-reserved', message: `\"${s}\" is a reserved mode name. Pick another name.` });\n const layer = brandLayers(config).brand;\n const map = fileMap(files);\n if (layer && !config.axes.brand?.values.includes(s) && map.has(fill(layer, { brand: s }))) out.push({ level: 'error', code: 'slug-file-exists', message: `${tokensPath(config, fill(layer, { brand: s }))} already exists. Pick another name or add it to bridge.config.json.` });\n return out;\n}\n\nexport function planNewBrand(source: BrandSource, input: NewBrandInput): NewBrandPlan {\n const { config } = source;\n const files = fileMap(source.files);\n const issues: BrandIssue[] = [];\n const slug = input.slug.trim();\n const name = input.name?.trim() || brandDisplayName(slug);\n const layers = brandLayers(config);\n const brandAxis = config.axes.brand;\n if (!brandAxis || !layers.brand) throw new Error('This repo has no brand mode: bridge.config.json needs modes.brand and a tokens layer with {brand}.');\n issues.push(...checkBrandSlug(config, files, slug));\n\n const from = input.from?.trim() || brandAxis.default;\n const blank = from === 'blank';\n if (!blank && !brandAxis.values.includes(from)) throw new Error(`Unknown brand \"${from}\" to start from. Brands: ${brandAxis.values.join(', ')} (or \"blank\").`);\n const template = blank ? brandAxis.default : from;\n const templateFile = fill(layers.brand, { brand: template });\n const templateText = files.get(templateFile);\n if (!templateText) throw new Error(`${tokensPath(config, templateFile)} is missing.`);\n const doc = JSON.parse(templateText) as Json;\n const before = new LayeredTokenSet(config, files);\n\n // Step that primary actions use in the light (default) theme of the starting brand: a hex primary is pinned there.\n const chain = before.resolve('color.action.primary.bg', before.normalizeCombo({ brand: template })).chain;\n const actionStep = Number(/^palette\\.primary\\.(\\d+)$/.exec(chain.find((c) => /^palette\\.primary\\.\\d+$/.test(c)) ?? '')?.[1] ?? 600) as Step;\n\n const anchors: Record<string, string> = {};\n const safeRamp = (role: string, hue: HueInput, kind: 'color' | 'neutral', pin?: Step) => {\n try {\n const r = rampFor(hue, pin, kind);\n if (r.issue) issues.push({ ...r.issue, path: `palette.${role}` });\n anchors[role] = r.anchor;\n return r.ramp;\n } catch (e) {\n issues.push({ level: 'error', code: 'invalid-color', message: (e as Error).message, path: `palette.${role}` });\n return undefined;\n }\n };\n // Generated ramps become primitives (color.<slug>-<role>.<step>); the brand file only aliases them.\n const prims: PrimitiveRamps = new Map();\n const addRamp = (role: string, ramp: Record<number, number[]>, description: string) => {\n const steps = new Map<number, unknown>(STEPS.map((st) => [st, dtcgColor(ramp[st]!)]));\n prims.set(`${slug}-${role}`, { description, steps });\n return `${slug}-${role}`;\n };\n if (input.primaryHue !== undefined && input.primaryHue !== '') {\n const ramp = safeRamp('primary', input.primaryHue, 'color', actionStep);\n if (ramp) {\n const r = addRamp('primary', ramp, `${name} primary. Generated by Bridge from ${anchors.primary}.`);\n aliasRamp(doc, 'primary', r, `${name} primary.`);\n if (input.colors?.accent === undefined) aliasRamp(doc, 'accent', r, `${name} accent: the primary ramp.`);\n if (input.colors?.link === undefined) aliasRamp(doc, 'link', r, `${name} links: the primary ramp.`);\n }\n }\n for (const role of ['accent', 'link'] as const) {\n const hue = input.colors?.[role];\n if (hue === undefined || hue === '') continue;\n const ramp = safeRamp(role, hue, 'color');\n if (ramp) aliasRamp(doc, role, addRamp(role, ramp, `${name} ${role}. Generated by Bridge from ${anchors[role]}.`), `${name} ${role}.`);\n }\n if (input.neutralHue !== undefined && input.neutralHue !== '') {\n const ramp = safeRamp('neutral', input.neutralHue, 'neutral');\n if (ramp) aliasRamp(doc, 'neutral', addRamp('neutral', ramp, `${name} neutral. Generated by Bridge from ${anchors.neutral}.`), `${name} neutral.`);\n }\n\n // Radius roles: aliases of the radius scale.\n const scale = new Map<number, string>();\n for (const [path, defs] of before.view(before.defaultCombo)) {\n const m = /^radius\\.([\\w-]+)$/.exec(path);\n const v = defs[defs.length - 1]!.value;\n if (m && isObj(v) && typeof v.value === 'number' && v.unit === 'px' && !getAt(doc, path)) scale.set(v.value, m[1]!);\n }\n const radius = input.radius ?? (blank ? RADIUS_PRESETS[0]!.radius : undefined);\n if (radius) {\n for (const role of RADIUS_ROLES) {\n const px = radius[role];\n if (px === undefined) continue;\n const step = scale.get(px);\n if (!step) issues.push({ level: 'error', code: 'radius-off-scale', message: `radius.${role} ${px}px is not on the radius scale (${[...scale.keys()].filter((x) => x < 9999).sort((a, b) => a - b).join(', ')} px).`, path: `radius.${role}` });\n else if (getAt(doc, `radius.${role}`)) setAt(doc, `radius.${role}`, { $value: `{radius.${step}}` });\n }\n }\n\n // Font roles and typography families.\n const fonts = input.fonts ?? (blank ? { heading: 'instrument-sans', text: 'instrument-sans' } : undefined);\n const fontToken = (id: string | undefined, role: string) => {\n if (!id) return undefined;\n const f = BRAND_FONTS.find((x) => x.id === id || x.token === id);\n const token = f?.token ?? (id.startsWith('font.family.') ? id : `font.family.${id}`);\n if (!before.view(before.defaultCombo).has(token) || ['font.family.sans', 'font.family.display', 'font.family.mono'].includes(token)) {\n issues.push({ level: 'error', code: 'unknown-font', message: `\"${id}\" is not a font this repo self-hosts. Pick one of: ${BRAND_FONTS.map((x) => x.label).join(', ')}.`, path: `font.family.${role}` });\n return undefined;\n }\n return token;\n };\n const heading = fontToken(fonts?.heading, 'display');\n const text = fontToken(fonts?.text, 'sans');\n if (heading && getAt(doc, 'font.family.display')) setAt(doc, 'font.family.display', { $value: `{${heading}}` });\n if (text && getAt(doc, 'font.family.sans')) setAt(doc, 'font.family.sans', { $value: `{${text}}` });\n for (const r of HEADING_ROLES) if (heading && getAt(doc, `typography.${r}.family`)) setAt(doc, `typography.${r}.family`, { $value: `{${heading}}` });\n for (const r of TEXT_ROLES) if (text && getAt(doc, `typography.${r}.family`)) setAt(doc, `typography.${r}.family`, { $value: `{${text}}` });\n\n // Exact values (the Figma plugin sends every variable of the new mode).\n for (const [path, raw] of Object.entries(input.overrides ?? {})) {\n const node = getAt(doc, path);\n if (!node || !('$value' in node)) {\n issues.push({ level: 'error', code: 'unknown-token', message: `${path} is not a token of the ${template} brand file, so a new brand cannot set it.`, path });\n continue;\n }\n setAt(doc, path, { $value: coerceValue(raw, typeAt(doc, path), node.$value) });\n }\n\n // Exact colors (Figma values, overrides) are hoisted too: a literal palette color becomes the primitive\n // color.<slug>-<role>.<step> and the role aliases it, so brand files never hold literal values.\n const palette = getAt(doc, 'palette');\n for (const [role, group] of Object.entries(palette ?? {})) {\n if (role.startsWith('$') || !isObj(group)) continue;\n for (const [step, node] of Object.entries(group)) {\n if (step.startsWith('$') || !isObj(node) || !('$value' in node) || typeof node.$value === 'string') continue;\n const ramp = `${slug}-${role}`;\n const entry = prims.get(ramp) ?? { description: `${name} ${role}. Exact values set when the brand was created.`, steps: new Map<number, unknown>() };\n entry.steps.set(Number(step), node.$value);\n prims.set(ramp, entry);\n setAt(doc, `palette.${role}.${step}`, { $value: `{color.${ramp}.${step}}` });\n }\n }\n const primDir = config.tokens.tiers.primitive?.[0]?.replace(/\\/$/, '') ?? config.tokens.primitives;\n const primFile = `${primDir}/${slug}.tokens.json`;\n if (prims.size && files.has(primFile)) issues.push({ level: 'error', code: 'slug-file-exists', message: `${tokensPath(config, primFile)} already exists. Pick another name.` });\n for (const r of prims.keys()) if (before.allPaths().some((p) => p.startsWith(`color.${r}.`))) issues.push({ level: 'error', code: 'ramp-exists', message: `A primitive ramp color.${r} already exists. Pick another name.` });\n\n doc.$description = `${name}: created with Bridge, started from ${blank ? 'a blank brand' : brandDisplayName(from)}.`;\n doc.$extensions = { ...(isObj(doc.$extensions) ? doc.$extensions : {}), 'dev.bridge.brand': { name, from, ...(Object.keys(anchors).length ? { anchors } : {}) } };\n // Keep $description and $extensions on top, like the hand-written brand files.\n const { $description, $extensions, ...rest } = doc;\n const brandFile = fill(layers.brand, { brand: slug });\n const nextFiles = new Map(files);\n const created: string[] = [];\n if (prims.size) {\n const color: Json = { $type: 'color' };\n for (const [r, { description, steps }] of prims) {\n const ramp: Json = { $description: description };\n for (const st of [...steps.keys()].sort((a, b) => a - b)) ramp[String(st)] = { $value: steps.get(st) };\n color[r] = ramp;\n }\n const prim = { $description: `${name} brand ramps, generated by Bridge (@bridge-ds/core ramp engine). Never used by components directly: brands/${slug}.tokens.json maps them to palette roles.`, color };\n nextFiles.set(primFile, `${JSON.stringify(prim, null, 2)}\\n`);\n created.push(primFile);\n }\n created.push(brandFile);\n nextFiles.set(brandFile, `${JSON.stringify({ $description, $extensions, ...rest }, null, 2)}\\n`);\n\n // Theme overrides of the starting brand come along: they point at palette roles, so they follow the new ramps.\n if (!blank && layers.override && layers.overrideAxis) {\n for (const v of config.axes[layers.overrideAxis]?.values ?? []) {\n const src = fill(layers.override, { brand: from, [layers.overrideAxis]: v });\n const text = files.get(src);\n if (!text) continue;\n const o = JSON.parse(text) as Json;\n const out = { ...o, $description: `${name} overrides on top of semantic/${v}, copied from ${brandDisplayName(from)}.` };\n const dst = fill(layers.override, { brand: slug, [layers.overrideAxis]: v });\n nextFiles.set(dst, `${JSON.stringify(out, null, 2)}\\n`);\n created.push(dst);\n }\n }\n\n // bridge.config.json: modes.brand += slug.\n const baseConfigText = source.configText ?? `${JSON.stringify(toConfigJson(config), null, 2)}\\n`;\n let configText = baseConfigText;\n let nextConfig = config;\n try {\n configText = addBrandToConfigText(baseConfigText, slug);\n nextConfig = issues.some((i) => i.code.startsWith('slug-')) ? config : loadConfig(configText);\n } catch (e) {\n issues.push({ level: 'error', code: 'config', message: (e as Error).message });\n }\n\n // Validation (only problems the new brand brings) and the contrast gate for the new brand in every theme.\n const after = new LayeredTokenSet(nextConfig, nextFiles);\n const key = (i: LayerIssue) => `${i.code}|${i.path ?? ''}|${i.message}`;\n const known = new Set(validateLayered(before).map(key));\n const brandKey = `brand=${slug}`;\n for (const i of validateLayered(after)) {\n if (known.has(key(i))) continue;\n if (i.modes && !i.modes.some((m) => m.split(',').includes(brandKey)) && !created.includes(i.file ?? '')) continue;\n issues.push({ level: i.level, code: i.code, message: i.message, ...(i.path ? { path: i.path } : {}), ...(i.file ? { file: tokensPath(config, i.file) } : {}) });\n }\n const pairs: ContrastPair[] = parseContrastChecks(source.contrastText);\n const inGate = nextConfig.axes.brand?.values.includes(slug);\n const combos = inGate ? after.combos(nextConfig.contrast?.modes).filter((c) => c.brand === slug) : [];\n const results = combos.flatMap((c) => pairs.map((p) => checkLayeredPair(after, p, c)));\n const failing = results.filter((r) => !r.pass);\n const themes = [...new Set(combos.map((c) => c.theme).filter((t): t is string => !!t))];\n\n // Ramps, resolved (so Figma values and overrides show as they will ship).\n const ramps: Record<string, BrandSwatch[]> = {};\n if (inGate) {\n const combo = after.normalizeCombo({ brand: slug });\n const read = (role: string) =>\n STEPS.map((s) => ({ step: s, hex: after.resolve(`palette.${role}.${s}`, combo).css })).filter((x) => /^#[0-9a-f]{6}$/i.test(x.hex));\n ramps.primary = read('primary');\n ramps.neutral = read('neutral');\n for (const role of ['accent', 'link']) {\n const r = read(role);\n if (JSON.stringify(r) !== JSON.stringify(ramps.primary)) ramps[role] = r;\n }\n }\n\n // Tier: every token of the new files is an addition, bridge.config.json is a guardrail. Tier 3, minor.\n const addedTokens = after.defs.filter((d) => created.includes(d.file)).map((d) => ({ kind: 'added' as const, path: d.path }));\n const risk = classifyRisk({ tokenChanges: addedTokens, files: [{ path: CONFIG_FILE, status: 'modified' }], config });\n const planned: PlannedFile[] = [\n ...created.map((f) => ({ path: tokensPath(config, f), action: 'create' as const, content: nextFiles.get(f)! })),\n { path: CONFIG_FILE, action: 'modify', content: configText },\n ];\n const cs = config.changesets ?? (config.changeset ? { dir: '.changeset', package: config.changeset.package } : undefined);\n const changeset = cs\n ? {\n path: `${cs.dir}/bridge-brand-${slug}.md`,\n content: formatChangeset(cs.package, 'minor', `Add the ${name} brand (\\`${slug}\\`), started from ${blank ? 'a blank brand' : brandDisplayName(from)}.`, `- ${created.map((f) => `\\`${tokensPath(config, f)}\\``).join('\\n- ')}\\n- \\`${CONFIG_FILE}\\`: modes.brand gains \"${slug}\", so the token build and the contrast gate cover it.`),\n }\n : undefined;\n if (changeset) planned.push({ path: changeset.path, action: 'create', content: changeset.content });\n\n const errors = issues.filter((i) => i.level === 'error');\n return {\n ok: errors.length === 0 && failing.length === 0 && results.length > 0,\n slug,\n name,\n from,\n title: `Add the ${name} brand`,\n branch: `${config.governance.branchPrefix}brand-${slug || 'new'}`,\n files: planned,\n tokenFiles: Object.fromEntries(nextFiles),\n configText,\n ramps,\n actionStep,\n contrast: { checks: results.length, passing: results.length - failing.length, failing, results, themes },\n issues,\n risk: { ...risk, bump: 'minor' },\n changeset,\n };\n}\n\n/** CSS variables of a planned brand in one theme (every semantic and component token), for live previews. */\nexport function brandPreviewVariables(source: BrandSource, plan: Pick<NewBrandPlan, 'slug' | 'tokenFiles' | 'configText'>, theme?: string): Record<string, string> {\n let config = source.config;\n try {\n config = loadConfig(plan.configText);\n } catch {\n /* keep the old config: the preview falls back to the default brand */\n }\n const set = new LayeredTokenSet(config, new Map(Object.entries(plan.tokenFiles)));\n let combo: Combo;\n try {\n combo = set.normalizeCombo({ brand: plan.slug, ...(theme ? { theme } : {}) });\n } catch {\n combo = set.normalizeCombo(theme ? { theme } : {});\n }\n const out: Record<string, string> = {};\n for (const path of set.view(combo).keys()) {\n const tier = set.tierOf(path);\n if (tier === 'primitive') continue;\n const r = set.resolve(path, combo);\n if (!r.error && r.css) out[set.cssVarName(path)] = r.css;\n }\n return out;\n}\n\n// --- PR body ----------------------------------------------------------------------------------------------\n\nconst code = (s: string) => `\\`${s}\\``;\n\n/** The \"New brand\" section: swatch ramps and the contrast summary. GitHub shows a chip next to `#rrggbb`. */\nexport function newBrandSection(plan: NewBrandPlan): string {\n const roles = Object.keys(plan.ramps);\n const rampTable = roles.length\n ? [\n `| Step | ${roles.map((r) => r[0]!.toUpperCase() + r.slice(1)).join(' | ')} |`,\n `| --- | ${roles.map(() => '---').join(' | ')} |`,\n ...STEPS.map((s) => `| ${s}${s === plan.actionStep ? ' (actions)' : ''} | ${roles.map((r) => code(plan.ramps[r]!.find((x) => x.step === s)?.hex ?? '')).join(' | ')} |`),\n ].join('\\n')\n : '_No ramps resolved._';\n const c = plan.contrast;\n const contrastLine = c.failing.length\n ? `**${c.failing.length} of ${c.checks} pairs fail** for ${plan.name} (${c.themes.join(' and ')}).`\n : `All ${c.checks} contrast checks pass for ${plan.name} in ${c.themes.join(' and ')}.`;\n const failRows = c.failing.slice(0, 20).map((r) => `| ${code(r.fg)} on ${code(r.bg)} | ${r.modes.split(',').find((m) => m.startsWith('theme='))?.slice(6) ?? r.modes} | ${r.ratio ?? 'n/a'} | ${r.min} |`);\n const tightest = [...c.results].filter((r) => r.pass && r.ratio !== null).sort((a, b) => a.ratio! - a.min - (b.ratio! - b.min)).slice(0, 3);\n return [\n '## New brand',\n '',\n `- Name: **${plan.name}** (${code(plan.slug)})`,\n `- Started from: ${plan.from === 'blank' ? 'a blank brand' : brandDisplayName(plan.from)}`,\n `- Primary actions use step ${plan.actionStep} of the primary ramp in the light theme.`,\n '',\n rampTable,\n '',\n '### Contrast',\n '',\n contrastLine,\n ...(failRows.length ? ['', '| Pair | Theme | Ratio | Min |', '| --- | --- | --- | --- |', ...failRows] : []),\n ...(tightest.length ? ['', `Tightest passing pairs: ${tightest.map((r) => `${code(r.fg)} on ${code(r.bg)} ${r.ratio}:1 (min ${r.min})`).join('; ')}.`] : []),\n ].join('\\n');\n}\n\nexport interface NewBrandBodyOptions {\n /** \"the bridge CLI\", \"Bridge MCP\", \"the Bridge Studio\", \"the DS Bridge Figma plugin\". */\n tool: string;\n author?: string;\n /** true when an AI agent proposed it. */\n agent?: boolean;\n /** Free text from the person proposing. */\n notes?: string;\n}\n\nexport function composeNewBrandBody(plan: NewBrandPlan, opts: NewBrandBodyOptions): string {\n const t = plan.risk.tier;\n const box = (n: 1 | 2 | 3) => `- ${n === t ? '[x]' : '[ ]'} ${RISK_LABELS[n]}`;\n const errors = plan.issues.filter((i) => i.level === 'error');\n const warnings = plan.issues.filter((i) => i.level === 'warning');\n return [\n '## What changed and why',\n '',\n `Adds the ${plan.name} brand. Components do not change: the brand re-points palette, radius and font roles, and the token build, the contrast gate and the docs pick it up from ${code('bridge.config.json')}.`,\n ...(opts.notes?.trim() ? ['', opts.notes.trim()] : []),\n '',\n `Proposed through ${opts.tool}${opts.author ? ` by ${opts.author}` : ''}.${opts.agent ? ' Agent-authored: a human design owner and tech owner review and merge.' : ''}`,\n '',\n newBrandSection(plan),\n '',\n '## Files',\n '',\n ...plan.files.map((f) => `- ${f.action === 'create' ? 'Create' : 'Modify'} ${code(f.path)}`),\n '',\n '## Risk tier',\n '',\n box(1),\n box(2),\n box(3),\n '',\n `- Brand added: ${plan.files.filter((f) => f.action === 'create' && f.path.endsWith('.tokens.json')).length} token file(s), every token new`,\n `- ${code('bridge.config.json')} is a guardrail file`,\n `- Semver bump: ${code(plan.risk.bump)} for ${code('@bridge-ds/tokens')}`,\n '',\n '## Checks',\n '',\n `- Token validation: ${errors.length ? `**${errors.length} error(s)**` : 'no errors'} (DTCG shapes, aliases, every mode)${warnings.length ? `, ${warnings.length} warning(s): ${warnings.map((w) => w.message).join(' ')}` : ''}`,\n `- Contrast gate for ${plan.name}: ${plan.contrast.failing.length ? `**${plan.contrast.failing.length} failing pair(s)**` : `all ${plan.contrast.checks} pairs pass`}`,\n '',\n '## Authored by',\n '',\n opts.agent ? '- [ ] Human' : '- [x] Human',\n opts.agent ? '- [x] AI agent (Claude), reviewed by a human before merge' : '- [ ] AI agent',\n '',\n '## Design review checklist',\n '',\n '- [ ] Checked in light and dark, with real components (Studio preview or Storybook brand switch)',\n '- [ ] Primary, zone and link colors read as one family',\n '- [ ] Changeset bump matches the tier',\n '',\n ].join('\\n');\n}\n","// Component docs drafted with Claude: the task (which sections, or a selected passage), the prompt, the answer\n// parsing and sanitizing, the merge into a docs.json, and the Messages API request. Shared by the docs-draft GitHub\n// Action (scripts/docs-draft.mjs), the in-place drafting of the Library page (apps/docs-site docs-ai) and the draft\n// exchange (the user's own Claude through the Bridge MCP server), so an answer is cleaned the same way everywhere.\n// Pure: no DOM, no Node-only API. The callers do the fetch.\n\nimport { cleanDraftText } from './change-drafts';\nimport {\n type ComponentDocsJson,\n type DocsConventions,\n type DocsExampleNode,\n type DocsGuidance,\n type DocsPrefill,\n PROSE_KEYS,\n type ProseKey,\n docsPrompt,\n markClaudeDraft,\n} from './docs-draft';\n\nexport const DOCS_DRAFT_MODEL = 'claude-sonnet-5-5';\nexport const ANTHROPIC_MESSAGES_URL = 'https://api.anthropic.com/v1/messages';\n\n/** How a selected passage is rewritten. */\nexport type DocsSelectionMode = 'clearer' | 'shorter' | 'voice';\nexport const DOCS_SELECTION_MODES: Record<DocsSelectionMode, string> = {\n clearer: 'Make it clearer: plain words, one idea per sentence, the most useful fact first.',\n shorter: 'Make it shorter: keep every fact, drop filler, aim for half the words or fewer.',\n voice: 'Put it in the Bridge voice: sentence case, verbs first, calm and precise, no marketing words, no em dash.',\n};\nexport const isDocsSelectionMode = (m: unknown): m is DocsSelectionMode => typeof m === 'string' && m in DOCS_SELECTION_MODES;\nexport const isProseKey = (k: unknown): k is ProseKey => typeof k === 'string' && (PROSE_KEYS as readonly string[]).includes(k);\n\n/**\n * One drafting job on a component's docs. \"sections\": write these prose sections (rewrite: even when they hold text;\n * check: written sections older than the code, returned only when no longer true for it, so an absent one is still\n * accurate). \"selection\": rewrite one passage of a section, nothing else.\n */\nexport type DocsDraftTask =\n | { kind: 'sections'; keys: ProseKey[]; rewrite?: boolean | undefined; check?: ProseKey[] | undefined }\n | { kind: 'selection'; key: ProseKey; text: string; mode: DocsSelectionMode };\n\n/** Problems in a task, as sentences. Empty when valid. */\nexport function validateDocsTask(x: unknown): string[] {\n if (!x || typeof x !== 'object') return ['The docs task is missing.'];\n const t = x as Partial<Record<string, unknown>>;\n if (t.kind === 'sections') {\n const keys = t.keys;\n if (!Array.isArray(keys) || !keys.length || !keys.every(isProseKey)) return [`The docs task lists no sections: use ${PROSE_KEYS.join(', ')}.`];\n if (t.check !== undefined && (!Array.isArray(t.check) || !t.check.every(isProseKey))) return ['check must list prose sections.'];\n return [];\n }\n if (t.kind === 'selection') {\n const out: string[] = [];\n if (!isProseKey(t.key)) out.push(`The selection needs a section: ${PROSE_KEYS.join(', ')}.`);\n if (typeof t.text !== 'string' || !t.text.trim()) out.push('The selection has no text.');\n if (!isDocsSelectionMode(t.mode)) out.push('The selection mode must be clearer, shorter or voice.');\n return out;\n }\n return ['The docs task kind must be \"sections\" or \"selection\".'];\n}\n\n/** The keys a task writes. */\nexport const docsTaskKeys = (t: DocsDraftTask): ProseKey[] => (t.kind === 'sections' ? t.keys : [t.key]);\n\n/** The prompt to rewrite a selected passage of a section: the facts and the conventions, the passage, one rule. */\nexport function docsSelectionPrompt(prefill: DocsPrefill, conventions: DocsConventions, sel: { key: ProseKey; text: string; mode: DocsSelectionMode }): string {\n const base = docsPrompt(prefill, conventions, { keys: [sel.key] });\n // Reuse the facts and conventions of the sections prompt, with the selection task and contract on top.\n const facts = base.slice(base.indexOf('Facts computed from the code:'));\n return [\n `Rewrite one passage of the \"${sel.key}\" section of ${prefill.component}.docs.json for the Bridge design system.`,\n DOCS_SELECTION_MODES[sel.mode],\n '',\n 'Rules:',\n '- Keep its meaning and every fact that the code supports. Never add props, variants, keyboard behavior or tokens that are not in the facts or the source below.',\n '- Bridge voice: sentence case, plain words, verbs first, no em dashes, no marketing words, no Markdown.',\n '- Rewrite only the passage: it is pasted back in place of the selection, inside the rest of the section.',\n '- Answer with one JSON object, nothing else: { \"replacement\": \"the rewritten passage\" }.',\n '',\n `<passage>\\n${sel.text.trim()}\\n</passage>`,\n '',\n facts,\n ].join('\\n');\n}\n\n/** The prompt of a task: docsPrompt for sections (only those keys), docsSelectionPrompt for a selection. */\nexport function docsTaskPrompt(prefill: DocsPrefill, conventions: DocsConventions, task: DocsDraftTask): string {\n if (task.kind === 'selection') return docsSelectionPrompt(prefill, conventions, task);\n return docsPrompt(prefill, conventions, { keys: task.keys, ...(task.rewrite ? { rewrite: true } : {}), ...(task.check?.length ? { check: task.check } : {}) });\n}\n\n// ---------------------------------------------------------------------------------------------\n// Answers: parse and sanitize\n\n/** The first JSON object in a model reply (plain, or inside a ```json fence). Throws when there is none. */\nexport function parseDocsReply(text: string): Record<string, unknown> {\n const fenced = /```(?:json)?\\s*([\\s\\S]*?)```/i.exec(text);\n const body = fenced ? fenced[1]! : text;\n const start = body.indexOf('{');\n const end = body.lastIndexOf('}');\n if (start < 0 || end <= start) throw new Error('The reply holds no JSON object.');\n const json = JSON.parse(body.slice(start, end + 1)) as unknown;\n if (!json || typeof json !== 'object' || Array.isArray(json)) throw new Error('The reply is not a docs.json object.');\n return json as Record<string, unknown>;\n}\n\n/** One line of docs prose: em dashes out, whitespace folded, trimmed. */\nexport const cleanDocsText = (s: string): string => cleanDraftText(s.replace(/[\\r\\n]+/g, ' '));\n\nconst isExample = (x: unknown): x is DocsExampleNode => {\n if (typeof x === 'string') return true;\n if (!x || typeof x !== 'object' || Array.isArray(x)) return false;\n const n = x as { c?: unknown; p?: unknown; children?: unknown };\n if (typeof n.c !== 'string' || !n.c) return false;\n if (n.p !== undefined && (!n.p || typeof n.p !== 'object' || Array.isArray(n.p))) return false;\n return n.children === undefined || (Array.isArray(n.children) && n.children.every(isExample));\n};\n\nconst textList = (x: unknown): string[] | undefined => {\n if (typeof x === 'string') x = [x];\n if (!Array.isArray(x)) return undefined;\n const out = x.filter((s): s is string => typeof s === 'string').map(cleanDocsText).filter(Boolean);\n return out.length ? out : undefined;\n};\n\nconst guidanceList = (x: unknown, examples: boolean): DocsGuidance[] | undefined => {\n if (!Array.isArray(x)) return undefined;\n const out: DocsGuidance[] = [];\n for (const g of x as unknown[]) {\n if (!g || typeof g !== 'object') continue;\n const r = g as { title?: unknown; text?: unknown; example?: unknown };\n const title = typeof r.title === 'string' ? cleanDocsText(r.title) : '';\n const text = typeof r.text === 'string' ? cleanDocsText(r.text) : '';\n if (!title || !text) continue;\n out.push({ title, text, ...(examples && r.example !== undefined && isExample(r.example) ? { example: r.example } : {}) });\n }\n return out.length ? out : undefined;\n};\n\nexport type DocsSections = Partial<Pick<ComponentDocsJson, ProseKey>>;\n\n/**\n * The prose sections of an answer, kept to the docs.json shapes: only `keys`, summary one cleaned paragraph, lists of\n * non-empty cleaned strings, dos and donts as {title, text} (an example only when `examples` and well formed). Em\n * dashes removed everywhere. Sections that come back empty or in the wrong shape are left out.\n */\nexport function sanitizeDocsSections(raw: unknown, keys: readonly ProseKey[] = PROSE_KEYS, opts: { examples?: boolean } = {}): DocsSections {\n const out: DocsSections = {};\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out;\n const r = raw as Record<string, unknown>;\n for (const k of keys) {\n const v = r[k];\n if (k === 'summary') {\n const s = typeof v === 'string' ? cleanDocsText(v) : '';\n if (s) out.summary = s;\n } else if (k === 'dos' || k === 'donts') {\n const g = guidanceList(v, opts.examples ?? false);\n if (g) out[k] = g;\n } else {\n const l = textList(v);\n if (l) out[k] = l;\n }\n }\n return out;\n}\n\n/** A rewritten passage: one cleaned paragraph without wrapping quotes, or '' when there is none. */\nexport function sanitizeDocsReplacement(raw: unknown): string {\n if (typeof raw !== 'string') return '';\n return cleanDocsText(raw.trim().replace(/^[\"'“]+|[\"'”]+$/g, ''));\n}\n\n/**\n * A task's answer. Sections tasks: `sections` drafted or fixed, and `checked`, the checked sections Claude verified and\n * left unchanged (still accurate). Selection: `replacement` only.\n */\nexport type DocsTaskAnswer = { sections: DocsSections; checked: ProseKey[]; replacement?: undefined } | { sections: DocsSections; checked?: undefined; replacement: string };\n\n/**\n * A task's answer from Claude's reply text. Sections: the requested keys, sanitized; throws when none came back.\n * Selection: `replacement` only (sections stay empty); a reply that is plain text counts as the passage.\n */\nexport function parseDocsTaskAnswer(task: DocsDraftTask, text: string): DocsTaskAnswer {\n if (task.kind === 'selection') {\n let raw: unknown = text;\n try {\n const json = parseDocsReply(text);\n raw = json.replacement ?? json.text ?? json[task.key];\n } catch {\n raw = text.replace(/```[a-z]*\\s*|```/gi, '');\n }\n const replacement = sanitizeDocsReplacement(raw);\n if (!replacement) throw new Error('Claude sent no rewritten passage. Try again.');\n return { sections: {}, replacement };\n }\n return docsSectionsAnswer(task, parseDocsReply(text));\n}\n\n/**\n * Sections and checked of a sections task from an answer object: absent checked keys are still accurate. Throws only\n * when the task checks nothing and none of its keys came back.\n */\nexport function docsSectionsAnswer(task: Extract<DocsDraftTask, { kind: 'sections' }>, raw: unknown): { sections: DocsSections; checked: ProseKey[] } {\n const check = (task.check ?? []).filter((k) => task.keys.includes(k));\n const sections = check.length ? sanitizeDocsSections(raw, task.keys) : docsSectionsResult(task, raw);\n return { sections, checked: check.filter((k) => sections[k] === undefined) };\n}\n\n/** The sections of a task from an answer object (API reply or the exchange). Throws when none of the keys came back. */\nexport function docsSectionsResult(task: Extract<DocsDraftTask, { kind: 'sections' }>, raw: unknown): DocsSections {\n const sections = sanitizeDocsSections(raw, task.keys);\n if (!Object.keys(sections).length) throw new Error(`Claude's answer holds none of the sections asked for (${task.keys.join(', ')}). Try again.`);\n return sections;\n}\n\n/**\n * Drafted sections applied to a docs.json, marked for review: the sections replace the ones there, the rest stays as\n * is (anatomy and preview are code-decided and never come from a draft), and draftedSections lists what waits.\n */\nexport function applyDocsSections<T extends Partial<ComponentDocsJson>>(docs: T, sections: DocsSections): T {\n const keys = PROSE_KEYS.filter((k) => sections[k] !== undefined);\n if (!keys.length) return docs;\n return markClaudeDraft({ ...docs, ...sections }, keys);\n}\n\n/**\n * The docs-draft Action's merge: Claude's prose on top of the pre-fill draft, only where the pre-fill is empty (a\n * written section is never overwritten), anatomy kept from the code, the drafted sections marked for review.\n */\nexport function mergeDocsDraft(prefillDraft: Partial<ComponentDocsJson>, reply: Record<string, unknown>): Partial<ComponentDocsJson> {\n const empty = PROSE_KEYS.filter((k) => {\n const v = prefillDraft[k];\n return v === undefined || (typeof v === 'string' ? !v.trim() : Array.isArray(v) && !v.length);\n });\n const sections = sanitizeDocsSections(reply, empty, { examples: true });\n const merged: Partial<ComponentDocsJson> = { ...prefillDraft, ...sections };\n if (reply.preview && !prefillDraft.preview && isExample(reply.preview)) merged.preview = reply.preview;\n merged.anatomy = prefillDraft.anatomy;\n const drafted = PROSE_KEYS.filter((k) => sections[k] !== undefined);\n return markClaudeDraft(merged, drafted.length && drafted.length < PROSE_KEYS.length ? drafted : undefined);\n}\n\n// ---------------------------------------------------------------------------------------------\n// The Messages API call (raw HTTP: no SDK dependency for one call)\n\nexport interface AnthropicHttpRequest {\n url: string;\n init: { method: 'POST'; headers: Record<string, string>; body: string };\n}\n\nexport interface AnthropicRequestInput {\n apiKey: string;\n prompt: string;\n model?: string | undefined;\n system?: string | undefined;\n maxTokens?: number | undefined;\n /** A direct call from a browser page (the user's own key): adds the header the API asks for. */\n browser?: boolean | undefined;\n /** Re-run a declined request on a fallback model inside the same call (server-side fallback beta). */\n fallback?: boolean | undefined;\n}\n\n/** The Messages API request for one prompt. The key goes in x-api-key, to api.anthropic.com only. */\nexport function anthropicRequest(input: AnthropicRequestInput): AnthropicHttpRequest {\n const headers: Record<string, string> = { 'x-api-key': input.apiKey, 'anthropic-version': '2023-06-01', 'content-type': 'application/json' };\n if (input.fallback) headers['anthropic-beta'] = 'server-side-fallback-2026-07-01';\n if (input.browser) headers['anthropic-dangerous-direct-browser-access'] = 'true';\n const body: Record<string, unknown> = {\n model: input.model || DOCS_DRAFT_MODEL,\n max_tokens: input.maxTokens ?? 16000,\n ...(input.fallback ? { fallbacks: 'default' } : {}),\n ...(input.system ? { system: input.system } : {}),\n messages: [{ role: 'user', content: input.prompt }],\n };\n return { url: ANTHROPIC_MESSAGES_URL, init: { method: 'POST', headers, body: JSON.stringify(body) } };\n}\n\n/** The text of a Messages API reply. Throws when Claude declined or the reply was cut off. */\nexport function anthropicReplyText(msg: unknown): string {\n const m = (msg ?? {}) as { stop_reason?: string; content?: { type?: string; text?: unknown }[] };\n if (m.stop_reason === 'refusal') throw new Error('Claude declined to draft this one.');\n if (m.stop_reason === 'max_tokens') throw new Error('The reply was cut off (max_tokens).');\n return (m.content ?? [])\n .filter((b) => b?.type === 'text' && typeof b.text === 'string')\n .map((b) => b.text as string)\n .join('');\n}\n","// Draft exchange: designers draft their change texts with their own Claude (Claude Desktop or Claude Code on their own\n// plan) through the Bridge MCP server, from the DS Bridge Figma plugin. Third-party apps cannot use a Claude plan, and\n// Bridge has no backend, so the channel is the GitHub repo both already reach with the designer's own token:\n//\n// 1. The plugin writes `.bridge/drafts/<sessionId>.json` (status \"pending\") on the requests branch, with the detected\n// changes, the deterministic draft and links to before and after PNGs uploaded next to it.\n// 2. The designer tells their Claude \"Draft my Bridge changes\". The MCP tool bridge_pending_drafts returns the pending\n// items (and the images, so Claude can see them), bridge_write_drafts writes the results back (status \"drafted\").\n// 3. The plugin polls the file, fills the fields it may fill, then deletes the file once the request or push is sent\n// (or cancelled).\n//\n// Bridge Studio uses the same exchange for component docs (a \"docs\" item, from the Library page): the item carries the\n// task (which prose sections, or a selected passage) and the full prompt with the facts from the code; the result\n// carries the sections (or the rewritten passage), sanitized to the docs.json shapes.\n//\n// Writers update with the file sha (optimistic concurrency) and retry on 409. Pure helpers plus a few GitHubClient\n// helpers: no DOM, no figma.*, no Node-only API.\n\nimport { DRAFT_LINE_MAX, cleanDraftText, sanitizeDraftLine, type DraftText } from './change-drafts';\nimport { type DocsDraftTask, type DocsSections, docsSectionsAnswer, docsTaskKeys, sanitizeDocsReplacement, validateDocsTask } from './docs-ai';\nimport type { ProseKey } from './docs-draft';\nimport { GitHubError, type GitHubClient } from './github-client';\nimport { REQUESTS_BRANCH, type RequestChange, type RequestKind, REQUEST_KINDS } from './requests';\n\nexport const DRAFT_EXCHANGE_VERSION = 1;\n/** Folder of pending draft sessions on the requests branch. */\nexport const DRAFTS_DIR = '.bridge/drafts';\n/** What the designer says to their Claude. */\nexport const DRAFT_PHRASE = 'Draft my Bridge changes';\nexport const DRAFT_TITLE_MAX = 70;\nexport const DRAFT_SUMMARY_SENTENCES = 3;\nexport { DRAFT_LINE_MAX };\nconst SUMMARY_MAX = 600;\n\nexport type DraftScope = 'request' | 'push' | 'docs';\n/** Who wrote the session: the DS Bridge Figma plugin, or Bridge Studio (component docs on the Library page). */\nexport type DraftSource = 'figma' | 'studio';\nexport type DraftSessionStatus = 'pending' | 'drafted';\n\nexport interface DraftImage {\n label: 'before' | 'after';\n /** Public URL on the requests branch (github.com/<repo>/blob/bridge-requests/<path>?raw=true). */\n url: string;\n /** Repo path on the requests branch, so tools can read it with the token. */\n path?: string | undefined;\n /** The change line (DraftLine id) this image shows, when an item has several components (a push). */\n line?: string | undefined;\n}\n\n/**\n * One detected component change to describe in one sentence (its \"change line\"): the main line of its row in the\n * plugin and the first line of its request. A request item has one, a push item one per component it requests.\n */\nexport interface DraftLine {\n /** Stable id to answer with (the plugin uses the component's node id). */\n id: string;\n component?: string | undefined;\n kind?: RequestKind | undefined;\n changes: RequestChange[];\n /** The deterministic line, from the changes only, as a starting point. */\n line: string;\n /** The deterministic request title of this component change, as a starting point. Missing from older plugins. */\n title?: string | undefined;\n}\n\nexport interface DraftVariableRow {\n path: string;\n before?: string | undefined;\n after?: string | undefined;\n}\n\nexport interface DraftItem {\n id: string;\n /** \"request\": one component change request. \"push\": the pull request description of variable edits. */\n scope: DraftScope;\n component?: string | undefined;\n kind?: RequestKind | undefined;\n changes: RequestChange[];\n /** Push only: the variable edits (token path, value now, value in Figma). */\n variables?: DraftVariableRow[] | undefined;\n /** Push only: components the push also sends a request for. */\n components?: string[] | undefined;\n /** What the designer already typed: their intent, kept in the answer. */\n notes?: string | undefined;\n images?: DraftImage[] | undefined;\n /** The deterministic draft (from the detected changes only), as a starting point. */\n draft: DraftText;\n /** Component changes to write one line each for. Missing in sessions from older plugins. */\n lines?: DraftLine[] | undefined;\n /** Docs only: the component docs to write. */\n docs?: DraftDocsItem | undefined;\n}\n\n/** A docs item: prose sections of one component's docs.json (or one selected passage), from Bridge Studio. */\nexport interface DraftDocsItem {\n /** Component slug on the Library page (button, icon-button). */\n slug: string;\n /** docs.json path in the repo. */\n path?: string | undefined;\n task: DocsDraftTask;\n /** The full prompt: the task, the rules, the facts from the code (props, CSS module classes, JSDoc, tokens), the voice. */\n prompt: string;\n}\n\nexport interface DraftResult {\n id: string;\n title: string;\n summary: string;\n /**\n * One sentence per change line of the item (by DraftLine id), and the title of the request it becomes. Optional:\n * older writers send none, or lines without a title.\n */\n lines?: DraftResultLine[] | undefined;\n /** Docs items (sections task): the sections Claude wrote, sanitized to the docs.json shapes. */\n docs?: DocsSections | undefined;\n /** Docs items (selection task): the rewritten passage. */\n replacement?: string | undefined;\n /** Docs items (sections task): checked sections Claude verified and left unchanged (still accurate). */\n checked?: ProseKey[] | undefined;\n by: 'claude';\n at: string;\n}\n\nexport interface DraftResultLine {\n id: string;\n /** May be empty when only the title was written. */\n line: string;\n /** The request title of this component change: short, sentence case, at most 70 characters (\"Add an icon after the label\"). */\n title?: string | undefined;\n}\n\nexport interface PendingDrafts {\n version: 1;\n sessionId: string;\n createdAt: string;\n status: DraftSessionStatus;\n source: DraftSource;\n items: DraftItem[];\n results?: DraftResult[] | undefined;\n}\n\n// ---------------------------------------------------------------------------------------------\n// The words Claude gets: the Bridge voice and the exact output contract.\n\nexport const DRAFT_VOICE_RULES = [\n 'Write like a calm, precise colleague. Sentence case. Start the title with a verb.',\n 'Look at the before and after images first, then the change table: say what changes for developers (props, variants, tokens, the look) and why it matters for people who use the component.',\n 'Use only facts from the changes, the images and the designer\\'s notes. Never invent numbers, names, usage or reasons. If the reason is unknown, say what changes and leave the reason out.',\n 'Keep the designer\\'s intent from their notes.',\n 'Never use an em dash: use a colon, a comma or parentheses. No exclamation marks, no emoji, no Markdown.',\n 'A request title never repeats the component name: the issue title already starts with it.',\n `For each change line, write one short sentence (at most ${DRAFT_LINE_MAX} characters, no trailing period) of what changed for developers, read from the before and after images: the part, the variant and the values when you can see them, for example \"Icon added after the label in primary sm: Pencil, 16px\". Never guess a value you cannot read.`,\n `For each change line, also write the title of the request it becomes: short, sentence case, starts with a verb, at most ${DRAFT_TITLE_MAX} characters, no trailing period, never the component name, for example \"Add an icon after the label\".`,\n];\n\nexport const DRAFT_OUTPUT_CONTRACT = [\n `Call bridge_write_drafts once per session with {\"sessionId\": \"...\", \"results\": [{\"id\": \"<item id>\", \"title\": \"...\", \"summary\": \"...\", \"lines\": [{\"id\": \"<line id>\", \"line\": \"...\", \"title\": \"...\"}]}]}, one result per item.`,\n `title: one line, at most ${DRAFT_TITLE_MAX} characters, no trailing period.`,\n `summary: at most ${DRAFT_SUMMARY_SENTENCES} sentences, plain text.`,\n `lines: one per change line the item lists (its \"lines\"), by line id: line is one sentence, at most ${DRAFT_LINE_MAX} characters, no trailing period; title is the request title for that component change, at most ${DRAFT_TITLE_MAX} characters, no trailing period. Leave lines out when the item lists none.`,\n 'Docs items (scope \"docs\", from Bridge Studio): follow the item\\'s prompt and send {\"id\": \"<item id>\", \"docs\": {<only the sections it asks for>}} for a sections task (a section to check goes in only when something in it is no longer true for the code: leave accurate ones out, {\"docs\": {}} when all are), or {\"id\": \"<item id>\", \"replacement\": \"...\"} for a selection task. No title or summary. The designer reviews them on the Library page.',\n 'The designer reviews the text in Figma before anything is sent.',\n];\n\n// ---------------------------------------------------------------------------------------------\n// Pure helpers\n\n/** A random session id: 16 lowercase base-36 characters, safe in a file name. */\nexport function newDraftSessionId(random: () => number = Math.random): string {\n let out = '';\n while (out.length < 16) out += Math.floor(random() * 36).toString(36);\n return out;\n}\n\nconst SESSION_RE = /^[a-z0-9-]{6,64}$/;\nexport const isDraftSessionId = (s: unknown): s is string => typeof s === 'string' && SESSION_RE.test(s);\n\n/** Path of a session file on the requests branch. */\nexport function draftSessionPath(sessionId: string): string {\n if (!isDraftSessionId(sessionId)) throw new Error(`\"${sessionId}\" is not a draft session id.`);\n return `${DRAFTS_DIR}/${sessionId}.json`;\n}\n\n/** Path of an image of a session item on the requests branch: `.bridge/drafts/<sessionId>/<itemId>-<label>.png`. */\nexport function draftImagePath(sessionId: string, itemId: string, label: DraftImage['label']): string {\n const item = itemId.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'item';\n draftSessionPath(sessionId);\n return `${DRAFTS_DIR}/${sessionId}/${item}-${label}.png`;\n}\n\nexport interface ComposeDraftsInput {\n items: DraftItem[];\n source?: DraftSource | undefined;\n sessionId?: string | undefined;\n now?: Date | undefined;\n random?: (() => number) | undefined;\n}\n\n/** A new pending session. Throws when it has no item or an item is invalid. */\nexport function composePendingDrafts(input: ComposeDraftsInput): PendingDrafts {\n const p: PendingDrafts = {\n version: DRAFT_EXCHANGE_VERSION,\n sessionId: input.sessionId ?? newDraftSessionId(input.random),\n createdAt: (input.now ?? new Date()).toISOString(),\n status: 'pending',\n source: input.source ?? 'figma',\n items: input.items.map((i) => ({ ...i, changes: i.changes ?? [] })),\n };\n const problems = validatePendingDrafts(p);\n if (problems.length) throw new Error(problems.join(' '));\n return p;\n}\n\nconst KINDS = new Set<string>(REQUEST_KINDS.map((k) => k.value));\nconst str = (x: unknown) => typeof x === 'string';\nconst optStr = (x: unknown) => x === undefined || typeof x === 'string';\n\n/** Problems in a session, as sentences. Empty when valid. */\nexport function validatePendingDrafts(x: unknown): string[] {\n const out: string[] = [];\n if (!x || typeof x !== 'object' || Array.isArray(x)) return ['A draft session is a JSON object.'];\n const p = x as Partial<PendingDrafts>;\n if (p.version !== DRAFT_EXCHANGE_VERSION) out.push(`Unsupported draft session version ${String(p.version)}: update Bridge.`);\n if (!isDraftSessionId(p.sessionId)) out.push('The session id is missing or invalid.');\n if (!str(p.createdAt) || Number.isNaN(Date.parse(p.createdAt!))) out.push('createdAt must be an ISO date.');\n if (p.status !== 'pending' && p.status !== 'drafted') out.push('status must be \"pending\" or \"drafted\".');\n if (p.source !== 'figma' && p.source !== 'studio') out.push('source must be \"figma\" or \"studio\".');\n if (!Array.isArray(p.items) || !p.items.length) out.push('A draft session needs at least one item.');\n const ids = new Set<string>();\n for (const [n, i] of (Array.isArray(p.items) ? p.items : []).entries()) {\n const at = `Item ${n + 1}`;\n if (!i || typeof i !== 'object') {\n out.push(`${at} is not an object.`);\n continue;\n }\n if (!str(i.id) || !i.id) out.push(`${at} has no id.`);\n else if (ids.has(i.id)) out.push(`${at} repeats the id \"${i.id}\".`);\n else ids.add(i.id);\n if (i.scope !== 'request' && i.scope !== 'push' && i.scope !== 'docs') out.push(`${at}: scope must be \"request\", \"push\" or \"docs\".`);\n if (i.scope === 'docs') {\n const d = i.docs;\n if (!d || typeof d !== 'object' || !str(d.slug) || !d.slug || !str(d.prompt) || !d.prompt || !optStr(d.path)) out.push(`${at}: a docs item needs docs {slug, task, prompt}.`);\n else out.push(...validateDocsTask(d.task).map((m) => `${at}: ${m}`));\n } else if (i.docs !== undefined) out.push(`${at}: only a docs item has docs.`);\n if (!optStr(i.component)) out.push(`${at}: component must be text.`);\n if (i.kind !== undefined && !KINDS.has(i.kind)) out.push(`${at}: unknown kind \"${String(i.kind)}\".`);\n if (!Array.isArray(i.changes) || i.changes.some((c) => !c || !str(c.field) || !optStr(c.before) || !optStr(c.after))) out.push(`${at}: changes must be a list of {field, before, after}.`);\n if (i.variables !== undefined && (!Array.isArray(i.variables) || i.variables.some((v) => !v || !str(v.path)))) out.push(`${at}: variables must be a list of {path, before, after}.`);\n if (i.variables !== undefined && i.scope !== 'push') out.push(`${at}: only a push item has variables.`);\n if (i.images !== undefined && (!Array.isArray(i.images) || i.images.some((m) => !m || (m.label !== 'before' && m.label !== 'after') || !str(m.url)))) out.push(`${at}: images must be a list of {label: before or after, url}.`);\n if (!i.draft || !str(i.draft.title) || !str(i.draft.summary)) out.push(`${at}: draft must hold a title and a summary.`);\n if (i.lines !== undefined && (!Array.isArray(i.lines) || i.lines.some((l) => !l || !str(l.id) || !l.id || !str(l.line) || !optStr(l.title) || !Array.isArray(l.changes)))) out.push(`${at}: lines must be a list of {id, changes, line, title}.`);\n }\n if (p.results !== undefined) {\n if (!Array.isArray(p.results)) out.push('results must be a list.');\n else\n for (const r of p.results) {\n if (!r || !str(r.id) || !str(r.title) || !str(r.summary)) out.push('Each result needs an id, a title and a summary.');\n else if (r.docs !== undefined && (!r.docs || typeof r.docs !== 'object' || Array.isArray(r.docs))) out.push('Result docs must be an object of sections.');\n else if (!optStr(r.replacement)) out.push('A result replacement must be text.');\n else if (r.lines !== undefined && (!Array.isArray(r.lines) || r.lines.some((l) => !l || !str(l.id) || !str(l.line) || !optStr(l.title)))) out.push('Result lines must be a list of {id, line, title}.');\n }\n }\n return out;\n}\n\n/** The session in a file's text, or undefined when it is not a valid session. */\nexport function parsePendingDrafts(text: string | null | undefined): PendingDrafts | undefined {\n if (!text) return undefined;\n let json: unknown;\n try {\n json = JSON.parse(text);\n } catch {\n return undefined;\n }\n return validatePendingDrafts(json).length ? undefined : (json as PendingDrafts);\n}\n\nexport function serializePendingDrafts(p: PendingDrafts): string {\n return `${JSON.stringify(p, null, 2)}\\n`;\n}\n\n/** Shortens to `max` characters at a word boundary, without a trailing period. */\nfunction clip(text: string, max: number): string {\n const t = text.replace(/\\s+/g, ' ').trim().replace(/\\.$/, '');\n if (t.length <= max) return t;\n const cut = t.slice(0, max + 1);\n const at = cut.lastIndexOf(' ');\n return (at > max * 0.5 ? cut.slice(0, at) : t.slice(0, max)).replace(/[\\s,;:]+$/, '');\n}\n\n/** At most 3 sentences and 600 characters. */\nfunction sentences(text: string): string {\n const t = text.replace(/\\s+/g, ' ').trim();\n const parts = t.match(/[^.!?]+(?:[.!?]+(?=\\s|$)|$)/g) ?? [t];\n let out = parts.slice(0, DRAFT_SUMMARY_SENTENCES).map((s) => s.trim()).join(' ');\n if (out.length > SUMMARY_MAX) out = `${clip(out, SUMMARY_MAX)}.`;\n return out;\n}\n\n/**\n * Title and summary kept to the contract: em dashes removed, title one line of at most 70 characters with no\n * trailing period, summary at most 3 sentences. Both may come back empty.\n */\nexport function sanitizeDraftText(raw: { title?: unknown; summary?: unknown }): DraftText {\n const title = typeof raw.title === 'string' ? clip(cleanDraftText(raw.title), DRAFT_TITLE_MAX) : '';\n const summary = typeof raw.summary === 'string' ? sentences(cleanDraftText(raw.summary)) : '';\n return { title, summary };\n}\n\n/** What a writer (bridge_write_drafts) sends for one item, before sanitizing. */\nexport interface DraftResultInput {\n id: string;\n title?: unknown;\n summary?: unknown;\n lines?: unknown;\n /** Docs items: the sections written (sections task). */\n docs?: unknown;\n /** Docs items: the rewritten passage (selection task). */\n replacement?: unknown;\n}\n\n/** The docs part of a result for a docs item, sanitized to its task. Throws when it holds nothing the task asked for. */\nexport function sanitizeDocsResult(item: DraftItem, r: DraftResultInput): Pick<DraftResult, 'docs' | 'replacement' | 'checked'> {\n const task = item.docs!.task;\n if (task.kind === 'selection') {\n const raw = r.replacement ?? (r.docs && typeof r.docs === 'object' ? (r.docs as Record<string, unknown>)[task.key] : undefined);\n const replacement = sanitizeDocsReplacement(raw);\n if (!replacement) throw new Error(`Item \"${item.id}\" asks to rewrite a passage of ${task.key}: send {\"id\": \"${item.id}\", \"replacement\": \"...\"}.`);\n return { replacement };\n }\n try {\n const { sections, checked } = docsSectionsAnswer(task, r.docs ?? {});\n return { docs: sections, checked };\n } catch {\n throw new Error(`Item \"${item.id}\" asks for the sections ${docsTaskKeys(task).join(', ')}: send {\"id\": \"${item.id}\", \"docs\": {${task.keys.map((k) => `\"${k}\": ...`).join(', ')}}} in the shapes of its prompt.`);\n }\n}\n\n/**\n * The change lines of a result kept to the contract: known line ids only (throws on an unknown one), one sentence of\n * at most 120 characters each, empty ones dropped, the last one per id kept.\n */\nexport function sanitizeResultLines(item: Pick<DraftItem, 'id' | 'lines'>, raw: unknown): DraftResultLine[] {\n if (raw === undefined || raw === null) return [];\n if (!Array.isArray(raw)) throw new Error(`lines for \"${item.id}\" must be a list of {\"id\", \"line\", \"title\"}.`);\n const known = new Set((item.lines ?? []).map((l) => l.id));\n const out = new Map<string, DraftResultLine>();\n for (const l of raw as { id?: unknown; line?: unknown; title?: unknown }[]) {\n const id = typeof l?.id === 'string' ? l.id : '';\n if (!known.has(id)) throw new Error(`Item \"${item.id}\" has no change line \"${id}\".${known.size ? ` Use the line ids from bridge_pending_drafts: ${[...known].join(', ')}.` : ' It lists no lines: leave lines out.'}`);\n const line = sanitizeDraftLine(l.line);\n const title = sanitizeDraftTitle(l.title);\n if (line || title) out.set(id, { id, line, ...(title ? { title } : {}) });\n }\n return [...out.values()];\n}\n\n/** A request title kept to the contract: one line, no em dash, sentence case, at most 70 characters, no trailing period. */\nexport function sanitizeDraftTitle(raw: unknown): string {\n if (typeof raw !== 'string') return '';\n const t = clip(cleanDraftText(raw.replace(/[\\r\\n]+/g, ' ')), DRAFT_TITLE_MAX);\n return t.charAt(0).toUpperCase() + t.slice(1);\n}\n\n/**\n * The session with these results added (a result for the same item replaces the earlier one). Results are sanitized.\n * Throws on an unknown item id or an empty result. Status is \"drafted\" once every item has a result.\n */\nexport function mergeDraftResults(p: PendingDrafts, results: DraftResultInput[], at: Date = new Date()): PendingDrafts {\n const ids = new Set(p.items.map((i) => i.id));\n const next = new Map((p.results ?? []).map((r) => [r.id, r]));\n for (const r of results) {\n if (!ids.has(r.id)) throw new Error(`Session ${p.sessionId} has no item \"${r.id}\". Use the ids from bridge_pending_drafts: ${[...ids].join(', ')}.`);\n const item = p.items.find((i) => i.id === r.id)!;\n if (item.scope === 'docs') {\n next.set(r.id, { id: r.id, title: '', summary: '', ...sanitizeDocsResult(item, r), by: 'claude', at: at.toISOString() });\n continue;\n }\n const clean = sanitizeDraftText(r);\n const lines = sanitizeResultLines(item, r.lines);\n if (!clean.title && !clean.summary && !lines.length) throw new Error(`The result for \"${r.id}\" has no title and no summary, and no line.`);\n next.set(r.id, { id: r.id, title: clean.title, summary: clean.summary, ...(lines.length ? { lines } : {}), by: 'claude', at: at.toISOString() });\n }\n const merged = p.items.map((i) => next.get(i.id)).filter((r): r is DraftResult => !!r);\n return { ...p, results: merged, status: merged.length === p.items.length ? 'drafted' : 'pending' };\n}\n\n/** The Markdown brief of one item, for Claude: what to write, the facts, the starting draft. */\nexport function draftItemBrief(i: DraftItem): string {\n if (i.scope === 'docs' && i.docs) {\n const t = i.docs.task;\n const check = t.kind === 'sections' ? (t.check ?? []).filter((k) => t.keys.includes(k)) : [];\n const write = t.kind === 'sections' ? t.keys.filter((k) => !check.includes(k)) : [];\n const what =\n t.kind === 'selection'\n ? `rewrite one passage of the ${t.key} section (${t.mode}), answer with \"replacement\"`\n : [\n write.length ? `${t.rewrite ? 'rewrite' : 'write'} the sections ${write.join(', ')}` : '',\n check.length ? `check the sections ${check.join(', ')} against the code and return one only when something in it is no longer true (leave accurate ones out)` : '',\n ]\n .filter(Boolean)\n .join('; ') + ', answer with \"docs\"';\n return [`Item ${i.id}: component docs${i.component ? ` of ${i.component}` : ''} from Bridge Studio (${i.docs.path ?? i.docs.slug}): ${what}.`, '', i.docs.prompt].join('\\n');\n }\n const kind = i.kind ? REQUEST_KINDS.find((k) => k.value === i.kind)?.label : undefined;\n const cell = (s: string | undefined) => (s ?? '').replace(/\\|/g, '\\\\|').replace(/\\n/g, ' ');\n const lines: string[] = [`Item ${i.id}: ${i.scope === 'request' ? 'a component change request (a GitHub issue developers implement)' : 'the description of a pull request with design token (variable) edits from Figma'}.`];\n if (i.component) lines.push(`Component: ${i.component}`);\n if (kind) lines.push(`Kind: ${kind}`);\n if (i.components?.length) lines.push(`Components with a change request: ${i.components.join(', ')}`);\n if (i.changes.length) lines.push('', '| What | Now | In Figma |', '| --- | --- | --- |', ...i.changes.map((c) => `| ${cell(c.field)} | ${cell(c.before) || 'none'} | ${cell(c.after) || 'removed'} |`));\n if (i.variables?.length) lines.push('', '| Token | Now | In Figma |', '| --- | --- | --- |', ...i.variables.map((v) => `| ${cell(v.path)} | ${cell(v.before) || 'none'} | ${cell(v.after) || 'removed'} |`));\n if (!i.changes.length && !i.variables?.length && !i.lines?.length) lines.push('', 'No change detected: rely on the notes and the images.');\n if (i.draft.title || i.draft.summary) lines.push('', 'Starting draft, written from the changes only:', `Title: ${i.draft.title}`, `Summary: ${i.draft.summary}`);\n if (i.notes?.trim()) lines.push('', 'The designer\\'s notes (keep their intent):', i.notes.trim());\n if (i.lines?.length) {\n lines.push('', `Change lines to write (one sentence each, at most ${DRAFT_LINE_MAX} characters, from the before and after images), each with the title of its request (at most ${DRAFT_TITLE_MAX} characters):`);\n for (const l of i.lines) {\n lines.push(`- Line ${l.id}${l.component ? `, ${l.component}` : ''}${l.kind ? ` (${REQUEST_KINDS.find((k) => k.value === l.kind)?.label ?? l.kind})` : ''}. Starting line: ${l.line || '(none)'}${l.title ? `. Starting title: ${l.title}` : ''}`);\n for (const c of l.changes) lines.push(` - ${c.field}: ${c.before || 'none'} -> ${c.after || 'removed'}`);\n }\n }\n if (i.images?.length) lines.push('', `Images: ${i.images.map((m) => `${m.label}${m.line ? ` (line ${m.line})` : ''} ${m.url}`).join(', ')}`);\n return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------------------------\n// GitHub: read and write sessions on the requests branch\n\ntype DraftClient = Pick<GitHubClient, 'getFile' | 'putFile' | 'deleteFile' | 'listDirectory'>;\n\nconst isConflict = (err: unknown) => err instanceof GitHubError ? err.status === 409 || (err.status === 422 && /sha/i.test(`${err.detail ?? ''} ${err.message}`)) : (err as { status?: number })?.status === 409;\n\n/** Writes a new session file on the requests branch (the branch must exist). Returns the session. */\nexport async function createPendingDrafts(client: DraftClient, p: PendingDrafts, branch = REQUESTS_BRANCH): Promise<PendingDrafts> {\n const problems = validatePendingDrafts(p);\n if (problems.length) throw new Error(problems.join(' '));\n await client.putFile({ path: draftSessionPath(p.sessionId), content: serializePendingDrafts(p), branch, message: `Bridge drafts: ${p.items.length === 1 ? '1 item' : `${p.items.length} items`} waiting for Claude` });\n return p;\n}\n\n/** One session and its file sha, or undefined when the file is gone (sent, cancelled) or not a session. */\nexport async function readPendingDrafts(client: Pick<GitHubClient, 'getFile'>, sessionId: string, branch = REQUESTS_BRANCH): Promise<{ drafts: PendingDrafts; sha: string } | undefined> {\n const f = await client.getFile(draftSessionPath(sessionId), branch);\n const drafts = parsePendingDrafts(f?.text);\n return f && drafts ? { drafts, sha: f.sha } : undefined;\n}\n\n/** Every valid session on the requests branch, newest first. Unreadable files are skipped. */\nexport async function listPendingDrafts(client: Pick<GitHubClient, 'getFile' | 'listDirectory'>, opts: { status?: DraftSessionStatus | 'all'; branch?: string } = {}): Promise<PendingDrafts[]> {\n const branch = opts.branch ?? REQUESTS_BRANCH;\n const entries = (await client.listDirectory(DRAFTS_DIR, branch)).filter((e) => e.type === 'file' && /\\.json$/.test(e.name));\n const out: PendingDrafts[] = [];\n for (const e of entries) {\n const id = e.name.replace(/\\.json$/, '');\n if (!isDraftSessionId(id)) continue;\n const r = await readPendingDrafts(client, id, branch).catch(() => undefined);\n if (r && r.drafts.sessionId === id) out.push(r.drafts);\n }\n const status = opts.status ?? 'all';\n return out.filter((p) => status === 'all' || p.status === status).sort((a, b) => b.createdAt.localeCompare(a.createdAt));\n}\n\n/**\n * Read, change and write a session with its sha; when someone else wrote it in between (409), read it again and\n * retry, up to `attempts` times. Throws when the session does not exist.\n */\nexport async function updatePendingDrafts(\n client: DraftClient,\n sessionId: string,\n change: (p: PendingDrafts) => PendingDrafts,\n opts: { branch?: string; attempts?: number; message?: string } = {},\n): Promise<PendingDrafts> {\n const branch = opts.branch ?? REQUESTS_BRANCH;\n const attempts = Math.max(1, opts.attempts ?? 3);\n for (let attempt = 1; ; attempt++) {\n const cur = await readPendingDrafts(client, sessionId, branch);\n if (!cur) throw new Error(`No pending drafts for session ${sessionId}: it was sent or cancelled in Figma. Call bridge_pending_drafts for the current ones.`);\n const next = change(cur.drafts);\n try {\n await client.putFile({ path: draftSessionPath(sessionId), content: serializePendingDrafts(next), branch, message: opts.message ?? 'Bridge drafts: update', sha: cur.sha });\n return next;\n } catch (err) {\n if (attempt >= attempts || !isConflict(err)) throw err;\n }\n }\n}\n\n/** Writes Claude's results into a session (sanitized, merged, status \"drafted\" when complete), retrying on 409. */\nexport function writeDraftResults(client: DraftClient, sessionId: string, results: DraftResultInput[], opts: { branch?: string; now?: Date; attempts?: number } = {}): Promise<PendingDrafts> {\n return updatePendingDrafts(client, sessionId, (p) => mergeDraftResults(p, results, opts.now), {\n ...opts,\n message: `Bridge drafts: ${results.length === 1 ? '1 text' : `${results.length} texts`} drafted by Claude`,\n });\n}\n\n/**\n * Removes a session once it was sent or cancelled: its file, then its images (best effort). Returns false when it was\n * already gone.\n */\nexport async function deletePendingDrafts(client: DraftClient, sessionId: string, opts: { branch?: string } = {}): Promise<boolean> {\n const branch = opts.branch ?? REQUESTS_BRANCH;\n const path = draftSessionPath(sessionId);\n const f = await client.getFile(path, branch);\n if (!f) return false;\n await client.deleteFile({ path, branch, message: 'Bridge drafts: done', sha: f.sha });\n const images = await client.listDirectory(`${DRAFTS_DIR}/${sessionId}`, branch).catch(() => []);\n for (const img of images.filter((e) => e.type === 'file')) {\n await client.deleteFile({ path: img.path, branch, message: 'Bridge drafts: done', sha: img.sha }).catch(() => undefined);\n }\n return true;\n}\n\n/** Creates the requests branch from the head of `baseBranch` when it is missing. Never moves an existing branch. */\nexport async function ensureRequestsBranch(client: Pick<GitHubClient, 'getBranchSha' | 'createBranch'>, baseBranch: string): Promise<void> {\n if (await client.getBranchSha(REQUESTS_BRANCH)) return;\n const head = await client.getBranchSha(baseBranch);\n if (!head) throw new Error(`Branch \"${baseBranch}\" was not found, so the ${REQUESTS_BRANCH} branch cannot start from it.`);\n await client.createBranch(REQUESTS_BRANCH, head);\n}\n\nexport interface DocsDraftSessionInput {\n component: string;\n slug: string;\n path?: string | undefined;\n task: DocsDraftTask;\n prompt: string;\n /** Branch the requests branch starts from when it does not exist yet. */\n baseBranch: string;\n now?: Date | undefined;\n random?: (() => number) | undefined;\n}\n\n/**\n * Bridge Studio asks the user's own Claude for component docs: one docs item in a new session (source \"studio\") on\n * the requests branch, created from `baseBranch` when missing. Returns the session to poll.\n */\nexport async function createDocsDraftSession(\n client: Pick<GitHubClient, 'getBranchSha' | 'createBranch' | 'getFile' | 'putFile' | 'deleteFile' | 'listDirectory'>,\n input: DocsDraftSessionInput,\n): Promise<PendingDrafts> {\n await ensureRequestsBranch(client, input.baseBranch);\n const what = input.task.kind === 'selection' ? `Rewrite a passage of ${input.task.key}` : `${input.task.rewrite ? 'Rewrite' : 'Write'} ${input.task.keys.join(', ')}`;\n const item: DraftItem = {\n id: 'docs-1',\n scope: 'docs',\n component: input.component,\n changes: [],\n draft: { title: `${input.component} docs`, summary: what },\n docs: { slug: input.slug, ...(input.path ? { path: input.path } : {}), task: input.task, prompt: input.prompt },\n };\n return createPendingDrafts(client, composePendingDrafts({ items: [item], source: 'studio', now: input.now, random: input.random }));\n}\n\n// ---------------------------------------------------------------------------------------------\n// Polling: the plugin and Studio read the session until Claude answers\n\nexport const DRAFT_POLL_INTERVAL_MS = 5_000;\nexport const DRAFT_POLL_TIMEOUT_MS = 10 * 60_000;\n\nexport interface DraftPollerOptions {\n client: Pick<GitHubClient, 'getFile'>;\n sessionId: string;\n intervalMs?: number | undefined;\n timeoutMs?: number | undefined;\n now?: (() => number) | undefined;\n setTimer?: ((fn: () => void, ms: number) => unknown) | undefined;\n clearTimer?: ((handle: unknown) => void) | undefined;\n /** Claude answered every item. Polling has stopped. */\n onResults: (results: DraftResult[], drafts: PendingDrafts) => void;\n /** No answer within the timeout. Polling has stopped; start() polls again. */\n onTimeout: () => void;\n /** The file is gone (sent or cancelled elsewhere). Polling has stopped. */\n onGone?: (() => void) | undefined;\n /** A read failed; polling goes on. */\n onError?: ((message: string) => void) | undefined;\n}\n\n/** Reads the session every 5 seconds until Claude answers, the file goes away, or 10 minutes pass. */\nexport class DraftPoller {\n private handle: unknown;\n private startedAt = 0;\n private running = false;\n private busy = false;\n\n constructor(private readonly o: DraftPollerOptions) {}\n\n get active(): boolean {\n return this.running;\n }\n\n private now(): number {\n return (this.o.now ?? Date.now)();\n }\n\n private schedule(): void {\n const set = this.o.setTimer ?? ((fn: () => void, ms: number) => setTimeout(fn, ms));\n this.handle = set(() => void this.tick(), this.o.intervalMs ?? DRAFT_POLL_INTERVAL_MS);\n }\n\n /** Starts (or restarts, after a timeout) polling; the timeout counts from now. */\n start(): void {\n this.stop();\n this.running = true;\n this.startedAt = this.now();\n this.schedule();\n }\n\n stop(): void {\n if (this.handle !== undefined) (this.o.clearTimer ?? ((h: unknown) => clearTimeout(h as ReturnType<typeof setTimeout>)))(this.handle);\n this.handle = undefined;\n this.running = false;\n }\n\n private async tick(): Promise<void> {\n if (!this.running) return;\n this.handle = undefined;\n const done = await this.check();\n if (done || !this.running) return;\n if (this.now() - this.startedAt >= (this.o.timeoutMs ?? DRAFT_POLL_TIMEOUT_MS)) {\n this.stop();\n this.o.onTimeout();\n return;\n }\n this.schedule();\n }\n\n /** Reads the file once. True when polling is over (answered or gone). */\n async check(): Promise<boolean> {\n if (this.busy) return false;\n this.busy = true;\n try {\n const cur = await readPendingDrafts(this.o.client, this.o.sessionId);\n if (!cur) {\n this.stop();\n this.o.onGone?.();\n return true;\n }\n if (cur.drafts.status === 'drafted' && cur.drafts.results?.length) {\n this.stop();\n this.o.onResults(cur.drafts.results, cur.drafts);\n return true;\n }\n return false;\n } catch (err) {\n this.o.onError?.(err instanceof Error ? err.message : String(err));\n return false;\n } finally {\n this.busy = false;\n }\n }\n}\n","// Explorations on GitHub: start one (branch from the base with the exploration note, a draft pull request labeled\n// `exploration`), list them, promote one to review, close one. Shared by Studio (in the browser, with the viewer's\n// token), the MCP server and the CLI. The pure rules are in explorations.ts.\n\nimport type { BridgeConfig } from './config';\nimport {\n EXPLORATION_LABEL,\n EXPLORATION_PREFIX,\n explorationNote,\n explorationNotePath,\n explorationPrBody,\n explorationPrTitle,\n explorationProblems,\n explorationSlug,\n explorationStatus,\n explorationTryIt,\n isExplorationPull,\n parseExplorationBody,\n promotionPlan,\n type Exploration,\n type ExplorationSource,\n type ExplorationStatus,\n type ExplorationTryIt,\n type PromotionPlan,\n} from './explorations';\nimport { GitHubError, type GitHubClient, type PullRequestSummary } from './github-client';\nimport { findPreviewComment, previewLinks, previewsSettled, type BranchPreview, type PreviewApps } from './previews';\nimport { branchPreviewUrls } from './previews-github';\n\nexport interface ExplorationSettings {\n /** Branch explorations start from and pull requests target (the default branch). */\n base: string;\n /** Snapshot packages (bridge.config.json previews.packages). */\n packages: string[];\n /** Per-branch preview URL templates (bridge.config.json previews.apps). */\n apps: PreviewApps;\n /** Requests the exploration answers, listed in its draft pull request body. */\n requests?: { number: number; title: string }[] | undefined;\n /** More labels for the draft pull request, such as the product ones (productMarks). */\n labels?: string[] | undefined;\n}\n\nexport interface ExplorationSummary {\n number: number;\n url: string;\n branch: string;\n slug: string;\n name: string;\n purpose: string;\n useCase?: string | undefined;\n status: ExplorationStatus;\n draft: boolean;\n author: string;\n /** Where it was started and the AI agent that started it, when the exploration block says so. */\n source?: ExplorationSource | undefined;\n agent?: string | undefined;\n updatedAt: string;\n /** Head commit of the branch. */\n headSha: string;\n /**\n * Template previews Vercel cannot have shortened (a host label of 63 characters or less), without a round trip. The\n * URLs Vercel reports, with their build state, come from `explorationTestBuildOnGitHub`.\n */\n previews: { app: string; label: string; url: string }[];\n}\n\n/** One exploration from a pull request summary. */\nexport function explorationSummary(p: PullRequestSummary, _owner: string, _repo: string, s: Pick<ExplorationSettings, 'packages' | 'apps'>): ExplorationSummary {\n const e = parseExplorationBody(p.body);\n const slug = p.headRef?.startsWith(EXPLORATION_PREFIX) ? p.headRef.slice(EXPLORATION_PREFIX.length) : (e?.slug ?? explorationSlug(p.title));\n return {\n number: p.number,\n url: p.url,\n branch: p.headRef,\n slug,\n name: e?.name ?? p.title.replace(/^[A-Z][A-Z0-9_]*-\\d+\\s+/, '').replace(/^Exploration:\\s*/i, ''),\n purpose: e?.purpose ?? '',\n ...(e?.useCase ? { useCase: e.useCase } : {}),\n status: explorationStatus({ state: p.state, labels: p.labels, headRef: p.headRef, body: p.body }),\n draft: p.draft,\n author: e?.author ?? p.author,\n ...(e?.source ? { source: e.source } : {}),\n ...(e?.agent ? { agent: e.agent } : {}),\n updatedAt: p.updatedAt,\n headSha: p.headSha,\n previews: previewLinks(s.apps, { branch: p.headRef, pr: p.number, sha: p.headSha }),\n };\n}\n\n/** Explorations of the repo, newest activity first. `state: 'open'` lists the running ones and the promoted open ones. */\nexport async function listExplorationsOnGitHub(gh: GitHubClient, s: Pick<ExplorationSettings, 'packages' | 'apps'>, opts: { state?: 'open' | 'closed' | 'all' } = {}): Promise<ExplorationSummary[]> {\n const pulls = await gh.listPullRequests(opts.state ?? 'open');\n return pulls.filter((p) => isExplorationPull({ state: p.state, labels: p.labels, headRef: p.headRef, body: p.body })).map((p) => explorationSummary(p, gh.owner, gh.name, s));\n}\n\nexport interface StartedExploration {\n branch: string;\n slug: string;\n pr: number;\n url: string;\n commit: string;\n /** Just started: the snapshot is not built yet. `explorationTestBuildOnGitHub` reads the command once it is. */\n tryIt: ExplorationTryIt;\n previews: { app: string; label: string; url: string }[];\n}\n\n/**\n * Starts an exploration: the branch `explore/<slug>` from the base with one commit (the exploration note), a draft\n * pull request labeled `exploration`, then the body rewritten with the pull request number so it carries the\n * install command. Refuses an exploration whose branch already exists.\n */\nexport async function startExplorationOnGitHub(gh: GitHubClient, e: Exploration, s: ExplorationSettings): Promise<StartedExploration> {\n const problems = explorationProblems(e);\n if (problems.length) throw new GitHubError(422, problems.join(' '));\n if (!gh.canWrite) throw new GitHubError(401, 'Starting an exploration needs a GitHub token (contents and pull requests, read and write, on this repository only).');\n const slug = e.slug || explorationSlug(e.name);\n const branch = `${EXPLORATION_PREFIX}${slug}`;\n const x = gh.withBranchPrefix(EXPLORATION_PREFIX);\n if (await x.getBranchSha(branch)) throw new GitHubError(422, `An exploration named \"${slug}\" already exists (${branch}). Pick another name, or continue that one.`);\n const full: Exploration = { ...e, slug, startedAt: e.startedAt ?? new Date().toISOString() };\n const commit = await x.commitToNewBranch({\n base: s.base,\n branch,\n message: `chore(explore): start ${full.name.trim()}\\n\\n${full.purpose.trim()}\\n\\nExploration: never merged as is. Promote it to review or close it.`,\n files: [{ path: explorationNotePath(slug), content: explorationNote(full) }],\n });\n const ctx = { owner: gh.owner, repo: gh.name, packages: s.packages, apps: s.apps, ...(s.requests?.length ? { requests: s.requests } : {}) };\n const title = full.jira ? `${full.jira.trim().toUpperCase()} ${explorationPrTitle(full)}` : explorationPrTitle(full);\n const pr = await x.createPullRequest({ title, head: branch, base: s.base, body: explorationPrBody(full, ctx), draft: true });\n await x.addLabels(pr.number, [EXPLORATION_LABEL, ...(s.labels ?? [])]);\n // The number exists now: the body gets the install command.\n await x.updatePullRequest(pr.number, { body: explorationPrBody(full, { ...ctx, pr: pr.number }) }).catch(() => undefined);\n return {\n branch,\n slug,\n pr: pr.number,\n url: pr.url,\n commit: commit.sha,\n tryIt: { state: 'building' },\n previews: previewLinks(s.apps, { branch, pr: pr.number, sha: commit.sha }),\n };\n}\n\n/**\n * Where the test build of an exploration stands: the install command from its sticky preview comment when it matches\n * the branch head, \"building\" while the workflow has not caught up, \"failed\" when the publish failed. Two reads.\n */\nexport async function explorationTryItOnGitHub(gh: GitHubClient, e: { number: number; branch: string }): Promise<ExplorationTryIt> {\n const [comments, head] = await Promise.all([gh.listIssueComments(e.number), gh.getBranchSha(e.branch).catch(() => undefined)]);\n return explorationTryIt({ comment: findPreviewComment(comments)?.body, headSha: head });\n}\n\nexport interface ExplorationTestBuild {\n /** The install command from the sticky preview comment, or building/failed. Never a guessed command. */\n tryIt: ExplorationTryIt;\n /** Every configured app with the URL Vercel reports (null while unknown) and its build state. */\n previews: BranchPreview[];\n /** True when the command is ready (or the publish failed) and every preview is built: polling can stop. */\n settled: boolean;\n}\n\n/**\n * Everything \"Try it\" shows for an exploration, read in one go: the command from the preview comment and the real\n * preview URLs (deployments, Vercel statuses, the Vercel comment). Comments and the branch head are read once.\n */\nexport async function explorationTestBuildOnGitHub(gh: GitHubClient, e: { number: number; branch: string }, config: Pick<BridgeConfig, 'previews'> | undefined): Promise<ExplorationTestBuild> {\n const [comments, head] = await Promise.all([gh.listIssueComments(e.number), gh.getBranchSha(e.branch).catch(() => undefined)]);\n const tryIt = explorationTryIt({ comment: findPreviewComment(comments)?.body, headSha: head });\n const previews = await branchPreviewUrls(gh, e.number, config, { branch: e.branch, sha: head, comments }).catch(() => [] as BranchPreview[]);\n return { tryIt, previews, settled: tryIt.state !== 'building' && previewsSettled(previews) };\n}\n\n/** The open exploration pull request of a branch, slug or number. */\nexport async function findExplorationOnGitHub(gh: GitHubClient, ref: string | number): Promise<PullRequestSummary & { body: string }> {\n if (typeof ref === 'number' || /^#?\\d+$/.test(String(ref))) {\n const p = await gh.getPullRequest(Number(String(ref).replace(/^#/, '')));\n if (!isExplorationPull({ state: p.state, labels: p.labels, headRef: p.headRef, body: p.body })) throw new GitHubError(422, `Pull request #${p.number} is not an exploration.`);\n return p;\n }\n const branch = `${EXPLORATION_PREFIX}${explorationSlug(String(ref))}`;\n const open = await gh.findOpenPullRequest(branch);\n if (!open) throw new GitHubError(404, `No open exploration on ${branch}. \\`bridge explore list\\` shows the running ones.`);\n return gh.getPullRequest(open.number);\n}\n\nexport interface PromotedExploration extends PromotionPlan {\n number: number;\n url: string;\n branch: string;\n /** Steps that did not go through, with what to do on GitHub instead. */\n warnings: string[];\n}\n\n/**\n * Promotes an exploration to a normal pull request for review: the exploration note removed from the branch, the\n * tier labels from the shared classifier, the `exploration` label removed, the body for review (closing the\n * requests implemented on it), and the draft marked ready for review (GraphQL). Never merges.\n */\nexport async function promoteExplorationOnGitHub(\n gh: GitHubClient,\n ref: string | number,\n opts: { config?: BridgeConfig | undefined; requests?: number[] | undefined; date?: Date | undefined; dryRun?: boolean | undefined } = {},\n): Promise<PromotedExploration> {\n const p = await findExplorationOnGitHub(gh, ref);\n const status = explorationStatus({ state: p.state, labels: p.labels, headRef: p.headRef, body: p.body });\n if (status !== 'active') throw new GitHubError(422, status === 'closed' ? `Exploration #${p.number} is closed. Reopen it on GitHub first.` : `#${p.number} is already promoted to review.`);\n const files = await gh.listPullRequestFiles(p.number);\n const plan = promotionPlan({ title: p.title, body: p.body, labels: p.labels, files: files.map((f) => ({ path: f.filename, status: f.status })), config: opts.config, requests: opts.requests, date: opts.date });\n const out: PromotedExploration = { ...plan, number: p.number, url: p.url, branch: p.headRef, warnings: [] };\n if (opts.dryRun) return out;\n if (!gh.canWrite) throw new GitHubError(401, 'Promoting an exploration needs a GitHub token (contents and pull requests, read and write).');\n const x = gh.withBranchPrefix(EXPLORATION_PREFIX);\n if (plan.removeFiles.length) {\n await x.commitToBranch({ branch: p.headRef, message: 'chore(explore): promote to review, remove the exploration note', files: plan.removeFiles.map((path) => ({ path, content: null })) }).catch((e: Error) => {\n // A refused token is not a partial success: nothing else would go through either.\n if (e instanceof GitHubError && e.auth === 'rejected') throw e;\n out.warnings.push(`The exploration note stays on the branch (${e.message}). Delete ${plan.removeFiles.join(', ')} before merging.`);\n });\n }\n await x.addLabels(p.number, plan.addLabels);\n await x.removeLabel(p.number, EXPLORATION_LABEL).catch((e: Error) => {\n if (!(e instanceof GitHubError && e.status === 404)) out.warnings.push(`The exploration label is still on (${e.message}). Remove it on GitHub.`);\n });\n await x.updatePullRequest(p.number, { title: plan.title, body: plan.body });\n await x.markReadyForReview(p.number).catch((e: Error) => {\n out.warnings.push(`Still a draft: ${e.message}`);\n });\n return out;\n}\n\n/** Closes an exploration without merging. The branch stays for reference; the workflow removes the prerelease. */\nexport async function closeExplorationOnGitHub(gh: GitHubClient, ref: string | number): Promise<{ number: number; url: string; branch: string }> {\n if (!gh.canWrite) throw new GitHubError(401, 'Closing an exploration needs a GitHub token (pull requests: write).');\n const p = await findExplorationOnGitHub(gh, ref);\n await gh.updatePullRequest(p.number, { state: 'closed' });\n return { number: p.number, url: p.url, branch: p.headRef };\n}\n","// Fidelity check: does a component built in Figma look like the code? Compares a Figma export of one variant with\n// an image of the same variant rendered from code (the Storybook reference images, see fidelity-references.ts).\n// Pure and dependency free: images are plain RGBA buffers, decoded by the caller (a canvas in the plugin, pngjs in\n// Node). The result shapes are JSON so a report can be stored and shown later (Studio Quality, follow-up).\n\n/** An RGBA image, 4 bytes per pixel, row by row (ImageData, pngjs and canvas all use this layout). */\nexport interface RgbaImage {\n width: number;\n height: number;\n data: Uint8Array | Uint8ClampedArray;\n}\n\nexport interface Size {\n width: number;\n height: number;\n}\n\nexport interface CompareOptions {\n /** Export scale of both images (device pixels per CSS pixel). Sizes are reported in CSS pixels. Default 2. */\n scale?: number;\n /**\n * Color distance under which two pixels are the same, 0 to 1 (YIQ, as pixelmatch). Default 0.1: absorbs gamma\n * and antialiasing ramps, catches a token swap (a gray one step away is about 0.12).\n */\n threshold?: number;\n /**\n * Neighborhood, in device pixels, searched for a matching pixel before one counts as different. Figma and Chrome\n * rasterize text and curves differently (glyph hinting, subpixel positions, corner antialiasing): a pixel that has\n * its twin within this distance is the same shape drawn half a pixel away. Default: one CSS pixel (= scale).\n */\n radius?: number;\n /** Largest share of different pixels, in percent, that still matches. Default 3. */\n maxPercent?: number;\n /** Largest size difference per side, in CSS pixels, that still matches. Default 1. */\n sizeTolerance?: number;\n /** Also return the diff overlay. Default true. */\n diffImage?: boolean;\n}\n\nexport interface ImageCompareResult {\n matches: boolean;\n /** Different pixels in percent of the larger canvas, two decimals. */\n percent: number;\n differentPixels: number;\n totalPixels: number;\n /** CSS pixel sizes (image size divided by the scale, rounded). */\n size: { figma: Size; code: Size };\n sizeMatches: boolean;\n /** The code image faded to gray with different pixels in red, on the larger canvas. */\n diff?: RgbaImage | undefined;\n}\n\nexport const FIDELITY_DEFAULTS = { scale: 2, threshold: 0.1, maxPercent: 3, sizeTolerance: 1 } as const;\n\n// Largest YIQ squared distance (black vs white), as in pixelmatch.\nconst MAX_DELTA = 35215;\n// Outside the overlap of two sizes: only near-white (transparent) pixels are the same.\nconst STRICT_THRESHOLD = 0.02;\n\n/** Pixel `i` of an image composited over white, or white outside the image. */\nfunction rgbAt(img: RgbaImage, x: number, y: number): [number, number, number] {\n if (x < 0 || y < 0 || x >= img.width || y >= img.height) return [255, 255, 255];\n const i = (y * img.width + x) * 4;\n const a = img.data[i + 3]! / 255;\n return [255 + (img.data[i]! - 255) * a, 255 + (img.data[i + 1]! - 255) * a, 255 + (img.data[i + 2]! - 255) * a];\n}\n\n/** YIQ squared distance between two opaque colors (pixelmatch's perceptual metric). */\nexport function colorDelta(a: [number, number, number], b: [number, number, number]): number {\n const dr = a[0] - b[0];\n const dg = a[1] - b[1];\n const db = a[2] - b[2];\n const y = dr * 0.29889531 + dg * 0.58662247 + db * 0.11448223;\n const i = dr * 0.59597799 - dg * 0.2741761 - db * 0.32180189;\n const q = dr * 0.21147017 - dg * 0.52261711 + db * 0.31114694;\n return 0.5053 * y * y + 0.299 * i * i + 0.1957 * q * q;\n}\n\n/** Whether color `c` appears in `img` within `radius` pixels of (x, y). */\nfunction foundNear(img: RgbaImage, x: number, y: number, c: [number, number, number], radius: number, max: number): boolean {\n for (let dy = -radius; dy <= radius; dy++) for (let dx = -radius; dx <= radius; dx++) if (colorDelta(c, rgbAt(img, x + dx, y + dy)) <= max) return true;\n return false;\n}\n\n/**\n * Compares a Figma export with the code reference of the same variant. A pixel differs when its color is not found\n * near the same place in the other image, in either direction: a shape drawn half a pixel away, or text rasterized\n * a little differently, matches; a missing border, another color, other padding or a different size does not.\n * Pixels outside the smaller image count as transparent: there, any visible color differs (a missing footer is a\n * difference even when its gray is light).\n */\nexport function compareImages(figma: RgbaImage, code: RgbaImage, options: CompareOptions = {}): ImageCompareResult {\n const scale = options.scale ?? FIDELITY_DEFAULTS.scale;\n const radius = Math.max(0, Math.round(options.radius ?? scale));\n const max = MAX_DELTA * (options.threshold ?? FIDELITY_DEFAULTS.threshold) ** 2;\n const strict = MAX_DELTA * STRICT_THRESHOLD ** 2;\n const width = Math.max(figma.width, code.width);\n const height = Math.max(figma.height, code.height);\n const total = width * height;\n const wantDiff = options.diffImage !== false;\n const out = wantDiff ? new Uint8ClampedArray(total * 4) : undefined;\n let different = 0;\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n const a = rgbAt(figma, x, y);\n const b = rgbAt(code, x, y);\n // Where only one image has pixels (a size difference), any visible color counts: a light surface on white is\n // a missing part, not antialiasing.\n const m = x < Math.min(figma.width, code.width) && y < Math.min(figma.height, code.height) ? max : strict;\n const same = colorDelta(a, b) <= m || (foundNear(code, x, y, a, radius, m) && foundNear(figma, x, y, b, radius, m));\n if (!same) different++;\n if (out) {\n const o = (y * width + x) * 4;\n if (same) {\n // The code image, faded: light gray context for the red marks.\n const gray = 255 + ((b[0] * 0.299 + b[1] * 0.587 + b[2] * 0.114) - 255) * 0.1;\n out[o] = out[o + 1] = out[o + 2] = gray;\n } else {\n out[o] = 220;\n out[o + 1] = 38;\n out[o + 2] = 38;\n }\n out[o + 3] = 255;\n }\n }\n }\n const css = (img: RgbaImage): Size => ({ width: Math.round(img.width / scale), height: Math.round(img.height / scale) });\n const size = { figma: css(figma), code: css(code) };\n const tol = options.sizeTolerance ?? FIDELITY_DEFAULTS.sizeTolerance;\n const sizeMatches = Math.abs(size.figma.width - size.code.width) <= tol && Math.abs(size.figma.height - size.code.height) <= tol;\n const percent = total ? Math.round((different / total) * 10000) / 100 : 0;\n return {\n matches: sizeMatches && percent <= (options.maxPercent ?? FIDELITY_DEFAULTS.maxPercent),\n percent,\n differentPixels: different,\n totalPixels: total,\n size,\n sizeMatches,\n ...(out ? { diff: { width, height, data: out } } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------------------------\n// Report: what a check found, per component and variant. JSON, storable as is.\n\nexport type FidelityVariantStatus = 'matches' | 'differs' | 'skipped';\n\nexport interface FidelityVariantResult {\n /** Variant key, as the plugin stores it (\"Size=md, State=Default, Variant=primary\"). */\n key: string;\n status: FidelityVariantStatus;\n percent?: number | undefined;\n size?: { figma: Size; code: Size } | undefined;\n /** Skipped variants: why there is nothing to compare, in designer words. */\n reason?: string | undefined;\n}\n\nexport type FidelityComponentStatus = 'matches' | 'differs' | 'not-checked';\n\nexport interface FidelityComponentResult {\n component: string;\n status: FidelityComponentStatus;\n checked: number;\n differing: number;\n skipped: number;\n /** The variant that differs most (or matches least well). */\n worst?: { key: string; percent: number; size: { figma: Size; code: Size } } | undefined;\n /** Not checked at all: why. */\n reason?: string | undefined;\n variants: FidelityVariantResult[];\n}\n\nexport interface FidelityReport {\n version: 1;\n checkedAt: string;\n /** Figma file the sets were exported from. */\n file?: string | undefined;\n /** Commit the code images were made from. */\n reference: { sha: string; createdAt: string };\n options: { scale: number; threshold: number; radius: number; maxPercent: number; sizeTolerance: number };\n components: FidelityComponentResult[];\n summary: { components: number; matches: number; differs: number; notChecked: number; variantsChecked: number; variantsSkipped: number };\n}\n\n/** Rolls variant results up into one component result. */\nexport function summarizeComponent(component: string, variants: FidelityVariantResult[], reason?: string): FidelityComponentResult {\n const compared = variants.filter((v) => v.status !== 'skipped');\n const differing = compared.filter((v) => v.status === 'differs');\n const rank = (v: FidelityVariantResult) => (v.status === 'differs' ? 1000 : 0) + (v.percent ?? 0) + (v.size && !sameSize(v.size) ? 500 : 0);\n const worst = [...compared].sort((a, b) => rank(b) - rank(a))[0];\n return {\n component,\n status: compared.length === 0 ? 'not-checked' : differing.length ? 'differs' : 'matches',\n checked: compared.length,\n differing: differing.length,\n skipped: variants.length - compared.length,\n ...(worst && worst.size ? { worst: { key: worst.key, percent: worst.percent ?? 0, size: worst.size } } : {}),\n ...(compared.length === 0 ? { reason: reason ?? variants.find((v) => v.reason)?.reason } : {}),\n variants,\n };\n}\n\nconst sameSize = (s: { figma: Size; code: Size }) => s.figma.width === s.code.width && s.figma.height === s.code.height;\n\nexport function buildFidelityReport(input: {\n components: FidelityComponentResult[];\n reference: { sha: string; createdAt: string };\n options?: CompareOptions;\n file?: string;\n now?: Date;\n}): FidelityReport {\n const o = input.options ?? {};\n const scale = o.scale ?? FIDELITY_DEFAULTS.scale;\n const c = input.components;\n return {\n version: 1,\n checkedAt: (input.now ?? new Date()).toISOString(),\n ...(input.file ? { file: input.file } : {}),\n reference: input.reference,\n options: {\n scale,\n threshold: o.threshold ?? FIDELITY_DEFAULTS.threshold,\n radius: Math.round(o.radius ?? scale),\n maxPercent: o.maxPercent ?? FIDELITY_DEFAULTS.maxPercent,\n sizeTolerance: o.sizeTolerance ?? FIDELITY_DEFAULTS.sizeTolerance,\n },\n components: c,\n summary: {\n components: c.length,\n matches: c.filter((x) => x.status === 'matches').length,\n differs: c.filter((x) => x.status === 'differs').length,\n notChecked: c.filter((x) => x.status === 'not-checked').length,\n variantsChecked: c.reduce((n, x) => n + x.checked, 0),\n variantsSkipped: c.reduce((n, x) => n + x.skipped, 0),\n },\n };\n}\n\nconst fmtPercent = (p: number) => (p >= 10 ? `${Math.round(p)}%` : p >= 1 ? `${Math.round(p * 10) / 10}%` : p > 0 ? 'under 1%' : '0%');\nconst fmtSize = (s: Size) => `${s.width}x${s.height}`;\n\n/** One variant's verdict: \"Matches the code\" or \"Differs from the code: 12% of pixels, size 120x40 vs 118x40\". */\nexport function fidelityVerdict(v: Pick<FidelityVariantResult, 'status' | 'percent' | 'size' | 'reason'>): string {\n if (v.status === 'skipped') return `Not compared: ${v.reason ?? 'no image of the code'}`;\n if (v.status === 'matches') return 'Matches the code';\n const parts = [`${fmtPercent(v.percent ?? 0)} of pixels`];\n if (v.size && !sameSize(v.size)) parts.push(`size ${fmtSize(v.size.figma)} vs ${fmtSize(v.size.code)}`);\n return `Differs from the code: ${parts.join(', ')}`;\n}\n\n/** One component's line, from its worst variant. */\nexport function fidelityComponentLine(c: FidelityComponentResult): string {\n if (c.status === 'not-checked') return `Not compared: ${c.reason ?? 'no image of the code'}`;\n if (c.status === 'matches') return c.checked === 1 ? 'Matches the code' : `Matches the code (${c.checked} variants)`;\n const w = c.worst!;\n const head = fidelityVerdict({ status: 'differs', percent: w.percent, size: w.size });\n return c.checked > 1 ? `${head} (${c.differing} of ${c.checked} variants)` : head;\n}\n","// Code images for the fidelity check: which code render matches each generated Figma variant, and where the images\n// live. The generator (component-specs.ts) draws one Figma variant per axis combination; this module turns that same\n// spec back into props, content and a pseudo state, so the hidden Storybook story \"Internal/Figma reference\" renders\n// what the Figma variant should look like (same texts, icons and width). A variant that cannot be rendered the same\n// way is skipped with a reason, never guessed.\n//\n// Images are made on main by .github/workflows/figma-references.yml (bridge figma-references) and published to the\n// `bridge-visual` branch, the one Visual impact already publishes to, under figma-references/: manifest.json plus one\n// PNG per variant. The plugin reads them through the GitHub contents API with the token it already has.\n\nimport { variantKeyOf, type ComponentSpec, type ComponentSpecsFile, type SpecExample, type SpecPart, type SpecVariant } from './component-spec';\n\nexport const FIGMA_REFERENCES_BRANCH = 'bridge-visual';\nexport const FIGMA_REFERENCES_DIR = 'figma-references';\nexport const FIGMA_REFERENCES_MANIFEST = `${FIGMA_REFERENCES_DIR}/manifest.json`;\n/** Story id of packages/react/src/stories/FigmaReference.stories.tsx. */\nexport const FIGMA_REFERENCE_STORY = 'internal-figma-reference--variant';\n/** Width token of a block-level root in Figma (the plugin draws fill roots at this width: FILL_WIDTH_TOKEN). */\nexport const FIGMA_FILL_WIDTH_TOKEN = 'size.80';\n\nexport type ReferencePseudo = 'hover' | 'active' | 'focus-visible';\n\n/** What the reference story renders for one variant. JSON, passed to the story as a string arg. */\nexport interface ReferenceRender {\n /** Export name of the component (\"Button\", \"Card\"). */\n component: string;\n /** Props from the variant axes and the default property values (\"variant\": \"primary\", \"disabled\": true). */\n props: Record<string, unknown>;\n /** Text children (the Label property) of a simple component. */\n text?: string | undefined;\n /** Compound parts, in order: export name and text (\"CardHeader\", \"Header\"). */\n parts?: { component: string; text: string }[] | undefined;\n /** Icon props -> Lucide icon name (\"icon\": \"Pencil\"). */\n icons?: Record<string, string> | undefined;\n /** Hover, pressed or focus, forced with the pseudo-states addon classes. */\n pseudo?: ReferencePseudo | undefined;\n /** Width token path of the frame the component sits in, for roots that fill their container. */\n width?: string | undefined;\n /**\n * Children from the code example the set was drawn with (a table's rows, a form's fields): texts and design system\n * elements with their props, icons by name. Replaces `text` and `parts`.\n */\n children?: (string | SpecExample)[] | undefined;\n}\n\nexport type ReferencePlan = { ok: true; render: ReferenceRender } | { ok: false; reason: string };\n\nconst STATE_PSEUDO: Record<string, ReferencePseudo | 'rest' | 'disabled'> = {\n default: 'rest',\n rest: 'rest',\n enabled: 'rest',\n hover: 'hover',\n hovered: 'hover',\n pressed: 'active',\n active: 'active',\n focus: 'focus-visible',\n focused: 'focus-visible',\n 'focus visible': 'focus-visible',\n disabled: 'disabled',\n};\n\nconst iconName = (component: string) => component.replace(/^Icon\\//, '');\nconst exportName = (name: string) => name.replace(/[^A-Za-z0-9]+/g, '');\n\n/** How to render one generated variant from code, or why it cannot be compared. */\nexport function planReference(spec: ComponentSpec, variant: SpecVariant, file?: Pick<ComponentSpecsFile, 'slots'>): ReferencePlan {\n // A popup drawn open: the code image shows the component closed, so there is nothing to compare it with.\n if (spec.view === 'popup') return { ok: false, reason: 'drawn open in Figma; the code image shows it closed' };\n const props: Record<string, unknown> = { ...(spec.fixed ?? {}) };\n let pseudo: ReferencePseudo | undefined;\n for (const axis of spec.axes) {\n const value = variant.props[axis.name];\n if (value === undefined) return { ok: false, reason: `the variant has no ${axis.name} value` };\n if (axis.prop) {\n props[axis.prop] = value === 'true' ? true : value === 'false' ? false : value;\n continue;\n }\n // The Checked axis the generator draws from Base UI's checked state: the checked and indeterminate props.\n if (axis.name === 'Checked') {\n props.checked = value === 'true';\n if (value === 'mixed') props.indeterminate = true;\n continue;\n }\n if (axis.name.toLowerCase() !== 'state') return { ok: false, reason: `${axis.name} has no matching option in code` };\n const s = STATE_PSEUDO[value.toLowerCase()];\n if (!s) return { ok: false, reason: `the ${value} state has no code equivalent to render` };\n if (s === 'disabled') props.disabled = true;\n else if (s !== 'rest') pseudo = s;\n }\n\n const root = spec.parts.find((p) => !p.parent);\n if (!root) return { ok: false, reason: 'the spec has no root layer' };\n const children = (id: string) => spec.parts.filter((p) => p.parent === id);\n const textOf = (part: SpecPart): string | { reason: string } => {\n const swapTo = variant.slots?.[part.id] ?? part.swap?.default;\n if (part.swap && swapTo) {\n const slot = file?.slots?.find((s) => s.name === swapTo);\n if (!slot) return { reason: `${swapTo} is not in the specs` };\n if (slot.kind !== 'text' || !slot.text) return { reason: `Figma shows a placeholder (${swapTo}) that code has no example of` };\n return slot.text.default;\n }\n const prop = spec.properties.find((p) => p.name === part.text && p.type === 'TEXT');\n return typeof prop?.default === 'string' ? prop.default : part.name;\n };\n\n let text: string | undefined;\n const icons: Record<string, string> = {};\n for (const prop of spec.properties) {\n if (prop.type === 'TEXT') {\n // Optional content hidden by default (an input's prefix, a description): not passed, as Figma does not show it.\n const hidden = spec.properties.some((b) => b.type === 'BOOLEAN' && b.prop === prop.prop && b.default === false);\n if (hidden && prop.prop) continue;\n if (prop.prop === 'children') text = String(prop.default);\n else if (prop.prop) props[prop.prop] = String(prop.default);\n continue;\n }\n // BOOLEAN: an optional icon shown by default gets its icon below; any other default-on flag is a prop, unless the\n // content it shows is already passed (a description's text, an example's token name).\n const iconPart = spec.parts.find((p) => p.kind === 'icon' && p.visible === prop.name);\n if (prop.default === true && !iconPart && prop.prop && props[prop.prop] === undefined && spec.example?.p?.[prop.prop] === undefined) props[prop.prop] = true;\n }\n\n for (const part of spec.parts) {\n if (part.kind !== 'icon' || !part.swap) continue;\n const shown = part.visible ? spec.properties.find((p) => p.name === part.visible)?.default === true : true;\n if (!shown) continue;\n if (!part.swap.prop) return { ok: false, reason: `the ${part.name} icon has no matching option in code` };\n icons[part.swap.prop] = iconName(variant.slots?.[part.id] ?? part.swap.default);\n }\n\n // Texts that no prop carries: an input's placeholder, or a compound component's parts (CardHeader...).\n let parts: { component: string; text: string }[] | undefined;\n const loose = spec.properties.filter((p) => p.type === 'TEXT' && !p.prop);\n const frames = children(root.id).filter((p) => p.kind === 'frame');\n // Compound parts are frames named like their text (CardHeader's \"Header\") or holding a slot, not a field's box.\n const compound = text === undefined && frames.length > 0 && frames.every((f) => spec.parts.some((p) => p.parent === f.id && p.kind === 'text' && (p.swap || p.text === f.name)));\n if (compound) {\n parts = [];\n for (const f of frames) {\n const t = spec.parts.find((p) => p.parent === f.id && p.kind === 'text')!;\n const value = textOf(t);\n if (typeof value !== 'string') return { ok: false, reason: value.reason };\n parts.push({ component: `${exportName(spec.name)}${exportName(f.name)}`, text: value });\n }\n }\n for (const p of loose) {\n // A value display Base UI writes from the component's value (a progress percentage): code writes it too.\n if (p.name === 'Value') continue;\n const part = spec.parts.find((x) => x.text === p.name);\n if (compound && part && part.parent !== root.id) continue;\n if (part && /placeholder$/.test(part.id)) {\n props.placeholder = String(p.default);\n continue;\n }\n return { ok: false, reason: `the ${p.name} text has no matching option in code` };\n }\n\n // The code example the content came from: its props (the variant's own win) and children.\n const example = spec.example;\n const exampleChildren = example?.children?.length ? example.children : undefined;\n return {\n ok: true,\n render: {\n component: exportName(spec.view || spec.fixed || example ? (example?.c ?? spec.component ?? spec.name) : spec.name),\n props: { ...(example?.p ?? {}), ...props },\n ...(exampleChildren ? { children: exampleChildren } : {}),\n ...(text !== undefined && !exampleChildren ? { text } : {}),\n ...(parts && !exampleChildren ? { parts } : {}),\n ...(Object.keys(icons).length ? { icons } : {}),\n ...(pseudo ? { pseudo } : {}),\n ...(root.fill ? { width: FIGMA_FILL_WIDTH_TOKEN } : {}),\n },\n };\n}\n\n/** File name of a variant's image, stable and file safe: \"button/size-md__state-default__variant-primary.png\". */\nexport function referenceImagePath(component: string, key: string): string {\n const slug = (s: string) => s.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');\n const file = key\n .split(',')\n .map((kv) => slug(kv))\n .filter(Boolean)\n .join('__');\n return `${slug(component)}/${file || 'default'}.png`;\n}\n\nexport type FigmaReferenceEntry = { file: string; width: number; height: number } | { skipped: string };\n\nexport interface FigmaReferenceManifest {\n version: 1;\n tool: '@bridge-ds/visual';\n createdAt: string;\n /** Commit of the code the images were made from. */\n sha: string;\n /** Device pixels per CSS pixel, the scale the plugin exports Figma variants at. */\n scale: number;\n mode: { brand: string; theme: string; density: string };\n storyId: string;\n components: Record<string, { specHash: string; variants: Record<string, FigmaReferenceEntry> }>;\n}\n\n/** Every variant of every spec with its render plan (the capture's to-do list). */\nexport function planReferences(file: ComponentSpecsFile): { component: string; specHash: string; key: string; plan: ReferencePlan }[] {\n return file.components.flatMap((spec) =>\n spec.variants.map((v) => ({ component: spec.name, specHash: spec.hash, key: variantKeyOf(v.props), plan: planReference(spec, v, file) })),\n );\n}\n","// Update a branch from main (\"bring in the latest library\"), shared by Bridge Studio, the MCP server and the CLI.\n// Reads how far a branch is behind and what both sides touched since they parted; when nothing conflicts, GitHub's\n// update-branch; when only token files conflict, a merge commit with the person's token choices (\"keep mine\" or\n// \"use main's\", core token-merge); anything in code stays with a developer. One implementation over the core\n// GitHub client: Studio passes its own client (studioClient), the MCP server and the CLI theirs.\nimport { loadConfig, DEFAULT_TOKEN_PATHS, type BridgeConfig } from './config';\nimport type { GitHubClient, TreeEntry } from './github-client';\nimport { buildTokenSet, layoutOptions, type LayoutOptions, type TokenSet } from './token-set';\nimport { parseContrastChecks, type ContrastPair } from './wcag';\nimport { applyTokenMerge, choiceFor, planTokenMerge, type MergeChoices, type TokenMergeConflict, type TokenMergeInput, type TokenMergePlan } from './token-merge';\n\nconst plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;\n\n/** A file of a compare (GET /repos/{o}/{r}/compare/{base}...{head}). */\nexport interface CompareFile {\n filename: string;\n status: string;\n previous_filename?: string | undefined;\n sha?: string | null | undefined;\n}\n\n/** Every path a compare file names: a renamed file counts under its old name too. */\nconst names = (files: CompareFile[]) => files.flatMap((f) => (f.previous_filename ? [f.filename, f.previous_filename] : [f.filename]));\n\n/** Files both the branch and main changed since they parted, split into token files and the rest (code). */\nexport function overlap(changeFiles: CompareFile[], libraryFiles: CompareFile[], isTokenFile: (path: string) => boolean): { tokenFiles: string[]; codeFiles: string[] } {\n const lib = new Set(names(libraryFiles));\n const both = [...new Set(names(changeFiles).filter((f) => lib.has(f)))].sort();\n return { tokenFiles: both.filter(isTokenFile), codeFiles: both.filter((f) => !isTokenFile(f)) };\n}\n\n/** GitHub lists at most 300 files per compare: past that, Bridge cannot know what both sides touched. */\nexport const COMPARE_FILE_LIMIT = 300;\n\nexport type ConflictRoute = { kind: 'tokens'; files: string[] } | { kind: 'code'; alsoTokens: boolean; files: string[] };\n\n/**\n * Who resolves the conflict. Only token files on both sides: the designer, in Bridge. Any code file on both sides, a\n * file list GitHub cut short, or no shared file at all (GitHub saw a conflict Bridge cannot explain): a developer.\n */\nexport function conflictRoute(o: { tokenFiles: string[]; codeFiles: string[] }, opts: { truncated?: boolean } = {}): ConflictRoute {\n if (opts.truncated || (!o.tokenFiles.length && !o.codeFiles.length)) return { kind: 'code', alsoTokens: false, files: [] };\n if (o.codeFiles.length) return { kind: 'code', alsoTokens: o.tokenFiles.length > 0, files: o.codeFiles };\n return { kind: 'tokens', files: o.tokenFiles };\n}\n\n/** A rule from GET /repos/{o}/{r}/rules/branches/{branch}. */\nexport interface BranchRuleLike {\n type: string;\n parameters?: { dismiss_stale_reviews_on_push?: boolean } | null;\n}\n\n/**\n * Whether GitHub dismisses approvals when new commits arrive, from the rules that apply to the library branch. True\n * or false when a pull request rule says so; null when no rule says (classic branch protection is not readable\n * without admin rights).\n */\nexport function dismissStaleFrom(rules: BranchRuleLike[] | null | undefined): boolean | null {\n const pr = (rules ?? []).filter((r) => r.type === 'pull_request');\n if (!pr.length) return null;\n return pr.some((r) => r.parameters?.dismiss_stale_reviews_on_push === true);\n}\n\n/** The commit message of the resolution, so History and the branch say what the person chose. */\nexport function resolutionMessage(input: { library: string; conflicts: TokenMergeConflict[]; choices: MergeChoices; who?: string | null | undefined }): string {\n const lines = input.conflicts.map((c) => `- ${c.path} (${c.file}): ${choiceFor(c, input.choices) === 'theirs' ? `used the ${input.library} value` : 'kept this change'}`);\n const title = input.conflicts.length ? `Bring in the latest ${input.library} and resolve ${plural(input.conflicts.length, 'token conflict')}` : `Bring in the latest ${input.library}`;\n const by = input.who ? `\\n\\nResolved in Bridge by @${input.who.replace(/^@/, '')}.` : '\\n\\nResolved in Bridge.';\n return `${title}${lines.length ? `\\n\\n${lines.join('\\n')}` : ''}${by}`;\n}\n\nexport type LibraryState = 'current' | 'behind' | 'conflict' | 'unknown';\n\nexport interface Freshness {\n state: LibraryState;\n /** Library updates (commits on the library branch) since the change started; null when not read. */\n behindBy: number | null;\n /** The commit the change and the library share. */\n mergeBase: string | null;\n}\n\n/**\n * How the change stands against the latest library. A conflict (mergeable false) wins: GitHub cannot combine them.\n * Otherwise it is behind when the library has commits the change has not. A shipped or closed change has nothing to\n * bring in. A compare that could not be read says unknown, never \"up to date\".\n */\nexport function freshness<C extends { behind_by?: number | undefined; merge_base_commit?: { sha: string } | null | undefined }>(input: { compare: C | null | undefined; mergeable: boolean | null | undefined; open: boolean }): Freshness {\n const behindBy = typeof input.compare?.behind_by === 'number' ? input.compare.behind_by : null;\n const mergeBase = input.compare?.merge_base_commit?.sha ?? null;\n if (!input.open) return { state: 'current', behindBy, mergeBase };\n if (input.mergeable === false) return { state: 'conflict', behindBy, mergeBase };\n if (behindBy === null) return { state: 'unknown', behindBy, mergeBase };\n return { state: behindBy > 0 ? 'behind' : 'current', behindBy, mergeBase };\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// Reads and writes over the core GitHub client\n\n/** The compare of main and a branch head, in the shape the conflict reader needs (client.compareDetailed). */\nexport interface LibraryCompare {\n mergeBase: string | null;\n baseSha: string | null;\n baseTree: string | null;\n files: CompareFile[];\n}\n\nexport interface LibraryConflicts {\n route: ConflictRoute;\n /** Present for a pure token-file conflict. */\n tokens?: {\n root: string;\n plan: TokenMergePlan;\n input: TokenMergeInput;\n sets: { base: TokenSet; mine: TokenSet; theirs: TokenSet };\n /** Every token file of each side, relative to the tokens root. */\n mineFiles: Record<string, string>;\n theirsFiles: Record<string, string>;\n pairs: ContrastPair[];\n options: LayoutOptions;\n };\n /** What the commit needs: main's tip and its tree, the branch head tree and its own files. */\n write?: { mainSha: string; mainTree: string; headSha: string; headTree: Map<string, TreeEntry>; changeFiles: CompareFile[] };\n}\n\nconst withoutRoot = (root: string, p: string) => (root && p.startsWith(`${root}/`) ? p.slice(root.length + 1) : p);\n\nasync function treeAt(gh: GitHubClient, sha: string): Promise<Map<string, TreeEntry>> {\n const t = await gh.getTree(await gh.getCommitTree(sha));\n if (t.truncated) throw new Error('This repository is too big for Bridge to read in one go. A developer resolves the conflict on GitHub.');\n return new Map(t.entries.filter((e) => e.type === 'blob').map((e) => [e.path, e]));\n}\n\nasync function textAt(gh: GitHubClient, sha: string, path: string): Promise<string> {\n return (await gh.readFile(path, sha)) ?? '';\n}\n\nasync function tokenFilesAt(gh: GitHubClient, sha: string, root: string, tree: Map<string, TreeEntry>): Promise<Record<string, string>> {\n const prefix = root ? `${root}/` : '';\n const paths = [...tree.keys()].filter((p) => p.startsWith(prefix) && p.endsWith('.tokens.json'));\n return Object.fromEntries(await Promise.all(paths.map(async (p) => [withoutRoot(root, p), await textAt(gh, sha, p)] as const)));\n}\n\nasync function configAt(gh: GitHubClient, sha: string, tree: Map<string, TreeEntry>): Promise<BridgeConfig | null> {\n if (!tree.has('bridge.config.json')) return null;\n try {\n return loadConfig(await textAt(gh, sha, 'bridge.config.json'));\n } catch {\n return null;\n }\n}\n\n/**\n * What conflicts and who resolves it. Reads the files main changed since the branch started (one compare), then, for\n * a pure token-file conflict, the token files at the shared start, in the branch and in main. `tokensRoot` is the\n * best guess before the config is read (Studio: its site config); `contrastFallback` the contrast checks to use when\n * main has none.\n */\nexport async function readLibraryConflicts(\n gh: GitHubClient,\n compare: LibraryCompare,\n headSha: string,\n opts: { tokensRoot?: string | undefined; contrastFallback?: string | undefined } = {},\n): Promise<LibraryConflicts> {\n const { mergeBase, baseSha: mainSha, baseTree: mainTree } = compare;\n const changeFiles = compare.files;\n if (!mergeBase || !mainSha || !mainTree) return { route: conflictRoute({ tokenFiles: [], codeFiles: [] }) };\n const library = (await gh.compareDetailed(mergeBase, mainSha)).files;\n const truncated = changeFiles.length >= COMPARE_FILE_LIMIT || library.length >= COMPARE_FILE_LIMIT;\n // The tokens root guess first: the config of main confirms it before anything is written.\n const guess = opts.tokensRoot ?? DEFAULT_TOKEN_PATHS.root;\n const route = conflictRoute(\n overlap(changeFiles, library, (p) => p.endsWith('.tokens.json') && p.startsWith(`${guess}/`)),\n { truncated },\n );\n if (route.kind !== 'tokens') return { route };\n\n const [baseTree, headTree, theirsTree] = await Promise.all([treeAt(gh, mergeBase), treeAt(gh, headSha), treeAt(gh, mainSha)]);\n const config = (await configAt(gh, mainSha, theirsTree)) ?? (await configAt(gh, mergeBase, baseTree));\n const root = config?.tokens.root ?? guess;\n const options = config ? layoutOptions(config) : {};\n const checksPath = `${root}/${config?.tokens.contrastChecks ?? DEFAULT_TOKEN_PATHS.contrastChecks}`;\n const [baseFiles, mineFiles, theirsFiles, checks] = await Promise.all([\n tokenFilesAt(gh, mergeBase, root, baseTree),\n tokenFilesAt(gh, headSha, root, headTree),\n tokenFilesAt(gh, mainSha, root, theirsTree),\n theirsTree.has(checksPath) ? textAt(gh, mainSha, checksPath) : Promise.resolve(''),\n ]);\n const input: TokenMergeInput = { base: baseFiles, mine: mineFiles, theirs: theirsFiles, files: route.files.map((f) => withoutRoot(root, f)) };\n return {\n route,\n tokens: {\n root,\n plan: planTokenMerge(input),\n input,\n sets: { base: buildTokenSet(baseFiles, options), mine: buildTokenSet(mineFiles, options), theirs: buildTokenSet(theirsFiles, options) },\n mineFiles,\n theirsFiles,\n pairs: parseContrastChecks(checks || opts.contrastFallback),\n options,\n },\n write: { mainSha, mainTree, headSha, headTree, changeFiles },\n };\n}\n\n/**\n * Every token file once resolved, relative to the tokens root: main's files, the branch's own token files where only\n * the branch touched them, and the merged files where both did.\n */\nexport function resolvedTokenFiles(data: LibraryConflicts, choices: MergeChoices): { all: Record<string, string>; merged: Record<string, string | null> } {\n const t = data.tokens!;\n const merged = applyTokenMerge(t.input, choices).files;\n const all: Record<string, string> = { ...t.theirsFiles };\n for (const f of data.write!.changeFiles) {\n for (const p of [f.previous_filename, f.filename]) {\n if (!p || !p.endsWith('.tokens.json') || !p.startsWith(`${t.root}/`)) continue;\n const rel = withoutRoot(t.root, p);\n if (rel in merged) continue;\n if (t.mineFiles[rel] === undefined) delete all[rel];\n else all[rel] = t.mineFiles[rel]!;\n }\n }\n for (const [rel, text] of Object.entries(merged)) {\n if (text === null) delete all[rel];\n else all[rel] = text;\n }\n return { all, merged };\n}\n\n/**\n * Commits the resolution to the branch: a merge commit of main and the branch, whose tree is main plus the branch's\n * own files plus the merged token files. Fast-forward only: when the branch moved meanwhile, GitHub refuses and\n * nothing is lost.\n */\nexport async function commitLibraryResolution(\n gh: GitHubClient,\n pull: { head: { ref: string; sha: string }; base: { ref: string } },\n data: LibraryConflicts,\n choices: MergeChoices,\n who: string | null | undefined,\n): Promise<string> {\n const t = data.tokens;\n const w = data.write;\n if (!t || !w) throw new Error('Only a token conflict can be resolved in Bridge. A developer resolves code conflicts on GitHub.');\n if (w.headSha !== pull.head.sha) throw new Error('The branch moved while you were choosing. Read it again and resolve again.');\n const { merged } = resolvedTokenFiles(data, choices);\n const shared = new Set(data.route.files);\n type Entry = { path: string; mode: string; sha: string | null } | { path: string; mode: string; content: string };\n const tree: Entry[] = [];\n for (const f of w.changeFiles) {\n if (shared.has(f.filename)) continue;\n if (f.previous_filename && !shared.has(f.previous_filename)) tree.push({ path: f.previous_filename, mode: '100644', sha: null });\n if (f.status === 'removed') {\n tree.push({ path: f.filename, mode: '100644', sha: null });\n continue;\n }\n const e = w.headTree.get(f.filename);\n if (!e) throw new Error(`Bridge could not read ${f.filename} in the branch. Read it again and try again.`);\n tree.push({ path: e.path, mode: e.mode, sha: e.sha });\n }\n for (const [rel, text] of Object.entries(merged)) {\n const path = t.root ? `${t.root}/${rel}` : rel;\n const mode = w.headTree.get(path)?.mode ?? '100644';\n tree.push(text === null ? { path, mode, sha: null } : { path, mode, content: text });\n }\n const newTree = await gh.createTreeEntries(w.mainTree, tree);\n const message = resolutionMessage({ library: pull.base.ref, conflicts: t.plan.conflicts, choices, who });\n const commit = await gh.createCommit(message, newTree, [w.headSha, w.mainSha]);\n await gh.updateBranch(pull.head.ref, commit);\n return commit;\n}\n","// The writes behind the actions on a branch in review, shared by Bridge Studio (scripts/reviews.ts), the MCP server\n// and the CLI: merge, merge as owner override (reason posted first, marked \"not merged\" when GitHub refuses), review,\n// close and reopen. The rules that decide whether they are allowed live in review-gate.ts; these only write, through\n// the core GitHub client, so every surface sends GitHub the same requests.\nimport type { GitHubClient, Review } from './github-client';\nimport { OVERRIDE_HEADING, overrideComment, overrideRefusedComment, type MergeMethod, type MissingApproval } from './review-gate';\n\n/** Merges a branch at the head the person saw (GitHub refuses when it moved meanwhile). Studio's Merge button: squash. */\nexport async function mergeOnGitHub(gh: GitHubClient, input: { number: number; headSha: string; method?: MergeMethod | undefined }): Promise<{ sha: string }> {\n const r = await gh.mergePullRequest(input.number, { method: input.method ?? 'squash', sha: input.headSha });\n return { sha: r.sha };\n}\n\n/** Where an owner override stopped: GitHub refused the reason comment (nothing merged), or the merge itself. */\nexport class OverrideMergeError extends Error {\n constructor(\n readonly stage: 'comment' | 'merge',\n message: string,\n readonly cause?: unknown,\n readonly commentUrl?: string | undefined,\n ) {\n super(message);\n this.name = 'OverrideMergeError';\n }\n}\n\n/**\n * Merge as owner override: posts the reason on the branch first (the audit trail History reads back), then merges\n * with the first merge method the repository allows. When GitHub refuses the merge, the comment is edited to say\n * \"Merge refused by GitHub ... Not merged\", so the trail never claims a merge that did not happen. The caller checks\n * the gate first (mergeGate: overridable) and the reason (overrideReasonProblem).\n */\nexport async function overrideMergeOnGitHub(\n gh: GitHubClient,\n input: { number: number; headSha: string; login: string; reason: string; missing: MissingApproval[]; method: MergeMethod },\n): Promise<{ sha: string; commentUrl: string; comment: string }> {\n const body = overrideComment(input.login, input.reason, input.missing);\n let comment: { id: number; url: string };\n try {\n comment = await gh.createIssueComment(input.number, body);\n } catch (err) {\n throw new OverrideMergeError('comment', `GitHub did not take the comment, so nothing merged: ${(err as Error).message}`, err);\n }\n try {\n const r = await gh.mergePullRequest(input.number, { method: input.method, sha: input.headSha, commitMessage: body.replace(OVERRIDE_HEADING, '').trim() });\n return { sha: r.sha, commentUrl: comment.url, comment: body };\n } catch (err) {\n const msg = (err as Error).message.trim().replace(/[.\\s]+$/, '');\n await gh.updateIssueComment(comment.id, overrideRefusedComment(body, msg)).catch(() => undefined);\n throw new OverrideMergeError(\n 'merge',\n `GitHub refused to merge it: ${msg}. Your reason stays on the branch, marked not merged. The protection of main may need an approving review or an admin bypass.`,\n err,\n comment.url,\n );\n }\n}\n\nexport type ReviewEvent = 'APPROVE' | 'REQUEST_CHANGES' | 'COMMENT';\n\n/** Approve, request changes or comment, on the head the reviewer saw. Changes and comments need a text. */\nexport async function reviewOnGitHub(gh: GitHubClient, input: { number: number; event: ReviewEvent; body?: string | undefined; headSha?: string | undefined }): Promise<Review> {\n const text = input.body?.trim() ?? '';\n if (input.event === 'REQUEST_CHANGES' && !text) throw new Error('Add a comment that says what to change.');\n if (input.event === 'COMMENT' && !text) throw new Error('Write a comment first.');\n return gh.submitReview(input.number, { event: input.event, body: text || undefined, commitId: input.headSha });\n}\n\n/** A comment on the branch's conversation. */\nexport async function commentOnGitHub(gh: GitHubClient, n: number, body: string): Promise<{ id: number; url: string }> {\n const text = body.trim();\n if (!text) throw new Error('Write the comment first.');\n return gh.createIssueComment(n, text);\n}\n\n/**\n * \"Ask someone else to review\": requests the review from `others` (core reviewersToAsk) and takes the viewer off the\n * requested reviewers when GitHub had them on it. Throws how to fix it when nobody else can.\n */\nexport async function askOthersToReviewOnGitHub(gh: GitHubClient, input: { number: number; others: string[]; viewer?: string | null | undefined; viewerRequested?: boolean | undefined }): Promise<string[]> {\n if (!input.others.length) throw new Error('Nobody else can give the missing approval. Review it, or ask an owner in Settings to add a reviewer.');\n await gh.requestReviewers(input.number, input.others);\n if (input.viewer && input.viewerRequested) await gh.removeRequestedReviewers(input.number, [input.viewer]).catch(() => undefined);\n return input.others;\n}\n\n/** Closes a branch without merging it. Its work stays on GitHub and it can be reopened. */\nexport async function closeOnGitHub(gh: GitHubClient, n: number): Promise<void> {\n await gh.updatePullRequest(n, { state: 'closed' });\n}\n\n/** Reopens a closed branch (GitHub refuses when its branch was deleted). */\nexport async function reopenOnGitHub(gh: GitHubClient, n: number): Promise<void> {\n await gh.updatePullRequest(n, { state: 'open' });\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// Adding edits to a branch already in review\n\nconst sameLogin = (a: string | null | undefined, b: string | null | undefined) => Boolean(a && b && a.toLowerCase().replace(/^@/, '') === b.toLowerCase().replace(/^@/, ''));\n\n/** Only the author or someone with write access to the repository adds to a branch. */\nexport function canAddTo(p: { user: { login: string } | null }, viewer: string | null | undefined, write: boolean): boolean {\n if (!viewer) return false;\n return write || sameLogin(p.user?.login, viewer);\n}\n\n/** The comment posted on the branch, so reviewers see what was added and from where. */\nexport function addedComment(paths: string[], viewer: string | null | undefined, from = 'the Bridge token editor'): string {\n const lines = paths.slice(0, 20).map((p) => `- \\`${p}\\``);\n if (paths.length > 20) lines.push(`- and ${paths.length - 20} more`);\n return `${viewer ? `@${viewer} added` : 'Added'} token edits from ${from}:\\n\\n${lines.join('\\n')}`;\n}\n","// \"Share with a product team\" on a branch, shared by Bridge Studio, the MCP server and the CLI: a product team installs the change in its own app before it ships, the\n// designer's release candidate. Everything comes from what the Preview packages workflow\n// (.github/workflows/preview-packages.yml) really does:\n// - every update to an open or draft change builds the library packages (previews.packages in bridge.config.json)\n// and posts the install command in its sticky comment (`<!-- bridge-branch-preview -->`), about two minutes\n// after the update, whether or not the checks pass;\n// - with pkg.pr.new, one snapshot per update, kept after the change ships or closes;\n// - without it (this repository today), tarballs on a `preview-pr-<n>` GitHub prerelease: only the latest update\n// is kept, and the \"Remove the preview prerelease\" job deletes it when the change ships or closes.\n// Nothing is published to the npm registry per change: there is no dist-tag, the command installs by URL.\nimport { readPreviewComment } from './previews';\n\n/** The dialog's explanation, in designer words. */\nexport const SHARE_EXPLAIN = 'Product teams can install this branch in their app before it is merged, and remove it any time.';\n\nexport type ChangeLifecycle = 'open' | 'draft' | 'merged' | 'closed';\ntype Source = 'pkg.pr.new' | 'release' | 'other';\n\nexport type ShareState =\n /** The command for the latest update is posted. */\n | { kind: 'ready'; command: string; source: Source }\n /** No command for the latest update yet. */\n | { kind: 'building' }\n /** The workflow posted for the latest update but could not publish. */\n | { kind: 'failed' }\n /** The change touches none of the preview packages: there is nothing to install. */\n | { kind: 'no-packages' }\n /** Shipped or closed. `stillWorks` from where the preview lived; null when no preview was ever posted. */\n | { kind: 'shipped' | 'closed'; stillWorks: boolean | null; command: string | null };\n\n/** `@bridge-ds/react` -> `packages/react/`, the folder the workflow builds it from (PACKAGE_DIRS). */\nexport const packageDir = (name: string): string => `packages/${name.replace(/^@[^/]+\\//, '')}/`;\n\n/** True when a changed file is inside one of the preview packages. */\nexport function touchesPackages(files: readonly string[], packages: readonly string[]): boolean {\n const dirs = packages.map(packageDir);\n return files.some((f) => dirs.some((d) => f.startsWith(d)));\n}\n\n/**\n * Whether a change offers sharing at all: never from a fork (the workflow cannot publish from one) or when the\n * repository has no preview packages configured.\n */\nexport const canShare = (x: { fromFork: boolean; packages: readonly string[] }): boolean => !x.fromFork && x.packages.length > 0;\n\n/**\n * Where the preview of a change stands, from its lifecycle, its changed files and the sticky preview comment. A\n * comment about an older update than the head means the new one is still being prepared: its command is never shown.\n */\nexport function shareState(x: { lifecycle: ChangeLifecycle; files: readonly string[]; packages: readonly string[]; comment: string | null | undefined; headSha: string }): ShareState {\n // Checked first: a change outside the packages never has anything to install, before or after it ships.\n if (!touchesPackages(x.files, x.packages)) return { kind: 'no-packages' };\n const c = readPreviewComment(x.comment);\n if (x.lifecycle === 'merged' || x.lifecycle === 'closed') {\n const kind = x.lifecycle === 'merged' ? 'shipped' : 'closed';\n if (!c || !c.command || c.source === 'none') return { kind, stillWorks: null, command: null };\n // pkg.pr.new keeps every snapshot; the prerelease is deleted when the change ships or closes.\n return { kind, stillWorks: c.source === 'pkg.pr.new' ? true : c.source === 'release' ? false : null, command: c.command };\n }\n if (!c) return { kind: 'building' };\n if (c.sha7 && !x.headSha.startsWith(c.sha7)) return { kind: 'building' };\n if (!c.command || c.source === 'none') return { kind: 'failed' };\n return { kind: 'ready', command: c.command, source: c.source };\n}\n\n/**\n * Whether the change page shows the action: always while the change is open or a draft (the dialog says why there is\n * nothing to install yet), and after it ships or closes only when a preview was posted that a team may have installed.\n */\nexport const showShare = (lifecycle: ChangeLifecycle, s: ShareState): boolean =>\n lifecycle === 'open' || lifecycle === 'draft' || ((s.kind === 'shipped' || s.kind === 'closed') && !!s.command);\n\n/** The dialog's description: the explanation while the change can still be tried, where it stands once finished. */\nexport const shareDescription = (s: ShareState): string =>\n s.kind === 'shipped' || s.kind === 'closed' ? (stateSentence(s) ?? SHARE_EXPLAIN) : SHARE_EXPLAIN;\n\n/** How a product goes back to the released packages. */\nexport const stableCommand = (packages: readonly string[]): string => `npm i ${packages.map((p) => `${p}@latest`).join(' ')}`;\n\n/** The one sentence the dialog shows under its explanation, in designer words. Null when the message says it all. */\nexport function stateSentence(s: ShareState): string | null {\n switch (s.kind) {\n case 'ready':\n return null;\n case 'building':\n return 'The preview version is being prepared. It is usually ready a couple of minutes after each update to the branch.';\n case 'failed':\n return 'The preview version could not be prepared for the latest update. Update the branch to try again, or ask a developer to run it again on GitHub.';\n case 'no-packages':\n return 'This branch does not touch the library tokens or components, so there is no preview version to install.';\n case 'shipped':\n return s.stillWorks === true\n ? 'This branch was merged. Its preview version still installs, and products get it with the next library release.'\n : s.stillWorks === false\n ? 'This branch was merged, so its preview version was removed. Products get it with the next library release.'\n : 'This branch was merged. Products get it with the next library release.';\n case 'closed':\n return s.stillWorks === true\n ? 'This branch was closed without merging. Its preview version still installs, but it will not reach the library.'\n : s.stillWorks === false\n ? 'This branch was closed without merging, so its preview version was removed.'\n : 'This branch was closed without merging.';\n }\n}\n\nexport interface ShareMessageInput {\n title: string;\n state: ShareState;\n packages: readonly string[];\n /** \"Try it in the product\": the admin preview with this change, when GitHub reports one. */\n tryUrl?: string | null | undefined;\n /** The change on GitHub, for the developer. */\n url: string;\n}\n\nexport interface ShareMessage {\n subject: string;\n body: string;\n}\n\nconst quote = (t: string) => `\"${t.trim().replace(/\"/g, \"'\")}\"`;\n\n/**\n * The ready-to-paste message for a developer of a product team: the change, the preview install command, where to\n * see it first, how long the preview lasts and how to go back. Plain text, for a chat or an email. Null when there is\n * nothing to install and nothing to undo (still building, failed, no packages, or never posted).\n */\nexport function shareMessage(x: ShareMessageInput): ShareMessage | null {\n const back = stableCommand(x.packages);\n const s = x.state;\n if (s.kind === 'ready') {\n const lasts =\n s.source === 'pkg.pr.new'\n ? 'This preview stays available. Each update to the change makes a new one: ask me for the latest command.'\n : 'This preview is replaced on each update to the change and removed when it ships or closes: ask me for the latest command if the install fails.';\n return {\n subject: `Try the design system change ${quote(x.title)} before it ships`,\n body: [\n 'Hi,',\n '',\n `Could you try the design system change ${quote(x.title)} in our product before it ships?`,\n ...(x.tryUrl ? ['', `See it in the demo product first: ${x.tryUrl}`] : []),\n '',\n 'Install the preview version in a staging branch (not production):',\n s.command,\n '',\n lasts,\n '',\n 'To go back to the stable version:',\n back,\n '',\n `Details for developers: ${x.url}`,\n ].join('\\n'),\n };\n }\n if ((s.kind === 'shipped' || s.kind === 'closed') && s.command) {\n const what = s.kind === 'shipped' ? `The design system change ${quote(x.title)} has shipped. You get it with the next library release.` : `The design system change ${quote(x.title)} was closed without shipping.`;\n const preview = s.stillWorks === false ? 'Its preview version was removed, so reinstalling it fails.' : s.stillWorks === true ? 'Its preview version still installs, but it is not the released version.' : '';\n return {\n subject: `Design system change ${quote(x.title)} ${s.kind === 'shipped' ? 'has shipped' : 'was closed'}`,\n body: ['Hi,', '', [what, preview].filter(Boolean).join(' '), '', 'If you installed its preview, go back to the stable version:', back, '', `Details for developers: ${x.url}`].join('\\n'),\n };\n }\n return null;\n}\n\n/** \"Open in email\": a mailto link with the subject and body. Nothing is sent by Studio. */\nexport const mailtoHref = (m: ShareMessage): string => `mailto:?subject=${encodeURIComponent(m.subject)}&body=${encodeURIComponent(m.body.replace(/\\r?\\n/g, '\\r\\n'))}`;\n","// \"Try it in the product\" on a branch, shared by Bridge Studio, the MCP server and the CLI: the product preview Vercel\n// built for the branch, opened with the Bridge toolbar (`?bridge=<number>`, apps/admin/src/bridge) on a given screen.\n// The URL is only one GitHub reported (Vercel commit status, deployment or bot comment), never the config template:\n// Vercel shortens long branch aliases, so a template URL can point nowhere.\nimport { resolveBranchPreviews, type BranchPreviewSources, type PreviewApps } from './previews';\n\nexport interface ProductScreen {\n label: string;\n route: string;\n tenant: string;\n theme: string;\n}\n\n/** The admin preview of a change, or null when GitHub reports none (or the build failed, or it comes from a fork). */\nexport function productPreview(apps: PreviewApps, ctx: { branch: string; pr: number; sha: string; fromFork?: boolean }, sources: BranchPreviewSources): string | null {\n if (!apps.admin || ctx.fromFork) return null;\n const admin = resolveBranchPreviews(apps, { branch: ctx.branch, pr: ctx.pr, sha: ctx.sha }, sources).find((p) => p.app === 'admin');\n if (!admin?.url || admin.source === 'template' || admin.state === 'failed') return null;\n return admin.url;\n}\n\n/**\n * The preview with the toolbar on, at that screen (shop and theme in the query, the hash route ra-core reads), else home.\n * Only http(s) previews: anything else (a javascript: or data: URL in a hostile comment) gives ''.\n */\nexport function tryInProductUrl(preview: string, pr: number, screen: ProductScreen | null): string {\n const url = new URL(preview);\n if (url.protocol !== 'https:' && url.protocol !== 'http:') return '';\n url.pathname = '/';\n url.search = '';\n url.searchParams.set('bridge', String(pr));\n if (screen) {\n url.searchParams.set('tenant', screen.tenant);\n url.searchParams.set('theme', screen.theme);\n }\n url.hash = screen ? screen.route : '';\n return url.href;\n}\n","// Try 2 to 4 token branches together, the reads and the rules shared by Bridge Studio, the MCP server and the CLI:\n// which branches can be combined (token files only: code would need a real combined build), each branch's own token\n// edits read from GitHub (its start against its current version, token-combine changeEdits), and where the\n// combination opens (the admin demo with the Bridge toolbar, `?bridge=101,118`). Nothing is written anywhere.\nimport type { GitHubClient } from './github-client';\nimport { changeEdits, encodePicks, type ChangeEdits, type CombinePicks, type CombineSource } from './token-combine';\n\nexport const MIN_TOGETHER = 2;\n\nexport const MAX_TOGETHER = 4;\n\n/**\n * Whether a change only edits tokens: token files under the tokens root, the contrast gate and release notes\n * (changesets). Anything else is code. No file read yet (or none) is not a token change.\n */\nexport function onlyTokens(files: string[], tokensRoot: string): boolean {\n const root = `${tokensRoot.replace(/^\\/+|\\/+$/g, '')}/`;\n return files.length > 0 && files.every((f) => (f.startsWith(root) && f.endsWith('.tokens.json')) || /contrast\\.checks\\.json$/.test(f) || f.startsWith('.changeset/'));\n}\n\n/** Token files a change edits, relative to the tokens root. */\nexport function tokenFilesOf(files: string[], tokensRoot: string): string[] {\n const root = `${tokensRoot.replace(/^\\/+|\\/+$/g, '')}/`;\n return files.filter((f) => f.startsWith(root) && f.endsWith('.tokens.json')).map((f) => f.slice(root.length));\n}\n\n/** A list of changes in an address: \"101,118,120\" (commas stay readable). */\nexport const changeList = (numbers: number[]) => numbers.join(',');\n\n/**\n * The admin demo with the Bridge toolbar on the combination: production (no preview holds all of them), the tokens\n * applied live. `bridge-use` carries the picks.\n */\nexport function tryTogetherUrl(admin: string, numbers: number[], picks: CombinePicks): string {\n const url = new URL(admin);\n url.pathname = '/';\n url.hash = '';\n const use = encodePicks(picks);\n url.search = `?bridge=${changeList(numbers)}${use ? `&bridge-use=${encodeURIComponent(use)}` : ''}`;\n return url.href;\n}\n\n/** GitHub lists at most 300 files per compare: past that, a branch cannot be read whole, so it is not combined. */\nexport const COMBINE_COMPARE_LIMIT = 300;\n\nexport interface CombineBranch {\n number: number;\n title: string;\n /** Only token files (and release notes): it can be combined. */\n tokens: boolean;\n /** Its own token edits; null for a code change. */\n edits: ChangeEdits | null;\n}\n\n/**\n * One branch as the combination needs it: one compare against the default branch (the files it edits since it\n * started, and where it started), then its token files at its start and now. Without a token the client reads the\n * public raw host, so visitors spend no API read on file contents.\n */\nexport async function readCombineBranch(gh: GitHubClient, pull: { number: number; title: string; headSha: string }, opts: { base: string; tokensRoot: string }): Promise<CombineBranch> {\n const compare = await gh.compareDetailed(opts.base, pull.headSha);\n const files = compare.files;\n const names = files.flatMap((f) => (f.previous_filename ? [f.filename, f.previous_filename] : [f.filename]));\n const start = compare.mergeBase;\n if (!start || files.length >= COMBINE_COMPARE_LIMIT || !onlyTokens(names, opts.tokensRoot)) return { number: pull.number, title: pull.title, tokens: false, edits: null };\n const root = opts.tokensRoot.replace(/^\\/+|\\/+$/g, '');\n const tokenFiles = files.filter((f) => tokenFilesOf([f.filename], root).length);\n const source: CombineSource = { number: pull.number, base: {}, head: {}, files: tokenFiles.map((f) => tokenFilesOf([f.filename], root)[0]!) };\n await Promise.all(\n tokenFiles.map(async (f) => {\n const rel = tokenFilesOf([f.filename], root)[0]!;\n source.base[rel] = f.status === 'added' ? undefined : await gh.readFile(f.previous_filename ?? f.filename, start);\n source.head[rel] = f.status === 'removed' ? undefined : await gh.readFile(f.filename, pull.headSha);\n }),\n );\n return { number: pull.number, title: pull.title, tokens: true, edits: changeEdits(source) };\n}\n","// Product branches and their library branches on GitHub, shared by Bridge Studio (in the browser, with the viewer's\n// token), the MCP server and the CLI: read what a product branch changes, record its missing pieces, open the library\n// branch of a piece and link both ways, let the product branch use the library branch's preview (Bridge merges the\n// library branch in), read where each linked library branch stands, and switch to the published version once it\n// ships. In suggest mode the library side is an issue (a suggestion or a request), never a branch. The pure rules are\n// in prod-branch.ts; finding the pieces (the audit) is in audit/missing-pieces.ts.\n\nimport type { ChangesMode } from './config';\nimport { EXPLORATION_NOTES_DIR, EXPLORATION_PREFIX, isExplorationBranch } from './explorations';\nimport { startExplorationOnGitHub, type ExplorationSettings } from './explorations-github';\nimport { GitHubError, type GitHubClient, type PullRequestSummary } from './github-client';\nimport { defaultProduct, productOfBranch, type ProductConfig } from './products';\nimport {\n libraryBranchPlan,\n linkStatus,\n mergePiecesRecord,\n NEEDED_BY_LABEL,\n parsePiecesRecord,\n libraryPreviewState,\n productBranchSentence,\n withLink,\n withNeededBy,\n withPiecesRecord,\n type LibraryBranchPlan,\n type LibraryLink,\n type LinkStatus,\n type MissingPiece,\n type PiecesRecord,\n type LibraryPreviewState,\n type ProductBranchRef,\n} from './prod-branch';\nimport { composeRequestIssue, type RequestSource } from './requests';\nimport { suggestionStateFromLabels, suggestionStatus } from './suggestions';\n\n/** Files the audit reads (styles, scripts, markup). Kept here so this module never loads the audit. */\nconst PRODUCT_FILE = /\\.(css|scss|sass|less|tsx|jsx|ts|js|mjs|cjs|mts|cts|astro|vue|svelte)$/;\nconst SKIP_FILE = /\\.d\\.[cm]?ts$|\\.(test|spec|stories|story)\\.[cm]?[jt]sx?$|\\.min\\.(css|js)$/;\n/** At most this many product files are read per check (two reads each). */\nexport const PIECES_FILE_LIMIT = 40;\n\ntype Pull = PullRequestSummary & { body: string; mergeable: boolean | null; requestedReviewers: string[] };\n\nexport interface ProductBranchRead {\n pull: Pull;\n product: ProductConfig;\n /** The product's changed files, their texts at the branch start (merge base with main) and at its head. */\n files: { path: string; before: string | null; after: string | null }[];\n /** Product files left unread past the limit. */\n skipped: number;\n record: PiecesRecord | undefined;\n}\n\nconst cleanPath = (p: string) => p.trim().replace(/^\\.?\\/+|\\/+$/g, '');\n\n/** The product of a branch, refusing the library itself: missing pieces are about a product built on the library. */\nfunction productOf(products: readonly ProductConfig[], pull: Pick<Pull, 'labels'>, files: string[]): ProductConfig {\n const product = productOfBranch(products, { labels: pull.labels, files });\n if (product.key === defaultProduct(products).key) throw new GitHubError(422, `This branch is a library branch (${product.name}), not a product branch: missing pieces are checked on a branch started for a product.`);\n return product;\n}\n\n/**\n * Reads a product branch for the check: the pull request, its product, and the product files it changes with their\n * text before and after (two reads per file, up to PIECES_FILE_LIMIT files).\n */\nexport async function readProductBranchOnGitHub(gh: GitHubClient, pr: number, opts: { products: readonly ProductConfig[] }): Promise<ProductBranchRead> {\n const pull = await gh.getPullRequest(pr);\n const cmp = await gh.compareDetailed(pull.baseRef, pull.headSha);\n const product = productOf(opts.products, pull, cmp.files.map((f) => f.filename));\n const dir = product.path ? `${cleanPath(product.path)}/` : '';\n const changed = cmp.files.filter((f) => f.status !== 'removed' && (!dir || f.filename.startsWith(dir)) && PRODUCT_FILE.test(f.filename) && !SKIP_FILE.test(f.filename) && !f.filename.split('/').includes('node_modules'));\n const read = changed.slice(0, PIECES_FILE_LIMIT);\n const start = cmp.mergeBase ?? pull.baseRef;\n const files = await Promise.all(\n read.map(async (f) => {\n const [before, after] = await Promise.all([f.status === 'added' ? Promise.resolve(undefined) : gh.getFileText(f.previous_filename ?? f.filename, start), gh.getFileText(f.filename, pull.headSha)]);\n return { path: f.filename, before: before ?? null, after: after ?? null };\n }),\n );\n return { pull, product, files, skipped: changed.length - read.length, record: parsePiecesRecord(pull.body) };\n}\n\n/** Saves a check in the product branch body, keeping the library branches already opened for its pieces. */\nexport async function recordPiecesOnGitHub(gh: GitHubClient, pr: number, check: { pieces: MissingPiece[]; fixes: number; headSha?: string | undefined; checkedAt?: string | undefined }): Promise<PiecesRecord> {\n const pull = await gh.getPullRequest(pr);\n const record = mergePiecesRecord(parsePiecesRecord(pull.body), { checkedAt: check.checkedAt ?? new Date().toISOString(), headSha: check.headSha ?? pull.headSha, pieces: check.pieces, fixes: check.fixes });\n await gh.updatePullRequest(pr, { body: withPiecesRecord(pull.body, record) });\n return record;\n}\n\n/** The client that may write a product branch: explorations need the `explore/` prefix. */\nconst productWriter = (gh: GitHubClient, branch: string) => (isExplorationBranch(branch) ? gh.withBranchPrefix(EXPLORATION_PREFIX) : gh);\n\nexport interface PreviewMerge {\n status: 'merged' | 'up-to-date' | 'conflict';\n sha: string | null;\n said: string;\n}\n\n/**\n * The product branch uses the library branch's preview: Bridge merges the library branch into it, so the product\n * preview deploy and anyone working on the branch get the real library change. A conflict is left to a developer.\n */\nexport async function useLibraryPreviewOnGitHub(gh: GitHubClient, input: { productBranch: string; libraryBranch: string; libraryNumber: number }): Promise<PreviewMerge> {\n const message = `chore(bridge): use the preview of ${input.libraryBranch} (#${input.libraryNumber})\\n\\nThe product branch takes the library branch before it ships. Switch to the published version once it does.`;\n try {\n const r = await productWriter(gh, input.productBranch).mergeIntoBranch(input.productBranch, input.libraryBranch, message);\n return { ...r, said: r.status === 'merged' ? 'Your branch now uses the preview of the library branch.' : 'Your branch already has the latest preview.' };\n } catch (err) {\n if (err instanceof GitHubError && err.status === 409) return { status: 'conflict', sha: null, said: `Your branch and the library branch change the same lines. A developer merges ${input.libraryBranch} into ${input.productBranch} by hand.` };\n throw err;\n }\n}\n\nexport interface OpenLibraryBranchInput {\n /** The product branch (pull request number). */\n pr: number;\n /** The piece id, from the recorded check. */\n piece: string;\n /** Branch library work starts from (the default branch). */\n base: string;\n products: readonly ProductConfig[];\n /** Previews and snapshot packages for a library exploration. */\n exploration: Pick<ExplorationSettings, 'packages' | 'apps'>;\n /**\n * Opens the token change of a token piece (planTokenProposal + writeTokenProposalOnGitHub where the caller has the\n * token files and contrast pairs). Without it a token piece is refused. In suggest mode (`ctx.mode`), it files a\n * suggestion instead (suggestTokenProposalOnGitHub with `neededBy: plan.neededBy`) and returns its result: a result\n * with `status: 'suggested'` is linked as a suggestion, anything else as a token change pull request.\n */\n writeTokens?: ((plan: Extract<LibraryBranchPlan, { kind: 'token-change' }>, ctx: { mode: ChangesMode }) => Promise<LibraryTokenWrite>) | undefined;\n /** Who opens it, and the AI agent behind it (\"claude\"). */\n openedBy?: string | undefined;\n agent?: string | undefined;\n source?: RequestSource | undefined;\n /** Merge the new library branch into the product branch when it already changes something (default true). */\n usePreview?: boolean | undefined;\n dryRun?: boolean | undefined;\n /**\n * \"direct\" (default here, so existing callers keep their behaviour): a token piece opens a pull request, a variant\n * an exploration branch. \"suggest\": a token piece is filed as a suggestion and a variant as a component request, so\n * the token only needs Issues write. Callers pass changesMode(config), or an explicit choice.\n */\n mode?: ChangesMode | undefined;\n}\n\n/** What writeTokens returns: the pull request it opened, or the suggestion it filed. */\nexport type LibraryTokenWrite = { number: number; url: string; branch: string; status?: undefined } | { status: 'suggested'; number: number; url: string };\n\nexport interface OpenedLibraryBranch {\n /** \"suggested\": the library side is a suggestion (`link.kind` 'suggestion', `link.number` its issue). */\n status: 'opened' | 'suggested' | 'already-linked' | 'dry-run';\n plan: LibraryBranchPlan;\n link: LibraryLink | null;\n preview: PreviewMerge | null;\n warnings: string[];\n}\n\n/** The product branch as the library side names it. */\nexport function productBranchRef(pull: Pick<Pull, 'number' | 'title' | 'headRef' | 'url' | 'author' | 'body'>, product: ProductConfig): ProductBranchRef {\n const name = /<!-- bridge-exploration (\\{[\\s\\S]*?\\}) -->/.exec(pull.body ?? '');\n let title = pull.title.replace(/^[A-Z][A-Z0-9_]*-\\d+\\s+/, '').replace(/^Exploration:\\s*/i, '');\n let author = pull.author;\n if (name) {\n try {\n const e = JSON.parse(name[1]!) as { name?: string; author?: string };\n if (e.name) title = e.name;\n if (e.author) author = e.author;\n } catch {\n // The pull request title is enough.\n }\n }\n return { pr: pull.number, title: title.charAt(0).toUpperCase() + title.slice(1), branch: pull.headRef, url: pull.url, productKey: product.key, productName: product.name, ...(author ? { author } : {}) };\n}\n\n/**\n * Opens the library side of a missing piece and links both ways: the library branch (or request) says \"Needed by\" the\n * product branch and carries the `needed-by-product` label; the product branch records the link. A token piece opens a\n * token change (through `writeTokens`), a variant a library exploration, a new component a request. When the new\n * library branch already changes something (a token change), the product branch takes its preview.\n * In suggest mode nothing is a branch: a token piece is a suggestion (through `writeTokens`), a variant and a new\n * component are requests; recording the link on the product branch is best effort (a warning when refused).\n */\nexport async function openLibraryBranchOnGitHub(gh: GitHubClient, input: OpenLibraryBranchInput): Promise<OpenedLibraryBranch> {\n const pull = await gh.getPullRequest(input.pr);\n const record = parsePiecesRecord(pull.body);\n const piece = record?.pieces.find((p) => p.id === input.piece);\n if (!record || !piece) throw new GitHubError(404, record ? `No piece \"${input.piece}\" on #${input.pr}. Pieces: ${record.pieces.map((p) => p.id).join(', ') || 'none'}.` : `#${input.pr} was not checked yet: find its missing pieces first (bridge_missing_pieces with record, or \\`bridge pieces ${input.pr} --record\\`).`);\n const product = productOf(input.products, pull, await gh.listPullRequestFiles(input.pr).then((f) => f.map((x) => x.filename), () => []));\n const mode: ChangesMode = input.mode ?? 'direct';\n const plan = libraryBranchPlan(piece, productBranchRef(pull, product), { source: input.source, requestedBy: input.openedBy, mode });\n const existing = record.links.find((l) => l.piece === piece.id);\n if (existing) return { status: 'already-linked', plan, link: existing, preview: null, warnings: [] };\n if (input.dryRun) return { status: 'dry-run', plan, link: null, preview: null, warnings: [] };\n if (!gh.canWrite) throw new GitHubError(401, mode === 'suggest' ? 'Suggesting a library change needs a GitHub token (issues: write).' : 'Opening a library branch needs a GitHub token (contents, pull requests and issues: write).');\n const warnings: string[] = [];\n const at = new Date().toISOString();\n const who = { ...(input.openedBy ? { openedBy: input.openedBy } : {}), ...(input.agent ? { agent: input.agent } : {}) };\n let link: LibraryLink;\n if (plan.kind === 'token-change') {\n if (!input.writeTokens) throw new GitHubError(422, 'This piece is a token: open it where the token files are read (Bridge Studio, bridge_open_library_branch or `bridge pieces open`).');\n const r = await input.writeTokens(plan, { mode });\n link = r.status === 'suggested' ? { piece: piece.id, kind: 'suggestion', number: r.number, url: r.url, title: plan.title, at, ...who } : { piece: piece.id, kind: 'token-change', number: r.number, url: r.url, title: plan.title, branch: r.branch, at, ...who };\n } else if (plan.kind === 'exploration') {\n const r = await startExplorationOnGitHub(gh, { ...plan.exploration, ...(input.openedBy ? { author: input.openedBy } : {}), ...(input.agent ? { agent: input.agent } : {}) }, { base: input.base, ...input.exploration, labels: [NEEDED_BY_LABEL] });\n link = { piece: piece.id, kind: 'exploration', number: r.pr, url: r.url, title: plan.title, branch: r.branch, at, ...who };\n } else {\n const issue = composeRequestIssue(plan.request, { labels: [NEEDED_BY_LABEL] });\n const r = await gh.createIssue(issue);\n link = { piece: piece.id, kind: 'request', number: r.number, url: r.url, title: plan.title, at, ...who };\n }\n // The library side says who needs it; the product side records the link.\n try {\n if (link.kind === 'request' || link.kind === 'suggestion') {\n const issue = await gh.getIssue(link.number);\n await gh.updateIssue(link.number, { body: withNeededBy(issue.body, plan.neededBy) });\n if (link.kind === 'suggestion' && !issue.labels.includes(NEEDED_BY_LABEL)) await gh.addLabels(link.number, [NEEDED_BY_LABEL]);\n } else {\n const lib = await gh.getPullRequest(link.number);\n await gh.updatePullRequest(link.number, { body: withNeededBy(lib.body, plan.neededBy) });\n await gh.addLabels(link.number, [NEEDED_BY_LABEL]);\n }\n } catch (err) {\n if (err instanceof GitHubError && err.auth === 'rejected') throw err;\n warnings.push(`The library side does not say who needs it yet (${(err as Error).message}). Add \"Needed by #${input.pr}\" to #${link.number} on GitHub.`);\n }\n try {\n const fresh = await gh.getPullRequest(input.pr);\n const next = withLink(parsePiecesRecord(fresh.body) ?? record, link);\n await gh.updatePullRequest(input.pr, { body: withPiecesRecord(fresh.body, next) });\n } catch (err) {\n // Direct mode needs the record (the token can write pull requests); a suggest-mode token may not.\n if (mode !== 'suggest') throw err;\n warnings.push(`#${input.pr} does not list #${link.number} yet (${(err as Error).message}). Add \"Library: #${link.number}\" to #${input.pr} on GitHub, so this piece is not sent twice.`);\n }\n let preview: PreviewMerge | null = null;\n if ((input.usePreview ?? true) && link.kind === 'token-change' && link.branch) {\n preview = await useLibraryPreviewOnGitHub(gh, { productBranch: pull.headRef, libraryBranch: link.branch, libraryNumber: link.number }).catch((err: Error) => {\n warnings.push(`Your branch does not use the preview yet: ${err.message}`);\n return null;\n });\n }\n return { status: link.kind === 'suggestion' ? 'suggested' : 'opened', plan, link, preview, warnings };\n}\n\nexport interface LinkedLibraryBranch {\n link: LibraryLink;\n piece: MissingPiece | undefined;\n status: LinkStatus;\n preview: LibraryPreviewState;\n /** Requested reviewers of a library pull request, or assignees of a request. */\n people: string[];\n}\n\nexport interface ProductBranchView {\n pull: Pull;\n product: ProductConfig;\n record: PiecesRecord | undefined;\n sentence: ReturnType<typeof productBranchSentence>;\n linked: LinkedLibraryBranch[];\n /** Pieces with no library branch yet. */\n open: MissingPiece[];\n}\n\nconst isNote = (path: string) => path.startsWith(`${EXPLORATION_NOTES_DIR}/`);\n\n/** Where one linked library branch stands, and what its preview means for the product branch. */\nexport async function linkedLibraryBranchOnGitHub(gh: GitHubClient, link: LibraryLink, product: { headSha: string; baseRef: string }, piece?: MissingPiece): Promise<LinkedLibraryBranch> {\n const nearest = piece?.nearest?.label;\n if (link.kind === 'suggestion') {\n const issue = await gh.getIssue(link.number);\n // Status from the issue and its state label (a cache): the review comments are read on the suggestion itself.\n const cached = suggestionStateFromLabels(issue.labels);\n const s = suggestionStatus({ state: issue.state, stateReason: issue.stateReason, applied: cached === 'applying', review: cached === 'applying' ? undefined : cached });\n const status = linkStatus({ kind: 'suggestion', status: s });\n const lifecycle = s === 'applied' ? 'merged' : issue.state === 'closed' ? 'closed' : 'open';\n const behindMain = lifecycle === 'merged' ? await gh.compare(product.baseRef, product.headSha).then((c) => c.behindBy, () => null) : null;\n const preview = libraryPreviewState({ kind: 'suggestion', lifecycle, hasChanges: false, missing: null, total: null, behindMain, nearest });\n return { link, piece, status, preview, people: status.people };\n }\n if (link.kind === 'request') {\n const issue = await gh.getIssue(link.number);\n const status = linkStatus({ kind: 'request', state: issue.state, stateReason: issue.stateReason });\n const lifecycle = issue.state === 'closed' ? (issue.stateReason === 'not_planned' ? 'closed' : 'merged') : 'open';\n const behindMain = lifecycle === 'merged' ? await gh.compare(product.baseRef, product.headSha).then((c) => c.behindBy, () => null) : null;\n const preview = libraryPreviewState({ kind: 'request', lifecycle, hasChanges: false, missing: null, total: null, behindMain, nearest });\n return { link, piece, status, preview, people: status.people };\n }\n const lib = await gh.getPullRequest(link.number);\n const reviews = await gh.listReviews(link.number).catch(() => []);\n const status = linkStatus({ kind: link.kind, state: lib.state, draft: lib.draft, labels: lib.labels, requestedReviewers: lib.requestedReviewers, reviews: reviews.map((r) => ({ user: r.user, state: r.state })) });\n const lifecycle = lib.state === 'merged' ? 'merged' : lib.state === 'open' ? 'open' : 'closed';\n let missing: number | null = null;\n let total: number | null = null;\n let behindMain: number | null = null;\n let hasChanges = true;\n if (lifecycle === 'open') {\n const [files, own, inProduct] = await Promise.all([\n gh.listPullRequestFiles(link.number).catch(() => null),\n gh.compare(lib.baseRef, lib.headSha).catch(() => null),\n gh.compare(product.headSha, lib.headSha).catch(() => null),\n ]);\n hasChanges = files ? files.some((f) => !isNote(f.filename)) : true;\n total = own?.aheadBy ?? null;\n missing = inProduct?.aheadBy ?? null;\n } else if (lifecycle === 'merged') {\n behindMain = await gh.compare(product.baseRef, product.headSha).then((c) => c.behindBy, () => null);\n }\n const preview = libraryPreviewState({ kind: link.kind, lifecycle, hasChanges, missing, total, behindMain, nearest });\n return { link, piece, status, preview, people: status.people };\n}\n\n/**\n * Everything a product branch page shows: the record, the sentence, and each linked library branch with its status,\n * its reviewers and what its preview means for the product branch. A few reads per linked branch.\n */\nexport async function productBranchViewOnGitHub(gh: GitHubClient, pr: number, opts: { products: readonly ProductConfig[]; viewer?: string | null | undefined; agentName?: string | undefined }): Promise<ProductBranchView> {\n const pull = await gh.getPullRequest(pr);\n const files = await gh.listPullRequestFiles(pr).then((f) => f.map((x) => x.filename), () => []);\n const product = productOf(opts.products, pull, files);\n const record = parsePiecesRecord(pull.body);\n const linked = await Promise.all(\n (record?.links ?? []).map((l) => linkedLibraryBranchOnGitHub(gh, l, { headSha: pull.headSha, baseRef: pull.baseRef }, record?.pieces.find((p) => p.id === l.piece))),\n );\n const open = (record?.pieces ?? []).filter((p) => !record!.links.some((l) => l.piece === p.id));\n return { pull, product, record, sentence: productBranchSentence(record, { viewer: opts.viewer, agentName: opts.agentName }), linked, open };\n}\n\n/**\n * \"Switch to the published version\": once the library branch shipped, main comes into the product branch (GitHub's\n * update branch), so the product branch stops carrying the library change and uses the shipped one. Conflicts are\n * left to bridge_update_from_main or a developer.\n */\nexport async function switchToPublishedOnGitHub(gh: GitHubClient, pr: number): Promise<{ status: 'switched' | 'up-to-date'; said: string }> {\n if (!gh.canWrite) throw new GitHubError(401, 'Switching needs a GitHub token (contents and pull requests: write).');\n const pull = await gh.getPullRequest(pr);\n if (pull.state !== 'open') throw new GitHubError(422, `#${pr} is ${pull.state}: only an open branch switches.`);\n const cmp = await gh.compare(pull.baseRef, pull.headSha);\n if (cmp.behindBy === 0) return { status: 'up-to-date', said: 'Your branch already uses the published version.' };\n try {\n await gh.updatePullRequestBranch(pr, pull.headSha);\n } catch (err) {\n if (err instanceof GitHubError && err.status === 422) throw new GitHubError(422, `Your branch and ${pull.baseRef} change the same lines, so Bridge cannot switch it alone. Use \"Update from main\" to pick the token values, or ask a developer.`, err.detail);\n throw err;\n }\n return { status: 'switched', said: `Your branch now uses the published version from ${pull.baseRef}.` };\n}\n","// A token change proposal: token edits checked like every Bridge write (no new validation error, no contrast pair that\n// starts failing), tiered by the shared classifier, with the designer-friendly body and a changeset; then, on GitHub,\n// either a new branch with one commit and a pull request (a draft from tier 2), labelled (\"direct\" mode), or a\n// suggestion: an issue holding the exact edits that owners approve and a developer applies (\"suggest\" mode, see\n// suggestions.ts). The MCP server (bridge_propose_token_change), the CLI (`bridge propose`) and Studio (a library\n// branch for a product branch's missing token) all write it through these functions.\nimport type { BridgeConfig } from './config';\nimport type { GitHubClient } from './github-client';\nimport type { NeededBy } from './prod-branch';\nimport type { RequestSource } from './requests';\nimport { createSuggestionOnGitHub } from './suggestions-github';\nimport { gitBlobSha, SUGGESTION_SCHEMA, type SuggestionPayloadV1 } from './suggestions';\nimport { branchWithJiraKey, titleWithJiraKey } from './jira';\nimport { LayeredTokenSet, validateLayered, type LayerIssue } from './layered';\nimport { classifyLayered, composeProposalBody, contrastDelta, diffLayered, layeredImpact, runLayeredContrast, type ChangeTier, type ContrastDelta, type ImpactEntry, type LayeredChange } from './layered-review';\nimport { slugify } from './pr-composer';\nimport { applyTokenEdits, type TokenEdit } from './token-edits';\nimport type { ContrastPair } from './wcag';\nimport { formatChangeset } from './changeset';\n\nexport interface TokenProposalPlan {\n title: string;\n summary: string;\n /** The token edits the plan applied: what a suggestion stores and re-applies on the current tokens. */\n edits: TokenEdit[];\n before: LayeredTokenSet;\n after: LayeredTokenSet;\n changes: LayeredChange[];\n tier: ChangeTier;\n contrast: ContrastDelta[];\n newFailures: ContrastDelta[];\n newErrors: LayerIssue[];\n impact: { total: number; entries: ImpactEntry[] };\n notes: string[];\n /** Token files edited, as repo paths. */\n touched: string[];\n /** Every file the commit writes: the token files and the changeset. */\n files: { path: string; content: string | null }[];\n body: string;\n /** Branch slug from the title. */\n slug: string;\n /** Why it cannot be opened (new validation errors, failing contrast pairs), or null. */\n blocked: string | null;\n}\n\nconst issueKey = (i: LayerIssue) => `${i.code}|${i.path ?? ''}|${i.file ?? ''}|${i.message}`;\n\n/**\n * What a token change would do, without writing: the token diff, validation and contrast against `before`, the tier,\n * the body and the files. `blocked` says why it must not be opened. Null when the edits change nothing.\n */\nexport function planTokenProposal(input: {\n before: LayeredTokenSet;\n pairs: ContrastPair[];\n edits: TokenEdit[];\n title: string;\n summary?: string | undefined;\n config: BridgeConfig;\n /** \"Bridge MCP\", \"Bridge Studio\". */\n tool?: string | undefined;\n /** More body paragraphs, after the generated body (the product line, \"Needed by\"). */\n bodyExtra?: string[] | undefined;\n}): TokenProposalPlan | null {\n const { before, config } = input;\n const r = applyTokenEdits(before, input.edits);\n const after = new LayeredTokenSet(before.config, r.files);\n const changes = diffLayered(before, after);\n if (!changes.length) return null;\n const prevErrors = new Set(validateLayered(before).map(issueKey));\n const newErrors = validateLayered(after).filter((i) => i.level === 'error' && !prevErrors.has(issueKey(i)));\n const modes = config.contrast?.modes;\n const contrast = input.pairs.length ? contrastDelta(runLayeredContrast(before, input.pairs, modes), runLayeredContrast(after, input.pairs, modes)) : [];\n const newFailures = contrast.filter((d) => d.passBefore && !d.passAfter);\n const impact = layeredImpact(before, after, changes);\n const tier = classifyLayered(changes, [], config);\n const summary = input.summary?.trim() || input.title;\n const body = [composeProposalBody({ summary, changes, contrast, impact, tier, validationErrors: newErrors.length, tool: input.tool ?? 'Bridge MCP' }), ...(input.bodyExtra ?? [])].filter(Boolean).join('\\n\\n');\n const slug = slugify(input.title, 48) || 'change';\n const changesetPath = `${config.changesets?.dir ?? '.changeset'}/bridge-${slug}.md`;\n const touched = r.touched.map((f) => after.repoPath(f));\n const files = [\n ...r.touched.map((f) => ({ path: after.repoPath(f), content: after.files.get(f)! as string | null })),\n ...(config.changesets ? [{ path: changesetPath, content: formatChangeset(config.changesets.package, tier.bump, summary) as string | null }] : []),\n ];\n const blocked = newErrors.length || newFailures.length ? [newErrors.length ? `${newErrors.length} new validation error(s)` : '', newFailures.length ? `${newFailures.length} contrast pair(s) would fail` : ''].filter(Boolean).join(' and ') : null;\n return { title: input.title, summary, edits: input.edits, before, after, changes, tier, contrast, newFailures, newErrors, impact, notes: r.notes, touched, files, body, slug, blocked };\n}\n\nexport interface OpenedTokenProposal {\n branch: string;\n commit: string;\n pr: number;\n url: string;\n labels: string[];\n draft: boolean;\n}\n\n/**\n * Opens a planned token change on GitHub: a new branch from `base` (the agent prefix, the Jira key, -2, -3 when the name\n * is taken), one commit, a pull request (a draft from tier 2, until design review) and its labels. Refuses a blocked plan.\n */\nexport async function writeTokenProposalOnGitHub(\n gh: GitHubClient,\n plan: TokenProposalPlan,\n opts: {\n base: string;\n branchPrefix: string;\n jira?: string | null | undefined;\n /** Labels before the tier ones (governance.labels), and after them (the product label). */\n labels?: string[] | undefined;\n labelsAfter?: string[] | undefined;\n /** Who proposes it, in the commit message: \"Bridge MCP (source: mcp)\". */\n tool?: string | undefined;\n },\n): Promise<OpenedTokenProposal> {\n if (plan.blocked) throw new Error(`Not opened: ${plan.blocked}. Bridge never opens a branch that breaks the gate.`);\n const jira = opts.jira ?? null;\n let branch = branchWithJiraKey(`${opts.branchPrefix}${plan.slug}`, jira);\n for (let i = 2; await gh.getBranchSha(branch).then(Boolean, () => false); i++) branch = branchWithJiraKey(`${opts.branchPrefix}${plan.slug}-${i}`, jira);\n const commit = await gh.commitToNewBranch({ base: opts.base, branch, message: `feat(tokens): ${plan.title}\\n\\nProposed through ${opts.tool ?? 'Bridge MCP'}. Tier ${plan.tier.tier}.`, files: plan.files });\n const labels = tokenLabels(plan, opts.labels, opts.labelsAfter);\n const draft = plan.tier.tier >= 2;\n const pr = await gh.createPullRequest({ base: opts.base, head: branch, title: titleWithJiraKey(`feat(tokens): ${plan.title}`, jira), body: plan.body, draft });\n await gh.addLabels(pr.number, labels);\n return { branch, commit: commit.sha, pr: pr.number, url: pr.url, labels, draft };\n}\n\nexport interface SuggestedTokenProposal {\n status: 'suggested';\n /** The suggestion issue. */\n number: number;\n url: string;\n /** sha256 of the payload: what approvals bind to. */\n sha: string;\n labels: string[];\n /** Sentences about parts that did not go through (labels refused). The suggestion itself holds. */\n warnings: string[];\n}\n\n/** The labels of a token change, before and after the tier ones: the same on a pull request and a suggestion. */\nconst tokenLabels = (plan: Pick<TokenProposalPlan, 'tier'>, before: string[] = [], after: string[] = []) => [\n ...new Set([...before, `tier: ${plan.tier.tier}`, ...(plan.tier.tier === 3 ? ['tokens'] : []), ...(plan.tier.bump === 'major' ? ['breaking'] : []), ...after]),\n];\n\n/** The suggestion payload (bridge.suggestion/1) of a planned token change, computed on `base`. Pure. */\nexport function tokenSuggestionPayload(\n plan: TokenProposalPlan,\n ctx: {\n base: { ref: string; sha: string };\n source: RequestSource;\n suggestedBy?: string | undefined;\n createdAt?: string | undefined;\n links?: SuggestionPayloadV1['links'];\n previews?: SuggestionPayloadV1['previews'];\n },\n): SuggestionPayloadV1 {\n // Token files are re-derived from the edits at apply time; only the other files (the changeset) are stored whole.\n const tokenFiles = new Set(plan.touched);\n const files = plan.files.filter((f) => !tokenFiles.has(f.path)).map((f) => ({ path: f.path, beforeSha: null, afterSha: f.content === null ? null : gitBlobSha(f.content), content: f.content }));\n return {\n schema: SUGGESTION_SCHEMA,\n kind: 'token-change',\n title: plan.title,\n summary: plan.summary,\n source: ctx.source,\n ...(ctx.suggestedBy ? { suggestedBy: ctx.suggestedBy.replace(/^@/, '') } : {}),\n createdAt: ctx.createdAt ?? new Date().toISOString(),\n base: ctx.base,\n tier: { tier: plan.tier.tier, bump: plan.tier.bump },\n tokens: {\n edits: plan.edits,\n changes: plan.changes.map((c) => ({ kind: c.kind, path: c.path, from: c.from, file: c.file, before: c.before, after: c.after, beforeCss: c.beforeCss, afterCss: c.afterCss })),\n },\n ...(files.length ? { files } : {}),\n checks: {\n newErrors: plan.newErrors.length,\n contrast: plan.contrast.map((d) => ({ pair: `${d.fg} on ${d.bg}`, mode: d.modes || undefined, before: d.before ?? 0, after: d.after ?? 0, min: d.min, pass: d.passAfter })),\n blocked: plan.blocked,\n impact: plan.impact.total,\n },\n ...(ctx.links ? { links: ctx.links } : {}),\n ...(ctx.previews?.length ? { previews: ctx.previews } : {}),\n };\n}\n\n/**\n * Files a planned token change as a suggestion (suggest mode): one issue with the readable change, the checks and the\n * exact edits, labelled like the pull request would be (tier, tokens, breaking), plus the suggestion labels. Needs\n * Issues write only: no branch, no commit, no pull request. Refuses a blocked plan, like writeTokenProposalOnGitHub.\n */\nexport async function suggestTokenProposalOnGitHub(\n gh: GitHubClient,\n plan: TokenProposalPlan,\n opts: {\n /** Default branch the plan was computed on. Its head commit is recorded as the suggestion's base. */\n base: string;\n source: RequestSource;\n /** GitHub login of who suggests it. */\n suggestedBy?: string | undefined;\n /** Labels before the tier ones (governance.labels), and after them (the product label). */\n labels?: string[] | undefined;\n labelsAfter?: string[] | undefined;\n /** The product branch that needs it (a missing piece). */\n neededBy?: NeededBy | undefined;\n /** The Figma origin, a suggestion it replaces. */\n links?: SuggestionPayloadV1['links'];\n previews?: SuggestionPayloadV1['previews'];\n assignees?: string[] | undefined;\n /** Commit sha of `base`, when the caller already read it (saves a call). */\n baseSha?: string | undefined;\n },\n): Promise<SuggestedTokenProposal> {\n if (plan.blocked) throw new Error(`Not suggested: ${plan.blocked}. Bridge never suggests a change that breaks the gate.`);\n const sha = opts.baseSha ?? (await gh.getBranchSha(opts.base));\n if (!sha) throw new Error(`Branch ${opts.base} not found. Check the default branch in bridge.config.json.`);\n const links = opts.neededBy || opts.links ? { ...opts.links, ...(opts.neededBy ? { neededBy: opts.neededBy } : {}) } : undefined;\n const payload = tokenSuggestionPayload(plan, { base: { ref: opts.base, sha }, source: opts.source, suggestedBy: opts.suggestedBy, links, previews: opts.previews });\n const labels = tokenLabels(plan, opts.labels, opts.labelsAfter);\n const created = await createSuggestionOnGitHub(gh, payload, { labels, assignees: opts.assignees, details: plan.body });\n return { status: 'suggested', number: created.number, url: created.url, sha: created.sha, labels, warnings: created.warnings };\n}\n","// Components pushed from Figma, on GitHub: open the library branch a component change goes to (a token change through\n// the shared token proposal write, or a Claude draft branch carrying the spec), list them with where each stands, read\n// one back as Claude's brief, and say when Claude has drafted the code. Shared by the DS Bridge Figma plugin, the MCP\n// server and the CLI. In suggest mode the same change is filed as a suggestion (an issue) instead of a branch. The\n// routing rules are in figma-push.ts.\n\nimport type { ChangesMode } from './config';\nimport { GitHubError, type GitHubClient } from './github-client';\nimport { REQUEST_LABEL, type RequestSource } from './requests';\nimport { createSuggestionOnGitHub } from './suggestions-github';\nimport { figmaNodeUrl, SUGGESTION_SCHEMA, type SuggestionFigmaNode, type SuggestionPayloadV1 } from './suggestions';\nimport type { TokenEdit } from './token-edits';\nimport {\n DRAFTED_BY_CLAUDE_LABEL,\n FIGMA_SPEC_DIR,\n FROM_FIGMA_LABEL,\n WAITING_FOR_CLAUDE_LABEL,\n figmaBranchTitle,\n figmaDraftBody,\n figmaDraftBrief,\n figmaOriginSection,\n figmaPushStatus,\n figmaSpecPath,\n figmaSpecSlug,\n formatFigmaSpec,\n parseFigmaOrigin,\n parseFigmaSpec,\n planComponentPush,\n withFigmaOrigin,\n type ComponentPushDiff,\n type ComponentPushPlan,\n type FigmaOrigin,\n type FigmaPushStatus,\n type PushTokenContext,\n} from './figma-push';\n\n/**\n * Opens the token change of an exact push: the caller plans it on the library's token files (planTokenProposal). In\n * suggest mode (`mode`), it files a suggestion instead (suggestTokenProposalOnGitHub with `links: { figma }`) and\n * returns its result: a result with `status: 'suggested'` is reported as a suggestion.\n */\nexport type FigmaTokenWriter = (input: {\n edits: TokenEdit[];\n title: string;\n summary: string;\n bodyExtra: string[];\n mode: ChangesMode;\n /** The Figma component, for the suggestion's links. */\n figma: { fileKey?: string | undefined; nodeId?: string | undefined; url?: string | undefined; nodes?: SuggestionFigmaNode[] | undefined };\n}) => Promise<{ number: number; url: string; branch: string; status?: undefined } | { status: 'suggested'; number: number; url: string }>;\n\nexport interface OpenComponentPushInput {\n diff: ComponentPushDiff;\n /** Token facts to route it (planComponentPush), or the route already planned with every component of the file. */\n tokens?: PushTokenContext | undefined;\n plan?: ComponentPushPlan | undefined;\n /** Branch library work starts from (the default branch). */\n base: string;\n /** governance.branchPrefix (\"bridge/\"). */\n branchPrefix: string;\n /** Labels the repo adds to every Bridge branch (governance.labels), before the Figma ones. */\n labels?: string[] | undefined;\n /** The token change of an exact push (planTokenProposal + writeTokenProposalOnGitHub where the token files are read). */\n writeTokens?: FigmaTokenWriter | undefined;\n /** \"the DS Bridge Figma plugin\", \"Bridge MCP\". */\n tool?: string | undefined;\n dryRun?: boolean | undefined;\n /**\n * \"direct\" (default here, so existing callers keep their behaviour): a branch and a pull request. \"suggest\": a\n * suggestion issue (a token change, or a component spec for Claude), no branch. Callers pass changesMode(config).\n */\n mode?: ChangesMode | undefined;\n /** Who sends it (a GitHub login), recorded on a suggestion. Defaults to the diff's requestedBy. */\n suggestedBy?: string | undefined;\n /** Commit sha of `base`, when the caller already read it (a component spec suggestion records it). */\n baseSha?: string | undefined;\n}\n\nexport interface OpenedComponentPush {\n status: 'opened' | 'suggested' | 'dry-run' | 'not-sent';\n plan: ComponentPushPlan;\n /** The library branch: a token change or a Claude draft branch (a draft pull request). Null when suggested. */\n link: { route: 'token-change' | 'claude-draft'; number: number; url: string; branch: string } | null;\n /** The suggestion issue (status 'suggested'): a token change, or a component spec Claude drafts the code from. */\n suggestion?: { route: 'token-change' | 'claude-draft'; number: number; url: string } | undefined;\n}\n\n/** The source of a push, as suggestions name it: the diff's own when it is one, else Figma. */\nconst pushSource = (d: ComponentPushDiff): RequestSource => (['figma', 'studio', 'cli', 'mcp'].includes(d.source as string) ? (d.source as RequestSource) : 'figma');\n\n/** Tier of a component spec: new parts of the API are tier 2 minor, other code changes tier 2 patch. */\nconst specTier = (d: ComponentPushDiff): SuggestionPayloadV1['tier'] => ({ tier: 2, bump: d.kind === 'new-component' || d.kind === 'new-variant' || d.kind === 'prop-change' ? 'minor' : 'patch' });\n\n/** The suggestion payload (bridge.suggestion/1, kind component-spec) of a push that needs code. Pure. */\nexport function componentSpecSuggestionPayload(\n d: ComponentPushDiff,\n plan: Pick<ComponentPushPlan, 'edits' | 'reasons' | 'issues'>,\n ctx: { base: { ref: string; sha: string }; suggestedBy?: string | undefined; createdAt?: string | undefined; componentsDir?: string | undefined },\n): SuggestionPayloadV1 {\n const specPath = figmaSpecPath(d);\n const spec = JSON.parse(formatFigmaSpec(d, plan)) as unknown;\n const brief = figmaDraftBrief({ ...d, tokenEdits: plan.edits, reasons: plan.reasons }, { suggestion: true, specPath, componentsDir: ctx.componentsDir });\n const by = (ctx.suggestedBy ?? d.requestedBy)?.replace(/^@/, '');\n const figma = d.figma?.fileKey || d.figma?.nodeId || d.figma?.url ? { ...(d.figma.fileKey ? { fileKey: d.figma.fileKey } : {}), ...(d.figma.nodeId ? { nodeId: d.figma.nodeId } : {}), ...(d.figma.url ? { url: d.figma.url } : {}), ...figmaNodes(d) } : undefined;\n // Screenshots, when the sender could store them (a token with contents write): links next to the Figma nodes.\n const previews = (d.images ?? []).map((url, i) => ({ label: `${d.component} in Figma${(d.images?.length ?? 0) > 1 ? ` ${i + 1}` : ''}`, url }));\n return {\n schema: SUGGESTION_SCHEMA,\n kind: 'component-spec',\n title: d.title,\n summary: d.summary.trim() || d.title,\n source: pushSource(d),\n ...(by ? { suggestedBy: by } : {}),\n createdAt: ctx.createdAt ?? new Date().toISOString(),\n base: ctx.base,\n tier: specTier(d),\n componentSpec: { component: d.component, specPath, spec, brief },\n checks: { newErrors: 0, contrast: [], blocked: null, impact: 0 },\n ...(figma ? { links: { figma } } : {}),\n ...(previews.length ? { previews } : {}),\n };\n}\n\n/** The Figma nodes of a push for a suggestion's links: the component as it is now (after), and before when known. */\nexport function figmaNodes(d: Pick<ComponentPushDiff, 'figma'>): { nodes?: SuggestionFigmaNode[] } {\n const f = d.figma;\n if (!f) return {};\n const url = (id: string, given?: string) => given ?? (f.fileKey ? figmaNodeUrl(f.fileKey, id) : undefined);\n const nodes: SuggestionFigmaNode[] = [];\n if (f.before?.nodeId) nodes.push({ nodeId: f.before.nodeId, state: 'before', ...(url(f.before.nodeId, f.before.url) ? { url: url(f.before.nodeId, f.before.url) } : {}), ...(f.before.nodeName ? { name: f.before.nodeName } : {}) });\n if (f.nodeId) nodes.push({ nodeId: f.nodeId, state: 'after', ...(url(f.nodeId, f.url) ? { url: url(f.nodeId, f.url) } : {}), ...(f.nodeName ? { name: f.nodeName } : {}) });\n return nodes.length ? { nodes } : {};\n}\n\n/**\n * Opens the library branch of a component change from Figma, linked to its origin (the Figma component): an exact token\n * swap opens a token change (the shared proposal write: contrast gate, tier, changeset); anything that needs code opens\n * a draft pull request carrying the spec (`.bridge/figma/<slug>.json`), labelled waiting for Claude. A manual change\n * opens nothing: its issues say what to do in Figma.\n * In suggest mode: the token swap is a token suggestion (through `writeTokens`), the code change a component spec\n * suggestion (the spec inside the payload, labelled from Figma and waiting for Claude). Issues write only.\n */\nexport async function openComponentPushOnGitHub(gh: GitHubClient, input: OpenComponentPushInput): Promise<OpenedComponentPush> {\n const d = input.diff;\n if (!input.plan && !input.tokens) throw new Error('Route the change first: pass the token facts or the plan.');\n const plan = input.plan ?? planComponentPush(d, input.tokens!);\n if (plan.route === 'manual') return { status: 'not-sent', plan, link: null };\n if (input.dryRun) return { status: 'dry-run', plan, link: null };\n const mode: ChangesMode = input.mode ?? 'direct';\n if (!gh.canWrite) throw new GitHubError(401, mode === 'suggest' ? 'Suggesting a component change needs a GitHub token (issues: write).' : 'Sending a component change needs a GitHub token (contents and pull requests: write).');\n const origin: FigmaOrigin = {\n component: d.component,\n figmaName: d.figmaName,\n route: plan.route,\n kind: d.kind,\n ...(d.figma?.nodeId ? { nodeId: d.figma.nodeId } : {}),\n ...(d.figma?.fileKey ? { fileKey: d.figma.fileKey } : {}),\n ...(d.figma?.url ? { url: d.figma.url } : {}),\n ...(d.requestedBy ? { requestedBy: d.requestedBy } : {}),\n };\n if (plan.route === 'token-change') {\n if (!input.writeTokens) throw new GitHubError(422, 'This change is a token change: send it where the token files are read (the DS Bridge plugin, bridge_push_figma_component or `bridge figma push`).');\n const figma = { ...(origin.fileKey ? { fileKey: origin.fileKey } : {}), ...(origin.nodeId ? { nodeId: origin.nodeId } : {}), ...(origin.url ? { url: origin.url } : {}), ...figmaNodes(d) };\n const r = await input.writeTokens({ edits: plan.edits, title: figmaBranchTitle(d), summary: d.summary.trim() || d.title, bodyExtra: [figmaOriginSection(origin)], mode, figma });\n await gh.addLabels(r.number, [FROM_FIGMA_LABEL]);\n if (r.status === 'suggested') return { status: 'suggested', plan, link: null, suggestion: { route: 'token-change', number: r.number, url: r.url } };\n return { status: 'opened', plan, link: { route: 'token-change', number: r.number, url: r.url, branch: r.branch } };\n }\n if (mode === 'suggest') {\n const sha = input.baseSha ?? (await gh.getBranchSha(input.base));\n if (!sha) throw new GitHubError(404, `Branch ${input.base} not found. Check the default branch in bridge.config.json.`);\n const payload = componentSpecSuggestionPayload(d, plan, { base: { ref: input.base, sha }, suggestedBy: input.suggestedBy });\n const created = await createSuggestionOnGitHub(gh, payload, { labels: [...(input.labels ?? []), WAITING_FOR_CLAUDE_LABEL] });\n return { status: 'suggested', plan, link: null, suggestion: { route: 'claude-draft', number: created.number, url: created.url } };\n }\n const spec = figmaSpecPath(d);\n const o: FigmaOrigin = { ...origin, spec, status: 'spec' };\n let branch = `${input.branchPrefix}figma-${figmaSpecSlug(d)}`;\n for (let i = 2; await gh.getBranchSha(branch).then(Boolean, () => false); i++) branch = `${input.branchPrefix}figma-${figmaSpecSlug(d)}-${i}`;\n await gh.commitToNewBranch({\n base: input.base,\n branch,\n message: `chore(figma): spec for ${figmaBranchTitle(d)}\\n\\nSent from Figma with ${input.tool ?? 'the DS Bridge Figma plugin'}. Claude AI drafts the code on this branch; a person reviews it.`,\n files: [{ path: spec, content: formatFigmaSpec(d, plan) }],\n });\n const pr = await gh.createPullRequest({ base: input.base, head: branch, title: figmaBranchTitle(d), body: figmaDraftBody(d, plan, o), draft: true });\n await gh.addLabels(pr.number, [...new Set([...(input.labels ?? []), FROM_FIGMA_LABEL, REQUEST_LABEL, WAITING_FOR_CLAUDE_LABEL])]);\n return { status: 'opened', plan, link: { route: 'claude-draft', number: pr.number, url: pr.url, branch } };\n}\n\nexport interface FigmaChangeRow {\n number: number;\n title: string;\n url: string;\n branch: string;\n origin: FigmaOrigin;\n status: FigmaPushStatus;\n}\n\n/** Library branches opened from Figma components (label from-figma), newest first, with where each stands. */\nexport async function listFigmaChangesOnGitHub(gh: GitHubClient, opts: { state?: 'open' | 'closed' | 'all' } = {}): Promise<FigmaChangeRow[]> {\n const pulls = await gh.listPullRequests(opts.state ?? 'open');\n const out: FigmaChangeRow[] = [];\n for (const p of pulls) {\n if (!p.labels.includes(FROM_FIGMA_LABEL)) continue;\n const origin = parseFigmaOrigin(p.body);\n if (!origin) continue;\n out.push({ number: p.number, title: p.title, url: p.url, branch: p.headRef, origin, status: figmaPushStatus({ state: p.state, draft: p.draft, labels: p.labels, route: origin.route }) });\n }\n return out;\n}\n\n/** One library branch from Figma, its spec and Claude's brief to draft the code. */\nexport async function figmaChangeOnGitHub(gh: GitHubClient, n: number, opts: { componentsDir?: string | undefined } = {}) {\n const pull = await gh.getPullRequest(n);\n const origin = parseFigmaOrigin(pull.body);\n if (!origin) throw new GitHubError(404, `#${n} was not sent from Figma (no \"From Figma\" block in its description).`);\n const status = figmaPushStatus({ state: pull.state, draft: pull.draft, labels: pull.labels, route: origin.route });\n if (origin.route === 'token-change') return { pull, origin, status, spec: undefined, brief: undefined };\n const text = origin.spec ? await gh.getFileText(origin.spec, pull.headSha).catch(() => undefined) : undefined;\n const spec = parseFigmaSpec(text);\n if (!spec) throw new GitHubError(404, `The spec ${origin.spec ?? FIGMA_SPEC_DIR} is missing from ${pull.headRef}. Send the component from Figma again.`);\n const brief = figmaDraftBrief(spec, { pr: n, branch: pull.headRef, specPath: origin.spec!, componentsDir: opts.componentsDir });\n return { pull, origin, status, spec, brief };\n}\n\n/**\n * Claude wrote the code: the branch is labelled drafted by Claude AI (no longer waiting) and its description says so.\n * Refused while the branch only carries the spec, so the label never claims code that is not there.\n */\nexport async function markFigmaChangeDraftedOnGitHub(gh: GitHubClient, n: number): Promise<{ status: FigmaPushStatus; files: string[] }> {\n if (!gh.canWrite) throw new GitHubError(401, 'Marking a branch drafted needs a GitHub token (pull requests: write).');\n const pull = await gh.getPullRequest(n);\n const origin = parseFigmaOrigin(pull.body);\n if (!origin || origin.route !== 'claude-draft') throw new GitHubError(422, `#${n} is not a Claude draft branch from Figma.`);\n if (pull.state !== 'open') throw new GitHubError(422, `#${n} is ${pull.state}: only an open branch is marked drafted.`);\n const files = (await gh.listPullRequestFiles(n)).map((f) => f.filename).filter((f) => !f.startsWith(`${FIGMA_SPEC_DIR}/`));\n if (!files.length) throw new GitHubError(422, `${pull.headRef} only carries the spec: write the component code there first, push it, then mark it drafted.`);\n await gh.updatePullRequest(n, { body: withFigmaOrigin(pull.body, { ...origin, status: 'drafted' }) });\n await gh.removeLabel(n, WAITING_FOR_CLAUDE_LABEL).catch(() => undefined);\n await gh.addLabels(n, [DRAFTED_BY_CLAUDE_LABEL]);\n const labels = [...pull.labels.filter((l) => l !== WAITING_FOR_CLAUDE_LABEL), DRAFTED_BY_CLAUDE_LABEL];\n return { status: figmaPushStatus({ state: pull.state, labels, route: origin.route }), files };\n}\n\n/** Where each pushed Figma component's library branch stands (by pull request number), for the plugin's Pull. */\nexport async function figmaPushStatusesOnGitHub(gh: GitHubClient, numbers: number[]): Promise<Map<number, FigmaPushStatus>> {\n const out = new Map<number, FigmaPushStatus>();\n await Promise.all(\n [...new Set(numbers)].map(async (n) => {\n try {\n const p = await gh.getPullRequest(n);\n out.set(n, figmaPushStatus({ state: p.state, draft: p.draft, labels: p.labels, route: parseFigmaOrigin(p.body)?.route }));\n } catch {\n // Unreadable: the component keeps its Figma version until the next pull reads it.\n }\n }),\n );\n return out;\n}\n","// Reading a deployed (or built) Storybook: its index, grouped into components, and the URLs that show a story.\n// Pure parsing plus one fetch helper over an injected fetch. No DOM, no Node APIs.\n//\n// Index formats:\n// index.json, v4 (Storybook 7) and v5 (8+): { v, entries: { [id]: { id, title, name, type, importPath, tags?, subtype?, exportName?, componentPath? } } }\n// stories.json, v3 (6.4/6.5 with buildStoriesJson, still emitted by some 7 builds):\n// { v, stories: { [id]: { id, title?, kind, name?, story, importPath, parameters?: { docsOnly? } } } }\n\n/** One index entry, normalised across versions. */\nexport interface StorybookEntry {\n id: string;\n /** Sidebar path, `/`-separated (\"Forms/Button\"). */\n title: string;\n /** Story or docs page name (\"Primary\", \"Docs\"). */\n name: string;\n type: 'story' | 'docs';\n /** Storybook 9+ marks test entries `test`; stories are `story`. Absent before. */\n subtype?: string;\n importPath: string;\n tags: string[];\n exportName?: string;\n componentPath?: string;\n}\n\n/** Entries that share a title: one component (or one docs-only page such as \"Intro\"). */\nexport interface StorybookComponent {\n title: string;\n /** Last segment of the title (\"Button\" for \"Forms/Button\"). */\n name: string;\n /** Segments before the name ([\"Forms\"]); empty at the root. */\n group: string[];\n /** Story entries in index order (test entries excluded). */\n stories: StorybookEntry[];\n docs: StorybookEntry[];\n /** Union of the entries' tags, sorted. */\n tags: string[];\n}\n\nexport type StorybookIndexSource = 'index.json' | 'stories.json';\n\nexport interface StorybookIndex {\n /** The index's `v` field. */\n version: number;\n source: StorybookIndexSource;\n entries: StorybookEntry[];\n /** Grouped by title, sorted by title. */\n components: StorybookComponent[];\n}\n\nexport type StorybookErrorCode = 'invalid-url' | 'not-found' | 'not-json' | 'private' | 'empty' | 'http' | 'network';\n\nexport class StorybookIndexError extends Error {\n constructor(\n readonly code: StorybookErrorCode,\n message: string,\n readonly status?: number,\n ) {\n super(message);\n this.name = 'StorybookIndexError';\n }\n}\n\nconst isObj = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);\nconst str = (v: unknown): string | undefined => (typeof v === 'string' && v.trim() ? v : undefined);\n\nfunction entryFrom(key: string, raw: unknown, v3: boolean): StorybookEntry | null {\n if (!isObj(raw)) return null;\n const id = str(raw.id) ?? key;\n const title = str(raw.title) ?? str(raw.kind);\n const name = str(raw.name) ?? str(raw.story);\n if (!id || !title || !name) return null;\n const params = isObj(raw.parameters) ? raw.parameters : {};\n const type: 'story' | 'docs' = raw.type === 'docs' || raw.type === 'story' ? raw.type : v3 && params.docsOnly === true ? 'docs' : 'story';\n const e: StorybookEntry = {\n id,\n title,\n name,\n type,\n importPath: str(raw.importPath) ?? str(params.fileName) ?? '',\n tags: Array.isArray(raw.tags) ? raw.tags.filter((t): t is string => typeof t === 'string') : [],\n };\n const subtype = str(raw.subtype);\n if (subtype) e.subtype = subtype;\n const exportName = str(raw.exportName);\n if (exportName) e.exportName = exportName;\n const componentPath = str(raw.componentPath);\n if (componentPath) e.componentPath = componentPath;\n return e;\n}\n\n/** Groups entries by title. Test entries (subtype `test`) stay out of `stories`. */\nexport function groupStorybookComponents(entries: StorybookEntry[]): StorybookComponent[] {\n const byTitle = new Map<string, StorybookComponent>();\n for (const e of entries) {\n let c = byTitle.get(e.title);\n if (!c) {\n const parts = e.title.split('/').map((p) => p.trim()).filter(Boolean);\n c = { title: e.title, name: parts[parts.length - 1] ?? e.title, group: parts.slice(0, -1), stories: [], docs: [], tags: [] };\n byTitle.set(e.title, c);\n }\n if (e.type === 'docs') c.docs.push(e);\n else if (e.subtype !== 'test') c.stories.push(e);\n for (const t of e.tags) if (!c.tags.includes(t)) c.tags.push(t);\n }\n const out = [...byTitle.values()].filter((c) => c.stories.length || c.docs.length);\n for (const c of out) c.tags.sort();\n return out.sort((a, b) => a.title.localeCompare(b.title));\n}\n\n/**\n * Parses an `index.json` (v4, v5) or `stories.json` (v3) body. Throws StorybookIndexError: `private` for a\n * Chromatic login answer, `empty` when the body has no readable entries.\n */\nexport function parseStorybookIndex(json: unknown, source?: StorybookIndexSource): StorybookIndex {\n if (!isObj(json)) throw new StorybookIndexError('not-json', 'The Storybook index is not a JSON object.');\n if (typeof json.loginUrl === 'string' && !('entries' in json) && !('stories' in json)) {\n throw new StorybookIndexError('private', 'This Storybook is private: it asks for a sign-in before showing its index.');\n }\n const map = isObj(json.entries) ? json.entries : isObj(json.stories) ? json.stories : null;\n if (!map) throw new StorybookIndexError('empty', 'This file has no Storybook entries.');\n const v3 = !isObj(json.entries);\n const entries = Object.entries(map)\n .map(([k, raw]) => entryFrom(k, raw, v3))\n .filter((e): e is StorybookEntry => e !== null);\n if (!entries.length) throw new StorybookIndexError('empty', 'This Storybook index lists no stories or docs.');\n const version = typeof json.v === 'number' ? json.v : v3 ? 3 : 4;\n return { version, source: source ?? (v3 ? 'stories.json' : 'index.json'), entries, components: groupStorybookComponents(entries) };\n}\n\n/**\n * The base address of a Storybook from what a person pastes: trims, drops the query and hash\n * (`?path=/story/...`), a trailing `index.html` / `iframe.html` / `index.json` / `stories.json`, and trailing slashes.\n * Throws `invalid-url` unless it is http(s); https is required except on localhost.\n */\nexport function normalizeStorybookUrl(input: string): string {\n let u: URL;\n try {\n u = new URL(input.trim());\n } catch {\n throw new StorybookIndexError('invalid-url', 'Enter the full Storybook address, for example https://storybook.example.com');\n }\n const local = u.hostname === 'localhost' || u.hostname === '127.0.0.1' || u.hostname === '[::1]';\n if (u.protocol !== 'https:' && !(u.protocol === 'http:' && local)) {\n throw new StorybookIndexError('invalid-url', 'The Storybook address must start with https://');\n }\n if (u.username || u.password) throw new StorybookIndexError('invalid-url', 'Remove the user name and password from the address.');\n const path = u.pathname.replace(/\\/(index\\.html|iframe\\.html|index\\.json|stories\\.json)$/i, '/').replace(/\\/+$/, '');\n return `${u.protocol}//${u.host}${path}`;\n}\n\n/** The index files to try, in order. */\nexport const storybookIndexUrls = (base: string): { url: string; source: StorybookIndexSource }[] => {\n const b = base.replace(/\\/+$/, '');\n return [\n { url: `${b}/index.json`, source: 'index.json' },\n { url: `${b}/stories.json`, source: 'stories.json' },\n ];\n};\n\nexport interface StorybookIframeOptions {\n /** `story` (default) or `docs`. */\n viewMode?: 'story' | 'docs';\n /** Toolbar globals (`globals=brand:ocean;theme:dark`), in insertion order. */\n globals?: Record<string, string>;\n /** Story args (`args=label:Save`). */\n args?: Record<string, string>;\n}\n\n// Storybook reads `key:value;key:value`; keep the separators literal and encode the rest.\nconst pairs = (o: Record<string, string>) =>\n Object.entries(o)\n .map(([k, v]) => `${encodeURIComponent(k)}:${encodeURIComponent(v)}`)\n .join(';');\n\n/** URL of one story (or docs page) rendered alone: `<base>/iframe.html?id=<id>&viewMode=story[&globals=..][&args=..]`. */\nexport function storybookIframeUrl(base: string, id: string, o: StorybookIframeOptions = {}): string {\n let url = `${base.replace(/\\/+$/, '')}/iframe.html?id=${encodeURIComponent(id)}&viewMode=${o.viewMode ?? 'story'}`;\n if (o.globals && Object.keys(o.globals).length) url += `&globals=${pairs(o.globals)}`;\n if (o.args && Object.keys(o.args).length) url += `&args=${pairs(o.args)}`;\n return url;\n}\n\n/** URL of a story or docs page in the full Storybook UI (sidebar and toolbar). */\nexport function storybookManagerUrl(base: string, id: string, viewMode: 'story' | 'docs' = 'story'): string {\n return `${base.replace(/\\/+$/, '')}/?path=/${viewMode}/${encodeURIComponent(id)}`;\n}\n\nexport type StorybookFetch = (url: string, init?: { headers?: Record<string, string>; signal?: AbortSignal }) => Promise<{\n ok: boolean;\n status: number;\n headers: { get(name: string): string | null };\n text(): Promise<string>;\n}>;\n\nexport interface FetchStorybookIndexOptions {\n fetch?: StorybookFetch;\n signal?: AbortSignal;\n}\n\n/**\n * Reads a Storybook's index: `index.json`, then `stories.json`. A 404, an HTML answer (static hosts that fall back\n * to index.html) or a body without entries moves on to the next file; the first readable index wins. Throws\n * StorybookIndexError with the most telling failure (`private` before `not-json` before `not-found`).\n */\nexport async function fetchStorybookIndex(base: string, o: FetchStorybookIndexOptions = {}): Promise<StorybookIndex> {\n const doFetch: StorybookFetch = o.fetch ?? ((url, init) => fetch(url, init));\n const rank: Record<StorybookErrorCode, number> = { private: 6, http: 5, network: 4, empty: 3, 'not-json': 2, 'not-found': 1, 'invalid-url': 0 };\n let worst: StorybookIndexError | null = null;\n const keep = (e: StorybookIndexError) => {\n if (!worst || rank[e.code] > rank[worst.code]) worst = e;\n };\n for (const { url, source } of storybookIndexUrls(base)) {\n let res: Awaited<ReturnType<StorybookFetch>>;\n try {\n res = await doFetch(url, { headers: { accept: 'application/json' }, ...(o.signal ? { signal: o.signal } : {}) });\n } catch (err) {\n if (o.signal?.aborted) throw err;\n keep(new StorybookIndexError('network', `Could not reach ${url}. The host may be down or may not allow reading from another site.`));\n continue;\n }\n if (res.status === 404 || res.status === 410) {\n keep(new StorybookIndexError('not-found', `No Storybook index at ${base}: neither index.json nor stories.json was found.`, res.status));\n continue;\n }\n if (res.status === 401 || res.status === 403) {\n keep(new StorybookIndexError('private', 'This Storybook is private: it asks for a sign-in before showing its index.', res.status));\n continue;\n }\n if (!res.ok) {\n keep(new StorybookIndexError('http', `The Storybook host answered ${res.status} for ${url}.`, res.status));\n continue;\n }\n const text = await res.text();\n let json: unknown;\n try {\n json = JSON.parse(text);\n } catch {\n keep(new StorybookIndexError('not-json', `${url} is not a Storybook index (the host answered with a web page).`));\n continue;\n }\n try {\n return parseStorybookIndex(json, source);\n } catch (err) {\n if (err instanceof StorybookIndexError) keep(err);\n else throw err;\n }\n }\n throw worst ?? new StorybookIndexError('not-found', `No Storybook index at ${base}.`);\n}\n","// Token rows for documentation pages: one record per token with the full alias chain\n// (component -> semantic -> brand palette role -> primitive -> resolved value), per brand x theme (and density).\n// Moved from the docs site (apps/docs-site/src/lib/tokens.ts) so the build and the browser share one reader.\n// Every folder comes from bridge.config.json (tokens.root and the tier folders), never from a hardcoded path.\n// Resolution order mirrors packages/tokens/build.mjs. Pure: takes file bodies, reads nothing itself.\n\nimport { tokensPath, type BridgeConfig } from './config';\n\n/** Token tiers of the rows, in resolution order: primitive <- brand <- semantic <- component. Density sits beside semantic. */\nexport type TokenRowTier = 'primitive' | 'brand' | 'semantic' | 'density' | 'component';\n\ntype Json = Record<string, unknown>;\n\nexport interface RawTokenEntry {\n path: string[];\n type: string;\n value: unknown;\n description?: string;\n /** DTCG $deprecated: true, or a string explaining what to use instead. */\n deprecated?: boolean | string;\n /** Repo-relative file the token is declared in. */\n file: string;\n}\n\nexport interface PrimitiveRow {\n path: string;\n segments: string[];\n type: string;\n /** Resolved CSS value. */\n css: string;\n hex?: string;\n cssVar: string;\n figma: string;\n description?: string;\n deprecated?: boolean | string;\n raw: unknown;\n file: string;\n}\n\nexport interface TokenRowMode {\n /** First alias target, or null when the value is literal. */\n alias: string | null;\n /** Every alias hop, from the token to the final primitive (palette roles included). */\n chain: string[];\n css: string;\n hex?: string;\n}\n\nexport interface TokenRow {\n path: string;\n segments: string[];\n type: string;\n cssVar: string;\n figma: string;\n description?: string;\n /** e.g. \"color.action\" or \"elevation\". */\n group: string;\n deprecated?: boolean | string;\n tier: Exclude<TokenRowTier, 'primitive'>;\n /** Source file(s) the token is declared in, repo-relative. */\n file: string;\n /** Values per theme in the default brand and default density. */\n modes: Record<string, TokenRowMode>;\n /** Values per brand x theme (default density). */\n brands: Record<string, Record<string, TokenRowMode>>;\n /** Density tokens only: value per density. */\n densities?: Record<string, TokenRowMode>;\n /** True when the brand x theme values differ from the default brand. */\n brandSpecific: boolean;\n}\n\n/** Brand, theme and density lists the rows are computed for, with their defaults and display names. */\nexport interface TokenRowAxes {\n brands: string[];\n defaultBrand: string;\n /** Display name per brand: the name a brand file records ($extensions dev.bridge.brand.name), else the slug in title case. */\n brandLabels: Record<string, string>;\n themes: string[];\n densities: string[];\n defaultDensity: string;\n}\n\n/** Repo-relative token files the rows read, from the tier folders of the config. */\nexport interface TokenRowFiles {\n primitivesDir: string;\n semanticDir: string;\n brandsDir: string;\n densityDir: string;\n componentsDir: string;\n baseFile: string;\n semanticFile(theme: string): string;\n brandFile(brand: string): string;\n overrideFile(brand: string, theme: string): string;\n densityFile(density: string): string;\n}\n\nexport interface TokenRows extends TokenRowAxes {\n primitives: PrimitiveRow[];\n /** Semantic tier: themed (one file per theme) and theme-independent (base). */\n semantic: TokenRow[];\n /** Brand tier: palette, radius and font roles per brand. */\n brand: TokenRow[];\n density: TokenRow[];\n component: TokenRow[];\n /** Every non-primitive token: brand, semantic, density, component. */\n all: TokenRow[];\n /** Repo-relative paths of every token source file, in tier order (what the \"last updated\" line watches). */\n sources: string[];\n}\n\n// Today's values, used when bridge.config.json names no axis (the docs site's fallbacks).\nconst FALLBACK_BRANDS = ['bridge', 'ocean'];\nconst FALLBACK_THEMES = ['light', 'dark'];\nconst FALLBACK_DENSITIES = ['comfortable', 'compact'];\n\n/** Brand, theme and density lists from bridge.config.json, as the docs pages iterate them. */\nexport function tokenRowAxes(config: BridgeConfig, readText: (path: string) => string | undefined = () => undefined): TokenRowAxes {\n const brandAxis = config.axes.brand;\n const brands = brandAxis?.values.length ? [...brandAxis.values] : [...FALLBACK_BRANDS];\n const defaultBrand = brandAxis?.default ?? brands[0]!;\n const themes = config.modes.themes.length ? [...config.modes.themes] : [...FALLBACK_THEMES];\n const densities = config.modes.densities.length ? [...config.modes.densities] : [...FALLBACK_DENSITIES];\n const files = tokenRowFiles(config);\n const brandName = (b: string): string => {\n try {\n const text = readText(files.brandFile(b));\n const name = text ? (JSON.parse(text) as { $extensions?: Record<string, { name?: unknown }> }).$extensions?.['dev.bridge.brand']?.name : undefined;\n if (typeof name === 'string' && name) return name;\n } catch {\n /* unreadable brand file: fall back to the slug */\n }\n return b\n .split('-')\n .map((w) => w.charAt(0).toUpperCase() + w.slice(1))\n .join(' ');\n };\n return {\n brands,\n defaultBrand,\n brandLabels: Object.fromEntries(brands.map((b) => [b, brandName(b)])),\n themes,\n densities,\n defaultDensity: config.modes.defaults.density ?? densities[0]!,\n };\n}\n\n/** The token files of each tier, repo-relative, from the config's tokens.root and tier folders. */\nexport function tokenRowFiles(config: BridgeConfig): TokenRowFiles {\n const t = config.tokens;\n const at = (rel: string) => tokensPath(config, rel);\n return {\n primitivesDir: at(t.primitives),\n semanticDir: at(t.semantic),\n brandsDir: at(t.brands),\n densityDir: at(t.density),\n componentsDir: at(t.components),\n baseFile: at(`${t.semantic}/${t.base}.tokens.json`),\n semanticFile: (theme) => at(`${t.semantic}/${theme}.tokens.json`),\n brandFile: (brand) => at(`${t.brands}/${brand}.tokens.json`),\n overrideFile: (brand, theme) => at(`${t.brands}/${brand}.${theme}.tokens.json`),\n densityFile: (density) => at(`${t.density}/${density}.tokens.json`),\n };\n}\n\n/** Flattens one DTCG document into raw tokens, inheriting $type from groups. */\nexport function flattenTokenFile(node: Json, file: string, path: string[] = [], inheritedType = ''): RawTokenEntry[] {\n const type = (node.$type as string) ?? inheritedType;\n if ('$value' in node) {\n return [\n {\n path,\n type,\n value: node.$value,\n description: node.$description as string | undefined,\n deprecated: node.$deprecated as boolean | string | undefined,\n file,\n },\n ];\n }\n const out: RawTokenEntry[] = [];\n for (const [key, child] of Object.entries(node)) {\n if (key.startsWith('$') || typeof child !== 'object' || child === null) continue;\n out.push(...flattenTokenFile(child as Json, file, [...path, key], type));\n }\n return out;\n}\n\nconst toHex2 = (n: number) =>\n Math.round(n * 255)\n .toString(16)\n .padStart(2, '0');\n\nfunction colorCss(c: unknown): { css: string; hex?: string } {\n if (typeof c === 'string') return { css: c, hex: /^#[0-9a-f]{6}$/i.test(c) ? c.toLowerCase() : undefined };\n const v = c as { components: number[]; alpha?: number; hex?: string };\n const [r = 0, g = 0, b = 0] = v.components;\n const hex = (v.hex ?? `#${[r, g, b].map(toHex2).join('')}`).toLowerCase();\n const alpha = v.alpha ?? 1;\n if (alpha < 1) return { css: `rgb(${[r, g, b].map((x) => Math.round(x * 255)).join(' ')} / ${alpha})`, hex };\n return { css: hex, hex };\n}\n\nconst dimCss = (d: unknown) => (typeof d === 'object' && d !== null ? `${(d as { value: number }).value}${(d as { unit: string }).unit}` : String(d));\n\nfunction shadowCss(s: unknown): string {\n if (typeof s === 'string') return s;\n const layers = (Array.isArray(s) ? s : [s]) as Array<Record<string, unknown>>;\n return layers\n .map((l) => [l.inset ? 'inset' : '', dimCss(l.offsetX), dimCss(l.offsetY), dimCss(l.blur), dimCss(l.spread), colorCss(l.color).css].filter(Boolean).join(' '))\n .join(', ');\n}\n\n/** CSS text (and hex for colors) of a literal DTCG value. */\nexport function tokenValueCss(type: string, value: unknown): { css: string; hex?: string } {\n switch (type) {\n case 'color':\n return colorCss(value);\n case 'dimension':\n case 'duration':\n return { css: dimCss(value) };\n case 'shadow':\n return { css: shadowCss(value) };\n case 'cubicBezier':\n return { css: Array.isArray(value) ? `cubic-bezier(${value.join(', ')})` : String(value) };\n case 'fontFamily':\n return { css: Array.isArray(value) ? value.map((n) => (/\\s/.test(n) ? `\"${n}\"` : n)).join(', ') : String(value) };\n default:\n return { css: String(value) };\n }\n}\n\n/** CSS variable of a token path (\"color.bg.default\" segments -> \"--color-bg-default\"). */\nexport const tokenRowCssVar = (segments: string[]) => `--${segments.join('-')}`;\n/** Figma variable name of a token path. */\nexport const tokenRowFigmaName = (segments: string[]) => segments.join('/');\n\nconst isAlias = (v: unknown): v is string => typeof v === 'string' && /^\\{[^}]+\\}$/.test(v);\n\n/**\n * Builds the rows from the token files of a repo. `readText` returns a repo-relative file body (undefined when\n * missing); `listFiles` returns the repo-relative files directly inside a directory. Throws on an alias that does not\n * resolve and on a themed token missing from another theme, as the token build does.\n */\nexport function buildTokenRows(config: BridgeConfig, readText: (path: string) => string | undefined, listFiles: (dir: string) => string[]): TokenRows {\n const axes = tokenRowAxes(config, readText);\n const { brands: BRANDS, defaultBrand: DEFAULT_BRAND, themes: MODES, densities: DENSITIES, defaultDensity: DEFAULT_DENSITY } = axes;\n const files = tokenRowFiles(config);\n const REF_THEME = MODES[0]!;\n\n const jsonFiles = (dir: string) =>\n listFiles(dir)\n .filter((f) => f.endsWith('.tokens.json'))\n .sort();\n const flatCache = new Map<string, RawTokenEntry[]>();\n const flatFile = (f: string): RawTokenEntry[] => {\n if (!flatCache.has(f)) {\n const text = readText(f);\n flatCache.set(f, text === undefined ? [] : flattenTokenFile(JSON.parse(text) as Json, f));\n }\n return flatCache.get(f)!;\n };\n const byPathOf = (tokens: RawTokenEntry[]) => new Map(tokens.map((t) => [t.path.join('.'), t]));\n\n const primitiveFiles = jsonFiles(files.primitivesDir);\n const componentFiles = jsonFiles(files.componentsDir);\n const sources = [\n ...primitiveFiles,\n ...jsonFiles(files.brandsDir),\n ...MODES.map(files.semanticFile),\n files.baseFile,\n ...jsonFiles(files.densityDir),\n ...componentFiles,\n ];\n\n const primitives: PrimitiveRow[] = primitiveFiles\n .flatMap((f) => flatFile(f))\n .map((t) => {\n const { css, hex } = tokenValueCss(t.type, t.value);\n return {\n path: t.path.join('.'),\n segments: t.path,\n type: t.type,\n css,\n hex,\n cssVar: tokenRowCssVar(t.path),\n figma: tokenRowFigmaName(t.path),\n description: t.description,\n deprecated: t.deprecated,\n raw: t.value,\n file: t.file,\n };\n });\n const primByPath = new Map(primitives.map((p) => [p.path, p]));\n\n const brandRaw = Object.fromEntries(BRANDS.map((b) => [b, flatFile(files.brandFile(b))]));\n const themeRaw = Object.fromEntries(MODES.map((m) => [m, flatFile(files.semanticFile(m))]));\n const baseRaw = flatFile(files.baseFile);\n const densityRaw = Object.fromEntries(DENSITIES.map((d) => [d, flatFile(files.densityFile(d))]));\n const componentRaw = componentFiles.flatMap((f) => flatFile(f));\n\n // Lookup layers for one combination, highest priority first (mirrors packages/tokens/build.mjs).\n const layerCache = new Map<string, Map<string, RawTokenEntry>[]>();\n const layers = (b: string, m: string, d: string) => {\n const k = `${b}.${m}.${d}`;\n if (!layerCache.has(k))\n layerCache.set(k, [\n byPathOf(flatFile(files.overrideFile(b, m))),\n byPathOf(themeRaw[m] ?? []),\n byPathOf(baseRaw),\n byPathOf(densityRaw[d] ?? []),\n byPathOf(componentRaw),\n byPathOf(brandRaw[b] ?? []),\n ]);\n return layerCache.get(k)!;\n };\n\n const resolve = (b: string, m: string, d: string, value: unknown, type: string): TokenRowMode => {\n const chain: string[] = [];\n let current = value;\n let currentType = type;\n let guard = 0;\n while (isAlias(current) && guard++ < 30) {\n const target = current.slice(1, -1);\n chain.push(target);\n const prim = primByPath.get(target);\n if (prim) return { alias: chain[0] ?? null, chain, css: prim.css, hex: prim.hex };\n const hit = layers(b, m, d)\n .map((l) => l.get(target))\n .find(Boolean);\n if (!hit) throw new Error(`tokens: alias {${target}} does not resolve in ${b} ${m} ${d}`);\n current = hit.value;\n currentType = hit.type || currentType;\n }\n const { css, hex } = tokenValueCss(currentType, current);\n return { alias: chain[0] ?? null, chain, css, hex };\n };\n\n const same = (a: TokenRowMode, c: TokenRowMode) => a.css === c.css && a.chain.join() === c.chain.join();\n\n /** Builds one documented token. `valueFor` returns the raw token for a brand x theme (x density). */\n const build = (t: RawTokenEntry, tier: TokenRow['tier'], valueFor: (b: string, m: string, d: string) => RawTokenEntry | undefined): TokenRow => {\n const at = (b: string, m: string, d: string = DEFAULT_DENSITY) => {\n const raw = valueFor(b, m, d) ?? t;\n return resolve(b, m, d, raw.value, raw.type || t.type);\n };\n const brands = Object.fromEntries(BRANDS.map((b) => [b, Object.fromEntries(MODES.map((m) => [m, at(b, m)]))])) as Record<string, Record<string, TokenRowMode>>;\n return {\n path: t.path.join('.'),\n segments: t.path,\n type: t.type,\n cssVar: tokenRowCssVar(t.path),\n figma: tokenRowFigmaName(t.path),\n description: t.description,\n group: t.path[0] === 'color' ? t.path.slice(0, 2).join('.') : t.path[0]!,\n deprecated: t.deprecated,\n tier,\n file: t.file,\n modes: brands[DEFAULT_BRAND]!,\n brands,\n densities: tier === 'density' ? Object.fromEntries(DENSITIES.map((d) => [d, at(DEFAULT_BRAND, REF_THEME, d)])) : undefined,\n brandSpecific: BRANDS.some((b) => MODES.some((m) => !same(brands[b]![m]!, brands[DEFAULT_BRAND]![m]!))),\n };\n };\n\n const brand = (brandRaw[DEFAULT_BRAND] ?? []).map((t) => build(t, 'brand', (b) => byPathOf(brandRaw[b] ?? []).get(t.path.join('.'))));\n\n // Themed semantic tokens: the first theme is the reference, every other theme must define the same paths.\n const themedBy = Object.fromEntries(MODES.map((m) => [m, byPathOf(themeRaw[m] ?? [])]));\n const themed = (themeRaw[REF_THEME] ?? []).map((t) => {\n const path = t.path.join('.');\n const others = MODES.slice(1).map((m) => {\n const hit = themedBy[m]!.get(path);\n if (!hit) throw new Error(`tokens: semantic token ${path} is missing in ${files.semanticFile(m)}`);\n return hit;\n });\n const s = build(t, 'semantic', (b, m) => byPathOf(flatFile(files.overrideFile(b, m))).get(path) ?? (m === REF_THEME ? t : themedBy[m]!.get(path)));\n s.description = [t, ...others].map((x) => x.description).find((x) => x !== undefined);\n s.deprecated = [t, ...others].map((x) => x.deprecated).find((x) => x !== undefined);\n s.file = MODES.map(files.semanticFile).join(', ');\n return s;\n });\n const base = baseRaw.map((t) => build(t, 'semantic', () => t));\n const semantic = [...themed, ...base];\n\n const density = (densityRaw[DEFAULT_DENSITY] ?? []).map((t) => build(t, 'density', (_b, _m, d) => byPathOf(densityRaw[d] ?? []).get(t.path.join('.'))));\n const component = componentRaw.map((t) => build(t, 'component', () => t));\n\n return { ...axes, primitives, semantic, brand, density, component, all: [...brand, ...semantic, ...density, ...component], sources };\n}\n\n/** Every CSS variable the rows define: cssVar -> token path, tier and type. */\nexport function tokenRowIndex(rows: Pick<TokenRows, 'primitives' | 'all'>): Map<string, { path: string; kind: TokenRowTier; type: string }> {\n const map = new Map<string, { path: string; kind: TokenRowTier; type: string }>();\n for (const p of rows.primitives) map.set(p.cssVar, { path: p.path, kind: 'primitive', type: p.type });\n for (const s of rows.all) map.set(s.cssVar, { path: s.path, kind: s.tier, type: s.type });\n return map;\n}\n","// WCAG 2.2 contrast of the foreground/background pairs the token build gates on (bridge.config.json contrast.path),\n// for every brand x theme of the token rows, so pages show exactly what the build enforces. Moved from the docs site\n// (apps/docs-site/src/lib/contrast.ts). Pure: takes the checks file text and the rows.\n\nimport type { TokenRow, TokenRows } from './token-rows';\n\nexport interface ContrastPairSpec {\n fg: string;\n bg: string;\n usage: 'text' | 'ui';\n /** Minimum ratio the build enforces for this pair. */\n min: number;\n}\n\nexport interface ContrastModeResult {\n fgHex: string;\n bgHex: string;\n /** Rounded down to 2 decimals, so 4.496 never displays as a passing 4.50. */\n ratio: number;\n aa: boolean;\n /** null when AAA is not defined (non-text UI). */\n aaa: boolean | null;\n}\n\nexport interface ContrastPairResult extends ContrastPairSpec {\n fgToken: TokenRow;\n bgToken: TokenRow;\n /** Default brand, per theme. */\n modes: Record<string, ContrastModeResult>;\n brands: Record<string, Record<string, ContrastModeResult>>;\n}\n\n/** WCAG thresholds: body text 4.5:1 (AA) and 7:1 (AAA); UI parts and graphics 3:1 (AA, 1.4.11). */\nexport const CONTRAST_THRESHOLDS = { text: { aa: 4.5, aaa: 7 }, ui: { aa: 3, aaa: null } } as const;\n\nconst channel = (c: number) => {\n const s = c / 255;\n return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;\n};\n\n/** Relative luminance of a #rrggbb color. */\nexport function hexLuminance(hex: string): number {\n const n = parseInt(hex.slice(1), 16);\n return 0.2126 * channel((n >> 16) & 255) + 0.7152 * channel((n >> 8) & 255) + 0.0722 * channel(n & 255);\n}\n\n/** Contrast ratio of two opaque #rrggbb colors. */\nexport function hexContrastRatio(a: string, b: string): number {\n const [hi, lo] = [hexLuminance(a), hexLuminance(b)].sort((x, y) => y - x) as [number, number];\n return (hi + 0.05) / (lo + 0.05);\n}\n\n/** The pairs of a contrast checks file ({ \"pairs\": [[fg, bg, min] | { fg, bg, min }] }). Empty when there is no file. */\nexport function parseContrastSpecs(text: string | null | undefined): ContrastPairSpec[] {\n if (!text) return [];\n const data = JSON.parse(text) as { pairs?: Array<[string, string, number] | { fg: string; bg: string; min: number }> };\n return (data.pairs ?? []).map((p) => {\n const [fg, bg, min] = Array.isArray(p) ? p : [p.fg, p.bg, p.min];\n return { fg, bg, min, usage: min >= CONTRAST_THRESHOLDS.text.aa ? 'text' : 'ui' };\n });\n}\n\n/** Resolves pair specs against the token rows in every brand and theme. Throws on a pair naming a missing token. */\nexport function evaluateContrastPairs(specs: ContrastPairSpec[], rows: Pick<TokenRows, 'all' | 'brands' | 'themes' | 'defaultBrand'>): ContrastPairResult[] {\n const byPath = new Map(rows.all.map((s) => [s.path, s]));\n return specs.map((spec) => {\n const fgToken = byPath.get(spec.fg);\n const bgToken = byPath.get(spec.bg);\n if (!fgToken || !bgToken) throw new Error(`contrast: pair ${spec.fg} on ${spec.bg} references a token that does not exist`);\n const t = CONTRAST_THRESHOLDS[spec.usage];\n const result = (b: string, m: string): ContrastModeResult => {\n const fgHex = fgToken.brands[b]![m]!.hex!;\n const bgHex = bgToken.brands[b]![m]!.hex!;\n const r = hexContrastRatio(fgHex, bgHex);\n return { fgHex, bgHex, ratio: Math.floor(r * 100) / 100, aa: r >= spec.min, aaa: t.aaa === null ? null : r >= t.aaa };\n };\n const brands = Object.fromEntries(rows.brands.map((b) => [b, Object.fromEntries(rows.themes.map((m) => [m, result(b, m)]))])) as Record<string, Record<string, ContrastModeResult>>;\n return { ...spec, fgToken, bgToken, modes: brands[rows.defaultBrand]!, brands };\n });\n}\n","// Component data for docs, from the files that already sit next to each component (moved from the docs site,\n// apps/docs-site/src/lib/components.ts):\n// <Name>.tsx props, defaults, JSDoc, sub-components (regex parsers: React + TypeScript only)\n// <Name><styleSuffix> which tokens each part and state uses\n// <Name>.stories.tsx Storybook story ids for the live preview\n// <Name><docsSuffix> usage guidance a parser cannot know (written by designers)\n// The components folder, the suffixes and the barrel file come from bridge.config.json (components.*).\n// Pure: takes file bodies, reads nothing itself.\n\nimport type { ProseKey } from './docs-draft';\nimport type { TokenRowTier } from './token-rows';\n\nexport type ExampleNode = string | { c: string; p?: Record<string, unknown>; children?: ExampleNode[] };\n\nexport interface GuidanceItem {\n title: string;\n text: string;\n example?: ExampleNode;\n}\n\n/** <Name>.docs.json. */\nexport interface ComponentDocs {\n summary: string;\n /** Navigation group. Optional; components without one are listed under \"Core\". */\n category?: string;\n /** Lifecycle shown on the component page and in the nav: stable (default), beta, deprecated. */\n status?: 'stable' | 'beta' | 'deprecated';\n preview?: ExampleNode;\n whenToUse: string[];\n whenNotToUse: string[];\n dos: GuidanceItem[];\n donts: GuidanceItem[];\n accessibility: string[];\n contentGuidelines?: string[];\n anatomy?: Record<string, string>;\n /** \"claude\" when an AI drafted the prose (docs-draft Action, bridge_draft_docs). */\n draftedBy?: string;\n /** Prose sections Claude drafted that wait for review, when a draft covered only some (missing: the whole file). */\n draftedSections?: ProseKey[];\n /** True while drafted prose waits for a reviewer. */\n needsReview?: boolean;\n}\n\nexport interface ComponentProp {\n name: string;\n type: string;\n required: boolean;\n defaultValue?: string;\n description?: string;\n}\n\n/** What the scan knows about a CSS variable: the token it is, and an optional docs link (the caller's routing). */\nexport interface ComponentVar {\n name: string;\n href?: string;\n known: boolean;\n path?: string;\n kind?: TokenRowTier;\n}\n\nexport interface ComponentCssRule {\n selector: string;\n /** First class in the selector, used for the anatomy label. */\n className: string;\n label: string;\n vars: ComponentVar[];\n}\n\nexport interface ScannedComponent {\n name: string;\n slug: string;\n /** Repo-relative folder. */\n dir: string;\n /** Repo-relative files (they may not all exist). */\n files: { tsx: string; css: string; stories: string; docs: string };\n description?: string;\n props: ComponentProp[];\n inherits?: string;\n omitted: string[];\n subcomponents: string[];\n rules: ComponentCssRule[];\n tokensUsed: { name: string; href?: string; known: boolean; kind?: string }[];\n /** Paths of the tokens its own stylesheet reads, in every tier. */\n tokenPaths: string[];\n /**\n * Tokens it reads through another component's stylesheet it imports (IconButton imports Button.module.css), by\n * that component, without the ones its own stylesheet already reads. Followed transitively.\n */\n inherited: { from: string; slug: string; paths: string[] }[];\n /** Own and inherited token paths: what the component actually paints with. */\n allTokenPaths: string[];\n stories: { name: string; id: string }[];\n docs: ComponentDocs | null;\n /** Family from docs.json `category`, else from the grouped exports of the barrel file. */\n category: string;\n}\n\n/** \"IconButton\" -> \"icon-button\". */\nexport const componentSlug = (s: string) =>\n s\n .replace(/([a-z0-9])([A-Z])/g, '$1-$2')\n .replace(/([A-Z])([A-Z][a-z])/g, '$1-$2')\n .toLowerCase();\n\nconst escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n/**\n * Families in the order the barrel file lists them (\"// Actions\" then its exports). `componentsRel` is the components\n * folder relative to the barrel's folder (\"components\"); exports from elsewhere are not members.\n */\nexport function parseComponentFamilies(indexSrc: string, componentsRel = 'components'): { name: string; members: string[] }[] {\n const out: { name: string; members: string[] }[] = [];\n const exportRe = new RegExp(`export \\\\* from '\\\\./${escapeRe(componentsRel)}/(\\\\w+)'`);\n for (const line of indexSrc.split('\\n')) {\n const head = line.match(/^\\/\\/\\s*([A-Z][\\w ]+)$/);\n if (head) out.push({ name: head[1]!.trim(), members: [] });\n const exp = line.match(exportRe);\n if (exp && out.length) out[out.length - 1]!.members.push(exp[1]!);\n }\n return out.filter((f) => f.members.length);\n}\n\nconst NATIVE: Record<string, string> = {\n HTMLButtonElement: 'button',\n HTMLInputElement: 'input',\n HTMLSpanElement: 'span',\n HTMLDivElement: 'div',\n HTMLAnchorElement: 'a',\n};\n\nfunction parseExtends(clause: string) {\n const el = clause.match(/<(HTML\\w+Element)>/)?.[1];\n const omitted = [...(clause.match(/Omit<[^,]+,\\s*([^>]+)>/)?.[1] ?? '').matchAll(/'([^']+)'/g)].map((m) => m[1]!);\n return { inherits: el ? (NATIVE[el] ?? el) : undefined, omitted };\n}\n\n/** Props (with defaults and JSDoc), the native element it extends, its description and sub-components, from <Name>.tsx. */\nexport function parseComponentTsx(\n name: string,\n src: string,\n): { props: ComponentProp[]; inherits: string | undefined; omitted: string[]; description: string | undefined; subcomponents: string[] } {\n const aliases = new Map<string, string>();\n for (const m of src.matchAll(/export type (\\w+)\\s*=\\s*([^;]+);/g)) aliases.set(m[1]!, m[2]!.trim());\n\n let props: ComponentProp[] = [];\n let inherits: string | undefined;\n let omitted: string[] = [];\n\n const iface = src.match(new RegExp(`export interface ${name}Props(?:\\\\s+extends\\\\s+([^{]+))?\\\\s*\\\\{([\\\\s\\\\S]*?)\\\\n\\\\}`));\n if (iface) {\n ({ inherits, omitted } = parseExtends(iface[1] ?? ''));\n for (const m of iface[2]!.matchAll(/(?:\\/\\*\\*([\\s\\S]*?)\\*\\/\\s*)?(\\w+)(\\?)?:\\s*([^;]+);/g)) {\n const rawType = m[4]!.trim();\n props.push({\n name: m[2]!,\n type: aliases.get(rawType) ?? rawType,\n required: !m[3],\n description:\n m[1]\n ?.replace(/^\\s*\\*\\s?/gm, '')\n .replace(/\\s+/g, ' ')\n .trim() || undefined,\n });\n }\n } else {\n const alias = aliases.get(`${name}Props`);\n if (alias) ({ inherits, omitted } = parseExtends(alias));\n }\n\n // Defaults come from the destructuring in the component signature: `{ variant = 'primary', ... }`.\n const sig = src.match(new RegExp(`function ${name}\\\\(\\\\s*\\\\{([^}]*)\\\\}`));\n if (sig) {\n for (const m of sig[1]!.matchAll(/(\\w+)\\s*=\\s*('[^']*'|[\\w.]+)/g)) {\n const p = props.find((x) => x.name === m[1]);\n if (p) p.defaultValue = m[2];\n }\n }\n\n // The JSDoc block that ends right before the match: the last comment of what precedes it, only when it opens with\n // \"/**\". Matching the whole prefix used to start at the first JSDoc of the file, so the JSDoc of a props interface\n // and the code after it leaked into the component description.\n const docBefore = (re: RegExp) => {\n const idx = src.search(re);\n if (idx < 0) return undefined;\n const before = src.slice(0, idx).trimEnd();\n if (!before.endsWith('*/')) return undefined;\n const start = before.lastIndexOf('/*', before.length - 2);\n if (start < 0 || before[start + 2] !== '*') return undefined;\n return before\n .slice(start + 3, -2)\n .replace(/^\\s*\\*\\s?/gm, '')\n .replace(/\\s+/g, ' ')\n .trim();\n };\n const description = docBefore(new RegExp(`export (?:function|const) ${name}\\\\b`));\n const subcomponents = [...src.matchAll(/export function (\\w+)/g)].map((m) => m[1]!).filter((n) => n !== name);\n props = props.sort((a, b) => Number(b.required) - Number(a.required));\n return { props, inherits, omitted, description, subcomponents };\n}\n\nconst stateOf = (selector: string) => {\n const states = [\n [/:focus-visible/, 'focus'],\n [/:hover/, 'hover'],\n [/:disabled(?!,)|^[^(]*:disabled/, 'disabled'],\n [/\\[data-loading\\]/, 'loading'],\n [/::placeholder/, 'placeholder'],\n ] as const;\n const hit = states.filter(([re]) => re.test(selector)).map(([, s]) => s);\n return hit.length ? `, ${hit.join(' + ')}` : '';\n};\n\n/** CSS variables Base UI sets at runtime (positioning, measured heights, swipe) and private --_* locals. Not tokens. */\nconst BASE_UI_RUNTIME = /^--(_|accordion-panel-|collapsible-panel-|active-tab-|anchor-|available-|drawer-swipe-|toast-(frontmost-height|height|index|offset-y|swipe-)|transform-origin)/;\n\n/**\n * Minimal CSS reader: selector -> var(--*) list, labelled with the docs.json anatomy. Skips @keyframes, flattens\n * @media. `describe` says what a variable is (token path, tier, docs link); undefined: not a token.\n */\nexport function parseComponentCss(src: string, labels: Record<string, string>, describe: (cssVar: string) => Omit<ComponentVar, 'name' | 'known'> | undefined): ComponentCssRule[] {\n const clean = src.replace(/\\/\\*[\\s\\S]*?\\*\\//g, '');\n const rules: ComponentCssRule[] = [];\n const walk = (text: string, prefix = ''): void => {\n let i = 0;\n let buf = '';\n while (i < text.length) {\n const ch = text[i]!;\n if (ch === '{') {\n const head = buf.trim();\n buf = '';\n let depth = 1;\n const start = ++i;\n while (i < text.length && depth > 0) {\n if (text[i] === '{') depth++;\n else if (text[i] === '}') depth--;\n i++;\n }\n const inner = text.slice(start, i - 1);\n if (head.startsWith('@keyframes')) continue;\n if (head.startsWith('@')) {\n walk(inner, `${head} `);\n continue;\n }\n const names = [...new Set([...inner.matchAll(/var\\((--[\\w-]+)/g)].map((m) => m[1]!))].filter((n) => !BASE_UI_RUNTIME.test(n));\n if (!names.length) continue;\n const className = head.match(/\\.([\\w-]+)/)?.[1] ?? head;\n rules.push({\n selector: prefix + head.replace(/\\s+/g, ' '),\n className,\n label: (labels[className] ?? className) + stateOf(head),\n vars: names.map((n) => {\n const d = describe(n);\n return { name: n, href: d?.href, known: !!d, path: d?.path, kind: d?.kind };\n }),\n });\n } else {\n buf += ch;\n i++;\n }\n }\n };\n walk(clean);\n return rules;\n}\n\n/** Story names and Storybook ids of a <Name>.stories.tsx (CSF with a `title`). */\nexport function parseComponentStories(src: string): { name: string; id: string }[] {\n const title = src.match(/title:\\s*'([^']+)'/)?.[1];\n if (!title) return [];\n const base = title\n .split('/')\n .map((s) => componentSlug(s.trim()).replace(/\\s+/g, '-'))\n .join('-');\n return [...src.matchAll(/export const (\\w+):\\s*Story/g)].map((m) => ({ name: m[1]!, id: `${base}--${componentSlug(m[1]!)}` }));\n}\n\n/**\n * Fills `inherited` and `allTokenPaths` from the stylesheets each component imports from another component,\n * transitively (A imports B's stylesheet, B imports C's: A inherits from B and C). Removes `reuses`.\n */\nexport function resolveInheritedTokens(list: (Pick<ScannedComponent, 'name' | 'slug' | 'tokenPaths' | 'inherited' | 'allTokenPaths'> & { reuses?: string[] })[]): void {\n const byName = new Map(list.map((c) => [c.name, c]));\n for (const c of list) {\n const seen = new Set<string>([c.name]);\n const queue = [...(c.reuses ?? [])];\n const inherited: ScannedComponent['inherited'] = [];\n const taken = new Set(c.tokenPaths);\n while (queue.length) {\n const from = byName.get(queue.shift()!);\n if (!from || seen.has(from.name)) continue;\n seen.add(from.name);\n const paths = from.tokenPaths.filter((p) => !taken.has(p));\n paths.forEach((p) => taken.add(p));\n inherited.push({ from: from.name, slug: from.slug, paths });\n queue.push(...(from.reuses ?? []));\n }\n c.inherited = inherited;\n c.allTokenPaths = [...taken].sort();\n }\n for (const c of list) delete c.reuses;\n}\n\nexport interface ComponentScanInput {\n /** Components folder, repo-relative (bridge.config.json components.dir). */\n dir: string;\n /** Every repo-relative file under `dir` (RepoSource.list(dir)). */\n files: string[];\n /** Body of a repo-relative file, undefined when missing. */\n readText: (path: string) => string | undefined;\n /** Barrel file body (components.index), for families. Undefined: no families. */\n indexText?: string | undefined;\n /** Components folder relative to the barrel's folder. Default \"components\". */\n indexRel?: string;\n docsSuffix?: string;\n styleSuffix?: string;\n /** What a CSS variable is (token path, tier, docs link). Undefined: not a token. */\n describeVar: (cssVar: string) => Omit<ComponentVar, 'name' | 'known'> | undefined;\n /** Problems found (a docs.json that does not parse) are reported here instead of failing the scan. */\n problems?: string[];\n}\n\n/**\n * Every component of the folder: a sub-folder <Name> holding <Name>.tsx. Sorted by family (barrel order), then name.\n */\nexport function scanComponents(input: ComponentScanInput): ScannedComponent[] {\n const { dir, readText, describeVar } = input;\n const docsSuffix = input.docsSuffix ?? '.docs.json';\n const styleSuffix = input.styleSuffix ?? '.module.css';\n const fileSet = new Set(input.files);\n const has = (p: string) => fileSet.has(p);\n const fam = input.indexText === undefined ? [] : parseComponentFamilies(input.indexText, input.indexRel ?? 'components');\n const familyOf = (name: string) => fam.find((f) => f.members.includes(name))?.name;\n const names = [\n ...new Set(\n input.files\n .map((f) => (f.startsWith(`${dir}/`) ? f.slice(dir.length + 1).split('/') : []))\n .filter((parts) => parts.length === 2 && parts[1] === `${parts[0]}.tsx`)\n .map((parts) => parts[0]!),\n ),\n ].sort();\n const reuseRe = new RegExp(`from\\\\s+'\\\\.\\\\.\\\\/(\\\\w+)\\\\/(\\\\w+)${escapeRe(styleSuffix)}'`, 'g');\n\n const result = names.map((name) => {\n const folder = `${dir}/${name}`;\n const files = { tsx: `${folder}/${name}.tsx`, css: `${folder}/${name}${styleSuffix}`, stories: `${folder}/${name}.stories.tsx`, docs: `${folder}/${name}${docsSuffix}` };\n let docs: ComponentDocs | null = null;\n if (has(files.docs)) {\n try {\n docs = JSON.parse(readText(files.docs) ?? '') as ComponentDocs;\n } catch (err) {\n input.problems?.push(`${files.docs}: ${(err as Error).message}`);\n }\n }\n const tsxSrc = readText(files.tsx) ?? '';\n const tsx = parseComponentTsx(name, tsxSrc);\n // Another component's stylesheet imported as is: import buttonStyles from '../Button/Button.module.css'.\n const reuses = [...tsxSrc.matchAll(reuseRe)].filter((m) => m[1] === m[2] && m[1] !== name).map((m) => m[1]!);\n const cssText = has(files.css) ? readText(files.css) : undefined;\n const rules = cssText === undefined ? [] : parseComponentCss(cssText, docs?.anatomy ?? {}, describeVar);\n const used = [...new Set(rules.flatMap((r) => r.vars.map((v) => v.name)))].sort();\n const storiesText = has(files.stories) ? readText(files.stories) : undefined;\n return {\n name,\n slug: componentSlug(name),\n dir: folder,\n files,\n ...tsx,\n rules,\n tokensUsed: used.map((n) => {\n const d = describeVar(n);\n return { name: n, href: d?.href, known: !!d, kind: d?.kind };\n }),\n tokenPaths: [...new Set(used.flatMap((n) => describeVar(n)?.path ?? []))].sort(),\n inherited: [] as ScannedComponent['inherited'],\n allTokenPaths: [] as string[],\n reuses,\n stories: storiesText === undefined ? [] : parseComponentStories(storiesText),\n docs,\n category: docs?.category ?? familyOf(name) ?? 'Core',\n };\n });\n const order = (c: { category: string }) => {\n const i = fam.findIndex((f) => f.name === c.category);\n return i < 0 ? fam.length : i;\n };\n result.sort((a, b) => order(a) - order(b) || a.name.localeCompare(b.name));\n resolveInheritedTokens(result);\n return result as ScannedComponent[];\n}\n","// The repo model: everything the docs site and Studio read from a design system repo, computed from a RepoSource.\n// One function for the build (fsSource over the checkout) and the browser (a GitHub source over any team's repo):\n// bridge.config.json parsed once, the token rows, contrast results, the component scan (props, CSS tokens, stories,\n// docs.json) and the Figma coverage of component-specs.json. Every path comes from the config; the defaults are\n// the paths this repo used before the config named them. Pure: no Node, no DOM.\n\nimport { ConfigError, defineConfig, loadConfig, tokensPath, CONFIG_FILE, DEFAULT_CHANGES_MODE, DEFAULT_OVERRIDE, type BridgeConfig, type BridgeConfigInput, type ChangesMode } from './config';\nimport { scanComponents, parseComponentFamilies, type ScannedComponent } from './component-scan';\nimport { parseComponentSpecs, type ComponentSpecsFile, type SpecCoverage } from './component-spec';\nimport { evaluateContrastPairs, parseContrastSpecs, type ContrastPairResult, type ContrastPairSpec } from './contrast-model';\nimport { globToRegExp, selectTokenFiles } from './layered';\nimport { DEFAULT_PRODUCTS, type ProductConfig } from './products';\nimport { readRepoTexts, parentDir, type RepoSource, type RepoSourceRef } from './repo-source';\nimport type { IntegrationsConfig } from './requests';\nimport type { Rights, VisualImpactMode } from './rights';\nimport { cssVarsIn } from './usage';\nimport { buildTokenRows, tokenRowAxes, tokenRowIndex, type TokenRows, type TokenRowTier } from './token-rows';\n\n/** Paths used when bridge.config.json does not name them: where this repo kept them before the config did. */\nexport const REPO_MODEL_DEFAULTS = {\n tokensRoot: 'packages/tokens/src',\n componentsDir: 'packages/react/src/components',\n componentSpecs: 'packages/react/component-specs.json',\n /** Optional token usage notes (group -> sentence), relative to tokens.root, when tokens.usage is not set. */\n tokensUsage: 'usage.json',\n /** Most global stylesheets read (components.styles): a broad glob never turns into hundreds of reads. */\n maxStylesheets: 50,\n repo: { owner: 'peterbono', repo: 'ai-design-system-demo', defaultBranch: 'main' },\n} as const;\n\n/** The repository settings the site and Studio act on (roles, owners, mode), derived from bridge.config.json. */\nexport interface SiteRepo {\n owner: string;\n repo: string;\n defaultBranch: string;\n /** GitHub logins that count as design and tech owners for Tier 3 approvals. Empty: any two distinct approvers. */\n owners: { design: string[]; tech: string[] };\n /** Who may merge past missing approvals from Reviews, with a reason. `allowed` empty: no override. */\n override: { allowed: string[]; requireReason: boolean; minReasonLength: number };\n /** Which owner group approves design, approves tech and ships. null: not set. */\n rights: Rights | null;\n /** governance.soloOwnerCanApproveBoth: the only owner's approval covers design and tech. Default false. */\n soloOwnerCanApproveBoth: boolean;\n /** Visual before and after: on every pull request (auto) or when someone asks (on-demand, label visual-check). */\n visualImpact: { mode: VisualImpactMode };\n /** Token root in the repo. */\n tokensRoot: string;\n /** Where component change requests go besides the GitHub issue. Empty: GitHub only. */\n integrations: IntegrationsConfig;\n /** The apps that consume the design system, the library being the default. */\n products: ProductConfig[];\n /** How changes reach the code: \"suggest\" (default) or \"direct\". */\n changes: ChangesMode;\n}\n\ntype LegacyRaw = { owner?: unknown; defaultBranch?: unknown; owners?: { design?: string[]; tech?: string[] }; governance?: { owners?: unknown } } | null | undefined;\n\n/**\n * SiteRepo from a parsed config. `raw` (the file as parsed JSON) carries the older top-level keys loadConfig does not\n * keep (`owner`, `defaultBranch`, `owners`); `fallback` names the repo when the config does not.\n */\nexport function siteRepoFromConfig(\n config: BridgeConfig,\n raw?: unknown,\n fallback: { owner: string; repo: string; defaultBranch: string } = REPO_MODEL_DEFAULTS.repo,\n): SiteRepo {\n const legacy = (raw && typeof raw === 'object' ? raw : undefined) as LegacyRaw;\n const g = config.governance;\n const legacyOwners = legacy?.governance?.owners === undefined ? legacy?.owners : undefined;\n return {\n owner: typeof legacy?.owner === 'string' && legacy.owner ? legacy.owner : (config.repo?.owner ?? fallback.owner),\n repo: config.repo?.name ?? fallback.repo,\n defaultBranch: typeof legacy?.defaultBranch === 'string' && legacy.defaultBranch ? legacy.defaultBranch : (config.repo?.defaultBranch ?? fallback.defaultBranch),\n owners: legacyOwners ? { design: legacyOwners.design ?? [], tech: legacyOwners.tech ?? [] } : { design: [...g.owners.design], tech: [...g.owners.tech] },\n override: g.override ? { ...g.override } : { ...DEFAULT_OVERRIDE },\n rights: g.rights ?? null,\n soloOwnerCanApproveBoth: g.soloOwnerCanApproveBoth === true,\n visualImpact: { mode: config.visualImpact?.mode === 'on-demand' ? 'on-demand' : 'auto' },\n tokensRoot: config.tokens.root,\n integrations: config.integrations ?? {},\n products: config.products.length ? config.products : DEFAULT_PRODUCTS.map((p) => ({ ...p })),\n changes: config.changes ?? DEFAULT_CHANGES_MODE,\n };\n}\n\n/**\n * The global stylesheet globs of a config: components.styles, else every .css file under the styles/ and theme/\n * folders next to the components folder (packages/react/src/styles, packages/react/src/theme here).\n */\nexport function styleGlobs(config: BridgeConfig): string[] {\n if (config.components?.styles) return [...config.components.styles];\n const parent = parentDir(config.components?.dir ?? REPO_MODEL_DEFAULTS.componentsDir);\n const at = (dir: string) => (parent ? `${parent}/${dir}/**/*.css` : `${dir}/**/*.css`);\n return [at('styles'), at('theme')];\n}\n\n/** The folder to list for a glob: its segments before the first wildcard ('' for the whole repository). */\nexport function globBase(glob: string): string {\n const segs = glob.split('/');\n const fixed: string[] = [];\n for (const seg of segs.slice(0, -1)) {\n if (/[*?[{]/.test(seg)) break;\n fixed.push(seg);\n }\n return fixed.join('/');\n}\n\n/**\n * The global stylesheets of a repository (styleGlobs): one listing per glob folder, files under the components folder\n * left to the component scan, at most REPO_MODEL_DEFAULTS.maxStylesheets (a problem says when more match).\n */\nexport async function listStylesheets(source: RepoSource, config: BridgeConfig): Promise<{ globs: string[]; paths: string[]; problems: string[] }> {\n const globs = styleGlobs(config);\n const matchers = globs.map(globToRegExp);\n const compDir = config.components?.dir ?? REPO_MODEL_DEFAULTS.componentsDir;\n const bases = [...new Set(globs.map(globBase))].filter((b, _, all) => !all.some((o) => o !== b && (o === '' || b.startsWith(`${o}/`))));\n const listed = (await Promise.all(bases.map((b) => source.list(b)))).flat();\n const paths = [...new Set(listed)].filter((p) => matchers.some((re) => re.test(p)) && !p.startsWith(`${compDir}/`)).sort();\n const max = REPO_MODEL_DEFAULTS.maxStylesheets;\n if (paths.length <= max) return { globs, paths, problems: [] };\n return { globs, paths: paths.slice(0, max), problems: [`components.styles matches ${paths.length} files: Bridge reads the first ${max}. Narrow the globs to the stylesheets the library ships.`] };\n}\n\n/**\n * The global stylesheets of a repository with the CSS custom properties each reads: what RepoModel.styles holds.\n * loadRepoModel reads them with everything else; a model computed without them (an older snapshot) can be completed\n * with this alone.\n */\nexport async function readStylesheets(source: RepoSource, config: BridgeConfig, concurrency = 8): Promise<RepoModel['styles'] & { problems: string[] }> {\n const { globs, paths, problems } = await listStylesheets(source, config);\n const bodies = await readRepoTexts(source, paths, concurrency);\n const vars: Record<string, string[]> = {};\n for (const p of paths) {\n const text = bodies.get(p);\n if (typeof text === 'string') vars[p] = cssVarsIn(text);\n }\n return { globs, vars, problems };\n}\n\n/** Fills the paths a config leaves out with REPO_MODEL_DEFAULTS (tokens.root, components.dir). */\nfunction withModelDefaults(raw: Record<string, unknown>): Record<string, unknown> {\n const tokens = (raw.tokens && typeof raw.tokens === 'object' ? raw.tokens : {}) as Record<string, unknown>;\n return {\n ...raw,\n tokens: { ...tokens, root: tokens.root ?? REPO_MODEL_DEFAULTS.tokensRoot },\n components: raw.components ?? { dir: REPO_MODEL_DEFAULTS.componentsDir },\n };\n}\n\n/** The config the model uses when the repo has no bridge.config.json (or an invalid one): the defaults above. */\nexport const defaultModelConfig = (): BridgeConfig => defineConfig(withModelDefaults({}) as BridgeConfigInput);\n\n/** bridge.config.json text -> config, parsed once. Never throws: problems are returned and the defaults stand in. */\nexport function parseModelConfig(text: string | null): { config: BridgeConfig; raw: unknown; problems: string[] } {\n if (text === null) return { config: defaultModelConfig(), raw: undefined, problems: [] };\n let raw: unknown;\n try {\n raw = JSON.parse(text);\n } catch (err) {\n return { config: defaultModelConfig(), raw: undefined, problems: [`${CONFIG_FILE} is not valid JSON (${(err as Error).message})`] };\n }\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return { config: defaultModelConfig(), raw, problems: [`${CONFIG_FILE}: top level must be an object`] };\n try {\n return { config: loadConfig(withModelDefaults(raw as Record<string, unknown>)), raw, problems: [] };\n } catch (err) {\n const problems = err instanceof ConfigError ? err.problems.map((p) => `${CONFIG_FILE}: ${p}`) : [`${CONFIG_FILE}: ${(err as Error).message}`];\n return { config: defaultModelConfig(), raw, problems };\n }\n}\n\nexport interface RepoModel {\n ref: RepoSourceRef;\n /** bridge.config.json as read, null when the repo has none. */\n configText: string | null;\n config: BridgeConfig;\n site: SiteRepo;\n /** What could not be read (invalid config, a docs.json that does not parse, an alias that does not resolve). */\n problems: string[];\n tokens: {\n /** tokens.root, repo-relative. */\n root: string;\n /** Token file bodies keyed by path relative to tokens.root, as buildTokenSet and the token explorer read them. */\n files: Record<string, string>;\n rows: TokenRows;\n /** Notes per token group (tokens.usage), null when the repo has none. */\n usage: Record<string, string> | null;\n };\n contrast: {\n /** Repo-relative checks file, undefined when the config names none. */\n path: string | undefined;\n specs: ContrastPairSpec[];\n pairs: ContrastPairResult[];\n };\n /** Null when the scan was skipped (options.components false). */\n components: {\n dir: string;\n /** Barrel file the families come from, when it exists. */\n index: string | undefined;\n families: { name: string; members: string[] }[];\n list: ScannedComponent[];\n } | null;\n /**\n * Global stylesheets of the library (components.styles): the globs read, and each matching file with the CSS custom\n * properties it reads (`var(--x)`), so a token read only by base styles counts as in use.\n */\n styles: {\n globs: string[];\n vars: Record<string, string[]>;\n };\n specs: {\n path: string;\n /** Parsed component-specs.json, null when missing or of another version. */\n file: ComponentSpecsFile | null;\n /** Figma coverage entries, read even from an older file. */\n coverage: SpecCoverage[];\n };\n}\n\nexport interface RepoModelOptions {\n /** Scan components (3-4 files per component). Default true. */\n components?: boolean;\n /** Docs link of a token's CSS variable (the caller's routing), given its type, tier and token path. Default: none. */\n href?: (cssVar: string, type: string, tier: TokenRowTier, path: string) => string | undefined;\n /** Requests in flight. Default 8. */\n concurrency?: number;\n /**\n * Hears how far the read has gone, in real file counts: once with every phase's total before the first body is\n * read, then once per file settled. Phases run in order: tokens (token files, contrast checks, usage notes), then\n * components (code, styles, stories, the index, the global stylesheets and the Figma specs), then docs (each component's docs file).\n */\n onProgress?: (progress: RepoModelProgress) => void;\n}\n\n/** The three reads of loadRepoModel, in the order they run. */\nexport type RepoModelPhase = 'tokens' | 'components' | 'docs';\n\nexport interface RepoModelProgress {\n /** The phase being read. */\n phase: RepoModelPhase;\n /** Files of this phase settled so far, and in all (a phase with nothing to read reports 0 of 0). */\n done: number;\n total: number;\n /** Across every phase: the bar of the whole read. `filesTotal` is known from the first report and never moves. */\n filesDone: number;\n filesTotal: number;\n}\n\nconst emptyRows = (config: BridgeConfig): TokenRows => ({ ...tokenRowAxes(config), primitives: [], semantic: [], brand: [], density: [], component: [], all: [], sources: [] });\n\n/** Reads a repo through `source` and computes its model. Never throws on repo content: see `problems`. */\nexport async function loadRepoModel(source: RepoSource, options: RepoModelOptions = {}): Promise<RepoModel> {\n const concurrency = options.concurrency ?? 8;\n const problems: string[] = [];\n // A file the source refuses as too large (status 413) is a problem of the repo, not a failure of the read.\n // Anything else (rate limit, network) still throws, so the caller can retry.\n const tooLarge = (path: string, err: unknown): null => {\n if ((err as { status?: unknown } | null)?.status !== 413) throw err;\n problems.push(`${path}: ${(err as Error).message}`);\n return null;\n };\n const configText = await source.text(CONFIG_FILE);\n const parsed = parseModelConfig(configText);\n const { config } = parsed;\n problems.push(...parsed.problems);\n const fallbackRepo = source.ref.owner && source.ref.repo ? { owner: source.ref.owner, repo: source.ref.repo, defaultBranch: REPO_MODEL_DEFAULTS.repo.defaultBranch } : REPO_MODEL_DEFAULTS.repo;\n const site = siteRepoFromConfig(config, parsed.raw, fallbackRepo);\n\n // Token files, the contrast checks and the usage notes.\n const root = config.tokens.root;\n const underRoot = await source.list(root === '.' ? '' : root);\n const tokenRel = selectTokenFiles(config, underRoot);\n const contrastPath = config.contrast?.path;\n const usagePath = tokensPath(config, config.tokens.usage ?? REPO_MODEL_DEFAULTS.tokensUsage);\n const tokenPaths = tokenRel.map((f) => tokensPath(config, f));\n const tokenRead = [...new Set([...tokenPaths, ...(contrastPath ? [contrastPath] : []), usagePath])];\n\n // Every path of the components and docs phases is known from the listing, before any body: the progress total is\n // exact from the first report.\n const comps = config.components ?? { dir: REPO_MODEL_DEFAULTS.componentsDir, docsSuffix: '.docs.json', styleSuffix: '.module.css' };\n const specsPath = comps.specs ?? REPO_MODEL_DEFAULTS.componentSpecs;\n const indexPath = comps.index ?? (parentDir(comps.dir) ? `${parentDir(comps.dir)}/index.ts` : 'index.ts');\n let compFiles: string[] = [];\n const codeRead: string[] = [specsPath];\n const docsRead: string[] = [];\n if (options.components !== false) {\n compFiles = await source.list(comps.dir);\n for (const f of compFiles) {\n const parts = f.slice(comps.dir.length + 1).split('/');\n if (parts.length !== 2) continue;\n const [n, file] = parts as [string, string];\n if (file === `${n}${comps.docsSuffix}`) docsRead.push(f);\n else if ([`${n}.tsx`, `${n}${comps.styleSuffix}`, `${n}.stories.tsx`].includes(file)) codeRead.push(f);\n }\n codeRead.push(indexPath);\n }\n // Global stylesheets (components.styles): their paths are known from listings, before any body.\n const listedStyles = await listStylesheets(source, config);\n problems.push(...listedStyles.problems);\n const stylePaths = listedStyles.paths;\n codeRead.push(...stylePaths);\n // A path is read once, in the first phase that asks for it.\n const seen = new Set<string>();\n const fresh = (paths: string[]) =>\n paths.filter((p) => {\n if (seen.has(p)) return false;\n seen.add(p);\n return true;\n });\n const phases: [RepoModelPhase, string[]][] = [\n ['tokens', fresh(tokenRead)],\n ['components', fresh(codeRead)],\n ['docs', fresh(docsRead)],\n ];\n const filesTotal = phases.reduce((n, [, paths]) => n + paths.length, 0);\n let before = 0;\n const readPhase = async (phase: RepoModelPhase, paths: string[]) => {\n const offset = before;\n const out = await readRepoTexts(source, paths, concurrency, tooLarge, (done, total) => options.onProgress?.({ phase, done, total, filesDone: offset + done, filesTotal }));\n before += paths.length;\n return out;\n };\n const bodies = await readPhase('tokens', phases[0]![1]);\n const read = (p: string) => bodies.get(p) ?? undefined;\n const files: Record<string, string> = {};\n tokenRel.forEach((rel, i) => {\n const body = read(tokenPaths[i]!);\n if (body !== undefined) files[rel] = body;\n });\n const listFiles = (dir: string) => underRoot.filter((p) => parentDir(p) === dir);\n\n let rows: TokenRows;\n try {\n rows = buildTokenRows(config, read, listFiles);\n } catch (err) {\n problems.push((err as Error).message);\n rows = emptyRows(config);\n }\n\n let usage: Record<string, string> | null = null;\n const usageText = read(usagePath);\n if (usageText !== undefined) {\n try {\n usage = JSON.parse(usageText) as Record<string, string>;\n } catch (err) {\n problems.push(`${usagePath}: ${(err as Error).message}`);\n }\n }\n\n let specs: ContrastPairSpec[] = [];\n let pairs: ContrastPairResult[] = [];\n try {\n specs = parseContrastSpecs(contrastPath ? read(contrastPath) : undefined);\n pairs = evaluateContrastPairs(specs, rows);\n } catch (err) {\n problems.push((err as Error).message);\n }\n\n // Components and the Figma coverage.\n const index = tokenRowIndex(rows);\n const describeVar = (cssVar: string) => {\n const hit = index.get(cssVar);\n return hit ? { path: hit.path, kind: hit.kind, href: options.href?.(cssVar, hit.type, hit.kind, hit.path) } : undefined;\n };\n let components: RepoModel['components'] = null;\n const code = await readPhase('components', phases[1]![1]);\n const docs = await readPhase('docs', phases[2]![1]);\n const readMore = (p: string) => code.get(p) ?? docs.get(p) ?? bodies.get(p) ?? undefined;\n if (options.components !== false) {\n const indexText = readMore(indexPath);\n const indexDir = parentDir(indexPath);\n const indexRel = indexDir && comps.dir.startsWith(`${indexDir}/`) ? comps.dir.slice(indexDir.length + 1) : comps.dir;\n const list = scanComponents({ dir: comps.dir, files: compFiles, readText: readMore, indexText, indexRel, docsSuffix: comps.docsSuffix, styleSuffix: comps.styleSuffix, describeVar, problems });\n components = { dir: comps.dir, index: indexText === undefined ? undefined : indexPath, families: indexText === undefined ? [] : parseComponentFamilies(indexText, indexRel), list };\n }\n\n const styleVars: Record<string, string[]> = {};\n for (const p of stylePaths) {\n const text = readMore(p);\n if (text !== undefined) styleVars[p] = cssVarsIn(text);\n }\n\n const specsText = readMore(specsPath);\n let specsFile: ComponentSpecsFile | null = null;\n let coverage: SpecCoverage[] = [];\n if (specsText !== undefined) {\n try {\n specsFile = parseComponentSpecs(specsText);\n } catch {\n /* another version: coverage below may still read */\n }\n try {\n coverage = (JSON.parse(specsText) as { coverage?: SpecCoverage[] }).coverage ?? [];\n } catch (err) {\n problems.push(`${specsPath}: ${(err as Error).message}`);\n }\n }\n\n return {\n ref: source.ref,\n configText,\n config,\n site,\n problems,\n tokens: { root, files, rows, usage },\n contrast: { path: contrastPath, specs, pairs },\n components,\n styles: { globs: listedStyles.globs, vars: styleVars },\n specs: { path: specsPath, file: specsFile, coverage },\n };\n}\n","// A RepoSource over GitHub, pinned to one commit sha: one recursive tree call lists every file with its blob sha,\n// then each body is read by that blob sha. Signed in, bodies come from the git blobs API with the raw media type\n// (the raw host refuses any request that carries a token: its CORS preflight answers 403). Anonymous, bodies of a\n// public repository come from raw.githubusercontent.com at the commit sha, sent without headers (a simple CORS\n// request, no API quota). Blobs are content-addressed: cached forever, never revalidated.\n\nimport { GitHubClient, GitHubError } from './github-client';\nimport { isUnder, normalizeRepoPath, type RepoSource } from './repo-source';\n\n/** Where blob bodies are kept between sources (IndexedDB in the browser). Keyed by blob sha; may be async. */\nexport interface BlobCache {\n get(sha: string): string | undefined | Promise<string | undefined>;\n set(sha: string, text: string): void | Promise<void>;\n}\n\nexport interface GitHubSourceOptions {\n /** Files larger than this are refused (status 413) instead of read. Default 1 MB. */\n maxFileBytes?: number;\n /** Body reads in flight at once. Default 4 (friendly to GitHub's secondary limits). */\n concurrency?: number;\n /**\n * A cache that outlives the source, keyed by blob sha. Bodies of private repositories land in it, so the caller\n * scopes it per repository and account and clears it on sign-out (plan 6.8).\n */\n blobCache?: BlobCache;\n /**\n * Hears what the source does: the tree once it is read (how many files the commit holds), then each body as it\n * lands, saying whether it came from the blob cache (no request) or from GitHub.\n */\n onProgress?: (event: GitHubSourceProgress) => void;\n}\n\n/** What a GitHub source reports through `onProgress`. */\nexport type GitHubSourceProgress = { kind: 'tree'; files: number } | { kind: 'file'; path: string; cached: boolean };\n\n/** How bodies are read: the blobs API with the token, or the raw host without one. */\nexport type GitHubSourceMode = 'api' | 'raw';\n\nexport interface GitHubSource extends RepoSource {\n /** Where body reads go: 'api' when the client has a token, 'raw' otherwise. */\n readonly mode: GitHubSourceMode;\n}\n\nconst FULL_SHA = /^[0-9a-f]{40}$/i;\n\n/** A concurrency limiter: at most `n` tasks run at once, the rest wait in order. */\nfunction limiter(n: number) {\n let active = 0;\n const waiting: (() => void)[] = [];\n return async <T>(task: () => Promise<T>): Promise<T> => {\n if (active >= n) await new Promise<void>((resolve) => waiting.push(resolve));\n active++;\n try {\n return await task();\n } finally {\n active--;\n waiting.shift()?.();\n }\n };\n}\n\n/**\n * A source over `client`'s repository at commit `sha` (a full 40-character sha: a branch name would move under the\n * cache). The first `list` or `text` call reads the tree; `text` of a path the tree does not list costs no request.\n */\nexport function gitHubSource(client: GitHubClient, sha: string, opts: GitHubSourceOptions = {}): GitHubSource {\n if (!FULL_SHA.test(sha)) throw new Error(`gitHubSource needs a full commit sha, got \"${sha}\". Resolve the branch head first.`);\n const maxBytes = opts.maxFileBytes ?? 1_000_000;\n const run = limiter(Math.max(1, opts.concurrency ?? 4));\n const mode: GitHubSourceMode = client.canWrite ? 'api' : 'raw';\n\n let tree: Promise<Map<string, { sha: string; size: number | undefined }>> | undefined;\n const readTree = () => {\n tree ??= client.getTree(sha, true).then(\n ({ entries, truncated }) => {\n if (truncated) throw new GitHubError(413, 'The repository tree is too large to read in one request.');\n const files = new Map<string, { sha: string; size: number | undefined }>();\n for (const e of entries) if (e.type === 'blob') files.set(e.path, { sha: e.sha, size: e.size });\n opts.onProgress?.({ kind: 'tree', files: files.size });\n return files;\n },\n (err: unknown) => {\n tree = undefined; // A failed read (rate limit, network) is retried by the next call.\n throw err;\n },\n );\n return tree;\n };\n\n const bodies = new Map<string, Promise<string>>();\n\n const readBody = async (path: string, blobSha: string): Promise<string> => {\n const kept = await opts.blobCache?.get(blobSha);\n if (kept !== undefined) {\n opts.onProgress?.({ kind: 'file', path, cached: true });\n return kept;\n }\n const text = mode === 'api' ? await client.getBlobRaw(blobSha) : await client.readRawFile(path, sha);\n if (text === undefined) {\n const hint = mode === 'raw' ? ' Sign in with GitHub to read a private repository.' : '';\n throw new GitHubError(404, `${path} is listed at ${sha.slice(0, 7)} but GitHub did not return it.${hint}`);\n }\n try {\n await opts.blobCache?.set(blobSha, text);\n } catch {\n // A full or blocked cache only costs a read next time.\n }\n opts.onProgress?.({ kind: 'file', path, cached: false });\n return text;\n };\n\n return {\n ref: { owner: client.owner, repo: client.name, sha },\n mode,\n async list(prefix?: string) {\n // Sorted, like every RepoSource.\n return [...(await readTree()).keys()].filter((f) => isUnder(f, prefix)).sort();\n },\n async text(path: string) {\n const p = normalizeRepoPath(path);\n const entry = (await readTree()).get(p);\n if (!entry) return null;\n if (entry.size !== undefined && entry.size > maxBytes) {\n throw new GitHubError(413, `${p} is ${Math.round(entry.size / 1000)} KB; Bridge reads files up to ${Math.round(maxBytes / 1000)} KB.`);\n }\n let body = bodies.get(entry.sha);\n if (!body) {\n body = run(() => readBody(p, entry.sha));\n bodies.set(entry.sha, body);\n body.catch(() => bodies.delete(entry.sha));\n }\n return body;\n },\n };\n}\n","// What one visitor can do in one repository, from GitHub alone (multi-team plan, section 3.3). Pure: the facts come\n// from GET /repos/{owner}/{repo} (visibility and the viewer's permissions) and, for a GitHub App sign-in, from the\n// user's installations. Roles from bridge.config.json (owners, rights) are evaluated on top by the caller, as today.\n\nimport { GitHubClient, GitHubError, type RepoInfo } from './github-client';\n\n/**\n * - anonymous-public: not signed in, the repository is public (read-only Studio).\n * - anonymous-unknown: not signed in, GitHub answers 404 (private or missing: GitHub does not say which).\n * - no-access: signed in, GitHub answers 404 (no such repo, not a collaborator, or the App is not installed on it).\n * - not-installed: signed in with explicit permission (triage or more) on a public repository, and the App's\n * installations do not cover it: it is not installed there.\n * - outside-contributor: signed in, public repository, read access only, and no App installation lists it. GitHub\n * lists installations only where the user has explicit permission, so this may be a non-collaborator of a repo\n * where Bridge is installed: never say \"not installed\" here. Browse only; ask an admin for access.\n * - reader: pull or triage. Browse, comment, file suggestions.\n * - writer: push or maintain. Plus direct changes.\n * - admin: admin. Plus settings and protection.\n */\nexport type RepoAccessState = 'anonymous-public' | 'anonymous-unknown' | 'no-access' | 'not-installed' | 'outside-contributor' | 'reader' | 'writer' | 'admin';\n\n/** The viewer's permissions on a repository, as GET /repos returns them. */\nexport type RepoPermissions = NonNullable<RepoInfo['permissions']>;\n\nexport interface AccessFacts {\n /** A token was sent. */\n signedIn: boolean;\n /** GET /repos answered 200 (false on 404). */\n visible: boolean;\n /**\n * An installation of the App the user can reach covers the repository; null or undefined when not checked\n * (personal token) or GitHub would not say.\n */\n installed?: boolean | null | undefined;\n /** GET /repos said the repository is private. */\n private?: boolean | undefined;\n permissions?: RepoPermissions | undefined;\n}\n\n/** The access state from the facts (section 3.3 table). */\nexport function accessState(f: AccessFacts): RepoAccessState {\n if (!f.visible) return f.signedIn ? 'no-access' : 'anonymous-unknown';\n if (!f.signedIn) return 'anonymous-public';\n const p = f.permissions ?? {};\n // A private repository an App token can see is one the App is installed on, whatever the listing said.\n if (f.installed === false && !f.private) return p.admin || p.maintain || p.push || p.triage ? 'not-installed' : 'outside-contributor';\n if (p.admin) return 'admin';\n if (p.push || p.maintain) return 'writer';\n return 'reader';\n}\n\nconst RANK: Record<RepoAccessState, number> = {\n 'anonymous-unknown': 0,\n 'no-access': 0,\n 'anonymous-public': 1,\n 'not-installed': 1,\n 'outside-contributor': 1,\n reader: 2,\n writer: 3,\n admin: 4,\n};\n\n/**\n * True when `state` grants at least what `min` grants: 'reader' (suggest, comment), 'writer' (direct changes),\n * 'admin' (settings). The read-only states rank as 'anonymous-public'; the closed ones rank lowest.\n */\nexport function accessAtLeast(state: RepoAccessState, min: 'anonymous-public' | 'reader' | 'writer' | 'admin'): boolean {\n return RANK[state] >= RANK[min];\n}\n\nexport interface RepoAccess {\n state: RepoAccessState;\n owner: string;\n repo: string;\n /** Undefined when GitHub did not show the repository. */\n private: boolean | undefined;\n defaultBranch: string | undefined;\n permissions: RepoPermissions | undefined;\n /** The App installation that gives the user this repository, when checked and found. */\n installationId?: number | undefined;\n /** With a Direct App client: whether that App is installed for the user on the repository (null when unknown). */\n directInstalled?: boolean | null | undefined;\n}\n\nexport interface ResolveAccessOptions {\n /**\n * The client's token is a GitHub App user-to-server token: check its installations (2 or 3 calls). Leave off for a\n * personal token or anonymous reads; the state then comes from GET /repos alone.\n */\n app?: boolean;\n /** A client with the Direct App's token, to learn whether that App is installed too (changes: \"direct\"). */\n direct?: GitHubClient;\n}\n\n/** Installed, not installed, or null when GitHub would not say (personal token, missing permission, network). */\nasync function installed(client: GitHubClient, owner: string, repo: string): Promise<{ installed: boolean | null; id?: number }> {\n try {\n const found = await client.findInstallation(owner, repo);\n return found ? { installed: true, id: found.id } : { installed: false };\n } catch (err) {\n if (err instanceof GitHubError && (err.status === 401 || err.status === 429)) throw err;\n return { installed: null };\n }\n}\n\n/**\n * Reads what the client's token (or no token) can do on the client's repository. With `app`, the client's token must\n * be a user token of the signing-in App (each App lists only its own installations). A 404 is a state, not an error;\n * a rejected token (401) and an exhausted rate limit (429) are thrown for the caller to handle as today.\n */\nexport async function resolveRepoAccess(client: GitHubClient, opts: ResolveAccessOptions = {}): Promise<RepoAccess> {\n const signedIn = client.canWrite;\n const base = { owner: client.owner, repo: client.name };\n let info: RepoInfo;\n try {\n info = await client.getRepo();\n } catch (err) {\n if (err instanceof GitHubError && err.status === 404) {\n return { ...base, state: accessState({ signedIn, visible: false }), private: undefined, defaultBranch: undefined, permissions: undefined };\n }\n throw err;\n }\n const inst = signedIn && opts.app ? await installed(client, client.owner, client.name) : { installed: null };\n const direct = signedIn && opts.direct ? (await installed(opts.direct, client.owner, client.name)).installed : undefined;\n return {\n ...base,\n state: accessState({ signedIn, visible: true, installed: inst.installed, private: info.private, permissions: info.permissions }),\n private: info.private,\n defaultBranch: info.defaultBranch,\n permissions: info.permissions,\n ...(inst.id !== undefined ? { installationId: inst.id } : {}),\n ...(direct !== undefined ? { directInstalled: direct } : {}),\n };\n}\n","// Repo snapshot: the files the repo model reads, written by `bridge snapshot` in a team's CI and published to the\n// `bridge-data` branch (.github/workflows/bridge-data.yml), plus what only Node can compute (adoption audits run on\n// product code) and a compact Figma coverage list. Hosted Studio and Library read it from the raw host with no API\n// quota: snapshotSource() serves it as a RepoSource, so loadRepoModel() gives the same model as a live read.\n// Pure: no Node, no DOM.\n\nimport type { AuditMetrics, AuditReport } from './audit/types';\nimport type { ContrastPairResult } from './contrast-model';\nimport type { SpecCoverage } from './component-spec';\nimport { isUnder, normalizeRepoPath, type RepoSource } from './repo-source';\nimport type { RepoModel } from './repo-model';\n\nexport const SNAPSHOT_SCHEMA_VERSION = 1;\n/** Branch the bridge-data workflow publishes to, and the files on it. */\nexport const SNAPSHOT_BRANCH = 'bridge-data';\nexport const SNAPSHOT_FILE = 'snapshot.json';\nexport const SNAPSHOT_AUDITS_DIR = 'audits';\n/** Above this, a snapshot is refused (a published file the browser downloads whole). */\nexport const SNAPSHOT_MAX_BYTES = 5_000_000;\n\n/** One adoption audit: the summary lives in snapshot.json, the full report in audits/<id>.json next to it. */\nexport interface SnapshotAudit {\n id: string;\n /** Path of the full report on the bridge-data branch (\"audits/admin.json\"). */\n path: string;\n label?: string;\n generatedAt: string;\n target: { path: string; files: number };\n metrics: AuditMetrics;\n}\n\n/** A contrast pair as computed when the snapshot was written, without the token rows (the model has them). */\nexport type SnapshotContrastPair = Omit<ContrastPairResult, 'fgToken' | 'bgToken'>;\n\n/** Counts for a header or a card, readable without loading the model. */\nexport interface SnapshotSummary {\n tokens: number;\n /** Null when the component scan was skipped. */\n components: number | null;\n contrast: { pairs: number; checks: number; failing: number };\n /** Components in Figma (generated or drafted) out of the visual ones, null without a specs file. */\n figma: { inFigma: number; visual: number } | null;\n}\n\nexport interface RepoSnapshot {\n kind: 'bridge-snapshot';\n schemaVersion: typeof SNAPSHOT_SCHEMA_VERSION;\n tool: { name: 'bridge'; version: string };\n generatedAt: string;\n repo: { owner: string; name: string; branch: string };\n /** Commit the snapshot was computed from. Fresh when it equals the default branch head. */\n sourceSha: string;\n /** Commit date of sourceSha (ISO), when known. */\n committedAt?: string;\n /** Every path the model listed (token root, components dir), so list() answers as the repository did. */\n paths: string[];\n /** Bodies of the files the model read, keyed by repo-relative path. */\n files: Record<string, string>;\n /**\n * Figma coverage of component-specs.json without the specs themselves (the file is over 1 MB here, too big for\n * the GitHub contents source). Null when the repository has no specs file.\n */\n figma: { path: string; generated?: string; coverage: SpecCoverage[] } | null;\n summary: SnapshotSummary;\n /** Contrast results as computed when the snapshot was written (the model recomputes the same from files). */\n contrast: { path?: string; pairs: SnapshotContrastPair[] };\n audits: SnapshotAudit[];\n /** What could not be read when the snapshot was written. */\n problems: string[];\n /**\n * The global stylesheet globs the model read (components.styles), their files among `files`. Absent from a snapshot\n * written before Bridge read global stylesheets: a reader then reads those files from the repository.\n */\n styles?: string[];\n}\n\nexport class SnapshotError extends Error {}\n\nconst isObj = (x: unknown): x is Record<string, unknown> => !!x && typeof x === 'object' && !Array.isArray(x);\nconst isStr = (x: unknown): x is string => typeof x === 'string';\n\n/** Validates a snapshot (text or parsed JSON). Throws SnapshotError naming the first problem. */\nexport function parseSnapshot(input: string | unknown): RepoSnapshot {\n let data: unknown = input;\n if (typeof input === 'string') {\n try {\n data = JSON.parse(input);\n } catch (err) {\n throw new SnapshotError(`${SNAPSHOT_FILE} is not valid JSON (${(err as Error).message})`);\n }\n }\n if (!isObj(data) || data.kind !== 'bridge-snapshot') throw new SnapshotError(`${SNAPSHOT_FILE} is not a Bridge snapshot`);\n if (data.schemaVersion !== SNAPSHOT_SCHEMA_VERSION) throw new SnapshotError(`${SNAPSHOT_FILE} is schema version ${String(data.schemaVersion)}; this version of Bridge reads ${SNAPSHOT_SCHEMA_VERSION}`);\n const repo = data.repo;\n if (!isObj(repo) || !isStr(repo.owner) || !isStr(repo.name) || !isStr(repo.branch)) throw new SnapshotError(`${SNAPSHOT_FILE}: repo needs owner, name and branch`);\n if (!isStr(data.sourceSha) || !data.sourceSha) throw new SnapshotError(`${SNAPSHOT_FILE}: sourceSha is missing`);\n if (!isStr(data.generatedAt)) throw new SnapshotError(`${SNAPSHOT_FILE}: generatedAt is missing`);\n if (!Array.isArray(data.paths) || !data.paths.every(isStr)) throw new SnapshotError(`${SNAPSHOT_FILE}: paths must be a list of strings`);\n if (!isObj(data.files) || !Object.values(data.files).every(isStr)) throw new SnapshotError(`${SNAPSHOT_FILE}: files must map paths to text`);\n if (data.figma !== null && (!isObj(data.figma) || !isStr(data.figma.path) || !Array.isArray(data.figma.coverage))) throw new SnapshotError(`${SNAPSHOT_FILE}: figma must be null or { path, coverage }`);\n if (!isObj(data.summary) || typeof data.summary.tokens !== 'number') throw new SnapshotError(`${SNAPSHOT_FILE}: summary is missing`);\n if (!isObj(data.contrast) || !Array.isArray(data.contrast.pairs)) throw new SnapshotError(`${SNAPSHOT_FILE}: contrast needs pairs`);\n if (!Array.isArray(data.audits) || !data.audits.every((a) => isObj(a) && isStr(a.id) && isStr(a.path) && isObj(a.metrics))) throw new SnapshotError(`${SNAPSHOT_FILE}: audits must be a list of { id, path, metrics }`);\n if (!Array.isArray(data.problems)) throw new SnapshotError(`${SNAPSHOT_FILE}: problems must be a list`);\n return data as unknown as RepoSnapshot;\n}\n\n/** True when the snapshot was computed from `headSha` (the default branch head): use it instead of a live read. */\nexport const snapshotIsFresh = (snapshot: Pick<RepoSnapshot, 'sourceSha'>, headSha: string | undefined): boolean => !!headSha && snapshot.sourceSha === headSha;\n\n/**\n * A RepoSource over a snapshot. The Figma specs path serves a compact file with the coverage only (no component\n * specs), so the model reads the coverage and leaves `specs.file` null.\n */\nexport function snapshotSource(snapshot: RepoSnapshot): RepoSource {\n const files = new Map(Object.entries(snapshot.files).map(([k, v]) => [normalizeRepoPath(k), v]));\n const figmaPath = snapshot.figma ? normalizeRepoPath(snapshot.figma.path) : undefined;\n if (snapshot.figma && figmaPath && !files.has(figmaPath)) {\n files.set(figmaPath, JSON.stringify({ ...(snapshot.figma.generated ? { generated: snapshot.figma.generated } : {}), coverage: snapshot.figma.coverage }));\n }\n const paths = [...new Set([...snapshot.paths.map(normalizeRepoPath), ...files.keys()])].sort();\n return {\n ref: { owner: snapshot.repo.owner, repo: snapshot.repo.name, sha: snapshot.sourceSha },\n list: async (prefix) => paths.filter((p) => isUnder(p, prefix)),\n text: async (path) => files.get(normalizeRepoPath(path)) ?? null,\n };\n}\n\n/**\n * Wraps a source and records what it lists and reads, so a snapshot carries exactly the files the model needs and\n * nothing else of the repository.\n */\nexport function recordingSource(source: RepoSource): { source: RepoSource; paths: Set<string>; files: Map<string, string> } {\n const paths = new Set<string>();\n const files = new Map<string, string>();\n return {\n paths,\n files,\n source: {\n get ref() {\n return source.ref;\n },\n async list(prefix) {\n const out = await source.list(prefix);\n for (const p of out) paths.add(p);\n return out;\n },\n async text(path) {\n const body = await source.text(path);\n if (body !== null) files.set(normalizeRepoPath(path), body);\n return body;\n },\n },\n };\n}\n\n/** Summary of an audit report for snapshot.json; the full report is written to `path`. */\nexport function snapshotAudit(id: string, report: AuditReport): SnapshotAudit {\n return {\n id,\n path: `${SNAPSHOT_AUDITS_DIR}/${id}.json`,\n ...(report.label ? { label: report.label } : {}),\n generatedAt: report.generatedAt,\n target: { path: report.target.path, files: report.target.files },\n metrics: report.metrics,\n };\n}\n\n/** A safe audit id from a label or path (\"apps/admin/src\" -> \"apps-admin-src\"). */\nexport const auditId = (s: string): string =>\n s\n .toLowerCase()\n .replace(/\\.json$/, '')\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '') || 'audit';\n\nexport interface BuildSnapshotInput {\n model: RepoModel;\n /** From recordingSource(): what loadRepoModel listed and read. */\n paths: Iterable<string>;\n files: Map<string, string> | Record<string, string>;\n version: string;\n branch?: string;\n committedAt?: string;\n generatedAt?: string;\n audits?: SnapshotAudit[];\n}\n\n/** Every brand x theme result of a pair (the default brand per theme when the rows have no brands). */\nconst pairResults = (p: SnapshotContrastPair) => {\n const brands = Object.values(p.brands);\n return brands.length ? brands.flatMap((b) => Object.values(b)) : Object.values(p.modes);\n};\n\n/** Counts of a model for the snapshot summary. */\nexport function snapshotSummary(model: RepoModel): SnapshotSummary {\n const results = model.contrast.pairs.flatMap((p) => pairResults(p).map((r) => r.ratio >= p.min));\n const coverage = model.specs.coverage;\n const visual = coverage.filter((c) => c.status !== 'layout').length;\n const inFigma = coverage.filter((c) => c.status === 'generated' || c.status === 'drafted').length;\n return {\n tokens: model.tokens.rows.all.length + model.tokens.rows.primitives.length,\n components: model.components ? model.components.list.length : null,\n contrast: { pairs: model.contrast.pairs.length, checks: results.length, failing: results.filter((ok) => !ok).length },\n figma: coverage.length ? { inFigma, visual } : null,\n };\n}\n\n/** Assembles the snapshot from a model and the files it was read from. The specs file becomes the coverage list. */\nexport function buildSnapshot(input: BuildSnapshotInput): RepoSnapshot {\n const { model } = input;\n const files: Record<string, string> = {};\n const entries = input.files instanceof Map ? [...input.files] : Object.entries(input.files);\n const specsPath = normalizeRepoPath(model.specs.path);\n for (const [k, v] of entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {\n const p = normalizeRepoPath(k);\n if (p !== specsPath) files[p] = v;\n }\n const hasSpecs = entries.some(([k]) => normalizeRepoPath(k) === specsPath);\n return {\n kind: 'bridge-snapshot',\n schemaVersion: SNAPSHOT_SCHEMA_VERSION,\n tool: { name: 'bridge', version: input.version },\n generatedAt: input.generatedAt ?? new Date().toISOString(),\n repo: { owner: model.ref.owner || model.site.owner, name: model.ref.repo || model.site.repo, branch: input.branch ?? model.site.defaultBranch },\n sourceSha: model.ref.sha,\n ...(input.committedAt ? { committedAt: input.committedAt } : {}),\n paths: [...new Set([...input.paths].map(normalizeRepoPath))].filter((p) => p !== specsPath).sort(),\n files,\n figma: hasSpecs ? { path: specsPath, ...(model.specs.file?.generated ? { generated: model.specs.file.generated } : {}), coverage: model.specs.coverage } : null,\n summary: snapshotSummary(model),\n contrast: { ...(model.contrast.path ? { path: model.contrast.path } : {}), pairs: model.contrast.pairs.map(({ fgToken: _fg, bgToken: _bg, ...rest }) => rest) },\n audits: input.audits ?? [],\n problems: [...model.problems],\n styles: [...model.styles.globs],\n };\n}\n\n/** llms.txt next to snapshot.json on the bridge-data branch: the published design system in plain text, for agents. */\nexport const SNAPSHOT_LLMS_FILE = 'llms.txt';\n\n/** Above this many tokens, llms.txt lists the first ones and points at snapshot.json for the rest. */\nexport const LLMS_MAX_TOKENS = 600;\n\n/** One line of repo text: whitespace collapsed, so a value cannot open a heading or a list of its own. */\nconst line = (text: unknown): string => (typeof text === 'string' ? text.replace(/\\s+/g, ' ').trim() : '');\nconst strings = (list: unknown): string[] => (Array.isArray(list) ? list.map(line).filter(Boolean) : []);\n\n/**\n * The design system of a snapshot as llms.txt (https://llmstxt.org): what it is, every token with its CSS variable and\n * values per theme, and every component with its usage guidance. Written by `bridge snapshot`; the hosted Library\n * links to it. Pure: the model the snapshot was computed from goes in, text comes out.\n */\nexport function snapshotLlmsTxt(model: RepoModel, snapshot: Pick<RepoSnapshot, 'repo' | 'sourceSha' | 'committedAt' | 'generatedAt'>): string {\n const { owner, name, branch } = snapshot.repo;\n const date = (snapshot.committedAt ?? snapshot.generatedAt).slice(0, 10);\n const rows = model.tokens.rows;\n const tokens = rows.all.filter((t) => !t.deprecated);\n const shown = tokens.slice(0, LLMS_MAX_TOKENS);\n const comps = model.components?.list ?? [];\n const out: string[] = [\n `# ${owner}/${name} design system`,\n '',\n `> Tokens, components and usage guidance of the design system in github.com/${owner}/${name}, read at ${snapshot.sourceSha.slice(0, 7)} on ${branch} (${date}). Published by Bridge for AI agents and people.`,\n '',\n `- Source: https://github.com/${owner}/${name}/tree/${snapshot.sourceSha}`,\n `- Every file Bridge read, as JSON: ${SNAPSHOT_FILE}, next to this file on the ${SNAPSHOT_BRANCH} branch.`,\n `- Themes: ${rows.themes.join(', ') || 'none'}. Brands: ${rows.brands.join(', ') || 'none'}. Densities: ${rows.densities.join(', ') || 'none'}.`,\n '',\n '## Tokens',\n '',\n `${tokens.length} tokens (brand, semantic, density and component tiers) on top of ${rows.primitives.length} primitives. Use the semantic tokens in product code, never the primitives. Values are for the default brand${rows.defaultBrand ? ` (${rows.defaultBrand})` : ''}.`,\n '',\n ];\n for (const t of shown) {\n const values = Object.entries(t.modes)\n .map(([theme, v]) => `${theme} ${line(v.css)}`)\n .join(', ');\n const note = line(t.description);\n out.push(`- \\`${t.path}\\` (\\`${t.cssVar}\\`, ${t.tier} ${t.type}): ${values || 'no value'}${note ? `. ${note}` : ''}`);\n }\n if (tokens.length > shown.length) out.push('', `${tokens.length - shown.length} more tokens are in ${SNAPSHOT_FILE}.`);\n out.push('', '## Components', '');\n if (!comps.length) out.push('No components were read (components.dir in bridge.config.json names the folder).');\n for (const c of comps) {\n const d = c.docs;\n out.push(`### ${line(c.name)}`, '');\n const summary = line(d?.summary) || line(c.description);\n if (summary) out.push(summary, '');\n out.push(`- Family: ${line(c.category)}${c.docs?.status && c.docs.status !== 'stable' ? `, ${c.docs.status}` : ''}`);\n if (c.allTokenPaths.length) out.push(`- Tokens: ${c.allTokenPaths.slice(0, 40).join(', ')}${c.allTokenPaths.length > 40 ? ', ...' : ''}`);\n for (const [label, list] of [\n ['Use it for', strings(d?.whenToUse)],\n ['Not for', strings(d?.whenNotToUse)],\n ['Accessibility', strings(d?.accessibility)],\n ] as const) {\n if (list.length) out.push(`- ${label}:`, ...list.map((x) => ` - ${x}`));\n }\n const dos = Array.isArray(d?.dos) ? d!.dos : [];\n const donts = Array.isArray(d?.donts) ? d!.donts : [];\n for (const g of dos) if (line(g?.title)) out.push(`- Do: ${line(g.title)}${line(g.text) ? `. ${line(g.text)}` : ''}`);\n for (const g of donts) if (line(g?.title)) out.push(`- Don't: ${line(g.title)}${line(g.text) ? `. ${line(g.text)}` : ''}`);\n out.push('');\n }\n return `${out.join('\\n').replace(/\\n{3,}/g, '\\n\\n').trim()}\\n`;\n}\n"],"names":["issueKey","t","isAlias","pairs","p","modesOf","a","idOf","names","cl","STEPS","isObj","text","cs","str","at","line","dr","dg","db","dy","dx","code","by","status","lifecycle","behindMain","preview","exportName","resolve","bg","ch"],"mappings":";;;;AA4CA,MAAMA,aAAW,CAAC,MAAa,GAAG,EAAE,IAAI,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,SAAS,iBAAiB,EAAE,UAAU,EAAE;AACtH,MAAM,WAAW,CAAC,SAAkB,SAAS,cAAc,cAAc,gBAAgB,IAAI;AAE7F,MAAM,YAAY,CAACC,OAAoBA,GAAE,SAAS,WAAWA,GAAE,KAAK,WAAW,UAAU;AACzF,MAAM,aAAa,CAACA,OAAoBA,GAAE,SAAS,eAAeA,GAAE,SAAS;AAG7E,SAAS,UAAU,OAAqC,QAA0C;AAChG,UAAQ,MAAM,MAAA;AAAA,IACZ,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACH,aAAO,OAAO,SAAS,cAAc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