@master/css-runtime 2.0.0-rc.73 → 2.0.0-rc.74

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.js ADDED
@@ -0,0 +1,1211 @@
1
+ import { AnimationRule, Layer, MasterCSS, ThemeLayer, VariableRule, compareRulePriority } from "@master/css-engine";
2
+ import { MASTER_CSS_HYDRATION_MANIFEST_ATTR, MASTER_CSS_HYDRATION_MANIFEST_SCRIPT_ID } from "@master/css-schema/hydration-manifest";
3
+ import { MASTER_CSS_RUNTIME_STYLE_ID } from "@master/css-schema/runtime-style";
4
+ //#region src/debuggers/log.ts
5
+ const createLogger = (type) => {
6
+ return (message, ...args) => {
7
+ if (!type) return console.log(message, ...args);
8
+ if (console[type]) console[type](`%c[Master CSS]%c ${message}`, "color: gray;", "color: inherit;", ...args);
9
+ };
10
+ };
11
+ const loggers = {
12
+ info: createLogger("info"),
13
+ debug: createLogger("debug"),
14
+ warn: console.warn,
15
+ error: console.error,
16
+ trace: console.trace,
17
+ table: console.table,
18
+ group: console.group,
19
+ groupCollapsed: console.group,
20
+ groupEnd: console.groupEnd,
21
+ time: console.time,
22
+ timeEnd: console.timeEnd
23
+ };
24
+ const log = createLogger();
25
+ Object.assign(log, loggers);
26
+ //#endregion
27
+ //#region src/debuggers/class-count.ts
28
+ function debugRuntimeMutation(records, classCounts, cssRuntime) {
29
+ const actualClassCounts = {};
30
+ let errored = false;
31
+ const resolveClass = (className) => {
32
+ if (Object.prototype.hasOwnProperty.call(actualClassCounts, className)) actualClassCounts[className]++;
33
+ else actualClassCounts[className] = 1;
34
+ };
35
+ (cssRuntime.root.constructor.name === "HTMLDocument" ? cssRuntime.host : cssRuntime.container).querySelectorAll("[class]").forEach((element) => {
36
+ element.classList.forEach(resolveClass);
37
+ });
38
+ cssRuntime.host.classList.forEach(resolveClass);
39
+ for (const className in actualClassCounts) {
40
+ const eachCount = cssRuntime.classCounts.get(className);
41
+ const eachActualCount = actualClassCounts[className];
42
+ if (eachCount !== eachActualCount) {
43
+ log.error(`Class count mismatch for \`${className}\` (expected ${eachActualCount}) (received ${eachCount})`);
44
+ errored = true;
45
+ }
46
+ }
47
+ cssRuntime.classCounts.forEach((eachCount, className) => {
48
+ if (!Object.prototype.hasOwnProperty.call(actualClassCounts, className)) {
49
+ log.error(`Class count mismatch for \`${className}\` (expected 0) (received ${eachCount})`);
50
+ errored = true;
51
+ }
52
+ });
53
+ if (errored) {
54
+ log.debug("Records:", records);
55
+ log.debug("Serialized Records:", serializeMutations(records));
56
+ log.debug("Counts:", classCounts);
57
+ }
58
+ }
59
+ function serializeMutations(mutations) {
60
+ return mutations.map((m) => {
61
+ const target = m.target;
62
+ return {
63
+ type: m.type,
64
+ attributeName: m.attributeName,
65
+ oldValue: m.oldValue,
66
+ target: {
67
+ tagName: target.tagName,
68
+ id: target.id,
69
+ classList: Array.from(target.classList)
70
+ },
71
+ added: Array.from(m.addedNodes).filter((n) => n.nodeType === 1).map((el) => ({
72
+ tagName: el.tagName,
73
+ id: el.id,
74
+ classList: Array.from(el.classList)
75
+ })),
76
+ removed: Array.from(m.removedNodes).filter((n) => n.nodeType === 1).map((el) => ({
77
+ tagName: el.tagName,
78
+ id: el.id,
79
+ classList: Array.from(el.classList)
80
+ }))
81
+ };
82
+ });
83
+ }
84
+ //#endregion
85
+ //#region src/debuggers/lifecycle.ts
86
+ function debugRuntimeCreated(cssRuntime) {
87
+ log.debug("created", cssRuntime);
88
+ }
89
+ function debugRuntimeHydrated(cssRuntime, result) {
90
+ log.debug("hydrated", cssRuntime, result);
91
+ }
92
+ function debugRuntimeObserved(cssRuntime) {
93
+ log.debug("observed", cssRuntime);
94
+ if (cssRuntime.progressive) {
95
+ log.info("Progressive rendering is adopted.");
96
+ log.debug("pre-rendered CSS", cssRuntime.style);
97
+ } else log.info("Runtime rendering is adopted.");
98
+ }
99
+ function debugRuntimeRefreshed(cssRuntime, manifest) {
100
+ log.debug("refreshed", cssRuntime, manifest);
101
+ }
102
+ function debugRuntimeDisconnected(cssRuntime) {
103
+ log.debug("disconnected", cssRuntime);
104
+ }
105
+ function debugRuntimeDestroyed(cssRuntime) {
106
+ log.debug("destroyed", cssRuntime);
107
+ }
108
+ //#endregion
109
+ //#region src/debuggers/index.ts
110
+ function startDebuggers() {
111
+ log.info("Debug mode is enabled by default in development.");
112
+ }
113
+ //#endregion
114
+ //#region src/register-global.ts
115
+ function registerGlobal(CSSRuntime) {
116
+ if (!globalThis.MasterCSSRuntime) globalThis.MasterCSSRuntime = CSSRuntime;
117
+ startDebuggers();
118
+ }
119
+ //#endregion
120
+ //#region src/utils/find-native-css-rule-index.ts
121
+ function findNativeCSSRuleIndex(cssRules, nativeRule) {
122
+ for (let i = 0; i < cssRules.length; i++) if (cssRules[i] === nativeRule) return i;
123
+ return -1;
124
+ }
125
+ //#endregion
126
+ //#region src/layer.ts
127
+ function getRuleNodes(rule) {
128
+ const nodes = rule.nodes;
129
+ return Array.isArray(nodes) ? nodes : void 0;
130
+ }
131
+ var RuntimeLayer = class extends Layer {
132
+ name;
133
+ cssRuntime;
134
+ rules = [];
135
+ tokenCounts = /* @__PURE__ */ new Map();
136
+ native = null;
137
+ constructor(name, cssRuntime) {
138
+ super(name, cssRuntime);
139
+ this.name = name;
140
+ this.cssRuntime = cssRuntime;
141
+ }
142
+ attach() {
143
+ super.attach();
144
+ const nativeSheet = this.cssRuntime.style?.sheet;
145
+ if (nativeSheet && !this.native?.parentStyleSheet) {
146
+ const insertedIndex = nativeSheet.insertRule(this.text, nativeSheet.cssRules.length);
147
+ this.native = nativeSheet.cssRules.item(insertedIndex);
148
+ }
149
+ }
150
+ insert(rule, index = this.rules.length) {
151
+ const hadNative = !!this.native?.parentStyleSheet;
152
+ const wasEmpty = this.rules.length === 0;
153
+ const insertedIndex = super.insert(rule, index);
154
+ if (insertedIndex === void 0 || !this.native) return;
155
+ const nativeInsertIndex = this.getNativeInsertIndex(insertedIndex);
156
+ const wasAttachedWithRule = !hadNative && wasEmpty;
157
+ const insertRuleSafely = (text, position) => {
158
+ if (wasAttachedWithRule) return this.native.cssRules.item(position);
159
+ else try {
160
+ const insertedIndex = this.native.insertRule(text, position);
161
+ return this.native.cssRules.item(insertedIndex);
162
+ } catch (error) {
163
+ console.error(error, rule);
164
+ /**
165
+ * If the rule is invalid, remove it from the rules array.
166
+ * It's important to note that the rule may break the entire CSS runtime,
167
+ */
168
+ this.rules.splice(insertedIndex, 1);
169
+ return;
170
+ }
171
+ };
172
+ const nodes = getRuleNodes(rule);
173
+ if (nodes) {
174
+ let currentIndex = nativeInsertIndex;
175
+ nodes.forEach((node) => {
176
+ node.native = insertRuleSafely(node.text, currentIndex);
177
+ if (node.native) currentIndex++;
178
+ });
179
+ } else rule.native = insertRuleSafely(rule.text, nativeInsertIndex);
180
+ return insertedIndex;
181
+ }
182
+ getNativeInsertIndex(index) {
183
+ let nativeIndex = 0;
184
+ for (let i = 0; i < index; i++) {
185
+ const rule = this.rules[i];
186
+ nativeIndex += getRuleNodes(rule)?.length ?? 1;
187
+ }
188
+ return nativeIndex;
189
+ }
190
+ detach() {
191
+ super.detach();
192
+ const nativeSheet = this.cssRuntime.style?.sheet;
193
+ if (nativeSheet && this.native?.parentStyleSheet) {
194
+ const foundIndex = findNativeCSSRuleIndex(nativeSheet.cssRules, this.native);
195
+ if (foundIndex !== -1) nativeSheet.deleteRule(foundIndex);
196
+ }
197
+ }
198
+ delete(key) {
199
+ const deletedRule = super.delete(key);
200
+ if (!deletedRule || !this.native) return;
201
+ const deleteRuleSafely = (rule) => {
202
+ if (!rule) return;
203
+ const foundIndex = findNativeCSSRuleIndex(this.native.cssRules, rule);
204
+ if (foundIndex !== -1) try {
205
+ this.native.deleteRule(foundIndex);
206
+ } catch (error) {
207
+ console.error(error, rule);
208
+ }
209
+ };
210
+ const nodes = getRuleNodes(deletedRule);
211
+ if (nodes) nodes.forEach((node) => deleteRuleSafely(node.native));
212
+ else deleteRuleSafely(deletedRule.native);
213
+ return deletedRule;
214
+ }
215
+ reset() {
216
+ super.reset();
217
+ const nativeSheet = this.cssRuntime.style?.sheet;
218
+ if (this.native && nativeSheet) {
219
+ const foundIndex = findNativeCSSRuleIndex(nativeSheet.cssRules, this.native);
220
+ if (foundIndex !== -1) nativeSheet.deleteRule(foundIndex);
221
+ this.native = null;
222
+ }
223
+ }
224
+ };
225
+ //#endregion
226
+ //#region src/utility-layer.ts
227
+ function findUtilityInsertIndex(rules, utility) {
228
+ let low = 0;
229
+ let high = rules.length;
230
+ while (low < high) {
231
+ const mid = low + high >> 1;
232
+ const rule = rules[mid];
233
+ if (!("priority" in rule)) return findUtilityInsertIndexLinear(rules, utility);
234
+ if (compareRulePriority(utility, rule) < 0) high = mid;
235
+ else low = mid + 1;
236
+ }
237
+ return low;
238
+ }
239
+ function findUtilityInsertIndexLinear(rules, utility) {
240
+ for (let i = 0; i < rules.length; i++) {
241
+ const rule = rules[i];
242
+ if (!("priority" in rule)) continue;
243
+ if (compareRulePriority(utility, rule) < 0) return i;
244
+ }
245
+ return rules.length;
246
+ }
247
+ var RuntimeUtilityLayer = class extends RuntimeLayer {
248
+ rules = [];
249
+ insert(utility) {
250
+ if (this.get(utility.key)) return;
251
+ if ("valid" in utility && !utility.valid) return;
252
+ let index = this.rules.length;
253
+ if ("priority" in utility) index = findUtilityInsertIndex(this.rules, utility);
254
+ const insertedIndex = super.insert(utility, index);
255
+ if (insertedIndex === void 0) return;
256
+ this.insertVariables(utility);
257
+ this.insertAnimations(utility);
258
+ return insertedIndex;
259
+ }
260
+ delete(key) {
261
+ const utility = super.delete(key);
262
+ if (!utility) return;
263
+ const deleteLayerToken = (layerToken, layer, visited = /* @__PURE__ */ new Set()) => {
264
+ if (visited.has(layerToken)) return;
265
+ visited.add(layerToken);
266
+ const count = layer.tokenCounts.get(layerToken) ?? 0;
267
+ const variable = layer === this.css.themeLayer ? this.css.variables.get(layerToken) : void 0;
268
+ if (count <= 1) {
269
+ const deletedRule = layer.delete(layerToken);
270
+ layer.tokenCounts.delete(layerToken);
271
+ variable?.dependencies?.forEach((dependency) => deleteLayerToken(dependency, layer, visited));
272
+ return deletedRule;
273
+ } else {
274
+ layer.tokenCounts.set(layerToken, count - 1);
275
+ variable?.dependencies?.forEach((dependency) => deleteLayerToken(dependency, layer, visited));
276
+ }
277
+ };
278
+ if ("variableNames" in utility) utility.variableNames?.forEach((eachVariableName) => {
279
+ deleteLayerToken(eachVariableName, this.css.themeLayer);
280
+ });
281
+ if ("animationNames" in utility) utility.animationNames?.forEach((eachAnimationName) => {
282
+ const deletedAnimationRule = deleteLayerToken(eachAnimationName, this.css.animationsNonLayer);
283
+ const variableNames = deletedAnimationRule && "variableNames" in deletedAnimationRule ? deletedAnimationRule.variableNames : void 0;
284
+ if (variableNames) variableNames.forEach((eachVariableName) => {
285
+ deleteLayerToken(eachVariableName, this.css.themeLayer);
286
+ });
287
+ });
288
+ return utility;
289
+ }
290
+ insertVariables(utility) {
291
+ if (!("variableNames" in utility)) return;
292
+ const insertVariable = (eachVariableName, visited = /* @__PURE__ */ new Set()) => {
293
+ if (visited.has(eachVariableName)) return;
294
+ visited.add(eachVariableName);
295
+ const variable = this.css.variables.get(eachVariableName);
296
+ if (!variable || variable.inline) return;
297
+ if (this.css.themeLayer.rules.find(({ name }) => name === eachVariableName) || this.css.isEmittedGlobalsVariable(eachVariableName)) {
298
+ const count = this.css.themeLayer.tokenCounts.get(eachVariableName) || 0;
299
+ this.css.themeLayer.tokenCounts.set(eachVariableName, count + 1);
300
+ } else {
301
+ const newRule = new VariableRule(eachVariableName, variable, this.css);
302
+ this.css.themeLayer.insert(newRule);
303
+ this.css.themeLayer.tokenCounts.set(eachVariableName, 1);
304
+ }
305
+ variable.dependencies?.forEach((dependency) => insertVariable(dependency, visited));
306
+ };
307
+ utility.variableNames?.forEach((eachVariableName) => insertVariable(eachVariableName));
308
+ }
309
+ insertAnimations(utility) {
310
+ if (!("animationNames" in utility)) return;
311
+ utility.animationNames?.forEach((eachAnimationName) => {
312
+ const animationRule = this.css.animationsNonLayer.rules.find(({ name }) => name === eachAnimationName);
313
+ if (animationRule || this.css.isEmittedGlobalsAnimation(eachAnimationName)) {
314
+ const count = this.css.animationsNonLayer.tokenCounts.get(eachAnimationName) || 0;
315
+ this.css.animationsNonLayer.tokenCounts.set(eachAnimationName, count + 1);
316
+ if (animationRule) this.insertVariables(animationRule);
317
+ } else {
318
+ const keyframes = this.css.animations.get(eachAnimationName);
319
+ if (!keyframes) return;
320
+ const newRule = new AnimationRule(eachAnimationName, keyframes, this.css);
321
+ this.css.animationsNonLayer.insert(newRule);
322
+ this.css.animationsNonLayer.tokenCounts.set(eachAnimationName, 1);
323
+ this.insertVariables(newRule);
324
+ }
325
+ });
326
+ }
327
+ };
328
+ //#endregion
329
+ //#region src/theme-layer.ts
330
+ var RuntimeThemeLayer = class extends ThemeLayer {
331
+ name;
332
+ cssRuntime;
333
+ native = null;
334
+ nativeBuckets = /* @__PURE__ */ new Map();
335
+ constructor(name, cssRuntime) {
336
+ super(name, cssRuntime);
337
+ this.name = name;
338
+ this.cssRuntime = cssRuntime;
339
+ }
340
+ attach() {
341
+ super.attach();
342
+ const nativeSheet = this.cssRuntime.style?.sheet;
343
+ if (nativeSheet && !this.native?.parentStyleSheet) {
344
+ const insertedIndex = nativeSheet.insertRule(this.text, nativeSheet.cssRules.length);
345
+ this.native = nativeSheet.cssRules.item(insertedIndex);
346
+ this.syncNativeBuckets();
347
+ }
348
+ }
349
+ getBucketKey(mediaText, selectorText) {
350
+ const normalizedMediaText = mediaText.replace(/\s*:\s*/g, ":").replace(/\s+/g, " ").trim();
351
+ const normalizedSelectorText = selectorText.replace(/\s*,\s*/g, ",").replace(/\s+/g, " ").trim();
352
+ return normalizedMediaText + "\n" + normalizedSelectorText;
353
+ }
354
+ setBucketSyntheticDeclarations(bucket, mode) {
355
+ for (const { name, value } of this.getBucketSyntheticDeclarations({
356
+ mediaText: bucket.mediaText,
357
+ mode,
358
+ selectorText: bucket.selectorText
359
+ })) bucket.styleRule.style.setProperty(name, value);
360
+ }
361
+ hasVariableDeclarations(styleRule) {
362
+ for (let index = 0; index < styleRule.style.length; index++) if (styleRule.style.item(index).startsWith("--")) return true;
363
+ return false;
364
+ }
365
+ getStyleRule(nativeRule) {
366
+ if (nativeRule instanceof CSSStyleRule) return nativeRule;
367
+ if (nativeRule instanceof CSSGroupingRule) return nativeRule.cssRules.item(0);
368
+ }
369
+ syncNativeBuckets() {
370
+ this.nativeBuckets.clear();
371
+ if (!this.native) return;
372
+ for (const nativeRule of this.native.cssRules) {
373
+ const styleRule = this.getStyleRule(nativeRule);
374
+ if (!styleRule) continue;
375
+ const mediaText = nativeRule instanceof CSSMediaRule ? nativeRule.conditionText : "";
376
+ const normalizedMediaText = mediaText ? `@media ${mediaText}` : "";
377
+ const key = this.getBucketKey(normalizedMediaText, styleRule.selectorText);
378
+ this.nativeBuckets.set(key, {
379
+ key,
380
+ mediaText: normalizedMediaText,
381
+ selectorText: styleRule.selectorText,
382
+ nativeRule,
383
+ styleRule
384
+ });
385
+ }
386
+ }
387
+ ensureNativeBucket(mediaText, selectorText, mode) {
388
+ if (!this.native) return;
389
+ const key = this.getBucketKey(mediaText, selectorText);
390
+ let bucket = this.nativeBuckets.get(key);
391
+ if (bucket) {
392
+ this.setBucketSyntheticDeclarations(bucket, mode);
393
+ return bucket;
394
+ }
395
+ const declarationText = this.getBucketSyntheticDeclarations({
396
+ mediaText,
397
+ mode,
398
+ selectorText
399
+ }).map(({ name, value }) => `${name}:${value}`).join(";");
400
+ const text = mediaText ? `${mediaText}{${selectorText}{${declarationText}}}` : `${selectorText}{${declarationText}}`;
401
+ const insertedIndex = this.native.insertRule(text, this.getNativeBucketInsertIndex(mediaText, selectorText));
402
+ const nativeRule = this.native.cssRules.item(insertedIndex);
403
+ if (!nativeRule) return;
404
+ const styleRule = this.getStyleRule(nativeRule);
405
+ if (!styleRule) return;
406
+ const newBucket = {
407
+ key,
408
+ mediaText,
409
+ mode,
410
+ selectorText,
411
+ nativeRule,
412
+ styleRule
413
+ };
414
+ this.nativeBuckets.set(key, newBucket);
415
+ return newBucket;
416
+ }
417
+ getNativeBucketInsertIndex(mediaText, selectorText) {
418
+ if (!this.native) return 0;
419
+ const bucket = {
420
+ mediaText,
421
+ selectorText
422
+ };
423
+ for (let index = 0; index < this.native.cssRules.length; index++) {
424
+ const nativeRule = this.native.cssRules.item(index);
425
+ if (!nativeRule) continue;
426
+ const styleRule = this.getStyleRule(nativeRule);
427
+ if (!styleRule) continue;
428
+ const nativeMediaText = nativeRule instanceof CSSMediaRule ? `@media ${nativeRule.conditionText}` : "";
429
+ if (this.shouldInsertBucketBefore(bucket, {
430
+ mediaText: nativeMediaText,
431
+ selectorText: styleRule.selectorText
432
+ })) return index;
433
+ }
434
+ return this.native.cssRules.length;
435
+ }
436
+ insert(rule, index = this.rules.length) {
437
+ const wasEmpty = this.rules.length === 0;
438
+ const insertedIndex = super.insert(rule, index);
439
+ if (insertedIndex === void 0 || !this.native || wasEmpty) return insertedIndex;
440
+ for (const node of rule.nodes) {
441
+ const bucket = this.ensureNativeBucket(node.mediaText, node.selectorText, node.mode);
442
+ if (bucket) {
443
+ this.setBucketSyntheticDeclarations(bucket, node.mode);
444
+ bucket.styleRule.style.setProperty(node.declarationName, node.declarationValue);
445
+ node.native = bucket.styleRule;
446
+ }
447
+ }
448
+ return insertedIndex;
449
+ }
450
+ delete(key) {
451
+ const rule = this.rules.find((rule) => rule.key === key);
452
+ const deletedRule = super.delete(key);
453
+ if (!rule || !deletedRule || !this.native) return deletedRule;
454
+ for (const node of rule.nodes) {
455
+ const bucketKey = this.getBucketKey(node.mediaText, node.selectorText);
456
+ const bucket = this.nativeBuckets.get(bucketKey);
457
+ if (!bucket) continue;
458
+ bucket.styleRule.style.removeProperty(node.declarationName);
459
+ if (!this.hasVariableDeclarations(bucket.styleRule)) {
460
+ const foundIndex = findNativeCSSRuleIndex(this.native.cssRules, bucket.nativeRule);
461
+ if (foundIndex !== -1) this.native.deleteRule(foundIndex);
462
+ this.nativeBuckets.delete(bucketKey);
463
+ }
464
+ }
465
+ return deletedRule;
466
+ }
467
+ detach() {
468
+ super.detach();
469
+ const nativeSheet = this.cssRuntime.style?.sheet;
470
+ if (nativeSheet && this.native?.parentStyleSheet) {
471
+ const foundIndex = findNativeCSSRuleIndex(nativeSheet.cssRules, this.native);
472
+ if (foundIndex !== -1) nativeSheet.deleteRule(foundIndex);
473
+ }
474
+ this.native = null;
475
+ this.nativeBuckets.clear();
476
+ }
477
+ reset() {
478
+ super.reset();
479
+ const nativeSheet = this.cssRuntime.style?.sheet;
480
+ if (this.native && nativeSheet) {
481
+ const foundIndex = findNativeCSSRuleIndex(nativeSheet.cssRules, this.native);
482
+ if (foundIndex !== -1) nativeSheet.deleteRule(foundIndex);
483
+ }
484
+ this.native = null;
485
+ this.nativeBuckets.clear();
486
+ }
487
+ };
488
+ //#endregion
489
+ //#region src/class-tracker.ts
490
+ function updateClassDelta(deltaCounts, className, delta) {
491
+ const nextDelta = (deltaCounts.get(className) || 0) + delta;
492
+ if (nextDelta) deltaCounts.set(className, nextDelta);
493
+ else deltaCounts.delete(className);
494
+ }
495
+ function traverseElementSubtree(root, visited, callback) {
496
+ const stack = [root];
497
+ while (stack.length) {
498
+ const el = stack.pop();
499
+ if (visited.has(el)) continue;
500
+ visited.add(el);
501
+ callback(el);
502
+ for (let child = el.lastElementChild; child; child = child.previousElementSibling) stack.push(child);
503
+ }
504
+ }
505
+ var RuntimeClassTracker = class {
506
+ snapshots = /* @__PURE__ */ new WeakMap();
507
+ reset() {
508
+ this.snapshots = /* @__PURE__ */ new WeakMap();
509
+ }
510
+ collectConnected(root, classCounts) {
511
+ this.reset();
512
+ const connectedNames = /* @__PURE__ */ new Set();
513
+ for (const el of root.querySelectorAll("[class]")) {
514
+ const classNames = this.snapshotElement(el);
515
+ if (!classNames) continue;
516
+ for (const className of classNames) {
517
+ const count = classCounts.get(className) || 0;
518
+ if (!count) connectedNames.add(className);
519
+ classCounts.set(className, count + 1);
520
+ }
521
+ }
522
+ return connectedNames;
523
+ }
524
+ collectMutations(records) {
525
+ const deltaCounts = /* @__PURE__ */ new Map();
526
+ const nodeCounts = /* @__PURE__ */ new Map();
527
+ const attrRecords = /* @__PURE__ */ new Set();
528
+ const visited = /* @__PURE__ */ new WeakSet();
529
+ const updateNodeCount = (el, delta) => {
530
+ const nextCount = (nodeCounts.get(el) || 0) + delta;
531
+ if (nextCount) nodeCounts.set(el, nextCount);
532
+ else nodeCounts.delete(el);
533
+ };
534
+ for (const record of records) if (record.type === "childList") {
535
+ for (const node of record.addedNodes) if (node instanceof Element && node.isConnected) updateNodeCount(node, 1);
536
+ for (const node of record.removedNodes) if (node instanceof Element && !node.isConnected) updateNodeCount(node, -1);
537
+ } else if (record.type === "attributes" && record.attributeName === "class") {
538
+ const target = record.target;
539
+ if (target instanceof Element) attrRecords.add(target);
540
+ }
541
+ for (const [node, count] of nodeCounts) if (count > 0) traverseElementSubtree(node, visited, (el) => this.diffElement(el, deltaCounts));
542
+ else if (count < 0 && !node.isConnected) traverseElementSubtree(node, visited, (el) => this.removeElement(el, deltaCounts));
543
+ for (const el of attrRecords) if (!visited.has(el)) this.diffElement(el, deltaCounts);
544
+ return deltaCounts;
545
+ }
546
+ snapshotElement(el) {
547
+ const classList = el.classList;
548
+ if (!classList.length) {
549
+ this.snapshots.delete(el);
550
+ return;
551
+ }
552
+ const classNames = /* @__PURE__ */ new Set();
553
+ for (let i = 0; i < classList.length; i++) classNames.add(classList.item(i));
554
+ this.snapshots.set(el, classNames);
555
+ return classNames;
556
+ }
557
+ diffElement(el, deltaCounts) {
558
+ const previousClassNames = this.snapshots.get(el);
559
+ const classList = el.classList;
560
+ let nextClassNames;
561
+ for (let i = 0; i < classList.length; i++) {
562
+ const className = classList.item(i);
563
+ if (!previousClassNames?.has(className)) updateClassDelta(deltaCounts, className, 1);
564
+ (nextClassNames ??= /* @__PURE__ */ new Set()).add(className);
565
+ }
566
+ if (previousClassNames) {
567
+ for (const className of previousClassNames) if (!nextClassNames?.has(className)) updateClassDelta(deltaCounts, className, -1);
568
+ }
569
+ if (nextClassNames) this.snapshots.set(el, nextClassNames);
570
+ else this.snapshots.delete(el);
571
+ }
572
+ removeElement(el, deltaCounts) {
573
+ const previousClassNames = this.snapshots.get(el);
574
+ if (!previousClassNames) return;
575
+ for (const className of previousClassNames) updateClassDelta(deltaCounts, className, -1);
576
+ this.snapshots.delete(el);
577
+ }
578
+ };
579
+ //#endregion
580
+ //#region src/generated-rule.ts
581
+ function collectVariableNames(text) {
582
+ const variableNames = /* @__PURE__ */ new Set();
583
+ for (const match of text.matchAll(/var\(\s*--([_a-zA-Z0-9-]+)/g)) variableNames.add(match[1]);
584
+ return variableNames;
585
+ }
586
+ var HydratedGeneratedRuleNode = class {
587
+ text;
588
+ native;
589
+ constructor(text) {
590
+ this.text = text;
591
+ }
592
+ };
593
+ var HydratedGeneratedRule = class {
594
+ ir;
595
+ layer;
596
+ native;
597
+ name;
598
+ key;
599
+ layerName;
600
+ type;
601
+ sortTier;
602
+ priority;
603
+ text;
604
+ valid = true;
605
+ fixedClass;
606
+ nodes;
607
+ variableNames;
608
+ animationNames;
609
+ selectorText;
610
+ constructor(ir, layer) {
611
+ this.ir = ir;
612
+ this.layer = layer;
613
+ this.name = ir.className;
614
+ this.key = ir.key;
615
+ this.layerName = ir.layer;
616
+ this.type = ir.type;
617
+ this.sortTier = ir.sortTier;
618
+ this.priority = ir.priority;
619
+ this.text = ir.text;
620
+ this.selectorText = ir.selectorText;
621
+ if (ir.nodes?.length) this.nodes = ir.nodes.map((node) => new HydratedGeneratedRuleNode(node.text));
622
+ const variableNames = collectVariableNames(ir.text);
623
+ ir.nodes?.forEach((node) => {
624
+ collectVariableNames(node.text).forEach((variableName) => variableNames.add(variableName));
625
+ });
626
+ ir.variableNames?.forEach((variableName) => variableNames.add(variableName));
627
+ if (variableNames.size) this.variableNames = variableNames;
628
+ if (ir.animationNames?.length) this.animationNames = new Set(ir.animationNames);
629
+ }
630
+ };
631
+ //#endregion
632
+ //#region src/native-declaration.ts
633
+ const supportsCache = /* @__PURE__ */ new Map();
634
+ const browserNativeDeclarationMatcher = ({ property, value }) => {
635
+ if (property.startsWith("--")) return true;
636
+ const cacheKey = property + "\0" + value;
637
+ const cached = supportsCache.get(cacheKey);
638
+ if (cached !== void 0) return cached;
639
+ const supported = Boolean(globalThis.CSS?.supports(property, value));
640
+ supportsCache.set(cacheKey, supported);
641
+ return supported;
642
+ };
643
+ //#endregion
644
+ //#region src/core.ts
645
+ const MASTER_CSS_RUNTIME_STYLE_SELECTOR = `style#${MASTER_CSS_RUNTIME_STYLE_ID}`;
646
+ function isDocumentRoot(root) {
647
+ const rootConstructorName = root?.constructor.name;
648
+ return rootConstructorName === "HTMLDocument" || rootConstructorName === "Document";
649
+ }
650
+ function findElementById(root, id) {
651
+ return isDocumentRoot(root) ? root.getElementById(id) : "querySelector" in root ? root.querySelector(`#${id}`) : void 0;
652
+ }
653
+ function parseHydrationManifest(source) {
654
+ try {
655
+ const hydrationManifest = JSON.parse(source);
656
+ return hydrationManifest?.version === 1 && Array.isArray(hydrationManifest.rules) ? hydrationManifest : void 0;
657
+ } catch (error) {
658
+ console.debug("Cannot parse Master CSS hydration manifest.", error);
659
+ }
660
+ }
661
+ function readInlineHydrationManifest(root) {
662
+ const source = findElementById(root, MASTER_CSS_HYDRATION_MANIFEST_SCRIPT_ID)?.textContent?.trim();
663
+ if (!source) return;
664
+ return parseHydrationManifest(source);
665
+ }
666
+ function readExternalHydrationManifestSource(root) {
667
+ const styleElement = findElementById(root, MASTER_CSS_RUNTIME_STYLE_ID);
668
+ const HTMLStyleElementConstructor = globalThis.HTMLStyleElement;
669
+ return HTMLStyleElementConstructor && styleElement instanceof HTMLStyleElementConstructor ? styleElement.getAttribute(MASTER_CSS_HYDRATION_MANIFEST_ATTR) : void 0;
670
+ }
671
+ var CSSRuntime = class CSSRuntime extends MasterCSS {
672
+ root;
673
+ hydrationManifest;
674
+ static instances = /* @__PURE__ */ new WeakMap();
675
+ host;
676
+ container;
677
+ baseLayer = new RuntimeUtilityLayer("base", this);
678
+ themeLayer = new RuntimeThemeLayer("theme", this);
679
+ defaultsLayer = new RuntimeUtilityLayer("defaults", this);
680
+ componentsLayer = new RuntimeUtilityLayer("components", this);
681
+ utilitiesLayer = new RuntimeUtilityLayer("utilities", this);
682
+ classCounts = /* @__PURE__ */ new Map();
683
+ classTracker = new RuntimeClassTracker();
684
+ pendingRemovedClassNames = /* @__PURE__ */ new Set();
685
+ pendingRemovalFrame;
686
+ pendingRemovalFlushFrame;
687
+ hydrationFailureReason;
688
+ observer;
689
+ progressive = false;
690
+ observing = false;
691
+ static create(options) {
692
+ const { manifest, root = document, emittedGlobals, hydrationManifest } = options;
693
+ const resolvedHydrationManifest = hydrationManifest === void 0 ? readInlineHydrationManifest(root) : hydrationManifest;
694
+ const current = globalThis.MasterCSSRuntime.instances.get(root);
695
+ if (current) {
696
+ current.registerEmittedGlobals(emittedGlobals);
697
+ if (resolvedHydrationManifest !== void 0) current.setHydrationManifest(resolvedHydrationManifest);
698
+ return current;
699
+ }
700
+ return new CSSRuntime(root, manifest, emittedGlobals, resolvedHydrationManifest).register();
701
+ }
702
+ constructor(root = document, manifest, emittedGlobals, hydrationManifest) {
703
+ super(manifest, emittedGlobals, { nativeDeclarationMatcher: browserNativeDeclarationMatcher });
704
+ this.root = root;
705
+ this.hydrationManifest = hydrationManifest;
706
+ if (isDocumentRoot(root)) {
707
+ this.container = root.head;
708
+ this.host = root.documentElement;
709
+ } else {
710
+ this.container = this.root;
711
+ this.host = this.root.host;
712
+ }
713
+ this.applyEmittedGlobalsCounts({ variables: this.emittedGlobals.variables });
714
+ }
715
+ register() {
716
+ const registered = globalThis.MasterCSSRuntime.instances.get(this.root) === this;
717
+ globalThis.MasterCSSRuntime.instances.set(this.root, this);
718
+ if (isDocumentRoot(this.root)) this.root.defaultView.globalThis.masterCSSRuntime = this;
719
+ if (!registered && true) debugRuntimeCreated(this);
720
+ return this;
721
+ }
722
+ unregister() {
723
+ globalThis.MasterCSSRuntime.instances.delete(this.root);
724
+ if (isDocumentRoot(this.root) && this.root.defaultView.globalThis.masterCSSRuntime === this) this.root.defaultView.globalThis.masterCSSRuntime = void 0;
725
+ return this;
726
+ }
727
+ setHydrationManifest(hydrationManifest) {
728
+ this.hydrationManifest = hydrationManifest;
729
+ return this;
730
+ }
731
+ needsHydrationManifest() {
732
+ return this.hydrationManifest === void 0 && Boolean(readExternalHydrationManifestSource(this.root));
733
+ }
734
+ async loadHydrationManifest() {
735
+ const inlineHydrationManifest = readInlineHydrationManifest(this.root);
736
+ if (inlineHydrationManifest) {
737
+ this.setHydrationManifest(inlineHydrationManifest);
738
+ return this;
739
+ }
740
+ const source = readExternalHydrationManifestSource(this.root);
741
+ if (!source) return this;
742
+ try {
743
+ const response = await fetch(source, { credentials: "same-origin" });
744
+ if (!response.ok) return this;
745
+ this.setHydrationManifest(parseHydrationManifest(await response.text()));
746
+ } catch (error) {
747
+ console.debug("Cannot load Master CSS hydration manifest.", error);
748
+ }
749
+ return this;
750
+ }
751
+ createRuntimeStyle() {
752
+ const ownerDocument = "createElement" in this.root ? this.root : this.root.ownerDocument;
753
+ this.style = ownerDocument.createElement("style");
754
+ this.style.id = MASTER_CSS_RUNTIME_STYLE_ID;
755
+ this.style.setAttribute("blocking", "render");
756
+ this.container.append(this.style);
757
+ }
758
+ warnHydrationFallback(reason) {
759
+ console.warn(`Master CSS progressive hydration requires a matching hydration manifest. ${reason} Rebuilding ${MASTER_CSS_RUNTIME_STYLE_SELECTOR} with the runtime.`);
760
+ }
761
+ useRuntimeStyle(connectedNames, reason) {
762
+ if (reason) this.warnHydrationFallback(reason);
763
+ this.style?.remove();
764
+ this.style = null;
765
+ this.progressive = false;
766
+ this.createRuntimeStyle();
767
+ this.insertStaticResources();
768
+ connectedNames.forEach((cls) => this.add(cls));
769
+ }
770
+ detectRuntimeStyle() {
771
+ if (this.root.styleSheets) for (const sheet of this.root.styleSheets) {
772
+ const { ownerNode } = sheet;
773
+ if (ownerNode instanceof HTMLStyleElement && ownerNode.id === MASTER_CSS_RUNTIME_STYLE_ID) {
774
+ this.style = ownerNode;
775
+ this.progressive = true;
776
+ break;
777
+ }
778
+ }
779
+ }
780
+ collectConnectedClasses() {
781
+ return this.classTracker.collectConnected(this.root, this.classCounts);
782
+ }
783
+ hydrateRuntimeStyle(connectedNames) {
784
+ const hydrateResult = this.style?.sheet && this.hydrate(this.style.sheet.cssRules);
785
+ if (hydrateResult) {
786
+ const hydratedClassNames = new Set(hydrateResult.allUtilities.map(({ fixedClass, name }) => fixedClass || name));
787
+ for (const cls of connectedNames) if (!hydratedClassNames.has(cls)) {
788
+ this.add(cls);
789
+ console.debug(`Missing prerendered rule for class \`${cls}\``);
790
+ }
791
+ } else this.useRuntimeStyle(connectedNames, this.hydrationFailureReason || `Cannot read ${MASTER_CSS_RUNTIME_STYLE_SELECTOR} CSS rules.`);
792
+ }
793
+ renderRuntimeStyle(connectedNames) {
794
+ this.createRuntimeStyle();
795
+ this.insertStaticResources();
796
+ connectedNames.forEach((cls) => this.add(cls));
797
+ }
798
+ getAnimationFrameWindow() {
799
+ return (isDocumentRoot(this.root) ? this.root : this.root.ownerDocument)?.defaultView || globalThis;
800
+ }
801
+ cancelPendingRemovalFrames() {
802
+ const view = this.getAnimationFrameWindow();
803
+ if (this.pendingRemovalFrame !== void 0) {
804
+ view.cancelAnimationFrame(this.pendingRemovalFrame);
805
+ this.pendingRemovalFrame = void 0;
806
+ }
807
+ if (this.pendingRemovalFlushFrame !== void 0) {
808
+ view.cancelAnimationFrame(this.pendingRemovalFlushFrame);
809
+ this.pendingRemovalFlushFrame = void 0;
810
+ }
811
+ }
812
+ clearPendingRemovedClassNames() {
813
+ this.pendingRemovedClassNames.clear();
814
+ this.cancelPendingRemovalFrames();
815
+ }
816
+ cancelPendingRemovedClassNames(classNames) {
817
+ if (!this.pendingRemovedClassNames.size) return;
818
+ for (const className of classNames) this.pendingRemovedClassNames.delete(className);
819
+ if (!this.pendingRemovedClassNames.size) this.cancelPendingRemovalFrames();
820
+ }
821
+ schedulePendingRemovalFlush() {
822
+ if (!this.pendingRemovedClassNames.size) return;
823
+ if (this.pendingRemovalFrame !== void 0 || this.pendingRemovalFlushFrame !== void 0) return;
824
+ const view = this.getAnimationFrameWindow();
825
+ this.pendingRemovalFrame = view.requestAnimationFrame(() => {
826
+ this.pendingRemovalFrame = void 0;
827
+ this.pendingRemovalFlushFrame = view.requestAnimationFrame(() => {
828
+ this.pendingRemovalFlushFrame = void 0;
829
+ this.flushPendingRemovedClassNames();
830
+ });
831
+ });
832
+ }
833
+ queueRemovedClassNames(classNames) {
834
+ for (const className of classNames) if (!this.classCounts.has(className)) this.pendingRemovedClassNames.add(className);
835
+ this.schedulePendingRemovalFlush();
836
+ }
837
+ flushPendingRemovedClassNames() {
838
+ if (!this.pendingRemovedClassNames.size) return;
839
+ const classNames = [];
840
+ for (const className of this.pendingRemovedClassNames) if (!this.classCounts.has(className)) classNames.push(className);
841
+ this.pendingRemovedClassNames.clear();
842
+ if (classNames.length) super.remove(...classNames);
843
+ }
844
+ handleMutationRecords(records) {
845
+ const deltaCounts = this.classTracker.collectMutations(records);
846
+ const addedClassNames = [];
847
+ const removedClassNames = [];
848
+ for (const [cls, change] of deltaCounts) {
849
+ const current = this.classCounts.get(cls) || 0;
850
+ const next = current + change;
851
+ if (next > 0) {
852
+ this.classCounts.set(cls, next);
853
+ if (current === 0) addedClassNames.push(cls);
854
+ } else {
855
+ this.classCounts.delete(cls);
856
+ removedClassNames.push(cls);
857
+ }
858
+ }
859
+ if (addedClassNames.length) this.add(...addedClassNames);
860
+ if (removedClassNames.length) this.queueRemovedClassNames(removedClassNames);
861
+ debugRuntimeMutation(records, deltaCounts, this);
862
+ }
863
+ add(...classNames) {
864
+ this.cancelPendingRemovedClassNames(classNames);
865
+ return super.add(...classNames);
866
+ }
867
+ remove(...classNames) {
868
+ this.cancelPendingRemovedClassNames(classNames);
869
+ super.remove(...classNames);
870
+ }
871
+ startMutationObserver() {
872
+ this.observer = new MutationObserver((records) => this.handleMutationRecords(records));
873
+ this.observer.observe(this.root, {
874
+ childList: true,
875
+ attributes: true,
876
+ attributeFilter: ["class"],
877
+ subtree: true
878
+ });
879
+ }
880
+ revealHostIfNeeded() {
881
+ if (!this.progressive) this.host.removeAttribute("hidden");
882
+ }
883
+ /**
884
+ * Observe the DOM for changes and update the running stylesheet. (browser only)
885
+ * @param options mutation observer options
886
+ * @returns this
887
+ */
888
+ observe() {
889
+ if (this.observing) return this;
890
+ this.detectRuntimeStyle();
891
+ const connectedNames = this.collectConnectedClasses();
892
+ if (this.progressive) this.hydrateRuntimeStyle(connectedNames);
893
+ else this.renderRuntimeStyle(connectedNames);
894
+ this.startMutationObserver();
895
+ this.revealHostIfNeeded();
896
+ this.observing = true;
897
+ debugRuntimeObserved(this);
898
+ return this;
899
+ }
900
+ failHydration(reason) {
901
+ this.hydrationFailureReason = reason;
902
+ }
903
+ getHydrationManifestLayerRules() {
904
+ const layers = /* @__PURE__ */ new Map();
905
+ if (!this.hydrationManifest?.rules?.length) return layers;
906
+ for (const rule of this.hydrationManifest.rules) {
907
+ const layerRules = layers.get(rule.layer);
908
+ if (layerRules) layerRules.push(rule);
909
+ else layers.set(rule.layer, [rule]);
910
+ }
911
+ return layers;
912
+ }
913
+ registerHydratedClassRule(className, rule) {
914
+ const classUtilities = this.classUtilities;
915
+ const rules = classUtilities.get(className);
916
+ if (rules) rules.push(rule);
917
+ else classUtilities.set(className, [rule]);
918
+ }
919
+ getUtilityLayerByName(name) {
920
+ switch (name) {
921
+ case "base": return this.baseLayer;
922
+ case "defaults": return this.defaultsLayer;
923
+ case "components": return this.componentsLayer;
924
+ case "utilities": return this.utilitiesLayer;
925
+ }
926
+ }
927
+ collectHydrationManifestVariableNames() {
928
+ const variableNames = /* @__PURE__ */ new Set();
929
+ const collectVariableReferences = (text) => {
930
+ for (const match of text.matchAll(/var\(\s*--([_a-zA-Z0-9-]+)/g)) collectVariable(match[1]);
931
+ };
932
+ const collectVariable = (variableName, visited = /* @__PURE__ */ new Set()) => {
933
+ if (visited.has(variableName)) return;
934
+ visited.add(variableName);
935
+ const variable = this.variables.get(variableName);
936
+ if (!variable) return;
937
+ variableNames.add(variableName);
938
+ variable.dependencies?.forEach((dependency) => collectVariable(dependency, visited));
939
+ };
940
+ for (const rule of this.hydrationManifest?.rules || []) {
941
+ rule.variableNames?.forEach((variableName) => collectVariable(variableName));
942
+ collectVariableReferences(rule.text);
943
+ rule.nodes?.forEach((node) => collectVariableReferences(node.text));
944
+ rule.animationNames?.forEach((animationName) => {
945
+ const keyframes = this.animations.get(animationName);
946
+ if (!keyframes) return;
947
+ new AnimationRule(animationName, keyframes, this).variableNames?.forEach((variableName) => collectVariable(variableName));
948
+ });
949
+ }
950
+ for (const [variableName, variable] of this.variables) if (variable.static) collectVariable(variableName);
951
+ return variableNames;
952
+ }
953
+ collectHydrationManifestAnimationNames() {
954
+ const animationNames = /* @__PURE__ */ new Set();
955
+ for (const rule of this.hydrationManifest?.rules || []) rule.animationNames?.forEach((animationName) => animationNames.add(animationName));
956
+ for (const animationName of this.animations.keys()) if (this.manifest.animationOptions?.[animationName]?.static) animationNames.add(animationName);
957
+ return animationNames;
958
+ }
959
+ nativeThemeLayerHasOnlyEmittedGlobalsVariables(nativeThemeLayer) {
960
+ if (!nativeThemeLayer) return false;
961
+ let found = false;
962
+ for (const nativeRule of nativeThemeLayer.cssRules) {
963
+ const styleRule = this.themeLayer.getStyleRule(nativeRule);
964
+ if (!styleRule) return false;
965
+ for (let index = 0; index < styleRule.style.length; index++) {
966
+ const propertyName = styleRule.style.item(index);
967
+ if (this.isSyntheticColorSchemeDeclaration(nativeRule, styleRule, propertyName)) continue;
968
+ if (!propertyName.startsWith("--")) return false;
969
+ found = true;
970
+ if (!this.isEmittedGlobalsVariable(propertyName.slice(2))) return false;
971
+ }
972
+ }
973
+ return found;
974
+ }
975
+ getVariableRuleBuckets(variableRules) {
976
+ const buckets = /* @__PURE__ */ new Map();
977
+ for (const rule of variableRules) for (const node of rule.nodes) {
978
+ const key = this.themeLayer.getBucketKey(node.mediaText, node.selectorText);
979
+ let bucket = buckets.get(key);
980
+ if (!bucket) {
981
+ bucket = {
982
+ mediaText: node.mediaText,
983
+ mode: node.mode,
984
+ selectorText: node.selectorText,
985
+ nodes: []
986
+ };
987
+ buckets.set(key, bucket);
988
+ }
989
+ bucket.nodes.push(node);
990
+ }
991
+ return Array.from(buckets.values());
992
+ }
993
+ isSyntheticColorSchemeDeclaration(nativeRule, styleRule, propertyName) {
994
+ if (propertyName !== "color-scheme") return false;
995
+ const colorScheme = styleRule.style.getPropertyValue(propertyName).trim();
996
+ return colorScheme === this.themeLayer.getBucketColorScheme({
997
+ mediaText: nativeRule instanceof CSSMediaRule ? `@media ${nativeRule.conditionText}` : "",
998
+ mode: colorScheme,
999
+ selectorText: styleRule.selectorText
1000
+ });
1001
+ }
1002
+ getNativeThemeRuleBucketKey(nativeRule) {
1003
+ const styleRule = this.themeLayer.getStyleRule(nativeRule);
1004
+ if (!styleRule) return;
1005
+ const mediaText = nativeRule instanceof CSSMediaRule ? `@media ${nativeRule.conditionText}` : "";
1006
+ return {
1007
+ key: this.themeLayer.getBucketKey(mediaText, styleRule.selectorText),
1008
+ styleRule
1009
+ };
1010
+ }
1011
+ hydrateHydrationManifestVariables(nativeThemeLayer) {
1012
+ const variableRules = [...this.collectHydrationManifestVariableNames()].filter((variableName) => !this.isEmittedGlobalsVariable(variableName)).map((variableName) => {
1013
+ const variable = this.variables.get(variableName);
1014
+ return variable && !variable.inline ? new VariableRule(variableName, variable, this) : void 0;
1015
+ }).filter((rule) => Boolean(rule));
1016
+ const expectedBuckets = this.getVariableRuleBuckets(variableRules);
1017
+ const nativeRuleCount = nativeThemeLayer?.cssRules.length || 0;
1018
+ if (expectedBuckets.length !== nativeRuleCount) return !variableRules.length && this.nativeThemeLayerHasOnlyEmittedGlobalsVariables(nativeThemeLayer);
1019
+ if (!variableRules.length) return true;
1020
+ if (!nativeThemeLayer) return false;
1021
+ this.themeLayer.native = nativeThemeLayer;
1022
+ const nativeBuckets = /* @__PURE__ */ new Map();
1023
+ for (const nativeRule of nativeThemeLayer.cssRules) {
1024
+ const nativeBucket = this.getNativeThemeRuleBucketKey(nativeRule);
1025
+ if (!nativeBucket || nativeBuckets.has(nativeBucket.key)) return false;
1026
+ nativeBuckets.set(nativeBucket.key, nativeBucket.styleRule);
1027
+ }
1028
+ for (const bucket of expectedBuckets) {
1029
+ const nativeStyleRule = nativeBuckets.get(this.themeLayer.getBucketKey(bucket.mediaText, bucket.selectorText));
1030
+ if (!nativeStyleRule) return false;
1031
+ for (const node of bucket.nodes) node.native = nativeStyleRule;
1032
+ }
1033
+ this.themeLayer.rules.push(...variableRules);
1034
+ this.themeLayer.syncNativeBuckets();
1035
+ if (this.themeLayer.rules.length && !this.rules.includes(this.themeLayer)) this.rules.push(this.themeLayer);
1036
+ return true;
1037
+ }
1038
+ hydrateHydrationManifestAnimations(nativeKeyframesRules) {
1039
+ const animationNames = this.collectHydrationManifestAnimationNames();
1040
+ const hydratedAnimationNames = /* @__PURE__ */ new Set();
1041
+ for (const animationName of animationNames) {
1042
+ if (this.isEmittedGlobalsAnimation(animationName)) {
1043
+ if (nativeKeyframesRules.has(animationName)) hydratedAnimationNames.add(animationName);
1044
+ continue;
1045
+ }
1046
+ const keyframes = this.animations.get(animationName);
1047
+ if (!keyframes) continue;
1048
+ const nativeRule = nativeKeyframesRules.get(animationName);
1049
+ if (!nativeRule) return false;
1050
+ const animationRule = new AnimationRule(animationName, keyframes, this);
1051
+ animationRule.native = nativeRule;
1052
+ this.animationsNonLayer.rules.push(animationRule);
1053
+ this.rules.push(animationRule);
1054
+ hydratedAnimationNames.add(animationName);
1055
+ }
1056
+ for (const animationName of nativeKeyframesRules.keys()) if (!hydratedAnimationNames.has(animationName)) return false;
1057
+ return true;
1058
+ }
1059
+ hydrateHydrationManifestLayer(layer, nativeLayerRule, manifestRules, result) {
1060
+ if (manifestRules.reduce((count, rule) => count + (rule.nodes?.length || 1), 0) !== nativeLayerRule.cssRules.length) return false;
1061
+ layer.native = nativeLayerRule;
1062
+ let nativeIndex = 0;
1063
+ for (const manifestRule of manifestRules) {
1064
+ const hydratedRule = new HydratedGeneratedRule(manifestRule, layer);
1065
+ const nodes = hydratedRule.nodes;
1066
+ if (nodes?.length) for (const node of nodes) node.native = nativeLayerRule.cssRules.item(nativeIndex++) || void 0;
1067
+ else hydratedRule.native = nativeLayerRule.cssRules.item(nativeIndex++) || void 0;
1068
+ layer.rules.push(hydratedRule);
1069
+ layer.insertVariables(hydratedRule);
1070
+ layer.insertAnimations(hydratedRule);
1071
+ this.registerHydratedClassRule(manifestRule.className, hydratedRule);
1072
+ result.allUtilities.push(hydratedRule);
1073
+ }
1074
+ if (layer.rules.length && !this.rules.includes(layer)) this.rules.push(layer);
1075
+ return true;
1076
+ }
1077
+ hydrate(nativeLayerRules) {
1078
+ this.hydrationFailureReason = void 0;
1079
+ if (this.hydrationManifest?.version !== 1 || !Array.isArray(this.hydrationManifest.rules)) return this.failHydration("Missing or invalid hydration manifest.");
1080
+ if (!this.hydrationManifest.rules.length) return this.failHydration(`Hydration manifest has no generated rules for ${MASTER_CSS_RUNTIME_STYLE_SELECTOR}.`);
1081
+ const result = { allUtilities: [] };
1082
+ const manifestLayerRules = this.getHydrationManifestLayerRules();
1083
+ const nativeUtilityLayerRules = /* @__PURE__ */ new Map();
1084
+ const nativeKeyframesRules = /* @__PURE__ */ new Map();
1085
+ let nativeThemeLayer;
1086
+ for (let i = 0; i < nativeLayerRules.length; i++) {
1087
+ const eachNativeCSSRule = nativeLayerRules[i];
1088
+ if (eachNativeCSSRule.constructor.name === "CSSLayerBlockRule") {
1089
+ const eachCSSLayerRule = eachNativeCSSRule;
1090
+ if (eachCSSLayerRule.name === "theme") {
1091
+ if (nativeThemeLayer) return this.failHydration(`Duplicate theme layer in ${MASTER_CSS_RUNTIME_STYLE_SELECTOR}.`);
1092
+ nativeThemeLayer = eachCSSLayerRule;
1093
+ continue;
1094
+ }
1095
+ const layer = this.getUtilityLayerByName(eachCSSLayerRule.name);
1096
+ if (!layer) return this.failHydration(`Unknown layer \`${eachCSSLayerRule.name}\` in ${MASTER_CSS_RUNTIME_STYLE_SELECTOR}.`);
1097
+ if (nativeUtilityLayerRules.has(layer.name)) return this.failHydration(`Duplicate layer \`${eachCSSLayerRule.name}\` in ${MASTER_CSS_RUNTIME_STYLE_SELECTOR}.`);
1098
+ nativeUtilityLayerRules.set(layer.name, eachCSSLayerRule);
1099
+ } else if (eachNativeCSSRule.constructor.name === "CSSKeyframesRule") {
1100
+ const nativeKeyframesRule = eachNativeCSSRule;
1101
+ nativeKeyframesRules.set(nativeKeyframesRule.name, nativeKeyframesRule);
1102
+ } else return this.failHydration(`Unknown top-level rule \`${eachNativeCSSRule.cssText}\` in ${MASTER_CSS_RUNTIME_STYLE_SELECTOR}.`);
1103
+ }
1104
+ for (const [layerName, manifestRules] of manifestLayerRules) {
1105
+ const nativeLayerRule = nativeUtilityLayerRules.get(layerName);
1106
+ if (!nativeLayerRule) return this.failHydration(`Missing layer \`${layerName}\` in ${MASTER_CSS_RUNTIME_STYLE_SELECTOR}.`);
1107
+ if (manifestRules.reduce((count, rule) => count + (rule.nodes?.length || 1), 0) !== nativeLayerRule.cssRules.length) return this.failHydration(`Layer \`${layerName}\` does not match the hydration manifest.`);
1108
+ }
1109
+ for (const [layerName, nativeLayerRule] of nativeUtilityLayerRules) if (!manifestLayerRules.has(layerName) && nativeLayerRule.cssRules.length) return this.failHydration(`Layer \`${layerName}\` has no hydration manifest rules.`);
1110
+ if (!this.hydrateHydrationManifestVariables(nativeThemeLayer)) return this.failHydration("Theme layer does not match the hydration manifest.");
1111
+ if (!this.hydrateHydrationManifestAnimations(nativeKeyframesRules)) return this.failHydration("Keyframes do not match the hydration manifest.");
1112
+ for (const [layerName, nativeLayerRule] of nativeUtilityLayerRules) {
1113
+ const manifestRules = manifestLayerRules.get(layerName);
1114
+ if (!manifestRules?.length) continue;
1115
+ const layer = this.getUtilityLayerByName(layerName);
1116
+ this.hydrateHydrationManifestLayer(layer, nativeLayerRule, manifestRules, result);
1117
+ }
1118
+ debugRuntimeHydrated(this, result);
1119
+ return result;
1120
+ }
1121
+ disconnect() {
1122
+ this.clearPendingRemovedClassNames();
1123
+ if (!this.observing) return;
1124
+ if (this.observer) {
1125
+ this.observer.disconnect();
1126
+ this.observer = void 0;
1127
+ }
1128
+ this.observing = false;
1129
+ this.reset();
1130
+ this.loadManifest(this.manifest);
1131
+ this.classCounts.clear();
1132
+ this.classTracker.reset();
1133
+ if (!this.progressive) {
1134
+ this.style?.remove();
1135
+ this.style = null;
1136
+ }
1137
+ debugRuntimeDisconnected(this);
1138
+ return this;
1139
+ }
1140
+ refresh(manifest = this.manifest) {
1141
+ this.clearPendingRemovedClassNames();
1142
+ if (!this.observing || !this.style.sheet) return this;
1143
+ const cssRules = this.style.sheet.cssRules;
1144
+ for (let i = cssRules.length - 1; i >= 0; i--) this.style.sheet.deleteRule(i);
1145
+ super.refresh(manifest);
1146
+ /**
1147
+ * Recreate rules from the current class names against the latest manifest.
1148
+ * 所以 refresh 過後 rules 可能會變多也可能會變少
1149
+ */
1150
+ this.classCounts.forEach((_, className) => {
1151
+ this.add(className);
1152
+ });
1153
+ debugRuntimeRefreshed(this, manifest);
1154
+ return this;
1155
+ }
1156
+ destroy() {
1157
+ this.disconnect();
1158
+ this.unregister();
1159
+ debugRuntimeDestroyed(this);
1160
+ return this;
1161
+ }
1162
+ };
1163
+ (function(CSSRuntime) {
1164
+ registerGlobal(CSSRuntime);
1165
+ })(CSSRuntime);
1166
+ //#endregion
1167
+ //#region src/css-runtime.ts
1168
+ function resolveManifest(host, manifest) {
1169
+ return typeof manifest === "function" ? manifest(host) : manifest;
1170
+ }
1171
+ function resolveRoot(host, root) {
1172
+ return typeof root === "function" ? root(host) : root || host.shadowRoot;
1173
+ }
1174
+ function resolveEmittedGlobals(host, emittedGlobals) {
1175
+ return typeof emittedGlobals === "function" ? emittedGlobals(host) : emittedGlobals;
1176
+ }
1177
+ function resolveHydrationManifest(host, hydrationManifest) {
1178
+ return typeof hydrationManifest === "function" ? hydrationManifest(host) : hydrationManifest;
1179
+ }
1180
+ function cssRuntime(options) {
1181
+ return function(target) {
1182
+ const connectedCallback = target.prototype.connectedCallback;
1183
+ const disconnectedCallback = target.prototype.disconnectedCallback;
1184
+ return class extends target {
1185
+ cssRuntime;
1186
+ connectedCallback() {
1187
+ connectedCallback?.call(this);
1188
+ const root = resolveRoot(this, options.root);
1189
+ if (!root) throw new Error("`@cssRuntime()` requires a shadow root. Provide `options.root` or create a shadow root before `connectedCallback()` finishes.");
1190
+ const cssRuntime = CSSRuntime.create({
1191
+ manifest: resolveManifest(this, options.manifest),
1192
+ root,
1193
+ emittedGlobals: resolveEmittedGlobals(this, options.emittedGlobals),
1194
+ hydrationManifest: resolveHydrationManifest(this, options.hydrationManifest)
1195
+ });
1196
+ this.cssRuntime = cssRuntime;
1197
+ if (cssRuntime.needsHydrationManifest()) cssRuntime.loadHydrationManifest().then(() => {
1198
+ if (this.cssRuntime === cssRuntime) cssRuntime.observe();
1199
+ });
1200
+ else cssRuntime.observe();
1201
+ }
1202
+ disconnectedCallback() {
1203
+ disconnectedCallback?.call(this);
1204
+ this.cssRuntime?.destroy();
1205
+ this.cssRuntime = void 0;
1206
+ }
1207
+ };
1208
+ };
1209
+ }
1210
+ //#endregion
1211
+ export { CSSRuntime, CSSRuntime as default, RuntimeUtilityLayer, cssRuntime };