@tenphi/glaze 0.0.0-snapshot.f3bb46b → 0.0.0-snapshot.fdc17e3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -98,7 +98,12 @@ const K2 = .03;
98
98
  const K3 = (1 + K1) / (1 + K2);
99
99
  const EPSILON = 1e-10;
100
100
  const constrainAngle = (angle) => (angle % 360 + 360) % 360;
101
+ /**
102
+ * OKHSL toe function: maps OKLab lightness L to perceptual lightness l.
103
+ * Exported for the OKHST tone transfers in `okhst.ts`.
104
+ */
101
105
  const toe = (x) => .5 * (K3 * x - K1 + Math.sqrt((K3 * x - K1) * (K3 * x - K1) + 4 * K2 * K3 * x));
106
+ /** Inverse OKHSL toe: maps perceptual lightness l back to OKLab lightness L. */
102
107
  const toeInv = (x) => (x ** 2 + K1 * x) / (K3 * (x + K2));
103
108
  const dot3 = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
104
109
  const dotXY = (a, b) => a[0] * b[0] + a[1] * b[1];
@@ -253,10 +258,48 @@ const getCs = (L, a, b, cusp) => {
253
258
  cMax
254
259
  ];
255
260
  };
261
+ const CYAN_A = Math.cos(199.8 * Math.PI / 180);
262
+ const CYAN_B = Math.sin(199.8 * Math.PI / 180);
263
+ const BLUE_A = Math.cos(267.4 * Math.PI / 180);
264
+ const BLUE_B = Math.sin(267.4 * Math.PI / 180);
265
+ let cyanCusp;
266
+ let blueCusp;
267
+ /**
268
+ * Computes the maximum safe OKLCH chroma that fits inside the sRGB gamut
269
+ * for all possible hues at a given OKLab lightness `L`.
270
+ */
271
+ function computeSafeChromaOKLCH(L) {
272
+ if (!cyanCusp) cyanCusp = findCuspOKLCH(CYAN_A, CYAN_B);
273
+ if (!blueCusp) blueCusp = findCuspOKLCH(BLUE_A, BLUE_B);
274
+ const c1 = findGamutIntersectionOKLCH(CYAN_A, CYAN_B, L, 1, L, cyanCusp);
275
+ const c2 = findGamutIntersectionOKLCH(BLUE_A, BLUE_B, L, 1, L, blueCusp);
276
+ return Math.min(c1, c2);
277
+ }
278
+ /** Per-hue cusp-lightness cache. The cusp is mode-independent, so keying on
279
+ * a rounded hue is safe and keeps the cache small. */
280
+ const cuspLightnessCache = /* @__PURE__ */ new Map();
281
+ /**
282
+ * OKHSL lightness of the gamut cusp for a hue — the lightness where the
283
+ * realizable chroma peaks. Reuses the same `find_cusp` OKHSL already runs for
284
+ * its `s` normalization (no new color math); the OKLab cusp lightness is run
285
+ * through the OKHSL `toe` and clamped to `[0.001, 0.999]` so divisions that
286
+ * key off it stay safe. Cached per (rounded) hue.
287
+ *
288
+ * @param h Hue, 0–360.
289
+ */
290
+ function cuspLightness(h) {
291
+ const key = Math.round(constrainAngle(h) * 100) / 100;
292
+ const cached = cuspLightnessCache.get(key);
293
+ if (cached !== void 0) return cached;
294
+ const hNorm = key / 360;
295
+ const lc = clampVal(toe(findCuspOKLCH(Math.cos(TAU * hNorm), Math.sin(TAU * hNorm))[0]), .001, .999);
296
+ cuspLightnessCache.set(key, lc);
297
+ return lc;
298
+ }
256
299
  /**
257
300
  * Convert OKHSL (h: 0–360, s: 0–1, l: 0–1) to OKLab [L, a, b].
258
301
  */
259
- function okhslToOklab(h, s, l) {
302
+ function okhslToOklab(h, s, l, pastel = false) {
260
303
  const L = toeInv(l);
261
304
  let a = 0;
262
305
  let b = 0;
@@ -264,24 +307,30 @@ function okhslToOklab(h, s, l) {
264
307
  if (L !== 0 && L !== 1 && s !== 0) {
265
308
  const a_ = Math.cos(TAU * hNorm);
266
309
  const b_ = Math.sin(TAU * hNorm);
267
- const [c0, cMid, cMax] = getCs(L, a_, b_, findCuspOKLCH(a_, b_));
268
- const mid = .8;
269
- const midInv = 1.25;
270
- let t, k0, k1, k2;
271
- if (s < mid) {
272
- t = midInv * s;
273
- k0 = 0;
274
- k1 = mid * c0;
275
- k2 = 1 - k1 / cMid;
310
+ if (pastel) {
311
+ const c = s * computeSafeChromaOKLCH(L);
312
+ a = c * a_;
313
+ b = c * b_;
276
314
  } else {
277
- t = 5 * (s - .8);
278
- k0 = cMid;
279
- k1 = .2 * cMid ** 2 * 1.25 ** 2 / c0;
280
- k2 = 1 - k1 / (cMax - cMid);
315
+ const [c0, cMid, cMax] = getCs(L, a_, b_, findCuspOKLCH(a_, b_));
316
+ const mid = .8;
317
+ const midInv = 1.25;
318
+ let t, k0, k1, k2;
319
+ if (s < mid) {
320
+ t = midInv * s;
321
+ k0 = 0;
322
+ k1 = mid * c0;
323
+ k2 = 1 - k1 / cMid;
324
+ } else {
325
+ t = 5 * (s - .8);
326
+ k0 = cMid;
327
+ k1 = .2 * cMid ** 2 * 1.25 ** 2 / c0;
328
+ k2 = 1 - k1 / (cMax - cMid);
329
+ }
330
+ const c = k0 + t * k1 / (1 - k2 * t);
331
+ a = c * a_;
332
+ b = c * b_;
281
333
  }
282
- const c = k0 + t * k1 / (1 - k2 * t);
283
- a = c * a_;
284
- b = c * b_;
285
334
  }
286
335
  return [
287
336
  L,
@@ -293,8 +342,8 @@ function okhslToOklab(h, s, l) {
293
342
  * Convert OKHSL (h: 0–360, s: 0–1, l: 0–1) to linear sRGB.
294
343
  * Channels may exceed [0, 1] near gamut boundaries — caller must clamp if needed.
295
344
  */
296
- function okhslToLinearSrgb(h, s, l) {
297
- return OKLabToLinearSRGB(okhslToOklab(h, s, l));
345
+ function okhslToLinearSrgb(h, s, l, pastel = false) {
346
+ return OKLabToLinearSRGB(okhslToOklab(h, s, l, pastel));
298
347
  }
299
348
  /**
300
349
  * Compute relative luminance Y from linear sRGB channels.
@@ -324,8 +373,8 @@ const sRGBGammaToLinear = (val) => {
324
373
  /**
325
374
  * Convert OKHSL to gamma-encoded sRGB (clamped to 0–1).
326
375
  */
327
- function okhslToSrgb(h, s, l) {
328
- const lin = okhslToLinearSrgb(h, s, l);
376
+ function okhslToSrgb(h, s, l, pastel = false) {
377
+ const lin = okhslToLinearSrgb(h, s, l, pastel);
329
378
  return [
330
379
  Math.max(0, Math.min(1, sRGBLinearToGamma(lin[0]))),
331
380
  Math.max(0, Math.min(1, sRGBLinearToGamma(lin[1]))),
@@ -343,10 +392,31 @@ function gamutClampedLuminance(linearRgb) {
343
392
  const b = sRGBGammaToLinear(Math.max(0, Math.min(1, sRGBLinearToGamma(linearRgb[2]))));
344
393
  return .2126 * r + .7152 * g + .0722 * b;
345
394
  }
395
+ /**
396
+ * Compute APCA screen luminance (`Ys`) from linear sRGB.
397
+ *
398
+ * APCA does not use the WCAG piecewise sRGB EOTF; it defines its own
399
+ * luminance as `0.2126·R^2.4 + 0.7152·G^2.4 + 0.0722·B^2.4` over the
400
+ * gamma-encoded (display) channels with a simple 2.4 exponent. The APCA
401
+ * soft-clamp threshold in `apcaContrast` is calibrated against this basis,
402
+ * so the solver must feed it `Ys`, not WCAG relative luminance. Channels
403
+ * are gamut-clamped to [0, 1] first, matching `gamutClampedLuminance`.
404
+ */
405
+ function apcaLuminanceFromLinearRgb(linearRgb) {
406
+ const r = Math.max(0, Math.min(1, sRGBLinearToGamma(linearRgb[0])));
407
+ const g = Math.max(0, Math.min(1, sRGBLinearToGamma(linearRgb[1])));
408
+ const b = Math.max(0, Math.min(1, sRGBLinearToGamma(linearRgb[2])));
409
+ return .2126 * Math.pow(r, 2.4) + .7152 * Math.pow(g, 2.4) + .0722 * Math.pow(b, 2.4);
410
+ }
346
411
  const linearSrgbToOklab = (rgb) => {
347
412
  return transform(cbrt3(transform(rgb, linear_sRGB_to_LMS_M)), LMS_to_OKLab_M);
348
413
  };
349
- const oklabToOkhsl = (lab) => {
414
+ /**
415
+ * Convert OKLab to OKHSL.
416
+ * Input: [L, a, b] where L: 0–1, a/b: roughly -0.5 to 0.5.
417
+ * Returns [h, s, l] where h: 0–360, s: 0–1, l: 0–1.
418
+ */
419
+ const oklabToOkhsl = (lab, pastel = false) => {
350
420
  const L = lab[0];
351
421
  const a = lab[1];
352
422
  const b = lab[2];
@@ -356,23 +426,32 @@ const oklabToOkhsl = (lab) => {
356
426
  0,
357
427
  toe(L)
358
428
  ];
429
+ const L_EXTREME_EPSILON = 1e-6;
430
+ if (L >= 1 - L_EXTREME_EPSILON || L <= L_EXTREME_EPSILON) return [
431
+ 0,
432
+ 0,
433
+ toe(L)
434
+ ];
359
435
  const a_ = a / C;
360
436
  const b_ = b / C;
361
437
  let h = Math.atan2(b, a) * (180 / Math.PI);
362
438
  h = constrainAngle(h);
363
- const [c0, cMid, cMax] = getCs(L, a_, b_, findCuspOKLCH(a_, b_));
364
- const mid = .8;
365
- const midInv = 1.25;
366
439
  let s;
367
- if (C < cMid) {
368
- const k1 = mid * c0;
369
- s = C / (k1 + C * (1 - k1 / cMid)) / midInv;
370
- } else {
371
- const k0 = cMid;
372
- const k1 = .2 * cMid ** 2 * 1.25 ** 2 / c0;
373
- const k2 = 1 - k1 / (cMax - cMid);
374
- const cDiff = C - k0;
375
- s = mid + cDiff / (k1 + cDiff * k2) / 5;
440
+ if (pastel) s = C / computeSafeChromaOKLCH(L);
441
+ else {
442
+ const [c0, cMid, cMax] = getCs(L, a_, b_, findCuspOKLCH(a_, b_));
443
+ const mid = .8;
444
+ const midInv = 1.25;
445
+ if (C < cMid) {
446
+ const k1 = mid * c0;
447
+ s = C / (k1 + C * (1 - k1 / cMid)) / midInv;
448
+ } else {
449
+ const k0 = cMid;
450
+ const k1 = .2 * cMid ** 2 * 1.25 ** 2 / c0;
451
+ const k2 = 1 - k1 / (cMax - cMid);
452
+ const cDiff = C - k0;
453
+ s = mid + cDiff / (k1 + cDiff * k2) / 5;
454
+ }
376
455
  }
377
456
  const l = toe(L);
378
457
  return [
@@ -385,40 +464,116 @@ const oklabToOkhsl = (lab) => {
385
464
  * Convert gamma-encoded sRGB (0–1 per channel) to OKHSL.
386
465
  * Returns [h, s, l] where h: 0–360, s: 0–1, l: 0–1.
387
466
  */
388
- function srgbToOkhsl(rgb) {
467
+ function srgbToOkhsl(rgb, pastel = false) {
389
468
  return oklabToOkhsl(linearSrgbToOklab([
390
469
  sRGBGammaToLinear(rgb[0]),
391
470
  sRGBGammaToLinear(rgb[1]),
392
471
  sRGBGammaToLinear(rgb[2])
393
- ]));
472
+ ]), pastel);
473
+ }
474
+ /**
475
+ * Convert CSS HSL (sRGB-based) to gamma-encoded sRGB [r, g, b] in 0–1 range.
476
+ * h: 0–360, s: 0–1, l: 0–1.
477
+ *
478
+ * Note: CSS HSL is not the same as OKHSL — it's HSL in the sRGB color space.
479
+ * Use this when parsing `hsl(...)` strings before passing to `srgbToOkhsl`.
480
+ */
481
+ function hslToSrgb(h, s, l) {
482
+ const hh = (h % 360 + 360) % 360 / 360;
483
+ const ss = clampVal(s, 0, 1);
484
+ const ll = clampVal(l, 0, 1);
485
+ if (ss === 0) return [
486
+ ll,
487
+ ll,
488
+ ll
489
+ ];
490
+ const q = ll < .5 ? ll * (1 + ss) : ll + ss - ll * ss;
491
+ const p = 2 * ll - q;
492
+ const hueToChannel = (t) => {
493
+ let tt = t;
494
+ if (tt < 0) tt += 1;
495
+ if (tt > 1) tt -= 1;
496
+ if (tt < 1 / 6) return p + (q - p) * 6 * tt;
497
+ if (tt < 1 / 2) return q;
498
+ if (tt < 2 / 3) return p + (q - p) * (2 / 3 - tt) * 6;
499
+ return p;
500
+ };
501
+ return [
502
+ hueToChannel(hh + 1 / 3),
503
+ hueToChannel(hh),
504
+ hueToChannel(hh - 1 / 3)
505
+ ];
394
506
  }
395
507
  /**
396
508
  * Parse a hex color string (#rgb or #rrggbb) to sRGB [r, g, b] in 0–1 range.
397
509
  * Returns null if the string is not a valid hex color.
510
+ *
511
+ * For 8-digit hex (`#rrggbbaa`) and 4-digit hex (`#rgba`) with alpha,
512
+ * use {@link parseHexAlpha}.
398
513
  */
399
514
  function parseHex(hex) {
515
+ const result = parseHexAlpha(hex);
516
+ if (!result || result.alpha !== void 0) return null;
517
+ return result.rgb;
518
+ }
519
+ /**
520
+ * Parse a hex color string (#rgb, #rrggbb, #rgba, or #rrggbbaa) to
521
+ * sRGB [r, g, b] in 0–1 range plus an optional alpha (0–1).
522
+ * Returns null if the string is not a valid hex color.
523
+ */
524
+ function parseHexAlpha(hex) {
400
525
  const h = hex.startsWith("#") ? hex.slice(1) : hex;
401
526
  if (h.length === 3) {
402
527
  const r = parseInt(h[0] + h[0], 16);
403
528
  const g = parseInt(h[1] + h[1], 16);
404
529
  const b = parseInt(h[2] + h[2], 16);
405
530
  if (isNaN(r) || isNaN(g) || isNaN(b)) return null;
406
- return [
531
+ return { rgb: [
407
532
  r / 255,
408
533
  g / 255,
409
534
  b / 255
410
- ];
535
+ ] };
536
+ }
537
+ if (h.length === 4) {
538
+ const r = parseInt(h[0] + h[0], 16);
539
+ const g = parseInt(h[1] + h[1], 16);
540
+ const b = parseInt(h[2] + h[2], 16);
541
+ const a = parseInt(h[3] + h[3], 16);
542
+ if (isNaN(r) || isNaN(g) || isNaN(b) || isNaN(a)) return null;
543
+ return {
544
+ rgb: [
545
+ r / 255,
546
+ g / 255,
547
+ b / 255
548
+ ],
549
+ alpha: a / 255
550
+ };
411
551
  }
412
552
  if (h.length === 6) {
413
553
  const r = parseInt(h.slice(0, 2), 16);
414
554
  const g = parseInt(h.slice(2, 4), 16);
415
555
  const b = parseInt(h.slice(4, 6), 16);
416
556
  if (isNaN(r) || isNaN(g) || isNaN(b)) return null;
417
- return [
557
+ return { rgb: [
418
558
  r / 255,
419
559
  g / 255,
420
560
  b / 255
421
- ];
561
+ ] };
562
+ }
563
+ if (h.length === 8) {
564
+ const r = parseInt(h.slice(0, 2), 16);
565
+ const g = parseInt(h.slice(2, 4), 16);
566
+ const b = parseInt(h.slice(4, 6), 16);
567
+ const a = parseInt(h.slice(6, 8), 16);
568
+ if (isNaN(r) || isNaN(g) || isNaN(b) || isNaN(a)) return null;
569
+ return {
570
+ rgb: [
571
+ r / 255,
572
+ g / 255,
573
+ b / 255
574
+ ],
575
+ alpha: a / 255
576
+ };
422
577
  }
423
578
  return null;
424
579
  }
@@ -429,24 +584,44 @@ function fmt$1(value, decimals) {
429
584
  * Format OKHSL values as a CSS `okhsl(H S% L%)` string.
430
585
  * h: 0–360, s: 0–100, l: 0–100 (percentage scale for s and l).
431
586
  */
432
- function formatOkhsl(h, s, l) {
433
- return `okhsl(${fmt$1(h, 2)} ${fmt$1(s, 2)}% ${fmt$1(l, 2)}%)`;
587
+ function formatOkhsl(h, s, l, pastel = false) {
588
+ let outS = s;
589
+ if (pastel) outS = oklabToOkhsl(okhslToOklab(h, s / 100, l / 100, true), false)[1] * 100;
590
+ return `okhsl(${fmt$1(h, 2)} ${fmt$1(outS, 2)}% ${fmt$1(l, 2)}%)`;
591
+ }
592
+ /**
593
+ * Format OKHST values as a CSS `okhst(H S% T%)` string.
594
+ * h: 0–360, s: 0–100, t: 0–100 (percentage scale for s and t).
595
+ *
596
+ * Pastel recompute matches `formatOkhsl`: convert via OKLab so external
597
+ * parsers that only understand non-pastel OKHST render identically.
598
+ */
599
+ function formatOkhst(h, s, t, pastel = false) {
600
+ let outS = s;
601
+ if (pastel) {
602
+ const REF_EPS = .05;
603
+ const den = Math.log(1 + REF_EPS) - Math.log(REF_EPS);
604
+ const y = Math.exp(t / 100 * den + Math.log(REF_EPS)) - REF_EPS;
605
+ const l = toe(Math.cbrt(Math.max(0, y)));
606
+ outS = oklabToOkhsl(okhslToOklab(h, s / 100, l, true), false)[1] * 100;
607
+ }
608
+ return `okhst(${fmt$1(h, 2)} ${fmt$1(outS, 2)}% ${fmt$1(t, 2)}%)`;
434
609
  }
435
610
  /**
436
611
  * Format OKHSL values as a CSS `rgb(R G B)` string.
437
612
  * Uses 2 decimal places to avoid 8-bit quantization contrast loss.
438
613
  * h: 0–360, s: 0–100, l: 0–100 (percentage scale for s and l).
439
614
  */
440
- function formatRgb(h, s, l) {
441
- const [r, g, b] = okhslToSrgb(h, s / 100, l / 100);
615
+ function formatRgb(h, s, l, pastel = false) {
616
+ const [r, g, b] = okhslToSrgb(h, s / 100, l / 100, pastel);
442
617
  return `rgb(${parseFloat((r * 255).toFixed(2))} ${parseFloat((g * 255).toFixed(2))} ${parseFloat((b * 255).toFixed(2))})`;
443
618
  }
444
619
  /**
445
620
  * Format OKHSL values as a CSS `hsl(H S% L%)` string.
446
621
  * h: 0–360, s: 0–100, l: 0–100 (percentage scale for s and l).
447
622
  */
448
- function formatHsl(h, s, l) {
449
- const [r, g, b] = okhslToSrgb(h, s / 100, l / 100);
623
+ function formatHsl(h, s, l, pastel = false) {
624
+ const [r, g, b] = okhslToSrgb(h, s / 100, l / 100, pastel);
450
625
  const max = Math.max(r, g, b);
451
626
  const min = Math.min(r, g, b);
452
627
  const delta = max - min;
@@ -465,410 +640,933 @@ function formatHsl(h, s, l) {
465
640
  * Format OKHSL values as a CSS `oklch(L C H)` string.
466
641
  * h: 0–360, s: 0–100, l: 0–100 (percentage scale for s and l).
467
642
  */
468
- function formatOklch(h, s, l) {
469
- const [L, a, b] = okhslToOklab(h, s / 100, l / 100);
470
- const C = Math.sqrt(a * a + b * b);
471
- let hh = Math.atan2(b, a) * (180 / Math.PI);
472
- hh = constrainAngle(hh);
643
+ function formatOklch(h, s, l, pastel = false) {
644
+ const [L, C, hh] = okhslToOklch(h, s / 100, l / 100, pastel);
473
645
  return `oklch(${fmt$1(L, 4)} ${fmt$1(C, 4)} ${fmt$1(hh, 2)})`;
474
646
  }
475
-
476
- //#endregion
477
- //#region src/contrast-solver.ts
478
647
  /**
479
- * OKHSL Contrast Solver
480
- *
481
- * Finds the closest OKHSL lightness that satisfies a WCAG 2 contrast target
482
- * against a base color. Used by glaze when resolving dependent colors
483
- * with `contrast`.
648
+ * Convert gamma-encoded sRGB channels (0–1) to a 6-digit lowercase hex
649
+ * string (`#rrggbb`). Channels are clamped to [0,1] and rounded to 8-bit.
650
+ * Alpha is not encoded here DTCG carries it as a separate `alpha` field.
484
651
  */
485
- const CONTRAST_PRESETS = {
486
- AA: 4.5,
487
- AAA: 7,
488
- "AA-large": 3,
489
- "AAA-large": 4.5
490
- };
491
- function resolveMinContrast(value) {
492
- if (typeof value === "number") return Math.max(1, value);
493
- return CONTRAST_PRESETS[value];
652
+ function srgbToHex(rgb) {
653
+ const toByte = (c) => Math.max(0, Math.min(255, Math.round(c * 255)));
654
+ const r = toByte(rgb[0]);
655
+ const g = toByte(rgb[1]);
656
+ const b = toByte(rgb[2]);
657
+ return `#${r.toString(16).padStart(2, "0")}${g.toString(16).padStart(2, "0")}${b.toString(16).padStart(2, "0")}`;
494
658
  }
495
- const CACHE_SIZE = 512;
496
- const luminanceCache = /* @__PURE__ */ new Map();
497
- const cacheOrder = [];
498
- function cachedLuminance(h, s, l) {
499
- const lRounded = Math.round(l * 1e4) / 1e4;
500
- const key = `${h}|${s}|${lRounded}`;
501
- const cached = luminanceCache.get(key);
502
- if (cached !== void 0) return cached;
503
- const y = gamutClampedLuminance(okhslToLinearSrgb(h, s, lRounded));
504
- if (luminanceCache.size >= CACHE_SIZE) {
505
- const evict = cacheOrder.shift();
506
- luminanceCache.delete(evict);
507
- }
508
- luminanceCache.set(key, y);
509
- cacheOrder.push(key);
510
- return y;
659
+ /**
660
+ * Convert OKHSL (h: 0–360, s: 0–1, l: 0–1) to OKLCH components `[L, C, H]`.
661
+ * L: 0–1, C: 0–~0.4 (chroma), H: 0–360 (hue). Shared by `formatOklch` and
662
+ * the DTCG `oklch` colorSpace exporter so the two never drift apart.
663
+ */
664
+ function okhslToOklch(h, s, l, pastel = false) {
665
+ const [L, a, b] = okhslToOklab(h, s, l, pastel);
666
+ return [
667
+ L,
668
+ Math.sqrt(a * a + b * b),
669
+ constrainAngle(Math.atan2(b, a) * (180 / Math.PI))
670
+ ];
511
671
  }
672
+
673
+ //#endregion
674
+ //#region src/config.ts
512
675
  /**
513
- * Binary search one branch [lo, hi] for the nearest passing lightness to `preferred`.
676
+ * Build a fresh defaults object. Called from module init and from
677
+ * `resetConfig()` so the two paths can't drift.
514
678
  */
515
- function searchBranch(h, s, lo, hi, yBase, target, epsilon, maxIter, preferred) {
516
- const yLo = cachedLuminance(h, s, lo);
517
- const yHi = cachedLuminance(h, s, hi);
518
- const crLo = contrastRatioFromLuminance(yLo, yBase);
519
- const crHi = contrastRatioFromLuminance(yHi, yBase);
520
- if (crLo < target && crHi < target) {
521
- if (crLo >= crHi) return {
522
- lightness: lo,
523
- contrast: crLo,
524
- met: false
525
- };
526
- return {
527
- lightness: hi,
528
- contrast: crHi,
529
- met: false
530
- };
531
- }
532
- let low = lo;
533
- let high = hi;
534
- for (let i = 0; i < maxIter; i++) {
535
- if (high - low < epsilon) break;
536
- const mid = (low + high) / 2;
537
- if (contrastRatioFromLuminance(cachedLuminance(h, s, mid), yBase) >= target) if (mid < preferred) low = mid;
538
- else high = mid;
539
- else if (mid < preferred) high = mid;
540
- else low = mid;
541
- }
542
- const yLow = cachedLuminance(h, s, low);
543
- const yHigh = cachedLuminance(h, s, high);
544
- const crLow = contrastRatioFromLuminance(yLow, yBase);
545
- const crHigh = contrastRatioFromLuminance(yHigh, yBase);
546
- const lowPasses = crLow >= target;
547
- const highPasses = crHigh >= target;
548
- if (lowPasses && highPasses) {
549
- if (Math.abs(low - preferred) <= Math.abs(high - preferred)) return {
550
- lightness: low,
551
- contrast: crLow,
552
- met: true
553
- };
554
- return {
555
- lightness: high,
556
- contrast: crHigh,
557
- met: true
558
- };
559
- }
560
- if (lowPasses) return {
561
- lightness: low,
562
- contrast: crLow,
563
- met: true
564
- };
565
- if (highPasses) return {
566
- lightness: high,
567
- contrast: crHigh,
568
- met: true
569
- };
570
- return coarseScan(h, s, lo, hi, yBase, target, epsilon, maxIter);
571
- }
572
- /**
573
- * Fallback coarse scan when binary search is unstable near gamut edges.
574
- */
575
- function coarseScan(h, s, lo, hi, yBase, target, epsilon, maxIter) {
576
- const STEPS = 64;
577
- const step = (hi - lo) / STEPS;
578
- let bestL = lo;
579
- let bestCr = 0;
580
- let bestMet = false;
581
- for (let i = 0; i <= STEPS; i++) {
582
- const l = lo + step * i;
583
- const cr = contrastRatioFromLuminance(cachedLuminance(h, s, l), yBase);
584
- if (cr >= target && !bestMet) {
585
- bestL = l;
586
- bestCr = cr;
587
- bestMet = true;
588
- } else if (cr >= target && bestMet) {
589
- bestL = l;
590
- bestCr = cr;
591
- } else if (!bestMet && cr > bestCr) {
592
- bestL = l;
593
- bestCr = cr;
594
- }
595
- }
596
- if (bestMet && bestL > lo + step) {
597
- let rLo = bestL - step;
598
- let rHi = bestL;
599
- for (let i = 0; i < maxIter; i++) {
600
- if (rHi - rLo < epsilon) break;
601
- const mid = (rLo + rHi) / 2;
602
- const cr = contrastRatioFromLuminance(cachedLuminance(h, s, mid), yBase);
603
- if (cr >= target) {
604
- rHi = mid;
605
- bestL = mid;
606
- bestCr = cr;
607
- } else rLo = mid;
608
- }
609
- }
679
+ function defaultConfig() {
610
680
  return {
611
- lightness: bestL,
612
- contrast: bestCr,
613
- met: bestMet
681
+ lightTone: {
682
+ lo: 10,
683
+ hi: 100,
684
+ eps: .05
685
+ },
686
+ darkTone: {
687
+ lo: 15,
688
+ hi: 95,
689
+ eps: .05
690
+ },
691
+ darkDesaturation: .1,
692
+ states: {
693
+ dark: "@dark",
694
+ highContrast: "@high-contrast"
695
+ },
696
+ modes: {
697
+ dark: true,
698
+ highContrast: false
699
+ },
700
+ autoFlip: true,
701
+ pastel: false,
702
+ inferRole: true
614
703
  };
615
704
  }
705
+ let globalConfig = defaultConfig();
616
706
  /**
617
- * Find the OKHSL lightness that satisfies a WCAG 2 contrast target
618
- * against a base color, staying as close to `preferredLightness` as possible.
707
+ * Monotonic counter incremented on every `configure()` / `resetConfig()`
708
+ * call. Theme / palette caches read this to invalidate stale resolve
709
+ * results when the config changes between exports.
619
710
  */
620
- function findLightnessForContrast(options) {
621
- const { hue, saturation, preferredLightness, baseLinearRgb, contrast: contrastInput, lightnessRange = [0, 1], epsilon = 1e-4, maxIterations = 14 } = options;
622
- const target = resolveMinContrast(contrastInput);
623
- const searchTarget = target * 1.007;
624
- const yBase = gamutClampedLuminance(baseLinearRgb);
625
- const crPref = contrastRatioFromLuminance(cachedLuminance(hue, saturation, preferredLightness), yBase);
626
- if (crPref >= searchTarget) return {
627
- lightness: preferredLightness,
628
- contrast: crPref,
629
- met: true,
630
- branch: "preferred"
631
- };
632
- const [minL, maxL] = lightnessRange;
633
- const darkerResult = preferredLightness > minL ? searchBranch(hue, saturation, minL, preferredLightness, yBase, searchTarget, epsilon, maxIterations, preferredLightness) : null;
634
- const lighterResult = preferredLightness < maxL ? searchBranch(hue, saturation, preferredLightness, maxL, yBase, searchTarget, epsilon, maxIterations, preferredLightness) : null;
635
- if (darkerResult) darkerResult.met = darkerResult.contrast >= target;
636
- if (lighterResult) lighterResult.met = lighterResult.contrast >= target;
637
- const darkerPasses = darkerResult?.met ?? false;
638
- const lighterPasses = lighterResult?.met ?? false;
639
- if (darkerPasses && lighterPasses) {
640
- if (Math.abs(darkerResult.lightness - preferredLightness) <= Math.abs(lighterResult.lightness - preferredLightness)) return {
641
- ...darkerResult,
642
- branch: "darker"
643
- };
644
- return {
645
- ...lighterResult,
646
- branch: "lighter"
647
- };
648
- }
649
- if (darkerPasses) return {
650
- ...darkerResult,
651
- branch: "darker"
652
- };
653
- if (lighterPasses) return {
654
- ...lighterResult,
655
- branch: "lighter"
656
- };
657
- const candidates = [];
658
- if (darkerResult) candidates.push({
659
- ...darkerResult,
660
- branch: "darker"
661
- });
662
- if (lighterResult) candidates.push({
663
- ...lighterResult,
664
- branch: "lighter"
665
- });
666
- if (candidates.length === 0) return {
667
- lightness: preferredLightness,
668
- contrast: crPref,
669
- met: false,
670
- branch: "preferred"
671
- };
672
- candidates.sort((a, b) => b.contrast - a.contrast);
673
- return candidates[0];
711
+ let configVersion = 0;
712
+ /** Live reference to the current config. Mutated by `configure()` / `resetConfig()`. */
713
+ function getConfig() {
714
+ return globalConfig;
715
+ }
716
+ function getConfigVersion() {
717
+ return configVersion;
674
718
  }
675
719
  /**
676
- * Binary-search one branch [lo, hi] for the nearest passing mix value
677
- * to `preferred`.
720
+ * Public-facing snapshot used by `glaze.getConfig()`. Returns a shallow
721
+ * copy so callers can't mutate the live config.
678
722
  */
679
- function searchMixBranch(lo, hi, yBase, target, epsilon, maxIter, preferred, luminanceAt) {
680
- const crLo = contrastRatioFromLuminance(luminanceAt(lo), yBase);
681
- const crHi = contrastRatioFromLuminance(luminanceAt(hi), yBase);
682
- if (crLo < target && crHi < target) {
683
- if (crLo >= crHi) return {
684
- lightness: lo,
685
- contrast: crLo,
686
- met: false
687
- };
688
- return {
689
- lightness: hi,
690
- contrast: crHi,
691
- met: false
692
- };
693
- }
694
- let low = lo;
695
- let high = hi;
696
- for (let i = 0; i < maxIter; i++) {
697
- if (high - low < epsilon) break;
698
- const mid = (low + high) / 2;
699
- if (contrastRatioFromLuminance(luminanceAt(mid), yBase) >= target) if (mid < preferred) low = mid;
700
- else high = mid;
701
- else if (mid < preferred) high = mid;
702
- else low = mid;
703
- }
704
- const crLow = contrastRatioFromLuminance(luminanceAt(low), yBase);
705
- const crHigh = contrastRatioFromLuminance(luminanceAt(high), yBase);
706
- const lowPasses = crLow >= target;
707
- const highPasses = crHigh >= target;
708
- if (lowPasses && highPasses) {
709
- if (Math.abs(low - preferred) <= Math.abs(high - preferred)) return {
710
- lightness: low,
711
- contrast: crLow,
712
- met: true
713
- };
714
- return {
715
- lightness: high,
716
- contrast: crHigh,
717
- met: true
718
- };
719
- }
720
- if (lowPasses) return {
721
- lightness: low,
722
- contrast: crLow,
723
- met: true
724
- };
725
- if (highPasses) return {
726
- lightness: high,
727
- contrast: crHigh,
728
- met: true
729
- };
730
- return crLow >= crHigh ? {
731
- lightness: low,
732
- contrast: crLow,
733
- met: false
734
- } : {
735
- lightness: high,
736
- contrast: crHigh,
737
- met: false
723
+ function snapshotConfig() {
724
+ return { ...globalConfig };
725
+ }
726
+ function configure(config) {
727
+ configVersion++;
728
+ globalConfig = {
729
+ lightTone: config.lightTone ?? globalConfig.lightTone,
730
+ darkTone: config.darkTone ?? globalConfig.darkTone,
731
+ darkDesaturation: config.darkDesaturation ?? globalConfig.darkDesaturation,
732
+ states: {
733
+ dark: config.states?.dark ?? globalConfig.states.dark,
734
+ highContrast: config.states?.highContrast ?? globalConfig.states.highContrast
735
+ },
736
+ modes: {
737
+ dark: config.modes?.dark ?? globalConfig.modes.dark,
738
+ highContrast: config.modes?.highContrast ?? globalConfig.modes.highContrast
739
+ },
740
+ shadowTuning: config.shadowTuning ?? globalConfig.shadowTuning,
741
+ autoFlip: config.autoFlip ?? globalConfig.autoFlip,
742
+ pastel: config.pastel ?? globalConfig.pastel,
743
+ inferRole: config.inferRole ?? globalConfig.inferRole
738
744
  };
739
745
  }
746
+ function resetConfig() {
747
+ configVersion++;
748
+ globalConfig = defaultConfig();
749
+ }
740
750
  /**
741
- * Find the mix parameter (ratio or opacity) that satisfies a WCAG 2 contrast
742
- * target against a base color, staying as close to `preferredValue` as possible.
751
+ * Merge a per-instance config override over a base resolved config.
752
+ * Only fields present in `override` are replaced; others fall through
753
+ * from `base`. `false` for tone windows passes through as-is
754
+ * (treated as the full range by `activeWindow()` in okhst.ts).
743
755
  */
744
- function findValueForMixContrast(options) {
745
- const { preferredValue, baseLinearRgb, contrast: contrastInput, luminanceAtValue, epsilon = 1e-4, maxIterations = 20 } = options;
746
- const target = resolveMinContrast(contrastInput);
747
- const searchTarget = target * 1.01;
748
- const yBase = gamutClampedLuminance(baseLinearRgb);
749
- const crPref = contrastRatioFromLuminance(luminanceAtValue(preferredValue), yBase);
750
- if (crPref >= searchTarget) return {
751
- value: preferredValue,
752
- contrast: crPref,
753
- met: true
754
- };
755
- const darkerResult = preferredValue > 0 ? searchMixBranch(0, preferredValue, yBase, searchTarget, epsilon, maxIterations, preferredValue, luminanceAtValue) : null;
756
- const lighterResult = preferredValue < 1 ? searchMixBranch(preferredValue, 1, yBase, searchTarget, epsilon, maxIterations, preferredValue, luminanceAtValue) : null;
757
- if (darkerResult) darkerResult.met = darkerResult.contrast >= target;
758
- if (lighterResult) lighterResult.met = lighterResult.contrast >= target;
759
- const darkerPasses = darkerResult?.met ?? false;
760
- const lighterPasses = lighterResult?.met ?? false;
761
- if (darkerPasses && lighterPasses) {
762
- if (Math.abs(darkerResult.lightness - preferredValue) <= Math.abs(lighterResult.lightness - preferredValue)) return {
763
- value: darkerResult.lightness,
764
- contrast: darkerResult.contrast,
765
- met: true
766
- };
767
- return {
768
- value: lighterResult.lightness,
769
- contrast: lighterResult.contrast,
770
- met: true
771
- };
772
- }
773
- if (darkerPasses) return {
774
- value: darkerResult.lightness,
775
- contrast: darkerResult.contrast,
776
- met: true
777
- };
778
- if (lighterPasses) return {
779
- value: lighterResult.lightness,
780
- contrast: lighterResult.contrast,
781
- met: true
782
- };
783
- const candidates = [];
784
- if (darkerResult) candidates.push({
785
- ...darkerResult,
786
- branch: "lower"
787
- });
788
- if (lighterResult) candidates.push({
789
- ...lighterResult,
790
- branch: "upper"
791
- });
792
- if (candidates.length === 0) return {
793
- value: preferredValue,
794
- contrast: crPref,
795
- met: false
796
- };
797
- candidates.sort((a, b) => b.contrast - a.contrast);
756
+ function mergeConfig(base, override) {
757
+ if (!override) return base;
798
758
  return {
799
- value: candidates[0].lightness,
800
- contrast: candidates[0].contrast,
801
- met: candidates[0].met
759
+ lightTone: override.lightTone !== void 0 ? override.lightTone : base.lightTone,
760
+ darkTone: override.darkTone !== void 0 ? override.darkTone : base.darkTone,
761
+ darkDesaturation: override.darkDesaturation ?? base.darkDesaturation,
762
+ states: base.states,
763
+ modes: base.modes,
764
+ shadowTuning: override.shadowTuning ?? base.shadowTuning,
765
+ autoFlip: override.autoFlip ?? base.autoFlip,
766
+ pastel: override.pastel ?? base.pastel,
767
+ inferRole: override.inferRole ?? base.inferRole
802
768
  };
803
769
  }
804
770
 
805
771
  //#endregion
806
- //#region src/glaze.ts
772
+ //#region src/format-guard.ts
773
+ const NON_NATIVE_FORMATS = new Set(["okhsl", "okhst"]);
807
774
  /**
808
- * Glaze OKHSL-based color theme generator.
809
- *
810
- * Generates robust light, dark, and high-contrast colors from a hue/saturation
811
- * seed, preserving contrast for UI pairs via explicit dependencies.
812
- */
813
- let globalConfig = {
814
- lightLightness: [10, 100],
815
- darkLightness: [15, 95],
816
- darkDesaturation: .1,
817
- darkCurve: .5,
818
- states: {
819
- dark: "@dark",
820
- highContrast: "@high-contrast"
775
+ * Throw when a non-native Glaze color space is requested for an export that
776
+ * emits raw CSS or non-Tasty token maps.
777
+ */
778
+ function assertNativeFormat(format, method) {
779
+ if (format !== void 0 && NON_NATIVE_FORMATS.has(format)) throw new Error(`glaze: ${format} output is only supported by tasty() (not a native CSS color space). Use tasty({ format: '${format}' }) or pick a native format (oklch|hsl|rgb) for ${method}().`);
780
+ }
781
+ const SCHEME_FIELDS = [
782
+ {
783
+ field: "light",
784
+ modes: () => true
785
+ },
786
+ {
787
+ field: "dark",
788
+ modes: (m) => m.dark
821
789
  },
822
- modes: {
823
- dark: true,
824
- highContrast: false
790
+ {
791
+ field: "lightContrast",
792
+ modes: (m) => m.highContrast
793
+ },
794
+ {
795
+ field: "darkContrast",
796
+ modes: (m) => m.dark && m.highContrast
825
797
  }
826
- };
798
+ ];
799
+ /**
800
+ * Throw when `splitHue` is enabled but any exported color is not pastel.
801
+ * Hue rotation is only clip-free when chroma is bounded by the hue-independent
802
+ * safe chroma (`computeSafeChromaOKLCH`).
803
+ */
804
+ function assertAllPastel(resolved, modes) {
805
+ const nonPastel = [];
806
+ for (const [name, color] of resolved) for (const { field, modes: active } of SCHEME_FIELDS) {
807
+ if (!active(modes)) continue;
808
+ if (color[field].pastel !== true) {
809
+ if (!nonPastel.includes(name)) nonPastel.push(name);
810
+ break;
811
+ }
812
+ }
813
+ if (nonPastel.length === 0) return;
814
+ throw new Error(`glaze: splitHue requires every color to be pastel (hue rotation is only clip-free when chroma is bounded by the hue-independent safe chroma). Non-pastel: ${nonPastel.join(", ")}. Set pastel: true (global or per-color) or drop splitHue.`);
815
+ }
816
+
817
+ //#endregion
818
+ //#region src/hc-pair.ts
827
819
  function pairNormal(p) {
828
820
  return Array.isArray(p) ? p[0] : p;
829
821
  }
830
822
  function pairHC(p) {
831
823
  return Array.isArray(p) ? p[1] : p;
832
824
  }
833
- function isShadowDef(def) {
834
- return def.type === "shadow";
825
+ function clamp(v, min, max) {
826
+ return Math.max(min, Math.min(max, v));
835
827
  }
836
- function isMixDef(def) {
837
- return def.type === "mix";
828
+ /** Whether a tone value is an extreme keyword (`'max'` / `'min'`). */
829
+ function isExtremeTone(value) {
830
+ return value === "max" || value === "min";
838
831
  }
839
- const DEFAULT_SHADOW_TUNING = {
840
- saturationFactor: .18,
841
- maxSaturation: .25,
842
- lightnessFactor: .25,
843
- lightnessBounds: [.05, .2],
844
- minGapTarget: .05,
845
- alphaMax: 1,
846
- bgHueBlend: .2
847
- };
848
- function resolveShadowTuning(perColor) {
832
+ /**
833
+ * Parse a value that can be absolute (number) or relative (signed string).
834
+ * Returns the numeric value and whether it's relative.
835
+ */
836
+ function parseRelativeOrAbsolute(value) {
837
+ if (typeof value === "number") return {
838
+ value,
839
+ relative: false
840
+ };
849
841
  return {
850
- ...DEFAULT_SHADOW_TUNING,
851
- ...globalConfig.shadowTuning,
852
- ...perColor,
853
- lightnessBounds: perColor?.lightnessBounds ?? globalConfig.shadowTuning?.lightnessBounds ?? DEFAULT_SHADOW_TUNING.lightnessBounds
842
+ value: parseFloat(value),
843
+ relative: true
854
844
  };
855
845
  }
856
- function circularLerp(a, b, t) {
857
- let diff = b - a;
858
- if (diff > 180) diff -= 360;
859
- else if (diff < -180) diff += 360;
860
- return ((a + diff * t) % 360 + 360) % 360;
861
- }
862
846
  /**
863
- * Compute the canonical max-contrast reference t value for normalization.
864
- * Uses bg.l=1, fg.l=0, intensity=100 the theoretical maximum.
865
- * This is a fixed constant per tuning configuration, ensuring uniform
866
- * scaling across all bg/fg pairs at low intensities.
847
+ * Parse a tone value into a normalized shape.
848
+ * - `'max'` / `'min'` → `{ kind: 'extreme', value: 100 | 0 }` (an absolute
849
+ * author tone before scheme mapping `'max'` is 100, `'min'` is 0).
850
+ * - `'+N'` / `'-N'` `{ kind: 'relative', value: ±N }`.
851
+ * - number → `{ kind: 'absolute', value }`.
867
852
  */
868
- function computeRefT(tuning) {
869
- const EPSILON = 1e-6;
870
- let lShRef = clamp(tuning.lightnessFactor, tuning.lightnessBounds[0], tuning.lightnessBounds[1]);
871
- lShRef = Math.max(Math.min(lShRef, 1 - tuning.minGapTarget), 0);
853
+ function parseToneValue(value) {
854
+ if (value === "max") return {
855
+ kind: "extreme",
856
+ value: 100
857
+ };
858
+ if (value === "min") return {
859
+ kind: "extreme",
860
+ value: 0
861
+ };
862
+ if (typeof value === "number") return {
863
+ kind: "absolute",
864
+ value
865
+ };
866
+ return {
867
+ kind: "relative",
868
+ value: parseFloat(value)
869
+ };
870
+ }
871
+ /**
872
+ * Compute the effective hue for a color, given the theme seed hue
873
+ * and an optional per-color hue override.
874
+ */
875
+ function resolveEffectiveHue(seedHue, defHue) {
876
+ if (defHue === void 0) return seedHue;
877
+ const parsed = parseRelativeOrAbsolute(defHue);
878
+ if (parsed.relative) return ((seedHue + parsed.value) % 360 + 360) % 360;
879
+ return (parsed.value % 360 + 360) % 360;
880
+ }
881
+ /**
882
+ * Check whether a tone value represents an absolute root definition
883
+ * (i.e. a number, not a relative string). Extreme keywords (`'max'` /
884
+ * `'min'`) also count — they need no base.
885
+ */
886
+ function isAbsoluteTone(tone) {
887
+ if (tone === void 0) return false;
888
+ const normal = Array.isArray(tone) ? tone[0] : tone;
889
+ return typeof normal === "number" || isExtremeTone(normal);
890
+ }
891
+
892
+ //#endregion
893
+ //#region src/okhst.ts
894
+ /**
895
+ * OKHST — the contrast-uniform tone space.
896
+ *
897
+ * OKHST is OKHSL with its lightness axis replaced by a contrast-uniform
898
+ * "tone" axis. It shares `h` / `s` with OKHSL verbatim and swaps `l` for
899
+ * `t`. This module owns:
900
+ *
901
+ * - the closed-form tone transfers (`toTone` / `fromTone`) at a fixed
902
+ * reference eps, plus the gray luminance helpers (`lToY` / `yToL`),
903
+ * - the `{ h, s, t }` <-> `{ h, s, l }` color-space converters,
904
+ * - the resolved-variant edge adapter (`variantToOkhsl`),
905
+ * - the per-scheme tone mapping that replaced the Möbius dark curve
906
+ * (`mapToneForScheme`), the dark desaturation reducer, and the solver's scheme
907
+ * tone range.
908
+ *
909
+ * See `docs/okhst.md` for the full specification and the calibrated
910
+ * default constants.
911
+ */
912
+ /**
913
+ * Reference eps for the OKHST color space. WCAG 2 contrast is
914
+ * `(Y_hi + 0.05) / (Y_lo + 0.05)`, so an eps of `0.05` makes equal tone
915
+ * steps yield equal WCAG contrast. This is the canonical eps used by
916
+ * `okhst()` input, `{ h, s, t }` input, stored `ResolvedColorVariant.t`,
917
+ * relative `tone` offsets, and the contrast solver.
918
+ */
919
+ const REF_EPS = .05;
920
+ /**
921
+ * Gray luminance from OKHSL lightness. For an achromatic color the OKLab
922
+ * lightness is `toeInv(l)` and luminance is its cube.
923
+ */
924
+ function lToY(l) {
925
+ const L = toeInv(l);
926
+ return L * L * L;
927
+ }
928
+ /** OKHSL lightness from gray luminance — exact inverse of {@link lToY}. */
929
+ function yToL(y) {
930
+ return toe(Math.cbrt(Math.max(0, y)));
931
+ }
932
+ /**
933
+ * Map a luminance `Y` (0–1) to tone (0–100) at the given eps.
934
+ * `toneFromY(0) === 0` and `toneFromY(1) === 100` for any eps.
935
+ */
936
+ function toneFromY(y, eps = REF_EPS) {
937
+ return (Math.log(y + eps) - Math.log(eps)) / (Math.log(1 + eps) - Math.log(eps)) * 100;
938
+ }
939
+ /** Map a tone (0–100) back to luminance (0–1). Inverse of {@link toneFromY}. */
940
+ function yFromTone(t, eps = REF_EPS) {
941
+ const den = Math.log(1 + eps) - Math.log(eps);
942
+ return Math.exp(t / 100 * den + Math.log(eps)) - eps;
943
+ }
944
+ /** OKHSL lightness (0–1) -> tone (0–100). */
945
+ function toTone(l, eps = REF_EPS) {
946
+ return toneFromY(lToY(l), eps);
947
+ }
948
+ /** Tone (0–100) -> OKHSL lightness (0–1). Inverse of {@link toTone}. */
949
+ function fromTone(t, eps = REF_EPS) {
950
+ return yToL(yFromTone(t, eps));
951
+ }
952
+ /** Convert OKHST `{ h, s, t }` (t in 0–1) to OKHSL `{ h, s, l }`. */
953
+ function okhstToOkhsl(c) {
954
+ return {
955
+ h: c.h,
956
+ s: c.s,
957
+ l: clamp(fromTone(c.t * 100), 0, 1)
958
+ };
959
+ }
960
+ /** Convert OKHSL `{ h, s, l }` to OKHST `{ h, s, t }` (t in 0–1). */
961
+ function okhslToOkhst(c) {
962
+ return {
963
+ h: c.h,
964
+ s: c.s,
965
+ t: clamp(toTone(c.l) / 100, 0, 1)
966
+ };
967
+ }
968
+ /**
969
+ * Edge adapter: a resolved variant stores canonical tone `t` (0–1). Convert
970
+ * it to the OKHSL `{ h, s, l }` the formatters and luminance pipeline expect.
971
+ */
972
+ function variantToOkhsl(v) {
973
+ return {
974
+ h: v.h,
975
+ s: v.s,
976
+ l: clamp(fromTone(v.t * 100), 0, 1)
977
+ };
978
+ }
979
+ /**
980
+ * Normalize any {@link ToneWindow} form to `{ lo, hi, eps }`.
981
+ * - `false`: full range `[0, 100]` at the reference eps (boundaries removed,
982
+ * curve preserved).
983
+ * - `[lo, hi]`: endpoints at the reference eps (the common form).
984
+ * - `{ lo, hi, eps }`: passed through (advanced eps tuning).
985
+ */
986
+ function normalizeToneWindow(win) {
987
+ if (win === false) return {
988
+ lo: 0,
989
+ hi: 100,
990
+ eps: REF_EPS
991
+ };
992
+ if (Array.isArray(win)) return {
993
+ lo: win[0],
994
+ hi: win[1],
995
+ eps: REF_EPS
996
+ };
997
+ return {
998
+ lo: win.lo,
999
+ hi: win.hi,
1000
+ eps: win.eps
1001
+ };
1002
+ }
1003
+ /**
1004
+ * Resolve the active tone window for a scheme as OKHSL-lightness endpoints.
1005
+ * - HC variants always return the full range `[0, 100]` with the mode eps.
1006
+ * - `false` (= "no clamping") is treated as `[0, 100]` with the reference eps.
1007
+ */
1008
+ function activeWindow(isHighContrast, kind, config) {
1009
+ const win = normalizeToneWindow(kind === "dark" ? config.darkTone : config.lightTone);
1010
+ if (isHighContrast) return {
1011
+ lo: 0,
1012
+ hi: 100,
1013
+ eps: win.eps
1014
+ };
1015
+ return win;
1016
+ }
1017
+ /**
1018
+ * Remap an authored tone (0–100) into a scheme window and return the final
1019
+ * OKHSL lightness (0–100). The window endpoints are OKHSL lightnesses; the
1020
+ * author tone is positioned within the window's tone interval (using the
1021
+ * window's render eps), then converted back to lightness.
1022
+ */
1023
+ function remapToneToLightness(authorTone, win) {
1024
+ const loT = toTone(win.lo / 100, win.eps);
1025
+ const hiT = toTone(win.hi / 100, win.eps);
1026
+ return clamp(fromTone(loT + authorTone / 100 * (hiT - loT), win.eps) * 100, 0, 100);
1027
+ }
1028
+ /**
1029
+ * Map an authored tone for a scheme and return the canonical stored tone
1030
+ * (0–100, reference eps).
1031
+ *
1032
+ * - `static`: identity — the same tone renders in every scheme.
1033
+ * - `auto` + dark: invert (`100 - tone`) then remap into the dark window.
1034
+ * - `auto`/`fixed` + light, or `fixed` + dark: remap, no inversion.
1035
+ *
1036
+ * The window remap uses the mode's render eps to land a final OKHSL
1037
+ * lightness; that lightness is then re-expressed as canonical tone so
1038
+ * relative offsets and contrast stay comparable across schemes.
1039
+ */
1040
+ function mapToneForScheme(authorTone, mode, isDark, isHighContrast, config) {
1041
+ if (mode === "static") return clamp(authorTone, 0, 100);
1042
+ const win = activeWindow(isHighContrast, isDark ? "dark" : "light", config);
1043
+ return clamp(toTone(remapToneToLightness(clamp(isDark && mode === "auto" ? 100 - authorTone : authorTone, 0, 100), win) / 100), 0, 100);
1044
+ }
1045
+ /** Dark-scheme desaturation reducer (unchanged from the legacy pipeline). */
1046
+ function mapSaturationDark(s, mode, config) {
1047
+ if (mode === "static") return s;
1048
+ return s * (1 - config.darkDesaturation);
1049
+ }
1050
+ /**
1051
+ * Tone search range (0–1) for the contrast solver in a given scheme.
1052
+ * `static` searches the full range; otherwise the scheme window's tone
1053
+ * endpoints (HC bypasses to full range).
1054
+ */
1055
+ function schemeToneRange(isDark, mode, isHighContrast, config) {
1056
+ if (mode === "static") return [0, 1];
1057
+ const win = activeWindow(isHighContrast, isDark ? "dark" : "light", config);
1058
+ return [clamp(toTone(win.lo / 100) / 100, 0, 1), clamp(toTone(win.hi / 100) / 100, 0, 1)];
1059
+ }
1060
+
1061
+ //#endregion
1062
+ //#region src/contrast-solver.ts
1063
+ /**
1064
+ * Contrast solver — operates in OKHST tone.
1065
+ *
1066
+ * Finds the tone closest to a preferred tone that satisfies a contrast
1067
+ * floor (WCAG 2 ratio or APCA Lc) against a base color. Because tone is
1068
+ * contrast-uniform, the WCAG branch gets a closed-form seed and the search
1069
+ * converges quickly.
1070
+ *
1071
+ * Public API: `findToneForContrast`, `findValueForMixContrast`,
1072
+ * `resolveMinContrast`, `resolveContrastForMode`, `apcaContrast`.
1073
+ */
1074
+ /**
1075
+ * Luminance of a linear-sRGB color in the basis the metric expects: WCAG
1076
+ * relative luminance for `wcag`, APCA screen luminance (`Ys`) for `apca`.
1077
+ */
1078
+ function metricLuminance(metric, linearRgb) {
1079
+ return metric === "apca" ? apcaLuminanceFromLinearRgb(linearRgb) : gamutClampedLuminance(linearRgb);
1080
+ }
1081
+ const APCA_PRESETS = {
1082
+ preferred: 90,
1083
+ body: 75,
1084
+ content: 60,
1085
+ large: 45,
1086
+ "non-text": 30,
1087
+ min: 15
1088
+ };
1089
+ /**
1090
+ * Resolve an APCA target — a raw Lc number (kept as-is) or an `ApcaPreset`
1091
+ * keyword mapped to its Lc value. The magnitude is forced non-negative.
1092
+ */
1093
+ function resolveApcaTarget(value) {
1094
+ if (typeof value === "number") return Math.abs(value);
1095
+ return APCA_PRESETS[value];
1096
+ }
1097
+ const CONTRAST_PRESETS = {
1098
+ AA: 4.5,
1099
+ AAA: 7,
1100
+ "AA-large": 3,
1101
+ "AAA-large": 4.5
1102
+ };
1103
+ function resolveMinContrast(value) {
1104
+ if (typeof value === "number") return Math.max(1, value);
1105
+ return CONTRAST_PRESETS[value];
1106
+ }
1107
+ function pickPair(p, isHighContrast) {
1108
+ return Array.isArray(p) ? isHighContrast ? p[1] : p[0] : p;
1109
+ }
1110
+ /**
1111
+ * Resolve a `ContrastSpec` (already selected from any outer HC pair) for a
1112
+ * given mode into `{ metric, target }`. Handles the inner metric HC pair and
1113
+ * preset resolution. `polarity` is passed through to the result for the APCA
1114
+ * branch (it controls argument order in the solver); WCAG ignores it.
1115
+ */
1116
+ function resolveContrastForMode(spec, isHighContrast, polarity) {
1117
+ if (typeof spec === "number" || typeof spec === "string") return {
1118
+ metric: "wcag",
1119
+ target: resolveMinContrast(spec)
1120
+ };
1121
+ if ("apca" in spec) return {
1122
+ metric: "apca",
1123
+ target: resolveApcaTarget(pickPair(spec.apca, isHighContrast)),
1124
+ polarity: polarity ?? "fg"
1125
+ };
1126
+ return {
1127
+ metric: "wcag",
1128
+ target: resolveMinContrast(pickPair(spec.wcag, isHighContrast))
1129
+ };
1130
+ }
1131
+ const APCA_EXPONENTS = {
1132
+ mainTRC: 2.4,
1133
+ normBG: .56,
1134
+ normTXT: .57,
1135
+ revTXT: .62,
1136
+ revBG: .65
1137
+ };
1138
+ const APCA_BLACK_THRESH = .022;
1139
+ const APCA_BLACK_CLIP = 1.414;
1140
+ const APCA_DELTA_Y_MIN = 5e-4;
1141
+ const APCA_SCALE = 1.14;
1142
+ const APCA_LO_OFFSET = .027;
1143
+ function apcaSoftClamp(y) {
1144
+ const yc = Math.max(0, y);
1145
+ if (yc >= APCA_BLACK_THRESH) return yc;
1146
+ return yc + Math.pow(APCA_BLACK_THRESH - yc, APCA_BLACK_CLIP);
1147
+ }
1148
+ /**
1149
+ * APCA lightness contrast (Lc), signed: positive for dark text on light bg,
1150
+ * negative for light text on dark bg. Inputs are screen luminances (0–1).
1151
+ */
1152
+ function apcaContrast(yText, yBg) {
1153
+ const txt = apcaSoftClamp(yText);
1154
+ const bg = apcaSoftClamp(yBg);
1155
+ if (Math.abs(bg - txt) < APCA_DELTA_Y_MIN) return 0;
1156
+ let sapc;
1157
+ if (bg > txt) {
1158
+ sapc = (Math.pow(bg, APCA_EXPONENTS.normBG) - Math.pow(txt, APCA_EXPONENTS.normTXT)) * APCA_SCALE;
1159
+ return sapc < .1 ? 0 : (sapc - APCA_LO_OFFSET) * 100;
1160
+ }
1161
+ sapc = (Math.pow(bg, APCA_EXPONENTS.revBG) - Math.pow(txt, APCA_EXPONENTS.revTXT)) * APCA_SCALE;
1162
+ return sapc > -.1 ? 0 : (sapc + APCA_LO_OFFSET) * 100;
1163
+ }
1164
+ const CACHE_SIZE = 512;
1165
+ const luminanceCache = /* @__PURE__ */ new Map();
1166
+ const cacheOrder = [];
1167
+ /**
1168
+ * Luminance of an OKHST color `(h, s, t)` with t in 0–1 (reference eps), in
1169
+ * the metric's luminance basis. The metric is part of the cache key because
1170
+ * WCAG and APCA derive different luminances from the same color.
1171
+ */
1172
+ function cachedLuminance(metric, h, s, t, pastel) {
1173
+ const tRounded = Math.round(t * 1e4) / 1e4;
1174
+ const key = `${metric}|${h}|${s}|${tRounded}|${pastel}`;
1175
+ const cached = luminanceCache.get(key);
1176
+ if (cached !== void 0) return cached;
1177
+ const y = metricLuminance(metric, okhslToLinearSrgb(h, s, fromTone(tRounded * 100, REF_EPS), pastel));
1178
+ if (luminanceCache.size >= CACHE_SIZE) {
1179
+ const evict = cacheOrder.shift();
1180
+ luminanceCache.delete(evict);
1181
+ }
1182
+ luminanceCache.set(key, y);
1183
+ cacheOrder.push(key);
1184
+ return y;
1185
+ }
1186
+ /**
1187
+ * Score a candidate luminance against the base for a metric. Returns a value
1188
+ * that is `>= target` exactly when the floor is met (WCAG ratio, or APCA Lc
1189
+ * magnitude). For APCA, `polarity` selects the argument order: `'fg'` (the
1190
+ * default) treats the candidate as the text against a background base
1191
+ * (`apcaContrast(yCandidate, yBase)`); `'bg'` treats the candidate as the
1192
+ * background (`apcaContrast(yBase, yCandidate)`). The magnitude is taken
1193
+ * either way. WCAG is symmetric, so polarity is ignored there.
1194
+ */
1195
+ function metricScore(metric, yCandidate, yBase, polarity) {
1196
+ if (metric === "wcag") return contrastRatioFromLuminance(yCandidate, yBase);
1197
+ const lc = polarity === "bg" ? apcaContrast(yBase, yCandidate) : apcaContrast(yCandidate, yBase);
1198
+ return Math.abs(lc);
1199
+ }
1200
+ /**
1201
+ * Binary search one branch `[lo, hi]` for the position nearest to `anchor`
1202
+ * that meets `target`. The domain is whatever `lum` interprets (tone 0–1 or
1203
+ * mix parameter 0–1); the search is identical in both cases.
1204
+ */
1205
+ function searchBranch(lum, lo, hi, yBase, metric, target, epsilon, maxIter, anchor, polarity) {
1206
+ const scoreLo = metricScore(metric, lum(lo), yBase, polarity);
1207
+ const scoreHi = metricScore(metric, lum(hi), yBase, polarity);
1208
+ if (scoreLo < target && scoreHi < target) return scoreLo >= scoreHi ? {
1209
+ pos: lo,
1210
+ contrast: scoreLo,
1211
+ met: false
1212
+ } : {
1213
+ pos: hi,
1214
+ contrast: scoreHi,
1215
+ met: false
1216
+ };
1217
+ let low = lo;
1218
+ let high = hi;
1219
+ for (let i = 0; i < maxIter; i++) {
1220
+ if (high - low < epsilon) break;
1221
+ const mid = (low + high) / 2;
1222
+ if (metricScore(metric, lum(mid), yBase, polarity) >= target) if (mid < anchor) low = mid;
1223
+ else high = mid;
1224
+ else if (mid < anchor) high = mid;
1225
+ else low = mid;
1226
+ }
1227
+ const scoreLow = metricScore(metric, lum(low), yBase, polarity);
1228
+ const scoreHigh = metricScore(metric, lum(high), yBase, polarity);
1229
+ const lowPasses = scoreLow >= target;
1230
+ const highPasses = scoreHigh >= target;
1231
+ if (lowPasses && highPasses) return Math.abs(low - anchor) <= Math.abs(high - anchor) ? {
1232
+ pos: low,
1233
+ contrast: scoreLow,
1234
+ met: true
1235
+ } : {
1236
+ pos: high,
1237
+ contrast: scoreHigh,
1238
+ met: true
1239
+ };
1240
+ if (lowPasses) return {
1241
+ pos: low,
1242
+ contrast: scoreLow,
1243
+ met: true
1244
+ };
1245
+ if (highPasses) return {
1246
+ pos: high,
1247
+ contrast: scoreHigh,
1248
+ met: true
1249
+ };
1250
+ return scoreLow >= scoreHigh ? {
1251
+ pos: low,
1252
+ contrast: scoreLow,
1253
+ met: false
1254
+ } : {
1255
+ pos: high,
1256
+ contrast: scoreHigh,
1257
+ met: false
1258
+ };
1259
+ }
1260
+ /**
1261
+ * Closed-form WCAG tone seed: the gray tone whose luminance produces exactly
1262
+ * the target ratio against the base, on the requested side. Used to bias the
1263
+ * preferred tone before the search so chromatic refinement starts close.
1264
+ */
1265
+ function wcagToneSeed(yBase, target, darker) {
1266
+ const yTarget = darker ? (yBase + .05) / target - .05 : target * (yBase + .05) - .05;
1267
+ const yClamped = Math.max(0, Math.min(1, yTarget));
1268
+ return Math.max(0, Math.min(1, toneFromY(yClamped, REF_EPS) / 100));
1269
+ }
1270
+ function solveNearestContrast(opts) {
1271
+ const { lum, yBase, metric, target, searchTarget, lo, hi, searchAnchor, distanceAnchor, epsilon, maxIterations, flip, initialIsLower, polarity } = opts;
1272
+ const runBranch = (lower) => lower ? searchBranch(lum, lo, searchAnchor, yBase, metric, searchTarget, epsilon, maxIterations, searchAnchor, polarity) : searchBranch(lum, searchAnchor, hi, yBase, metric, searchTarget, epsilon, maxIterations, searchAnchor, polarity);
1273
+ const initialResult = runBranch(initialIsLower);
1274
+ initialResult.met = initialResult.contrast >= target;
1275
+ if (initialResult.met && !flip) return {
1276
+ ...initialResult,
1277
+ lower: initialIsLower
1278
+ };
1279
+ if (flip) {
1280
+ const oppositeResult = (initialIsLower ? distanceAnchor < hi : distanceAnchor > lo) ? runBranch(!initialIsLower) : null;
1281
+ if (oppositeResult) oppositeResult.met = oppositeResult.contrast >= target;
1282
+ if (initialResult.met && oppositeResult?.met) return Math.abs(initialResult.pos - distanceAnchor) <= Math.abs(oppositeResult.pos - distanceAnchor) ? {
1283
+ ...initialResult,
1284
+ lower: initialIsLower
1285
+ } : {
1286
+ ...oppositeResult,
1287
+ lower: !initialIsLower,
1288
+ flipped: true
1289
+ };
1290
+ if (initialResult.met) return {
1291
+ ...initialResult,
1292
+ lower: initialIsLower
1293
+ };
1294
+ if (oppositeResult?.met) return {
1295
+ ...oppositeResult,
1296
+ lower: !initialIsLower,
1297
+ flipped: true
1298
+ };
1299
+ }
1300
+ const extreme = initialIsLower ? lo : hi;
1301
+ return {
1302
+ pos: extreme,
1303
+ contrast: metricScore(metric, lum(extreme), yBase, polarity),
1304
+ met: false,
1305
+ lower: initialIsLower
1306
+ };
1307
+ }
1308
+ /**
1309
+ * Find the tone that satisfies a contrast floor against a base color,
1310
+ * staying as close to `preferredTone` as possible.
1311
+ */
1312
+ function findToneForContrast(options) {
1313
+ const { hue, saturation, preferredTone, baseLinearRgb, contrast, toneRange = [0, 1], epsilon = 1e-4, maxIterations = 18, pastel = false } = options;
1314
+ const { metric, target, polarity } = contrast;
1315
+ const searchTarget = metric === "wcag" ? target * 1.01 : target + .5;
1316
+ const yBase = metricLuminance(metric, baseLinearRgb);
1317
+ const lum = (t) => cachedLuminance(metric, hue, saturation, t, pastel);
1318
+ const scorePref = metricScore(metric, lum(preferredTone), yBase, polarity);
1319
+ if (scorePref >= searchTarget) return {
1320
+ tone: preferredTone,
1321
+ contrast: scorePref,
1322
+ met: true,
1323
+ branch: "preferred"
1324
+ };
1325
+ const [minT, maxT] = toneRange;
1326
+ const canDarker = preferredTone > minT;
1327
+ const canLighter = preferredTone < maxT;
1328
+ let initialIsDarker;
1329
+ if (options.initialDirection !== void 0) initialIsDarker = options.initialDirection === "darker";
1330
+ else if (canDarker && !canLighter) initialIsDarker = true;
1331
+ else if (!canDarker && canLighter) initialIsDarker = false;
1332
+ else if (!canDarker && !canLighter) return {
1333
+ tone: preferredTone,
1334
+ contrast: scorePref,
1335
+ met: false,
1336
+ branch: "preferred"
1337
+ };
1338
+ else initialIsDarker = metricScore(metric, lum(minT), yBase, polarity) >= metricScore(metric, lum(maxT), yBase, polarity);
1339
+ const solved = solveNearestContrast({
1340
+ lum,
1341
+ yBase,
1342
+ metric,
1343
+ target,
1344
+ searchTarget,
1345
+ lo: minT,
1346
+ hi: maxT,
1347
+ searchAnchor: metric === "wcag" ? clamp(initialIsDarker ? Math.min(preferredTone, wcagToneSeed(yBase, target, true)) : Math.max(preferredTone, wcagToneSeed(yBase, target, false)), minT, maxT) : preferredTone,
1348
+ distanceAnchor: preferredTone,
1349
+ epsilon,
1350
+ maxIterations,
1351
+ flip: options.flip ?? false,
1352
+ initialIsLower: initialIsDarker,
1353
+ polarity
1354
+ });
1355
+ return {
1356
+ tone: solved.pos,
1357
+ contrast: solved.contrast,
1358
+ met: solved.met,
1359
+ branch: solved.lower ? "darker" : "lighter",
1360
+ ...solved.flipped ? { flipped: true } : {}
1361
+ };
1362
+ }
1363
+ /**
1364
+ * Find the mix parameter (ratio or opacity) that satisfies a contrast floor
1365
+ * against a base color, staying as close to `preferredValue` as possible.
1366
+ */
1367
+ function findValueForMixContrast(options) {
1368
+ const { preferredValue, baseLinearRgb, contrast, luminanceAtValue, epsilon = 1e-4, maxIterations = 20 } = options;
1369
+ const { metric, target, polarity } = contrast;
1370
+ const searchTarget = metric === "wcag" ? target * 1.01 : target + .5;
1371
+ const yBase = metricLuminance(metric, baseLinearRgb);
1372
+ const scorePref = metricScore(metric, luminanceAtValue(preferredValue), yBase, polarity);
1373
+ if (scorePref >= searchTarget) return {
1374
+ value: preferredValue,
1375
+ contrast: scorePref,
1376
+ met: true
1377
+ };
1378
+ const canLower = preferredValue > 0;
1379
+ const canUpper = preferredValue < 1;
1380
+ let initialIsLower;
1381
+ if (canLower && !canUpper) initialIsLower = true;
1382
+ else if (!canLower && canUpper) initialIsLower = false;
1383
+ else if (!canLower && !canUpper) return {
1384
+ value: preferredValue,
1385
+ contrast: scorePref,
1386
+ met: false
1387
+ };
1388
+ else initialIsLower = metricScore(metric, luminanceAtValue(0), yBase, polarity) >= metricScore(metric, luminanceAtValue(1), yBase, polarity);
1389
+ const solved = solveNearestContrast({
1390
+ lum: luminanceAtValue,
1391
+ yBase,
1392
+ metric,
1393
+ target,
1394
+ searchTarget,
1395
+ lo: 0,
1396
+ hi: 1,
1397
+ searchAnchor: preferredValue,
1398
+ distanceAnchor: preferredValue,
1399
+ epsilon,
1400
+ maxIterations,
1401
+ flip: options.flip ?? false,
1402
+ initialIsLower,
1403
+ polarity
1404
+ });
1405
+ return {
1406
+ value: solved.pos,
1407
+ contrast: solved.contrast,
1408
+ met: solved.met,
1409
+ ...solved.flipped ? { flipped: true } : {}
1410
+ };
1411
+ }
1412
+
1413
+ //#endregion
1414
+ //#region src/roles.ts
1415
+ const SURFACE_KEYWORDS = new Set([
1416
+ "surface",
1417
+ "bg",
1418
+ "background",
1419
+ "fill",
1420
+ "canvas",
1421
+ "paper",
1422
+ "layer"
1423
+ ]);
1424
+ const TEXT_KEYWORDS = new Set([
1425
+ "text",
1426
+ "fg",
1427
+ "foreground",
1428
+ "content",
1429
+ "ink",
1430
+ "label",
1431
+ "stroke"
1432
+ ]);
1433
+ const BORDER_KEYWORDS = new Set([
1434
+ "border",
1435
+ "divider",
1436
+ "outline",
1437
+ "separator",
1438
+ "hairline",
1439
+ "rule"
1440
+ ]);
1441
+ const ALIAS_TO_ROLE = {
1442
+ surface: "surface",
1443
+ bg: "surface",
1444
+ background: "surface",
1445
+ fill: "surface",
1446
+ canvas: "surface",
1447
+ paper: "surface",
1448
+ layer: "surface",
1449
+ text: "text",
1450
+ fg: "text",
1451
+ foreground: "text",
1452
+ content: "text",
1453
+ ink: "text",
1454
+ label: "text",
1455
+ stroke: "text",
1456
+ border: "border",
1457
+ divider: "border",
1458
+ outline: "border",
1459
+ separator: "border",
1460
+ hairline: "border",
1461
+ rule: "border"
1462
+ };
1463
+ /**
1464
+ * Normalize a `RoleInput` (canonical value or alias) into a canonical `Role`.
1465
+ * Returns `undefined` for unrecognized strings so callers can fall through to
1466
+ * the next step of the resolution chain.
1467
+ */
1468
+ function normalizeRole(input) {
1469
+ if (input === void 0) return void 0;
1470
+ return ALIAS_TO_ROLE[input];
1471
+ }
1472
+ /**
1473
+ * Tokenize a color name into lowercase keyword tokens, splitting on
1474
+ * non-alphanumeric boundaries and at camelCase boundaries. Examples:
1475
+ * - `'button-text'` → `['button', 'text']`
1476
+ * - `'inputBg'` → `['input', 'bg']`
1477
+ * - `'card_border-outline'` → `['card', 'border', 'outline']`
1478
+ */
1479
+ function tokenizeName(name) {
1480
+ const pieces = name.split(/[^0-9a-zA-Z]+/).filter(Boolean);
1481
+ const tokens = [];
1482
+ for (const piece of pieces) {
1483
+ const sub = piece.replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/\s+/).filter(Boolean);
1484
+ for (const s of sub) tokens.push(s.toLowerCase());
1485
+ }
1486
+ return tokens;
1487
+ }
1488
+ /**
1489
+ * Infer a `Role` from a color name by matching its tokens against the role
1490
+ * keyword sets. When multiple tokens match, the **last** recognized token
1491
+ * wins (so `button-text` → `text`, `input-bg` → `surface`, `card-border` →
1492
+ * `border`). Returns `undefined` when no token matches.
1493
+ */
1494
+ function inferRoleFromName(name) {
1495
+ const tokens = tokenizeName(name);
1496
+ let inferred;
1497
+ for (const token of tokens) if (SURFACE_KEYWORDS.has(token)) inferred = "surface";
1498
+ else if (TEXT_KEYWORDS.has(token)) inferred = "text";
1499
+ else if (BORDER_KEYWORDS.has(token)) inferred = "border";
1500
+ return inferred;
1501
+ }
1502
+ /**
1503
+ * Map a role to its APCA polarity. `text` and `border` are foreground spots
1504
+ * against their base (the candidate is the text argument); `surface` is the
1505
+ * background (the base is the text argument).
1506
+ */
1507
+ function roleToPolarity(role) {
1508
+ return role === "surface" ? "bg" : "fg";
1509
+ }
1510
+ /**
1511
+ * The opposite role of `role`, used when a color with no explicit role and no
1512
+ * inferable name depends on a base: the dependent color plays the opposite
1513
+ * role of its base. `surface` ↔ `text`; `border` is treated as a foreground
1514
+ * spot, so its opposite is `surface`.
1515
+ */
1516
+ function oppositeRole(role) {
1517
+ if (role === "surface") return "text";
1518
+ return "surface";
1519
+ }
1520
+
1521
+ //#endregion
1522
+ //#region src/shadow.ts
1523
+ /**
1524
+ * Shadow color computation.
1525
+ *
1526
+ * Owns the shadow / mix def predicates, default tuning constants, the
1527
+ * tuning merge, and the actual `computeShadow` math (hue blend,
1528
+ * saturation cap, lightness clamp, alpha curve). The resolver consumes
1529
+ * this module per scheme variant.
1530
+ */
1531
+ function isShadowDef(def) {
1532
+ return def.type === "shadow";
1533
+ }
1534
+ function isMixDef(def) {
1535
+ return def.type === "mix";
1536
+ }
1537
+ const DEFAULT_SHADOW_TUNING = {
1538
+ saturationFactor: .18,
1539
+ maxSaturation: .25,
1540
+ lightnessFactor: .25,
1541
+ lightnessBounds: [.05, .2],
1542
+ minGapTarget: .05,
1543
+ alphaMax: 1,
1544
+ bgHueBlend: .2
1545
+ };
1546
+ function resolveShadowTuning(perColor, globalTuning) {
1547
+ return {
1548
+ ...DEFAULT_SHADOW_TUNING,
1549
+ ...globalTuning,
1550
+ ...perColor,
1551
+ lightnessBounds: perColor?.lightnessBounds ?? globalTuning?.lightnessBounds ?? DEFAULT_SHADOW_TUNING.lightnessBounds
1552
+ };
1553
+ }
1554
+ function circularLerp(a, b, t) {
1555
+ let diff = b - a;
1556
+ if (diff > 180) diff -= 360;
1557
+ else if (diff < -180) diff += 360;
1558
+ return ((a + diff * t) % 360 + 360) % 360;
1559
+ }
1560
+ /**
1561
+ * Compute the canonical max-contrast reference t value for normalization.
1562
+ * Uses bg.l=1, fg.l=0, intensity=100 — the theoretical maximum.
1563
+ * This is a fixed constant per tuning configuration, ensuring uniform
1564
+ * scaling across all bg/fg pairs at low intensities.
1565
+ */
1566
+ function computeRefT(tuning) {
1567
+ const EPSILON = 1e-6;
1568
+ let lShRef = clamp(tuning.lightnessFactor, tuning.lightnessBounds[0], tuning.lightnessBounds[1]);
1569
+ lShRef = Math.max(Math.min(lShRef, 1 - tuning.minGapTarget), 0);
872
1570
  return 1 / Math.max(1 - lShRef, EPSILON);
873
1571
  }
874
1572
  function computeShadow(bg, fg, intensity, tuning) {
@@ -891,36 +1589,49 @@ function computeShadow(bg, fg, intensity, tuning) {
891
1589
  alpha
892
1590
  };
893
1591
  }
894
- function validateColorDefs(defs) {
895
- const names = new Set(Object.keys(defs));
1592
+
1593
+ //#endregion
1594
+ //#region src/validation.ts
1595
+ /**
1596
+ * Color graph validation and topological sort.
1597
+ *
1598
+ * `validateColorDefs` rejects bad references (missing / shadow-referencing /
1599
+ * base/contrast/tone mismatches) and detects cycles before the
1600
+ * resolver runs. `topoSort` orders defs so each color is processed after
1601
+ * its base / bg / fg / target dependencies.
1602
+ */
1603
+ function validateColorDefs(defs, externalBases) {
1604
+ const localNames = new Set(Object.keys(defs));
1605
+ const allNames = new Set([...localNames, ...externalBases ? externalBases.keys() : []]);
896
1606
  for (const [name, def] of Object.entries(defs)) {
897
1607
  if (isShadowDef(def)) {
898
- if (!names.has(def.bg)) throw new Error(`glaze: shadow "${name}" references non-existent bg "${def.bg}".`);
899
- if (isShadowDef(defs[def.bg])) throw new Error(`glaze: shadow "${name}" bg "${def.bg}" references another shadow color.`);
1608
+ if (!allNames.has(def.bg)) throw new Error(`glaze: shadow "${name}" references non-existent bg "${def.bg}".`);
1609
+ if (localNames.has(def.bg) && isShadowDef(defs[def.bg])) throw new Error(`glaze: shadow "${name}" bg "${def.bg}" references another shadow color.`);
900
1610
  if (def.fg !== void 0) {
901
- if (!names.has(def.fg)) throw new Error(`glaze: shadow "${name}" references non-existent fg "${def.fg}".`);
902
- if (isShadowDef(defs[def.fg])) throw new Error(`glaze: shadow "${name}" fg "${def.fg}" references another shadow color.`);
1611
+ if (!allNames.has(def.fg)) throw new Error(`glaze: shadow "${name}" references non-existent fg "${def.fg}".`);
1612
+ if (localNames.has(def.fg) && isShadowDef(defs[def.fg])) throw new Error(`glaze: shadow "${name}" fg "${def.fg}" references another shadow color.`);
903
1613
  }
904
1614
  continue;
905
1615
  }
906
1616
  if (isMixDef(def)) {
907
- if (!names.has(def.base)) throw new Error(`glaze: mix "${name}" references non-existent base "${def.base}".`);
908
- if (!names.has(def.target)) throw new Error(`glaze: mix "${name}" references non-existent target "${def.target}".`);
909
- if (isShadowDef(defs[def.base])) throw new Error(`glaze: mix "${name}" base "${def.base}" references a shadow color.`);
910
- if (isShadowDef(defs[def.target])) throw new Error(`glaze: mix "${name}" target "${def.target}" references a shadow color.`);
1617
+ if (!allNames.has(def.base)) throw new Error(`glaze: mix "${name}" references non-existent base "${def.base}".`);
1618
+ if (!allNames.has(def.target)) throw new Error(`glaze: mix "${name}" references non-existent target "${def.target}".`);
1619
+ if (localNames.has(def.base) && isShadowDef(defs[def.base])) throw new Error(`glaze: mix "${name}" base "${def.base}" references a shadow color.`);
1620
+ if (localNames.has(def.target) && isShadowDef(defs[def.target])) throw new Error(`glaze: mix "${name}" target "${def.target}" references a shadow color.`);
911
1621
  continue;
912
1622
  }
913
1623
  const regDef = def;
914
1624
  if (regDef.contrast !== void 0 && !regDef.base) throw new Error(`glaze: color "${name}" has "contrast" without "base".`);
915
- if (regDef.lightness !== void 0 && !isAbsoluteLightness(regDef.lightness) && !regDef.base) throw new Error(`glaze: color "${name}" has relative "lightness" without "base".`);
916
- if (regDef.base && !names.has(regDef.base)) throw new Error(`glaze: color "${name}" references non-existent base "${regDef.base}".`);
917
- if (regDef.base && isShadowDef(defs[regDef.base])) throw new Error(`glaze: color "${name}" base "${regDef.base}" references a shadow color.`);
918
- if (!isAbsoluteLightness(regDef.lightness) && regDef.base === void 0) throw new Error(`glaze: color "${name}" must have either absolute "lightness" (root) or "base" (dependent).`);
919
- if (regDef.contrast !== void 0 && regDef.opacity !== void 0) console.warn(`glaze: color "${name}" has both "contrast" and "opacity". Opacity makes perceived lightness unpredictable.`);
1625
+ if (regDef.tone !== void 0 && !isAbsoluteTone(regDef.tone) && !regDef.base) throw new Error(`glaze: color "${name}" has relative "tone" without "base".`);
1626
+ if (regDef.base && !allNames.has(regDef.base)) throw new Error(`glaze: color "${name}" references non-existent base "${regDef.base}".`);
1627
+ if (regDef.base && localNames.has(regDef.base) && isShadowDef(defs[regDef.base])) throw new Error(`glaze: color "${name}" base "${regDef.base}" references a shadow color.`);
1628
+ if (!isAbsoluteTone(regDef.tone) && regDef.base === void 0) throw new Error(`glaze: color "${name}" must have either absolute "tone" (root) or "base" (dependent).`);
1629
+ if (regDef.contrast !== void 0 && regDef.opacity !== void 0) console.warn(`glaze: color "${name}" has both "contrast" and "opacity". Opacity makes perceived tone unpredictable.`);
920
1630
  }
921
1631
  const visited = /* @__PURE__ */ new Set();
922
1632
  const inStack = /* @__PURE__ */ new Set();
923
1633
  function dfs(name) {
1634
+ if (!localNames.has(name)) return;
924
1635
  if (inStack.has(name)) throw new Error(`glaze: circular base reference detected involving "${name}".`);
925
1636
  if (visited.has(name)) return;
926
1637
  inStack.add(name);
@@ -938,7 +1649,7 @@ function validateColorDefs(defs) {
938
1649
  inStack.delete(name);
939
1650
  visited.add(name);
940
1651
  }
941
- for (const name of names) dfs(name);
1652
+ for (const name of localNames) dfs(name);
942
1653
  }
943
1654
  function topoSort(defs) {
944
1655
  const result = [];
@@ -947,6 +1658,7 @@ function topoSort(defs) {
947
1658
  if (visited.has(name)) return;
948
1659
  visited.add(name);
949
1660
  const def = defs[name];
1661
+ if (def === void 0) return;
950
1662
  if (isShadowDef(def)) {
951
1663
  visit(def.bg);
952
1664
  if (def.fg) visit(def.fg);
@@ -962,185 +1674,278 @@ function topoSort(defs) {
962
1674
  for (const name of Object.keys(defs)) visit(name);
963
1675
  return result;
964
1676
  }
965
- function lightnessWindow(isHighContrast, kind) {
966
- if (isHighContrast) return [0, 100];
967
- return kind === "dark" ? globalConfig.darkLightness : globalConfig.lightLightness;
968
- }
969
- function mapLightnessLight(l, mode, isHighContrast) {
970
- if (mode === "static") return l;
971
- const [lo, hi] = lightnessWindow(isHighContrast, "light");
972
- return l * (hi - lo) / 100 + lo;
973
- }
974
- function mobiusCurve(t, beta) {
975
- if (beta >= 1) return t;
976
- return t / (t + beta * (1 - t));
977
- }
978
- function mapLightnessDark(l, mode, isHighContrast) {
979
- if (mode === "static") return l;
980
- const beta = isHighContrast ? pairHC(globalConfig.darkCurve) : pairNormal(globalConfig.darkCurve);
981
- const [darkLo, darkHi] = lightnessWindow(isHighContrast, "dark");
982
- if (mode === "fixed") return l * (darkHi - darkLo) / 100 + darkLo;
983
- const [lightLo, lightHi] = lightnessWindow(isHighContrast, "light");
984
- const t = (lightHi - (l * (lightHi - lightLo) / 100 + lightLo)) / (lightHi - lightLo);
985
- return darkLo + (darkHi - darkLo) * mobiusCurve(t, beta);
986
- }
987
- function lightMappedToDark(lightL, isHighContrast) {
988
- const beta = isHighContrast ? pairHC(globalConfig.darkCurve) : pairNormal(globalConfig.darkCurve);
989
- const [lightLo, lightHi] = lightnessWindow(isHighContrast, "light");
990
- const [darkLo, darkHi] = lightnessWindow(isHighContrast, "dark");
991
- const t = (lightHi - clamp(lightL, lightLo, lightHi)) / (lightHi - lightLo);
992
- return darkLo + (darkHi - darkLo) * mobiusCurve(t, beta);
993
- }
994
- function mapSaturationDark(s, mode) {
995
- if (mode === "static") return s;
996
- return s * (1 - globalConfig.darkDesaturation);
997
- }
998
- function schemeLightnessRange(isDark, mode, isHighContrast) {
999
- if (mode === "static") return [0, 1];
1000
- const [lo, hi] = lightnessWindow(isHighContrast, isDark ? "dark" : "light");
1001
- return [lo / 100, hi / 100];
1677
+
1678
+ //#endregion
1679
+ //#region src/warnings.ts
1680
+ /**
1681
+ * Contrast-warning dispatcher.
1682
+ *
1683
+ * Tokens memoize their resolution, but a long-lived process (e.g. a dev
1684
+ * server with HMR) can re-resolve the same theme many times. The cache
1685
+ * here dedupes warnings within a session with a soft cap to keep noise
1686
+ * bounded.
1687
+ */
1688
+ const CONTRAST_WARN_CACHE_LIMIT = 256;
1689
+ const contrastWarnCache = /* @__PURE__ */ new Set();
1690
+ /**
1691
+ * Slack factor below the requested target before we emit a warning.
1692
+ * The contrast solver overshoots to absorb rounding noise, so an actual
1693
+ * value within ~2x that overshoot is effectively a pass.
1694
+ */
1695
+ const CONTRAST_WARN_SLACK_WCAG = .98;
1696
+ /** APCA Lc is on a 0–106 scale; allow a small absolute slack. */
1697
+ const CONTRAST_WARN_SLACK_APCA = 1.5;
1698
+ function schemeLabel(isDark, isHighContrast) {
1699
+ if (isDark && isHighContrast) return "darkContrast";
1700
+ if (isDark) return "dark";
1701
+ if (isHighContrast) return "lightContrast";
1702
+ return "light";
1703
+ }
1704
+ function metricLabel(c) {
1705
+ return c.metric === "apca" ? `APCA Lc ${c.target.toFixed(1)}` : `WCAG ${c.target.toFixed(2)}`;
1706
+ }
1707
+ function dedupe(key) {
1708
+ if (contrastWarnCache.has(key)) return true;
1709
+ if (contrastWarnCache.size >= CONTRAST_WARN_CACHE_LIMIT) contrastWarnCache.clear();
1710
+ contrastWarnCache.add(key);
1711
+ return false;
1712
+ }
1713
+ /** Warn when the solver could not reach the requested contrast floor. */
1714
+ function warnContrastUnmet(name, isDark, isHighContrast, contrast, actual) {
1715
+ if (actual >= (contrast.metric === "apca" ? contrast.target - CONTRAST_WARN_SLACK_APCA : contrast.target * CONTRAST_WARN_SLACK_WCAG)) return;
1716
+ const scheme = schemeLabel(isDark, isHighContrast);
1717
+ if (dedupe(`unmet|${name}|${scheme}|${contrast.metric}|${contrast.target.toFixed(2)}|${actual.toFixed(2)}`)) return;
1718
+ console.warn(`glaze: color "${name}" cannot meet ${metricLabel(contrast)} in ${scheme} scheme (got ${actual.toFixed(2)}). Try widening the tone window, lowering the contrast target, or picking a base color further from this color's tone.`);
1002
1719
  }
1003
- function clamp(v, min, max) {
1004
- return Math.max(min, Math.min(max, v));
1720
+ /**
1721
+ * Verification (§10): a chromatic swatch inherits the gray tone's
1722
+ * lightness but drifts in real luminance, so a contrast-floored color may
1723
+ * land slightly under the contrast its tone implies. Emit an advisory
1724
+ * warning when the actual measured contrast drifts below the target.
1725
+ */
1726
+ function warnContrastDrift(name, isDark, isHighContrast, contrast, yColor, yBase) {
1727
+ const actual = contrast.metric === "apca" ? Math.abs(contrast.polarity === "bg" ? apcaContrast(yBase, yColor) : apcaContrast(yColor, yBase)) : contrastRatioFromLuminance(yColor, yBase);
1728
+ if (actual >= (contrast.metric === "apca" ? contrast.target - CONTRAST_WARN_SLACK_APCA : contrast.target * CONTRAST_WARN_SLACK_WCAG)) return;
1729
+ const scheme = schemeLabel(isDark, isHighContrast);
1730
+ if (dedupe(`drift|${name}|${scheme}|${contrast.metric}|${contrast.target.toFixed(2)}|${actual.toFixed(2)}`)) return;
1731
+ console.warn(`glaze: color "${name}" drifts below ${metricLabel(contrast)} in ${scheme} scheme (measured ${actual.toFixed(2)}). Chromatic luminance differs from the gray tone; nudge the tone or saturation if the floor matters.`);
1005
1732
  }
1733
+
1734
+ //#endregion
1735
+ //#region src/resolver.ts
1006
1736
  /**
1007
- * Parse a value that can be absolute (number) or relative (signed string).
1008
- * Returns the numeric value and whether it's relative.
1737
+ * Color resolution engine.
1738
+ *
1739
+ * Runs the four-pass solver (light → light-HC → dark → dark-HC) that
1740
+ * turns a `ColorMap` into a fully resolved `ResolvedColor` per name.
1741
+ * Owns the per-scheme resolve helpers for regular, shadow, and mix
1742
+ * color defs.
1743
+ *
1744
+ * Variants are stored in OKHST: `h` / `s` are OKHSL hue/saturation and
1745
+ * `t` is the canonical contrast-uniform tone (0–1, reference eps). The
1746
+ * resolver works in tone for regular colors and converts to/from OKHSL
1747
+ * lightness only at the mix/shadow and luminance edges.
1748
+ *
1749
+ * Every function receives a single `GlazeConfigResolved` so the full
1750
+ * per-instance config (including overrides) is available without
1751
+ * re-reading the global singleton mid-resolve.
1009
1752
  */
1010
- function parseRelativeOrAbsolute(value) {
1011
- if (typeof value === "number") return {
1012
- value,
1013
- relative: false
1753
+ function getSchemeVariant(color, isDark, isHighContrast) {
1754
+ if (isDark && isHighContrast) return color.darkContrast;
1755
+ if (isDark) return color.dark;
1756
+ if (isHighContrast) return color.lightContrast;
1757
+ return color.light;
1758
+ }
1759
+ /** Edge adapter: resolved variant (`t`) → OKHSL-lightness variant. */
1760
+ function toOkhslVariant(v) {
1761
+ const c = variantToOkhsl(v);
1762
+ return {
1763
+ h: c.h,
1764
+ s: c.s,
1765
+ l: c.l,
1766
+ alpha: v.alpha,
1767
+ pastel: v.pastel
1014
1768
  };
1769
+ }
1770
+ /** Edge adapter: OKHSL-lightness variant → resolved variant (`t`). */
1771
+ function toToneVariant(v) {
1772
+ const c = okhslToOkhst({
1773
+ h: v.h,
1774
+ s: v.s,
1775
+ l: v.l
1776
+ });
1015
1777
  return {
1016
- value: parseFloat(value),
1017
- relative: true
1778
+ h: c.h,
1779
+ s: c.s,
1780
+ t: c.t,
1781
+ alpha: v.alpha
1018
1782
  };
1019
1783
  }
1020
1784
  /**
1021
- * Compute the effective hue for a color, given the theme seed hue
1022
- * and an optional per-color hue override.
1785
+ * Resolve the role of a base color referenced by `baseName`, returning the
1786
+ * role the *dependent* color should take (the opposite of the base's role).
1787
+ * A base that lives in `defs` recursively resolves and is inverted via
1788
+ * `oppositeRole`; an external base (no local def, e.g. an injected standalone
1789
+ * token) is treated as a background, so the dependent defaults to foreground
1790
+ * (`'text'`).
1023
1791
  */
1024
- function resolveEffectiveHue(seedHue, defHue) {
1025
- if (defHue === void 0) return seedHue;
1026
- const parsed = parseRelativeOrAbsolute(defHue);
1027
- if (parsed.relative) return ((seedHue + parsed.value) % 360 + 360) % 360;
1028
- return (parsed.value % 360 + 360) % 360;
1792
+ function resolveBaseRoleInMap(baseName, defs, inferRole, roles) {
1793
+ if (!baseName) return void 0;
1794
+ const baseDef = defs[baseName];
1795
+ if (!baseDef) return "text";
1796
+ return oppositeRole(resolveRoleInMap(baseName, baseDef, defs, inferRole, roles));
1797
+ }
1798
+ /**
1799
+ * Role-resolution core that does not need a full `ResolveContext`. Shared by
1800
+ * the resolver (via `resolveRole`) and `verifyContrastDrift`.
1801
+ */
1802
+ function resolveRoleInMap(name, def, defs, inferRole, roles) {
1803
+ const cached = roles.get(name);
1804
+ if (cached) return cached;
1805
+ let role;
1806
+ if (isShadowDef(def)) role = "surface";
1807
+ else if (isMixDef(def)) role = normalizeRole(def.role) ?? (inferRole ? inferRoleFromName(name) : void 0) ?? resolveBaseRoleInMap(def.base, defs, inferRole, roles) ?? "text";
1808
+ else {
1809
+ const regDef = def;
1810
+ role = normalizeRole(regDef.role) ?? (inferRole ? inferRoleFromName(name) : void 0) ?? resolveBaseRoleInMap(regDef.base, defs, inferRole, roles) ?? "text";
1811
+ }
1812
+ const finalRole = role ?? "text";
1813
+ roles.set(name, finalRole);
1814
+ return finalRole;
1029
1815
  }
1030
1816
  /**
1031
- * Check whether a lightness value represents an absolute root definition
1032
- * (i.e. a number, not a relative string).
1817
+ * Resolve a color's semantic `role` (text / surface / border) per the chain:
1818
+ * 1. explicit `def.role` (normalized)
1819
+ * 2. inferred from the color name when `config.inferRole` is on
1820
+ * 3. opposite of the base's role
1821
+ * 4. `'text'` (foreground) default
1822
+ *
1823
+ * Memoized on `ctx.roles` so the four scheme passes share one resolution.
1824
+ * Shadows have no contrast participation and default to `'surface'`.
1033
1825
  */
1034
- function isAbsoluteLightness(lightness) {
1035
- if (lightness === void 0) return false;
1036
- return typeof (Array.isArray(lightness) ? lightness[0] : lightness) === "number";
1826
+ function resolveRole(name, def, ctx) {
1827
+ return resolveRoleInMap(name, def, ctx.defs, ctx.config.inferRole, ctx.roles);
1828
+ }
1829
+ function resolveContrastSpec(spec, isHighContrast, polarity) {
1830
+ return resolveContrastForMode(isHighContrast ? pairHC(spec) : pairNormal(spec), isHighContrast, polarity);
1037
1831
  }
1038
- function resolveRootColor(_name, def, _ctx, isHighContrast) {
1039
- const rawL = def.lightness;
1832
+ /**
1833
+ * Apply the relative-tone delta against a base, honoring `flip`.
1834
+ *
1835
+ * When `flip` is on and `base + delta` falls outside `[0, 100]`, mirror the
1836
+ * delta to the other side of the base (so an offset that would clamp instead
1837
+ * reflects back into range). When off, the caller clamps as usual.
1838
+ */
1839
+ function applyToneFlip(delta, baseTone, flip) {
1840
+ if (!flip) return delta;
1841
+ const target = baseTone + delta;
1842
+ if (target >= 0 && target <= 100) return delta;
1843
+ return -delta;
1844
+ }
1845
+ function resolveRootColor(def, isHighContrast) {
1846
+ const rawT = def.tone;
1040
1847
  return {
1041
- lightL: clamp(parseRelativeOrAbsolute(isHighContrast ? pairHC(rawL) : pairNormal(rawL)).value, 0, 100),
1848
+ authorTone: clamp(parseToneValue(isHighContrast ? pairHC(rawT) : pairNormal(rawT)).value, 0, 100),
1042
1849
  satFactor: clamp(def.saturation ?? 1, 0, 1)
1043
1850
  };
1044
1851
  }
1045
- function resolveDependentColor(name, def, ctx, isHighContrast, isDark, effectiveHue) {
1852
+ function resolveDependentColor(name, def, ctx, isHighContrast, isDark, effectiveHue, polarity, effectivePastel) {
1046
1853
  const baseName = def.base;
1047
1854
  const baseResolved = ctx.resolved.get(baseName);
1048
1855
  if (!baseResolved) throw new Error(`glaze: base "${baseName}" not yet resolved for "${name}".`);
1049
1856
  const mode = def.mode ?? "auto";
1050
1857
  const satFactor = clamp(def.saturation ?? 1, 0, 1);
1858
+ const flip = def.flip ?? ctx.config.autoFlip;
1859
+ const pastel = effectivePastel;
1051
1860
  const baseVariant = getSchemeVariant(baseResolved, isDark, isHighContrast);
1052
- const baseL = baseVariant.l * 100;
1053
- let preferredL;
1054
- const rawLightness = def.lightness;
1055
- if (rawLightness === void 0) preferredL = baseL;
1861
+ const baseTone = baseVariant.t * 100;
1862
+ let preferredTone;
1863
+ const rawTone = def.tone;
1864
+ if (rawTone === void 0) preferredTone = baseTone;
1056
1865
  else {
1057
- const parsed = parseRelativeOrAbsolute(isHighContrast ? pairHC(rawLightness) : pairNormal(rawLightness));
1058
- if (parsed.relative) {
1059
- const delta = parsed.value;
1060
- if (isDark && mode === "auto") preferredL = lightMappedToDark(clamp(getSchemeVariant(baseResolved, false, isHighContrast).l * 100 + delta, 0, 100), isHighContrast);
1061
- else preferredL = clamp(baseL + delta, 0, 100);
1062
- } else if (isDark) preferredL = mapLightnessDark(parsed.value, mode, isHighContrast);
1063
- else preferredL = mapLightnessLight(parsed.value, mode, isHighContrast);
1866
+ const parsed = parseToneValue(isHighContrast ? pairHC(rawTone) : pairNormal(rawTone));
1867
+ if (parsed.kind === "relative") if (isDark && mode === "auto") {
1868
+ const baseLightTone = getSchemeVariant(baseResolved, false, isHighContrast).t * 100;
1869
+ preferredTone = mapToneForScheme(clamp(baseLightTone + applyToneFlip(parsed.value, baseLightTone, flip), 0, 100), "auto", true, isHighContrast, ctx.config);
1870
+ } else preferredTone = clamp(baseTone + applyToneFlip(parsed.value, baseTone, flip), 0, 100);
1871
+ else preferredTone = mapToneForScheme(parsed.value, mode, isDark, isHighContrast, ctx.config);
1064
1872
  }
1065
1873
  const rawContrast = def.contrast;
1066
1874
  if (rawContrast !== void 0) {
1067
- const minCr = isHighContrast ? pairHC(rawContrast) : pairNormal(rawContrast);
1068
- const effectiveSat = isDark ? mapSaturationDark(satFactor * ctx.saturation / 100, mode) : satFactor * ctx.saturation / 100;
1069
- const baseLinearRgb = okhslToLinearSrgb(baseVariant.h, baseVariant.s, baseVariant.l);
1070
- const windowRange = schemeLightnessRange(isDark, mode, isHighContrast);
1875
+ const resolvedContrast = resolveContrastSpec(rawContrast, isHighContrast, polarity);
1876
+ const effectiveSat = isDark ? mapSaturationDark(satFactor * ctx.saturation / 100, mode, ctx.config) : satFactor * ctx.saturation / 100;
1877
+ const baseOkhsl = toOkhslVariant(baseVariant);
1878
+ const baseLinearRgb = okhslToLinearSrgb(baseOkhsl.h, baseOkhsl.s, baseOkhsl.l, baseVariant.pastel ?? ctx.config.pastel);
1879
+ const toneRange = schemeToneRange(isDark, mode, isHighContrast, ctx.config);
1880
+ let initialDirection;
1881
+ if (preferredTone < baseTone) initialDirection = "darker";
1882
+ else if (preferredTone > baseTone) initialDirection = "lighter";
1883
+ const result = findToneForContrast({
1884
+ hue: effectiveHue,
1885
+ saturation: effectiveSat,
1886
+ preferredTone: clamp(preferredTone / 100, toneRange[0], toneRange[1]),
1887
+ baseLinearRgb,
1888
+ contrast: resolvedContrast,
1889
+ toneRange: [0, 1],
1890
+ initialDirection,
1891
+ flip,
1892
+ pastel
1893
+ });
1894
+ if (!result.met) warnContrastUnmet(name, isDark, isHighContrast, resolvedContrast, result.contrast);
1071
1895
  return {
1072
- l: findLightnessForContrast({
1073
- hue: effectiveHue,
1074
- saturation: effectiveSat,
1075
- preferredLightness: clamp(preferredL / 100, windowRange[0], windowRange[1]),
1076
- baseLinearRgb,
1077
- contrast: minCr,
1078
- lightnessRange: [0, 1]
1079
- }).lightness * 100,
1896
+ tone: result.tone * 100,
1080
1897
  satFactor
1081
1898
  };
1082
1899
  }
1083
1900
  return {
1084
- l: clamp(preferredL, 0, 100),
1901
+ tone: clamp(preferredTone, 0, 100),
1085
1902
  satFactor
1086
1903
  };
1087
1904
  }
1088
- function getSchemeVariant(color, isDark, isHighContrast) {
1089
- if (isDark && isHighContrast) return color.darkContrast;
1090
- if (isDark) return color.dark;
1091
- if (isHighContrast) return color.lightContrast;
1092
- return color.light;
1093
- }
1094
1905
  function resolveColorForScheme(name, def, ctx, isDark, isHighContrast) {
1095
1906
  if (isShadowDef(def)) return resolveShadowForScheme(def, ctx, isDark, isHighContrast);
1096
- if (isMixDef(def)) return resolveMixForScheme(def, ctx, isDark, isHighContrast);
1907
+ if (isMixDef(def)) return resolveMixForScheme(name, def, ctx, isDark, isHighContrast);
1097
1908
  const regDef = def;
1098
1909
  const mode = regDef.mode ?? "auto";
1099
- const isRoot = isAbsoluteLightness(regDef.lightness) && !regDef.base;
1910
+ const isRoot = isAbsoluteTone(regDef.tone) && !regDef.base;
1100
1911
  const effectiveHue = resolveEffectiveHue(ctx.hue, regDef.hue);
1101
- let lightL;
1912
+ const polarity = roleToPolarity(resolveRole(name, def, ctx));
1913
+ const pastel = regDef.pastel ?? ctx.config.pastel;
1914
+ let finalTone;
1102
1915
  let satFactor;
1103
1916
  if (isRoot) {
1104
- const root = resolveRootColor(name, regDef, ctx, isHighContrast);
1105
- lightL = root.lightL;
1917
+ const root = resolveRootColor(regDef, isHighContrast);
1918
+ finalTone = mapToneForScheme(root.authorTone, mode, isDark, isHighContrast, ctx.config);
1106
1919
  satFactor = root.satFactor;
1107
1920
  } else {
1108
- const dep = resolveDependentColor(name, regDef, ctx, isHighContrast, isDark, effectiveHue);
1109
- lightL = dep.l;
1921
+ const dep = resolveDependentColor(name, regDef, ctx, isHighContrast, isDark, effectiveHue, polarity, pastel);
1922
+ finalTone = dep.tone;
1110
1923
  satFactor = dep.satFactor;
1111
1924
  }
1112
- let finalL;
1113
- let finalSat;
1114
- if (isDark && isRoot) {
1115
- finalL = mapLightnessDark(lightL, mode, isHighContrast);
1116
- finalSat = mapSaturationDark(satFactor * ctx.saturation / 100, mode);
1117
- } else if (isDark && !isRoot) {
1118
- finalL = lightL;
1119
- finalSat = mapSaturationDark(satFactor * ctx.saturation / 100, mode);
1120
- } else if (isRoot) {
1121
- finalL = mapLightnessLight(lightL, mode, isHighContrast);
1122
- finalSat = satFactor * ctx.saturation / 100;
1123
- } else {
1124
- finalL = lightL;
1125
- finalSat = satFactor * ctx.saturation / 100;
1126
- }
1925
+ const baseSat = satFactor * ctx.saturation / 100;
1926
+ const finalSat = isDark ? mapSaturationDark(baseSat, mode, ctx.config) : baseSat;
1927
+ const toneFraction = clamp(finalTone / 100, 0, 1);
1127
1928
  return {
1128
1929
  h: effectiveHue,
1129
1930
  s: clamp(finalSat, 0, 1),
1130
- l: clamp(finalL / 100, 0, 1),
1131
- alpha: regDef.opacity ?? 1
1931
+ t: toneFraction,
1932
+ alpha: regDef.opacity ?? 1,
1933
+ pastel
1132
1934
  };
1133
1935
  }
1134
1936
  function resolveShadowForScheme(def, ctx, isDark, isHighContrast) {
1135
- const bgVariant = getSchemeVariant(ctx.resolved.get(def.bg), isDark, isHighContrast);
1937
+ const bgVariant = toOkhslVariant(getSchemeVariant(ctx.resolved.get(def.bg), isDark, isHighContrast));
1136
1938
  let fgVariant;
1137
- if (def.fg) fgVariant = getSchemeVariant(ctx.resolved.get(def.fg), isDark, isHighContrast);
1939
+ if (def.fg) fgVariant = toOkhslVariant(getSchemeVariant(ctx.resolved.get(def.fg), isDark, isHighContrast));
1138
1940
  const intensity = isHighContrast ? pairHC(def.intensity) : pairNormal(def.intensity);
1139
- const tuning = resolveShadowTuning(def.tuning);
1140
- return computeShadow(bgVariant, fgVariant, intensity, tuning);
1941
+ const tuning = resolveShadowTuning(def.tuning, ctx.config.shadowTuning);
1942
+ return {
1943
+ ...toToneVariant(computeShadow(bgVariant, fgVariant, intensity, tuning)),
1944
+ pastel: def.pastel ?? ctx.config.pastel
1945
+ };
1141
1946
  }
1142
- function variantToLinearRgb(v) {
1143
- return okhslToLinearSrgb(v.h, v.s, v.l);
1947
+ function okhslVariantToLinearRgb(v, pastel) {
1948
+ return okhslToLinearSrgb(v.h, v.s, v.l, pastel);
1144
1949
  }
1145
1950
  /**
1146
1951
  * Resolve hue for OKHSL mixing, handling achromatic colors.
@@ -1163,77 +1968,92 @@ function linearSrgbLerp(base, target, t) {
1163
1968
  base[2] + (target[2] - base[2]) * t
1164
1969
  ];
1165
1970
  }
1166
- function linearRgbToVariant(rgb) {
1971
+ function linearRgbToToneVariant(rgb, pastel) {
1167
1972
  const [h, s, l] = srgbToOkhsl([
1168
1973
  Math.max(0, Math.min(1, sRGBLinearToGamma(rgb[0]))),
1169
1974
  Math.max(0, Math.min(1, sRGBLinearToGamma(rgb[1]))),
1170
1975
  Math.max(0, Math.min(1, sRGBLinearToGamma(rgb[2])))
1171
- ]);
1172
- return {
1976
+ ], pastel);
1977
+ return toToneVariant({
1173
1978
  h,
1174
1979
  s,
1175
1980
  l,
1176
1981
  alpha: 1
1177
- };
1982
+ });
1178
1983
  }
1179
- function resolveMixForScheme(def, ctx, isDark, isHighContrast) {
1984
+ function resolveMixForScheme(name, def, ctx, isDark, isHighContrast) {
1180
1985
  const baseResolved = ctx.resolved.get(def.base);
1181
1986
  const targetResolved = ctx.resolved.get(def.target);
1182
- const baseVariant = getSchemeVariant(baseResolved, isDark, isHighContrast);
1183
- const targetVariant = getSchemeVariant(targetResolved, isDark, isHighContrast);
1987
+ const baseVariant = toOkhslVariant(getSchemeVariant(baseResolved, isDark, isHighContrast));
1988
+ const targetVariant = toOkhslVariant(getSchemeVariant(targetResolved, isDark, isHighContrast));
1184
1989
  let t = clamp(isHighContrast ? pairHC(def.value) : pairNormal(def.value), 0, 100) / 100;
1185
1990
  const blend = def.blend ?? "opaque";
1186
1991
  const space = def.space ?? "okhsl";
1187
- const baseLinear = variantToLinearRgb(baseVariant);
1188
- const targetLinear = variantToLinearRgb(targetVariant);
1992
+ const polarity = roleToPolarity(resolveRole(name, def, ctx));
1993
+ const pastel = def.pastel ?? ctx.config.pastel;
1994
+ const baseLinear = okhslVariantToLinearRgb(baseVariant, baseVariant.pastel ?? ctx.config.pastel);
1995
+ const targetLinear = okhslVariantToLinearRgb(targetVariant, targetVariant.pastel ?? ctx.config.pastel);
1189
1996
  if (def.contrast !== void 0) {
1190
- const minCr = isHighContrast ? pairHC(def.contrast) : pairNormal(def.contrast);
1997
+ const resolvedContrast = resolveContrastSpec(def.contrast, isHighContrast, polarity);
1998
+ const metric = resolvedContrast.metric;
1191
1999
  let luminanceAt;
1192
- if (blend === "transparent") luminanceAt = (v) => gamutClampedLuminance(linearSrgbLerp(baseLinear, targetLinear, v));
1193
- else if (space === "srgb") luminanceAt = (v) => gamutClampedLuminance(linearSrgbLerp(baseLinear, targetLinear, v));
2000
+ if (blend === "transparent" || space === "srgb") luminanceAt = (v) => metricLuminance(metric, linearSrgbLerp(baseLinear, targetLinear, v));
1194
2001
  else luminanceAt = (v) => {
1195
- return gamutClampedLuminance(okhslToLinearSrgb(mixHue(baseVariant, targetVariant, v), baseVariant.s + (targetVariant.s - baseVariant.s) * v, baseVariant.l + (targetVariant.l - baseVariant.l) * v));
2002
+ return metricLuminance(metric, okhslToLinearSrgb(mixHue(baseVariant, targetVariant, v), baseVariant.s + (targetVariant.s - baseVariant.s) * v, baseVariant.l + (targetVariant.l - baseVariant.l) * v, pastel));
1196
2003
  };
1197
2004
  t = findValueForMixContrast({
1198
2005
  preferredValue: t,
1199
2006
  baseLinearRgb: baseLinear,
1200
2007
  targetLinearRgb: targetLinear,
1201
- contrast: minCr,
1202
- luminanceAtValue: luminanceAt
2008
+ contrast: resolvedContrast,
2009
+ luminanceAtValue: luminanceAt,
2010
+ flip: ctx.config.autoFlip
1203
2011
  }).value;
1204
2012
  }
1205
2013
  if (blend === "transparent") return {
1206
- h: targetVariant.h,
1207
- s: targetVariant.s,
1208
- l: targetVariant.l,
1209
- alpha: clamp(t, 0, 1)
2014
+ ...toToneVariant({
2015
+ h: targetVariant.h,
2016
+ s: targetVariant.s,
2017
+ l: targetVariant.l,
2018
+ alpha: clamp(t, 0, 1)
2019
+ }),
2020
+ pastel
2021
+ };
2022
+ if (space === "srgb") return {
2023
+ ...linearRgbToToneVariant(linearSrgbLerp(baseLinear, targetLinear, t), pastel),
2024
+ pastel
1210
2025
  };
1211
- if (space === "srgb") return linearRgbToVariant(linearSrgbLerp(baseLinear, targetLinear, t));
1212
2026
  return {
1213
- h: mixHue(baseVariant, targetVariant, t),
1214
- s: clamp(baseVariant.s + (targetVariant.s - baseVariant.s) * t, 0, 1),
1215
- l: clamp(baseVariant.l + (targetVariant.l - baseVariant.l) * t, 0, 1),
1216
- alpha: 1
2027
+ ...toToneVariant({
2028
+ h: mixHue(baseVariant, targetVariant, t),
2029
+ s: clamp(baseVariant.s + (targetVariant.s - baseVariant.s) * t, 0, 1),
2030
+ l: clamp(baseVariant.l + (targetVariant.l - baseVariant.l) * t, 0, 1),
2031
+ alpha: 1
2032
+ }),
2033
+ pastel
1217
2034
  };
1218
2035
  }
1219
- function resolveAllColors(hue, saturation, defs) {
1220
- validateColorDefs(defs);
1221
- const order = topoSort(defs);
1222
- const ctx = {
1223
- hue,
1224
- saturation,
1225
- defs,
1226
- resolved: /* @__PURE__ */ new Map()
1227
- };
1228
- function defMode(def) {
1229
- if (isShadowDef(def) || isMixDef(def)) return void 0;
1230
- return def.mode ?? "auto";
1231
- }
1232
- const lightMap = /* @__PURE__ */ new Map();
2036
+ function defMode(def) {
2037
+ if (isShadowDef(def) || isMixDef(def)) return void 0;
2038
+ return def.mode ?? "auto";
2039
+ }
2040
+ /**
2041
+ * Run a single resolve pass over all local names. Pass 1 lazily creates
2042
+ * each `ResolvedColor` (all four slots seeded with the just-resolved
2043
+ * variant) the first time it sees a name; later passes update the
2044
+ * `target` slot on the existing record.
2045
+ */
2046
+ function runPass(order, defs, ctx, isDark, isHighContrast, target) {
2047
+ const out = /* @__PURE__ */ new Map();
1233
2048
  for (const name of order) {
1234
- const variant = resolveColorForScheme(name, defs[name], ctx, false, false);
1235
- lightMap.set(name, variant);
1236
- ctx.resolved.set(name, {
2049
+ const variant = resolveColorForScheme(name, defs[name], ctx, isDark, isHighContrast);
2050
+ out.set(name, variant);
2051
+ const existing = ctx.resolved.get(name);
2052
+ if (existing) ctx.resolved.set(name, {
2053
+ ...existing,
2054
+ [target]: variant
2055
+ });
2056
+ else ctx.resolved.set(name, {
1237
2057
  name,
1238
2058
  light: variant,
1239
2059
  dark: variant,
@@ -1242,49 +2062,92 @@ function resolveAllColors(hue, saturation, defs) {
1242
2062
  mode: defMode(defs[name])
1243
2063
  });
1244
2064
  }
1245
- const lightHCMap = /* @__PURE__ */ new Map();
1246
- for (const name of order) ctx.resolved.set(name, {
1247
- ...ctx.resolved.get(name),
1248
- lightContrast: lightMap.get(name)
1249
- });
1250
- for (const name of order) {
1251
- const variant = resolveColorForScheme(name, defs[name], ctx, false, true);
1252
- lightHCMap.set(name, variant);
1253
- ctx.resolved.set(name, {
1254
- ...ctx.resolved.get(name),
1255
- lightContrast: variant
1256
- });
1257
- }
1258
- const darkMap = /* @__PURE__ */ new Map();
1259
- for (const name of order) ctx.resolved.set(name, {
1260
- name,
1261
- light: lightMap.get(name),
1262
- dark: lightMap.get(name),
1263
- lightContrast: lightHCMap.get(name),
1264
- darkContrast: lightHCMap.get(name),
1265
- mode: defMode(defs[name])
1266
- });
2065
+ return out;
2066
+ }
2067
+ /**
2068
+ * Re-seed a single variant slot with a previously-resolved map so the
2069
+ * upcoming pass reads sensible fallbacks via `getSchemeVariant`.
2070
+ */
2071
+ function seedField(order, ctx, field, source) {
1267
2072
  for (const name of order) {
1268
- const variant = resolveColorForScheme(name, defs[name], ctx, true, false);
1269
- darkMap.set(name, variant);
2073
+ const existing = ctx.resolved.get(name);
1270
2074
  ctx.resolved.set(name, {
1271
- ...ctx.resolved.get(name),
1272
- dark: variant
2075
+ ...existing,
2076
+ [field]: source.get(name)
1273
2077
  });
1274
2078
  }
1275
- const darkHCMap = /* @__PURE__ */ new Map();
1276
- for (const name of order) ctx.resolved.set(name, {
1277
- ...ctx.resolved.get(name),
1278
- darkContrast: darkMap.get(name)
1279
- });
2079
+ }
2080
+ /**
2081
+ * After the four passes, surface chromatic contrast drift (§10): a color
2082
+ * resolved with a `base` + `contrast` may land slightly under the contrast
2083
+ * its tone implies because chromatic luminance drifts from the gray tone.
2084
+ */
2085
+ function verifyContrastDrift(order, defs, result, config) {
2086
+ const roles = /* @__PURE__ */ new Map();
1280
2087
  for (const name of order) {
1281
- const variant = resolveColorForScheme(name, defs[name], ctx, true, true);
1282
- darkHCMap.set(name, variant);
1283
- ctx.resolved.set(name, {
1284
- ...ctx.resolved.get(name),
1285
- darkContrast: variant
1286
- });
2088
+ const def = defs[name];
2089
+ if (isShadowDef(def) || isMixDef(def)) continue;
2090
+ const regDef = def;
2091
+ if (regDef.contrast === void 0 || !regDef.base) continue;
2092
+ const color = result.get(name);
2093
+ const base = result.get(regDef.base);
2094
+ if (!color || !base) continue;
2095
+ const polarity = roleToPolarity(resolveRoleInMap(name, def, defs, config.inferRole, roles));
2096
+ for (const s of [
2097
+ {
2098
+ isDark: false,
2099
+ isHighContrast: false,
2100
+ field: "light"
2101
+ },
2102
+ {
2103
+ isDark: false,
2104
+ isHighContrast: true,
2105
+ field: "lightContrast"
2106
+ },
2107
+ {
2108
+ isDark: true,
2109
+ isHighContrast: false,
2110
+ field: "dark"
2111
+ },
2112
+ {
2113
+ isDark: true,
2114
+ isHighContrast: true,
2115
+ field: "darkContrast"
2116
+ }
2117
+ ]) {
2118
+ const spec = resolveContrastSpec(regDef.contrast, s.isHighContrast, polarity);
2119
+ const cVariant = color[s.field];
2120
+ const bVariant = base[s.field];
2121
+ const cOkhsl = toOkhslVariant(cVariant);
2122
+ const bOkhsl = toOkhslVariant(bVariant);
2123
+ const cPastel = cVariant.pastel ?? config.pastel;
2124
+ const bPastel = bVariant.pastel ?? config.pastel;
2125
+ const yC = metricLuminance(spec.metric, okhslToLinearSrgb(cOkhsl.h, cOkhsl.s, cOkhsl.l, cPastel));
2126
+ const yB = metricLuminance(spec.metric, okhslToLinearSrgb(bOkhsl.h, bOkhsl.s, bOkhsl.l, bPastel));
2127
+ warnContrastDrift(name, s.isDark, s.isHighContrast, spec, yC, yB);
2128
+ }
1287
2129
  }
2130
+ }
2131
+ function resolveAllColors(hue, saturation, defs, config, externalBases) {
2132
+ validateColorDefs(defs, externalBases);
2133
+ const order = topoSort(defs);
2134
+ const ctx = {
2135
+ hue,
2136
+ saturation,
2137
+ defs,
2138
+ resolved: /* @__PURE__ */ new Map(),
2139
+ config,
2140
+ roles: /* @__PURE__ */ new Map()
2141
+ };
2142
+ if (externalBases) for (const [name, color] of externalBases) ctx.resolved.set(name, color);
2143
+ const lightMap = runPass(order, defs, ctx, false, false, "light");
2144
+ seedField(order, ctx, "lightContrast", lightMap);
2145
+ const lightHCMap = runPass(order, defs, ctx, false, true, "lightContrast");
2146
+ seedField(order, ctx, "dark", lightMap);
2147
+ seedField(order, ctx, "darkContrast", lightHCMap);
2148
+ const darkMap = runPass(order, defs, ctx, true, false, "dark");
2149
+ seedField(order, ctx, "darkContrast", darkMap);
2150
+ const darkHCMap = runPass(order, defs, ctx, true, true, "darkContrast");
1288
2151
  const result = /* @__PURE__ */ new Map();
1289
2152
  for (const name of order) result.set(name, {
1290
2153
  name,
@@ -1294,8 +2157,126 @@ function resolveAllColors(hue, saturation, defs) {
1294
2157
  darkContrast: darkHCMap.get(name),
1295
2158
  mode: defMode(defs[name])
1296
2159
  });
2160
+ verifyContrastDrift(order, defs, result, config);
1297
2161
  return result;
1298
2162
  }
2163
+
2164
+ //#endregion
2165
+ //#region src/channels.ts
2166
+ /**
2167
+ * Hue channel planning for `splitHue` exports.
2168
+ *
2169
+ * Builds per-color hue var references and scheme-independent `--*-hue`
2170
+ * declarations for oklch CSS / Tasty output when every color is pastel.
2171
+ */
2172
+ const ACHROMATIC_EPSILON = 1e-6;
2173
+ function cssProp(prefix, name, suffix) {
2174
+ return `--${prefix}${name}${suffix}`;
2175
+ }
2176
+ function isAchromatic(v) {
2177
+ return v.s <= ACHROMATIC_EPSILON;
2178
+ }
2179
+ function themeHuePlan(name, def, variant, ctx) {
2180
+ if (def === void 0 || isShadowDef(def) || isMixDef(def) || isAchromatic(variant)) return {
2181
+ hueVar: "",
2182
+ inline: true,
2183
+ declarations: []
2184
+ };
2185
+ const regDef = def;
2186
+ const baseHueVar = `var(--${ctx.baseName}-hue)`;
2187
+ if (regDef.hue === void 0) return {
2188
+ hueVar: baseHueVar,
2189
+ inline: false,
2190
+ declarations: []
2191
+ };
2192
+ const parsed = parseRelativeOrAbsolute(regDef.hue);
2193
+ const prop = cssProp(ctx.prefix, name, "-hue");
2194
+ if (parsed.relative) {
2195
+ const sign = parsed.value >= 0 ? "+" : "-";
2196
+ const magnitude = Math.abs(parsed.value);
2197
+ const value = `calc(var(--${ctx.baseName}-hue) ${sign} ${magnitude})`;
2198
+ return {
2199
+ hueVar: `var(${prop})`,
2200
+ inline: false,
2201
+ declarations: [{
2202
+ prop,
2203
+ value
2204
+ }]
2205
+ };
2206
+ }
2207
+ const absHue = (parsed.value % 360 + 360) % 360;
2208
+ return {
2209
+ hueVar: `var(${prop})`,
2210
+ inline: false,
2211
+ declarations: [{
2212
+ prop,
2213
+ value: String(absHue)
2214
+ }]
2215
+ };
2216
+ }
2217
+ function standaloneHuePlan(name, variant, ctx) {
2218
+ if (isAchromatic(variant)) return {
2219
+ hueVar: "",
2220
+ inline: true,
2221
+ declarations: []
2222
+ };
2223
+ const hue = ctx.resolvedHue ?? variant.h;
2224
+ const prop = cssProp(ctx.prefix, name, "-hue");
2225
+ return {
2226
+ hueVar: `var(${prop})`,
2227
+ inline: false,
2228
+ declarations: [{
2229
+ prop,
2230
+ value: String(hue)
2231
+ }]
2232
+ };
2233
+ }
2234
+ function buildHuePlan(name, def, variant, ctx) {
2235
+ if (ctx.mode === "standalone") return standaloneHuePlan(name, variant, ctx);
2236
+ return themeHuePlan(name, def, variant, ctx);
2237
+ }
2238
+ /** Collect unique hue declarations across all colors (theme + per-color). */
2239
+ function collectHueDeclarations(resolved, ctx) {
2240
+ if (ctx.emitDeclarations === false) return [];
2241
+ const seen = /* @__PURE__ */ new Set();
2242
+ const out = [];
2243
+ const push = (decl) => {
2244
+ if (seen.has(decl.prop)) return;
2245
+ seen.add(decl.prop);
2246
+ out.push(decl);
2247
+ };
2248
+ if (ctx.mode === "theme") push({
2249
+ prop: `--${ctx.baseName}-hue`,
2250
+ value: String(ctx.seedHue)
2251
+ });
2252
+ for (const [name, color] of resolved) {
2253
+ const def = ctx.defs[name];
2254
+ const plan = buildHuePlan(name, def, color.light, ctx);
2255
+ for (const decl of plan.declarations) push(decl);
2256
+ }
2257
+ return out;
2258
+ }
2259
+ function buildHuePlans(resolved, ctx) {
2260
+ const plans = /* @__PURE__ */ new Map();
2261
+ for (const [name, color] of resolved) plans.set(name, buildHuePlan(name, ctx.defs[name], color.light, ctx));
2262
+ return plans;
2263
+ }
2264
+
2265
+ //#endregion
2266
+ //#region src/formatters.ts
2267
+ /**
2268
+ * Output formatting for resolved color maps.
2269
+ *
2270
+ * Owns the CSS-string formatter dispatch table (`okhsl` / `rgb` / `hsl` /
2271
+ * `oklch`) and the token-map shapes Glaze emits:
2272
+ * - `buildTokenMap` — Tasty style-to-state bindings (`#name` keys, state aliases).
2273
+ * - `buildFlatTokenMap` — `{ light, dark, ... }` per-variant maps.
2274
+ * - `buildJsonMap` — `{ name: { light, dark, ... } }` per-color JSON.
2275
+ * - `buildCssMap` — CSS custom property declaration strings per variant.
2276
+ * - `buildDtcgMap` — W3C DTCG (2025.10) token documents, one per scheme.
2277
+ * - `buildDtcgResolver` — W3C DTCG Resolver-Module document (one modifier, a context per scheme).
2278
+ * - `buildTailwindMap` — Tailwind v4 `@theme` block + dark/HC overrides.
2279
+ */
1299
2280
  const formatters = {
1300
2281
  okhsl: formatOkhsl,
1301
2282
  rgb: formatRgb,
@@ -1305,68 +2286,116 @@ const formatters = {
1305
2286
  function fmt(value, decimals) {
1306
2287
  return parseFloat(value.toFixed(decimals)).toString();
1307
2288
  }
1308
- function formatVariant(v, format = "okhsl") {
1309
- const base = formatters[format](v.h, v.s * 100, v.l * 100);
2289
+ function formatVariant(v, format = "okhsl", pastel = false) {
2290
+ const effectivePastel = v.pastel ?? pastel;
2291
+ let base;
2292
+ if (format === "okhst") base = formatOkhst(v.h, v.s * 100, v.t * 100, effectivePastel);
2293
+ else {
2294
+ const { l } = variantToOkhsl(v);
2295
+ base = formatters[format](v.h, v.s * 100, l * 100, effectivePastel);
2296
+ }
2297
+ if (v.alpha >= 1) return base;
2298
+ const closing = base.lastIndexOf(")");
2299
+ return `${base.slice(0, closing)} / ${fmt(v.alpha, 4)})`;
2300
+ }
2301
+ /**
2302
+ * Format a resolved variant as `oklch(L C <hueVar>)`, splicing a CSS hue var
2303
+ * for `splitHue` exports. Falls back to inline when the plan is inline.
2304
+ */
2305
+ function formatVariantHue(v, plan, pastel = false) {
2306
+ const effectivePastel = v.pastel ?? pastel;
2307
+ const { l } = variantToOkhsl(v);
2308
+ const [L, C] = okhslToOklch(v.h, v.s, l, effectivePastel);
2309
+ let base;
2310
+ if (plan.inline) if (v.s <= 1e-6) base = `oklch(${fmt(L, 4)} 0 0)`;
2311
+ else base = formatOklch(v.h, v.s * 100, l * 100, effectivePastel);
2312
+ else base = `oklch(${fmt(L, 4)} ${fmt(C, 4)} ${plan.hueVar})`;
1310
2313
  if (v.alpha >= 1) return base;
1311
2314
  const closing = base.lastIndexOf(")");
1312
2315
  return `${base.slice(0, closing)} / ${fmt(v.alpha, 4)})`;
1313
2316
  }
2317
+ function formatColorValue(v, format, pastel, huePlan) {
2318
+ if (format === "oklch" && huePlan !== void 0) return formatVariantHue(v, huePlan, pastel);
2319
+ return formatVariant(v, format, pastel);
2320
+ }
1314
2321
  function resolveModes(override) {
2322
+ const cfg = getConfig();
1315
2323
  return {
1316
- dark: override?.dark ?? globalConfig.modes.dark,
1317
- highContrast: override?.highContrast ?? globalConfig.modes.highContrast
2324
+ dark: override?.dark ?? cfg.modes.dark,
2325
+ highContrast: override?.highContrast ?? cfg.modes.highContrast
1318
2326
  };
1319
2327
  }
1320
- function buildTokenMap(resolved, prefix, states, modes, format = "okhsl") {
2328
+ function buildTokenMap(resolved, prefix, states, modes, format = "okhsl", pastel = false, channelCtx) {
1321
2329
  const tokens = {};
2330
+ const huePlans = channelCtx !== void 0 && format === "oklch" ? buildHuePlans(resolved, channelCtx) : void 0;
2331
+ if (huePlans !== void 0 && channelCtx !== void 0) {
2332
+ const emitDecls = channelCtx.emitDeclarations !== false;
2333
+ if (emitDecls && channelCtx.mode === "theme") tokens[`#${channelCtx.baseName}-hue`] = { "": String(channelCtx.seedHue) };
2334
+ for (const [name, color] of resolved) {
2335
+ const plan = huePlans.get(name);
2336
+ if (emitDecls) for (const decl of plan.declarations) {
2337
+ const key = `#${decl.prop.slice(2)}`;
2338
+ if (!(key in tokens)) tokens[key] = { "": decl.value };
2339
+ }
2340
+ const colorKey = `#${prefix}${name}`;
2341
+ tokens[colorKey] = buildTokenEntry(color, states, modes, format, pastel, huePlans.get(name));
2342
+ }
2343
+ return tokens;
2344
+ }
1322
2345
  for (const [name, color] of resolved) {
1323
2346
  const key = `#${prefix}${name}`;
1324
- const entry = { "": formatVariant(color.light, format) };
1325
- if (modes.dark) entry[states.dark] = formatVariant(color.dark, format);
1326
- if (modes.highContrast) entry[states.highContrast] = formatVariant(color.lightContrast, format);
1327
- if (modes.dark && modes.highContrast) entry[`${states.dark} & ${states.highContrast}`] = formatVariant(color.darkContrast, format);
1328
- tokens[key] = entry;
2347
+ tokens[key] = buildTokenEntry(color, states, modes, format, pastel);
1329
2348
  }
1330
2349
  return tokens;
1331
2350
  }
1332
- function buildFlatTokenMap(resolved, prefix, modes, format = "okhsl") {
2351
+ function buildTokenEntry(color, states, modes, format, pastel, huePlan) {
2352
+ const entry = { "": formatColorValue(color.light, format, pastel, huePlan) };
2353
+ if (modes.dark) entry[states.dark] = formatColorValue(color.dark, format, pastel, huePlan);
2354
+ if (modes.highContrast) entry[states.highContrast] = formatColorValue(color.lightContrast, format, pastel, huePlan);
2355
+ if (modes.dark && modes.highContrast) entry[`${states.dark} & ${states.highContrast}`] = formatColorValue(color.darkContrast, format, pastel, huePlan);
2356
+ return entry;
2357
+ }
2358
+ function buildFlatTokenMap(resolved, prefix, modes, format = "okhsl", pastel = false) {
1333
2359
  const result = { light: {} };
1334
2360
  if (modes.dark) result.dark = {};
1335
2361
  if (modes.highContrast) result.lightContrast = {};
1336
2362
  if (modes.dark && modes.highContrast) result.darkContrast = {};
1337
2363
  for (const [name, color] of resolved) {
1338
2364
  const key = `${prefix}${name}`;
1339
- result.light[key] = formatVariant(color.light, format);
1340
- if (modes.dark) result.dark[key] = formatVariant(color.dark, format);
1341
- if (modes.highContrast) result.lightContrast[key] = formatVariant(color.lightContrast, format);
1342
- if (modes.dark && modes.highContrast) result.darkContrast[key] = formatVariant(color.darkContrast, format);
2365
+ result.light[key] = formatVariant(color.light, format, pastel);
2366
+ if (modes.dark) result.dark[key] = formatVariant(color.dark, format, pastel);
2367
+ if (modes.highContrast) result.lightContrast[key] = formatVariant(color.lightContrast, format, pastel);
2368
+ if (modes.dark && modes.highContrast) result.darkContrast[key] = formatVariant(color.darkContrast, format, pastel);
1343
2369
  }
1344
2370
  return result;
1345
2371
  }
1346
- function buildJsonMap(resolved, modes, format = "okhsl") {
2372
+ function buildJsonMap(resolved, modes, format = "okhsl", pastel = false) {
1347
2373
  const result = {};
1348
2374
  for (const [name, color] of resolved) {
1349
- const entry = { light: formatVariant(color.light, format) };
1350
- if (modes.dark) entry.dark = formatVariant(color.dark, format);
1351
- if (modes.highContrast) entry.lightContrast = formatVariant(color.lightContrast, format);
1352
- if (modes.dark && modes.highContrast) entry.darkContrast = formatVariant(color.darkContrast, format);
2375
+ const entry = { light: formatVariant(color.light, format, pastel) };
2376
+ if (modes.dark) entry.dark = formatVariant(color.dark, format, pastel);
2377
+ if (modes.highContrast) entry.lightContrast = formatVariant(color.lightContrast, format, pastel);
2378
+ if (modes.dark && modes.highContrast) entry.darkContrast = formatVariant(color.darkContrast, format, pastel);
1353
2379
  result[name] = entry;
1354
2380
  }
1355
2381
  return result;
1356
2382
  }
1357
- function buildCssMap(resolved, prefix, suffix, format) {
2383
+ function buildCssMap(resolved, prefix, suffix, format, pastel = false, channelCtx) {
1358
2384
  const lines = {
1359
2385
  light: [],
1360
2386
  dark: [],
1361
2387
  lightContrast: [],
1362
2388
  darkContrast: []
1363
2389
  };
2390
+ const huePlans = channelCtx !== void 0 && format === "oklch" ? buildHuePlans(resolved, channelCtx) : void 0;
2391
+ if (huePlans !== void 0 && channelCtx !== void 0) for (const decl of collectHueDeclarations(resolved, channelCtx)) lines.light.push(`${decl.prop}: ${decl.value};`);
1364
2392
  for (const [name, color] of resolved) {
1365
2393
  const prop = `--${prefix}${name}${suffix}`;
1366
- lines.light.push(`${prop}: ${formatVariant(color.light, format)};`);
1367
- lines.dark.push(`${prop}: ${formatVariant(color.dark, format)};`);
1368
- lines.lightContrast.push(`${prop}: ${formatVariant(color.lightContrast, format)};`);
1369
- lines.darkContrast.push(`${prop}: ${formatVariant(color.darkContrast, format)};`);
2394
+ const plan = huePlans?.get(name);
2395
+ lines.light.push(`${prop}: ${formatColorValue(color.light, format, pastel, plan)};`);
2396
+ lines.dark.push(`${prop}: ${formatColorValue(color.dark, format, pastel, plan)};`);
2397
+ lines.lightContrast.push(`${prop}: ${formatColorValue(color.lightContrast, format, pastel, plan)};`);
2398
+ lines.darkContrast.push(`${prop}: ${formatColorValue(color.darkContrast, format, pastel, plan)};`);
1370
2399
  }
1371
2400
  return {
1372
2401
  light: lines.light.join("\n"),
@@ -1375,71 +2404,812 @@ function buildCssMap(resolved, prefix, suffix, format) {
1375
2404
  darkContrast: lines.darkContrast.join("\n")
1376
2405
  };
1377
2406
  }
1378
- function createTheme(hue, saturation, initialColors) {
1379
- let colorDefs = initialColors ? { ...initialColors } : {};
2407
+ function roundTo(value, decimals) {
2408
+ return parseFloat(value.toFixed(decimals));
2409
+ }
2410
+ /**
2411
+ * Build a DTCG `$value` color object for a resolved variant.
2412
+ *
2413
+ * `srgb` (default) emits gamma sRGB components in 0–1 plus a 6-digit `hex`
2414
+ * hint — the most universally understood form (Figma, Tokens Studio, Style
2415
+ * Dictionary). `oklch` emits `[L, C, H]` components with no hex — Glaze-native
2416
+ * and wide-gamut. `alpha` is included only when below 1.
2417
+ */
2418
+ function dtcgColorValue(v, colorSpace = "srgb", pastel = false) {
2419
+ const effectivePastel = v.pastel ?? pastel;
2420
+ const { l } = variantToOkhsl(v);
2421
+ const alpha = v.alpha < 1 ? roundTo(v.alpha, 6) : void 0;
2422
+ if (colorSpace === "oklch") {
2423
+ const [L, C, H] = okhslToOklch(v.h, v.s, l, effectivePastel);
2424
+ const value = {
2425
+ colorSpace: "oklch",
2426
+ components: [
2427
+ roundTo(L, 6),
2428
+ roundTo(C, 6),
2429
+ roundTo(H, 4)
2430
+ ]
2431
+ };
2432
+ if (alpha !== void 0) value.alpha = alpha;
2433
+ return value;
2434
+ }
2435
+ const [r, g, b] = okhslToSrgb(v.h, v.s, l, effectivePastel);
2436
+ const value = {
2437
+ colorSpace: "srgb",
2438
+ components: [
2439
+ roundTo(r, 6),
2440
+ roundTo(g, 6),
2441
+ roundTo(b, 6)
2442
+ ],
2443
+ hex: srgbToHex([
2444
+ r,
2445
+ g,
2446
+ b
2447
+ ])
2448
+ };
2449
+ if (alpha !== void 0) value.alpha = alpha;
2450
+ return value;
2451
+ }
2452
+ function dtcgToken(v, colorSpace, pastel) {
2453
+ return {
2454
+ $type: "color",
2455
+ $value: dtcgColorValue(v, colorSpace, pastel)
2456
+ };
2457
+ }
2458
+ /**
2459
+ * Build a `GlazeDtcgResult`: one spec-conformant DTCG token document per
2460
+ * scheme variant, gated by `modes`. Light is always present.
2461
+ */
2462
+ function buildDtcgMap(resolved, prefix, modes, colorSpace = "srgb", pastel = false) {
2463
+ const light = {};
2464
+ const dark = modes.dark ? {} : void 0;
2465
+ const lightContrast = modes.highContrast ? {} : void 0;
2466
+ const darkContrast = modes.dark && modes.highContrast ? {} : void 0;
2467
+ for (const [name, color] of resolved) {
2468
+ const key = `${prefix}${name}`;
2469
+ light[key] = dtcgToken(color.light, colorSpace, pastel);
2470
+ if (dark) dark[key] = dtcgToken(color.dark, colorSpace, pastel);
2471
+ if (lightContrast) lightContrast[key] = dtcgToken(color.lightContrast, colorSpace, pastel);
2472
+ if (darkContrast) darkContrast[key] = dtcgToken(color.darkContrast, colorSpace, pastel);
2473
+ }
2474
+ return {
2475
+ light,
2476
+ dark,
2477
+ lightContrast,
2478
+ darkContrast
2479
+ };
2480
+ }
2481
+ /**
2482
+ * Default context names emitted on the `scheme` modifier — the Glaze variant
2483
+ * keys, so the resolver document mirrors `GlazeDtcgResult` exactly.
2484
+ */
2485
+ const DEFAULT_DTCG_CONTEXT_NAMES = {
2486
+ light: "light",
2487
+ dark: "dark",
2488
+ lightContrast: "lightContrast",
2489
+ darkContrast: "darkContrast"
2490
+ };
2491
+ /**
2492
+ * Wrap a per-scheme `GlazeDtcgResult` into a single W3C DTCG Resolver-Module
2493
+ * document. The light document becomes `sets[setName].sources[0]` (the default
2494
+ * context); each other present variant becomes a `contexts[ctx]` override
2495
+ * array on a single `modifiers[modifierName]`. Absent variants (per the
2496
+ * `modes` already applied to `result`) are omitted — light is always present
2497
+ * and is the modifier `default`. Only the resolver-specific options are read;
2498
+ * `modes` / `colorSpace` were already consumed by the `buildDtcgMap` call that
2499
+ * produced `result`.
2500
+ */
2501
+ function buildDtcgResolver(result, options) {
2502
+ const setName = options?.setName ?? "base";
2503
+ const modifierName = options?.modifierName ?? "scheme";
2504
+ const ctx = {
2505
+ ...DEFAULT_DTCG_CONTEXT_NAMES,
2506
+ ...options?.contextNames
2507
+ };
2508
+ const contexts = { [ctx.light]: [] };
2509
+ if (result.dark) contexts[ctx.dark] = [result.dark];
2510
+ if (result.lightContrast) contexts[ctx.lightContrast] = [result.lightContrast];
2511
+ if (result.darkContrast) contexts[ctx.darkContrast] = [result.darkContrast];
2512
+ return {
2513
+ version: options?.version ?? "2025.10",
2514
+ sets: { [setName]: { sources: [result.light] } },
2515
+ modifiers: { [modifierName]: {
2516
+ default: ctx.light,
2517
+ contexts
2518
+ } },
2519
+ resolutionOrder: [{ $ref: `#/sets/${setName}` }, { $ref: `#/modifiers/${modifierName}` }]
2520
+ };
2521
+ }
2522
+ function tailwindLinesFor(resolved, themePrefix, cssPrefix, format, pastel) {
2523
+ const lines = {
2524
+ light: [],
2525
+ dark: [],
2526
+ lightContrast: [],
2527
+ darkContrast: []
2528
+ };
2529
+ for (const [name, color] of resolved) {
2530
+ const prop = `--${cssPrefix}${themePrefix}${name}`;
2531
+ lines.light.push(`${prop}: ${formatVariant(color.light, format, pastel)};`);
2532
+ lines.dark.push(`${prop}: ${formatVariant(color.dark, format, pastel)};`);
2533
+ lines.lightContrast.push(`${prop}: ${formatVariant(color.lightContrast, format, pastel)};`);
2534
+ lines.darkContrast.push(`${prop}: ${formatVariant(color.darkContrast, format, pastel)};`);
2535
+ }
2536
+ return lines;
2537
+ }
2538
+ function indentBlock(text, pad) {
2539
+ return text.split("\n").map((line) => line.length === 0 ? line : pad + line).join("\n");
2540
+ }
2541
+ function emitRule(selector, body) {
2542
+ return `${selector} {\n${indentBlock(body, " ")}\n}`;
2543
+ }
2544
+ /**
2545
+ * Emit a CSS block for a set of declarations scoped by one or more selectors
2546
+ * / at-rules. Class-like selectors concatenate (`.dark.high-contrast`);
2547
+ * at-rules (`@media …`) nest `:root` (or the chained selector) inside.
2548
+ */
2549
+ function emitScoped(scopes, declarations) {
2550
+ if (declarations.length === 0) return void 0;
2551
+ const atRules = [];
2552
+ let selectorChain = "";
2553
+ for (const scope of scopes) if (scope.startsWith("@")) atRules.push(scope);
2554
+ else selectorChain += scope;
2555
+ let css = emitRule(selectorChain || ":root", declarations.join("\n"));
2556
+ for (const rule of atRules) css = emitRule(rule, css);
2557
+ return css;
2558
+ }
2559
+ /**
2560
+ * Render accumulated per-scheme declaration lines as a Tailwind v4 CSS string:
2561
+ * an `@theme` block (light baseline) plus dark / high-contrast overrides under
2562
+ * the configured selectors. Empty blocks are skipped.
2563
+ */
2564
+ function emitTailwindCss(lines, modes, darkSelector, highContrastSelector) {
2565
+ const blocks = [];
2566
+ if (lines.light.length > 0) blocks.push(emitRule("@theme", lines.light.join("\n")));
2567
+ if (modes.dark) {
2568
+ const dark = emitScoped([darkSelector], lines.dark);
2569
+ if (dark) blocks.push(dark);
2570
+ }
2571
+ if (modes.highContrast) {
2572
+ const hc = emitScoped([highContrastSelector], lines.lightContrast);
2573
+ if (hc) blocks.push(hc);
2574
+ }
2575
+ if (modes.dark && modes.highContrast) {
2576
+ const dhc = emitScoped([darkSelector, highContrastSelector], lines.darkContrast);
2577
+ if (dhc) blocks.push(dhc);
2578
+ }
2579
+ return blocks.join("\n\n");
2580
+ }
2581
+ /**
2582
+ * Build per-scheme declaration lines for a single theme (used by
2583
+ * `theme.tailwind()` and as the palette `buildOne` step).
2584
+ */
2585
+ function buildTailwindLines(resolved, themePrefix, cssPrefix, format, pastel) {
2586
+ return tailwindLinesFor(resolved, themePrefix, cssPrefix, format, pastel);
2587
+ }
2588
+ /**
2589
+ * Build a complete Tailwind v4 CSS string for a single theme.
2590
+ */
2591
+ function buildTailwindMap(resolved, themePrefix, cssPrefix, modes, format, darkSelector, highContrastSelector, pastel = false) {
2592
+ return emitTailwindCss(tailwindLinesFor(resolved, themePrefix, cssPrefix, format, pastel), modes, darkSelector, highContrastSelector);
2593
+ }
2594
+
2595
+ //#endregion
2596
+ //#region src/color-token.ts
2597
+ /**
2598
+ * Standalone single-color tokens (`glaze.color()` / `glaze.colorFrom()`).
2599
+ *
2600
+ * Owns the value-shorthand parser (hex, `rgb()` / `hsl()` / `okhsl()` /
2601
+ * `okhst()` / `oklch()`, `{ r, g, b }`, `{ h, s, l }`, `{ h, s, t }`,
2602
+ * `{ l, c, h }`), the structured-input validator, the two factory paths
2603
+ * (value vs structured), and the JSON-safe export / rehydration round-trip.
2604
+ *
2605
+ * Standalone tokens snapshot the full effective config at create time
2606
+ * so later `configure()` calls do not retroactively change exported
2607
+ * tokens. The snapshot is built eagerly in
2608
+ * `buildValueFormConfigOverride()` / `buildStructuredConfigOverride()`.
2609
+ * The token's resolved variants are then memoized on first
2610
+ * `.resolve()` / `.token()` / ... call.
2611
+ */
2612
+ /** Internal name of the user-facing standalone color in the synthesized def map. */
2613
+ const STANDALONE_VALUE = "value";
2614
+ /** Internal name of the hidden static-anchor seed used for relative tone / contrast. */
2615
+ const STANDALONE_SEED = "seed";
2616
+ /** Internal name of an externally-resolved `GlazeColorToken` injected as a base reference. */
2617
+ const STANDALONE_BASE = "externalBase";
2618
+ /** Reserved internal names that user-supplied `name` must not collide with. */
2619
+ const RESERVED_STANDALONE_NAMES = new Set([
2620
+ STANDALONE_VALUE,
2621
+ STANDALONE_SEED,
2622
+ STANDALONE_BASE
2623
+ ]);
2624
+ /**
2625
+ * Build the per-token effective config override for a value-form color.
2626
+ *
2627
+ * Light window defaults to `false` (preserve input tone exactly).
2628
+ * All other fields snapshot from global at create time. User override
2629
+ * fields win over all defaults.
2630
+ */
2631
+ function buildValueFormConfigOverride(userOverride) {
2632
+ const cfg = getConfig();
2633
+ return {
2634
+ lightTone: userOverride?.lightTone !== void 0 ? userOverride.lightTone : false,
2635
+ darkTone: userOverride?.darkTone !== void 0 ? userOverride.darkTone : cfg.darkTone,
2636
+ darkDesaturation: userOverride?.darkDesaturation ?? cfg.darkDesaturation,
2637
+ autoFlip: userOverride?.autoFlip ?? cfg.autoFlip,
2638
+ shadowTuning: userOverride?.shadowTuning ?? cfg.shadowTuning
2639
+ };
2640
+ }
2641
+ /**
2642
+ * Build the per-token effective config override for a structured-form color.
2643
+ *
2644
+ * Both light and dark windows snapshot from global at create time.
2645
+ * User override fields win.
2646
+ */
2647
+ function buildStructuredConfigOverride(userOverride) {
2648
+ const cfg = getConfig();
2649
+ return {
2650
+ lightTone: userOverride?.lightTone !== void 0 ? userOverride.lightTone : cfg.lightTone,
2651
+ darkTone: userOverride?.darkTone !== void 0 ? userOverride.darkTone : cfg.darkTone,
2652
+ darkDesaturation: userOverride?.darkDesaturation ?? cfg.darkDesaturation,
2653
+ autoFlip: userOverride?.autoFlip ?? cfg.autoFlip,
2654
+ shadowTuning: userOverride?.shadowTuning ?? cfg.shadowTuning
2655
+ };
2656
+ }
2657
+ /**
2658
+ * Build the `GlazeConfigResolved` to pass to `resolveAllColors` from a
2659
+ * snapshot override. Uses `defaultConfig()` as the base so all required
2660
+ * fields are present; the snapshot fields win.
2661
+ */
2662
+ function resolvedConfigFromOverride(override) {
2663
+ return mergeConfig(defaultConfig(), override);
2664
+ }
2665
+ /**
2666
+ * Matches the CSS color functions Glaze itself emits (`rgb()`, `hsl()`,
2667
+ * `okhsl()`, `oklch()`) plus their legacy alpha aliases (`rgba()`, `hsla()`).
2668
+ *
2669
+ * Only bare numeric components are supported. Named colors (`red`),
2670
+ * relative-color syntax (`from <color> ...`), and angle units other
2671
+ * than bare degrees (`deg` is the only suffix tolerated by `parseFloat`)
2672
+ * are out of scope.
2673
+ */
2674
+ const COLOR_FN_RE = /^(rgba?|hsla?|okhsl|okhst|oklch)\(\s*([^)]*)\s*\)$/i;
2675
+ function parseNumberOrPercent(raw, percentScale) {
2676
+ if (raw.endsWith("%")) return parseFloat(raw) / 100 * percentScale;
2677
+ return parseFloat(raw);
2678
+ }
2679
+ /**
2680
+ * Split the body of a CSS color function into its components and detect
2681
+ * whether an alpha channel was present.
2682
+ *
2683
+ * Handles both modern slash syntax (`R G B / A` or `R, G, B / A`) and
2684
+ * legacy comma syntax (`R, G, B, A`). The alpha value itself is discarded
2685
+ * by the caller — standalone Glaze colors have no opacity field.
2686
+ */
2687
+ function splitColorBody(body) {
2688
+ const slashIdx = body.indexOf("/");
2689
+ if (slashIdx !== -1) return {
2690
+ components: body.slice(0, slashIdx).trim().split(/[\s,]+/).filter(Boolean),
2691
+ hadAlpha: body.slice(slashIdx + 1).trim().length > 0
2692
+ };
2693
+ const components = body.split(/[\s,]+/).filter(Boolean);
2694
+ if (components.length === 4) {
2695
+ components.pop();
2696
+ return {
2697
+ components,
2698
+ hadAlpha: true
2699
+ };
2700
+ }
2701
+ return {
2702
+ components,
2703
+ hadAlpha: false
2704
+ };
2705
+ }
2706
+ function warnDroppedAlpha(input) {
2707
+ console.warn(`glaze: alpha component dropped from "${input}" (standalone color has no opacity field).`);
2708
+ }
2709
+ function parseColorString(input) {
2710
+ if (input.startsWith("#")) {
2711
+ const parsed = parseHexAlpha(input);
2712
+ if (!parsed) throw new Error(`glaze: invalid hex color "${input}".`);
2713
+ if (parsed.alpha !== void 0) warnDroppedAlpha(input);
2714
+ const [h, s, l] = srgbToOkhsl(parsed.rgb);
2715
+ return {
2716
+ h,
2717
+ s,
2718
+ l
2719
+ };
2720
+ }
2721
+ const m = input.match(COLOR_FN_RE);
2722
+ if (!m) throw new Error(`glaze: unsupported color string "${input}".`);
2723
+ const fn = m[1].toLowerCase();
2724
+ const { components, hadAlpha } = splitColorBody(m[2].trim());
2725
+ if (hadAlpha) warnDroppedAlpha(input);
2726
+ if (components.length !== 3) throw new Error(`glaze: expected 3 components in "${input}".`);
2727
+ switch (fn) {
2728
+ case "rgb":
2729
+ case "rgba": {
2730
+ const [h, s, l] = srgbToOkhsl([
2731
+ parseNumberOrPercent(components[0], 255) / 255,
2732
+ parseNumberOrPercent(components[1], 255) / 255,
2733
+ parseNumberOrPercent(components[2], 255) / 255
2734
+ ]);
2735
+ return {
2736
+ h,
2737
+ s,
2738
+ l
2739
+ };
2740
+ }
2741
+ case "hsl":
2742
+ case "hsla": {
2743
+ const [oh, os, ol] = srgbToOkhsl(hslToSrgb(parseFloat(components[0]), parseNumberOrPercent(components[1], 1), parseNumberOrPercent(components[2], 1)));
2744
+ return {
2745
+ h: oh,
2746
+ s: os,
2747
+ l: ol
2748
+ };
2749
+ }
2750
+ case "okhsl": return {
2751
+ h: parseFloat(components[0]),
2752
+ s: parseNumberOrPercent(components[1], 1),
2753
+ l: parseNumberOrPercent(components[2], 1)
2754
+ };
2755
+ case "okhst": return okhstToOkhsl({
2756
+ h: parseFloat(components[0]),
2757
+ s: parseNumberOrPercent(components[1], 1),
2758
+ t: parseNumberOrPercent(components[2], 1)
2759
+ });
2760
+ case "oklch": {
2761
+ const L = parseNumberOrPercent(components[0], 1);
2762
+ const C = parseNumberOrPercent(components[1], .4);
2763
+ const hRad = parseFloat(components[2]) * Math.PI / 180;
2764
+ const [h, s, l] = oklabToOkhsl([
2765
+ L,
2766
+ C * Math.cos(hRad),
2767
+ C * Math.sin(hRad)
2768
+ ]);
2769
+ return {
2770
+ h,
2771
+ s,
2772
+ l
2773
+ };
2774
+ }
2775
+ }
2776
+ throw new Error(`glaze: unsupported color function "${fn}".`);
2777
+ }
2778
+ /**
2779
+ * Validate a user-supplied `OkhslColor`. Catches the common 0-100 vs 0-1
2780
+ * confusion (the structured form uses 0-100, OKHSL objects use 0-1).
2781
+ */
2782
+ function validateOkhslColor(value) {
2783
+ const { h, s, l } = value;
2784
+ if (!Number.isFinite(h) || !Number.isFinite(s) || !Number.isFinite(l)) throw new Error("glaze.color: OkhslColor h/s/l must be finite numbers.");
2785
+ if (s > 1.5 || l > 1.5) throw new Error("glaze.color: OkhslColor s/l must be in 0–1 range. Did you mean the structured form { hue, saturation, tone } (which uses 0–100)?");
2786
+ }
2787
+ /** Validate a user-supplied `{ r, g, b }` object in 0–255. */
2788
+ function validateRgbColor(value) {
2789
+ for (const key of [
2790
+ "r",
2791
+ "g",
2792
+ "b"
2793
+ ]) {
2794
+ const n = value[key];
2795
+ if (!Number.isFinite(n) || n < 0 || n > 255) throw new Error(`glaze.color: RgbColor ${key} must be a finite number in 0–255 (got ${n}).`);
2796
+ }
2797
+ }
2798
+ /** Validate a user-supplied `{ l, c, h }` OKLCh object. */
2799
+ function validateOklchColor(value) {
2800
+ const { l, c, h } = value;
2801
+ if (!Number.isFinite(l) || !Number.isFinite(c) || !Number.isFinite(h)) throw new Error("glaze.color: OklchColor l/c/h must be finite numbers.");
2802
+ if (l > 1.5 || c > 1.5) throw new Error("glaze.color: OklchColor l/c must be in 0–1 range (matching oklch() strings).");
2803
+ }
2804
+ function oklchComponentsToOkhsl(l, c, hDeg) {
2805
+ const hRad = hDeg * Math.PI / 180;
2806
+ const [h, s, outL] = oklabToOkhsl([
2807
+ l,
2808
+ c * Math.cos(hRad),
2809
+ c * Math.sin(hRad)
2810
+ ]);
2811
+ return {
2812
+ h,
2813
+ s,
2814
+ l: outL
2815
+ };
2816
+ }
2817
+ function isRgbColorObject(value) {
2818
+ return "r" in value && "g" in value && "b" in value;
2819
+ }
2820
+ function isOklchColorObject(value) {
2821
+ return "c" in value && "l" in value && "h" in value;
2822
+ }
2823
+ function isOkhstColorObject(value) {
2824
+ return "t" in value && "h" in value && "s" in value;
2825
+ }
2826
+ /** Validate a user-supplied `{ h, s, t }` OKHST object (s/t in 0–1). */
2827
+ function validateOkhstColor(value) {
2828
+ const { h, s, t } = value;
2829
+ if (!Number.isFinite(h) || !Number.isFinite(s) || !Number.isFinite(t)) throw new Error("glaze.color: OkhstColor h/s/t must be finite numbers.");
2830
+ if (s > 1.5 || t > 1.5) throw new Error("glaze.color: OkhstColor s/t must be in 0–1 range. Did you mean the structured form { hue, saturation, tone } (which uses 0–100)?");
2831
+ }
2832
+ /**
2833
+ * Validate a user-supplied `opacity` override on `glaze.color()`.
2834
+ * Must be a finite number in `0..=1`.
2835
+ */
2836
+ function validateStandaloneOpacity(value) {
2837
+ if (!Number.isFinite(value) || value < 0 || value > 1) throw new Error(`glaze.color: opacity must be a finite number in 0–1 (got ${value}).`);
2838
+ }
2839
+ /**
2840
+ * Validate a structured `GlazeColorInput`. Range-checks the `hue` /
2841
+ * `saturation` / `tone` numerics (and any HC-pair second value)
2842
+ * before the resolver sees them so out-of-range or non-finite inputs
2843
+ * fail with a helpful, top-level error rather than producing a
2844
+ * NaN-laden token. `opacity` is checked here too so all input
2845
+ * validation lives in one place.
2846
+ */
2847
+ function validateStructuredInput(input) {
2848
+ if (!Number.isFinite(input.hue)) throw new Error(`glaze.color: structured hue must be a finite number (got ${input.hue}).`);
2849
+ if (!Number.isFinite(input.saturation) || input.saturation < 0 || input.saturation > 100) throw new Error(`glaze.color: structured saturation must be a finite number in 0–100 (got ${input.saturation}).`);
2850
+ const checkTone = (value, label) => {
2851
+ if (value === "max" || value === "min") return;
2852
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 100) throw new Error(`glaze.color: structured ${label} must be a finite number in 0–100 or 'max'/'min' (got ${String(value)}).`);
2853
+ };
2854
+ if (Array.isArray(input.tone)) {
2855
+ checkTone(input.tone[0], "tone[normal]");
2856
+ checkTone(input.tone[1], "tone[hc]");
2857
+ } else checkTone(input.tone, "tone");
2858
+ if (input.saturationFactor !== void 0) {
2859
+ if (!Number.isFinite(input.saturationFactor) || input.saturationFactor < 0 || input.saturationFactor > 1) throw new Error(`glaze.color: structured saturationFactor must be a finite number in 0–1 (got ${input.saturationFactor}).`);
2860
+ }
2861
+ if (input.opacity !== void 0) validateStandaloneOpacity(input.opacity);
2862
+ }
2863
+ /**
2864
+ * Validate a user-supplied `name` override. Rejects empty / whitespace-only
2865
+ * strings and names colliding with `glaze`'s reserved internal sentinels.
2866
+ */
2867
+ function validateStandaloneName(name) {
2868
+ if (typeof name !== "string" || name.trim() === "") throw new Error("glaze.color: name must be a non-empty string. Omit `name` if you do not want to set a debug label.");
2869
+ if (RESERVED_STANDALONE_NAMES.has(name)) {
2870
+ const reserved = [...RESERVED_STANDALONE_NAMES].map((n) => `"${n}"`).join(", ");
2871
+ throw new Error(`glaze.color: name "${name}" is reserved (used internally). Reserved names are: ${reserved}. Pick a different name.`);
2872
+ }
2873
+ }
2874
+ /**
2875
+ * Extract an OKHSL color from any `GlazeColorValue` form. Also used by
2876
+ * `glaze.shadow()` so all shadow inputs (hex, color functions, OKHSL,
2877
+ * literal objects) go through one parser.
2878
+ */
2879
+ function extractOkhslFromValue(value) {
2880
+ if (typeof value === "string") return parseColorString(value);
2881
+ if (Array.isArray(value)) throw new Error("glaze.color: RGB tuple [r, g, b] is no longer supported — use { r, g, b } instead.");
2882
+ if (isRgbColorObject(value)) {
2883
+ validateRgbColor(value);
2884
+ const [h, s, l] = srgbToOkhsl([
2885
+ value.r / 255,
2886
+ value.g / 255,
2887
+ value.b / 255
2888
+ ]);
2889
+ return {
2890
+ h,
2891
+ s,
2892
+ l
2893
+ };
2894
+ }
2895
+ if (isOklchColorObject(value)) {
2896
+ validateOklchColor(value);
2897
+ return oklchComponentsToOkhsl(value.l, value.c, value.h);
2898
+ }
2899
+ if (isOkhstColorObject(value)) {
2900
+ validateOkhstColor(value);
2901
+ return okhstToOkhsl(value);
2902
+ }
2903
+ validateOkhslColor(value);
2904
+ return value;
2905
+ }
2906
+ /**
2907
+ * Build the `ColorMap` for a value-shorthand `glaze.color()` call.
2908
+ *
2909
+ * The user-facing color (`STANDALONE_VALUE`) defaults to `mode: 'auto'`
2910
+ * across every value-shorthand form.
2911
+ *
2912
+ * When the user requests `contrast` or relative `tone`, a hidden
2913
+ * `STANDALONE_SEED` def is synthesized at `mode: 'static'`. That keeps
2914
+ * the seed pinned to the literal user-provided color across all four
2915
+ * variants, so the contrast solver always anchors against it.
2916
+ */
2917
+ function buildStandaloneValueDefs(main, options) {
2918
+ const seedHue = typeof options?.hue === "number" ? options.hue : main.h;
2919
+ const seedSaturation = options?.saturation ?? main.s * 100;
2920
+ const relativeHue = typeof options?.hue === "string" ? options.hue : void 0;
2921
+ const toneOption = options?.tone;
2922
+ const hasExternalBase = options?.base !== void 0;
2923
+ const needsSeedAnchor = !hasExternalBase && (options?.contrast !== void 0 || toneOption !== void 0 && !isAbsoluteTone(toneOption));
2924
+ if (options?.opacity !== void 0) validateStandaloneOpacity(options.opacity);
2925
+ const userName = options?.name;
2926
+ if (userName !== void 0) validateStandaloneName(userName);
2927
+ const primary = userName ?? STANDALONE_VALUE;
2928
+ const seedTone = toTone(main.l);
2929
+ const valueDef = {
2930
+ hue: relativeHue,
2931
+ saturation: options?.saturationFactor,
2932
+ tone: toneOption ?? seedTone,
2933
+ contrast: options?.contrast,
2934
+ mode: options?.mode ?? "auto",
2935
+ flip: options?.flip,
2936
+ opacity: options?.opacity,
2937
+ pastel: options?.pastel,
2938
+ role: options?.role,
2939
+ base: hasExternalBase ? STANDALONE_BASE : needsSeedAnchor ? STANDALONE_SEED : void 0
2940
+ };
2941
+ const defs = { [primary]: valueDef };
2942
+ if (needsSeedAnchor) defs[STANDALONE_SEED] = {
2943
+ hue: main.h,
2944
+ saturation: 1,
2945
+ tone: seedTone,
2946
+ mode: "static"
2947
+ };
2948
+ return {
2949
+ seedHue,
2950
+ seedSaturation,
2951
+ defs,
2952
+ primary
2953
+ };
2954
+ }
2955
+ function createColorTokenFromDefs(seedHue, seedSaturation, defs, primary, effectiveConfig, baseToken, exportData) {
2956
+ let cached;
2957
+ const resolveOnce = () => {
2958
+ if (cached) return cached;
2959
+ cached = resolveAllColors(seedHue, seedSaturation, defs, effectiveConfig, baseToken ? new Map([[STANDALONE_BASE, baseToken.resolve()]]) : void 0);
2960
+ return cached;
2961
+ };
2962
+ const resolveStates = (options) => {
2963
+ const cfg = getConfig();
2964
+ return {
2965
+ dark: options?.states?.dark ?? cfg.states.dark,
2966
+ highContrast: options?.states?.highContrast ?? cfg.states.highContrast
2967
+ };
2968
+ };
2969
+ const tokenLike = (options) => {
2970
+ return buildTokenMap(resolveOnce(), "", resolveStates(options), resolveModes(options?.modes), options?.format, effectiveConfig.pastel)[`#${primary}`];
2971
+ };
1380
2972
  return {
1381
- get hue() {
1382
- return hue;
1383
- },
1384
- get saturation() {
1385
- return saturation;
1386
- },
1387
- colors(defs) {
1388
- colorDefs = {
1389
- ...colorDefs,
1390
- ...defs
1391
- };
1392
- },
1393
- color(name, def) {
1394
- if (def === void 0) return colorDefs[name];
1395
- colorDefs[name] = def;
1396
- },
1397
- remove(names) {
1398
- const list = Array.isArray(names) ? names : [names];
1399
- for (const name of list) delete colorDefs[name];
1400
- },
1401
- has(name) {
1402
- return name in colorDefs;
1403
- },
1404
- list() {
1405
- return Object.keys(colorDefs);
1406
- },
1407
- reset() {
1408
- colorDefs = {};
1409
- },
1410
- export() {
1411
- return {
1412
- hue,
1413
- saturation,
1414
- colors: { ...colorDefs }
1415
- };
2973
+ resolve() {
2974
+ return resolveOnce().get(primary);
1416
2975
  },
1417
- extend(options) {
1418
- return createTheme(options.hue ?? hue, options.saturation ?? saturation, options.colors ? {
1419
- ...colorDefs,
1420
- ...options.colors
1421
- } : { ...colorDefs });
2976
+ token: tokenLike,
2977
+ tasty: tokenLike,
2978
+ json(options) {
2979
+ const format = options?.format ?? "oklch";
2980
+ assertNativeFormat(format, "json");
2981
+ return buildJsonMap(resolveOnce(), resolveModes(options?.modes), format, effectiveConfig.pastel)[primary];
1422
2982
  },
1423
- resolve() {
1424
- return resolveAllColors(hue, saturation, colorDefs);
2983
+ css(options) {
2984
+ const format = options.format ?? "rgb";
2985
+ assertNativeFormat(format, "css");
2986
+ const resolved = resolveOnce().get(primary);
2987
+ const renamed = new Map([[options.name, resolved]]);
2988
+ let channelCtx;
2989
+ if (options.splitHue && format === "oklch") {
2990
+ assertAllPastel(renamed, resolveModes());
2991
+ channelCtx = {
2992
+ seedHue,
2993
+ baseName: options.name,
2994
+ prefix: "",
2995
+ defs: { [options.name]: defs[primary] },
2996
+ mode: "standalone",
2997
+ resolvedHue: resolved.light.h
2998
+ };
2999
+ }
3000
+ return buildCssMap(renamed, "", options.suffix ?? "-color", format, effectiveConfig.pastel, channelCtx);
1425
3001
  },
1426
- tokens(options) {
1427
- return buildFlatTokenMap(resolveAllColors(hue, saturation, colorDefs), "", resolveModes(options?.modes), options?.format);
3002
+ dtcg(options) {
3003
+ const modes = resolveModes(options?.modes);
3004
+ const doc = buildDtcgMap(resolveOnce(), "", modes, options?.colorSpace ?? "srgb", effectiveConfig.pastel);
3005
+ const result = { light: doc.light[primary] };
3006
+ if (doc.dark) result.dark = doc.dark[primary];
3007
+ if (doc.lightContrast) result.lightContrast = doc.lightContrast[primary];
3008
+ if (doc.darkContrast) result.darkContrast = doc.darkContrast[primary];
3009
+ return result;
1428
3010
  },
1429
- tasty(options) {
1430
- return buildTokenMap(resolveAllColors(hue, saturation, colorDefs), "", {
1431
- dark: options?.states?.dark ?? globalConfig.states.dark,
1432
- highContrast: options?.states?.highContrast ?? globalConfig.states.highContrast
1433
- }, resolveModes(options?.modes), options?.format);
3011
+ dtcgResolver(options) {
3012
+ const doc = buildDtcgMap(resolveOnce(), "", resolveModes(options?.modes), options?.colorSpace ?? "srgb", effectiveConfig.pastel);
3013
+ const name = options.name;
3014
+ const result = { light: { [name]: doc.light[primary] } };
3015
+ if (doc.dark) result.dark = { [name]: doc.dark[primary] };
3016
+ if (doc.lightContrast) result.lightContrast = { [name]: doc.lightContrast[primary] };
3017
+ if (doc.darkContrast) result.darkContrast = { [name]: doc.darkContrast[primary] };
3018
+ return buildDtcgResolver(result, options);
1434
3019
  },
1435
- json(options) {
1436
- return buildJsonMap(resolveAllColors(hue, saturation, colorDefs), resolveModes(options?.modes), options?.format);
3020
+ tailwind(options) {
3021
+ const format = options.format ?? "oklch";
3022
+ assertNativeFormat(format, "tailwind");
3023
+ return buildTailwindMap(new Map([[options.name, resolveOnce().get(primary)]]), "", options.namespace ?? "color-", resolveModes(options?.modes), format, options.darkSelector ?? ".dark", options.highContrastSelector ?? ".high-contrast", effectiveConfig.pastel);
1437
3024
  },
1438
- css(options) {
1439
- return buildCssMap(resolveAllColors(hue, saturation, colorDefs), "", options?.suffix ?? "-color", options?.format ?? "rgb");
1440
- }
3025
+ export: exportData
3026
+ };
3027
+ }
3028
+ /**
3029
+ * When a value/`from` color links to a base that was created via the
3030
+ * structured form (with explicit `hue`/`saturation`/`tone`), resolve
3031
+ * that base with `lightTone: false` for the linking math so the
3032
+ * contrast/tone anchor matches the input tone — not the
3033
+ * windowed output. The original base token's `.resolve()` is unaffected.
3034
+ */
3035
+ function toLinkingBase(base) {
3036
+ if (!base) return void 0;
3037
+ const exp = base.export();
3038
+ if (exp.form !== "structured") return base;
3039
+ const linkingConfig = {
3040
+ ...exp.config ?? {},
3041
+ lightTone: false
3042
+ };
3043
+ return colorFromExport({
3044
+ ...exp,
3045
+ config: linkingConfig
3046
+ });
3047
+ }
3048
+ /**
3049
+ * Resolve `base` (which may be a token reference or a raw color value)
3050
+ * into a `GlazeColorToken`. Raw values are auto-wrapped via
3051
+ * `createColorTokenFromValue` so they pick up the same auto-invert
3052
+ * defaults as an explicit wrap. Returns `undefined` when no base is provided.
3053
+ */
3054
+ function resolveBaseToken(base) {
3055
+ if (base === void 0) return void 0;
3056
+ if (isGlazeColorToken(base)) return base;
3057
+ return createColorTokenFromValue(base, void 0, void 0);
3058
+ }
3059
+ /**
3060
+ * Discriminate a `GlazeColorToken` from a raw `GlazeColorValue`.
3061
+ */
3062
+ function isGlazeColorToken(candidate) {
3063
+ return typeof candidate === "object" && candidate !== null && !Array.isArray(candidate) && "resolve" in candidate && typeof candidate.resolve === "function";
3064
+ }
3065
+ function createColorToken(input, configOverride) {
3066
+ validateStructuredInput(input);
3067
+ const userName = input.name;
3068
+ if (userName !== void 0) validateStandaloneName(userName);
3069
+ const primary = userName ?? STANDALONE_VALUE;
3070
+ const baseToken = resolveBaseToken(input.base);
3071
+ const hasExternalBase = baseToken !== void 0;
3072
+ const needsSeedAnchor = !hasExternalBase && input.contrast !== void 0;
3073
+ const defs = { [primary]: {
3074
+ tone: input.tone,
3075
+ saturation: input.saturationFactor,
3076
+ mode: input.mode ?? "auto",
3077
+ flip: input.flip,
3078
+ contrast: input.contrast,
3079
+ opacity: input.opacity,
3080
+ pastel: input.pastel,
3081
+ role: input.role,
3082
+ base: hasExternalBase ? STANDALONE_BASE : needsSeedAnchor ? STANDALONE_SEED : void 0
3083
+ } };
3084
+ if (needsSeedAnchor) {
3085
+ const seedTone = pairNormal(input.tone);
3086
+ defs[STANDALONE_SEED] = {
3087
+ tone: seedTone === "max" ? 100 : seedTone === "min" ? 0 : seedTone,
3088
+ saturation: 1,
3089
+ mode: "static"
3090
+ };
3091
+ }
3092
+ const effectiveConfigOverride = buildStructuredConfigOverride(configOverride);
3093
+ const effectiveConfig = resolvedConfigFromOverride(effectiveConfigOverride);
3094
+ const exportData = () => ({
3095
+ form: "structured",
3096
+ input: buildStructuredInputExport(input),
3097
+ config: effectiveConfigOverride
3098
+ });
3099
+ return createColorTokenFromDefs(input.hue, input.saturation, defs, primary, effectiveConfig, baseToken, exportData);
3100
+ }
3101
+ function createColorTokenFromValue(value, options, configOverride) {
3102
+ const main = extractOkhslFromValue(value);
3103
+ const linkingBase = toLinkingBase(resolveBaseToken(options?.base));
3104
+ const { seedHue, seedSaturation, defs, primary } = buildStandaloneValueDefs(main, options);
3105
+ const effectiveConfigOverride = buildValueFormConfigOverride(configOverride);
3106
+ const effectiveConfig = resolvedConfigFromOverride(effectiveConfigOverride);
3107
+ const exportData = () => ({
3108
+ form: "value",
3109
+ input: value,
3110
+ ...options !== void 0 ? { overrides: buildOverridesExport(options) } : {},
3111
+ config: effectiveConfigOverride
3112
+ });
3113
+ return createColorTokenFromDefs(seedHue, seedSaturation, defs, primary, effectiveConfig, linkingBase, exportData);
3114
+ }
3115
+ /**
3116
+ * Build a JSON-safe snapshot of `GlazeColorOverrides`. `base` is
3117
+ * recursively serialized when it was originally a token; raw values are
3118
+ * preserved as-is so `glaze.colorFrom(...)` round-trips them.
3119
+ */
3120
+ function buildOverridesExport(options) {
3121
+ const out = {};
3122
+ if (options.hue !== void 0) out.hue = options.hue;
3123
+ if (options.saturation !== void 0) out.saturation = options.saturation;
3124
+ if (options.tone !== void 0) out.tone = options.tone;
3125
+ if (options.saturationFactor !== void 0) out.saturationFactor = options.saturationFactor;
3126
+ if (options.mode !== void 0) out.mode = options.mode;
3127
+ if (options.flip !== void 0) out.flip = options.flip;
3128
+ if (options.contrast !== void 0) out.contrast = options.contrast;
3129
+ if (options.opacity !== void 0) out.opacity = options.opacity;
3130
+ if (options.name !== void 0) out.name = options.name;
3131
+ if (options.pastel !== void 0) out.pastel = options.pastel;
3132
+ if (options.role !== void 0) out.role = options.role;
3133
+ if (options.base !== void 0) out.base = isGlazeColorToken(options.base) ? options.base.export() : options.base;
3134
+ return out;
3135
+ }
3136
+ function buildStructuredInputExport(input) {
3137
+ const out = {
3138
+ hue: input.hue,
3139
+ saturation: input.saturation,
3140
+ tone: input.tone
1441
3141
  };
3142
+ if (input.saturationFactor !== void 0) out.saturationFactor = input.saturationFactor;
3143
+ if (input.mode !== void 0) out.mode = input.mode;
3144
+ if (input.flip !== void 0) out.flip = input.flip;
3145
+ if (input.opacity !== void 0) out.opacity = input.opacity;
3146
+ if (input.contrast !== void 0) out.contrast = input.contrast;
3147
+ if (input.name !== void 0) out.name = input.name;
3148
+ if (input.pastel !== void 0) out.pastel = input.pastel;
3149
+ if (input.role !== void 0) out.role = input.role;
3150
+ if (input.base !== void 0) out.base = isGlazeColorToken(input.base) ? input.base.export() : input.base;
3151
+ return out;
3152
+ }
3153
+ /**
3154
+ * Discriminate a `GlazeColorTokenExport` from a raw `GlazeColorValue`.
3155
+ */
3156
+ function isExportedToken(candidate) {
3157
+ return typeof candidate === "object" && candidate !== null && !Array.isArray(candidate) && "form" in candidate && (candidate.form === "value" || candidate.form === "structured");
3158
+ }
3159
+ function rehydrateOverrides(data) {
3160
+ const out = {};
3161
+ if (data.hue !== void 0) out.hue = data.hue;
3162
+ if (data.saturation !== void 0) out.saturation = data.saturation;
3163
+ if (data.tone !== void 0) out.tone = data.tone;
3164
+ if (data.saturationFactor !== void 0) out.saturationFactor = data.saturationFactor;
3165
+ if (data.mode !== void 0) out.mode = data.mode;
3166
+ if (data.flip !== void 0) out.flip = data.flip;
3167
+ if (data.contrast !== void 0) out.contrast = data.contrast;
3168
+ if (data.opacity !== void 0) out.opacity = data.opacity;
3169
+ if (data.name !== void 0) out.name = data.name;
3170
+ if (data.pastel !== void 0) out.pastel = data.pastel;
3171
+ if (data.role !== void 0) out.role = data.role;
3172
+ if (data.base !== void 0) out.base = isExportedToken(data.base) ? colorFromExport(data.base) : data.base;
3173
+ return out;
3174
+ }
3175
+ function rehydrateStructuredInput(data) {
3176
+ const out = {
3177
+ hue: data.hue,
3178
+ saturation: data.saturation,
3179
+ tone: data.tone
3180
+ };
3181
+ if (data.saturationFactor !== void 0) out.saturationFactor = data.saturationFactor;
3182
+ if (data.mode !== void 0) out.mode = data.mode;
3183
+ if (data.flip !== void 0) out.flip = data.flip;
3184
+ if (data.opacity !== void 0) out.opacity = data.opacity;
3185
+ if (data.contrast !== void 0) out.contrast = data.contrast;
3186
+ if (data.name !== void 0) out.name = data.name;
3187
+ if (data.pastel !== void 0) out.pastel = data.pastel;
3188
+ if (data.role !== void 0) out.role = data.role;
3189
+ if (data.base !== void 0) out.base = isExportedToken(data.base) ? colorFromExport(data.base) : data.base;
3190
+ return out;
3191
+ }
3192
+ /**
3193
+ * Rehydrate a token from its `.export()` snapshot. Recursively rebuilds
3194
+ * any base dependency. Inverse of `GlazeColorToken.export()`.
3195
+ *
3196
+ * The stored `config` field contains the full effective config override
3197
+ * snapshotted at creation time, so the rehydrated token is deterministic
3198
+ * regardless of subsequent `glaze.configure()` calls.
3199
+ */
3200
+ function colorFromExport(data) {
3201
+ if (data === null || typeof data !== "object") throw new Error(`glaze.colorFrom: expected an object from token.export(), got ${data === null ? "null" : typeof data}.`);
3202
+ if (data.form !== "value" && data.form !== "structured") throw new Error(`glaze.colorFrom: invalid "form" field — expected "value" or "structured" (got ${JSON.stringify(data.form)}).`);
3203
+ if (data.input === void 0) throw new Error(`glaze.colorFrom: missing "input" field — expected the original ${data.form === "value" ? "GlazeColorValue" : "GlazeColorInput"}.`);
3204
+ if (data.form === "value") {
3205
+ const value = data.input;
3206
+ return createColorTokenFromValue(value, data.overrides ? rehydrateOverrides(data.overrides) : void 0, data.config);
3207
+ }
3208
+ return createColorToken(rehydrateStructuredInput(data.input), data.config);
1442
3209
  }
3210
+
3211
+ //#endregion
3212
+ //#region src/palette.ts
1443
3213
  function resolvePrefix(options, themeName, defaultPrefix = false) {
1444
3214
  const prefix = options?.prefix ?? defaultPrefix;
1445
3215
  if (prefix === true) return `${themeName}-`;
@@ -1479,212 +3249,424 @@ function filterCollisions(resolved, prefix, seen, themeName, isPrimary) {
1479
3249
  }
1480
3250
  return filtered;
1481
3251
  }
3252
+ function colorMapFromTheme(theme) {
3253
+ const defs = {};
3254
+ for (const name of theme.list()) {
3255
+ const def = theme.color(name);
3256
+ if (def !== void 0) defs[name] = def;
3257
+ }
3258
+ return defs;
3259
+ }
3260
+ function channelCtxForTheme(theme, themeName, passPrefix, themedPrefix, splitHue, format, modes, filtered) {
3261
+ if (!splitHue || format !== "oklch") return void 0;
3262
+ assertAllPastel(filtered, modes);
3263
+ return {
3264
+ seedHue: theme.hue,
3265
+ baseName: themeName,
3266
+ prefix: themedPrefix,
3267
+ defs: colorMapFromTheme(theme),
3268
+ mode: "theme",
3269
+ emitDeclarations: passPrefix === themedPrefix
3270
+ };
3271
+ }
3272
+ /**
3273
+ * Shared per-theme driver for `tokens` / `tasty` / `css`. `json` skips
3274
+ * this because it doesn't do collision filtering or primary duplication.
3275
+ */
3276
+ function buildPaletteOutput(themes, paletteOptions, options, buildOne, merge, empty) {
3277
+ const effectivePrimary = resolveEffectivePrimary(options?.primary, paletteOptions?.primary);
3278
+ if (options?.primary !== void 0) validatePrimaryTheme(effectivePrimary, themes);
3279
+ const acc = empty();
3280
+ const seen = /* @__PURE__ */ new Map();
3281
+ for (const [themeName, theme] of Object.entries(themes)) {
3282
+ const resolved = theme.resolve();
3283
+ const pastel = theme.getConfig().pastel;
3284
+ const prefix = resolvePrefix(options, themeName, true);
3285
+ merge(acc, buildOne(filterCollisions(resolved, prefix, seen, themeName), prefix, pastel, themeName, theme));
3286
+ if (themeName === effectivePrimary) merge(acc, buildOne(filterCollisions(resolved, "", seen, themeName, true), "", pastel, themeName, theme));
3287
+ }
3288
+ return acc;
3289
+ }
1482
3290
  function createPalette(themes, paletteOptions) {
1483
3291
  validatePrimaryTheme(paletteOptions?.primary, themes);
3292
+ const buildDtcgResult = (options) => {
3293
+ const modes = resolveModes(options?.modes);
3294
+ const colorSpace = options?.colorSpace ?? "srgb";
3295
+ return buildPaletteOutput(themes, paletteOptions, options, (filtered, prefix, pastel, _themeName, _theme) => buildDtcgMap(filtered, prefix, modes, colorSpace, pastel), (acc, part) => {
3296
+ Object.assign(acc.light, part.light);
3297
+ if (part.dark) acc.dark = Object.assign(acc.dark ?? {}, part.dark);
3298
+ if (part.lightContrast) acc.lightContrast = Object.assign(acc.lightContrast ?? {}, part.lightContrast);
3299
+ if (part.darkContrast) acc.darkContrast = Object.assign(acc.darkContrast ?? {}, part.darkContrast);
3300
+ }, () => ({ light: {} }));
3301
+ };
1484
3302
  return {
1485
3303
  tokens(options) {
1486
- const effectivePrimary = resolveEffectivePrimary(options?.primary, paletteOptions?.primary);
1487
- if (options?.primary !== void 0) validatePrimaryTheme(effectivePrimary, themes);
3304
+ const format = options?.format ?? "oklch";
3305
+ assertNativeFormat(format, "tokens");
1488
3306
  const modes = resolveModes(options?.modes);
1489
- const allTokens = {};
1490
- const seen = /* @__PURE__ */ new Map();
1491
- for (const [themeName, theme] of Object.entries(themes)) {
1492
- const resolved = theme.resolve();
1493
- const prefix = resolvePrefix(options, themeName, true);
1494
- const tokens = buildFlatTokenMap(filterCollisions(resolved, prefix, seen, themeName), prefix, modes, options?.format);
1495
- for (const variant of Object.keys(tokens)) {
1496
- if (!allTokens[variant]) allTokens[variant] = {};
1497
- Object.assign(allTokens[variant], tokens[variant]);
1498
- }
1499
- if (themeName === effectivePrimary) {
1500
- const unprefixed = buildFlatTokenMap(filterCollisions(resolved, "", seen, themeName, true), "", modes, options?.format);
1501
- for (const variant of Object.keys(unprefixed)) Object.assign(allTokens[variant], unprefixed[variant]);
3307
+ return buildPaletteOutput(themes, paletteOptions, options, (filtered, prefix, pastel) => buildFlatTokenMap(filtered, prefix, modes, format, pastel), (acc, part) => {
3308
+ for (const variant of Object.keys(part)) {
3309
+ if (!acc[variant]) acc[variant] = {};
3310
+ Object.assign(acc[variant], part[variant]);
1502
3311
  }
1503
- }
1504
- return allTokens;
3312
+ }, () => ({}));
1505
3313
  },
1506
3314
  tasty(options) {
1507
- const effectivePrimary = resolveEffectivePrimary(options?.primary, paletteOptions?.primary);
1508
- if (options?.primary !== void 0) validatePrimaryTheme(effectivePrimary, themes);
3315
+ const cfg = getConfig();
1509
3316
  const states = {
1510
- dark: options?.states?.dark ?? globalConfig.states.dark,
1511
- highContrast: options?.states?.highContrast ?? globalConfig.states.highContrast
3317
+ dark: options?.states?.dark ?? cfg.states.dark,
3318
+ highContrast: options?.states?.highContrast ?? cfg.states.highContrast
1512
3319
  };
1513
3320
  const modes = resolveModes(options?.modes);
1514
- const allTokens = {};
1515
- const seen = /* @__PURE__ */ new Map();
1516
- for (const [themeName, theme] of Object.entries(themes)) {
1517
- const resolved = theme.resolve();
1518
- const prefix = resolvePrefix(options, themeName, true);
1519
- const tokens = buildTokenMap(filterCollisions(resolved, prefix, seen, themeName), prefix, states, modes, options?.format);
1520
- Object.assign(allTokens, tokens);
1521
- if (themeName === effectivePrimary) {
1522
- const unprefixed = buildTokenMap(filterCollisions(resolved, "", seen, themeName, true), "", states, modes, options?.format);
1523
- Object.assign(allTokens, unprefixed);
1524
- }
1525
- }
1526
- return allTokens;
3321
+ const format = options?.format ?? "okhsl";
3322
+ return buildPaletteOutput(themes, paletteOptions, options, (filtered, prefix, pastel, themeName, theme) => {
3323
+ return buildTokenMap(filtered, prefix, states, modes, format, pastel, channelCtxForTheme(theme, themeName, prefix, resolvePrefix(options, themeName, true), options?.splitHue, format, modes, filtered));
3324
+ }, (acc, part) => Object.assign(acc, part), () => ({}));
1527
3325
  },
1528
3326
  json(options) {
3327
+ const format = options?.format ?? "oklch";
3328
+ assertNativeFormat(format, "json");
1529
3329
  const modes = resolveModes(options?.modes);
1530
3330
  const result = {};
1531
- for (const [themeName, theme] of Object.entries(themes)) result[themeName] = buildJsonMap(theme.resolve(), modes, options?.format);
3331
+ for (const [themeName, theme] of Object.entries(themes)) result[themeName] = buildJsonMap(theme.resolve(), modes, format, theme.getConfig().pastel);
1532
3332
  return result;
1533
3333
  },
1534
3334
  css(options) {
1535
- const effectivePrimary = resolveEffectivePrimary(options?.primary, paletteOptions?.primary);
1536
- if (options?.primary !== void 0) validatePrimaryTheme(effectivePrimary, themes);
1537
3335
  const suffix = options?.suffix ?? "-color";
1538
3336
  const format = options?.format ?? "rgb";
1539
- const allLines = {
3337
+ assertNativeFormat(format, "css");
3338
+ const modes = resolveModes();
3339
+ const lines = buildPaletteOutput(themes, paletteOptions, options, (filtered, prefix, pastel, themeName, theme) => {
3340
+ return buildCssMap(filtered, prefix, suffix, format, pastel, channelCtxForTheme(theme, themeName, prefix, resolvePrefix(options, themeName, true), options?.splitHue, format, modes, filtered));
3341
+ }, (acc, part) => {
3342
+ for (const key of [
3343
+ "light",
3344
+ "dark",
3345
+ "lightContrast",
3346
+ "darkContrast"
3347
+ ]) if (part[key]) acc[key].push(part[key]);
3348
+ }, () => ({
1540
3349
  light: [],
1541
3350
  dark: [],
1542
3351
  lightContrast: [],
1543
3352
  darkContrast: []
3353
+ }));
3354
+ return {
3355
+ light: lines.light.join("\n"),
3356
+ dark: lines.dark.join("\n"),
3357
+ lightContrast: lines.lightContrast.join("\n"),
3358
+ darkContrast: lines.darkContrast.join("\n")
1544
3359
  };
1545
- const seen = /* @__PURE__ */ new Map();
1546
- for (const [themeName, theme] of Object.entries(themes)) {
1547
- const resolved = theme.resolve();
1548
- const prefix = resolvePrefix(options, themeName, true);
1549
- const css = buildCssMap(filterCollisions(resolved, prefix, seen, themeName), prefix, suffix, format);
1550
- for (const key of [
3360
+ },
3361
+ dtcg(options) {
3362
+ return buildDtcgResult(options);
3363
+ },
3364
+ dtcgResolver(options) {
3365
+ return buildDtcgResolver(buildDtcgResult(options), options);
3366
+ },
3367
+ tailwind(options) {
3368
+ const modes = resolveModes(options?.modes);
3369
+ const cssPrefix = options?.namespace ?? "color-";
3370
+ const format = options?.format ?? "oklch";
3371
+ assertNativeFormat(format, "tailwind");
3372
+ const darkSelector = options?.darkSelector ?? ".dark";
3373
+ const highContrastSelector = options?.highContrastSelector ?? ".high-contrast";
3374
+ return emitTailwindCss(buildPaletteOutput(themes, paletteOptions, options, (filtered, prefix, pastel, _themeName, _theme) => buildTailwindLines(filtered, prefix, cssPrefix, format, pastel), (acc, part) => {
3375
+ for (const variant of [
1551
3376
  "light",
1552
3377
  "dark",
1553
3378
  "lightContrast",
1554
3379
  "darkContrast"
1555
- ]) if (css[key]) allLines[key].push(css[key]);
1556
- if (themeName === effectivePrimary) {
1557
- const unprefixed = buildCssMap(filterCollisions(resolved, "", seen, themeName, true), "", suffix, format);
1558
- for (const key of [
1559
- "light",
1560
- "dark",
1561
- "lightContrast",
1562
- "darkContrast"
1563
- ]) if (unprefixed[key]) allLines[key].push(unprefixed[key]);
1564
- }
1565
- }
1566
- return {
1567
- light: allLines.light.join("\n"),
1568
- dark: allLines.dark.join("\n"),
1569
- lightContrast: allLines.lightContrast.join("\n"),
1570
- darkContrast: allLines.darkContrast.join("\n")
1571
- };
3380
+ ]) acc[variant].push(...part[variant]);
3381
+ }, () => ({
3382
+ light: [],
3383
+ dark: [],
3384
+ lightContrast: [],
3385
+ darkContrast: []
3386
+ })), modes, darkSelector, highContrastSelector);
1572
3387
  }
1573
3388
  };
1574
3389
  }
1575
- function createColorToken(input) {
1576
- const defs = { __color__: {
1577
- lightness: input.lightness,
1578
- saturation: input.saturationFactor,
1579
- mode: input.mode
1580
- } };
3390
+
3391
+ //#endregion
3392
+ //#region src/theme.ts
3393
+ function createTheme(hue, saturation, initialColors, configOverride) {
3394
+ let colorDefs = initialColors ? { ...initialColors } : {};
3395
+ let cache = null;
3396
+ function getEffectiveConfig() {
3397
+ const version = getConfigVersion();
3398
+ if (cache && cache.version === version) return cache.effectiveConfig;
3399
+ return mergeConfig(getConfig(), configOverride);
3400
+ }
3401
+ function resolveCached() {
3402
+ const version = getConfigVersion();
3403
+ if (cache && cache.version === version) return cache.map;
3404
+ const effectiveConfig = mergeConfig(getConfig(), configOverride);
3405
+ const map = resolveAllColors(hue, saturation, colorDefs, effectiveConfig);
3406
+ cache = {
3407
+ map,
3408
+ version,
3409
+ effectiveConfig
3410
+ };
3411
+ return map;
3412
+ }
3413
+ function invalidate() {
3414
+ cache = null;
3415
+ }
3416
+ function channelCtxFor(options, formatDefault, prefix) {
3417
+ const format = options?.format ?? formatDefault;
3418
+ if (!options?.splitHue || format !== "oklch") return void 0;
3419
+ assertAllPastel(resolveCached(), resolveModes(options?.modes));
3420
+ return {
3421
+ seedHue: hue,
3422
+ baseName: options.name ?? "theme",
3423
+ prefix,
3424
+ defs: colorDefs,
3425
+ mode: "theme"
3426
+ };
3427
+ }
1581
3428
  return {
3429
+ get hue() {
3430
+ return hue;
3431
+ },
3432
+ get saturation() {
3433
+ return saturation;
3434
+ },
3435
+ getConfig() {
3436
+ return getEffectiveConfig();
3437
+ },
3438
+ colors(defs) {
3439
+ colorDefs = {
3440
+ ...colorDefs,
3441
+ ...defs
3442
+ };
3443
+ invalidate();
3444
+ },
3445
+ color(name, def) {
3446
+ if (def === void 0) return colorDefs[name];
3447
+ colorDefs[name] = def;
3448
+ invalidate();
3449
+ },
3450
+ remove(names) {
3451
+ const list = Array.isArray(names) ? names : [names];
3452
+ for (const name of list) delete colorDefs[name];
3453
+ invalidate();
3454
+ },
3455
+ has(name) {
3456
+ return name in colorDefs;
3457
+ },
3458
+ list() {
3459
+ return Object.keys(colorDefs);
3460
+ },
3461
+ reset() {
3462
+ colorDefs = {};
3463
+ invalidate();
3464
+ },
3465
+ export() {
3466
+ const out = {
3467
+ hue,
3468
+ saturation,
3469
+ colors: { ...colorDefs }
3470
+ };
3471
+ if (configOverride !== void 0) out.config = configOverride;
3472
+ return out;
3473
+ },
3474
+ extend(options) {
3475
+ const newHue = options.hue ?? hue;
3476
+ const newSat = options.saturation ?? saturation;
3477
+ const inheritedColors = {};
3478
+ for (const [name, def] of Object.entries(colorDefs)) if (def.inherit !== false) inheritedColors[name] = def;
3479
+ return createTheme(newHue, newSat, options.colors ? {
3480
+ ...inheritedColors,
3481
+ ...options.colors
3482
+ } : { ...inheritedColors }, configOverride || options.config ? {
3483
+ ...configOverride ?? {},
3484
+ ...options.config ?? {}
3485
+ } : void 0);
3486
+ },
1582
3487
  resolve() {
1583
- return resolveAllColors(input.hue, input.saturation, defs).get("__color__");
3488
+ return new Map(resolveCached());
1584
3489
  },
1585
- token(options) {
1586
- return buildTokenMap(resolveAllColors(input.hue, input.saturation, defs), "", {
1587
- dark: options?.states?.dark ?? globalConfig.states.dark,
1588
- highContrast: options?.states?.highContrast ?? globalConfig.states.highContrast
1589
- }, resolveModes(options?.modes), options?.format)["#__color__"];
3490
+ tokens(options) {
3491
+ const format = options?.format ?? "oklch";
3492
+ assertNativeFormat(format, "tokens");
3493
+ const modes = resolveModes(options?.modes);
3494
+ return buildFlatTokenMap(resolveCached(), "", modes, format, getEffectiveConfig().pastel);
1590
3495
  },
1591
3496
  tasty(options) {
1592
- return buildTokenMap(resolveAllColors(input.hue, input.saturation, defs), "", {
1593
- dark: options?.states?.dark ?? globalConfig.states.dark,
1594
- highContrast: options?.states?.highContrast ?? globalConfig.states.highContrast
1595
- }, resolveModes(options?.modes), options?.format)["#__color__"];
3497
+ const cfg = getEffectiveConfig();
3498
+ const states = {
3499
+ dark: options?.states?.dark ?? cfg.states.dark,
3500
+ highContrast: options?.states?.highContrast ?? cfg.states.highContrast
3501
+ };
3502
+ const modes = resolveModes(options?.modes);
3503
+ const format = options?.format ?? "okhsl";
3504
+ const channelCtx = channelCtxFor(options, "okhsl", "");
3505
+ return buildTokenMap(resolveCached(), "", states, modes, format, cfg.pastel, channelCtx);
1596
3506
  },
1597
3507
  json(options) {
1598
- return buildJsonMap(resolveAllColors(input.hue, input.saturation, defs), resolveModes(options?.modes), options?.format)["__color__"];
3508
+ const format = options?.format ?? "oklch";
3509
+ assertNativeFormat(format, "json");
3510
+ const modes = resolveModes(options?.modes);
3511
+ return buildJsonMap(resolveCached(), modes, format, getEffectiveConfig().pastel);
3512
+ },
3513
+ css(options) {
3514
+ const format = options?.format ?? "rgb";
3515
+ assertNativeFormat(format, "css");
3516
+ const channelCtx = channelCtxFor(options, "rgb", "");
3517
+ return buildCssMap(resolveCached(), "", options?.suffix ?? "-color", format, getEffectiveConfig().pastel, channelCtx);
3518
+ },
3519
+ dtcg(options) {
3520
+ const modes = resolveModes(options?.modes);
3521
+ return buildDtcgMap(resolveCached(), "", modes, options?.colorSpace ?? "srgb", getEffectiveConfig().pastel);
3522
+ },
3523
+ dtcgResolver(options) {
3524
+ return buildDtcgResolver(buildDtcgMap(resolveCached(), "", resolveModes(options?.modes), options?.colorSpace ?? "srgb", getEffectiveConfig().pastel), options);
3525
+ },
3526
+ tailwind(options) {
3527
+ const format = options?.format ?? "oklch";
3528
+ assertNativeFormat(format, "tailwind");
3529
+ const modes = resolveModes(options?.modes);
3530
+ return buildTailwindMap(resolveCached(), "", options?.namespace ?? "color-", modes, format, options?.darkSelector ?? ".dark", options?.highContrastSelector ?? ".high-contrast", getEffectiveConfig().pastel);
1599
3531
  }
1600
3532
  };
1601
3533
  }
3534
+
3535
+ //#endregion
3536
+ //#region src/glaze.ts
3537
+ /**
3538
+ * Glaze — OKHST color theme generator.
3539
+ *
3540
+ * Public API entry. Wires `glaze()` and its attached static methods to
3541
+ * the focused modules in this folder:
3542
+ * - `theme.ts` — single-theme factory
3543
+ * - `palette.ts` — multi-theme composition
3544
+ * - `color-token.ts` — standalone single-color tokens (`glaze.color`)
3545
+ * - `shadow.ts` — standalone shadow factory (`glaze.shadow`)
3546
+ * - `formatters.ts` — variant → string (`glaze.format`)
3547
+ * - `config.ts` — global config singleton
3548
+ */
1602
3549
  /**
1603
3550
  * Create a single-hue glaze theme.
1604
3551
  *
3552
+ * An optional `config` override can be supplied to customize the resolve
3553
+ * behavior for this theme (tone windows, etc.). The
3554
+ * override is **merged over the live global config at resolve time** —
3555
+ * the theme still reacts to later `configure()` calls for fields it
3556
+ * didn't override.
3557
+ *
1605
3558
  * @example
1606
3559
  * ```ts
1607
- * const primary = glaze({ hue: 280, saturation: 80 });
1608
- * // or shorthand:
1609
3560
  * const primary = glaze(280, 80);
3561
+ * // or shorthand:
3562
+ * const primary = glaze({ hue: 280, saturation: 80 });
3563
+ * // with config override:
3564
+ * const raw = glaze(280, 80, { lightTone: false });
1610
3565
  * ```
1611
3566
  */
1612
- function glaze(hueOrOptions, saturation) {
1613
- if (typeof hueOrOptions === "number") return createTheme(hueOrOptions, saturation ?? 100);
1614
- return createTheme(hueOrOptions.hue, hueOrOptions.saturation);
3567
+ function glaze(hueOrOptions, saturation, config) {
3568
+ if (typeof hueOrOptions === "number") return createTheme(hueOrOptions, saturation ?? 100, void 0, config);
3569
+ return createTheme(hueOrOptions.hue, hueOrOptions.saturation, void 0, config);
1615
3570
  }
1616
- /**
1617
- * Configure global glaze settings.
1618
- */
1619
- glaze.configure = function configure(config) {
1620
- globalConfig = {
1621
- lightLightness: config.lightLightness ?? globalConfig.lightLightness,
1622
- darkLightness: config.darkLightness ?? globalConfig.darkLightness,
1623
- darkDesaturation: config.darkDesaturation ?? globalConfig.darkDesaturation,
1624
- darkCurve: config.darkCurve ?? globalConfig.darkCurve,
1625
- states: {
1626
- dark: config.states?.dark ?? globalConfig.states.dark,
1627
- highContrast: config.states?.highContrast ?? globalConfig.states.highContrast
1628
- },
1629
- modes: {
1630
- dark: config.modes?.dark ?? globalConfig.modes.dark,
1631
- highContrast: config.modes?.highContrast ?? globalConfig.modes.highContrast
1632
- },
1633
- shadowTuning: config.shadowTuning ?? globalConfig.shadowTuning
1634
- };
3571
+ /** Configure global glaze settings. */
3572
+ glaze.configure = function configure$1(config) {
3573
+ configure(config);
1635
3574
  };
1636
- /**
1637
- * Compose multiple themes into a palette.
1638
- */
3575
+ /** Compose multiple themes into a palette. */
1639
3576
  glaze.palette = function palette(themes, options) {
1640
3577
  return createPalette(themes, options);
1641
3578
  };
1642
- /**
1643
- * Create a theme from a serialized export.
1644
- */
3579
+ /** Create a theme from a serialized export. */
1645
3580
  glaze.from = function from(data) {
1646
- return createTheme(data.hue, data.saturation, data.colors);
3581
+ return createTheme(data.hue, data.saturation, data.colors, data.config);
1647
3582
  };
1648
3583
  /**
1649
3584
  * Create a standalone single-color token.
3585
+ *
3586
+ * **arg1 — the color** (four accepted shapes, discriminated by structure):
3587
+ *
3588
+ * | Shape | Example | Notes |
3589
+ * |---|---|---|
3590
+ * | Bare string | `'#26fcb2'`, `'rgb(38 252 178)'` | Hex or CSS color function (incl. `okhst()`) |
3591
+ * | Value object | `{ h: 152, s: 0.95, l: 0.74 }` | OKHSL, OKHST (`{h,s,t}`), `{r,g,b}`, `{l,c,h}` |
3592
+ * | `{ from, ...overrides }` | `{ from: '#fff', base: bg, contrast: 'AA' }` | Value + color overrides |
3593
+ * | Structured | `{ hue: 152, saturation: 95, tone: 74 }` | Full theme-style token |
3594
+ *
3595
+ * **arg2 — config override** (optional, all shapes):
3596
+ * Overrides the resolve-relevant global config fields for this token.
3597
+ * Fields that are omitted fall through to the live global config at
3598
+ * create time (and are snapshotted). Pass `false` for a tone window
3599
+ * to disable clamping entirely.
3600
+ *
3601
+ * ```ts
3602
+ * // Bare string — no overrides
3603
+ * glaze.color('#26fcb2')
3604
+ *
3605
+ * // From form — value + color overrides
3606
+ * glaze.color({ from: '#fff', base: bg, contrast: 'AA' })
3607
+ *
3608
+ * // Structured form — full theme-style token
3609
+ * glaze.color({ hue: 152, saturation: 95, tone: 74 })
3610
+ *
3611
+ * // Config override on any form
3612
+ * glaze.color('#26fcb2', { darkTone: false, autoFlip: false })
3613
+ * glaze.color({ from: '#fff', base: bg })
3614
+ * ```
3615
+ *
3616
+ * Defaults: every form defaults to `mode: 'auto'`. Value-shorthand forms
3617
+ * (bare strings and value objects) preserve light tone exactly
3618
+ * (`lightTone: false` internally). Structured form snapshots both
3619
+ * tone windows from `globalConfig` at create time.
3620
+ *
3621
+ * Relative `tone: '+N'` and `contrast` anchor to the literal seed by
3622
+ * default; when `base` is set they anchor to the base's resolved variant
3623
+ * per scheme. Relative `hue: '+N'` always anchors to the seed, not the base.
1650
3624
  */
1651
- glaze.color = function color(input) {
1652
- return createColorToken(input);
3625
+ glaze.color = function color(input, config) {
3626
+ if (typeof input === "string") return createColorTokenFromValue(input, void 0, config);
3627
+ const obj = input;
3628
+ if ("from" in obj) {
3629
+ const { from, ...overrides } = input;
3630
+ return createColorTokenFromValue(from, overrides, config);
3631
+ }
3632
+ if ("hue" in obj) return createColorToken(input, config);
3633
+ return createColorTokenFromValue(input, void 0, config);
1653
3634
  };
1654
3635
  /**
1655
3636
  * Compute a shadow color from a bg/fg pair and intensity.
3637
+ *
3638
+ * Both `bg` and `fg` accept any `GlazeColorValue` form: hex (`#rgb` /
3639
+ * `#rrggbb` / `#rrggbbaa`), `rgb()` / `hsl()` / `okhsl()` / `oklch()`
3640
+ * strings, or `{ r, g, b }` / `{ h, s, l }` / `{ l, c, h }` objects.
1656
3641
  */
1657
3642
  glaze.shadow = function shadow(input) {
1658
- const bg = parseOkhslInput(input.bg);
1659
- const fg = input.fg ? parseOkhslInput(input.fg) : void 0;
1660
- const tuning = resolveShadowTuning(input.tuning);
1661
- return computeShadow({
3643
+ const bg = extractOkhslFromValue(input.bg);
3644
+ const fg = input.fg ? extractOkhslFromValue(input.fg) : void 0;
3645
+ const cfg = getConfig();
3646
+ const tuning = resolveShadowTuning(input.tuning, cfg.shadowTuning);
3647
+ const result = computeShadow({
1662
3648
  ...bg,
1663
3649
  alpha: 1
1664
3650
  }, fg ? {
1665
3651
  ...fg,
1666
3652
  alpha: 1
1667
3653
  } : void 0, input.intensity, tuning);
3654
+ const { h, s, t } = okhslToOkhst({
3655
+ h: result.h,
3656
+ s: result.s,
3657
+ l: result.l
3658
+ });
3659
+ return {
3660
+ h,
3661
+ s,
3662
+ t,
3663
+ alpha: result.alpha
3664
+ };
1668
3665
  };
1669
- /**
1670
- * Format a resolved color variant as a CSS string.
1671
- */
1672
- glaze.format = function format(variant, colorFormat) {
1673
- return formatVariant(variant, colorFormat);
3666
+ /** Format a resolved color variant as a CSS string. */
3667
+ glaze.format = function format(variant, colorFormat, pastel) {
3668
+ return formatVariant(variant, colorFormat, pastel);
1674
3669
  };
1675
- function parseOkhslInput(input) {
1676
- if (typeof input === "string") {
1677
- const rgb = parseHex(input);
1678
- if (!rgb) throw new Error(`glaze: invalid hex color "${input}".`);
1679
- const [h, s, l] = srgbToOkhsl(rgb);
1680
- return {
1681
- h,
1682
- s,
1683
- l
1684
- };
1685
- }
1686
- return input;
1687
- }
1688
3670
  /**
1689
3671
  * Create a theme from a hex color string.
1690
3672
  * Extracts hue and saturation from the color.
@@ -1708,46 +3690,73 @@ glaze.fromRgb = function fromRgb(r, g, b) {
1708
3690
  return createTheme(h, s * 100);
1709
3691
  };
1710
3692
  /**
1711
- * Get the current global configuration (for testing/debugging).
3693
+ * Rehydrate a `glaze.color()` token from a `.export()` snapshot.
3694
+ *
3695
+ * The snapshot is a plain JSON-safe object containing the original
3696
+ * input value, overrides (with any `base` token recursively serialized),
3697
+ * and the effective config snapshot. The reconstructed token is identical
3698
+ * in behavior to the original at the time of export.
3699
+ *
3700
+ * @example
3701
+ * ```ts
3702
+ * const text = glaze.color({ from: '#1a1a1a', contrast: 'AA' });
3703
+ * const data = text.export(); // JSON-safe
3704
+ * localStorage.setItem('text', JSON.stringify(data));
3705
+ * // ...later...
3706
+ * const restored = glaze.colorFrom(JSON.parse(localStorage.getItem('text')!));
3707
+ * ```
1712
3708
  */
3709
+ glaze.colorFrom = function colorFrom(data) {
3710
+ return colorFromExport(data);
3711
+ };
3712
+ /** Get the current global configuration (for testing/debugging). */
1713
3713
  glaze.getConfig = function getConfig() {
1714
- return { ...globalConfig };
3714
+ return snapshotConfig();
1715
3715
  };
1716
- /**
1717
- * Reset global configuration to defaults.
1718
- */
1719
- glaze.resetConfig = function resetConfig() {
1720
- globalConfig = {
1721
- lightLightness: [10, 100],
1722
- darkLightness: [15, 95],
1723
- darkDesaturation: .1,
1724
- darkCurve: .5,
1725
- states: {
1726
- dark: "@dark",
1727
- highContrast: "@high-contrast"
1728
- },
1729
- modes: {
1730
- dark: true,
1731
- highContrast: false
1732
- }
1733
- };
3716
+ /** Reset global configuration to defaults. */
3717
+ glaze.resetConfig = function resetConfig$1() {
3718
+ resetConfig();
1734
3719
  };
1735
3720
 
1736
3721
  //#endregion
3722
+ exports.REF_EPS = REF_EPS;
3723
+ exports.apcaContrast = apcaContrast;
3724
+ exports.assertAllPastel = assertAllPastel;
3725
+ exports.assertNativeFormat = assertNativeFormat;
1737
3726
  exports.contrastRatioFromLuminance = contrastRatioFromLuminance;
1738
- exports.findLightnessForContrast = findLightnessForContrast;
3727
+ exports.cuspLightness = cuspLightness;
3728
+ exports.findToneForContrast = findToneForContrast;
1739
3729
  exports.findValueForMixContrast = findValueForMixContrast;
1740
3730
  exports.formatHsl = formatHsl;
1741
3731
  exports.formatOkhsl = formatOkhsl;
3732
+ exports.formatOkhst = formatOkhst;
1742
3733
  exports.formatOklch = formatOklch;
1743
3734
  exports.formatRgb = formatRgb;
3735
+ exports.fromTone = fromTone;
1744
3736
  exports.gamutClampedLuminance = gamutClampedLuminance;
1745
3737
  exports.glaze = glaze;
3738
+ exports.hslToSrgb = hslToSrgb;
3739
+ exports.inferRoleFromName = inferRoleFromName;
3740
+ exports.normalizeRole = normalizeRole;
1746
3741
  exports.okhslToLinearSrgb = okhslToLinearSrgb;
3742
+ exports.okhslToOkhst = okhslToOkhst;
1747
3743
  exports.okhslToOklab = okhslToOklab;
3744
+ exports.okhslToOklch = okhslToOklch;
1748
3745
  exports.okhslToSrgb = okhslToSrgb;
3746
+ exports.okhstToOkhsl = okhstToOkhsl;
3747
+ exports.oklabToOkhsl = oklabToOkhsl;
3748
+ exports.oppositeRole = oppositeRole;
1749
3749
  exports.parseHex = parseHex;
3750
+ exports.parseHexAlpha = parseHexAlpha;
1750
3751
  exports.relativeLuminanceFromLinearRgb = relativeLuminanceFromLinearRgb;
3752
+ exports.resolveApcaTarget = resolveApcaTarget;
3753
+ exports.resolveContrastForMode = resolveContrastForMode;
1751
3754
  exports.resolveMinContrast = resolveMinContrast;
3755
+ exports.roleToPolarity = roleToPolarity;
3756
+ exports.srgbToHex = srgbToHex;
1752
3757
  exports.srgbToOkhsl = srgbToOkhsl;
3758
+ exports.toTone = toTone;
3759
+ exports.toneFromY = toneFromY;
3760
+ exports.variantToOkhsl = variantToOkhsl;
3761
+ exports.yFromTone = yFromTone;
1753
3762
  //# sourceMappingURL=index.cjs.map