@bridge-ds/core 0.18.0 → 0.19.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/bridge.config.schema.json +16 -0
- package/dist/audit/index.js +3 -3
- package/dist/audit/report.d.ts +17 -2
- package/dist/branch-actions.d.ts +7 -1
- package/dist/build-requests-github.d.ts +25 -0
- package/dist/build-requests.d.ts +403 -0
- package/dist/changelog-model.d.ts +102 -0
- package/dist/component-spec.d.ts +3 -1
- package/dist/config.d.ts +21 -0
- package/dist/css-color.d.ts +25 -0
- package/dist/docs-proposal.d.ts +1 -0
- package/dist/explorations.d.ts +1 -0
- package/dist/fidelity-references.d.ts +12 -0
- package/dist/figma-fix-loop.d.ts +153 -0
- package/dist/figma-fixes.d.ts +169 -0
- package/dist/figma-push-github.d.ts +7 -2
- package/dist/figma-push.d.ts +15 -2
- package/dist/gap-case.d.ts +144 -0
- package/dist/github-client.d.ts +31 -0
- package/dist/id-map.d.ts +10 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +3412 -658
- package/dist/index.js.map +1 -1
- package/dist/layered-review.d.ts +2 -0
- package/dist/measure-status.d.ts +127 -0
- package/dist/measured-only.d.ts +28 -0
- package/dist/measured-spec.d.ts +349 -0
- package/dist/measured-tokens.d.ts +25 -0
- package/dist/motion-docs.d.ts +51 -0
- package/dist/node/audit.d.ts +11 -3
- package/dist/node/index.d.ts +1 -0
- package/dist/node/index.js +1637 -24
- package/dist/node/index.js.map +1 -1
- package/dist/node/measure-script.d.ts +1 -0
- package/dist/node/measure.d.ts +212 -0
- package/dist/node/spec-css.d.ts +9 -1
- package/dist/node/tokens-script.d.ts +3 -0
- package/dist/pr-composer.d.ts +5 -0
- package/dist/previews.d.ts +4 -1
- package/dist/{prod-branch-DenQkr_e.js → prod-branch-Bdx_2bRQ.js} +197 -159
- package/dist/prod-branch-Bdx_2bRQ.js.map +1 -0
- package/dist/prod-branch.d.ts +1 -1
- package/dist/repo-model.d.ts +5 -1
- package/dist/repo-source-github.d.ts +8 -0
- package/dist/{repo-source-CRfhLO87.js → repo-source-m0Tc603o.js} +1406 -629
- package/dist/repo-source-m0Tc603o.js.map +1 -0
- package/dist/repo-source.d.ts +6 -0
- package/dist/{report-DVEmUr0p.js → report-DFPKygfk.js} +17 -6
- package/dist/{report-DVEmUr0p.js.map → report-DFPKygfk.js.map} +1 -1
- package/dist/requester.d.ts +14 -0
- package/dist/requests.d.ts +2 -0
- package/dist/review-gate.d.ts +183 -2
- package/dist/risk.d.ts +12 -0
- package/dist/share-branch.d.ts +1 -1
- package/dist/snapshot.d.ts +34 -0
- package/dist/suggestion-review.d.ts +2 -0
- package/dist/suggestions-github.d.ts +21 -0
- package/dist/suggestions.d.ts +6 -0
- package/dist/token-proposal.d.ts +7 -0
- package/dist/try-in-product.d.ts +9 -0
- package/package.json +1 -1
- package/dist/prod-branch-DenQkr_e.js.map +0 -1
- package/dist/repo-source-CRfhLO87.js.map +0 -1
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","../src/activity.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 // Without a token (a guest on a public repository) bodies come from the raw host by commit and path, which costs no\n // API request; a private or missing file there falls back to the blobs API.\n const body = async (sha: string, e: TreeEntry): Promise<string> => (!client.canWrite ? await client.readRawFile(e.path, sha).catch(() => undefined) : undefined) ?? client.getBlobText(e.sha);\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 body(sha, e)] 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 ? body(sha, e) : 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","// Repo activity: the team's work in progress, written by `bridge snapshot --activity` in the team's CI (with the\n// workflow's GITHUB_TOKEN) and published next to snapshot.json on the bridge-data branch as activity.json. A\n// signed-out visitor of a hosted Studio gets GitHub's 60 API requests an hour, about three page views; with\n// activity.json Home, Branches, Review, History, suggestions and requests read nothing from the API at all.\n//\n// Two parts:\n// - `responses`: the GitHub REST reads (GET) those pages make, as GitHub answered them, trimmed of what no page reads\n// (API links, nested repository objects, diffs). The Studio answers its own GETs from them (activityAnswer), so every\n// view, rule and gate keeps one code path whatever the source, the way snapshotSource() serves the repo model.\n// - Summaries for readers that do not run the Studio (agents, the Library, a status line): open branches, open\n// suggestions with their parsed payload, request issues, recent merges, and the token history report.\n//\n// Pure: no Node, no DOM. The CLI hands it a fetch carrying the token.\n\nimport { GitHubClient, type FetchLike } from './github-client';\nimport type { BridgeConfig } from './config';\nimport { packageDirCandidates, type HistoryReport } from './history';\nimport { gitHubHistoryBackend, loadGitHubHistory } from './history-github';\nimport { parseRequestIssue, requestStatus, REQUEST_LABEL, type RequestKind, type RequestStatus } from './requests';\nimport { effectiveTier } from './review-gate';\nimport type { RiskTier } from './risk';\nimport { getSuggestionOnGitHub, listSuggestionsOnGitHub } from './suggestions-github';\nimport type { SuggestionKind, SuggestionPayloadV1, SuggestionStatus } from './suggestions';\nimport { SNAPSHOT_BRANCH } from './snapshot';\n\nexport const ACTIVITY_SCHEMA_VERSION = 1;\n/** Next to snapshot.json on the bridge-data branch. */\nexport const ACTIVITY_FILE = 'activity.json';\n/** Above this, the recorded reads are dropped heaviest first (trees, then older branches) until it fits. */\nexport const ACTIVITY_MAX_BYTES = 3_000_000;\n/** A guest reads activity.json while it is younger than this; older, the Studio reads GitHub live. */\nexport const ACTIVITY_MAX_AGE_MS = 24 * 60 * 60 * 1000;\n\n/** How much one activity.json carries. Each is a count of items, newest first. */\nexport const ACTIVITY_LIMITS = {\n /** Open pull requests recorded in full (the page of each; the list carries every open one). */\n branches: 30,\n /** Open suggestions read with their comments (parsed payload, counted approvals). */\n suggestions: 30,\n /** Request issues listed (open and closed); open ones are read with their comments. */\n requests: 30,\n /** Merged pull requests summarized. */\n merged: 20,\n /** Token history entries (core loadGitHubHistory limit). */\n history: 20,\n /** History entries whose two commits' file lists are recorded, so their before/after opens without the API. */\n historyTrees: 10,\n} as const;\nexport type ActivityLimits = { [K in keyof typeof ACTIVITY_LIMITS]: number };\n\n/** One GitHub answer: its status (200, or 404 for a read that finds nothing) and its JSON body, trimmed. */\nexport interface ActivityResponse {\n status: number;\n body: unknown;\n}\n\nexport interface ActivityBranch {\n number: number;\n title: string;\n author: string;\n url: string;\n branch: string;\n base: string;\n headSha: string;\n baseSha: string;\n state: 'open' | 'draft';\n labels: string[];\n /** Risk tier from the labels, the body or the files (review-gate effectiveTier); null when none says. */\n tier: RiskTier | null;\n createdAt: string;\n updatedAt: string;\n /** Conversation plus line comments. Null when the branch was not read in full (over the limit). */\n comments: number | null;\n /** Files the branch changes, and the token files among them (the token diff opens from them). Null: not read. */\n files: { changed: number; tokens: string[] } | null;\n /** Previews built for the head commit (commit statuses with a link, success only). */\n previews: { context: string; url: string }[];\n /** Combined check state of the head commit. */\n checks: 'success' | 'failure' | 'pending' | 'none' | null;\n}\n\nexport interface ActivitySuggestion {\n number: number;\n title: string;\n author: string;\n url: string;\n createdAt: string;\n kind: SuggestionKind | null;\n status: SuggestionStatus;\n labels: string[];\n comments: number | null;\n /** The parsed suggestion (null when its block does not parse). */\n payload: SuggestionPayloadV1 | null;\n approvers: string[];\n}\n\nexport interface ActivityRequest {\n number: number;\n title: string;\n author: string;\n url: string;\n state: 'open' | 'closed';\n status: RequestStatus;\n kind: RequestKind | null;\n component: string | null;\n labels: string[];\n createdAt: string;\n}\n\nexport interface ActivityMerged {\n number: number;\n title: string;\n author: string;\n url: string;\n mergedAt: string;\n labels: string[];\n tier: RiskTier | null;\n}\n\nexport interface RepoActivity {\n kind: 'bridge-activity';\n schemaVersion: typeof ACTIVITY_SCHEMA_VERSION;\n tool: { name: 'bridge'; version: string };\n generatedAt: string;\n repo: { owner: string; name: string; branch: string };\n /** Default branch head when it was written. */\n headSha: string;\n branches: ActivityBranch[];\n suggestions: ActivitySuggestion[];\n requests: ActivityRequest[];\n merged: ActivityMerged[];\n /** Token history of the default branch (core HistoryReport), null when it could not be read. */\n history: HistoryReport | null;\n /** GitHub REST answers by activityKey (path relative to api.github.com, query sorted). */\n responses: Record<string, ActivityResponse>;\n /** What was left out to stay within the limits, in words. */\n truncated: string[];\n /** What could not be read. */\n problems: string[];\n}\n\nexport class ActivityError extends Error {}\n\nconst isObj = (x: unknown): x is Record<string, unknown> => !!x && typeof x === 'object' && !Array.isArray(x);\nconst API = 'https://api.github.com';\n\n/**\n * The key of a GitHub REST read: the path relative to api.github.com with the query parameters sorted, and the\n * owner and repository (or user) lowercased, since GitHub reads them without case. Null for any other host.\n */\nexport function activityKey(url: string): string | null {\n let u: URL;\n try {\n u = new URL(url, API);\n } catch {\n return null;\n }\n if (u.origin !== API) return null;\n const parts = u.pathname.split('/');\n if (parts[1] === 'repos' && parts.length > 3) {\n parts[2] = parts[2]!.toLowerCase();\n parts[3] = parts[3]!.toLowerCase();\n } else if (parts[1] === 'users' && parts.length > 2) parts[2] = parts[2]!.toLowerCase();\n const q = [...u.searchParams].sort(([a, av], [b, bv]) => (a === b ? (av < bv ? -1 : 1) : a < b ? -1 : 1));\n const search = q.length ? `?${new URLSearchParams(q).toString()}` : '';\n return parts.join('/') + search;\n}\n\n// --- trimming -----------------------------------------------------------------------------------------------------\n\n/** URL fields a page reads; every other `*_url` and `url` is an API link nothing follows. */\nconst KEPT_URLS = new Set(['html_url', 'avatar_url', 'target_url', 'details_url', 'environment_url', 'raw_url']);\n/** Fields no page reads that weigh the most. */\nconst DROPPED = new Set(['_links', 'patch', 'body_html', 'body_text', 'reactions', 'performed_via_github_app', 'node_id', 'gravatar_id', 'user_view_type', 'site_admin', 'event', 'sub_issues_summary', 'issue_dependencies_summary', 'pull_request_review_id']);\nconst LONG_TEXT = 60_000;\n\nconst trimUser = (u: Record<string, unknown>) => ({\n login: u.login,\n ...(u.id !== undefined ? { id: u.id } : {}),\n ...(u.avatar_url ? { avatar_url: u.avatar_url } : {}),\n ...(u.html_url ? { html_url: u.html_url } : {}),\n ...(u.type ? { type: u.type } : {}),\n});\n\nconst trimRepo = (r: Record<string, unknown>) => ({\n ...(r.id !== undefined ? { id: r.id } : {}),\n name: r.name,\n full_name: r.full_name,\n ...(r.private !== undefined ? { private: r.private } : {}),\n ...(r.fork !== undefined ? { fork: r.fork } : {}),\n ...(r.default_branch ? { default_branch: r.default_branch } : {}),\n ...(isObj(r.owner) ? { owner: trimUser(r.owner) } : {}),\n ...(r.html_url ? { html_url: r.html_url } : {}),\n});\n\n/**\n * A GitHub answer without what no page reads: API links, node ids, diffs, reactions, the repository objects nested in\n * a pull request's head and base (name, owner and fork kept), and user objects beyond login, avatar and type. A tree\n * keeps path, type and sha per entry. Strings longer than 60 000 characters are cut.\n */\nexport function trimGitHub(value: unknown, key = ''): unknown {\n if (typeof value === 'string') return value.length > LONG_TEXT ? value.slice(0, LONG_TEXT) : value;\n if (Array.isArray(value)) return value.map((v) => trimGitHub(v, key));\n if (!isObj(value)) return value;\n if (key === 'tree' && typeof value.path === 'string' && typeof value.type === 'string') return { path: value.path, type: value.type, sha: value.sha, ...(value.mode ? { mode: value.mode } : {}) };\n if ((key === 'repo' || key === 'repository' || key === 'head_repository') && typeof value.full_name === 'string') return trimRepo(value);\n if (typeof value.login === 'string' && ('avatar_url' in value || 'type' in value)) return trimUser(value);\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) {\n if (DROPPED.has(k)) continue;\n if ((k === 'url' || k.endsWith('_url')) && !KEPT_URLS.has(k)) continue;\n if (k === 'output' && isObj(v)) {\n out[k] = { title: v.title ?? null, summary: typeof v.summary === 'string' ? v.summary.slice(0, 2000) : null, annotations_count: v.annotations_count ?? 0 };\n continue;\n }\n if (k === 'app' && isObj(v)) {\n out[k] = { id: v.id, slug: v.slug, name: v.name };\n continue;\n }\n out[k] = trimGitHub(v, k);\n }\n return out;\n}\n\n// --- recording ----------------------------------------------------------------------------------------------------\n\nconst JSON_ACCEPT = /application\\/(vnd\\.github\\+)?json/;\n/** What a recordingFetch shaper returns for a read it should not keep. */\nexport const SKIP: unique symbol = Symbol('skip');\n\n/**\n * The paths of a tree the Studio reads from a recorded tree: token files and the contrast checks (the branch token\n * diff), bridge.config.json, changesets, and the CHANGELOG.md and package.json the history reads. Every other entry is\n * left out of activity.json, which keeps a tree at a few kilobytes instead of a whole repository listing.\n */\nexport function activityTreeFilter(config: BridgeConfig): (path: string) => boolean {\n const under = (dir: string | undefined) => {\n const d = (dir ?? '').replace(/^\\.\\/|\\/$/g, '');\n return d && d !== '.' ? `${d}/` : '';\n };\n const tokens = under(config.tokens.root);\n const changesets = config.changesets ? under(config.changesets.dir) : null;\n const pkg = new Set(packageDirCandidates(config).flatMap((d) => [d ? `${d}/CHANGELOG.md` : 'CHANGELOG.md', d ? `${d}/package.json` : 'package.json']));\n return (p) => p === 'bridge.config.json' || pkg.has(p) || (tokens ? p.startsWith(tokens) : p.endsWith('.json')) || (changesets !== null && changesets !== '' && p.startsWith(changesets));\n}\n\n/** History internals the Studio never reads from a recorded answer (it reads the history report instead). */\nconst UNREAD = [/\\/git\\/blobs\\//, /\\/commits\\/[^/]+\\/pulls$/, /\\/commits\\?/, /\\/tags\\?/, /\\/contents\\//];\n\n/** The shaper collectActivity records with: trees filtered (activityTreeFilter), compares to what a branch page reads. */\nexport function activityShaper(config: BridgeConfig): (key: string, body: unknown) => unknown | typeof SKIP {\n const keep = activityTreeFilter(config);\n return (key, body) => {\n if (UNREAD.some((r) => r.test(key))) return SKIP;\n if (key.includes('/git/trees/') && isObj(body) && Array.isArray(body.tree)) return { sha: body.sha, tree: (body.tree as { path: string }[]).filter((e) => keep(e.path)), truncated: Boolean(body.truncated) };\n if (key.includes('/compare/') && isObj(body)) {\n const c = body as Record<string, any>;\n return {\n status: c.status,\n ahead_by: c.ahead_by,\n behind_by: c.behind_by,\n total_commits: c.total_commits,\n merge_base_commit: c.merge_base_commit ? { sha: c.merge_base_commit.sha } : null,\n base_commit: c.base_commit ? { sha: c.base_commit.sha, commit: { tree: { sha: c.base_commit.commit?.tree?.sha } } } : null,\n files: Array.isArray(c.files) ? c.files.map((f: Record<string, unknown>) => ({ filename: f.filename, status: f.status, ...(f.previous_filename ? { previous_filename: f.previous_filename } : {}), sha: f.sha, additions: f.additions, deletions: f.deletions, changes: f.changes })) : [],\n };\n }\n return body;\n };\n}\n\n/** Changes listed per history entry; an import of hundreds of tokens keeps its counts and its first changes. */\nexport const HISTORY_MAX_CHANGES = 100;\n\n/** A history report with each entry's change and reason lists capped (counts stay whole). */\nexport function capHistory(report: HistoryReport, max = HISTORY_MAX_CHANGES): HistoryReport {\n return {\n ...report,\n entries: report.entries.map((e) => (e.changes.length > max || (e.reasons?.length ?? 0) > max ? { ...e, changes: e.changes.slice(0, max), ...(e.reasons ? { reasons: e.reasons.slice(0, max) } : {}) } : e)),\n };\n}\n\n/**\n * Wraps a fetch and records every GitHub REST GET that answers 200 or 404 with JSON, trimmed, under its activityKey.\n * Reads with another media type (raw file bodies) pass through unrecorded.\n */\nexport function recordingFetch(fetchImpl: FetchLike, into: Map<string, ActivityResponse>, shape: (key: string, body: unknown) => unknown | typeof SKIP = (_k, b) => b): FetchLike {\n return async (url, init) => {\n const res = await fetchImpl(url, init);\n const method = (init?.method ?? 'GET').toUpperCase();\n const accept = init?.headers?.Accept ?? init?.headers?.accept ?? 'application/vnd.github+json';\n const key = activityKey(url);\n if (method !== 'GET' || !key || !JSON_ACCEPT.test(accept) || (res.status !== 200 && res.status !== 404)) return res;\n const text = await res.text();\n let body: unknown;\n try {\n body = JSON.parse(text);\n } catch {\n return { ok: res.ok, status: res.status, headers: res.headers, json: async () => JSON.parse(text), text: async () => text };\n }\n const shaped = shape(key, trimGitHub(body));\n if (shaped !== SKIP) into.set(key, { status: res.status, body: shaped });\n return { ok: res.ok, status: res.status, ...(res.headers ? { headers: res.headers } : {}), json: async () => JSON.parse(text) as unknown, text: async () => text };\n };\n}\n\n// --- collecting ---------------------------------------------------------------------------------------------------\n\nexport interface CollectActivityInput {\n /** fetch for api.github.com (the token goes in `token`). */\n fetch: FetchLike;\n token: string;\n owner: string;\n repo: string;\n /** The repository's Bridge config (tokens root, governance, changesets): history and suggestion approvals read it. */\n config: BridgeConfig;\n version: string;\n generatedAt?: string;\n /**\n * The activity published last time. Its history (and the file lists recorded for it) is kept when the default\n * branch head has not moved, which saves most of the reads of a run on a schedule or a pull request event.\n */\n previous?: RepoActivity | null;\n limits?: Partial<ActivityLimits>;\n}\n\ninterface RawPull {\n number: number;\n title: string;\n html_url: string;\n draft?: boolean;\n state: string;\n body?: string | null;\n user?: { login?: string } | null;\n labels?: ({ name?: string } | string)[];\n head: { ref: string; sha: string };\n base: { ref: string; sha: string };\n created_at: string;\n updated_at: string;\n merged_at?: string | null;\n comments?: number;\n review_comments?: number;\n}\n\nconst labelObjs = (labels: RawPull['labels']) => labelNames(labels).map((name) => ({ name }));\nfunction labelNames(labels: RawPull['labels']): string[] {\n return (labels ?? []).map((l) => (typeof l === 'string' ? l : (l.name ?? ''))).filter(Boolean);\n}\nconst byUpdated = <T extends { updated_at: string }>(a: T, b: T) => (a.updated_at < b.updated_at ? 1 : a.updated_at > b.updated_at ? -1 : 0);\n\n/**\n * Reads the team's activity from GitHub: the same reads, with the same paths, as the hosted Studio's guest pages\n * (Home, Branches and each open branch, Review, History, suggestions, requests), recorded, plus the summaries. A read\n * that fails is noted in `problems` and the rest goes on; an exhausted hourly limit stops the reading there.\n */\nexport async function collectActivity(input: CollectActivityInput): Promise<RepoActivity> {\n const limits: ActivityLimits = { ...ACTIVITY_LIMITS, ...input.limits };\n const responses = new Map<string, ActivityResponse>();\n const rec = recordingFetch(input.fetch, responses, activityShaper(input.config));\n const client = new GitHubClient(`${input.owner}/${input.repo}`, input.token, rec, { attempts: 2, baseDelayMs: 500, sleep: (ms) => new Promise((r) => setTimeout(r, ms)) }, { etags: false });\n const R = `/repos/${input.owner}/${input.repo}`;\n const problems: string[] = [];\n const truncated: string[] = [];\n let limited = false;\n const headers: Record<string, string> = { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28', ...(input.token ? { Authorization: `Bearer ${input.token}` } : {}) };\n\n /** One GET of a path as the Studio writes it; undefined when it failed (noted). */\n const get = async <T>(path: string): Promise<T | undefined> => {\n if (limited) return undefined;\n try {\n const res = await rec(`${API}${path}`, { headers });\n if (res.status === 404) return undefined;\n if (!res.ok) {\n if ((res.status === 403 || res.status === 429) && res.headers?.get('x-ratelimit-remaining') === '0') {\n limited = true;\n problems.push('GitHub hourly limit reached while reading activity: the rest was left out.');\n } else problems.push(`GitHub answered ${res.status} for ${path}`);\n return undefined;\n }\n return (await res.json()) as T;\n } catch (err) {\n problems.push(`Could not read ${path}: ${(err as Error).message}`);\n return undefined;\n }\n };\n /** A core read; its failure is noted and gives `fallback`. */\n const safely = async <T>(what: string, fn: () => Promise<T>, fallback: T): Promise<T> => {\n if (limited) return fallback;\n try {\n return await fn();\n } catch (err) {\n const msg = (err as Error).message;\n if (/limit/i.test(msg) && (err as { status?: number }).status === 429) limited = true;\n problems.push(`${what}: ${msg}`);\n return fallback;\n }\n };\n\n // The repository and its default branch head (every team page reads both first).\n const info = await safely('Repository', () => client.getRepo(), null);\n const branch = info?.defaultBranch ?? input.config.repo?.defaultBranch ?? 'main';\n const headSha = (await safely('Default branch', () => client.getBranchSha(branch), undefined)) ?? '';\n\n // Branches: the open list, the closed lists the Branches and Requests views read, then each open branch's page.\n const open = (await get<RawPull[]>(`${R}/pulls?state=open&per_page=100`)) ?? [];\n const closed = (await get<RawPull[]>(`${R}/pulls?state=closed&sort=updated&direction=desc&per_page=30`)) ?? [];\n await get(`${R}/pulls?state=closed&per_page=50&sort=updated&direction=desc`);\n await get(`${R}/rules/branches/${encodeURIComponent(branch)}`);\n await get(`${R}/git/matching-refs/heads/bridge-visual`);\n await safely('Owner account', () => client.getAccountType(input.owner), null);\n\n // What the last activity recorded, reused where nothing changed (keeps a scheduled run to a few requests).\n const prev = input.previous ?? null;\n const sameRepoPrev = Boolean(prev && sameRepo(prev, input));\n const prevOk = sameRepoPrev && Boolean(headSha) && prev!.headSha === headSha;\n /** A read the last activity recorded, when `reuse`; else read now. */\n const kept = async <T>(path: string, reuse: boolean): Promise<T | undefined> => {\n const key = reuse ? activityKey(`${API}${path}`) : null;\n const hit = key ? prev!.responses[key] : undefined;\n if (key && hit) {\n responses.set(key, hit);\n return hit.status === 200 ? (hit.body as T) : undefined;\n }\n return get<T>(path);\n };\n\n const branches: ActivityBranch[] = [];\n const sorted = [...open].sort(byUpdated);\n if (sorted.length > limits.branches) truncated.push(`${sorted.length - limits.branches} open branches beyond the ${limits.branches} most recently updated are listed without their pages.`);\n for (const [i, p] of sorted.entries()) {\n const full = i < limits.branches;\n const base: ActivityBranch = {\n number: p.number,\n title: p.title,\n author: p.user?.login ?? '',\n url: p.html_url,\n branch: p.head.ref,\n base: p.base.ref,\n headSha: p.head.sha,\n baseSha: p.base.sha,\n state: p.draft ? 'draft' : 'open',\n labels: labelNames(p.labels),\n tier: effectiveTier(labelObjs(p.labels), p.body ?? null, null),\n createdAt: p.created_at,\n updatedAt: p.updated_at,\n comments: null,\n files: null,\n previews: [],\n checks: null,\n };\n if (!full || limited) {\n branches.push(base);\n continue;\n }\n const n = p.number;\n // A branch nobody touched since the last activity (same update time, same head, same default branch head) keeps\n // its recorded page; its checks and statuses are read again (they change without touching the pull request).\n // Trees are named by commit and never change.\n const was = prevOk ? prev!.branches.find((b) => b.number === n) : undefined;\n const same = Boolean(was && was.updatedAt === p.updated_at && was.headSha === p.head.sha && was.comments !== null);\n const [pull, files, , , , , status] = await Promise.all([\n kept<RawPull>(`${R}/pulls/${n}`, same),\n kept<{ filename: string; status?: string }[]>(`${R}/pulls/${n}/files?per_page=100`, same),\n kept(`${R}/pulls/${n}/reviews?per_page=100`, same),\n kept(`${R}/issues/${n}/comments?per_page=100`, same),\n kept(`${R}/pulls/${n}/comments?per_page=100`, same),\n get(`${R}/commits/${p.head.sha}/check-runs?per_page=100`),\n get<{ state?: string; statuses?: { context: string; state: string; target_url?: string | null }[] }>(`${R}/commits/${p.head.sha}/status`),\n kept(`${R}/compare/${encodeURIComponent(p.base.ref)}...${p.head.sha}`, same),\n kept(`${R}/git/trees/${p.base.sha}?recursive=1`, sameRepoPrev),\n kept(`${R}/git/trees/${p.head.sha}?recursive=1`, sameRepoPrev),\n kept(`${R}/issues/${n}/labels`, same),\n ]);\n const root = input.config.tokens.root.replace(/\\/$/, '');\n branches.push({\n ...base,\n tier: effectiveTier(labelObjs((pull ?? p).labels), (pull ?? p).body ?? null, files ?? null),\n comments: pull ? (pull.comments ?? 0) + (pull.review_comments ?? 0) : null,\n files: files ? { changed: files.length, tokens: files.map((f) => f.filename).filter((f) => f.startsWith(`${root}/`) && f.endsWith('.json')) } : null,\n previews: (status?.statuses ?? []).filter((s) => s.state === 'success' && s.target_url && /^https:\\/\\//.test(s.target_url)).map((s) => ({ context: s.context, url: s.target_url! })),\n checks: status ? (status.state === 'success' || status.state === 'failure' || status.state === 'pending' ? status.state : 'none') : null,\n });\n }\n\n // Suggestions: the open list as Branches reads it, then each one as its page reads it (payload, approvals).\n const gov = { owners: input.config.governance.owners, rights: input.config.governance.rights, soloOwnerCanApproveBoth: input.config.governance.soloOwnerCanApproveBoth };\n const items = await safely('Suggestions', () => listSuggestionsOnGitHub(client, { state: 'open' }), []);\n const pullsAll = items.length ? await safely('Pull requests', () => client.listPullRequests('all'), []) : [];\n if (items.length > limits.suggestions) truncated.push(`${items.length - limits.suggestions} open suggestions beyond the ${limits.suggestions} newest are listed without their pages.`);\n const suggestions: ActivitySuggestion[] = [];\n for (const [i, s] of items.entries()) {\n const d = i < limits.suggestions ? await safely(`Suggestion #${s.number}`, () => getSuggestionOnGitHub(client, s.number, gov, { pulls: pullsAll }), null) : null;\n suggestions.push({\n number: s.number,\n title: s.title,\n author: s.author,\n url: s.url,\n createdAt: s.createdAt,\n kind: s.kind ?? null,\n status: d?.status ?? s.status,\n labels: s.labels,\n comments: d ? d.comments.length : null,\n payload: d?.parsed.ok ? d.parsed.payload : null,\n approvers: d?.approvals?.approvers ?? [],\n });\n }\n\n // Requests: the list the Requests view reads, and each open one as its page reads it.\n const issues = await safely('Requests', () => client.listIssues({ label: REQUEST_LABEL, state: 'all', perPage: 50 }), []);\n const requests: ActivityRequest[] = [];\n const openIssues = issues.filter((i) => i.state === 'open');\n if (openIssues.length > limits.requests) truncated.push(`${openIssues.length - limits.requests} open requests beyond the ${limits.requests} newest are listed without their pages.`);\n for (const [i, r] of issues.slice(0, Math.max(limits.requests, 0)).entries()) {\n if (r.state === 'open' && i < limits.requests) {\n await get(`${R}/issues/${r.number}`);\n await get(`${R}/issues/${r.number}/comments?per_page=100`);\n }\n const parsed = parseRequestIssue(r.body);\n const linked = [...open, ...closed].filter((p) => new RegExp(`(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\\\\s+#${r.number}\\\\b`, 'i').test(p.body ?? ''));\n requests.push({\n number: r.number,\n title: r.title,\n author: r.author,\n url: r.url,\n state: r.state,\n status: requestStatus({ state: r.state, stateReason: r.stateReason, linkedPrs: linked.map((p) => ({ state: p.state === 'open' ? 'open' : 'closed', merged: Boolean(p.merged_at) })) }),\n kind: parsed?.kind ?? null,\n component: parsed?.component ?? null,\n labels: r.labels,\n createdAt: r.createdAt,\n });\n }\n\n const merged: ActivityMerged[] = closed\n .filter((p) => p.merged_at)\n .slice(0, limits.merged)\n .map((p) => ({ number: p.number, title: p.title, author: p.user?.login ?? '', url: p.html_url, mergedAt: p.merged_at!, labels: labelNames(p.labels), tier: effectiveTier(labelObjs(p.labels), p.body ?? null, null) }));\n\n // Token history: kept from the last activity while the head has not moved (it is the costly part), else read again,\n // with the file lists of the newest entries' commits so their before/after opens without the API.\n let history: HistoryReport | null = null;\n if (prevOk && prev!.history) {\n history = prev!.history;\n for (const [k, v] of Object.entries(prev!.responses)) if (isHistoryKey(k) && !responses.has(k)) responses.set(k, v);\n } else if (!limited && headSha) {\n const read = await safely('Token history', () => loadGitHubHistory(client, input.config, { ref: branch, limit: limits.history }), null);\n history = read && capHistory(read);\n if (history) {\n const backend = gitHubHistoryBackend(client, input.config, { concurrency: 2 });\n const shas = [...new Set(history.entries.filter((e) => !e.bulk).slice(0, limits.historyTrees).flatMap((e) => [e.sha, ...(e.baseSha ? [e.baseSha] : [])]))];\n for (const sha of shas) await safely(`Files at ${sha.slice(0, 7)}`, () => backend.tree(sha), []);\n }\n }\n\n const activity: RepoActivity = {\n kind: 'bridge-activity',\n schemaVersion: ACTIVITY_SCHEMA_VERSION,\n tool: { name: 'bridge', version: input.version },\n generatedAt: input.generatedAt ?? new Date().toISOString(),\n repo: { owner: input.owner, name: input.repo, branch },\n headSha,\n branches,\n suggestions,\n requests,\n merged,\n history,\n responses: Object.fromEntries([...responses].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))),\n truncated,\n problems,\n };\n return fitActivity(activity);\n}\n\nconst sameRepo = (a: RepoActivity, b: { owner: string; repo: string }) => a.repo.owner.toLowerCase() === b.owner.toLowerCase() && a.repo.name.toLowerCase() === b.repo.toLowerCase();\nconst isHistoryKey = (k: string) => /\\/git\\/commits\\/[0-9a-f]+$/.test(k) || /\\/git\\/trees\\/[0-9a-f]+\\?recursive=1$/.test(k);\n\n/** Bytes of the activity as written. */\nexport const activityBytes = (a: RepoActivity): number => new TextEncoder().encode(`${JSON.stringify(a)}\\n`).length;\n\n/**\n * Keeps the activity under `max` bytes: drops the recorded file lists (trees) first, then the pages of the least\n * recently updated branches, then every recorded read. The summaries always stay. Says what it dropped in `truncated`.\n */\nexport function fitActivity(activity: RepoActivity, max = ACTIVITY_MAX_BYTES): RepoActivity {\n if (activityBytes(activity) <= max) return activity;\n const out = { ...activity, responses: { ...activity.responses }, truncated: [...activity.truncated] };\n const drop = (test: (k: string) => boolean) => {\n for (const k of Object.keys(out.responses)) if (test(k)) delete out.responses[k];\n };\n drop((k) => k.includes('/git/trees/'));\n out.truncated.push('File lists were left out to keep activity.json small: a branch or history change reads them from GitHub.');\n if (activityBytes(out) <= max) return out;\n const old = [...out.branches].sort((a, b) => (a.updatedAt < b.updatedAt ? -1 : 1));\n for (const b of old) {\n drop((k) => new RegExp(`/(pulls|issues)/${b.number}(/|$|\\\\?)`).test(k) || k.includes(`/commits/${b.headSha}/`) || k.includes(`...${b.headSha}`));\n if (activityBytes(out) <= max) {\n out.truncated.push('The pages of the least recently updated branches were left out: they read from GitHub.');\n return out;\n }\n }\n out.responses = {};\n out.truncated.push('Every recorded read was left out: pages read GitHub live.');\n return out;\n}\n\n// --- reading ------------------------------------------------------------------------------------------------------\n\n/** Validates an activity (text or parsed JSON). Throws ActivityError naming the first problem. */\nexport function parseActivity(input: string | unknown): RepoActivity {\n let data: unknown = input;\n if (typeof input === 'string') {\n try {\n data = JSON.parse(input);\n } catch (err) {\n throw new ActivityError(`${ACTIVITY_FILE} is not valid JSON (${(err as Error).message})`);\n }\n }\n if (!isObj(data) || data.kind !== 'bridge-activity') throw new ActivityError(`${ACTIVITY_FILE} is not a Bridge activity file`);\n if (data.schemaVersion !== ACTIVITY_SCHEMA_VERSION) throw new ActivityError(`${ACTIVITY_FILE} is schema version ${String(data.schemaVersion)}; this version of Bridge reads ${ACTIVITY_SCHEMA_VERSION}`);\n const repo = data.repo;\n if (!isObj(repo) || typeof repo.owner !== 'string' || typeof repo.name !== 'string' || typeof repo.branch !== 'string') throw new ActivityError(`${ACTIVITY_FILE}: repo needs owner, name and branch`);\n if (typeof data.generatedAt !== 'string' || Number.isNaN(Date.parse(data.generatedAt))) throw new ActivityError(`${ACTIVITY_FILE}: generatedAt is missing`);\n for (const k of ['branches', 'suggestions', 'requests', 'merged', 'truncated', 'problems'] as const) if (!Array.isArray(data[k])) throw new ActivityError(`${ACTIVITY_FILE}: ${k} must be a list`);\n if (!isObj(data.responses) || !Object.values(data.responses).every((r) => isObj(r) && typeof r.status === 'number')) throw new ActivityError(`${ACTIVITY_FILE}: responses must map paths to { status, body }`);\n if (data.history !== null && !(isObj(data.history) && Array.isArray(data.history.entries))) throw new ActivityError(`${ACTIVITY_FILE}: history must be null or a history report`);\n return data as unknown as RepoActivity;\n}\n\n/** Milliseconds since the activity was written (never negative). */\nexport const activityAge = (a: Pick<RepoActivity, 'generatedAt'>, now = Date.now()): number => Math.max(0, now - Date.parse(a.generatedAt));\n\n/** True while a guest should read the activity instead of GitHub: written for this repository, and recently. */\nexport function activityIsUsable(a: Pick<RepoActivity, 'generatedAt' | 'repo'>, team: { owner: string; repo: string }, now = Date.now(), maxAge = ACTIVITY_MAX_AGE_MS): boolean {\n return a.repo.owner.toLowerCase() === team.owner.toLowerCase() && a.repo.name.toLowerCase() === team.repo.toLowerCase() && activityAge(a, now) <= maxAge;\n}\n\n/**\n * The recorded answer to a GitHub REST GET, or undefined when the activity did not record it (read it live). Only\n * reads of the activity's own repository (and the user accounts it recorded) are answered.\n */\nexport function activityAnswer(a: Pick<RepoActivity, 'responses' | 'repo'>, url: string): ActivityResponse | undefined {\n const key = activityKey(url);\n if (!key) return undefined;\n const own = `/repos/${a.repo.owner.toLowerCase()}/${a.repo.name.toLowerCase()}`;\n if (!(key === own || key.startsWith(`${own}/`) || key.startsWith(`${own}?`) || key.startsWith('/users/'))) return undefined;\n return Object.prototype.hasOwnProperty.call(a.responses, key) ? a.responses[key] : undefined;\n}\n\n/** \"activity.json\" on the bridge-data branch of a public repository, on the raw host (no API quota). */\nexport const activityRawUrl = (owner: string, repo: string): string => `https://raw.githubusercontent.com/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/${SNAPSHOT_BRANCH}/${ACTIVITY_FILE}`;\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","av","bv","shape"],"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,SAAY,GAAG,WAAW,MAAM,IAAI,CAAC;AAAA,IAC5E,KAAK;AACH,UAAI,MAAM,SAAS,SAAS;AAC1B,YAAI,UAAU,MAAM,EAAG,QAAO;AAC9B,YAAI,OAAO,SAAS,eAAe,OAAO,KAAK,WAAW,cAAc,EAAG,QAAO;AAClF,eAAO;AAAA,MACT;AACA,aAAO,OAAO,SAAS,eAAe,OAAO,SAAS,UAAU,SAAY;AAAA,IAC9E,KAAK;AACH,UAAI,UAAU,MAAM,KAAK,WAAW,MAAM,EAAG,QAAO;AACpD,aAAO,OAAO,SAAS,cAAc,6EAA6E;AAAA,EAAA;AAExH;AAGA,MAAM,aAAqB,CAAC,SAAS,YAAY,WAAW,WAAW;AAEvE,SAAS,WAAW,KAAe,OAAmD,OAAgB,MAAc,OAAe,QAAuB;AACxJ,MAAI,CAACC,UAAQ,KAAK,GAAG;AACnB,QAAI,WAAW,SAAS,MAAM,IAAI,KAAK,UAAU,QAAW;AAC1D,aAAO,KAAK;AAAA,QACV,MAAM;AAAA,QACN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,KAAK,CAAC,IAAI,mBAAmB,IAAI,CAAC,IAAI,eAAe,IAAI,aAAa;"}
|
|
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/try-in-product.ts","../src/explorations-github.ts","../src/measured-tokens.ts","../src/measure-status.ts","../src/fidelity.ts","../src/fidelity-references.ts","../src/gap-case.ts","../src/figma-fixes.ts","../src/measured-only.ts","../src/figma-fix-loop.ts","../src/library-update.ts","../src/branch-actions.ts","../src/share-branch.ts","../src/combine-branches.ts","../src/prod-branch-github.ts","../src/token-proposal.ts","../src/figma-push-github.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/changelog-model.ts","../src/motion-docs.ts","../src/snapshot.ts","../src/activity.ts","../src/build-requests.ts","../src/build-requests-github.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 * Tokens the code renamed between two commits: removed and added between `base` and `head` with the same type, tier\n * and values and a similar path. One pair per token; a token that matches more than one counterpart equally is left\n * as a removal and an addition (no guess). Lets a pull rename the Figma variable instead of orphaning it and adding a\n * new one, so everything bound to it keeps its binding.\n */\nexport function remoteRenames(base: Map<string, LogicalToken>, head: Map<string, LogicalToken>): { from: LogicalToken; to: LogicalToken }[] {\n const removed = [...base.values()].filter((t) => !head.has(t.id));\n const added = [...head.values()].filter((t) => !base.has(t.id));\n const score = (a: LogicalToken, b: LogicalToken) => (sameContent(a, b) ? pathSimilarity(a.path, b.path) : 0);\n const best = (list: LogicalToken[], other: (x: LogicalToken) => number) => {\n const ranked = list.map((x) => ({ x, s: other(x) })).filter((r) => r.s >= SIMILARITY_THRESHOLD).sort((a, b) => b.s - a.s);\n return ranked[0] && (!ranked[1] || ranked[1].s < ranked[0].s) ? ranked[0].x : undefined;\n };\n const out: { from: LogicalToken; to: LogicalToken }[] = [];\n for (const r of removed) {\n const a = best(added, (x) => score(r, x));\n // Both ways: the added token's best match is this removed one.\n if (a && best(removed, (x) => score(x, a)) === r) out.push({ from: r, to: a });\n }\n return out;\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 // Without a token (a guest on a public repository) bodies come from the raw host by commit and path, which costs no\n // API request; a private or missing file there falls back to the blobs API.\n const body = async (sha: string, e: TreeEntry): Promise<string> => (!client.canWrite ? await client.readRawFile(e.path, sha).catch(() => undefined) : undefined) ?? client.getBlobText(e.sha);\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 body(sha, e)] 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 ? body(sha, e) : 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 // A sentence ends at . ! or ? followed by a space or the end: a dot inside a token path (tag.bg) is not an end.\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","// \"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\n/**\n * True when nothing reported an online preview of the branch (no Vercel status, deployment or comment, only config\n * templates): explorations and library branches are not deployed, a developer tries them on their machine.\n */\nexport function noOnlinePreview(previews: readonly { source: string | null }[]): boolean {\n return previews.every((p) => !p.source || p.source === 'template');\n}\n\n/** The command that puts a branch on a developer's machine, quoted when the name has shell characters. */\nexport function localTryCommand(branch: string): string {\n const name = /^[\\w./-]+$/.test(branch) ? branch : `'${branch.replace(/'/g, `'\\\\''`)}'`;\n return `git fetch origin && git switch ${name}`;\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';\nimport { noOnlinePreview } from './try-in-product';\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 // Not deployed (nothing reported once the test build is done): nothing more will come, polling can stop.\n return { tryIt, previews, settled: tryIt.state !== 'building' && (previewsSettled(previews) || noOnlinePreview(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","// Tokens from a measure: the custom properties a design system's CSS defines (`bridge specs --measure --tokens`, the\n// `tokens` of measured-specs.json) written as a two-tier DTCG repo Bridge reads like any other: Primitives (one value)\n// and Semantic (aliases, one file per mode). For a design system that ships no token files, only CSS.\n//\n// - Only the properties measured stories use, with their alias targets (the harvest marks them `used`).\n// - A primitive holds one value. A property whose literal changes with the mode (compiled themes: Carbon, Primer) is\n// semantic: in each mode it aliases the primitive holding that value, an existing one or a palette entry made for it.\n// - A semantic property aliases its declared target when that target is a fixed primitive, else the primitive of its\n// value in each mode: the two tiers never chain semantic to semantic.\n// - The first mode set the measure read is the theme axis (one Figma mode per value).\n//\n// Pure: no Node or DOM API.\n\nimport type { MeasuredSpecsFile, MeasuredTokenProperty, MeasuredTokens } from './measured-spec';\n\nexport interface TokenRepoFromMeasure {\n /** Files relative to `root` (`primitives/measured.tokens.json`, `semantic/<mode>.tokens.json`). */\n files: Record<string, string>;\n /** bridge.config.json for them. */\n config: Record<string, unknown>;\n /** CSS custom property -> token path written (`--cds-layer-01` -> layer.01). */\n paths: Map<string, string>;\n report: { primitives: number; semantic: number; palette: number; modes: string[]; skipped: string[] };\n}\n\ntype Value = string | number;\n\nconst hex2 = (x: number) => Math.round(Math.max(0, Math.min(255, x))).toString(16).padStart(2, '0');\n\n/** `rgb(31, 41, 55)` / `rgba(...)` -> 0..255 channels and alpha. */\nfunction rgbOf(v: string): { r: number; g: number; b: number; a: number } | undefined {\n const m = /^rgba?\\(([^)]*)\\)$/i.exec(v.trim());\n if (!m) return undefined;\n const [r, g, b, a] = m[1]!.split(/[\\s,/]+/).filter(Boolean).map((x) => (x.endsWith('%') ? Number(x.slice(0, -1)) / 100 : Number(x)));\n return [r, g, b].every((x) => x !== undefined && Number.isFinite(x)) ? { r: r!, g: g!, b: b!, a: a === undefined || !Number.isFinite(a) ? 1 : a } : undefined;\n}\n\n/** A DTCG $type and $value for a measured value, or undefined when Bridge has no variable for it. */\nfunction dtcg(type: MeasuredTokenProperty['type'], v: Value, name: string): { $type: string; $value: unknown } | undefined {\n // An empty value (a variable that resolves to nothing, or to itself) is no token: what uses it keeps its computed value.\n if (typeof v === 'string' && !v.trim()) return undefined;\n if (type === 'color' && typeof v === 'string') {\n const c = rgbOf(v);\n if (!c) return undefined;\n const hex = `#${hex2(c.r)}${hex2(c.g)}${hex2(c.b)}${c.a < 1 ? hex2(c.a * 255) : ''}`;\n return { $type: 'color', $value: { colorSpace: 'srgb', components: [c.r / 255, c.g / 255, c.b / 255], ...(c.a < 1 ? { alpha: c.a } : {}), hex } };\n }\n if (type === 'length' && typeof v === 'number') return { $type: 'dimension', $value: { value: v, unit: 'px' } };\n if (type === 'number' && typeof v === 'number') return { $type: 'number', $value: v };\n if (type === 'string' && typeof v === 'string' && /font-?family/i.test(name)) {\n const families = v.split(',').map((f) => f.trim().replace(/^[\"']|[\"']$/g, '')).filter(Boolean);\n return families.length ? { $type: 'fontFamily', $value: families } : undefined;\n }\n return undefined;\n}\n\n/** Same value for the palette index: colors as hex, lengths and numbers as text. */\nconst valueKey = (type: string, v: Value) => `${type}:${typeof v === 'string' ? (rgbOf(v) ? Object.values(rgbOf(v)!).join(',') : v) : v}`;\n\n/** A token path from the measure's (`layer/background` -> layer.background), unique, never both a token and a group. */\nfunction dotPaths(props: MeasuredTokenProperty[]): Map<string, string> {\n const base = new Map(props.map((p) => [p.name, p.path.split('/').filter(Boolean).join('.').replace(/[^\\w.-]/g, '-')]));\n const all = new Set(base.values());\n const out = new Map<string, string>();\n const taken = new Set<string>();\n for (const [name, path] of base) {\n // A token that is also a group (`layer` next to `layer.background`): its value moves to `layer.default`.\n let p = [...all].some((x) => x.startsWith(`${path}.`)) ? `${path}.default` : path;\n for (let i = 2; taken.has(p); i++) p = `${path}-${i}`;\n taken.add(p);\n out.set(name, p);\n }\n return out;\n}\n\nfunction nest(flat: Record<string, unknown>): Record<string, unknown> {\n const root: Record<string, unknown> = {};\n for (const [path, token] of Object.entries(flat).sort(([a], [b]) => a.localeCompare(b))) {\n const parts = path.split('.');\n let at = root;\n for (const part of parts.slice(0, -1)) at = (at[part] ??= {}) as Record<string, unknown>;\n at[parts.at(-1)!] = token;\n }\n return root;\n}\n\n/** The two-tier repo for a token harvest (see the top of this file). */\nexport function tokenRepoFromMeasure(t: MeasuredTokens): TokenRepoFromMeasure {\n const axis = t.modes[0];\n const modes = axis ? [axis.default, ...axis.values.filter((v) => v !== axis.default)] : ['default'];\n const key = (mode: string) => (axis ? `${axis.global}:${mode}` : '');\n const props = t.properties.filter((p) => p.used);\n const byName = new Map(props.map((p) => [p.name, p]));\n const paths = dotPaths(props);\n const valueIn = (p: MeasuredTokenProperty, mode: string) => p.values?.[key(mode)] ?? p.value;\n const skipped: string[] = [];\n\n // Primitives: one value, as the CSS writes it (a literal, or the resolved value of an expression).\n const primitives: Record<string, unknown> = {};\n const byValue = new Map<string, string>();\n const fixed = props.filter((p) => p.tier === 'primitive' && !p.values);\n for (const p of fixed) {\n const d = dtcg(p.type, p.value, p.name);\n if (!d) {\n skipped.push(p.name);\n continue;\n }\n const path = paths.get(p.name)!;\n primitives[path] = d;\n if (!byValue.has(valueKey(p.type, p.value))) byValue.set(valueKey(p.type, p.value), path);\n }\n // A palette entry for a value no fixed primitive holds.\n let palette = 0;\n const primitiveOf = (type: MeasuredTokenProperty['type'], v: Value, name: string): string | undefined => {\n const k = valueKey(type, v);\n const known = byValue.get(k);\n if (known) return known;\n const d = dtcg(type, v, name);\n if (!d) return undefined;\n const hex = (d.$value as { hex?: string }).hex;\n let path = type === 'color' && hex ? `palette.${hex.slice(1)}` : `palette.${type}.${String(v).replace(/[^\\w]/g, '-')}`;\n for (let i = 2; primitives[path]; i++) path = `${path}-${i}`;\n primitives[path] = d;\n byValue.set(k, path);\n palette++;\n return path;\n };\n\n // Semantic: aliases per mode, to a fixed primitive (its declared target) or the primitive of its value there.\n const semantic: Record<string, Record<string, unknown>> = Object.fromEntries(modes.map((m) => [m, {}]));\n let semanticCount = 0;\n for (const p of props) {\n if (p.tier === 'primitive' && !p.values) continue;\n const path = paths.get(p.name)!;\n let ok = true;\n const per: Record<string, string> = {};\n for (const mode of modes) {\n const declared = p.tier === 'semantic' ? (p.aliasOfByMode?.[key(mode)] ?? p.aliasOf) : undefined;\n const target = declared ? byName.get(declared) : undefined;\n const direct = target && target.tier === 'primitive' && !target.values && primitives[paths.get(target.name)!] ? paths.get(target.name)! : undefined;\n const to = direct ?? primitiveOf(p.type, valueIn(p, mode), p.name);\n if (!to) {\n ok = false;\n break;\n }\n per[mode] = to;\n }\n if (!ok) {\n skipped.push(p.name);\n continue;\n }\n const type = (primitives[per[modes[0]!]!] as { $type: string }).$type;\n for (const mode of modes) semantic[mode]![path] = { $type: type, $value: `{${per[mode]}}` };\n semanticCount++;\n }\n\n const files: Record<string, string> = { 'primitives/measured.tokens.json': `${JSON.stringify(nest(primitives), null, 2)}\\n` };\n for (const mode of modes) files[`semantic/${mode}.tokens.json`] = `${JSON.stringify(nest(semantic[mode]!), null, 2)}\\n`;\n const config: Record<string, unknown> = {\n tokens: {\n root: 'tokens',\n include: ['**/*.tokens.json'],\n tiers: { primitive: ['primitives'], semantic: ['semantic'] },\n layers: [{ files: 'primitives/*.tokens.json' }, { files: 'semantic/{theme}.tokens.json' }],\n },\n modes: { theme: { values: modes, default: modes[0] } },\n };\n return {\n files,\n config,\n paths: new Map([...paths].filter(([name]) => primitives[paths.get(name)!] || Object.values(semantic).some((s) => s[paths.get(name)!]))),\n report: { primitives: Object.keys(primitives).length, semantic: semanticCount, palette, modes, skipped },\n };\n}\n\n/** How a measure names a CSS variable it found no token for (core/node measure's default): `--cds-layer-01` -> cds.layer.01. */\nconst measureDefaultPath = (name: string) => name.replace(/^--/, '').split('-').filter(Boolean).join('.');\n\n/**\n * The measured specs with their values pointing at the tokens `tokenRepoFromMeasure` wrote: a value the measure named\n * after its CSS variable (`cds.layer.01`) becomes the written path (`layer.01`), and a field whose declaration is a\n * variable alone (`var(--cds-button-primary, #0f62fe)`) gets the written path of the first variable of its chain. Other\n * values are kept: a calc() of a token, or a value that only matches one, stays a literal.\n */\nexport function withRepoTokenPaths(file: MeasuredSpecsFile, paths: Map<string, string>): MeasuredSpecsFile {\n const rename = new Map([...paths].map(([name, path]) => [measureDefaultPath(name), path]));\n type Spec = NonNullable<MeasuredSpecsFile['stories'][number]['spec']>;\n const spec = <T extends Spec | undefined>(s: T): T => {\n if (!s) return s;\n const values: Spec['values'] = {};\n for (const [part, fields] of Object.entries(s.values)) values[part] = Object.fromEntries(Object.entries(fields).map(([k, v]) => [k, typeof v === 'string' && rename.has(v) ? rename.get(v) : v]));\n for (const [part, fields] of Object.entries(s.tokens ?? {})) {\n for (const [field, t] of Object.entries(fields ?? {})) {\n if (!t || t.via !== 'declared' || !t.exact) continue;\n const path = t.chain.map((name) => paths.get(name)).find(Boolean);\n if (path) values[part] = { ...values[part], [field]: path };\n }\n }\n return { ...s, values } as T;\n };\n return { ...file, stories: file.stories.map((s) => ({ ...s, ...(s.spec ? { spec: spec(s.spec) } : {}), ...(s.instances ? { instances: s.instances.map((i) => spec(i)) } : {}) })) };\n}\n","// What the measure can promise, per component: the variants to measure (story args and forced states), how code props\n// map to Figma component properties, and one status for the onboarding contract screen (Matches, Differs, Can't check\n// yet with a reason from a closed list). Browser safe: the plugin and the docs site read it; the CLI computes it.\n// The measure is the referee: a status is only ever computed from measured stories, never declared.\n\nimport type { SpecPart, SpecValue, SpecVariant } from './component-spec';\nimport { compareSpecToMeasured, type FieldDiff, type MeasuredArgType, type MeasuredSpecsStory, type MeasuredState } from './measured-spec';\n\n// ---------------------------------------------------------------------------------------------\n// Variant coverage: which args and states to measure\n\n/** Props that never draw a variant (element type, wiring, content). */\nconst NOT_AN_AXIS = /^(as|asChild|render|component|className|class|style|id|key|ref|role|type|name|form|dir|lang|tabIndex|slot|children|htmlFor|value|defaultValue|placeholder|href|target|rel|src|alt)$/i;\nconst DISABLED_PROP = /^(is)?disabled$/i;\nconst INDETERMINATE_PROP = /^(is)?indeterminate$/i;\nconst MIXED = /^(mixed|indeterminate|partial)$/i;\n\nexport interface VariantMeasure {\n /** Args passed to the story (`{ variant: 'danger', size: 'lg', disabled: true }`). */\n overrides: Record<string, string | number | boolean>;\n /** Pseudo state forced on the component; absent at rest and for disabled (an arg). */\n state?: MeasuredState | undefined;\n}\n\nexport interface PlanVariantOptions {\n /** Props to vary; default every enum prop (2 to 12 options) that is not wiring (`as`, `type`, `className`...). */\n axes?: string[] | undefined;\n /** Exact values per prop (from a Figma mapping: variantValuesFromMapping); replaces `axes`. Booleans vary too. */\n values?: Record<string, (string | boolean)[]> | undefined;\n /** Exact prop combinations (variantCombosFromMapping); replaces `values` and `axes`. */\n combos?: Record<string, string | boolean>[] | undefined;\n /** States to measure on each combination (default rest, hover, disabled). */\n states?: ('rest' | MeasuredState | 'disabled')[] | undefined;\n /** At most this many measures (default 128); the axes are kept, states are dropped first. */\n max?: number | undefined;\n}\n\n/**\n * Every variant to measure for a component, from its argTypes: the cartesian product of its enum props, times the\n * states (hover, focus and active forced in Chrome, disabled as an arg when the component has a disabled prop).\n */\nexport function planVariantMeasures(argTypes: Record<string, MeasuredArgType>, o: PlanVariantOptions = {}): VariantMeasure[] {\n const valuesOf = (k: string): (string | boolean)[] => o.values?.[k] ?? (argTypes[k]?.kind === 'boolean' ? [false, true] : (argTypes[k]?.options ?? []));\n const names = o.values ? Object.keys(o.values) : (o.axes ?? Object.keys(argTypes).filter((k) => argTypes[k]!.kind === 'enum' && !NOT_AN_AXIS.test(k)));\n const axes = names.map((k) => [k, valuesOf(k)] as const).filter(([, opts]) => opts.length >= (o.values ? 1 : 2) && opts.length <= 12);\n let combos: Record<string, string | boolean>[] = [{}];\n for (const [k, opts] of axes) combos = combos.flatMap((c) => opts.map((v) => ({ ...c, [k]: v })));\n if (o.combos?.length) combos = o.combos;\n // `disabled` even when docgen leaves it out of the argTypes (an inherited HTML prop); a prop that is not a boolean is not it.\n const disabled = Object.keys(argTypes).find((k) => DISABLED_PROP.test(k) && argTypes[k]!.kind === 'boolean') ?? (argTypes.disabled ? undefined : 'disabled');\n let states = (o.states ?? ['rest', 'hover', 'disabled']).filter((s) => s !== 'disabled' || disabled);\n const max = o.max ?? 128;\n while (states.length > 1 && combos.length * states.length > max) states = states.slice(0, -1);\n const out: VariantMeasure[] = [];\n for (const c of combos.slice(0, max))\n for (const s of states) {\n if (s === 'disabled') out.push({ overrides: { ...c, [disabled!]: true } });\n else if (s === 'rest') out.push({ overrides: { ...c } });\n else out.push({ overrides: { ...c }, state: s });\n }\n return out.slice(0, max);\n}\n\n/**\n * The prop combinations a Figma component's variants mean in code (State aside): the product of its VARIANT axes,\n * each value with the props it sets (Checked=mixed sets `checked: false, indeterminate: true`). Unmapped values are left out.\n */\nexport function variantCombosFromMapping(mapping: PropsToFigma): Record<string, string | boolean>[] {\n let combos: Record<string, string | boolean>[] = [{}];\n for (const m of mapping.mapped) {\n if (m.type !== 'VARIANT' || m.prop === 'state' || !m.values) continue;\n const opts = Object.entries(m.values).map(([fv, code]) => ({ [m.prop]: code, ...(m.also?.[fv] ?? {}) }));\n const seen = new Set<string>();\n const uniq = opts.filter((o) => !seen.has(JSON.stringify(o)) && seen.add(JSON.stringify(o)));\n combos = combos.flatMap((c) => uniq.map((o) => ({ ...c, ...o })));\n }\n return combos;\n}\n\n/**\n * The prop combinations to measure for some axes, at most `cap`: the full product when it fits; else every value of\n * each axis alone (the others at their first value), then every pair of axes, until the cap. `capped` says the full\n * product was not measured.\n */\nexport function boundedCombos(axes: [string, (string | boolean)[]][], cap = 48): { combos: Record<string, string | boolean>[]; capped: boolean } {\n const live = axes.filter(([, v]) => v.length >= 2);\n const total = live.reduce((n, [, v]) => n * v.length, 1);\n if (total <= cap) {\n let combos: Record<string, string | boolean>[] = [{}];\n for (const [k, vals] of live) combos = combos.flatMap((c) => vals.map((v) => ({ ...c, [k]: v })));\n return { combos, capped: false };\n }\n const base = Object.fromEntries(live.map(([k, v]) => [k, v[0]!]));\n const seen = new Set<string>();\n const out: Record<string, string | boolean>[] = [];\n const add = (c: Record<string, string | boolean>) => {\n const key = JSON.stringify(Object.entries(c).sort());\n if (out.length >= cap || seen.has(key)) return;\n seen.add(key);\n out.push(c);\n };\n add(base);\n for (const [k, vals] of live) for (const v of vals) add({ ...base, [k]: v });\n for (let i = 0; i < live.length; i++)\n for (let j = i + 1; j < live.length; j++)\n for (const a of live[i]![1]) for (const b of live[j]![1]) add({ ...base, [live[i]![0]]: a, [live[j]![0]]: b });\n return { combos: out, capped: true };\n}\n\n/** The values to measure per prop for a Figma component: its VARIANT axes mapped to props (State aside). */\nexport function variantValuesFromMapping(mapping: PropsToFigma): Record<string, (string | boolean)[]> {\n const out: Record<string, (string | boolean)[]> = {};\n for (const m of mapping.mapped) if (m.type === 'VARIANT' && m.prop !== 'state' && m.values) out[m.prop] = [...new Set(Object.values(m.values))];\n return out;\n}\n\n// ---------------------------------------------------------------------------------------------\n// Code props <-> Figma component properties\n\n/** A Figma component property as the plugin reads it (componentPropertyDefinitions) or the specs write it. */\nexport interface FigmaPropertyRef {\n name: string;\n type: 'VARIANT' | 'BOOLEAN' | 'TEXT' | 'INSTANCE_SWAP' | string;\n /** VARIANT values. */\n values?: string[] | undefined;\n default?: unknown;\n}\n\nexport interface PropMapping {\n figma: string;\n type: FigmaPropertyRef['type'];\n /** The code prop, or `state` for a Figma State axis (pseudo states and disabled). */\n prop: string;\n /** VARIANT: Figma value -> code value. Missing values are listed in `unmatchedValues`. */\n values?: Record<string, string | boolean> | undefined;\n /** VARIANT values that also set other props (Checked=mixed: `{ indeterminate: true }`). */\n also?: Record<string, Record<string, string | boolean>> | undefined;\n unmatchedValues?: string[] | undefined;\n}\n\nexport interface PropsToFigma {\n mapped: PropMapping[];\n /** Figma properties with no code prop (\"tone has no prop in code\"). */\n figmaOnly: string[];\n /** Enum and boolean props with no Figma property. */\n codeOnly: string[];\n}\n\nconst key = (s: string) => s.toLowerCase().replace(/[^a-z0-9]/g, '');\nconst TEXT_PROPS = ['children', 'label', 'text', 'title'];\n/** Figma State values -> what reproduces them in code. */\nconst STATE_VALUES: Record<string, MeasuredState | 'rest' | 'disabled'> = { default: 'rest', rest: 'rest', enabled: 'rest', hover: 'hover', hovered: 'hover', focus: 'focus-visible', focused: 'focus-visible', focusvisible: 'focus-visible', pressed: 'active', active: 'active', disabled: 'disabled' };\n\n/**\n * Maps Figma component properties to code props by name (case, spaces and dashes ignored; `is` prefixes and `Show x`\n * booleans folded), VARIANT values to enum options the same way, and a Figma `State` axis to pseudo states and the\n * disabled prop.\n */\nexport function mapPropsToFigma(argTypes: Record<string, MeasuredArgType>, figma: FigmaPropertyRef[]): PropsToFigma {\n const props = Object.keys(argTypes);\n const used = new Set<string>();\n const find = (name: string, kinds: MeasuredArgType['kind'][]) => {\n const k = key(name).replace(/^show/, '');\n return props.find((p) => !used.has(p) && kinds.includes(argTypes[p]!.kind) && (key(p) === k || key(p) === `is${k}` || key(p) === `has${k}` || key(p) === `show${k}`));\n };\n const out: PropsToFigma = { mapped: [], figmaOnly: [], codeOnly: [] };\n for (const f of figma) {\n if (f.type === 'VARIANT' && key(f.name) === 'state') {\n const values: Record<string, string | boolean> = {};\n const unmatched: string[] = [];\n // React components take `disabled` even when docgen leaves it out of the argTypes (an inherited HTML prop).\n const disabled = props.find((p) => DISABLED_PROP.test(p) && argTypes[p]!.kind === 'boolean');\n for (const v of f.values ?? []) {\n const s = STATE_VALUES[key(v)];\n if (!s) unmatched.push(v);\n else values[v] = s;\n }\n if (disabled) used.add(disabled);\n out.mapped.push({ figma: f.name, type: f.type, prop: 'state', values, ...(unmatched.length ? { unmatchedValues: unmatched } : {}) });\n continue;\n }\n const prop =\n f.type === 'VARIANT' ? find(f.name, ['enum', 'boolean']) : f.type === 'BOOLEAN' ? find(f.name, ['boolean']) : f.type === 'TEXT' ? (find(f.name, ['text']) ?? (key(f.name) === 'label' || key(f.name) === 'text' ? props.find((p) => !used.has(p) && TEXT_PROPS.includes(p)) : undefined)) : find(f.name, ['other', 'enum']);\n if (!prop) {\n out.figmaOnly.push(f.name);\n continue;\n }\n used.add(prop);\n const m: PropMapping = { figma: f.name, type: f.type, prop };\n if (f.type === 'VARIANT') {\n const a = argTypes[prop]!;\n const values: Record<string, string | boolean> = {};\n const unmatched: string[] = [];\n for (const v of f.values ?? []) {\n if (a.kind === 'boolean') {\n if (/^(true|yes|on)$/i.test(v)) values[v] = true;\n else if (/^(false|no|off)$/i.test(v)) values[v] = false;\n else if (MIXED.test(v)) {\n // A checkbox's third state: not checked, indeterminate (Base UI and React's `indeterminate`), even when docgen\n // leaves the prop out; a story that does not take it is reported when measured.\n values[v] = false;\n m.also = { ...(m.also ?? {}), [v]: { [props.find((p) => INDETERMINATE_PROP.test(p) && argTypes[p]!.kind === 'boolean') ?? 'indeterminate']: true } };\n } else unmatched.push(v);\n continue;\n }\n const hit = (a.options ?? []).find((x) => key(x) === key(v));\n if (hit !== undefined) values[v] = hit;\n else unmatched.push(v);\n }\n m.values = values;\n if (unmatched.length) m.unmatchedValues = unmatched;\n }\n out.mapped.push(m);\n }\n out.codeOnly = props.filter((p) => !used.has(p) && (argTypes[p]!.kind === 'enum' || argTypes[p]!.kind === 'boolean') && !NOT_AN_AXIS.test(p) && !DISABLED_PROP.test(p));\n return out;\n}\n\n// ---------------------------------------------------------------------------------------------\n// One status per component for the contract screen\n\nexport type ComponentCheck = 'matches' | 'differs' | 'cant-check';\n\n/** Why a component can't be checked yet: a closed list, so the copy stays honest. */\nexport type CantCheckReason =\n | 'no-story' // no story shows the component\n | 'did-not-render' // every story failed (the error is in `detail`)\n | 'no-token-variables' // literal values, no CSS variables: nothing to bind Figma variables to\n | 'popup-closed' // a popup the measure could not open\n | 'no-figma' // no Figma component to compare with yet\n | 'prop-unmapped' // a Figma variant property has no prop in code\n | 'no-story-for-variant'; // some Figma variants have no story (or args) that renders them\n\nexport const CANT_CHECK_COPY: Record<CantCheckReason, string> = {\n 'no-story': 'No story shows this component',\n 'did-not-render': 'The story did not render',\n 'no-token-variables': 'Values are not tokens: the styles use literal values, no CSS variables',\n 'popup-closed': 'Opens in a popup that Bridge could not open',\n 'no-figma': 'No Figma component to compare with yet',\n 'prop-unmapped': 'A Figma property has no prop in code',\n 'no-story-for-variant': 'No story shows some variants',\n};\n\nexport interface VariantCheck {\n /** Figma variant key (\"Size=md, State=Hover\"). */\n key: string;\n status: ComponentCheck;\n /** Story measured for it. */\n story?: string | undefined;\n reason?: CantCheckReason | undefined;\n diffs?: FieldDiff[] | undefined;\n compared?: number | undefined;\n}\n\nexport interface ComponentStatus {\n name: string;\n status: ComponentCheck;\n /** Can't check yet: why (closed list) and the sentence to show. */\n reason?: CantCheckReason | undefined;\n /** One sentence in designer words: the first difference, or the reason with its detail. */\n summary: string;\n detail?: string | undefined;\n variants: VariantCheck[];\n mapping?: PropsToFigma | undefined;\n /** Share of measured values tied to a declared CSS variable. */\n tokenShare?: number | undefined;\n}\n\n/** The Figma side of a component, in the spec shape: what the plugin reads from the Figma set (or the specs it was drawn from). */\nexport interface FigmaComponentRef {\n properties: FigmaPropertyRef[];\n parts: SpecPart[];\n variants: Pick<SpecVariant, 'props' | 'values'>[];\n}\n\nexport interface ComponentStatusInput {\n name: string;\n /** The component's measured stories (any args and states). */\n stories: MeasuredSpecsStory[];\n argTypes?: Record<string, MeasuredArgType> | undefined;\n figma?: FigmaComponentRef | undefined;\n /** Token path -> resolved value in the measured page, for value-level agreement. */\n resolve?: ((tokenPath: string) => string | number | undefined) | undefined;\n /** No Figma set of this name, but sets drawn from it open (Dialog/Popup): named in the reason. */\n figmaSets?: string[] | undefined;\n /** Below this share of values tied to CSS variables, the library has no tokens to check (default 0.1). */\n minTokenShare?: number | undefined;\n}\n\nconst FIELD_WORDS: Record<string, string> = {\n fill: 'Fill',\n stroke: 'Border color',\n strokeWeight: 'Border width',\n cornerRadius: 'Corner radius',\n paddingTop: 'Top padding',\n paddingRight: 'Right padding',\n paddingBottom: 'Bottom padding',\n paddingLeft: 'Left padding',\n itemSpacing: 'Gap',\n counterAxisSpacing: 'Row gap',\n width: 'Width',\n height: 'Height',\n minWidth: 'Min width',\n minHeight: 'Min height',\n opacity: 'Opacity',\n textFill: 'Text color',\n fontFamily: 'Font',\n fontSize: 'Font size',\n fontWeight: 'Font weight',\n lineHeight: 'Line height',\n letterSpacing: 'Letter spacing',\n};\nconst show = (v: SpecValue | undefined) => (v === undefined || v === null ? 'none' : typeof v === 'number' ? `${v} px` : v);\n\n/** A difference in designer words: \"Left padding is 6 px in code, 8 px in Figma (label)\". */\nexport function describeDiff(d: FieldDiff): string {\n const what = FIELD_WORDS[d.field] ?? d.field;\n const where = d.part === 'root' ? '' : ` (${d.part.replace(/-/g, ' ')})`;\n const unitless = d.field === 'fontWeight' || d.field === 'opacity';\n const v = (x: SpecValue | undefined) => (unitless && typeof x === 'number' ? String(x) : show(x));\n return `${what} is ${v(d.measured)} in code, ${v(d.static)} in Figma${where}`;\n}\n\nconst sameValue = (a: unknown, b: unknown) => a === b || (a !== undefined && b !== undefined && key(String(a)) === key(String(b)));\n\n/**\n * One component's status from its measured stories and its Figma side. The order of the checks is the order a team\n * fixes them in: something to measure, tokens to bind, a Figma component, props that name its variants, a story per\n * variant, then the values.\n */\nexport function componentStatus(input: ComponentStatusInput): ComponentStatus {\n const base = { name: input.name, variants: [] as VariantCheck[] };\n const cant = (reason: CantCheckReason, detail?: string, extra: Partial<ComponentStatus> = {}): ComponentStatus => ({\n ...base,\n ...extra,\n status: 'cant-check',\n reason,\n summary: detail ? `${CANT_CHECK_COPY[reason]}: ${detail}` : CANT_CHECK_COPY[reason],\n ...(detail ? { detail } : {}),\n });\n if (!input.stories.length) return cant('no-story');\n const ok = input.stories.filter((s) => s.spec && !s.error);\n if (!ok.length) {\n const popup = input.stories.find((s) => s.opened === 'none');\n if (popup) return cant('popup-closed', popup.error);\n return cant('did-not-render', input.stories.find((s) => s.error)?.error);\n }\n const fields = ok.reduce((n, s) => n + s.spec!.coverage.fields, 0);\n const declared = ok.reduce((n, s) => n + s.spec!.coverage.declared, 0);\n const tokenShare = fields ? declared / fields : 0;\n if (tokenShare < (input.minTokenShare ?? 0.1)) return cant('no-token-variables', `${Math.round(tokenShare * 100)}% of values come from CSS variables`, { tokenShare });\n if (!input.figma) {\n if (!input.figmaSets?.length) return cant('no-figma', undefined, { tokenShare });\n // Figma draws the open popup, not the trigger the story shows closed: honest about which and how to check it.\n return { ...base, tokenShare, status: 'cant-check', reason: 'no-figma', detail: input.figmaSets.join(', '), summary: `Figma draws the open popup (${input.figmaSets.join(', ')}): measure it open with --open` };\n }\n\n const argTypes = input.argTypes ?? {};\n const mapping = mapPropsToFigma(argTypes, input.figma.properties);\n const variantAxes = input.figma.properties.filter((p) => p.type === 'VARIANT');\n const unmappedAxis = variantAxes.find((p) => mapping.figmaOnly.includes(p.name));\n if (unmappedAxis) return cant('prop-unmapped', `${unmappedAxis.name} has no prop in code`, { mapping, tokenShare });\n\n const variants: VariantCheck[] = [];\n for (const v of input.figma.variants) {\n const vkey = Object.entries(v.props).map(([k, x]) => `${k}=${x}`).join(', ');\n // The props and state this Figma variant means in code.\n const want: Record<string, unknown> = {};\n let state: MeasuredState | undefined;\n let unreachable = false;\n for (const [axis, value] of Object.entries(v.props)) {\n const m = mapping.mapped.find((x) => x.figma === axis);\n if (!m) continue;\n const code = m.values?.[value];\n if (code === undefined) {\n unreachable = true;\n continue;\n }\n if (m.prop === 'state') {\n if (code === 'disabled') want[Object.keys(argTypes).find((k) => DISABLED_PROP.test(k)) ?? 'disabled'] = true; else if (code !== 'rest') state = code as MeasuredState;\n } else {\n want[m.prop] = code;\n Object.assign(want, m.also?.[value] ?? {});\n }\n }\n // Flags a variant sets only for some values (indeterminate for Checked=mixed): off for the other values.\n const flags = new Set(mapping.mapped.flatMap((m) => Object.values(m.also ?? {}).flatMap((x) => Object.keys(x))));\n const matching = unreachable\n ? []\n : ok.filter((s) => {\n const has = { ...(s.props ?? {}), ...(s.overrides ?? {}) } as Record<string, unknown>;\n if ((s.state ?? undefined) !== state) return false;\n if (!Object.entries(want).every(([k, x]) => sameValue(has[k], x))) return false;\n // A rest variant is not the disabled story.\n return Object.keys(has).every((k) => !(DISABLED_PROP.test(k) || flags.has(k)) || want[k] !== undefined || has[k] !== true);\n });\n if (!matching.length) {\n variants.push({ key: vkey, status: 'cant-check', reason: 'no-story-for-variant' });\n continue;\n }\n // Several stories render these props (a plain table, a sortable one, a selected row): the one closest to the\n // Figma variant's content is its counterpart; extra features in other stories are content, not drift.\n // Single-instance stories first; a gallery's first instance only when nothing else renders the variant.\n matching.sort((x, y) => (x.gallery ? 1 : 0) - (y.gallery ? 1 : 0));\n let story = matching[0]!;\n let c = compareSpecToMeasured(input.figma.parts, v.values, story.instances?.[0] ?? story.spec!, input.resolve, { properties: input.figma.properties });\n let diffs = c.diffs.filter((d) => d.measured !== undefined);\n for (const other of matching.slice(1)) {\n if (!diffs.length) break;\n const oc = compareSpecToMeasured(input.figma.parts, v.values, other.instances?.[0] ?? other.spec!, input.resolve, { properties: input.figma.properties });\n const od = oc.diffs.filter((d) => d.measured !== undefined);\n if (od.length < diffs.length) [story, c, diffs] = [other, oc, od];\n }\n variants.push({ key: vkey, story: story.id, status: diffs.length ? 'differs' : 'matches', compared: c.compared, ...(diffs.length ? { diffs } : {}) });\n }\n const differs = variants.filter((v) => v.status === 'differs');\n const missing = variants.filter((v) => v.status === 'cant-check');\n if (differs.length) {\n const all = differs.flatMap((v) => v.diffs ?? []);\n const more = all.length - 1;\n return { ...base, variants, mapping, tokenShare, status: 'differs', summary: `${describeDiff(all[0]!)}${more > 0 ? `, +${more} more` : ''}` };\n }\n if (missing.length) {\n const first = missing.slice(0, 2).map((v) => v.key).join('; ');\n // The measure tried and the story refused the arg: say which, that is the fix (add it to the story's argTypes).\n const refused = [...new Set(input.stories.map((x) => /does not take the arg ([\\w-]+)/.exec(x.error ?? '')?.[1]).filter((x): x is string => !!x))];\n const why = refused.length ? `; the story does not take ${refused.join(', ')}` : '';\n return { ...cant('no-story-for-variant', `${first}${missing.length > 2 ? ` (+${missing.length - 2} more)` : ''}${why}`, { mapping, tokenShare }), variants };\n }\n if (!variants.length) return cant('no-story-for-variant', 'the Figma component has no variants to compare', { mapping, tokenShare });\n return { ...base, variants, mapping, tokenShare, status: 'matches', summary: `Matches Figma on ${variants.length} variant${variants.length === 1 ? '' : 's'}` };\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 * Export name of the compound component this set is a part of (AccordionItem in Accordion, Radio in RadioGroup,\n * MenuItem in Menu): the part needs its parent around it to render, and the image shows the part alone.\n */\n within?: string | undefined;\n /**\n * A popup drawn open (Dialog/Popup): the root renders open (`defaultOpen`), and the image is the popup Base UI\n * portals, found by the class of the spec's root part (\"popup\", \"tooltip\"), not the trigger.\n */\n popup?: { className: string } | 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 if (spec.view === 'popup') return planPopup(spec, variant);\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 === 'media') return { reason: `Figma shows a media placeholder (${swapTo}); code shows the image it is given, nothing to compare` };\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 // A set named \"Folder/Variant\" (Pagination/Full) renders its folder's component; any other set its own name.\n const component = exportName(example?.c ?? (spec.name.includes('/') ? (spec.component ?? spec.name) : spec.name));\n // A part of a compound component (AccordionItem, from the Accordion folder) renders inside that component.\n const parent = spec.component ? exportName(spec.component) : undefined;\n return {\n ok: true,\n render: {\n component,\n ...(parent && parent !== component ? { within: parent } : {}),\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/**\n * A popup drawn open in Figma (Dialog/Popup), rendered open in code: the component's root with `defaultOpen`, around\n * its example. An example of the content part (DialogContent) goes inside the root with its trigger (a popover is\n * placed against it); an example of the root itself (a Select with options) only gets `defaultOpen`.\n */\nfunction planPopup(spec: ComponentSpec, variant: SpecVariant): ReferencePlan {\n const root = spec.parts.find((p) => !p.parent);\n // The variant's axes are props of the element the example draws (DialogContent's size, AlertDialogContent's tone).\n const own: Record<string, unknown> = {};\n for (const axis of spec.axes) {\n const value = variant.props[axis.name];\n if (!axis.prop || value === undefined) return { ok: false, reason: `${axis.name} has no matching option in code` };\n own[axis.prop] = value === 'true' ? true : value === 'false' ? false : value;\n }\n // \"Dialog.module.css .popup, Dialog.module.css .md\": the first class of its module, the one the popup carries.\n const className = /\\.module\\.css \\.([\\w-]+)/.exec(root?.source ?? '')?.[1];\n const component = spec.component ? exportName(spec.component) : undefined;\n const example = spec.example;\n if (!component || !example) return { ok: false, reason: 'drawn open from no code example: nothing to open in code' };\n if (!className) return { ok: false, reason: 'the popup has no class to find it by in code' };\n const popup = { className };\n if (exportName(example.c) === component) {\n return { ok: true, render: { component, props: { ...(example.p ?? {}), ...own, defaultOpen: true }, ...(example.children?.length ? { children: example.children } : {}), popup } };\n }\n return {\n ok: true,\n render: { component, props: { defaultOpen: true }, children: [{ c: `${component}Trigger`, children: ['Open'] }, { ...example, p: { ...(example.p ?? {}), ...own } }], popup },\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","// Gap case: for one component the Figma pull drew, what differs from the code, per variant, in words a designer reads\n// and in deltas a fix can be written from. The story shot is the referee (the plugin's Check fidelity says which\n// variants differ); the measure (measured-specs.json) and what Figma drew (the spec the builder drew from, plus what the\n// plugin reads back from the layers) say why. Claude reads a gap case to propose a fix (figma-fixes.json), Bridge\n// re-checks against the shot, a person approves. Pure and browser safe: the plugin UI, the CLI and the docs site run it.\n\nimport { variantKeyOf, type ComponentSpec, type SpecField, type SpecPart, type SpecValue, type SpecVariant } from './component-spec';\nimport type { FidelityComponentResult, FidelityVariantResult, Size } from './fidelity';\nimport { compareSpecToMeasured, pairParts, withoutAddedWrappers, type MeasuredBox, type MeasuredSpec, type MeasuredSpecsFile, type MeasuredSpecsStory, type MeasuredState } from './measured-spec';\n\nexport const GAP_CASE_VERSION = 1;\n\n/** How a story reaches a variant: at rest, a forced pseudo state, or disabled (an arg). */\nexport type GapState = 'rest' | MeasuredState | 'disabled';\n\n/**\n * What a difference is about. A Figma field (fill, paddingTop, cornerRadius, height...), or: `presence` (a part one side\n * draws and the other does not), `sizing` (fixed in code, hugging in Figma), `direction` (auto layout direction).\n */\nexport type GapProperty = SpecField | 'presence' | 'sizing' | 'direction';\n\n/** One concrete difference. `expected` is the code (the measure), `actual` is Figma (what was drawn). */\nexport interface GapDifference {\n /** Plain words: \"Height 72 in Figma vs 84 in code: 12 px missing below the label wrapper\". */\n text: string;\n /** Part id, as the measure and the built set name it (\"root\", \"cds--toggle-switch\"). */\n part: string;\n /** The part in words (\"toggle switch\"). */\n partName: string;\n property: GapProperty;\n /** Code: token path, px number, null (no paint), `present`, `fixed`, `HORIZONTAL`... */\n expected: SpecValue | boolean;\n /** Figma: the same kinds, `missing`, `hidden`, `hug`... */\n actual: SpecValue | boolean;\n /** Numbers: actual minus expected, px (negative: Figma is smaller). */\n delta?: number | undefined;\n}\n\nexport interface GapStoryRef {\n /** Storybook story id. */\n id: string;\n name?: string | undefined;\n /** Story URL the measure opened (args in it). */\n url?: string | undefined;\n /** The props it rendered with (args over the component defaults), and the args Bridge passed to reach the variant. */\n props: Record<string, string | number | boolean>;\n overrides?: Record<string, string | number | boolean> | undefined;\n state: GapState;\n}\n\nexport interface GapVariant {\n /** Figma variant key (variantKeyOf: \"Size=md, State=Default\"). */\n key: string;\n /** Figma props of the variant. */\n props: Record<string, string>;\n /** The referee's verdict for this variant: the plugin's Check fidelity (`unchecked` without one). */\n verdict: 'differs' | 'unchecked';\n /** Different pixels in percent, and both sizes, when the shot was compared. */\n percent?: number | undefined;\n size?: { figma: Size; code: Size } | undefined;\n story?: GapStoryRef | undefined;\n /** The story's screenshot, relative to measured-specs.json (the referee image). */\n shot?: string | undefined;\n /** What Figma drew for this variant: a node id or an exported PNG, when the plugin passes one. */\n figmaRender?: string | undefined;\n differences: GapDifference[];\n /** Why the list is empty when the shots differ: no story, or the measure agrees and only the images tell. */\n unexplained?: string | undefined;\n}\n\nexport interface GapCase {\n version: typeof GAP_CASE_VERSION;\n component: string;\n storybook: string;\n /** `shots`: the variants come from the fidelity check. `values`: no check was passed, variants with differences. */\n referee: 'shots' | 'values';\n /** Variants compared, and how many differ. */\n checked: number;\n differing: number;\n /** One sentence for a designer. */\n summary: string;\n /** Lines for a developer (or Claude): story, args, state, shot and every delta per variant. */\n detail: string;\n variants: GapVariant[];\n /** Fixes from figma-fixes.json already applied to this component (the patched measure says so). */\n fixes?: string[] | undefined;\n}\n\n/** What the plugin reads back from one drawn variant, laid over the spec it drew from. All optional. */\nexport interface GapBuiltVariant {\n /** Field values the layers hold (part id -> field -> value), when they differ from the spec's. */\n values?: SpecVariant['values'] | undefined;\n /** Parts hidden in this variant. */\n hidden?: string[] | undefined;\n /** Part id -> its box relative to the variant's top-left, px: lets the gap say where space is missing. */\n boxes?: Record<string, MeasuredBox> | undefined;\n}\n\nexport interface GapCaseInput {\n /** Set name (\"Toggle\"): the last segment of the stories' title. */\n component: string;\n measured: MeasuredSpecsFile;\n /** What the pull drew the set from (specsFromMeasure's spec, or the overlaid static spec). */\n spec?: ComponentSpec | undefined;\n /** The plugin's Check fidelity result for this set: the referee. */\n fidelity?: FidelityComponentResult | undefined;\n /** Variant key -> what the layers read back. */\n built?: Record<string, GapBuiltVariant> | undefined;\n /** Variant key -> the story shot the set was compared with (MeasuredShots[set]). */\n shots?: Record<string, { file: string }> | undefined;\n /** Variant key -> a reference to what Figma drew (node id, PNG path). */\n figmaRenders?: Record<string, string> | undefined;\n /** Token path -> its value in the measured page. Default: the measure's resolved values and token harvest. */\n resolve?: ((tokenPath: string) => string | number | undefined) | undefined;\n}\n\n// ---------------------------------------------------------------------------------------------\n// Helpers\n\nconst lc = (s: string) => s.toLowerCase().replace(/[^a-z0-9]/g, '');\nconst setNameOf = (title: string) => title.split('/').at(-1)!.trim();\n\n/** The stories of a set: the last title segment, case and punctuation ignored. */\nexport function storiesOfComponent(file: Pick<MeasuredSpecsFile, 'stories'>, component: string): MeasuredSpecsStory[] {\n return file.stories.filter((s) => lc(setNameOf(s.title)) === lc(component));\n}\n\n/** A story's state: its forced pseudo state, else disabled when the arg says so, else at rest. */\nexport function storyState(s: Pick<MeasuredSpecsStory, 'state' | 'props' | 'overrides'>): GapState {\n if (s.state) return s.state;\n const p = { ...(s.props ?? {}), ...(s.overrides ?? {}) };\n return p.disabled === true || p.isDisabled === true ? 'disabled' : 'rest';\n}\n\nconst STATE_WORDS: Record<string, GapState> = { default: 'rest', rest: 'rest', enabled: 'rest', hover: 'hover', hovered: 'hover', pressed: 'active', active: 'active', focus: 'focus-visible', focused: 'focus-visible', focusvisible: 'focus-visible', disabled: 'disabled' };\n\n/**\n * The story a Figma variant was drawn from: the one whose shot it was compared with, else the first (single instance\n * before galleries) whose props, overrides and state give the variant's axis values.\n */\nexport function storyForVariant(spec: Pick<ComponentSpec, 'axes'>, props: Record<string, string>, stories: MeasuredSpecsStory[], shot?: { file: string }): MeasuredSpecsStory | undefined {\n const ok = stories.filter((s) => s.spec && !s.error);\n const fits = (s: MeasuredSpecsStory) => {\n const p = { ...(s.props ?? {}), ...(s.overrides ?? {}) } as Record<string, unknown>;\n return spec.axes.every((axis) => {\n const want = props[axis.name];\n if (want === undefined) return true;\n if (axis.prop) return p[axis.prop] !== undefined ? lc(String(p[axis.prop])) === lc(want) : lc(want) === lc(axis.default);\n if (lc(axis.name) === 'state') return (STATE_WORDS[lc(want)] ?? lc(want)) === storyState(s);\n if (lc(axis.name) === 'checked') return lc(want) === (p.indeterminate === true ? 'mixed' : String(p.checked === true));\n return p[axis.name] === undefined ? lc(want) === lc(axis.default) : lc(String(p[axis.name])) === lc(want);\n });\n };\n const order = (list: MeasuredSpecsStory[]) => [...list].sort((a, b) => Number(!!a.gallery) - Number(!!b.gallery));\n if (shot) {\n const same = ok.filter((s) => s.shot?.file === shot.file);\n if (same.length) return order(same).find(fits) ?? same[0];\n }\n return order(ok).find(fits);\n}\n\n/** A part in words: the measure's ids are class names (\"cds--toggle__switch\" -> \"toggle switch\"). */\nexport function partWords(part: Pick<SpecPart, 'id' | 'name'> | undefined, id = part?.id ?? ''): string {\n if (id === 'root') return 'component';\n const base = (part?.id ?? id).replace(/^[a-z]{1,6}--/i, '').replace(/[-_]+/g, ' ').replace(/([a-z])([A-Z])/g, '$1 $2').trim().toLowerCase();\n return base || (part?.name ?? id).toLowerCase();\n}\n\nconst round = (n: number) => (Math.abs(n - Math.round(n)) < 0.1 ? Math.round(n) : Math.round(n * 10) / 10);\n\nconst FIELD_WORDS: Partial<Record<SpecField, string>> = {\n fill: 'Fill',\n stroke: 'Border color',\n strokeWeight: 'Border width',\n strokeTopWeight: 'Top border',\n strokeRightWeight: 'Right border',\n strokeBottomWeight: 'Bottom border',\n strokeLeftWeight: 'Left border',\n cornerRadius: 'Corner radius',\n paddingTop: 'Top padding',\n paddingRight: 'Right padding',\n paddingBottom: 'Bottom padding',\n paddingLeft: 'Left padding',\n itemSpacing: 'Gap',\n counterAxisSpacing: 'Row gap',\n width: 'Width',\n height: 'Height',\n minWidth: 'Min width',\n minHeight: 'Min height',\n opacity: 'Opacity',\n textFill: 'Text color',\n fontFamily: 'Font',\n fontSize: 'Font size',\n fontWeight: 'Font weight',\n lineHeight: 'Line height',\n letterSpacing: 'Letter spacing',\n textDecoration: 'Text decoration',\n};\n\n/** A value for people: none, a px number (a radius at half the box or more reads \"full\"), or the token path. */\nfunction showValue(v: SpecValue | boolean | undefined, field: GapProperty, box?: MeasuredBox): string {\n if (v === undefined || v === null) return field === 'presence' ? 'missing' : 'none';\n if (typeof v === 'boolean') return String(v);\n if (typeof v === 'number') {\n if (field === 'cornerRadius' && box && v > 0 && v >= Math.min(box.width, box.height) / 2 - 0.5) return 'full';\n return String(round(v));\n }\n return v;\n}\n\n/** Token path -> value, from the measure: components[].resolved, then the token harvest (by CSS name). */\nexport function measuredResolver(file: Pick<MeasuredSpecsFile, 'components' | 'tokens'>): (path: string) => string | number | undefined {\n const byKey = new Map<string, string | number>();\n for (const p of file.tokens?.properties ?? []) {\n byKey.set(lc(p.name), p.value);\n byKey.set(lc(p.path), p.value);\n }\n for (const c of file.components ?? []) for (const [path, value] of Object.entries(c.resolved ?? {})) byKey.set(lc(path), value);\n return (path) => byKey.get(lc(path));\n}\n\n// ---------------------------------------------------------------------------------------------\n// Where a size difference comes from\n\ninterface Contribution {\n amount: number;\n text: string;\n}\n\n/**\n * Splits a size difference between a frame's children along one axis: the space before each child, each child's own\n * size, and the space after the last. A child whose own size accounts for it is explained one level down.\n */\nfunction locate(parentBuilt: string, parentMeasured: string, axis: 'y' | 'x', built: Record<string, MeasuredBox>, measured: MeasuredSpec, builtParts: SpecPart[], pairs: Map<string, string>, depth = 0): Contribution[] {\n const len = axis === 'y' ? 'height' : 'width';\n const before = axis === 'y' ? 'above' : 'before';\n const after = axis === 'y' ? 'below' : 'after';\n const pb = built[parentBuilt];\n const pm = measured.boxes[parentMeasured];\n if (!pb || !pm) return [];\n const kids = builtParts\n .filter((p) => p.parent === parentBuilt && !p.pin && !p.cover && pairs.has(p.id) && built[p.id] && measured.boxes[pairs.get(p.id)!])\n .map((p) => ({ p, b: built[p.id]!, m: measured.boxes[pairs.get(p.id)!]! }))\n .sort((a, b) => a.m[axis] - b.m[axis]);\n if (!kids.length) return [];\n const out: Contribution[] = [];\n const say = (amount: number, where: string) => {\n if (Math.abs(amount) < 1) return;\n out.push({ amount, text: `${round(Math.abs(amount))} px ${amount < 0 ? 'missing' : 'extra'} ${where}` });\n };\n // Children side by side on this axis (a row's height): only the tallest child and the paddings explain it.\n const stacked = kids.every((k, i) => i === 0 || k.m[axis] >= kids[i - 1]!.m[axis] + kids[i - 1]!.m[len] - 0.5);\n if (!stacked) {\n const tallest = [...kids].sort((a, b) => b.m[len] - a.m[len])[0]!;\n const change = tallest.b[len] - tallest.m[len];\n if (Math.abs(change) >= 1) out.push(...ownSize(tallest, change));\n return out;\n }\n let prevB = pb[axis];\n let prevM = pm[axis];\n kids.forEach((k, i) => {\n const gap = k.b[axis] - prevB - (k.m[axis] - prevM);\n say(gap, i === 0 ? `${before} the ${partWords(k.p)}` : `${after} the ${partWords(kids[i - 1]!.p)}`);\n const change = k.b[len] - k.m[len];\n if (Math.abs(change) >= 1) out.push(...ownSize(k, change));\n prevB = k.b[axis] + k.b[len];\n prevM = k.m[axis] + k.m[len];\n });\n say(pb[axis] + pb[len] - prevB - (pm[axis] + pm[len] - prevM), `${after} the ${partWords(kids.at(-1)!.p)}`);\n return out;\n\n function ownSize(k: { p: SpecPart; b: MeasuredBox; m: MeasuredBox }, change: number): Contribution[] {\n const inner = depth < 3 ? locate(k.p.id, pairs.get(k.p.id)!, axis, built, measured, builtParts, pairs, depth + 1) : [];\n if (inner.length) return inner;\n return [{ amount: change, text: `the ${partWords(k.p)} is ${round(Math.abs(change))} px ${change < 0 ? (axis === 'y' ? 'shorter' : 'narrower') : axis === 'y' ? 'taller' : 'wider'} in Figma` }];\n }\n}\n\n// ---------------------------------------------------------------------------------------------\n// One variant\n\nexport interface VariantGapInput {\n /** The parts the set was drawn with, and this variant's values and hidden parts. */\n parts: SpecPart[];\n variant: Pick<SpecVariant, 'values' | 'hidden' | 'layout'>;\n properties?: ComponentSpec['properties'] | undefined;\n built?: GapBuiltVariant | undefined;\n measured: MeasuredSpec;\n /** The fidelity check's sizes (CSS px), when the shot was compared. */\n size?: { figma: Size; code: Size } | undefined;\n resolve?: ((tokenPath: string) => string | number | undefined) | undefined;\n}\n\n/**\n * The differences between what Figma drew for one variant and what the code renders (its measured story): the size and\n * where it comes from, parts one side lacks, fixed sizes Figma hugs, auto layout direction, then field values.\n */\nexport function variantDifferences(input: VariantGapInput): GapDifference[] {\n const { measured } = input;\n const parts = withoutAddedWrappers(input.parts, measured);\n const builtValues: SpecVariant['values'] = {};\n for (const [id, f] of Object.entries(input.variant.values ?? {})) builtValues[id] = { ...f };\n for (const [id, f] of Object.entries(input.built?.values ?? {})) builtValues[id] = { ...(builtValues[id] ?? {}), ...f };\n const hiddenSet = new Set([...(input.variant.hidden ?? []), ...(input.built?.hidden ?? [])]);\n const byId = new Map(parts.map((p) => [p.id, p]));\n const isHidden = (p: SpecPart): boolean => hiddenSet.has(p.id) || (!!p.parent && !!byId.get(p.parent) && isHidden(byId.get(p.parent)!));\n const visible = parts.filter((p) => !isHidden(p));\n const pairOpts = { properties: input.properties };\n const pairs = pairParts(visible, measured, pairOpts);\n const pairedMeasured = new Set(pairs.values());\n const mById = new Map(measured.parts.map((p) => [p.id, p]));\n const out: GapDifference[] = [];\n const name = (id: string) => partWords(byId.get(id) ?? mById.get(id), id);\n\n // 1. Size of the whole variant: the shot sizes, else the layers' root box.\n const rootB = visible.find((p) => !p.parent);\n const codeBox = measured.boxes.root;\n const figmaSize = input.size?.figma ?? (rootB && input.built?.boxes?.[rootB.id]) ?? undefined;\n const codeSize = input.size?.code ?? codeBox;\n let sized = false;\n if (figmaSize && codeSize) {\n for (const [field, axis] of [['height', 'y'], ['width', 'x']] as const) {\n const delta = figmaSize[field] - codeSize[field];\n if (Math.abs(delta) < 1) continue;\n sized = true;\n const where = rootB && input.built?.boxes ? locate(rootB.id, 'root', axis, input.built.boxes, measured, visible, pairs) : [];\n where.sort((a, b) => Math.abs(b.amount) - Math.abs(a.amount));\n const why = where.length ? `: ${where.slice(0, 2).map((w) => w.text).join(', ')}` : '';\n out.push({ text: `${FIELD_WORDS[field]} ${round(figmaSize[field])} in Figma vs ${round(codeSize[field])} in code${why}`, part: 'root', partName: 'component', property: field, expected: round(codeSize[field]), actual: round(figmaSize[field]), delta: round(delta) });\n }\n }\n\n // 2. Parts one side draws and the other does not (the top-most only: a missing knob, not its every layer).\n const pairsAll = pairParts(parts, measured, pairOpts);\n const hiddenFor = new Map<string, string>();\n for (const [b, m] of pairsAll) if (isHidden(byId.get(b)!)) hiddenFor.set(m, b);\n for (const m of measured.parts) {\n if (m.id === 'root' || pairedMeasured.has(m.id)) continue;\n if (m.parent && m.parent !== 'root' && !pairedMeasured.has(m.parent)) continue;\n const hiddenPart = hiddenFor.get(m.id);\n out.push({\n text: hiddenPart ? `The ${name(m.id)} is hidden in Figma, shown in code` : `The ${name(m.id)} is missing in Figma`,\n part: hiddenPart ?? m.id,\n partName: name(m.id),\n property: 'presence',\n expected: 'present',\n actual: hiddenPart ? 'hidden' : 'missing',\n });\n }\n for (const p of visible) {\n if (!p.parent || pairs.has(p.id)) continue;\n if (!pairs.has(p.parent)) continue;\n out.push({ text: `The ${name(p.id)} is in Figma, not in the code render`, part: p.id, partName: name(p.id), property: 'presence', expected: 'absent', actual: 'present' });\n }\n\n // 3. Sizes the CSS fixes that Figma hugs (an icon button around its icon).\n for (const [b, m] of pairs) {\n const fixed = measured.sized?.[m];\n if (!fixed) continue;\n for (const field of ['width', 'height'] as const) {\n if (fixed[field] === undefined || builtValues[b]?.[field] !== undefined) continue;\n if (b === rootB?.id && sized) continue;\n out.push({ text: `${FIELD_WORDS[field]} fixed at ${round(fixed[field]!)} in code, hugs its content in Figma (${name(b)})`, part: b, partName: name(b), property: 'sizing', expected: 'fixed', actual: 'hug' });\n }\n }\n\n // 4. Auto layout direction.\n for (const [b, m] of pairs) {\n const bl = input.variant.layout?.[b] ?? byId.get(b)?.layout;\n const ml = mById.get(m)?.layout;\n if (!bl || !ml || bl.direction === ml.direction) continue;\n const words = (d: string) => (d === 'VERTICAL' ? 'stacked' : 'side by side');\n out.push({ text: `Children ${words(bl.direction)} in Figma, ${words(ml.direction)} in code (${name(b)})`, part: b, partName: name(b), property: 'direction', expected: ml.direction, actual: bl.direction });\n }\n\n // 5. Field values, same rules as the bench (same token, or same value in the page).\n const c = compareSpecToMeasured(visible, builtValues, measured, input.resolve, pairOpts);\n for (const d of c.diffs) {\n if (d.measured === undefined) continue;\n if (d.part === rootB?.id && sized && (d.field === 'width' || d.field === 'height')) continue;\n const box = measured.boxes[pairs.get(d.part) ?? ''];\n const actual = d.static ?? null;\n const expected = d.measured;\n const where = d.part === rootB?.id ? '' : ` (${name(d.part)})`;\n const numeric = typeof actual === 'number' && typeof expected === 'number';\n out.push({\n text: `${FIELD_WORDS[d.field] ?? d.field} ${showValue(actual, d.field, box)} in Figma vs ${showValue(expected, d.field, box)} in code${where}`,\n part: d.part,\n partName: name(d.part),\n property: d.field,\n expected,\n actual,\n ...(numeric ? { delta: round((actual as number) - (expected as number)) } : {}),\n });\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------------------------\n// The case\n\nconst stateWords: Record<GapState, string> = { rest: 'at rest', hover: 'hover', active: 'pressed', 'focus-visible': 'focus', disabled: 'disabled' };\n\n/**\n * The gap case of one component: the variants the referee says differ (the fidelity check; without one, every variant\n * with a difference), each with its story, args, state, shot, Figma render and the differences in words and deltas.\n */\nexport function buildGapCase(input: GapCaseInput): GapCase {\n const stories = storiesOfComponent(input.measured, input.component);\n const resolve = input.resolve ?? measuredResolver(input.measured);\n const spec = input.spec;\n const fixes = fixesOf(input.measured, input.component);\n const checkedVariants: { key: string; props: Record<string, string>; result?: FidelityVariantResult | undefined; variant?: SpecVariant | undefined }[] = [];\n const specVariant = new Map((spec?.variants ?? []).map((v) => [variantKeyOf(v.props), v]));\n if (input.fidelity) {\n for (const r of input.fidelity.variants) if (r.status !== 'skipped') checkedVariants.push({ key: r.key, props: specVariant.get(r.key)?.props ?? propsOfKey(r.key), result: r, variant: specVariant.get(r.key) });\n } else for (const [key, v] of specVariant) checkedVariants.push({ key, props: v.props, variant: v });\n\n const variants: GapVariant[] = [];\n for (const cv of checkedVariants) {\n if (cv.result && cv.result.status !== 'differs') continue;\n const shot = input.shots?.[cv.key];\n const story = spec ? storyForVariant(spec, cv.props, stories, shot) : shot ? stories.find((s) => s.shot?.file === shot.file) : undefined;\n const gv: GapVariant = {\n key: cv.key,\n props: cv.props,\n verdict: cv.result ? 'differs' : 'unchecked',\n ...(cv.result?.percent !== undefined ? { percent: cv.result.percent } : {}),\n ...(cv.result?.size ? { size: cv.result.size } : {}),\n ...(story ? { story: storyRef(story) } : {}),\n ...(shot?.file ?? story?.shot?.file ? { shot: shot?.file ?? story?.shot?.file } : {}),\n ...(input.figmaRenders?.[cv.key] ? { figmaRender: input.figmaRenders[cv.key] } : {}),\n differences: [],\n };\n const measured = story ? (story.instances?.[0] ?? story.spec) : undefined;\n if (!story || !measured) gv.unexplained = 'No measured story renders this variant: measure it, or point it to a story (figma-fixes.json, kind \"story\")';\n else if (!spec || !cv.variant) {\n if (cv.result?.size) gv.differences = variantDifferences({ parts: [], variant: { values: {} }, measured, size: cv.result.size, resolve }).filter((d) => d.part === 'root');\n if (!gv.differences.length) gv.unexplained = 'The pull did not pass the set it drew: only the shots tell this variant apart';\n } else {\n gv.differences = variantDifferences({ parts: spec.parts, variant: cv.variant, properties: spec.properties, built: input.built?.[cv.key], measured, size: cv.result?.size, resolve });\n if (!gv.differences.length) gv.unexplained = agreeWords(cv.result?.percent);\n }\n if (!cv.result && !gv.differences.length) continue;\n variants.push(gv);\n }\n const checked = checkedVariants.length;\n const differing = variants.length;\n const referee = input.fidelity ? 'shots' : 'values';\n return {\n version: GAP_CASE_VERSION,\n component: input.component,\n storybook: input.measured.storybook,\n referee,\n checked,\n differing,\n summary: gapSummary(input.component, variants, checked, input.fidelity),\n detail: gapDetail(input.component, variants, checked, referee),\n variants,\n ...(fixes.length ? { fixes } : {}),\n };\n}\n\nfunction propsOfKey(key: string): Record<string, string> {\n if (key === 'Default') return {};\n return Object.fromEntries(key.split(', ').map((kv) => kv.split('=') as [string, string]));\n}\n\nfunction storyRef(s: MeasuredSpecsStory): GapStoryRef {\n return {\n id: s.id,\n ...(s.name ? { name: s.name } : {}),\n ...(s.url ? { url: s.url } : {}),\n props: { ...(s.props ?? {}) },\n ...(s.overrides && Object.keys(s.overrides).length ? { overrides: { ...s.overrides } } : {}),\n state: storyState(s),\n };\n}\n\n/** Past this share of different pixels, values that agree mean the measure misses what differs, not a near match. */\nconst UNMEASURED_PERCENT = 5;\n\n/** Why a differing variant has no measured difference: a near match to compare by eye, or what Bridge does not measure. */\nfunction agreeWords(percent: number | undefined): string {\n if (percent !== undefined && percent > UNMEASURED_PERCENT)\n return `Bridge doesn't measure what differs here yet: the measured values agree, but ${percent}% of the pixels differ. Not a match: the images decide`;\n return 'The measured values agree with what Figma drew: compare the shot with the Figma render (text rendering, an icon, an image)';\n}\n\n/** Fix ids figma-fixes.json applied to this component (applyFixes writes them on the component entry). */\nfunction fixesOf(file: MeasuredSpecsFile, component: string): string[] {\n const entries = (file.components ?? []).filter((c) => lc(setNameOf(c.title)) === lc(component)) as { figma?: { fixes?: string[] } }[];\n return [...new Set(entries.flatMap((c) => c.figma?.fixes ?? []))];\n}\n\nfunction gapSummary(component: string, variants: GapVariant[], checked: number, fidelity?: FidelityComponentResult): string {\n if (fidelity && fidelity.status === 'not-checked') return `${component} was not compared with the code${fidelity.reason ? `: ${fidelity.reason}` : ''}.`;\n if (!variants.length) return checked ? `${component} matches the code on ${checked} variant${checked === 1 ? '' : 's'}.` : `${component} has no variant to compare.`;\n const first = variants.flatMap((v) => v.differences)[0];\n const head = `${component} differs from the code on ${variants.length} of ${checked} variant${checked === 1 ? '' : 's'}`;\n if (!first) return variants.some((v) => (v.percent ?? 0) > UNMEASURED_PERCENT) ? `${head}: Bridge doesn't measure what differs here yet (the measured values agree, the images do not).` : `${head}: the measure agrees, compare the images.`;\n const more = variants.reduce((n, v) => n + v.differences.length, 0) - 1;\n return `${head}. ${first.text}${more > 0 ? `, and ${more} more` : ''}.`;\n}\n\nfunction gapDetail(component: string, variants: GapVariant[], checked: number, referee: GapCase['referee']): string {\n const lines = [`${component}: ${variants.length} of ${checked} variants differ (${referee === 'shots' ? 'story shots are the referee' : 'no fidelity check passed: measured values only'}).`];\n const fmt = (v: unknown) => (v === null ? 'none' : typeof v === 'string' ? v : JSON.stringify(v));\n for (const v of variants) {\n const where = v.story ? `story ${v.story.id}${v.story.overrides ? ` args ${JSON.stringify(v.story.overrides)}` : ''}, ${stateWords[v.story.state]}` : 'no story';\n const pixels = v.percent !== undefined ? `, ${v.percent}% of pixels` : '';\n const size = v.size ? `, Figma ${round(v.size.figma.width)}x${round(v.size.figma.height)} vs code ${round(v.size.code.width)}x${round(v.size.code.height)}` : '';\n lines.push(`- ${v.key}: ${where}${v.shot ? `, shot ${v.shot}` : ''}${v.figmaRender ? `, Figma ${v.figmaRender}` : ''}${pixels}${size}`);\n for (const d of v.differences) lines.push(` - ${d.part} ${d.property}: expected ${fmt(d.expected)}, actual ${fmt(d.actual)}${d.delta !== undefined ? ` (${d.delta > 0 ? '+' : ''}${d.delta} px)` : ''}`);\n if (v.unexplained) lines.push(` - ${v.unexplained}`);\n }\n return lines.join('\\n');\n}\n","// Figma fixes: corrections a team keeps in its repo (figma-fixes.json, next to bridge.config.json and\n// measured-specs.json) for the components the general measure does not draw right. Claude writes them from a gap case,\n// a person reviews them like any change, and the story shot decides: a fix that does not bring the Figma render closer\n// to the shot is not a fix. Every pull re-applies them to a fresh measure (applyFixes), so they survive pulls.\n//\n// Four kinds, each small and explicit:\n// part a spec patch on one part (values, fixed / hug / fill, align, direction, overlay, hide)\n// axis how a story arg becomes a Figma property (rename it and its values, ignore it, prune combinations)\n// story which story a variant is drawn from\n// status a note, or an honest status (Differs / Can't check) with its reason; never \"matches\"\n//\n// Pure and browser safe: the Figma plugin applies them to measured-specs.json before it builds, the CLI checks them.\n\nimport { COLOR_FIELDS, SPEC_FIELDS, type SpecField, type SpecLayout, type SpecPart, type SpecValue } from './component-spec';\nimport type { MeasuredArgType, MeasuredSpec, MeasuredSpecsComponent, MeasuredSpecsFile, MeasuredSpecsStory } from './measured-spec';\nimport { storyState, type GapState } from './gap-case';\n\nexport const FIGMA_FIXES_VERSION = 1;\n/** Where the fixes live in the team's repo when nothing else is said. */\nexport const DEFAULT_FIGMA_FIXES_FILE = 'figma-fixes.json';\n\nexport type FixArgValue = string | number | boolean;\n\n/** Which variants a fix applies to: stories whose props (args over defaults, plus overrides) include `args`, in `state`. */\nexport interface FixWhere {\n args?: Record<string, FixArgValue> | undefined;\n state?: GapState | undefined;\n}\n\ninterface FixBase {\n /** Stable and unique in the file: lower case, digits and dashes (\"toggle-knob-radius\"). Provenance names it. */\n id: string;\n /** The Figma set: the last segment of the stories' title (\"Toggle\"), case ignored. */\n component: string;\n /** Why, in plain words: read in review and shown where the fix applies. */\n reason: string;\n /** Who wrote it: \"claude\" or a GitHub login. */\n by?: string | undefined;\n /** Only these variants. Absent: every story of the component. */\n where?: FixWhere | undefined;\n}\n\nexport type FixSize = 'hug' | 'fill' | 'fixed' | number;\nexport type FixPrimary = SpecLayout['primary'];\nexport type FixCounter = SpecLayout['counter'];\nexport type FixPin = { top?: number; right?: number; bottom?: number; left?: number };\n\n/** (a) A spec patch on one part of the measured render. */\nexport interface PartFix extends FixBase {\n kind: 'part';\n /** Part id (\"cds--toggle-switch\", \"root\"), or a CSS class with a dot (\".cds--toggle__switch\"): every part with it. */\n part: string;\n /** Field values: a token path, a px number, null (no paint, colors only), or \"full\" for a corner radius (pill). */\n set?: Partial<Record<SpecField, SpecValue | 'full'>> | undefined;\n /** fixed: the measured size (or this number, px), hug: its content, fill: its container. */\n width?: FixSize | undefined;\n height?: FixSize | undefined;\n /** Auto layout of a frame part. */\n direction?: SpecLayout['direction'] | undefined;\n align?: { primary?: FixPrimary | undefined; counter?: FixCounter | undefined } | undefined;\n /** true: over its parent, filling it (out of auto layout). An object: pinned at these offsets (px). false: back in the flow. */\n overlay?: boolean | FixPin | undefined;\n /** Not drawn (with everything inside it). */\n hide?: boolean | undefined;\n}\n\n/** (b) How a story arg becomes a Figma property. */\nexport interface AxisFix extends FixBase {\n kind: 'axis';\n /**\n * map: name the property (`property`) and its values (`values`: code value -> Figma value).\n * ignore: the arg is not a property; only stories at its default value are drawn.\n * prune: drop the variants `where` names (a combination code allows that the library never shows).\n */\n action: 'map' | 'ignore' | 'prune';\n arg?: string | undefined;\n property?: string | undefined;\n values?: Record<string, string> | undefined;\n}\n\n/** (c) The story a variant is drawn from. */\nexport interface StoryFix extends FixBase {\n kind: 'story';\n /** The story to use, as measured: its id, and the args and state of the measured entry when there are several. */\n use: { story: string; args?: Record<string, FixArgValue> | undefined; state?: GapState | undefined };\n}\n\n/** (d) A note, or the status to show with its reason, when a variant will not converge. Never \"matches\". */\nexport interface StatusFix extends FixBase {\n kind: 'status';\n /** Absent: a note only. */\n status?: 'differs' | 'cant-check' | undefined;\n}\n\nexport type FigmaFix = PartFix | AxisFix | StoryFix | StatusFix;\n\nexport interface FigmaFixesFile {\n $schema?: string | undefined;\n version: typeof FIGMA_FIXES_VERSION;\n fixes: FigmaFix[];\n}\n\n// ---------------------------------------------------------------------------------------------\n// Validation\n\nexport class FigmaFixesError extends Error {\n constructor(public readonly problems: string[]) {\n super(`figma-fixes.json: ${problems.join('; ')}`);\n }\n}\n\nconst isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);\nconst STATES: readonly GapState[] = ['rest', 'hover', 'active', 'focus-visible', 'disabled'];\nconst KINDS = ['part', 'axis', 'story', 'status'] as const;\nconst BASE_KEYS = ['id', 'component', 'reason', 'by', 'where', 'kind'];\nconst KEYS: Record<(typeof KINDS)[number], string[]> = {\n part: ['part', 'set', 'width', 'height', 'direction', 'align', 'overlay', 'hide'],\n axis: ['action', 'arg', 'property', 'values'],\n story: ['use'],\n status: ['status'],\n};\nconst PRIMARY = ['MIN', 'CENTER', 'MAX', 'SPACE_BETWEEN'];\nconst COUNTER = ['MIN', 'CENTER', 'MAX', 'STRETCH'];\nconst plain = (v: unknown) => typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean';\n\nfunction whereProblems(w: unknown, at: (why: string) => void) {\n if (!isObj(w)) return at('where must be an object with args and/or state');\n for (const k of Object.keys(w)) if (k !== 'args' && k !== 'state') at(`where.${k} is not known (args, state)`);\n if (w.args !== undefined && (!isObj(w.args) || !Object.values(w.args).every(plain))) at('where.args maps arg names to a text, number or true/false');\n if (w.state !== undefined && !STATES.includes(w.state as GapState)) at(`where.state is one of ${STATES.join(', ')}`);\n}\n\n/**\n * Every problem in a fixes file, in plain words (empty when it is valid): version, unique ids, a component and a reason\n * on every fix, known kinds and keys, and each kind's fields.\n */\nexport function validateFigmaFixes(data: unknown): string[] {\n const out: string[] = [];\n if (!isObj(data)) return ['expected an object with version and fixes'];\n if (data.version !== FIGMA_FIXES_VERSION) out.push(`version ${String(data.version)} is not supported (expected ${FIGMA_FIXES_VERSION})`);\n for (const k of Object.keys(data)) if (!['$schema', 'version', 'fixes'].includes(k)) out.push(`${k} is not known (version, fixes)`);\n if (!Array.isArray(data.fixes)) return [...out, 'fixes must be a list'];\n const ids = new Set<string>();\n data.fixes.forEach((f, i) => {\n const label = isObj(f) && typeof f.id === 'string' ? `fix ${f.id}` : `fix ${i + 1}`;\n const at = (why: string) => out.push(`${label}: ${why}`);\n if (!isObj(f)) return at('must be an object');\n if (typeof f.id !== 'string' || !/^[a-z0-9][a-z0-9-]{0,79}$/.test(f.id)) at('id must be lower case letters, digits and dashes');\n else if (ids.has(f.id)) at('id is repeated');\n else ids.add(f.id);\n if (typeof f.component !== 'string' || !f.component.trim()) at('component is missing (the Figma set name, like \"Toggle\")');\n if (typeof f.reason !== 'string' || f.reason.trim().length < 8) at('reason is missing: say why, in a sentence');\n else if (/\\u2014/.test(f.reason)) at('reason uses an em dash: use a colon or a comma');\n if (f.by !== undefined && typeof f.by !== 'string') at('by must be a text');\n if (f.where !== undefined) whereProblems(f.where, at);\n if (!KINDS.includes(f.kind as (typeof KINDS)[number])) return at(`kind must be one of ${KINDS.join(', ')}`);\n const kind = f.kind as (typeof KINDS)[number];\n for (const k of Object.keys(f)) if (!BASE_KEYS.includes(k) && !KEYS[kind].includes(k)) at(`${k} is not a key of a ${kind} fix`);\n if (kind === 'part') partProblems(f, at);\n if (kind === 'axis') axisProblems(f, at);\n if (kind === 'story') {\n const u = f.use;\n if (!isObj(u) || typeof u.story !== 'string' || !u.story) at('use.story is the story id to draw the variant from');\n else {\n for (const k of Object.keys(u)) if (!['story', 'args', 'state'].includes(k)) at(`use.${k} is not known (story, args, state)`);\n if (u.args !== undefined && (!isObj(u.args) || !Object.values(u.args).every(plain))) at('use.args maps arg names to a text, number or true/false');\n if (u.state !== undefined && !STATES.includes(u.state as GapState)) at(`use.state is one of ${STATES.join(', ')}`);\n }\n if (!isObj(f.where) || (!f.where.args && !f.where.state)) at('where names the variant (args and/or state) the story is for');\n }\n if (kind === 'status') {\n if (f.status === 'matches') at('status cannot be \"matches\": only the shot comparison says a component matches');\n else if (f.status !== undefined && f.status !== 'differs' && f.status !== 'cant-check') at('status is differs or cant-check (absent: a note)');\n }\n });\n return out;\n}\n\nfunction partProblems(f: Record<string, unknown>, at: (why: string) => void) {\n if (typeof f.part !== 'string' || !f.part.trim()) at('part is a part id or a .class');\n const changes = ['set', 'width', 'height', 'direction', 'align', 'overlay', 'hide'].filter((k) => f[k] !== undefined);\n if (!changes.length) at('changes nothing: give set, width, height, direction, align, overlay or hide');\n if (f.hide !== undefined && typeof f.hide !== 'boolean') at('hide is true or false');\n if (f.hide === true && changes.length > 1) at('hide goes alone: a hidden part has nothing else to change');\n if (f.set !== undefined) {\n if (!isObj(f.set) || !Object.keys(f.set).length) at('set maps fields to values');\n else\n for (const [field, value] of Object.entries(f.set)) {\n if (!SPEC_FIELDS.includes(field as SpecField)) {\n at(`set.${field} is not a field (${SPEC_FIELDS.join(', ')})`);\n continue;\n }\n const color = COLOR_FIELDS.has(field as SpecField);\n if (value === 'full') {\n if (field !== 'cornerRadius') at(`set.${field}: \"full\" is for cornerRadius only`);\n } else if (value === null) {\n if (!color) at(`set.${field} cannot be none (only colors can)`);\n } else if (typeof value === 'number') {\n if (color) at(`set.${field} is a color: a token path or null, not a number`);\n else if (!Number.isFinite(value)) at(`set.${field} must be a finite number`);\n } else if (typeof value !== 'string' || !value.trim()) at(`set.${field} must be a token path, a number or null`);\n else if (field === 'textDecoration' && !/^(UNDERLINE|STRIKETHROUGH|NONE)$/.test(value)) at(`set.textDecoration is UNDERLINE, STRIKETHROUGH or NONE`);\n }\n }\n for (const side of ['width', 'height'] as const) {\n const v = f[side];\n if (v !== undefined && !['hug', 'fill', 'fixed'].includes(v as string) && !(typeof v === 'number' && v > 0)) at(`${side} is hug, fill, fixed or a size in px`);\n }\n if (f.direction !== undefined && f.direction !== 'HORIZONTAL' && f.direction !== 'VERTICAL') at('direction is HORIZONTAL or VERTICAL');\n if (f.align !== undefined) {\n const a = f.align;\n if (!isObj(a) || (a.primary === undefined && a.counter === undefined)) at('align gives primary and/or counter');\n else {\n if (a.primary !== undefined && !PRIMARY.includes(a.primary as string)) at(`align.primary is ${PRIMARY.join(', ')}`);\n if (a.counter !== undefined && !COUNTER.includes(a.counter as string)) at(`align.counter is ${COUNTER.join(', ')}`);\n }\n }\n if (f.overlay !== undefined && typeof f.overlay !== 'boolean') {\n const o = f.overlay;\n if (!isObj(o) || !Object.keys(o).length || !Object.entries(o).every(([k, v]) => ['top', 'right', 'bottom', 'left'].includes(k) && typeof v === 'number')) at('overlay is true, false, or offsets in px ({ \"top\": 3, \"left\": 3 })');\n }\n if (f.part === 'root' && (f.hide === true || f.overlay !== undefined)) at('the root cannot be hidden or overlaid');\n}\n\nfunction axisProblems(f: Record<string, unknown>, at: (why: string) => void) {\n const action = f.action;\n if (action !== 'map' && action !== 'ignore' && action !== 'prune') return at('action is map, ignore or prune');\n if (action !== 'prune' && (typeof f.arg !== 'string' || !f.arg)) at(`${action} needs arg (the story arg, like \"kind\")`);\n if (action === 'map') {\n if (f.property === undefined && f.values === undefined) at('map gives property (the Figma name) and/or values');\n if (f.property !== undefined && (typeof f.property !== 'string' || !f.property.trim())) at('property is the Figma property name');\n if (f.values !== undefined && (!isObj(f.values) || !Object.values(f.values).every((v) => typeof v === 'string' && v.trim()))) at('values maps code values to Figma values (texts)');\n else if (isObj(f.values)) {\n const figma = Object.values(f.values) as string[];\n if (new Set(figma).size !== figma.length) at('values gives two code values the same Figma value: use prune for the one to drop');\n }\n }\n if (action === 'ignore' && (f.property !== undefined || f.values !== undefined)) at('ignore takes no property or values');\n if (action === 'prune') {\n if (!isObj(f.where) || (!f.where.args && !f.where.state)) at('prune needs where (the args and/or state of the variants to drop)');\n if (f.property !== undefined || f.values !== undefined) at('prune takes no property or values');\n }\n}\n\n/** Reads figma-fixes.json (text or parsed JSON); throws FigmaFixesError with every problem. */\nexport function parseFigmaFixes(input: string | unknown): FigmaFixesFile {\n let data: unknown = input;\n if (typeof input === 'string') {\n try {\n data = JSON.parse(input);\n } catch (e) {\n throw new FigmaFixesError([`not JSON: ${(e as Error).message}`]);\n }\n }\n const problems = validateFigmaFixes(data);\n if (problems.length) throw new FigmaFixesError(problems);\n return data as FigmaFixesFile;\n}\n\n// ---------------------------------------------------------------------------------------------\n// Applying\n\n/** What applyFixes writes on a component entry for the pull: Figma names, dropped args and combinations, status. */\nexport interface FigmaHints {\n /** Arg -> Figma property name. */\n properties?: Record<string, string> | undefined;\n /** Arg -> code value -> Figma value. */\n values?: Record<string, Record<string, string>> | undefined;\n /** Args that are not Figma properties. */\n ignored?: string[] | undefined;\n /** Variant combinations dropped. */\n pruned?: FixWhere[] | undefined;\n /** Status to show for the component, or for some variants (`where`), with the reason. */\n status?: { status: 'differs' | 'cant-check'; reason: string; fix: string; where?: FixWhere | undefined }[] | undefined;\n notes?: { text: string; fix: string; where?: FixWhere | undefined }[] | undefined;\n /** Ids of the fixes applied to this component, in file order. */\n fixes?: string[] | undefined;\n}\n\nexport type FixedComponent = MeasuredSpecsComponent & { figma?: FigmaHints | undefined };\n/** A measured story a fix changed: the ids of those fixes. */\nexport type FixedStory = MeasuredSpecsStory & { fixes?: string[] | undefined };\n\nexport interface AppliedFix {\n id: string;\n kind: FigmaFix['kind'];\n component: string;\n /** applied: it changed what the pull draws. not-found: nothing matched (the code or the measure moved: re-check it). already: the input had it. */\n result: 'applied' | 'not-found' | 'already';\n /** Story entries it changed. */\n stories: number;\n /** Plain words: what it did, or what it did not find. */\n detail: string;\n}\n\n/** The pull's input with the fixes laid on, and where they came from. */\nexport type FixedMeasuredSpecsFile = Omit<MeasuredSpecsFile, 'stories' | 'components'> & {\n stories: FixedStory[];\n components?: FixedComponent[] | undefined;\n /** The fixes run that made this file. */\n figmaFixes?: { applied: AppliedFix[] } | undefined;\n};\n\nconst lc = (s: string) => s.toLowerCase().replace(/[^a-z0-9]/g, '');\nconst setNameOf = (title: string) => title.split('/').at(-1)!.trim();\nconst propsOf = (s: MeasuredSpecsStory) => ({ ...(s.props ?? {}), ...(s.overrides ?? {}) }) as Record<string, FixArgValue>;\nconst sameArg = (a: unknown, b: unknown) => a === b || (a !== undefined && b !== undefined && String(a).toLowerCase() === String(b).toLowerCase());\n\n/** A story is one of `where`'s variants: every arg it names, at that value, and the state. */\nexport function storyMatchesWhere(s: MeasuredSpecsStory, where: FixWhere | undefined): boolean {\n if (!where) return true;\n const p = propsOf(s);\n if (where.args && !Object.entries(where.args).every(([k, v]) => sameArg(p[k], v))) return false;\n if (where.state && storyState(s) !== where.state) return false;\n return true;\n}\n\n/** Parts a part fix names: an id, or every part with a class. */\nfunction partsNamed(spec: MeasuredSpec, sel: string): SpecPart[] {\n if (sel.startsWith('.')) {\n const cls = sel.slice(1);\n return spec.parts.filter((p) => (p.source ?? '').split(/[\\s,]+/).map((x) => x.replace(/^\\./, '')).includes(cls));\n }\n return spec.parts.filter((p) => p.id === sel);\n}\n\nconst clone = <T>(v: T): T => JSON.parse(JSON.stringify(v)) as T;\n\n/** One part fix on one measured spec. Returns whether anything matched. */\nfunction patchSpec(spec: MeasuredSpec, fix: PartFix): boolean {\n const targets = partsNamed(spec, fix.part);\n if (!targets.length) return false;\n for (const part of targets) {\n const id = part.id;\n const box = spec.boxes[id];\n const parent = part.parent ? spec.parts.find((p) => p.id === part.parent) : undefined;\n if (fix.hide) {\n const gone = new Set([id]);\n for (const p of spec.parts) if (p.parent && gone.has(p.parent)) gone.add(p.id);\n spec.parts = spec.parts.filter((p) => !gone.has(p.id));\n for (const map of [spec.values, spec.raw, spec.tokens, spec.boxes, spec.sized ?? {}, spec.spacers ?? {}, spec.vectors ?? {}] as Record<string, unknown>[]) for (const g of gone) delete map[g];\n continue;\n }\n const values = (spec.values[id] ??= {});\n for (const [field, value] of Object.entries(fix.set ?? {}) as [SpecField, SpecValue | 'full'][]) {\n values[field] = value === 'full' ? (box ? Math.min(box.width, box.height) / 2 : 9999) : value;\n }\n for (const side of ['width', 'height'] as const) {\n const how = fix[side];\n if (how === undefined) continue;\n const flowsAlong = parent?.layout?.direction === (side === 'width' ? 'HORIZONTAL' : 'VERTICAL');\n if (how === 'hug') {\n delete values[side];\n if (spec.sized?.[id]) delete spec.sized[id]![side];\n if (part.stretch) delete part.stretch[side];\n if (flowsAlong) delete part.grow;\n if (!part.parent && side === 'width') delete part.fill;\n } else if (how === 'fill') {\n if (spec.sized?.[id]) delete spec.sized[id]![side];\n if (!part.parent) {\n if (side === 'width') part.fill = true;\n } else if (flowsAlong) part.grow = true;\n else part.stretch = { ...(part.stretch ?? {}), [side]: true };\n } else {\n const px = how === 'fixed' ? (typeof values[side] === 'number' ? (values[side] as number) : box?.[side]) : how;\n if (px === undefined) continue;\n values[side] = px;\n spec.sized = { ...(spec.sized ?? {}), [id]: { ...(spec.sized?.[id] ?? {}), [side]: px } };\n if (part.stretch) delete part.stretch[side];\n if (flowsAlong) delete part.grow;\n if (!part.parent && side === 'width') delete part.fill;\n }\n }\n if (fix.direction || fix.align) {\n part.layout = { direction: 'HORIZONTAL', primary: 'MIN', counter: 'MIN', ...(part.layout ?? {}) };\n if (fix.direction) part.layout.direction = fix.direction;\n if (fix.align?.primary) part.layout.primary = fix.align.primary;\n if (fix.align?.counter) part.layout.counter = fix.align.counter;\n }\n if (fix.overlay !== undefined) {\n delete part.cover;\n delete part.pin;\n if (fix.overlay === true) part.cover = true;\n else if (fix.overlay !== false) part.pin = { ...fix.overlay };\n }\n }\n return true;\n}\n\n/**\n * The measured specs the pull reads, with the fixes laid on, and one provenance record per fix. Pure: the input is not\n * changed. Fixes run in file order; a fix whose component, part or story is not in this measure is reported\n * `not-found` (the code or the measure moved: re-check it) and changes nothing. A file that already carries a fix run\n * (`figmaFixes`) keeps those fixes and only runs the new ones.\n */\nexport function applyFixes(measured: MeasuredSpecsFile | FixedMeasuredSpecsFile, fixes: FigmaFixesFile | FigmaFix[]): { file: FixedMeasuredSpecsFile; applied: AppliedFix[] } {\n const list = Array.isArray(fixes) ? fixes : fixes.fixes;\n const file = clone(measured) as FixedMeasuredSpecsFile;\n const before = new Set((file.figmaFixes?.applied ?? []).filter((a) => a.result === 'applied').map((a) => a.id));\n const applied: AppliedFix[] = [];\n const entryOf = (component: string): FixedComponent | undefined => (file.components ?? []).find((c) => lc(setNameOf(c.title)) === lc(component));\n const hints = (component: string): FigmaHints | undefined => {\n const c = entryOf(component);\n return c ? (c.figma ??= {}) : undefined;\n };\n const mark = (s: FixedStory, id: string) => {\n s.fixes = [...new Set([...(s.fixes ?? []), id])];\n };\n\n for (const fix of list) {\n const record = (result: AppliedFix['result'], stories: number, detail: string) => applied.push({ id: fix.id, kind: fix.kind, component: fix.component, result, stories, detail });\n if (before.has(fix.id)) {\n record('already', 0, 'already applied to this file');\n continue;\n }\n const mine = () => file.stories.filter((s) => lc(setNameOf(s.title)) === lc(fix.component));\n if (!mine().length) {\n record('not-found', 0, `no measured story of ${fix.component}`);\n continue;\n }\n const scoped = () => mine().filter((s) => storyMatchesWhere(s, fix.where));\n\n if (fix.kind === 'part') {\n let n = 0;\n for (const s of scoped()) {\n let hit = false;\n for (const spec of [s.spec, ...(s.instances ?? [])]) if (spec && patchSpec(spec, fix)) hit = true;\n if (hit) {\n n++;\n mark(s, fix.id);\n }\n }\n if (n) record('applied', n, `${describePartFix(fix)} on ${n} stor${n === 1 ? 'y' : 'ies'}`);\n else record('not-found', 0, `no part ${fix.part} in the ${scoped().length ? 'stories it names' : 'variants where names'}`);\n } else if (fix.kind === 'axis') {\n const h = hints(fix.component);\n if (fix.action === 'prune') {\n const drop = new Set(scoped());\n if (!drop.size) {\n record('not-found', 0, 'no measured variant matches where');\n continue;\n }\n file.stories = file.stories.filter((s) => !drop.has(s));\n if (h) h.pruned = [...(h.pruned ?? []), fix.where!];\n record('applied', drop.size, `dropped ${drop.size} variant stor${drop.size === 1 ? 'y' : 'ies'}`);\n } else {\n const arg = fix.arg!;\n const entry = entryOf(fix.component);\n const known = !!entry?.argTypes[arg] || mine().some((s) => arg in propsOf(s));\n if (!known) {\n record('not-found', 0, `${fix.component} has no arg ${arg}`);\n continue;\n }\n if (fix.action === 'map') {\n if (h) {\n if (fix.property) h.properties = { ...(h.properties ?? {}), [arg]: fix.property };\n if (fix.values) h.values = { ...(h.values ?? {}), [arg]: { ...(h.values?.[arg] ?? {}), ...fix.values } };\n }\n record('applied', 0, `${arg} drawn as ${fix.property ?? arg}${fix.values ? ` (${Object.entries(fix.values).map(([c, f]) => `${c} as ${f}`).join(', ')})` : ''}`);\n } else {\n // Not a property: only stories at its default (the argType's, else the first story's, else false) are drawn.\n const at: MeasuredArgType | undefined = entry?.argTypes[arg];\n const lead = mine().find((s) => !s.overrides || !(arg in s.overrides));\n const baseline = at?.default ?? (lead ? propsOf(lead)[arg] : undefined) ?? (at?.kind === 'boolean' ? false : undefined);\n const drop = new Set(scoped().filter((s) => baseline !== undefined && propsOf(s)[arg] !== undefined && !sameArg(propsOf(s)[arg], baseline)));\n file.stories = file.stories.filter((s) => !drop.has(s));\n if (entry) {\n delete entry.argTypes[arg];\n entry.figma ??= {};\n entry.figma.ignored = [...new Set([...(entry.figma.ignored ?? []), arg])];\n }\n record('applied', drop.size, `${arg} is not a Figma property${drop.size ? `: ${drop.size} stor${drop.size === 1 ? 'y' : 'ies'} at another value left out` : ''}`);\n }\n }\n } else if (fix.kind === 'story') {\n const src = file.stories.find(\n (s) => s.id === fix.use.story && s.spec && !s.error && (!fix.use.args || Object.entries(fix.use.args).every(([k, v]) => sameArg(propsOf(s)[k], v))) && (!fix.use.state || storyState(s) === fix.use.state),\n );\n if (!src) {\n record('not-found', 0, `no measured render of story ${fix.use.story}${fix.use.args ? ` with ${JSON.stringify(fix.use.args)}` : ''}`);\n continue;\n }\n const target = fix.where ?? {};\n const others = new Set(scoped().filter((s) => s !== src));\n // The chosen render stands for the variant: its args and state are the variant's, its picture the story's.\n const copy = clone(src) as FixedStory;\n const overrides: Record<string, FixArgValue> = { ...(copy.overrides ?? {}), ...(target.args ?? {}) };\n if (target.state === 'disabled') overrides.disabled = true;\n copy.overrides = overrides;\n if (target.state && target.state !== 'rest' && target.state !== 'disabled') copy.state = target.state;\n else if (target.state) delete copy.state;\n // A story of another component (a richer demo) is drawn in this set.\n if (lc(setNameOf(copy.title)) !== lc(fix.component)) copy.title = copy.title.split('/').slice(0, -1).concat(fix.component).join('/');\n mark(copy, fix.id);\n // In place of the first story it replaces, so the pull meets it where it met them.\n let placed = false;\n file.stories = file.stories.flatMap((s) => (others.has(s) ? (placed ? [] : ((placed = true), [copy])) : [s]));\n if (!placed) file.stories.push(copy);\n record('applied', others.size + 1, `variant ${whereWords(target)} drawn from ${src.id}${others.size ? `, in place of ${others.size} other stor${others.size === 1 ? 'y' : 'ies'}` : ''}`);\n } else {\n const h = hints(fix.component);\n if (!h) {\n record('not-found', 0, `no component entry for ${fix.component} in the measure`);\n continue;\n }\n if (fix.status) {\n h.status = [...(h.status ?? []), { status: fix.status, reason: fix.reason, fix: fix.id, ...(fix.where ? { where: fix.where } : {}) }];\n if (!fix.where) {\n const st = (file.statuses ?? []).find((x) => lc(x.name) === lc(fix.component));\n if (st && st.status !== fix.status) {\n st.status = fix.status;\n delete st.reason;\n st.summary = fix.reason;\n }\n }\n } else h.notes = [...(h.notes ?? []), { text: fix.reason, fix: fix.id, ...(fix.where ? { where: fix.where } : {}) }];\n record('applied', 0, fix.status ? `${fix.status === 'differs' ? 'Differs' : \"Can't check\"}: ${fix.reason}` : `note: ${fix.reason}`);\n }\n const h = hints(fix.component);\n if (h && applied.at(-1)!.result === 'applied') h.fixes = [...new Set([...(h.fixes ?? []), fix.id])];\n }\n file.figmaFixes = { applied: [...(file.figmaFixes?.applied ?? []).filter((a) => a.result === 'applied'), ...applied.filter((a) => a.result !== 'already')] };\n return { file, applied };\n}\n\nfunction whereWords(w: FixWhere): string {\n const args = Object.entries(w.args ?? {}).map(([k, v]) => `${k}=${String(v)}`);\n if (w.state) args.push(`state=${w.state}`);\n return args.join(', ') || 'every variant';\n}\n\n/** A part fix in a few words, for provenance and review: \"toggle switch: cornerRadius full, width fixed\". */\nexport function describePartFix(f: PartFix): string {\n if (f.hide) return `${f.part} hidden`;\n const bits = [\n ...Object.entries(f.set ?? {}).map(([k, v]) => `${k} ${v === null ? 'none' : String(v)}`),\n ...(f.width !== undefined ? [`width ${String(f.width)}`] : []),\n ...(f.height !== undefined ? [`height ${String(f.height)}`] : []),\n ...(f.direction ? [`direction ${f.direction}`] : []),\n ...(f.align ? [`align ${[f.align.primary, f.align.counter].filter(Boolean).join(' ')}`] : []),\n ...(f.overlay !== undefined ? [`overlay ${typeof f.overlay === 'boolean' ? String(f.overlay) : JSON.stringify(f.overlay)}`] : []),\n ];\n return `${f.part}: ${bits.join(', ')}`;\n}\n\n/** One line per fix result, for the CLI and the plugin's pull report. */\nexport function appliedFixLines(applied: AppliedFix[]): string[] {\n return applied.map((a) => `${a.result === 'applied' ? 'applied' : a.result === 'already' ? 'already applied' : 'not found'} ${a.id} (${a.component}, ${a.kind}): ${a.detail}`);\n}\n","// The Figma plugin's measured-only pull, in core so the plugin, the CLI and the MCP server draw the same sets\n// (bridge_try_figma_fix rebuilds them offline).\n//\n// Spec source \"measured only\": component specs built from measured-specs.json alone, with no static spec to lay them\n// on. What any design system can give: a Storybook. The measure (`bridge specs --measure --variants`) records each\n// story's props, its forced state and its rendered tree in the spec shape; this file groups the stories into Figma sets.\n// Pure: no DOM, no figma.*.\n//\n// - Axes: the component's enum props (2 to 12 options, as Storybook knows them) with the values the stories show, the\n// booleans the stories show both ways, a Checked axis from a `checked` prop (mixed from `indeterminate`), and a State\n// axis from the forced states and `disabled`.\n// - A story stands for a variant only when its other booleans are at their defaults (a Loading story is not a variant).\n// - Parts: the default variant's rendered tree. The other variants pair their tree with it (core pairParts, as the bench\n// does); a part a variant does not render is hidden there.\n// - Sizes: a frame with content hugs it (its measured px are not kept); a leaf (an icon, a dot) keeps them, and so\n// does the width of a root that fills its container (the measure lays it out at a set width).\n// - Variables are not built here: they come from the measure's token harvest (to come), or the repo's tokens.\n\nimport { hashSpec, variantKeyOf, type ComponentSpec, type ComponentSpecsFile, type SpecAxis, type SpecField, type SpecLayout, type SpecPart, type SpecValue, type SpecVariant } from './component-spec';\nimport type { FigmaHints, FixedComponent, FixedMeasuredSpecsFile } from './figma-fixes';\nimport { pairParts, type MeasuredArgType, type MeasuredPart, type MeasuredSpec, type MeasuredSpecsFile, type MeasuredSpecsStory } from './measured-spec';\n\n/** What building from the measure gave: sets, variants, and the stories it used. */\nexport interface MeasuredOnlyReport {\n sets: number;\n variants: number;\n stories: number;\n /** Components with stories that gave no set (every story failed, or none at rest). */\n skipped: string[];\n}\n\n/** The screenshot of the story a variant was built from (`--shots`), path relative to measured-specs.json. */\nexport interface VariantShot {\n file: string;\n width: number;\n height: number;\n}\n\n/** Set name -> variant key (variantKeyOf) -> its story's screenshot: the reference Check fidelity compares with. */\nexport type MeasuredShots = Record<string, Record<string, VariantShot>>;\n\n/** Props that never draw a variant (wiring, element type, content), as in core's measure-status. */\nconst NOT_AN_AXIS = /^(as|asChild|render|component|className|class|style|id|key|ref|role|type|name|form|dir|lang|tabIndex|slot|children|htmlFor|value|defaultValue|placeholder|href|target|rel|src|alt)$/i;\nconst STATE_PROPS = new Set(['disabled', 'checked', 'indeterminate']);\nconst STATES: { value: string; of: (s: MeasuredSpecsStory) => boolean }[] = [\n { value: 'Default', of: (s) => !s.state && s.props?.disabled !== true },\n { value: 'Hover', of: (s) => s.state === 'hover' && s.props?.disabled !== true },\n { value: 'Pressed', of: (s) => s.state === 'active' && s.props?.disabled !== true },\n { value: 'Focus', of: (s) => s.state === 'focus-visible' && s.props?.disabled !== true },\n { value: 'Disabled', of: (s) => s.props?.disabled === true },\n];\n\nconst setNameOf = (title: string) => title.split('/').at(-1)!.trim();\nconst axisName = (prop: string) => prop.charAt(0).toUpperCase() + prop.slice(1).replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase();\nconst propsOf = (s: MeasuredSpecsStory) => ({ ...(s.props ?? {}), ...(s.overrides ?? {}) });\n\n/** The story's value on a Checked axis: \"mixed\" when indeterminate, else its `checked`. */\nfunction checkedOf(s: MeasuredSpecsStory): string {\n const p = propsOf(s);\n return p.indeterminate === true ? 'mixed' : String(p.checked === true);\n}\n\n/** Fields a literal can stand in for when no token is known: the look a design system without tokens still has. */\nconst LITERAL_FIELDS: SpecField[] = ['fill', 'textFill', 'stroke', 'fontFamily', 'shadow'];\n\n/**\n * A part's values in the pull's shape. Frames with content hug it: their measured px are what the content made, not a\n * size of their own. A token the library does not have (`known` says no), or a color or font family with no token at\n * all, takes the measured literal (`rgb(...)`, px, a family list): the set draws what code draws, unbound.\n */\nfunction valuesOf(\n spec: MeasuredSpec,\n partId: string,\n hasChildren: boolean,\n known: (path: string) => boolean,\n fills = false,\n own: { width: boolean; height: boolean } = { width: true, height: true },\n): Partial<Record<SpecField, SpecValue>> {\n const sized = { ...(hasChildren ? boxSized(spec, partId, own) : {}), ...spec.sized?.[partId] };\n const v = { ...(spec.values[partId] ?? {}) };\n const raw = spec.raw[partId] ?? {};\n for (const field of Object.keys(v) as SpecField[]) {\n const value = v[field];\n if (typeof value !== 'string' || value.startsWith('calc(') || known(value)) continue;\n const literal = raw[field];\n if (literal === undefined) delete v[field];\n else v[field] = literal;\n }\n for (const field of LITERAL_FIELDS) if (v[field] === undefined && typeof raw[field] === 'string') v[field] = raw[field];\n if (hasChildren) {\n // A root that fills its container keeps the width the measure laid it out at (its story's render has it).\n if (typeof v.width === 'number' && !fills) delete v.width;\n if (typeof v.height === 'number') delete v.height;\n }\n // A size the CSS sets stays fixed, content or not (a 40x40 button around a 16 px icon).\n if (sized?.width !== undefined) v.width = sized.width;\n if (sized?.height !== undefined) v.height = sized.height;\n return v;\n}\n\n/**\n * A size of its own, read from the boxes: a frame bigger than its children plus its padding on an axis (a 48 px button\n * around a 16 px icon, a 24 px label row around a 16 px label) keeps that size, as its CSS gives it, when the measure\n * did not say so. `own`: the axes its parent does not size (not stretched across, not grown along).\n */\nfunction boxSized(spec: MeasuredSpec, partId: string, own: { width: boolean; height: boolean }): { width?: number; height?: number } {\n const box = spec.boxes?.[partId];\n const kids = spec.parts.filter((c) => c.parent === partId && !c.pin && !c.cover && !c.overlay).map((c) => spec.boxes?.[c.id]).filter((b): b is NonNullable<typeof b> => !!b);\n if (!box || !kids.length) return {};\n const raw = spec.raw[partId] ?? {};\n const num = (f: SpecField) => (typeof raw[f] === 'number' ? (raw[f] as number) : 0);\n const left = Math.min(...kids.map((k) => k.x));\n const top = Math.min(...kids.map((k) => k.y));\n // The border is in the box too (CSS border-box), even a transparent one.\n const side = (f: SpecField) => (typeof raw[f] === 'number' ? (raw[f] as number) : num('strokeWeight'));\n const contentW = Math.max(...kids.map((k) => k.x + k.width)) - left + num('paddingLeft') + num('paddingRight') + side('strokeLeftWeight') + side('strokeRightWeight');\n const contentH = Math.max(...kids.map((k) => k.y + k.height)) - top + num('paddingTop') + num('paddingBottom') + side('strokeTopWeight') + side('strokeBottomWeight');\n const out: { width?: number; height?: number } = {};\n if (own.width && box.width - contentW > 1) out.width = box.width;\n if (own.height && box.height - contentH > 1) out.height = box.height;\n return out;\n}\n\n/** One Figma set from the stories of one component, or undefined when none stands for a variant. */\nfunction setOf(\n name: string,\n stories: MeasuredSpecsStory[],\n argTypes: Record<string, MeasuredArgType>,\n source: string,\n known: (path: string) => boolean,\n hints: FigmaHints = {},\n): { spec: ComponentSpec; shots: Record<string, VariantShot> } | undefined {\n // figma-fixes.json names an arg's Figma property and values (\"kind\" -> \"Variant\", \"danger--ghost\" -> \"Danger ghost\").\n const propName = (prop: string) => hints.properties?.[prop] ?? axisName(prop);\n const figmaValue = (prop: string, value: string) => hints.values?.[prop]?.[value] ?? value;\n // Only stories as written or measured for a variant: their other booleans at the component's defaults.\n // Other booleans compare with the component's Default story, not Storybook's defaults: a design system's stories can\n // all set one (Carbon IconButton: defaultOpen, highContrast), and that is then how the component is shown.\n const lead = stories.find((s) => s.name === 'Default' && !s.state) ?? stories[0];\n const baseline = (k: string, a: MeasuredArgType) => (lead ? propsOf(lead)[k] : undefined) ?? a.default ?? false;\n // A skeleton (the loading placeholder) is not a variant. A gallery (its first instance) only stands for a variant no\n // single-instance story renders: it comes last, and the first story of a variant wins.\n const shown = stories.filter((s) => !/skeleton/i.test(s.name));\n const ordered = [...(shown.length ? shown : stories)].sort((a, b) => Number(!!a.gallery) - Number(!!b.gallery));\n // A boolean the stories show both ways is an axis (Carbon Toggle `toggled`); drawnAxes drops it if it draws nothing.\n const valueOf = (s: MeasuredSpecsStory, k: string, a: MeasuredArgType) => (propsOf(s)[k] ?? a.default ?? false) === true;\n const flags = Object.entries(argTypes).filter(\n ([k, a]) => a.kind === 'boolean' && !STATE_PROPS.has(k) && !NOT_AN_AXIS.test(k) && ordered.some((s) => valueOf(s, k, a)) && ordered.some((s) => !valueOf(s, k, a)),\n );\n const plain = ordered.filter((s) =>\n Object.entries(argTypes).every(\n ([k, a]) => a.kind !== 'boolean' || STATE_PROPS.has(k) || NOT_AN_AXIS.test(k) || flags.some(([f]) => f === k) || (propsOf(s)[k] ?? a.default ?? false) === baseline(k, a),\n ),\n );\n if (!plain.length) return undefined;\n const axes: SpecAxis[] = [];\n for (const [prop, a] of flags) {\n const def = String(baseline(prop, a) === true);\n axes.push({ name: propName(prop), prop, values: [figmaValue(prop, def), figmaValue(prop, def === 'true' ? 'false' : 'true')], default: figmaValue(prop, def) });\n }\n for (const [prop, a] of Object.entries(argTypes)) {\n if (a.kind !== 'enum' || NOT_AN_AXIS.test(prop) || !a.options || a.options.length < 2 || a.options.length > 12) continue;\n const seen = new Set(plain.map((s) => String(propsOf(s)[prop] ?? a.default ?? a.options![0])));\n const values = a.options.filter((o) => seen.has(o));\n if (values.length < 2) continue;\n const def = a.default !== undefined && values.includes(String(a.default)) ? String(a.default) : values[0]!;\n axes.push({ name: propName(prop), prop, values: [...new Set(values.map((v) => figmaValue(prop, v)))], default: figmaValue(prop, def) });\n }\n if ('checked' in argTypes || plain.some((s) => 'checked' in propsOf(s))) {\n const values = ['false', 'true', 'mixed'].filter((v) => plain.some((s) => checkedOf(s) === v));\n if (values.length > 1) axes.push({ name: 'Checked', values, default: values[0]! });\n }\n const states = STATES.filter((st) => plain.some(st.of)).map((st) => st.value);\n if (states.length > 1) axes.push({ name: 'State', values: states, default: states[0]! });\n\n // One story per variant: the first one that stands for it.\n const keyOf = (s: MeasuredSpecsStory): Record<string, string> | undefined => {\n const props: Record<string, string> = {};\n for (const axis of axes) {\n const flag = flags.find(([k]) => k === axis.prop);\n const value =\n axis.name === 'State'\n ? STATES.find((st) => st.of(s))?.value\n : axis.name === 'Checked'\n ? checkedOf(s)\n : flag\n ? figmaValue(flag[0], String(valueOf(s, flag[0], flag[1])))\n : propsOf(s)[axis.prop!] === undefined\n ? axis.default\n : figmaValue(axis.prop!, String(propsOf(s)[axis.prop!]));\n if (value === undefined || !axis.values.includes(value)) return undefined;\n props[axis.name] = value;\n }\n return props;\n };\n const candidates = new Map<string, { props: Record<string, string>; stories: MeasuredSpecsStory[] }>();\n for (const s of plain) {\n const props = keyOf(s);\n if (!props) continue;\n const k = JSON.stringify(props);\n if (!candidates.has(k)) candidates.set(k, { props, stories: [] });\n candidates.get(k)!.stories.push(s);\n }\n // The states of a variant come from one story where they can, the one most of them were measured on: Kbd at rest\n // in an input group but hovered alone draws its rest from the story it was hovered in. A state only another story\n // shows (a Disabled story) still comes from that story.\n const storyFor = new Map<string, string>();\n if (axes.some((a) => a.name === 'State')) {\n const rest = (p: Record<string, string>) => JSON.stringify(Object.entries(p).filter(([k]) => k !== 'State'));\n const groups = new Map<string, { props: Record<string, string>; stories: MeasuredSpecsStory[] }[]>();\n for (const c of candidates.values()) groups.set(rest(c.props), [...(groups.get(rest(c.props)) ?? []), c]);\n for (const [key, group] of groups) {\n const ids = [...new Set(group.flatMap((c) => c.stories.map((s) => s.id)))];\n const score = (id: string) => group.filter((c) => c.stories.some((s) => s.id === id)).length;\n storyFor.set(key, ids.reduce((best, id) => (score(id) > score(best) ? id : best), ids[0]!));\n }\n for (const c of candidates.values()) {\n const same = c.stories.filter((s) => s.id === storyFor.get(rest(c.props)));\n if (same.length) c.stories = same;\n }\n }\n const byVariant = new Map([...candidates].map(([k, c]) => [k, { props: c.props, story: c.stories[0]! }]));\n if (!byVariant.size) return undefined;\n const isDefault = (p: Record<string, string>) => axes.every((a) => p[a.name] === a.default);\n const base = [...byVariant.values()].find((v) => isDefault(v.props)) ?? [...byVariant.values()][0]!;\n const baseSpec = base.story.spec!;\n // A part the measure drew as an SVG (an icon, a check mark) is a vector part: the builder draws its markup.\n const parts: MeasuredPart[] = baseSpec.parts.map((p) => (baseSpec.vectors?.[p.id] ? { ...p, kind: 'vector' as const } : { ...p }));\n // An overlay (a popover, a badge, a focus ring) is out of the flow: absolute where the measure saw it, never sizing\n // its parent. Without a box to place it, it covers its parent.\n for (const p of parts) {\n if (!p.overlay || p.pin || p.cover) continue;\n const pin = pinFromBoxes(baseSpec, p);\n if (pin) p.pin = pin;\n else p.cover = true;\n }\n // A frame that paints nothing and holds only overlays (a popover's container) is out of the flow with them: it covers\n // its parent instead of stacking under it.\n const paints = (id: string) => {\n const v = baseSpec.values[id] ?? {};\n return [v.fill, v.stroke].some((x) => x !== undefined && x !== null);\n };\n for (const p of [...parts].reverse()) {\n if (!p.parent || p.kind !== 'frame' || p.pin || p.cover || p.overlay || paints(p.id)) continue;\n const kids = parts.filter((c) => c.parent === p.id);\n if (kids.length && kids.every((c) => c.overlay || c.pin || c.cover)) p.cover = true;\n }\n // A frame that aligns its lone child (a switch and its knob) has room around it: it keeps its measured size.\n const aligners = new Set(\n parts\n .filter((p) => {\n const flow = parts.filter((c) => c.parent === p.id && !c.pin && !c.cover && !c.overlay);\n return flow.length === 1 && !!p.layout?.align?.[flow[0]!.id];\n })\n .map((p) => p.id),\n );\n for (const p of parts) if (p.layout) p.layout = alignedLayout(p, parts);\n // Only children in the flow size a frame: one holding only positioned parts (a switch and its knob) keeps its size.\n const parents = new Set(parts.filter((p) => !p.pin && !p.cover).map((p) => p.parent).filter(Boolean));\n const variants: SpecVariant[] = [];\n const axesMemo = new Map<string, boolean>();\n const shotOf = new Map<SpecVariant, VariantShot>();\n const spacersOf = new Map<SpecVariant, Record<string, number>>();\n const wrapsOf = new Map<SpecVariant, Record<string, NonNullable<MeasuredPart['wrap']>['padding']>>();\n for (const { props, story } of byVariant.values()) {\n const m = story.spec!;\n // Paired on the measure's own parts: an icon made a vector here is still an icon there.\n const pairs = story === base.story ? new Map(parts.map((p) => [p.id, p.id])) : pairParts(baseSpec.parts, m);\n const values: SpecVariant['values'] = {};\n const vectors: NonNullable<SpecVariant['vectors']> = {};\n const pins: NonNullable<SpecVariant['pins']> = {};\n const hidden: string[] = [];\n const spacers: Record<string, number> = {};\n const wraps: Record<string, NonNullable<MeasuredPart['wrap']>['padding']> = {};\n const layouts: NonNullable<SpecVariant['layout']> = {};\n for (const p of parts) {\n const mid = pairs.get(p.id);\n if (mid === undefined) {\n hidden.push(p.id);\n continue;\n }\n values[p.id] = valuesOf(m, mid, parents.has(p.id) && !aligners.has(p.id), known, !p.parent && !!p.fill, ownAxes(p, parts, baseSpec, axesMemo));\n if (m.spacers?.[mid]) spacers[p.id] = m.spacers[mid]!;\n // An icon's fill is the color it draws with (CSS `fill`), not a background: the frame would paint a square.\n if (p.kind === 'icon' || p.kind === 'vector') delete values[p.id]!.fill;\n // A positioned part (a pseudo-element knob) placed elsewhere in this variant: checked moves it to the right.\n const mp = m.parts.find((x) => x.id === mid);\n const pin = mp?.pin ?? (mp?.overlay ? pinFromBoxes(m, mp) : undefined);\n if (p.pin && pin && JSON.stringify(pin) !== JSON.stringify(p.pin)) pins[p.id] = pin;\n // A decoration aligned elsewhere in this variant (the knob at the end when on): its parent's alignment moves.\n if (mp?.layout && p.layout) {\n const layout = alignedLayout({ ...mp, id: p.id }, m.parts.map((x) => ({ ...x, parent: x.parent === mid ? p.id : x.parent })));\n if (layout && (layout.primary !== p.layout.primary || layout.counter !== p.layout.counter || layout.direction !== p.layout.direction)) layouts[p.id] = layout;\n }\n if (mp?.wrap) wraps[p.id] = mp.wrap.padding;\n const vec = p.kind === 'vector' ? m.vectors?.[mid] : undefined;\n // Strokes bind by shape order: with a token the library does not have, the SVG keeps its own (resolved) colors.\n if (vec) vectors[p.id] = { svg: vec.svg, strokes: vec.strokes.every((v) => typeof v !== 'string' || known(v)) ? [...vec.strokes] : [] };\n }\n const variant: SpecVariant = { props, values, ...(hidden.length ? { hidden } : {}), ...(Object.keys(vectors).length ? { vectors } : {}), ...(Object.keys(pins).length ? { pins } : {}), ...(Object.keys(layouts).length ? { layout: layouts } : {}) };\n variants.push(variant);\n spacersOf.set(variant, spacers);\n wrapsOf.set(variant, wraps);\n if (story.shot) shotOf.set(variant, story.shot);\n }\n textRootInFrame(parts, variants);\n spacerWrappers(parts, variants, spacersOf, wrapsOf);\n const properties = textProperties(parts, base.story, argTypes, new Set(axes.map((a) => a.name)));\n const kept = drawnAxes(axes, variants);\n // The story it was measured from: the set's doc section links to it.\n const story = `${source.replace(/\\/+$/, '')}/?path=/story/${base.story.id}`;\n const spec: ComponentSpec = { name, hash: '', source: [story], axes: kept.axes, properties, parts, variants: withoutIdleStates(kept.variants), unmapped: [] };\n // Pruning an axis rewrites a variant's props (a new object): its shot follows by position in the kept list.\n const shots: Record<string, VariantShot> = {};\n kept.variants.forEach((v) => {\n const from = variants.find((x) => JSON.stringify(x.values) === JSON.stringify(v.values) && Object.entries(v.props).every(([k, val]) => x.props[k] === val));\n const shot = from && shotOf.get(from);\n if (shot) shots[variantKeyOf(v.props)] = shot;\n });\n return { spec: { ...spec, hash: hashSpec(spec) }, shots };\n}\n\nconst TEXT_FIELDS = new Set<SpecField>(['textFill', 'fontFamily', 'fontSize', 'fontWeight', 'lineHeight', 'letterSpacing', 'textDecoration']);\n\n/**\n * A component whose root is a text (a link: `<a>` with only text in it) is drawn as a frame that hugs a text, since a\n * Figma component is a frame. The text fields move to the text, the box fields (fill, padding, stroke) stay on the frame,\n * which hugs the text as any frame with content does.\n */\nfunction textRootInFrame(parts: SpecPart[], variants: SpecVariant[]): void {\n const root = parts.find((p) => !p.parent);\n if (!root || root.kind !== 'text') return;\n const id = `${root.id}-text`;\n const text: SpecPart = { ...root, id, name: `${root.name} text`, parent: root.id };\n parts.splice(parts.indexOf(root), 1, { id: root.id, name: root.name, kind: 'frame', ...(root.source ? { source: root.source } : {}), layout: { direction: 'HORIZONTAL', primary: 'MIN', counter: 'MIN' } }, text);\n for (const v of variants) {\n const all = v.values[root.id] ?? {};\n v.values[root.id] = Object.fromEntries(Object.entries(all).filter(([f, value]) => !TEXT_FIELDS.has(f as SpecField) && !((f === 'width' || f === 'height') && typeof value === 'number')));\n v.values[id] = Object.fromEntries(Object.entries(all).filter(([f]) => TEXT_FIELDS.has(f as SpecField)));\n if (v.hidden?.includes(root.id)) v.hidden.push(id);\n }\n}\n\n/**\n * The axes a part's parent does not size. A parent stretches its child across, or a growing child fills along, only when\n * the parent has that size itself (a filling root, a size the CSS or the boxes give, or stretched in turn by such a\n * parent): a wrapper that hugs a 40 px button gives it no width, the button keeps its own.\n */\nfunction ownAxes(part: MeasuredPart, parts: readonly MeasuredPart[], spec?: MeasuredSpec, memo = new Map<string, boolean>()): { width: boolean; height: boolean } {\n const parent = parts.find((x) => x.id === part.parent);\n const dir = parent?.layout?.direction;\n const stretch = parent?.layout?.counter === 'STRETCH';\n const sizedBy = (axis: 'width' | 'height') => !parent || !spec || definiteAxis(parent, axis, parts, spec, memo);\n const acrossW = dir === 'VERTICAL' && stretch && sizedBy('width');\n const alongW = dir === 'HORIZONTAL' && !!part.grow && sizedBy('width');\n const acrossH = dir === 'HORIZONTAL' && stretch && sizedBy('height');\n const alongH = dir === 'VERTICAL' && !!part.grow && sizedBy('height');\n return {\n width: !(!part.parent && part.fill) && !acrossW && !alongW && !part.stretch?.width,\n height: !acrossH && !alongH && !part.stretch?.height,\n };\n}\n\n/** Whether a part has a size of its own on an axis, from the measure, its boxes, or a parent that gives it one. */\nfunction definiteAxis(part: MeasuredPart, axis: 'width' | 'height', parts: readonly MeasuredPart[], spec: MeasuredSpec, memo: Map<string, boolean>): boolean {\n const key = `${part.id}:${axis}`;\n const known = memo.get(key);\n if (known !== undefined) return known;\n memo.set(key, false);\n let result: boolean;\n if (!part.parent) result = axis === 'width' && !!part.fill;\n else if (spec.sized?.[part.id]?.[axis] !== undefined) result = true;\n else {\n const own = ownAxes(part, parts, spec, memo);\n const hasKids = parts.some((c) => c.parent === part.id && !c.pin && !c.cover && !c.overlay);\n result = !own[axis] || (hasKids ? boxSized(spec, part.id, own)[axis] !== undefined : typeof spec.values[part.id]?.[axis] === 'number');\n }\n memo.set(key, result);\n return result;\n}\n\n/** An overlay's place in its parent, from the measured boxes (px from the parent's top and left edges). */\nfunction pinFromBoxes(spec: MeasuredSpec, part: MeasuredPart): NonNullable<SpecPart['pin']> | undefined {\n const box = spec.boxes?.[part.id];\n const parent = part.parent ? spec.boxes?.[part.parent] : undefined;\n if (!box || !parent) return undefined;\n return { top: Math.round((box.y - parent.y) * 100) / 100, left: Math.round((box.x - parent.x) * 100) / 100 };\n}\n\n/**\n * A frame whose one child in the flow is aligned by the measure (`layout.align`: a knob at the start or the end of its\n * switch) carries that alignment itself, so a designer can resize the component and the child stays where code puts it.\n * Its padding (in values) is the offset. With several children in the flow, the frame keeps its own alignment.\n */\nfunction alignedLayout(part: MeasuredPart, parts: readonly MeasuredPart[]): SpecLayout | undefined {\n const layout = part.layout;\n if (!layout?.align) return layout;\n const { align, ...own } = layout;\n const flow = parts.filter((c) => c.parent === part.id && !c.pin && !c.cover && !c.overlay);\n const a = flow.length === 1 ? align[flow[0]!.id] : undefined;\n return a ? { ...own, primary: a.primary ?? own.primary, counter: a.counter ?? own.counter } : own;\n}\n\n/**\n * A margin the parent's gap does not cover (`spacers`: the extra space before a part) becomes a wrapper named after the\n * part (\"Label wrapper\"), its padding on the side the margin is: Figma's auto layout has one gap per frame.\n */\nfunction spacerWrappers(\n parts: SpecPart[],\n variants: SpecVariant[],\n spacersOf: Map<SpecVariant, Record<string, number>>,\n wrapsOf: Map<SpecVariant, Record<string, NonNullable<MeasuredPart['wrap']>['padding']>> = new Map(),\n): void {\n const wrapped = parts.filter((p) => p.parent && !p.pin && !p.cover && variants.some((v) => spacersOf.get(v)?.[p.id] || wrapsOf.get(v)?.[p.id]));\n for (const p of wrapped) {\n const parent = parts.find((x) => x.id === p.parent);\n const row = parent?.layout?.direction === 'HORIZONTAL';\n const id = `${p.id}-wrapper`;\n const wrapper: SpecPart = { id, name: `${p.name} wrapper`, kind: 'frame', parent: p.parent, layout: { direction: row ? 'HORIZONTAL' : 'VERTICAL', primary: 'MIN', counter: 'STRETCH' }, ...(p.grow ? { grow: p.grow } : {}) };\n parts.splice(parts.indexOf(p), 0, wrapper);\n p.parent = id;\n for (const v of variants) {\n // The margins the measure gives (`wrap`), or the extra space before the part (`spacers`).\n const pad = wrapsOf.get(v)?.[p.id];\n const space = spacersOf.get(v)?.[p.id] ?? 0;\n const values: Partial<Record<SpecField, SpecValue>> = {};\n if (pad?.top) values.paddingTop = pad.top;\n if (pad?.right) values.paddingRight = pad.right;\n if (pad?.bottom) values.paddingBottom = pad.bottom;\n if (pad?.left) values.paddingLeft = pad.left;\n if (space) values[row ? 'paddingLeft' : 'paddingTop'] = ((values[row ? 'paddingLeft' : 'paddingTop'] as number | undefined) ?? 0) + space;\n v.values[id] = values;\n if (v.hidden?.includes(p.id)) v.hidden.push(id);\n }\n }\n}\n\n/**\n * A string arg whose value is a text the default story draws is a TEXT property on that text (\"Label\", \"Helper text\"):\n * a designer changes the words of an instance without detaching it.\n */\nfunction textProperties(parts: SpecPart[], story: MeasuredSpecsStory, argTypes: Record<string, MeasuredArgType>, axes: Set<string>): ComponentSpec['properties'] {\n const properties: ComponentSpec['properties'] = [];\n const props = propsOf(story);\n for (const [k, a] of Object.entries(argTypes)) {\n const value = props[k];\n if (a.kind !== 'text' || NOT_AN_AXIS.test(k) || typeof value !== 'string' || !value.trim()) continue;\n const part = parts.find((p) => p.kind === 'text' && !p.text && p.characters?.trim() === value.trim());\n const name = axisName(k);\n if (!part || axes.has(name) || properties.some((x) => x.name === name)) continue;\n part.text = name;\n properties.push({ name, type: 'TEXT', default: value, prop: k });\n }\n return properties;\n}\n\n/**\n * A pointer state a variant draws exactly like its resting one (hover on a read-only or disabled field) is not a\n * variant: the set only has the combinations that look different, as the code renders them.\n */\nfunction withoutIdleStates(variants: SpecVariant[]): SpecVariant[] {\n const look = (v: SpecVariant) => JSON.stringify([v.values, v.hidden ?? [], v.vectors ?? {}, v.pins ?? {}]);\n const rest = (v: SpecVariant) => JSON.stringify(Object.entries(v.props).filter(([k]) => k !== 'State'));\n const resting = new Map(variants.filter((v) => v.props.State === 'Default').map((v) => [rest(v), look(v)]));\n return variants.filter((v) => !['Hover', 'Pressed', 'Focus'].includes(v.props.State ?? '') || resting.get(rest(v)) !== look(v));\n}\n\n/**\n * Only what changes the drawing is a Figma property, as the static generator keeps only props that change the styles:\n * a state the CSS does not style (the measure forces hover on everything) and an axis whose values all draw the same\n * (validationMode) are left out, with the variants they made.\n */\nfunction drawnAxes(axes: SpecAxis[], variants: SpecVariant[]): { axes: SpecAxis[]; variants: SpecVariant[] } {\n const look = (v: SpecVariant) => JSON.stringify([v.values, v.hidden ?? [], v.vectors ?? {}, v.pins ?? {}]);\n let current = { axes, variants };\n for (const axis of axes) {\n const others = (v: SpecVariant) => JSON.stringify(current.axes.filter((a) => a !== axis).map((a) => v.props[a.name]));\n const twin = new Map<string, SpecVariant>();\n for (const v of current.variants) if (v.props[axis.name] === axis.default) twin.set(others(v), v);\n // A value draws something of its own when one of its variants differs from its default twin.\n // The measure forces hover while it presses or focuses: Pressed (or Focus) that draws like Hover is not styled.\n const hoverTwin = new Map<string, SpecVariant>();\n if (axis.name === 'State') for (const v of current.variants) if (v.props.State === 'Hover') hoverTwin.set(others(v), v);\n // Without a default twin (the stories skip that combination), any other value of the axis there stands in.\n const stand = (v: SpecVariant) => current.variants.filter((x) => x.props[axis.name] !== v.props[axis.name] && others(x) === others(v));\n const differs = (v: SpecVariant, from: Map<string, SpecVariant>) =>\n from.has(others(v)) ? look(from.get(others(v))!) !== look(v) : from !== twin || stand(v).every((x) => look(x) !== look(v));\n const drawn = axis.values.filter(\n (value) =>\n value === axis.default ||\n current.variants.some((v) => v.props[axis.name] === value && differs(v, twin) && (!['Pressed', 'Focus'].includes(value) || !hoverTwin.size || differs(v, hoverTwin))),\n );\n const values = axis.values.filter((value) => drawn.includes(value));\n // A value that draws like the default stands for it where the default has no story (only `tel` was hovered).\n const variants = current.variants.filter((v) => values.includes(v.props[axis.name]!));\n const covered = new Set(variants.filter((v) => v.props[axis.name] === axis.default).map(others));\n for (const v of current.variants) {\n if (values.includes(v.props[axis.name]!) || covered.has(others(v))) continue;\n covered.add(others(v));\n variants.push({ ...v, props: { ...v.props, [axis.name]: axis.default } });\n }\n if (values.length > 1) current = { axes: current.axes.map((a) => (a === axis ? { ...a, values } : a)), variants };\n else\n current = {\n axes: current.axes.filter((a) => a !== axis),\n variants: variants.map((v) => ({ ...v, props: Object.fromEntries(Object.entries(v.props).filter(([k]) => k !== axis.name)) })),\n };\n }\n return current;\n}\n\n/** Every set the measure can give, by component (the last segment of a story's title: \"Figma variants/Radio\" is Radio). */\nexport function specsFromMeasure(\n file: MeasuredSpecsFile | FixedMeasuredSpecsFile,\n opts: { known?: ((path: string) => boolean) | undefined } = {},\n): { specs: ComponentSpecsFile; report: MeasuredOnlyReport; shots: MeasuredShots; hints: Record<string, FigmaHints> } {\n const known = opts.known ?? (() => true);\n const groups = new Map<string, MeasuredSpecsStory[]>();\n for (const s of file.stories) {\n if (s.error || !s.spec) continue;\n const name = setNameOf(s.title);\n groups.set(name, [...(groups.get(name) ?? []), s]);\n }\n const argTypesOf = (name: string) => Object.assign({}, ...(file.components ?? []).filter((c) => setNameOf(c.title) === name).map((c) => c.argTypes));\n // What figma-fixes.json says about a set (applyFixes): its property names and values, its status and notes.\n const hints: Record<string, FigmaHints> = {};\n for (const c of (file.components ?? []) as FixedComponent[]) if (c.figma) hints[setNameOf(c.title)] = { ...hints[setNameOf(c.title)], ...c.figma };\n const components: ComponentSpec[] = [];\n const shots: MeasuredShots = {};\n const report: MeasuredOnlyReport = { sets: 0, variants: 0, stories: 0, skipped: [] };\n for (const [name, stories] of [...groups].sort(([a], [b]) => a.localeCompare(b))) {\n const built = setOf(name, stories, argTypesOf(name), file.storybook, known, hints[name]);\n if (!built) {\n report.skipped.push(name);\n continue;\n }\n const spec = built.spec;\n components.push(spec);\n if (Object.keys(built.shots).length) shots[name] = built.shots;\n report.sets++;\n report.variants += spec.variants.length;\n report.stories += stories.length;\n }\n return { specs: { version: 1, generated: `Measured from ${file.storybook} on ${file.measuredAt} (bridge specs --measure).`, components }, report, shots, hints };\n}\n","// The Claude correction loop for the Figma pull, step 3: the team's own Claude (Claude Code or Claude Desktop through the\n// Bridge MCP server, or an API key the team set) reads a gap case, writes fixes (figma-fixes.json), and Bridge is the\n// referee. This file is the referee's offline half and the brief: which components differ (figmaGaps), one component's\n// gap case (gapCaseFor), and the VALUES check of proposed fixes (tryFigmaFixes): the fixes are validated, laid on the\n// measure, the set is rebuilt the way the plugin pulls it (specsFromMeasure), and each differing variant is compared\n// again with what the code renders. The PIXEL check (the story shot against the real Figma render) runs later, in the\n// plugin's Check fidelity after the next pull: nothing here can say a component matches.\n//\n// Pure and browser safe: the MCP server, the CLI, the plugin and Studio can all run it. Bridge holds no API key: the\n// prompt and the reply parser are here for the CLI loop runner (`bridge fix --with-claude`), which uses the team's key.\n\nimport { variantKeyOf, type ComponentSpec, type SpecField, type SpecPart, type SpecValue, type SpecVariant } from './component-spec';\nimport type { FidelityComponentResult, FidelityReport } from './fidelity';\nimport { applyFixes, describePartFix, validateFigmaFixes, type AppliedFix, type FigmaHints, type FigmaFix, type FigmaFixesFile, type FixedMeasuredSpecsFile, FIGMA_FIXES_VERSION } from './figma-fixes';\nimport { buildGapCase, measuredResolver, storiesOfComponent, storyForVariant, variantDifferences, type GapBuiltVariant, type GapCase, type GapDifference } from './gap-case';\nimport type { MeasuredSpecsFile } from './measured-spec';\nimport { specsFromMeasure } from './measured-only';\n\n/** Where the plugin's Check fidelity run lives in the team's repo (or on the requests branch), next to measured-specs.json. */\nexport const DEFAULT_FIDELITY_RUN_FILE = 'figma-fidelity.json';\n/** Rounds of try per component before the loop gives up and proposes an honest status instead. */\nexport const FIX_LOOP_MAX_ROUNDS = 3;\n/** The model the CLI loop runner asks when the team's API key is set and no model is named. */\nexport const FIX_LOOP_MODEL = 'claude-sonnet-5-5';\n\n/**\n * One Check fidelity run, as the plugin saves it: the report (the shot referee), and per set what the layers read back\n * (values, hidden parts, boxes: they let the gap say where space is missing) and a reference to each Figma render.\n */\nexport interface FigmaFidelityRun {\n version: 1;\n report: FidelityReport;\n /** Set name -> variant key -> what the plugin read back from the layers. */\n built?: Record<string, Record<string, GapBuiltVariant>> | undefined;\n /** Set name -> variant key -> node id or exported PNG. */\n figmaRenders?: Record<string, Record<string, string>> | undefined;\n /** measuredAt of the measured-specs.json the pull drew from. */\n measuredAt?: string | undefined;\n}\n\nconst isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);\n\n/**\n * Reads a fidelity run: the plugin's run file, a bare FidelityReport (\"Copy the report\"), or one component's result.\n * Throws a sentence that says what is wrong.\n */\nexport function parseFidelityRun(input: string | unknown): FigmaFidelityRun {\n let data: unknown = input;\n if (typeof input === 'string') {\n try {\n data = JSON.parse(input);\n } catch (e) {\n throw new Error(`The fidelity report is not JSON: ${(e as Error).message}`);\n }\n }\n if (!isObj(data)) throw new Error('The fidelity report is not an object: copy it from the plugin (Check fidelity, Copy the report).');\n if (isObj(data.report) && Array.isArray(data.report.components)) return data as unknown as FigmaFidelityRun;\n if (Array.isArray(data.components)) return { version: 1, report: data as unknown as FidelityReport };\n if (typeof data.component === 'string' && Array.isArray(data.variants)) {\n const c = data as unknown as FidelityComponentResult;\n return {\n version: 1,\n report: {\n version: 1,\n checkedAt: '',\n reference: { sha: '', createdAt: '' },\n options: { scale: 2, threshold: 0.1, radius: 2, maxPercent: 3, sizeTolerance: 1 },\n components: [c],\n summary: { components: 1, matches: c.status === 'matches' ? 1 : 0, differs: c.status === 'differs' ? 1 : 0, notChecked: c.status === 'not-checked' ? 1 : 0, variantsChecked: c.checked, variantsSkipped: c.skipped },\n },\n };\n }\n throw new Error('This is not a fidelity report: expected the plugin\\'s Check fidelity report (components with variants).');\n}\n\nconst lc = (s: string) => s.toLowerCase().replace(/[^a-z0-9]/g, '');\nconst setNameOf = (title: string) => title.split('/').at(-1)!.trim();\nconst byName = <T>(map: Record<string, T> | undefined, name: string): T | undefined => (map ? Object.entries(map).find(([k]) => lc(k) === lc(name))?.[1] : undefined);\n\n// ---------------------------------------------------------------------------------------------\n// Which components differ\n\nexport interface FigmaGapRow {\n component: string;\n /** Differs: the shots (or the measure) say so. Can't check: nothing to compare, or a status fix says so. */\n status: 'differs' | 'cant-check';\n /** One sentence for a designer. */\n summary: string;\n /** What said it: the plugin's Check fidelity (shots), the measure's --check (values), or a status fix. */\n source: 'fidelity' | 'measure' | 'figma-fixes';\n checked?: number | undefined;\n differing?: number | undefined;\n /** Fix ids figma-fixes.json already applies to it. */\n fixes?: string[] | undefined;\n}\n\n/**\n * The components whose Figma build differs from their story, or that cannot be checked: from the fidelity run when\n * there is one (the shots are the referee), else from the measure's statuses (`bridge specs --measure --check`). A\n * status fix in figma-fixes.json shows with its reason. Matching components are left out.\n */\nexport function figmaGaps(measured: FixedMeasuredSpecsFile | MeasuredSpecsFile, run?: FigmaFidelityRun): FigmaGapRow[] {\n const rows = new Map<string, FigmaGapRow>();\n const fixed = measured as FixedMeasuredSpecsFile;\n const fixesOf = (name: string) => (fixed.components ?? []).filter((c) => lc(setNameOf(c.title)) === lc(name)).flatMap((c) => c.figma?.fixes ?? []);\n const put = (row: FigmaGapRow) => {\n const f = fixesOf(row.component);\n rows.set(lc(row.component), { ...row, ...(f.length ? { fixes: f } : {}) });\n };\n if (run) {\n for (const c of run.report.components) {\n if (c.status === 'matches') continue;\n const status = c.status === 'differs' ? 'differs' : 'cant-check';\n const summary =\n status === 'differs'\n ? `${c.component} differs from its story on ${c.differing} of ${c.checked} variant${c.checked === 1 ? '' : 's'}${c.worst ? `: ${Math.round(c.worst.percent * 10) / 10}% of pixels on ${c.worst.key}` : ''}.`\n : `${c.component} was not compared with its story${c.reason ? `: ${c.reason}` : ''}.`;\n put({ component: c.component, status, summary, source: 'fidelity', checked: c.checked, differing: c.differing });\n }\n } else {\n for (const s of measured.statuses ?? []) {\n if (s.status === 'matches') continue;\n put({ component: s.name, status: s.status, summary: s.summary, source: 'measure' });\n }\n }\n // A status fix speaks for the component as a whole (no `where`): its reason is the sentence a designer sees.\n for (const c of fixed.components ?? []) {\n for (const st of c.figma?.status ?? []) {\n if (st.where) continue;\n const name = setNameOf(c.title);\n const had = rows.get(lc(name));\n if (run && !had) continue;\n put({ component: had?.component ?? name, status: st.status, summary: st.reason, source: 'figma-fixes', ...(had?.checked !== undefined ? { checked: had.checked, differing: had.differing } : {}) });\n }\n }\n return [...rows.values()].sort((a, b) => (a.status === b.status ? a.component.localeCompare(b.component) : a.status === 'differs' ? -1 : 1));\n}\n\n// ---------------------------------------------------------------------------------------------\n// One component's gap case\n\nexport interface GapCaseForInput {\n component: string;\n /** measured-specs.json as measured (the team's fixes are applied here). */\n measured: MeasuredSpecsFile;\n /** figma-fixes.json, when the repo has one. */\n fixes?: FigmaFixesFile | undefined;\n run?: FigmaFidelityRun | undefined;\n}\n\nexport interface GapCaseFor {\n gap: GapCase;\n /** The measure with the team's fixes on (what the pull reads). */\n measured: FixedMeasuredSpecsFile;\n /** The set the pull draws from it (specsFromMeasure), when the measure gives one. */\n spec?: ComponentSpec | undefined;\n fidelity?: FidelityComponentResult | undefined;\n shots: Record<string, { file: string }>;\n}\n\n/** The gap case of one component, built the way the plugin pulls it: fixes applied, set rebuilt, the run's verdicts. */\nexport function gapCaseFor(input: GapCaseForInput): GapCaseFor {\n const fixed = input.fixes ? applyFixes(input.measured, input.fixes).file : (input.measured as FixedMeasuredSpecsFile);\n const { specs, shots } = specsFromMeasure(fixed as MeasuredSpecsFile);\n const spec = specs.components.find((c) => lc(c.name) === lc(input.component));\n const fidelity = input.run?.report.components.find((c) => lc(c.component) === lc(input.component));\n const setShots = byName(shots, input.component) ?? {};\n const gap = buildGapCase({\n component: spec?.name ?? input.component,\n measured: fixed as MeasuredSpecsFile,\n spec,\n fidelity,\n built: byName(input.run?.built, input.component),\n figmaRenders: byName(input.run?.figmaRenders, input.component),\n shots: setShots,\n });\n return { gap, measured: fixed, spec, fidelity, shots: setShots };\n}\n\n// ---------------------------------------------------------------------------------------------\n// The fix schema, in a page Claude reads (docs/FIGMA-FIXES.md says the same, longer)\n\nexport const FIX_SCHEMA_SUMMARY = `figma-fixes.json fixes (version ${FIGMA_FIXES_VERSION}). Each fix is one JSON object:\n- Every fix: \"id\" (lower case, digits, dashes, unique), \"kind\", \"component\" (the Figma set, e.g. \"TextInput\"), \"reason\" (one plain sentence, no em dash), optional \"by\": \"claude\", optional \"where\": { \"args\": { \"<arg>\": value }, \"state\": \"rest\" | \"hover\" | \"active\" | \"focus-visible\" | \"disabled\" } (absent: every variant).\n- kind \"part\": \"part\" is a part id from the gap case (\"root\", \"cds--text-input-label-wrapper\") or \".class\". At least one of: \"set\" { field: token path | px number | null (colors only) | \"full\" (cornerRadius only) }, \"width\" / \"height\": \"fixed\" (the measured size) | px number | \"hug\" | \"fill\", \"direction\": \"HORIZONTAL\" | \"VERTICAL\", \"align\": { \"primary\": MIN|CENTER|MAX|SPACE_BETWEEN, \"counter\": MIN|CENTER|MAX|STRETCH }, \"overlay\": true | false | { \"top\": 3, \"left\": 3 }, \"hide\": true (alone; never the root). Fields: fill, stroke, strokeWeight, strokeTopWeight, strokeRightWeight, strokeBottomWeight, strokeLeftWeight, cornerRadius, paddingTop, paddingRight, paddingBottom, paddingLeft, itemSpacing, counterAxisSpacing, width, height, minWidth, minHeight, opacity, textFill, fontFamily, fontSize, fontWeight, lineHeight, letterSpacing, textDecoration.\n- kind \"axis\": \"action\" \"map\" (\"arg\", \"property\" and/or \"values\" { code value: Figma value }), \"ignore\" (\"arg\"), or \"prune\" (\"where\" names the variants to drop).\n- kind \"story\": \"where\" names the variant, \"use\": { \"story\": \"<story id>\", \"args\"?, \"state\"? } is the measured render to draw it from.\n- kind \"status\": \"status\": \"differs\" | \"cant-check\" with the reason; never \"matches\" (only the shots say a component matches). Without \"status\": a note.\nRules: fix only the component you were given; prefer the smallest fix that explains the differences (a part's size \"fixed\" when Figma hugs what code fixes, a missing padding, a hidden part); never invent a part id or a token: use the ones in the gap case.`;\n\n// ---------------------------------------------------------------------------------------------\n// Try: the values referee\n\nexport type FixDiffResult = 'resolved' | 'closer' | 'same' | 'worse' | 'unknown';\nexport type FixVerdict = 'closer' | 'same' | 'worse';\n\nexport interface TriedDifference {\n text: string;\n part: string;\n property: GapDifference['property'];\n /** Code (the measure). */\n expected: SpecValue | boolean;\n /** Figma now (the gap case), and what the rebuilt set draws with the fixes. */\n before: SpecValue | boolean;\n after: SpecValue | boolean | undefined;\n deltaBefore?: number | undefined;\n deltaAfter?: number | undefined;\n result: FixDiffResult;\n /** The size after is worked out from the layer boxes and the changed paddings, gaps and fixed sizes. */\n estimated?: boolean | undefined;\n}\n\nexport interface TriedVariant {\n key: string;\n story?: string | undefined;\n /** gone: the fixes drop this variant (prune, ignore). */\n verdict: FixVerdict | 'gone';\n differences: TriedDifference[];\n /** Differences the fixes add: the rebuilt set now disagrees with the code where it agreed. */\n regressions: GapDifference[];\n}\n\nexport interface TryFixesResult {\n status: 'invalid' | 'checked';\n component: string;\n /** Validation problems (status invalid): fix them and try again. */\n problems: string[];\n /** One record per proposed fix: applied, not-found (its part or story is not in this measure), already. */\n applied: AppliedFix[];\n /** The values referee's verdict on the whole: closer, same or worse. */\n verdict: FixVerdict;\n referee: 'values';\n variants: TriedVariant[];\n /** One sentence. */\n summary: string;\n /** Lines for Claude: per variant, each difference before and after. */\n detail: string;\n /** The figma-fixes.json the fixes make (the repo's fixes, with these added or replacing the same ids). */\n file?: FigmaFixesFile | undefined;\n}\n\nexport interface TryFixesInput extends GapCaseForInput {\n /** The fixes to try, added to the repo's (a fix with the id of one already there replaces it). */\n proposed: unknown[];\n}\n\n/** The repo's fixes with the proposed ones: a proposed fix replaces one with the same id, the others are appended. */\nexport function mergeFigmaFixes(existing: FigmaFixesFile | undefined, proposed: FigmaFix[]): FigmaFixesFile {\n const ids = new Set(proposed.map((f) => f.id));\n return { ...(existing?.$schema ? { $schema: existing.$schema } : {}), version: FIGMA_FIXES_VERSION, fixes: [...(existing?.fixes ?? []).filter((f) => !ids.has(f.id)), ...proposed] };\n}\n\n/** Problems a proposed list has before the file is even built: not a list, or a fix for another component. */\nfunction proposedProblems(component: string, proposed: unknown[], existing: FigmaFix[] = []): string[] {\n if (!Array.isArray(proposed) || !proposed.length) return ['fixes must be a non-empty list of fix objects'];\n const out: string[] = [];\n proposed.forEach((f, i) => {\n if (!isObj(f)) return;\n const label = typeof f.id === 'string' ? `fix ${f.id}` : `fix ${i + 1}`;\n if (typeof f.component === 'string' && lc(f.component) !== lc(component)) out.push(`${label}: component is ${f.component}, but this loop fixes ${component} only (one component at a time)`);\n const taken = existing.find((x) => x.id === f.id && lc(x.component) !== lc(component));\n if (taken) out.push(`${label}: the id is taken by a fix for ${taken.component}: pick another id`);\n });\n return out;\n}\n\n/**\n * The values referee: validates the proposed fixes, lays them on the measure, rebuilds the set the way the plugin pulls\n * it, and compares each variant the gap case lists with what the code renders, before and after. A difference is\n * resolved, closer, the same or worse; a difference the fixes add elsewhere is a regression. The verdict is closer when\n * more moved closer than got worse. Offline: no Figma, no shots. The pixel check runs in the plugin after the pull.\n */\nexport function tryFigmaFixes(input: TryFixesInput): TryFixesResult {\n const component = input.component;\n const empty = (problems: string[]): TryFixesResult => ({\n status: 'invalid',\n component,\n problems,\n applied: [],\n verdict: 'same',\n referee: 'values',\n variants: [],\n summary: `Not tried: ${problems.length} problem${problems.length === 1 ? '' : 's'} in the fixes. Fix them and try again.`,\n detail: problems.map((p) => `- ${p}`).join('\\n'),\n });\n const pre = proposedProblems(component, input.proposed, input.fixes?.fixes);\n if (pre.length) return empty(pre);\n const proposedIds = new Set((input.proposed as { id?: unknown }[]).map((f) => f.id).filter((x): x is string => typeof x === 'string'));\n const draft = { version: FIGMA_FIXES_VERSION, fixes: [...(input.fixes?.fixes ?? []).filter((f) => !proposedIds.has(f.id)), ...input.proposed] };\n const problems = validateFigmaFixes(draft);\n if (problems.length) return empty(problems);\n const file = draft as FigmaFixesFile;\n const proposed = file.fixes.filter((f) => proposedIds.has(f.id));\n\n const before = gapCaseFor({ component, measured: input.measured, fixes: input.fixes, run: input.run });\n const afterRun = applyFixes(input.measured, file);\n const applied = afterRun.applied.filter((a) => proposedIds.has(a.id));\n const afterBuilt = specsFromMeasure(afterRun.file as MeasuredSpecsFile);\n const afterSpec = afterBuilt.specs.components.find((c) => lc(c.name) === lc(component));\n const hintsA = afterSpec ? afterBuilt.hints[afterSpec.name] : undefined;\n const hintsB = before.spec ? specsFromMeasure(before.measured as MeasuredSpecsFile).hints[before.spec.name] : undefined;\n const resolve = measuredResolver(before.measured);\n const built = byName(input.run?.built, component);\n const stories = storiesOfComponent(before.measured, component);\n\n const variants: TriedVariant[] = [];\n for (const gv of before.gap.variants) {\n const vb = before.spec?.variants.find((v) => variantKeyOf(v.props) === gv.key);\n // An axis fix renames a property or its values: the same variant under its new name.\n const want = before.spec ? renamedProps(gv.props, before.spec, afterSpec, hintsB, hintsA) : gv.props;\n const va = afterSpec?.variants.find((v) => variantKeyOf(v.props) === gv.key) ?? afterSpec?.variants.find((v) => sameProps(v.props, want));\n if (!va || !afterSpec) {\n variants.push({ key: gv.key, ...(gv.story ? { story: gv.story.id } : {}), verdict: 'gone', differences: [], regressions: [] });\n continue;\n }\n const differences = gv.differences.map((d) => tryDifference(d, before.spec, vb, afterSpec, va, built?.[gv.key], resolve));\n let regressions: GapDifference[] = [];\n const story = before.spec ? storyForVariant(before.spec, gv.props, stories, before.shots[gv.key]) : undefined;\n const m = story ? (story.instances?.[0] ?? story.spec) : undefined;\n if (m && before.spec && vb) {\n const key = (d: GapDifference) => `${d.part}|${d.property}`;\n const had = new Set(variantDifferences({ parts: before.spec.parts, variant: vb, properties: before.spec.properties, measured: m, resolve }).map(key));\n const seen = new Set(gv.differences.map(key));\n regressions = variantDifferences({ parts: afterSpec.parts, variant: va, properties: afterSpec.properties, measured: m, resolve }).filter((d) => !had.has(key(d)) && !seen.has(key(d)));\n }\n variants.push({ key: gv.key, ...(gv.story ? { story: gv.story.id } : {}), verdict: verdictOf(differences, regressions), differences, regressions });\n }\n const all = variants.flatMap((v) => v.differences);\n const regressions = variants.reduce((n, v) => n + v.regressions.length, 0);\n const verdict = verdictOf(all, variants.flatMap((v) => v.regressions));\n const notFound = applied.filter((a) => a.result === 'not-found');\n return {\n status: 'checked',\n component,\n problems: [],\n applied,\n verdict,\n referee: 'values',\n variants,\n summary: trySummary(component, before.gap, all, regressions, verdict, notFound, proposed),\n detail: tryDetail(variants, applied),\n file,\n };\n}\n\nconst sameProps = (a: Record<string, string>, b: Record<string, string>) => Object.keys(a).length === Object.keys(b).length && Object.entries(a).every(([k, v]) => b[k] === v);\n\n/** A variant's props as the set names them after the fixes: axes renamed and values mapped (figma-fixes.json axis fixes). */\nfunction renamedProps(props: Record<string, string>, specB: ComponentSpec, specA: ComponentSpec | undefined, hintsB: FigmaHints | undefined, hintsA: FigmaHints | undefined): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [name, value] of Object.entries(props)) {\n const prop = specB.axes.find((a) => a.name === name)?.prop;\n if (!prop) {\n out[name] = value;\n continue;\n }\n const axis = specA?.axes.find((a) => a.prop === prop);\n if (!axis) continue;\n const code = Object.entries(hintsB?.values?.[prop] ?? {}).find(([, f]) => f === value)?.[0] ?? value;\n out[axis.name] = hintsA?.values?.[prop]?.[code] ?? code;\n }\n return out;\n}\n\nfunction verdictOf(diffs: TriedDifference[], regressions: GapDifference[]): FixVerdict {\n const better = diffs.filter((d) => d.result === 'resolved' || d.result === 'closer').length;\n const worse = diffs.filter((d) => d.result === 'worse').length + regressions.length;\n return better > worse ? 'closer' : worse > better ? 'worse' : 'same';\n}\n\nconst isNum = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);\nconst round = (n: number) => Math.round(n * 10) / 10;\n\n/** A value as a number of px when it is one (a number, \"12px\", a token whose value in the page is px). */\nfunction numberOf(v: unknown, resolve: (p: string) => string | number | undefined): number | undefined {\n if (isNum(v)) return v;\n if (typeof v !== 'string') return undefined;\n const t = v.trim();\n if (/^-?[\\d.]+(px)?$/.test(t)) return parseFloat(t);\n const r = resolve(t);\n if (isNum(r)) return r;\n if (typeof r === 'string' && /^-?[\\d.]+(px)?$/.test(r.trim())) return parseFloat(r);\n return undefined;\n}\n\nfunction sameValue(a: unknown, b: unknown, resolve: (p: string) => string | number | undefined): boolean {\n if (a === b) return true;\n if (a === undefined || b === undefined) return false;\n const na = numberOf(a, resolve);\n const nb = numberOf(b, resolve);\n if (na !== undefined && nb !== undefined) return Math.abs(na - nb) <= 0.5;\n const s = (v: unknown) => {\n const r = typeof v === 'string' ? (resolve(v) ?? v) : v;\n return String(r).replace(/\\s+/g, '').toLowerCase();\n };\n return s(a) === s(b);\n}\n\nconst valueIn = (v: SpecVariant | undefined, part: string, field: SpecField) => v?.values[part]?.[field];\n\n/** How a difference stands once the fixes are on: the rebuilt set's value for it, against the code's. */\nfunction tryDifference(\n d: GapDifference,\n specB: ComponentSpec | undefined,\n vb: SpecVariant | undefined,\n specA: ComponentSpec,\n va: SpecVariant,\n built: GapBuiltVariant | undefined,\n resolve: (p: string) => string | number | undefined,\n): TriedDifference {\n const base: TriedDifference = { text: d.text, part: d.part, property: d.property, expected: d.expected, before: d.actual, after: d.actual, ...(d.delta !== undefined ? { deltaBefore: d.delta } : {}), result: 'same' };\n const done = (after: SpecValue | boolean | undefined, extra: Partial<TriedDifference> = {}): TriedDifference => {\n const out = { ...base, after, ...extra };\n if (out.result !== 'unknown') {\n if (sameValue(after, d.expected, resolve)) out.result = 'resolved';\n else if (d.delta !== undefined && isNum(out.deltaAfter)) out.result = Math.abs(out.deltaAfter) < Math.abs(d.delta) - 0.25 ? 'closer' : Math.abs(out.deltaAfter) > Math.abs(d.delta) + 0.25 ? 'worse' : 'same';\n else out.result = 'same';\n }\n return out;\n };\n const partOf = (spec: ComponentSpec | undefined, id: string) => spec?.parts.find((p) => p.id === id);\n const hiddenIn = (spec: ComponentSpec, v: SpecVariant, id: string): boolean => {\n if (!partOf(spec, id)) return true;\n if (v.hidden?.includes(id)) return true;\n const p = partOf(spec, id)!;\n return p.parent ? hiddenIn(spec, v, p.parent) : false;\n };\n\n if (d.property === 'presence') {\n if (d.actual === 'hidden' || d.actual === 'missing') return done(partOf(specA, d.part) && !hiddenIn(specA, va, d.part) ? 'present' : d.actual);\n if (d.expected === 'absent') return done(hiddenIn(specA, va, d.part) ? 'absent' : 'present');\n return done(d.actual);\n }\n if (d.property === 'direction') {\n const dir = va.layout?.[d.part]?.direction ?? partOf(specA, d.part)?.layout?.direction;\n return done(dir ?? d.actual);\n }\n if (d.property === 'sizing') {\n const field: SpecField = /^height/i.test(d.text) ? 'height' : 'width';\n return done(isNum(valueIn(va, d.part, field)) ? 'fixed' : d.actual);\n }\n if ((d.property === 'height' || d.property === 'width') && d.part === 'root' && isNum(d.actual) && isNum(d.expected)) {\n // The size of the whole variant: exact when the root is now fixed, else worked out from what the fixes change.\n const field = d.property;\n const root = specA.parts.find((p) => !p.parent);\n const fixedNow = root ? valueIn(va, root.id, field) : undefined;\n const fixedBefore = root ? valueIn(vb, root.id, field) : undefined;\n if (isNum(fixedNow) && !sameValue(fixedNow, fixedBefore, resolve)) return done(round(fixedNow), { deltaAfter: round(fixedNow - d.expected) });\n if (!specB || !vb || !root) return { ...base, result: 'unknown' };\n const shift = sizeShift(field, specB, vb, specA, va, built, resolve);\n if (shift === undefined) return { ...base, result: 'unknown' };\n const after = round(d.actual + shift);\n return done(after, { deltaAfter: round(after - d.expected), ...(shift ? { estimated: true } : {}) });\n }\n // A field value on a part: the rebuilt set's value when the fixes changed it, else what Figma has now.\n const field = d.property as SpecField;\n const now = valueIn(va, d.part, field);\n const was = valueIn(vb, d.part, field);\n if (JSON.stringify(now) === JSON.stringify(was)) return done(d.actual, d.delta !== undefined ? { deltaAfter: d.delta } : {});\n const after = now === undefined ? null : now;\n const na = numberOf(after, resolve);\n const ne = numberOf(d.expected, resolve);\n return done(after, na !== undefined && ne !== undefined ? { deltaAfter: round(na - ne) } : {});\n}\n\n/**\n * How much a variant's height (or width) moves with the fixes, from the parts stacked along that axis: changed paddings,\n * gaps times the gaps between visible children, and parts that now have a fixed size (from their box in the layers).\n * Undefined when a part becomes fixed and its size in Figma is not known (no layer boxes).\n */\nfunction sizeShift(field: 'height' | 'width', specB: ComponentSpec, vb: SpecVariant, specA: ComponentSpec, va: SpecVariant, built: GapBuiltVariant | undefined, resolve: (p: string) => string | number | undefined): number | undefined {\n const along = field === 'height' ? 'VERTICAL' : 'HORIZONTAL';\n const pads: SpecField[] = field === 'height' ? ['paddingTop', 'paddingBottom'] : ['paddingLeft', 'paddingRight'];\n const n = (v: unknown) => numberOf(v, resolve) ?? 0;\n const hidden = new Set([...(va.hidden ?? [])]);\n const kids = (id: string) => specA.parts.filter((p) => p.parent === id && !p.pin && !p.cover && !hidden.has(p.id));\n let shift = 0;\n let unknown = false;\n const walk = (p: SpecPart) => {\n const own = valueIn(va, p.id, field);\n const was = valueIn(vb, p.id, field);\n if (p.parent && isNum(own) && !sameValue(own, was, resolve)) {\n const current = built?.boxes?.[p.id]?.[field] ?? (isNum(was) ? was : undefined);\n if (current === undefined) unknown = true;\n else shift += own - current;\n return; // A fixed part: what is inside no longer moves the variant.\n }\n for (const f of pads) shift += n(valueIn(va, p.id, f)) - n(valueIn(vb, p.id, f));\n const dirA = va.layout?.[p.id]?.direction ?? p.layout?.direction;\n const children = kids(p.id);\n if (dirA === along) {\n const gaps = Math.max(0, children.length - 1);\n shift += gaps * (n(valueIn(va, p.id, 'itemSpacing')) - n(valueIn(vb, p.id, 'itemSpacing')));\n for (const c of children) walk(c);\n }\n };\n const root = specA.parts.find((p) => !p.parent);\n if (!root || !specB.parts.length) return undefined;\n walk(root);\n return unknown ? undefined : round(shift);\n}\n\nfunction trySummary(component: string, gap: GapCase, diffs: TriedDifference[], regressions: number, verdict: FixVerdict, notFound: AppliedFix[], proposed: FigmaFix[]): string {\n if (!gap.variants.length) return `${component} has no differing variant in the gap case: nothing for these fixes to move (the values referee needs a Check fidelity report or a difference in the measure).`;\n const resolved = diffs.filter((d) => d.result === 'resolved').length;\n const closer = diffs.filter((d) => d.result === 'closer').length;\n const worse = diffs.filter((d) => d.result === 'worse').length;\n const bits = [`${resolved} of ${diffs.length} difference${diffs.length === 1 ? '' : 's'} resolved`, ...(closer ? [`${closer} closer`] : []), ...(worse ? [`${worse} worse`] : []), ...(regressions ? [`${regressions} new`] : [])];\n const word = verdict === 'closer' ? 'Closer to the code' : verdict === 'worse' ? 'Further from the code' : 'No closer to the code';\n const statusOnly = proposed.length > 0 && proposed.every((f) => f.kind === 'status' || (f.kind === 'axis' && f.action === 'map'));\n const missing = notFound.length ? ` ${notFound.map((a) => a.id).join(', ')} found nothing in the measure.` : '';\n const note = statusOnly && verdict === 'same' ? ' These fixes change how the set is named or labelled, not what it draws.' : '';\n return `${word} on the measured values: ${bits.join(', ')}.${missing}${note} The pixel check runs in the plugin after the next pull.`;\n}\n\nfunction tryDetail(variants: TriedVariant[], applied: AppliedFix[]): string {\n const fmt = (v: unknown) => (v === null ? 'none' : v === undefined ? 'unknown' : typeof v === 'string' ? v : JSON.stringify(v));\n const lines: string[] = [];\n for (const a of applied) lines.push(`${a.id}: ${a.result}${a.detail ? `, ${a.detail}` : ''}`);\n for (const v of variants) {\n lines.push(`- ${v.key}${v.story ? ` (story ${v.story})` : ''}: ${v.verdict}`);\n for (const d of v.differences) {\n const delta = d.deltaBefore !== undefined ? ` (${d.deltaBefore > 0 ? '+' : ''}${d.deltaBefore} px -> ${d.deltaAfter === undefined ? '?' : `${d.deltaAfter > 0 ? '+' : ''}${d.deltaAfter}`} px)` : '';\n lines.push(` - ${d.part} ${d.property}: expected ${fmt(d.expected)}, was ${fmt(d.before)}, now ${fmt(d.after)}${delta}: ${d.result}${d.estimated ? ' (estimated from the layer boxes)' : ''}`);\n }\n for (const r of v.regressions) lines.push(` - new: ${r.text}`);\n }\n return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------------------------\n// The change for review\n\n/** Plain words for one fix, for the pull request body. */\nexport function fixWords(f: FigmaFix): string {\n if (f.kind === 'part') return describePartFix(f);\n if (f.kind === 'axis') return f.action === 'prune' ? 'drop variants' : f.action === 'ignore' ? `${f.arg} is not a Figma property` : `${f.arg} drawn as ${f.property ?? f.arg}`;\n if (f.kind === 'story') return `draw the variant from story ${f.use.story}`;\n return f.status ? `status ${f.status === 'differs' ? 'Differs' : \"Can't check\"}` : 'note';\n}\n\n/** A part fix that sizes, places or lays out a part: the values referee can't judge it, Check fidelity does. */\nexport function touchesLayout(f: FigmaFix): boolean {\n return f.kind === 'part' && (f.width !== undefined || f.height !== undefined || f.direction !== undefined || f.align !== undefined || f.overlay !== undefined);\n}\n\n/** The pull request body of a figma-fixes.json change: the gap, each fix with its reason, before and after. */\nexport function figmaFixesPrBody(input: { component: string; summary: string; gap: GapCase; tried: TryFixesResult; fixes: FigmaFix[]; tool: string }): string {\n const { tried } = input;\n const where = (f: FigmaFix) => {\n const w = f.where;\n if (!w) return '';\n const args = Object.entries(w.args ?? {}).map(([k, v]) => `${k}=${String(v)}`);\n if (w.state) args.push(`state ${w.state}`);\n return args.length ? ` (only ${args.join(', ')})` : '';\n };\n const lines = [\n `## ${input.component} in Figma, fixed with Claude`,\n '',\n input.summary.trim(),\n '',\n '### The gap',\n '',\n input.gap.summary,\n '',\n '### Fixes',\n '',\n ...input.fixes.map((f) => `- \\`${f.id}\\` (${f.kind}): ${fixWords(f)}${where(f)}. ${f.reason}`),\n '',\n '### Before and after (values referee)',\n '',\n tried.summary,\n '',\n ...tried.variants.flatMap((v) => [\n `- ${v.key}: ${v.verdict}`,\n ...v.differences.map((d) => ` - ${d.text}: ${d.result}${d.deltaBefore !== undefined ? ` (${d.deltaBefore} px, now ${d.deltaAfter ?? '?'} px${d.estimated ? ', estimated' : ''})` : ''}`),\n ...v.regressions.map((r) => ` - new difference: ${r.text}`),\n ]),\n '',\n ...(tried.verdict === 'same' && input.fixes.some(touchesLayout)\n ? [\"These fixes size, place or lay out parts. The values referee can't judge layout, so it says same: Check fidelity decides.\", '']\n : []),\n 'The values referee compares the rebuilt set with what the code renders. The story shot is the final referee: pull this branch in the DS Bridge Figma plugin and run Check fidelity before approving. A fix stays only when the variant moved closer to its shot.',\n '',\n `Drafted by Claude through ${input.tool}. figma-fixes.json only: no component, token or plugin change.`,\n ];\n return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------------------------\n// The loop runner's prompt and reply (for a team API key; Claude Code uses the MCP tools instead)\n\nexport interface FixAttempt {\n fixes: unknown[];\n /** Validation problems, or the try's detail. */\n feedback: string;\n verdict?: FixVerdict | undefined;\n}\n\n/** The prompt for one round: the gap case, the schema, and what the earlier rounds gave. Asks for fix objects only. */\nexport function fixPrompt(gap: GapCase, attempts: FixAttempt[] = []): string {\n const parts = [\n `You fix how Bridge draws the ${gap.component} component in Figma so it matches its Storybook story. Bridge measured the story in a browser and drew the Figma set from that measure; some variants differ. Write corrections for figma-fixes.json.`,\n '',\n FIX_SCHEMA_SUMMARY,\n '',\n 'The gap case (expected is the code, actual is Figma):',\n '',\n JSON.stringify({ component: gap.component, summary: gap.summary, detail: gap.detail, variants: gap.variants.map((v) => ({ key: v.key, story: v.story, differences: v.differences, unexplained: v.unexplained })), fixes: gap.fixes }, null, 1),\n ];\n for (const [i, a] of attempts.entries()) {\n parts.push('', `Round ${i + 1}: you proposed`, JSON.stringify(a.fixes), `Bridge said${a.verdict ? ` (${a.verdict})` : ''}:`, a.feedback);\n }\n parts.push(\n '',\n attempts.length\n ? 'Revise: keep what moved closer, change what did not. Use the same ids for fixes you revise.'\n : 'Propose the smallest set of fixes that explains the differences.',\n 'Answer with a JSON array of fix objects only, no prose, \"by\": \"claude\" on each. If no fix can move it closer, answer one fix of kind \"status\" with \"status\": \"differs\" (or \"cant-check\") and the reason in a sentence.',\n );\n return parts.join('\\n');\n}\n\n/** The fix objects in a reply: a JSON array (or { \"fixes\": [...] }), in a code fence or not. Throws a sentence otherwise. */\nexport function parseFixReply(text: string): unknown[] {\n const fence = /```(?:json)?\\s*([\\s\\S]*?)```/.exec(text);\n const body = (fence ? fence[1]! : text).trim();\n const start = body.search(/[[{]/);\n if (start < 0) throw new Error('The reply has no JSON: expected an array of fix objects.');\n const open = body[start]!;\n const end = body.lastIndexOf(open === '[' ? ']' : '}');\n let data: unknown;\n try {\n data = JSON.parse(body.slice(start, end + 1));\n } catch (e) {\n throw new Error(`The reply is not valid JSON: ${(e as Error).message}`);\n }\n if (Array.isArray(data)) return data;\n if (isObj(data) && Array.isArray(data.fixes)) return data.fixes;\n if (isObj(data) && typeof data.kind === 'string') return [data];\n throw new Error('The reply is JSON but not a list of fix objects.');\n}\n\n/** A status fix for a component that did not converge: what the loop proposes after its last round. */\nexport function statusFixFor(gap: GapCase, existingIds: string[] = []): FigmaFix {\n let id = `${lc(gap.component) || 'component'}-differs`;\n for (let i = 2; existingIds.includes(id); i++) id = `${lc(gap.component)}-differs-${i}`;\n const reason = `${gap.summary.replace(/\\u2014/g, ',').replace(/\\.$/, '')}. Claude found no fix that brings it closer in ${FIX_LOOP_MAX_ROUNDS} rounds.`;\n return { id, kind: 'status', component: gap.component, status: 'differs', reason, by: 'claude' };\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/**\n * Merges a branch at the head the person saw (GitHub refuses when it moved meanwhile). Studio's Merge button: squash.\n * `draft`: GitHub still calls it a draft though the gate reads it ready (core isDraft, `drafted-by-claude`), so it is\n * marked ready for review first: GitHub never merges a draft.\n */\nexport async function mergeOnGitHub(gh: GitHubClient, input: { number: number; headSha: string; method?: MergeMethod | undefined; draft?: boolean | undefined }): Promise<{ sha: string }> {\n if (input.draft) await gh.markReadyForReview(input.number);\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; draft?: boolean | undefined },\n): Promise<{ sha: string; commentUrl: string; comment: string }> {\n // A GitHub draft the gate reads ready (core isDraft): marked ready first, GitHub never merges a draft.\n if (input.draft) await gh.markReadyForReview(input.number);\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 change in their app before it is in the library, 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 change.';\n case 'failed':\n return 'The preview version could not be prepared for the latest update. Update the change to try again, or ask a developer to run it again on GitHub.';\n case 'no-packages':\n return 'This change 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 change was added to the library. Its preview version still installs, and products get it with the next library release.'\n : s.stillWorks === false\n ? 'This change was added to the library, so its preview version was removed. Products get it with the next library release.'\n : 'This change was added to the library. Products get it with the next library release.';\n case 'closed':\n return s.stillWorks === true\n ? 'This change was closed without adding it to the library. Its preview version still installs, but it will not reach the library.'\n : s.stillWorks === false\n ? 'This change was closed without adding it to the library, so its preview version was removed.'\n : 'This change was closed without adding it to the library.';\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 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 /** Pushed from the Figma plugin: the body says design-approved and what happens next (docs/BUILD-REQUESTS.md). */\n fromFigma?: boolean | 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.fromFigma ? { fromFigma: true } : {}) }), ...(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 * Open it as a draft or not. Default: a draft from tier 2, until design review. A token push from Figma with values\n * only opens ready (false): it ships after the automatic checks (docs/BUILD-REQUESTS.md).\n */\n draft?: boolean | 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 = opts.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 Bridge Figma plugin'}. A developer builds the code on this branch with Claude; 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/** The same GitHub failure (status, auth state, permission kept for the callers' advice), led by what it left undone. */\nfunction ledBy(e: unknown, lead: string): GitHubError {\n const why = e instanceof Error ? e.message : String(e);\n if (!(e instanceof GitHubError)) return new GitHubError(502, `${lead} ${why}`);\n return new GitHubError(e.status, `${lead} ${why}`, e.detail, { auth: e.auth, permission: e.permission, resetsAt: e.resetsAt });\n}\n\n/**\n * Claude wrote the code: the pull request is marked ready for review, then the branch is labelled drafted-by-claude\n * (no longer waiting) and its description says so. Refused while the branch only carries the spec, so the label never\n * claims code that is not there. Ready goes first: when GitHub refuses it, nothing else changed, so the label never\n * says \"drafted\" on a branch reviewers cannot see yet. Running it again after a partial failure finishes the job.\n */\nexport async function markFigmaChangeDraftedOnGitHub(gh: GitHubClient, n: number): Promise<{ status: FigmaPushStatus; files: string[]; ready: boolean }> {\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 if (pull.draft) {\n try {\n await gh.markReadyForReview(n);\n } catch (e) {\n throw ledBy(e, `#${n} is not marked drafted and its labels are unchanged:`);\n }\n }\n try {\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 } catch (e) {\n throw ledBy(e, `#${n} is ready for review, but the ${DRAFTED_BY_CLAUDE_LABEL} label did not go on (run it again to finish):`);\n }\n const labels = [...pull.labels.filter((l) => l !== WAITING_FOR_CLAUDE_LABEL), DRAFTED_BY_CLAUDE_LABEL];\n return { status: figmaPushStatus({ state: pull.state, draft: false, labels, route: origin.route }), files, ready: true };\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","// 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 // Storybook's own sanitize for the title: lower case, every run of other characters one dash. It does not split\n // camel case (\"Forms/ChoiceCard\" is forms-choicecard), unlike the export name (\"NarrowConflict\" is narrow-conflict).\n const base = title\n .toLowerCase()\n .replace(/[^\\p{L}\\p{N}]+/gu, '-')\n .replace(/^-+|-+$/g, '');\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, type DemoConfig } 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 /** The team's display name from bridge.config.json `name`, when set. */\n name?: string;\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 /** A public demo's persona (config \"demo\"), when set. */\n demo?: DemoConfig;\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 ...(config.demo ? { demo: { ...config.demo } } : {}),\n ...(config.name ? { name: config.name } : {}),\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 // Every body is known now: a source that batches reads asks for them in a few requests instead of one each.\n await source.prefetch?.(phases.flatMap(([, paths]) => paths)).catch(() => undefined);\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 * Reads many blob bodies in one request (the Bridge read path, /api/contribute?blobs=): the text of each sha it\n * could read, null for a blob that does not exist; a sha left out is read on its own. Used by `prefetch` in 'api'\n * mode only, `batchSize` shas per request (default 80), `batchConcurrency` requests at once (default 3).\n */\n batch?: (shas: string[]) => Promise<Record<string, string | null>>;\n batchSize?: number;\n batchConcurrency?: number;\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 /** Bodies a batch read brought (text, or null: the blob is not there), taken by readBody instead of a request. */\n const batched = new Map<string, Promise<string | null | undefined>>();\n const batchRun = limiter(Math.max(1, opts.batchConcurrency ?? 3));\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 fromBatch = batched.has(blobSha) ? await batched.get(blobSha)! : undefined;\n batched.delete(blobSha);\n const text = typeof fromBatch === 'string' ? fromBatch : 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 /** Starts batch reads of these blobs (api mode with a batch reader only); each sha gets its promise at once. */\n const prefetch = async (paths: string[]) => {\n const batch = opts.batch;\n if (!batch || mode !== 'api' || !paths.length) return;\n const files = await readTree();\n const want: string[] = [];\n for (const p of paths) {\n const e = files.get(normalizeRepoPath(p));\n if (!e || (e.size !== undefined && e.size > maxBytes) || bodies.has(e.sha) || batched.has(e.sha) || want.includes(e.sha)) continue;\n if ((await opts.blobCache?.get(e.sha)) !== undefined) continue;\n want.push(e.sha);\n }\n const size = Math.max(1, opts.batchSize ?? 80);\n for (let i = 0; i < want.length; i += size) {\n const chunk = want.slice(i, i + size);\n const read = batchRun(() => batch(chunk)).catch(() => ({}) as Record<string, string | null>);\n for (const s of chunk) batched.set(s, read.then((r) => (s in r ? r[s] : undefined)));\n }\n };\n\n return {\n ref: { owner: client.owner, repo: client.name, sha },\n mode,\n prefetch,\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","// Pure parsing and grouping of a design system's releases, for the Library Changelog and the team snapshot. No fs,\n// no git: the caller reads the files and passes the text in. Sources, all already in a repository:\n// - each package's CHANGELOG.md, written by the changesets release action (\"## 1.1.0\", \"### Minor Changes\",\n// \"- abc1234: text\"),\n// - .changeset/*.md, the entries waiting for the next release,\n// - release dates from the release tags (@bridge-ds/react@1.1.0) or from git, passed in by the caller.\n// Bridge's docs site re-exports it under its former names (apps/docs-site/src/lib/changelog-model.ts).\n\nexport type ChangelogBump = 'major' | 'minor' | 'patch';\n\nexport interface ChangelogEntry {\n source: 'changeset' | 'release';\n /** First sentence of the note, the row title. */\n title: string;\n /** Rest of the note's first paragraph, may be empty. */\n detail: string;\n kind: string; // human label: Breaking, New, Fix, Internal\n bump: ChangelogBump | null;\n packages: string[];\n forYou: string;\n /** The author wrote the \"For you:\" line (forYou is not the default for the bump). */\n forYouAuthored?: boolean;\n date?: string;\n /** Changeset id: the commit sha prefix in a CHANGELOG.md, or the .changeset file path for pending ones. */\n ref?: string;\n}\n\nexport interface ChangelogReleasePackage {\n name: string;\n version: string;\n /** Published to npm (not a private app). */\n published: boolean;\n}\n\nexport interface ChangelogRelease {\n /** \"v1.1.0\" (the Library version, from @bridge-ds/react) or \"core 0.3.1\" when react is not in the release. */\n name: string;\n date?: string;\n pending: boolean;\n packages: ChangelogReleasePackage[];\n entries: ChangelogEntry[];\n announcement: string;\n}\n\n/** One \"## x.y.z\" section of a package CHANGELOG.md. */\nexport interface ChangelogSection {\n pkg: string;\n version: string;\n published: boolean;\n notes: { id: string; bump: ChangelogBump; text: string }[];\n}\n\nconst FOR_YOU: Record<string, string> = {\n major: 'Action needed: something you use was renamed, removed or changed visibly. Check the notes before updating.',\n minor: 'New option available. Nothing breaks; use it when it helps.',\n patch: 'No action needed. A fix or a detail now matches the spec.',\n internal: 'Nothing changes in Figma or in the product. Internal tooling only.',\n};\n\nconst BUMP_RANK: Record<ChangelogBump, number> = { patch: 0, minor: 1, major: 2 };\nconst HEAD_BUMP: Record<string, ChangelogBump> = { 'Major Changes': 'major', 'Minor Changes': 'minor', 'Patch Changes': 'patch' };\n\nexport const shortPackage = (name: string) => name.replace(/^@bridge-ds\\//, '');\n\nconst kindOfBump = (b: ChangelogBump | null, packages: string[]) =>\n packages.length === 0 ? 'Internal' : b === 'major' ? 'Breaking' : b === 'minor' ? 'New' : 'Fix';\n\n/** Splits a paragraph into sentences: \". \", \"! \" or \"? \" before a capital, a quote or a backtick, never inside `code`. */\nexport function noteSentences(para: string): string[] {\n const out: string[] = [];\n let start = 0;\n let inCode = false;\n for (let i = 0; i < para.length - 2; i++) {\n const ch = para[i]!;\n if (ch === '`') inCode = !inCode;\n if (!inCode && /[.!?]/.test(ch) && para[i + 1] === ' ' && /[A-Z\"`(]/.test(para[i + 2]!)) {\n out.push(para.slice(start, i + 1).trim());\n start = i + 2;\n }\n }\n const rest = para.slice(start).trim();\n if (rest) out.push(rest);\n return out;\n}\n\n/** Longest second sentence shown under a title; a longer one stays in the full notes rather than being cut. */\nexport const CHANGELOG_DETAIL_MAX = 240;\n\n/**\n * A note as a row: its first sentence is the title (no trailing period), the second one the description when it is\n * short enough to read in a list, and the author's \"For you:\" line when there is one.\n */\nexport function splitNote(text: string): { title: string; detail: string; forYou?: string } {\n const forYou = text.match(/^\\s*For you:\\s*(.+)$/im)?.[1]?.trim();\n const para = text\n .replace(/^\\s*For you:.*$/gim, '')\n .trim()\n .split(/\\n\\s*\\n/)[0]!\n .replace(/\\s+/g, ' ')\n .trim();\n const [first = '', second = ''] = noteSentences(para);\n return { title: first.replace(/\\.$/, ''), detail: second.length <= CHANGELOG_DETAIL_MAX ? second : '', forYou };\n}\n\n/** Parses a package CHANGELOG.md into its version sections. \"Updated dependencies\" lines are not changes. */\nexport function parseChangelogSections(md: string, pkg: string, published: boolean): ChangelogSection[] {\n const sections: ChangelogSection[] = [];\n let current: ChangelogSection | null = null;\n let bump: ChangelogBump = 'patch';\n let note: { id: string; bump: ChangelogBump; lines: string[] } | null = null;\n const flush = () => {\n if (note && current) current.notes.push({ id: note.id, bump: note.bump, text: note.lines.join('\\n').trim() });\n note = null;\n };\n for (const line of md.split('\\n')) {\n const v = line.match(/^## (\\d+\\.\\d+\\.\\d+\\S*)\\s*$/);\n if (v) {\n flush();\n current = { pkg, version: v[1]!, published, notes: [] };\n sections.push(current);\n continue;\n }\n const h = line.match(/^### (.+?)\\s*$/);\n if (h) {\n flush();\n bump = HEAD_BUMP[h[1]!] ?? 'patch';\n continue;\n }\n const item = line.match(/^- ([0-9a-f]{7,40}): (.*)$/);\n if (item && current) {\n flush();\n note = { id: item[1]!.slice(0, 7), bump, lines: [item[2]!] };\n continue;\n }\n if (/^- /.test(line)) {\n flush(); // \"- Updated dependencies [...]\" and other lines without a changeset id\n continue;\n }\n if (note) (note as { lines: string[] }).lines.push(line.replace(/^ {2}/, ''));\n }\n flush();\n return sections;\n}\n\n/** One pending .changeset/*.md file, or null when it is not a changeset. */\nexport function parseChangeset(src: string, ref: string): ChangelogEntry | null {\n const m = src.match(/^---\\n([\\s\\S]*?)\\n?---\\n([\\s\\S]*)$/);\n if (!m) return null;\n const bumps = [...m[1]!.matchAll(/\"([^\"]+)\":\\s*(major|minor|patch)/g)].map((x) => ({ pkg: x[1]!, bump: x[2] as ChangelogBump }));\n const top = bumps.reduce<ChangelogBump | null>((b, x) => (b === null || BUMP_RANK[x.bump] > BUMP_RANK[b] ? x.bump : b), null);\n const { title, detail, forYou } = splitNote(m[2]!);\n if (!title) return null;\n const packages = bumps.map((x) => x.pkg);\n return {\n source: 'changeset',\n title,\n detail,\n kind: kindOfBump(top, packages),\n bump: top,\n packages,\n forYou: forYou ?? (packages.length ? FOR_YOU[top ?? 'patch']! : FOR_YOU.internal!),\n forYouAuthored: Boolean(forYou),\n ref,\n };\n}\n\nconst semverDesc = (a: string, b: string) => {\n const pa = a.split(/[.-]/).map((n) => Number.parseInt(n, 10) || 0);\n const pb = b.split(/[.-]/).map((n) => Number.parseInt(n, 10) || 0);\n for (let i = 0; i < 3; i++) if (pa[i] !== pb[i]) return pb[i]! - pa[i]!;\n return 0;\n};\n\n/**\n * Groups version sections into releases. Sections released together share a date, or, when no date is known\n * (shallow clone, no tags), share a changeset: the release action writes one changeset into every package it\n * bumps. Each changeset shows once per release, with every package it touched. Newest first.\n * `dateOf(pkg, version)` returns the release date (YYYY-MM-DD) or undefined; it never guesses.\n */\nexport function groupReleases(sections: ChangelogSection[], dateOf: (pkg: string, version: string) => string | undefined, libraryPackage = '@bridge-ds/react'): Omit<ChangelogRelease, 'announcement'>[] {\n const all = sections;\n const parent = all.map((_, i) => i);\n const find = (i: number): number => (parent[i] === i ? i : (parent[i] = find(parent[i]!)));\n const union = (a: number, b: number) => {\n parent[find(a)] = find(b);\n };\n const dates = all.map((s) => dateOf(s.pkg, s.version));\n const byKey = new Map<string, number>();\n all.forEach((s, i) => {\n const keys = [...(dates[i] ? [`d:${dates[i]}`] : []), ...s.notes.map((n) => `n:${n.id}`)];\n for (const k of keys) {\n const j = byKey.get(k);\n if (j === undefined) byKey.set(k, i);\n else union(i, j);\n }\n });\n const groups = new Map<number, number[]>();\n all.forEach((_, i) => groups.set(find(i), [...(groups.get(find(i)) ?? []), i]));\n\n const out: Omit<ChangelogRelease, 'announcement'>[] = [];\n for (const members of groups.values()) {\n const secs = members.map((i) => all[i]!);\n const known = members.map((i) => dates[i]).filter((d): d is string => Boolean(d)).sort();\n const date = known.length ? known[known.length - 1] : undefined;\n const entries = new Map<string, ChangelogEntry & { rank: number }>();\n for (const s of secs) {\n for (const n of s.notes) {\n // One commit can add several changesets: the id alone is not unique, the id and the text are.\n const key = `${n.id}:${n.text.slice(0, 80)}`;\n const prev = entries.get(key);\n if (prev) {\n if (!prev.packages.includes(s.pkg)) prev.packages.push(s.pkg);\n if (BUMP_RANK[n.bump] > prev.rank) {\n prev.rank = BUMP_RANK[n.bump];\n prev.bump = n.bump;\n }\n continue;\n }\n const { title, detail, forYou } = splitNote(n.text);\n entries.set(key, { source: 'release', title, detail, kind: '', bump: n.bump, packages: [s.pkg], forYou: forYou ?? '', forYouAuthored: Boolean(forYou), date, ref: n.id, rank: BUMP_RANK[n.bump] });\n }\n }\n const list = sortChangelogEntries(\n [...entries.values()].map(({ rank: _rank, ...e }) => ({\n ...e,\n kind: kindOfBump(e.bump, e.packages),\n forYou: e.forYou || FOR_YOU[e.bump ?? 'patch']!,\n })),\n );\n if (list.length === 0) continue; // only dependency bumps and no date to place them with\n const packages = secs\n .map((s) => ({ name: s.pkg, version: s.version, published: s.published }))\n .sort((a, b) => Number(b.published) - Number(a.published) || (a.name === libraryPackage ? -1 : b.name === libraryPackage ? 1 : a.name.localeCompare(b.name)));\n const lib = packages.find((p) => p.name === libraryPackage);\n const lead = lib ?? packages.find((p) => p.published) ?? packages[0]!;\n out.push({ name: lib ? `v${lib.version}` : `${shortPackage(lead.name)} ${lead.version}`, date, pending: false, packages, entries: list });\n }\n return out.sort((a, b) => {\n if (a.date && b.date && a.date !== b.date) return a.date < b.date ? 1 : -1;\n if (Boolean(a.date) !== Boolean(b.date)) return a.date ? -1 : 1;\n return semverDesc(a.packages[0]?.version ?? '0.0.0', b.packages[0]?.version ?? '0.0.0');\n });\n}\n\nconst KIND_ORDER = ['Breaking', 'New', 'Fix', 'Internal'];\n\n/** Breaking first, then New, Fix, Internal; the notes' own order inside a kind. */\nexport function sortChangelogEntries<T extends { kind: string }>(entries: T[]): T[] {\n const rank = (k: string) => (KIND_ORDER.indexOf(k) < 0 ? KIND_ORDER.length : KIND_ORDER.indexOf(k));\n return entries.map((e, i) => ({ e, i })).sort((a, b) => rank(a.e.kind) - rank(b.e.kind) || a.i - b.i).map((x) => x.e);\n}\n\nexport function releaseAnnouncement(r: Omit<ChangelogRelease, 'announcement'>): string {\n const visible = r.entries.filter((e) => e.kind !== 'Internal');\n const action = r.entries.some((e) => e.kind === 'Breaking');\n const lines = [\n r.pending\n ? `Design system update coming in the next release${action ? ' (action needed)' : ''}:`\n : `Design system ${r.name} is out${action ? ' (action needed)' : ''}:`,\n ...(visible.length ? visible : r.entries).slice(0, 8).map((e) => `- ${e.kind}: ${e.title.replace(/`/g, '')}`),\n '',\n action\n ? 'Some changes need action: check the changelog before you update your files.'\n : 'Nothing breaks. Figma variables and the docs update automatically after merge.',\n 'Full changelog: /changelog/',\n ];\n return lines.join('\\n');\n}\n\n/** Meta line of an entry: the bump in words, then the packages (short names). Over `max`, only a count. */\nexport function releasePackagesLabel(packages: string[], max = 3): { tags: string[]; count: string | null } {\n const tags = packages.map(shortPackage);\n if (tags.length <= max) return { tags, count: null };\n return { tags, count: `${tags.length} packages` };\n}\n\n/** A release as the snapshot carries it: the announcement is left out (releaseAnnouncement(r) rebuilds it). */\nexport type ChangelogReleaseRow = Omit<ChangelogRelease, 'announcement'>;\n\nexport interface CollectReleasesInput {\n /** Each package's CHANGELOG.md text, with its npm name and whether it is published (not private). */\n changelogs: { pkg: string; published: boolean; text: string }[];\n /** Pending .changeset/*.md files: `ref` is the file path. README.md is not a changeset and is skipped by the caller. */\n changesets?: { ref: string; text: string }[];\n /** Release date (YYYY-MM-DD) of a package version, or undefined; never guessed. */\n dateOf?: (pkg: string, version: string) => string | undefined;\n /** Package whose version names a release (\"v1.1.0\"). */\n libraryPackage?: string;\n}\n\n/**\n * Every release of a repository, newest first: the pending changesets as \"Coming in the next release\" when there are\n * any, then the published versions grouped by groupReleases. What the Changelog shows and the team snapshot carries.\n */\nexport function collectReleases(input: CollectReleasesInput): ChangelogReleaseRow[] {\n const sections = input.changelogs.flatMap((c) => parseChangelogSections(c.text, c.pkg, c.published));\n const released = groupReleases(sections, input.dateOf ?? (() => undefined), input.libraryPackage);\n const pending = (input.changesets ?? []).map((c) => parseChangeset(c.text, c.ref)).filter((e): e is ChangelogEntry => e !== null);\n const next: ChangelogReleaseRow[] = pending.length ? [{ name: 'Coming in the next release', pending: true, packages: [], entries: sortChangelogEntries(pending), date: undefined }] : [];\n return [...next, ...released];\n}\n","// The \"Motion and interaction\" section of a component page, generated like the props table: what makes the component\n// move (hover, press, check, open), what changes, the motion tokens with their values, the easing, and what reduced\n// motion does. Built on componentMotion (the same reading the Figma prototypes use), from the component specs\n// `bridge specs` writes. The team snapshot carries it per component (snapshot.ts). Pure: no fs, no DOM. The docs site\n// re-exports it (apps/docs-site/src/lib/motion-docs.ts), unit tested there in motion-docs.test.ts.\nimport { componentMotion, type ComponentSpec, type SpecCoverage, type SpecTransition } from './component-spec';\n\n/** A motion token as the page shows it: the token name (mono) and its value in words (\"75 ms\"). */\nexport interface MotionValue {\n token?: string | undefined;\n value: string;\n}\n\nexport interface MotionRow {\n /** The part that moves, when the component has several (\"Popup\", \"Checkbox item\"). */\n part?: string | undefined;\n /** What makes it move, designer words (\"Hover\", \"Open\", \"Check and uncheck\"). */\n when: string;\n /** What changes (\"Background and text color\"). */\n what: string;\n duration: MotionValue;\n easing: MotionValue | null;\n}\n\nexport interface MotionDocs {\n /** One sentence: what animates, or that nothing does. */\n summary: string;\n rows: MotionRow[];\n /** What reduced motion does, one sentence; null when nothing animates. */\n reduced: string | null;\n /** Whether to show a Part column (several parts move). */\n showPart: boolean;\n /** Motion tokens the component's CSS uses for motion the rows do not list (a tab indicator sliding). */\n unlisted: string[];\n}\n\nconst PROPERTY_WORDS: Record<string, string> = {\n 'background-color': 'background',\n 'border-color': 'border',\n color: 'text color',\n 'text-decoration-color': 'underline',\n 'box-shadow': 'shadow',\n opacity: 'fade',\n transform: 'movement',\n height: 'height',\n width: 'width',\n};\n\n/** CSS properties in designer words, joined: [\"background-color\", \"color\"] -> \"Background and text color\". */\nexport function propertyWords(props: string[]): string {\n const words = [...new Set(props.map((p) => PROPERTY_WORDS[p] ?? p.replace(/-/g, ' ')))];\n if (!words.length) return '';\n const list = words.length > 1 ? `${words.slice(0, -1).join(', ')} and ${words[words.length - 1]}` : words[0]!;\n return list.charAt(0).toUpperCase() + list.slice(1);\n}\n\nconst EASING_WORDS: Record<string, string> = {\n standard: 'settles in place',\n enter: 'starts fast, lands softly',\n exit: 'starts softly, leaves fast',\n linear: 'constant speed',\n};\n\n/** A duration in ms, with its token. */\nexport const durationValue = (t: Pick<SpecTransition, 'duration' | 'durationToken'>): MotionValue => ({ token: t.durationToken, value: `${Math.round(t.duration)} ms` });\n\n/** An easing in words, with its token: motion.easing.enter -> \"starts fast, lands softly\". */\nexport function easingValue(t: Pick<SpecTransition, 'easing' | 'easingToken'>): MotionValue {\n const role = t.easingToken?.split('.').pop();\n if (role && EASING_WORDS[role]) return { token: t.easingToken, value: EASING_WORDS[role]! };\n if (t.easing.type === 'LINEAR') return { token: t.easingToken, value: 'constant speed' };\n return { token: t.easingToken, value: `cubic-bezier(${(t.easing.bezier ?? []).join(', ')})` };\n}\n\n/** The part a set draws, in words: \"Combobox/Popup\" -> \"Popup\", \"MenuCheckboxItem\" -> \"Checkbox item\". */\nexport function partLabel(spec: Pick<ComponentSpec, 'name' | 'component' | 'view'>, component: string): string {\n if (spec.name === component) return spec.view === 'without-popup' ? 'Trigger' : component;\n const rest = spec.name.startsWith(`${component}/`) ? spec.name.slice(component.length + 1) : spec.name.startsWith(component) ? spec.name.slice(component.length) : spec.name;\n const words = rest.replace(/([a-z])([A-Z])/g, '$1 $2').toLowerCase();\n return words.charAt(0).toUpperCase() + words.slice(1);\n}\n\nconst sameSpeed = (a: SpecTransition, b: SpecTransition) =>\n a.duration === b.duration && a.durationToken === b.durationToken && a.easingToken === b.easingToken && JSON.stringify(a.easing) === JSON.stringify(b.easing);\n\n/** A moment a set moves: what makes it move (\"Hover\", \"Open\"), the transition, the properties it animates. */\nexport interface MotionMoment {\n when: string;\n t: SpecTransition;\n props: string[];\n}\n\n/**\n * The moments a set moves, from its interactions and its opening and closing: one per trigger and speed (Hover,\n * Press, Check, Uncheck, Open, Close). Instant changes are left out.\n */\nexport function motionMoments(spec: Pick<ComponentSpec, 'name' | 'variants' | 'interactions' | 'motion'>): MotionMoment[] {\n const m = componentMotion(spec);\n const groups: MotionMoment[] = [];\n const push = (when: string, t: SpecTransition) => {\n const g = groups.find((x) => x.when === when && sameSpeed(x.t, t));\n if (g) g.props.push(...t.properties);\n else groups.push({ when, t, props: [...t.properties] });\n };\n for (const x of m.triggers) {\n if (!x.transition) continue;\n if (x.trigger === 'ON_HOVER' || x.trigger === 'MOUSE_ENTER' || x.trigger === 'MOUSE_LEAVE') push('Hover', x.transition);\n else if (x.trigger === 'ON_PRESS') push('Press', x.transition);\n else if (x.axis === 'Checked') push(x.to === 'false' ? 'Uncheck' : 'Check', x.transition);\n else push(`${x.axis}: ${x.from} to ${x.to}`, x.transition);\n }\n if (m.opening?.enter) push('Open', m.opening.enter);\n if (m.opening?.exit) push('Close', m.opening.exit);\n return groups;\n}\n\n/** Rows of one set: interactions, opening and closing, loops. Same trigger and speed merge into one row. */\nfunction setRows(spec: ComponentSpec, part: string | undefined): MotionRow[] {\n const m = componentMotion(spec);\n const groups = motionMoments(spec);\n // Check and uncheck (open and close) at the same speed and on the same properties read as one row.\n for (const [a, b, both] of [['Check', 'Uncheck', 'Check and uncheck'], ['Open', 'Close', 'Open and close']] as const) {\n const x = groups.find((g) => g.when === a);\n const y = groups.find((g) => g.when === b);\n if (x && y && sameSpeed(x.t, y.t) && propertyWords(x.props) === propertyWords(y.props)) {\n x.when = both;\n groups.splice(groups.indexOf(y), 1);\n }\n }\n const rows: MotionRow[] = groups.map((g) => ({ ...(part ? { part } : {}), when: g.when, what: propertyWords(g.props), duration: durationValue(g.t), easing: easingValue(g.t) }));\n for (const n of m.cannotPlay) {\n const loop = /^Looping animation (\\S+), (\\d+) ms/.exec(n.what);\n if (!loop) continue;\n rows.push({ ...(part ? { part } : {}), when: 'While shown', what: `Loops (${loop[1]})`, duration: { token: n.durationToken, value: `${loop[2]} ms` }, easing: null });\n }\n return rows;\n}\n\nconst listWords = (xs: string[]) => (xs.length > 1 ? `${xs.slice(0, -1).join(', ')} and ${xs[xs.length - 1]}` : (xs[0] ?? ''));\n\n/**\n * The section for one component: its sets (specs whose `component`, or name, is the component), and its Figma coverage\n * entry for the components the generator does not read (drafted, layout helpers).\n */\nexport function motionDocs(component: string, specs: ComponentSpec[], coverage?: Pick<SpecCoverage, 'status' | 'reason'>, codeTokens: string[] = []): MotionDocs {\n const sets = specs.filter((s) => (s.component ?? s.name) === component && !s.drafted);\n const codeMotion = [...new Set(codeTokens.filter((t) => /^motion\\.duration\\./.test(t)))].sort();\n const reducedAll = 'With reduced motion turned on, its changes happen at once.';\n const notListed = (why: string): MotionDocs => ({\n summary: `${component} has motion in code that this page cannot list yet${why}: try it in the preview.`,\n rows: [],\n reduced: reducedAll,\n showPart: false,\n unlisted: codeMotion,\n });\n if (!sets.length) {\n if (codeMotion.length) return notListed(coverage?.status === 'drafted' && coverage.reason ? ` (it ${coverage.reason})` : '');\n const drafted = coverage?.status === 'drafted' || specs.some((s) => (s.component ?? s.name) === component && s.drafted);\n return {\n summary: drafted\n ? `Motion for ${component} is not listed yet: Bridge cannot read it from the code on its own${coverage?.reason ? ` (it ${coverage.reason})` : ''}.`\n : coverage?.status === 'layout'\n ? `${component} does not animate: it only lays out other components.`\n : coverage && coverage.status !== 'generated'\n ? `Motion for ${component} is not listed yet${coverage.reason ? `: ${coverage.reason}` : ''}.`\n : `${component} does not animate.`,\n rows: [],\n reduced: null,\n showPart: false,\n unlisted: [],\n };\n }\n const perSet = sets.map((s) => ({ s, rows: setRows(s, undefined) })).filter((x) => x.rows.length);\n const showPart = perSet.length > 1;\n const rows = perSet.flatMap(({ s, rows: r }) => (showPart ? r.map((row) => ({ ...row, part: partLabel(s, component) })) : r));\n if (!rows.length) return codeMotion.length ? notListed('') : { summary: `${component} does not animate: its states change at once.`, rows: [], reduced: null, showPart: false, unlisted: [] };\n const whens = [...new Set(rows.filter((r) => r.when !== 'While shown').flatMap((r) => r.when.toLowerCase().split(' and ')))];\n const loops = rows.filter((r) => r.when === 'While shown');\n const summary = whens.length ? `${component} animates on ${listWords(whens)}${loops.length ? ', and loops while it is shown' : ''}.` : `${component} loops while it is shown.`;\n // tokens.css under prefers-reduced-motion: every motion.duration.* is 0 ms, except the spin, which only slows down.\n const isSpin = (r: MotionRow) => !!r.duration.token?.endsWith('.spin');\n const effects = [\n ...(whens.length ? ['every change happens at once'] : []),\n ...(loops.some((r) => !isSpin(r)) ? ['the loop stops'] : []),\n ...(loops.some(isSpin) ? ['the spinner keeps turning, slower, so it never looks frozen'] : []),\n ];\n const reduced = `With reduced motion turned on, ${listWords(effects)}`;\n const listed = new Set(rows.map((r) => r.duration.token));\n return { summary, rows, reduced: `${reduced}.`, showPart, unlisted: codeMotion.filter((t) => !listed.has(t)) };\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 { ChangelogReleaseRow } from './changelog-model';\nimport type { ContrastPairResult } from './contrast-model';\nimport type { SpecCoverage } from './component-spec';\nimport { motionDocs, type MotionDocs } from './motion-docs';\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/** Releases a snapshot keeps, newest first (the pending one counts); older ones stay in the CHANGELOG.md files. */\nexport const SNAPSHOT_MAX_RELEASES = 60;\n\n/** A workspace package of the repository, for the Library's Install page. */\nexport interface SnapshotPackage {\n name: string;\n version: string;\n /** Not published to npm. */\n private: boolean;\n /** Repo-relative folder (\".\" for the root package). */\n dir: string;\n}\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 * Releases from the packages' CHANGELOG.md files and the pending changesets, newest first, at most\n * SNAPSHOT_MAX_RELEASES. Dates come from release tags or git history, absent when the clone has neither. Absent from\n * a snapshot written before Bridge read releases, or when the repository has no changelog.\n */\n releases?: ChangelogReleaseRow[];\n /** Workspace packages (name, version, private, folder). Absent from a snapshot written before Bridge read them. */\n packages?: SnapshotPackage[];\n /**\n * Motion and interaction docs per component (motionDocs), keyed by component name, computed from the specs file the\n * snapshot does not carry. Absent without a readable specs file or a component scan.\n */\n motion?: Record<string, MotionDocs>;\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 if (data.releases !== undefined && (!Array.isArray(data.releases) || !data.releases.every((r) => isObj(r) && isStr(r.name) && Array.isArray(r.entries)))) throw new SnapshotError(`${SNAPSHOT_FILE}: releases must be a list of { name, entries }`);\n if (data.packages !== undefined && (!Array.isArray(data.packages) || !data.packages.every((p) => isObj(p) && isStr(p.name) && isStr(p.version) && isStr(p.dir)))) throw new SnapshotError(`${SNAPSHOT_FILE}: packages must be a list of { name, version, dir }`);\n if (data.motion !== undefined && (!isObj(data.motion) || !Object.values(data.motion).every((m) => isObj(m) && Array.isArray(m.rows)))) throw new SnapshotError(`${SNAPSHOT_FILE}: motion must map components to { summary, rows }`);\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 /** collectReleases() of the repository; kept to the newest SNAPSHOT_MAX_RELEASES. */\n releases?: ChangelogReleaseRow[];\n packages?: SnapshotPackage[];\n}\n\n/**\n * Motion docs of every scanned component, from the parsed specs file: what the Library's motion section shows. Null\n * without a specs file or a component scan.\n */\nexport function snapshotMotion(model: Pick<RepoModel, 'components' | 'specs'>): Record<string, MotionDocs> | null {\n const file = model.specs.file;\n if (!file || !model.components) return null;\n const out: Record<string, MotionDocs> = {};\n for (const c of model.components.list) {\n try {\n out[c.name] = motionDocs(c.name, file.components, model.specs.coverage.find((x) => x.name === c.name), c.tokenPaths);\n } catch {\n // A spec of an unexpected shape (hand-edited, older generator): no motion section rather than no snapshot.\n }\n }\n return out;\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 const motion = snapshotMotion(model);\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 ...(input.releases ? { releases: input.releases.slice(0, SNAPSHOT_MAX_RELEASES) } : {}),\n ...(input.packages ? { packages: [...input.packages].sort((a, b) => (a.dir < b.dir ? -1 : a.dir > b.dir ? 1 : 0)) } : {}),\n ...(motion ? { motion } : {}),\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","// Repo activity: the team's work in progress, written by `bridge snapshot --activity` in the team's CI (with the\n// workflow's GITHUB_TOKEN) and published next to snapshot.json on the bridge-data branch as activity.json. A\n// signed-out visitor of a hosted Studio gets GitHub's 60 API requests an hour, about three page views; with\n// activity.json Home, Branches, Review, History, suggestions and requests read nothing from the API at all.\n//\n// Two parts:\n// - `responses`: the GitHub REST reads (GET) those pages make, as GitHub answered them, trimmed of what no page reads\n// (API links, nested repository objects, diffs). The Studio answers its own GETs from them (activityAnswer), so every\n// view, rule and gate keeps one code path whatever the source, the way snapshotSource() serves the repo model.\n// - Summaries for readers that do not run the Studio (agents, the Library, a status line): open branches, open\n// suggestions with their parsed payload, request issues, recent merges, and the token history report.\n//\n// Pure: no Node, no DOM. The CLI hands it a fetch carrying the token.\n\nimport { GitHubClient, type FetchLike } from './github-client';\nimport type { BridgeConfig } from './config';\nimport { packageDirCandidates, type HistoryReport } from './history';\nimport { gitHubHistoryBackend, loadGitHubHistory } from './history-github';\nimport { parseRequestIssue, requestStatus, REQUEST_LABEL, type RequestKind, type RequestStatus } from './requests';\nimport { effectiveTier } from './review-gate';\nimport type { RiskTier } from './risk';\nimport { getSuggestionOnGitHub, listSuggestionsOnGitHub } from './suggestions-github';\nimport type { SuggestionKind, SuggestionPayloadV1, SuggestionStatus } from './suggestions';\nimport { SNAPSHOT_BRANCH } from './snapshot';\n\nexport const ACTIVITY_SCHEMA_VERSION = 1;\n/** Next to snapshot.json on the bridge-data branch. */\nexport const ACTIVITY_FILE = 'activity.json';\n/** Above this, the recorded reads are dropped heaviest first (trees, then older branches) until it fits. */\nexport const ACTIVITY_MAX_BYTES = 3_000_000;\n/** A guest reads activity.json while it is younger than this; older, the Studio reads GitHub live. */\nexport const ACTIVITY_MAX_AGE_MS = 24 * 60 * 60 * 1000;\n\n/** How much one activity.json carries. Each is a count of items, newest first. */\nexport const ACTIVITY_LIMITS = {\n /** Open pull requests recorded in full (the page of each; the list carries every open one). */\n branches: 30,\n /** Open suggestions read with their comments (parsed payload, counted approvals). */\n suggestions: 30,\n /** Request issues listed (open and closed); open ones are read with their comments. */\n requests: 30,\n /** Merged pull requests summarized. */\n merged: 20,\n /** Token history entries (core loadGitHubHistory limit). */\n history: 20,\n /** History entries whose two commits' file lists are recorded, so their before/after opens without the API. */\n historyTrees: 10,\n} as const;\nexport type ActivityLimits = { [K in keyof typeof ACTIVITY_LIMITS]: number };\n\n/** One GitHub answer: its status (200, or 404 for a read that finds nothing) and its JSON body, trimmed. */\nexport interface ActivityResponse {\n status: number;\n body: unknown;\n}\n\nexport interface ActivityBranch {\n number: number;\n title: string;\n author: string;\n url: string;\n branch: string;\n base: string;\n headSha: string;\n baseSha: string;\n state: 'open' | 'draft';\n labels: string[];\n /** Risk tier from the labels, the body or the files (review-gate effectiveTier); null when none says. */\n tier: RiskTier | null;\n createdAt: string;\n updatedAt: string;\n /** Conversation plus line comments. Null when the branch was not read in full (over the limit). */\n comments: number | null;\n /** Files the branch changes, and the token files among them (the token diff opens from them). Null: not read. */\n files: { changed: number; tokens: string[] } | null;\n /** Previews built for the head commit (commit statuses with a link, success only). */\n previews: { context: string; url: string }[];\n /** Combined check state of the head commit. */\n checks: 'success' | 'failure' | 'pending' | 'none' | null;\n}\n\nexport interface ActivitySuggestion {\n number: number;\n title: string;\n author: string;\n url: string;\n createdAt: string;\n kind: SuggestionKind | null;\n status: SuggestionStatus;\n labels: string[];\n comments: number | null;\n /** The parsed suggestion (null when its block does not parse). */\n payload: SuggestionPayloadV1 | null;\n approvers: string[];\n}\n\nexport interface ActivityRequest {\n number: number;\n title: string;\n author: string;\n url: string;\n state: 'open' | 'closed';\n status: RequestStatus;\n kind: RequestKind | null;\n component: string | null;\n labels: string[];\n createdAt: string;\n}\n\nexport interface ActivityMerged {\n number: number;\n title: string;\n author: string;\n url: string;\n mergedAt: string;\n labels: string[];\n tier: RiskTier | null;\n}\n\nexport interface RepoActivity {\n kind: 'bridge-activity';\n schemaVersion: typeof ACTIVITY_SCHEMA_VERSION;\n tool: { name: 'bridge'; version: string };\n generatedAt: string;\n repo: { owner: string; name: string; branch: string };\n /** Default branch head when it was written. */\n headSha: string;\n branches: ActivityBranch[];\n suggestions: ActivitySuggestion[];\n requests: ActivityRequest[];\n merged: ActivityMerged[];\n /** Token history of the default branch (core HistoryReport), null when it could not be read. */\n history: HistoryReport | null;\n /** GitHub REST answers by activityKey (path relative to api.github.com, query sorted). */\n responses: Record<string, ActivityResponse>;\n /** What was left out to stay within the limits, in words. */\n truncated: string[];\n /** What could not be read. */\n problems: string[];\n}\n\nexport class ActivityError extends Error {}\n\nconst isObj = (x: unknown): x is Record<string, unknown> => !!x && typeof x === 'object' && !Array.isArray(x);\nconst API = 'https://api.github.com';\n\n/**\n * The key of a GitHub REST read: the path relative to api.github.com with the query parameters sorted, and the\n * owner and repository (or user) lowercased, since GitHub reads them without case. Null for any other host.\n */\nexport function activityKey(url: string): string | null {\n let u: URL;\n try {\n u = new URL(url, API);\n } catch {\n return null;\n }\n if (u.origin !== API) return null;\n const parts = u.pathname.split('/');\n if (parts[1] === 'repos' && parts.length > 3) {\n parts[2] = parts[2]!.toLowerCase();\n parts[3] = parts[3]!.toLowerCase();\n } else if (parts[1] === 'users' && parts.length > 2) parts[2] = parts[2]!.toLowerCase();\n const q = [...u.searchParams].sort(([a, av], [b, bv]) => (a === b ? (av < bv ? -1 : 1) : a < b ? -1 : 1));\n const search = q.length ? `?${new URLSearchParams(q).toString()}` : '';\n return parts.join('/') + search;\n}\n\n// --- trimming -----------------------------------------------------------------------------------------------------\n\n/** URL fields a page reads; every other `*_url` and `url` is an API link nothing follows. */\nconst KEPT_URLS = new Set(['html_url', 'avatar_url', 'target_url', 'details_url', 'environment_url', 'raw_url']);\n/** Fields no page reads that weigh the most. */\nconst DROPPED = new Set(['_links', 'patch', 'body_html', 'body_text', 'reactions', 'performed_via_github_app', 'node_id', 'gravatar_id', 'user_view_type', 'site_admin', 'event', 'sub_issues_summary', 'issue_dependencies_summary', 'pull_request_review_id']);\nconst LONG_TEXT = 60_000;\n\nconst trimUser = (u: Record<string, unknown>) => ({\n login: u.login,\n ...(u.id !== undefined ? { id: u.id } : {}),\n ...(u.avatar_url ? { avatar_url: u.avatar_url } : {}),\n ...(u.html_url ? { html_url: u.html_url } : {}),\n ...(u.type ? { type: u.type } : {}),\n});\n\nconst trimRepo = (r: Record<string, unknown>) => ({\n ...(r.id !== undefined ? { id: r.id } : {}),\n name: r.name,\n full_name: r.full_name,\n ...(r.private !== undefined ? { private: r.private } : {}),\n ...(r.fork !== undefined ? { fork: r.fork } : {}),\n ...(r.default_branch ? { default_branch: r.default_branch } : {}),\n ...(isObj(r.owner) ? { owner: trimUser(r.owner) } : {}),\n ...(r.html_url ? { html_url: r.html_url } : {}),\n});\n\n/**\n * A GitHub answer without what no page reads: API links, node ids, diffs, reactions, the repository objects nested in\n * a pull request's head and base (name, owner and fork kept), and user objects beyond login, avatar and type. A tree\n * keeps path, type and sha per entry. Strings longer than 60 000 characters are cut.\n */\nexport function trimGitHub(value: unknown, key = ''): unknown {\n if (typeof value === 'string') return value.length > LONG_TEXT ? value.slice(0, LONG_TEXT) : value;\n if (Array.isArray(value)) return value.map((v) => trimGitHub(v, key));\n if (!isObj(value)) return value;\n if (key === 'tree' && typeof value.path === 'string' && typeof value.type === 'string') return { path: value.path, type: value.type, sha: value.sha, ...(value.mode ? { mode: value.mode } : {}) };\n if ((key === 'repo' || key === 'repository' || key === 'head_repository') && typeof value.full_name === 'string') return trimRepo(value);\n if (typeof value.login === 'string' && ('avatar_url' in value || 'type' in value)) return trimUser(value);\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) {\n if (DROPPED.has(k)) continue;\n if ((k === 'url' || k.endsWith('_url')) && !KEPT_URLS.has(k)) continue;\n if (k === 'output' && isObj(v)) {\n out[k] = { title: v.title ?? null, summary: typeof v.summary === 'string' ? v.summary.slice(0, 2000) : null, annotations_count: v.annotations_count ?? 0 };\n continue;\n }\n if (k === 'app' && isObj(v)) {\n out[k] = { id: v.id, slug: v.slug, name: v.name };\n continue;\n }\n out[k] = trimGitHub(v, k);\n }\n return out;\n}\n\n// --- recording ----------------------------------------------------------------------------------------------------\n\nconst JSON_ACCEPT = /application\\/(vnd\\.github\\+)?json/;\n/** What a recordingFetch shaper returns for a read it should not keep. */\nexport const SKIP: unique symbol = Symbol('skip');\n\n/**\n * The paths of a tree the Studio reads from a recorded tree: token files and the contrast checks (the branch token\n * diff), bridge.config.json, changesets, and the CHANGELOG.md and package.json the history reads. Every other entry is\n * left out of activity.json, which keeps a tree at a few kilobytes instead of a whole repository listing.\n */\nexport function activityTreeFilter(config: BridgeConfig): (path: string) => boolean {\n const under = (dir: string | undefined) => {\n const d = (dir ?? '').replace(/^\\.\\/|\\/$/g, '');\n return d && d !== '.' ? `${d}/` : '';\n };\n const tokens = under(config.tokens.root);\n const changesets = config.changesets ? under(config.changesets.dir) : null;\n const pkg = new Set(packageDirCandidates(config).flatMap((d) => [d ? `${d}/CHANGELOG.md` : 'CHANGELOG.md', d ? `${d}/package.json` : 'package.json']));\n return (p) => p === 'bridge.config.json' || pkg.has(p) || (tokens ? p.startsWith(tokens) : p.endsWith('.json')) || (changesets !== null && changesets !== '' && p.startsWith(changesets));\n}\n\n/** History internals the Studio never reads from a recorded answer (it reads the history report instead). */\nconst UNREAD = [/\\/git\\/blobs\\//, /\\/commits\\/[^/]+\\/pulls$/, /\\/commits\\?/, /\\/tags\\?/, /\\/contents\\//];\n\n/** The shaper collectActivity records with: trees filtered (activityTreeFilter), compares to what a branch page reads. */\nexport function activityShaper(config: BridgeConfig): (key: string, body: unknown) => unknown | typeof SKIP {\n const keep = activityTreeFilter(config);\n return (key, body) => {\n if (UNREAD.some((r) => r.test(key))) return SKIP;\n if (key.includes('/git/trees/') && isObj(body) && Array.isArray(body.tree)) return { sha: body.sha, tree: (body.tree as { path: string }[]).filter((e) => keep(e.path)), truncated: Boolean(body.truncated) };\n if (key.includes('/compare/') && isObj(body)) {\n const c = body as Record<string, any>;\n return {\n status: c.status,\n ahead_by: c.ahead_by,\n behind_by: c.behind_by,\n total_commits: c.total_commits,\n merge_base_commit: c.merge_base_commit ? { sha: c.merge_base_commit.sha } : null,\n base_commit: c.base_commit ? { sha: c.base_commit.sha, commit: { tree: { sha: c.base_commit.commit?.tree?.sha } } } : null,\n files: Array.isArray(c.files) ? c.files.map((f: Record<string, unknown>) => ({ filename: f.filename, status: f.status, ...(f.previous_filename ? { previous_filename: f.previous_filename } : {}), sha: f.sha, additions: f.additions, deletions: f.deletions, changes: f.changes })) : [],\n };\n }\n return body;\n };\n}\n\n/** Changes listed per history entry; an import of hundreds of tokens keeps its counts and its first changes. */\nexport const HISTORY_MAX_CHANGES = 100;\n\n/** A history report with each entry's change and reason lists capped (counts stay whole). */\nexport function capHistory(report: HistoryReport, max = HISTORY_MAX_CHANGES): HistoryReport {\n return {\n ...report,\n entries: report.entries.map((e) => (e.changes.length > max || (e.reasons?.length ?? 0) > max ? { ...e, changes: e.changes.slice(0, max), ...(e.reasons ? { reasons: e.reasons.slice(0, max) } : {}) } : e)),\n };\n}\n\n/**\n * Wraps a fetch and records every GitHub REST GET that answers 200 or 404 with JSON, trimmed, under its activityKey.\n * Reads with another media type (raw file bodies) pass through unrecorded.\n */\nexport function recordingFetch(fetchImpl: FetchLike, into: Map<string, ActivityResponse>, shape: (key: string, body: unknown) => unknown | typeof SKIP = (_k, b) => b): FetchLike {\n return async (url, init) => {\n const res = await fetchImpl(url, init);\n const method = (init?.method ?? 'GET').toUpperCase();\n const accept = init?.headers?.Accept ?? init?.headers?.accept ?? 'application/vnd.github+json';\n const key = activityKey(url);\n if (method !== 'GET' || !key || !JSON_ACCEPT.test(accept) || (res.status !== 200 && res.status !== 404)) return res;\n const text = await res.text();\n let body: unknown;\n try {\n body = JSON.parse(text);\n } catch {\n return { ok: res.ok, status: res.status, headers: res.headers, json: async () => JSON.parse(text), text: async () => text };\n }\n const shaped = shape(key, trimGitHub(body));\n if (shaped !== SKIP) into.set(key, { status: res.status, body: shaped });\n return { ok: res.ok, status: res.status, ...(res.headers ? { headers: res.headers } : {}), json: async () => JSON.parse(text) as unknown, text: async () => text };\n };\n}\n\n// --- collecting ---------------------------------------------------------------------------------------------------\n\nexport interface CollectActivityInput {\n /** fetch for api.github.com (the token goes in `token`). */\n fetch: FetchLike;\n token: string;\n owner: string;\n repo: string;\n /** The repository's Bridge config (tokens root, governance, changesets): history and suggestion approvals read it. */\n config: BridgeConfig;\n version: string;\n generatedAt?: string;\n /**\n * The activity published last time. Its history (and the file lists recorded for it) is kept when the default\n * branch head has not moved, which saves most of the reads of a run on a schedule or a pull request event.\n */\n previous?: RepoActivity | null;\n limits?: Partial<ActivityLimits>;\n}\n\ninterface RawPull {\n number: number;\n title: string;\n html_url: string;\n draft?: boolean;\n state: string;\n body?: string | null;\n user?: { login?: string } | null;\n labels?: ({ name?: string } | string)[];\n head: { ref: string; sha: string };\n base: { ref: string; sha: string };\n created_at: string;\n updated_at: string;\n merged_at?: string | null;\n comments?: number;\n review_comments?: number;\n}\n\nconst labelObjs = (labels: RawPull['labels']) => labelNames(labels).map((name) => ({ name }));\nfunction labelNames(labels: RawPull['labels']): string[] {\n return (labels ?? []).map((l) => (typeof l === 'string' ? l : (l.name ?? ''))).filter(Boolean);\n}\nconst byUpdated = <T extends { updated_at: string }>(a: T, b: T) => (a.updated_at < b.updated_at ? 1 : a.updated_at > b.updated_at ? -1 : 0);\n\n/**\n * Reads the team's activity from GitHub: the same reads, with the same paths, as the hosted Studio's guest pages\n * (Home, Branches and each open branch, Review, History, suggestions, requests), recorded, plus the summaries. A read\n * that fails is noted in `problems` and the rest goes on; an exhausted hourly limit stops the reading there.\n */\nexport async function collectActivity(input: CollectActivityInput): Promise<RepoActivity> {\n const limits: ActivityLimits = { ...ACTIVITY_LIMITS, ...input.limits };\n const responses = new Map<string, ActivityResponse>();\n const rec = recordingFetch(input.fetch, responses, activityShaper(input.config));\n const client = new GitHubClient(`${input.owner}/${input.repo}`, input.token, rec, { attempts: 2, baseDelayMs: 500, sleep: (ms) => new Promise((r) => setTimeout(r, ms)) }, { etags: false });\n const R = `/repos/${input.owner}/${input.repo}`;\n const problems: string[] = [];\n const truncated: string[] = [];\n let limited = false;\n const headers: Record<string, string> = { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28', ...(input.token ? { Authorization: `Bearer ${input.token}` } : {}) };\n\n /** One GET of a path as the Studio writes it; undefined when it failed (noted). */\n const get = async <T>(path: string): Promise<T | undefined> => {\n if (limited) return undefined;\n try {\n const res = await rec(`${API}${path}`, { headers });\n if (res.status === 404) return undefined;\n if (!res.ok) {\n if ((res.status === 403 || res.status === 429) && res.headers?.get('x-ratelimit-remaining') === '0') {\n limited = true;\n problems.push('GitHub hourly limit reached while reading activity: the rest was left out.');\n } else problems.push(`GitHub answered ${res.status} for ${path}`);\n return undefined;\n }\n return (await res.json()) as T;\n } catch (err) {\n problems.push(`Could not read ${path}: ${(err as Error).message}`);\n return undefined;\n }\n };\n /** A core read; its failure is noted and gives `fallback`. */\n const safely = async <T>(what: string, fn: () => Promise<T>, fallback: T): Promise<T> => {\n if (limited) return fallback;\n try {\n return await fn();\n } catch (err) {\n const msg = (err as Error).message;\n if (/limit/i.test(msg) && (err as { status?: number }).status === 429) limited = true;\n problems.push(`${what}: ${msg}`);\n return fallback;\n }\n };\n\n // The repository and its default branch head (every team page reads both first).\n const info = await safely('Repository', () => client.getRepo(), null);\n const branch = info?.defaultBranch ?? input.config.repo?.defaultBranch ?? 'main';\n const headSha = (await safely('Default branch', () => client.getBranchSha(branch), undefined)) ?? '';\n\n // Branches: the open list, the closed lists the Branches and Requests views read, then each open branch's page.\n const open = (await get<RawPull[]>(`${R}/pulls?state=open&per_page=100`)) ?? [];\n const closed = (await get<RawPull[]>(`${R}/pulls?state=closed&sort=updated&direction=desc&per_page=30`)) ?? [];\n await get(`${R}/pulls?state=closed&per_page=50&sort=updated&direction=desc`);\n await get(`${R}/rules/branches/${encodeURIComponent(branch)}`);\n await get(`${R}/git/matching-refs/heads/bridge-visual`);\n await safely('Owner account', () => client.getAccountType(input.owner), null);\n\n // What the last activity recorded, reused where nothing changed (keeps a scheduled run to a few requests).\n const prev = input.previous ?? null;\n const sameRepoPrev = Boolean(prev && sameRepo(prev, input));\n const prevOk = sameRepoPrev && Boolean(headSha) && prev!.headSha === headSha;\n /** A read the last activity recorded, when `reuse`; else read now. */\n const kept = async <T>(path: string, reuse: boolean): Promise<T | undefined> => {\n const key = reuse ? activityKey(`${API}${path}`) : null;\n const hit = key ? prev!.responses[key] : undefined;\n if (key && hit) {\n responses.set(key, hit);\n return hit.status === 200 ? (hit.body as T) : undefined;\n }\n return get<T>(path);\n };\n\n const branches: ActivityBranch[] = [];\n const sorted = [...open].sort(byUpdated);\n if (sorted.length > limits.branches) truncated.push(`${sorted.length - limits.branches} open branches beyond the ${limits.branches} most recently updated are listed without their pages.`);\n for (const [i, p] of sorted.entries()) {\n const full = i < limits.branches;\n const base: ActivityBranch = {\n number: p.number,\n title: p.title,\n author: p.user?.login ?? '',\n url: p.html_url,\n branch: p.head.ref,\n base: p.base.ref,\n headSha: p.head.sha,\n baseSha: p.base.sha,\n state: p.draft ? 'draft' : 'open',\n labels: labelNames(p.labels),\n tier: effectiveTier(labelObjs(p.labels), p.body ?? null, null),\n createdAt: p.created_at,\n updatedAt: p.updated_at,\n comments: null,\n files: null,\n previews: [],\n checks: null,\n };\n if (!full || limited) {\n branches.push(base);\n continue;\n }\n const n = p.number;\n // A branch nobody touched since the last activity (same update time, same head, same default branch head) keeps\n // its recorded page; its checks and statuses are read again (they change without touching the pull request).\n // Trees are named by commit and never change.\n const was = prevOk ? prev!.branches.find((b) => b.number === n) : undefined;\n const same = Boolean(was && was.updatedAt === p.updated_at && was.headSha === p.head.sha && was.comments !== null);\n const [pull, files, , , , , status] = await Promise.all([\n kept<RawPull>(`${R}/pulls/${n}`, same),\n kept<{ filename: string; status?: string }[]>(`${R}/pulls/${n}/files?per_page=100`, same),\n kept(`${R}/pulls/${n}/reviews?per_page=100`, same),\n kept(`${R}/issues/${n}/comments?per_page=100`, same),\n kept(`${R}/pulls/${n}/comments?per_page=100`, same),\n get(`${R}/commits/${p.head.sha}/check-runs?per_page=100`),\n get<{ state?: string; statuses?: { context: string; state: string; target_url?: string | null }[] }>(`${R}/commits/${p.head.sha}/status`),\n kept(`${R}/compare/${encodeURIComponent(p.base.ref)}...${p.head.sha}`, same),\n kept(`${R}/git/trees/${p.base.sha}?recursive=1`, sameRepoPrev),\n kept(`${R}/git/trees/${p.head.sha}?recursive=1`, sameRepoPrev),\n kept(`${R}/issues/${n}/labels`, same),\n ]);\n const root = input.config.tokens.root.replace(/\\/$/, '');\n branches.push({\n ...base,\n tier: effectiveTier(labelObjs((pull ?? p).labels), (pull ?? p).body ?? null, files ?? null),\n comments: pull ? (pull.comments ?? 0) + (pull.review_comments ?? 0) : null,\n files: files ? { changed: files.length, tokens: files.map((f) => f.filename).filter((f) => f.startsWith(`${root}/`) && f.endsWith('.json')) } : null,\n previews: (status?.statuses ?? []).filter((s) => s.state === 'success' && s.target_url && /^https:\\/\\//.test(s.target_url)).map((s) => ({ context: s.context, url: s.target_url! })),\n checks: status ? (status.state === 'success' || status.state === 'failure' || status.state === 'pending' ? status.state : 'none') : null,\n });\n }\n\n // Suggestions: the open list as Branches reads it, then each one as its page reads it (payload, approvals).\n const gov = { owners: input.config.governance.owners, rights: input.config.governance.rights, soloOwnerCanApproveBoth: input.config.governance.soloOwnerCanApproveBoth };\n const items = await safely('Suggestions', () => listSuggestionsOnGitHub(client, { state: 'open' }), []);\n const pullsAll = items.length ? await safely('Pull requests', () => client.listPullRequests('all'), []) : [];\n if (items.length > limits.suggestions) truncated.push(`${items.length - limits.suggestions} open suggestions beyond the ${limits.suggestions} newest are listed without their pages.`);\n const suggestions: ActivitySuggestion[] = [];\n for (const [i, s] of items.entries()) {\n const d = i < limits.suggestions ? await safely(`Suggestion #${s.number}`, () => getSuggestionOnGitHub(client, s.number, gov, { pulls: pullsAll }), null) : null;\n suggestions.push({\n number: s.number,\n title: s.title,\n author: s.author,\n url: s.url,\n createdAt: s.createdAt,\n kind: s.kind ?? null,\n status: d?.status ?? s.status,\n labels: s.labels,\n comments: d ? d.comments.length : null,\n payload: d?.parsed.ok ? d.parsed.payload : null,\n approvers: d?.approvals?.approvers ?? [],\n });\n }\n\n // Requests: the list the Requests view reads, and each open one as its page reads it.\n const issues = await safely('Requests', () => client.listIssues({ label: REQUEST_LABEL, state: 'all', perPage: 50 }), []);\n const requests: ActivityRequest[] = [];\n const openIssues = issues.filter((i) => i.state === 'open');\n if (openIssues.length > limits.requests) truncated.push(`${openIssues.length - limits.requests} open requests beyond the ${limits.requests} newest are listed without their pages.`);\n for (const [i, r] of issues.slice(0, Math.max(limits.requests, 0)).entries()) {\n if (r.state === 'open' && i < limits.requests) {\n await get(`${R}/issues/${r.number}`);\n await get(`${R}/issues/${r.number}/comments?per_page=100`);\n }\n const parsed = parseRequestIssue(r.body);\n const linked = [...open, ...closed].filter((p) => new RegExp(`(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\\\\s+#${r.number}\\\\b`, 'i').test(p.body ?? ''));\n requests.push({\n number: r.number,\n title: r.title,\n author: r.author,\n url: r.url,\n state: r.state,\n status: requestStatus({ state: r.state, stateReason: r.stateReason, linkedPrs: linked.map((p) => ({ state: p.state === 'open' ? 'open' : 'closed', merged: Boolean(p.merged_at) })) }),\n kind: parsed?.kind ?? null,\n component: parsed?.component ?? null,\n labels: r.labels,\n createdAt: r.createdAt,\n });\n }\n\n const merged: ActivityMerged[] = closed\n .filter((p) => p.merged_at)\n .slice(0, limits.merged)\n .map((p) => ({ number: p.number, title: p.title, author: p.user?.login ?? '', url: p.html_url, mergedAt: p.merged_at!, labels: labelNames(p.labels), tier: effectiveTier(labelObjs(p.labels), p.body ?? null, null) }));\n\n // Token history: kept from the last activity while the head has not moved (it is the costly part), else read again,\n // with the file lists of the newest entries' commits so their before/after opens without the API.\n let history: HistoryReport | null = null;\n if (prevOk && prev!.history) {\n history = prev!.history;\n for (const [k, v] of Object.entries(prev!.responses)) if (isHistoryKey(k) && !responses.has(k)) responses.set(k, v);\n } else if (!limited && headSha) {\n const read = await safely('Token history', () => loadGitHubHistory(client, input.config, { ref: branch, limit: limits.history }), null);\n history = read && capHistory(read);\n if (history) {\n const backend = gitHubHistoryBackend(client, input.config, { concurrency: 2 });\n const shas = [...new Set(history.entries.filter((e) => !e.bulk).slice(0, limits.historyTrees).flatMap((e) => [e.sha, ...(e.baseSha ? [e.baseSha] : [])]))];\n for (const sha of shas) await safely(`Files at ${sha.slice(0, 7)}`, () => backend.tree(sha), []);\n }\n }\n\n const activity: RepoActivity = {\n kind: 'bridge-activity',\n schemaVersion: ACTIVITY_SCHEMA_VERSION,\n tool: { name: 'bridge', version: input.version },\n generatedAt: input.generatedAt ?? new Date().toISOString(),\n repo: { owner: input.owner, name: input.repo, branch },\n headSha,\n branches,\n suggestions,\n requests,\n merged,\n history,\n responses: Object.fromEntries([...responses].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))),\n truncated,\n problems,\n };\n return fitActivity(activity);\n}\n\nconst sameRepo = (a: RepoActivity, b: { owner: string; repo: string }) => a.repo.owner.toLowerCase() === b.owner.toLowerCase() && a.repo.name.toLowerCase() === b.repo.toLowerCase();\nconst isHistoryKey = (k: string) => /\\/git\\/commits\\/[0-9a-f]+$/.test(k) || /\\/git\\/trees\\/[0-9a-f]+\\?recursive=1$/.test(k);\n\n/** Bytes of the activity as written. */\nexport const activityBytes = (a: RepoActivity): number => new TextEncoder().encode(`${JSON.stringify(a)}\\n`).length;\n\n/**\n * Keeps the activity under `max` bytes: drops the recorded file lists (trees) first, then the pages of the least\n * recently updated branches, then every recorded read. The summaries always stay. Says what it dropped in `truncated`.\n */\nexport function fitActivity(activity: RepoActivity, max = ACTIVITY_MAX_BYTES): RepoActivity {\n if (activityBytes(activity) <= max) return activity;\n const out = { ...activity, responses: { ...activity.responses }, truncated: [...activity.truncated] };\n const drop = (test: (k: string) => boolean) => {\n for (const k of Object.keys(out.responses)) if (test(k)) delete out.responses[k];\n };\n drop((k) => k.includes('/git/trees/'));\n out.truncated.push('File lists were left out to keep activity.json small: a branch or history change reads them from GitHub.');\n if (activityBytes(out) <= max) return out;\n const old = [...out.branches].sort((a, b) => (a.updatedAt < b.updatedAt ? -1 : 1));\n for (const b of old) {\n drop((k) => new RegExp(`/(pulls|issues)/${b.number}(/|$|\\\\?)`).test(k) || k.includes(`/commits/${b.headSha}/`) || k.includes(`...${b.headSha}`));\n if (activityBytes(out) <= max) {\n out.truncated.push('The pages of the least recently updated branches were left out: they read from GitHub.');\n return out;\n }\n }\n out.responses = {};\n out.truncated.push('Every recorded read was left out: pages read GitHub live.');\n return out;\n}\n\n// --- reading ------------------------------------------------------------------------------------------------------\n\n/** Validates an activity (text or parsed JSON). Throws ActivityError naming the first problem. */\nexport function parseActivity(input: string | unknown): RepoActivity {\n let data: unknown = input;\n if (typeof input === 'string') {\n try {\n data = JSON.parse(input);\n } catch (err) {\n throw new ActivityError(`${ACTIVITY_FILE} is not valid JSON (${(err as Error).message})`);\n }\n }\n if (!isObj(data) || data.kind !== 'bridge-activity') throw new ActivityError(`${ACTIVITY_FILE} is not a Bridge activity file`);\n if (data.schemaVersion !== ACTIVITY_SCHEMA_VERSION) throw new ActivityError(`${ACTIVITY_FILE} is schema version ${String(data.schemaVersion)}; this version of Bridge reads ${ACTIVITY_SCHEMA_VERSION}`);\n const repo = data.repo;\n if (!isObj(repo) || typeof repo.owner !== 'string' || typeof repo.name !== 'string' || typeof repo.branch !== 'string') throw new ActivityError(`${ACTIVITY_FILE}: repo needs owner, name and branch`);\n if (typeof data.generatedAt !== 'string' || Number.isNaN(Date.parse(data.generatedAt))) throw new ActivityError(`${ACTIVITY_FILE}: generatedAt is missing`);\n for (const k of ['branches', 'suggestions', 'requests', 'merged', 'truncated', 'problems'] as const) if (!Array.isArray(data[k])) throw new ActivityError(`${ACTIVITY_FILE}: ${k} must be a list`);\n if (!isObj(data.responses) || !Object.values(data.responses).every((r) => isObj(r) && typeof r.status === 'number')) throw new ActivityError(`${ACTIVITY_FILE}: responses must map paths to { status, body }`);\n if (data.history !== null && !(isObj(data.history) && Array.isArray(data.history.entries))) throw new ActivityError(`${ACTIVITY_FILE}: history must be null or a history report`);\n return data as unknown as RepoActivity;\n}\n\n/** Milliseconds since the activity was written (never negative). */\nexport const activityAge = (a: Pick<RepoActivity, 'generatedAt'>, now = Date.now()): number => Math.max(0, now - Date.parse(a.generatedAt));\n\n/** True while a guest should read the activity instead of GitHub: written for this repository, and recently. */\nexport function activityIsUsable(a: Pick<RepoActivity, 'generatedAt' | 'repo'>, team: { owner: string; repo: string }, now = Date.now(), maxAge = ACTIVITY_MAX_AGE_MS): boolean {\n return a.repo.owner.toLowerCase() === team.owner.toLowerCase() && a.repo.name.toLowerCase() === team.repo.toLowerCase() && activityAge(a, now) <= maxAge;\n}\n\n/**\n * The recorded answer to a GitHub REST GET, or undefined when the activity did not record it (read it live). Only\n * reads of the activity's own repository (and the user accounts it recorded) are answered.\n */\nexport function activityAnswer(a: Pick<RepoActivity, 'responses' | 'repo'>, url: string): ActivityResponse | undefined {\n const key = activityKey(url);\n if (!key) return undefined;\n const own = `/repos/${a.repo.owner.toLowerCase()}/${a.repo.name.toLowerCase()}`;\n if (!(key === own || key.startsWith(`${own}/`) || key.startsWith(`${own}?`) || key.startsWith('/users/'))) return undefined;\n return Object.prototype.hasOwnProperty.call(a.responses, key) ? a.responses[key] : undefined;\n}\n\n/** \"activity.json\" on the bridge-data branch of a public repository, on the raw host (no API quota). */\nexport const activityRawUrl = (owner: string, repo: string): string => `https://raw.githubusercontent.com/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/${SNAPSHOT_BRANCH}/${ACTIVITY_FILE}`;\n","// Pushes from the Figma plugin to the library, and build requests (docs/BUILD-REQUESTS.md).\n//\n// The rule: a push from the Figma plugin counts as design-approved. Keeping unvalidated work out of Figma main is the\n// team's own discipline, not Bridge's. So:\n// - token VALUE changes (and additions) ship after the automatic checks, with no person in the loop;\n// - token RENAMES or REMOVALS wait for a developer OK (the tech approval): they can break product code;\n// - structure changes (a new variant, option, layout, a new component) become a BUILD REQUEST for developers: a GitHub\n// issue (labels component-change and bridge-build) carrying the Figma link, before and after images, the props\n// needed and a brief ready for Claude. Developers split and track the work in GitHub or Jira; Bridge only reads it.\n// Explorations keep their own flow (docs/EXPLORATIONS.md): nothing here applies to them.\n//\n// Pure and browser safe: the Figma plugin, Studio, the MCP server and the CLI share these rules. The GitHub reads and\n// writes are in build-requests-github.ts; the gate rule (design and tech approval credited to a Figma push) is\n// withFigmaPushApprovals in review-gate.ts, applied by branchVerdict.\n\nimport { type BridgeConfig } from './config';\nimport { EXPLORATION_LABEL } from './explorations';\nimport { DRAFTED_BY_CLAUDE_LABEL, FROM_FIGMA_LABEL, WAITING_FOR_CLAUDE_LABEL, parseFigmaOrigin } from './figma-push';\nimport { closingIssueNumbers, composeRequestIssue, parseRequestIssue, REQUEST_KINDS, REQUEST_LABEL, requestIssueTitle, type ComponentChangeRequest, type RequestIssue, type RequestKind } from './requests';\nimport { isGuardrail, type ChangedFile, type TokenChangeKind, type TokenChangeSummary } from './risk';\nimport { pullState, type CiSummary } from './review-gate';\n\n/** Every build request issue carries this label (with component-change, which the Jira Action mirrors). */\nexport const BUILD_REQUEST_LABEL = 'bridge-build';\n/** The label the plugin puts on what it pushes (token pull requests, suggestions and requests). */\nexport const SOURCE_FIGMA_LABEL = 'source: figma';\n/** A build request waits this many days before it reads as stale. */\nexport const BUILD_STALE_DAYS = 7;\n\n/**\n * What the two images of a build request are called on designer screens (Studio): the component as it is in code\n * now, and the design in Figma. The data keeps its field names, `before` and `after`; the GitHub issue table, read by\n * developers, keeps Before and After.\n */\nexport const BUILD_IMAGE_LABEL = { before: 'In code now', after: 'In Figma' } as const;\n\n// ---------------------------------------------------------------------------------------------------------------\n// What a push from Figma is, and what it changes\n\nconst names = (labels: readonly ({ name?: string } | string)[] | null | undefined) => (labels ?? []).map((l) => (typeof l === 'string' ? l : (l.name ?? '')).toLowerCase());\n\n/**\n * Whether a pull request (or issue) was pushed from the Figma plugin: the `source: figma` or `from-figma` label, or the\n * hidden \"From Figma\" origin block of a component branch.\n */\nexport function isFigmaPush(p: { labels?: readonly ({ name?: string } | string)[] | null | undefined; body?: string | null | undefined }): boolean {\n const l = names(p.labels);\n return l.includes(SOURCE_FIGMA_LABEL) || l.includes(FROM_FIGMA_LABEL) || Boolean(parseFigmaOrigin(p.body));\n}\n\n/**\n * What a push from Figma changes, from the pull request's real files and token changes (never from what its body says):\n * - `token-values`: token files only (values changed or tokens added), plus changesets, docs and Bridge's own files;\n * - `token-structure`: a token renamed or removed;\n * - `token-unknown`: token files changed but the token changes were not read (counts like token-structure);\n * - `component`: component or other source code (a Claude draft branch, the pull request of a build request);\n * - `outside`: a guardrail file (CI, AGENTS.md, bridge.config.json, contrast checks): no Figma credit at all.\n */\nexport type FigmaPushScope = 'token-values' | 'token-structure' | 'token-unknown' | 'component' | 'outside';\n\nconst VALUE_SIDE = [/^\\.changeset\\//, /^\\.bridge\\//, /\\.md$/, /^docs\\//];\n\n/** A token file: `*.tokens.json`, or a JSON file under `tokens.root`. */\nexport function isTokenPath(path: string, config?: BridgeConfig | undefined): boolean {\n const p = path.replace(/^\\/+/, '');\n const tokenDir = config?.tokens?.root?.replace(/\\/+$/, '');\n return p.endsWith('.tokens.json') || (tokenDir ? p.startsWith(`${tokenDir}/`) && p.endsWith('.json') : false);\n}\n\nexport function figmaPushScope(input: { files: readonly ChangedFile[]; tokenChanges: readonly { kind: TokenChangeKind | string }[] | null | undefined; config?: BridgeConfig | undefined }): FigmaPushScope {\n let code = false;\n let tokenFiles = false;\n for (const f of input.files) {\n const p = f.path.replace(/^\\/+/, '');\n const isToken = isTokenPath(p, input.config);\n if (isGuardrail(p, input.config)) return 'outside';\n if (isToken) tokenFiles = true;\n else if (!VALUE_SIDE.some((r) => r.test(p))) code = true;\n }\n if (code) return 'component';\n const changes = input.tokenChanges;\n if (changes?.some((c) => c.kind === 'renamed' || c.kind === 'removed')) return 'token-structure';\n if (tokenFiles && !changes) return 'token-unknown';\n // Nothing but a spec, docs or a changeset: no token value to ship, so nothing ships by itself.\n if (!tokenFiles || !changes?.length) return 'component';\n return 'token-values';\n}\n\n/**\n * Whether the token files of a pull request are worth reading to tell a token value change (isTokenValueChange): it\n * changes token files, and nothing beside them but changesets, docs and Bridge's own files. Every other pull request\n * (code, a guardrail file, no token file) is not one, with no read.\n */\nexport function mayBeTokenValueChange(files: readonly ChangedFile[], config?: BridgeConfig | undefined): boolean {\n // As if the token files held a value change: the files alone decide whether reading them can tell one.\n return figmaPushScope({ files, tokenChanges: [{ kind: 'changed' }], config }) === 'token-values';\n}\n\n/**\n * Decision TV-1 (docs/BUILD-REQUESTS.md, \"Token values from Studio\"): a pull request that only changes token values\n * (values changed or tokens added, from its real files and token changes, never from its body), whoever opened it.\n * Once the design approval is given it ships after the automatic checks, with no developer code OK (review-gate\n * withTokenValueApprovals, branchVerdict `tokenValues`). A rename or removal, unread token changes (null), code, a\n * guardrail file or a running exploration is not one: those still need the tech approval.\n */\nexport function isTokenValueChange(input: {\n files: readonly ChangedFile[];\n tokenChanges: readonly { kind: TokenChangeKind | string }[] | null | undefined;\n config?: BridgeConfig | undefined;\n labels?: readonly ({ name?: string } | string)[] | null | undefined;\n}): boolean {\n if (names(input.labels).includes(EXPLORATION_LABEL)) return false;\n return figmaPushScope(input) === 'token-values';\n}\n\n/**\n * The token changes between two versions of token files, by kind, from their text alone (DTCG: a node with `$value` is a\n * token, its path the keys joined by \".\"). For callers that only have the files of a pull request (the server arming a\n * merge, Studio's branch page): a path gone is `removed` (a rename reads as removed plus added, which gates the same),\n * a new path `added`, a different `$value`, `$type` or extension `changed`, a different `$description` only\n * `changed` with descriptionOnly. Unreadable JSON throws, so the caller treats the changes as unknown.\n */\nexport function tokenFileChanges(files: readonly { before: string | null | undefined; after: string | null | undefined }[]): TokenChangeSummary[] {\n const flat = (text: string | null | undefined) => {\n const out = new Map<string, Record<string, unknown>>();\n if (!text) return out;\n const walk = (node: unknown, path: string[]) => {\n if (!node || typeof node !== 'object' || Array.isArray(node)) return;\n const o = node as Record<string, unknown>;\n if ('$value' in o) {\n out.set(path.join('.'), o);\n return;\n }\n for (const [k, v] of Object.entries(o)) if (!k.startsWith('$')) walk(v, [...path, k]);\n };\n walk(JSON.parse(text), []);\n return out;\n };\n const changes: TokenChangeSummary[] = [];\n for (const f of files) {\n const before = flat(f.before);\n const after = flat(f.after);\n for (const [path, b] of before) {\n const a = after.get(path);\n if (!a) {\n changes.push({ kind: 'removed', path });\n continue;\n }\n const { $description: bd, ...bRest } = b;\n const { $description: ad, ...aRest } = a;\n const same = JSON.stringify(bRest) === JSON.stringify(aRest);\n if (!same) changes.push({ kind: 'changed', path });\n else if (bd !== ad) changes.push({ kind: 'changed', path, descriptionOnly: true });\n }\n for (const path of after.keys()) if (!before.has(path)) changes.push({ kind: 'added', path });\n }\n return changes;\n}\n\n/** The Figma push facts the gate reads (branchVerdict `figmaPush`). Null when the pull request is not one. */\nexport interface FigmaPush {\n scope: FigmaPushScope;\n}\n\n/**\n * The Figma push facts of a pull request: pushed from the plugin (isFigmaPush), or the pull request of a build request\n * sent from Figma (`closesFigmaBuildRequest`: its body closes one). Null otherwise, and for a running exploration.\n */\nexport function figmaPushOf(\n pr: { labels?: readonly ({ name?: string } | string)[] | null | undefined; body?: string | null | undefined },\n facts: { files: readonly ChangedFile[]; tokenChanges: readonly { kind: TokenChangeKind | string }[] | null | undefined; config?: BridgeConfig | undefined; closesFigmaBuildRequest?: boolean | undefined },\n): FigmaPush | null {\n if (names(pr.labels).includes(EXPLORATION_LABEL)) return null;\n if (!isFigmaPush(pr) && !facts.closesFigmaBuildRequest) return null;\n const scope = figmaPushScope(facts);\n // A library branch that carries a component spec (Claude draft, a build request's branch) is code work: it never ships\n // by itself, even while it only holds the spec.\n const l = names(pr.labels);\n const draft = l.includes(WAITING_FOR_CLAUDE_LABEL) || l.includes(DRAFTED_BY_CLAUDE_LABEL) || parseFigmaOrigin(pr.body)?.route === 'claude-draft' || facts.closesFigmaBuildRequest;\n return { scope: draft && scope.startsWith('token-') ? 'component' : scope };\n}\n\n/** Whether a scope ships with no person in the loop: design approved by the push, tech approved by being values only. */\nexport const shipsByItself = (scope: FigmaPushScope | null | undefined): boolean => scope === 'token-values';\n\n// ---------------------------------------------------------------------------------------------------------------\n// The publish result the plugin shows, per component or token\n\n/**\n * Where one published thing went:\n * - `shipped`: a token pull request with values only. Bridge merges it once the automatic checks pass (auto-merge\n * armed); poll libraryArrival until it reads \"In the library\".\n * - `waiting-for-developer`: a pull request a developer approves first (a token renamed or removed).\n * - `build-request`: an issue developers build from (a structure change).\n */\nexport type PublishRoute = 'shipped' | 'waiting-for-developer' | 'build-request';\n\nexport interface PublishOutcome {\n /** What was published: a token path, or a component name. */\n subject: { type: 'token' | 'component'; name: string };\n route: PublishRoute;\n /** The pull request (shipped, waiting-for-developer) or the issue (build-request). */\n ref: { kind: 'pull' | 'issue'; number: number; url: string };\n /**\n * `shipped` only: whether Bridge armed the merge (auto-merge on GitHub, or the Bridge app merging on green checks).\n * False when it could not (no Bridge app on the repository, auto-merge off): the route is then reported as\n * `waiting-for-developer` instead, so this is true on every `shipped` outcome.\n */\n armed?: boolean | undefined;\n}\n\nexport interface PublishResult {\n outcomes: PublishOutcome[];\n}\n\nexport const PUBLISH_ROUTE_COPY: Record<PublishRoute, { label: string; sentence: string }> = {\n shipped: { label: 'On its way to the library', sentence: 'It ships by itself once the automatic checks pass.' },\n 'waiting-for-developer': { label: 'Waiting for a developer', sentence: 'A renamed or removed token can break product code, so a developer OKs it first.' },\n 'build-request': { label: 'Build request sent', sentence: 'Developers build it from what you sent. Follow it in Being built.' },\n};\n\n/**\n * The route of a token push, from its token changes: values changed or tokens added ship; a rename or a removal waits\n * for a developer. `armed` false (Bridge could not arm the merge) also waits for a developer.\n */\nexport function tokenPublishRoute(changes: readonly { kind: TokenChangeKind | string }[], armed = true): Exclude<PublishRoute, 'build-request'> {\n if (changes.some((c) => c.kind === 'renamed' || c.kind === 'removed')) return 'waiting-for-developer';\n return armed ? 'shipped' : 'waiting-for-developer';\n}\n\n/** One sentence for the end of a publish: \"2 on their way to the library, 1 waiting for a developer, 1 build request sent.\" */\nexport function publishSummary(r: PublishResult): string {\n const n = (route: PublishRoute) => r.outcomes.filter((o) => o.route === route).length;\n const parts: string[] = [];\n const s = n('shipped');\n const w = n('waiting-for-developer');\n const b = n('build-request');\n if (s) parts.push(`${s} on ${s === 1 ? 'its' : 'their'} way to the library`);\n if (w) parts.push(`${w} waiting for a developer`);\n if (b) parts.push(`${b} build request${b === 1 ? '' : 's'} sent`);\n return parts.length ? `${parts.join(', ')}.`.replace(/^./, (c) => c.toUpperCase()) : 'Nothing was published.';\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// After publish: is it in the library yet\n\nexport type LibraryArrivalKey = 'on-its-way' | 'in-the-library' | 'held' | 'not-shipped';\n\nexport interface LibraryArrival {\n key: LibraryArrivalKey;\n label: string;\n sentence: string;\n /** Stop polling: it is in the library, or it will not get there by itself. */\n final: boolean;\n}\n\n/**\n * Where a published pull request stands, for the plugin to poll after `shipped` (every 20 to 30 seconds is plenty)\n * and for Studio. Never names a technical blocker: a failing check, a conflict or a change request all read \"Held for a\n * developer\". `held` is final for polling on a conflict or a change request (a person picks it up from there), not on a\n * failed check, which a re-run can clear.\n */\nexport function libraryArrival(p: {\n state: string;\n merged_at?: string | null | undefined;\n merged?: boolean | undefined;\n mergeable?: boolean | null | undefined;\n ci?: CiSummary | null | undefined;\n changesRequested?: number | undefined;\n}): LibraryArrival {\n const lifecycle = pullState({ state: p.state, merged_at: p.merged_at ?? null, merged: p.merged ?? p.state === 'merged' });\n if (lifecycle === 'merged') return { key: 'in-the-library', label: 'In the library', sentence: 'It is in the library. Storybook shows it after the next deploy.', final: true };\n if (lifecycle === 'closed') return { key: 'not-shipped', label: 'Not shipped', sentence: 'A developer closed it without shipping. Pull in the plugin to bring Figma back in line with the library.', final: true };\n // A failed check can be re-run and the armed auto-merge then ships it, so polling goes on; a conflict or a change\n // request needs a person, so polling stops there.\n const needsPerson = p.mergeable === false || (p.changesRequested ?? 0) > 0;\n if (needsPerson || p.ci?.state === 'fail')\n return { key: 'held', label: 'Held for a developer', sentence: 'Something needs a developer before it ships. They are told on GitHub; nothing to do on your side.', final: needsPerson };\n return { key: 'on-its-way', label: 'On its way to the library', sentence: PUBLISH_ROUTE_COPY.shipped.sentence, final: false };\n}\n\n/** The review Bridge's app leaves on a token push it ships (the merge rule's record on GitHub). */\nexport const FIGMA_SHIP_HEADING = '**Bridge: shipped from Figma**';\n\nexport function figmaShipReviewBody(by?: string | null): string {\n const who = by ? ` by ${by.startsWith('@') || by.includes(' ') ? by : `@${by}`}` : '';\n return `${FIGMA_SHIP_HEADING}\\n\\nPushed from Figma${who}: token values only, so it ships once the automatic checks pass (docs/BUILD-REQUESTS.md). Undo it from History in Bridge Studio.`;\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// The build request issue\n\n/** A prop (option) the build needs. */\nexport interface BuildProp {\n name: string;\n /** \"variant\", \"boolean\", \"text\", \"instance swap\", or a TypeScript type. */\n type?: string | undefined;\n values?: string[] | undefined;\n default?: string | undefined;\n /** \"new\", \"changed\" or \"removed\"; default new. */\n change?: 'new' | 'changed' | 'removed' | undefined;\n note?: string | undefined;\n}\n\n/** What a build request adds to a component change request (kept in the request's hidden block, under `build`). */\nexport interface BuildRequestExtra {\n v: 1;\n /** Image URLs of the design before and after the change. */\n before?: string[] | undefined;\n after?: string[] | undefined;\n props?: BuildProp[] | undefined;\n /** Where the full spec lives, when it is not in the issue (too large): a path on a branch, or a URL. */\n specPath?: string | undefined;\n}\n\n/** The input of the build request issue builder (the Figma plugin, Studio, the CLI and the MCP server). */\nexport interface BuildRequestInput {\n /** Coded name (\"Button\"), or the proposed name of a new component. */\n component: string;\n kind: RequestKind;\n /** One line, sentence case: \"Add a lg size\". */\n title: string;\n /** What and why, in the designer's words. */\n summary: string;\n /** What changes for developers in one sentence. */\n line?: string | undefined;\n changes?: ComponentChangeRequest['changes'] | undefined;\n figma: { fileKey?: string | undefined; nodeId?: string | undefined; nodeName?: string | undefined; url?: string | undefined };\n images?: { before?: string[] | undefined; after?: string[] | undefined } | undefined;\n props?: BuildProp[] | undefined;\n /** The structured spec (the plugin's ComponentPushDiff, with its token edits), shown collapsed. Omitted when too large. */\n spec?: unknown;\n specPath?: string | undefined;\n /** A brief for Claude written by the caller; default buildRequestBrief. */\n brief?: string | undefined;\n source: ComponentChangeRequest['source'];\n /** GitHub login of who pushed, when known (the \"Requested by\" record). */\n requestedBy?: string | undefined;\n}\n\n/** Kinds that are structure changes, so a push from Figma becomes a build request. */\nexport const BUILD_KINDS: readonly RequestKind[] = ['new-component', 'new-variant', 'prop-change', 'structure', 'visual'];\n\n/** The largest spec JSON kept in the issue body (GitHub caps a body at 65,536 characters). */\nexport const BUILD_SPEC_MAX = 30_000;\nconst SPEC_MARK = '<!-- bridge-build-spec -->';\n\nconst kindLabel = (k: RequestKind) => REQUEST_KINDS.find((x) => x.value === k)?.label ?? 'Change';\n\n/** The request a build request input stands for (what parseRequestIssue reads back, with `build`). */\nexport function buildRequestOf(input: BuildRequestInput): ComponentChangeRequest & { build: BuildRequestExtra } {\n const before = input.images?.before?.filter(Boolean) ?? [];\n const after = input.images?.after?.filter(Boolean) ?? [];\n const build: BuildRequestExtra = {\n v: 1,\n ...(before.length ? { before } : {}),\n ...(after.length ? { after } : {}),\n ...(input.props?.length ? { props: input.props } : {}),\n ...(input.specPath ? { specPath: input.specPath } : {}),\n };\n return {\n component: input.component,\n kind: input.kind,\n title: input.title,\n summary: input.summary,\n ...(input.line ? { line: input.line } : {}),\n changes: input.changes ?? [],\n figma: input.figma,\n ...(after.length ? { images: after } : {}),\n source: input.source,\n ...(input.requestedBy ? { requestedBy: input.requestedBy } : {}),\n build,\n };\n}\n\nconst propLine = (p: BuildProp) => {\n const what = p.change === 'removed' ? 'remove' : p.change === 'changed' ? 'change' : 'add';\n const values = p.values?.length ? `: ${p.values.join(', ')}` : '';\n const def = p.default ? ` (default ${p.default})` : '';\n return `${what} \\`${p.name}\\`${p.type ? ` ${p.type}` : ''}${values}${def}${p.note ? `. ${p.note}` : ''}`;\n};\n\n/**\n * The brief Claude gets to build it (\"Copy brief for Claude\" in Studio, `bridge build show` in the CLI,\n * `bridge_get_build_request` in the MCP server). Without an issue number (inside the issue body), it says \"this issue\".\n */\nexport function buildRequestBrief(\n r: ComponentChangeRequest & { build?: BuildRequestExtra | undefined },\n ctx: { issue?: number | undefined; issueUrl?: string | undefined; componentsDir?: string | undefined; agentsFile?: string | undefined; files?: string[] | undefined } = {},\n): string {\n const ref = ctx.issue ? `#${ctx.issue}` : 'this issue';\n const dir = `${(ctx.componentsDir ?? 'packages/react/src/components').replace(/\\/+$/, '')}/${r.component}`;\n const b = r.build;\n const before = b?.before ?? [];\n const after = b?.after ?? r.images ?? [];\n return [\n `Build Bridge build request ${ref}${ctx.issueUrl ? ` (${ctx.issueUrl})` : ''}: a component change designed and validated in Figma.`,\n '',\n r.kind === 'new-component' ? `New component: ${r.component} (create ${dir})` : `Component: ${r.component} (${dir})`,\n `Kind: ${kindLabel(r.kind)}`,\n `Change: ${r.title}`,\n ...(r.line?.trim() ? [`What changes: ${r.line.trim()}`] : []),\n '',\n r.summary.trim(),\n '',\n ...(r.changes.length ? ['Changes in Figma:', ...r.changes.map((c) => `- ${c.field}: ${c.before ?? '(none)'} -> ${c.after ?? '(removed)'}`), ''] : []),\n ...(b?.props?.length ? ['Props needed:', ...b.props.map((p) => `- ${propLine(p)}`), ''] : []),\n ...(r.figma?.url ? [`Design: ${r.figma.url}`] : []),\n ...(r.figma?.fileKey && r.figma.nodeId ? [`Read it from Figma: Figma MCP get_design_context { fileKey: \"${r.figma.fileKey}\", nodeId: \"${r.figma.nodeId}\" }.`] : []),\n ...(before.length ? ['Before:', ...before.map((u) => `- ${u}`)] : []),\n ...(after.length ? ['After:', ...after.map((u) => `- ${u}`)] : []),\n b?.specPath ? `Spec: ${b.specPath}` : `Spec: the collapsed \"Spec\" section of ${ref}, when there is one (variant matrix, properties, bound variables as token paths).`,\n ...(ctx.files?.length ? ['', 'Files of this component:', ...ctx.files.map((f) => `- ${f}`)] : []),\n '',\n 'Rules:',\n `- Follow ${ctx.agentsFile ?? 'AGENTS.md'}: Base UI for behavior, tokens only in component CSS, states, stories, docs.json, tests, changeset.`,\n '- The design is already approved in Figma: build what it shows. Never invent a token or a value: use the variables the design binds. A value the library lacks is a token change, said in the pull request.',\n '- Keep every existing variant and prop unchanged unless the request changes it.',\n `- Work on a branch named agent/build-${ctx.issue ?? '<issue number>'}. The pull request body must contain \"Closes ${ctx.issue ? `#${ctx.issue}` : '#<issue number>'}\", so the request reads Shipped when it merges.`,\n `- If something is unclear, comment on ${ref} instead of guessing.`,\n ].join('\\n');\n}\n\n/**\n * The GitHub issue of a build request: a component change request issue (component-change, so the bridge-jira Action\n * mirrors it to Jira) with the bridge-build label, before and after images side by side, the props needed, the spec\n * collapsed and the brief for Claude collapsed. parseBuildRequestIssue reads it back.\n */\nexport function composeBuildRequestIssue(input: BuildRequestInput, opts: { labels?: string[] | undefined; assignees?: string[] | undefined; componentUrl?: string | undefined } = {}): RequestIssue {\n const r = buildRequestOf(input);\n const base = composeRequestIssue(r, { labels: [BUILD_REQUEST_LABEL, ...(opts.labels ?? [])], ...(opts.assignees ? { assignees: opts.assignees } : {}), ...(opts.componentUrl ? { componentUrl: opts.componentUrl } : {}) });\n const before = r.build.before ?? [];\n const after = r.build.after ?? [];\n const img = (u: string, i: number, what: string) => ``;\n // composeRequestIssue already shows the after images inline; the before and after table replaces them when both exist.\n let body = base.body;\n if (before.length && after.length) {\n for (const [i, u] of after.entries()) body = body.replace(`\\n`, '');\n const rows = Math.max(before.length, after.length);\n const table = [`| ${BUILD_IMAGE_LABEL.before} | ${BUILD_IMAGE_LABEL.after} |`, '| --- | --- |', ...Array.from({ length: rows }, (_, i) => `| ${before[i] ? img(before[i]!, i, 'before') : ''} | ${after[i] ? img(after[i]!, i, 'after') : ''} |`)];\n body = insertBefore(body, '## How to implement', [...table, ''].join('\\n'));\n } else if (before.length) {\n body = insertBefore(body, '## How to implement', [...before.map((u, i) => img(u, i, 'before')), ''].join('\\n'));\n }\n if (r.build.props?.length) body = insertBefore(body, '## How to implement', ['**Props needed:**', ...r.build.props.map((p) => `- ${propLine(p)}`), ''].join('\\n'));\n const brief = input.brief?.trim() || buildRequestBrief(r);\n const specJson = input.spec === undefined ? '' : JSON.stringify(input.spec, null, 2);\n const spec = specJson && specJson.length <= BUILD_SPEC_MAX ? ['<details><summary>Spec</summary>', '', SPEC_MARK, '', '```json', specJson.replace(/```/g, '```'), '```', '', '</details>', ''] : [];\n const tail = ['<details><summary>Brief for Claude</summary>', '', '```text', brief.replace(/```/g, '```'), '```', '', '</details>', '', ...spec].join('\\n');\n body = insertBefore(body, '<sub>Requested from', `${tail}\\n`);\n body = body.replace('\\n## How to implement\\n', '\\n## How to build it\\n');\n return { ...base, body };\n}\n\nfunction insertBefore(body: string, marker: string, block: string): string {\n const at = body.indexOf(`\\n${marker}`);\n return at < 0 ? `${body}\\n\\n${block}` : `${body.slice(0, at + 1)}${block}\\n${body.slice(at + 1)}`;\n}\n\n/** The build request in an issue body, or undefined when it has no Bridge request block. `build` is empty for a plain request. */\nexport function parseBuildRequestIssue(body: string | null | undefined): (ComponentChangeRequest & { build: BuildRequestExtra }) | undefined {\n const r = parseRequestIssue(body) as (ComponentChangeRequest & { build?: BuildRequestExtra }) | undefined;\n if (!r) return undefined;\n return { ...r, build: r.build && r.build.v === 1 ? r.build : { v: 1 } };\n}\n\n/** The spec kept collapsed in a build request issue, or undefined. */\nexport function parseBuildSpec(body: string | null | undefined): unknown {\n const at = (body ?? '').indexOf(SPEC_MARK);\n if (at < 0) return undefined;\n const m = /```json\\n([\\s\\S]*?)\\n```/.exec(body!.slice(at));\n if (!m) return undefined;\n try {\n return JSON.parse(m[1]!.replace(/```/g, '```'));\n } catch {\n return undefined;\n }\n}\n\n/** Whether an issue is a build request: every component change request is one (bridge-build marks the new ones). Explorations are not. */\nexport function isBuildRequestIssue(labels: readonly ({ name?: string } | string)[] | null | undefined): boolean {\n const l = names(labels);\n return (l.includes(BUILD_REQUEST_LABEL) || l.includes(REQUEST_LABEL)) && !l.includes(EXPLORATION_LABEL);\n}\n\n// ---------------------------------------------------------------------------------------------------------------\n// Where a build request stands, read from GitHub only\n\n/**\n * Requested (nobody assigned) -> Picked up (assigned: \"Ana is on it\") -> In progress (a linked draft pull request, or a\n * linked branch with commits) -> In review (a linked pull request ready for review) -> Shipped (merged, or the issue\n * closed as completed). `not-planned`: closed as not planned.\n */\nexport type BuildStatus = 'requested' | 'picked-up' | 'in-progress' | 'in-review' | 'shipped' | 'not-planned';\n\nexport const BUILD_STATUS_LABEL: Record<BuildStatus, string> = {\n requested: 'Requested',\n 'picked-up': 'Picked up',\n 'in-progress': 'In progress',\n 'in-review': 'In review',\n shipped: 'Shipped',\n 'not-planned': 'Not planned',\n};\n\n/** Steps of the status timeline, in order (not-planned is off the line). */\nexport const BUILD_STEPS: readonly BuildStatus[] = ['requested', 'picked-up', 'in-progress', 'in-review', 'shipped'];\n\n/** A pull request linked to a build request (closes it, or the build request is that branch). */\nexport interface BuildPullLike {\n number: number;\n url?: string | undefined;\n /** \"open\", \"closed\" or \"merged\" (PullRequestSummary), or GitHub's open/closed with merged_at. */\n state: string;\n draft?: boolean | undefined;\n mergedAt?: string | null | undefined;\n merged_at?: string | null | undefined;\n labels?: readonly ({ name?: string } | string)[] | undefined;\n author?: string | undefined;\n assignees?: string[] | undefined;\n createdAt?: string | undefined;\n updatedAt?: string | undefined;\n body?: string | undefined;\n /** Commits on the branch, when known (a branch with only the spec commit is not work in progress). */\n commits?: number | null | undefined;\n headRef?: string | undefined;\n title?: string | undefined;\n}\n\nexport interface BuildIssueLike {\n number: number;\n url: string;\n title: string;\n body: string;\n state: 'open' | 'closed';\n stateReason?: string | null | undefined;\n labels: readonly ({ name?: string } | string)[];\n author?: string | undefined;\n assignees?: string[] | undefined;\n createdAt: string;\n closedAt?: string | null | undefined;\n}\n\nexport interface BuildStatusEvent {\n status: BuildStatus;\n /** ISO date, when GitHub says. */\n at?: string | undefined;\n /** Who, when it is a person (\"ana\"). */\n who?: string | undefined;\n}\n\nexport interface BuildRequestView {\n /** \"issue-12\" or \"pull-34\". */\n id: string;\n /** Where it lives: an issue, or (direct mode, no issue) the library branch from Figma waiting for a developer. */\n kind: 'issue' | 'pull';\n number: number;\n url: string;\n component: string;\n /** \"Add a lg size\": the request's title, without the component prefix. */\n title: string;\n requestKind: RequestKind | null;\n status: BuildStatus;\n label: string;\n /** One designer sentence: \"Ana is on it.\", \"Waiting for a developer for 9 days.\" */\n sentence: string;\n /** Who works on it: the assignees, else the author of the linked pull request in progress. */\n builders: string[];\n requestedBy: string | null;\n createdAt: string;\n ageDays: number;\n /** Requested for more than BUILD_STALE_DAYS days. */\n stale: boolean;\n shippedAt: string | null;\n /** The linked pull request that moves it furthest. */\n pull: { number: number; url?: string | undefined; state: string } | null;\n /** Jira key from the bridge-jira Action's `jira: DS-12` label. */\n jira: string | null;\n figmaUrl: string | null;\n /** The status timeline: each step reached, with when and who when GitHub says. */\n timeline: BuildStatusEvent[];\n}\n\nconst DAY = 86_400_000;\nconst mergedAtOf = (p: BuildPullLike) => p.mergedAt ?? p.merged_at ?? null;\nconst isMerged = (p: BuildPullLike) => Boolean(mergedAtOf(p)) || p.state === 'merged';\nconst isOpen = (p: BuildPullLike) => p.state === 'open';\nconst pullNames = (p: BuildPullLike) => names(p.labels);\n/** A Figma library branch that still carries the spec only: not work in progress. */\nconst specOnly = (p: BuildPullLike) => pullNames(p).includes(WAITING_FOR_CLAUDE_LABEL) && !(p.commits != null && p.commits > 1);\n/** Ready for review: open, not a draft (a drafted-by-claude branch is ready even while GitHub calls it a draft). */\nconst ready = (p: BuildPullLike) => isOpen(p) && (!p.draft || pullNames(p).includes(DRAFTED_BY_CLAUDE_LABEL)) && !specOnly(p);\n\n/** The issue numbers a pull request links: \"Closes #n\" in its body, plus GitHub's linked issues when the caller read them. */\nexport function linkedIssueNumbers(p: Pick<BuildPullLike, 'body'>, extra: readonly number[] = []): number[] {\n return [...new Set([...closingIssueNumbers(p.body), ...extra])];\n}\n\n/** The Jira key the bridge-jira Action labelled an issue with (\"jira: DS-12\"), or null. */\nexport function jiraKeyOfLabels(labels: readonly ({ name?: string } | string)[] | null | undefined): string | null {\n for (const l of labels ?? []) {\n const n = typeof l === 'string' ? l : (l.name ?? '');\n const m = /^jira:\\s*([A-Z][A-Z0-9_]*-\\d+)$/i.exec(n.trim());\n if (m) return m[1]!.toUpperCase();\n }\n return null;\n}\n\nconst first = (xs: readonly string[]) => xs[0];\nconst listNames = (xs: string[]) => (xs.length <= 1 ? (xs[0] ?? '') : `${xs.slice(0, -1).join(', ')} and ${xs[xs.length - 1]}`);\n\n/**\n * The status of one build request, from GitHub only: the issue (state, reason, assignees) and the pull requests linked\n * to it. `nameOf` turns a login into the name a designer knows (team members), default the login.\n */\nexport function buildRequestStatus(\n x: { issue?: BuildIssueLike | null | undefined; pull?: BuildPullLike | null | undefined; linked?: readonly BuildPullLike[] | undefined },\n now: Date | number = Date.now(),\n nameOf: (login: string) => string = (l) => l,\n): Pick<BuildRequestView, 'status' | 'label' | 'sentence' | 'builders' | 'ageDays' | 'stale' | 'shippedAt' | 'pull' | 'timeline' | 'createdAt'> {\n const nowMs = typeof now === 'number' ? now : now.getTime();\n const own = x.pull ?? null;\n const linked = [...(own ? [own] : []), ...(x.linked ?? [])];\n const createdAt = x.issue?.createdAt ?? own?.createdAt ?? own?.updatedAt ?? new Date(nowMs).toISOString();\n // Who picked it up: the issue's assignees, else the assignees of a linked pull request (a developer may assign\n // themselves on the library branch from Figma that carries the spec and closes the issue).\n const linkedAssignees = linked.filter((p) => isOpen(p) || isMerged(p)).flatMap((p) => p.assignees ?? []);\n const assignees = x.issue?.assignees?.length ? x.issue.assignees : [...new Set(linkedAssignees)];\n // The person who sent it never reads as its builder (the branch from Figma is opened in their name).\n const requester = (x.issue?.author ?? own?.author ?? '').toLowerCase();\n const merged = linked.filter(isMerged).sort((a, b) => String(mergedAtOf(b)).localeCompare(String(mergedAtOf(a))))[0];\n const inReview = linked.find(ready);\n const building = linked.find((p) => isOpen(p) && !specOnly(p));\n // The issue's own state decides first when it is closed: completed reads shipped even without a merged pull request.\n const issueClosed = x.issue?.state === 'closed';\n const ownClosed = !x.issue && own && !isOpen(own) && !isMerged(own);\n let status: BuildStatus;\n if (merged || (issueClosed && x.issue?.stateReason !== 'not_planned')) status = 'shipped';\n else if (issueClosed || ownClosed) status = 'not-planned';\n else if (inReview) status = 'in-review';\n else if (building) status = 'in-progress';\n else if (assignees.length) status = 'picked-up';\n else status = 'requested';\n const workPull = merged ?? inReview ?? building ?? null;\n const builders = assignees.length ? [...assignees] : workPull?.author && (status === 'in-progress' || status === 'in-review' || status === 'shipped') && workPull !== own && workPull.author.toLowerCase() !== requester ? [workPull.author] : [];\n const ageDays = Math.max(0, Math.floor((nowMs - Date.parse(createdAt)) / DAY));\n const stale = status === 'requested' && ageDays > BUILD_STALE_DAYS;\n const shippedAt = status === 'shipped' ? (merged ? mergedAtOf(merged) : null) ?? x.issue?.closedAt ?? null : null;\n const who = listNames(builders.map(nameOf));\n const sentence: Record<BuildStatus, string> = {\n requested: stale ? `Waiting for a developer to pick it up for ${ageDays} days.` : 'Waiting for a developer to pick it up.',\n 'picked-up': `${who} ${builders.length > 1 ? 'are' : 'is'} on it.`,\n 'in-progress': who ? `${who} ${builders.length > 1 ? 'are' : 'is'} building it.` : 'A developer is building it.',\n 'in-review': 'Built. A developer reviews the code before it ships.',\n shipped: 'In the library. Storybook shows it after the next deploy.',\n 'not-planned': 'Developers closed it without building it.',\n };\n const reached = status === 'not-planned' ? ['requested'] : BUILD_STEPS.slice(0, BUILD_STEPS.indexOf(status) + 1);\n const timeline: BuildStatusEvent[] = reached.map((s) => {\n if (s === 'requested') return { status: s, at: createdAt, ...(x.issue?.author ? { who: x.issue.author } : own?.author ? { who: own.author } : {}) };\n if (s === 'picked-up') return { status: s, ...(first(builders) ? { who: first(builders) } : {}) };\n if (s === 'in-progress') {\n // The branch from Figma was opened by the sender when they pushed: its date and author are not when work started.\n const theirs = building && building !== own && building.author && building.author.toLowerCase() !== requester;\n return { status: s, ...(theirs && building.createdAt ? { at: building.createdAt } : {}), ...(theirs ? { who: building.author } : first(builders) ? { who: first(builders) } : {}) };\n }\n if (s === 'shipped') return { status: s, ...(shippedAt ? { at: shippedAt } : {}) };\n return { status: s as BuildStatus };\n });\n if (status === 'not-planned') timeline.push({ status: 'not-planned', ...(x.issue?.closedAt ? { at: x.issue.closedAt } : {}) });\n return {\n status,\n label: status === 'requested' && stale ? `Requested ${ageDays} days ago` : BUILD_STATUS_LABEL[status],\n sentence: sentence[status],\n builders,\n ageDays,\n stale,\n shippedAt,\n pull: workPull ? { number: workPull.number, url: workPull.url, state: isMerged(workPull) ? 'merged' : workPull.state } : null,\n timeline,\n createdAt,\n };\n}\n\nconst stripSubject = (title: string, component: string) => {\n const t = title.trim();\n const p = `${component}:`;\n return t.toLowerCase().startsWith(p.toLowerCase()) ? t.slice(p.length).trim().replace(/^./, (c) => c.toUpperCase()) : t;\n};\n\n/** Order of the list: what waits longest first, then work in flight, then shipped, newest first within each. */\nconst STATUS_ORDER: Record<BuildStatus, number> = { requested: 0, 'picked-up': 1, 'in-progress': 2, 'in-review': 3, shipped: 4, 'not-planned': 5 };\n\n/**\n * Every build request, from the issues and pull requests read on GitHub: issues that are build requests\n * (isBuildRequestIssue) with the pull requests that close them, plus library branches from Figma waiting for a\n * developer that no issue covers (direct mode). `linkedByIssue`: GitHub's linked pull requests per issue number, when the\n * caller read the timeline (Development links), on top of \"Closes #n\".\n */\nexport function assembleBuildRequests(input: {\n issues: readonly BuildIssueLike[];\n pulls: readonly BuildPullLike[];\n now?: Date | number | undefined;\n nameOf?: ((login: string) => string) | undefined;\n linkedByIssue?: ReadonlyMap<number, readonly number[]> | undefined;\n}): BuildRequestView[] {\n const now = input.now ?? Date.now();\n const out: BuildRequestView[] = [];\n const claimed = new Set<number>();\n for (const issue of input.issues) {\n if (!isBuildRequestIssue(issue.labels)) continue;\n const extra = input.linkedByIssue?.get(issue.number) ?? [];\n const linked = input.pulls.filter((p) => closingIssueNumbers(p.body).includes(issue.number) || extra.includes(p.number));\n for (const p of linked) claimed.add(p.number);\n const r = parseBuildRequestIssue(issue.body);\n const component = r?.component ?? (issue.title.split(':')[0] ?? '').trim();\n const s = buildRequestStatus({ issue, linked }, now, input.nameOf);\n out.push({\n id: `issue-${issue.number}`,\n kind: 'issue',\n number: issue.number,\n url: issue.url,\n component,\n title: r?.title ?? stripSubject(issue.title, component),\n requestKind: r?.kind ?? null,\n ...s,\n requestedBy: r?.requestedBy ?? issue.author ?? null,\n jira: jiraKeyOfLabels(issue.labels),\n figmaUrl: r?.figma?.url ?? null,\n });\n }\n for (const p of input.pulls) {\n if (claimed.has(p.number)) continue;\n const l = pullNames(p);\n if (l.includes(EXPLORATION_LABEL)) continue;\n const o = parseFigmaOrigin(p.body);\n const fromFigmaDraft = l.includes(WAITING_FOR_CLAUDE_LABEL) || l.includes(DRAFTED_BY_CLAUDE_LABEL) || o?.route === 'claude-draft';\n if (!fromFigmaDraft || !(l.includes(FROM_FIGMA_LABEL) || o)) continue;\n const title = p.title ?? '';\n const component = o?.component ?? (title.includes(':') ? title.split(':')[0]!.trim() : ((p.headRef ?? '').split('/').pop() ?? ''));\n const s = buildRequestStatus({ pull: p }, now, input.nameOf);\n out.push({\n id: `pull-${p.number}`,\n kind: 'pull',\n number: p.number,\n url: p.url ?? '',\n component,\n title: stripSubject(title, component),\n requestKind: o?.kind ?? null,\n ...s,\n requestedBy: o?.requestedBy ?? p.author ?? null,\n jira: jiraKeyOfLabels(p.labels),\n figmaUrl: o?.url ?? null,\n });\n }\n return out.sort((a, b) => STATUS_ORDER[a.status] - STATUS_ORDER[b.status] || (a.status === 'shipped' ? String(b.shippedAt).localeCompare(String(a.shippedAt)) : a.createdAt.localeCompare(b.createdAt)));\n}\n\n/** The filters of the Being built page. */\nexport type BuildFilter = 'all' | 'waiting' | 'in-progress' | 'shipped-this-week';\n\nexport const BUILD_FILTER_LABEL: Record<BuildFilter, string> = {\n all: 'All',\n waiting: 'Waiting to be picked up',\n 'in-progress': 'In progress',\n 'shipped-this-week': 'Shipped this week',\n};\n\n/** Whether a build request shows under a filter. \"All\" leaves out what was closed as not planned more than a week ago. */\nexport function matchesBuildFilter(v: Pick<BuildRequestView, 'status' | 'shippedAt' | 'timeline'>, f: BuildFilter, now: Date | number = Date.now()): boolean {\n const nowMs = typeof now === 'number' ? now : now.getTime();\n const recent = (iso: string | null | undefined) => Boolean(iso) && nowMs - Date.parse(iso!) <= 7 * DAY;\n switch (f) {\n case 'waiting':\n return v.status === 'requested';\n case 'in-progress':\n return v.status === 'picked-up' || v.status === 'in-progress' || v.status === 'in-review';\n case 'shipped-this-week':\n return v.status === 'shipped' && recent(v.shippedAt);\n default:\n return v.status === 'not-planned' ? recent(v.timeline.find((e) => e.status === 'not-planned')?.at) : true;\n }\n}\n\n/** Build requests still open (not shipped, not closed). */\nexport const openBuildRequests = <V extends Pick<BuildRequestView, 'status'>>(views: readonly V[]): V[] => views.filter((v) => v.status !== 'shipped' && v.status !== 'not-planned');\n\n/** The calm summary line of the home: \"3 being built, 1 waiting to be picked up.\" Null when nothing is open. */\nexport function buildSummaryLine(views: readonly Pick<BuildRequestView, 'status' | 'stale'>[]): string | null {\n const open = openBuildRequests(views);\n if (!open.length) return null;\n const waiting = open.filter((v) => v.status === 'requested').length;\n const building = open.length - waiting;\n const parts = [...(building ? [`${building} being built`] : []), ...(waiting ? [`${waiting} waiting to be picked up`] : [])];\n return `${parts.join(', ')}.`.replace(/^./, (c) => c.toUpperCase());\n}\n\n/**\n * The Library component page line while build requests for a component are open: \"Figma is ahead: 2 changes being\n * built (Ana).\" Null when none is open (it disappears once shipped).\n */\nexport function figmaAheadLine(views: readonly Pick<BuildRequestView, 'component' | 'status' | 'builders'>[], component: string, nameOf: (login: string) => string = (l) => l): { count: number; builders: string[]; sentence: string } | null {\n const open = openBuildRequests(views).filter((v) => v.component.toLowerCase() === component.toLowerCase());\n if (!open.length) return null;\n const builders = [...new Set(open.flatMap((v) => v.builders))].map(nameOf);\n const n = open.length;\n return { count: n, builders, sentence: `Figma is ahead: ${n} change${n === 1 ? '' : 's'} being built${builders.length ? ` (${listNames(builders)})` : ''}.` };\n}\n\n/** \"Button: add a lg size\", the issue title of a build request (same rule as every request). */\nexport const buildRequestTitle = (r: Pick<BuildRequestInput, 'component' | 'title'>) => requestIssueTitle(r);\n","// Build requests and Figma token pushes on GitHub: file a build request, list build requests with their status (read\n// only: developers split and track the work in GitHub or Jira), and read where a shipped token push stands. Shared by\n// the Figma plugin, Studio, the MCP server and the CLI. The rules are in build-requests.ts.\n\nimport {\n BUILD_REQUEST_LABEL,\n assembleBuildRequests,\n composeBuildRequestIssue,\n libraryArrival,\n type BuildIssueLike,\n type BuildPullLike,\n type BuildRequestInput,\n type BuildRequestView,\n type LibraryArrival,\n type PublishOutcome,\n} from './build-requests';\nimport type { GitHubClient } from './github-client';\nimport { REQUEST_LABEL } from './requests';\nimport { summarizeApprovals, summarizeCi } from './review-gate';\n\n/**\n * Files a build request: one issue, labeled component-change (the bridge-jira Action mirrors it to Jira when set up),\n * bridge-build, the request kind and the source. `labels` and `assignees` come from integrations.requests. Returns the\n * outcome the plugin shows (\"Build request sent\").\n */\nexport async function createBuildRequestOnGitHub(\n gh: GitHubClient,\n input: BuildRequestInput,\n opts: { labels?: string[] | undefined; assignees?: string[] | undefined; componentUrl?: string | undefined } = {},\n): Promise<PublishOutcome> {\n const issue = composeBuildRequestIssue(input, opts);\n const created = await gh.createIssue({ title: issue.title, body: issue.body, labels: issue.labels, ...(issue.assignees.length ? { assignees: issue.assignees } : {}) });\n return { subject: { type: 'component', name: input.component }, route: 'build-request', ref: { kind: 'issue', number: created.number, url: created.url } };\n}\n\n/**\n * Every build request with its status, read from GitHub: the component-change and bridge-build issues, and the pull\n * requests that close them or are library branches from Figma. Two to three list calls, no per-item reads.\n */\nexport async function listBuildRequestsOnGitHub(gh: GitHubClient, opts: { now?: Date | number | undefined; nameOf?: ((login: string) => string) | undefined } = {}): Promise<BuildRequestView[]> {\n const [requests, builds, pulls] = await Promise.all([\n gh.listIssues({ label: REQUEST_LABEL, state: 'all', perPage: 100 }),\n gh.listIssues({ label: BUILD_REQUEST_LABEL, state: 'all', perPage: 100 }),\n gh.listPullRequests('all'),\n ]);\n const seen = new Set<number>();\n const issues: BuildIssueLike[] = [];\n for (const i of [...requests, ...builds]) {\n if (seen.has(i.number)) continue;\n seen.add(i.number);\n issues.push({ ...i, stateReason: i.stateReason, assignees: i.assignees ?? [], closedAt: i.closedAt ?? null });\n }\n const prs: BuildPullLike[] = pulls.map((p) => ({ ...p, assignees: p.assignees ?? [] }));\n return assembleBuildRequests({ issues, pulls: prs, now: opts.now, nameOf: opts.nameOf });\n}\n\n/**\n * Where a token push the plugin published as `shipped` stands: poll it until `final` (\"In the library\", or \"Held for a\n * developer\" / \"Not shipped\"). Reads the pull request, its checks and its reviews.\n */\nexport async function libraryArrivalOnGitHub(gh: GitHubClient, n: number): Promise<LibraryArrival> {\n const pr = await gh.getPullRequest(n);\n if (pr.state !== 'open') return libraryArrival({ state: pr.state, merged_at: pr.mergedAt ?? null });\n const [runs, statuses, reviews] = await Promise.all([\n gh.listCheckRuns(pr.headSha).catch(() => []),\n gh.listCommitStatuses(pr.headSha).catch(() => []),\n gh.listReviews(n).catch(() => []),\n ]);\n const ci = summarizeCi(\n runs.map((r) => ({ name: r.name, status: r.status, conclusion: r.conclusion })),\n statuses.map((s) => ({ context: s.context, state: s.state, description: s.description })),\n );\n const approvals = summarizeApprovals(\n reviews.map((r) => ({ user: r.user ? { login: r.user } : null, state: r.state, submitted_at: r.submittedAt ?? null })),\n { design: [], tech: [] },\n pr.author,\n );\n return libraryArrival({ state: pr.state, mergeable: pr.mergeable, ci, changesRequested: approvals.changesRequested.length });\n}\n"],"names":["issueKey","t","isAlias","p","modesOf","a","byName","idOf","key","names","cl","STEPS","isObj","text","cs","KINDS","at","line","valueIn","NOT_AN_AXIS","valuesOf","code","FIELD_WORDS","sameValue","first","dr","dg","db","dy","dx","lc","setNameOf","round","bl","resolve","cv","STATES","propsOf","h","plain","story","look","variants","fixesOf","problems","regressions","after","field","by","status","lifecycle","behindMain","preview","bg","el","ch","av","bv","shape","bd","ci"],"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,SAAY,GAAG,WAAW,MAAM,IAAI,CAAC;AAAA,IAC5E,KAAK;AACH,UAAI,MA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