@monoes/monodesign 1.2.20 → 1.2.23

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.
Files changed (95) hide show
  1. package/README.md +2 -2
  2. package/cli/engine/cli/main.mjs +21 -1
  3. package/cli/engine/design-system-checks.mjs +381 -0
  4. package/cli/engine/design-system-parse.mjs +433 -0
  5. package/cli/engine/design-system.mjs +20 -736
  6. package/cli/engine/detect-antipatterns-browser.js +28 -5
  7. package/cli/engine/detect-antipatterns.mjs +1 -0
  8. package/cli/engine/engines/regex/detect-text-matchers.mjs +371 -0
  9. package/cli/engine/engines/regex/detect-text-run.mjs +186 -0
  10. package/cli/engine/engines/regex/detect-text.mjs +11 -523
  11. package/cli/engine/engines/static-html/css-cascade-color.mjs +219 -0
  12. package/cli/engine/engines/static-html/css-cascade-static-data.mjs +138 -0
  13. package/cli/engine/engines/static-html/css-cascade-static-dom.mjs +132 -0
  14. package/cli/engine/engines/static-html/css-cascade-static-parse.mjs +393 -0
  15. package/cli/engine/engines/static-html/css-cascade.mjs +24 -837
  16. package/cli/engine/engines/static-html/detect-html.mjs +6 -1
  17. package/cli/engine/findings-group.mjs +94 -0
  18. package/cli/engine/fix/index.mjs +1 -26
  19. package/cli/engine/fix/unified-diff.mjs +107 -0
  20. package/cli/engine/rules/checks-background.mjs +17 -3
  21. package/cli/engine/rules/checks-element.mjs +2 -0
  22. package/cli/engine/rules/checks-pure.mjs +9 -2
  23. package/cli/lib/monodesign-config-consent.mjs +93 -0
  24. package/cli/lib/monodesign-config-core.mjs +37 -0
  25. package/cli/lib/monodesign-config-detection.mjs +133 -0
  26. package/cli/lib/monodesign-config-filter.mjs +198 -0
  27. package/cli/lib/monodesign-config-ignore-value.mjs +212 -0
  28. package/cli/lib/monodesign-config.mjs +21 -623
  29. package/package.json +2 -2
  30. package/skill/scripts/context-fields.mjs +65 -0
  31. package/skill/scripts/context-resolve.mjs +425 -0
  32. package/skill/scripts/context-update.mjs +151 -0
  33. package/skill/scripts/context-utils.mjs +68 -0
  34. package/skill/scripts/context-workspace.mjs +245 -0
  35. package/skill/scripts/context.mjs +17 -891
  36. package/skill/scripts/hook-admin-config.mjs +152 -0
  37. package/skill/scripts/hook-admin-ignore.mjs +131 -0
  38. package/skill/scripts/hook-admin-manifest.mjs +292 -0
  39. package/skill/scripts/hook-admin.mjs +8 -541
  40. package/skill/scripts/hook-lib-cache.mjs +145 -0
  41. package/skill/scripts/hook-lib-config.mjs +292 -0
  42. package/skill/scripts/hook-lib-detector.mjs +72 -0
  43. package/skill/scripts/hook-lib-events.mjs +182 -0
  44. package/skill/scripts/hook-lib-findings.mjs +201 -0
  45. package/skill/scripts/hook-lib-ignore.mjs +205 -0
  46. package/skill/scripts/hook-lib-render.mjs +273 -0
  47. package/skill/scripts/hook-lib-run.mjs +281 -0
  48. package/skill/scripts/hook-lib-scan-targets.mjs +128 -0
  49. package/skill/scripts/hook-lib.mjs +71 -1747
  50. package/skill/scripts/lib/design-parser-colors.mjs +182 -0
  51. package/skill/scripts/lib/design-parser-extract.mjs +333 -0
  52. package/skill/scripts/lib/design-parser-sections.mjs +214 -0
  53. package/skill/scripts/lib/design-parser-yaml.mjs +135 -0
  54. package/skill/scripts/lib/design-parser.mjs +10 -783
  55. package/skill/scripts/live/manual-apply-chunk.mjs +151 -0
  56. package/skill/scripts/live/manual-apply-compact.mjs +122 -0
  57. package/skill/scripts/live/manual-apply-evidence.mjs +115 -0
  58. package/skill/scripts/live/manual-apply-log.mjs +179 -0
  59. package/skill/scripts/live/manual-apply-transaction.mjs +122 -0
  60. package/skill/scripts/live/manual-apply.mjs +65 -640
  61. package/skill/scripts/live/svelte-component-accept.mjs +248 -0
  62. package/skill/scripts/live/svelte-component-css.mjs +230 -0
  63. package/skill/scripts/live/svelte-component-markup.mjs +104 -0
  64. package/skill/scripts/live/svelte-component-scaffold.mjs +118 -0
  65. package/skill/scripts/live/svelte-component-session.mjs +158 -0
  66. package/skill/scripts/live/svelte-component.mjs +32 -792
  67. package/skill/scripts/live-accept-mutate.mjs +152 -0
  68. package/skill/scripts/live-accept-parse.mjs +370 -0
  69. package/skill/scripts/live-accept-scrub.mjs +59 -0
  70. package/skill/scripts/live-accept-search.mjs +58 -0
  71. package/skill/scripts/live-accept.mjs +15 -631
  72. package/skill/scripts/live-commit-manual-edits-paths.mjs +27 -0
  73. package/skill/scripts/live-commit-manual-edits-repair.mjs +166 -0
  74. package/skill/scripts/live-commit-manual-edits-rollback.mjs +231 -0
  75. package/skill/scripts/live-commit-manual-edits-utils.mjs +167 -0
  76. package/skill/scripts/live-commit-manual-edits-verify.mjs +356 -0
  77. package/skill/scripts/live-commit-manual-edits.mjs +24 -881
  78. package/skill/scripts/live-copy-edit-agent.mjs +16 -551
  79. package/skill/scripts/live-copy-edit-compact.mjs +137 -0
  80. package/skill/scripts/live-copy-edit-post-apply.mjs +175 -0
  81. package/skill/scripts/live-copy-edit-runners.mjs +297 -0
  82. package/skill/scripts/live-inject-csp.mjs +132 -0
  83. package/skill/scripts/live-inject-files.mjs +229 -0
  84. package/skill/scripts/live-inject-tag.mjs +114 -0
  85. package/skill/scripts/live-inject.mjs +13 -440
  86. package/skill/scripts/live-server-poll.mjs +232 -0
  87. package/skill/scripts/live-server-routes.mjs +449 -0
  88. package/skill/scripts/live-server-state.mjs +361 -0
  89. package/skill/scripts/live-server.mjs +10 -946
  90. package/skill/scripts/live-wrap-css.mjs +132 -0
  91. package/skill/scripts/live-wrap-manual-edit.mjs +153 -0
  92. package/skill/scripts/live-wrap-search.mjs +247 -0
  93. package/skill/scripts/live-wrap.mjs +21 -484
  94. package/skill/scripts/palette-seeds.mjs +401 -0
  95. package/skill/scripts/palette.mjs +1 -395
@@ -2,848 +2,35 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
 
4
4
  import { profileStep, recordProfileEvent } from '../../profile/profiler.mjs';
5
- import { parseAnyColor, resolveLengthPx, resolveVarRefs } from '../../rules/checks.mjs';
6
-
7
- // ---------------------------------------------------------------------------
8
- // jsdom CSS-variable border override map
9
- // ---------------------------------------------------------------------------
10
- //
11
- // jsdom's CSSOM silently drops any border shorthand that contains a var()
12
- // reference — the computed style for the element then shows empty width,
13
- // empty style, and a default black color. That's enough to hide the most
14
- // common real-world side-tab pattern in AI-generated pages:
15
- //
16
- // :root { --brand: #87a8ff; }
17
- // .card { border-left: 5px solid var(--brand); border-radius: 4px; }
18
- //
19
- // Real browsers (and therefore the browser detector path) resolve var()
20
- // natively, so this only affects the Node jsdom path.
21
- //
22
- // This pre-pass walks the stylesheets, finds any rule whose per-side or
23
- // all-sides border property contains var(), resolves the var() against
24
- // :root-level custom properties (read from the documentElement's computed
25
- // style, which jsdom DOES handle correctly), and attaches the resolved
26
- // width+color to every element that matches the rule's selector. The
27
- // Node-side `checkElementBorders` adapter consumes that map as a fallback
28
- // whenever jsdom's computed style came back empty.
29
- //
30
- // Limitations (intentional, to keep the pass simple):
31
- // * Only :root-level custom properties are resolved. Scoped overrides on
32
- // descendants are not tracked — uncommon in practice and would require
33
- // a per-element cascade walk.
34
- // * @media / @supports wrapped rules are ignored (jsdom often mishandles
35
- // these anyway).
36
- // * The fallback only fills sides that jsdom left empty, so any rule
37
- // whose border parses normally still wins via the computed style.
38
-
39
- const BORDER_SHORTHAND_RE = /^(\d+(?:\.\d+)?)px\s+(solid|dashed|dotted|double|groove|ridge|inset|outset)\s+(.+)$/i;
40
-
41
- // isNeutralColor only understands rgba()/oklch()/lch()/lab()/hsl()/hwb().
42
- // CSS variables typically hold hex or named colors, so normalize those to
43
- // rgb() before handing the value off to the shared check. Anything we don't
44
- // recognise is passed through unchanged — isNeutralColor then treats it as
45
- // non-neutral, which is the safer default (matches the oklch-era bugfix).
46
- const NAMED_COLORS = {
47
- white: [255, 255, 255], black: [0, 0, 0], gray: [128, 128, 128],
48
- grey: [128, 128, 128], silver: [192, 192, 192], red: [255, 0, 0],
49
- green: [0, 128, 0], blue: [0, 0, 255], yellow: [255, 255, 0],
50
- };
51
-
52
- function normalizeColorForCheck(value) {
53
- if (!value) return value;
54
- const v = value.trim();
55
- const hex6 = v.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i);
56
- if (hex6) {
57
- const [r, g, b] = [parseInt(hex6[1], 16), parseInt(hex6[2], 16), parseInt(hex6[3], 16)];
58
- return `rgb(${r}, ${g}, ${b})`;
59
- }
60
- const hex3 = v.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i);
61
- if (hex3) {
62
- const [r, g, b] = [
63
- parseInt(hex3[1] + hex3[1], 16),
64
- parseInt(hex3[2] + hex3[2], 16),
65
- parseInt(hex3[3] + hex3[3], 16),
66
- ];
67
- return `rgb(${r}, ${g}, ${b})`;
68
- }
69
- const named = NAMED_COLORS[v.toLowerCase()];
70
- if (named) return `rgb(${named[0]}, ${named[1]}, ${named[2]})`;
71
- return v;
72
- }
73
-
74
- function buildBorderOverrideMap(document, window) {
75
- const map = new Map();
76
- const rootStyle = window.getComputedStyle(document.documentElement);
77
-
78
- function resolveVar(value, depth = 0) {
79
- if (!value || depth > 10 || !value.includes('var(')) return value;
80
- return value.replace(
81
- /var\(\s*(--[\w-]+)\s*(?:,\s*([^)]+))?\s*\)/g,
82
- (_, name, fallback) => {
83
- const v = rootStyle.getPropertyValue(name).trim();
84
- if (v) return resolveVar(v, depth + 1);
85
- if (fallback) return resolveVar(fallback.trim(), depth + 1);
86
- return '';
87
- }
88
- );
89
- }
90
-
91
- function parseShorthand(text) {
92
- const m = text.trim().match(BORDER_SHORTHAND_RE);
93
- if (!m) return null;
94
- return { width: parseFloat(m[1]), color: normalizeColorForCheck(m[3]) };
95
- }
96
-
97
- // Read from the per-property accessors on rule.style. jsdom preserves
98
- // each border-* shorthand it parsed, even when the overall cssText has
99
- // been truncated (e.g. a `border: 1px solid var(...)` followed by a
100
- // `border-left: ...` loses the first declaration but keeps the second).
101
- const SIDE_PROPS = [
102
- ['borderLeft', 'Left'],
103
- ['borderRight', 'Right'],
104
- ['borderTop', 'Top'],
105
- ['borderBottom', 'Bottom'],
106
- ['borderInlineStart', 'Left'],
107
- ['borderInlineEnd', 'Right'],
108
- ];
109
-
110
- for (const sheet of document.styleSheets) {
111
- let rules;
112
- try { rules = sheet.cssRules || []; } catch { continue; }
113
- for (const rule of rules) {
114
- // CSSStyleRule only; skip @media / @keyframes / @supports wrappers.
115
- if (rule.type !== 1 || !rule.style || !rule.selectorText) continue;
116
-
117
- const perSide = {};
118
-
119
- for (const [prop, side] of SIDE_PROPS) {
120
- const val = rule.style[prop];
121
- if (!val?.includes('var(')) continue;
122
- const parsed = parseShorthand(resolveVar(val));
123
- if (parsed?.color) perSide[side] = parsed;
124
- }
125
-
126
- // Uniform `border: <w> <style> var(...)` applies to every side the
127
- // per-side map didn't already claim.
128
- const borderAll = rule.style.border;
129
- if (borderAll?.includes('var(')) {
130
- const parsed = parseShorthand(resolveVar(borderAll));
131
- if (parsed?.color) {
132
- for (const s of ['Top', 'Right', 'Bottom', 'Left']) {
133
- if (!perSide[s]) perSide[s] = parsed;
134
- }
135
- }
136
- }
137
-
138
- // Longhand `border-*-color: var(...)` with width/style in separate
139
- // declarations. Rare in AI-generated pages, but cheap to cover.
140
- for (const [prop, side] of [
141
- ['borderLeftColor', 'Left'],
142
- ['borderRightColor', 'Right'],
143
- ['borderTopColor', 'Top'],
144
- ['borderBottomColor', 'Bottom'],
145
- ]) {
146
- const val = rule.style[prop];
147
- if (!val?.includes('var(')) continue;
148
- const resolved = resolveVar(val).trim();
149
- if (!resolved) continue;
150
- // Width may or may not come from this rule — that's fine; the
151
- // adapter only substitutes the color when jsdom left it as a
152
- // literal var() string.
153
- if (!perSide[side]) perSide[side] = { width: 0, color: normalizeColorForCheck(resolved) };
154
- }
155
-
156
- if (Object.keys(perSide).length === 0) continue;
157
-
158
- let matched;
159
- try { matched = document.querySelectorAll(rule.selectorText); }
160
- catch { continue; }
161
-
162
- for (const el of matched) {
163
- const existing = map.get(el);
164
- if (existing) {
165
- // Later rules overwrite earlier ones — approximates source-order
166
- // cascade for equal-specificity rules and is good enough for the
167
- // uncontested var()-dropped sides we're trying to recover.
168
- Object.assign(existing, perSide);
169
- } else {
170
- map.set(el, { ...perSide });
171
- }
172
- }
173
- }
174
- }
175
-
176
- return map;
177
- }
178
-
179
- // Strip `@layer NAME { … }` wrappers from a CSS / HTML source, leaving
180
- // the inner rules as flat CSS. jsdom doesn't implement CSS @layer, so
181
- // any rule inside a layer block becomes invisible to getComputedStyle.
182
- // Tailwind v4 makes this ubiquitous: every utility class lives in
183
- // `@layer utilities`, and Preflight lives in `@layer base`. Without
184
- // unwrapping, every Tailwind-styled element returns empty computed
185
- // styles. We walk the source character-by-character, balancing braces
186
- // so we correctly handle nested style rules inside the layer block.
187
- function unwrapCssAtLayer(source) {
188
- // biome-ignore lint/complexity/useOptionalChain: exported helper with no typed callers; `source?.includes` would throw for a falsy non-string (0/false) that this guard currently returns unchanged
189
- if (!source || !source.includes('@layer')) return source;
190
- // Find `@layer <name>? {` openers. The match starts at the @, and
191
- // we then balance braces from the opening { onward.
192
- const re = /@layer\b[^{;]*\{/g;
193
- let out = '';
194
- let lastIdx = 0;
195
- let m;
196
- while ((m = re.exec(source)) !== null) {
197
- const openStart = m.index;
198
- const openEnd = m.index + m[0].length; // position right after `{`
199
- let depth = 1;
200
- let i = openEnd;
201
- while (i < source.length && depth > 0) {
202
- const c = source.charCodeAt(i);
203
- if (c === 0x7b /* { */) depth++;
204
- else if (c === 0x7d /* } */) depth--;
205
- i++;
206
- }
207
- if (depth !== 0) {
208
- // Unbalanced — bail and return source unchanged.
209
- return source;
210
- }
211
- // Emit everything before the @layer, then the inner contents
212
- // (between the opening { and the matched closing }), then advance.
213
- out += source.slice(lastIdx, openStart);
214
- out += source.slice(openEnd, i - 1); // i-1 = position of the closing }
215
- lastIdx = i;
216
- re.lastIndex = i;
217
- }
218
- out += source.slice(lastIdx);
219
- return out;
220
- }
5
+ import { resolveVarRefs } from '../../rules/checks.mjs';
6
+ import { BORDER_SHORTHAND_RE, NAMED_COLORS, normalizeColorForCheck, buildBorderOverrideMap, unwrapCssAtLayer } from './css-cascade-color.mjs';
7
+ import { STATIC_INHERITED_PROPS, STATIC_DEFAULT_STYLE, STATIC_PROP_MAP, STATIC_NAMED_COLORS } from './css-cascade-static-data.mjs';
8
+ import {
9
+ splitCssList,
10
+ splitCssTokens,
11
+ cssPropToCamel,
12
+ staticColorToCss,
13
+ parseStaticColor,
14
+ extractStaticColor,
15
+ normalizeStaticCssValue,
16
+ expandStaticBoxValues,
17
+ parseStaticBorder,
18
+ parseStaticFont,
19
+ parseStaticTransition,
20
+ parseStaticAnimation,
21
+ expandStaticDeclaration,
22
+ compareStaticPriority,
23
+ staticSpecificity,
24
+ applyStaticDeclaration,
25
+ parseStaticStyleAttribute,
26
+ collectStaticCssRules,
27
+ } from './css-cascade-static-parse.mjs';
28
+ import { StaticElement, StaticDocument } from './css-cascade-static-dom.mjs';
221
29
 
222
30
  // ---------------------------------------------------------------------------
223
31
  // Static HTML/CSS detection (default for local HTML files)
224
32
  // ---------------------------------------------------------------------------
225
33
 
226
- const STATIC_INHERITED_PROPS = new Set([
227
- 'color', 'fontFamily', 'fontSize', 'fontStyle', 'fontWeight',
228
- 'lineHeight', 'letterSpacing', 'textTransform', 'textAlign', 'hyphens',
229
- 'webkitHyphens',
230
- ]);
231
-
232
- const STATIC_DEFAULT_STYLE = {
233
- color: 'rgb(0, 0, 0)',
234
- backgroundColor: 'rgba(0, 0, 0, 0)',
235
- backgroundImage: 'none',
236
- borderTopWidth: '0px',
237
- borderRightWidth: '0px',
238
- borderBottomWidth: '0px',
239
- borderLeftWidth: '0px',
240
- borderTopColor: 'rgb(0, 0, 0)',
241
- borderRightColor: 'rgb(0, 0, 0)',
242
- borderBottomColor: 'rgb(0, 0, 0)',
243
- borderLeftColor: 'rgb(0, 0, 0)',
244
- borderRadius: '0px',
245
- outlineWidth: '0px',
246
- outlineColor: 'rgb(0, 0, 0)',
247
- outlineStyle: 'none',
248
- boxShadow: 'none',
249
- fontFamily: '',
250
- fontSize: '16px',
251
- fontStyle: 'normal',
252
- fontWeight: '400',
253
- lineHeight: 'normal',
254
- letterSpacing: 'normal',
255
- textTransform: 'none',
256
- textAlign: 'start',
257
- hyphens: 'manual',
258
- webkitHyphens: 'manual',
259
- transitionProperty: '',
260
- transitionTimingFunction: '',
261
- animationName: '',
262
- animationTimingFunction: '',
263
- webkitBackgroundClip: '',
264
- backgroundClip: '',
265
- width: '',
266
- height: '',
267
- paddingTop: '0px',
268
- paddingRight: '0px',
269
- paddingBottom: '0px',
270
- paddingLeft: '0px',
271
- marginTop: '0px',
272
- marginRight: '0px',
273
- marginBottom: '0px',
274
- marginLeft: '0px',
275
- position: 'static',
276
- visibility: 'visible',
277
- top: 'auto',
278
- right: 'auto',
279
- bottom: 'auto',
280
- left: 'auto',
281
- inset: '',
282
- display: '',
283
- overflow: 'visible',
284
- overflowX: 'visible',
285
- overflowY: 'visible',
286
- };
287
-
288
- const STATIC_PROP_MAP = {
289
- 'background-color': 'backgroundColor',
290
- 'background-image': 'backgroundImage',
291
- 'background-clip': 'backgroundClip',
292
- '-webkit-background-clip': 'webkitBackgroundClip',
293
- 'border-radius': 'borderRadius',
294
- 'border-top-width': 'borderTopWidth',
295
- 'border-right-width': 'borderRightWidth',
296
- 'border-bottom-width': 'borderBottomWidth',
297
- 'border-left-width': 'borderLeftWidth',
298
- 'border-top-color': 'borderTopColor',
299
- 'border-right-color': 'borderRightColor',
300
- 'border-bottom-color': 'borderBottomColor',
301
- 'border-left-color': 'borderLeftColor',
302
- 'outline-width': 'outlineWidth',
303
- 'outline-color': 'outlineColor',
304
- 'outline-style': 'outlineStyle',
305
- 'box-shadow': 'boxShadow',
306
- 'font-family': 'fontFamily',
307
- 'font-size': 'fontSize',
308
- 'font-style': 'fontStyle',
309
- 'font-weight': 'fontWeight',
310
- 'line-height': 'lineHeight',
311
- 'letter-spacing': 'letterSpacing',
312
- 'text-transform': 'textTransform',
313
- 'text-align': 'textAlign',
314
- 'hyphens': 'hyphens',
315
- '-webkit-hyphens': 'webkitHyphens',
316
- 'transition-property': 'transitionProperty',
317
- 'transition-timing-function': 'transitionTimingFunction',
318
- 'animation-name': 'animationName',
319
- 'animation-timing-function': 'animationTimingFunction',
320
- 'width': 'width',
321
- 'height': 'height',
322
- 'padding-top': 'paddingTop',
323
- 'padding-right': 'paddingRight',
324
- 'padding-bottom': 'paddingBottom',
325
- 'padding-left': 'paddingLeft',
326
- 'margin-top': 'marginTop',
327
- 'margin-right': 'marginRight',
328
- 'margin-bottom': 'marginBottom',
329
- 'margin-left': 'marginLeft',
330
- 'position': 'position',
331
- 'visibility': 'visibility',
332
- 'top': 'top',
333
- 'right': 'right',
334
- 'bottom': 'bottom',
335
- 'left': 'left',
336
- 'inset': 'inset',
337
- 'display': 'display',
338
- 'overflow': 'overflow',
339
- 'overflow-x': 'overflowX',
340
- 'overflow-y': 'overflowY',
341
- };
342
-
343
- const STATIC_NAMED_COLORS = {
344
- black: { r: 0, g: 0, b: 0, a: 1 },
345
- white: { r: 255, g: 255, b: 255, a: 1 },
346
- transparent: { r: 0, g: 0, b: 0, a: 0 },
347
- gray: { r: 128, g: 128, b: 128, a: 1 },
348
- grey: { r: 128, g: 128, b: 128, a: 1 },
349
- silver: { r: 192, g: 192, b: 192, a: 1 },
350
- red: { r: 255, g: 0, b: 0, a: 1 },
351
- green: { r: 0, g: 128, b: 0, a: 1 },
352
- blue: { r: 0, g: 0, b: 255, a: 1 },
353
- };
354
-
355
- function splitCssList(value) {
356
- const parts = [];
357
- let depth = 0, quote = '', start = 0;
358
- for (let i = 0; i < value.length; i++) {
359
- const ch = value[i];
360
- if (quote) {
361
- if (ch === quote && value[i - 1] !== '\\') quote = '';
362
- continue;
363
- }
364
- if (ch === '"' || ch === "'") { quote = ch; continue; }
365
- if (ch === '(' || ch === '[') depth++;
366
- else if (ch === ')' || ch === ']') depth = Math.max(0, depth - 1);
367
- else if (ch === ',' && depth === 0) {
368
- parts.push(value.slice(start, i).trim());
369
- start = i + 1;
370
- }
371
- }
372
- const tail = value.slice(start).trim();
373
- if (tail) parts.push(tail);
374
- return parts;
375
- }
376
-
377
- function splitCssTokens(value) {
378
- const tokens = [];
379
- let depth = 0, quote = '', current = '';
380
- for (let i = 0; i < value.length; i++) {
381
- const ch = value[i];
382
- if (quote) {
383
- current += ch;
384
- if (ch === quote && value[i - 1] !== '\\') quote = '';
385
- continue;
386
- }
387
- if (ch === '"' || ch === "'") { quote = ch; current += ch; continue; }
388
- if (ch === '(') { depth++; current += ch; continue; }
389
- if (ch === ')') { depth = Math.max(0, depth - 1); current += ch; continue; }
390
- if (/\s/.test(ch) && depth === 0) {
391
- if (current) { tokens.push(current); current = ''; }
392
- continue;
393
- }
394
- current += ch;
395
- }
396
- if (current) tokens.push(current);
397
- return tokens;
398
- }
399
-
400
- function cssPropToCamel(prop) {
401
- if (!prop) return prop;
402
- const mapped = STATIC_PROP_MAP[prop];
403
- if (mapped) return mapped;
404
- return prop.replace(/-([a-z])/g, (_m, ch) => ch.toUpperCase());
405
- }
406
-
407
- function staticColorToCss(c) {
408
- if (!c) return '';
409
- if (c.a != null && c.a < 1) return `rgba(${c.r}, ${c.g}, ${c.b}, ${Number(c.a.toFixed(3))})`;
410
- return `rgb(${c.r}, ${c.g}, ${c.b})`;
411
- }
412
-
413
- function parseStaticColor(value) {
414
- const parsed = parseAnyColor(value);
415
- if (parsed) return parsed;
416
- const named = STATIC_NAMED_COLORS[String(value || '').trim().toLowerCase()];
417
- return named ? { ...named } : null;
418
- }
419
-
420
- function extractStaticColor(value) {
421
- if (!value) return '';
422
- const raw = String(value).trim();
423
- if (/^var\(/i.test(raw)) return raw;
424
- const colorLike = raw.match(/(?:rgba?\([^)]+\)|oklch\([^)]+\)|oklab\([^)]+\)|lch\([^)]+\)|lab\([^)]+\)|hsla?\([^)]+\)|hwb\([^)]+\)|#[0-9a-f]{3,8}\b|\b(?:black|white|gray|grey|silver|red|green|blue|transparent)\b)/i);
425
- if (!colorLike) return '';
426
- return colorLike[0];
427
- }
428
-
429
- function normalizeStaticCssValue(prop, value, customProps, parentStyle, currentStyle = null) {
430
- let resolved = resolveVarRefs(String(value || '').trim(), customProps);
431
- if (resolved === 'inherit') return parentStyle?.[prop] || STATIC_DEFAULT_STYLE[prop] || '';
432
- const isModernBorderColor = /^border[A-Z][a-z]+Color$/.test(prop) && /^(?:oklch|oklab|lch|lab|hsl|hwb)\(/i.test(resolved);
433
- if (!isModernBorderColor && (/color$/i.test(prop) || prop === 'color' || prop === 'backgroundColor')) {
434
- const parsed = parseStaticColor(resolved);
435
- if (parsed) resolved = staticColorToCss(parsed);
436
- }
437
- if (prop === 'fontSize') {
438
- const base = parseFloat(parentStyle?.fontSize) || 16;
439
- const px = resolveLengthPx(resolved, base);
440
- if (px != null) resolved = `${px}px`;
441
- }
442
- if (prop === 'letterSpacing') {
443
- const base = parseFloat(currentStyle?.fontSize || parentStyle?.fontSize) || 16;
444
- const px = resolveLengthPx(resolved, base);
445
- if (px != null) resolved = `${px}px`;
446
- }
447
- if (prop === 'lineHeight' && resolved !== 'normal') {
448
- const base = parseFloat(currentStyle?.fontSize || parentStyle?.fontSize) || 16;
449
- const px = resolveLengthPx(resolved, base);
450
- if (px != null) resolved = `${px}px`;
451
- }
452
- return resolved;
453
- }
454
-
455
- function expandStaticBoxValues(tokens) {
456
- if (tokens.length === 0) return ['0px', '0px', '0px', '0px'];
457
- if (tokens.length === 1) return [tokens[0], tokens[0], tokens[0], tokens[0]];
458
- if (tokens.length === 2) return [tokens[0], tokens[1], tokens[0], tokens[1]];
459
- if (tokens.length === 3) return [tokens[0], tokens[1], tokens[2], tokens[1]];
460
- return [tokens[0], tokens[1], tokens[2], tokens[3]];
461
- }
462
-
463
- function parseStaticBorder(value) {
464
- const tokens = splitCssTokens(value);
465
- let width = '', color = '';
466
- for (const token of tokens) {
467
- if (!width && /^-?[\d.]+(?:px|rem|em|%)$/.test(token)) width = token;
468
- if (!color) color = extractStaticColor(token);
469
- }
470
- return { width, color };
471
- }
472
-
473
- function parseStaticFont(value) {
474
- const out = [];
475
- const slashParts = value.match(/(?:^|\s)([\d.]+(?:px|rem|em|%))(?:\/([^\s]+))?/);
476
- if (/\bitalic\b/i.test(value)) out.push(['fontStyle', 'italic']);
477
- const weight = value.match(/\b([1-9]00|bold|normal|lighter|bolder)\b/i);
478
- if (weight) out.push(['fontWeight', weight[1]]);
479
- if (slashParts) {
480
- out.push(['fontSize', slashParts[1]]);
481
- if (slashParts[2]) out.push(['lineHeight', slashParts[2]]);
482
- const familyStart = value.indexOf(slashParts[0]) + slashParts[0].length;
483
- const family = value.slice(familyStart).trim();
484
- if (family) out.push(['fontFamily', family]);
485
- }
486
- return out;
487
- }
488
-
489
- function parseStaticTransition(value) {
490
- const props = [];
491
- const timings = [];
492
- for (const item of splitCssList(value)) {
493
- const tokens = splitCssTokens(item);
494
- const timing = tokens.find(token => /^(?:ease|linear|step-|cubic-bezier\()/i.test(token));
495
- if (timing) timings.push(timing);
496
- const prop = tokens.find(token => /^[a-z-]+$/i.test(token) && !/^(?:ease|linear|infinite|alternate|forwards|backwards|both|normal|none)$/.test(token) && !/s$/.test(token));
497
- if (prop) props.push(prop);
498
- }
499
- return {
500
- property: props.join(', '),
501
- timing: timings.join(', '),
502
- };
503
- }
504
-
505
- function parseStaticAnimation(value) {
506
- const names = [];
507
- const timings = [];
508
- for (const item of splitCssList(value)) {
509
- const tokens = splitCssTokens(item);
510
- const timing = tokens.find(token => /^(?:ease|linear|step-|cubic-bezier\()/i.test(token));
511
- if (timing) timings.push(timing);
512
- const name = tokens.find(token =>
513
- /^[a-z_-][\w-]*$/i.test(token) &&
514
- !/^(?:ease|linear|infinite|alternate|forwards|backwards|both|normal|none|running|paused)$/.test(token)
515
- );
516
- if (name) names.push(name);
517
- }
518
- return {
519
- name: names.join(', '),
520
- timing: timings.join(', '),
521
- };
522
- }
523
-
524
- function expandStaticDeclaration(prop, value) {
525
- const p = prop.toLowerCase();
526
- const v = String(value || '').trim();
527
- if (!v) return [];
528
- if (p.startsWith('--')) return [[p, v]];
529
- if (p === 'background') {
530
- const out = [];
531
- const hasImage = /gradient|url\(/i.test(v);
532
- if (hasImage) out.push(['backgroundImage', v]);
533
- const beforeImage = hasImage ? v.split(/(?:repeating-)?(?:linear|radial|conic)-gradient\(|url\(/i)[0] : v;
534
- const color = extractStaticColor(hasImage ? beforeImage : v);
535
- if (color) out.push(['backgroundColor', color]);
536
- return out;
537
- }
538
- if (p === 'border') {
539
- const parsed = parseStaticBorder(v);
540
- const out = [];
541
- for (const side of ['Top', 'Right', 'Bottom', 'Left']) {
542
- if (parsed.width) out.push([`border${side}Width`, parsed.width]);
543
- if (parsed.color) out.push([`border${side}Color`, parsed.color]);
544
- }
545
- return out;
546
- }
547
- if (p === 'outline') {
548
- // `outline` shorthand: width | style | color, in any order. Reuse the
549
- // border parser for width + color, then sniff a style keyword from the
550
- // tokens (solid|dashed|...). `outline: 0` (single-token zero) zeros
551
- // the width and effectively hides the outline.
552
- const tokens = splitCssTokens(v);
553
- const parsed = parseStaticBorder(v);
554
- const styleToken = tokens.find(t =>
555
- /^(none|hidden|solid|dashed|dotted|double|groove|ridge|inset|outset)$/i.test(t)
556
- );
557
- const out = [];
558
- if (parsed.width) out.push(['outlineWidth', parsed.width]);
559
- if (parsed.color) out.push(['outlineColor', parsed.color]);
560
- if (styleToken) out.push(['outlineStyle', styleToken.toLowerCase()]);
561
- // `outline: 0` with no other tokens: explicit zero width.
562
- if (!parsed.width && /^0(?:px|rem|em|%)?$/.test(v.trim())) {
563
- out.push(['outlineWidth', '0px']);
564
- }
565
- return out;
566
- }
567
- const sideMatch = p.match(/^border-(top|right|bottom|left)$/);
568
- if (sideMatch) {
569
- const parsed = parseStaticBorder(v);
570
- const side = sideMatch[1][0].toUpperCase() + sideMatch[1].slice(1);
571
- return [
572
- ...(parsed.width ? [[`border${side}Width`, parsed.width]] : []),
573
- ...(parsed.color ? [[`border${side}Color`, parsed.color]] : []),
574
- ];
575
- }
576
- if (p === 'border-width') {
577
- const vals = expandStaticBoxValues(splitCssTokens(v));
578
- return [
579
- ['borderTopWidth', vals[0]],
580
- ['borderRightWidth', vals[1]],
581
- ['borderBottomWidth', vals[2]],
582
- ['borderLeftWidth', vals[3]],
583
- ];
584
- }
585
- if (p === 'border-color') {
586
- const vals = expandStaticBoxValues(splitCssTokens(v));
587
- return [
588
- ['borderTopColor', vals[0]],
589
- ['borderRightColor', vals[1]],
590
- ['borderBottomColor', vals[2]],
591
- ['borderLeftColor', vals[3]],
592
- ];
593
- }
594
- if (p === 'padding') {
595
- const vals = expandStaticBoxValues(splitCssTokens(v));
596
- return [
597
- ['paddingTop', vals[0]],
598
- ['paddingRight', vals[1]],
599
- ['paddingBottom', vals[2]],
600
- ['paddingLeft', vals[3]],
601
- ];
602
- }
603
- if (p === 'margin') {
604
- const vals = expandStaticBoxValues(splitCssTokens(v));
605
- return [
606
- ['marginTop', vals[0]],
607
- ['marginRight', vals[1]],
608
- ['marginBottom', vals[2]],
609
- ['marginLeft', vals[3]],
610
- ];
611
- }
612
- if (p === 'font') return parseStaticFont(v);
613
- if (p === 'transition') {
614
- const parsed = parseStaticTransition(v);
615
- return [
616
- ...(parsed.property ? [['transitionProperty', parsed.property]] : []),
617
- ...(parsed.timing ? [['transitionTimingFunction', parsed.timing]] : []),
618
- ];
619
- }
620
- if (p === 'animation') {
621
- const parsed = parseStaticAnimation(v);
622
- return [
623
- ...(parsed.name ? [['animationName', parsed.name]] : []),
624
- ...(parsed.timing ? [['animationTimingFunction', parsed.timing]] : []),
625
- ];
626
- }
627
- const mapped = cssPropToCamel(p);
628
- if (STATIC_DEFAULT_STYLE[mapped] != null || STATIC_INHERITED_PROPS.has(mapped)) {
629
- return [[mapped, v]];
630
- }
631
- return [];
632
- }
633
-
634
- function compareStaticPriority(a, b) {
635
- if (!a) return true;
636
- if (!!b.important !== !!a.important) return !!b.important;
637
- if (!!b.inline !== !!a.inline) return !!b.inline;
638
- for (let i = 0; i < 3; i++) {
639
- if ((b.specificity[i] || 0) !== (a.specificity[i] || 0)) {
640
- return (b.specificity[i] || 0) > (a.specificity[i] || 0);
641
- }
642
- }
643
- return b.order >= a.order;
644
- }
645
-
646
- function staticSpecificity(selector) {
647
- const noWhere = selector.replace(/:where\([^)]*\)/g, '');
648
- const ids = (noWhere.match(/#[\w-]+/g) || []).length;
649
- const classes = (noWhere.match(/\.[\w-]+|\[[^\]]+\]|:(?!:)[\w-]+(?:\([^)]*\))?/g) || []).length;
650
- const stripped = noWhere
651
- .replace(/#[\w-]+/g, ' ')
652
- .replace(/\.[\w-]+|\[[^\]]+\]|:{1,2}[\w-]+(?:\([^)]*\))?/g, ' ')
653
- .replace(/[*>+~(),]/g, ' ');
654
- const types = (stripped.match(/\b[a-zA-Z][\w-]*\b/g) || []).length;
655
- return [ids, classes, types];
656
- }
657
-
658
- function applyStaticDeclaration(specified, node, prop, value, meta) {
659
- let map = specified.get(node);
660
- if (!map) { map = new Map(); specified.set(node, map); }
661
- for (const [expandedProp, expandedValue] of expandStaticDeclaration(prop, value)) {
662
- const existing = map.get(expandedProp);
663
- const next = { ...meta, prop: expandedProp, value: expandedValue };
664
- if (compareStaticPriority(existing, next)) map.set(expandedProp, next);
665
- }
666
- }
667
-
668
- function parseStaticStyleAttribute(styleText, orderBase = 0) {
669
- const decls = [];
670
- for (const part of String(styleText || '').split(';')) {
671
- const idx = part.indexOf(':');
672
- if (idx <= 0) continue;
673
- const prop = part.slice(0, idx).trim();
674
- let value = part.slice(idx + 1).trim();
675
- const important = /!important\s*$/i.test(value);
676
- value = value.replace(/\s*!important\s*$/i, '').trim();
677
- decls.push({ prop, value, important, order: orderBase + decls.length });
678
- }
679
- return decls;
680
- }
681
-
682
- function collectStaticCssRules(cssText, csstree) {
683
- const rules = [];
684
- let ast;
685
- try {
686
- ast = csstree.parse(cssText, { positions: false, parseValue: true, parseCustomProperty: false });
687
- } catch {
688
- return rules;
689
- }
690
- let order = 0;
691
- const walkList = (list, atRuleStack = []) => {
692
- list?.forEach?.(node => {
693
- if (node.type === 'Rule' && node.block) {
694
- if (atRuleStack.some(name => /keyframes$/i.test(name))) return;
695
- const selectorText = csstree.generate(node.prelude).trim();
696
- const declarations = [];
697
- node.block.children?.forEach?.(child => {
698
- if (child.type !== 'Declaration') return;
699
- declarations.push({
700
- prop: child.property,
701
- value: csstree.generate(child.value).trim(),
702
- important: !!child.important,
703
- });
704
- });
705
- for (const selector of splitCssList(selectorText)) {
706
- if (selector) rules.push({ selector, declarations, specificity: staticSpecificity(selector), order: order++ });
707
- }
708
- return;
709
- }
710
- if (node.type === 'Atrule' && node.block) {
711
- const name = String(node.name || '').toLowerCase();
712
- if (name === 'media' || name === 'supports' || name === 'layer') {
713
- walkList(node.block.children, [...atRuleStack, name]);
714
- }
715
- }
716
- });
717
- };
718
- walkList(ast.children);
719
- return rules;
720
- }
721
-
722
- class StaticElement {
723
- constructor(node, doc) {
724
- this.node = node;
725
- this._doc = doc;
726
- this.nodeType = 1;
727
- this.tagName = String(node.name || '').toUpperCase();
728
- this.nodeName = this.tagName;
729
- }
730
- get parentElement() {
731
- let cur = this.node.parent;
732
- while (cur && cur.type !== 'tag') cur = cur.parent;
733
- return cur ? this._doc.wrap(cur) : null;
734
- }
735
- get previousElementSibling() {
736
- let cur = this.node.prev;
737
- while (cur && cur.type !== 'tag') cur = cur.prev;
738
- return cur ? this._doc.wrap(cur) : null;
739
- }
740
- get children() {
741
- return (this.node.children || []).filter(child => child.type === 'tag').map(child => this._doc.wrap(child));
742
- }
743
- get childNodes() {
744
- return (this.node.children || []).map(child => {
745
- if (child.type === 'text') return { nodeType: 3, textContent: child.data || '' };
746
- if (child.type === 'tag') return this._doc.wrap(child);
747
- return { nodeType: 8, textContent: child.data || '' };
748
- });
749
- }
750
- get textContent() {
751
- return this._doc.domutils.textContent(this.node);
752
- }
753
- get className() {
754
- return this.getAttribute('class') || '';
755
- }
756
- get id() {
757
- return this.getAttribute('id') || '';
758
- }
759
- getAttribute(name) {
760
- return this.node.attribs?.[name] ?? null;
761
- }
762
- querySelector(selector) {
763
- try {
764
- const found = this._doc.selectOne(selector, this.node.children || []);
765
- return found ? this._doc.wrap(found) : null;
766
- } catch {
767
- return null;
768
- }
769
- }
770
- querySelectorAll(selector) {
771
- try {
772
- return this._doc.selectAll(selector, this.node.children || []).map(node => this._doc.wrap(node));
773
- } catch {
774
- return [];
775
- }
776
- }
777
- closest(selector) {
778
- let cur = this.node;
779
- while (cur && cur.type === 'tag') {
780
- try {
781
- if (this._doc.is(cur, selector)) return this._doc.wrap(cur);
782
- } catch {
783
- return null;
784
- }
785
- cur = cur.parent;
786
- while (cur && cur.type !== 'tag') cur = cur.parent;
787
- }
788
- return null;
789
- }
790
- contains(other) {
791
- let cur = other?.node || null;
792
- while (cur) {
793
- if (cur === this.node) return true;
794
- cur = cur.parent;
795
- }
796
- return false;
797
- }
798
- }
799
-
800
- class StaticDocument {
801
- constructor(root, modules) {
802
- this.root = root;
803
- this.selectAll = modules.selectAll;
804
- this.selectOne = modules.selectOne;
805
- this.is = modules.is;
806
- this.domutils = modules.domutils;
807
- this._wrappers = new WeakMap();
808
- this._styleMap = new WeakMap();
809
- }
810
- wrap(node) {
811
- let wrapped = this._wrappers.get(node);
812
- if (!wrapped) {
813
- wrapped = new StaticElement(node, this);
814
- this._wrappers.set(node, wrapped);
815
- }
816
- return wrapped;
817
- }
818
- querySelectorAll(selector) {
819
- try {
820
- return this.selectAll(selector, this.root.children || []).map(node => this.wrap(node));
821
- } catch {
822
- return [];
823
- }
824
- }
825
- querySelector(selector) {
826
- try {
827
- const found = this.selectOne(selector, this.root.children || []);
828
- return found ? this.wrap(found) : null;
829
- } catch {
830
- return null;
831
- }
832
- }
833
- get documentElement() {
834
- return this.querySelector('html');
835
- }
836
- get body() {
837
- return this.querySelector('body');
838
- }
839
- setStyle(node, style) {
840
- this._styleMap.set(node, style);
841
- }
842
- getStyle(el) {
843
- return this._styleMap.get(el.node) || makeStaticStyle();
844
- }
845
- }
846
-
847
34
  function makeStaticStyle(values = {}) {
848
35
  const style = { ...STATIC_DEFAULT_STYLE, ...values };
849
36
  style.getPropertyValue = (prop) => {