@becket-ui/mcp 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-UWMYE5IA.js → chunk-I4QZIQ42.js} +1 -1
- package/dist/chunk-I4QZIQ42.js.map +1 -0
- package/dist/data/catalog.json +88 -12
- package/dist/{extractPDF-GMTNLU27.js → extractPDF-EMWJFZGY.js} +2 -2
- package/dist/extractPDF-EMWJFZGY.js.map +1 -0
- package/dist/server.js +2 -2
- package/dist/server.js.map +1 -1
- package/package.json +3 -3
- package/dist/chunk-UWMYE5IA.js.map +0 -1
- package/dist/extractPDF-GMTNLU27.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../tokens/theme/color.mjs","../../tokens/theme/contrast.mjs","../../tokens/theme/derive.mjs","../../tokens/theme/index.mjs","../src/theme/extractColors.ts"],"sourcesContent":["/** @param {number} value */\nconst clamp01 = (value) => Math.min(1, Math.max(0, value));\n\nfunction toLinear(channel) {\n return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4;\n}\n\nfunction linearToOklch([r, g, b]) {\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 a = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s;\n const bb = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s;\n const C = Math.hypot(a, bb);\n return {\n L: 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,\n C: C < 1e-4 ? 0 : C,\n // Grays have no meaningful hue; 0 keeps the output stable.\n h: C < 1e-4 ? 0 : ((Math.atan2(bb, a) * 180) / Math.PI + 360) % 360,\n };\n}\n\n// Unclamped: channels outside 0–1 mean out of gamut.\nfunction oklchToLinear({ L, C, h }) {\n const radians = (h * Math.PI) / 180;\n const a = C * Math.cos(radians);\n const b = C * Math.sin(radians);\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\nfunction number(part, scale = 1) {\n const value = part.trim();\n if (value === 'none') return 0;\n if (value.endsWith('%')) return (Number.parseFloat(value) / 100) * scale;\n return Number.parseFloat(value);\n}\n\n/**\n * Parse a CSS color (hex, rgb(), hsl(), oklch() or a basic color name) into OKLCH.\n * Alpha is ignored: Becket brand tokens are opaque.\n *\n * @param {string} input\n * @returns {{ L: number, C: number, h: number } | null} null when the format isn't supported\n */\nexport function parseColor(input) {\n if (typeof input !== 'string') return null;\n // CSS's basic color names, the ones logos and SVGs use. Rarer names aren't guessed.\n const value = (\n {\n black: '#000000',\n white: '#ffffff',\n red: '#ff0000',\n green: '#008000',\n blue: '#0000ff',\n yellow: '#ffff00',\n orange: '#ffa500',\n purple: '#800080',\n gray: '#808080',\n grey: '#808080',\n navy: '#000080',\n teal: '#008080',\n maroon: '#800000',\n olive: '#808000',\n lime: '#00ff00',\n aqua: '#00ffff',\n fuchsia: '#ff00ff',\n silver: '#c0c0c0',\n }[input.trim().toLowerCase()] ?? input\n ).trim();\n\n const hex = value.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i);\n if (hex) {\n return linearToOklch(\n // #abc → #aabbcc; the first three pairs are r, g, b (alpha is dropped).\n (hex[1].length <= 4 ? [...hex[1]].map((digit) => digit + digit).join('') : hex[1])\n .match(/../g)\n .slice(0, 3)\n .map((pair) => toLinear(Number.parseInt(pair, 16) / 255)),\n );\n }\n\n const fn = value.match(/^(rgba?|hsla?|oklch)\\(\\s*([^)]*)\\)$/i);\n if (!fn) return null;\n const kind = fn[1].toLowerCase();\n // `1 2 3 / 0.5` or `1, 2, 3, 0.5`: three channels, alpha dropped.\n const withoutAlpha = fn[2].split('/')[0];\n const parts = (\n withoutAlpha.includes(',') ? withoutAlpha.split(',') : withoutAlpha.trim().split(/\\s+/)\n ).slice(0, 3);\n if (parts.length !== 3) return null;\n\n if (kind.startsWith('rgb')) {\n const rgb = parts.map((part) => clamp01(number(part, 255) / 255));\n if (rgb.some(Number.isNaN)) return null;\n return linearToOklch(rgb.map(toLinear));\n }\n if (kind.startsWith('hsl')) {\n const hue = Number.parseFloat(parts[0]);\n const saturation = clamp01(number(parts[1]));\n const lightness = clamp01(number(parts[2]));\n if ([hue, saturation, lightness].some(Number.isNaN)) return null;\n // CSS Color 4 hsl() → sRGB.\n const chroma = (1 - Math.abs(2 * lightness - 1)) * saturation;\n const sector = (((hue % 360) + 360) % 360) / 60;\n const x = chroma * (1 - Math.abs((sector % 2) - 1));\n const [r, g, b] = [\n [chroma, x, 0],\n [x, chroma, 0],\n [0, chroma, x],\n [0, x, chroma],\n [x, 0, chroma],\n [chroma, 0, x],\n ][Math.min(5, Math.floor(sector))];\n const offset = lightness - chroma / 2;\n return linearToOklch([r + offset, g + offset, b + offset].map(toLinear));\n }\n const [L, C, h] = [number(parts[0]), number(parts[1], 0.4), number(parts[2])];\n if ([L, C, h].some(Number.isNaN)) return null;\n return { L: clamp01(L), C: Math.max(0, C), h: ((h % 360) + 360) % 360 };\n}\n\n/**\n * Bring a color into sRGB by lowering chroma only, keeping lightness and hue. That keeps\n * contrast predictable, which matters more here than keeping saturation.\n *\n * @param {{ L: number, C: number, h: number }} color\n */\nexport function toGamut(color) {\n // In gamut: every linear channel within 0–1, give or take float noise.\n if (oklchToLinear(color).every((channel) => channel >= -1e-4 && channel <= 1 + 1e-4))\n return color;\n let [low, high] = [0, color.C];\n for (let step = 0; step < 24; step += 1) {\n const middle = (low + high) / 2;\n if (\n oklchToLinear({ ...color, C: middle }).every(\n (channel) => channel >= -1e-4 && channel <= 1 + 1e-4,\n )\n )\n low = middle;\n else high = middle;\n }\n return { ...color, C: low };\n}\n\n/** @param {{ L: number, C: number, h: number }} color */\nexport function formatOklch({ L, C, h }) {\n const round = (value, digits) => Number(value.toFixed(digits));\n return `oklch(${round(L, 4)} ${round(C, 4)} ${round(C === 0 ? 0 : h, 2)})`;\n}\n\n/** @param {{ L: number, C: number, h: number }} color */\nexport function formatHex(color) {\n return `#${oklchToLinear(toGamut(color))\n .map((linear) => {\n const channel = clamp01(linear);\n // Linear light → sRGB channel (the inverse of toLinear).\n return Math.round(\n clamp01(channel <= 0.0031308 ? channel * 12.92 : 1.055 * channel ** (1 / 2.4) - 0.055) *\n 255,\n )\n .toString(16)\n .padStart(2, '0');\n })\n .join('')}`;\n}\n\n/**\n * WCAG 2 contrast ratio between two colors (CSS strings or parsed OKLCH), 1–21. Channels are\n * clamped to sRGB first, as a browser would display them.\n *\n * @param {string | { L: number, C: number, h: number }} foreground\n * @param {string | { L: number, C: number, h: number }} background\n */\nexport function contrastRatio(foreground, background) {\n const [first, second] = [foreground, background].map((color) => {\n const parsed = typeof color === 'string' ? parseColor(color) : color;\n if (!parsed)\n throw new Error(`Can't read the color \"${color}\". Use hex, rgb(), hsl() or oklch().`);\n const [r, g, b] = oklchToLinear(parsed).map(clamp01);\n return 0.2126 * r + 0.7152 * g + 0.0722 * b;\n });\n const [high, low] = first > second ? [first, second] : [second, first];\n return (high + 0.05) / (low + 0.05);\n}\n\n/**\n * Perceptual distance (ΔE OK, Euclidean in OKLab). Around 0.02 is a just-noticeable difference.\n *\n * @param {{ L: number, C: number, h: number }} first\n * @param {{ L: number, C: number, h: number }} second\n */\nexport function colorDistance(first, second) {\n const [a, b] = [first, second].map(({ L, C, h }) => [\n L,\n C * Math.cos((h * Math.PI) / 180),\n C * Math.sin((h * Math.PI) / 180),\n ]);\n return Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);\n}\n\n/**\n * The OKLCH color for an sRGB triplet (0–255). Used by image decoders.\n *\n * @param {[number, number, number]} rgb\n */\nexport function rgbToOklch(rgb) {\n return linearToOklch(rgb.map((channel) => toLinear(channel / 255)));\n}\n","import { contrastRatio, formatOklch, parseColor } from './color.mjs';\n\n/**\n * Default color tokens as index.css declares them. `{key}` is a reference to another token, so\n * a theme that changes `primary` also moves `link`. contrast.test.mjs asserts these match\n * index.css, so they can't drift.\n */\nexport const defaultColors = {\n dark: {\n primary: 'oklch(0.75 0.15 78)',\n secondary: 'oklch(0.70 0.13 125)',\n tertiary: 'oklch(0.60 0.16 48)',\n // index.css: color-mix(in oklch, primary 88%, white)\n primaryHover: { mixWithWhite: 'primary', amount: 0.88 },\n 'neutral.50': 'oklch(0.96 0.012 78)',\n 'neutral.100': 'oklch(0.94 0.012 78)',\n 'neutral.200': 'oklch(0.89 0.012 75)',\n 'neutral.300': 'oklch(0.84 0.012 72)',\n 'neutral.400': 'oklch(0.75 0.012 70)',\n 'neutral.500': 'oklch(0.65 0.012 65)',\n 'neutral.600': 'oklch(0.55 0.014 62)',\n 'neutral.700': 'oklch(0.45 0.014 60)',\n 'neutral.800': 'oklch(0.35 0.015 60)',\n 'neutral.900': 'oklch(0.22 0.015 60)',\n white: 'oklch(99% 0 0)',\n background: '{neutral.900}',\n text: '{neutral.50}',\n muted: '{neutral.300}',\n surface: '{neutral.800}',\n border: '{neutral.200}',\n danger: 'oklch(0.76 0.16 25)',\n accent: 'oklch(0.86 0.12 125)',\n link: '{primary}',\n linkHover: 'oklch(0.78 0.13 78)',\n linkVisited: 'oklch(0.72 0.12 125)',\n warning: 'oklch(0.72 0.16 42)',\n success: 'oklch(0.68 0.14 165)',\n },\n /** Only what `[data-theme='light']` changes; the rest is inherited from dark. */\n light: {\n background: '{neutral.50}',\n text: '{neutral.900}',\n muted: 'oklch(0.53 0.014 62)',\n surface: '{white}',\n danger: 'oklch(0.48 0.20 25)',\n accent: 'oklch(0.38 0.14 125)',\n link: 'oklch(0.54 0.12 70)',\n linkHover: 'oklch(0.46 0.11 70)',\n linkVisited: 'oklch(0.52 0.09 125)',\n },\n};\n\nconst text = 4.5;\nconst canvases = ['background', 'surface'];\n\n/**\n * Every pair Becket draws. `required` pairs pass in the default theme and must pass in any\n * theme. `advisory` pairs fail in the default theme too (see their `note`), so they're\n * reported, not enforced, until Becket's recipes change.\n */\nexport const contrastPairs = [\n ...['text', 'muted', 'link', 'linkHover', 'linkVisited', 'danger', 'accent'].flatMap(\n (foreground) =>\n canvases.map((background) => ({\n foreground,\n background,\n minimum: text,\n level: 'required',\n use: `${foreground} text on ${background}`,\n })),\n ),\n ...['primary', 'primaryHover', 'secondary'].map((background) => ({\n foreground: 'neutral.900',\n background,\n minimum: text,\n level: 'required',\n use: `label on a filled ${background} control`,\n })),\n {\n foreground: 'neutral.900',\n background: 'tertiary',\n minimum: text,\n level: 'advisory',\n use: 'label over the tertiary end of a gradient fill',\n note: 'The default tertiary is 4.13:1; the label mostly sits over the primary half.',\n },\n ...canvases.map((background) => ({\n foreground: 'primary',\n background,\n // Non-text UI and state indicators (WCAG 1.4.11).\n minimum: 3,\n level: 'advisory',\n use: `focus ring and checked controls on ${background}`,\n note: 'A primary light enough for dark labels is usually too light for 3:1 on a near-white canvas; the default is 2.02:1 in light.',\n })),\n];\n\n/**\n * Final colors in both themes for a theme config, as OKLCH.\n *\n * Mirrors the CSS that `defineBecketTheme` emits: its `:root` block is unlayered, so it beats\n * index.css's layered light block too. A plain string (or a `{ dark }` value) therefore applies\n * in light as well, unless the config also gives `light`.\n *\n * @param {import('./index.d.ts').BecketTheme} [theme]\n */\nexport function resolveBecketColors(theme = {}) {\n const root = {};\n const lightOnly = {};\n for (const [key, value] of Object.entries(theme.colors ?? {})) {\n if (value == null) continue;\n if (key === 'neutral') {\n for (const [step, color] of Object.entries(value)) root[`neutral.${step}`] = color;\n } else if (typeof value === 'object') {\n if (value.dark) root[key] = value.dark;\n if (value.light) lightOnly[key] = value.light;\n } else {\n root[key] = value;\n }\n }\n const [dark, light] = [\n { ...defaultColors.dark, ...root },\n { ...defaultColors.dark, ...defaultColors.light, ...root, ...lightOnly },\n ].map((table) => {\n const resolved = {};\n const resolve = (key, depth = 0) => {\n if (resolved[key]) return resolved[key];\n if (depth > 8) throw new Error(`Color token \"${key}\" refers to itself`);\n const value = table[key];\n if (value == null) throw new Error(`Unknown color token \"${key}\"`);\n let color;\n if (typeof value === 'object') {\n const base = resolve(value.mixWithWhite, depth + 1);\n // color-mix(in oklch, base n%, white): white has no hue, so the hue stays the base's.\n color = {\n L: base.L * value.amount + (1 - value.amount),\n C: base.C * value.amount,\n h: base.h,\n };\n } else {\n const reference = value.match(/^\\{([\\w.]+)\\}$/);\n color = reference ? resolve(reference[1], depth + 1) : parseColor(value);\n if (!color)\n throw new Error(`Can't read colors.${key} \"${value}\". Use hex, rgb(), hsl() or oklch().`);\n }\n resolved[key] = color;\n return color;\n };\n for (const key of Object.keys(table)) resolve(key);\n return resolved;\n });\n return { dark, light };\n}\n\n/**\n * WCAG 2.2 AA contrast for every pair in contrastPairs, in dark and light.\n *\n * @param {import('./index.d.ts').BecketTheme} [theme]\n * @returns {import('./index.d.ts').BecketContrastReport}\n */\nexport function checkBecketThemeContrast(theme = {}) {\n const colors = resolveBecketColors(theme);\n const results = ['dark', 'light'].flatMap((mode) =>\n contrastPairs.map((pair) => {\n const ratio = contrastRatio(colors[mode][pair.foreground], colors[mode][pair.background]);\n return {\n ...pair,\n theme: mode,\n ratio: Math.floor(ratio * 100) / 100,\n passes: ratio >= pair.minimum,\n foregroundColor: formatOklch(colors[mode][pair.foreground]),\n backgroundColor: formatOklch(colors[mode][pair.background]),\n };\n }),\n );\n return {\n passes: results.every((result) => result.passes || result.level === 'advisory'),\n failures: results.filter((result) => !result.passes && result.level === 'required'),\n advisories: results.filter((result) => !result.passes && result.level === 'advisory'),\n results,\n };\n}\n","import { contrastRatio, formatOklch, parseColor, toGamut } from './color.mjs';\nimport { checkBecketThemeContrast, resolveBecketColors } from './contrast.mjs';\n\n// Aim slightly above 4.5:1 so values rounded for CSS still pass.\nconst textTarget = 4.6;\n\nfunction fitLightness({ color, against, minimum, direction }) {\n for (let L = color.L; L >= 0 && L <= 1; L += direction === 'lighter' ? 0.005 : -0.005) {\n const candidate = toGamut({ ...color, L });\n if (against.every((other) => contrastRatio(candidate, other) >= minimum)) return candidate;\n }\n return null;\n}\n\nfunction describe(color) {\n return `L ${color.L.toFixed(2)}`;\n}\n\n/**\n * @param {import('./index.d.ts').DeriveBecketThemeInput} input\n * @returns {import('./index.d.ts').DerivedBecketTheme}\n */\nexport function deriveBecketTheme({ brand, pinned = {} }) {\n if (!Array.isArray(brand) || brand.length === 0 || brand.length > 3) {\n throw new Error('Pass one to three brand colors, most important first.');\n }\n const seeds = brand.map((value) => {\n const color = parseColor(value);\n if (!color)\n throw new Error(`Can't read the brand color \"${value}\". Use hex, rgb(), hsl() or oklch().`);\n return color;\n });\n const [primarySeed] = seeds;\n // With fewer than three colors, follow the default theme's shape: secondary is the brand hue\n // turned ~45° and tertiary ~30° the other way, at the same lightness and chroma.\n const secondarySeed = seeds[1] ?? { ...primarySeed, h: (primarySeed.h + 45) % 360 };\n\n const notes = [];\n const colors = {};\n const note = (token, reason) => notes.push({ token, reason });\n\n // A whisper of the brand hue in the grays, like the default theme's warm neutrals. Below 0.012\n // the tint is invisible; above it grays start to read as a color.\n const tint = primarySeed.C < 0.02 ? 0 : 0.012;\n colors.neutral = Object.fromEntries(\n // The default theme's lightness ladder, so text and canvases keep their contrast.\n Object.entries({\n 50: 0.96,\n 100: 0.94,\n 200: 0.89,\n 300: 0.84,\n 400: 0.75,\n 500: 0.65,\n 600: 0.55,\n 700: 0.45,\n 800: 0.35,\n 900: 0.22,\n }).map(([step, L]) => [step, formatOklch({ L, C: tint, h: tint ? primarySeed.h : 0 })]),\n );\n colors.muted = { light: formatOklch({ L: 0.53, C: tint, h: tint ? primarySeed.h : 0 }) };\n note(\n 'neutral',\n tint\n ? `Grays tinted toward the brand hue (${primarySeed.h.toFixed(0)}°), lightness unchanged.`\n : 'The brand is near-gray, so neutrals stay untinted.',\n );\n\n // Fit everything against the canvases the user will actually see, pinned ones included.\n const canvases = resolveBecketColors({ colors: { ...colors, ...pinned } });\n const dark = [canvases.dark.background, canvases.dark.surface];\n const light = [canvases.light.background, canvases.light.surface];\n\n const fill = ({ token, seed, label }) => {\n const fitted = fitLightness({\n color: seed,\n // Filled controls put neutral.900 labels on the brand color.\n against: [canvases.dark['neutral.900']],\n minimum: textTarget,\n direction: 'lighter',\n });\n colors[token] = formatOklch(fitted);\n if (fitted.L !== seed.L)\n note(\n token,\n `${label} lightened from ${describe(seed)} to ${describe(fitted)} so dark button labels reach 4.5:1.`,\n );\n else note(token, `${label} used as is.`);\n };\n fill({ token: 'primary', seed: primarySeed, label: 'Brand color 1' });\n fill({\n token: 'secondary',\n seed: secondarySeed,\n label: seeds[1] ? 'Brand color 2' : 'Derived from brand color 1 (hue +45°)',\n });\n fill({\n token: 'tertiary',\n seed: seeds[2] ?? { ...primarySeed, h: (primarySeed.h + 330) % 360 },\n label: seeds[2] ? 'Brand color 3' : 'Derived from brand color 1 (hue −30°)',\n });\n\n const onCanvas = ({ token, seed, label }) => {\n const darkFit = fitLightness({\n color: seed,\n against: dark,\n minimum: textTarget,\n direction: 'lighter',\n });\n const lightFit = fitLightness({\n color: seed,\n against: light,\n minimum: textTarget,\n direction: 'darker',\n });\n if (!darkFit || !lightFit) {\n note(\n token,\n `${label} can't reach 4.5:1 on your pinned canvas in ${darkFit ? 'light' : 'dark'}; left at the Becket default.`,\n );\n return null;\n }\n colors[token] = { dark: formatOklch(darkFit), light: formatOklch(lightFit) };\n const exact = [darkFit.L === seed.L && 'dark', lightFit.L === seed.L && 'light'].filter(\n Boolean,\n );\n note(\n token,\n exact.length === 2\n ? `${label} used as is in both themes.`\n : exact.length === 1\n ? `${label} used as is in ${exact[0]}; a ${exact[0] === 'dark' ? 'darker' : 'lighter'} shade (${describe(exact[0] === 'dark' ? lightFit : darkFit)}) in ${exact[0] === 'dark' ? 'light' : 'dark'} for 4.5:1 on the canvas.`\n : `${label} shaded per theme (dark ${describe(darkFit)}, light ${describe(lightFit)}) for 4.5:1 on the canvas.`,\n );\n return { dark: darkFit, light: lightFit };\n };\n const link = onCanvas({ token: 'link', seed: primarySeed, label: 'Brand color 1' });\n onCanvas({\n token: 'linkVisited',\n seed: secondarySeed,\n label: seeds[1] ? 'Brand color 2' : 'The derived secondary',\n });\n onCanvas({\n token: 'accent',\n seed: secondarySeed,\n label: seeds[1] ? 'Brand color 2' : 'The derived secondary',\n });\n if (link) {\n // Hover moves away from the canvas, so it keeps (and gains) contrast.\n colors.linkHover = {\n dark: formatOklch(toGamut({ ...link.dark, L: Math.min(1, link.dark.L + 0.06) })),\n light: formatOklch(\n fitLightness({\n color: { ...link.light, L: Math.max(0, link.light.L - 0.08) },\n against: light,\n minimum: textTarget,\n direction: 'darker',\n }),\n ),\n };\n note('linkHover', 'The link color a step lighter on dark and a step darker on light.');\n }\n\n // Body text only moves when a pinned canvas breaks it; otherwise the neutral ladder already passes.\n for (const token of ['text', 'muted']) {\n if (pinned[token]) continue;\n const current = resolveBecketColors({ colors: { ...colors, ...pinned } });\n const darkFit = fitLightness({\n color: current.dark[token],\n against: dark,\n minimum: textTarget,\n direction: 'lighter',\n });\n const lightFit = fitLightness({\n color: current.light[token],\n against: light,\n minimum: textTarget,\n direction: 'darker',\n });\n if (darkFit.L === current.dark[token].L && lightFit.L === current.light[token].L) continue;\n colors[token] = { dark: formatOklch(darkFit), light: formatOklch(lightFit) };\n note(token, 'Adjusted so it stays at 4.5:1 on your pinned canvas.');\n }\n\n // Within 20° of Becket's danger hue (25°).\n const fromDanger = Math.abs(primarySeed.h - 25);\n if (primarySeed.C >= 0.08 && Math.min(fromDanger, 360 - fromDanger) < 20) {\n note(\n 'danger',\n 'Your brand is red, like error text. Danger stays Becket red; make sure errors also carry an icon or text, not color alone.',\n );\n }\n\n for (const [token, value] of Object.entries(pinned)) {\n if (token === 'neutral') colors.neutral = { ...colors.neutral, ...value };\n else colors[token] = value;\n note(token, 'Pinned by you, kept exactly.');\n }\n\n const theme = { colors };\n return { theme, notes, contrast: checkBecketThemeContrast(theme) };\n}\n","export { colorDistance, contrastRatio, formatHex, formatOklch, parseColor, rgbToOklch, toGamut } from './color.mjs';\nexport { contrastPairs, checkBecketThemeContrast, resolveBecketColors } from './contrast.mjs';\nexport { deriveBecketTheme } from './derive.mjs';\n\nconst PREFIX = '--beckui--';\n\nconst COLOR_FLAT = [\n 'primary',\n 'secondary',\n 'tertiary',\n 'primaryHover',\n 'lightBackground',\n 'lightText',\n 'warning',\n 'success',\n];\n\nconst COLOR_THEMED = [\n 'background',\n 'text',\n 'muted',\n 'border',\n 'danger',\n 'accent',\n 'surface',\n 'link',\n 'linkHover',\n 'linkVisited',\n];\nconst NEUTRAL_STEPS = ['50', '100', '200', '300', '400', '500', '600', '700', '800', '900'];\nconst RADII = ['none', 'sm', 'md', 'lg', 'xl', 'full'];\n// `base` rescales the whole type scale; the steps are ratios of it.\nconst FONT_SIZES = ['base', 'xs', 'sm', 'md', 'lg', 'xl', '2xl', '3xl', '4xl', '5xl', '6xl'];\n// `unit` rescales every Fibonacci spacing and size step; `textUnit` the em-based text spacing.\nconst SPACING = ['unit', 'textUnit', 'xs', 'sm', 'md', 'lg', 'xl'];\nconst FONTS = ['sans', 'mono'];\nconst DENSITY_SIZES = {\n button: ['sm', 'md'],\n field: ['sm', 'md', 'lg'],\n tag: ['sm', 'md', 'lg'],\n};\n\nfunction kebab(value) {\n return value.replace(/[A-Z]/g, (char) => `-${char.toLowerCase()}`);\n}\n\nfunction cssVar(parts) {\n return `${PREFIX}${parts.map(kebab).join('-')}`;\n}\n\nfunction assertAllowedKeys(object, allowed, label) {\n for (const key of Object.keys(object)) {\n if (!allowed.includes(key)) {\n throw new Error(`Unknown Becket theme key \"${label}.${key}\"`);\n }\n }\n}\n\nfunction pushDecl(decls, name, value) {\n if (value == null || value === '') return;\n decls.push(` ${name}: ${value};`);\n}\n\nfunction pushThemed(rootDecls, lightDecls, name, value) {\n if (value == null || value === '') return;\n if (typeof value === 'object') {\n if (value.dark) pushDecl(rootDecls, name, value.dark);\n if (value.light) pushDecl(lightDecls, name, value.light);\n return;\n }\n pushDecl(rootDecls, name, value);\n}\n\nfunction colorDecls(colors, rootDecls, lightDecls) {\n assertAllowedKeys(colors, [...COLOR_FLAT, ...COLOR_THEMED, 'neutral'], 'colors');\n\n for (const key of COLOR_FLAT) {\n const value = colors[key];\n if (value == null) continue;\n if (typeof value === 'object') {\n throw new Error(`colors.${key} must be a CSS color string`);\n }\n pushDecl(rootDecls, cssVar(['colors', key]), value);\n }\n\n for (const key of COLOR_THEMED) {\n pushThemed(rootDecls, lightDecls, cssVar(['colors', key]), colors[key]);\n }\n\n if (colors.neutral) {\n assertAllowedKeys(colors.neutral, NEUTRAL_STEPS, 'colors.neutral');\n for (const step of NEUTRAL_STEPS) {\n pushDecl(rootDecls, cssVar(['colors', 'neutral', step]), colors.neutral[step]);\n }\n }\n}\n\nfunction densityDecls(density, decls) {\n assertAllowedKeys(density, ['button', 'field', 'tag'], 'density');\n for (const component of Object.keys(DENSITY_SIZES)) {\n const sizes = density[component];\n if (!sizes) continue;\n const allowed = DENSITY_SIZES[component];\n assertAllowedKeys(sizes, allowed, `density.${component}`);\n for (const size of allowed) {\n const box = sizes[size];\n if (!box) continue;\n assertAllowedKeys(box, ['px', 'py'], `density.${component}.${size}`);\n if (box.px) decls.push(` --beckui-${component}-px-${size}: ${box.px};`);\n if (box.py) decls.push(` --beckui-${component}-py-${size}: ${box.py};`);\n }\n }\n}\n\nfunction sheet(selector, decls) {\n if (!decls.length) return '';\n return `${selector} {\\n${decls.join('\\n')}\\n}\\n`;\n}\n\n/**\n * Emit unlayered `:root` / `html[data-theme='light']` overrides. Import or\n * inject **after** `@becket-ui/tokens/index.css` so these win over `@layer tokens`.\n *\n * @param {import('./index.d.ts').BecketTheme} config\n * @returns {string}\n */\nexport function defineBecketTheme(config = {}) {\n assertAllowedKeys(\n config,\n ['colors', 'radii', 'fontSizes', 'spacing', 'sizes', 'fonts', 'density'],\n 'theme',\n );\n\n const rootDecls = [];\n const lightDecls = [];\n\n if (config.colors) colorDecls(config.colors, rootDecls, lightDecls);\n\n if (config.radii) {\n assertAllowedKeys(config.radii, RADII, 'radii');\n for (const key of RADII) {\n pushDecl(rootDecls, cssVar(['radii', key]), config.radii[key]);\n }\n }\n\n if (config.fontSizes) {\n assertAllowedKeys(config.fontSizes, FONT_SIZES, 'fontSizes');\n for (const key of FONT_SIZES) {\n pushDecl(rootDecls, cssVar(['font-sizes', key]), config.fontSizes[key]);\n }\n }\n\n if (config.spacing) {\n assertAllowedKeys(config.spacing, SPACING, 'spacing');\n for (const key of SPACING) {\n pushDecl(rootDecls, cssVar(['spacing', key]), config.spacing[key]);\n }\n }\n\n if (config.sizes) {\n assertAllowedKeys(config.sizes, ['field'], 'sizes');\n pushDecl(rootDecls, cssVar(['sizes', 'field']), config.sizes.field);\n }\n\n if (config.fonts) {\n assertAllowedKeys(config.fonts, FONTS, 'fonts');\n for (const key of FONTS) {\n pushDecl(rootDecls, cssVar(['fonts', key]), config.fonts[key]);\n }\n }\n\n if (config.density) densityDecls(config.density, rootDecls);\n\n const css = `${sheet(':root', rootDecls)}${sheet(\"html[data-theme='light']\", lightDecls)}`;\n if (!css) {\n return '/* defineBecketTheme: empty config, Becket defaults unchanged */\\n';\n }\n return css;\n}\n\nexport const BECKET_PUBLIC_COLOR_KEYS = [...COLOR_FLAT, ...COLOR_THEMED];\nexport const BECKET_PUBLIC_NEUTRAL_STEPS = NEUTRAL_STEPS;\n","import {\n colorDistance,\n formatHex,\n parseColor,\n rgbToOklch,\n type Oklch,\n} from '@becket-ui/tokens/theme';\nimport jpeg from 'jpeg-js';\nimport { PNG } from 'pngjs';\n\nimport type { Source } from './loadSource';\n\nexport type ColorRole = 'background' | 'neutral' | 'brand';\nexport type ExtractedColor = { hex: string; color: Oklch; share: number; role: ColorRole };\n\n// Decompression bombs: a tiny PNG can claim gigapixels. Real logos and manual pages are far below.\nconst maxPixels = 50_000_000;\n// Colors closer than this (ΔE OK) are one color: anti-aliasing, JPEG noise, gradients' near steps.\nconst sameColor = 0.05;\n// Below this chroma a color reads as white, gray or black.\nexport const neutralChroma = 0.04;\n\n// A color that keeps touching the image's edges is the background: logos have padding, photos\n// behind them touch every edge.\nexport function colorsFromPixels({\n width,\n height,\n data,\n}: {\n width: number;\n height: number;\n data: Uint8Array;\n}): ExtractedColor[] {\n // Sample at most ~160k pixels: plenty for a palette, and fast on a 2000×2000 logo.\n const step = Math.max(1, Math.floor(Math.sqrt((width * height) / 160_000)));\n const border = Math.max(1, Math.round(Math.min(width, height) * 0.02));\n const bins = new Map<number, { count: number; edge: number; r: number; g: number; b: number }>();\n let opaque = 0;\n let edgeSamples = 0;\n\n for (let y = 0; y < height; y += step) {\n for (let x = 0; x < width; x += step) {\n const offset = (y * width + x) * 4;\n if (data[offset + 3] < 128) continue;\n const [r, g, b] = [data[offset], data[offset + 1], data[offset + 2]];\n const key = ((r >> 3) << 10) | ((g >> 3) << 5) | (b >> 3);\n const isEdge = x < border || y < border || x >= width - border || y >= height - border;\n const bin = bins.get(key) ?? { count: 0, edge: 0, r: 0, g: 0, b: 0 };\n bin.count += 1;\n bin.r += r;\n bin.g += g;\n bin.b += b;\n if (isEdge) bin.edge += 1;\n bins.set(key, bin);\n opaque += 1;\n if (isEdge) edgeSamples += 1;\n }\n }\n if (opaque === 0) return [];\n\n const clusters: { count: number; edge: number; color: Oklch }[] = [];\n for (const bin of [...bins.values()].toSorted((a, b) => b.count - a.count)) {\n const color = rgbToOklch([bin.r / bin.count, bin.g / bin.count, bin.b / bin.count]);\n const home = clusters.find((cluster) => colorDistance(cluster.color, color) < sameColor);\n if (home) {\n home.count += bin.count;\n home.edge += bin.edge;\n continue;\n }\n if (clusters.length < 64) clusters.push({ count: bin.count, edge: bin.edge, color });\n }\n\n return (\n clusters\n // Under 0.5% is anti-aliasing or a stray pixel.\n .filter((cluster) => cluster.count / opaque >= 0.005)\n .map((cluster): ExtractedColor => ({\n hex: formatHex(cluster.color),\n color: cluster.color,\n share: cluster.count / opaque,\n // The background touches the edges at least half as often as the average opaque pixel,\n // and covers 5% or more of the edge.\n role:\n edgeSamples > 0 &&\n cluster.edge / cluster.count >= (edgeSamples / opaque) * 0.5 &&\n cluster.edge / edgeSamples >= 0.05\n ? 'background'\n : cluster.color.C < neutralChroma\n ? 'neutral'\n : 'brand',\n }))\n .toSorted((a, b) => b.share - a.share)\n );\n}\n\nexport function mergeClose(colors: ExtractedColor[]): ExtractedColor[] {\n const merged: ExtractedColor[] = [];\n for (const color of colors.toSorted((a, b) => b.share - a.share)) {\n const home = merged.find(\n (each) => each.role === color.role && colorDistance(each.color, color.color) < sameColor,\n );\n if (home) home.share += color.share;\n else merged.push({ ...color });\n }\n return merged;\n}\n\nexport function extractImageColors(source: Source): {\n colors: ExtractedColor[];\n method: string;\n skipped: string[];\n} {\n if (source.kind === 'png') {\n // The header's size, read before decoding: decompression bombs claim gigapixels in a tiny file.\n const [width, height] = [source.bytes.readUInt32BE(16), source.bytes.readUInt32BE(20)];\n if (width * height > maxPixels)\n throw new Error(`The PNG is ${width}×${height}; the limit is ${maxPixels / 1e6} megapixels.`);\n return {\n colors: colorsFromPixels(PNG.sync.read(source.bytes)),\n method: 'PNG pixels',\n skipped: [],\n };\n }\n if (source.kind === 'jpeg') {\n return {\n colors: colorsFromPixels(\n jpeg.decode(source.bytes, {\n useTArray: true,\n formatAsRGBA: true,\n maxResolutionInMP: maxPixels / 1e6,\n maxMemoryUsageInMB: 1024,\n }),\n ),\n method: 'JPEG pixels',\n skipped: [],\n };\n }\n if (source.kind === 'svg') {\n // Colors the SVG declares (fill, stroke, stop-color, color, in attributes and CSS), weighted by\n // how often each appears. The SVG is read as text: nothing renders, runs or loads.\n const svg = source.bytes.toString('utf8');\n const counts = new Map<string, { color: Oklch; count: number }>();\n const skippedValues = new Set<string>();\n for (const [, , raw] of svg.matchAll(\n /(?:^|[\\s;\"'{])(fill|stroke|stop-color|color|flood-color)\\s*(?:=\\s*[\"']|:\\s*)([^\"';}>]+)/gi,\n )) {\n const value = raw.trim().replace(/\\s*!important$/, '');\n const lower = value.toLowerCase();\n if (\n ['none', 'currentcolor', 'transparent', 'inherit', 'initial', 'unset'].includes(lower) ||\n lower.startsWith('url(') ||\n lower.startsWith('var(')\n )\n continue;\n // parseColor knows the basic color names; rarer ones are reported as skipped, not guessed.\n const color = parseColor(value);\n if (!color) {\n skippedValues.add(value);\n continue;\n }\n const hex = formatHex(color);\n const entry = counts.get(hex) ?? { color, count: 0 };\n entry.count += 1;\n counts.set(hex, entry);\n }\n const embedded = [...svg.matchAll(/data:image\\/(?:png|jpeg);base64,([A-Za-z0-9+/=\\s]+)/g)].map(\n ([, data]) => Buffer.from(data.replace(/\\s+/g, ''), 'base64'),\n );\n // Summed once here, not per color inside the map below.\n const total = [...counts.values()].reduce((sum, entry) => sum + entry.count, 0);\n return {\n colors: mergeClose([\n ...[...counts.entries()].map(([hex, entry]): ExtractedColor => ({\n hex,\n color: entry.color,\n share: entry.count / total,\n role: entry.color.C < neutralChroma ? 'neutral' : 'brand',\n })),\n ...embedded.flatMap((bytes) => {\n try {\n return extractImageColors({\n bytes,\n kind: bytes[0] === 0x89 ? 'png' : 'jpeg',\n label: source.label,\n }).colors.map((color) => ({ ...color, share: color.share / embedded.length }));\n } catch {\n // A broken embedded image doesn't hide the colors the SVG declares.\n return [];\n }\n }),\n ]),\n method: embedded.length\n ? 'SVG colors and embedded images (by how often each color is used, not by area)'\n : 'SVG colors (by how often each is used, not by area)',\n skipped: [...skippedValues],\n };\n }\n if (source.kind === 'webp' || source.kind === 'gif') {\n throw new Error(\n `${source.kind.toUpperCase()} isn't supported yet. Export the logo as SVG or PNG, or tell me its colors.`,\n );\n }\n throw new Error(\"That isn't a PNG, JPEG,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MACD,QAAQ,SAAS,SACb,kFACA;AAAA,MACJ,SAAS,CAAC,GAAG,aAAa;AAAA,IAC5B;AAAA,EACF;AACA,MAAI,OAAO,SAAS,UAAU,OAAO,SAAS,OAAO;AACnD,UAAM,IAAI;AAAA,MACR,GAAG,OAAO,KAAK,YAAY,CAAC;AAAA,IAC9B;AAAA,EACF;AACA,QAAM,IAAI,MAAM,0CAA0C;AAC5D;","names":["canvases"]}
|
package/dist/data/catalog.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"package": "@becket-ui/react",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
4
4
|
"components": [
|
|
5
5
|
{
|
|
6
6
|
"name": "Button",
|
|
@@ -49,6 +49,10 @@
|
|
|
49
49
|
"name": "Default",
|
|
50
50
|
"code": "export const Default: Story = {};"
|
|
51
51
|
},
|
|
52
|
+
{
|
|
53
|
+
"name": "ForcedColors",
|
|
54
|
+
"code": "export const ForcedColors: Story = { ...Default, parameters: { forcedColors: true } };"
|
|
55
|
+
},
|
|
52
56
|
{
|
|
53
57
|
"name": "WithGradient",
|
|
54
58
|
"code": "export const WithGradient: Story = {\n args: {\n children: 'Gradient',\n visual: 'primary',\n withGradient: true,\n },\n};"
|
|
@@ -59,15 +63,15 @@
|
|
|
59
63
|
},
|
|
60
64
|
{
|
|
61
65
|
"name": "BrandTheme",
|
|
62
|
-
"code": "
|
|
66
|
+
"code": "export const BrandTheme: Story = {\n render: (args) => (\n <>\n <style>{brandThemeCss}</style>\n <Stack gap=\"md\" align=\"start\">\n <Text fontSize=\"sm\" color=\"muted\" maxW=\"34\">\n Injects <code>--beckui--colors-primary: oklch(0.82 0.14 280)</code> (violet)\n so theming is obvious. Default primary is yellow.\n </Text>\n <Button {...args}>Brand primary</Button>\n <Button {...args} withGradient>\n Brand gradient\n </Button>\n </Stack>\n </>\n ),\n args: {\n visual: 'primary',\n },\n};"
|
|
63
67
|
},
|
|
64
68
|
{
|
|
65
69
|
"name": "InstanceOverride",
|
|
66
|
-
"code": "
|
|
70
|
+
"code": "export const InstanceOverride: Story = {\n args: {\n children: 'One-off override',\n visual: 'primary',\n style: {\n background: 'rebeccapurple',\n borderRadius: '9999px',\n color: 'white',\n padding: '0.75rem 1.5rem',\n },\n },\n};"
|
|
67
71
|
},
|
|
68
72
|
{
|
|
69
73
|
"name": "DensityOverride",
|
|
70
|
-
"code": "
|
|
74
|
+
"code": "export const DensityOverride: Story = {\n render: (args) => (\n <>\n <style>{densityCss}</style>\n <Stack gap=\"md\" align=\"start\" style={{ padding: '1rem' }}>\n <Button {...args}>Dense md</Button>\n <Button {...args} size=\"sm\">\n Dense sm (unchanged vars)\n </Button>\n </Stack>\n </>\n ),\n args: {\n visual: 'primary',\n size: 'md',\n },\n};"
|
|
71
75
|
},
|
|
72
76
|
{
|
|
73
77
|
"name": "AsLink",
|
|
@@ -119,6 +123,10 @@
|
|
|
119
123
|
"name": "WithGradient",
|
|
120
124
|
"code": "export const WithGradient: Story = {\n args: {\n children: 'Heading with gradient',\n size: '2xl',\n withGradient: true,\n },\n};"
|
|
121
125
|
},
|
|
126
|
+
{
|
|
127
|
+
"name": "ForcedColors",
|
|
128
|
+
"code": "export const ForcedColors: Story = { ...WithGradient, parameters: { forcedColors: true } };"
|
|
129
|
+
},
|
|
122
130
|
{
|
|
123
131
|
"name": "AsElement",
|
|
124
132
|
"code": "export const AsElement: Story = {\n render: () => (\n <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>\n <Heading as=\"h1\">Level 1</Heading>\n <Heading as=\"h2\">Level 2</Heading>\n <Heading as=\"h3\">Level 3</Heading>\n <Heading as=\"h4\">Level 4</Heading>\n <Heading as=\"h5\">Level 5</Heading>\n <Heading as=\"h6\">Level 6</Heading>\n </div>\n ),\n};"
|
|
@@ -139,7 +147,7 @@
|
|
|
139
147
|
"summary": null,
|
|
140
148
|
"recipe": null,
|
|
141
149
|
"variants": null,
|
|
142
|
-
"dts": "import { type ElementType } from 'react';\nimport { type JsxStyleProps } from '@becket-ui/tokens';\
|
|
150
|
+
"dts": "import { type ElementType } from 'react';\nimport { type JsxStyleProps } from '@becket-ui/tokens';\n/** Style props still need Panda or precompiled values. */\nexport type TextProps<T extends ElementType = 'p' | 'span' | 'div' | 'strong' | 'em' | 'label'> = React.ComponentPropsWithoutRef<T> & JsxStyleProps & {\n as?: T;\n};\nexport declare const Text: import(\"react\").ForwardRefExoticComponent<TextProps<\"div\" | \"em\" | \"label\" | \"p\" | \"span\" | \"strong\"> & import(\"react\").RefAttributes<HTMLElement>>;\n//# sourceMappingURL=Text.d.ts.map",
|
|
143
151
|
"examples": [
|
|
144
152
|
{
|
|
145
153
|
"name": "Default",
|
|
@@ -323,7 +331,7 @@
|
|
|
323
331
|
},
|
|
324
332
|
{
|
|
325
333
|
"name": "DensityOverride",
|
|
326
|
-
"code": "
|
|
334
|
+
"code": "export const DensityOverride: Story = {\n render: (args) => (\n <>\n <style>{tagDensityCss}</style>\n <Stack gap=\"md\" align=\"start\">\n <HStack gap=\"sm\">\n <Tag {...args}>Dense md</Tag>\n <Tag {...args} size=\"sm\">\n sm\n </Tag>\n </HStack>\n </Stack>\n </>\n ),\n};"
|
|
327
335
|
}
|
|
328
336
|
]
|
|
329
337
|
},
|
|
@@ -425,6 +433,10 @@
|
|
|
425
433
|
"name": "Default",
|
|
426
434
|
"code": "export const Default: Story = {\n args: {\n size: 'md',\n disabled: false,\n defaultChecked: false,\n label: 'Notifications',\n },\n};"
|
|
427
435
|
},
|
|
436
|
+
{
|
|
437
|
+
"name": "ForcedColors",
|
|
438
|
+
"code": "export const ForcedColors: Story = { ...Default, parameters: { forcedColors: true } };"
|
|
439
|
+
},
|
|
428
440
|
{
|
|
429
441
|
"name": "Checked",
|
|
430
442
|
"code": "export const Checked: Story = {\n args: {\n size: 'md',\n defaultChecked: true,\n label: 'Enabled',\n },\n};"
|
|
@@ -494,7 +506,7 @@
|
|
|
494
506
|
},
|
|
495
507
|
{
|
|
496
508
|
"name": "DensityOverride",
|
|
497
|
-
"code": "
|
|
509
|
+
"code": "export const DensityOverride: Story = {\n render: (args: FieldProps) => (\n <>\n <style>{fieldDensityCss}</style>\n <Stack gap=\"md\" align=\"start\">\n <Field {...args}>\n <FieldLabel>Dense field</FieldLabel>\n <FieldControl placeholder=\"md padding vars\" />\n </Field>\n <Field {...args} size=\"sm\">\n <FieldLabel>sm (other vars)</FieldLabel>\n <FieldControl placeholder=\"sm\" />\n </Field>\n </Stack>\n </>\n ),\n};"
|
|
498
510
|
}
|
|
499
511
|
]
|
|
500
512
|
},
|
|
@@ -528,6 +540,10 @@
|
|
|
528
540
|
"name": "Default",
|
|
529
541
|
"code": "export const Default: Story = {\n args: {\n label: 'Offset',\n placeholder: '3',\n helperText: 'Optional helper text',\n },\n};"
|
|
530
542
|
},
|
|
543
|
+
{
|
|
544
|
+
"name": "ForcedColors",
|
|
545
|
+
"code": "export const ForcedColors: Story = { ...Default, parameters: { forcedColors: true } };"
|
|
546
|
+
},
|
|
531
547
|
{
|
|
532
548
|
"name": "Invalid",
|
|
533
549
|
"code": "export const Invalid: Story = {\n args: {\n label: 'Email',\n defaultValue: 'not-an-email',\n invalid: true,\n helperText: 'Enter a valid email address',\n },\n};"
|
|
@@ -575,6 +591,10 @@
|
|
|
575
591
|
"name": "Default",
|
|
576
592
|
"code": "export const Default: Story = {\n args: {\n description: 'You can unsubscribe anytime.',\n },\n};"
|
|
577
593
|
},
|
|
594
|
+
{
|
|
595
|
+
"name": "ForcedColors",
|
|
596
|
+
"code": "export const ForcedColors: Story = {\n // Each box names its own state, so the label control has nothing to drive here.\n parameters: { forcedColors: true, controls: { include: ['size', 'disabled', 'description'] } },\n render: (args) => (\n <Stack gap=\"md\">\n <Checkbox {...args} label=\"Unchecked\" />\n <Checkbox {...args} label=\"Checked\" defaultChecked />\n </Stack>\n ),\n};"
|
|
597
|
+
},
|
|
578
598
|
{
|
|
579
599
|
"name": "Checked",
|
|
580
600
|
"code": "export const Checked: Story = {\n args: {\n defaultChecked: true,\n label: 'Checked',\n },\n};"
|
|
@@ -622,6 +642,10 @@
|
|
|
622
642
|
"name": "Default",
|
|
623
643
|
"code": "export const Default: Story = {\n render: (args) => (\n <RadioGroup {...args}>\n <PlanRadios />\n </RadioGroup>\n ),\n};"
|
|
624
644
|
},
|
|
645
|
+
{
|
|
646
|
+
"name": "ForcedColors",
|
|
647
|
+
"code": "export const ForcedColors: Story = {\n ...Default,\n args: { defaultValue: 'pro' },\n parameters: { forcedColors: true },\n};"
|
|
648
|
+
},
|
|
625
649
|
{
|
|
626
650
|
"name": "DefaultSelected",
|
|
627
651
|
"code": "export const DefaultSelected: Story = {\n args: { defaultValue: 'pro' },\n render: (args) => (\n <RadioGroup {...args}>\n <PlanRadios />\n </RadioGroup>\n ),\n};"
|
|
@@ -678,6 +702,10 @@
|
|
|
678
702
|
"name": "Default",
|
|
679
703
|
"code": "export const Default: Story = {\n args: { helperText: 'Native select — works without JS.' },\n};"
|
|
680
704
|
},
|
|
705
|
+
{
|
|
706
|
+
"name": "ForcedColors",
|
|
707
|
+
"code": "export const ForcedColors: Story = { ...Default, parameters: { forcedColors: true } };"
|
|
708
|
+
},
|
|
681
709
|
{
|
|
682
710
|
"name": "Invalid",
|
|
683
711
|
"code": "export const Invalid: Story = {\n args: {\n invalid: true,\n helperText: 'Pick a fruit',\n defaultValue: '',\n },\n};"
|
|
@@ -722,6 +750,10 @@
|
|
|
722
750
|
"name": "Default",
|
|
723
751
|
"code": "export const Default: Story = {\n args: {\n placeholder: 'Write a short note',\n helperText: 'Resize is vertical.',\n },\n};"
|
|
724
752
|
},
|
|
753
|
+
{
|
|
754
|
+
"name": "ForcedColors",
|
|
755
|
+
"code": "export const ForcedColors: Story = { ...Default, parameters: { forcedColors: true } };"
|
|
756
|
+
},
|
|
725
757
|
{
|
|
726
758
|
"name": "Invalid",
|
|
727
759
|
"code": "export const Invalid: Story = {\n args: {\n invalid: true,\n defaultValue: 'Too short',\n helperText: 'Add more detail',\n },\n};"
|
|
@@ -970,7 +1002,7 @@
|
|
|
970
1002
|
"false"
|
|
971
1003
|
]
|
|
972
1004
|
},
|
|
973
|
-
"dts": "
|
|
1005
|
+
"dts": "import { type ComponentPropsWithoutRef, type ElementType } from 'react';\nimport { type BreakpointAlias } from '../helpers/responsive.js';\nexport type HideProps = ComponentPropsWithoutRef<'div'> & {\n /** Hide when viewport is **below** this breakpoint (show from breakpoint up). */\n below?: BreakpointAlias;\n /** Hide from this breakpoint **and up** (show only below). */\n from?: BreakpointAlias;\n /**\n * When visible, use `display: contents` so the wrapper does not affect flex/grid\n * (Chakra Show/Hide pattern). Set `false` for a real block box.\n */\n asContents?: boolean;\n as?: ElementType;\n};\n/**\n * Conditionally hide children by breakpoint.\n * Prefer over duplicating trees for mobile/desktop — keeps `data-testid` stable.\n *\n * @example\n * <Hide below=\"desktop\">{sidebar}</Hide>\n * <Hide from=\"desktop\">{mobileOnlyNav}</Hide>\n */\nexport declare const Hide: import(\"react\").ForwardRefExoticComponent<Omit<import(\"react\").DetailedHTMLProps<import(\"react\").HTMLAttributes<HTMLDivElement>, HTMLDivElement>, \"ref\"> & {\n /** Hide when viewport is **below** this breakpoint (show from breakpoint up). */\n below?: BreakpointAlias;\n /** Hide from this breakpoint **and up** (show only below). */\n from?: BreakpointAlias;\n /**\n * When visible, use `display: contents` so the wrapper does not affect flex/grid\n * (Chakra Show/Hide pattern). Set `false` for a real block box.\n */\n asContents?: boolean;\n as?: ElementType;\n} & import(\"react\").RefAttributes<HTMLDivElement>>;\n//# sourceMappingURL=Hide.d.ts.map",
|
|
974
1006
|
"examples": [
|
|
975
1007
|
{
|
|
976
1008
|
"name": "Default",
|
|
@@ -996,7 +1028,7 @@
|
|
|
996
1028
|
"group": "Overlays",
|
|
997
1029
|
"storyTitle": "Overlays/Tooltip",
|
|
998
1030
|
"client": true,
|
|
999
|
-
"summary":
|
|
1031
|
+
"summary": "Makes a trigger that isn't a tab stop into one; wrap a disabled button yourself.",
|
|
1000
1032
|
"recipe": "tooltip",
|
|
1001
1033
|
"variants": {
|
|
1002
1034
|
"placement": [
|
|
@@ -1006,7 +1038,7 @@
|
|
|
1006
1038
|
"right"
|
|
1007
1039
|
]
|
|
1008
1040
|
},
|
|
1009
|
-
"dts": "
|
|
1041
|
+
"dts": "import { type ReactNode } from 'react';\nexport type TooltipPlacement = 'top' | 'bottom' | 'left' | 'right';\nexport type TooltipProps = {\n /** Short glossary / hint text (or node). */\n content: ReactNode;\n children: ReactNode;\n placement?: TooltipPlacement;\n /** Delay before open on hover/focus (ms). */\n delayMs?: number;\n disabled?: boolean;\n};\n/** Makes a trigger that isn't a tab stop into one; wrap a disabled button yourself. */\nexport declare const Tooltip: import(\"react\").ForwardRefExoticComponent<TooltipProps & import(\"react\").RefAttributes<HTMLElement>>;\n//# sourceMappingURL=Tooltip.d.ts.map",
|
|
1010
1042
|
"examples": [
|
|
1011
1043
|
{
|
|
1012
1044
|
"name": "Default",
|
|
@@ -1015,6 +1047,10 @@
|
|
|
1015
1047
|
{
|
|
1016
1048
|
"name": "Placements",
|
|
1017
1049
|
"code": "export const Placements: Story = {\n render: () => (\n <HStack gap=\"lg\" align=\"center\" style={{ padding: '5rem', flexWrap: 'wrap' }}>\n {/* as const: `placement` takes these literals, not any string. */}\n {(['top', 'bottom', 'left', 'right'] as const).map((placement) => (\n <Tooltip key={placement} content={`Placement: ${placement}`} placement={placement}>\n <Button size=\"sm\" visual=\"neutral\">\n {placement}\n </Button>\n </Tooltip>\n ))}\n </HStack>\n ),\n};"
|
|
1050
|
+
},
|
|
1051
|
+
{
|
|
1052
|
+
"name": "IconTrigger",
|
|
1053
|
+
"code": "export const IconTrigger: Story = {\n args: {\n content: 'More information',\n placement: 'top',\n delayMs: 200,\n disabled: false,\n },\n render: (args: TooltipProps) => (\n <Box padding=\"xl\">\n <Tooltip {...args}>\n <Icon label=\"Info\">\n <svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" strokeWidth={2}>\n <circle cx=\"12\" cy=\"12\" r=\"9\" />\n <path d=\"M12 11v5M12 8h.01\" />\n </svg>\n </Icon>\n </Tooltip>\n </Box>\n ),\n};"
|
|
1018
1054
|
}
|
|
1019
1055
|
]
|
|
1020
1056
|
},
|
|
@@ -1043,6 +1079,10 @@
|
|
|
1043
1079
|
"name": "Default",
|
|
1044
1080
|
"code": "export const Default: Story = {\n render: function DialogDemo() {\n const [open, setOpen] = useState(false);\n return (\n <>\n <Button visual=\"primary\" onClick={() => setOpen(true)}>\n Open dialog\n </Button>\n <Dialog\n open={open}\n onOpenChange={setOpen}\n title=\"Confirm\"\n footer={\n <>\n <Button visual=\"outline\" onClick={() => setOpen(false)}>\n Cancel\n </Button>\n <Button visual=\"primary\" onClick={() => setOpen(false)}>\n Confirm\n </Button>\n </>\n }\n >\n <Text>\n Native dialog. Escape and backdrop click close it. Focus moves to Cancel, not Close.\n </Text>\n </Dialog>\n </>\n );\n },\n};"
|
|
1045
1081
|
},
|
|
1082
|
+
{
|
|
1083
|
+
"name": "ForcedColors",
|
|
1084
|
+
"code": "export const ForcedColors: Story = {\n render: () => (\n <Dialog defaultOpen title=\"Confirm\">\n <Text>Close keeps a visible focus outline in a contrast theme.</Text>\n </Dialog>\n ),\n parameters: { forcedColors: true },\n};"
|
|
1085
|
+
},
|
|
1046
1086
|
{
|
|
1047
1087
|
"name": "Alert",
|
|
1048
1088
|
"code": "export const Alert: Story = {\n render: function AlertDialogDemo() {\n const [open, setOpen] = useState(false);\n return (\n <>\n <Button visual=\"primary\" onClick={() => setOpen(true)}>\n Delete\n </Button>\n <Dialog\n role=\"alertdialog\"\n open={open}\n onOpenChange={setOpen}\n title=\"Delete item?\"\n footer={\n <>\n <Button visual=\"outline\" onClick={() => setOpen(false)}>\n Cancel\n </Button>\n <Button visual=\"primary\" onClick={() => setOpen(false)}>\n Delete\n </Button>\n </>\n }\n >\n <Text>This cannot be undone. Backdrop click does not dismiss an alertdialog.</Text>\n </Dialog>\n </>\n );\n },\n};"
|
|
@@ -1083,6 +1123,10 @@
|
|
|
1083
1123
|
"name": "Default",
|
|
1084
1124
|
"code": "export const Default: Story = {\n render: function DrawerDemo(args: DrawerProps) {\n const [open, setOpen] = useState(false);\n return (\n <>\n <Button visual=\"primary\" onClick={() => setOpen(true)}>\n Open drawer\n </Button>\n <Drawer\n {...args}\n open={open}\n onOpenChange={setOpen}\n title=\"Filters\"\n footer={\n <Button visual=\"primary\" onClick={() => setOpen(false)}>\n Done\n </Button>\n }\n >\n <Text>Same a11y as Dialog: Escape, backdrop, focus return. Placement is CSS.</Text>\n </Drawer>\n </>\n );\n },\n};"
|
|
1085
1125
|
},
|
|
1126
|
+
{
|
|
1127
|
+
"name": "ForcedColors",
|
|
1128
|
+
"code": "export const ForcedColors: Story = {\n render: (args) => (\n <Drawer {...args} defaultOpen title=\"Filters\">\n <Text>Close keeps a visible focus outline in a contrast theme.</Text>\n </Drawer>\n ),\n parameters: { forcedColors: true },\n};"
|
|
1129
|
+
},
|
|
1086
1130
|
{
|
|
1087
1131
|
"name": "Start",
|
|
1088
1132
|
"code": "export const Start: Story = {\n ...Default,\n args: { placement: 'start' },\n};"
|
|
@@ -1105,15 +1149,23 @@
|
|
|
1105
1149
|
"group": "Overlays",
|
|
1106
1150
|
"storyTitle": "Overlays/Menu",
|
|
1107
1151
|
"client": true,
|
|
1108
|
-
"summary":
|
|
1152
|
+
"summary": "Focus returns to the trigger on activation and on Escape.",
|
|
1109
1153
|
"recipe": "menu",
|
|
1110
1154
|
"variants": {},
|
|
1111
|
-
"dts": "import { type ButtonHTMLAttributes, type DetailsHTMLAttributes, type ReactNode } from 'react';\nexport type MenuProps = Omit<DetailsHTMLAttributes<HTMLDetailsElement>, 'onToggle'> & {\n label: ReactNode;\n};\nexport declare const Menu: import(\"react\").ForwardRefExoticComponent<Omit<DetailsHTMLAttributes<HTMLDetailsElement>, \"onToggle\"> & {\n label: ReactNode;\n} & import(\"react\").RefAttributes<HTMLDetailsElement>>;\ntype MenuItemProps = ButtonHTMLAttributes<HTMLButtonElement>;\nexport declare const MenuItem: import(\"react\").ForwardRefExoticComponent<MenuItemProps & import(\"react\").RefAttributes<HTMLButtonElement>>;\nexport {};\n//# sourceMappingURL=Menu.d.ts.map",
|
|
1155
|
+
"dts": "import { type ButtonHTMLAttributes, type DetailsHTMLAttributes, type ReactNode } from 'react';\nexport type MenuProps = Omit<DetailsHTMLAttributes<HTMLDetailsElement>, 'onToggle'> & {\n label: ReactNode;\n};\n/** Focus returns to the trigger on activation and on Escape. */\nexport declare const Menu: import(\"react\").ForwardRefExoticComponent<Omit<DetailsHTMLAttributes<HTMLDetailsElement>, \"onToggle\"> & {\n label: ReactNode;\n} & import(\"react\").RefAttributes<HTMLDetailsElement>>;\ntype MenuItemProps = ButtonHTMLAttributes<HTMLButtonElement>;\nexport declare const MenuItem: import(\"react\").ForwardRefExoticComponent<MenuItemProps & import(\"react\").RefAttributes<HTMLButtonElement>>;\nexport {};\n//# sourceMappingURL=Menu.d.ts.map",
|
|
1112
1156
|
"examples": [
|
|
1113
1157
|
{
|
|
1114
1158
|
"name": "Default",
|
|
1115
1159
|
"code": "export const Default: Story = {\n render: function MenuDemo(args: MenuProps) {\n const [last, setLast] = useState('none');\n return (\n <>\n <Menu {...args}>\n <MenuItem onClick={() => setLast('Edit')}>Edit</MenuItem>\n <MenuItem onClick={() => setLast('Duplicate')}>Duplicate</MenuItem>\n <MenuItem onClick={() => setLast('Delete')}>Delete</MenuItem>\n </Menu>\n <Text>Last action: {last}</Text>\n </>\n );\n },\n};"
|
|
1116
1160
|
},
|
|
1161
|
+
{
|
|
1162
|
+
"name": "ForcedColors",
|
|
1163
|
+
"code": "export const ForcedColors: Story = { ...Default, parameters: { forcedColors: true } };"
|
|
1164
|
+
},
|
|
1165
|
+
{
|
|
1166
|
+
"name": "ForcedColorsItem",
|
|
1167
|
+
"code": "export const ForcedColorsItem: Story = {\n ...Default,\n parameters: { forcedColors: { keys: '{Tab}{ArrowDown}' } },\n};"
|
|
1168
|
+
},
|
|
1117
1169
|
{
|
|
1118
1170
|
"name": "Open",
|
|
1119
1171
|
"code": "export const Open: Story = {\n render: function OpenMenuDemo(args: MenuProps) {\n return (\n <Menu {...args} open>\n <MenuItem>Edit</MenuItem>\n <MenuItem>Duplicate</MenuItem>\n <MenuItem>Delete</MenuItem>\n </Menu>\n );\n },\n};"
|
|
@@ -1142,6 +1194,10 @@
|
|
|
1142
1194
|
{
|
|
1143
1195
|
"name": "Default",
|
|
1144
1196
|
"code": "export const Default: Story = {\n render: () => (\n <Tabs defaultValue=\"one\">\n <TabList>\n <Tab value=\"one\">Overview</Tab>\n <Tab value=\"two\">Activity</Tab>\n <Tab value=\"three\" disabled>\n Disabled\n </Tab>\n </TabList>\n <TabPanel value=\"one\">\n <Text>First panel. Arrow keys move between tabs.</Text>\n </TabPanel>\n <TabPanel value=\"two\">\n <Text>Second panel.</Text>\n </TabPanel>\n <TabPanel value=\"three\">\n <Text>Hidden while disabled tab is unused.</Text>\n </TabPanel>\n </Tabs>\n ),\n};"
|
|
1197
|
+
},
|
|
1198
|
+
{
|
|
1199
|
+
"name": "ForcedColors",
|
|
1200
|
+
"code": "export const ForcedColors: Story = { ...Default, parameters: { forcedColors: true } };"
|
|
1145
1201
|
}
|
|
1146
1202
|
]
|
|
1147
1203
|
},
|
|
@@ -1325,6 +1381,10 @@
|
|
|
1325
1381
|
"name": "Default",
|
|
1326
1382
|
"code": "export const Default: Story = {};"
|
|
1327
1383
|
},
|
|
1384
|
+
{
|
|
1385
|
+
"name": "ForcedColors",
|
|
1386
|
+
"code": "export const ForcedColors: Story = { ...Default, parameters: { forcedColors: true } };"
|
|
1387
|
+
},
|
|
1328
1388
|
{
|
|
1329
1389
|
"name": "Muted",
|
|
1330
1390
|
"code": "export const Muted: Story = {\n args: { visual: 'muted', children: 'Muted link' },\n};"
|
|
@@ -1649,6 +1709,10 @@
|
|
|
1649
1709
|
"name": "Default",
|
|
1650
1710
|
"code": "export const Default: Story = {};"
|
|
1651
1711
|
},
|
|
1712
|
+
{
|
|
1713
|
+
"name": "ForcedColors",
|
|
1714
|
+
"code": "export const ForcedColors: Story = { ...Default, parameters: { forcedColors: true } };"
|
|
1715
|
+
},
|
|
1652
1716
|
{
|
|
1653
1717
|
"name": "Middle",
|
|
1654
1718
|
"code": "export const Middle: Story = { args: { page: 6 } };"
|
|
@@ -1712,6 +1776,10 @@
|
|
|
1712
1776
|
"name": "Default",
|
|
1713
1777
|
"code": "export const Default: Story = {\n render: (args) => (\n <Breadcrumb {...args}>\n <BreadcrumbItem href=\"#home\">Home</BreadcrumbItem>\n <BreadcrumbItem href=\"#blog\">Blog</BreadcrumbItem>\n <BreadcrumbItem current>Writing tokens</BreadcrumbItem>\n </Breadcrumb>\n ),\n};"
|
|
1714
1778
|
},
|
|
1779
|
+
{
|
|
1780
|
+
"name": "ForcedColors",
|
|
1781
|
+
"code": "export const ForcedColors: Story = { ...Default, parameters: { forcedColors: true } };"
|
|
1782
|
+
},
|
|
1715
1783
|
{
|
|
1716
1784
|
"name": "Sizes",
|
|
1717
1785
|
"code": "export const Sizes: Story = {\n render: (args) => (\n <Stack gap=\"md\">\n {breadcrumbRecipe.variantMap.size.map((size) => (\n <Breadcrumb key={size} {...args} size={size} aria-label={`Breadcrumb, ${size}`}>\n <BreadcrumbItem href=\"#home\">Home</BreadcrumbItem>\n <BreadcrumbItem href=\"#docs\">Docs</BreadcrumbItem>\n <BreadcrumbItem current>Theming</BreadcrumbItem>\n </Breadcrumb>\n ))}\n </Stack>\n ),\n};"
|
|
@@ -1767,6 +1835,10 @@
|
|
|
1767
1835
|
"name": "Horizontal",
|
|
1768
1836
|
"code": "export const Horizontal: Story = {\n render: (args) => (\n <Steps {...args} aria-label=\"Sign-up progress\">\n <Step status=\"complete\" title=\"Account\" />\n <Step status=\"current\" title=\"Profile\" />\n <Step status=\"upcoming\" title=\"Done\" />\n </Steps>\n ),\n};"
|
|
1769
1837
|
},
|
|
1838
|
+
{
|
|
1839
|
+
"name": "ForcedColors",
|
|
1840
|
+
"code": "export const ForcedColors: Story = { ...Horizontal, parameters: { forcedColors: true } };"
|
|
1841
|
+
},
|
|
1770
1842
|
{
|
|
1771
1843
|
"name": "Vertical",
|
|
1772
1844
|
"code": "export const Vertical: Story = {\n render: (args) => (\n <Steps {...args} orientation=\"vertical\" aria-label=\"Sign-up progress\">\n <Step status=\"complete\" title=\"Account\" />\n <Step status=\"current\" title=\"Profile\" />\n <Step status=\"upcoming\" title=\"Done\" />\n </Steps>\n ),\n};"
|
|
@@ -1804,6 +1876,10 @@
|
|
|
1804
1876
|
{
|
|
1805
1877
|
"name": "Default",
|
|
1806
1878
|
"code": "export const Default: Story = {\n render: () => (\n <>\n <SkipLink href=\"#story-main\" />\n <Text color=\"muted\">Press Tab: the skip link appears at the top left.</Text>\n <main id=\"story-main\" />\n </>\n ),\n};"
|
|
1879
|
+
},
|
|
1880
|
+
{
|
|
1881
|
+
"name": "ForcedColors",
|
|
1882
|
+
"code": "export const ForcedColors: Story = { ...Default, parameters: { forcedColors: true } };"
|
|
1807
1883
|
}
|
|
1808
1884
|
]
|
|
1809
1885
|
},
|
|
@@ -4,7 +4,7 @@ import {
|
|
|
4
4
|
neutralChroma,
|
|
5
5
|
parseColor,
|
|
6
6
|
rgbToOklch
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-I4QZIQ42.js";
|
|
8
8
|
|
|
9
9
|
// src/theme/extractPDF.ts
|
|
10
10
|
import { getDocumentProxy, getResolvedPDFJS } from "unpdf";
|
|
@@ -152,4 +152,4 @@ async function extractPDF(source) {
|
|
|
152
152
|
export {
|
|
153
153
|
extractPDF
|
|
154
154
|
};
|
|
155
|
-
//# sourceMappingURL=extractPDF-
|
|
155
|
+
//# sourceMappingURL=extractPDF-EMWJFZGY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/theme/extractPDF.ts"],"sourcesContent":["import { formatHex, parseColor, rgbToOklch } from '@becket-ui/tokens/theme';\nimport { getDocumentProxy, getResolvedPDFJS } from 'unpdf';\n\nimport { mergeClose, neutralChroma, type ExtractedColor } from './extractColors';\nimport type { Source } from './loadSource';\nimport type { Findings, Stated } from './suggestTheme';\n\n// Brand manuals put colors, type and spacing up front; past this, pages are mostly imagery.\nconst maxPages = 60;\n\nexport async function extractPDF(source: Source): Promise<Findings> {\n const { OPS } = await getResolvedPDFJS();\n const pdf = await getDocumentProxy(new Uint8Array(source.bytes));\n const totalPages = pdf.numPages;\n const pageCount = Math.min(totalPages, maxPages);\n const pages: string[] = [];\n const fills = new Map<string, number>();\n const fontUse = new Map<string, { family: string; characters: number; page: number }>();\n\n for (let number = 1; number <= pageCount; number += 1) {\n const page = await pdf.getPage(number);\n let text = '';\n let lastY: number | null = null;\n const charactersByFont = new Map<string, number>();\n for (const item of (await page.getTextContent()).items) {\n if (!('str' in item)) continue;\n const y = item.transform[5];\n if (lastY !== null && Math.abs(y - lastY) > 1) text += '\\n';\n text += item.str;\n if (item.hasEOL) text += '\\n';\n lastY = y;\n charactersByFont.set(\n item.fontName,\n (charactersByFont.get(item.fontName) ?? 0) + item.str.trim().length,\n );\n }\n pages.push(text);\n\n const operators = await page.getOperatorList();\n operators.fnArray.forEach((fn, index) => {\n if (fn !== OPS.setFillRGBColor) return;\n // pdf.js passes the fill as one \"#rrggbb\" string; argsArray is typed `any[]`.\n const [hex] = operators.argsArray[index] as [string];\n if (typeof hex === 'string') fills.set(hex, (fills.get(hex) ?? 0) + 1);\n });\n for (const [id, characters] of charactersByFont) {\n if (!characters || !page.commonObjs.has(id)) continue;\n // commonObjs.get returns `any`; a loaded font carries its PostScript name.\n const font = page.commonObjs.get(id) as { name?: string } | undefined;\n if (!font?.name) continue;\n // \"ABCDEF+OpenSans-SemiBoldItalic\" → \"Open Sans\": drop the subset tag and the weight/style.\n const name = font.name\n .replace(/^[A-Z]{6}\\+/, '')\n .replace(\n /[-,]?(Thin|ExtraLight|UltraLight|Light|Regular|Book|Roman|Medium|SemiBold|DemiBold|Bold|ExtraBold|UltraBold|Black|Heavy|Italic|Oblique|It|MT|PS)+$/,\n '',\n )\n .replace(/[-_,]+$/, '');\n const family = name.includes(' ') ? name : name.replace(/([a-z])([A-Z])/g, '$1 $2');\n const entry = fontUse.get(family) ?? { family, characters: 0, page: number };\n entry.characters += characters;\n fontUse.set(family, entry);\n }\n page.cleanup();\n }\n await pdf.loadingTask.destroy();\n\n // What the manual says outright, line by line.\n const stated: Stated = { colors: [], fonts: [], radii: [], baseSize: [] };\n pages.forEach((text, index) => {\n const page = index + 1;\n for (const line of text.split('\\n')) {\n for (const { pattern, read, approximate } of [\n {\n pattern: /#([0-9a-f]{6}|[0-9a-f]{3})\\b/gi,\n read: (match: RegExpMatchArray) => `#${match[1]}`,\n },\n {\n pattern: /\\bRGB[:\\s]*\\(?\\s*(\\d{1,3})[,\\s/]+(\\d{1,3})[,\\s/]+(\\d{1,3})\\)?/gi,\n read: (match: RegExpMatchArray) =>\n match.slice(1, 4).every((channel) => Number(channel) <= 255)\n ? `rgb(${match[1]}, ${match[2]}, ${match[3]})`\n : null,\n },\n {\n // \"CMYK 100 58 0 43\", \"C100 M58 Y0 K43\", \"C 100 / M 58 / Y 0 / K 43\"\n pattern:\n /\\b(?:CMYK[:\\s]*\\(?\\s*(\\d{1,3})[,\\s/%]+(\\d{1,3})[,\\s/%]+(\\d{1,3})[,\\s/%]+(\\d{1,3})|C\\s*(\\d{1,3})[,\\s/%]*M\\s*(\\d{1,3})[,\\s/%]*Y\\s*(\\d{1,3})[,\\s/%]*K\\s*(\\d{1,3}))/gi,\n read: (match: RegExpMatchArray) => {\n const [c, m, y, k] = (match[1] ? match.slice(1, 5) : match.slice(5, 9)).map(\n (part) => Number(part) / 100,\n );\n if ([c, m, y, k].some((part) => part > 1)) return null;\n // Uncalibrated conversion: close enough to pick a hue, not a print match. Reported as approximate.\n const [r, g, b] = [c, m, y].map((part) => Math.round(255 * (1 - part) * (1 - k)));\n return formatHex(rgbToOklch([r, g, b]));\n },\n approximate: true,\n },\n ]) {\n for (const match of line.matchAll(pattern)) {\n const value = read(match);\n const color = value && parseColor(value);\n if (!color) continue;\n const hex = formatHex(color);\n if (stated.colors.some((entry) => entry.hex === hex)) continue;\n // The words right before the color, e.g. \"Ocean Blue\" in \"Ocean Blue #0A3D91\".\n const name = line\n .slice(0, match.index ?? 0)\n .replace(/(primary|secondary|accent|color|colour|hex|rgb|cmyk)\\s*:?\\s*$/i, '')\n .trim()\n .split(/\\s+/)\n .slice(-3)\n .filter((word) => /^[A-Za-z][A-Za-z'’-]*:?$/.test(word))\n .join(' ')\n .replace(/:$/, '');\n const label = name.length >= 3 ? name : undefined;\n stated.colors.push({\n hex,\n name: approximate ? `${label ?? ''} (from CMYK, approximate)`.trim() : label,\n page,\n });\n }\n }\n for (const match of line.matchAll(\n /\\b(?:corner|border)[\\s-]*radi(?:us|i)\\b[^0-9\\n]{0,24}(\\d+(?:\\.\\d+)?)\\s*(px|pt)\\b/gi,\n )) {\n stated.radii.push({\n // px or pt → rem, so the theme keeps following the browser's text size.\n value: `${Number(((match[2].toLowerCase() === 'pt' ? (Number(match[1]) * 4) / 3 : Number(match[1])) / 16).toFixed(4))}rem`,\n page,\n });\n }\n for (const match of line.matchAll(\n /\\b(?:body|base|paragraph)\\s*(?:text|copy|font)?\\s*(?:size)?\\b[^0-9\\n]{0,24}(\\d+(?:\\.\\d+)?)\\s*(px|pt)\\b/gi,\n )) {\n const size = Number(match[1]);\n if (size < 10 || size > 24) continue;\n stated.baseSize.push({\n value: `${Number(((match[2].toLowerCase() === 'pt' ? (size * 4) / 3 : size) / 16).toFixed(4))}rem`,\n page,\n });\n }\n }\n });\n stated.fonts = [...fontUse.values()]\n // Fonts every PDF tool falls back to; a manual set in one of these rarely means \"use it\".\n .filter(\n (font) =>\n !/^(Helvetica|Arial|Times|TimesNewRoman|Courier|Symbol|ZapfDingbats|ArialMT)$/i.test(\n font.family.replace(/\\s/g, ''),\n ),\n )\n // pdf.js names glyph-drawn (Type 3) and unnamed fonts with placeholders, not real families.\n .filter(\n (font) => /[a-z]{2}/i.test(font.family) && !/^(Type\\s?3|T3\\s?Font|g_d\\d)/i.test(font.family),\n )\n .toSorted((a, b) => b.characters - a.characters)\n .map(({ family, page }) => ({ family, page }));\n\n // Summed once here, not per color inside the flatMap below.\n const total = [...fills.values()].reduce((sum, count) => sum + count, 0);\n return {\n label: source.label,\n method: `PDF, ${pageCount} of ${totalPages} pages: stated colors, fonts and sizes from the text, plus artwork fill colors (by how often each is used, not by area)`,\n colors: mergeClose(\n [...fills.entries()].flatMap(([hex, count]): ExtractedColor[] => {\n const color = parseColor(hex);\n if (!color) return [];\n return [\n {\n hex: formatHex(color),\n color,\n share: count / total,\n role: color.C < neutralChroma ? 'neutral' : 'brand',\n },\n ];\n }),\n ),\n stated,\n skipped:\n totalPages > maxPages\n ? [`pages ${maxPages + 1}–${totalPages} (only the first ${maxPages} are read)`]\n : [],\n };\n}\n"],"mappings":";;;;;;;;;AACA,SAAS,kBAAkB,wBAAwB;AAOnD,IAAM,WAAW;AAEjB,eAAsB,WAAW,QAAmC;AAClE,QAAM,EAAE,IAAI,IAAI,MAAM,iBAAiB;AACvC,QAAM,MAAM,MAAM,iBAAiB,IAAI,WAAW,OAAO,KAAK,CAAC;AAC/D,QAAM,aAAa,IAAI;AACvB,QAAM,YAAY,KAAK,IAAI,YAAY,QAAQ;AAC/C,QAAM,QAAkB,CAAC;AACzB,QAAM,QAAQ,oBAAI,IAAoB;AACtC,QAAM,UAAU,oBAAI,IAAkE;AAEtF,WAAS,SAAS,GAAG,UAAU,WAAW,UAAU,GAAG;AACrD,UAAM,OAAO,MAAM,IAAI,QAAQ,MAAM;AACrC,QAAI,OAAO;AACX,QAAI,QAAuB;AAC3B,UAAM,mBAAmB,oBAAI,IAAoB;AACjD,eAAW,SAAS,MAAM,KAAK,eAAe,GAAG,OAAO;AACtD,UAAI,EAAE,SAAS,MAAO;AACtB,YAAM,IAAI,KAAK,UAAU,CAAC;A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,OAAO,QAAQ,OAAO,EAAE;AAAA,IAC/B;AAAA,EACJ,EAEC;AAAA,IACC,CAAC,SAAS,YAAY,KAAK,KAAK,MAAM,KAAK,CAAC,+BAA+B,KAAK,KAAK,MAAM;AAAA,EAC7F,EACC,SAAS,CAAC,GAAG,MAAM,EAAE,aAAa,EAAE,UAAU,EAC9C,IAAI,CAAC,EAAE,QAAQ,KAAK,OAAO,EAAE,QAAQ,KAAK,EAAE;AAG/C,QAAM,QAAQ,CAAC,GAAG,MAAM,OAAO,CAAC,EAAE,OAAO,CAAC,KAAK,UAAU,MAAM,OAAO,CAAC;AACvE,SAAO;AAAA,IACL,OAAO,OAAO;AAAA,IACd,QAAQ,QAAQ,SAAS,OAAO,UAAU;AAAA,IAC1C,QAAQ;AAAA,MACN,CAAC,GAAG,MAAM,QAAQ,CAAC,EAAE,QAAQ,CAAC,CAAC,KAAK,KAAK,MAAwB;AAC/D,cAAM,QAAQ,WAAW,GAAG;AAC5B,YAAI,CAAC,MAAO,QAAO,CAAC;AACpB,eAAO;AAAA,UACL;AAAA,YACE,KAAK,UAAU,KAAK;AAAA,YACpB;AAAA,YACA,OAAO,QAAQ;AAAA,YACf,MAAM,MAAM,IAAI,gBAAgB,YAAY;AAAA,UAC9C;AAAA,QACF;AAAA,MACF,CAAC;AAAA,IACH;AAAA,IACA;AAAA,IACA,SACE,aAAa,WACT,CAAC,SAAS,WAAW,CAAC,SAAI,UAAU,oBAAoB,QAAQ,YAAY,IAC5E,CAAC;AAAA,EACT;AACF;","names":[]}
|
package/dist/server.js
CHANGED
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
formatHex,
|
|
10
10
|
neutralChroma,
|
|
11
11
|
parseColor
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-I4QZIQ42.js";
|
|
13
13
|
|
|
14
14
|
// src/server.ts
|
|
15
15
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
@@ -630,7 +630,7 @@ async function suggestTheme(input) {
|
|
|
630
630
|
}
|
|
631
631
|
const source = await loadSource(input);
|
|
632
632
|
if (source.kind === "pdf") {
|
|
633
|
-
const { extractPDF } = await import("./extractPDF-
|
|
633
|
+
const { extractPDF } = await import("./extractPDF-EMWJFZGY.js");
|
|
634
634
|
return formatSuggestion(await extractPDF(source));
|
|
635
635
|
}
|
|
636
636
|
const { colors, method, skipped } = extractImageColors(source);
|
package/dist/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts","../src/createServer.ts","../src/data.ts","../src/review.ts","../src/theme/setTheme.ts","../src/theme/loadSource.ts","../src/theme/suggestTheme.ts","../src/tools.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\n\nimport { createServer } from './createServer';\n\nawait createServer().connect(new StdioServerTransport());\n","import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\n\nimport { loadData, type Data } from './data';\nimport { formatReview, reviewUsage } from './review';\nimport { setTheme } from './theme/setTheme';\nimport { suggestTheme } from './theme/suggestTheme';\nimport { componentExample, componentProps, guidelines, installation, listComponents, theme } from './tools';\n\n// as const: the MCP SDK types a text block's `type` as the literal 'text'.\nconst text = (value: string) => ({ content: [{ type: 'text' as const, text: value }] });\n\nexport function createServer(data: Data = loadData()): McpServer {\n const server = new McpServer({ name: 'becket-ui', version: data.catalog.version });\n const readOnly = { readOnlyHint: true, openWorldHint: false };\n\n server.registerTool(\n 'installation',\n {\n title: 'Install Becket UI',\n description: 'How to install and set up Becket UI in a React app: packages, the one CSS import, and the theme on <html>.',\n annotations: readOnly,\n },\n async () => text(installation(data)),\n );\n\n server.registerTool(\n 'list_components',\n {\n title: 'List Becket components',\n description: 'Every public Becket UI component by group, with its parts and whether it needs client JS.',\n annotations: readOnly,\n },\n async () => text(listComponents(data)),\n );\n\n server.registerTool(\n 'get_component_props',\n {\n title: 'Get component props',\n description: 'Exact props of a Becket component (TypeScript declarations) and its recipe variant values. Accepts a component or part name, e.g. Button, CardHeader, SearchIcon.',\n inputSchema: { name: z.string().describe('Component or part name, e.g. \"Card\" or \"CardHeader\"') },\n annotations: readOnly,\n },\n async ({ name }) => text(componentProps(data, name)),\n );\n\n server.registerTool(\n 'get_component_example',\n {\n title: 'Get component examples',\n description: 'Usage examples for a Becket component (its Storybook stories). Optionally pick one story by name.',\n inputSchema: {\n name: z.string().describe('Component name, e.g. \"Dialog\"'),\n story: z.string().optional().describe('Story name, e.g. \"Open\"'),\n },\n annotations: readOnly,\n },\n async ({ name, story }) => text(componentExample(data, name, story)),\n );\n\n server.registerTool(\n 'get_theme',\n {\n title: 'Get theme tokens',\n description: 'Becket design tokens with dark and light values: colors, spacing, radii, sizes, font-sizes, shadows.',\n inputSchema: {\n group: z.enum(['colors', 'spacing', 'radii', 'sizes', 'font-sizes', 'shadows']).optional().describe('One token group; omit for all'),\n },\n annotations: readOnly,\n },\n async ({ group }) => text(theme(data, group)),\n );\n\n server.registerTool(\n 'get_guidelines',\n {\n title: 'Get the Becket app-code guide',\n description: 'Rules for writing app code with Becket: which component replaces each raw element, props-then-tokens styling, abstraction, state, accessibility. Read before writing UI.',\n inputSchema: {\n topic: z.string().optional().describe('Section filter, e.g. \"component\", \"tokens\", \"accessibility\", \"example\", \"checklist\"'),\n },\n annotations: readOnly,\n },\n async ({ topic }) => text(guidelines(data, topic)),\n );\n\n server.registerTool(\n 'review_usage',\n {\n title: 'Review Becket usage',\n description: 'Check React code against the Becket app-code guide: raw layout/text/controls, literal colors, pixel spacing, recipe classes, Chakra imports, unknown exports. Run before finishing.',\n inputSchema: { code: z.string().describe('The TSX/JSX source to review') },\n annotations: readOnly,\n },\n async ({ code }) => text(formatReview(reviewUsage(code, data))),\n );\n\n const tokens = z.record(z.string(), z.string());\n server.registerTool(\n 'set_theme',\n {\n title: 'Set a brand theme',\n description:\n 'Turn brand tokens into Becket theme CSS that passes WCAG 2.2 AA in dark and light. Give one to three brand colors (Becket derives every color token) and/or exact tokens. Returns the CSS to write, the same theme as defineBecketTheme() code, why each value was chosen, and a contrast report. Writes nothing; you write the file. For a logo, image URL or brand manual, call suggest_theme first.',\n inputSchema: {\n brand: z.array(z.string()).min(1).max(3).optional().describe('Brand colors, most important first: hex, rgb(), hsl() or oklch()'),\n colors: z\n .record(z.string(), z.union([z.string(), z.record(z.string(), z.string())]))\n .optional()\n .describe('Exact color tokens to keep, e.g. { \"background\": { \"dark\": \"#101820\", \"light\": \"#ffffff\" } }. With brand, these are pinned and the rest is derived.'),\n fonts: tokens.optional().describe('{ \"sans\": \"Inter\", \"mono\": \"JetBrains Mono\" }'),\n radii: tokens.optional().describe('none, sm, md, lg, xl, full, e.g. { \"md\": \"0.25rem\" }'),\n fontSizes: tokens.optional().describe('{ \"base\": \"1rem\" } resizes all text; xs–6xl override single steps'),\n spacing: tokens.optional().describe('{ \"unit\": \"0.25rem\" } resizes all spacing; textUnit (em) spacing inside text'),\n sizes: tokens.optional().describe('{ \"field\": \"16rem\" }'),\n density: z\n .record(z.string(), z.record(z.string(), z.object({ px: z.string().optional(), py: z.string().optional() })))\n .optional()\n .describe('Component padding, e.g. { \"button\": { \"md\": { \"px\": \"0.75rem\" } } }'),\n },\n annotations: readOnly,\n },\n async (input) => text(setTheme(input)),\n );\n\n server.registerTool(\n 'suggest_theme',\n {\n title: 'Suggest a brand theme',\n description:\n \"Read a logo (PNG, JPEG, SVG) or a brand manual (PDF) and suggest Becket brand tokens: colors, plus fonts, corner radius and text size when a manual states them. Returns what it found and a step-by-step script: ask the user one decision at a time, then call set_theme with what they confirm. Pass exactly one of path, url (public https) or base64. For an image only pasted in chat, pass the colors you see in `colors` instead.\",\n inputSchema: {\n path: z.string().optional().describe('Local file path, absolute or relative to the working directory'),\n url: z.string().optional().describe('Public https URL of the image or PDF'),\n base64: z.string().optional().describe('File contents as base64 or a data: URL'),\n colors: z.array(z.string()).min(1).max(8).optional().describe('Colors you read from an image you can see but cannot pass as a file, most prominent first'),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async (input) => text(await suggestTheme(input)),\n );\n\n return server;\n}\n","import { readFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nexport type Example = { name: string; code: string };\n\nexport type Component = {\n name: string;\n file: string;\n exports: string[];\n hooks: string[];\n types: string[];\n group: string | null;\n storyTitle: string | null;\n client: boolean;\n summary: string | null;\n recipe: string | null;\n variants: Record<string, string[]> | null;\n dts: string;\n examples: Example[];\n};\n\nexport type Catalog = {\n package: string;\n version: string;\n components: Component[];\n helpers: { file: string; exports: string[]; types: string[] }[];\n};\n\nexport type ThemeToken = { token: string; cssVar: string; value: string; light?: string };\nexport type Theme = Record<string, ThemeToken[]>;\n\nexport type Data = { catalog: Catalog; theme: Theme; guidelines: string };\n\n/** Data is generated next to the bundle by scripts/build-data.mjs (dist/data). */\nexport function loadData(dataDir = join(dirname(fileURLToPath(import.meta.url)), 'data')): Data {\n const read = (file: string) => readFileSync(join(dataDir, file), 'utf8');\n return {\n catalog: JSON.parse(read('catalog.json')) as Catalog,\n theme: JSON.parse(read('theme.json')) as Theme,\n guidelines: read('guidelines.md'),\n };\n}\n","import type { Data } from './data';\n\nexport type Finding = { line: number; rule: string; message: string; fix: string };\n\ntype Rule = {\n rule: string;\n pattern: RegExp;\n message: string;\n fix: string;\n};\n\n/**\n * Line rules from the app-code guide (packages/react/guides/building-with-becket.md).\n * Heuristic on purpose: it flags the patterns agents most often write instead of\n * Becket components; a TODO naming a ticket on the same line acknowledges a known gap.\n */\nconst LINE_RULES: Rule[] = [\n {\n rule: 'no-chakra',\n pattern: /from\\s+['\"]@chakra-ui\\//,\n message: 'Imports Chakra UI.',\n fix: \"Import the equivalent from '@becket-ui/react'; Becket has no provider.\",\n },\n {\n rule: 'no-recipe-classes',\n pattern: /beckui--[\\w-]+/,\n message: 'Uses a generated .beckui--* class name.',\n fix: 'Use the component and its props; recipe classes are not API.',\n },\n {\n rule: 'no-raw-flex-or-grid',\n pattern: /display\\s*:\\s*['\"]?(?:inline-)?(?:flex|grid)/,\n message: 'Lays out with an inline display: flex/grid style.',\n fix: 'Use VStack / HStack / Flex (flex) or SimpleGrid (grid) with gap=\"xs|sm|md|lg|xl\".',\n },\n {\n rule: 'no-raw-heading',\n pattern: /<h[1-6][\\s>]/,\n message: 'Uses a raw h1–h6 element.',\n fix: 'Use <Heading as=\"h1\" size=\"2xl\"> (as sets the level, size sets the look).',\n },\n {\n rule: 'no-raw-text',\n pattern: /<(?:p|span)\\s[^>]*style=\\{\\{[^}]*(?:fontSize|fontWeight|color)\\s*:/,\n message: 'Styles text with an inline style on p/span.',\n fix: 'Use <Text fontSize=\"sm\" color=\"muted\">, or <Text as=\"strong\"> for bold.',\n },\n {\n rule: 'no-raw-divider',\n pattern: /<hr[\\s/>]|height\\s*:\\s*1(?:px)?\\s*[,}]/,\n message: 'Draws a divider with hr or a 1px element.',\n fix: 'Use <Separator /> (orientation=\"vertical\" inside a row).',\n },\n {\n rule: 'no-raw-controls',\n pattern: /<(?:button|input|select|textarea)[\\s>/]/,\n message: 'Uses a raw form control.',\n fix: 'Use Button, TextField / Field + FieldControl, Select, Textarea, Checkbox, RadioGroup + Radio or Switch.',\n },\n {\n rule: 'no-color-literals',\n pattern: /['\"`]#[0-9a-fA-F]{3,8}['\"`]|\\b(?:rgb|rgba|hsl|hsla)\\(/,\n message: 'Uses a literal color.',\n fix: 'Use tokens: color=\"muted\" on Text, or var(--beckui--colors-<token>) in your own CSS (see get_theme).',\n },\n {\n rule: 'no-pixel-spacing',\n pattern: /\\b(?:gap|padding|margin|rowGap|columnGap)(?:Top|Bottom|Left|Right|Inline|Block)?\\s*:\\s*(?:['\"]?\\d+(?:px)?['\"]?)\\s*[,}]/,\n message: 'Sets spacing in pixels.',\n fix: 'Use gap=\"xs|sm|md|lg|xl\" on layout components, or var(--beckui--spacing-<token>) in your own CSS.',\n },\n {\n rule: 'theme-at-root',\n pattern: /data-theme=/,\n message: 'Sets data-theme on an element in JSX.',\n fix: 'Set the theme once on <html data-theme=\"dark|light\"> at the app root.',\n },\n];\n\n/** Imports from '@becket-ui/react' that aren't public exports. */\nfunction unknownImports(code: string, data: Data): Finding[] {\n const known = new Set([\n ...data.catalog.components.flatMap((component) => [...component.exports, ...component.hooks, ...component.types]),\n ...data.catalog.helpers.flatMap((helper) => [...helper.exports, ...helper.types]),\n ]);\n const findings: Finding[] = [];\n const statement = /import\\s+(?:type\\s+)?\\{([^}]*)\\}\\s+from\\s+['\"]@becket-ui\\/react['\"]/g;\n for (const match of code.matchAll(statement)) {\n const line = code.slice(0, match.index).split('\\n').length;\n for (const raw of match[1].split(',')) {\n const name = raw.replace(/^\\s*type\\s+/, '').split(/\\s+as\\s+/)[0].trim();\n if (name && !known.has(name)) {\n findings.push({\n line,\n rule: 'unknown-export',\n message: `\"${name}\" is not exported by @becket-ui/react.`,\n fix: 'Check list_components; compose existing components instead of inventing one.',\n });\n }\n }\n }\n return findings;\n}\n\nexport function reviewUsage(code: string, data: Data): Finding[] {\n const findings: Finding[] = [];\n code.split('\\n').forEach((text, index) => {\n if (/TODO\\s*\\(MAV-\\d+\\)/.test(text)) return;\n for (const rule of LINE_RULES) {\n if (rule.pattern.test(text)) findings.push({ line: index + 1, rule: rule.rule, message: rule.message, fix: rule.fix });\n }\n });\n return [...findings, ...unknownImports(code, data)].sort((a, b) => a.line - b.line);\n}\n\nexport function formatReview(findings: Finding[]): string {\n if (findings.length === 0) {\n return 'No issues found. The code follows the Becket app-code guide for everything this check covers (layout, text, controls, colors, spacing, theme, imports).';\n }\n const rows = findings.map((finding) => `- line ${finding.line} [${finding.rule}] ${finding.message} Fix: ${finding.fix}`);\n return `${findings.length} issue(s):\\n${rows.join('\\n')}\\n\\nFix them and run review_usage again. A line with \"TODO (MAV-…)\" is treated as an acknowledged gap.`;\n}\n","import {\n BECKET_PUBLIC_COLOR_KEYS,\n checkBecketThemeContrast,\n defineBecketTheme,\n deriveBecketTheme,\n type BecketContrastReport,\n type BecketTheme,\n type BecketThemeColors,\n} from '@becket-ui/tokens/theme';\n\n/** Every token group set_theme accepts, as plain strings so agents can pass what users say. */\nexport type SetThemeInput = {\n /** One to three brand colors, most important first. Becket derives the rest. */\n brand?: string[];\n /** Exact color tokens. Kept as given (with `brand`) and checked like every other color. */\n colors?: Record<string, string | Record<string, string>>;\n fonts?: Record<string, string>;\n radii?: Record<string, string>;\n fontSizes?: Record<string, string>;\n spacing?: Record<string, string>;\n sizes?: Record<string, string>;\n density?: Record<string, Record<string, { px?: string; py?: string }>>;\n};\n\n// as const: literal group names, so `input[group]` type-checks against SetThemeInput.\nconst groups = ['colors', 'fonts', 'radii', 'fontSizes', 'spacing', 'sizes', 'density'] as const;\n\nexport function setTheme(input: SetThemeInput): string {\n if (\n !input.brand?.length &&\n !groups.some((group) => input[group] && Object.keys(input[group]).length > 0)\n ) {\n return `Nothing to set. Pass brand colors (\\`brand: [\"#0a3d91\"]\\`) and/or exact tokens: ${groups.join(', ')}. To start from a logo, image URL or brand manual, call suggest_theme first.`;\n }\n\n const notes: { token: string; reason: string }[] = [];\n const theme: BecketTheme = {};\n\n // px → rem (em for the text unit), so browser text-size settings still scale it (WCAG 1.4.4).\n // as const: literal group names, so `input[group]` type-checks.\n for (const group of ['spacing', 'fontSizes', 'radii'] as const) {\n if (!input[group]) continue;\n const cleaned: Record<string, string> = {};\n for (const [key, value] of Object.entries(input[group])) {\n const px = value.trim().match(/^(-?\\d*\\.?\\d+)px$/);\n cleaned[key] = px\n ? `${Number((Number(px[1]) / 16).toFixed(4))}${group === 'spacing' && key === 'textUnit' ? 'em' : 'rem'}`\n : value;\n if (px) {\n notes.push({\n token: `${group}.${key}`,\n reason: `${value} written as ${cleaned[key]} so browser text-size settings still scale it (WCAG 1.4.4).`,\n });\n }\n }\n theme[group] = cleaned;\n }\n\n if (input.fonts) {\n const generic = [\n 'sans-serif',\n 'serif',\n 'monospace',\n 'system-ui',\n 'ui-sans-serif',\n 'ui-monospace',\n 'ui-serif',\n 'cursive',\n 'fantasy',\n ];\n const fonts: Record<string, string> = {};\n for (const [key, family] of Object.entries(input.fonts)) {\n const names = family\n .split(',')\n .map((name) => name.trim())\n .filter(Boolean);\n // Multi-word family names need quotes in CSS; generic families must not have them.\n const quoted = names.map((name) =>\n /^['\"]/.test(name) || !/\\s/.test(name) || generic.includes(name) ? name : `'${name}'`,\n );\n if (\n (key !== 'sans' && key !== 'mono') ||\n names.some((name) => generic.includes(name.toLowerCase()))\n ) {\n fonts[key] = quoted.join(', ');\n continue;\n }\n fonts[key] = [\n ...quoted,\n key === 'sans'\n ? \"system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif\"\n : \"ui-monospace, 'SF Mono', Menlo, Consolas, monospace\",\n ].join(', ');\n notes.push({\n token: `fonts.${key}`,\n reason: `System fallbacks added after ${family}, so text renders before (or without) the webfont.`,\n });\n }\n theme.fonts = fonts;\n notes.push({\n token: 'fonts',\n reason:\n 'Becket only names the font. Load the webfont in your app (@font-face or your font host) and check its license covers the web.',\n });\n }\n\n if (input.sizes) theme.sizes = input.sizes;\n // Zod already checked the shape; defineBecketTheme below rejects unknown component or size keys.\n if (input.density) theme.density = input.density as BecketTheme['density'];\n\n let contrast: BecketContrastReport;\n try {\n if (input.brand?.length) {\n const derived = deriveBecketTheme({\n brand: input.brand,\n // Same as above: defineBecketTheme validates the color keys.\n pinned: input.colors as BecketThemeColors | undefined,\n });\n theme.colors = derived.theme.colors;\n notes.unshift(...derived.notes);\n } else if (input.colors) {\n // Same as above: defineBecketTheme validates the color keys.\n theme.colors = input.colors as BecketThemeColors;\n }\n // defineBecketTheme validates every key; run it before the contrast check so typos come first.\n defineBecketTheme(theme);\n contrast = checkBecketThemeContrast(theme);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const path = message.match(/Unknown Becket theme key \"(?:theme\\.)?([^\"]+)\"/)?.[1];\n if (!path) return `${message} Nothing was generated.`;\n const [group] = path.split('.');\n const keys: Record<string, readonly string[]> = {\n colors: [...BECKET_PUBLIC_COLOR_KEYS.filter((key) => !key.startsWith('light')), 'neutral'],\n fonts: ['sans', 'mono'],\n radii: ['none', 'sm', 'md', 'lg', 'xl', 'full'],\n fontSizes: ['base', 'xs', 'sm', 'md', 'lg', 'xl', '2xl', '3xl', '4xl', '5xl', '6xl'],\n spacing: ['unit', 'textUnit', 'xs', 'sm', 'md', 'lg', 'xl'],\n sizes: ['field'],\n };\n return `${message}. Did you mean ${\n // What people call Becket tokens, mapped to the real key; otherwise list the group's keys.\n new Map([\n ['colors.brand', 'brand (a top-level list of one to three colors)'],\n ['colors.main', 'colors.primary'],\n ['colors.primaryColor', 'colors.primary'],\n ['colors.secondaryColor', 'colors.secondary'],\n ['colors.bg', 'colors.background'],\n ['colors.backgroundColor', 'colors.background'],\n ['colors.foreground', 'colors.text'],\n ['colors.textColor', 'colors.text'],\n ['colors.error', 'colors.danger'],\n ['colors.gray', 'colors.neutral'],\n ['colors.grey', 'colors.neutral'],\n ['fonts.body', 'fonts.sans'],\n ['fonts.heading', 'fonts.sans (Becket uses one sans family for headings and body)'],\n ['fonts.code', 'fonts.mono'],\n ['radii.default', 'radii.md'],\n ['fontSizes.root', 'fontSizes.base'],\n ['spacing.base', 'spacing.unit'],\n ]).get(path) ??\n `one of ${(keys[group] ?? groups).map((key) => (keys[group] ? `${group}.${key}` : key)).join(', ')}`\n }? Nothing was generated.`;\n }\n\n const required = contrast.results.filter((result) => result.level === 'required');\n const flagged = [...contrast.failures, ...contrast.advisories];\n return [\n `# Becket theme${contrast.passes ? '' : ' (contrast failures, see below)'}`,\n '## Contrast',\n [\n contrast.passes\n ? `All ${required.length} required pairs pass WCAG 2.2 AA in dark and light.`\n : `${contrast.failures.length} of ${required.length} required pairs FAIL WCAG 2.2 AA. Don't ship this theme as is.`,\n flagged.length\n ? [\n '| theme | where | ratio | needs | result |',\n '| --- | --- | --- | --- | --- |',\n ...flagged.map(\n (result) =>\n `| ${result.theme} | ${result.use} | ${result.ratio}:1 | ${result.minimum}:1 | ${result.passes ? 'pass' : result.level === 'advisory' ? 'advisory' : '**FAIL**'} |`,\n ),\n ].join('\\n')\n : null,\n contrast.advisories.length\n ? `Advisory rows aren't enforced because Becket's own default theme misses them too, but fix them when you can: ${[...new Set(contrast.advisories.map((result) => result.note))].join(' ')}`\n : null,\n ]\n .filter(Boolean)\n .join('\\n\\n'),\n '## Theme CSS',\n `Write this to a file such as \\`src/becket-theme.css\\` and import it right after \\`@becket-ui/tokens/index.css\\`. It's unlayered, so it wins over Becket's defaults. Keep \\`data-theme\\` on <html>.\\n\\n\\`\\`\\`css\\n${defineBecketTheme(theme)}\\`\\`\\``,\n '## Same theme in code',\n `\\`\\`\\`ts\\nimport { defineBecketTheme } from '@becket-ui/tokens/theme';\\n\\nexport const becketTheme = defineBecketTheme(${JSON.stringify(theme, null, 2)});\\n\\`\\`\\`\\nInject \\`becketTheme\\` in a <style> tag after index.css, or keep the CSS file above. Use one, not both.`,\n notes.length\n ? `## Why each value\\n${notes.map((note) => `- ${note.token}: ${note.reason}`).join('\\n')}`\n : null,\n '## Next',\n contrast.passes\n ? \"Show the user the brand colors and any value that was shaded for contrast, then write the CSS file. Don't hand-edit colors afterwards; call set_theme again so they stay checked.\"\n : `Tell the user which pairs fail and why. ${input.brand?.length ? 'Offer to unpin the failing color so Becket shades it,' : 'Offer to pass the color as `brand` instead of an exact token, so Becket shades it,'} or to pick another value, then call set_theme again. Don't write a failing theme without the user's say-so.`,\n ]\n .filter(Boolean)\n .join('\\n\\n');\n}\n","import { lookup as dnsLookup, type LookupAddress } from 'node:dns';\nimport { readFile, stat } from 'node:fs/promises';\nimport { request } from 'node:https';\nimport { BlockList, isIP } from 'node:net';\nimport { basename, resolve } from 'node:path';\n\nexport type SourceKind = 'png' | 'jpeg' | 'svg' | 'pdf' | 'webp' | 'gif' | 'unknown';\nexport type Source = { bytes: Buffer; kind: SourceKind; label: string };\nexport type SourceInput = { path?: string; url?: string; base64?: string };\n\n/** Brand manuals run to tens of pages of images; logos are far smaller. */\nconst maxBytes = 25 * 1024 * 1024;\nconst timeoutMs = 15_000;\nconst maxRedirects = 5;\n\n/** Detect the format from the bytes, never from the file name or Content-Type. */\nexport function detectKind(bytes: Buffer): SourceKind {\n if (bytes.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])))\n return 'png';\n if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'jpeg';\n if (bytes.subarray(0, 5).toString('latin1') === '%PDF-') return 'pdf';\n if (\n bytes.subarray(0, 4).toString('latin1') === 'RIFF' &&\n bytes.subarray(8, 12).toString('latin1') === 'WEBP'\n )\n return 'webp';\n if (bytes.subarray(0, 4).toString('latin1') === 'GIF8') return 'gif';\n const head = bytes.subarray(0, 4096).toString('utf8').replace(/^/, '').trimStart();\n if (\n (head.startsWith('<?xml') ||\n head.startsWith('<svg') ||\n head.startsWith('<!--') ||\n head.startsWith('<!DOCTYPE svg')) &&\n /<svg[\\s>]/i.test(head)\n )\n return 'svg';\n return 'unknown';\n}\n\n/**\n * Addresses a URL fetch must never reach: loopback, private, link-local (cloud metadata),\n * carrier-grade NAT, multicast, reserved, and their IPv4-mapped IPv6 forms.\n */\nconst blocked = new BlockList();\n// as const: each entry stays a [network, prefix] tuple, the shape addSubnet takes.\nfor (const [network, prefix] of [\n ['0.0.0.0', 8],\n ['10.0.0.0', 8],\n ['100.64.0.0', 10],\n ['127.0.0.0', 8],\n ['169.254.0.0', 16],\n ['172.16.0.0', 12],\n ['192.0.0.0', 24],\n ['192.0.2.0', 24],\n ['192.168.0.0', 16],\n ['198.18.0.0', 15],\n ['198.51.100.0', 24],\n ['203.0.113.0', 24],\n ['224.0.0.0', 4],\n ['240.0.0.0', 4],\n] as const) {\n blocked.addSubnet(network, prefix, 'ipv4');\n}\n// as const: each entry stays a [network, prefix] tuple, the shape addSubnet takes.\nfor (const [network, prefix] of [\n ['::', 128],\n ['::1', 128],\n ['fc00::', 7],\n ['fe80::', 10],\n ['ff00::', 8],\n ['2001:db8::', 32],\n ['64:ff9b::', 96],\n] as const) {\n blocked.addSubnet(network, prefix, 'ipv6');\n}\n\nexport function isPublicAddress(address: string): boolean {\n const family = isIP(address);\n if (family === 0) return false;\n if (family === 4) return !blocked.check(address, 'ipv4');\n // IPv4-mapped IPv6 (::ffff:127.0.0.1, ::ffff:7f00:1) is the IPv4 host underneath. The URL\n // parser normalizes every spelling to the hex form.\n const mapped = new URL(`http://[${address}]`).hostname.match(\n /^\\[::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})\\]$/,\n );\n if (mapped) {\n const [high, low] = [Number.parseInt(mapped[1], 16), Number.parseInt(mapped[2], 16)];\n return isPublicAddress([high >> 8, high & 255, low >> 8, low & 255].join('.'));\n }\n return !blocked.check(address, 'ipv6');\n}\n\n/** Every URL, the first and each redirect, is checked here before it's requested. */\nfunction download(raw: string, redirects: number): Promise<Buffer> {\n return new Promise((resolvePromise, reject) => {\n // A throw in here rejects the promise.\n let url: URL;\n try {\n url = new URL(raw);\n } catch {\n throw new Error(`\"${raw}\" isn't a URL.`);\n }\n if (url.protocol !== 'https:')\n throw new Error(`Only https URLs are fetched, not ${url.protocol}//.`);\n if (url.username || url.password) throw new Error('URLs with credentials are refused.');\n const host = url.hostname.replace(/^\\[|\\]$/g, '');\n if (isIP(host) && !isPublicAddress(host))\n throw new Error(\n `${host} is a private or reserved address; only public https URLs are fetched.`,\n );\n if (\n host === 'localhost' ||\n host.endsWith('.localhost') ||\n host.endsWith('.local') ||\n host.endsWith('.internal')\n ) {\n throw new Error(`${host} is a local host name; only public https URLs are fetched.`);\n }\n\n const req = request(\n url,\n {\n // Resolve, then refuse private addresses. This runs at connect time, so a DNS answer that\n // changes between a check and the request (rebinding) can't reach an internal host.\n lookup: (hostname, options, callback) => {\n dnsLookup(hostname, { ...options, all: true }, (error, addresses) => {\n if (error) return callback(error, '', 0);\n // With `all: true` Node passes an array, but its callback type only models the\n // single-address form; the same goes for the reply below.\n const list = addresses as unknown as LookupAddress[];\n const refused = list.find((entry) => !isPublicAddress(entry.address));\n if (refused || list.length === 0) {\n return callback(\n new Error(\n `${hostname} resolves to a private or reserved address (${refused?.address ?? 'none'}); only public https URLs are fetched.`,\n ),\n '',\n 0,\n );\n }\n if (options.all) {\n // See above: the all-addresses reply isn't in Node's callback type.\n return (callback as unknown as (error: null, addresses: LookupAddress[]) => void)(\n null,\n list,\n );\n }\n return callback(null, list[0].address, list[0].family);\n });\n },\n timeout: timeoutMs,\n headers: { accept: 'image/*, application/pdf', 'user-agent': '@becket-ui/mcp' },\n },\n (response) => {\n const status = response.statusCode ?? 0;\n if (status >= 300 && status < 400 && response.headers.location) {\n response.resume();\n if (redirects >= maxRedirects)\n return reject(new Error(`More than ${maxRedirects} redirects.`));\n try {\n return resolvePromise(\n download(new URL(response.headers.location, url).toString(), redirects + 1),\n );\n } catch (error) {\n // A Location that can't be read as a URL.\n return reject(error);\n }\n }\n if (status !== 200) {\n response.resume();\n return reject(new Error(`The server answered ${status}.`));\n }\n const declared = Number(response.headers['content-length'] ?? 0);\n if (declared > maxBytes) {\n response.destroy();\n return reject(\n new Error(\n `The file is ${(declared / 1048576).toFixed(1)} MB; the limit is ${maxBytes / 1048576} MB.`,\n ),\n );\n }\n const chunks: Buffer[] = [];\n let size = 0;\n response.on('data', (chunk: Buffer) => {\n size += chunk.length;\n if (size > maxBytes) {\n response.destroy();\n reject(new Error(`The file is over the ${maxBytes / 1048576} MB limit.`));\n return;\n }\n chunks.push(chunk);\n });\n response.on('end', () => resolvePromise(Buffer.concat(chunks)));\n response.on('error', reject);\n },\n );\n req.on('timeout', () => req.destroy(new Error(`No answer within ${timeoutMs / 1000} s.`)));\n req.on('error', reject);\n req.end();\n });\n}\n\n/** Read an image or PDF from a local path, an https URL or base64 (a data: URL works too). */\nexport async function loadSource(input: SourceInput): Promise<Source> {\n if ([input.path, input.url, input.base64].filter(Boolean).length !== 1)\n throw new Error('Pass exactly one of path, url or base64.');\n\n let bytes: Buffer;\n let label: string;\n if (input.path) {\n const path = resolve(input.path);\n const info = await stat(path).catch(() => null);\n if (!info?.isFile()) throw new Error(`No file at ${path}.`);\n if (info.size > maxBytes)\n throw new Error(\n `${basename(path)} is ${(info.size / 1048576).toFixed(1)} MB; the limit is ${maxBytes / 1048576} MB.`,\n );\n bytes = await readFile(path);\n label = basename(path);\n } else if (input.url) {\n bytes = await download(input.url, 0);\n label = input.url;\n } else {\n const data = (input.base64 ?? '').replace(/^data:[^;,]+;base64,/, '').replace(/\\s+/g, '');\n if (!/^[A-Za-z0-9+/]+={0,2}$/.test(data)) throw new Error(\"base64 isn't valid base64.\");\n if ((data.length * 3) / 4 > maxBytes)\n throw new Error(`The data is over the ${maxBytes / 1048576} MB limit.`);\n bytes = Buffer.from(data, 'base64');\n label = 'base64 data';\n }\n if (bytes.length === 0) throw new Error('The file is empty.');\n return { bytes, kind: detectKind(bytes), label };\n}\n","import { colorDistance, deriveBecketTheme, formatHex, parseColor } from '@becket-ui/tokens/theme';\n\nimport { extractImageColors, neutralChroma, type ExtractedColor } from './extractColors';\nimport { loadSource, type SourceInput } from './loadSource';\n\nexport type SuggestThemeInput = SourceInput & {\n /** Colors the agent read from an image it can see but can't pass as a file (e.g. pasted in chat). */\n colors?: string[];\n};\n\n/** What a source says outright (a brand manual), as opposed to what was sampled from pixels. */\nexport type Stated = {\n colors: { hex: string; name?: string; page: number }[];\n fonts: { family: string; page: number }[];\n radii: { value: string; page: number }[];\n baseSize: { value: string; page: number }[];\n};\n\nexport type Findings = {\n label: string;\n method: string;\n colors: ExtractedColor[];\n stated?: Stated;\n skipped: string[];\n};\n\n/** Up to three brand colors, most visual weight first, distinct from each other. */\nexport function pickBrand(findings: Findings): string[] {\n // Stated colors (a manual) always come first, in the manual's order.\n const candidates = [\n ...(findings.stated?.colors ?? []).flatMap((entry) => {\n const color = parseColor(entry.hex);\n return color ? [{ hex: entry.hex, color }] : [];\n }),\n ...findings.colors\n .filter((color) => color.role !== 'background')\n // A gradient shows up as several close shades of one hue (ΔE OK under 0.1, which most\n // people read as one color); weigh each color with its family.\n .map((entry, _, sampled) => ({\n ...entry,\n family: sampled\n .filter((other) => colorDistance(other.color, entry.color) < 0.1)\n .reduce((sum, other) => sum + other.share, 0),\n }))\n // Under 5% of the artwork is a one-off graphic, not the brand.\n .filter((entry) => entry.family >= 0.05)\n .toSorted((a, b) => b.family - a.family),\n ];\n const picked: typeof candidates = [];\n for (const candidate of candidates) {\n if (candidate.color.C < neutralChroma) continue;\n // Brand colors are different hues. Manuals print tint ramps (one hue, many lightnesses);\n // those are shades of one brand color, not three.\n if (\n picked.some((other) => {\n const gap = Math.abs(other.color.h - candidate.color.h);\n return Math.min(gap, 360 - gap) < 30;\n })\n )\n continue;\n picked.push(candidate);\n if (picked.length === 3) break;\n }\n if (picked.length > 0) return picked.map((entry) => entry.hex);\n // A black, gray or white logo: use its darkest neutral, and Becket stays untinted.\n const darkest = candidates\n .filter((entry) => entry.color.L < 0.9)\n .toSorted((a, b) => a.color.L - b.color.L)[0];\n return darkest ? [darkest.hex] : [];\n}\n\nexport function formatSuggestion(findings: Findings): string {\n const brand = pickBrand(findings);\n const stated = findings.stated;\n const lines: string[] = [\n `# Brand suggestion from ${findings.label}`,\n `Read as: ${findings.method}.`,\n ];\n\n if (stated?.colors.length) {\n lines.push(\n '## Colors the source states',\n // One entry: sections are joined with blank lines, which would break a Markdown table apart.\n [\n '| color | name | page |',\n '| --- | --- | --- |',\n ...stated.colors.map((entry) => `| ${entry.hex} | ${entry.name ?? ''} | ${entry.page} |`),\n ].join('\\n'),\n );\n }\n if (findings.colors.length) {\n lines.push(\n stated ? '## Colors sampled from its artwork' : '## Colors found',\n [\n '| color | share | role |',\n '| --- | --- | --- |',\n ...findings.colors\n .slice(0, 10)\n .map((color) => `| ${color.hex} | ${Math.round(color.share * 100)}% | ${color.role} |`),\n ].join('\\n'),\n );\n }\n if (findings.skipped.length)\n lines.push(\n `Skipped (not a color Becket can read): ${findings.skipped.slice(0, 10).join(', ')}.`,\n );\n\n if (brand.length === 0) {\n lines.push(\n '## Next',\n 'No brand color found. Ask the user for their brand colors (hex is best), then call set_theme with `brand`.',\n );\n return lines.join('\\n\\n');\n }\n\n const fonts = stated?.fonts ?? [];\n const steps = [\n 'brand colors',\n fonts.length ? 'brand font' : null,\n stated?.radii.length || stated?.baseSize.length ? 'corners and text size' : null,\n ].filter(Boolean);\n lines.push(\n '## Guided setup',\n `Ask the user one step at a time and wait for each answer. ${steps.length} step${steps.length > 1 ? 's' : ''}: ${steps.join(', then ')}.`,\n `### Step 1 of ${steps.length}: brand colors`,\n `Ask: \"These look like your brand colors: ${brand.join(', ')}. Which should Becket use, most important first?\" Offer:`,\n ...[\n { label: 'Recommended', brand },\n ...(brand.length >= 2\n ? [\n { label: 'Swap the first two', brand: [brand[1], brand[0], ...brand.slice(2)] },\n { label: 'First color only', brand: [brand[0]] },\n ]\n : []),\n ].map((option, index) => {\n // Preview each option with the real derivation, so the user sees what they'd get.\n const { theme, contrast, notes } = deriveBecketTheme({ brand: option.brand });\n const [button, link] = [\n theme.colors?.primary,\n typeof theme.colors?.link === 'object' ? theme.colors.link.light : theme.colors?.link,\n ].map((value) => {\n const color = typeof value === 'string' ? parseColor(value) : null;\n return color ? formatHex(color) : String(value);\n });\n return `${index + 1}. ${option.label}: \\`${JSON.stringify(option.brand)}\\` — buttons ${button}${notes.some((note) => note.token === 'primary' && /lightened/.test(note.reason)) ? ` (lightened from ${option.brand[0]} for readable labels)` : ''}, light-theme links ${link}; ${contrast.passes ? 'passes AA in dark and light' : `${contrast.failures.length} AA failures`}`;\n }),\n 'Or the user gives their own hex values. Becket shades any color that would fail contrast and says why.',\n );\n\n let step = 1;\n if (fonts.length) {\n step += 1;\n const families = [...new Set(fonts.map((font) => font.family))];\n lines.push(\n `### Step ${step} of ${steps.length}: brand font`,\n `Ask: \"Your manual uses ${families.slice(0, 3).join(', ')}. Use ${families[0]} for Becket's text?\" Offer: yes (\\`fonts: { \"sans\": \"${families[0]}\" }\\`), another of those, or keep Becket's system font. Mention the app must load the webfont and its license must cover the web.`,\n );\n }\n if (stated?.radii.length || stated?.baseSize.length) {\n step += 1;\n const radius = stated.radii[0];\n const base = stated.baseSize[0];\n lines.push(\n `### Step ${step} of ${steps.length}: corners and text size`,\n `Ask: \"Your manual sets ${[\n radius && `corner radius ${radius.value} (page ${radius.page})`,\n base && `body text ${base.value} (page ${base.page})`,\n ]\n .filter(Boolean)\n .join(' and ')}. Apply ${radius && base ? 'them' : 'it'} to Becket?\" If yes, add ${[\n radius && `radii: { \"md\": \"${radius.value}\" }`,\n base && `fontSizes: { \"base\": \"${base.value}\" }`,\n ]\n .filter(Boolean)\n .join(', ')}. Otherwise keep Becket's defaults.`,\n );\n }\n if (!fonts.length) {\n lines.push(\n stated ? 'No font name found in the manual.' : 'An image has no font name to read.',\n 'If the user mentions a brand font, add `fonts: { \"sans\": \"<family>\" }`; otherwise keep Becket\\'s system font. Don\\'t guess a font from a logo.',\n );\n }\n lines.push(\n '### Finish',\n `Call set_theme with only what the user confirmed, e.g. \\`${JSON.stringify({ brand })}\\`. It returns the CSS to write and a contrast report. Don't call set_theme before the user confirms the brand colors.`,\n );\n return lines.join('\\n\\n');\n}\n\nexport async function suggestTheme(input: SuggestThemeInput): Promise<string> {\n try {\n if (input.colors?.length && !input.path && !input.url && !input.base64) {\n return formatSuggestion({\n label: 'the colors you read from the image',\n method: 'colors passed by the agent, in the order given',\n colors: input.colors.map((value, _, all): ExtractedColor => {\n const color = parseColor(value);\n if (!color)\n throw new Error(`Can't read the color \"${value}\". Use hex, rgb(), hsl() or oklch().`);\n return {\n hex: formatHex(color),\n color,\n share: 1 / all.length,\n role: color.C < neutralChroma ? 'neutral' : 'brand',\n };\n }),\n skipped: [],\n });\n }\n const source = await loadSource(input);\n if (source.kind === 'pdf') {\n const { extractPDF } = await import('./extractPDF');\n return formatSuggestion(await extractPDF(source));\n }\n const { colors, method, skipped } = extractImageColors(source);\n return formatSuggestion({ label: source.label, method, colors, skipped });\n } catch (error) {\n return `Couldn't read that source: ${error instanceof Error ? error.message : String(error)}\\n\\nIf the image is only in the chat (pasted), read its main colors yourself and call suggest_theme with \\`colors: [\"#…\", \"#…\"]\\`, or ask the user for the file path.`;\n }\n}\n","import type { Component, Data } from './data';\n\n/**\n * Tool handlers as plain functions returning text, so they're testable without\n * a transport. server.ts wires them to MCP.\n */\n\nexport function installation(data: Data): string {\n const { version } = data.catalog;\n return `# Installing Becket UI (@becket-ui/react ${version})\n\npnpm add @becket-ui/react @becket-ui/tokens\n\n1. Import the CSS once, at the app entry:\n import '@becket-ui/tokens/index.css';\n2. Put the theme on <html>: <html data-theme=\"dark\"> (dark is the default) or \"light\".\n Set it at the app root, never inside a screen. There is no provider and no theme wrapper.\n3. Import components from '@becket-ui/react':\n import { Button, Card, Container, Stack, Text } from '@becket-ui/react';\n\n- Panda CSS is not required: styles ship prebuilt in index.css. Don't copy .beckui--* class names.\n- index.css paints the page background, text color and font from the theme.\n- Components marked client in list_components use state or effects ('use client'); the rest render in React Server Components.\n\nTo brand Becket, call set_theme with brand colors or tokens, or suggest_theme with a logo, image URL or brand manual.\n\nBefore writing UI, call get_guidelines (the app-code guide). Before finishing, call review_usage on your code.`;\n}\n\nexport function listComponents(data: Data): string {\n const byGroup = new Map<string, Component[]>();\n for (const component of data.catalog.components) {\n const group = component.group ?? 'Other';\n byGroup.set(group, [...(byGroup.get(group) ?? []), component]);\n }\n const sections = [...byGroup.entries()].map(([group, components]) => {\n const rows = components.map((component) => {\n const parts = component.exports.filter((name) => name !== component.name);\n const tags = [component.client ? 'client' : 'server-safe', component.examples.length ? `${component.examples.length} examples` : null]\n .filter(Boolean)\n .join(', ');\n return `- ${component.name}${parts.length ? ` (also: ${parts.join(', ')})` : ''} [${tags}]${component.summary ? ` — ${component.summary.split('\\n')[0]}` : ''}`;\n });\n return `## ${group}\\n${rows.join('\\n')}`;\n });\n return `@becket-ui/react ${data.catalog.version}: ${data.catalog.components.length} component files.\\nUse get_component_props for exact props and get_component_example for usage.\\n\\n${sections.join('\\n\\n')}`;\n}\n\n/** Find a component by its name, any of its exports (e.g. CardHeader, Thead, SearchIcon) or its file. */\nexport function findComponent(data: Data, name: string): Component | undefined {\n const wanted = name.trim().toLowerCase();\n return data.catalog.components.find(\n (component) =>\n component.name.toLowerCase() === wanted ||\n component.file.toLowerCase() === wanted ||\n component.exports.some((exported) => exported.toLowerCase() === wanted),\n );\n}\n\nfunction notFound(data: Data, name: string): string {\n const names = data.catalog.components.map((component) => component.name).join(', ');\n return `No Becket component named \"${name}\". Available: ${names}.`;\n}\n\nexport function componentProps(data: Data, name: string): string {\n const component = findComponent(data, name);\n if (!component) return notFound(data, name);\n const variants = component.variants\n ? Object.entries(component.variants)\n .map(([prop, values]) => `- ${prop}: ${values.map((value) => `\"${value}\"`).join(' | ')}`)\n .join('\\n')\n : null;\n return [\n `# ${component.name}${component.group ? ` (${component.group})` : ''}`,\n component.summary,\n `Exports: ${component.exports.join(', ')}${component.hooks.length ? `; hooks: ${component.hooks.join(', ')}` : ''}`,\n `Rendering: ${component.client ? \"client component ('use client': state, effects or browser APIs)\" : 'no client JS required; safe in React Server Components'}`,\n variants ? `## Recipe variants (exact values)\\n${variants}` : null,\n `## Type declarations\\n\\`\\`\\`ts\\n${component.dts}\\n\\`\\`\\``,\n ]\n .filter(Boolean)\n .join('\\n\\n');\n}\n\nexport function componentExample(data: Data, name: string, story?: string): string {\n const component = findComponent(data, name);\n if (!component) return notFound(data, name);\n if (component.examples.length === 0) {\n return `${component.name} has no examples yet. Read get_component_props for its API.`;\n }\n const chosen = story\n ? component.examples.filter((example) => example.name.toLowerCase() === story.trim().toLowerCase())\n : component.examples;\n if (chosen.length === 0) {\n return `No example \"${story}\" for ${component.name}. Available: ${component.examples.map((example) => example.name).join(', ')}.`;\n }\n const note =\n 'These are Storybook stories. In app code, import from \"@becket-ui/react\", drop `args`/`Story` typing, and follow get_guidelines.';\n return `# ${component.name} examples\\n${note}\\n\\n${chosen.map((example) => `## ${example.name}\\n\\`\\`\\`tsx\\n${example.code}\\n\\`\\`\\``).join('\\n\\n')}`;\n}\n\nexport function theme(data: Data, group?: string): string {\n const groups = group ? Object.entries(data.theme).filter(([name]) => name === group) : Object.entries(data.theme);\n if (groups.length === 0) return `Unknown token group \"${group}\". Groups: ${Object.keys(data.theme).join(', ')}.`;\n const sections = groups.map(([name, tokens]) => {\n const rows = tokens.map((token) => `| ${token.token} | \\`${token.cssVar}\\` | ${token.value} | ${token.light ?? 'same'} |`);\n return `## ${name}\\n| token | CSS variable | dark (default) | light |\\n| --- | --- | --- | --- |\\n${rows.join('\\n')}`;\n });\n return `Becket tokens. In components, pass token names as props (gap=\"md\", color=\"muted\"). In your own CSS, use the CSS variables. Never hex, rgb() or px.\\n\\n${sections.join('\\n\\n')}`;\n}\n\n/** Topics are the guide's numbered sections, e.g. \"layout\" matches \"2. Must use a Becket component…\". */\nexport function guidelines(data: Data, topic?: string): string {\n const sections = data.guidelines.split(/\\n(?=## )/);\n if (!topic) return data.guidelines;\n const wanted = topic.trim().toLowerCase();\n const matches = sections.filter((section) => section.split('\\n')[0].toLowerCase().includes(wanted));\n if (matches.length > 0) return matches.join('\\n\\n');\n const titles = sections.slice(1).map((section) => section.split('\\n')[0].replace(/^## /, ''));\n return `No section matches \"${topic}\". Sections:\\n${titles.map((title) => `- ${title}`).join('\\n')}`;\n}\n"],"mappings":";;;;;;;;;;;;;;AACA,SAAS,4BAA4B;;;ACDrC,SAAS,iBAAiB;AAC1B,SAAS,SAAS;;;ACDlB,SAAS,oBAAoB;AAC7B,SAAS,SAAS,YAAY;AAC9B,SAAS,qBAAqB;AAiCvB,SAAS,SAAS,UAAU,KAAK,QAAQ,cAAc,YAAY,GAAG,CAAC,GAAG,MAAM,GAAS;AAC9F,QAAM,OAAO,CAAC,SAAiB,aAAa,KAAK,SAAS,IAAI,GAAG,MAAM;AACvE,SAAO;AAAA,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EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,EAAE,IAAI,CAAC,EAAE,SAAS,EAAE,SAAS,2FAA2F;AAAA,MAC3J;AAAA,MACA,aAAa,EAAE,cAAc,MAAM,eAAe,KAAK;AAAA,IACzD;AAAA,IACA,OAAO,UAAU,KAAK,MAAM,aAAa,KAAK,CAAC;AAAA,EACjD;AAEA,SAAO;AACT;;;AD3IA,MAAM,aAAa,EAAE,QAAQ,IAAI,qBAAqB,CAAC;","names":["text","theme","theme","groups"]}
|
|
1
|
+
{"version":3,"sources":["../src/server.ts","../src/createServer.ts","../src/data.ts","../src/review.ts","../src/theme/setTheme.ts","../src/theme/loadSource.ts","../src/theme/suggestTheme.ts","../src/tools.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\n\nimport { createServer } from './createServer';\n\nawait createServer().connect(new StdioServerTransport());\n","import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\n\nimport { loadData, type Data } from './data';\nimport { formatReview, reviewUsage } from './review';\nimport { setTheme } from './theme/setTheme';\nimport { suggestTheme } from './theme/suggestTheme';\nimport { componentExample, componentProps, guidelines, installation, listComponents, theme } from './tools';\n\n// as const: the MCP SDK types a text block's `type` as the literal 'text'.\nconst text = (value: string) => ({ content: [{ type: 'text' as const, text: value }] });\n\nexport function createServer(data: Data = loadData()): McpServer {\n const server = new McpServer({ name: 'becket-ui', version: data.catalog.version });\n const readOnly = { readOnlyHint: true, openWorldHint: false };\n\n server.registerTool(\n 'installation',\n {\n title: 'Install Becket UI',\n description: 'How to install and set up Becket UI in a React app: packages, the one CSS import, and the theme on <html>.',\n annotations: readOnly,\n },\n async () => text(installation(data)),\n );\n\n server.registerTool(\n 'list_components',\n {\n title: 'List Becket components',\n description: 'Every public Becket UI component by group, with its parts and whether it needs client JS.',\n annotations: readOnly,\n },\n async () => text(listComponents(data)),\n );\n\n server.registerTool(\n 'get_component_props',\n {\n title: 'Get component props',\n description: 'Exact props of a Becket component (TypeScript declarations) and its recipe variant values. Accepts a component or part name, e.g. Button, CardHeader, SearchIcon.',\n inputSchema: { name: z.string().describe('Component or part name, e.g. \"Card\" or \"CardHeader\"') },\n annotations: readOnly,\n },\n async ({ name }) => text(componentProps(data, name)),\n );\n\n server.registerTool(\n 'get_component_example',\n {\n title: 'Get component examples',\n description: 'Usage examples for a Becket component (its Storybook stories). Optionally pick one story by name.',\n inputSchema: {\n name: z.string().describe('Component name, e.g. \"Dialog\"'),\n story: z.string().optional().describe('Story name, e.g. \"Open\"'),\n },\n annotations: readOnly,\n },\n async ({ name, story }) => text(componentExample(data, name, story)),\n );\n\n server.registerTool(\n 'get_theme',\n {\n title: 'Get theme tokens',\n description: 'Becket design tokens with dark and light values: colors, spacing, radii, sizes, font-sizes, shadows.',\n inputSchema: {\n group: z.enum(['colors', 'spacing', 'radii', 'sizes', 'font-sizes', 'shadows']).optional().describe('One token group; omit for all'),\n },\n annotations: readOnly,\n },\n async ({ group }) => text(theme(data, group)),\n );\n\n server.registerTool(\n 'get_guidelines',\n {\n title: 'Get the Becket app-code guide',\n description: 'Rules for writing app code with Becket: which component replaces each raw element, props-then-tokens styling, abstraction, state, accessibility. Read before writing UI.',\n inputSchema: {\n topic: z.string().optional().describe('Section filter, e.g. \"component\", \"tokens\", \"accessibility\", \"example\", \"checklist\"'),\n },\n annotations: readOnly,\n },\n async ({ topic }) => text(guidelines(data, topic)),\n );\n\n server.registerTool(\n 'review_usage',\n {\n title: 'Review Becket usage',\n description: 'Check React code against the Becket app-code guide: raw layout/text/controls, literal colors, pixel spacing, recipe classes, Chakra imports, unknown exports. Run before finishing.',\n inputSchema: { code: z.string().describe('The TSX/JSX source to review') },\n annotations: readOnly,\n },\n async ({ code }) => text(formatReview(reviewUsage(code, data))),\n );\n\n const tokens = z.record(z.string(), z.string());\n server.registerTool(\n 'set_theme',\n {\n title: 'Set a brand theme',\n description:\n 'Turn brand tokens into Becket theme CSS that passes WCAG 2.2 AA in dark and light. Give one to three brand colors (Becket derives every color token) and/or exact tokens. Returns the CSS to write, the same theme as defineBecketTheme() code, why each value was chosen, and a contrast report. Writes nothing; you write the file. For a logo, image URL or brand manual, call suggest_theme first.',\n inputSchema: {\n brand: z.array(z.string()).min(1).max(3).optional().describe('Brand colors, most important first: hex, rgb(), hsl() or oklch()'),\n colors: z\n .record(z.string(), z.union([z.string(), z.record(z.string(), z.string())]))\n .optional()\n .describe('Exact color tokens to keep, e.g. { \"background\": { \"dark\": \"#101820\", \"light\": \"#ffffff\" } }. With brand, these are pinned and the rest is derived.'),\n fonts: tokens.optional().describe('{ \"sans\": \"Inter\", \"mono\": \"JetBrains Mono\" }'),\n radii: tokens.optional().describe('none, sm, md, lg, xl, full, e.g. { \"md\": \"0.25rem\" }'),\n fontSizes: tokens.optional().describe('{ \"base\": \"1rem\" } resizes all text; xs–6xl override single steps'),\n spacing: tokens.optional().describe('{ \"unit\": \"0.25rem\" } resizes all spacing; textUnit (em) spacing inside text'),\n sizes: tokens.optional().describe('{ \"field\": \"16rem\" }'),\n density: z\n .record(z.string(), z.record(z.string(), z.object({ px: z.string().optional(), py: z.string().optional() })))\n .optional()\n .describe('Component padding, e.g. { \"button\": { \"md\": { \"px\": \"0.75rem\" } } }'),\n },\n annotations: readOnly,\n },\n async (input) => text(setTheme(input)),\n );\n\n server.registerTool(\n 'suggest_theme',\n {\n title: 'Suggest a brand theme',\n description:\n \"Read a logo (PNG, JPEG, SVG) or a brand manual (PDF) and suggest Becket brand tokens: colors, plus fonts, corner radius and text size when a manual states them. Returns what it found and a step-by-step script: ask the user one decision at a time, then call set_theme with what they confirm. Pass exactly one of path, url (public https) or base64. For an image only pasted in chat, pass the colors you see in `colors` instead.\",\n inputSchema: {\n path: z.string().optional().describe('Local file path, absolute or relative to the working directory'),\n url: z.string().optional().describe('Public https URL of the image or PDF'),\n base64: z.string().optional().describe('File contents as base64 or a data: URL'),\n colors: z.array(z.string()).min(1).max(8).optional().describe('Colors you read from an image you can see but cannot pass as a file, most prominent first'),\n },\n annotations: { readOnlyHint: true, openWorldHint: true },\n },\n async (input) => text(await suggestTheme(input)),\n );\n\n return server;\n}\n","import { readFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nexport type Example = { name: string; code: string };\n\nexport type Component = {\n name: string;\n file: string;\n exports: string[];\n hooks: string[];\n types: string[];\n group: string | null;\n storyTitle: string | null;\n client: boolean;\n summary: string | null;\n recipe: string | null;\n variants: Record<string, string[]> | null;\n dts: string;\n examples: Example[];\n};\n\nexport type Catalog = {\n package: string;\n version: string;\n components: Component[];\n helpers: { file: string; exports: string[]; types: string[] }[];\n};\n\nexport type ThemeToken = { token: string; cssVar: string; value: string; light?: string };\nexport type Theme = Record<string, ThemeToken[]>;\n\nexport type Data = { catalog: Catalog; theme: Theme; guidelines: string };\n\nexport function loadData(dataDir = join(dirname(fileURLToPath(import.meta.url)), 'data')): Data {\n const read = (file: string) => readFileSync(join(dataDir, file), 'utf8');\n return {\n catalog: JSON.parse(read('catalog.json')) as Catalog,\n theme: JSON.parse(read('theme.json')) as Theme,\n guidelines: read('guidelines.md'),\n };\n}\n","import type { Data } from './data';\n\nexport type Finding = { line: number; rule: string; message: string; fix: string };\n\ntype Rule = {\n rule: string;\n pattern: RegExp;\n message: string;\n fix: string;\n};\n\n// Heuristic on purpose: it flags the patterns agents most often write instead of Becket components.\nconst LINE_RULES: Rule[] = [\n {\n rule: 'no-chakra',\n pattern: /from\\s+['\"]@chakra-ui\\//,\n message: 'Imports Chakra UI.',\n fix: \"Import the equivalent from '@becket-ui/react'; Becket has no provider.\",\n },\n {\n rule: 'no-recipe-classes',\n pattern: /beckui--[\\w-]+/,\n message: 'Uses a generated .beckui--* class name.',\n fix: 'Use the component and its props; recipe classes are not API.',\n },\n {\n rule: 'no-raw-flex-or-grid',\n pattern: /display\\s*:\\s*['\"]?(?:inline-)?(?:flex|grid)/,\n message: 'Lays out with an inline display: flex/grid style.',\n fix: 'Use VStack / HStack / Flex (flex) or SimpleGrid (grid) with gap=\"xs|sm|md|lg|xl\".',\n },\n {\n rule: 'no-raw-heading',\n pattern: /<h[1-6][\\s>]/,\n message: 'Uses a raw h1–h6 element.',\n fix: 'Use <Heading as=\"h1\" size=\"2xl\"> (as sets the level, size sets the look).',\n },\n {\n rule: 'no-raw-text',\n pattern: /<(?:p|span)\\s[^>]*style=\\{\\{[^}]*(?:fontSize|fontWeight|color)\\s*:/,\n message: 'Styles text with an inline style on p/span.',\n fix: 'Use <Text fontSize=\"sm\" color=\"muted\">, or <Text as=\"strong\"> for bold.',\n },\n {\n rule: 'no-raw-divider',\n pattern: /<hr[\\s/>]|height\\s*:\\s*1(?:px)?\\s*[,}]/,\n message: 'Draws a divider with hr or a 1px element.',\n fix: 'Use <Separator /> (orientation=\"vertical\" inside a row).',\n },\n {\n rule: 'no-raw-controls',\n pattern: /<(?:button|input|select|textarea)[\\s>/]/,\n message: 'Uses a raw form control.',\n fix: 'Use Button, TextField / Field + FieldControl, Select, Textarea, Checkbox, RadioGroup + Radio or Switch.',\n },\n {\n rule: 'no-color-literals',\n pattern: /['\"`]#[0-9a-fA-F]{3,8}['\"`]|\\b(?:rgb|rgba|hsl|hsla)\\(/,\n message: 'Uses a literal color.',\n fix: 'Use tokens: color=\"muted\" on Text, or var(--beckui--colors-<token>) in your own CSS (see get_theme).',\n },\n {\n rule: 'no-pixel-spacing',\n pattern: /\\b(?:gap|padding|margin|rowGap|columnGap)(?:Top|Bottom|Left|Right|Inline|Block)?\\s*:\\s*(?:['\"]?\\d+(?:px)?['\"]?)\\s*[,}]/,\n message: 'Sets spacing in pixels.',\n fix: 'Use gap=\"xs|sm|md|lg|xl\" on layout components, or var(--beckui--spacing-<token>) in your own CSS.',\n },\n {\n rule: 'theme-at-root',\n pattern: /data-theme=/,\n message: 'Sets data-theme on an element in JSX.',\n fix: 'Set the theme once on <html data-theme=\"dark|light\"> at the app root.',\n },\n];\n\nfunction unknownImports(code: string, data: Data): Finding[] {\n const known = new Set([\n ...data.catalog.components.flatMap((component) => [...component.exports, ...component.hooks, ...component.types]),\n ...data.catalog.helpers.flatMap((helper) => [...helper.exports, ...helper.types]),\n ]);\n const findings: Finding[] = [];\n const statement = /import\\s+(?:type\\s+)?\\{([^}]*)\\}\\s+from\\s+['\"]@becket-ui\\/react['\"]/g;\n for (const match of code.matchAll(statement)) {\n const line = code.slice(0, match.index).split('\\n').length;\n for (const raw of match[1].split(',')) {\n const name = raw.replace(/^\\s*type\\s+/, '').split(/\\s+as\\s+/)[0].trim();\n if (name && !known.has(name)) {\n findings.push({\n line,\n rule: 'unknown-export',\n message: `\"${name}\" is not exported by @becket-ui/react.`,\n fix: 'Check list_components; compose existing components instead of inventing one.',\n });\n }\n }\n }\n return findings;\n}\n\nexport function reviewUsage(code: string, data: Data): Finding[] {\n const findings: Finding[] = [];\n code.split('\\n').forEach((text, index) => {\n if (/TODO\\s*\\(MAV-\\d+\\)/.test(text)) return;\n for (const rule of LINE_RULES) {\n if (rule.pattern.test(text)) findings.push({ line: index + 1, rule: rule.rule, message: rule.message, fix: rule.fix });\n }\n });\n return [...findings, ...unknownImports(code, data)].sort((a, b) => a.line - b.line);\n}\n\nexport function formatReview(findings: Finding[]): string {\n if (findings.length === 0) {\n return 'No issues found. The code follows the Becket app-code guide for everything this check covers (layout, text, controls, colors, spacing, theme, imports).';\n }\n const rows = findings.map((finding) => `- line ${finding.line} [${finding.rule}] ${finding.message} Fix: ${finding.fix}`);\n return `${findings.length} issue(s):\\n${rows.join('\\n')}\\n\\nFix them and run review_usage again. A line with \"TODO (MAV-…)\" is treated as an acknowledged gap.`;\n}\n","import {\n BECKET_PUBLIC_COLOR_KEYS,\n checkBecketThemeContrast,\n defineBecketTheme,\n deriveBecketTheme,\n type BecketContrastReport,\n type BecketTheme,\n type BecketThemeColors,\n} from '@becket-ui/tokens/theme';\n\nexport type SetThemeInput = {\n brand?: string[];\n colors?: Record<string, string | Record<string, string>>;\n fonts?: Record<string, string>;\n radii?: Record<string, string>;\n fontSizes?: Record<string, string>;\n spacing?: Record<string, string>;\n sizes?: Record<string, string>;\n density?: Record<string, Record<string, { px?: string; py?: string }>>;\n};\n\n// as const: literal group names, so `input[group]` type-checks against SetThemeInput.\nconst groups = ['colors', 'fonts', 'radii', 'fontSizes', 'spacing', 'sizes', 'density'] as const;\n\nexport function setTheme(input: SetThemeInput): string {\n if (\n !input.brand?.length &&\n !groups.some((group) => input[group] && Object.keys(input[group]).length > 0)\n ) {\n return `Nothing to set. Pass brand colors (\\`brand: [\"#0a3d91\"]\\`) and/or exact tokens: ${groups.join(', ')}. To start from a logo, image URL or brand manual, call suggest_theme first.`;\n }\n\n const notes: { token: string; reason: string }[] = [];\n const theme: BecketTheme = {};\n\n // px → rem (em for the text unit), so browser text-size settings still scale it (WCAG 1.4.4).\n // as const: literal group names, so `input[group]` type-checks.\n for (const group of ['spacing', 'fontSizes', 'radii'] as const) {\n if (!input[group]) continue;\n const cleaned: Record<string, string> = {};\n for (const [key, value] of Object.entries(input[group])) {\n const px = value.trim().match(/^(-?\\d*\\.?\\d+)px$/);\n cleaned[key] = px\n ? `${Number((Number(px[1]) / 16).toFixed(4))}${group === 'spacing' && key === 'textUnit' ? 'em' : 'rem'}`\n : value;\n if (px) {\n notes.push({\n token: `${group}.${key}`,\n reason: `${value} written as ${cleaned[key]} so browser text-size settings still scale it (WCAG 1.4.4).`,\n });\n }\n }\n theme[group] = cleaned;\n }\n\n if (input.fonts) {\n const generic = [\n 'sans-serif',\n 'serif',\n 'monospace',\n 'system-ui',\n 'ui-sans-serif',\n 'ui-monospace',\n 'ui-serif',\n 'cursive',\n 'fantasy',\n ];\n const fonts: Record<string, string> = {};\n for (const [key, family] of Object.entries(input.fonts)) {\n const names = family\n .split(',')\n .map((name) => name.trim())\n .filter(Boolean);\n // Multi-word family names need quotes in CSS; generic families must not have them.\n const quoted = names.map((name) =>\n /^['\"]/.test(name) || !/\\s/.test(name) || generic.includes(name) ? name : `'${name}'`,\n );\n if (\n (key !== 'sans' && key !== 'mono') ||\n names.some((name) => generic.includes(name.toLowerCase()))\n ) {\n fonts[key] = quoted.join(', ');\n continue;\n }\n fonts[key] = [\n ...quoted,\n key === 'sans'\n ? \"system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif\"\n : \"ui-monospace, 'SF Mono', Menlo, Consolas, monospace\",\n ].join(', ');\n notes.push({\n token: `fonts.${key}`,\n reason: `System fallbacks added after ${family}, so text renders before (or without) the webfont.`,\n });\n }\n theme.fonts = fonts;\n notes.push({\n token: 'fonts',\n reason:\n 'Becket only names the font. Load the webfont in your app (@font-face or your font host) and check its license covers the web.',\n });\n }\n\n if (input.sizes) theme.sizes = input.sizes;\n // Zod already checked the shape; defineBecketTheme below rejects unknown component or size keys.\n if (input.density) theme.density = input.density as BecketTheme['density'];\n\n let contrast: BecketContrastReport;\n try {\n if (input.brand?.length) {\n const derived = deriveBecketTheme({\n brand: input.brand,\n // Same as above: defineBecketTheme validates the color keys.\n pinned: input.colors as BecketThemeColors | undefined,\n });\n theme.colors = derived.theme.colors;\n notes.unshift(...derived.notes);\n } else if (input.colors) {\n // Same as above: defineBecketTheme validates the color keys.\n theme.colors = input.colors as BecketThemeColors;\n }\n // defineBecketTheme validates every key; run it before the contrast check so typos come first.\n defineBecketTheme(theme);\n contrast = checkBecketThemeContrast(theme);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n const path = message.match(/Unknown Becket theme key \"(?:theme\\.)?([^\"]+)\"/)?.[1];\n if (!path) return `${message} Nothing was generated.`;\n const [group] = path.split('.');\n const keys: Record<string, readonly string[]> = {\n colors: [...BECKET_PUBLIC_COLOR_KEYS.filter((key) => !key.startsWith('light')), 'neutral'],\n fonts: ['sans', 'mono'],\n radii: ['none', 'sm', 'md', 'lg', 'xl', 'full'],\n fontSizes: ['base', 'xs', 'sm', 'md', 'lg', 'xl', '2xl', '3xl', '4xl', '5xl', '6xl'],\n spacing: ['unit', 'textUnit', 'xs', 'sm', 'md', 'lg', 'xl'],\n sizes: ['field'],\n };\n return `${message}. Did you mean ${\n // What people call Becket tokens, mapped to the real key; otherwise list the group's keys.\n new Map([\n ['colors.brand', 'brand (a top-level list of one to three colors)'],\n ['colors.main', 'colors.primary'],\n ['colors.primaryColor', 'colors.primary'],\n ['colors.secondaryColor', 'colors.secondary'],\n ['colors.bg', 'colors.background'],\n ['colors.backgroundColor', 'colors.background'],\n ['colors.foreground', 'colors.text'],\n ['colors.textColor', 'colors.text'],\n ['colors.error', 'colors.danger'],\n ['colors.gray', 'colors.neutral'],\n ['colors.grey', 'colors.neutral'],\n ['fonts.body', 'fonts.sans'],\n ['fonts.heading', 'fonts.sans (Becket uses one sans family for headings and body)'],\n ['fonts.code', 'fonts.mono'],\n ['radii.default', 'radii.md'],\n ['fontSizes.root', 'fontSizes.base'],\n ['spacing.base', 'spacing.unit'],\n ]).get(path) ??\n `one of ${(keys[group] ?? groups).map((key) => (keys[group] ? `${group}.${key}` : key)).join(', ')}`\n }? Nothing was generated.`;\n }\n\n const required = contrast.results.filter((result) => result.level === 'required');\n const flagged = [...contrast.failures, ...contrast.advisories];\n return [\n `# Becket theme${contrast.passes ? '' : ' (contrast failures, see below)'}`,\n '## Contrast',\n [\n contrast.passes\n ? `All ${required.length} required pairs pass WCAG 2.2 AA in dark and light.`\n : `${contrast.failures.length} of ${required.length} required pairs FAIL WCAG 2.2 AA. Don't ship this theme as is.`,\n flagged.length\n ? [\n '| theme | where | ratio | needs | result |',\n '| --- | --- | --- | --- | --- |',\n ...flagged.map(\n (result) =>\n `| ${result.theme} | ${result.use} | ${result.ratio}:1 | ${result.minimum}:1 | ${result.passes ? 'pass' : result.level === 'advisory' ? 'advisory' : '**FAIL**'} |`,\n ),\n ].join('\\n')\n : null,\n contrast.advisories.length\n ? `Advisory rows aren't enforced because Becket's own default theme misses them too, but fix them when you can: ${[...new Set(contrast.advisories.map((result) => result.note))].join(' ')}`\n : null,\n ]\n .filter(Boolean)\n .join('\\n\\n'),\n '## Theme CSS',\n `Write this to a file such as \\`src/becket-theme.css\\` and import it right after \\`@becket-ui/tokens/index.css\\`. It's unlayered, so it wins over Becket's defaults. Keep \\`data-theme\\` on <html>.\\n\\n\\`\\`\\`css\\n${defineBecketTheme(theme)}\\`\\`\\``,\n '## Same theme in code',\n `\\`\\`\\`ts\\nimport { defineBecketTheme } from '@becket-ui/tokens/theme';\\n\\nexport const becketTheme = defineBecketTheme(${JSON.stringify(theme, null, 2)});\\n\\`\\`\\`\\nInject \\`becketTheme\\` in a <style> tag after index.css, or keep the CSS file above. Use one, not both.`,\n notes.length\n ? `## Why each value\\n${notes.map((note) => `- ${note.token}: ${note.reason}`).join('\\n')}`\n : null,\n '## Next',\n contrast.passes\n ? \"Show the user the brand colors and any value that was shaded for contrast, then write the CSS file. Don't hand-edit colors afterwards; call set_theme again so they stay checked.\"\n : `Tell the user which pairs fail and why. ${input.brand?.length ? 'Offer to unpin the failing color so Becket shades it,' : 'Offer to pass the color as `brand` instead of an exact token, so Becket shades it,'} or to pick another value, then call set_theme again. Don't write a failing theme without the user's say-so.`,\n ]\n .filter(Boolean)\n .join('\\n\\n');\n}\n","import { lookup as dnsLookup, type LookupAddress } from 'node:dns';\nimport { readFile, stat } from 'node:fs/promises';\nimport { request } from 'node:https';\nimport { BlockList, isIP } from 'node:net';\nimport { basename, resolve } from 'node:path';\n\nexport type SourceKind = 'png' | 'jpeg' | 'svg' | 'pdf' | 'webp' | 'gif' | 'unknown';\nexport type Source = { bytes: Buffer; kind: SourceKind; label: string };\nexport type SourceInput = { path?: string; url?: string; base64?: string };\n\n// Brand manuals run to tens of pages of images; logos are far smaller.\nconst maxBytes = 25 * 1024 * 1024;\nconst timeoutMs = 15_000;\nconst maxRedirects = 5;\n\n// From the bytes, never the file name or Content-Type, which the source controls.\nexport function detectKind(bytes: Buffer): SourceKind {\n if (bytes.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])))\n return 'png';\n if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'jpeg';\n if (bytes.subarray(0, 5).toString('latin1') === '%PDF-') return 'pdf';\n if (\n bytes.subarray(0, 4).toString('latin1') === 'RIFF' &&\n bytes.subarray(8, 12).toString('latin1') === 'WEBP'\n )\n return 'webp';\n if (bytes.subarray(0, 4).toString('latin1') === 'GIF8') return 'gif';\n const head = bytes.subarray(0, 4096).toString('utf8').replace(/^/, '').trimStart();\n if (\n (head.startsWith('<?xml') ||\n head.startsWith('<svg') ||\n head.startsWith('<!--') ||\n head.startsWith('<!DOCTYPE svg')) &&\n /<svg[\\s>]/i.test(head)\n )\n return 'svg';\n return 'unknown';\n}\n\n// Includes link-local (cloud metadata) and IPv4-mapped IPv6 forms, which a naive check misses.\nconst blocked = new BlockList();\n// as const: each entry stays a [network, prefix] tuple, the shape addSubnet takes.\nfor (const [network, prefix] of [\n ['0.0.0.0', 8],\n ['10.0.0.0', 8],\n ['100.64.0.0', 10],\n ['127.0.0.0', 8],\n ['169.254.0.0', 16],\n ['172.16.0.0', 12],\n ['192.0.0.0', 24],\n ['192.0.2.0', 24],\n ['192.168.0.0', 16],\n ['198.18.0.0', 15],\n ['198.51.100.0', 24],\n ['203.0.113.0', 24],\n ['224.0.0.0', 4],\n ['240.0.0.0', 4],\n] as const) {\n blocked.addSubnet(network, prefix, 'ipv4');\n}\n// as const: each entry stays a [network, prefix] tuple, the shape addSubnet takes.\nfor (const [network, prefix] of [\n ['::', 128],\n ['::1', 128],\n ['fc00::', 7],\n ['fe80::', 10],\n ['ff00::', 8],\n ['2001:db8::', 32],\n ['64:ff9b::', 96],\n] as const) {\n blocked.addSubnet(network, prefix, 'ipv6');\n}\n\nexport function isPublicAddress(address: string): boolean {\n const family = isIP(address);\n if (family === 0) return false;\n if (family === 4) return !blocked.check(address, 'ipv4');\n // IPv4-mapped IPv6 (::ffff:127.0.0.1, ::ffff:7f00:1) is the IPv4 host underneath. The URL\n // parser normalizes every spelling to the hex form.\n const mapped = new URL(`http://[${address}]`).hostname.match(\n /^\\[::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})\\]$/,\n );\n if (mapped) {\n const [high, low] = [Number.parseInt(mapped[1], 16), Number.parseInt(mapped[2], 16)];\n return isPublicAddress([high >> 8, high & 255, low >> 8, low & 255].join('.'));\n }\n return !blocked.check(address, 'ipv6');\n}\n\n// Every redirect is checked too, or a public URL could bounce the fetch to a private address.\nfunction download(raw: string, redirects: number): Promise<Buffer> {\n return new Promise((resolvePromise, reject) => {\n // A throw in here rejects the promise.\n let url: URL;\n try {\n url = new URL(raw);\n } catch {\n throw new Error(`\"${raw}\" isn't a URL.`);\n }\n if (url.protocol !== 'https:')\n throw new Error(`Only https URLs are fetched, not ${url.protocol}//.`);\n if (url.username || url.password) throw new Error('URLs with credentials are refused.');\n const host = url.hostname.replace(/^\\[|\\]$/g, '');\n if (isIP(host) && !isPublicAddress(host))\n throw new Error(\n `${host} is a private or reserved address; only public https URLs are fetched.`,\n );\n if (\n host === 'localhost' ||\n host.endsWith('.localhost') ||\n host.endsWith('.local') ||\n host.endsWith('.internal')\n ) {\n throw new Error(`${host} is a local host name; only public https URLs are fetched.`);\n }\n\n const req = request(\n url,\n {\n // Resolve, then refuse private addresses. This runs at connect time, so a DNS answer that\n // changes between a check and the request (rebinding) can't reach an internal host.\n lookup: (hostname, options, callback) => {\n dnsLookup(hostname, { ...options, all: true }, (error, addresses) => {\n if (error) return callback(error, '', 0);\n // With `all: true` Node passes an array, but its callback type only models the\n // single-address form; the same goes for the reply below.\n const list = addresses as unknown as LookupAddress[];\n const refused = list.find((entry) => !isPublicAddress(entry.address));\n if (refused || list.length === 0) {\n return callback(\n new Error(\n `${hostname} resolves to a private or reserved address (${refused?.address ?? 'none'}); only public https URLs are fetched.`,\n ),\n '',\n 0,\n );\n }\n if (options.all) {\n // See above: the all-addresses reply isn't in Node's callback type.\n return (callback as unknown as (error: null, addresses: LookupAddress[]) => void)(\n null,\n list,\n );\n }\n return callback(null, list[0].address, list[0].family);\n });\n },\n timeout: timeoutMs,\n headers: { accept: 'image/*, application/pdf', 'user-agent': '@becket-ui/mcp' },\n },\n (response) => {\n const status = response.statusCode ?? 0;\n if (status >= 300 && status < 400 && response.headers.location) {\n response.resume();\n if (redirects >= maxRedirects)\n return reject(new Error(`More than ${maxRedirects} redirects.`));\n try {\n return resolvePromise(\n download(new URL(response.headers.location, url).toString(), redirects + 1),\n );\n } catch (error) {\n // A Location that can't be read as a URL.\n return reject(error);\n }\n }\n if (status !== 200) {\n response.resume();\n return reject(new Error(`The server answered ${status}.`));\n }\n const declared = Number(response.headers['content-length'] ?? 0);\n if (declared > maxBytes) {\n response.destroy();\n return reject(\n new Error(\n `The file is ${(declared / 1048576).toFixed(1)} MB; the limit is ${maxBytes / 1048576} MB.`,\n ),\n );\n }\n const chunks: Buffer[] = [];\n let size = 0;\n response.on('data', (chunk: Buffer) => {\n size += chunk.length;\n if (size > maxBytes) {\n response.destroy();\n reject(new Error(`The file is over the ${maxBytes / 1048576} MB limit.`));\n return;\n }\n chunks.push(chunk);\n });\n response.on('end', () => resolvePromise(Buffer.concat(chunks)));\n response.on('error', reject);\n },\n );\n req.on('timeout', () => req.destroy(new Error(`No answer within ${timeoutMs / 1000} s.`)));\n req.on('error', reject);\n req.end();\n });\n}\n\nexport async function loadSource(input: SourceInput): Promise<Source> {\n if ([input.path, input.url, input.base64].filter(Boolean).length !== 1)\n throw new Error('Pass exactly one of path, url or base64.');\n\n let bytes: Buffer;\n let label: string;\n if (input.path) {\n const path = resolve(input.path);\n const info = await stat(path).catch(() => null);\n if (!info?.isFile()) throw new Error(`No file at ${path}.`);\n if (info.size > maxBytes)\n throw new Error(\n `${basename(path)} is ${(info.size / 1048576).toFixed(1)} MB; the limit is ${maxBytes / 1048576} MB.`,\n );\n bytes = await readFile(path);\n label = basename(path);\n } else if (input.url) {\n bytes = await download(input.url, 0);\n label = input.url;\n } else {\n const data = (input.base64 ?? '').replace(/^data:[^;,]+;base64,/, '').replace(/\\s+/g, '');\n if (!/^[A-Za-z0-9+/]+={0,2}$/.test(data)) throw new Error(\"base64 isn't valid base64.\");\n if ((data.length * 3) / 4 > maxBytes)\n throw new Error(`The data is over the ${maxBytes / 1048576} MB limit.`);\n bytes = Buffer.from(data, 'base64');\n label = 'base64 data';\n }\n if (bytes.length === 0) throw new Error('The file is empty.');\n return { bytes, kind: detectKind(bytes), label };\n}\n","import { colorDistance, deriveBecketTheme, formatHex, parseColor } from '@becket-ui/tokens/theme';\n\nimport { extractImageColors, neutralChroma, type ExtractedColor } from './extractColors';\nimport { loadSource, type SourceInput } from './loadSource';\n\nexport type SuggestThemeInput = SourceInput & {\n colors?: string[];\n};\n\nexport type Stated = {\n colors: { hex: string; name?: string; page: number }[];\n fonts: { family: string; page: number }[];\n radii: { value: string; page: number }[];\n baseSize: { value: string; page: number }[];\n};\n\nexport type Findings = {\n label: string;\n method: string;\n colors: ExtractedColor[];\n stated?: Stated;\n skipped: string[];\n};\n\nexport function pickBrand(findings: Findings): string[] {\n // Stated colors (a manual) always come first, in the manual's order.\n const candidates = [\n ...(findings.stated?.colors ?? []).flatMap((entry) => {\n const color = parseColor(entry.hex);\n return color ? [{ hex: entry.hex, color }] : [];\n }),\n ...findings.colors\n .filter((color) => color.role !== 'background')\n // A gradient shows up as several close shades of one hue (ΔE OK under 0.1, which most\n // people read as one color); weigh each color with its family.\n .map((entry, _, sampled) => ({\n ...entry,\n family: sampled\n .filter((other) => colorDistance(other.color, entry.color) < 0.1)\n .reduce((sum, other) => sum + other.share, 0),\n }))\n // Under 5% of the artwork is a one-off graphic, not the brand.\n .filter((entry) => entry.family >= 0.05)\n .toSorted((a, b) => b.family - a.family),\n ];\n const picked: typeof candidates = [];\n for (const candidate of candidates) {\n if (candidate.color.C < neutralChroma) continue;\n // Brand colors are different hues. Manuals print tint ramps (one hue, many lightnesses);\n // those are shades of one brand color, not three.\n if (\n picked.some((other) => {\n const gap = Math.abs(other.color.h - candidate.color.h);\n return Math.min(gap, 360 - gap) < 30;\n })\n )\n continue;\n picked.push(candidate);\n if (picked.length === 3) break;\n }\n if (picked.length > 0) return picked.map((entry) => entry.hex);\n // A black, gray or white logo: use its darkest neutral, and Becket stays untinted.\n const darkest = candidates\n .filter((entry) => entry.color.L < 0.9)\n .toSorted((a, b) => a.color.L - b.color.L)[0];\n return darkest ? [darkest.hex] : [];\n}\n\nexport function formatSuggestion(findings: Findings): string {\n const brand = pickBrand(findings);\n const stated = findings.stated;\n const lines: string[] = [\n `# Brand suggestion from ${findings.label}`,\n `Read as: ${findings.method}.`,\n ];\n\n if (stated?.colors.length) {\n lines.push(\n '## Colors the source states',\n // One entry: sections are joined with blank lines, which would break a Markdown table apart.\n [\n '| color | name | page |',\n '| --- | --- | --- |',\n ...stated.colors.map((entry) => `| ${entry.hex} | ${entry.name ?? ''} | ${entry.page} |`),\n ].join('\\n'),\n );\n }\n if (findings.colors.length) {\n lines.push(\n stated ? '## Colors sampled from its artwork' : '## Colors found',\n [\n '| color | share | role |',\n '| --- | --- | --- |',\n ...findings.colors\n .slice(0, 10)\n .map((color) => `| ${color.hex} | ${Math.round(color.share * 100)}% | ${color.role} |`),\n ].join('\\n'),\n );\n }\n if (findings.skipped.length)\n lines.push(\n `Skipped (not a color Becket can read): ${findings.skipped.slice(0, 10).join(', ')}.`,\n );\n\n if (brand.length === 0) {\n lines.push(\n '## Next',\n 'No brand color found. Ask the user for their brand colors (hex is best), then call set_theme with `brand`.',\n );\n return lines.join('\\n\\n');\n }\n\n const fonts = stated?.fonts ?? [];\n const steps = [\n 'brand colors',\n fonts.length ? 'brand font' : null,\n stated?.radii.length || stated?.baseSize.length ? 'corners and text size' : null,\n ].filter(Boolean);\n lines.push(\n '## Guided setup',\n `Ask the user one step at a time and wait for each answer. ${steps.length} step${steps.length > 1 ? 's' : ''}: ${steps.join(', then ')}.`,\n `### Step 1 of ${steps.length}: brand colors`,\n `Ask: \"These look like your brand colors: ${brand.join(', ')}. Which should Becket use, most important first?\" Offer:`,\n ...[\n { label: 'Recommended', brand },\n ...(brand.length >= 2\n ? [\n { label: 'Swap the first two', brand: [brand[1], brand[0], ...brand.slice(2)] },\n { label: 'First color only', brand: [brand[0]] },\n ]\n : []),\n ].map((option, index) => {\n // Preview each option with the real derivation, so the user sees what they'd get.\n const { theme, contrast, notes } = deriveBecketTheme({ brand: option.brand });\n const [button, link] = [\n theme.colors?.primary,\n typeof theme.colors?.link === 'object' ? theme.colors.link.light : theme.colors?.link,\n ].map((value) => {\n const color = typeof value === 'string' ? parseColor(value) : null;\n return color ? formatHex(color) : String(value);\n });\n return `${index + 1}. ${option.label}: \\`${JSON.stringify(option.brand)}\\` — buttons ${button}${notes.some((note) => note.token === 'primary' && /lightened/.test(note.reason)) ? ` (lightened from ${option.brand[0]} for readable labels)` : ''}, light-theme links ${link}; ${contrast.passes ? 'passes AA in dark and light' : `${contrast.failures.length} AA failures`}`;\n }),\n 'Or the user gives their own hex values. Becket shades any color that would fail contrast and says why.',\n );\n\n let step = 1;\n if (fonts.length) {\n step += 1;\n const families = [...new Set(fonts.map((font) => font.family))];\n lines.push(\n `### Step ${step} of ${steps.length}: brand font`,\n `Ask: \"Your manual uses ${families.slice(0, 3).join(', ')}. Use ${families[0]} for Becket's text?\" Offer: yes (\\`fonts: { \"sans\": \"${families[0]}\" }\\`), another of those, or keep Becket's system font. Mention the app must load the webfont and its license must cover the web.`,\n );\n }\n if (stated?.radii.length || stated?.baseSize.length) {\n step += 1;\n const radius = stated.radii[0];\n const base = stated.baseSize[0];\n lines.push(\n `### Step ${step} of ${steps.length}: corners and text size`,\n `Ask: \"Your manual sets ${[\n radius && `corner radius ${radius.value} (page ${radius.page})`,\n base && `body text ${base.value} (page ${base.page})`,\n ]\n .filter(Boolean)\n .join(' and ')}. Apply ${radius && base ? 'them' : 'it'} to Becket?\" If yes, add ${[\n radius && `radii: { \"md\": \"${radius.value}\" }`,\n base && `fontSizes: { \"base\": \"${base.value}\" }`,\n ]\n .filter(Boolean)\n .join(', ')}. Otherwise keep Becket's defaults.`,\n );\n }\n if (!fonts.length) {\n lines.push(\n stated ? 'No font name found in the manual.' : 'An image has no font name to read.',\n 'If the user mentions a brand font, add `fonts: { \"sans\": \"<family>\" }`; otherwise keep Becket\\'s system font. Don\\'t guess a font from a logo.',\n );\n }\n lines.push(\n '### Finish',\n `Call set_theme with only what the user confirmed, e.g. \\`${JSON.stringify({ brand })}\\`. It returns the CSS to write and a contrast report. Don't call set_theme before the user confirms the brand colors.`,\n );\n return lines.join('\\n\\n');\n}\n\nexport async function suggestTheme(input: SuggestThemeInput): Promise<string> {\n try {\n if (input.colors?.length && !input.path && !input.url && !input.base64) {\n return formatSuggestion({\n label: 'the colors you read from the image',\n method: 'colors passed by the agent, in the order given',\n colors: input.colors.map((value, _, all): ExtractedColor => {\n const color = parseColor(value);\n if (!color)\n throw new Error(`Can't read the color \"${value}\". Use hex, rgb(), hsl() or oklch().`);\n return {\n hex: formatHex(color),\n color,\n share: 1 / all.length,\n role: color.C < neutralChroma ? 'neutral' : 'brand',\n };\n }),\n skipped: [],\n });\n }\n const source = await loadSource(input);\n if (source.kind === 'pdf') {\n const { extractPDF } = await import('./extractPDF');\n return formatSuggestion(await extractPDF(source));\n }\n const { colors, method, skipped } = extractImageColors(source);\n return formatSuggestion({ label: source.label, method, colors, skipped });\n } catch (error) {\n return `Couldn't read that source: ${error instanceof Error ? error.message : String(error)}\\n\\nIf the image is only in the chat (pasted), read its main colors yourself and call suggest_theme with \\`colors: [\"#…\", \"#…\"]\\`, or ask the user for the file path.`;\n }\n}\n","import type { Component, Data } from './data';\n\nexport function installation(data: Data): string {\n const { version } = data.catalog;\n return `# Installing Becket UI (@becket-ui/react ${version})\n\npnpm add @becket-ui/react @becket-ui/tokens\n\n1. Import the CSS once, at the app entry:\n import '@becket-ui/tokens/index.css';\n2. Put the theme on <html>: <html data-theme=\"dark\"> (dark is the default) or \"light\".\n Set it at the app root, never inside a screen. There is no provider and no theme wrapper.\n3. Import components from '@becket-ui/react':\n import { Button, Card, Container, Stack, Text } from '@becket-ui/react';\n\n- Panda CSS is not required: styles ship prebuilt in index.css. Don't copy .beckui--* class names.\n- index.css paints the page background, text color and font from the theme.\n- Components marked client in list_components use state or effects ('use client'); the rest render in React Server Components.\n\nTo brand Becket, call set_theme with brand colors or tokens, or suggest_theme with a logo, image URL or brand manual.\n\nBefore writing UI, call get_guidelines (the app-code guide). Before finishing, call review_usage on your code.`;\n}\n\nexport function listComponents(data: Data): string {\n const byGroup = new Map<string, Component[]>();\n for (const component of data.catalog.components) {\n const group = component.group ?? 'Other';\n byGroup.set(group, [...(byGroup.get(group) ?? []), component]);\n }\n const sections = [...byGroup.entries()].map(([group, components]) => {\n const rows = components.map((component) => {\n const parts = component.exports.filter((name) => name !== component.name);\n const tags = [component.client ? 'client' : 'server-safe', component.examples.length ? `${component.examples.length} examples` : null]\n .filter(Boolean)\n .join(', ');\n return `- ${component.name}${parts.length ? ` (also: ${parts.join(', ')})` : ''} [${tags}]${component.summary ? ` — ${component.summary.split('\\n')[0]}` : ''}`;\n });\n return `## ${group}\\n${rows.join('\\n')}`;\n });\n return `@becket-ui/react ${data.catalog.version}: ${data.catalog.components.length} component files.\\nUse get_component_props for exact props and get_component_example for usage.\\n\\n${sections.join('\\n\\n')}`;\n}\n\nexport function findComponent(data: Data, name: string): Component | undefined {\n const wanted = name.trim().toLowerCase();\n return data.catalog.components.find(\n (component) =>\n component.name.toLowerCase() === wanted ||\n component.file.toLowerCase() === wanted ||\n component.exports.some((exported) => exported.toLowerCase() === wanted),\n );\n}\n\nfunction notFound(data: Data, name: string): string {\n const names = data.catalog.components.map((component) => component.name).join(', ');\n return `No Becket component named \"${name}\". Available: ${names}.`;\n}\n\nexport function componentProps(data: Data, name: string): string {\n const component = findComponent(data, name);\n if (!component) return notFound(data, name);\n const variants = component.variants\n ? Object.entries(component.variants)\n .map(([prop, values]) => `- ${prop}: ${values.map((value) => `\"${value}\"`).join(' | ')}`)\n .join('\\n')\n : null;\n return [\n `# ${component.name}${component.group ? ` (${component.group})` : ''}`,\n component.summary,\n `Exports: ${component.exports.join(', ')}${component.hooks.length ? `; hooks: ${component.hooks.join(', ')}` : ''}`,\n `Rendering: ${component.client ? \"client component ('use client': state, effects or browser APIs)\" : 'no client JS required; safe in React Server Components'}`,\n variants ? `## Recipe variants (exact values)\\n${variants}` : null,\n `## Type declarations\\n\\`\\`\\`ts\\n${component.dts}\\n\\`\\`\\``,\n ]\n .filter(Boolean)\n .join('\\n\\n');\n}\n\nexport function componentExample(data: Data, name: string, story?: string): string {\n const component = findComponent(data, name);\n if (!component) return notFound(data, name);\n if (component.examples.length === 0) {\n return `${component.name} has no examples yet. Read get_component_props for its API.`;\n }\n const chosen = story\n ? component.examples.filter((example) => example.name.toLowerCase() === story.trim().toLowerCase())\n : component.examples;\n if (chosen.length === 0) {\n return `No example \"${story}\" for ${component.name}. Available: ${component.examples.map((example) => example.name).join(', ')}.`;\n }\n const note =\n 'These are Storybook stories. In app code, import from \"@becket-ui/react\", drop `args`/`Story` typing, and follow get_guidelines.';\n return `# ${component.name} examples\\n${note}\\n\\n${chosen.map((example) => `## ${example.name}\\n\\`\\`\\`tsx\\n${example.code}\\n\\`\\`\\``).join('\\n\\n')}`;\n}\n\nexport function theme(data: Data, group?: string): string {\n const groups = group ? Object.entries(data.theme).filter(([name]) => name === group) : Object.entries(data.theme);\n if (groups.length === 0) return `Unknown token group \"${group}\". Groups: ${Object.keys(data.theme).join(', ')}.`;\n const sections = groups.map(([name, tokens]) => {\n const rows = tokens.map((token) => `| ${token.token} | \\`${token.cssVar}\\` | ${token.value} | ${token.light ?? 'same'} |`);\n return `## ${name}\\n| token | CSS variable | dark (default) | light |\\n| --- | --- | --- | --- |\\n${rows.join('\\n')}`;\n });\n return `Becket tokens. In components, pass token names as props (gap=\"md\", color=\"muted\"). In your own CSS, use the CSS variables. Never hex, rgb() or px.\\n\\n${sections.join('\\n\\n')}`;\n}\n\nexport function guidelines(data: Data, topic?: string): string {\n const sections = data.guidelines.split(/\\n(?=## )/);\n if (!topic) return data.guidelines;\n const wanted = topic.trim().toLowerCase();\n const matches = sections.filter((section) => section.split('\\n')[0].toLowerCase().includes(wanted));\n if (matches.length > 0) return matches.join('\\n\\n');\n const titles = sections.slice(1).map((section) => section.split('\\n')[0].replace(/^## /, ''));\n return `No section matches \"${topic}\". Sections:\\n${titles.map((title) => `- ${title}`).join('\\n')}`;\n}\n"],"mappings":";;;;;;;;;;;;;;AACA,SAAS,4BAA4B;;;ACDrC,SAAS,iBAAiB;AAC1B,SAAS,SAAS;;;ACDlB,SAAS,oBAAoB;AAC7B,SAAS,SAAS,YAAY;AAC9B,SAAS,qBAAqB;AAgCvB,SAAS,SAAS,UAAU,KAAK,QAAQ,cAAc,YAAY,GAAG,CAAC,GAAG,MAAM,GAAS;AAC9F,QAAM,OAAO,CAAC,SAAiB,aAAa,KAAK,SAAS,IAAI,GAAG,MAAM;AACvE,SAAO;AAAA,IACL,SAAS,KAAK,MAAM,KAAK,cAAc,CAAC;AAAA,IACxC,OAAO,KAAK,MAAM,KAAK,YAAY,CAAC;AAAA,IACpC,YAAY,KAAK,eAAe;AAAA,EAClC;AACF;;;AC7BA,IAAM,aAAqB;AAAA,EACzB;AAAA,IACE,MAAM;AAAA,IACN,SAAS;AAAA,IACT,SAAS;AAAA,IACT,KAAK;AAAA,EACP;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,SAAS;AAAA,IACT,SAAS;AAAA,IACT,KAAK;AAAA,EACP;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,SAAS;AAAA,IACT,SAAS;AAAA,IACT,KAAK;AAAA,EACP;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,SAAS;AAAA,IACT,SAAS;AAAA,IACT,KAAK;AAAA,EACP;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,SAAS;AAAA,IACT,SAAS;AAAA,IACT,KAAK;AAAA,EACP;AAAA,E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AS,sBAAsB;AAAA,QACxD,SAAS,EACN,OAAO,EAAE,OAAO,GAAG,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,SAAS,GAAG,IAAI,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,EAC3G,SAAS,EACT,SAAS,qEAAqE;AAAA,MACnF;AAAA,MACA,aAAa;AAAA,IACf;AAAA,IACA,OAAO,UAAU,KAAK,SAAS,KAAK,CAAC;AAAA,EACvC;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,MACE,OAAO;AAAA,MACP,aACE;AAAA,MACF,aAAa;AAAA,QACX,MAAM,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,gEAAgE;AAAA,QACrG,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,sCAAsC;AAAA,QAC1E,QAAQ,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,wCAAwC;AAAA,QAC/E,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,EAAE,IAAI,CAAC,EAAE,SAAS,EAAE,SAAS,2FAA2F;AAAA,MAC3J;AAAA,MACA,aAAa,EAAE,cAAc,MAAM,eAAe,KAAK;AAAA,IACzD;AAAA,IACA,OAAO,UAAU,KAAK,MAAM,aAAa,KAAK,CAAC;AAAA,EACjD;AAEA,SAAO;AACT;;;AD3IA,MAAM,aAAa,EAAE,QAAQ,IAAI,qBAAqB,CAAC;","names":["text","theme","theme","groups"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@becket-ui/mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
4
4
|
"description": "MCP server that teaches coding agents to build UIs with Becket UI: components, props, examples, tokens and a usage review.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -42,8 +42,8 @@
|
|
|
42
42
|
"zod": "^4.6.7"
|
|
43
43
|
},
|
|
44
44
|
"devDependencies": {
|
|
45
|
-
"@becket-ui/react": "0.
|
|
46
|
-
"@becket-ui/tokens": "0.
|
|
45
|
+
"@becket-ui/react": "0.9.0",
|
|
46
|
+
"@becket-ui/tokens": "0.9.0",
|
|
47
47
|
"@types/node": "^22.18.0",
|
|
48
48
|
"@types/pngjs": "6.0.5",
|
|
49
49
|
"tsup": "^8.5.1",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../tokens/theme/color.mjs","../../tokens/theme/contrast.mjs","../../tokens/theme/derive.mjs","../../tokens/theme/index.mjs","../src/theme/extractColors.ts"],"sourcesContent":["/**\n * Color parsing, OKLCH conversion and WCAG 2 contrast. Shared by the contrast test, the theme\n * checker and palette derivation so every one of them measures with the same math.\n */\n\n/** @param {number} value */\nconst clamp01 = (value) => Math.min(1, Math.max(0, value));\n\n/** sRGB channel (0–1) → linear light. */\nfunction toLinear(channel) {\n return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4;\n}\n\n/** Linear sRGB → OKLCH (CSS Color 4). */\nfunction linearToOklch([r, g, b]) {\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 a = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s;\n const bb = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s;\n const C = Math.hypot(a, bb);\n return {\n L: 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,\n C: C < 1e-4 ? 0 : C,\n // Grays have no meaningful hue; 0 keeps the output stable.\n h: C < 1e-4 ? 0 : ((Math.atan2(bb, a) * 180) / Math.PI + 360) % 360,\n };\n}\n\n/** OKLCH → linear sRGB, unclamped (channels outside 0–1 mean out of gamut). */\nfunction oklchToLinear({ L, C, h }) {\n const radians = (h * Math.PI) / 180;\n const a = C * Math.cos(radians);\n const b = C * Math.sin(radians);\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\n/** \"50%\" → 0.5 of `scale`, \"0.5\" → 0.5. */\nfunction number(part, scale = 1) {\n const value = part.trim();\n if (value === 'none') return 0;\n if (value.endsWith('%')) return (Number.parseFloat(value) / 100) * scale;\n return Number.parseFloat(value);\n}\n\n/**\n * Parse a CSS color (hex, rgb(), hsl(), oklch() or a basic color name) into OKLCH.\n * Alpha is ignored: Becket brand tokens are opaque.\n *\n * @param {string} input\n * @returns {{ L: number, C: number, h: number } | null} null when the format isn't supported\n */\nexport function parseColor(input) {\n if (typeof input !== 'string') return null;\n // CSS's basic color names, the ones logos and SVGs use. Rarer names aren't guessed.\n const value = (\n {\n black: '#000000',\n white: '#ffffff',\n red: '#ff0000',\n green: '#008000',\n blue: '#0000ff',\n yellow: '#ffff00',\n orange: '#ffa500',\n purple: '#800080',\n gray: '#808080',\n grey: '#808080',\n navy: '#000080',\n teal: '#008080',\n maroon: '#800000',\n olive: '#808000',\n lime: '#00ff00',\n aqua: '#00ffff',\n fuchsia: '#ff00ff',\n silver: '#c0c0c0',\n }[input.trim().toLowerCase()] ?? input\n ).trim();\n\n const hex = value.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i);\n if (hex) {\n return linearToOklch(\n // #abc → #aabbcc; the first three pairs are r, g, b (alpha is dropped).\n (hex[1].length <= 4 ? [...hex[1]].map((digit) => digit + digit).join('') : hex[1])\n .match(/../g)\n .slice(0, 3)\n .map((pair) => toLinear(Number.parseInt(pair, 16) / 255)),\n );\n }\n\n const fn = value.match(/^(rgba?|hsla?|oklch)\\(\\s*([^)]*)\\)$/i);\n if (!fn) return null;\n const kind = fn[1].toLowerCase();\n // `1 2 3 / 0.5` or `1, 2, 3, 0.5`: three channels, alpha dropped.\n const withoutAlpha = fn[2].split('/')[0];\n const parts = (\n withoutAlpha.includes(',') ? withoutAlpha.split(',') : withoutAlpha.trim().split(/\\s+/)\n ).slice(0, 3);\n if (parts.length !== 3) return null;\n\n if (kind.startsWith('rgb')) {\n const rgb = parts.map((part) => clamp01(number(part, 255) / 255));\n if (rgb.some(Number.isNaN)) return null;\n return linearToOklch(rgb.map(toLinear));\n }\n if (kind.startsWith('hsl')) {\n const hue = Number.parseFloat(parts[0]);\n const saturation = clamp01(number(parts[1]));\n const lightness = clamp01(number(parts[2]));\n if ([hue, saturation, lightness].some(Number.isNaN)) return null;\n // CSS Color 4 hsl() → sRGB.\n const chroma = (1 - Math.abs(2 * lightness - 1)) * saturation;\n const sector = (((hue % 360) + 360) % 360) / 60;\n const x = chroma * (1 - Math.abs((sector % 2) - 1));\n const [r, g, b] = [\n [chroma, x, 0],\n [x, chroma, 0],\n [0, chroma, x],\n [0, x, chroma],\n [x, 0, chroma],\n [chroma, 0, x],\n ][Math.min(5, Math.floor(sector))];\n const offset = lightness - chroma / 2;\n return linearToOklch([r + offset, g + offset, b + offset].map(toLinear));\n }\n const [L, C, h] = [number(parts[0]), number(parts[1], 0.4), number(parts[2])];\n if ([L, C, h].some(Number.isNaN)) return null;\n return { L: clamp01(L), C: Math.max(0, C), h: ((h % 360) + 360) % 360 };\n}\n\n/**\n * Bring a color into sRGB by lowering chroma only, keeping lightness and hue. That keeps\n * contrast predictable, which matters more here than keeping saturation.\n *\n * @param {{ L: number, C: number, h: number }} color\n */\nexport function toGamut(color) {\n // In gamut: every linear channel within 0–1, give or take float noise.\n if (oklchToLinear(color).every((channel) => channel >= -1e-4 && channel <= 1 + 1e-4))\n return color;\n let [low, high] = [0, color.C];\n for (let step = 0; step < 24; step += 1) {\n const middle = (low + high) / 2;\n if (\n oklchToLinear({ ...color, C: middle }).every(\n (channel) => channel >= -1e-4 && channel <= 1 + 1e-4,\n )\n )\n low = middle;\n else high = middle;\n }\n return { ...color, C: low };\n}\n\n/** @param {{ L: number, C: number, h: number }} color */\nexport function formatOklch({ L, C, h }) {\n const round = (value, digits) => Number(value.toFixed(digits));\n return `oklch(${round(L, 4)} ${round(C, 4)} ${round(C === 0 ? 0 : h, 2)})`;\n}\n\n/** @param {{ L: number, C: number, h: number }} color */\nexport function formatHex(color) {\n return `#${oklchToLinear(toGamut(color))\n .map((linear) => {\n const channel = clamp01(linear);\n // Linear light → sRGB channel (the inverse of toLinear).\n return Math.round(\n clamp01(channel <= 0.0031308 ? channel * 12.92 : 1.055 * channel ** (1 / 2.4) - 0.055) *\n 255,\n )\n .toString(16)\n .padStart(2, '0');\n })\n .join('')}`;\n}\n\n/**\n * WCAG 2 contrast ratio between two colors (CSS strings or parsed OKLCH), 1–21. Channels are\n * clamped to sRGB first, as a browser would display them.\n *\n * @param {string | { L: number, C: number, h: number }} foreground\n * @param {string | { L: number, C: number, h: number }} background\n */\nexport function contrastRatio(foreground, background) {\n const [first, second] = [foreground, background].map((color) => {\n const parsed = typeof color === 'string' ? parseColor(color) : color;\n if (!parsed)\n throw new Error(`Can't read the color \"${color}\". Use hex, rgb(), hsl() or oklch().`);\n const [r, g, b] = oklchToLinear(parsed).map(clamp01);\n return 0.2126 * r + 0.7152 * g + 0.0722 * b;\n });\n const [high, low] = first > second ? [first, second] : [second, first];\n return (high + 0.05) / (low + 0.05);\n}\n\n/**\n * Perceptual distance (ΔE OK, Euclidean in OKLab). Around 0.02 is a just-noticeable difference.\n *\n * @param {{ L: number, C: number, h: number }} first\n * @param {{ L: number, C: number, h: number }} second\n */\nexport function colorDistance(first, second) {\n const [a, b] = [first, second].map(({ L, C, h }) => [\n L,\n C * Math.cos((h * Math.PI) / 180),\n C * Math.sin((h * Math.PI) / 180),\n ]);\n return Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);\n}\n\n/**\n * The OKLCH color for an sRGB triplet (0–255). Used by image decoders.\n *\n * @param {[number, number, number]} rgb\n */\nexport function rgbToOklch(rgb) {\n return linearToOklch(rgb.map((channel) => toLinear(channel / 255)));\n}\n","/**\n * Resolve a BecketTheme to final colors in both themes, the way the browser would, and check\n * every pair Becket draws text or controls with.\n */\n\nimport { contrastRatio, formatOklch, parseColor } from './color.mjs';\n\n/**\n * Default color tokens as index.css declares them. `{key}` is a reference to another token, so\n * a theme that changes `primary` also moves `link`. contrast.test.mjs asserts these match\n * index.css, so they can't drift.\n */\nexport const defaultColors = {\n dark: {\n primary: 'oklch(0.75 0.15 78)',\n secondary: 'oklch(0.70 0.13 125)',\n tertiary: 'oklch(0.60 0.16 48)',\n // index.css: color-mix(in oklch, primary 88%, white)\n primaryHover: { mixWithWhite: 'primary', amount: 0.88 },\n 'neutral.50': 'oklch(0.96 0.012 78)',\n 'neutral.100': 'oklch(0.94 0.012 78)',\n 'neutral.200': 'oklch(0.89 0.012 75)',\n 'neutral.300': 'oklch(0.84 0.012 72)',\n 'neutral.400': 'oklch(0.75 0.012 70)',\n 'neutral.500': 'oklch(0.65 0.012 65)',\n 'neutral.600': 'oklch(0.55 0.014 62)',\n 'neutral.700': 'oklch(0.45 0.014 60)',\n 'neutral.800': 'oklch(0.35 0.015 60)',\n 'neutral.900': 'oklch(0.22 0.015 60)',\n white: 'oklch(99% 0 0)',\n background: '{neutral.900}',\n text: '{neutral.50}',\n muted: '{neutral.300}',\n surface: '{neutral.800}',\n border: '{neutral.200}',\n danger: 'oklch(0.76 0.16 25)',\n accent: 'oklch(0.86 0.12 125)',\n link: '{primary}',\n linkHover: 'oklch(0.78 0.13 78)',\n linkVisited: 'oklch(0.72 0.12 125)',\n warning: 'oklch(0.72 0.16 42)',\n success: 'oklch(0.68 0.14 165)',\n },\n /** Only what `[data-theme='light']` changes; the rest is inherited from dark. */\n light: {\n background: '{neutral.50}',\n text: '{neutral.900}',\n muted: 'oklch(0.53 0.014 62)',\n surface: '{white}',\n danger: 'oklch(0.48 0.20 25)',\n accent: 'oklch(0.38 0.14 125)',\n link: 'oklch(0.54 0.12 70)',\n linkHover: 'oklch(0.46 0.11 70)',\n linkVisited: 'oklch(0.52 0.09 125)',\n },\n};\n\nconst text = 4.5;\nconst canvases = ['background', 'surface'];\n\n/**\n * Every pair Becket draws. `required` pairs pass in the default theme and must pass in any\n * theme. `advisory` pairs fail in the default theme too (see their `note`), so they're\n * reported, not enforced, until Becket's recipes change.\n */\nexport const contrastPairs = [\n ...['text', 'muted', 'link', 'linkHover', 'linkVisited', 'danger', 'accent'].flatMap(\n (foreground) =>\n canvases.map((background) => ({\n foreground,\n background,\n minimum: text,\n level: 'required',\n use: `${foreground} text on ${background}`,\n })),\n ),\n ...['primary', 'primaryHover', 'secondary'].map((background) => ({\n foreground: 'neutral.900',\n background,\n minimum: text,\n level: 'required',\n use: `label on a filled ${background} control`,\n })),\n {\n foreground: 'neutral.900',\n background: 'tertiary',\n minimum: text,\n level: 'advisory',\n use: 'label over the tertiary end of a gradient fill',\n note: 'The default tertiary is 4.13:1; the label mostly sits over the primary half.',\n },\n ...canvases.map((background) => ({\n foreground: 'primary',\n background,\n // Non-text UI and state indicators (WCAG 1.4.11).\n minimum: 3,\n level: 'advisory',\n use: `focus ring and checked controls on ${background}`,\n note: 'A primary light enough for dark labels is usually too light for 3:1 on a near-white canvas; the default is 2.02:1 in light.',\n })),\n];\n\n/**\n * Final colors in both themes for a theme config, as OKLCH.\n *\n * Mirrors the CSS that `defineBecketTheme` emits: its `:root` block is unlayered, so it beats\n * index.css's layered light block too. A plain string (or a `{ dark }` value) therefore applies\n * in light as well, unless the config also gives `light`.\n *\n * @param {import('./index.d.ts').BecketTheme} [theme]\n */\nexport function resolveBecketColors(theme = {}) {\n const root = {};\n const lightOnly = {};\n for (const [key, value] of Object.entries(theme.colors ?? {})) {\n if (value == null) continue;\n if (key === 'neutral') {\n for (const [step, color] of Object.entries(value)) root[`neutral.${step}`] = color;\n } else if (typeof value === 'object') {\n if (value.dark) root[key] = value.dark;\n if (value.light) lightOnly[key] = value.light;\n } else {\n root[key] = value;\n }\n }\n const [dark, light] = [\n { ...defaultColors.dark, ...root },\n { ...defaultColors.dark, ...defaultColors.light, ...root, ...lightOnly },\n ].map((table) => {\n const resolved = {};\n const resolve = (key, depth = 0) => {\n if (resolved[key]) return resolved[key];\n if (depth > 8) throw new Error(`Color token \"${key}\" refers to itself`);\n const value = table[key];\n if (value == null) throw new Error(`Unknown color token \"${key}\"`);\n let color;\n if (typeof value === 'object') {\n const base = resolve(value.mixWithWhite, depth + 1);\n // color-mix(in oklch, base n%, white): white has no hue, so the hue stays the base's.\n color = {\n L: base.L * value.amount + (1 - value.amount),\n C: base.C * value.amount,\n h: base.h,\n };\n } else {\n const reference = value.match(/^\\{([\\w.]+)\\}$/);\n color = reference ? resolve(reference[1], depth + 1) : parseColor(value);\n if (!color)\n throw new Error(`Can't read colors.${key} \"${value}\". Use hex, rgb(), hsl() or oklch().`);\n }\n resolved[key] = color;\n return color;\n };\n for (const key of Object.keys(table)) resolve(key);\n return resolved;\n });\n return { dark, light };\n}\n\n/**\n * WCAG 2.2 AA contrast for every pair in contrastPairs, in dark and light.\n *\n * @param {import('./index.d.ts').BecketTheme} [theme]\n * @returns {import('./index.d.ts').BecketContrastReport}\n */\nexport function checkBecketThemeContrast(theme = {}) {\n const colors = resolveBecketColors(theme);\n const results = ['dark', 'light'].flatMap((mode) =>\n contrastPairs.map((pair) => {\n const ratio = contrastRatio(colors[mode][pair.foreground], colors[mode][pair.background]);\n return {\n ...pair,\n theme: mode,\n ratio: Math.floor(ratio * 100) / 100,\n passes: ratio >= pair.minimum,\n foregroundColor: formatOklch(colors[mode][pair.foreground]),\n backgroundColor: formatOklch(colors[mode][pair.background]),\n };\n }),\n );\n return {\n passes: results.every((result) => result.passes || result.level === 'advisory'),\n failures: results.filter((result) => !result.passes && result.level === 'required'),\n advisories: results.filter((result) => !result.passes && result.level === 'advisory'),\n results,\n };\n}\n","/**\n * Turn one to three brand colors into a full Becket color theme that passes WCAG 2.2 AA in\n * dark and light. Works in OKLCH and only moves lightness (and chroma when a lighter or darker\n * shade leaves sRGB), so the brand hue never changes.\n */\n\nimport { contrastRatio, formatOklch, parseColor, toGamut } from './color.mjs';\nimport { checkBecketThemeContrast, resolveBecketColors } from './contrast.mjs';\n\n// Aim slightly above 4.5:1 so values rounded for CSS still pass.\nconst textTarget = 4.6;\n\n/**\n * Move a color's lightness in one direction, one small step at a time, until it reaches\n * `minimum` against every color in `against`. The first step is the color itself, so one that\n * already passes comes back unchanged. Null when no lightness in that direction works.\n */\nfunction fitLightness({ color, against, minimum, direction }) {\n for (let L = color.L; L >= 0 && L <= 1; L += direction === 'lighter' ? 0.005 : -0.005) {\n const candidate = toGamut({ ...color, L });\n if (against.every((other) => contrastRatio(candidate, other) >= minimum)) return candidate;\n }\n return null;\n}\n\nfunction describe(color) {\n return `L ${color.L.toFixed(2)}`;\n}\n\n/**\n * @param {import('./index.d.ts').DeriveBecketThemeInput} input\n * @returns {import('./index.d.ts').DerivedBecketTheme}\n */\nexport function deriveBecketTheme({ brand, pinned = {} }) {\n if (!Array.isArray(brand) || brand.length === 0 || brand.length > 3) {\n throw new Error('Pass one to three brand colors, most important first.');\n }\n const seeds = brand.map((value) => {\n const color = parseColor(value);\n if (!color)\n throw new Error(`Can't read the brand color \"${value}\". Use hex, rgb(), hsl() or oklch().`);\n return color;\n });\n const [primarySeed] = seeds;\n // With fewer than three colors, follow the default theme's shape: secondary is the brand hue\n // turned ~45° and tertiary ~30° the other way, at the same lightness and chroma.\n const secondarySeed = seeds[1] ?? { ...primarySeed, h: (primarySeed.h + 45) % 360 };\n\n const notes = [];\n const colors = {};\n const note = (token, reason) => notes.push({ token, reason });\n\n // A whisper of the brand hue in the grays, like the default theme's warm neutrals. Below 0.012\n // the tint is invisible; above it grays start to read as a color.\n const tint = primarySeed.C < 0.02 ? 0 : 0.012;\n colors.neutral = Object.fromEntries(\n // The default theme's lightness ladder, so text and canvases keep their contrast.\n Object.entries({\n 50: 0.96,\n 100: 0.94,\n 200: 0.89,\n 300: 0.84,\n 400: 0.75,\n 500: 0.65,\n 600: 0.55,\n 700: 0.45,\n 800: 0.35,\n 900: 0.22,\n }).map(([step, L]) => [step, formatOklch({ L, C: tint, h: tint ? primarySeed.h : 0 })]),\n );\n colors.muted = { light: formatOklch({ L: 0.53, C: tint, h: tint ? primarySeed.h : 0 }) };\n note(\n 'neutral',\n tint\n ? `Grays tinted toward the brand hue (${primarySeed.h.toFixed(0)}°), lightness unchanged.`\n : 'The brand is near-gray, so neutrals stay untinted.',\n );\n\n // Fit everything against the canvases the user will actually see, pinned ones included.\n const canvases = resolveBecketColors({ colors: { ...colors, ...pinned } });\n const dark = [canvases.dark.background, canvases.dark.surface];\n const light = [canvases.light.background, canvases.light.surface];\n\n const fill = ({ token, seed, label }) => {\n const fitted = fitLightness({\n color: seed,\n // Filled controls put neutral.900 labels on the brand color.\n against: [canvases.dark['neutral.900']],\n minimum: textTarget,\n direction: 'lighter',\n });\n colors[token] = formatOklch(fitted);\n if (fitted.L !== seed.L)\n note(\n token,\n `${label} lightened from ${describe(seed)} to ${describe(fitted)} so dark button labels reach 4.5:1.`,\n );\n else note(token, `${label} used as is.`);\n };\n fill({ token: 'primary', seed: primarySeed, label: 'Brand color 1' });\n fill({\n token: 'secondary',\n seed: secondarySeed,\n label: seeds[1] ? 'Brand color 2' : 'Derived from brand color 1 (hue +45°)',\n });\n fill({\n token: 'tertiary',\n seed: seeds[2] ?? { ...primarySeed, h: (primarySeed.h + 330) % 360 },\n label: seeds[2] ? 'Brand color 3' : 'Derived from brand color 1 (hue −30°)',\n });\n\n const onCanvas = ({ token, seed, label }) => {\n const darkFit = fitLightness({\n color: seed,\n against: dark,\n minimum: textTarget,\n direction: 'lighter',\n });\n const lightFit = fitLightness({\n color: seed,\n against: light,\n minimum: textTarget,\n direction: 'darker',\n });\n if (!darkFit || !lightFit) {\n note(\n token,\n `${label} can't reach 4.5:1 on your pinned canvas in ${darkFit ? 'light' : 'dark'}; left at the Becket default.`,\n );\n return null;\n }\n colors[token] = { dark: formatOklch(darkFit), light: formatOklch(lightFit) };\n const exact = [darkFit.L === seed.L && 'dark', lightFit.L === seed.L && 'light'].filter(\n Boolean,\n );\n note(\n token,\n exact.length === 2\n ? `${label} used as is in both themes.`\n : exact.length === 1\n ? `${label} used as is in ${exact[0]}; a ${exact[0] === 'dark' ? 'darker' : 'lighter'} shade (${describe(exact[0] === 'dark' ? lightFit : darkFit)}) in ${exact[0] === 'dark' ? 'light' : 'dark'} for 4.5:1 on the canvas.`\n : `${label} shaded per theme (dark ${describe(darkFit)}, light ${describe(lightFit)}) for 4.5:1 on the canvas.`,\n );\n return { dark: darkFit, light: lightFit };\n };\n const link = onCanvas({ token: 'link', seed: primarySeed, label: 'Brand color 1' });\n onCanvas({\n token: 'linkVisited',\n seed: secondarySeed,\n label: seeds[1] ? 'Brand color 2' : 'The derived secondary',\n });\n onCanvas({\n token: 'accent',\n seed: secondarySeed,\n label: seeds[1] ? 'Brand color 2' : 'The derived secondary',\n });\n if (link) {\n // Hover moves away from the canvas, so it keeps (and gains) contrast.\n colors.linkHover = {\n dark: formatOklch(toGamut({ ...link.dark, L: Math.min(1, link.dark.L + 0.06) })),\n light: formatOklch(\n fitLightness({\n color: { ...link.light, L: Math.max(0, link.light.L - 0.08) },\n against: light,\n minimum: textTarget,\n direction: 'darker',\n }),\n ),\n };\n note('linkHover', 'The link color a step lighter on dark and a step darker on light.');\n }\n\n // Body text only moves when a pinned canvas breaks it; otherwise the neutral ladder already passes.\n for (const token of ['text', 'muted']) {\n if (pinned[token]) continue;\n const current = resolveBecketColors({ colors: { ...colors, ...pinned } });\n const darkFit = fitLightness({\n color: current.dark[token],\n against: dark,\n minimum: textTarget,\n direction: 'lighter',\n });\n const lightFit = fitLightness({\n color: current.light[token],\n against: light,\n minimum: textTarget,\n direction: 'darker',\n });\n if (darkFit.L === current.dark[token].L && lightFit.L === current.light[token].L) continue;\n colors[token] = { dark: formatOklch(darkFit), light: formatOklch(lightFit) };\n note(token, 'Adjusted so it stays at 4.5:1 on your pinned canvas.');\n }\n\n // Within 20° of Becket's danger hue (25°).\n const fromDanger = Math.abs(primarySeed.h - 25);\n if (primarySeed.C >= 0.08 && Math.min(fromDanger, 360 - fromDanger) < 20) {\n note(\n 'danger',\n 'Your brand is red, like error text. Danger stays Becket red; make sure errors also carry an icon or text, not color alone.',\n );\n }\n\n for (const [token, value] of Object.entries(pinned)) {\n if (token === 'neutral') colors.neutral = { ...colors.neutral, ...value };\n else colors[token] = value;\n note(token, 'Pinned by you, kept exactly.');\n }\n\n const theme = { colors };\n return { theme, notes, contrast: checkBecketThemeContrast(theme) };\n}\n","/** Public CSS-variable theming. No Panda, no theme provider. */\n\nexport { colorDistance, contrastRatio, formatHex, formatOklch, parseColor, rgbToOklch, toGamut } from './color.mjs';\nexport { contrastPairs, checkBecketThemeContrast, resolveBecketColors } from './contrast.mjs';\nexport { deriveBecketTheme } from './derive.mjs';\n\nconst PREFIX = '--beckui--';\n\nconst COLOR_FLAT = [\n 'primary',\n 'secondary',\n 'tertiary',\n 'primaryHover',\n 'lightBackground',\n 'lightText',\n 'warning',\n 'success',\n];\n\nconst COLOR_THEMED = [\n 'background',\n 'text',\n 'muted',\n 'border',\n 'danger',\n 'accent',\n 'surface',\n 'link',\n 'linkHover',\n 'linkVisited',\n];\nconst NEUTRAL_STEPS = ['50', '100', '200', '300', '400', '500', '600', '700', '800', '900'];\nconst RADII = ['none', 'sm', 'md', 'lg', 'xl', 'full'];\n// `base` rescales the whole type scale; the steps are ratios of it.\nconst FONT_SIZES = ['base', 'xs', 'sm', 'md', 'lg', 'xl', '2xl', '3xl', '4xl', '5xl', '6xl'];\n// `unit` rescales every Fibonacci spacing and size step; `textUnit` the em-based text spacing.\nconst SPACING = ['unit', 'textUnit', 'xs', 'sm', 'md', 'lg', 'xl'];\nconst FONTS = ['sans', 'mono'];\nconst DENSITY_SIZES = {\n button: ['sm', 'md'],\n field: ['sm', 'md', 'lg'],\n tag: ['sm', 'md', 'lg'],\n};\n\nfunction kebab(value) {\n return value.replace(/[A-Z]/g, (char) => `-${char.toLowerCase()}`);\n}\n\nfunction cssVar(parts) {\n return `${PREFIX}${parts.map(kebab).join('-')}`;\n}\n\nfunction assertAllowedKeys(object, allowed, label) {\n for (const key of Object.keys(object)) {\n if (!allowed.includes(key)) {\n throw new Error(`Unknown Becket theme key \"${label}.${key}\"`);\n }\n }\n}\n\nfunction pushDecl(decls, name, value) {\n if (value == null || value === '') return;\n decls.push(` ${name}: ${value};`);\n}\n\nfunction pushThemed(rootDecls, lightDecls, name, value) {\n if (value == null || value === '') return;\n if (typeof value === 'object') {\n if (value.dark) pushDecl(rootDecls, name, value.dark);\n if (value.light) pushDecl(lightDecls, name, value.light);\n return;\n }\n pushDecl(rootDecls, name, value);\n}\n\nfunction colorDecls(colors, rootDecls, lightDecls) {\n assertAllowedKeys(colors, [...COLOR_FLAT, ...COLOR_THEMED, 'neutral'], 'colors');\n\n for (const key of COLOR_FLAT) {\n const value = colors[key];\n if (value == null) continue;\n if (typeof value === 'object') {\n throw new Error(`colors.${key} must be a CSS color string`);\n }\n pushDecl(rootDecls, cssVar(['colors', key]), value);\n }\n\n for (const key of COLOR_THEMED) {\n pushThemed(rootDecls, lightDecls, cssVar(['colors', key]), colors[key]);\n }\n\n if (colors.neutral) {\n assertAllowedKeys(colors.neutral, NEUTRAL_STEPS, 'colors.neutral');\n for (const step of NEUTRAL_STEPS) {\n pushDecl(rootDecls, cssVar(['colors', 'neutral', step]), colors.neutral[step]);\n }\n }\n}\n\nfunction densityDecls(density, decls) {\n assertAllowedKeys(density, ['button', 'field', 'tag'], 'density');\n for (const component of Object.keys(DENSITY_SIZES)) {\n const sizes = density[component];\n if (!sizes) continue;\n const allowed = DENSITY_SIZES[component];\n assertAllowedKeys(sizes, allowed, `density.${component}`);\n for (const size of allowed) {\n const box = sizes[size];\n if (!box) continue;\n assertAllowedKeys(box, ['px', 'py'], `density.${component}.${size}`);\n if (box.px) decls.push(` --beckui-${component}-px-${size}: ${box.px};`);\n if (box.py) decls.push(` --beckui-${component}-py-${size}: ${box.py};`);\n }\n }\n}\n\nfunction sheet(selector, decls) {\n if (!decls.length) return '';\n return `${selector} {\\n${decls.join('\\n')}\\n}\\n`;\n}\n\n/**\n * Emit unlayered `:root` / `html[data-theme='light']` overrides. Import or\n * inject **after** `@becket-ui/tokens/index.css` so these win over `@layer tokens`.\n *\n * @param {import('./index.d.ts').BecketTheme} config\n * @returns {string}\n */\nexport function defineBecketTheme(config = {}) {\n assertAllowedKeys(\n config,\n ['colors', 'radii', 'fontSizes', 'spacing', 'sizes', 'fonts', 'density'],\n 'theme',\n );\n\n const rootDecls = [];\n const lightDecls = [];\n\n if (config.colors) colorDecls(config.colors, rootDecls, lightDecls);\n\n if (config.radii) {\n assertAllowedKeys(config.radii, RADII, 'radii');\n for (const key of RADII) {\n pushDecl(rootDecls, cssVar(['radii', key]), config.radii[key]);\n }\n }\n\n if (config.fontSizes) {\n assertAllowedKeys(config.fontSizes, FONT_SIZES, 'fontSizes');\n for (const key of FONT_SIZES) {\n pushDecl(rootDecls, cssVar(['font-sizes', key]), config.fontSizes[key]);\n }\n }\n\n if (config.spacing) {\n assertAllowedKeys(config.spacing, SPACING, 'spacing');\n for (const key of SPACING) {\n pushDecl(rootDecls, cssVar(['spacing', key]), config.spacing[key]);\n }\n }\n\n if (config.sizes) {\n assertAllowedKeys(config.sizes, ['field'], 'sizes');\n pushDecl(rootDecls, cssVar(['sizes', 'field']), config.sizes.field);\n }\n\n if (config.fonts) {\n assertAllowedKeys(config.fonts, FONTS, 'fonts');\n for (const key of FONTS) {\n pushDecl(rootDecls, cssVar(['fonts', key]), config.fonts[key]);\n }\n }\n\n if (config.density) densityDecls(config.density, rootDecls);\n\n const css = `${sheet(':root', rootDecls)}${sheet(\"html[data-theme='light']\", lightDecls)}`;\n if (!css) {\n return '/* defineBecketTheme: empty config, Becket defaults unchanged */\\n';\n }\n return css;\n}\n\nexport const BECKET_PUBLIC_COLOR_KEYS = [...COLOR_FLAT, ...COLOR_THEMED];\nexport const BECKET_PUBLIC_NEUTRAL_STEPS = NEUTRAL_STEPS;\n","import {\n colorDistance,\n formatHex,\n parseColor,\n rgbToOklch,\n type Oklch,\n} from '@becket-ui/tokens/theme';\nimport jpeg from 'jpeg-js';\nimport { PNG } from 'pngjs';\n\nimport type { Source } from './loadSource';\n\nexport type ColorRole = 'background' | 'neutral' | 'brand';\nexport type ExtractedColor = { hex: string; color: Oklch; share: number; role: ColorRole };\n\n// Decompression bombs: a tiny PNG can claim gigapixels. Real logos and manual pages are far below.\nconst maxPixels = 50_000_000;\n// Colors closer than this (ΔE OK) are one color: anti-aliasing, JPEG noise, gradients' near steps.\nconst sameColor = 0.05;\n/** Below this chroma a color reads as white, gray or black. Shared with suggest_theme and PDFs. */\nexport const neutralChroma = 0.04;\n\n/**\n * Dominant colors of a bitmap. Transparent pixels are ignored. A color that keeps touching the\n * image's edges is the background (logos have padding; photos behind them touch every edge).\n * Each color is its most common exact shade, not an average, so edges and noise don't tint it.\n */\nexport function colorsFromPixels({\n width,\n height,\n data,\n}: {\n width: number;\n height: number;\n data: Uint8Array;\n}): ExtractedColor[] {\n // Sample at most ~160k pixels: plenty for a palette, and fast on a 2000×2000 logo.\n const step = Math.max(1, Math.floor(Math.sqrt((width * height) / 160_000)));\n const border = Math.max(1, Math.round(Math.min(width, height) * 0.02));\n const bins = new Map<number, { count: number; edge: number; r: number; g: number; b: number }>();\n let opaque = 0;\n let edgeSamples = 0;\n\n for (let y = 0; y < height; y += step) {\n for (let x = 0; x < width; x += step) {\n const offset = (y * width + x) * 4;\n if (data[offset + 3] < 128) continue;\n const [r, g, b] = [data[offset], data[offset + 1], data[offset + 2]];\n const key = ((r >> 3) << 10) | ((g >> 3) << 5) | (b >> 3);\n const isEdge = x < border || y < border || x >= width - border || y >= height - border;\n const bin = bins.get(key) ?? { count: 0, edge: 0, r: 0, g: 0, b: 0 };\n bin.count += 1;\n bin.r += r;\n bin.g += g;\n bin.b += b;\n if (isEdge) bin.edge += 1;\n bins.set(key, bin);\n opaque += 1;\n if (isEdge) edgeSamples += 1;\n }\n }\n if (opaque === 0) return [];\n\n const clusters: { count: number; edge: number; color: Oklch }[] = [];\n for (const bin of [...bins.values()].toSorted((a, b) => b.count - a.count)) {\n const color = rgbToOklch([bin.r / bin.count, bin.g / bin.count, bin.b / bin.count]);\n const home = clusters.find((cluster) => colorDistance(cluster.color, color) < sameColor);\n if (home) {\n home.count += bin.count;\n home.edge += bin.edge;\n continue;\n }\n if (clusters.length < 64) clusters.push({ count: bin.count, edge: bin.edge, color });\n }\n\n return (\n clusters\n // Under 0.5% is anti-aliasing or a stray pixel.\n .filter((cluster) => cluster.count / opaque >= 0.005)\n .map((cluster): ExtractedColor => ({\n hex: formatHex(cluster.color),\n color: cluster.color,\n share: cluster.count / opaque,\n // The background touches the edges at least half as often as the average opaque pixel,\n // and covers 5% or more of the edge.\n role:\n edgeSamples > 0 &&\n cluster.edge / cluster.count >= (edgeSamples / opaque) * 0.5 &&\n cluster.edge / edgeSamples >= 0.05\n ? 'background'\n : cluster.color.C < neutralChroma\n ? 'neutral'\n : 'brand',\n }))\n .toSorted((a, b) => b.share - a.share)\n );\n}\n\n/** Merge near-identical colors (keeping the more common one's exact value), most common first. */\nexport function mergeClose(colors: ExtractedColor[]): ExtractedColor[] {\n const merged: ExtractedColor[] = [];\n for (const color of colors.toSorted((a, b) => b.share - a.share)) {\n const home = merged.find(\n (each) => each.role === color.role && colorDistance(each.color, color.color) < sameColor,\n );\n if (home) home.share += color.share;\n else merged.push({ ...color });\n }\n return merged;\n}\n\n/** Dominant colors of a PNG, JPEG or SVG source. */\nexport function extractImageColors(source: Source): {\n colors: ExtractedColor[];\n method: string;\n skipped: string[];\n} {\n if (source.kind === 'png') {\n // The header's size, read before decoding: decompression bombs claim gigapixels in a tiny file.\n const [width, height] = [source.bytes.readUInt32BE(16), source.bytes.readUInt32BE(20)];\n if (width * height > maxPixels)\n throw new Error(`The PNG is ${width}×${height}; the limit is ${maxPixels / 1e6} megapixels.`);\n return {\n colors: colorsFromPixels(PNG.sync.read(source.bytes)),\n method: 'PNG pixels',\n skipped: [],\n };\n }\n if (source.kind === 'jpeg') {\n return {\n colors: colorsFromPixels(\n jpeg.decode(source.bytes, {\n useTArray: true,\n formatAsRGBA: true,\n maxResolutionInMP: maxPixels / 1e6,\n maxMemoryUsageInMB: 1024,\n }),\n ),\n method: 'JPEG pixels',\n skipped: [],\n };\n }\n if (source.kind === 'svg') {\n // Colors the SVG declares (fill, stroke, stop-color, color, in attributes and CSS), weighted by\n // how often each appears. The SVG is read as text: nothing renders, runs or loads.\n const svg = source.bytes.toString('utf8');\n const counts = new Map<string, { color: Oklch; count: number }>();\n const skippedValues = new Set<string>();\n for (const [, , raw] of svg.matchAll(\n /(?:^|[\\s;\"'{])(fill|stroke|stop-color|color|flood-color)\\s*(?:=\\s*[\"']|:\\s*)([^\"';}>]+)/gi,\n )) {\n const value = raw.trim().replace(/\\s*!important$/, '');\n const lower = value.toLowerCase();\n if (\n ['none', 'currentcolor', 'transparent', 'inherit', 'initial', 'unset'].includes(lower) ||\n lower.startsWith('url(') ||\n lower.startsWith('var(')\n )\n continue;\n // parseColor knows the basic color names; rarer ones are reported as skipped, not guessed.\n const color = parseColor(value);\n if (!color) {\n skippedValues.add(value);\n continue;\n }\n const hex = formatHex(color);\n const entry = counts.get(hex) ?? { color, count: 0 };\n entry.count += 1;\n counts.set(hex, entry);\n }\n const embedded = [...svg.matchAll(/data:image\\/(?:png|jpeg);base64,([A-Za-z0-9+/=\\s]+)/g)].map(\n ([, data]) => Buffer.from(data.replace(/\\s+/g, ''), 'base64'),\n );\n // Summed once here, not per color inside the map below.\n const total = [...counts.values()].reduce((sum, entry) => sum + entry.count, 0);\n return {\n colors: mergeClose([\n ...[...counts.entries()].map(([hex, entry]): ExtractedColor => ({\n hex,\n color: entry.color,\n share: entry.count / total,\n role: entry.color.C < neutralChroma ? 'neutral' : 'brand',\n })),\n ...embedded.flatMap((bytes) => {\n try {\n return extractImageColors({\n bytes,\n kind: bytes[0] === 0x89 ? 'png' : 'jpeg',\n label: source.label,\n }).colors.map((color) => ({ ...color, share: color.share / embedded.length }));\n } catch {\n // A broken embedded image doesn't hide the colors the SVG declares.\n return [];\n }\n }),\n ]),\n method: embedded.length\n ? 'SVG colors and embedded images (by how often each color is used, not by area)'\n : 'SVG colors (by how often each is used, not by area)',\n skipped: [...skippedValues],\n };\n }\n if (source.kind === 'webp' || source.kind === 'gif') {\n throw new Error(\n `${source.kind.toUpperCase()} isn't supported yet. Export the logo as SVG or PNG, or tell me its colors.`,\n );\n }\n throw new Error(\"That isn't a PNG, JPEG, SVG or PDF file.\");\n}\n"],"mappings":";AAMA,IAAM,UAAU,CAAC,UAAU,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,KAAK,CAAC;AAGzD,SAAS,SAAS,SAAS;AACzB,SAAO,WAAW,UAAU,UAAU,UAAU,UAAU,SAAS,UAAU;AAC/E;AAGA,SAAS,cAAc,CAAC,GAAG,GAAG,CAAC,GAAG;AAChC,QAAM,IAAI,KAAK,KAAK,eAAe,IAAI,eAAe,IAAI,eAAe,CAAC;AAC1E,QAAM,IAAI,KAAK,KAAK,eAAe,IAAI,eAAe,IAAI,eAAe,CAAC;AAC1E,QAAM,IAAI,KAAK,KAAK,eAAe,IAAI,eAAe,IAAI,eAAe,CAAC;AAC1E,QAAM,IAAI,eAAe,IAAI,cAAc,IAAI,eAAe;AAC9D,QAAM,KAAK,eAAe,IAAI,eAAe,IAAI,cAAc;AAC/D,QAAM,IAAI,KAAK,MAAM,GAAG,EAAE;AAC1B,SAAO;AAAA,IACL,GAAG,eAAe,IAAI,cAAc,IAAI,eAAe;AAAA,IACvD,GAAG,IAAI,OAA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AAC,GAAG,OAAO,QAAQ,CAAC,EAAE,IAAI,CAAC,CAAC,KAAK,KAAK,OAAuB;AAAA,UAC9D;AAAA,UACA,OAAO,MAAM;AAAA,UACb,OAAO,MAAM,QAAQ;AAAA,UACrB,MAAM,MAAM,MAAM,IAAI,gBAAgB,YAAY;AAAA,QACpD,EAAE;AAAA,QACF,GAAG,SAAS,QAAQ,CAAC,UAAU;AAC7B,cAAI;AACF,mBAAO,mBAAmB;AAAA,cACxB;AAAA,cACA,MAAM,MAAM,CAAC,MAAM,MAAO,QAAQ;AAAA,cAClC,OAAO,OAAO;AAAA,YAChB,CAAC,EAAE,OAAO,IAAI,CAAC,WAAW,EAAE,GAAG,OAAO,OAAO,MAAM,QAAQ,SAAS,OAAO,EAAE;AAAA,UAC/E,QAAQ;AAEN,mBAAO,CAAC;AAAA,UACV;AAAA,QACF,CAAC;AAAA,MACH,CAAC;AAAA,MACD,QAAQ,SAAS,SACb,kFACA;AAAA,MACJ,SAAS,CAAC,GAAG,aAAa;AAAA,IAC5B;AAAA,EACF;AACA,MAAI,OAAO,SAAS,UAAU,OAAO,SAAS,OAAO;AACnD,UAAM,IAAI;AAAA,MACR,GAAG,OAAO,KAAK,YAAY,CAAC;AAAA,IAC9B;AAAA,EACF;AACA,QAAM,IAAI,MAAM,0CAA0C;AAC5D;","names":["canvases"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/theme/extractPDF.ts"],"sourcesContent":["import { formatHex, parseColor, rgbToOklch } from '@becket-ui/tokens/theme';\nimport { getDocumentProxy, getResolvedPDFJS } from 'unpdf';\n\nimport { mergeClose, neutralChroma, type ExtractedColor } from './extractColors';\nimport type { Source } from './loadSource';\nimport type { Findings, Stated } from './suggestTheme';\n\n// Brand manuals put colors, type and spacing up front; past this, pages are mostly imagery.\nconst maxPages = 60;\n\n/** Colors, fonts, corner radius and text size from a brand manual PDF. Nothing in the PDF runs. */\nexport async function extractPDF(source: Source): Promise<Findings> {\n const { OPS } = await getResolvedPDFJS();\n const pdf = await getDocumentProxy(new Uint8Array(source.bytes));\n const totalPages = pdf.numPages;\n const pageCount = Math.min(totalPages, maxPages);\n const pages: string[] = [];\n const fills = new Map<string, number>();\n const fontUse = new Map<string, { family: string; characters: number; page: number }>();\n\n for (let number = 1; number <= pageCount; number += 1) {\n const page = await pdf.getPage(number);\n let text = '';\n let lastY: number | null = null;\n const charactersByFont = new Map<string, number>();\n for (const item of (await page.getTextContent()).items) {\n if (!('str' in item)) continue;\n const y = item.transform[5];\n if (lastY !== null && Math.abs(y - lastY) > 1) text += '\\n';\n text += item.str;\n if (item.hasEOL) text += '\\n';\n lastY = y;\n charactersByFont.set(\n item.fontName,\n (charactersByFont.get(item.fontName) ?? 0) + item.str.trim().length,\n );\n }\n pages.push(text);\n\n const operators = await page.getOperatorList();\n operators.fnArray.forEach((fn, index) => {\n if (fn !== OPS.setFillRGBColor) return;\n // pdf.js passes the fill as one \"#rrggbb\" string; argsArray is typed `any[]`.\n const [hex] = operators.argsArray[index] as [string];\n if (typeof hex === 'string') fills.set(hex, (fills.get(hex) ?? 0) + 1);\n });\n for (const [id, characters] of charactersByFont) {\n if (!characters || !page.commonObjs.has(id)) continue;\n // commonObjs.get returns `any`; a loaded font carries its PostScript name.\n const font = page.commonObjs.get(id) as { name?: string } | undefined;\n if (!font?.name) continue;\n // \"ABCDEF+OpenSans-SemiBoldItalic\" → \"Open Sans\": drop the subset tag and the weight/style.\n const name = font.name\n .replace(/^[A-Z]{6}\\+/, '')\n .replace(\n /[-,]?(Thin|ExtraLight|UltraLight|Light|Regular|Book|Roman|Medium|SemiBold|DemiBold|Bold|ExtraBold|UltraBold|Black|Heavy|Italic|Oblique|It|MT|PS)+$/,\n '',\n )\n .replace(/[-_,]+$/, '');\n const family = name.includes(' ') ? name : name.replace(/([a-z])([A-Z])/g, '$1 $2');\n const entry = fontUse.get(family) ?? { family, characters: 0, page: number };\n entry.characters += characters;\n fontUse.set(family, entry);\n }\n page.cleanup();\n }\n await pdf.loadingTask.destroy();\n\n // What the manual says outright, line by line.\n const stated: Stated = { colors: [], fonts: [], radii: [], baseSize: [] };\n pages.forEach((text, index) => {\n const page = index + 1;\n for (const line of text.split('\\n')) {\n for (const { pattern, read, approximate } of [\n {\n pattern: /#([0-9a-f]{6}|[0-9a-f]{3})\\b/gi,\n read: (match: RegExpMatchArray) => `#${match[1]}`,\n },\n {\n pattern: /\\bRGB[:\\s]*\\(?\\s*(\\d{1,3})[,\\s/]+(\\d{1,3})[,\\s/]+(\\d{1,3})\\)?/gi,\n read: (match: RegExpMatchArray) =>\n match.slice(1, 4).every((channel) => Number(channel) <= 255)\n ? `rgb(${match[1]}, ${match[2]}, ${match[3]})`\n : null,\n },\n {\n // \"CMYK 100 58 0 43\", \"C100 M58 Y0 K43\", \"C 100 / M 58 / Y 0 / K 43\"\n pattern:\n /\\b(?:CMYK[:\\s]*\\(?\\s*(\\d{1,3})[,\\s/%]+(\\d{1,3})[,\\s/%]+(\\d{1,3})[,\\s/%]+(\\d{1,3})|C\\s*(\\d{1,3})[,\\s/%]*M\\s*(\\d{1,3})[,\\s/%]*Y\\s*(\\d{1,3})[,\\s/%]*K\\s*(\\d{1,3}))/gi,\n read: (match: RegExpMatchArray) => {\n const [c, m, y, k] = (match[1] ? match.slice(1, 5) : match.slice(5, 9)).map(\n (part) => Number(part) / 100,\n );\n if ([c, m, y, k].some((part) => part > 1)) return null;\n // Uncalibrated conversion: close enough to pick a hue, not a print match. Reported as approximate.\n const [r, g, b] = [c, m, y].map((part) => Math.round(255 * (1 - part) * (1 - k)));\n return formatHex(rgbToOklch([r, g, b]));\n },\n approximate: true,\n },\n ]) {\n for (const match of line.matchAll(pattern)) {\n const value = read(match);\n const color = value && parseColor(value);\n if (!color) continue;\n const hex = formatHex(color);\n if (stated.colors.some((entry) => entry.hex === hex)) continue;\n // The words right before the color, e.g. \"Ocean Blue\" in \"Ocean Blue #0A3D91\".\n const name = line\n .slice(0, match.index ?? 0)\n .replace(/(primary|secondary|accent|color|colour|hex|rgb|cmyk)\\s*:?\\s*$/i, '')\n .trim()\n .split(/\\s+/)\n .slice(-3)\n .filter((word) => /^[A-Za-z][A-Za-z'’-]*:?$/.test(word))\n .join(' ')\n .replace(/:$/, '');\n const label = name.length >= 3 ? name : undefined;\n stated.colors.push({\n hex,\n name: approximate ? `${label ?? ''} (from CMYK, approximate)`.trim() : label,\n page,\n });\n }\n }\n for (const match of line.matchAll(\n /\\b(?:corner|border)[\\s-]*radi(?:us|i)\\b[^0-9\\n]{0,24}(\\d+(?:\\.\\d+)?)\\s*(px|pt)\\b/gi,\n )) {\n stated.radii.push({\n // px or pt → rem, so the theme keeps following the browser's text size.\n value: `${Number(((match[2].toLowerCase() === 'pt' ? (Number(match[1]) * 4) / 3 : Number(match[1])) / 16).toFixed(4))}rem`,\n page,\n });\n }\n for (const match of line.matchAll(\n /\\b(?:body|base|paragraph)\\s*(?:text|copy|font)?\\s*(?:size)?\\b[^0-9\\n]{0,24}(\\d+(?:\\.\\d+)?)\\s*(px|pt)\\b/gi,\n )) {\n const size = Number(match[1]);\n if (size < 10 || size > 24) continue;\n stated.baseSize.push({\n value: `${Number(((match[2].toLowerCase() === 'pt' ? (size * 4) / 3 : size) / 16).toFixed(4))}rem`,\n page,\n });\n }\n }\n });\n stated.fonts = [...fontUse.values()]\n // Fonts every PDF tool falls back to; a manual set in one of these rarely means \"use it\".\n .filter(\n (font) =>\n !/^(Helvetica|Arial|Times|TimesNewRoman|Courier|Symbol|ZapfDingbats|ArialMT)$/i.test(\n font.family.replace(/\\s/g, ''),\n ),\n )\n // pdf.js names glyph-drawn (Type 3) and unnamed fonts with placeholders, not real families.\n .filter(\n (font) => /[a-z]{2}/i.test(font.family) && !/^(Type\\s?3|T3\\s?Font|g_d\\d)/i.test(font.family),\n )\n .toSorted((a, b) => b.characters - a.characters)\n .map(({ family, page }) => ({ family, page }));\n\n // Summed once here, not per color inside the flatMap below.\n const total = [...fills.values()].reduce((sum, count) => sum + count, 0);\n return {\n label: source.label,\n method: `PDF, ${pageCount} of ${totalPages} pages: stated colors, fonts and sizes from the text, plus artwork fill colors (by how often each is used, not by area)`,\n colors: mergeClose(\n [...fills.entries()].flatMap(([hex, count]): ExtractedColor[] => {\n const color = parseColor(hex);\n if (!color) return [];\n return [\n {\n hex: formatHex(color),\n color,\n share: count / total,\n role: color.C < neutralChroma ? 'neutral' : 'brand',\n },\n ];\n }),\n ),\n stated,\n skipped:\n totalPages > maxPages\n ? [`pages ${maxPages + 1}–${totalPages} (only the first ${maxPages} are read)`]\n : [],\n };\n}\n"],"mappings":";;;;;;;;;AACA,SAAS,kBAAkB,wBAAwB;AAOnD,IAAM,WAAW;AAGjB,eAAsB,WAAW,QAAmC;AAClE,QAAM,EAAE,IAAI,IAAI,MAAM,iBAAiB;AACvC,QAAM,MAAM,MAAM,iBAAiB,IAAI,WAAW,OAAO,KAAK,CAAC;AAC/D,QAAM,aAAa,IAAI;AACvB,QAAM,YAAY,KAAK,IAAI,YAAY,QAAQ;AAC/C,QAAM,QAAkB,CAAC;AACzB,QAAM,QAAQ,oBAAI,IAAoB;AACtC,QAAM,UAAU,oBAAI,IAAkE;AAEtF,WAAS,SAAS,GAAG,UAAU,WAAW,UAAU,GAAG;AACrD,UAAM,OAAO,MAAM,IAAI,QAAQ,MAAM;AACrC,QAAI,OAAO;AACX,QAAI,QAAuB;AAC3B,UAAM,mBAAmB,oBAAI,IAAoB;AACjD,eAAW,SAAS,MAAM,KAAK,eAAe,GAAG,OAAO;AACtD,UAAI,EAAE,SAAS,MAAO;AACtB,YAAM,IAAI,KAAK,UAAU,CAAC;AAC1B,UAAI,UAAU,QAAQ,KAAK,IAAI,IAAI,KAAK,IAAI,EAAG,SAAQ;AACvD,cAAQ,KAAK;AACb,UAAI,KAAK,OAAQ,SAAQ;AACzB,cAAQ;AACR,uBAAiB;AAAA,QACf,KAAK;AAAA,SACJ,iBAAiB,IAAI,KAAK,QAAQ,KAAK,KAAK,KAAK,IAAI,KAA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