@umber-style/core 0.1.0-alpha.0 → 0.1.0-alpha.1

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.mjs CHANGED
@@ -1,11 +1,45 @@
1
+ // src/standIn.ts
2
+ const BRAND$3 = Symbol.for("umber-style.stand-in");
3
+ /**
4
+ * A stand-in for the theme at `path` (a dotted path, '' for the theme itself): any key read from it is
5
+ * a stand-in one level down, a call is a stand-in for `path(arguments)` (a helper of the theme such as
6
+ * `breakpoints.up('md')`), a symbol reads as undefined, listing its keys throws, calling it with a function throws, and as text it is its path. `keyframes` and
7
+ * `globalStyles` name the styles of a function of the theme with it, so that the name does not depend on
8
+ * the theme's values.
9
+ */
10
+ function createStandIn(path) {
11
+ const call = (...values) => {
12
+ if (values.some((value) => typeof value === "function" && !isStandIn(value))) throw new TypeError(`A function of the theme given to keyframes() or globalStyles() cannot pass a function to "${path}": its name is made before the theme is known. Read each token by its key.`);
13
+ return createStandIn(`${path}(${values.map(String).join(",")})`);
14
+ };
15
+ return new Proxy(call, {
16
+ get: (_target, key) => {
17
+ if (key === Symbol.toPrimitive) return () => path;
18
+ if (typeof key === "symbol") return void 0;
19
+ return createStandIn(path === "" ? key : `${path}.${key}`);
20
+ },
21
+ has: (_target, key) => key === BRAND$3,
22
+ ownKeys: () => {
23
+ throw new TypeError(`A function of the theme given to keyframes() or globalStyles() cannot list the keys of "${path}" (Object.keys, a spread, for...in): its name is made before the theme is known. Read each token by its key.`);
24
+ }
25
+ });
26
+ }
27
+ /** Whether `value` was made by `createStandIn`. */
28
+ function isStandIn(value) {
29
+ return typeof value === "function" && BRAND$3 in value;
30
+ }
31
+ /** `value` as its path when it is a stand-in, else `value` itself: a helper that computes with a token takes a stand-in as the text of a reference. */
32
+ function readStandIn(value) {
33
+ return isStandIn(value) ? String(value) : value;
34
+ }
1
35
  // src/alpha.ts
2
- const BRAND$1 = Symbol.for("umber-style.alpha-color");
36
+ const BRAND$2 = Symbol.for("umber-style.alpha-color");
3
37
  const NUMBER$1 = String.raw`[+-]?(?:\d+\.?\d*|\.\d+)`;
4
38
  const HEX_PATTERN = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
5
39
  const FUNCTION_PATTERNS = [new RegExp(String.raw`^rgba?\(\s*(${NUMBER$1})\s*,\s*(${NUMBER$1})\s*,\s*(${NUMBER$1})\s*(?:,\s*(${NUMBER$1}%?)\s*)?\)$`, "i"), new RegExp(String.raw`^rgba?\(\s*(${NUMBER$1})\s+(${NUMBER$1})\s+(${NUMBER$1})\s*(?:/\s*(${NUMBER$1}%?)\s*)?\)$`, "i")];
6
40
  /** Whether `value` was made by `alpha()` as a mix: a plain string is a color, not a fallback pair. */
7
41
  function isAlphaColor(value) {
8
- return typeof value === "object" && value !== null && BRAND$1 in value;
42
+ return typeof value === "object" && value !== null && BRAND$2 in value;
9
43
  }
10
44
  /** `value` limited to `low` through `high`. */
11
45
  function clamp(value, low, high) {
@@ -77,14 +111,15 @@ function assertAlphaInput(color, opacity) {
77
111
  * that is not a string or an opacity that is not a number, a `RangeError` for an opacity outside 0 to 1.
78
112
  */
79
113
  function alpha(color, opacity) {
80
- assertAlphaInput(color, opacity);
81
- if (opacity === 1) return color;
114
+ const text = readStandIn(color);
115
+ assertAlphaInput(text, opacity);
116
+ if (opacity === 1) return text;
82
117
  if (opacity === 0) return "transparent";
83
- const value = `color-mix(in srgb, ${color} ${Math.round(opacity * 1e4) / 100}%, transparent)`;
118
+ const value = `color-mix(in srgb, ${text} ${Math.round(opacity * 1e4) / 100}%, transparent)`;
84
119
  const mix = {};
85
120
  Object.defineProperties(mix, {
86
121
  fallback: {
87
- value: toRgba(color, opacity) ?? color,
122
+ value: toRgba(text, opacity) ?? text,
88
123
  enumerable: true
89
124
  },
90
125
  value: {
@@ -92,7 +127,7 @@ function alpha(color, opacity) {
92
127
  enumerable: true
93
128
  },
94
129
  toString: { value: () => value },
95
- [BRAND$1]: { value: true }
130
+ [BRAND$2]: { value: true }
96
131
  });
97
132
  return Object.freeze(mix);
98
133
  }
@@ -106,6 +141,26 @@ function alpha(color, opacity) {
106
141
  function at(key, style) {
107
142
  return { [key]: style };
108
143
  }
144
+ // src/cacheRegistry.ts
145
+ const registry$1 = /* @__PURE__ */ new WeakMap();
146
+ /** Records `cache` as the cache of its prefix in `page`, unless a cache of that prefix was recorded there before. */
147
+ function registerCache(page, cache) {
148
+ let caches = registry$1.get(page);
149
+ if (caches === void 0) {
150
+ caches = /* @__PURE__ */ new Map();
151
+ registry$1.set(page, caches);
152
+ }
153
+ if (!caches.has(cache.prefix)) caches.set(cache.prefix, cache);
154
+ }
155
+ /**
156
+ * The cache of `prefix` in `page`: the first cache of that prefix made with a sheet in a style element of
157
+ * that document (`createCache` records it), or undefined where none was made. It is how code that has no
158
+ * engine of its own (a component that a server component renders, in the browser) reaches the cache of the
159
+ * page, for example to release a global rule that a server sent.
160
+ */
161
+ function findCache(prefix, page) {
162
+ return registry$1.get(page)?.get(prefix);
163
+ }
109
164
  // src/hash.ts
110
165
  const MULTIPLIER = 0x5bd1e995;
111
166
  /** Multiplies `value` by the hash constant, kept to 32 bits. */
@@ -134,14 +189,20 @@ function hashString(text) {
134
189
  // src/findMissingStyles.ts
135
190
  const STATE_PATTERN = /:(hover|focus|active|focus-visible|focus-within)\b/;
136
191
  const NAME_CODES = /[a-z0-9_-]/;
137
- /** The prefix named by the first style element of an engine on the page, or undefined. */
138
- function findPrefix() {
139
- const element = document.querySelector("style[data-style], style[data-precedence]");
192
+ /** A selector that names the root element or the body: `html`, `body` or `:root` as a whole word. */
193
+ const ROOT_PATTERN = /(?:^|[\s>+~(,])(?:html|body)(?![\w-])|:root(?![\w-])/;
194
+ /** The prefix named by the first style element of an engine in `page`, or undefined. */
195
+ function findPrefix(page) {
196
+ const element = page.querySelector("style[data-style], style[data-precedence]");
140
197
  return element?.dataset.style ?? element?.dataset.precedence;
141
198
  }
199
+ /** Whether `rule` is a style rule. A rule of another document (an iframe's) is not an instance of this window's `CSSStyleRule`, so the name of its class is read instead. */
200
+ function isStyleRule(rule) {
201
+ return rule.constructor.name === "CSSStyleRule";
202
+ }
142
203
  /** The style rules under `list`, groups included. */
143
204
  function collectStyleRules(list, found) {
144
- for (const rule of list) if (rule instanceof CSSStyleRule) found.push(rule);
205
+ for (const rule of list) if (isStyleRule(rule)) found.push(rule);
145
206
  else if ("cssRules" in rule) collectStyleRules(rule.cssRules, found);
146
207
  return found;
147
208
  }
@@ -185,11 +246,11 @@ function isMatched(element, rule) {
185
246
  return false;
186
247
  }
187
248
  }
188
- /** The rules of the engine's style elements, each with the variables it uses without a fallback. */
189
- function collectRules(prefix) {
190
- const selector = `style[data-style="${prefix}"], style[data-precedence="${prefix}"]`;
249
+ /** The rules of the engine's style elements in `page` (those of `data-umber` too), each with the variables it uses without a fallback. */
250
+ function collectRules(page, prefix) {
251
+ const selector = `style[data-style="${prefix}"], style[data-precedence="${prefix}"], style[data-umber~="${prefix}"], style[data-umber~="${prefix}-global"]`;
191
252
  const rules = [];
192
- for (const element of document.querySelectorAll(selector)) if (element.sheet) collectStyleRules(element.sheet.cssRules, rules);
253
+ for (const element of page.querySelectorAll(selector)) if (element.sheet) collectStyleRules(element.sheet.cssRules, rules);
193
254
  return rules.map((rule) => ({
194
255
  rule,
195
256
  variables: readBareVariables(rule.cssText, `--${prefix}-`),
@@ -230,37 +291,209 @@ function findVariableProblems(element, label, rules, problems) {
230
291
  }
231
292
  }
232
293
  /**
294
+ * The global rules (rules that name no class of the engine) for `html`, `body` or `:root` that match
295
+ * `element`, `<html>` or `<body>` without a class of the engine, and use variables that have no value
296
+ * on it: one problem for each rule, with all of those variables. A variable is declared on the element
297
+ * that carries a theme class and below it, so a rule for `html` or `body` sees the variables of a theme
298
+ * only when they are declared on `:root` (what the outermost provider does) or the theme class is on
299
+ * `<html>`; then there is no problem.
300
+ */
301
+ function findRootProblems(element, label, rules, start, problems) {
302
+ const computed = getComputedStyle(element);
303
+ for (const { rule, variables, isState } of rules) {
304
+ const selector = rule.selectorText;
305
+ const isGlobal = readClassNames(selector, start).length === 0 && ROOT_PATTERN.test(selector);
306
+ if (variables.length === 0 || isState || !isGlobal || !isMatched(element, rule)) continue;
307
+ const missing = variables.filter((name) => computed.getPropertyValue(name).trim() === "");
308
+ if (missing.length === 0) continue;
309
+ const message = `${label} has no value for ${missing.join(", ")}, which the global rule ${selector} uses: a rule for html or body sees the variables of a theme declared on :root (the outermost provider) or on <html> (its theme class)`;
310
+ problems.push({
311
+ kind: "root-without-theme",
312
+ name: missing[0],
313
+ element: label,
314
+ message,
315
+ key: `root:${selector}`
316
+ });
317
+ }
318
+ }
319
+ /**
233
320
  * Looks at a page that an engine styled, and lists what is missing. For each element under `root`
234
- * (the document by default): every class of the engine on it is named by at least one rule of the
321
+ * (the document by default; the style elements are read in the document of `root`): every class of the engine on it is named by at least one rule of the
235
322
  * engine's style elements (its own, and the ones React hoists), and every variable of the engine that
236
323
  * a rule matching the element uses, without a fallback, has a value on the element. The classes that
237
324
  * are markers (`<prefix>-boundary`, `<prefix>-scheme-light` and `-dark`) have no rule of their own and
238
- * are left out, and so are the rules for `:hover`, `:focus` and the like. An empty list means nothing
239
- * is missing. Where there is no document, or no style element of an engine, the list is empty.
325
+ * are left out, and so is `<prefix>-theme-0`, the theme class of a theme that declares nothing, which has
326
+ * no rule by design; and so are the rules for `:hover`, `:focus` and the like. `<html>` and `<body>` without
327
+ * a class of the engine are checked for the global rules that name them (see `root-without-theme`). An
328
+ * empty list means nothing is missing. Where there is no document, or no style element of an engine,
329
+ * the list is empty.
240
330
  */
241
331
  function findMissingStyles(root, options = {}) {
242
332
  if (typeof document === "undefined") return [];
243
- const prefix = options.prefix ?? findPrefix();
244
- if (prefix === void 0) return [];
245
333
  const scope = root ?? document;
246
- const rules = collectRules(prefix);
334
+ const page = scope.ownerDocument ?? scope;
335
+ const prefix = options.prefix ?? findPrefix(page);
336
+ if (prefix === void 0) return [];
337
+ const rules = collectRules(page, prefix);
247
338
  const named = new Set(rules.flatMap(({ rule }) => readClassNames(rule.selectorText, `${prefix}-`)));
248
339
  const markers = /* @__PURE__ */ new Set([
249
340
  `${prefix}-boundary`,
250
341
  `${prefix}-scheme-light`,
251
- `${prefix}-scheme-dark`
342
+ `${prefix}-scheme-dark`,
343
+ `${prefix}-theme-0`
252
344
  ]);
253
345
  const problems = [];
254
- const elements = [...scope instanceof Element ? [scope] : [], ...scope.querySelectorAll("*")];
346
+ const elements = [...scope.nodeType === 1 ? [scope] : [], ...scope.querySelectorAll("*")];
255
347
  for (const element of elements) {
256
348
  const classes = [...element.classList].filter((name) => name.startsWith(`${prefix}-`) && !markers.has(name));
257
- if (classes.length === 0) continue;
349
+ if (classes.length === 0) {
350
+ if (element === page.documentElement || element === page.body) findRootProblems(element, describe(element), rules, `${prefix}-`, problems);
351
+ continue;
352
+ }
258
353
  const label = describe(element);
259
354
  findClassProblems(label, classes, named, problems);
260
355
  findVariableProblems(element, label, rules, problems);
261
356
  }
262
357
  return problems;
263
358
  }
359
+ // src/findUnsupportedDeclarations.ts
360
+ const KEYFRAMES_AT_RULE$1 = "@keyframes";
361
+ const IMPORTANT = "important";
362
+ /** A value that starts with a vendor prefix: a keyword or a function written for another browser. */
363
+ const VENDOR_VALUE = /^-(?:webkit|moz|ms|o)-/i;
364
+ /**
365
+ * `CSS.supports` of the browser, or undefined where there is none to trust: no `CSS` (a server), one
366
+ * that throws or answers two plain questions wrong, or jsdom, which answers from a table of its own and
367
+ * not from what a browser renders. The checker of a cache asks once, when it is made.
368
+ */
369
+ function findBrowserSupports() {
370
+ try {
371
+ return !navigator.userAgent.includes("jsdom") && CSS.supports("color", "red") && !CSS.supports("color", "not-a-color") ? (property, value) => CSS.supports(property, value) : void 0;
372
+ } catch {
373
+ return;
374
+ }
375
+ }
376
+ /** The index after the string that starts at `index`, which is a quote. */
377
+ function skipString$1(text, index) {
378
+ const quote = text[index];
379
+ let position = index + 1;
380
+ while (position < text.length && text[position] !== quote) position += text[position] === "\\" ? 2 : 1;
381
+ return position + 1;
382
+ }
383
+ /** Opens a block at `index`, a `{`: its prelude is the text since `boundary`. */
384
+ function openBlock$2(stack, text, boundary, index) {
385
+ const parent = stack.at(-1);
386
+ if (parent) parent.hasChild = true;
387
+ stack.push({
388
+ prelude: text.slice(boundary, index).trim(),
389
+ bodyStart: index + 1,
390
+ hasChild: false
391
+ });
392
+ }
393
+ /** Closes the innermost block at `index`, a `}`: a block without a block of its own that is not an at-rule is a rule to add to `rules`. */
394
+ function closeBlock$2(stack, text, index, rules) {
395
+ const block = stack.pop();
396
+ if (!block || block.hasChild || block.prelude.startsWith("@")) return;
397
+ const parent = stack.at(-1)?.prelude ?? "";
398
+ rules.push({
399
+ selector: block.prelude,
400
+ parent,
401
+ body: text.slice(block.bodyStart, index)
402
+ });
403
+ }
404
+ /** The innermost blocks of `text` that are not at-rules: the rules that hold declarations. */
405
+ function readStyleRules(text) {
406
+ const rules = [];
407
+ const stack = [];
408
+ let boundary = 0;
409
+ let index = 0;
410
+ while (index < text.length) {
411
+ const char = text[index];
412
+ if (char === "\"" || char === "'") {
413
+ index = skipString$1(text, index);
414
+ continue;
415
+ }
416
+ if (char === ";") boundary = index + 1;
417
+ else if (char === "{") {
418
+ openBlock$2(stack, text, boundary, index);
419
+ boundary = index + 1;
420
+ } else if (char === "}") {
421
+ closeBlock$2(stack, text, index, rules);
422
+ boundary = index + 1;
423
+ }
424
+ index++;
425
+ }
426
+ return rules;
427
+ }
428
+ /** Adds the declaration `declaration` (`property:value`) to `declarations`, unless it has no ':'. */
429
+ function addDeclaration(declarations, declaration) {
430
+ const colon = declaration.indexOf(":");
431
+ if (colon === -1) return;
432
+ declarations.set(declaration.slice(0, colon).trim(), declaration.slice(colon + 1).trim());
433
+ }
434
+ /** The declarations of `body` by property, the last one of each: the items before it in a fallback list are meant to be dropped. */
435
+ function readLastDeclarations(body) {
436
+ const declarations = /* @__PURE__ */ new Map();
437
+ let depth = 0;
438
+ let start = 0;
439
+ let index = 0;
440
+ while (index <= body.length) {
441
+ const char = body[index];
442
+ if (char === "\"" || char === "'") {
443
+ index = skipString$1(body, index);
444
+ continue;
445
+ }
446
+ if (char === "(") depth++;
447
+ else if (char === ")") depth--;
448
+ else if (index === body.length || char === ";" && depth === 0) {
449
+ addDeclaration(declarations, body.slice(start, index));
450
+ start = index + 1;
451
+ }
452
+ index++;
453
+ }
454
+ return declarations;
455
+ }
456
+ /**
457
+ * `value` without a `!important` at its end (in any case, with whitespace around the `!`), and without
458
+ * the whitespace before it. A scan from the end: nothing is tried twice, so it takes linear time.
459
+ */
460
+ function stripImportant(value) {
461
+ const trimmed = value.trimEnd();
462
+ if (trimmed.slice(-9).toLowerCase() !== IMPORTANT) return value;
463
+ const before = trimmed.slice(0, -9).trimEnd();
464
+ return before.endsWith("!") ? before.slice(0, -1).trimEnd() : value;
465
+ }
466
+ /** What a message names a rule by: its `@keyframes` rule, the last class of the engine in its selector, or its selector for a global rule. */
467
+ function describeRule({ selector, parent }, classPattern) {
468
+ if (parent.startsWith(KEYFRAMES_AT_RULE$1)) return `the keyframes ${parent.slice(10).trim()}`;
469
+ const name = [...selector.matchAll(classPattern)].at(-1)?.[1];
470
+ return name === void 0 ? `the global rule ${selector}` : `the class ${name}`;
471
+ }
472
+ /**
473
+ * Asks the browser about each declaration of `texts`, rules that an engine wrote, and returns a message
474
+ * for each one that it does not support. Only the last declaration of a property in a rule is asked
475
+ * about. A property that starts with a hyphen is left out: a custom property takes any value, and one
476
+ * with a vendor prefix is written for another browser, as is a value that starts with a vendor prefix
477
+ * (`-moz-available`, `-webkit-linear-gradient(...)`). For a value with `var(`, which is valid until it
478
+ * is used, the browser is asked whether it knows the property at all. `!important` is not part of the
479
+ * question. At-rules with descriptors (`@property`, `@font-face`) are not asked about.
480
+ */
481
+ function findUnsupportedDeclarations(texts, prefix, supports) {
482
+ const classPattern = new RegExp(String.raw`\.(${prefix}-[a-z0-9_-]*)`, "g");
483
+ const messages = [];
484
+ for (const text of texts) for (const rule of readStyleRules(text)) addRuleMessages(rule, classPattern, supports, messages);
485
+ return messages;
486
+ }
487
+ /** Adds to `messages` a message for each last declaration of `rule` that the browser does not support (see `findUnsupportedDeclarations`). */
488
+ function addRuleMessages(rule, classPattern, supports, messages) {
489
+ for (const [name, value] of readLastDeclarations(rule.body)) {
490
+ const plain = stripImportant(value);
491
+ if (name.startsWith("-") || VENDOR_VALUE.test(plain)) continue;
492
+ if (supports(name, plain.includes("var(") ? "inherit" : plain)) continue;
493
+ const owner = describeRule(rule, classPattern);
494
+ messages.push(`${owner} declares ${name}:${value}, which this browser does not support`);
495
+ }
496
+ }
264
497
  // src/devChecks.ts
265
498
  /** How long a check waits after the last insertion, in milliseconds: rules arrive in bursts while a page renders. */
266
499
  const CHECK_DELAY = 250;
@@ -273,26 +506,39 @@ function isDevelopment() {
273
506
  }
274
507
  }
275
508
  /**
276
- * The function that asks for a check of the page: it runs `findMissingStyles` once, after the calls
277
- * have stopped for a short while, and warns once for each problem (never again for the same one).
509
+ * The function that asks for a check of `page` (the document by default): it runs `findMissingStyles` once, after the calls
510
+ * have stopped for a short while, and warns once for each problem (never again for the same one). The
511
+ * rules given to it are asked about in the same run: a declaration that the browser does not support
512
+ * (`findUnsupportedDeclarations`) is warned about once for each message. Where the browser cannot be
513
+ * asked (no `CSS.supports`, or jsdom) the rules are not kept.
278
514
  */
279
- function createDevChecker(prefix, delay = CHECK_DELAY) {
515
+ function createDevChecker(prefix, delay = CHECK_DELAY, page = document) {
280
516
  const warned = /* @__PURE__ */ new Set();
517
+ const supports = findBrowserSupports();
518
+ const written = [];
281
519
  let timer;
520
+ const warn = (key, message) => {
521
+ if (warned.has(key)) return;
522
+ warned.add(key);
523
+ console.warn(`[${prefix}] ${message}`);
524
+ };
282
525
  const run = () => {
283
526
  timer = void 0;
284
- for (const problem of findMissingStyles(document, { prefix })) {
285
- if (warned.has(problem.key)) continue;
286
- warned.add(problem.key);
287
- console.warn(`[${prefix}] ${problem.message}`);
288
- }
527
+ for (const problem of findMissingStyles(page, { prefix })) warn(problem.key, problem.message);
528
+ if (!supports) return;
529
+ for (const message of findUnsupportedDeclarations(written.splice(0), prefix, supports)) warn(`declaration:${message}`, message);
289
530
  };
290
- return () => {
531
+ return (rules) => {
532
+ if (supports && rules) written.push(...rules);
291
533
  timer ??= setTimeout(run, delay);
292
534
  };
293
535
  }
294
536
  // src/fingerprint.ts
295
- /** The short code each option has in the stamp, in the order they are written. */
537
+ /**
538
+ * The short code each option has in the stamp, in the order they are written. An option added later has
539
+ * a third entry, the value it is left out with: the stamp of a page that does not turn it on stays the
540
+ * same text as before, and a stamp that lacks it reads as that value.
541
+ */
296
542
  const CODES = [
297
543
  ["p", "prefix"],
298
544
  ["x", "suffix"],
@@ -302,6 +548,11 @@ const CODES = [
302
548
  ["b", "hasBaseClass"],
303
549
  ["s", "hasScope"],
304
550
  ["f", "hasColorFallbacks"],
551
+ [
552
+ "v",
553
+ "hasValueRepair",
554
+ "0"
555
+ ],
305
556
  ["t", "tokens"]
306
557
  ];
307
558
  /** The text of one option in the stamp: a flag is 1 or 0, a string is encoded. */
@@ -311,7 +562,10 @@ function toStampValue(value) {
311
562
  }
312
563
  /** The stamp of `options`, short enough for an attribute: `p=umber;x=;l=1;y=1;...`. */
313
564
  function createFingerprint(options) {
314
- return CODES.map(([code, name]) => `${code}=${toStampValue(options[name])}`).join(";");
565
+ return CODES.flatMap(([code, name, omitted]) => {
566
+ const value = toStampValue(options[name]);
567
+ return value === omitted ? [] : [`${code}=${value}`];
568
+ }).join(";");
315
569
  }
316
570
  /** The values of a stamp, by short code. */
317
571
  function parseFingerprint(stamp) {
@@ -324,215 +578,142 @@ function parseFingerprint(stamp) {
324
578
  function describeFingerprintDifferences(server, browser) {
325
579
  const theirs = parseFingerprint(server);
326
580
  const ours = parseFingerprint(browser);
327
- const differences = CODES.filter(([code]) => theirs.get(code) !== ours.get(code)).map(([code, name]) => `${name} (server: ${decodeURIComponent(theirs.get(code) ?? "")}, browser: ${decodeURIComponent(ours.get(code))})`);
581
+ const differences = CODES.filter(([code, , omitted]) => (theirs.get(code) ?? omitted) !== (ours.get(code) ?? omitted)).map(([code, name, omitted]) => `${name} (server: ${decodeURIComponent(theirs.get(code) ?? omitted ?? "")}, browser: ${decodeURIComponent(ours.get(code) ?? omitted)})`);
328
582
  if (differences.length === 0) return "";
329
583
  return `UmberStyle: the server rendered this page with other options than the browser uses. Differing options: ${differences.join("; ")}. Create the style with the same options on both sides.`;
330
584
  }
331
- // src/codeAt.ts
332
- /** The code point at `index` of `text`; NaN past the end, so that every comparison with a code is false. */
333
- function codeAt(text, index) {
334
- return text.codePointAt(index) ?? NaN;
585
+ // src/calc.ts
586
+ const LENGTH_PATTERN$1 = /^(-?(?:\d+(?:\.\d*)?|\.\d+))([a-z]+|%)$/i;
587
+ const CALC_PREFIX = "calc(";
588
+ /** `value` rounded so that float noise (0.1 * 3) does not reach the CSS; `-0` is `0`. */
589
+ function tidy(value) {
590
+ return Math.round(value * 1e6) / 1e6 + 0;
335
591
  }
336
- // src/variables.ts
337
- const VARIABLE_OPEN = "var(";
338
- /** Whether `code` is a character of a variable name: a lowercase letter, a digit, '-' or '_'. */
339
- function isNameCode$1(code) {
340
- return code >= 97 && code <= 122 || code >= 48 && code <= 57 || code === 45 || code === 95;
592
+ /** Throws unless `value` is a finite number; `what` names the argument in the message. */
593
+ function assertFinite(name, what, value) {
594
+ if (typeof value !== "number") throw new TypeError(`${name}(): ${what} must be a number, got ${typeof value}`);
595
+ if (!Number.isFinite(value)) throw new RangeError(`${name}(): ${what} must be finite, got ${value}`);
341
596
  }
342
- /** The index of the first character at or after `index` that is not whitespace. */
343
- function skipSpaces$1(text, index) {
344
- let position = index;
345
- while (codeAt(text, position) <= 32) position++;
346
- return position;
597
+ /** Throws unless `value` is a string or a finite number. */
598
+ function assertOperand(name, value) {
599
+ if (isAlphaColor(value)) throw new TypeError(`${name}(): an alpha() color is not a length or a number, so it cannot be an operand`);
600
+ if (typeof value !== "string") assertFinite(name, "a value", value);
347
601
  }
348
- /**
349
- * The names of the variables that `css` refers to and that start with `start` (`--<prefix>-`), in order
350
- * of appearance, with repeats. A reference may have a fallback, which may refer to others. One pass.
351
- */
352
- function scanVariables(css, start) {
353
- const names = [];
354
- let from = css.indexOf(VARIABLE_OPEN);
355
- while (from !== -1) {
356
- const begin = skipSpaces$1(css, from + 4);
357
- let end = begin + start.length;
358
- if (css.startsWith(start, begin)) {
359
- while (isNameCode$1(codeAt(css, end))) end++;
360
- names.push(css.slice(begin, end));
361
- }
362
- from = css.indexOf(VARIABLE_OPEN, begin);
602
+ /** The inside of `value` when the whole of it is one `calc(...)`, else undefined. */
603
+ function unwrapCalc(value) {
604
+ if (!value.startsWith(CALC_PREFIX) || !value.endsWith(")")) return void 0;
605
+ let depth = 0;
606
+ for (let index = 4; index < value.length; index += 1) {
607
+ if (value[index] === "(") depth += 1;
608
+ if (value[index] === ")") depth -= 1;
609
+ if (depth === 0 && index < value.length - 1) return void 0;
363
610
  }
364
- return names;
611
+ return value.slice(5, -1);
365
612
  }
366
- // src/scanStyleText.ts
367
- /** Makes findings that hold nothing. */
368
- function createEmptyFindings() {
369
- return {
370
- hasLayerOrder: false,
371
- classes: /* @__PURE__ */ new Set(),
372
- themes: /* @__PURE__ */ new Map(),
373
- properties: /* @__PURE__ */ new Map(),
374
- variables: /* @__PURE__ */ new Set()
375
- };
613
+ /** `operand` as a part of a calc expression: a number is a length in px, an inner calc gets parentheses. */
614
+ function toTerm(operand) {
615
+ if (typeof operand === "number") return `${tidy(operand)}px`;
616
+ const inner = unwrapCalc(operand);
617
+ return inner === void 0 ? operand : `(${inner})`;
376
618
  }
377
- const PROPERTY_AT_RULE = "@property";
378
- /** Whether `code` is a character of a class name: a lowercase letter, a digit, '-' or '_'. */
379
- function isNameCode(code) {
380
- return code >= 97 && code <= 122 || code >= 48 && code <= 57 || code === 45 || code === 95;
619
+ /** `operand` as a literal length (a number is in px), or undefined when it is not one. */
620
+ function toLength(operand) {
621
+ if (typeof operand === "number") return {
622
+ value: operand,
623
+ unit: "px"
624
+ };
625
+ const match = LENGTH_PATTERN$1.exec(operand.trim());
626
+ return match ? {
627
+ value: Number.parseFloat(match[1]),
628
+ unit: match[2].toLowerCase()
629
+ } : void 0;
381
630
  }
382
- /** The classes in `selector` whose name starts with `start` (`<prefix>-`), without the dot. */
383
- function readClasses(selector, start) {
384
- const names = [];
385
- let from = selector.indexOf(`.${start}`);
386
- while (from !== -1) {
387
- let end = from + 1 + start.length;
388
- while (isNameCode(codeAt(selector, end))) end++;
389
- names.push(selector.slice(from + 1, end));
390
- from = selector.indexOf(`.${start}`, end);
631
+ const OPERATIONS = {
632
+ "*": (value, factor) => value * factor,
633
+ "/": (value, factor) => value / factor
634
+ };
635
+ /** `value` (a stand-in of `keyframes` as its path) multiplied or divided by `factor`, as a number, a literal length or a calc. */
636
+ function scale(name, given, factor, operator) {
637
+ const value = readStandIn(given);
638
+ assertOperand(name, value);
639
+ assertFinite(name, operator === "*" ? "the factor" : "the divisor", factor);
640
+ if (factor === 0) {
641
+ if (operator === "/") throw new RangeError(`${name}(): the divisor must not be 0`);
642
+ return 0;
391
643
  }
392
- return names;
644
+ if (factor === 1) return value;
645
+ if (typeof value === "number") return tidy(OPERATIONS[operator](value, factor));
646
+ const length = toLength(value);
647
+ return length === void 0 ? `${CALC_PREFIX}${toTerm(value)} ${operator} ${factor})` : `${tidy(OPERATIONS[operator](length.value, factor))}${length.unit}`;
393
648
  }
394
- /** The names of the variables that `body`, the declarations of a rule, declares. */
395
- function readDeclared(body) {
396
- const names = /* @__PURE__ */ new Set();
397
- for (const part of body.split(";")) {
398
- const text = part.trimStart();
399
- if (text.startsWith("--")) names.add(text.slice(0, text.indexOf(":")));
649
+ /** The sum of `terms` when they are all numbers, else undefined. */
650
+ function sumNumbers(terms) {
651
+ let total = 0;
652
+ for (const { operand, sign } of terms) {
653
+ if (typeof operand !== "number") return void 0;
654
+ total += sign * operand;
400
655
  }
401
- return names;
402
- }
403
- /** The index after the string that starts at `index`, which is a quote. */
404
- function skipString(text, index) {
405
- const quote = text[index];
406
- let position = index + 1;
407
- while (position < text.length && text[position] !== quote) position += text[position] === "\\" ? 2 : 1;
408
- return position + 1;
656
+ return tidy(total);
409
657
  }
410
- /** Records the innermost rule `prelude{body}` of a style element in `found`. */
411
- function record(found, prefix, prelude, body) {
412
- if (prelude.startsWith(PROPERTY_AT_RULE)) {
413
- found.properties.set(prelude.slice(9).trim(), `${prelude}{${body}}`);
414
- return;
415
- }
416
- if (prelude.startsWith("@")) return;
417
- const themeStart = `${prefix}-theme-`;
418
- const classes = readClasses(prelude, `${prefix}-`);
419
- const themeId = classes.length === 1 && prelude === `.${classes[0]}` ? classes[0] : void 0;
420
- if (themeId?.startsWith(themeStart)) {
421
- const declared = found.themes.get(themeId) ?? /* @__PURE__ */ new Set();
422
- for (const name of readDeclared(body)) declared.add(name);
423
- found.themes.set(themeId, declared);
424
- return;
658
+ /** The sum of `terms` when they are literal lengths of one unit, else undefined. */
659
+ function sumLengths(terms) {
660
+ const lengths = terms.map(({ operand }) => toLength(operand));
661
+ const unit = lengths[0]?.unit;
662
+ let total = 0;
663
+ for (const [index, length] of lengths.entries()) {
664
+ if (length === void 0 || length.unit !== unit) return void 0;
665
+ total += terms[index].sign * length.value;
425
666
  }
426
- const markers = /* @__PURE__ */ new Set([
427
- `${prefix}-boundary`,
428
- `${prefix}-scheme-light`,
429
- `${prefix}-scheme-dark`
430
- ]);
431
- for (const name of classes) if (!name.startsWith(themeStart) && !markers.has(name)) found.classes.add(name);
432
- for (const name of scanVariables(body, `--${prefix}-`)) found.variables.add(name);
667
+ return `${tidy(total)}${unit}`;
433
668
  }
434
- /** Opens a block at `index`, a `{`: its prelude is the text since `boundary`. */
435
- function openBlock(stack, text, boundary, index) {
436
- const parent = stack.at(-1);
437
- if (parent) parent.hasChild = true;
438
- stack.push({
439
- prelude: text.slice(boundary, index).trim(),
440
- bodyStart: index + 1,
441
- hasChild: false
442
- });
669
+ /** `terms` as one calc: the first term, then each with its sign. */
670
+ function toCalc(terms) {
671
+ const body = terms.map(({ operand, sign }, index) => {
672
+ const term = toTerm(operand);
673
+ if (index === 0) return term;
674
+ return `${sign === 1 ? "+" : "-"} ${term}`;
675
+ }).join(" ");
676
+ return `${CALC_PREFIX}${body})`;
443
677
  }
444
- /** Closes the innermost block at `index`, a `}`; a block without a block of its own is a rule to record. */
445
- function closeBlock(stack, found, prefix, text, index) {
446
- const block = stack.pop();
447
- if (block && !block.hasChild) record(found, prefix, block.prelude, text.slice(block.bodyStart, index));
678
+ /** `terms` added and subtracted, as a number, a literal length or one calc. */
679
+ function sum(terms) {
680
+ if (terms.length === 1) return terms[0].operand;
681
+ return sumNumbers(terms) ?? sumLengths(terms) ?? toCalc(terms);
448
682
  }
449
- /**
450
- * Reads the CSS that an engine wrote (compact, no comments) in one pass and adds what it holds to
451
- * `found`: the layer order statement, the classes with a rule, each theme class with the variables it
452
- * declares, the `@property` rules and the variables that rules use.
453
- */
454
- function scanStyleText(prefix, text, found = createEmptyFindings()) {
455
- const stack = [];
456
- let boundary = 0;
457
- let index = 0;
458
- while (index < text.length) {
459
- const char = text[index];
460
- if (char === "\"" || char === "'") {
461
- index = skipString(text, index);
462
- continue;
463
- }
464
- if (char === "{") {
465
- openBlock(stack, text, boundary, index);
466
- boundary = index + 1;
467
- } else if (char === "}") {
468
- closeBlock(stack, found, prefix, text, index);
469
- boundary = index + 1;
470
- } else if (char === ";" && stack.length === 0) {
471
- if (text.slice(boundary, index).trim().startsWith("@layer")) found.hasLayerOrder = true;
472
- boundary = index + 1;
473
- }
474
- index++;
475
- }
476
- return found;
683
+ /** The terms of `values` with `sign`, without the zeros that change nothing; each is checked, a stand-in as its path. */
684
+ function toTerms(name, given, sign) {
685
+ const values = given.map((value) => readStandIn(value));
686
+ for (const value of values) assertOperand(name, value);
687
+ return values.filter((value) => value !== 0).map((operand) => ({
688
+ operand,
689
+ sign
690
+ }));
477
691
  }
478
- // src/sheetEntry.ts
479
- const BRAND = Symbol.for("umber-style.sheet-entry");
480
- const SOURCE = Symbol.for("umber-style.sheet-entry-source");
481
- const ENTRY_KEY_PREFIX = "--umber-entry-";
482
- /**
483
- * Makes the entry of a class name: a frozen object that `isSheetEntry` knows and that prints as the
484
- * class name. Its one enumerable key is a custom property named after the class, with the value `null`,
485
- * so that a framework that merges the style objects of an array (Vue does) keeps every entry, and
486
- * `flattenStyle` finds them by the key. Both frameworks skip a `null` style value on a plain element, on
487
- * the client and on the server, so an entry given to a plain element renders no style attribute. With a
488
- * `source` (a cache made it) the class name is read through it, so that the rule is written when the entry
489
- * is used, not when it is made; without one the entry is just the name.
490
- */
491
- function createSheetEntry(className, source) {
492
- const entry = {
493
- [`${ENTRY_KEY_PREFIX}${className}`]: null,
494
- [BRAND]: true
495
- };
496
- const read = () => source?.use("components") ?? className;
497
- Object.defineProperties(entry, {
498
- className: { get: read },
499
- toString: { value: read },
500
- ...source ? { [SOURCE]: { value: source } } : {}
501
- });
502
- return Object.freeze(entry);
692
+ function multiply(value, factor) {
693
+ return scale("multiply", value, factor, "*");
503
694
  }
504
- /** Whether `value` was made by `createSheetEntry`: a class name is a plain string, a style object has no brand. */
505
- function isSheetEntry(value) {
506
- return typeof value === "object" && value !== null && BRAND in value;
695
+ function divide(value, divisor) {
696
+ return scale("divide", value, divisor, "/");
507
697
  }
508
- /** What a cache gave `entry` to make its classes, or undefined for an entry that is only a name. */
509
- function readEntrySource(entry) {
510
- return entry[SOURCE];
698
+ function add(...values) {
699
+ const terms = toTerms("add", values, 1);
700
+ return terms.length === 0 ? 0 : sum(terms);
511
701
  }
512
- /**
513
- * What a `style` prop holds, as a flat list in order, for the cache to merge into one class: sheet
514
- * entries and plain style objects, with arrays flattened and what is empty dropped. An object in which a
515
- * framework merged entries and plain keys (Vue does) is split back into its entries, then the rest; an
516
- * entry is looked up by its class name with `findEntry` (a cache's `findEntry`), else it is only the name.
517
- * A string is an error: a text style cannot be merged into a class.
518
- */
519
- function flattenStyle(style, findEntry) {
520
- const flat = [];
521
- const visit = (value) => {
522
- if (Array.isArray(value)) value.forEach(visit);
523
- else if (typeof value === "string" && value) throw new Error("A style given as a string cannot be merged into a class: use a sheet entry or an object.");
524
- else if (isSheetEntry(value) && readEntrySource(value)) flat.push(value);
525
- else if (typeof value === "object" && value !== null) {
526
- const rest = {};
527
- for (const [key, item] of Object.entries(value)) if (key.startsWith(ENTRY_KEY_PREFIX)) {
528
- const name = key.slice(14);
529
- flat.push(findEntry?.(name) ?? createSheetEntry(name));
530
- } else rest[key] = item;
531
- if (Object.keys(rest).length > 0) flat.push(rest);
532
- }
533
- };
534
- visit(style);
535
- return flat;
702
+ function subtract(value, ...values) {
703
+ const first = readStandIn(value);
704
+ assertOperand("subtract", first);
705
+ return sum([{
706
+ operand: first,
707
+ sign: 1
708
+ }, ...toTerms("subtract", values, -1)]);
709
+ }
710
+ function negate(value) {
711
+ return scale("negate", value, -1, "*");
712
+ }
713
+ // src/codeAt.ts
714
+ /** The code point at `index` of `text`; NaN past the end, so that every comparison with a code is false. */
715
+ function codeAt(text, index) {
716
+ return text.codePointAt(index) ?? NaN;
536
717
  }
537
718
  // src/scope.ts
538
719
  /** The scoping of a cache that gave none: the default prefix, with `@scope`. */
@@ -633,6 +814,13 @@ const UNITLESS = /* @__PURE__ */ new Set([
633
814
  "strokeOpacity",
634
815
  "strokeWidth"
635
816
  ]);
817
+ /** The properties whose value is a time: a number is in milliseconds. */
818
+ const TIMES = /* @__PURE__ */ new Set([
819
+ "animationDelay",
820
+ "animationDuration",
821
+ "transitionDelay",
822
+ "transitionDuration"
823
+ ]);
636
824
  const propertyNames = /* @__PURE__ */ new Map();
637
825
  /** Whether `value` is a nested style object, not an array, an `alpha()` result or a plain value. */
638
826
  function isStyleObject(value) {
@@ -648,9 +836,78 @@ function toPropertyName(key) {
648
836
  }
649
837
  return name;
650
838
  }
651
- /** The CSS text of one declared value. */
652
- function toValue(key, value) {
653
- return typeof value === "number" && value !== 0 && !key.startsWith("--") && !UNITLESS.has(key) ? `${value}px` : String(value);
839
+ const REFERENCE = "var(";
840
+ const HEX_PAIR = /^[0-9a-f]{2}$/i;
841
+ /** The units that make a reference a time: `var(--x)ms` is `calc(var(--x) * 1ms)`. */
842
+ const TIME_UNITS = ["ms", "s"];
843
+ /** Whether the character code `code` can be part of an identifier: a letter, a digit, `-`, `_` or any non-ASCII character. NaN (past either end of the text) cannot. */
844
+ function isNameCode$2(code) {
845
+ return code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122 || code === 45 || code === 95 || code >= 128;
846
+ }
847
+ /** Whether the character at `at` is a minus that stands alone before a reference: at the start of the value, or after a space, a comma or `(`. */
848
+ function isLoneMinus(value, at) {
849
+ return value[at] === "-" && (at === 0 || " ,(".includes(value[at - 1]));
850
+ }
851
+ /** The index just after the parenthesis that closes the one before `start`, or -1 when none does. */
852
+ function findClose(value, start) {
853
+ let depth = 1;
854
+ for (let index = start; index < value.length; index++) if (value[index] === "(") depth++;
855
+ else if (value[index] === ")" && --depth === 0) return index + 1;
856
+ return -1;
857
+ }
858
+ /**
859
+ * `reference` with what follows it at `at` taken in, and where the rest of the value starts: two hex
860
+ * digits of alpha are what `alpha()` writes for that opacity, a time unit makes a `calc()` of a time.
861
+ * The digits or the unit must end there: `var(--x)1Fa` is left alone.
862
+ */
863
+ function repairSuffix(value, at, reference) {
864
+ const pair = value.slice(at, at + 2);
865
+ if (HEX_PAIR.test(pair) && !isNameCode$2(codeAt(value, at + 2))) return [String(alpha(reference, Number.parseInt(pair, 16) / 255)), at + 2];
866
+ for (const unit of TIME_UNITS) {
867
+ const end = at + unit.length;
868
+ if (value.slice(at, end).toLowerCase() === unit && !isNameCode$2(codeAt(value, end))) return [`calc(${reference} * 1${unit})`, end];
869
+ }
870
+ return [reference, at];
871
+ }
872
+ /**
873
+ * `value` with the string forms of token maths that are never valid CSS rewritten: a reference followed
874
+ * by two hex digits (`var(--x)1F`) as `alpha()` writes it, a minus before a reference (`-var(--x)`) as
875
+ * `negate()` writes it, and a reference followed by `ms` or `s` as a `calc()` of a time. A reference may
876
+ * have a fallback, which is repaired too. Any other text is kept as it is.
877
+ */
878
+ function repairValue(value) {
879
+ let repaired = "";
880
+ let from = 0;
881
+ let index = value.indexOf(REFERENCE);
882
+ while (index !== -1) {
883
+ const hasMinus = isLoneMinus(value, index - 1);
884
+ if (isNameCode$2(codeAt(value, index - 1)) && !hasMinus) {
885
+ index = value.indexOf(REFERENCE, index + 4);
886
+ continue;
887
+ }
888
+ const close = findClose(value, index + 4);
889
+ if (close === -1) break;
890
+ const inner = value.slice(index + 4, close - 1);
891
+ const [text, end] = repairSuffix(value, close, `${REFERENCE}${repairValue(inner)})`);
892
+ const start = hasMinus ? index - 1 : index;
893
+ repaired += value.slice(from, start) + (hasMinus ? String(negate(text)) : text);
894
+ from = end;
895
+ index = value.indexOf(REFERENCE, end);
896
+ }
897
+ return repaired + value.slice(from);
898
+ }
899
+ /**
900
+ * The CSS text of one declared value: a number is a time in `ms` (0 too: a time needs its unit), or a
901
+ * length in `px` unless it is 0 or the property takes a plain number. With `hasValueRepair` a string
902
+ * that holds a reference, outside a custom property, has its string forms of token maths rewritten.
903
+ */
904
+ function toValue(key, value, hasValueRepair) {
905
+ if (typeof value === "string") {
906
+ if (!hasValueRepair || !value.includes(REFERENCE) || key.startsWith("--")) return value;
907
+ return repairValue(value);
908
+ }
909
+ if (TIMES.has(key)) return `${value}ms`;
910
+ return value !== 0 && !key.startsWith("--") && !UNITLESS.has(key) ? `${value}px` : String(value);
654
911
  }
655
912
  /** Splits `selector` on the commas that are not inside brackets or parentheses. */
656
913
  function splitSelectors(selector) {
@@ -736,14 +993,14 @@ function compileNested(selector, key, value, context) {
736
993
  return compileStyle(selector, value, context).map((rule) => `${key}{${rule}}`);
737
994
  }
738
995
  /** The declarations of one item: a custom property takes any text, so a fallback would always win there, and is not written. */
739
- function toItemDeclarations(key, name, item, hasColorFallbacks) {
740
- if (!isAlphaColor(item)) return `${name}:${toValue(key, item)};`;
741
- return `${hasColorFallbacks && !key.startsWith("--") ? `${name}:${item.fallback};` : ""}${name}:${item.value};`;
996
+ function toItemDeclarations(key, name, item, context) {
997
+ if (!isAlphaColor(item)) return `${name}:${toValue(key, item, context.hasValueRepair)};`;
998
+ return `${context.hasColorFallbacks && !key.startsWith("--") ? `${name}:${item.fallback};` : ""}${name}:${item.value};`;
742
999
  }
743
1000
  /** The declarations of one property: one for a value, one for each item of a fallback list. */
744
- function toDeclarations(key, value, hasColorFallbacks) {
1001
+ function toDeclarations(key, value, context) {
745
1002
  const name = toPropertyName(key);
746
- return (Array.isArray(value) ? value : [value]).map((item) => toItemDeclarations(key, name, item, hasColorFallbacks)).join("");
1003
+ return (Array.isArray(value) ? value : [value]).map((item) => toItemDeclarations(key, name, item, context)).join("");
747
1004
  }
748
1005
  /** The rules of `style` for `selector`, with the options of `context`. */
749
1006
  function compileStyle(selector, style, context) {
@@ -752,18 +1009,20 @@ function compileStyle(selector, style, context) {
752
1009
  for (const [key, value] of Object.entries(style)) {
753
1010
  if (key === "label" || value === null || value === void 0 || value === false) continue;
754
1011
  if (isStyleObject(value)) nested.push(...compileNested(selector, key, value, context));
755
- else declarations += toDeclarations(key, value, context.hasColorFallbacks);
1012
+ else declarations += toDeclarations(key, value, context);
756
1013
  }
757
1014
  return declarations ? [`${selector}{${declarations}}`, ...nested] : nested;
758
1015
  }
759
1016
  /**
760
1017
  * The flat CSS rules of `style` for `selector`; without `hasColorFallbacks` an `alpha()` result is
761
1018
  * written as its mix alone. A `when()` or `whenScheme()` key becomes a scoped rule, written as
762
- * `scoping` says.
1019
+ * `scoping` says. With `hasValueRepair` the string forms of token maths that are never valid CSS
1020
+ * (`var(--x)1F`, `-var(--x)`, `var(--x)ms`) are rewritten in each value.
763
1021
  */
764
- function compileRules(selector, style, hasColorFallbacks = true, scoping = DEFAULT_SCOPING) {
1022
+ function compileRules(selector, style, hasColorFallbacks = true, scoping = DEFAULT_SCOPING, hasValueRepair = false) {
765
1023
  return compileStyle(selector, style, {
766
1024
  hasColorFallbacks,
1025
+ hasValueRepair,
767
1026
  scoping
768
1027
  });
769
1028
  }
@@ -772,13 +1031,789 @@ function readLabel(style) {
772
1031
  const { label } = style;
773
1032
  return typeof label === "string" ? label : "";
774
1033
  }
1034
+ // src/sheetEntry.ts
1035
+ const BRAND$1 = Symbol.for("umber-style.sheet-entry");
1036
+ const SOURCE = Symbol.for("umber-style.sheet-entry-source");
1037
+ const ENTRY_KEY_PREFIX = "--umber-entry-";
1038
+ /**
1039
+ * Makes the entry of a class name: a frozen object that `isSheetEntry` knows and that prints as the
1040
+ * class name. Its one enumerable key is a custom property named after the class, with the value `null`,
1041
+ * so that a framework that merges the style objects of an array (Vue does) keeps every entry, and
1042
+ * `flattenStyle` finds them by the key. Both frameworks skip a `null` style value on a plain element, on
1043
+ * the client and on the server, so an entry given to a plain element renders no style attribute. With a
1044
+ * `source` (a cache made it) the class name is read through it, so that the rule is written when the entry
1045
+ * is used, not when it is made; without one the entry is just the name.
1046
+ */
1047
+ function createSheetEntry(className, source) {
1048
+ const entry = {
1049
+ [`${ENTRY_KEY_PREFIX}${className}`]: null,
1050
+ [BRAND$1]: true
1051
+ };
1052
+ const read = () => source?.use("components") ?? className;
1053
+ Object.defineProperties(entry, {
1054
+ className: { get: read },
1055
+ toString: { value: read },
1056
+ ...source ? { [SOURCE]: { value: source } } : {}
1057
+ });
1058
+ return Object.freeze(entry);
1059
+ }
1060
+ /** Whether `value` was made by `createSheetEntry`: a class name is a plain string, a style object has no brand. */
1061
+ function isSheetEntry(value) {
1062
+ return typeof value === "object" && value !== null && BRAND$1 in value;
1063
+ }
1064
+ /** What a cache gave `entry` to make its classes, or undefined for an entry that is only a name. */
1065
+ function readEntrySource(entry) {
1066
+ return entry[SOURCE];
1067
+ }
1068
+ /** The cache that made the first entry among `values` that a cache made, or undefined when there is none. */
1069
+ function findEntryCache(values) {
1070
+ for (const value of values) {
1071
+ const source = isSheetEntry(value) ? readEntrySource(value) : void 0;
1072
+ if (source) return source.cache;
1073
+ }
1074
+ }
1075
+ /**
1076
+ * The style of `value` when it is a sheet entry, else `value` as it is: for a place that takes a style
1077
+ * object and so also an entry. Throws a `TypeError`, that names `caller`, for an entry that is only a class
1078
+ * name (one that no cache made), whose style is not known.
1079
+ */
1080
+ function readEntryStyle(value, caller) {
1081
+ if (!isSheetEntry(value)) return value;
1082
+ const source = readEntrySource(value);
1083
+ if (!source) throw new TypeError(`${caller}(): the sheet entry "${value.className}" is only a class name, so its style cannot be merged.`);
1084
+ return source.style;
1085
+ }
1086
+ /**
1087
+ * What a `style` prop holds, as a flat list in order, for the cache to merge into one class: sheet
1088
+ * entries and plain style objects, with arrays flattened and what is empty dropped. An object in which a
1089
+ * framework merged entries and plain keys (Vue does) is split back into its entries, then the rest; an
1090
+ * entry is looked up by its class name with `findEntry` (a cache's `findEntry`), else it is only the name.
1091
+ * A string is an error: a text style cannot be merged into a class.
1092
+ */
1093
+ function flattenStyle(style, findEntry) {
1094
+ const flat = [];
1095
+ const visit = (value) => {
1096
+ if (Array.isArray(value)) value.forEach(visit);
1097
+ else if (typeof value === "string" && value) throw new Error("A style given as a string cannot be merged into a class: use a sheet entry or an object.");
1098
+ else if (isSheetEntry(value) && readEntrySource(value)) flat.push(value);
1099
+ else if (typeof value === "object" && value !== null) {
1100
+ const rest = {};
1101
+ for (const [key, item] of Object.entries(value)) if (key.startsWith(ENTRY_KEY_PREFIX)) {
1102
+ const name = key.slice(14);
1103
+ flat.push(findEntry?.(name) ?? createSheetEntry(name));
1104
+ } else rest[key] = item;
1105
+ if (Object.keys(rest).length > 0) flat.push(rest);
1106
+ }
1107
+ };
1108
+ visit(style);
1109
+ return flat;
1110
+ }
1111
+ // src/templateStyle.ts
1112
+ /** The character that stands for an interpolation in the joined text of a template: CSS never holds it. */
1113
+ const HOLE = "\0";
1114
+ /**
1115
+ * After an interpolation that starts a statement: a newline before anything but spaces and a line
1116
+ * comment, then a character that does not go on with a selector or a property name. The interpolation is
1117
+ * then a statement of its own, as `${mixin}` alone on its line is.
1118
+ */
1119
+ const OWN_LINE = /[^\S\n]*(?:\/\/.*)?\n\s*[^\s{,:>+~]/y;
1120
+ const templates = /* @__PURE__ */ new WeakMap();
1121
+ /** Throws the `TypeError` of a template that cannot be read: `problem`, with the line and the text around `at`. */
1122
+ function fail(text, at, problem) {
1123
+ const line = text.slice(0, at).split("\n").length;
1124
+ const around = text.slice(Math.max(0, at - 30), at + 10).replaceAll(HOLE, `\${}`).replace(/\s+/g, " ").trim();
1125
+ throw new TypeError(`parseStyleTemplate(): ${problem} at line ${line}: "${around}"`);
1126
+ }
1127
+ /** The style key of a CSS property name: camelCase (`-webkit-x` is `WebkitX`, written back as it was); a custom property as it is. */
1128
+ function toKey(name) {
1129
+ if (name.startsWith("--")) return name;
1130
+ return name.toLowerCase().replace(/-([a-z])/g, (_match, letter) => letter.toUpperCase());
1131
+ }
1132
+ /** `pieces` as one text: adjacent static text joined, trimmed at both ends; a string when no interpolation is left. */
1133
+ function join(pieces) {
1134
+ const joined = [];
1135
+ let text = "";
1136
+ for (const piece of pieces) if (typeof piece === "string") text += piece;
1137
+ else {
1138
+ joined.push(text, piece);
1139
+ text = "";
1140
+ }
1141
+ joined.push(text);
1142
+ joined[0] = joined[0].trimStart();
1143
+ joined[joined.length - 1] = joined.at(-1).trimEnd();
1144
+ return joined.length === 1 ? joined[0] : joined.filter((piece) => piece !== "");
1145
+ }
1146
+ /** Ends the text not yet in the pieces of the statement: it becomes a piece unless it is only whitespace at the start. */
1147
+ function flush(state) {
1148
+ if (state.pieces.length > 0 || state.chunk.trim()) state.pieces.push(state.chunk);
1149
+ state.chunk = "";
1150
+ }
1151
+ /** Adds a space to the statement, unless it already ends with one. */
1152
+ function space(state) {
1153
+ if (!state.chunk.endsWith(" ")) state.chunk += " ";
1154
+ }
1155
+ /** Counts the holes from `from` to `to` as read: they are in a comment, and stand for nothing. */
1156
+ function skip(state, from, to) {
1157
+ state.hole += state.text.slice(from, to).split(HOLE).length - 1;
1158
+ }
1159
+ /** Adds the next interpolation to the pieces of the statement. */
1160
+ function addHole(state) {
1161
+ flush(state);
1162
+ state.pieces.push(state.hole++);
1163
+ }
1164
+ /** Adds the declaration that was read to the block: the pieces before its first ':' are its key, the rest its value. */
1165
+ function endDeclaration(state, at) {
1166
+ const key = join(state.pieces.slice(0, state.split));
1167
+ if (key === "") fail(state.text, at, "a declaration without a property");
1168
+ state.body.push({
1169
+ key: typeof key === "string" ? toKey(key) : key,
1170
+ value: join(state.pieces.slice(state.split + 1))
1171
+ });
1172
+ }
1173
+ /** Adds the interpolations that were read without a ':' to the block, each a statement of its own; any other text is a declaration without one. */
1174
+ function endInterpolations(state, at) {
1175
+ for (const piece of state.pieces) if (typeof piece === "number") state.body.push(piece);
1176
+ else if (piece.trim()) fail(state.text, at, "a declaration without \":\"");
1177
+ }
1178
+ /** Ends the statement being read at `at`, and starts the next one. */
1179
+ function end(state, at) {
1180
+ flush(state);
1181
+ if (state.split >= 0) endDeclaration(state, at);
1182
+ else endInterpolations(state, at);
1183
+ state.pieces = [];
1184
+ state.split = -1;
1185
+ }
1186
+ /** Reads the interpolation at `index`; one that starts a statement and stands on its own line ends it. Returns the index after it. */
1187
+ function readHole(state, index) {
1188
+ addHole(state);
1189
+ if (state.pieces.length === 1) {
1190
+ OWN_LINE.lastIndex = index + 1;
1191
+ if (OWN_LINE.test(state.text)) end(state, index);
1192
+ }
1193
+ return index + 1;
1194
+ }
1195
+ /** Copies the character at `index` into the statement, and the next one when it is an escape: `HOLE` and past the end are not above it, so a hole is not kept. Returns the index after them. */
1196
+ function readEscaped(state, index) {
1197
+ const { text } = state;
1198
+ const length = text[index] === "\\" && text[index + 1] > HOLE ? 2 : 1;
1199
+ state.chunk += text.slice(index, index + length);
1200
+ return index + length;
1201
+ }
1202
+ /** Reads the string that starts at `index`, with the interpolations in it. Returns the index after its closing quote. */
1203
+ function readString(state, index) {
1204
+ const { text } = state;
1205
+ const quote = text[index];
1206
+ state.chunk += quote;
1207
+ let at = index + 1;
1208
+ while (text[at] !== quote) {
1209
+ if (at >= text.length) fail(text, index, "an unclosed string");
1210
+ if (text[at] === HOLE) {
1211
+ addHole(state);
1212
+ at++;
1213
+ } else at = readEscaped(state, at);
1214
+ }
1215
+ state.chunk += quote;
1216
+ return at + 1;
1217
+ }
1218
+ /** Reads the comment that starts at `index`: it is a space. Returns the index after its `*` and `/`. */
1219
+ function readComment$1(state, index) {
1220
+ const close = state.text.indexOf("*/", index + 2);
1221
+ if (close < 0) fail(state.text, index, "an unclosed comment");
1222
+ skip(state, index, close);
1223
+ space(state);
1224
+ return close + 2;
1225
+ }
1226
+ /** Reads the line comment that starts at `index`. Returns the index of the newline that ends it, or the end of the text. */
1227
+ function readLineComment(state, index) {
1228
+ const stop = state.text.indexOf("\n", index);
1229
+ const close = stop < 0 ? state.text.length : stop;
1230
+ skip(state, index, close);
1231
+ return close;
1232
+ }
1233
+ /** Reads the `/` at `index`: the start of a comment, or a character of the statement. Returns the index after what it read. */
1234
+ function readSlash(state, index) {
1235
+ const next = state.text[index + 1];
1236
+ if (next === "*") return readComment$1(state, index);
1237
+ if (next === "/" && state.depth === 0) return readLineComment(state, index);
1238
+ state.chunk += "/";
1239
+ return index + 1;
1240
+ }
1241
+ /** Reads `char` at `index` inside parentheses, or the `(` that opens them: it is a character of the statement. */
1242
+ function readParenthesized(state, char, index) {
1243
+ if (char === "(" && state.depth++ === 0) state.parenAt = index;
1244
+ else if (char === ")") state.depth--;
1245
+ state.chunk += char;
1246
+ }
1247
+ /** Reads the first ':' of a statement: what is before it is the key of a declaration. */
1248
+ function readColon(state) {
1249
+ flush(state);
1250
+ state.split = state.pieces.length;
1251
+ state.pieces.push(":");
1252
+ }
1253
+ /** Reads the `{` at `index`: the statement read so far is the prelude of a block, which is open until its `}`. */
1254
+ function openBlock$1(state, index) {
1255
+ flush(state);
1256
+ const prelude = join(state.pieces);
1257
+ if (prelude === "") fail(state.text, index, "a block without a selector");
1258
+ const block = {
1259
+ prelude,
1260
+ body: []
1261
+ };
1262
+ state.body.push(block);
1263
+ state.open.push([state.body, index]);
1264
+ state.body = block.body;
1265
+ state.pieces = [];
1266
+ state.split = -1;
1267
+ }
1268
+ /** Reads the `}` at `index`: it ends the statement being read and the innermost open block. */
1269
+ function closeBlock$1(state, index) {
1270
+ end(state, index);
1271
+ const parent = state.open.pop();
1272
+ if (!parent) fail(state.text, index, "a \"}\" without a \"{\"");
1273
+ state.body = parent[0];
1274
+ }
1275
+ /** Reads `char` at `index`, outside strings, comments and parentheses. */
1276
+ function readStatementChar(state, char, index) {
1277
+ switch (char) {
1278
+ case ":":
1279
+ if (state.split < 0) readColon(state);
1280
+ else state.chunk += char;
1281
+ break;
1282
+ case ";":
1283
+ end(state, index);
1284
+ break;
1285
+ case "{":
1286
+ openBlock$1(state, index);
1287
+ break;
1288
+ case "}":
1289
+ closeBlock$1(state, index);
1290
+ break;
1291
+ default: state.chunk += char;
1292
+ }
1293
+ }
1294
+ /** Reads `char` at `index`, which starts nothing longer: whitespace, a character in parentheses, or one of a statement. */
1295
+ function readChar(state, char, index) {
1296
+ if (char <= " ") space(state);
1297
+ else if (state.depth > 0 || char === "(") readParenthesized(state, char, index);
1298
+ else readStatementChar(state, char, index);
1299
+ }
1300
+ /** Reads what starts at `index`: an interpolation, a string, an escape, a comment, or one character. Returns the index after it. */
1301
+ function readNext(state, index) {
1302
+ const char = state.text[index];
1303
+ switch (char) {
1304
+ case HOLE: return readHole(state, index);
1305
+ case "\"":
1306
+ case "'": return readString(state, index);
1307
+ case "\\": return readEscaped(state, index);
1308
+ case "/": return readSlash(state, index);
1309
+ default:
1310
+ readChar(state, char, index);
1311
+ return index + 1;
1312
+ }
1313
+ }
1314
+ /**
1315
+ * The statements of `text`, a template's strings joined with `HOLE`, in one pass. Outside strings and
1316
+ * comments a run of whitespace is one space; a comment is a space; the holes in a comment are skipped.
1317
+ */
1318
+ function parse(text) {
1319
+ const root = [];
1320
+ const state = {
1321
+ text,
1322
+ open: [],
1323
+ body: root,
1324
+ pieces: [],
1325
+ chunk: "",
1326
+ split: -1,
1327
+ hole: 0,
1328
+ depth: 0,
1329
+ parenAt: 0
1330
+ };
1331
+ let index = 0;
1332
+ while (index < text.length) index = readNext(state, index);
1333
+ if (state.depth > 0) fail(text, state.parenAt, "an unclosed \"(\"");
1334
+ end(state, text.length);
1335
+ const unclosed = state.open.pop();
1336
+ if (unclosed) fail(text, unclosed[1], "an unclosed block");
1337
+ return root;
1338
+ }
1339
+ /** Whether `value` is a function of the props: not one that prints as text of its own (a stand-in for the theme, a component that is a selector). */
1340
+ function isCallable(value) {
1341
+ return typeof value === "function" && value.toString === Function.prototype.toString;
1342
+ }
1343
+ /** Whether `value`, or an item of it, is a function of the props. */
1344
+ function isDynamic(value) {
1345
+ return isCallable(value) || Array.isArray(value) && value.some(isDynamic);
1346
+ }
1347
+ /** `value` with each function called with `props`, until it is not a function. */
1348
+ function resolve(value, props) {
1349
+ let resolved = value;
1350
+ while (isCallable(resolved)) resolved = resolved(props);
1351
+ return resolved;
1352
+ }
1353
+ /** Whether `value` is a plain object, not one with a text of its own (a sheet entry, an `alpha()` result). */
1354
+ function isPlainObject$2(value) {
1355
+ return typeof value === "object" && value !== null && value.toString === Object.prototype.toString;
1356
+ }
1357
+ /** An interpolation as text in a value, a selector or a property name. */
1358
+ function toText$1(value, props) {
1359
+ const resolved = resolve(value, props);
1360
+ if (Array.isArray(resolved)) return resolved.map((item) => toText$1(item, props)).join("");
1361
+ if (resolved === null || resolved === void 0 || typeof resolved === "boolean") return "";
1362
+ if (isPlainObject$2(resolved)) throw new TypeError("parseStyleTemplate(): a style object can stand only between declarations, not in a value, a selector or a property name.");
1363
+ return String(resolved);
1364
+ }
1365
+ /** `text` with its interpolations filled in, trimmed. */
1366
+ function fill(text, values, props) {
1367
+ if (typeof text === "string") return text;
1368
+ let filled = "";
1369
+ for (const piece of text) filled += typeof piece === "string" ? piece : toText$1(values[piece], props);
1370
+ return filled.trim();
1371
+ }
1372
+ /** A declared value: an `alpha()` result that is the whole value is kept, so that its fallback is written; anything else is text. */
1373
+ function fillValue(text, values, props) {
1374
+ if (typeof text === "string" || text.length > 1) return fill(text, values, props);
1375
+ const value = resolve(values[text[0]], props);
1376
+ return isAlphaColor(value) ? value : toText$1(value, props).trim();
1377
+ }
1378
+ /** Whether `value` is a nested style, not a declared value. */
1379
+ function isNested(value) {
1380
+ return typeof value === "object" && value !== null && !Array.isArray(value) && !isAlphaColor(value);
1381
+ }
1382
+ /**
1383
+ * Sets `key` of `style` to `value`, at the end: a nested style is merged into the one before it; a value
1384
+ * declared again is added to the one before it as a fallback list, as CSS writes both.
1385
+ */
1386
+ function put(style, key, value) {
1387
+ const earlier = style[key];
1388
+ delete style[key];
1389
+ if (isNested(value)) style[key] = isNested(earlier) ? mergeStyles([earlier, value]) : value;
1390
+ else if (earlier === void 0 || earlier === null || earlier === false || isNested(earlier)) style[key] = value;
1391
+ else style[key] = [earlier, value].flat();
1392
+ }
1393
+ /** `style` with the interpolation `value` that stands between declarations merged in. */
1394
+ function include(style, value, props) {
1395
+ const resolved = resolve(value, props);
1396
+ if (Array.isArray(resolved)) return resolved.reduce((merged, item) => include(merged, item, props), style);
1397
+ if (resolved === null || resolved === void 0 || typeof resolved === "boolean") return style;
1398
+ if (isSheetEntry(resolved)) {
1399
+ const source = readEntrySource(resolved);
1400
+ if (!source) throw new TypeError(`parseStyleTemplate(): the sheet entry "${resolved.className}" is only a class name, so its style cannot be merged.`);
1401
+ return mergeStyles([style, source.style]);
1402
+ }
1403
+ if (isPlainObject$2(resolved)) return mergeStyles([style, resolved]);
1404
+ return build(parse(String(resolved)), [], props, style);
1405
+ }
1406
+ /** The style of `nodes`, with `values` for the interpolations and `props` for the functions among them, added to `style`. */
1407
+ function build(nodes, values, props, style = {}) {
1408
+ let built = style;
1409
+ for (const node of nodes) if (typeof node === "number") built = include(built, values[node], props);
1410
+ else if ("body" in node) put(built, fill(node.prelude, values, props), build(node.body, values, props));
1411
+ else {
1412
+ const key = typeof node.key === "string" ? node.key : toKey(fill(node.key, values, props));
1413
+ put(built, key, fillValue(node.value, values, props));
1414
+ }
1415
+ return built;
1416
+ }
1417
+ /** Whether `value` is the strings of a tagged template: an array with `raw`, which a call with styles never is. */
1418
+ function isTemplateStrings(value) {
1419
+ return Array.isArray(value) && Object.hasOwn(value, "raw");
1420
+ }
1421
+ /**
1422
+ * The style of a tagged template, `strings` and `values` as a tag is given them: CSS text with
1423
+ * declarations, nested rules (`&:hover { }`, `> p { }`), at-rules (`@media (...) { }`) and comments.
1424
+ * A value is kept as text (`padding: 8px` is `'8px'`); a property is a camelCase key; a property declared
1425
+ * twice in a block is a fallback list. An interpolation in a value, a selector or a property name is
1426
+ * text; one alone between declarations is merged in: a style object, a sheet entry, CSS text, or a list
1427
+ * of them. `null`, `undefined`, `true` and `false` are nothing. When an interpolation is a function, the
1428
+ * result is a function of the props that calls it with them (what it returns is an interpolation too);
1429
+ * else it is the style. The text is split once for each `strings` array. Throws a `TypeError` with the
1430
+ * text around the place for a template that cannot be read.
1431
+ */
1432
+ function parseStyleTemplate(strings, values) {
1433
+ const nodes = templates.get(strings) ?? parse(strings.join(HOLE));
1434
+ templates.set(strings, nodes);
1435
+ return values.some(isDynamic) ? (props) => build(nodes, values, props) : build(nodes, values, void 0);
1436
+ }
1437
+ /**
1438
+ * The steps of an animation from a tagged template: `from { ... } 50% { ... } to { ... }`, read as
1439
+ * `parseStyleTemplate` reads a style. When an interpolation is a function, the result is a function of
1440
+ * the theme, and the function is called with `{ theme }`, as a function in a style is.
1441
+ */
1442
+ function parseKeyframesTemplate(strings, values) {
1443
+ const steps = parseStyleTemplate(strings, values);
1444
+ return typeof steps === "function" ? (theme) => steps({ theme }) : steps;
1445
+ }
1446
+ // src/globalStyles.ts
1447
+ const BRAND = Symbol.for("umber-style.global-styles");
1448
+ /** The at-rules that hold rules (selectors as keys); every other at-rule holds declarations. */
1449
+ const GROUP_AT_RULE = /^@(?:media|supports|container|layer|scope|starting-style|document)(?![\w-])/;
1450
+ /** `value` for the id of a handle: a stand-in as its path, everything else as it is. */
1451
+ function toText(_key, value) {
1452
+ return readStandIn(value);
1453
+ }
1454
+ function globalStyles(first, ...values) {
1455
+ if (isTemplateStrings(first)) {
1456
+ const parsed = parseStyleTemplate(first, values);
1457
+ return globalStyles(typeof parsed === "function" ? (theme) => parsed({ theme }) : parsed);
1458
+ }
1459
+ const styles = first;
1460
+ if (typeof styles === "function") {
1461
+ const hash = hashString(`theme:${JSON.stringify(styles(createStandIn("")), toText)}`);
1462
+ return Object.freeze({
1463
+ [BRAND]: true,
1464
+ id: `global-${hash}`,
1465
+ resolve: (readTheme) => styles(readTheme())
1466
+ });
1467
+ }
1468
+ if (typeof styles !== "object" || styles === null || Array.isArray(styles)) throw new TypeError("globalStyles(): the styles must be an object, or a function that returns one.");
1469
+ return Object.freeze({
1470
+ [BRAND]: true,
1471
+ id: `global-${hashString(JSON.stringify(styles))}`,
1472
+ resolve: () => styles
1473
+ });
1474
+ }
1475
+ /** Whether `value` is a handle that `globalStyles` made. */
1476
+ function isGlobalStyles(value) {
1477
+ return typeof value === "object" && value !== null && BRAND in value;
1478
+ }
1479
+ /** The styles of one item of a `GlobalInput`: a handle resolves itself, a function is called with the theme that `readTheme` gives. */
1480
+ function readGlobalStyles(item, readTheme) {
1481
+ if (isGlobalStyles(item)) return item.resolve(readTheme);
1482
+ return typeof item === "function" ? item(readTheme()) : item;
1483
+ }
1484
+ /** The style of one item under `key` (a sheet entry is read as its style); a `TypeError` for anything that is not a style object. */
1485
+ function readGlobalItem(key, each) {
1486
+ const item = readEntryStyle(each, "globalStyles");
1487
+ if (typeof item !== "object" || item === null || Array.isArray(item)) throw new TypeError(`globalStyles(): "${key}" must hold a style object, or a list of them.`);
1488
+ return item;
1489
+ }
1490
+ /** Adds to `rules` the rules of the style `item` under `key`: an at-rule that holds rules around the rules of its keys, any other key compiled as a class's style is. */
1491
+ function addGlobalItemRules(rules, key, item, hasColorFallbacks, scoping, hasValueRepair) {
1492
+ if (!GROUP_AT_RULE.test(key)) {
1493
+ rules.push(...compileRules(key, item, hasColorFallbacks, scoping, hasValueRepair));
1494
+ return;
1495
+ }
1496
+ const inner = compileGlobalRules(item, hasColorFallbacks, scoping, hasValueRepair);
1497
+ if (inner.length > 0) rules.push(`${key}{${inner.join("")}}`);
1498
+ }
1499
+ /**
1500
+ * The flat CSS rules of global styles, in the order of their keys: a selector's style compiled as a
1501
+ * class's is, an at-rule that holds rules as one rule around the rules of its keys, any other at-rule as
1502
+ * a rule of declarations (one for each item of a list). Throws a `TypeError` for styles that are not an
1503
+ * object, and for a key that holds no style.
1504
+ */
1505
+ function compileGlobalRules(styles, hasColorFallbacks, scoping, hasValueRepair) {
1506
+ if (typeof styles !== "object" || styles === null || Array.isArray(styles)) throw new TypeError("globalStyles(): the styles must be an object, or a function that returns one.");
1507
+ const rules = [];
1508
+ for (const [key, value] of Object.entries(styles)) {
1509
+ if (value === null || value === void 0 || value === false) continue;
1510
+ for (const each of Array.isArray(value) ? value : [value]) addGlobalItemRules(rules, key, readGlobalItem(key, each), hasColorFallbacks, scoping, hasValueRepair);
1511
+ }
1512
+ return rules;
1513
+ }
1514
+ // src/keyframes.ts
1515
+ const DEFAULT_LABEL = "keyframes";
1516
+ const LABEL_PATTERN = /^[A-Za-z_][\w-]*$/;
1517
+ const OFFSET_PATTERN = /^(?:\d+(?:\.\d+)?|\.\d+)%$/;
1518
+ const ANIMATION = "animation";
1519
+ const NAME_SUFFIX = "-name:";
1520
+ const NONE = [];
1521
+ const registry = /* @__PURE__ */ new Map();
1522
+ /** The value of `key` in a step, with a stand-in (alone or in a list) turned into its path; a nested style is a `TypeError`. */
1523
+ function readStepValue(offset, key, value) {
1524
+ if (Array.isArray(value)) return value.map((item) => readStandIn(item));
1525
+ const read = readStandIn(value);
1526
+ if (typeof read !== "object" || read === null || isAlphaColor(read)) return read;
1527
+ throw new TypeError(`keyframes(): the step "${offset}" holds "${key}", a nested style (a selector or an at-rule). A step is flat: it holds declarations only.`);
1528
+ }
1529
+ /** The offset of one part of a step key, from 0 to 100; a `TypeError` for anything else. */
1530
+ function readOffset(part, key) {
1531
+ if (part === "from") return 0;
1532
+ if (part === "to") return 100;
1533
+ const offset = OFFSET_PATTERN.test(part) ? Number.parseFloat(part) : NaN;
1534
+ if (Number.isNaN(offset) || offset > 100) throw new TypeError(`keyframes(): "${key}" is not a step: use from, to, a percentage from 0% to 100%, or a comma list of them.`);
1535
+ return offset;
1536
+ }
1537
+ /** The steps by offset, sorted: comma lists expanded, `from` and `to` as 0% and 100%, steps of one offset merged with the later one winning. */
1538
+ function normalizeSteps(steps) {
1539
+ if (typeof steps !== "object" || steps === null) throw new TypeError("keyframes(): the steps must be an object, or a function that returns one.");
1540
+ const merged = /* @__PURE__ */ new Map();
1541
+ for (const [key, step] of Object.entries(steps)) {
1542
+ if (typeof step !== "object" || step === null) throw new TypeError(`keyframes(): the step "${key}" must be an object of declarations.`);
1543
+ const flat = {};
1544
+ for (const [name, value] of Object.entries(step)) flat[name] = readStepValue(key, name, value);
1545
+ for (const part of key.split(",")) {
1546
+ const offset = readOffset(part.trim(), key);
1547
+ const earlier = merged.get(offset);
1548
+ merged.set(offset, earlier ? mergeStyles([earlier, flat]) : flat);
1549
+ }
1550
+ }
1551
+ return [...merged].sort(([first], [second]) => first - second);
1552
+ }
1553
+ /** The body of a `@keyframes` rule: each step that declares something, sorted, written as the rule of a class. */
1554
+ function compileSteps(steps, hasColorFallbacks, hasValueRepair) {
1555
+ return normalizeSteps(steps).flatMap(([offset, step]) => compileRules(`${offset}%`, step, hasColorFallbacks, DEFAULT_SCOPING, hasValueRepair)).join("");
1556
+ }
1557
+ function keyframes(first, ...rest) {
1558
+ if (isTemplateStrings(first)) return keyframes(parseKeyframesTemplate(first, rest));
1559
+ const steps = first;
1560
+ const { label = DEFAULT_LABEL } = rest[0] ?? {};
1561
+ if (!LABEL_PATTERN.test(label)) throw new TypeError(`keyframes(): the label "${label}" is not an identifier: use letters, digits, '-' and '_', not starting with a digit or '-'.`);
1562
+ const isThemed = typeof steps === "function";
1563
+ const resolved = isThemed ? steps(createStandIn("")) : steps;
1564
+ const name = `${label}-${hashString((isThemed ? "theme:" : "") + compileSteps(resolved, true, false))}`;
1565
+ if (!registry.has(name)) registry.set(name, steps);
1566
+ return name;
1567
+ }
1568
+ /** Whether `name` is a name that `keyframes` returned. */
1569
+ function isKeyframesName(name) {
1570
+ return registry.has(name);
1571
+ }
1572
+ /**
1573
+ * The `@keyframes` rule of the registered `name`: steps given as a function are resolved against the
1574
+ * theme that `readTheme` gives, which is read only then.
1575
+ */
1576
+ function createKeyframesRule(name, readTheme, hasColorFallbacks, hasValueRepair) {
1577
+ const steps = registry.get(name);
1578
+ return `@keyframes ${name}{${compileSteps(typeof steps === "function" ? steps(readTheme()) : steps, hasColorFallbacks, hasValueRepair)}}`;
1579
+ }
1580
+ /** Adds to `names` each identifier of `value` that is a registered name. */
1581
+ function addRegistered(value, names) {
1582
+ for (const word of value.split(/[^\w-]+/)) if (registry.has(word) && !names.includes(word)) names.push(word);
1583
+ }
1584
+ /** Where the value starts when the `animation` at `index` of `rule` begins an `animation` or `animation-name` declaration, else -1. */
1585
+ function findValueStart(rule, index) {
1586
+ const before = rule[index - 1];
1587
+ if (before !== "{" && before !== ";") return -1;
1588
+ const after = index + 9;
1589
+ if (rule[after] === ":") return after + 1;
1590
+ return rule.startsWith(NAME_SUFFIX, after) ? after + 6 : -1;
1591
+ }
1592
+ /**
1593
+ * The registered names that the `animation` and `animation-name` declarations of `rules` (compiled rules,
1594
+ * whose declarations each end with `;`) use, in nested selectors and at-rules too, matched as whole
1595
+ * identifiers. Nothing is read while no name is registered.
1596
+ */
1597
+ function findAnimationNames(rules) {
1598
+ if (registry.size === 0) return NONE;
1599
+ const names = [];
1600
+ for (const rule of rules) {
1601
+ let index = rule.indexOf(ANIMATION);
1602
+ while (index !== -1) {
1603
+ const start = findValueStart(rule, index);
1604
+ if (start !== -1) {
1605
+ index = rule.indexOf(";", start);
1606
+ addRegistered(rule.slice(start, index), names);
1607
+ }
1608
+ index = rule.indexOf(ANIMATION, index + 1);
1609
+ }
1610
+ }
1611
+ return names;
1612
+ }
1613
+ // src/variables.ts
1614
+ const VARIABLE_OPEN = "var(";
1615
+ /** Whether `code` is a character of a variable name: a lowercase letter, a digit, '-' or '_'. */
1616
+ function isNameCode$1(code) {
1617
+ return code >= 97 && code <= 122 || code >= 48 && code <= 57 || code === 45 || code === 95;
1618
+ }
1619
+ /** The index of the first character at or after `index` that is not whitespace. */
1620
+ function skipSpaces$1(text, index) {
1621
+ let position = index;
1622
+ while (codeAt(text, position) <= 32) position++;
1623
+ return position;
1624
+ }
1625
+ /**
1626
+ * The names of the variables that `css` refers to and that start with `start` (`--<prefix>-`), in order
1627
+ * of appearance, with repeats. A reference may have a fallback, which may refer to others. One pass.
1628
+ */
1629
+ function scanVariables(css, start) {
1630
+ const names = [];
1631
+ let from = css.indexOf(VARIABLE_OPEN);
1632
+ while (from !== -1) {
1633
+ const begin = skipSpaces$1(css, from + 4);
1634
+ let end = begin + start.length;
1635
+ if (css.startsWith(start, begin)) {
1636
+ while (isNameCode$1(codeAt(css, end))) end++;
1637
+ names.push(css.slice(begin, end));
1638
+ }
1639
+ from = css.indexOf(VARIABLE_OPEN, begin);
1640
+ }
1641
+ return names;
1642
+ }
1643
+ // src/scanStyleText.ts
1644
+ /** Makes findings that hold nothing. */
1645
+ function createEmptyFindings() {
1646
+ return {
1647
+ hasLayerOrder: false,
1648
+ classes: /* @__PURE__ */ new Set(),
1649
+ themes: /* @__PURE__ */ new Map(),
1650
+ properties: /* @__PURE__ */ new Map(),
1651
+ keyframes: /* @__PURE__ */ new Set(),
1652
+ variables: /* @__PURE__ */ new Set(),
1653
+ ruleCount: 0,
1654
+ globals: [],
1655
+ roots: []
1656
+ };
1657
+ }
1658
+ const LAYER_AT_RULE = "@layer";
1659
+ const ROOT_SELECTOR$1 = ":where(:root)";
1660
+ const PROPERTY_AT_RULE = "@property";
1661
+ const KEYFRAMES_AT_RULE = "@keyframes";
1662
+ /** Whether `code` is a character of a class name: a lowercase letter, a digit, '-' or '_'. */
1663
+ function isNameCode(code) {
1664
+ return code >= 97 && code <= 122 || code >= 48 && code <= 57 || code === 45 || code === 95;
1665
+ }
1666
+ /** The classes in `selector` whose name starts with `start` (`<prefix>-`), without the dot. */
1667
+ function readClasses(selector, start) {
1668
+ const names = [];
1669
+ let from = selector.indexOf(`.${start}`);
1670
+ while (from !== -1) {
1671
+ let end = from + 1 + start.length;
1672
+ while (isNameCode(codeAt(selector, end))) end++;
1673
+ names.push(selector.slice(from + 1, end));
1674
+ from = selector.indexOf(`.${start}`, end);
1675
+ }
1676
+ return names;
1677
+ }
1678
+ /** The names of the variables that `body`, the declarations of a rule, declares. */
1679
+ function readDeclared(body) {
1680
+ const names = /* @__PURE__ */ new Set();
1681
+ for (const part of body.split(";")) {
1682
+ const text = part.trimStart();
1683
+ if (text.startsWith("--")) names.add(text.slice(0, text.indexOf(":")));
1684
+ }
1685
+ return names;
1686
+ }
1687
+ /** The index after the string that starts at `index`, which is a quote. */
1688
+ function skipString(text, index) {
1689
+ const quote = text[index];
1690
+ let position = index + 1;
1691
+ while (position < text.length && text[position] !== quote) position += text[position] === "\\" ? 2 : 1;
1692
+ return position + 1;
1693
+ }
1694
+ /** Records the innermost rule `prelude{body}` of a style element in `found`. */
1695
+ function record(found, prefix, prelude, body) {
1696
+ if (prelude.startsWith(PROPERTY_AT_RULE)) {
1697
+ found.properties.set(prelude.slice(9).trim(), `${prelude}{${body}}`);
1698
+ return;
1699
+ }
1700
+ if (prelude.startsWith("@") || prelude === ROOT_SELECTOR$1) return;
1701
+ const themeStart = `${prefix}-theme-`;
1702
+ const classes = readClasses(prelude, `${prefix}-`);
1703
+ const themeId = classes.length === 1 && prelude === `.${classes[0]}` ? classes[0] : void 0;
1704
+ if (themeId?.startsWith(themeStart)) {
1705
+ const declared = found.themes.get(themeId) ?? /* @__PURE__ */ new Set();
1706
+ for (const name of readDeclared(body)) declared.add(name);
1707
+ found.themes.set(themeId, declared);
1708
+ return;
1709
+ }
1710
+ const markers = /* @__PURE__ */ new Set([
1711
+ `${prefix}-boundary`,
1712
+ `${prefix}-scheme-light`,
1713
+ `${prefix}-scheme-dark`
1714
+ ]);
1715
+ for (const name of classes) if (!name.startsWith(themeStart) && !markers.has(name)) found.classes.add(name);
1716
+ for (const name of scanVariables(body, `--${prefix}-`)) found.variables.add(name);
1717
+ }
1718
+ /** Opens a block at `index`, a `{`: its prelude is the text since `boundary`. */
1719
+ function openBlock(stack, text, boundary, index) {
1720
+ const parent = stack.at(-1);
1721
+ if (parent) parent.hasChild = true;
1722
+ stack.push({
1723
+ prelude: text.slice(boundary, index).trim(),
1724
+ bodyStart: index + 1,
1725
+ hasChild: false
1726
+ });
1727
+ }
1728
+ /** Closes the innermost block at `index`, a `}`, and returns it: a `@keyframes` rule records its name, and a block without a block of its own is a rule to record. */
1729
+ function closeBlock(stack, found, prefix, text, index) {
1730
+ const block = stack.pop();
1731
+ if (block?.prelude.startsWith(KEYFRAMES_AT_RULE)) found.keyframes.add(block.prelude.slice(10).trim());
1732
+ else if (block && !block.hasChild) record(found, prefix, block.prelude, text.slice(block.bodyStart, index));
1733
+ return block;
1734
+ }
1735
+ /** Whether a top-level rule with `prelude` may be a global rule: in the global layer, or in none and not a rule that the engine writes for something else. */
1736
+ function isGlobalPrelude(prefix, prelude) {
1737
+ if (prelude.startsWith(LAYER_AT_RULE)) return prelude === `${LAYER_AT_RULE} ${prefix}-global`;
1738
+ return !prelude.startsWith(PROPERTY_AT_RULE) && !prelude.startsWith(KEYFRAMES_AT_RULE) && !prelude.startsWith(`.${prefix}-`);
1739
+ }
1740
+ /** Whether the top-level rule `text` is the rule of a root theme, in the theme layer or in none. */
1741
+ function isRootRule(prefix, text) {
1742
+ return text.startsWith(`${ROOT_SELECTOR$1}{`) || text.startsWith(`${LAYER_AT_RULE} ${prefix}-theme{${ROOT_SELECTOR$1}{`);
1743
+ }
1744
+ /** Closes the innermost block at `index`, a `}`; when it is a top-level rule (which started at `ruleStart`), records its place in `found`, and whether it is the rule of a root theme or may be a global rule. */
1745
+ function closeRule(stack, found, prefix, text, ruleStart, index) {
1746
+ const block = closeBlock(stack, found, prefix, text, index);
1747
+ if (!block || stack.length > 0) return;
1748
+ const place = found.ruleCount++;
1749
+ const rule = text.slice(ruleStart, index + 1).trimStart();
1750
+ if (isRootRule(prefix, rule)) found.roots.push(place);
1751
+ else if (isGlobalPrelude(prefix, block.prelude)) found.globals.push([place, rule]);
1752
+ }
1753
+ /** Records the top-level statement `statement` (the text before a `;`, trimmed) in `found`: a rule unless it is empty, and the layer order statement when it is one. */
1754
+ function recordStatement(found, statement) {
1755
+ if (statement.startsWith(LAYER_AT_RULE)) found.hasLayerOrder = true;
1756
+ if (statement !== "") found.ruleCount++;
1757
+ }
1758
+ /**
1759
+ * Reads the CSS that an engine wrote (compact, no comments) in one pass and adds what it holds to
1760
+ * `found`: the layer order statement, the classes with a rule, each theme class with the variables it
1761
+ * declares, the `@property` rules, the names of the `@keyframes` rules, the variables that rules use, how
1762
+ * many rules are at the top level, the top-level rules that may be global rules, and the places of the
1763
+ * rules of a root theme.
1764
+ */
1765
+ function scanStyleText(prefix, text, found = createEmptyFindings()) {
1766
+ const stack = [];
1767
+ let boundary = 0;
1768
+ let ruleStart = 0;
1769
+ let index = 0;
1770
+ while (index < text.length) {
1771
+ const char = text[index];
1772
+ if (char === "\"" || char === "'") {
1773
+ index = skipString(text, index);
1774
+ continue;
1775
+ }
1776
+ if (char === "{") {
1777
+ if (stack.length === 0) ruleStart = boundary;
1778
+ openBlock(stack, text, boundary, index);
1779
+ boundary = index + 1;
1780
+ } else if (char === "}") {
1781
+ closeRule(stack, found, prefix, text, ruleStart, index);
1782
+ boundary = index + 1;
1783
+ } else if (char === ";" && stack.length === 0) {
1784
+ recordStatement(found, text.slice(boundary, index).trim());
1785
+ boundary = index + 1;
1786
+ }
1787
+ index++;
1788
+ }
1789
+ return found;
1790
+ }
775
1791
  // src/theme.ts
1792
+ /** The selector of the rule of the root theme: the document root, with no specificity. */
1793
+ const ROOT_SELECTOR = ":where(:root)";
1794
+ /** The rule `selector{body}` of a theme, inside the theme layer of `prefix` when there are layers. */
1795
+ function createThemeRule(prefix, hasLayers, selector, body) {
1796
+ const rule = `${selector}{${body}}`;
1797
+ return hasLayers ? `@layer ${prefix}-theme{${rule}}` : rule;
1798
+ }
776
1799
  /** The CSS declarations `name:value;` of `entries`. */
777
1800
  function toDeclarationText(entries) {
778
1801
  let text = "";
779
1802
  for (const [name, value] of entries) text += `${name}:${value};`;
780
1803
  return text;
781
1804
  }
1805
+ /** The hash of all the declarations of a theme, as text, and of its color-scheme: what names its class or root rule. */
1806
+ function hashTheme(variables, colorScheme) {
1807
+ return hashString(colorScheme ? `${variables}color-scheme:${colorScheme};` : variables);
1808
+ }
1809
+ /**
1810
+ * The theme class of the declarations `variables` (the text of `toDeclarationText`, as `readThemeText`
1811
+ * gives it) and of `colorScheme`, `<prefix>-theme-<hash>`, without registering it: the name that
1812
+ * `createThemeClass` gives the same declarations.
1813
+ */
1814
+ function createThemeId(prefix, variables, colorScheme) {
1815
+ return `${prefix}-theme-${hashTheme(variables, colorScheme)}`;
1816
+ }
782
1817
  /**
783
1818
  * Registers the theme class of `declarations` and returns it: the scope of a theme. Its name is the
784
1819
  * hash of all the declarations, whatever the cache writes of them (see `hasPruning`).
@@ -786,11 +1821,21 @@ function toDeclarationText(entries) {
786
1821
  function createThemeClass(cache, declarations, options = {}) {
787
1822
  const { colorScheme } = options;
788
1823
  const variables = toDeclarationText(Object.entries(declarations));
789
- const body = colorScheme ? `${variables}color-scheme:${colorScheme};` : variables;
790
- const className = `${cache.prefix}-theme-${hashString(body)}`;
1824
+ const className = createThemeId(cache.prefix, variables, colorScheme);
791
1825
  cache.insertTheme(className, declarations, colorScheme);
792
1826
  return className;
793
1827
  }
1828
+ /**
1829
+ * Makes `declarations` the root theme, the one declared on `:root` (see `Cache.insertRoot`), and returns
1830
+ * its id, `<prefix>-root-<hash>`: like a theme class, named by the hash of all its declarations.
1831
+ */
1832
+ function declareRootTheme(cache, declarations, options = {}) {
1833
+ const { colorScheme } = options;
1834
+ const variables = toDeclarationText(Object.entries(declarations));
1835
+ const id = `${cache.prefix}-root-${hashTheme(variables, colorScheme)}`;
1836
+ cache.insertRoot(id, declarations, colorScheme);
1837
+ return id;
1838
+ }
794
1839
  // src/cache.ts
795
1840
  /** The cascade layers of a cache, from the lowest priority to the highest. */
796
1841
  const RULE_LAYERS = [
@@ -812,36 +1857,62 @@ function createMemorySheet() {
812
1857
  },
813
1858
  replace(index, rule) {
814
1859
  rules[index] = rule;
1860
+ },
1861
+ remove(index) {
1862
+ rules.splice(index, 1);
815
1863
  }
816
1864
  };
817
1865
  }
818
- /** A sheet in the style element marked `data-style="<key>"`, which it creates when there is none. */
1866
+ /** Deletes `rule` from the style sheet that holds it, found by its place now; a rule that is held by none any more is left. */
1867
+ function deleteCssRule(rule) {
1868
+ const parent = rule.parentStyleSheet;
1869
+ if (parent) parent.deleteRule(Array.prototype.indexOf.call(parent.cssRules, rule));
1870
+ }
1871
+ /**
1872
+ * A sheet in the style element marked `data-style="<key>"` of the document of `container`, which it
1873
+ * creates in `container` when that document has none. It keeps the browser's object of each rule it
1874
+ * inserts, and removes a rule by finding where that object is at the time, so rules that others insert
1875
+ * into or delete from the element do not confuse it. Its `document` is that document: a cache over it
1876
+ * reads that one (an iframe's, for a container in the iframe).
1877
+ */
819
1878
  function createDomSheet(key, container = document.head) {
820
- let element = document.querySelector(`style[data-style="${key}"]`);
1879
+ const owner = container.ownerDocument;
1880
+ let element = owner.querySelector(`style[data-style="${key}"]`);
821
1881
  if (!element) {
822
- element = document.createElement("style");
1882
+ element = owner.createElement("style");
823
1883
  element.dataset.style = key;
824
1884
  container.appendChild(element);
825
1885
  }
826
1886
  const sheet = element.sheet;
827
1887
  const rules = [];
1888
+ const objects = [];
828
1889
  return {
829
1890
  rules,
1891
+ document: owner,
830
1892
  insert(rule) {
831
1893
  try {
832
- sheet.insertRule(rule, sheet.cssRules.length);
1894
+ const index = sheet.insertRule(rule, sheet.cssRules.length);
1895
+ objects.push(sheet.cssRules[index]);
833
1896
  rules.push(rule);
834
1897
  } catch {}
1898
+ },
1899
+ remove(index) {
1900
+ rules.splice(index, 1);
1901
+ deleteCssRule(objects.splice(index, 1)[0]);
835
1902
  }
836
1903
  };
837
1904
  }
838
- /** The selector of the style elements that hold engine rules: the cache's own, and the ones React hoists for the same prefix. */
1905
+ /**
1906
+ * The selector of the style elements that hold engine rules: the cache's own, the ones React hoists for
1907
+ * the same prefix, and the `data-umber="<prefix> <ids>"` and `data-umber="<prefix>-global <ids>"` elements
1908
+ * of `@umber-style/server` and of an app's own registry.
1909
+ */
839
1910
  function createStyleSelector(prefix) {
840
- return `style[data-style="${prefix}"], style[data-precedence="${prefix}"]`;
1911
+ return `style[data-style="${prefix}"], style[data-precedence="${prefix}"], style[data-umber~="${prefix}"], style[data-umber~="${prefix}-global"]`;
841
1912
  }
842
- /** The stamp of the options that the server wrote: on a style element, or on the `<meta>` that a server component renders. */
843
- function readServerStamp(prefix) {
844
- const element = document.querySelector(`style[data-style="${prefix}"][data-options], meta[name="${prefix}-options"]`);
1913
+ /** The stamp of the options that the server wrote in `page`: on a style element, or on the `<meta>` that a server component renders. */
1914
+ function readServerStamp(page, prefix) {
1915
+ const element = page.querySelector(`style[data-style="${prefix}"][data-options], meta[name="${prefix}-options"]`);
845
1916
  return element?.dataset.options ?? element?.getAttribute("content") ?? void 0;
846
1917
  }
847
1918
  /** The class names in `value`, a class string or a sheet entry. */
@@ -861,10 +1932,10 @@ function compareCodeUnits(first, second) {
861
1932
  return first < second ? -1 : 1;
862
1933
  }
863
1934
  /** Adds to `names` every variable that the theme values of `themeIds` bring in for a name already in it. */
864
- function addThemeReferences(names, themeIds, themes) {
1935
+ function addThemeReferences(names, themeIds, readDeclarations) {
865
1936
  const queue = [...names];
866
1937
  for (const queued of queue) for (const id of themeIds) {
867
- const value = themes.get(id)?.declarations[queued];
1938
+ const value = readDeclarations(id)?.[queued];
868
1939
  if (value === void 0) continue;
869
1940
  for (const name of scanVariables(value, VARIABLE_START)) {
870
1941
  if (!names.has(name)) queue.push(name);
@@ -874,9 +1945,10 @@ function addThemeReferences(names, themeIds, themes) {
874
1945
  }
875
1946
  /**
876
1947
  * Splits `values` into the styles to merge (the style of an entry a cache made, registered classes
877
- * resolved back) and the class names to pass through. `sole` is the entry when the one style is its own.
1948
+ * resolved back) and the class names to pass through. `sole` is the entry when the one style is its own;
1949
+ * an entry of another cache is first made this cache's own with `adopt`.
878
1950
  */
879
- function sortClassValues(values, registered) {
1951
+ function sortClassValues(values, registered, adopt) {
880
1952
  const styles = [];
881
1953
  const rawClasses = [];
882
1954
  let entry;
@@ -886,7 +1958,7 @@ function sortClassValues(values, registered) {
886
1958
  styles.push(value);
887
1959
  continue;
888
1960
  }
889
- const source = typeof value === "string" ? void 0 : readEntrySource(value);
1961
+ const source = typeof value === "string" ? void 0 : readEntrySource(adopt(value));
890
1962
  if (source) {
891
1963
  styles.push(source.style);
892
1964
  entry = source;
@@ -902,7 +1974,7 @@ function sortClassValues(values, registered) {
902
1974
  }
903
1975
  /** Makes a cache: it turns styles into classes and inserts each class's rules once. */
904
1976
  function createCache(options = {}) {
905
- const { prefix = "css", suffix = "", hasLabels = true, hasLayers = true, hasPruning = true, hasColorFallbacks = true, hasScope = true, hasBaseClass = true } = options;
1977
+ const { prefix = "css", suffix = "", hasLabels = true, hasLayers = true, hasPruning = true, hasColorFallbacks = true, hasValueRepair = false, hasScope = true, hasBaseClass = true } = options;
906
1978
  if (!PREFIX_PATTERN.test(prefix)) throw new Error(`Invalid cache prefix "${prefix}": use lowercase letters, digits and hyphens.`);
907
1979
  const fingerprint = createFingerprint({
908
1980
  prefix,
@@ -913,22 +1985,23 @@ function createCache(options = {}) {
913
1985
  hasBaseClass,
914
1986
  hasScope,
915
1987
  hasColorFallbacks,
1988
+ hasValueRepair,
916
1989
  tokens: options.tokenSignature ?? ""
917
1990
  });
918
- const hasDocument = typeof document !== "undefined";
919
- if (hasDocument) {
920
- const stamp = readServerStamp(prefix);
1991
+ const page = options.sheet?.document ?? (typeof document === "undefined" ? void 0 : document);
1992
+ if (page) {
1993
+ const stamp = readServerStamp(page, prefix);
921
1994
  const difference = stamp === void 0 ? "" : describeFingerprintDifferences(stamp, fingerprint);
922
1995
  if (difference !== "") throw new Error(difference);
923
1996
  }
924
- const { hasDevChecks = hasDocument && isDevelopment() } = options;
925
- const checkLater = hasDevChecks ? createDevChecker(prefix) : void 0;
1997
+ const { hasDevChecks = page !== void 0 && isDevelopment() } = options;
1998
+ const checkLater = hasDevChecks ? createDevChecker(prefix, void 0, page) : void 0;
926
1999
  const insertedIds = /* @__PURE__ */ new Set();
927
2000
  const used = /* @__PURE__ */ new Set();
928
2001
  const pinned = /* @__PURE__ */ new Set();
929
2002
  const pageThemes = /* @__PURE__ */ new Map();
930
2003
  const afters = /* @__PURE__ */ new Map();
931
- const sheet = options.sheet ?? (typeof document === "undefined" ? createMemorySheet() : createDomSheet(prefix));
2004
+ const sheet = options.sheet ?? (page ? createDomSheet(prefix, page.head) : createMemorySheet());
932
2005
  const registered = /* @__PURE__ */ new Map();
933
2006
  const entries = /* @__PURE__ */ new Map();
934
2007
  const scoping = {
@@ -942,35 +2015,69 @@ function createCache(options = {}) {
942
2015
  const layerOrder = hasLayers ? `@layer ${layerNames};` : "";
943
2016
  const layerOrderId = `${prefix}-layers`;
944
2017
  const wrapInLayer = (rules, layer) => hasLayers && layer ? rules.map((rule) => `@layer ${prefix}-${layer}{${rule}}`) : rules;
945
- const insertLayered = (layered) => {
946
- if (hasLayers && layered.length > 0 && !insertedIds.has(layerOrderId)) {
2018
+ const { onInsert } = options;
2019
+ const insertLayerOrder = () => {
2020
+ if (hasLayers && !insertedIds.has(layerOrderId)) {
947
2021
  insertedIds.add(layerOrderId);
948
2022
  sheet.insert(layerOrder);
2023
+ onInsert?.(layerOrderId, layerOrder);
2024
+ }
2025
+ };
2026
+ /** Writes `layered` after the layer order statement, and reports them under `name`; with `indexes`, the place of each rule that the sheet took is added to it. */
2027
+ const insertLayered = (name, layered, indexes) => {
2028
+ if (layered.length === 0) return;
2029
+ insertLayerOrder();
2030
+ if (indexes) for (const rule of layered) {
2031
+ const index = sheet.rules.length;
2032
+ sheet.insert(rule);
2033
+ if (sheet.rules.length > index) indexes.push(index);
949
2034
  }
950
- for (const rule of layered) sheet.insert(rule);
951
- if (layered.length > 0) checkLater?.();
2035
+ else for (const rule of layered) sheet.insert(rule);
2036
+ onInsert?.(name, layered.join(""));
2037
+ checkLater?.(layered);
952
2038
  };
953
2039
  const themes = /* @__PURE__ */ new Map();
2040
+ const roots = /* @__PURE__ */ new Map();
2041
+ let root;
2042
+ let pageRoots = [];
2043
+ /** The rule of a root theme with the variables `names`, and its color-scheme; none when that is nothing. */
2044
+ const createRootRules = (theme, names) => {
2045
+ const body = toDeclarationText([...names].map((name) => [name, theme.declarations[name]])) + theme.schemeText;
2046
+ return body === "" ? [] : [createThemeRule(prefix, hasLayers, ROOT_SELECTOR, body)];
2047
+ };
2048
+ /** Writes the rule of the root theme anew with every variable written so far, after removing the one it had where the sheet can; a sheet that cannot keeps it, and the new rule, later, wins. */
2049
+ const writeRoot = (entry) => {
2050
+ const rules = createRootRules(roots.get(entry.id), entry.written);
2051
+ insertedRules.set(entry.id, rules);
2052
+ const { remove } = sheet;
2053
+ if (entry.index !== void 0 && remove) removeAt(remove, entry.index);
2054
+ entry.index = void 0;
2055
+ const before = sheet.rules.length;
2056
+ insertLayered(`${entry.id}-${hashString(rules.join(""))}`, rules);
2057
+ if (sheet.rules.length > before) entry.index = sheet.rules.length - 1;
2058
+ };
954
2059
  /** Writes `names` for a theme class: a rule of its own, or in place of the rule it has when the sheet can replace. */
955
2060
  const writeTheme = (className, entry, names) => {
956
2061
  const added = toDeclarationText(names.map((name) => [name, entry.declarations[name]]));
957
2062
  const ownScheme = entry.isSent ? "" : entry.schemeText;
958
2063
  const first = entry.isStarted ? "" : ownScheme;
959
2064
  if (added + first === "") return;
2065
+ const part = wrapInLayer([`.${className}{${added + first}}`], "theme");
2066
+ const reported = entry.isStarted ? `${className}-${hashString(added)}` : className;
960
2067
  entry.isStarted = true;
961
2068
  for (const name of names) entry.written.add(name);
962
2069
  entry.variables += added;
963
2070
  const { index } = entry;
964
- const body = index === void 0 ? added + first : entry.variables + ownScheme;
965
- const rules = wrapInLayer([`.${className}{${body}}`], "theme");
966
2071
  if (sheet.replace && index !== void 0) {
2072
+ const rules = wrapInLayer([`.${className}{${entry.variables + ownScheme}}`], "theme");
967
2073
  sheet.replace(index, rules[0]);
968
2074
  entry.rules = rules;
2075
+ onInsert?.(reported, part[0]);
969
2076
  } else {
970
2077
  const before = sheet.rules.length;
971
- insertLayered(rules);
2078
+ insertLayered(reported, part);
972
2079
  if (sheet.replace && sheet.rules.length > before) entry.index = sheet.rules.length - 1;
973
- entry.rules = [...entry.rules, ...rules];
2080
+ entry.rules = [...entry.rules, ...part];
974
2081
  }
975
2082
  insertedRules.set(className, entry.rules);
976
2083
  };
@@ -984,6 +2091,34 @@ function createCache(options = {}) {
984
2091
  propertyRules = rules;
985
2092
  for (const name of Object.keys(rules)) if (!hasPruning || used.has(name)) writeProperty(name);
986
2093
  };
2094
+ const animations = /* @__PURE__ */ new Map();
2095
+ let readKeyframesTheme = () => {
2096
+ throw new Error("keyframes(): these steps are a function of the theme, and this cache has no theme: make the cache through an engine.");
2097
+ };
2098
+ /** The `@keyframes` rule of `name`: the one written, else made now. */
2099
+ const readKeyframesRule = (name) => insertedRules.get(name)?.[0] ?? createKeyframesRule(name, readKeyframesTheme, hasColorFallbacks, hasValueRepair);
2100
+ /** Writes the `@keyframes` rule of the registered `name` once, outside every layer, unless the page has it. */
2101
+ const writeKeyframes = (name) => {
2102
+ const id = `@keyframes:${name}`;
2103
+ if (insertedIds.has(id)) return;
2104
+ const rule = readKeyframesRule(name);
2105
+ insertOnce(id, [rule]);
2106
+ insertedRules.set(name, [rule]);
2107
+ };
2108
+ /** Inserts the rules of a class once, after the `@keyframes` rules of the animations they use; with `indexes`, the places of its rules are added to it. */
2109
+ const insertClass = (className, rules, layer, indexes) => {
2110
+ if (insertedIds.has(className)) return;
2111
+ const names = findAnimationNames(rules);
2112
+ if (names.length > 0) {
2113
+ animations.set(className, names);
2114
+ names.forEach(writeKeyframes);
2115
+ }
2116
+ insertOnce(className, rules, layer, indexes);
2117
+ };
2118
+ const insertKeyframes = (name) => {
2119
+ if (!isKeyframesName(name)) throw new TypeError(`insertKeyframes(): "${name}" is not a name that keyframes() returned, so there is no rule to write.`);
2120
+ writeKeyframes(name);
2121
+ };
987
2122
  const markUsed = (names) => {
988
2123
  if (!hasPruning) return;
989
2124
  const queue = [...names];
@@ -992,7 +2127,7 @@ function createCache(options = {}) {
992
2127
  if (used.has(name)) continue;
993
2128
  used.add(name);
994
2129
  fresh.push(name);
995
- for (const { declarations } of themes.values()) {
2130
+ for (const { declarations } of [...themes.values(), ...roots.values()]) {
996
2131
  const value = declarations[name];
997
2132
  if (value !== void 0) queue.push(...scanVariables(value, VARIABLE_START));
998
2133
  }
@@ -1000,6 +2135,39 @@ function createCache(options = {}) {
1000
2135
  if (fresh.length === 0) return;
1001
2136
  fresh.forEach(writeProperty);
1002
2137
  for (const [className, entry] of themes) writeTheme(className, entry, fresh.filter((name) => entry.declarations[name] !== void 0 && !entry.written.has(name)));
2138
+ if (root === void 0) return;
2139
+ const { declarations } = roots.get(root.id);
2140
+ const added = fresh.filter((name) => declarations[name] !== void 0);
2141
+ if (added.length === 0) return;
2142
+ for (const name of added) root.written.add(name);
2143
+ writeRoot(root);
2144
+ };
2145
+ const insertRoot = (id, declarations, colorScheme) => {
2146
+ if (!roots.has(id)) {
2147
+ roots.set(id, {
2148
+ declarations,
2149
+ schemeText: colorScheme ? `color-scheme:${colorScheme};` : ""
2150
+ });
2151
+ themeNames.set(id, Object.keys(declarations));
2152
+ }
2153
+ if (root?.id === id) return;
2154
+ for (const rule of pageRoots) if (rule) deleteCssRule(rule);
2155
+ pageRoots = [];
2156
+ if (root) {
2157
+ insertedIds.delete(root.id);
2158
+ insertedRules.delete(root.id);
2159
+ }
2160
+ insertedIds.add(id);
2161
+ const names = Object.keys(declarations);
2162
+ const isUsed = (name) => !hasPruning || used.has(name);
2163
+ const entry = {
2164
+ id,
2165
+ written: new Set(names.filter(isUsed)),
2166
+ index: root?.index
2167
+ };
2168
+ root = entry;
2169
+ writeRoot(entry);
2170
+ markUsed([...entry.written].flatMap((name) => scanVariables(declarations[name], VARIABLE_START)));
1003
2171
  };
1004
2172
  const insertTheme = (className, declarations, colorScheme) => {
1005
2173
  const schemeText = colorScheme ? `color-scheme:${colorScheme};` : "";
@@ -1029,21 +2197,102 @@ function createCache(options = {}) {
1029
2197
  markUsed(names.filter((name) => used.has(name)).flatMap((name) => scanVariables(declarations[name], VARIABLE_START)));
1030
2198
  writeTheme(className, entry, names.filter((name) => used.has(name) && !entry.written.has(name)));
1031
2199
  };
1032
- function insertOnce(id, rules, layer) {
2200
+ function insertOnce(id, rules, layer, indexes) {
1033
2201
  if (insertedIds.has(id)) return false;
1034
2202
  insertedIds.add(id);
1035
2203
  const layered = wrapInLayer(rules, layer);
1036
2204
  insertedRules.set(id, layered);
1037
- insertLayered(layered);
2205
+ insertLayered(id, layered, indexes);
1038
2206
  if (hasPruning) markUsed(rules.flatMap((rule) => scanVariables(rule, VARIABLE_START)));
1039
2207
  return true;
1040
2208
  }
2209
+ const globals = /* @__PURE__ */ new Map();
2210
+ const pageGlobals = /* @__PURE__ */ new Map();
2211
+ let readArrived = () => void 0;
2212
+ const held = /* @__PURE__ */ new Map();
2213
+ const releasing = /* @__PURE__ */ new Set();
2214
+ const compileGlobal = (styles) => {
2215
+ const flat = compileGlobalRules(styles, hasColorFallbacks, scoping, hasValueRepair);
2216
+ const rules = wrapInLayer(flat, "global");
2217
+ return {
2218
+ id: `${prefix}-global-${hashString(rules.join(""))}`,
2219
+ rules,
2220
+ animations: findAnimationNames(flat)
2221
+ };
2222
+ };
2223
+ /** Whether the page has every one of `rules`, not taken by another set. */
2224
+ const hasPageRules = (rules) => rules.every((rule) => pageGlobals.get(rule)?.length);
2225
+ /** The rules of the page for `rules`, taken so that no other set takes them, when the page has every one of them; else undefined. */
2226
+ const takePageRules = (rules) => {
2227
+ if (!hasPageRules(rules)) return void 0;
2228
+ return rules.map((rule) => pageGlobals.get(rule).shift());
2229
+ };
2230
+ /** Writes the rules of `global`, or takes them over from the page, after the `@keyframes` rules they use. */
2231
+ const writeGlobal = ({ id, rules, animations: names }) => {
2232
+ names.forEach(writeKeyframes);
2233
+ if (!hasPageRules(rules)) readArrived();
2234
+ const pageRules = takePageRules(rules);
2235
+ const indexes = [];
2236
+ if (pageRules === void 0) {
2237
+ insertLayerOrder();
2238
+ for (const rule of rules) {
2239
+ const index = sheet.rules.length;
2240
+ sheet.insert(rule);
2241
+ if (sheet.rules.length > index) indexes.push(index);
2242
+ }
2243
+ onInsert?.(id, rules.join(""));
2244
+ checkLater?.(rules);
2245
+ }
2246
+ markUsed(rules.flatMap((rule) => scanVariables(rule, VARIABLE_START)));
2247
+ const entry = {
2248
+ count: 0,
2249
+ appCount: 0,
2250
+ rules,
2251
+ animations: names,
2252
+ indexes,
2253
+ pageRules
2254
+ };
2255
+ globals.set(id, entry);
2256
+ return entry;
2257
+ };
2258
+ /** Removes the rule at `index` of the sheet, and moves down every place the cache keeps that is after it. */
2259
+ const removeAt = (remove, index) => {
2260
+ remove(index);
2261
+ for (const entry of [...globals.values(), ...held.values()]) entry.indexes = entry.indexes.map((at) => at > index ? at - 1 : at);
2262
+ for (const entry of themes.values()) if (entry.index !== void 0 && entry.index > index) entry.index--;
2263
+ if (root?.index !== void 0 && root.index > index) root.index--;
2264
+ };
2265
+ /** Removes the rules of a set that nothing holds any more, unless they cannot be removed: then they stay, and count as written. */
2266
+ const removeGlobal = (id, entry) => {
2267
+ const { pageRules, indexes } = entry;
2268
+ const { remove } = sheet;
2269
+ if (pageRules ? pageRules.includes(void 0) : remove === void 0) return;
2270
+ globals.delete(id);
2271
+ pageRules?.forEach((rule) => deleteCssRule(rule));
2272
+ for (let at = indexes.length - 1; at >= 0; at--) removeAt(remove, indexes[at]);
2273
+ };
2274
+ const insertGlobal = (global, { isRendered = false } = {}) => {
2275
+ const entry = globals.get(global.id) ?? writeGlobal(global);
2276
+ const forApp = isRendered ? 0 : 1;
2277
+ entry.count++;
2278
+ entry.appCount += forApp;
2279
+ let isReleased = false;
2280
+ return () => {
2281
+ if (isReleased) return;
2282
+ isReleased = true;
2283
+ entry.count--;
2284
+ entry.appCount -= forApp;
2285
+ if (entry.count === 0) removeGlobal(global.id, entry);
2286
+ };
2287
+ };
1041
2288
  const getFullRules = (id) => {
1042
2289
  const entry = themes.get(id);
1043
2290
  const properties = (themeNames.get(id) ?? []).flatMap((name) => propertyRules[name] ?? []);
2291
+ const rootTheme = roots.get(id);
2292
+ if (rootTheme) return [...properties, ...createRootRules(rootTheme, Object.keys(rootTheme.declarations))];
1044
2293
  if (entry === void 0) return [...properties, ...insertedRules.get(id) ?? []];
1045
2294
  const body = toDeclarationText(Object.entries(entry.declarations)) + entry.schemeText;
1046
- return [...properties, ...body ? wrapInLayer([`.${id}{${body}}`], "theme") : []];
2295
+ return [...properties, ...body ? [createThemeRule(prefix, hasLayers, `.${id}`, body)] : []];
1047
2296
  };
1048
2297
  /** The name of a class: the layer and `after` are part of the hash, so that the same styles in two layers, or after two classes, are two classes. */
1049
2298
  const nameClass = (layer, merged, rules, after) => {
@@ -1055,24 +2304,132 @@ function createCache(options = {}) {
1055
2304
  hash
1056
2305
  ].filter(Boolean).join("-") + suffix;
1057
2306
  };
2307
+ /** The merged style of `styles` (the label last) and the name of its class; undefined when it has no rule. */
2308
+ const prepareClass = (layer, label, after, styles) => {
2309
+ if (styles.length === 0) return void 0;
2310
+ const merged = mergeStyles(label ? [...styles, { label }] : styles);
2311
+ const rules = compileRules("&", merged, hasColorFallbacks, scoping, hasValueRepair);
2312
+ if (rules.length === 0) return void 0;
2313
+ return {
2314
+ merged,
2315
+ className: nameClass(layer, merged, rules, after)
2316
+ };
2317
+ };
2318
+ /** The rules of the class `className` with the style `merged`. */
2319
+ const compileClass = (className, merged) => compileRules(`.${className}`, merged, hasColorFallbacks, scoping, hasValueRepair);
1058
2320
  const cssWith = (options, ...values) => {
1059
2321
  const { layer = "components", label, after = "" } = options;
1060
- const { styles, rawClasses, sole } = sortClassValues(values, registered);
2322
+ const { styles, rawClasses, sole } = sortClassValues(values, registered, adoptEntry);
1061
2323
  if (sole && after === "") return [...rawClasses, sole.use(layer)].filter(Boolean).join(" ");
1062
- if (styles.length === 0) return rawClasses.join(" ");
1063
- const merged = mergeStyles(label ? [...styles, { label }] : styles);
1064
- const rules = compileRules("&", merged, hasColorFallbacks, scoping);
1065
- if (rules.length === 0) return rawClasses.join(" ");
1066
- const className = nameClass(layer, merged, rules, after);
2324
+ const prepared = prepareClass(layer, label, after, styles);
2325
+ if (prepared === void 0) return rawClasses.join(" ");
2326
+ const { merged, className } = prepared;
2327
+ if (held.size > 0) held.delete(className);
1067
2328
  registered.set(className, merged);
1068
2329
  if (after !== "") afters.set(className, after);
1069
- insertOnce(className, compileRules(`.${className}`, merged, hasColorFallbacks, scoping), layer);
2330
+ insertClass(className, compileClass(className, merged), layer);
1070
2331
  return [...rawClasses, className].join(" ");
1071
2332
  };
2333
+ /**
2334
+ * Registers and writes the held class `className`, or takes it over from the page when the page has
2335
+ * it. A class written by this cache is removed after the delay unless it is held by then.
2336
+ */
2337
+ const writeHeld = (className, merged, layer) => {
2338
+ const rules = compileClass(className, merged);
2339
+ const isPage = insertedIds.has(className);
2340
+ const entry = {
2341
+ count: 0,
2342
+ indexes: [],
2343
+ pageRules: isPage ? rules.length : void 0,
2344
+ hold: () => {
2345
+ let holder = held.get(className);
2346
+ if (holder === void 0) {
2347
+ if (registered.has(className)) return () => void 0;
2348
+ holder = writeHeld(className, merged, layer);
2349
+ }
2350
+ const current = holder;
2351
+ current.count++;
2352
+ let isReleased = false;
2353
+ return () => {
2354
+ if (isReleased) return;
2355
+ isReleased = true;
2356
+ current.count--;
2357
+ if (current.count === 0) scheduleRelease(className);
2358
+ };
2359
+ }
2360
+ };
2361
+ held.set(className, entry);
2362
+ registered.set(className, merged);
2363
+ insertClass(className, rules, layer, entry.indexes);
2364
+ if (!isPage) scheduleRelease(className);
2365
+ return entry;
2366
+ };
2367
+ /** The rules of the page (the style elements of the engine) that name the class `className`, when there are `count` of them; else undefined. */
2368
+ const findPageRules = (className, count) => {
2369
+ const escaped = className.replaceAll(/[^\w-]/g, String.raw`\$&`);
2370
+ const pattern = new RegExp(String.raw`\.${escaped}(?![\w-])`);
2371
+ const found = [];
2372
+ for (const element of page.querySelectorAll(createStyleSelector(prefix))) for (const rule of element.sheet?.cssRules ?? []) if (pattern.test(rule.cssText)) found.push(rule);
2373
+ return found.length === count ? found : void 0;
2374
+ };
2375
+ /** Removes a held class that nothing holds: its rules from the sheet, or from the page when they are the page's and can all be found; then the class is forgotten. Rules that cannot be found stay, and the class is permanent. */
2376
+ const removeHeld = (className, entry) => {
2377
+ held.delete(className);
2378
+ if (entry.pageRules === void 0) for (let at = entry.indexes.length - 1; at >= 0; at--) removeAt(sheet.remove, entry.indexes[at]);
2379
+ else {
2380
+ const rules = findPageRules(className, entry.pageRules);
2381
+ if (rules === void 0) return;
2382
+ rules.forEach(deleteCssRule);
2383
+ }
2384
+ registered.delete(className);
2385
+ insertedIds.delete(className);
2386
+ insertedRules.delete(className);
2387
+ animations.delete(className);
2388
+ };
2389
+ /** Removes each held class that waits for its removal and that nothing holds any more. */
2390
+ const flushReleases = () => {
2391
+ for (const className of releasing) {
2392
+ const entry = held.get(className);
2393
+ if (entry?.count === 0) removeHeld(className, entry);
2394
+ }
2395
+ releasing.clear();
2396
+ };
2397
+ /** Marks `className` for removal after the delay: one macrotask, so that a class let go and held again in the same task (a commit, a value that comes straight back) stays. */
2398
+ const scheduleRelease = (className) => {
2399
+ releasing.add(className);
2400
+ if (releasing.size === 1) setTimeout(flushReleases, 0);
2401
+ };
2402
+ const cssHeld = (options, ...values) => {
2403
+ const { layer = "components", label } = options;
2404
+ const { styles, rawClasses, sole } = sortClassValues(values, registered, adoptEntry);
2405
+ if (sole || sheet.remove === void 0) return {
2406
+ className: cssWith(options, ...values),
2407
+ hold: void 0
2408
+ };
2409
+ const prepared = prepareClass(layer, label, "", styles);
2410
+ if (prepared === void 0) return {
2411
+ className: rawClasses.join(" "),
2412
+ hold: void 0
2413
+ };
2414
+ const { merged, className: name } = prepared;
2415
+ const className = [...rawClasses, name].join(" ");
2416
+ let entry = held.get(name);
2417
+ if (entry === void 0) {
2418
+ if (registered.has(name)) return {
2419
+ className,
2420
+ hold: void 0
2421
+ };
2422
+ entry = writeHeld(name, merged, layer);
2423
+ }
2424
+ return {
2425
+ className,
2426
+ hold: entry.hold
2427
+ };
2428
+ };
1072
2429
  const cssIn = (layer, ...values) => cssWith({ layer }, ...values);
1073
2430
  const createEntry = (style) => {
1074
2431
  const merged = mergeStyles([style]);
1075
- const rules = compileRules("&", merged, hasColorFallbacks, scoping);
2432
+ const rules = compileRules("&", merged, hasColorFallbacks, scoping, hasValueRepair);
1076
2433
  const names = {};
1077
2434
  const nameFor = (role) => {
1078
2435
  names[role] ??= rules.length === 0 ? "" : nameClass(role, merged, rules, "");
@@ -1080,11 +2437,13 @@ function createCache(options = {}) {
1080
2437
  };
1081
2438
  const source = {
1082
2439
  style: merged,
2440
+ cache: self,
1083
2441
  use(role) {
1084
2442
  const name = nameFor(role);
2443
+ if (held.size > 0) held.delete(name);
1085
2444
  if (name !== "" && !registered.has(name)) {
1086
2445
  registered.set(name, merged);
1087
- insertOnce(name, compileRules(`.${name}`, merged, hasColorFallbacks, scoping), role);
2446
+ insertClass(name, compileClass(name, merged), role);
1088
2447
  }
1089
2448
  return name;
1090
2449
  }
@@ -1093,10 +2452,22 @@ function createCache(options = {}) {
1093
2452
  entries.set(nameFor("components"), entry);
1094
2453
  return entry;
1095
2454
  };
1096
- /** Takes in what rules on the page say: the classes, the layer order, the `@property` rules and the themes that are written, and the variables the rules use. */
2455
+ const adopted = /* @__PURE__ */ new WeakMap();
2456
+ const adoptEntry = (entry) => {
2457
+ const source = readEntrySource(entry);
2458
+ if (source === void 0 || source.cache === self) return entry;
2459
+ let own = adopted.get(source);
2460
+ if (own === void 0) {
2461
+ own = createEntry(source.style);
2462
+ adopted.set(source, own);
2463
+ }
2464
+ return own;
2465
+ };
2466
+ /** Takes in what rules on the page say: the classes, the layer order, the `@property` and `@keyframes` rules and the themes that are written, and the variables the rules use. */
1097
2467
  const absorb = (found) => {
1098
2468
  if (found.hasLayerOrder) insertedIds.add(layerOrderId);
1099
2469
  for (const name of found.classes) insertedIds.add(name);
2470
+ for (const name of found.keyframes) insertedIds.add(`@keyframes:${name}`);
1100
2471
  for (const [name, rule] of found.properties) insertedIds.add(`@property:${name}:${hashString(rule)}`);
1101
2472
  for (const [className, names] of found.themes) {
1102
2473
  insertedIds.add(className);
@@ -1110,19 +2481,35 @@ function createCache(options = {}) {
1110
2481
  }
1111
2482
  markUsed(found.variables);
1112
2483
  };
1113
- if (hasDocument) {
2484
+ if (page) {
1114
2485
  const selector = createStyleSelector(prefix);
1115
2486
  const scanned = /* @__PURE__ */ new WeakSet();
1116
2487
  const scan = (element) => {
1117
- if (scanned.has(element)) return;
2488
+ if (scanned.has(element) || element.getAttribute("media") === "not all") return;
1118
2489
  scanned.add(element);
1119
- absorb(scanStyleText(prefix, element.textContent));
2490
+ const found = scanStyleText(prefix, element.textContent);
2491
+ absorb(found);
2492
+ const list = element.sheet?.cssRules;
2493
+ const objects = list?.length === found.ruleCount ? list : void 0;
2494
+ for (const [index, text] of found.globals) {
2495
+ const known = pageGlobals.get(text) ?? [];
2496
+ known.push(objects?.[index]);
2497
+ pageGlobals.set(text, known);
2498
+ }
2499
+ for (const index of found.roots) pageRoots.push(objects?.[index]);
2500
+ };
2501
+ for (const element of page.querySelectorAll(selector)) scan(element);
2502
+ const readRecords = (records) => {
2503
+ for (const { addedNodes } of records) for (const node of addedNodes) if (node === page.body) observer.observe(node, { childList: true });
2504
+ else if (node.nodeType === 1 && node.matches(selector)) scan(node);
1120
2505
  };
1121
- for (const element of document.querySelectorAll(selector)) scan(element);
1122
- new MutationObserver((records) => {
1123
- for (const { addedNodes } of records) for (const node of addedNodes) if (node instanceof Element && node.matches(selector)) scan(node);
2506
+ const observer = new MutationObserver((records) => {
2507
+ readRecords(records);
1124
2508
  checkLater?.();
1125
- }).observe(document.head, { childList: true });
2509
+ });
2510
+ observer.observe(page.head, { childList: true });
2511
+ observer.observe(page.body ?? page.documentElement, { childList: true });
2512
+ readArrived = () => readRecords(observer.takeRecords());
1126
2513
  checkLater?.();
1127
2514
  }
1128
2515
  /** What orders the classes of a page: a props class is right after its base class (its `after`), the rest by name. */
@@ -1131,11 +2518,15 @@ function createCache(options = {}) {
1131
2518
  const readNames = (id) => themeNames.get(id);
1132
2519
  /** The rules that the cache wrote under `id`, a class or a theme class it made. */
1133
2520
  const readRules = (id) => insertedRules.get(id);
1134
- /** The variables a page needs declared: those its rules refer to, those marked from outside, and what the values of the themes in play refer to. */
1135
- const collectPageVariables = (classIds, themeIds) => {
2521
+ /** The variables a page needs declared: those its rules (of classes, and `@keyframes` and global rules) refer to, those marked from outside, and what the values of the themes in play refer to. */
2522
+ const collectPageVariables = (classIds, themeIds, otherRules) => {
1136
2523
  const names = new Set(pinned);
1137
- for (const id of classIds) for (const rule of readRules(id)) for (const name of scanVariables(rule, VARIABLE_START)) names.add(name);
1138
- addThemeReferences(names, themeIds, themes);
2524
+ const addVariables = (rule) => {
2525
+ for (const name of scanVariables(rule, VARIABLE_START)) names.add(name);
2526
+ };
2527
+ for (const id of classIds) readRules(id).forEach(addVariables);
2528
+ otherRules.forEach(addVariables);
2529
+ addThemeReferences(names, themeIds, (id) => themes.get(id)?.declarations ?? roots.get(id)?.declarations);
1139
2530
  return names;
1140
2531
  };
1141
2532
  /** The rule of a theme class for a page: with pruning, only the variables in `names`, and its color-scheme. */
@@ -1145,31 +2536,62 @@ function createCache(options = {}) {
1145
2536
  const body = toDeclarationText(Object.keys(entry.declarations).filter((name) => names.has(name)).map((name) => [name, entry.declarations[name]])) + entry.schemeText;
1146
2537
  return body === "" ? [] : wrapInLayer([`.${id}{${body}}`], "theme");
1147
2538
  };
1148
- const extractPage = (classNames, pageOptions = {}) => {
1149
- const { themes: offered = [], carried = /* @__PURE__ */ new Set() } = pageOptions;
2539
+ const extractPageParts = (classNames, pageOptions = {}) => {
2540
+ const { themes: offered = [], animations: named = [], carried = /* @__PURE__ */ new Set(), rendered = /* @__PURE__ */ new Set() } = pageOptions;
1150
2541
  const wanted = /* @__PURE__ */ new Set([...classNames, ...offered]);
1151
2542
  const themeIds = [...wanted].filter((name) => themeNames.has(name)).sort(compareCodeUnits);
1152
2543
  const classIds = [...wanted].filter((name) => name.startsWith(`${prefix}-`) && !themeNames.has(name)).filter((name) => insertedRules.has(name)).sort((first, second) => sortKey(first) < sortKey(second) ? -1 : 1);
1153
- const names = hasPruning ? collectPageVariables(classIds, themeIds) : /* @__PURE__ */ new Set();
1154
- const covered = new Set(themeIds.filter((id) => carried.has(id)).flatMap(readNames));
1155
- const declared = hasPruning ? names : themeIds.flatMap(readNames);
2544
+ const held = [...globals].filter(([id, entry]) => entry.appCount > 0 || rendered.has(id) || carried.has(id));
2545
+ const pageAnimations = [...classIds.flatMap((id) => animations.get(id) ?? []), ...held.flatMap(([, entry]) => entry.animations)];
2546
+ const keyframesRules = [.../* @__PURE__ */ new Set([...pageAnimations, ...named])].filter((name) => isKeyframesName(name) && !carried.has(name)).sort(compareCodeUnits).map(readKeyframesRule);
2547
+ const allGlobalRules = held.flatMap(([, entry]) => entry.rules);
2548
+ const rootIds = root === void 0 ? [] : [root.id];
2549
+ const allThemeIds = [...rootIds, ...themeIds];
2550
+ const names = hasPruning ? collectPageVariables(classIds, allThemeIds, [...keyframesRules, ...allGlobalRules]) : /* @__PURE__ */ new Set();
2551
+ const covered = new Set(allThemeIds.filter((id) => carried.has(id)).flatMap(readNames));
2552
+ const declared = hasPruning ? names : allThemeIds.flatMap(readNames);
1156
2553
  const properties = [...new Set(declared)].filter((name) => propertyRules[name] !== void 0 && !covered.has(name)).sort(compareCodeUnits);
2554
+ const newRoots = rootIds.filter((id) => !carried.has(id));
1157
2555
  const newThemes = themeIds.filter((id) => !carried.has(id));
2556
+ const newGlobals = held.filter(([id]) => !carried.has(id));
1158
2557
  const newClasses = classIds.filter((id) => !carried.has(id));
1159
- const themeRules = newThemes.flatMap((id) => createPageThemeRules(id, names));
2558
+ const themeRules = [...newRoots.flatMap((id) => {
2559
+ const theme = roots.get(id);
2560
+ const all = Object.keys(theme.declarations);
2561
+ return createRootRules(theme, hasPruning ? all.filter((name) => names.has(name)) : all);
2562
+ }), ...newThemes.flatMap((id) => createPageThemeRules(id, names))];
2563
+ const globalRules = newGlobals.flatMap(([, entry]) => entry.rules);
1160
2564
  const classRules = newClasses.flatMap(readRules);
1161
- const hasLayered = themeRules.length + classRules.length > 0;
2565
+ const hasLayered = themeRules.length + globalRules.length + classRules.length > 0;
2566
+ return {
2567
+ global: {
2568
+ css: [
2569
+ hasLayers && hasLayered ? layerOrder : "",
2570
+ ...properties.map((name) => propertyRules[name]),
2571
+ ...keyframesRules,
2572
+ ...themeRules,
2573
+ ...globalRules
2574
+ ].join(""),
2575
+ ids: [
2576
+ ...newRoots,
2577
+ ...newThemes,
2578
+ ...newGlobals.map(([id]) => id)
2579
+ ]
2580
+ },
2581
+ classes: {
2582
+ css: classRules.join(""),
2583
+ ids: newClasses
2584
+ }
2585
+ };
2586
+ };
2587
+ const extractPage = (classNames, pageOptions) => {
2588
+ const { global, classes } = extractPageParts(classNames, pageOptions);
1162
2589
  return {
1163
- css: [
1164
- hasLayers && hasLayered ? layerOrder : "",
1165
- ...properties.map((name) => propertyRules[name]),
1166
- ...themeRules,
1167
- ...classRules
1168
- ].join(""),
1169
- ids: [...newThemes, ...newClasses]
2590
+ css: global.css + classes.css,
2591
+ ids: [...global.ids, ...classes.ids]
1170
2592
  };
1171
2593
  };
1172
- return {
2594
+ const self = {
1173
2595
  prefix,
1174
2596
  hasLayers,
1175
2597
  layerOrder,
@@ -1177,8 +2599,10 @@ function createCache(options = {}) {
1177
2599
  css: (...values) => cssIn("components", ...values),
1178
2600
  cssIn,
1179
2601
  cssWith,
2602
+ cssHeld,
1180
2603
  createEntry,
1181
2604
  findEntry: (className) => entries.get(className),
2605
+ adoptEntry,
1182
2606
  hasBaseClass,
1183
2607
  hasScope,
1184
2608
  hasPruning,
@@ -1189,142 +2613,32 @@ function createCache(options = {}) {
1189
2613
  markUsed(list);
1190
2614
  },
1191
2615
  insertTheme,
2616
+ insertRoot,
1192
2617
  registerProperties,
2618
+ setKeyframesTheme: (read) => {
2619
+ readKeyframesTheme = read;
2620
+ },
2621
+ insertKeyframes,
2622
+ getAnimations: (className) => animations.get(className) ?? [],
2623
+ compileGlobal,
2624
+ insertGlobal,
1193
2625
  insertOnce,
1194
2626
  getRules: (id) => insertedRules.get(id) ?? [],
1195
2627
  getFullRules,
1196
2628
  extract: () => ({
1197
2629
  css: sheet.rules.join(""),
1198
- ids: [...insertedIds, ...used]
2630
+ ids: [
2631
+ ...insertedIds,
2632
+ ...globals.keys(),
2633
+ ...used
2634
+ ]
1199
2635
  }),
1200
2636
  extractPage,
2637
+ extractPageParts,
1201
2638
  fingerprint
1202
2639
  };
1203
- }
1204
- // src/calc.ts
1205
- const LENGTH_PATTERN$1 = /^(-?(?:\d+(?:\.\d*)?|\.\d+))([a-z]+|%)$/i;
1206
- const CALC_PREFIX = "calc(";
1207
- /** `value` rounded so that float noise (0.1 * 3) does not reach the CSS; `-0` is `0`. */
1208
- function tidy(value) {
1209
- return Math.round(value * 1e6) / 1e6 + 0;
1210
- }
1211
- /** Throws unless `value` is a finite number; `what` names the argument in the message. */
1212
- function assertFinite(name, what, value) {
1213
- if (typeof value !== "number") throw new TypeError(`${name}(): ${what} must be a number, got ${typeof value}`);
1214
- if (!Number.isFinite(value)) throw new RangeError(`${name}(): ${what} must be finite, got ${value}`);
1215
- }
1216
- /** Throws unless `value` is a string or a finite number. */
1217
- function assertOperand(name, value) {
1218
- if (isAlphaColor(value)) throw new TypeError(`${name}(): an alpha() color is not a length or a number, so it cannot be an operand`);
1219
- if (typeof value !== "string") assertFinite(name, "a value", value);
1220
- }
1221
- /** The inside of `value` when the whole of it is one `calc(...)`, else undefined. */
1222
- function unwrapCalc(value) {
1223
- if (!value.startsWith(CALC_PREFIX) || !value.endsWith(")")) return void 0;
1224
- let depth = 0;
1225
- for (let index = 4; index < value.length; index += 1) {
1226
- if (value[index] === "(") depth += 1;
1227
- if (value[index] === ")") depth -= 1;
1228
- if (depth === 0 && index < value.length - 1) return void 0;
1229
- }
1230
- return value.slice(5, -1);
1231
- }
1232
- /** `operand` as a part of a calc expression: a number is a length in px, an inner calc gets parentheses. */
1233
- function toTerm(operand) {
1234
- if (typeof operand === "number") return `${tidy(operand)}px`;
1235
- const inner = unwrapCalc(operand);
1236
- return inner === void 0 ? operand : `(${inner})`;
1237
- }
1238
- /** `operand` as a literal length (a number is in px), or undefined when it is not one. */
1239
- function toLength(operand) {
1240
- if (typeof operand === "number") return {
1241
- value: operand,
1242
- unit: "px"
1243
- };
1244
- const match = LENGTH_PATTERN$1.exec(operand.trim());
1245
- return match ? {
1246
- value: Number.parseFloat(match[1]),
1247
- unit: match[2].toLowerCase()
1248
- } : void 0;
1249
- }
1250
- const OPERATIONS = {
1251
- "*": (value, factor) => value * factor,
1252
- "/": (value, factor) => value / factor
1253
- };
1254
- /** `value` multiplied or divided by `factor`, as a number, a literal length or a calc. */
1255
- function scale(name, value, factor, operator) {
1256
- assertOperand(name, value);
1257
- assertFinite(name, operator === "*" ? "the factor" : "the divisor", factor);
1258
- if (factor === 0) {
1259
- if (operator === "/") throw new RangeError(`${name}(): the divisor must not be 0`);
1260
- return 0;
1261
- }
1262
- if (factor === 1) return value;
1263
- if (typeof value === "number") return tidy(OPERATIONS[operator](value, factor));
1264
- const length = toLength(value);
1265
- return length === void 0 ? `${CALC_PREFIX}${toTerm(value)} ${operator} ${factor})` : `${tidy(OPERATIONS[operator](length.value, factor))}${length.unit}`;
1266
- }
1267
- /** The sum of `terms` when they are all numbers, else undefined. */
1268
- function sumNumbers(terms) {
1269
- let total = 0;
1270
- for (const { operand, sign } of terms) {
1271
- if (typeof operand !== "number") return void 0;
1272
- total += sign * operand;
1273
- }
1274
- return tidy(total);
1275
- }
1276
- /** The sum of `terms` when they are literal lengths of one unit, else undefined. */
1277
- function sumLengths(terms) {
1278
- const lengths = terms.map(({ operand }) => toLength(operand));
1279
- const unit = lengths[0]?.unit;
1280
- let total = 0;
1281
- for (const [index, length] of lengths.entries()) {
1282
- if (length === void 0 || length.unit !== unit) return void 0;
1283
- total += terms[index].sign * length.value;
1284
- }
1285
- return `${tidy(total)}${unit}`;
1286
- }
1287
- /** `terms` as one calc: the first term, then each with its sign. */
1288
- function toCalc(terms) {
1289
- const body = terms.map(({ operand, sign }, index) => {
1290
- const term = toTerm(operand);
1291
- if (index === 0) return term;
1292
- return `${sign === 1 ? "+" : "-"} ${term}`;
1293
- }).join(" ");
1294
- return `${CALC_PREFIX}${body})`;
1295
- }
1296
- /** `terms` added and subtracted, as a number, a literal length or one calc. */
1297
- function sum(terms) {
1298
- if (terms.length === 1) return terms[0].operand;
1299
- return sumNumbers(terms) ?? sumLengths(terms) ?? toCalc(terms);
1300
- }
1301
- /** The terms of `values` with `sign`, without the zeros that change nothing; each is checked. */
1302
- function toTerms(name, values, sign) {
1303
- for (const value of values) assertOperand(name, value);
1304
- return values.filter((value) => value !== 0).map((operand) => ({
1305
- operand,
1306
- sign
1307
- }));
1308
- }
1309
- function multiply(value, factor) {
1310
- return scale("multiply", value, factor, "*");
1311
- }
1312
- function divide(value, divisor) {
1313
- return scale("divide", value, divisor, "/");
1314
- }
1315
- function add(...values) {
1316
- const terms = toTerms("add", values, 1);
1317
- return terms.length === 0 ? 0 : sum(terms);
1318
- }
1319
- function subtract(value, ...values) {
1320
- assertOperand("subtract", value);
1321
- return sum([{
1322
- operand: value,
1323
- sign: 1
1324
- }, ...toTerms("subtract", values, -1)]);
1325
- }
1326
- function negate(value) {
1327
- return scale("negate", value, -1, "*");
2640
+ if (sheet.document) registerCache(sheet.document, self);
2641
+ return self;
1328
2642
  }
1329
2643
  // src/lazyRecord.ts
1330
2644
  /**
@@ -1362,6 +2676,34 @@ function createDeferredRecord(source, build) {
1362
2676
  return built[key];
1363
2677
  });
1364
2678
  }
2679
+ /**
2680
+ * An object that stands for the one `make` returns, which is made the first time the object is used in
2681
+ * any way (a property read, `in`, a listing of its keys, a check of whether it is frozen): from then on it
2682
+ * has the same properties, and is frozen as that one is. When `make` throws, the next use tries again. For a value that a module makes before the
2683
+ * engine it needs may exist, such as a `css()` result of a default style before `configure` is called.
2684
+ */
2685
+ function createDeferredObject(make) {
2686
+ const target = {};
2687
+ let isMade = false;
2688
+ const ensure = () => {
2689
+ if (!isMade) {
2690
+ const made = make();
2691
+ isMade = true;
2692
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(made));
2693
+ Object.setPrototypeOf(target, Object.getPrototypeOf(made));
2694
+ if (Object.isFrozen(made)) Object.freeze(target);
2695
+ }
2696
+ return target;
2697
+ };
2698
+ return new Proxy(target, {
2699
+ get: (_target, key) => Reflect.get(ensure(), key),
2700
+ has: (_target, key) => Reflect.has(ensure(), key),
2701
+ ownKeys: () => Reflect.ownKeys(ensure()),
2702
+ getOwnPropertyDescriptor: (_target, key) => Reflect.getOwnPropertyDescriptor(ensure(), key),
2703
+ getPrototypeOf: () => Reflect.getPrototypeOf(ensure()),
2704
+ isExtensible: () => Reflect.isExtensible(ensure())
2705
+ });
2706
+ }
1365
2707
  // src/styleBase.ts
1366
2708
  /** Whether `style` is a function style. */
1367
2709
  function isStyleFunction(style) {
@@ -1434,6 +2776,35 @@ function splitLeading(list, props, view) {
1434
2776
  propsFrom
1435
2777
  };
1436
2778
  }
2779
+ // src/sameView.ts
2780
+ /** Whether `value` is an array, or an object made by a literal. */
2781
+ function isContainer(value) {
2782
+ if (typeof value !== "object" || value === null) return false;
2783
+ const prototype = Object.getPrototypeOf(value);
2784
+ return prototype === Object.prototype || prototype === null || Array.isArray(value);
2785
+ }
2786
+ /** Whether two descriptors hold the same: equal values, or the same accessors. */
2787
+ function isSameDescriptor(first, second) {
2788
+ if ("value" in first) return "value" in second && isSameView(first.value, second.value);
2789
+ return first.get === second.get && first.set === second.set;
2790
+ }
2791
+ /**
2792
+ * Whether two theme views hold the same thing: arrays and plain objects with the same own members
2793
+ * (enumerable or not), each the same, and anything else the same value (a function, a class instance,
2794
+ * by identity). Two views of themes that differ only in the values of their variables are the same.
2795
+ */
2796
+ function isSameView(first, second) {
2797
+ if (first === second) return true;
2798
+ if (!isContainer(first) || !isContainer(second)) return false;
2799
+ if (Object.getPrototypeOf(first) !== Object.getPrototypeOf(second)) return false;
2800
+ const keys = Reflect.ownKeys(first);
2801
+ if (keys.length !== Reflect.ownKeys(second).length) return false;
2802
+ return keys.every((key) => {
2803
+ const other = Object.getOwnPropertyDescriptor(second, key);
2804
+ const own = Object.getOwnPropertyDescriptor(first, key);
2805
+ return other !== void 0 && isSameDescriptor(own, other);
2806
+ });
2807
+ }
1437
2808
  // src/registered.ts
1438
2809
  const SYNTAXES = [
1439
2810
  "<color>",
@@ -1640,12 +3011,18 @@ function createTokens(theme, options = {}) {
1640
3011
  function isThemedSheet(sheet) {
1641
3012
  return typeof sheet.resolve === "function";
1642
3013
  }
3014
+ /** How many recent views a new view is compared with. */
3015
+ const RECENT_VIEWS = 8;
1643
3016
  /** What is thrown when something needs the shape of the theme before any theme is known. */
1644
3017
  const NO_THEME_MESSAGE = "There is no theme yet: render a ThemeProvider with the full theme first, or call setTheme (or configure({ theme })) before a function style, a sheet or useTheme is used.";
1645
3018
  /** `text` in kebab-case: ButtonBase gives button-base. */
1646
3019
  function toKebabCase(text) {
1647
3020
  return text.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
1648
3021
  }
3022
+ /** Whether `value`, given to a styled component from outside, is a plain style object: not a sheet entry, not a class name. */
3023
+ function isPlainStyle(value) {
3024
+ return typeof value === "object" && value !== null && !isSheetEntry(value);
3025
+ }
1649
3026
  /** The label of a styled component: `name-slot`, or '' without a name. */
1650
3027
  function createLabel({ name, slot = "root" }) {
1651
3028
  return name ? `${toKebabCase(name)}-${toKebabCase(slot)}` : "";
@@ -1656,8 +3033,15 @@ function createTokenSignature(values) {
1656
3033
  }
1657
3034
  /** Makes an engine that has no theme yet: it takes one from `setTheme`, or from the first `themeClass`. It needs no framework. */
1658
3035
  function createLazyEngine(options = {}) {
3036
+ return createFamilyEngine(options, {
3037
+ theme: void 0,
3038
+ engines: /* @__PURE__ */ new WeakMap()
3039
+ });
3040
+ }
3041
+ /** Makes an engine of `family`: its cache is the one in `options` or a new one; its base theme is the family's. */
3042
+ function createFamilyEngine(options, family) {
1659
3043
  const { cache: given, suffix, hasLabels, hasLayers, hasPruning, hasColorFallbacks } = options;
1660
- const { hasScope, hasBaseClass, hasDevChecks } = options;
3044
+ const { hasScope, hasBaseClass, hasDevChecks, hasValueRepair } = options;
1661
3045
  const { alwaysDeclare = [] } = options;
1662
3046
  const { rawKeys, lengthKeys, modes, registered } = options;
1663
3047
  if (given && options.prefix !== void 0 && options.prefix !== given.prefix) throw new TypeError(`the engine options give the prefix "${options.prefix}", which differs from the prefix "${given.prefix}" of the given cache; variables and classes would use two prefixes. Leave out \`prefix\`, or give the same one.`);
@@ -1669,6 +3053,7 @@ function createLazyEngine(options = {}) {
1669
3053
  hasLayers,
1670
3054
  hasPruning,
1671
3055
  hasColorFallbacks,
3056
+ hasValueRepair,
1672
3057
  hasScope,
1673
3058
  hasBaseClass,
1674
3059
  hasDevChecks,
@@ -1687,34 +3072,50 @@ function createLazyEngine(options = {}) {
1687
3072
  modes,
1688
3073
  registered
1689
3074
  };
1690
- let baseTheme;
3075
+ let tokensTheme;
1691
3076
  let tokens;
1692
3077
  let version = 0;
1693
- const readTokens = () => {
1694
- if (!tokens) throw new Error(NO_THEME_MESSAGE);
1695
- return tokens;
1696
- };
1697
- const setTheme = (theme) => {
1698
- if (theme === baseTheme) return;
1699
- baseTheme = theme;
3078
+ /** Makes the tokens of the base theme of the family, when they were made from another one or not yet. */
3079
+ const sync = () => {
3080
+ const theme = family.theme;
3081
+ if (theme === tokensTheme) return;
3082
+ tokensTheme = theme;
1700
3083
  tokens = createTokens(theme, tokenOptions);
1701
3084
  views = /* @__PURE__ */ new WeakMap();
3085
+ recentViews = [];
1702
3086
  cache.registerProperties(tokens.registrations);
1703
3087
  cache.markUsed(tokens.findNames(alwaysDeclare));
1704
3088
  version++;
1705
3089
  };
3090
+ const readTokens = () => {
3091
+ sync();
3092
+ if (!tokens) throw new Error(NO_THEME_MESSAGE);
3093
+ return tokens;
3094
+ };
3095
+ cache.setKeyframesTheme(() => readTokens().refs);
3096
+ const setTheme = (theme) => {
3097
+ family.theme = theme;
3098
+ sync();
3099
+ };
1706
3100
  let views = /* @__PURE__ */ new WeakMap();
3101
+ let recentViews = [];
1707
3102
  const createThemeView = (realTheme) => {
3103
+ sync();
1708
3104
  let view = views.get(realTheme);
1709
3105
  if (view === void 0) {
1710
- view = (tokens ?? createTokens(realTheme, tokenOptions)).createView(realTheme);
3106
+ const made = (tokens ?? createTokens(realTheme, tokenOptions)).createView(realTheme);
3107
+ view = recentViews.find((recent) => isSameView(recent, made));
3108
+ if (view === void 0) {
3109
+ view = made;
3110
+ recentViews = [made, ...recentViews].slice(0, RECENT_VIEWS);
3111
+ }
1711
3112
  views.set(realTheme, view);
1712
3113
  }
1713
3114
  return view;
1714
3115
  };
1715
3116
  const themeClasses = /* @__PURE__ */ new WeakMap();
1716
3117
  const themeId = (partial, colorScheme) => {
1717
- if (!tokens) setTheme(partial);
3118
+ if (family.theme === void 0) setTheme(partial);
1718
3119
  const key = colorScheme ?? "";
1719
3120
  const known = themeClasses.get(partial) ?? /* @__PURE__ */ new Map();
1720
3121
  themeClasses.set(partial, known);
@@ -1725,6 +3126,39 @@ function createLazyEngine(options = {}) {
1725
3126
  }
1726
3127
  return className;
1727
3128
  };
3129
+ const roots = /* @__PURE__ */ new WeakMap();
3130
+ const declareRoot = (theme, colorScheme) => {
3131
+ if (family.theme === void 0) setTheme(theme);
3132
+ const key = colorScheme ?? "";
3133
+ const known = roots.get(theme) ?? /* @__PURE__ */ new Map();
3134
+ roots.set(theme, known);
3135
+ let made = known.get(key);
3136
+ if (made === void 0) {
3137
+ const declarations = readTokens().declare(theme);
3138
+ made = [declareRootTheme(cache, declarations, { colorScheme }), declarations];
3139
+ known.set(key, made);
3140
+ }
3141
+ const [id, declarations] = made;
3142
+ cache.insertRoot(id, declarations, colorScheme);
3143
+ return id;
3144
+ };
3145
+ const themeTexts = /* @__PURE__ */ new WeakMap();
3146
+ const readThemeText = (partial) => {
3147
+ sync();
3148
+ let text = themeTexts.get(partial);
3149
+ if (text === void 0) {
3150
+ const { declare, registrations } = tokens ?? createTokens(partial, tokenOptions);
3151
+ const declarations = declare(partial);
3152
+ const names = Object.keys(declarations);
3153
+ text = {
3154
+ declarations: toDeclarationText(Object.entries(declarations)),
3155
+ properties: names.map((name) => registrations[name] ?? "").join(""),
3156
+ names
3157
+ };
3158
+ if (tokens) themeTexts.set(partial, text);
3159
+ }
3160
+ return text;
3161
+ };
1728
3162
  const findThemeIds = (partial) => [...themeClasses.get(partial)?.values() ?? []];
1729
3163
  const themeClass = (partial, colorScheme) => createThemeClassName(cache.prefix, themeId(partial, colorScheme), colorScheme);
1730
3164
  const when = (partial, colorScheme) => createThemeKey(themeId(partial, colorScheme));
@@ -1748,8 +3182,9 @@ function createLazyEngine(options = {}) {
1748
3182
  }
1749
3183
  return entries;
1750
3184
  }
3185
+ const { refs } = readTokens();
1751
3186
  if (baseEntries === void 0 || madeAt !== version) {
1752
- baseEntries = createEntries(styles(readTokens().refs));
3187
+ baseEntries = createEntries(styles(refs));
1753
3188
  madeAt = version;
1754
3189
  }
1755
3190
  return baseEntries;
@@ -1808,45 +3243,97 @@ function createLazyEngine(options = {}) {
1808
3243
  };
1809
3244
  /** Without layers there is no override class and no order between classes to rely on: what comes in is merged with all of the styles, into the one class. */
1810
3245
  const getMerged = (props, theme, extras) => cache.css(...resolveAll(list, props, theme), ...extras);
3246
+ const getClassName = (props, extra, theme) => {
3247
+ const extras = Array.isArray(extra) ? extra : [extra];
3248
+ const hasExtras = extras.some(Boolean);
3249
+ if (hasExtras && !cache.hasLayers) return getMerged(props, theme, extras);
3250
+ const own = getOwn(getPlan(props, theme), props, theme);
3251
+ if (!hasExtras) return own;
3252
+ return [own, cache.cssWith({
3253
+ layer: "overrides",
3254
+ label: label || void 0
3255
+ }, ...extras)].filter(Boolean).join(" ");
3256
+ };
1811
3257
  return {
1812
3258
  styles: list,
1813
3259
  isDynamic: hasFunction,
1814
- getClassName(props, extra, theme) {
3260
+ getClassName,
3261
+ getHeldClass(props, extra, theme) {
1815
3262
  const extras = Array.isArray(extra) ? extra : [extra];
1816
- const hasExtras = extras.some(Boolean);
1817
- if (hasExtras && !cache.hasLayers) return getMerged(props, theme, extras);
3263
+ if (!extras.some(isPlainStyle)) return {
3264
+ className: getClassName(props, extras, theme),
3265
+ hold: void 0
3266
+ };
3267
+ if (!cache.hasLayers) return cache.cssHeld({}, ...resolveAll(list, props, theme), ...extras);
1818
3268
  const own = getOwn(getPlan(props, theme), props, theme);
1819
- if (!hasExtras) return own;
1820
- return [own, cache.cssWith({
3269
+ const overrides = cache.cssHeld({
1821
3270
  layer: "overrides",
1822
3271
  label: label || void 0
1823
- }, ...extras)].filter(Boolean).join(" ");
3272
+ }, ...extras);
3273
+ return {
3274
+ className: [own, overrides.className].filter(Boolean).join(" "),
3275
+ hold: overrides.hold
3276
+ };
1824
3277
  }
1825
3278
  };
1826
3279
  };
1827
- return {
3280
+ const resolveGlobal = (input, theme) => {
3281
+ const readTheme = () => theme ?? readTokens().refs;
3282
+ return (Array.isArray(input) ? input : [input]).map((item) => cache.compileGlobal(readGlobalStyles(item, readTheme)));
3283
+ };
3284
+ const insertGlobal = (input, theme) => {
3285
+ const releases = resolveGlobal(input, theme).map((set) => cache.insertGlobal(set));
3286
+ return () => {
3287
+ for (const release of releases) release();
3288
+ };
3289
+ };
3290
+ const adoptedSheets = /* @__PURE__ */ new WeakMap();
3291
+ const adoptSheet = (entries) => {
3292
+ let adopted = adoptedSheets.get(entries);
3293
+ if (adopted === void 0) {
3294
+ adopted = createLazyRecord(Object.keys(entries), (key) => cache.adoptEntry(entries[key]));
3295
+ adoptedSheets.set(entries, adopted);
3296
+ }
3297
+ return adopted;
3298
+ };
3299
+ const engine = {
1828
3300
  cache,
1829
3301
  css: cache.css,
3302
+ resolveGlobal,
3303
+ insertGlobal,
1830
3304
  get hasTheme() {
1831
- return baseTheme !== void 0;
3305
+ return family.theme !== void 0;
1832
3306
  },
1833
3307
  get baseTheme() {
1834
- return baseTheme;
3308
+ return family.theme;
1835
3309
  },
1836
3310
  get refs() {
1837
3311
  return readTokens().refs;
1838
3312
  },
3313
+ tokenOptions,
1839
3314
  scopeClass,
3315
+ keyframes,
3316
+ insertKeyframes: cache.insertKeyframes,
1840
3317
  setTheme,
1841
3318
  createThemeView,
1842
3319
  themeClass,
1843
3320
  themeId,
1844
3321
  findThemeIds,
3322
+ declareRoot,
3323
+ readThemeText,
1845
3324
  when,
1846
3325
  whenScheme: createSchemeKey,
1847
3326
  createSheet,
1848
- createStyler
3327
+ createStyler,
3328
+ withCache: (other) => family.engines.get(other) ?? createFamilyEngine({
3329
+ ...options,
3330
+ prefix: void 0,
3331
+ cache: other
3332
+ }, family),
3333
+ adoptSheet
1849
3334
  };
3335
+ family.engines.set(cache, engine);
3336
+ return engine;
1850
3337
  }
1851
3338
  /** Makes the engine of one theme shape: a cache, the theme as variables, and what the bindings build on. It needs no framework. */
1852
3339
  function createEngine(theme, options = {}) {
@@ -1854,7 +3341,91 @@ function createEngine(theme, options = {}) {
1854
3341
  engine.setTheme(theme);
1855
3342
  return engine;
1856
3343
  }
3344
+ // src/css.ts
3345
+ /** Whether `value`, or an item of a list in it, is a function. */
3346
+ function hasFunction(value) {
3347
+ return typeof value === "function" || Array.isArray(value) && value.some(hasFunction);
3348
+ }
3349
+ /**
3350
+ * The style of `args` when they are a tagged template (`caller` was used as a tag), read as CSS text;
3351
+ * undefined when they are not. `caller` has no props, so a function among the interpolations is a
3352
+ * `TypeError` that names it.
3353
+ */
3354
+ function readStaticTemplate(args, caller) {
3355
+ const [first, ...values] = args;
3356
+ if (!isTemplateStrings(first)) return void 0;
3357
+ const parsed = parseStyleTemplate(first, values);
3358
+ if (typeof parsed === "function") throw new TypeError(`${caller}(): an interpolation of this template is a function, which needs props, and ${caller}() has none. Use the template with styled, or call the function yourself and interpolate what it returns.`);
3359
+ return parsed;
3360
+ }
3361
+ /**
3362
+ * Throws a `TypeError` that names `caller` when an argument, or an item of a list among them, is a
3363
+ * function: `caller` has no props to call it with.
3364
+ */
3365
+ function rejectFunctions(args, caller) {
3366
+ if (args.some(hasFunction)) throw new TypeError(`${caller}(): a function is not a style here, because ${caller}() has no props. Give it to styled, or call it yourself and pass what it returns.`);
3367
+ }
3368
+ /**
3369
+ * The style of the arguments of `css()`: a tagged template read as CSS text, or style objects, `css()`
3370
+ * results and sheet entries, with lists flattened and `false`, `null` and `undefined` dropped, merged in
3371
+ * order, the last winning. An entry that a framework merged into an object is found with `findEntry`.
3372
+ * Throws a `TypeError` for a function, for a string, and for an entry that is only a class name.
3373
+ */
3374
+ function readCssStyle(args, findEntry) {
3375
+ const template = readStaticTemplate(args, "css");
3376
+ if (template) return template;
3377
+ rejectFunctions(args, "css");
3378
+ return mergeStyles(flattenStyle(args, findEntry).map((item) => readEntryStyle(item, "css")));
3379
+ }
3380
+ /**
3381
+ * `css()` of a web binding over `cache`: one sheet entry of the merged style (see `readCssStyle`). Its
3382
+ * class name is worked out now and its rule is written when the entry is first used, as an entry of a
3383
+ * sheet; equal styles give the same class.
3384
+ */
3385
+ function createCssEntry(cache, args) {
3386
+ return cache.createEntry(readCssStyle(args, cache.findEntry));
3387
+ }
3388
+ /**
3389
+ * The styles of a call of the function that `styled(tag)` returns: as a tag, the template is one style
3390
+ * (an object, or a function of the props when an interpolation is a function); else the styles given,
3391
+ * with lists flattened.
3392
+ */
3393
+ function readStyleArguments(args) {
3394
+ const [first, ...values] = args;
3395
+ if (isTemplateStrings(first)) return [parseStyleTemplate(first, values)];
3396
+ return args.flat(1e400);
3397
+ }
3398
+ /**
3399
+ * The `toString` of a styled component, which makes it a selector in a template or a key
3400
+ * (`${Button}:hover &`): `.` and a class that every element of the component has. That is the
3401
+ * component's own `target` when it was given one (each class of it, when it holds several); else, when none of its styles is a function, its class
3402
+ * (the base class, the same for every element); else there is none, and it throws a `TypeError` that says
3403
+ * to give the component a `target`.
3404
+ */
3405
+ function createComponentSelector(target, styler) {
3406
+ return () => {
3407
+ if (target) return `.${target.trim().replaceAll(/\s+/g, ".")}`;
3408
+ const className = styler.isDynamic ? "" : styler.getClassName({});
3409
+ if (className === "") throw new TypeError("A styled component used as a selector needs a class that every element of it has: give it a `target` (styled(tag, { target: \"my-button\" })), or write its styles without functions.");
3410
+ return `.${className}`;
3411
+ };
3412
+ }
1857
3413
  // src/scanHtml.ts
3414
+ /** The end of the name of a marker of global rules: `<prefix>-global`. */
3415
+ const MARKER_END = "-global";
3416
+ /**
3417
+ * The marker by which a `Global` that renders no style element names its sets in the markup of a server
3418
+ * render, so that `extractPageStyles` puts them in that page only: the sets that have rules, by id. None
3419
+ * when no set has a rule. A binding renders it as `<meta name="<name>" content="<ids>">` (React) or as a
3420
+ * comment `<!--<name> <ids>-->` (Vue).
3421
+ */
3422
+ function createGlobalMarker(prefix, sets) {
3423
+ const ids = sets.filter(({ rules }) => rules.length > 0).map(({ id }) => id);
3424
+ return ids.length === 0 ? void 0 : {
3425
+ name: `${prefix}${MARKER_END}`,
3426
+ ids: ids.join(" ")
3427
+ };
3428
+ }
1858
3429
  /** The elements whose content is text, not markup: nothing in them is an attribute. */
1859
3430
  const RAW_TEXT_ELEMENTS = /* @__PURE__ */ new Set([
1860
3431
  "script",
@@ -1902,62 +3473,89 @@ function readValue(html, index) {
1902
3473
  end
1903
3474
  };
1904
3475
  }
1905
- /** Reads the attributes of the tag whose name ended at `index`, adds what matters to `found`, and returns the index after the `>`. */
1906
- function readAttributes(html, index, found) {
3476
+ /** Adds the ids that a marker names to `found`: the tokens of `content` when `name` is that of a marker. */
3477
+ function addMarked(found, name, content) {
3478
+ if (name.endsWith(MARKER_END)) addTokens(found.rendered, content);
3479
+ }
3480
+ /** Adds what the attribute `name` with `value` says to `found`, or keeps it in `meta`. */
3481
+ function addAttribute(found, meta, name, value) {
3482
+ if (name === "class" || name === "classname") addTokens(found.classes, value);
3483
+ else if (name === "data-href") addTokens(found.carried, value);
3484
+ else if (name === "name") meta.name = value;
3485
+ else if (name === "content") meta.content = value;
3486
+ }
3487
+ /** Reads the attribute that starts at `index`, adds what matters to `found` or `meta`, and returns the index after it. */
3488
+ function readAttribute(html, index, found, meta) {
3489
+ let position = readNameEnd(html, index);
3490
+ if (position === index) position++;
3491
+ const name = html.slice(index, position).toLowerCase();
3492
+ position = skipSpaces(html, position);
3493
+ if (html[position] !== "=") return position;
3494
+ const { value, end } = readValue(html, skipSpaces(html, position + 1));
3495
+ addAttribute(found, meta, name, value);
3496
+ return end;
3497
+ }
3498
+ /** Reads the attributes of the tag whose name ended at `index`, adds what matters to `found`, and returns the index after the `>`. A `<meta>` (`isMeta`) is read for the marker of global rules too. */
3499
+ function readAttributes(html, index, found, isMeta) {
3500
+ const meta = {
3501
+ name: "",
3502
+ content: ""
3503
+ };
1907
3504
  let position = index;
1908
3505
  while (position < html.length) {
1909
3506
  const code = codeAt(html, position);
1910
- if (code === 62) return position + 1;
1911
- if (isSpace(code) || code === 47) {
1912
- position++;
1913
- continue;
3507
+ if (code === 62) {
3508
+ if (isMeta) addMarked(found, meta.name, meta.content);
3509
+ return position + 1;
1914
3510
  }
1915
- const nameStart = position;
1916
- while (position < html.length && !isNameEnd(codeAt(html, position))) position++;
1917
- if (position === nameStart) position++;
1918
- const name = html.slice(nameStart, position).toLowerCase();
1919
- position = skipSpaces(html, position);
1920
- if (html[position] !== "=") continue;
1921
- const { value, end } = readValue(html, skipSpaces(html, position + 1));
1922
- position = end;
1923
- if (name === "class" || name === "classname") addTokens(found.classes, value);
1924
- else if (name === "data-href") addTokens(found.carried, value);
3511
+ position = isSpace(code) || code === 47 ? position + 1 : readAttribute(html, position, found, meta);
1925
3512
  }
1926
3513
  return html.length;
1927
3514
  }
3515
+ /** Reads the comment whose text starts at `start` and ends at `end`: a marker of global rules adds the ids it names to `found`. */
3516
+ function readComment(html, start, end, found) {
3517
+ if (!isLetter(codeAt(html, start))) return;
3518
+ const text = html.slice(start, end);
3519
+ const space = text.indexOf(" ");
3520
+ if (space !== -1) addMarked(found, text.slice(0, space), text.slice(space + 1));
3521
+ }
1928
3522
  /** The index of the `</name` that closes a raw text element, or the end of the document. */
1929
3523
  function findClosingTag(html, index, name) {
1930
3524
  let at = html.indexOf("</", index);
1931
3525
  while (at !== -1 && html.slice(at + 2, at + 2 + name.length).toLowerCase() !== name) at = html.indexOf("</", at + 2);
1932
3526
  return at === -1 ? html.length : at;
1933
3527
  }
1934
- /** The index of the end of the tag name that starts at `index`. */
1935
- function readTagNameEnd(html, index) {
3528
+ /** The index of the end of the name (of a tag or an attribute) that starts at `index`. */
3529
+ function readNameEnd(html, index) {
1936
3530
  let end = index;
1937
3531
  while (end < html.length && !isNameEnd(codeAt(html, end))) end++;
1938
3532
  return end;
1939
3533
  }
1940
3534
  /**
1941
3535
  * The class tokens of `html`: the values of the `class` and `className` attributes, in one pass over
1942
- * the markup. Comments and the content of `script`, `style`, `textarea` and `title` are skipped, so
1943
- * a class name inside a script or a text is not taken for a class. Quoted and bare values are read;
1944
- * a class name in any other attribute is not looked at. The pass moves forward only: its time is
1945
- * linear in the length of the document, and there is no pattern to backtrack.
3536
+ * the markup, with the keys of the style elements it carries (`data-href`) and the ids that the markers
3537
+ * of `Global` name. Comments other than a marker and the content of `script`, `style`, `textarea` and
3538
+ * `title` are skipped, so a class name inside a script or a text is not taken for a class. Quoted and
3539
+ * bare values are read; a class name in any other attribute is not looked at. The pass moves forward
3540
+ * only: its time is linear in the length of the document, and there is no pattern to backtrack.
1946
3541
  */
1947
3542
  function scanHtml(html) {
1948
3543
  const found = {
1949
3544
  classes: /* @__PURE__ */ new Set(),
1950
- carried: /* @__PURE__ */ new Set()
3545
+ carried: /* @__PURE__ */ new Set(),
3546
+ rendered: /* @__PURE__ */ new Set()
1951
3547
  };
1952
3548
  let at = html.indexOf("<");
1953
3549
  while (at !== -1) {
1954
3550
  if (html.startsWith("<!--", at)) {
1955
3551
  const close = html.indexOf("-->", at + 4);
1956
- at = close === -1 ? html.length : close + 3;
3552
+ const end = close === -1 ? html.length : close;
3553
+ readComment(html, at + 4, end, found);
3554
+ at = end + 3;
1957
3555
  } else if (isLetter(codeAt(html, at + 1))) {
1958
- const nameEnd = readTagNameEnd(html, at + 1);
3556
+ const nameEnd = readNameEnd(html, at + 1);
1959
3557
  const name = html.slice(at + 1, nameEnd).toLowerCase();
1960
- at = readAttributes(html, nameEnd, found);
3558
+ at = readAttributes(html, nameEnd, found, name === "meta");
1961
3559
  if (RAW_TEXT_ELEMENTS.has(name)) at = findClosingTag(html, at, name);
1962
3560
  } else at++;
1963
3561
  at = html.indexOf("<", at);
@@ -1982,19 +3580,17 @@ function createStyleTag(cache) {
1982
3580
  /**
1983
3581
  * The CSS of one page, decided from the page: the finished `html` is scanned for the class names it
1984
3582
  * holds (the values of its `class` and `className` attributes only; scripts, styles, comments and other
1985
- * attributes are not looked at), and only those classes are written, with the theme classes
1986
- * trimmed to the variables that the page uses. Nothing depends on what else the cache holds, on the
3583
+ * attributes are not looked at), and only those classes are written, with the `@keyframes` rules they
3584
+ * use and the theme classes trimmed to the variables that the page uses. Nothing depends on what else the cache holds, on the
1987
3585
  * order pages were rendered in, or on pages being rendered at the same time, and the cache is not changed.
1988
3586
  * The `<style href precedence>` elements that `html` carries already (React's server render of the
1989
- * client build emits them) are not written again.
3587
+ * client build emits them) are not written again. The global rules are those inserted for the app
3588
+ * (`engine.insertGlobal`), which are in every page, and those of the `Global` components that `html`
3589
+ * rendered: a style element it carries, or a marker that names the set (a `<meta name="<prefix>-global">`
3590
+ * of React, a comment `<!--<prefix>-global ...-->` of Vue). A set that another page rendered is not.
1990
3591
  */
1991
3592
  function extractPageStyles(cache, html, options = {}) {
1992
- const { classes, carried } = scanHtml(html);
1993
- const themes = (options.themes ?? []).flatMap((value) => value.split(/\s+/));
1994
- const { css, ids } = cache.extractPage(classes, {
1995
- themes,
1996
- carried
1997
- });
3593
+ const { css, ids } = cache.extractPage(...readPage(html, options));
1998
3594
  return {
1999
3595
  css,
2000
3596
  ids,
@@ -2002,6 +3598,24 @@ function extractPageStyles(cache, html, options = {}) {
2002
3598
  tag: createTag(cache, css)
2003
3599
  };
2004
3600
  }
3601
+ /** The class names of `html`, and what `extractPage` is told besides them. */
3602
+ function readPage(html, options) {
3603
+ const { classes, carried, rendered } = scanHtml(html);
3604
+ return [classes, {
3605
+ themes: (options.themes ?? []).flatMap((value) => value.split(/\s+/)),
3606
+ animations: options.animations,
3607
+ carried,
3608
+ rendered
3609
+ }];
3610
+ }
3611
+ /**
3612
+ * `extractPageStyles` in two parts, decided from `html` the same way: the rules that no class stands for
3613
+ * (the layer order, the `@property` and `@keyframes` rules, the theme classes, the global rules) and the
3614
+ * rules of the classes. The two CSS texts joined in this order are the CSS of `extractPageStyles`.
3615
+ */
3616
+ function extractPageStyleParts(cache, html, options = {}) {
3617
+ return cache.extractPageParts(...readPage(html, options));
3618
+ }
2005
3619
  // src/mergeDeep.ts
2006
3620
  /** Whether `value` is an object made by a literal, not a class instance. */
2007
3621
  function isPlainObject(value) {
@@ -2009,12 +3623,48 @@ function isPlainObject(value) {
2009
3623
  const prototype = Object.getPrototypeOf(value);
2010
3624
  return prototype === Object.prototype || prototype === null;
2011
3625
  }
2012
- /** `override` over `base`: plain objects merge key by key, everything else is replaced, undefined keeps `base`. */
3626
+ /**
3627
+ * `override` over `base`: plain objects merge key by key, everything else is replaced, undefined keeps
3628
+ * `base`. Every own member is taken with its descriptor, so a member that is not enumerable (a helper
3629
+ * function on `breakpoints`) is kept, from `override` when it has one, else from `base`.
3630
+ */
2013
3631
  function mergeDeep(base, override) {
2014
3632
  if (override === void 0) return base;
2015
3633
  if (!isPlainObject(base) || !isPlainObject(override)) return override;
2016
- const merged = { ...base };
2017
- for (const [key, value] of Object.entries(override)) merged[key] = mergeDeep(base[key], value);
2018
- return merged;
3634
+ const descriptors = Object.getOwnPropertyDescriptors(base);
3635
+ const given = Object.getOwnPropertyDescriptors(override);
3636
+ for (const key of Reflect.ownKeys(given)) {
3637
+ const descriptor = given[key];
3638
+ descriptors[key] = "value" in descriptor ? {
3639
+ ...descriptor,
3640
+ value: mergeDeep(base[key], descriptor.value)
3641
+ } : descriptor;
3642
+ }
3643
+ return Object.create(Object.getPrototypeOf(base), descriptors);
2019
3644
  }
2020
- export { DEFAULT_SCOPING, NO_THEME_MESSAGE, RULE_LAYERS, add, alpha, assertAlphaInput, at, compileRules, createCache, createDeferredRecord, createDomSheet, createEngine, createLazyEngine, createLazyRecord, createMemorySheet, createNoSchemeGuard, createSchemeKey, createScopeRule, createSheetEntry, createStyleTag, createThemeClass, createThemeClassName, createThemeKey, createTokens, divide, extractPageStyles, findMissingStyles, flattenStyle, getBoundaryClass, getSchemeClass, hashString, isAlphaColor, isSheetEntry, isThemedSheet, mergeDeep, mergeStyles, multiply, negate, readCondition, readEntrySource, readLabel, subtract, toDeclarationText, toRgba };
3645
+ // src/tagShorthands.ts
3646
+ /** What a shorthand can be: a tag name, a lowercase letter then letters and digits (`div`, `h1`, `foreignObject`). */
3647
+ const TAG_PATTERN = /^[a-z][a-zA-Z0-9]*$/;
3648
+ /**
3649
+ * `styled` with a shorthand for every tag: `styled.div(...styles)` is `styled('div')(...styles)`. Nothing
3650
+ * is made up front: a member that the function does not have and that looks like a tag name is made when
3651
+ * it is read. `then` is not a tag, so that `styled` is never taken for a promise.
3652
+ */
3653
+ function withTagShorthands(styled) {
3654
+ return new Proxy(styled, { get(target, key, receiver) {
3655
+ if (typeof key !== "string" || key in target || key === "then" || !TAG_PATTERN.test(key)) return Reflect.get(target, key, receiver);
3656
+ return target(key);
3657
+ } });
3658
+ }
3659
+ // src/themeInput.ts
3660
+ /** The theme where there is no provider and no base theme: an object with nothing in it, never changed. */
3661
+ const EMPTY_THEME = Object.freeze({});
3662
+ /** The theme that a provider given `input` adds below `outer` (the theme above it, or `EMPTY_THEME`): the result of a function, or the object as it is. */
3663
+ function resolveThemeInput(input, outer) {
3664
+ return typeof input === "function" ? input(outer) : input;
3665
+ }
3666
+ /** The theme below a provider: `given` merged over the theme above it, or `given` as it is where there is none above and no base theme. */
3667
+ function mergeTheme(outer, given) {
3668
+ return outer === void 0 ? given : mergeDeep(outer, given);
3669
+ }
3670
+ export { DEFAULT_SCOPING, EMPTY_THEME, NO_THEME_MESSAGE, ROOT_SELECTOR, RULE_LAYERS, add, alpha, assertAlphaInput, at, compileRules, createCache, createComponentSelector, createCssEntry, createDeferredObject, createDeferredRecord, createDomSheet, createEngine, createGlobalMarker, createLazyEngine, createLazyRecord, createMemorySheet, createNoSchemeGuard, createSchemeKey, createScopeRule, createSheetEntry, createStyleSelector, createStyleTag, createThemeClass, createThemeClassName, createThemeId, createThemeKey, createThemeRule, createTokens, declareRootTheme, divide, extractPageStyleParts, extractPageStyles, findCache, findEntryCache, findMissingStyles, flattenStyle, getBoundaryClass, getSchemeClass, globalStyles, hashString, isAlphaColor, isDevelopment, isSheetEntry, isTemplateStrings, isThemedSheet, keyframes, mergeDeep, mergeStyles, mergeTheme, multiply, negate, parseKeyframesTemplate, parseStyleTemplate, readCondition, readCssStyle, readEntrySource, readEntryStyle, readLabel, readStaticTemplate, readStyleArguments, rejectFunctions, resolveThemeInput, subtract, toDeclarationText, toRgba, withTagShorthands };