@tenphi/glaze 0.0.0-snapshot.4c063ef

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 ADDED
@@ -0,0 +1,1448 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+
3
+ //#region src/okhsl-color-math.ts
4
+ const OKLab_to_LMS_M = [
5
+ [
6
+ 1,
7
+ .3963377773761749,
8
+ .2158037573099136
9
+ ],
10
+ [
11
+ 1,
12
+ -.1055613458156586,
13
+ -.0638541728258133
14
+ ],
15
+ [
16
+ 1,
17
+ -.0894841775298119,
18
+ -1.2914855480194092
19
+ ]
20
+ ];
21
+ const LMS_to_linear_sRGB_M = [
22
+ [
23
+ 4.076741636075959,
24
+ -3.307711539258062,
25
+ .2309699031821041
26
+ ],
27
+ [
28
+ -1.2684379732850313,
29
+ 2.6097573492876878,
30
+ -.3413193760026569
31
+ ],
32
+ [
33
+ -.004196076138675526,
34
+ -.703418617935936,
35
+ 1.7076146940746113
36
+ ]
37
+ ];
38
+ const linear_sRGB_to_LMS_M = [
39
+ [
40
+ .4122214708,
41
+ .5363325363,
42
+ .0514459929
43
+ ],
44
+ [
45
+ .2119034982,
46
+ .6806995451,
47
+ .1073969566
48
+ ],
49
+ [
50
+ .0883024619,
51
+ .2817188376,
52
+ .6299787005
53
+ ]
54
+ ];
55
+ const LMS_to_OKLab_M = [
56
+ [
57
+ .2104542553,
58
+ .793617785,
59
+ -.0040720468
60
+ ],
61
+ [
62
+ 1.9779984951,
63
+ -2.428592205,
64
+ .4505937099
65
+ ],
66
+ [
67
+ .0259040371,
68
+ .7827717662,
69
+ -.808675766
70
+ ]
71
+ ];
72
+ const OKLab_to_linear_sRGB_coefficients = [
73
+ [[-1.8817030993265873, -.8093650129914302], [
74
+ 1.19086277,
75
+ 1.76576728,
76
+ .59662641,
77
+ .75515197,
78
+ .56771245
79
+ ]],
80
+ [[1.8144407988010998, -1.194452667805235], [
81
+ .73956515,
82
+ -.45954404,
83
+ .08285427,
84
+ .12541073,
85
+ -.14503204
86
+ ]],
87
+ [[.13110757611180954, 1.813339709266608], [
88
+ 1.35733652,
89
+ -.00915799,
90
+ -1.1513021,
91
+ -.50559606,
92
+ .00692167
93
+ ]]
94
+ ];
95
+ const TAU = 2 * Math.PI;
96
+ const K1 = .206;
97
+ const K2 = .03;
98
+ const K3 = (1 + K1) / (1 + K2);
99
+ const EPSILON = 1e-10;
100
+ const constrainAngle = (angle) => (angle % 360 + 360) % 360;
101
+ const toe = (x) => .5 * (K3 * x - K1 + Math.sqrt((K3 * x - K1) * (K3 * x - K1) + 4 * K2 * K3 * x));
102
+ const toeInv = (x) => (x ** 2 + K1 * x) / (K3 * (x + K2));
103
+ const dot3 = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
104
+ const dotXY = (a, b) => a[0] * b[0] + a[1] * b[1];
105
+ const transform = (input, matrix) => [
106
+ dot3(input, matrix[0]),
107
+ dot3(input, matrix[1]),
108
+ dot3(input, matrix[2])
109
+ ];
110
+ const cubed3 = (lms) => [
111
+ lms[0] ** 3,
112
+ lms[1] ** 3,
113
+ lms[2] ** 3
114
+ ];
115
+ const cbrt3 = (lms) => [
116
+ Math.cbrt(lms[0]),
117
+ Math.cbrt(lms[1]),
118
+ Math.cbrt(lms[2])
119
+ ];
120
+ const clampVal = (v, min, max) => Math.max(min, Math.min(max, v));
121
+ const OKLabToLinearSRGB = (lab) => {
122
+ return transform(cubed3(transform(lab, OKLab_to_LMS_M)), LMS_to_linear_sRGB_M);
123
+ };
124
+ const computeMaxSaturationOKLC = (a, b) => {
125
+ const okCoeff = OKLab_to_linear_sRGB_coefficients;
126
+ const lmsToRgb = LMS_to_linear_sRGB_M;
127
+ const tmp2 = [a, b];
128
+ const tmp3 = [
129
+ 0,
130
+ a,
131
+ b
132
+ ];
133
+ let chnlCoeff;
134
+ let chnlLMS;
135
+ if (dotXY(okCoeff[0][0], tmp2) > 1) {
136
+ chnlCoeff = okCoeff[0][1];
137
+ chnlLMS = lmsToRgb[0];
138
+ } else if (dotXY(okCoeff[1][0], tmp2) > 1) {
139
+ chnlCoeff = okCoeff[1][1];
140
+ chnlLMS = lmsToRgb[1];
141
+ } else {
142
+ chnlCoeff = okCoeff[2][1];
143
+ chnlLMS = lmsToRgb[2];
144
+ }
145
+ const [k0, k1, k2, k3, k4] = chnlCoeff;
146
+ const [wl, wm, ws] = chnlLMS;
147
+ let sat = k0 + k1 * a + k2 * b + k3 * (a * a) + k4 * a * b;
148
+ const dotYZ = (mat, vec) => mat[1] * vec[1] + mat[2] * vec[2];
149
+ const kl = dotYZ(OKLab_to_LMS_M[0], tmp3);
150
+ const km = dotYZ(OKLab_to_LMS_M[1], tmp3);
151
+ const ks = dotYZ(OKLab_to_LMS_M[2], tmp3);
152
+ const l_ = 1 + sat * kl;
153
+ const m_ = 1 + sat * km;
154
+ const s_ = 1 + sat * ks;
155
+ const l = l_ ** 3;
156
+ const m = m_ ** 3;
157
+ const s = s_ ** 3;
158
+ const lds = 3 * kl * l_ * l_;
159
+ const mds = 3 * km * m_ * m_;
160
+ const sds = 3 * ks * s_ * s_;
161
+ const lds2 = 6 * kl * kl * l_;
162
+ const mds2 = 6 * km * km * m_;
163
+ const sds2 = 6 * ks * ks * s_;
164
+ const f = wl * l + wm * m + ws * s;
165
+ const f1 = wl * lds + wm * mds + ws * sds;
166
+ const f2 = wl * lds2 + wm * mds2 + ws * sds2;
167
+ sat = sat - f * f1 / (f1 * f1 - .5 * f * f2);
168
+ return sat;
169
+ };
170
+ const findCuspOKLCH = (a, b) => {
171
+ const S_cusp = computeMaxSaturationOKLC(a, b);
172
+ const rgb_at_max = OKLabToLinearSRGB([
173
+ 1,
174
+ S_cusp * a,
175
+ S_cusp * b
176
+ ]);
177
+ const L_cusp = Math.cbrt(1 / Math.max(Math.max(rgb_at_max[0], rgb_at_max[1]), Math.max(rgb_at_max[2], 0)));
178
+ return [L_cusp, L_cusp * S_cusp];
179
+ };
180
+ const findGamutIntersectionOKLCH = (a, b, l1, c1, l0, cusp) => {
181
+ const lmsToRgb = LMS_to_linear_sRGB_M;
182
+ const tmp3 = [
183
+ 0,
184
+ a,
185
+ b
186
+ ];
187
+ const floatMax = Number.MAX_VALUE;
188
+ let t;
189
+ const dotYZ = (mat, vec) => mat[1] * vec[1] + mat[2] * vec[2];
190
+ const dotXYZ = (vec, x, y, z) => vec[0] * x + vec[1] * y + vec[2] * z;
191
+ if ((l1 - l0) * cusp[1] - (cusp[0] - l0) * c1 <= 0) {
192
+ const denom = c1 * cusp[0] + cusp[1] * (l0 - l1);
193
+ t = denom === 0 ? 0 : cusp[1] * l0 / denom;
194
+ } else {
195
+ const denom = c1 * (cusp[0] - 1) + cusp[1] * (l0 - l1);
196
+ t = denom === 0 ? 0 : cusp[1] * (l0 - 1) / denom;
197
+ const dl = l1 - l0;
198
+ const dc = c1;
199
+ const kl = dotYZ(OKLab_to_LMS_M[0], tmp3);
200
+ const km = dotYZ(OKLab_to_LMS_M[1], tmp3);
201
+ const ks = dotYZ(OKLab_to_LMS_M[2], tmp3);
202
+ const L = l0 * (1 - t) + t * l1;
203
+ const C = t * c1;
204
+ const l_ = L + C * kl;
205
+ const m_ = L + C * km;
206
+ const s_ = L + C * ks;
207
+ const l = l_ ** 3;
208
+ const m = m_ ** 3;
209
+ const s = s_ ** 3;
210
+ const ldt = 3 * (dl + dc * kl) * l_ * l_;
211
+ const mdt = 3 * (dl + dc * km) * m_ * m_;
212
+ const sdt = 3 * (dl + dc * ks) * s_ * s_;
213
+ const ldt2 = 6 * (dl + dc * kl) ** 2 * l_;
214
+ const mdt2 = 6 * (dl + dc * km) ** 2 * m_;
215
+ const sdt2 = 6 * (dl + dc * ks) ** 2 * s_;
216
+ const r_ = dotXYZ(lmsToRgb[0], l, m, s) - 1;
217
+ const r1 = dotXYZ(lmsToRgb[0], ldt, mdt, sdt);
218
+ const r2 = dotXYZ(lmsToRgb[0], ldt2, mdt2, sdt2);
219
+ const ur = r1 / (r1 * r1 - .5 * r_ * r2);
220
+ let tr = -r_ * ur;
221
+ const g_ = dotXYZ(lmsToRgb[1], l, m, s) - 1;
222
+ const g1 = dotXYZ(lmsToRgb[1], ldt, mdt, sdt);
223
+ const g2 = dotXYZ(lmsToRgb[1], ldt2, mdt2, sdt2);
224
+ const ug = g1 / (g1 * g1 - .5 * g_ * g2);
225
+ let tg = -g_ * ug;
226
+ const b_ = dotXYZ(lmsToRgb[2], l, m, s) - 1;
227
+ const b1 = dotXYZ(lmsToRgb[2], ldt, mdt, sdt);
228
+ const b2 = dotXYZ(lmsToRgb[2], ldt2, mdt2, sdt2);
229
+ const ub = b1 / (b1 * b1 - .5 * b_ * b2);
230
+ let tb = -b_ * ub;
231
+ tr = ur >= 0 ? tr : floatMax;
232
+ tg = ug >= 0 ? tg : floatMax;
233
+ tb = ub >= 0 ? tb : floatMax;
234
+ t += Math.min(tr, Math.min(tg, tb));
235
+ }
236
+ return t;
237
+ };
238
+ const computeSt = (cusp) => [cusp[1] / cusp[0], cusp[1] / (1 - cusp[0])];
239
+ const computeStMid = (a, b) => [.11516993 + 1 / (7.4477897 + 4.1590124 * b + a * (-2.19557347 + 1.75198401 * b + a * (-2.13704948 - 10.02301043 * b + a * (-4.24894561 + 5.38770819 * b + 4.69891013 * a)))), .11239642 + 1 / (1.6132032 - .68124379 * b + a * (.40370612 + .90148123 * b + a * (-.27087943 + .6122399 * b + a * (.00299215 - .45399568 * b - .14661872 * a))))];
240
+ const getCs = (L, a, b, cusp) => {
241
+ const cMax = findGamutIntersectionOKLCH(a, b, L, 1, L, cusp);
242
+ const stMax = computeSt(cusp);
243
+ const k = cMax / Math.min(L * stMax[0], (1 - L) * stMax[1]);
244
+ const stMid = computeStMid(a, b);
245
+ let ca = L * stMid[0];
246
+ let cb = (1 - L) * stMid[1];
247
+ const cMid = .9 * k * Math.sqrt(Math.sqrt(1 / (1 / ca ** 4 + 1 / cb ** 4)));
248
+ ca = L * .4;
249
+ cb = (1 - L) * .8;
250
+ return [
251
+ Math.sqrt(1 / (1 / ca ** 2 + 1 / cb ** 2)),
252
+ cMid,
253
+ cMax
254
+ ];
255
+ };
256
+ /**
257
+ * Convert OKHSL (h: 0–360, s: 0–1, l: 0–1) to linear sRGB.
258
+ * Channels may exceed [0, 1] near gamut boundaries — caller must clamp if needed.
259
+ */
260
+ function okhslToLinearSrgb(h, s, l) {
261
+ const L = toeInv(l);
262
+ let a = 0;
263
+ let b = 0;
264
+ const hNorm = constrainAngle(h) / 360;
265
+ if (L !== 0 && L !== 1 && s !== 0) {
266
+ const a_ = Math.cos(TAU * hNorm);
267
+ const b_ = Math.sin(TAU * hNorm);
268
+ const [c0, cMid, cMax] = getCs(L, a_, b_, findCuspOKLCH(a_, b_));
269
+ const mid = .8;
270
+ const midInv = 1.25;
271
+ let t, k0, k1, k2;
272
+ if (s < mid) {
273
+ t = midInv * s;
274
+ k0 = 0;
275
+ k1 = mid * c0;
276
+ k2 = 1 - k1 / cMid;
277
+ } else {
278
+ t = 5 * (s - .8);
279
+ k0 = cMid;
280
+ k1 = .2 * cMid ** 2 * 1.25 ** 2 / c0;
281
+ k2 = 1 - k1 / (cMax - cMid);
282
+ }
283
+ const c = k0 + t * k1 / (1 - k2 * t);
284
+ a = c * a_;
285
+ b = c * b_;
286
+ }
287
+ return OKLabToLinearSRGB([
288
+ L,
289
+ a,
290
+ b
291
+ ]);
292
+ }
293
+ /**
294
+ * Compute relative luminance Y from linear sRGB channels.
295
+ * Per WCAG 2: Y = 0.2126·R + 0.7152·G + 0.0722·B
296
+ */
297
+ function relativeLuminanceFromLinearRgb(rgb) {
298
+ return .2126 * rgb[0] + .7152 * rgb[1] + .0722 * rgb[2];
299
+ }
300
+ /**
301
+ * WCAG 2 contrast ratio from two luminance values.
302
+ */
303
+ function contrastRatioFromLuminance(yA, yB) {
304
+ const lighter = Math.max(yA, yB);
305
+ const darker = Math.min(yA, yB);
306
+ return (lighter + .05) / (darker + .05);
307
+ }
308
+ const sRGBLinearToGamma = (val) => {
309
+ const sign = val < 0 ? -1 : 1;
310
+ const abs = Math.abs(val);
311
+ return abs > .0031308 ? sign * (1.055 * Math.pow(abs, 1 / 2.4) - .055) : 12.92 * val;
312
+ };
313
+ const sRGBGammaToLinear = (val) => {
314
+ const sign = val < 0 ? -1 : 1;
315
+ const abs = Math.abs(val);
316
+ return abs <= .04045 ? val / 12.92 : sign * Math.pow((abs + .055) / 1.055, 2.4);
317
+ };
318
+ /**
319
+ * Convert OKHSL to gamma-encoded sRGB (clamped to 0–1).
320
+ */
321
+ function okhslToSrgb(h, s, l) {
322
+ const lin = okhslToLinearSrgb(h, s, l);
323
+ return [
324
+ Math.max(0, Math.min(1, sRGBLinearToGamma(lin[0]))),
325
+ Math.max(0, Math.min(1, sRGBLinearToGamma(lin[1]))),
326
+ Math.max(0, Math.min(1, sRGBLinearToGamma(lin[2])))
327
+ ];
328
+ }
329
+ /**
330
+ * Convert OKHSL (h: 0–360, s: 0–1, l: 0–1) to OKLab [L, a, b].
331
+ */
332
+ function okhslToOklab(h, s, l) {
333
+ const L = toeInv(l);
334
+ let a = 0;
335
+ let b = 0;
336
+ const hNorm = constrainAngle(h) / 360;
337
+ if (L !== 0 && L !== 1 && s !== 0) {
338
+ const a_ = Math.cos(TAU * hNorm);
339
+ const b_ = Math.sin(TAU * hNorm);
340
+ const [c0, cMid, cMax] = getCs(L, a_, b_, findCuspOKLCH(a_, b_));
341
+ const mid = .8;
342
+ const midInv = 1.25;
343
+ let t, k0, k1, k2;
344
+ if (s < mid) {
345
+ t = midInv * s;
346
+ k0 = 0;
347
+ k1 = mid * c0;
348
+ k2 = 1 - k1 / cMid;
349
+ } else {
350
+ t = 5 * (s - .8);
351
+ k0 = cMid;
352
+ k1 = .2 * cMid ** 2 * 1.25 ** 2 / c0;
353
+ k2 = 1 - k1 / (cMax - cMid);
354
+ }
355
+ const c = k0 + t * k1 / (1 - k2 * t);
356
+ a = c * a_;
357
+ b = c * b_;
358
+ }
359
+ return [
360
+ L,
361
+ a,
362
+ b
363
+ ];
364
+ }
365
+ const linearSrgbToOklab = (rgb) => {
366
+ return transform(cbrt3(transform(rgb, linear_sRGB_to_LMS_M)), LMS_to_OKLab_M);
367
+ };
368
+ const oklabToOkhsl = (lab) => {
369
+ const L = lab[0];
370
+ const a = lab[1];
371
+ const b = lab[2];
372
+ const C = Math.sqrt(a * a + b * b);
373
+ if (C < EPSILON) return [
374
+ 0,
375
+ 0,
376
+ toe(L)
377
+ ];
378
+ const a_ = a / C;
379
+ const b_ = b / C;
380
+ let h = Math.atan2(b, a) * (180 / Math.PI);
381
+ h = constrainAngle(h);
382
+ const [c0, cMid, cMax] = getCs(L, a_, b_, findCuspOKLCH(a_, b_));
383
+ const mid = .8;
384
+ const midInv = 1.25;
385
+ let s;
386
+ if (C < cMid) {
387
+ const k1 = mid * c0;
388
+ s = C / (k1 + C * (1 - k1 / cMid)) / midInv;
389
+ } else {
390
+ const k0 = cMid;
391
+ const k1 = .2 * cMid ** 2 * 1.25 ** 2 / c0;
392
+ const k2 = 1 - k1 / (cMax - cMid);
393
+ const cDiff = C - k0;
394
+ s = mid + cDiff / (k1 + cDiff * k2) / 5;
395
+ }
396
+ const l = toe(L);
397
+ return [
398
+ h,
399
+ clampVal(s, 0, 1),
400
+ clampVal(l, 0, 1)
401
+ ];
402
+ };
403
+ /**
404
+ * Convert gamma-encoded sRGB (0–1 per channel) to OKHSL.
405
+ * Returns [h, s, l] where h: 0–360, s: 0–1, l: 0–1.
406
+ */
407
+ function srgbToOkhsl(rgb) {
408
+ return oklabToOkhsl(linearSrgbToOklab([
409
+ sRGBGammaToLinear(rgb[0]),
410
+ sRGBGammaToLinear(rgb[1]),
411
+ sRGBGammaToLinear(rgb[2])
412
+ ]));
413
+ }
414
+ /**
415
+ * Parse a hex color string (#rgb or #rrggbb) to sRGB [r, g, b] in 0–1 range.
416
+ * Returns null if the string is not a valid hex color.
417
+ */
418
+ function parseHex(hex) {
419
+ const h = hex.startsWith("#") ? hex.slice(1) : hex;
420
+ if (h.length === 3) {
421
+ const r = parseInt(h[0] + h[0], 16);
422
+ const g = parseInt(h[1] + h[1], 16);
423
+ const b = parseInt(h[2] + h[2], 16);
424
+ if (isNaN(r) || isNaN(g) || isNaN(b)) return null;
425
+ return [
426
+ r / 255,
427
+ g / 255,
428
+ b / 255
429
+ ];
430
+ }
431
+ if (h.length === 6) {
432
+ const r = parseInt(h.slice(0, 2), 16);
433
+ const g = parseInt(h.slice(2, 4), 16);
434
+ const b = parseInt(h.slice(4, 6), 16);
435
+ if (isNaN(r) || isNaN(g) || isNaN(b)) return null;
436
+ return [
437
+ r / 255,
438
+ g / 255,
439
+ b / 255
440
+ ];
441
+ }
442
+ return null;
443
+ }
444
+ function fmt$1(value, decimals) {
445
+ return parseFloat(value.toFixed(decimals)).toString();
446
+ }
447
+ /**
448
+ * Format OKHSL values as a CSS `okhsl(H S% L%)` string.
449
+ * h: 0–360, s: 0–100, l: 0–100 (percentage scale for s and l).
450
+ */
451
+ function formatOkhsl(h, s, l) {
452
+ return `okhsl(${fmt$1(h, 1)} ${fmt$1(s, 1)}% ${fmt$1(l, 1)}%)`;
453
+ }
454
+ /**
455
+ * Format OKHSL values as a CSS `rgb(R G B)` string with rounded integer values.
456
+ * h: 0–360, s: 0–100, l: 0–100 (percentage scale for s and l).
457
+ */
458
+ function formatRgb(h, s, l) {
459
+ const [r, g, b] = okhslToSrgb(h, s / 100, l / 100);
460
+ return `rgb(${Math.round(r * 255)} ${Math.round(g * 255)} ${Math.round(b * 255)})`;
461
+ }
462
+ /**
463
+ * Format OKHSL values as a CSS `hsl(H S% L%)` string.
464
+ * h: 0–360, s: 0–100, l: 0–100 (percentage scale for s and l).
465
+ */
466
+ function formatHsl(h, s, l) {
467
+ const [r, g, b] = okhslToSrgb(h, s / 100, l / 100);
468
+ const max = Math.max(r, g, b);
469
+ const min = Math.min(r, g, b);
470
+ const delta = max - min;
471
+ let hh = 0;
472
+ let ss = 0;
473
+ const ll = (max + min) / 2;
474
+ if (delta > 0) {
475
+ ss = ll > .5 ? delta / (2 - max - min) : delta / (max + min);
476
+ if (max === r) hh = ((g - b) / delta + (g < b ? 6 : 0)) * 60;
477
+ else if (max === g) hh = ((b - r) / delta + 2) * 60;
478
+ else hh = ((r - g) / delta + 4) * 60;
479
+ }
480
+ return `hsl(${fmt$1(hh, 1)} ${fmt$1(ss * 100, 1)}% ${fmt$1(ll * 100, 1)}%)`;
481
+ }
482
+ /**
483
+ * Format OKHSL values as a CSS `oklch(L C H)` string.
484
+ * h: 0–360, s: 0–100, l: 0–100 (percentage scale for s and l).
485
+ */
486
+ function formatOklch(h, s, l) {
487
+ const [L, a, b] = okhslToOklab(h, s / 100, l / 100);
488
+ const C = Math.sqrt(a * a + b * b);
489
+ let hh = Math.atan2(b, a) * (180 / Math.PI);
490
+ hh = constrainAngle(hh);
491
+ return `oklch(${fmt$1(L, 4)} ${fmt$1(C, 4)} ${fmt$1(hh, 1)})`;
492
+ }
493
+
494
+ //#endregion
495
+ //#region src/contrast-solver.ts
496
+ /**
497
+ * OKHSL Contrast Solver
498
+ *
499
+ * Finds the closest OKHSL lightness that satisfies a WCAG 2 contrast target
500
+ * against a base color. Used by glaze when resolving dependent colors
501
+ * with `contrast`.
502
+ */
503
+ const CONTRAST_PRESETS = {
504
+ AA: 4.5,
505
+ AAA: 7,
506
+ "AA-large": 3,
507
+ "AAA-large": 4.5
508
+ };
509
+ function resolveMinContrast(value) {
510
+ if (typeof value === "number") return Math.max(1, value);
511
+ return CONTRAST_PRESETS[value];
512
+ }
513
+ const CACHE_SIZE = 512;
514
+ const luminanceCache = /* @__PURE__ */ new Map();
515
+ const cacheOrder = [];
516
+ function cachedLuminance(h, s, l) {
517
+ const lRounded = Math.round(l * 1e4) / 1e4;
518
+ const key = `${h}|${s}|${lRounded}`;
519
+ const cached = luminanceCache.get(key);
520
+ if (cached !== void 0) return cached;
521
+ const y = relativeLuminanceFromLinearRgb(okhslToLinearSrgb(h, s, lRounded));
522
+ if (luminanceCache.size >= CACHE_SIZE) {
523
+ const evict = cacheOrder.shift();
524
+ luminanceCache.delete(evict);
525
+ }
526
+ luminanceCache.set(key, y);
527
+ cacheOrder.push(key);
528
+ return y;
529
+ }
530
+ /**
531
+ * Binary search one branch [lo, hi] for the nearest passing lightness to `preferred`.
532
+ */
533
+ function searchBranch(h, s, lo, hi, yBase, target, epsilon, maxIter, preferred) {
534
+ const yLo = cachedLuminance(h, s, lo);
535
+ const yHi = cachedLuminance(h, s, hi);
536
+ const crLo = contrastRatioFromLuminance(yLo, yBase);
537
+ const crHi = contrastRatioFromLuminance(yHi, yBase);
538
+ if (crLo < target && crHi < target) {
539
+ if (crLo >= crHi) return {
540
+ lightness: lo,
541
+ contrast: crLo,
542
+ met: false
543
+ };
544
+ return {
545
+ lightness: hi,
546
+ contrast: crHi,
547
+ met: false
548
+ };
549
+ }
550
+ let low = lo;
551
+ let high = hi;
552
+ for (let i = 0; i < maxIter; i++) {
553
+ if (high - low < epsilon) break;
554
+ const mid = (low + high) / 2;
555
+ if (contrastRatioFromLuminance(cachedLuminance(h, s, mid), yBase) >= target) if (mid < preferred) low = mid;
556
+ else high = mid;
557
+ else if (mid < preferred) high = mid;
558
+ else low = mid;
559
+ }
560
+ const yLow = cachedLuminance(h, s, low);
561
+ const yHigh = cachedLuminance(h, s, high);
562
+ const crLow = contrastRatioFromLuminance(yLow, yBase);
563
+ const crHigh = contrastRatioFromLuminance(yHigh, yBase);
564
+ const lowPasses = crLow >= target;
565
+ const highPasses = crHigh >= target;
566
+ if (lowPasses && highPasses) {
567
+ if (Math.abs(low - preferred) <= Math.abs(high - preferred)) return {
568
+ lightness: low,
569
+ contrast: crLow,
570
+ met: true
571
+ };
572
+ return {
573
+ lightness: high,
574
+ contrast: crHigh,
575
+ met: true
576
+ };
577
+ }
578
+ if (lowPasses) return {
579
+ lightness: low,
580
+ contrast: crLow,
581
+ met: true
582
+ };
583
+ if (highPasses) return {
584
+ lightness: high,
585
+ contrast: crHigh,
586
+ met: true
587
+ };
588
+ return coarseScan(h, s, lo, hi, yBase, target, epsilon, maxIter);
589
+ }
590
+ /**
591
+ * Fallback coarse scan when binary search is unstable near gamut edges.
592
+ */
593
+ function coarseScan(h, s, lo, hi, yBase, target, epsilon, maxIter) {
594
+ const STEPS = 64;
595
+ const step = (hi - lo) / STEPS;
596
+ let bestL = lo;
597
+ let bestCr = 0;
598
+ let bestMet = false;
599
+ for (let i = 0; i <= STEPS; i++) {
600
+ const l = lo + step * i;
601
+ const cr = contrastRatioFromLuminance(cachedLuminance(h, s, l), yBase);
602
+ if (cr >= target && !bestMet) {
603
+ bestL = l;
604
+ bestCr = cr;
605
+ bestMet = true;
606
+ } else if (cr >= target && bestMet) {
607
+ bestL = l;
608
+ bestCr = cr;
609
+ } else if (!bestMet && cr > bestCr) {
610
+ bestL = l;
611
+ bestCr = cr;
612
+ }
613
+ }
614
+ if (bestMet && bestL > lo + step) {
615
+ let rLo = bestL - step;
616
+ let rHi = bestL;
617
+ for (let i = 0; i < maxIter; i++) {
618
+ if (rHi - rLo < epsilon) break;
619
+ const mid = (rLo + rHi) / 2;
620
+ const cr = contrastRatioFromLuminance(cachedLuminance(h, s, mid), yBase);
621
+ if (cr >= target) {
622
+ rHi = mid;
623
+ bestL = mid;
624
+ bestCr = cr;
625
+ } else rLo = mid;
626
+ }
627
+ }
628
+ return {
629
+ lightness: bestL,
630
+ contrast: bestCr,
631
+ met: bestMet
632
+ };
633
+ }
634
+ /**
635
+ * Find the OKHSL lightness that satisfies a WCAG 2 contrast target
636
+ * against a base color, staying as close to `preferredLightness` as possible.
637
+ */
638
+ function findLightnessForContrast(options) {
639
+ const { hue, saturation, preferredLightness, baseLinearRgb, contrast: contrastInput, lightnessRange = [0, 1], epsilon = 1e-4, maxIterations = 14 } = options;
640
+ const target = resolveMinContrast(contrastInput);
641
+ const yBase = relativeLuminanceFromLinearRgb(baseLinearRgb);
642
+ const crPref = contrastRatioFromLuminance(cachedLuminance(hue, saturation, preferredLightness), yBase);
643
+ if (crPref >= target) return {
644
+ lightness: preferredLightness,
645
+ contrast: crPref,
646
+ met: true,
647
+ branch: "preferred"
648
+ };
649
+ const [minL, maxL] = lightnessRange;
650
+ const darkerResult = preferredLightness > minL ? searchBranch(hue, saturation, minL, preferredLightness, yBase, target, epsilon, maxIterations, preferredLightness) : null;
651
+ const lighterResult = preferredLightness < maxL ? searchBranch(hue, saturation, preferredLightness, maxL, yBase, target, epsilon, maxIterations, preferredLightness) : null;
652
+ const darkerPasses = darkerResult?.met ?? false;
653
+ const lighterPasses = lighterResult?.met ?? false;
654
+ if (darkerPasses && lighterPasses) {
655
+ if (Math.abs(darkerResult.lightness - preferredLightness) <= Math.abs(lighterResult.lightness - preferredLightness)) return {
656
+ ...darkerResult,
657
+ branch: "darker"
658
+ };
659
+ return {
660
+ ...lighterResult,
661
+ branch: "lighter"
662
+ };
663
+ }
664
+ if (darkerPasses) return {
665
+ ...darkerResult,
666
+ branch: "darker"
667
+ };
668
+ if (lighterPasses) return {
669
+ ...lighterResult,
670
+ branch: "lighter"
671
+ };
672
+ const candidates = [];
673
+ if (darkerResult) candidates.push({
674
+ ...darkerResult,
675
+ branch: "darker"
676
+ });
677
+ if (lighterResult) candidates.push({
678
+ ...lighterResult,
679
+ branch: "lighter"
680
+ });
681
+ if (candidates.length === 0) return {
682
+ lightness: preferredLightness,
683
+ contrast: crPref,
684
+ met: false,
685
+ branch: "preferred"
686
+ };
687
+ candidates.sort((a, b) => b.contrast - a.contrast);
688
+ return candidates[0];
689
+ }
690
+
691
+ //#endregion
692
+ //#region src/glaze.ts
693
+ /**
694
+ * Glaze — OKHSL-based color theme generator.
695
+ *
696
+ * Generates robust light, dark, and high-contrast colors from a hue/saturation
697
+ * seed, preserving contrast for UI pairs via explicit dependencies.
698
+ */
699
+ let globalConfig = {
700
+ lightLightness: [10, 100],
701
+ darkLightness: [15, 95],
702
+ darkDesaturation: .1,
703
+ states: {
704
+ dark: "@dark",
705
+ highContrast: "@high-contrast"
706
+ },
707
+ modes: {
708
+ dark: true,
709
+ highContrast: false
710
+ }
711
+ };
712
+ function pairNormal(p) {
713
+ return Array.isArray(p) ? p[0] : p;
714
+ }
715
+ function pairHC(p) {
716
+ return Array.isArray(p) ? p[1] : p;
717
+ }
718
+ function isShadowDef(def) {
719
+ return def.type === "shadow";
720
+ }
721
+ const DEFAULT_SHADOW_TUNING = {
722
+ saturationFactor: .18,
723
+ maxSaturation: .25,
724
+ lightnessFactor: .25,
725
+ lightnessBounds: [.05, .2],
726
+ minGapTarget: .05,
727
+ alphaMax: 1,
728
+ bgHueBlend: .2
729
+ };
730
+ function resolveShadowTuning(perColor) {
731
+ return {
732
+ ...DEFAULT_SHADOW_TUNING,
733
+ ...globalConfig.shadowTuning,
734
+ ...perColor,
735
+ lightnessBounds: perColor?.lightnessBounds ?? globalConfig.shadowTuning?.lightnessBounds ?? DEFAULT_SHADOW_TUNING.lightnessBounds
736
+ };
737
+ }
738
+ function circularLerp(a, b, t) {
739
+ let diff = b - a;
740
+ if (diff > 180) diff -= 360;
741
+ else if (diff < -180) diff += 360;
742
+ return ((a + diff * t) % 360 + 360) % 360;
743
+ }
744
+ /**
745
+ * Compute the canonical max-contrast reference t value for normalization.
746
+ * Uses bg.l=1, fg.l=0, intensity=100 — the theoretical maximum.
747
+ * This is a fixed constant per tuning configuration, ensuring uniform
748
+ * scaling across all bg/fg pairs at low intensities.
749
+ */
750
+ function computeRefT(tuning) {
751
+ const EPSILON = 1e-6;
752
+ let lShRef = clamp(tuning.lightnessFactor, tuning.lightnessBounds[0], tuning.lightnessBounds[1]);
753
+ lShRef = Math.max(Math.min(lShRef, 1 - tuning.minGapTarget), 0);
754
+ return 1 / Math.max(1 - lShRef, EPSILON);
755
+ }
756
+ function computeShadow(bg, fg, intensity, tuning) {
757
+ const EPSILON = 1e-6;
758
+ const clampedIntensity = clamp(intensity, 0, 100);
759
+ const contrastWeight = fg ? Math.abs(bg.l - fg.l) : 1;
760
+ const deltaL = clampedIntensity / 100 * contrastWeight;
761
+ const h = fg ? circularLerp(fg.h, bg.h, tuning.bgHueBlend) : bg.h;
762
+ const s = fg ? Math.min(fg.s * tuning.saturationFactor, tuning.maxSaturation) : 0;
763
+ let lSh = clamp(bg.l * tuning.lightnessFactor, tuning.lightnessBounds[0], tuning.lightnessBounds[1]);
764
+ lSh = Math.max(Math.min(lSh, bg.l - tuning.minGapTarget), 0);
765
+ const t = deltaL / Math.max(bg.l - lSh, EPSILON);
766
+ const tRef = computeRefT(tuning);
767
+ const norm = Math.tanh(tRef / tuning.alphaMax);
768
+ const alpha = Math.min(tuning.alphaMax * Math.tanh(t / tuning.alphaMax) / norm, tuning.alphaMax);
769
+ return {
770
+ h,
771
+ s,
772
+ l: lSh,
773
+ alpha
774
+ };
775
+ }
776
+ function validateColorDefs(defs) {
777
+ const names = new Set(Object.keys(defs));
778
+ for (const [name, def] of Object.entries(defs)) {
779
+ if (isShadowDef(def)) {
780
+ if (!names.has(def.bg)) throw new Error(`glaze: shadow "${name}" references non-existent bg "${def.bg}".`);
781
+ if (isShadowDef(defs[def.bg])) throw new Error(`glaze: shadow "${name}" bg "${def.bg}" references another shadow color.`);
782
+ if (def.fg !== void 0) {
783
+ if (!names.has(def.fg)) throw new Error(`glaze: shadow "${name}" references non-existent fg "${def.fg}".`);
784
+ if (isShadowDef(defs[def.fg])) throw new Error(`glaze: shadow "${name}" fg "${def.fg}" references another shadow color.`);
785
+ }
786
+ continue;
787
+ }
788
+ const regDef = def;
789
+ if (regDef.contrast !== void 0 && !regDef.base) throw new Error(`glaze: color "${name}" has "contrast" without "base".`);
790
+ if (regDef.lightness !== void 0 && !isAbsoluteLightness(regDef.lightness) && !regDef.base) throw new Error(`glaze: color "${name}" has relative "lightness" without "base".`);
791
+ if (isAbsoluteLightness(regDef.lightness) && regDef.base !== void 0) console.warn(`glaze: color "${name}" has absolute "lightness" and "base". Absolute lightness takes precedence.`);
792
+ if (regDef.base && !names.has(regDef.base)) throw new Error(`glaze: color "${name}" references non-existent base "${regDef.base}".`);
793
+ if (regDef.base && isShadowDef(defs[regDef.base])) throw new Error(`glaze: color "${name}" base "${regDef.base}" references a shadow color.`);
794
+ if (!isAbsoluteLightness(regDef.lightness) && regDef.base === void 0) throw new Error(`glaze: color "${name}" must have either absolute "lightness" (root) or "base" (dependent).`);
795
+ if (regDef.contrast !== void 0 && regDef.opacity !== void 0) console.warn(`glaze: color "${name}" has both "contrast" and "opacity". Opacity makes perceived lightness unpredictable.`);
796
+ }
797
+ const visited = /* @__PURE__ */ new Set();
798
+ const inStack = /* @__PURE__ */ new Set();
799
+ function dfs(name) {
800
+ if (inStack.has(name)) throw new Error(`glaze: circular base reference detected involving "${name}".`);
801
+ if (visited.has(name)) return;
802
+ inStack.add(name);
803
+ const def = defs[name];
804
+ if (isShadowDef(def)) {
805
+ dfs(def.bg);
806
+ if (def.fg) dfs(def.fg);
807
+ } else {
808
+ const regDef = def;
809
+ if (regDef.base) dfs(regDef.base);
810
+ }
811
+ inStack.delete(name);
812
+ visited.add(name);
813
+ }
814
+ for (const name of names) dfs(name);
815
+ }
816
+ function topoSort(defs) {
817
+ const result = [];
818
+ const visited = /* @__PURE__ */ new Set();
819
+ function visit(name) {
820
+ if (visited.has(name)) return;
821
+ visited.add(name);
822
+ const def = defs[name];
823
+ if (isShadowDef(def)) {
824
+ visit(def.bg);
825
+ if (def.fg) visit(def.fg);
826
+ } else {
827
+ const regDef = def;
828
+ if (regDef.base) visit(regDef.base);
829
+ }
830
+ result.push(name);
831
+ }
832
+ for (const name of Object.keys(defs)) visit(name);
833
+ return result;
834
+ }
835
+ function mapLightnessLight(l, mode) {
836
+ if (mode === "static") return l;
837
+ const [lo, hi] = globalConfig.lightLightness;
838
+ return l * (hi - lo) / 100 + lo;
839
+ }
840
+ function mapLightnessDark(l, mode) {
841
+ if (mode === "static") return l;
842
+ const [lo, hi] = globalConfig.darkLightness;
843
+ if (mode === "fixed") return l * (hi - lo) / 100 + lo;
844
+ return (100 - l) * (hi - lo) / 100 + lo;
845
+ }
846
+ function mapSaturationDark(s, mode) {
847
+ if (mode === "static") return s;
848
+ return s * (1 - globalConfig.darkDesaturation);
849
+ }
850
+ function clamp(v, min, max) {
851
+ return Math.max(min, Math.min(max, v));
852
+ }
853
+ /**
854
+ * Parse a value that can be absolute (number) or relative (signed string).
855
+ * Returns the numeric value and whether it's relative.
856
+ */
857
+ function parseRelativeOrAbsolute(value) {
858
+ if (typeof value === "number") return {
859
+ value,
860
+ relative: false
861
+ };
862
+ return {
863
+ value: parseFloat(value),
864
+ relative: true
865
+ };
866
+ }
867
+ /**
868
+ * Compute the effective hue for a color, given the theme seed hue
869
+ * and an optional per-color hue override.
870
+ */
871
+ function resolveEffectiveHue(seedHue, defHue) {
872
+ if (defHue === void 0) return seedHue;
873
+ const parsed = parseRelativeOrAbsolute(defHue);
874
+ if (parsed.relative) return ((seedHue + parsed.value) % 360 + 360) % 360;
875
+ return (parsed.value % 360 + 360) % 360;
876
+ }
877
+ /**
878
+ * Check whether a lightness value represents an absolute root definition
879
+ * (i.e. a number, not a relative string).
880
+ */
881
+ function isAbsoluteLightness(lightness) {
882
+ if (lightness === void 0) return false;
883
+ return typeof (Array.isArray(lightness) ? lightness[0] : lightness) === "number";
884
+ }
885
+ function resolveRootColor(_name, def, _ctx, isHighContrast) {
886
+ const rawL = def.lightness;
887
+ return {
888
+ lightL: clamp(parseRelativeOrAbsolute(isHighContrast ? pairHC(rawL) : pairNormal(rawL)).value, 0, 100),
889
+ satFactor: clamp(def.saturation ?? 1, 0, 1)
890
+ };
891
+ }
892
+ function resolveDependentColor(name, def, ctx, isHighContrast, isDark, effectiveHue) {
893
+ const baseName = def.base;
894
+ const baseResolved = ctx.resolved.get(baseName);
895
+ if (!baseResolved) throw new Error(`glaze: base "${baseName}" not yet resolved for "${name}".`);
896
+ const mode = def.mode ?? "auto";
897
+ const satFactor = clamp(def.saturation ?? 1, 0, 1);
898
+ const baseVariant = getSchemeVariant(baseResolved, isDark, isHighContrast);
899
+ const baseL = baseVariant.l * 100;
900
+ let preferredL;
901
+ const rawLightness = def.lightness;
902
+ if (rawLightness === void 0) preferredL = baseL;
903
+ else {
904
+ const parsed = parseRelativeOrAbsolute(isHighContrast ? pairHC(rawLightness) : pairNormal(rawLightness));
905
+ if (parsed.relative) {
906
+ let delta = parsed.value;
907
+ if (isDark && mode === "auto") delta = -delta;
908
+ preferredL = clamp(baseL + delta, 0, 100);
909
+ } else if (isDark) preferredL = mapLightnessDark(parsed.value, mode);
910
+ else preferredL = clamp(parsed.value, 0, 100);
911
+ }
912
+ const rawContrast = def.contrast;
913
+ if (rawContrast !== void 0) {
914
+ const minCr = isHighContrast ? pairHC(rawContrast) : pairNormal(rawContrast);
915
+ const effectiveSat = isDark ? mapSaturationDark(satFactor * ctx.saturation / 100, mode) : satFactor * ctx.saturation / 100;
916
+ const baseLinearRgb = okhslToLinearSrgb(baseVariant.h, baseVariant.s, baseVariant.l);
917
+ return {
918
+ l: findLightnessForContrast({
919
+ hue: effectiveHue,
920
+ saturation: effectiveSat,
921
+ preferredLightness: preferredL / 100,
922
+ baseLinearRgb,
923
+ contrast: minCr
924
+ }).lightness * 100,
925
+ satFactor
926
+ };
927
+ }
928
+ return {
929
+ l: clamp(preferredL, 0, 100),
930
+ satFactor
931
+ };
932
+ }
933
+ function getSchemeVariant(color, isDark, isHighContrast) {
934
+ if (isDark && isHighContrast) return color.darkContrast;
935
+ if (isDark) return color.dark;
936
+ if (isHighContrast) return color.lightContrast;
937
+ return color.light;
938
+ }
939
+ function resolveColorForScheme(name, def, ctx, isDark, isHighContrast) {
940
+ if (isShadowDef(def)) return resolveShadowForScheme(def, ctx, isDark, isHighContrast);
941
+ const regDef = def;
942
+ const mode = regDef.mode ?? "auto";
943
+ const isRoot = isAbsoluteLightness(regDef.lightness) && !regDef.base;
944
+ const effectiveHue = resolveEffectiveHue(ctx.hue, regDef.hue);
945
+ let lightL;
946
+ let satFactor;
947
+ if (isRoot) {
948
+ const root = resolveRootColor(name, regDef, ctx, isHighContrast);
949
+ lightL = root.lightL;
950
+ satFactor = root.satFactor;
951
+ } else {
952
+ const dep = resolveDependentColor(name, regDef, ctx, isHighContrast, isDark, effectiveHue);
953
+ lightL = dep.l;
954
+ satFactor = dep.satFactor;
955
+ }
956
+ let finalL;
957
+ let finalSat;
958
+ if (isDark && isRoot) {
959
+ finalL = mapLightnessDark(lightL, mode);
960
+ finalSat = mapSaturationDark(satFactor * ctx.saturation / 100, mode);
961
+ } else if (isDark && !isRoot) {
962
+ finalL = lightL;
963
+ finalSat = mapSaturationDark(satFactor * ctx.saturation / 100, mode);
964
+ } else if (isRoot) {
965
+ finalL = mapLightnessLight(lightL, mode);
966
+ finalSat = satFactor * ctx.saturation / 100;
967
+ } else {
968
+ finalL = lightL;
969
+ finalSat = satFactor * ctx.saturation / 100;
970
+ }
971
+ return {
972
+ h: effectiveHue,
973
+ s: clamp(finalSat, 0, 1),
974
+ l: clamp(finalL / 100, 0, 1),
975
+ alpha: regDef.opacity ?? 1
976
+ };
977
+ }
978
+ function resolveShadowForScheme(def, ctx, isDark, isHighContrast) {
979
+ const bgVariant = getSchemeVariant(ctx.resolved.get(def.bg), isDark, isHighContrast);
980
+ let fgVariant;
981
+ if (def.fg) fgVariant = getSchemeVariant(ctx.resolved.get(def.fg), isDark, isHighContrast);
982
+ const intensity = isHighContrast ? pairHC(def.intensity) : pairNormal(def.intensity);
983
+ const tuning = resolveShadowTuning(def.tuning);
984
+ return computeShadow(bgVariant, fgVariant, intensity, tuning);
985
+ }
986
+ function resolveAllColors(hue, saturation, defs) {
987
+ validateColorDefs(defs);
988
+ const order = topoSort(defs);
989
+ const ctx = {
990
+ hue,
991
+ saturation,
992
+ defs,
993
+ resolved: /* @__PURE__ */ new Map()
994
+ };
995
+ function defMode(def) {
996
+ return isShadowDef(def) ? void 0 : def.mode ?? "auto";
997
+ }
998
+ const lightMap = /* @__PURE__ */ new Map();
999
+ for (const name of order) {
1000
+ const variant = resolveColorForScheme(name, defs[name], ctx, false, false);
1001
+ lightMap.set(name, variant);
1002
+ ctx.resolved.set(name, {
1003
+ name,
1004
+ light: variant,
1005
+ dark: variant,
1006
+ lightContrast: variant,
1007
+ darkContrast: variant,
1008
+ mode: defMode(defs[name])
1009
+ });
1010
+ }
1011
+ const lightHCMap = /* @__PURE__ */ new Map();
1012
+ for (const name of order) ctx.resolved.set(name, {
1013
+ ...ctx.resolved.get(name),
1014
+ lightContrast: lightMap.get(name)
1015
+ });
1016
+ for (const name of order) {
1017
+ const variant = resolveColorForScheme(name, defs[name], ctx, false, true);
1018
+ lightHCMap.set(name, variant);
1019
+ ctx.resolved.set(name, {
1020
+ ...ctx.resolved.get(name),
1021
+ lightContrast: variant
1022
+ });
1023
+ }
1024
+ const darkMap = /* @__PURE__ */ new Map();
1025
+ for (const name of order) ctx.resolved.set(name, {
1026
+ name,
1027
+ light: lightMap.get(name),
1028
+ dark: lightMap.get(name),
1029
+ lightContrast: lightHCMap.get(name),
1030
+ darkContrast: lightHCMap.get(name),
1031
+ mode: defMode(defs[name])
1032
+ });
1033
+ for (const name of order) {
1034
+ const variant = resolveColorForScheme(name, defs[name], ctx, true, false);
1035
+ darkMap.set(name, variant);
1036
+ ctx.resolved.set(name, {
1037
+ ...ctx.resolved.get(name),
1038
+ dark: variant
1039
+ });
1040
+ }
1041
+ const darkHCMap = /* @__PURE__ */ new Map();
1042
+ for (const name of order) ctx.resolved.set(name, {
1043
+ ...ctx.resolved.get(name),
1044
+ darkContrast: darkMap.get(name)
1045
+ });
1046
+ for (const name of order) {
1047
+ const variant = resolveColorForScheme(name, defs[name], ctx, true, true);
1048
+ darkHCMap.set(name, variant);
1049
+ ctx.resolved.set(name, {
1050
+ ...ctx.resolved.get(name),
1051
+ darkContrast: variant
1052
+ });
1053
+ }
1054
+ const result = /* @__PURE__ */ new Map();
1055
+ for (const name of order) result.set(name, {
1056
+ name,
1057
+ light: lightMap.get(name),
1058
+ dark: darkMap.get(name),
1059
+ lightContrast: lightHCMap.get(name),
1060
+ darkContrast: darkHCMap.get(name),
1061
+ mode: defMode(defs[name])
1062
+ });
1063
+ return result;
1064
+ }
1065
+ const formatters = {
1066
+ okhsl: formatOkhsl,
1067
+ rgb: formatRgb,
1068
+ hsl: formatHsl,
1069
+ oklch: formatOklch
1070
+ };
1071
+ function fmt(value, decimals) {
1072
+ return parseFloat(value.toFixed(decimals)).toString();
1073
+ }
1074
+ function formatVariant(v, format = "okhsl") {
1075
+ const base = formatters[format](v.h, v.s * 100, v.l * 100);
1076
+ if (v.alpha >= 1) return base;
1077
+ const closing = base.lastIndexOf(")");
1078
+ return `${base.slice(0, closing)} / ${fmt(v.alpha, 4)})`;
1079
+ }
1080
+ function resolveModes(override) {
1081
+ return {
1082
+ dark: override?.dark ?? globalConfig.modes.dark,
1083
+ highContrast: override?.highContrast ?? globalConfig.modes.highContrast
1084
+ };
1085
+ }
1086
+ function buildTokenMap(resolved, prefix, states, modes, format = "okhsl") {
1087
+ const tokens = {};
1088
+ for (const [name, color] of resolved) {
1089
+ const key = `#${prefix}${name}`;
1090
+ const entry = { "": formatVariant(color.light, format) };
1091
+ if (modes.dark) entry[states.dark] = formatVariant(color.dark, format);
1092
+ if (modes.highContrast) entry[states.highContrast] = formatVariant(color.lightContrast, format);
1093
+ if (modes.dark && modes.highContrast) entry[`${states.dark} & ${states.highContrast}`] = formatVariant(color.darkContrast, format);
1094
+ tokens[key] = entry;
1095
+ }
1096
+ return tokens;
1097
+ }
1098
+ function buildFlatTokenMap(resolved, prefix, modes, format = "okhsl") {
1099
+ const result = { light: {} };
1100
+ if (modes.dark) result.dark = {};
1101
+ if (modes.highContrast) result.lightContrast = {};
1102
+ if (modes.dark && modes.highContrast) result.darkContrast = {};
1103
+ for (const [name, color] of resolved) {
1104
+ const key = `${prefix}${name}`;
1105
+ result.light[key] = formatVariant(color.light, format);
1106
+ if (modes.dark) result.dark[key] = formatVariant(color.dark, format);
1107
+ if (modes.highContrast) result.lightContrast[key] = formatVariant(color.lightContrast, format);
1108
+ if (modes.dark && modes.highContrast) result.darkContrast[key] = formatVariant(color.darkContrast, format);
1109
+ }
1110
+ return result;
1111
+ }
1112
+ function buildJsonMap(resolved, modes, format = "okhsl") {
1113
+ const result = {};
1114
+ for (const [name, color] of resolved) {
1115
+ const entry = { light: formatVariant(color.light, format) };
1116
+ if (modes.dark) entry.dark = formatVariant(color.dark, format);
1117
+ if (modes.highContrast) entry.lightContrast = formatVariant(color.lightContrast, format);
1118
+ if (modes.dark && modes.highContrast) entry.darkContrast = formatVariant(color.darkContrast, format);
1119
+ result[name] = entry;
1120
+ }
1121
+ return result;
1122
+ }
1123
+ function buildCssMap(resolved, prefix, suffix, format) {
1124
+ const lines = {
1125
+ light: [],
1126
+ dark: [],
1127
+ lightContrast: [],
1128
+ darkContrast: []
1129
+ };
1130
+ for (const [name, color] of resolved) {
1131
+ const prop = `--${prefix}${name}${suffix}`;
1132
+ lines.light.push(`${prop}: ${formatVariant(color.light, format)};`);
1133
+ lines.dark.push(`${prop}: ${formatVariant(color.dark, format)};`);
1134
+ lines.lightContrast.push(`${prop}: ${formatVariant(color.lightContrast, format)};`);
1135
+ lines.darkContrast.push(`${prop}: ${formatVariant(color.darkContrast, format)};`);
1136
+ }
1137
+ return {
1138
+ light: lines.light.join("\n"),
1139
+ dark: lines.dark.join("\n"),
1140
+ lightContrast: lines.lightContrast.join("\n"),
1141
+ darkContrast: lines.darkContrast.join("\n")
1142
+ };
1143
+ }
1144
+ function createTheme(hue, saturation, initialColors) {
1145
+ let colorDefs = initialColors ? { ...initialColors } : {};
1146
+ return {
1147
+ get hue() {
1148
+ return hue;
1149
+ },
1150
+ get saturation() {
1151
+ return saturation;
1152
+ },
1153
+ colors(defs) {
1154
+ colorDefs = {
1155
+ ...colorDefs,
1156
+ ...defs
1157
+ };
1158
+ },
1159
+ color(name, def) {
1160
+ if (def === void 0) return colorDefs[name];
1161
+ colorDefs[name] = def;
1162
+ },
1163
+ remove(names) {
1164
+ const list = Array.isArray(names) ? names : [names];
1165
+ for (const name of list) delete colorDefs[name];
1166
+ },
1167
+ has(name) {
1168
+ return name in colorDefs;
1169
+ },
1170
+ list() {
1171
+ return Object.keys(colorDefs);
1172
+ },
1173
+ reset() {
1174
+ colorDefs = {};
1175
+ },
1176
+ export() {
1177
+ return {
1178
+ hue,
1179
+ saturation,
1180
+ colors: { ...colorDefs }
1181
+ };
1182
+ },
1183
+ extend(options) {
1184
+ return createTheme(options.hue ?? hue, options.saturation ?? saturation, options.colors ? {
1185
+ ...colorDefs,
1186
+ ...options.colors
1187
+ } : { ...colorDefs });
1188
+ },
1189
+ resolve() {
1190
+ return resolveAllColors(hue, saturation, colorDefs);
1191
+ },
1192
+ tokens(options) {
1193
+ return buildFlatTokenMap(resolveAllColors(hue, saturation, colorDefs), "", resolveModes(options?.modes), options?.format);
1194
+ },
1195
+ tasty(options) {
1196
+ return buildTokenMap(resolveAllColors(hue, saturation, colorDefs), "", {
1197
+ dark: options?.states?.dark ?? globalConfig.states.dark,
1198
+ highContrast: options?.states?.highContrast ?? globalConfig.states.highContrast
1199
+ }, resolveModes(options?.modes), options?.format);
1200
+ },
1201
+ json(options) {
1202
+ return buildJsonMap(resolveAllColors(hue, saturation, colorDefs), resolveModes(options?.modes), options?.format);
1203
+ },
1204
+ css(options) {
1205
+ return buildCssMap(resolveAllColors(hue, saturation, colorDefs), "", options?.suffix ?? "-color", options?.format ?? "rgb");
1206
+ }
1207
+ };
1208
+ }
1209
+ function resolvePrefix(options, themeName) {
1210
+ if (options?.prefix === true) return `${themeName}-`;
1211
+ if (typeof options?.prefix === "object" && options.prefix !== null) return options.prefix[themeName] ?? `${themeName}-`;
1212
+ return "";
1213
+ }
1214
+ function createPalette(themes) {
1215
+ return {
1216
+ tokens(options) {
1217
+ const modes = resolveModes(options?.modes);
1218
+ const allTokens = {};
1219
+ for (const [themeName, theme] of Object.entries(themes)) {
1220
+ const tokens = buildFlatTokenMap(theme.resolve(), resolvePrefix(options, themeName), modes, options?.format);
1221
+ for (const variant of Object.keys(tokens)) {
1222
+ if (!allTokens[variant]) allTokens[variant] = {};
1223
+ Object.assign(allTokens[variant], tokens[variant]);
1224
+ }
1225
+ }
1226
+ return allTokens;
1227
+ },
1228
+ tasty(options) {
1229
+ const states = {
1230
+ dark: options?.states?.dark ?? globalConfig.states.dark,
1231
+ highContrast: options?.states?.highContrast ?? globalConfig.states.highContrast
1232
+ };
1233
+ const modes = resolveModes(options?.modes);
1234
+ const allTokens = {};
1235
+ for (const [themeName, theme] of Object.entries(themes)) {
1236
+ const tokens = buildTokenMap(theme.resolve(), resolvePrefix(options, themeName), states, modes, options?.format);
1237
+ Object.assign(allTokens, tokens);
1238
+ }
1239
+ return allTokens;
1240
+ },
1241
+ json(options) {
1242
+ const modes = resolveModes(options?.modes);
1243
+ const result = {};
1244
+ for (const [themeName, theme] of Object.entries(themes)) result[themeName] = buildJsonMap(theme.resolve(), modes, options?.format);
1245
+ return result;
1246
+ },
1247
+ css(options) {
1248
+ const suffix = options?.suffix ?? "-color";
1249
+ const format = options?.format ?? "rgb";
1250
+ const allLines = {
1251
+ light: [],
1252
+ dark: [],
1253
+ lightContrast: [],
1254
+ darkContrast: []
1255
+ };
1256
+ for (const [themeName, theme] of Object.entries(themes)) {
1257
+ const css = buildCssMap(theme.resolve(), resolvePrefix(options, themeName), suffix, format);
1258
+ for (const key of [
1259
+ "light",
1260
+ "dark",
1261
+ "lightContrast",
1262
+ "darkContrast"
1263
+ ]) if (css[key]) allLines[key].push(css[key]);
1264
+ }
1265
+ return {
1266
+ light: allLines.light.join("\n"),
1267
+ dark: allLines.dark.join("\n"),
1268
+ lightContrast: allLines.lightContrast.join("\n"),
1269
+ darkContrast: allLines.darkContrast.join("\n")
1270
+ };
1271
+ }
1272
+ };
1273
+ }
1274
+ function createColorToken(input) {
1275
+ const defs = { __color__: {
1276
+ lightness: input.lightness,
1277
+ saturation: input.saturationFactor,
1278
+ mode: input.mode
1279
+ } };
1280
+ return {
1281
+ resolve() {
1282
+ return resolveAllColors(input.hue, input.saturation, defs).get("__color__");
1283
+ },
1284
+ token(options) {
1285
+ return buildTokenMap(resolveAllColors(input.hue, input.saturation, defs), "", {
1286
+ dark: options?.states?.dark ?? globalConfig.states.dark,
1287
+ highContrast: options?.states?.highContrast ?? globalConfig.states.highContrast
1288
+ }, resolveModes(options?.modes), options?.format)["#__color__"];
1289
+ },
1290
+ tasty(options) {
1291
+ return buildTokenMap(resolveAllColors(input.hue, input.saturation, defs), "", {
1292
+ dark: options?.states?.dark ?? globalConfig.states.dark,
1293
+ highContrast: options?.states?.highContrast ?? globalConfig.states.highContrast
1294
+ }, resolveModes(options?.modes), options?.format)["#__color__"];
1295
+ },
1296
+ json(options) {
1297
+ return buildJsonMap(resolveAllColors(input.hue, input.saturation, defs), resolveModes(options?.modes), options?.format)["__color__"];
1298
+ }
1299
+ };
1300
+ }
1301
+ /**
1302
+ * Create a single-hue glaze theme.
1303
+ *
1304
+ * @example
1305
+ * ```ts
1306
+ * const primary = glaze({ hue: 280, saturation: 80 });
1307
+ * // or shorthand:
1308
+ * const primary = glaze(280, 80);
1309
+ * ```
1310
+ */
1311
+ function glaze(hueOrOptions, saturation) {
1312
+ if (typeof hueOrOptions === "number") return createTheme(hueOrOptions, saturation ?? 100);
1313
+ return createTheme(hueOrOptions.hue, hueOrOptions.saturation);
1314
+ }
1315
+ /**
1316
+ * Configure global glaze settings.
1317
+ */
1318
+ glaze.configure = function configure(config) {
1319
+ globalConfig = {
1320
+ lightLightness: config.lightLightness ?? globalConfig.lightLightness,
1321
+ darkLightness: config.darkLightness ?? globalConfig.darkLightness,
1322
+ darkDesaturation: config.darkDesaturation ?? globalConfig.darkDesaturation,
1323
+ states: {
1324
+ dark: config.states?.dark ?? globalConfig.states.dark,
1325
+ highContrast: config.states?.highContrast ?? globalConfig.states.highContrast
1326
+ },
1327
+ modes: {
1328
+ dark: config.modes?.dark ?? globalConfig.modes.dark,
1329
+ highContrast: config.modes?.highContrast ?? globalConfig.modes.highContrast
1330
+ },
1331
+ shadowTuning: config.shadowTuning ?? globalConfig.shadowTuning
1332
+ };
1333
+ };
1334
+ /**
1335
+ * Compose multiple themes into a palette.
1336
+ */
1337
+ glaze.palette = function palette(themes) {
1338
+ return createPalette(themes);
1339
+ };
1340
+ /**
1341
+ * Create a theme from a serialized export.
1342
+ */
1343
+ glaze.from = function from(data) {
1344
+ return createTheme(data.hue, data.saturation, data.colors);
1345
+ };
1346
+ /**
1347
+ * Create a standalone single-color token.
1348
+ */
1349
+ glaze.color = function color(input) {
1350
+ return createColorToken(input);
1351
+ };
1352
+ /**
1353
+ * Compute a shadow color from a bg/fg pair and intensity.
1354
+ */
1355
+ glaze.shadow = function shadow(input) {
1356
+ const bg = parseOkhslInput(input.bg);
1357
+ const fg = input.fg ? parseOkhslInput(input.fg) : void 0;
1358
+ const tuning = resolveShadowTuning(input.tuning);
1359
+ return computeShadow({
1360
+ ...bg,
1361
+ alpha: 1
1362
+ }, fg ? {
1363
+ ...fg,
1364
+ alpha: 1
1365
+ } : void 0, input.intensity, tuning);
1366
+ };
1367
+ /**
1368
+ * Format a resolved color variant as a CSS string.
1369
+ */
1370
+ glaze.format = function format(variant, colorFormat) {
1371
+ return formatVariant(variant, colorFormat);
1372
+ };
1373
+ function parseOkhslInput(input) {
1374
+ if (typeof input === "string") {
1375
+ const rgb = parseHex(input);
1376
+ if (!rgb) throw new Error(`glaze: invalid hex color "${input}".`);
1377
+ const [h, s, l] = srgbToOkhsl(rgb);
1378
+ return {
1379
+ h,
1380
+ s,
1381
+ l
1382
+ };
1383
+ }
1384
+ return input;
1385
+ }
1386
+ /**
1387
+ * Create a theme from a hex color string.
1388
+ * Extracts hue and saturation from the color.
1389
+ */
1390
+ glaze.fromHex = function fromHex(hex) {
1391
+ const rgb = parseHex(hex);
1392
+ if (!rgb) throw new Error(`glaze: invalid hex color "${hex}".`);
1393
+ const [h, s] = srgbToOkhsl(rgb);
1394
+ return createTheme(h, s * 100);
1395
+ };
1396
+ /**
1397
+ * Create a theme from RGB values (0–255).
1398
+ * Extracts hue and saturation from the color.
1399
+ */
1400
+ glaze.fromRgb = function fromRgb(r, g, b) {
1401
+ const [h, s] = srgbToOkhsl([
1402
+ r / 255,
1403
+ g / 255,
1404
+ b / 255
1405
+ ]);
1406
+ return createTheme(h, s * 100);
1407
+ };
1408
+ /**
1409
+ * Get the current global configuration (for testing/debugging).
1410
+ */
1411
+ glaze.getConfig = function getConfig() {
1412
+ return { ...globalConfig };
1413
+ };
1414
+ /**
1415
+ * Reset global configuration to defaults.
1416
+ */
1417
+ glaze.resetConfig = function resetConfig() {
1418
+ globalConfig = {
1419
+ lightLightness: [10, 100],
1420
+ darkLightness: [15, 95],
1421
+ darkDesaturation: .1,
1422
+ states: {
1423
+ dark: "@dark",
1424
+ highContrast: "@high-contrast"
1425
+ },
1426
+ modes: {
1427
+ dark: true,
1428
+ highContrast: false
1429
+ }
1430
+ };
1431
+ };
1432
+
1433
+ //#endregion
1434
+ exports.contrastRatioFromLuminance = contrastRatioFromLuminance;
1435
+ exports.findLightnessForContrast = findLightnessForContrast;
1436
+ exports.formatHsl = formatHsl;
1437
+ exports.formatOkhsl = formatOkhsl;
1438
+ exports.formatOklch = formatOklch;
1439
+ exports.formatRgb = formatRgb;
1440
+ exports.glaze = glaze;
1441
+ exports.okhslToLinearSrgb = okhslToLinearSrgb;
1442
+ exports.okhslToOklab = okhslToOklab;
1443
+ exports.okhslToSrgb = okhslToSrgb;
1444
+ exports.parseHex = parseHex;
1445
+ exports.relativeLuminanceFromLinearRgb = relativeLuminanceFromLinearRgb;
1446
+ exports.resolveMinContrast = resolveMinContrast;
1447
+ exports.srgbToOkhsl = srgbToOkhsl;
1448
+ //# sourceMappingURL=index.cjs.map