@becket-ui/mcp 0.0.0-stage → 0.5.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.
@@ -0,0 +1,780 @@
1
+ // ../tokens/theme/color.mjs
2
+ var clamp01 = (value) => Math.min(1, Math.max(0, value));
3
+ function toLinear(channel) {
4
+ return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4;
5
+ }
6
+ function linearToOklch([r, g, b]) {
7
+ const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);
8
+ const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
9
+ const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
10
+ const a = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s;
11
+ const bb = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s;
12
+ const C = Math.hypot(a, bb);
13
+ return {
14
+ L: 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,
15
+ C: C < 1e-4 ? 0 : C,
16
+ // Grays have no meaningful hue; 0 keeps the output stable.
17
+ h: C < 1e-4 ? 0 : (Math.atan2(bb, a) * 180 / Math.PI + 360) % 360
18
+ };
19
+ }
20
+ function oklchToLinear({ L, C, h }) {
21
+ const radians = h * Math.PI / 180;
22
+ const a = C * Math.cos(radians);
23
+ const b = C * Math.sin(radians);
24
+ const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3;
25
+ const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3;
26
+ const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3;
27
+ return [
28
+ 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,
29
+ -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,
30
+ -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s
31
+ ];
32
+ }
33
+ function number(part, scale = 1) {
34
+ const value = part.trim();
35
+ if (value === "none") return 0;
36
+ if (value.endsWith("%")) return Number.parseFloat(value) / 100 * scale;
37
+ return Number.parseFloat(value);
38
+ }
39
+ function parseColor(input) {
40
+ if (typeof input !== "string") return null;
41
+ const value = ({
42
+ black: "#000000",
43
+ white: "#ffffff",
44
+ red: "#ff0000",
45
+ green: "#008000",
46
+ blue: "#0000ff",
47
+ yellow: "#ffff00",
48
+ orange: "#ffa500",
49
+ purple: "#800080",
50
+ gray: "#808080",
51
+ grey: "#808080",
52
+ navy: "#000080",
53
+ teal: "#008080",
54
+ maroon: "#800000",
55
+ olive: "#808000",
56
+ lime: "#00ff00",
57
+ aqua: "#00ffff",
58
+ fuchsia: "#ff00ff",
59
+ silver: "#c0c0c0"
60
+ }[input.trim().toLowerCase()] ?? input).trim();
61
+ const hex = value.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i);
62
+ if (hex) {
63
+ return linearToOklch(
64
+ // #abc → #aabbcc; the first three pairs are r, g, b (alpha is dropped).
65
+ (hex[1].length <= 4 ? [...hex[1]].map((digit) => digit + digit).join("") : hex[1]).match(/../g).slice(0, 3).map((pair) => toLinear(Number.parseInt(pair, 16) / 255))
66
+ );
67
+ }
68
+ const fn = value.match(/^(rgba?|hsla?|oklch)\(\s*([^)]*)\)$/i);
69
+ if (!fn) return null;
70
+ const kind = fn[1].toLowerCase();
71
+ const withoutAlpha = fn[2].split("/")[0];
72
+ const parts = (withoutAlpha.includes(",") ? withoutAlpha.split(",") : withoutAlpha.trim().split(/\s+/)).slice(0, 3);
73
+ if (parts.length !== 3) return null;
74
+ if (kind.startsWith("rgb")) {
75
+ const rgb = parts.map((part) => clamp01(number(part, 255) / 255));
76
+ if (rgb.some(Number.isNaN)) return null;
77
+ return linearToOklch(rgb.map(toLinear));
78
+ }
79
+ if (kind.startsWith("hsl")) {
80
+ const hue = Number.parseFloat(parts[0]);
81
+ const saturation = clamp01(number(parts[1]));
82
+ const lightness = clamp01(number(parts[2]));
83
+ if ([hue, saturation, lightness].some(Number.isNaN)) return null;
84
+ const chroma = (1 - Math.abs(2 * lightness - 1)) * saturation;
85
+ const sector = (hue % 360 + 360) % 360 / 60;
86
+ const x = chroma * (1 - Math.abs(sector % 2 - 1));
87
+ const [r, g, b] = [
88
+ [chroma, x, 0],
89
+ [x, chroma, 0],
90
+ [0, chroma, x],
91
+ [0, x, chroma],
92
+ [x, 0, chroma],
93
+ [chroma, 0, x]
94
+ ][Math.min(5, Math.floor(sector))];
95
+ const offset = lightness - chroma / 2;
96
+ return linearToOklch([r + offset, g + offset, b + offset].map(toLinear));
97
+ }
98
+ const [L, C, h] = [number(parts[0]), number(parts[1], 0.4), number(parts[2])];
99
+ if ([L, C, h].some(Number.isNaN)) return null;
100
+ return { L: clamp01(L), C: Math.max(0, C), h: (h % 360 + 360) % 360 };
101
+ }
102
+ function toGamut(color) {
103
+ if (oklchToLinear(color).every((channel) => channel >= -1e-4 && channel <= 1 + 1e-4))
104
+ return color;
105
+ let [low, high] = [0, color.C];
106
+ for (let step = 0; step < 24; step += 1) {
107
+ const middle = (low + high) / 2;
108
+ if (oklchToLinear({ ...color, C: middle }).every(
109
+ (channel) => channel >= -1e-4 && channel <= 1 + 1e-4
110
+ ))
111
+ low = middle;
112
+ else high = middle;
113
+ }
114
+ return { ...color, C: low };
115
+ }
116
+ function formatOklch({ L, C, h }) {
117
+ const round = (value, digits) => Number(value.toFixed(digits));
118
+ return `oklch(${round(L, 4)} ${round(C, 4)} ${round(C === 0 ? 0 : h, 2)})`;
119
+ }
120
+ function formatHex(color) {
121
+ return `#${oklchToLinear(toGamut(color)).map((linear) => {
122
+ const channel = clamp01(linear);
123
+ return Math.round(
124
+ clamp01(channel <= 31308e-7 ? channel * 12.92 : 1.055 * channel ** (1 / 2.4) - 0.055) * 255
125
+ ).toString(16).padStart(2, "0");
126
+ }).join("")}`;
127
+ }
128
+ function contrastRatio(foreground, background) {
129
+ const [first, second] = [foreground, background].map((color) => {
130
+ const parsed = typeof color === "string" ? parseColor(color) : color;
131
+ if (!parsed)
132
+ throw new Error(`Can't read the color "${color}". Use hex, rgb(), hsl() or oklch().`);
133
+ const [r, g, b] = oklchToLinear(parsed).map(clamp01);
134
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
135
+ });
136
+ const [high, low] = first > second ? [first, second] : [second, first];
137
+ return (high + 0.05) / (low + 0.05);
138
+ }
139
+ function colorDistance(first, second) {
140
+ const [a, b] = [first, second].map(({ L, C, h }) => [
141
+ L,
142
+ C * Math.cos(h * Math.PI / 180),
143
+ C * Math.sin(h * Math.PI / 180)
144
+ ]);
145
+ return Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
146
+ }
147
+ function rgbToOklch(rgb) {
148
+ return linearToOklch(rgb.map((channel) => toLinear(channel / 255)));
149
+ }
150
+
151
+ // ../tokens/theme/contrast.mjs
152
+ var defaultColors = {
153
+ dark: {
154
+ primary: "oklch(0.75 0.15 78)",
155
+ secondary: "oklch(0.70 0.13 125)",
156
+ tertiary: "oklch(0.60 0.16 48)",
157
+ // index.css: color-mix(in oklch, primary 88%, white)
158
+ primaryHover: { mixWithWhite: "primary", amount: 0.88 },
159
+ "neutral.50": "oklch(0.96 0.012 78)",
160
+ "neutral.100": "oklch(0.94 0.012 78)",
161
+ "neutral.200": "oklch(0.89 0.012 75)",
162
+ "neutral.300": "oklch(0.84 0.012 72)",
163
+ "neutral.400": "oklch(0.75 0.012 70)",
164
+ "neutral.500": "oklch(0.65 0.012 65)",
165
+ "neutral.600": "oklch(0.55 0.014 62)",
166
+ "neutral.700": "oklch(0.45 0.014 60)",
167
+ "neutral.800": "oklch(0.35 0.015 60)",
168
+ "neutral.900": "oklch(0.22 0.015 60)",
169
+ white: "oklch(99% 0 0)",
170
+ background: "{neutral.900}",
171
+ text: "{neutral.50}",
172
+ muted: "{neutral.300}",
173
+ surface: "{neutral.800}",
174
+ border: "{neutral.200}",
175
+ danger: "oklch(0.76 0.16 25)",
176
+ accent: "oklch(0.86 0.12 125)",
177
+ link: "{primary}",
178
+ linkHover: "oklch(0.78 0.13 78)",
179
+ linkVisited: "oklch(0.72 0.12 125)",
180
+ warning: "oklch(0.72 0.16 42)",
181
+ success: "oklch(0.68 0.14 165)"
182
+ },
183
+ /** Only what `[data-theme='light']` changes; the rest is inherited from dark. */
184
+ light: {
185
+ background: "{neutral.50}",
186
+ text: "{neutral.900}",
187
+ muted: "oklch(0.53 0.014 62)",
188
+ surface: "{white}",
189
+ danger: "oklch(0.48 0.20 25)",
190
+ accent: "oklch(0.38 0.14 125)",
191
+ link: "oklch(0.54 0.12 70)",
192
+ linkHover: "oklch(0.46 0.11 70)",
193
+ linkVisited: "oklch(0.52 0.09 125)"
194
+ }
195
+ };
196
+ var text = 4.5;
197
+ var canvases = ["background", "surface"];
198
+ var contrastPairs = [
199
+ ...["text", "muted", "link", "linkHover", "linkVisited", "danger", "accent"].flatMap(
200
+ (foreground) => canvases.map((background) => ({
201
+ foreground,
202
+ background,
203
+ minimum: text,
204
+ level: "required",
205
+ use: `${foreground} text on ${background}`
206
+ }))
207
+ ),
208
+ ...["primary", "primaryHover", "secondary"].map((background) => ({
209
+ foreground: "neutral.900",
210
+ background,
211
+ minimum: text,
212
+ level: "required",
213
+ use: `label on a filled ${background} control`
214
+ })),
215
+ {
216
+ foreground: "neutral.900",
217
+ background: "tertiary",
218
+ minimum: text,
219
+ level: "advisory",
220
+ use: "label over the tertiary end of a gradient fill",
221
+ note: "The default tertiary is 4.13:1; the label mostly sits over the primary half."
222
+ },
223
+ ...canvases.map((background) => ({
224
+ foreground: "primary",
225
+ background,
226
+ // Non-text UI and state indicators (WCAG 1.4.11).
227
+ minimum: 3,
228
+ level: "advisory",
229
+ use: `focus ring and checked controls on ${background}`,
230
+ 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."
231
+ }))
232
+ ];
233
+ function resolveBecketColors(theme = {}) {
234
+ const root = {};
235
+ const lightOnly = {};
236
+ for (const [key, value] of Object.entries(theme.colors ?? {})) {
237
+ if (value == null) continue;
238
+ if (key === "neutral") {
239
+ for (const [step, color] of Object.entries(value)) root[`neutral.${step}`] = color;
240
+ } else if (typeof value === "object") {
241
+ if (value.dark) root[key] = value.dark;
242
+ if (value.light) lightOnly[key] = value.light;
243
+ } else {
244
+ root[key] = value;
245
+ }
246
+ }
247
+ const [dark, light] = [
248
+ { ...defaultColors.dark, ...root },
249
+ { ...defaultColors.dark, ...defaultColors.light, ...root, ...lightOnly }
250
+ ].map((table) => {
251
+ const resolved = {};
252
+ const resolve = (key, depth = 0) => {
253
+ if (resolved[key]) return resolved[key];
254
+ if (depth > 8) throw new Error(`Color token "${key}" refers to itself`);
255
+ const value = table[key];
256
+ if (value == null) throw new Error(`Unknown color token "${key}"`);
257
+ let color;
258
+ if (typeof value === "object") {
259
+ const base = resolve(value.mixWithWhite, depth + 1);
260
+ color = {
261
+ L: base.L * value.amount + (1 - value.amount),
262
+ C: base.C * value.amount,
263
+ h: base.h
264
+ };
265
+ } else {
266
+ const reference = value.match(/^\{([\w.]+)\}$/);
267
+ color = reference ? resolve(reference[1], depth + 1) : parseColor(value);
268
+ if (!color)
269
+ throw new Error(`Can't read colors.${key} "${value}". Use hex, rgb(), hsl() or oklch().`);
270
+ }
271
+ resolved[key] = color;
272
+ return color;
273
+ };
274
+ for (const key of Object.keys(table)) resolve(key);
275
+ return resolved;
276
+ });
277
+ return { dark, light };
278
+ }
279
+ function checkBecketThemeContrast(theme = {}) {
280
+ const colors = resolveBecketColors(theme);
281
+ const results = ["dark", "light"].flatMap(
282
+ (mode) => contrastPairs.map((pair) => {
283
+ const ratio = contrastRatio(colors[mode][pair.foreground], colors[mode][pair.background]);
284
+ return {
285
+ ...pair,
286
+ theme: mode,
287
+ ratio: Math.floor(ratio * 100) / 100,
288
+ passes: ratio >= pair.minimum,
289
+ foregroundColor: formatOklch(colors[mode][pair.foreground]),
290
+ backgroundColor: formatOklch(colors[mode][pair.background])
291
+ };
292
+ })
293
+ );
294
+ return {
295
+ passes: results.every((result) => result.passes || result.level === "advisory"),
296
+ failures: results.filter((result) => !result.passes && result.level === "required"),
297
+ advisories: results.filter((result) => !result.passes && result.level === "advisory"),
298
+ results
299
+ };
300
+ }
301
+
302
+ // ../tokens/theme/derive.mjs
303
+ var textTarget = 4.6;
304
+ function fitLightness({ color, against, minimum, direction }) {
305
+ for (let L = color.L; L >= 0 && L <= 1; L += direction === "lighter" ? 5e-3 : -5e-3) {
306
+ const candidate = toGamut({ ...color, L });
307
+ if (against.every((other) => contrastRatio(candidate, other) >= minimum)) return candidate;
308
+ }
309
+ return null;
310
+ }
311
+ function describe(color) {
312
+ return `L ${color.L.toFixed(2)}`;
313
+ }
314
+ function deriveBecketTheme({ brand, pinned = {} }) {
315
+ if (!Array.isArray(brand) || brand.length === 0 || brand.length > 3) {
316
+ throw new Error("Pass one to three brand colors, most important first.");
317
+ }
318
+ const seeds = brand.map((value) => {
319
+ const color = parseColor(value);
320
+ if (!color)
321
+ throw new Error(`Can't read the brand color "${value}". Use hex, rgb(), hsl() or oklch().`);
322
+ return color;
323
+ });
324
+ const [primarySeed] = seeds;
325
+ const secondarySeed = seeds[1] ?? { ...primarySeed, h: (primarySeed.h + 45) % 360 };
326
+ const notes = [];
327
+ const colors = {};
328
+ const note = (token, reason) => notes.push({ token, reason });
329
+ const tint = primarySeed.C < 0.02 ? 0 : 0.012;
330
+ colors.neutral = Object.fromEntries(
331
+ // The default theme's lightness ladder, so text and canvases keep their contrast.
332
+ Object.entries({
333
+ 50: 0.96,
334
+ 100: 0.94,
335
+ 200: 0.89,
336
+ 300: 0.84,
337
+ 400: 0.75,
338
+ 500: 0.65,
339
+ 600: 0.55,
340
+ 700: 0.45,
341
+ 800: 0.35,
342
+ 900: 0.22
343
+ }).map(([step, L]) => [step, formatOklch({ L, C: tint, h: tint ? primarySeed.h : 0 })])
344
+ );
345
+ colors.muted = { light: formatOklch({ L: 0.53, C: tint, h: tint ? primarySeed.h : 0 }) };
346
+ note(
347
+ "neutral",
348
+ tint ? `Grays tinted toward the brand hue (${primarySeed.h.toFixed(0)}\xB0), lightness unchanged.` : "The brand is near-gray, so neutrals stay untinted."
349
+ );
350
+ const canvases2 = resolveBecketColors({ colors: { ...colors, ...pinned } });
351
+ const dark = [canvases2.dark.background, canvases2.dark.surface];
352
+ const light = [canvases2.light.background, canvases2.light.surface];
353
+ const fill = ({ token, seed, label }) => {
354
+ const fitted = fitLightness({
355
+ color: seed,
356
+ // Filled controls put neutral.900 labels on the brand color.
357
+ against: [canvases2.dark["neutral.900"]],
358
+ minimum: textTarget,
359
+ direction: "lighter"
360
+ });
361
+ colors[token] = formatOklch(fitted);
362
+ if (fitted.L !== seed.L)
363
+ note(
364
+ token,
365
+ `${label} lightened from ${describe(seed)} to ${describe(fitted)} so dark button labels reach 4.5:1.`
366
+ );
367
+ else note(token, `${label} used as is.`);
368
+ };
369
+ fill({ token: "primary", seed: primarySeed, label: "Brand color 1" });
370
+ fill({
371
+ token: "secondary",
372
+ seed: secondarySeed,
373
+ label: seeds[1] ? "Brand color 2" : "Derived from brand color 1 (hue +45\xB0)"
374
+ });
375
+ fill({
376
+ token: "tertiary",
377
+ seed: seeds[2] ?? { ...primarySeed, h: (primarySeed.h + 330) % 360 },
378
+ label: seeds[2] ? "Brand color 3" : "Derived from brand color 1 (hue \u221230\xB0)"
379
+ });
380
+ const onCanvas = ({ token, seed, label }) => {
381
+ const darkFit = fitLightness({
382
+ color: seed,
383
+ against: dark,
384
+ minimum: textTarget,
385
+ direction: "lighter"
386
+ });
387
+ const lightFit = fitLightness({
388
+ color: seed,
389
+ against: light,
390
+ minimum: textTarget,
391
+ direction: "darker"
392
+ });
393
+ if (!darkFit || !lightFit) {
394
+ note(
395
+ token,
396
+ `${label} can't reach 4.5:1 on your pinned canvas in ${darkFit ? "light" : "dark"}; left at the Becket default.`
397
+ );
398
+ return null;
399
+ }
400
+ colors[token] = { dark: formatOklch(darkFit), light: formatOklch(lightFit) };
401
+ const exact = [darkFit.L === seed.L && "dark", lightFit.L === seed.L && "light"].filter(
402
+ Boolean
403
+ );
404
+ note(
405
+ token,
406
+ exact.length === 2 ? `${label} used as is in both themes.` : exact.length === 1 ? `${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.` : `${label} shaded per theme (dark ${describe(darkFit)}, light ${describe(lightFit)}) for 4.5:1 on the canvas.`
407
+ );
408
+ return { dark: darkFit, light: lightFit };
409
+ };
410
+ const link = onCanvas({ token: "link", seed: primarySeed, label: "Brand color 1" });
411
+ onCanvas({
412
+ token: "linkVisited",
413
+ seed: secondarySeed,
414
+ label: seeds[1] ? "Brand color 2" : "The derived secondary"
415
+ });
416
+ onCanvas({
417
+ token: "accent",
418
+ seed: secondarySeed,
419
+ label: seeds[1] ? "Brand color 2" : "The derived secondary"
420
+ });
421
+ if (link) {
422
+ colors.linkHover = {
423
+ dark: formatOklch(toGamut({ ...link.dark, L: Math.min(1, link.dark.L + 0.06) })),
424
+ light: formatOklch(
425
+ fitLightness({
426
+ color: { ...link.light, L: Math.max(0, link.light.L - 0.08) },
427
+ against: light,
428
+ minimum: textTarget,
429
+ direction: "darker"
430
+ })
431
+ )
432
+ };
433
+ note("linkHover", "The link color a step lighter on dark and a step darker on light.");
434
+ }
435
+ for (const token of ["text", "muted"]) {
436
+ if (pinned[token]) continue;
437
+ const current = resolveBecketColors({ colors: { ...colors, ...pinned } });
438
+ const darkFit = fitLightness({
439
+ color: current.dark[token],
440
+ against: dark,
441
+ minimum: textTarget,
442
+ direction: "lighter"
443
+ });
444
+ const lightFit = fitLightness({
445
+ color: current.light[token],
446
+ against: light,
447
+ minimum: textTarget,
448
+ direction: "darker"
449
+ });
450
+ if (darkFit.L === current.dark[token].L && lightFit.L === current.light[token].L) continue;
451
+ colors[token] = { dark: formatOklch(darkFit), light: formatOklch(lightFit) };
452
+ note(token, "Adjusted so it stays at 4.5:1 on your pinned canvas.");
453
+ }
454
+ const fromDanger = Math.abs(primarySeed.h - 25);
455
+ if (primarySeed.C >= 0.08 && Math.min(fromDanger, 360 - fromDanger) < 20) {
456
+ note(
457
+ "danger",
458
+ "Your brand is red, like error text. Danger stays Becket red; make sure errors also carry an icon or text, not color alone."
459
+ );
460
+ }
461
+ for (const [token, value] of Object.entries(pinned)) {
462
+ if (token === "neutral") colors.neutral = { ...colors.neutral, ...value };
463
+ else colors[token] = value;
464
+ note(token, "Pinned by you, kept exactly.");
465
+ }
466
+ const theme = { colors };
467
+ return { theme, notes, contrast: checkBecketThemeContrast(theme) };
468
+ }
469
+
470
+ // ../tokens/theme/index.mjs
471
+ var PREFIX = "--beckui--";
472
+ var COLOR_FLAT = [
473
+ "primary",
474
+ "secondary",
475
+ "tertiary",
476
+ "primaryHover",
477
+ "lightBackground",
478
+ "lightText",
479
+ "warning",
480
+ "success"
481
+ ];
482
+ var COLOR_THEMED = [
483
+ "background",
484
+ "text",
485
+ "muted",
486
+ "border",
487
+ "danger",
488
+ "accent",
489
+ "surface",
490
+ "link",
491
+ "linkHover",
492
+ "linkVisited"
493
+ ];
494
+ var NEUTRAL_STEPS = ["50", "100", "200", "300", "400", "500", "600", "700", "800", "900"];
495
+ var RADII = ["none", "sm", "md", "lg", "xl", "full"];
496
+ var FONT_SIZES = ["base", "xs", "sm", "md", "lg", "xl", "2xl", "3xl", "4xl", "5xl", "6xl"];
497
+ var SPACING = ["unit", "textUnit", "xs", "sm", "md", "lg", "xl"];
498
+ var FONTS = ["sans", "mono"];
499
+ var DENSITY_SIZES = {
500
+ button: ["sm", "md"],
501
+ field: ["sm", "md", "lg"],
502
+ tag: ["sm", "md", "lg"]
503
+ };
504
+ function kebab(value) {
505
+ return value.replace(/[A-Z]/g, (char) => `-${char.toLowerCase()}`);
506
+ }
507
+ function cssVar(parts) {
508
+ return `${PREFIX}${parts.map(kebab).join("-")}`;
509
+ }
510
+ function assertAllowedKeys(object, allowed, label) {
511
+ for (const key of Object.keys(object)) {
512
+ if (!allowed.includes(key)) {
513
+ throw new Error(`Unknown Becket theme key "${label}.${key}"`);
514
+ }
515
+ }
516
+ }
517
+ function pushDecl(decls, name, value) {
518
+ if (value == null || value === "") return;
519
+ decls.push(` ${name}: ${value};`);
520
+ }
521
+ function pushThemed(rootDecls, lightDecls, name, value) {
522
+ if (value == null || value === "") return;
523
+ if (typeof value === "object") {
524
+ if (value.dark) pushDecl(rootDecls, name, value.dark);
525
+ if (value.light) pushDecl(lightDecls, name, value.light);
526
+ return;
527
+ }
528
+ pushDecl(rootDecls, name, value);
529
+ }
530
+ function colorDecls(colors, rootDecls, lightDecls) {
531
+ assertAllowedKeys(colors, [...COLOR_FLAT, ...COLOR_THEMED, "neutral"], "colors");
532
+ for (const key of COLOR_FLAT) {
533
+ const value = colors[key];
534
+ if (value == null) continue;
535
+ if (typeof value === "object") {
536
+ throw new Error(`colors.${key} must be a CSS color string`);
537
+ }
538
+ pushDecl(rootDecls, cssVar(["colors", key]), value);
539
+ }
540
+ for (const key of COLOR_THEMED) {
541
+ pushThemed(rootDecls, lightDecls, cssVar(["colors", key]), colors[key]);
542
+ }
543
+ if (colors.neutral) {
544
+ assertAllowedKeys(colors.neutral, NEUTRAL_STEPS, "colors.neutral");
545
+ for (const step of NEUTRAL_STEPS) {
546
+ pushDecl(rootDecls, cssVar(["colors", "neutral", step]), colors.neutral[step]);
547
+ }
548
+ }
549
+ }
550
+ function densityDecls(density, decls) {
551
+ assertAllowedKeys(density, ["button", "field", "tag"], "density");
552
+ for (const component of Object.keys(DENSITY_SIZES)) {
553
+ const sizes = density[component];
554
+ if (!sizes) continue;
555
+ const allowed = DENSITY_SIZES[component];
556
+ assertAllowedKeys(sizes, allowed, `density.${component}`);
557
+ for (const size of allowed) {
558
+ const box = sizes[size];
559
+ if (!box) continue;
560
+ assertAllowedKeys(box, ["px", "py"], `density.${component}.${size}`);
561
+ if (box.px) decls.push(` --beckui-${component}-px-${size}: ${box.px};`);
562
+ if (box.py) decls.push(` --beckui-${component}-py-${size}: ${box.py};`);
563
+ }
564
+ }
565
+ }
566
+ function sheet(selector, decls) {
567
+ if (!decls.length) return "";
568
+ return `${selector} {
569
+ ${decls.join("\n")}
570
+ }
571
+ `;
572
+ }
573
+ function defineBecketTheme(config = {}) {
574
+ assertAllowedKeys(
575
+ config,
576
+ ["colors", "radii", "fontSizes", "spacing", "sizes", "fonts", "density"],
577
+ "theme"
578
+ );
579
+ const rootDecls = [];
580
+ const lightDecls = [];
581
+ if (config.colors) colorDecls(config.colors, rootDecls, lightDecls);
582
+ if (config.radii) {
583
+ assertAllowedKeys(config.radii, RADII, "radii");
584
+ for (const key of RADII) {
585
+ pushDecl(rootDecls, cssVar(["radii", key]), config.radii[key]);
586
+ }
587
+ }
588
+ if (config.fontSizes) {
589
+ assertAllowedKeys(config.fontSizes, FONT_SIZES, "fontSizes");
590
+ for (const key of FONT_SIZES) {
591
+ pushDecl(rootDecls, cssVar(["font-sizes", key]), config.fontSizes[key]);
592
+ }
593
+ }
594
+ if (config.spacing) {
595
+ assertAllowedKeys(config.spacing, SPACING, "spacing");
596
+ for (const key of SPACING) {
597
+ pushDecl(rootDecls, cssVar(["spacing", key]), config.spacing[key]);
598
+ }
599
+ }
600
+ if (config.sizes) {
601
+ assertAllowedKeys(config.sizes, ["field"], "sizes");
602
+ pushDecl(rootDecls, cssVar(["sizes", "field"]), config.sizes.field);
603
+ }
604
+ if (config.fonts) {
605
+ assertAllowedKeys(config.fonts, FONTS, "fonts");
606
+ for (const key of FONTS) {
607
+ pushDecl(rootDecls, cssVar(["fonts", key]), config.fonts[key]);
608
+ }
609
+ }
610
+ if (config.density) densityDecls(config.density, rootDecls);
611
+ const css = `${sheet(":root", rootDecls)}${sheet("html[data-theme='light']", lightDecls)}`;
612
+ if (!css) {
613
+ return "/* defineBecketTheme: empty config, Becket defaults unchanged */\n";
614
+ }
615
+ return css;
616
+ }
617
+ var BECKET_PUBLIC_COLOR_KEYS = [...COLOR_FLAT, ...COLOR_THEMED];
618
+
619
+ // src/theme/extractColors.ts
620
+ import jpeg from "jpeg-js";
621
+ import { PNG } from "pngjs";
622
+ var maxPixels = 5e7;
623
+ var sameColor = 0.05;
624
+ var neutralChroma = 0.04;
625
+ function colorsFromPixels({
626
+ width,
627
+ height,
628
+ data
629
+ }) {
630
+ const step = Math.max(1, Math.floor(Math.sqrt(width * height / 16e4)));
631
+ const border = Math.max(1, Math.round(Math.min(width, height) * 0.02));
632
+ const bins = /* @__PURE__ */ new Map();
633
+ let opaque = 0;
634
+ let edgeSamples = 0;
635
+ for (let y = 0; y < height; y += step) {
636
+ for (let x = 0; x < width; x += step) {
637
+ const offset = (y * width + x) * 4;
638
+ if (data[offset + 3] < 128) continue;
639
+ const [r, g, b] = [data[offset], data[offset + 1], data[offset + 2]];
640
+ const key = r >> 3 << 10 | g >> 3 << 5 | b >> 3;
641
+ const isEdge = x < border || y < border || x >= width - border || y >= height - border;
642
+ const bin = bins.get(key) ?? { count: 0, edge: 0, r: 0, g: 0, b: 0 };
643
+ bin.count += 1;
644
+ bin.r += r;
645
+ bin.g += g;
646
+ bin.b += b;
647
+ if (isEdge) bin.edge += 1;
648
+ bins.set(key, bin);
649
+ opaque += 1;
650
+ if (isEdge) edgeSamples += 1;
651
+ }
652
+ }
653
+ if (opaque === 0) return [];
654
+ const clusters = [];
655
+ for (const bin of [...bins.values()].toSorted((a, b) => b.count - a.count)) {
656
+ const color = rgbToOklch([bin.r / bin.count, bin.g / bin.count, bin.b / bin.count]);
657
+ const home = clusters.find((cluster) => colorDistance(cluster.color, color) < sameColor);
658
+ if (home) {
659
+ home.count += bin.count;
660
+ home.edge += bin.edge;
661
+ continue;
662
+ }
663
+ if (clusters.length < 64) clusters.push({ count: bin.count, edge: bin.edge, color });
664
+ }
665
+ return clusters.filter((cluster) => cluster.count / opaque >= 5e-3).map((cluster) => ({
666
+ hex: formatHex(cluster.color),
667
+ color: cluster.color,
668
+ share: cluster.count / opaque,
669
+ // The background touches the edges at least half as often as the average opaque pixel,
670
+ // and covers 5% or more of the edge.
671
+ role: edgeSamples > 0 && cluster.edge / cluster.count >= edgeSamples / opaque * 0.5 && cluster.edge / edgeSamples >= 0.05 ? "background" : cluster.color.C < neutralChroma ? "neutral" : "brand"
672
+ })).toSorted((a, b) => b.share - a.share);
673
+ }
674
+ function mergeClose(colors) {
675
+ const merged = [];
676
+ for (const color of colors.toSorted((a, b) => b.share - a.share)) {
677
+ const home = merged.find(
678
+ (each) => each.role === color.role && colorDistance(each.color, color.color) < sameColor
679
+ );
680
+ if (home) home.share += color.share;
681
+ else merged.push({ ...color });
682
+ }
683
+ return merged;
684
+ }
685
+ function extractImageColors(source) {
686
+ if (source.kind === "png") {
687
+ const [width, height] = [source.bytes.readUInt32BE(16), source.bytes.readUInt32BE(20)];
688
+ if (width * height > maxPixels)
689
+ throw new Error(`The PNG is ${width}\xD7${height}; the limit is ${maxPixels / 1e6} megapixels.`);
690
+ return {
691
+ colors: colorsFromPixels(PNG.sync.read(source.bytes)),
692
+ method: "PNG pixels",
693
+ skipped: []
694
+ };
695
+ }
696
+ if (source.kind === "jpeg") {
697
+ return {
698
+ colors: colorsFromPixels(
699
+ jpeg.decode(source.bytes, {
700
+ useTArray: true,
701
+ formatAsRGBA: true,
702
+ maxResolutionInMP: maxPixels / 1e6,
703
+ maxMemoryUsageInMB: 1024
704
+ })
705
+ ),
706
+ method: "JPEG pixels",
707
+ skipped: []
708
+ };
709
+ }
710
+ if (source.kind === "svg") {
711
+ const svg = source.bytes.toString("utf8");
712
+ const counts = /* @__PURE__ */ new Map();
713
+ const skippedValues = /* @__PURE__ */ new Set();
714
+ for (const [, , raw] of svg.matchAll(
715
+ /(?:^|[\s;"'{])(fill|stroke|stop-color|color|flood-color)\s*(?:=\s*["']|:\s*)([^"';}>]+)/gi
716
+ )) {
717
+ const value = raw.trim().replace(/\s*!important$/, "");
718
+ const lower = value.toLowerCase();
719
+ if (["none", "currentcolor", "transparent", "inherit", "initial", "unset"].includes(lower) || lower.startsWith("url(") || lower.startsWith("var("))
720
+ continue;
721
+ const color = parseColor(value);
722
+ if (!color) {
723
+ skippedValues.add(value);
724
+ continue;
725
+ }
726
+ const hex = formatHex(color);
727
+ const entry = counts.get(hex) ?? { color, count: 0 };
728
+ entry.count += 1;
729
+ counts.set(hex, entry);
730
+ }
731
+ const embedded = [...svg.matchAll(/data:image\/(?:png|jpeg);base64,([A-Za-z0-9+/=\s]+)/g)].map(
732
+ ([, data]) => Buffer.from(data.replace(/\s+/g, ""), "base64")
733
+ );
734
+ const total = [...counts.values()].reduce((sum, entry) => sum + entry.count, 0);
735
+ return {
736
+ colors: mergeClose([
737
+ ...[...counts.entries()].map(([hex, entry]) => ({
738
+ hex,
739
+ color: entry.color,
740
+ share: entry.count / total,
741
+ role: entry.color.C < neutralChroma ? "neutral" : "brand"
742
+ })),
743
+ ...embedded.flatMap((bytes) => {
744
+ try {
745
+ return extractImageColors({
746
+ bytes,
747
+ kind: bytes[0] === 137 ? "png" : "jpeg",
748
+ label: source.label
749
+ }).colors.map((color) => ({ ...color, share: color.share / embedded.length }));
750
+ } catch {
751
+ return [];
752
+ }
753
+ })
754
+ ]),
755
+ method: embedded.length ? "SVG colors and embedded images (by how often each color is used, not by area)" : "SVG colors (by how often each is used, not by area)",
756
+ skipped: [...skippedValues]
757
+ };
758
+ }
759
+ if (source.kind === "webp" || source.kind === "gif") {
760
+ throw new Error(
761
+ `${source.kind.toUpperCase()} isn't supported yet. Export the logo as SVG or PNG, or tell me its colors.`
762
+ );
763
+ }
764
+ throw new Error("That isn't a PNG, JPEG, SVG or PDF file.");
765
+ }
766
+
767
+ export {
768
+ parseColor,
769
+ formatHex,
770
+ colorDistance,
771
+ rgbToOklch,
772
+ checkBecketThemeContrast,
773
+ deriveBecketTheme,
774
+ defineBecketTheme,
775
+ BECKET_PUBLIC_COLOR_KEYS,
776
+ neutralChroma,
777
+ mergeClose,
778
+ extractImageColors
779
+ };
780
+ //# sourceMappingURL=chunk-UWMYE5IA.js.map