@wix/validation-infra 0.0.0-stage → 0.5.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.
Files changed (152) hide show
  1. package/README.md +192 -2
  2. package/dist/constants.d.ts +29 -0
  3. package/dist/constants.js +45 -0
  4. package/dist/index.d.ts +11 -0
  5. package/dist/index.js +13 -0
  6. package/dist/package-readers/constants.d.ts +6 -0
  7. package/dist/package-readers/constants.js +6 -0
  8. package/dist/package-readers/index.d.ts +1 -0
  9. package/dist/package-readers/index.js +1 -0
  10. package/dist/package-readers/read-from-files.d.ts +6 -0
  11. package/dist/package-readers/read-from-files.js +76 -0
  12. package/dist/package-readers/types.d.ts +7 -0
  13. package/dist/package-readers/types.js +1 -0
  14. package/dist/package-readers/utils.d.ts +4 -0
  15. package/dist/package-readers/utils.js +15 -0
  16. package/dist/page-model/build-page-model.d.ts +3 -0
  17. package/dist/page-model/build-page-model.js +12 -0
  18. package/dist/page-model/connect-css.d.ts +3 -0
  19. package/dist/page-model/connect-css.js +43 -0
  20. package/dist/page-model/constants.d.ts +17 -0
  21. package/dist/page-model/constants.js +17 -0
  22. package/dist/page-model/css-selectors.d.ts +2 -0
  23. package/dist/page-model/css-selectors.js +7 -0
  24. package/dist/page-model/index.d.ts +4 -0
  25. package/dist/page-model/index.js +4 -0
  26. package/dist/page-model/pages.d.ts +2 -0
  27. package/dist/page-model/pages.js +18 -0
  28. package/dist/page-model/read-css.d.ts +4 -0
  29. package/dist/page-model/read-css.js +98 -0
  30. package/dist/page-model/read-structure.d.ts +3 -0
  31. package/dist/page-model/read-structure.js +59 -0
  32. package/dist/page-model/read-theme.d.ts +6 -0
  33. package/dist/page-model/read-theme.js +14 -0
  34. package/dist/page-model/types.d.ts +92 -0
  35. package/dist/page-model/types.js +1 -0
  36. package/dist/page-model/utils.d.ts +16 -0
  37. package/dist/page-model/utils.js +29 -0
  38. package/dist/project-model/index.d.ts +5 -0
  39. package/dist/project-model/index.js +5 -0
  40. package/dist/project-model/menu-files.d.ts +4 -0
  41. package/dist/project-model/menu-files.js +14 -0
  42. package/dist/project-model/package-json.d.ts +5 -0
  43. package/dist/project-model/package-json.js +27 -0
  44. package/dist/project-model/popups.d.ts +4 -0
  45. package/dist/project-model/popups.js +12 -0
  46. package/dist/project-model/project-model.d.ts +4 -0
  47. package/dist/project-model/project-model.js +14 -0
  48. package/dist/project-model/types.d.ts +20 -0
  49. package/dist/project-model/types.js +2 -0
  50. package/dist/rules/index.d.ts +4 -0
  51. package/dist/rules/index.js +5 -0
  52. package/dist/rules/project/define-project-rule.d.ts +5 -0
  53. package/dist/rules/project/define-project-rule.js +4 -0
  54. package/dist/rules/project/index.d.ts +2 -0
  55. package/dist/rules/project/index.js +2 -0
  56. package/dist/rules/project/types.d.ts +16 -0
  57. package/dist/rules/project/types.js +1 -0
  58. package/dist/rules/site-app/define-rule.d.ts +5 -0
  59. package/dist/rules/site-app/define-rule.js +4 -0
  60. package/dist/rules/site-app/index.d.ts +2 -0
  61. package/dist/rules/site-app/index.js +1 -0
  62. package/dist/rules/site-app/types.d.ts +26 -0
  63. package/dist/rules/site-app/types.js +1 -0
  64. package/dist/rules/site-code/define-site-code-rule.d.ts +5 -0
  65. package/dist/rules/site-code/define-site-code-rule.js +4 -0
  66. package/dist/rules/site-code/index.d.ts +2 -0
  67. package/dist/rules/site-code/index.js +2 -0
  68. package/dist/rules/site-code/types.d.ts +11 -0
  69. package/dist/rules/site-code/types.js +1 -0
  70. package/dist/rules/types.d.ts +13 -0
  71. package/dist/rules/types.js +3 -0
  72. package/dist/rules-adapter/eslint/index.d.ts +1 -0
  73. package/dist/rules-adapter/eslint/index.js +1 -0
  74. package/dist/rules-adapter/eslint/types.d.ts +5 -0
  75. package/dist/rules-adapter/eslint/types.js +1 -0
  76. package/dist/rules-adapter/index.d.ts +2 -0
  77. package/dist/rules-adapter/index.js +2 -0
  78. package/dist/rules-adapter/types.d.ts +16 -0
  79. package/dist/rules-adapter/types.js +1 -0
  80. package/dist/rules-adapter/utils.d.ts +7 -0
  81. package/dist/rules-adapter/utils.js +20 -0
  82. package/dist/rules-api/component-catalog.d.ts +8 -0
  83. package/dist/rules-api/component-catalog.js +28 -0
  84. package/dist/rules-api/constants.d.ts +7 -0
  85. package/dist/rules-api/constants.js +7 -0
  86. package/dist/rules-api/index.d.ts +18 -0
  87. package/dist/rules-api/index.js +14 -0
  88. package/dist/rules-api/report.d.ts +8 -0
  89. package/dist/rules-api/report.js +13 -0
  90. package/dist/rules-api/rules-api.d.ts +13 -0
  91. package/dist/rules-api/rules-api.js +139 -0
  92. package/dist/rules-api/types.d.ts +141 -0
  93. package/dist/rules-api/types.js +1 -0
  94. package/dist/rules-api/utils.d.ts +14 -0
  95. package/dist/rules-api/utils.js +27 -0
  96. package/dist/shared/constants.d.ts +188 -0
  97. package/dist/shared/constants.js +242 -0
  98. package/dist/shared/css-variables.d.ts +9 -0
  99. package/dist/shared/css-variables.js +38 -0
  100. package/dist/shared/css.d.ts +78 -0
  101. package/dist/shared/css.js +426 -0
  102. package/dist/shared/element-match.d.ts +16 -0
  103. package/dist/shared/element-match.js +72 -0
  104. package/dist/shared/font-weights.d.ts +2 -0
  105. package/dist/shared/font-weights.js +551 -0
  106. package/dist/shared/index.d.ts +16 -0
  107. package/dist/shared/index.js +15 -0
  108. package/dist/shared/interactions-config.d.ts +15 -0
  109. package/dist/shared/interactions-config.js +120 -0
  110. package/dist/shared/links.d.ts +21 -0
  111. package/dist/shared/links.js +93 -0
  112. package/dist/shared/posix-path.d.ts +8 -0
  113. package/dist/shared/posix-path.js +27 -0
  114. package/dist/shared/site-files-tree-mapping.d.ts +40 -0
  115. package/dist/shared/site-files-tree-mapping.js +41 -0
  116. package/dist/shared/site-folders.d.ts +3 -0
  117. package/dist/shared/site-folders.js +17 -0
  118. package/dist/shared/site-media.d.ts +3 -0
  119. package/dist/shared/site-media.js +11 -0
  120. package/dist/shared/syntax-tree.d.ts +4 -0
  121. package/dist/shared/syntax-tree.js +30 -0
  122. package/dist/shared/transformation-values.d.ts +22 -0
  123. package/dist/shared/transformation-values.js +74 -0
  124. package/dist/shared/types.d.ts +477 -0
  125. package/dist/shared/types.js +1 -0
  126. package/dist/shared/utils.d.ts +155 -0
  127. package/dist/shared/utils.js +553 -0
  128. package/dist/shared/wrapper-contract.d.ts +31 -0
  129. package/dist/shared/wrapper-contract.js +157 -0
  130. package/dist/shared/wrapper-image-props.d.ts +3 -0
  131. package/dist/shared/wrapper-image-props.js +75 -0
  132. package/dist/site-code-model/constants.d.ts +107 -0
  133. package/dist/site-code-model/constants.js +102 -0
  134. package/dist/site-code-model/index.d.ts +3 -0
  135. package/dist/site-code-model/index.js +4 -0
  136. package/dist/site-code-model/manifest-values.d.ts +15 -0
  137. package/dist/site-code-model/manifest-values.js +88 -0
  138. package/dist/site-code-model/read-module.d.ts +4 -0
  139. package/dist/site-code-model/read-module.js +267 -0
  140. package/dist/site-code-model/read-site-code-model.d.ts +9 -0
  141. package/dist/site-code-model/read-site-code-model.js +42 -0
  142. package/dist/site-code-model/source-locations.d.ts +5 -0
  143. package/dist/site-code-model/source-locations.js +95 -0
  144. package/dist/site-code-model/types.d.ts +102 -0
  145. package/dist/site-code-model/types.js +1 -0
  146. package/dist/testing.d.ts +24 -0
  147. package/dist/testing.js +61 -0
  148. package/dist/types.d.ts +95 -0
  149. package/dist/types.js +1 -0
  150. package/dist/validate.d.ts +7 -0
  151. package/dist/validate.js +180 -0
  152. package/package.json +59 -3
@@ -0,0 +1,426 @@
1
+ import { ATTRIBUTE_SELECTOR, BASE_CLASS, CSS_IDENT, CSS_NAME, DASHED_ID, FONT_SIZE, FONT_WEIGHT_NUMBER, FUNCTIONAL_PSEUDO, LEGACY_ATTRIBUTE, LAYOUT_CLASS_SELECTOR, LAYOUT_VARIABLE_TOKEN, LINK_HTML_ENTITIES, NAMED_QUERY, PREAMBLE_LAYER, PSEUDO_CLASS, QUOTED_STRING, RESERVED_IDENTIFIERS, SCOPE_OWNER, STATE_CLASS, STYLE_ATTRIBUTE, THEME_FONT_TOKEN, TYPE_CLASS, TYPE_SELECTOR, VAR_WITHOUT_FALLBACK, } from "./constants.js";
2
+ /** Every `--name: value` in a file, wherever it's declared, in order. No file → none. */
3
+ export function readThemeTokens(file) {
4
+ const tokens = [];
5
+ file?.walkDecls(/^--/, ({ prop, value, source }) => {
6
+ tokens.push({ name: prop, value: value.trim(), line: source?.start?.line ?? 1 });
7
+ });
8
+ return tokens;
9
+ }
10
+ /** The theme's font tokens (`--wst-heading-1-font: …`), as readThemeTokens reads them. */
11
+ export const readThemeFontTokens = (file) => readThemeTokens(file).filter(({ name }) => THEME_FONT_TOKEN.test(name));
12
+ /** Every `@custom-media --name (query)` at a file's top level, in order, as the import reads them; theme.css's are the site's breakpoints. No file → none. */
13
+ export function readCustomMedia(file) {
14
+ if (file === undefined)
15
+ return [];
16
+ return file.nodes.flatMap((node) => (node.type === 'atrule' && node.name === 'custom-media' ? [{ ...parseCustomMedia(node.params), line: node.source?.start?.line ?? 1 }] : []));
17
+ }
18
+ /** A `@media` query's params → the breakpoint name it uses: '(--tablet)' → '--tablet'; null for a range or anything that isn't one name. */
19
+ export const readBreakpointName = (query) => NAMED_QUERY.exec(query.trim())?.[1] ?? null;
20
+ /** `--tablet (max-width: 1023px)` → its name and its query, as written (the import compares the text). A malformed declaration keeps what it has: `mobile (…)` → name 'mobile'; `--phone` → query ''. */
21
+ function parseCustomMedia(params) {
22
+ const [, name = '', query = ''] = /^(\S*)\s*([\s\S]*)$/.exec(params.trim()) ?? [];
23
+ return { name, query };
24
+ }
25
+ /** A layout value as the import reads it (layoutVariables.ts literalOf): `var(--name, <fallback>)`, a field connected to one of the site's layout
26
+ * variables, by its fallback; any other value as is. */
27
+ export const getLayoutLiteral = (value) => readLayoutVariable(value)?.fallback ?? value;
28
+ /** `var(--name, <fallback>)` → the variable's name (no `--`) and its fallback, as written; undefined for any other value (layoutVariables.ts parseLayoutVariableToken). */
29
+ export function readLayoutVariable(value) {
30
+ const match = LAYOUT_VARIABLE_TOKEN.exec(value);
31
+ return match ? { name: match[1], fallback: match[2] } : undefined;
32
+ }
33
+ /** A `font` shorthand's weight and family; undefined for a `var(…)` or a value with no family after its size. */
34
+ export function readFontShorthand(value) {
35
+ if (value.includes('var('))
36
+ return undefined;
37
+ const parts = splitFontParts(value);
38
+ const size = parts.findLastIndex((part) => FONT_SIZE.test(part));
39
+ if (size === -1 || size === parts.length - 1)
40
+ return undefined;
41
+ return { weight: readFontWeight(parts.slice(0, size)), family: parts.slice(size + 1).join(' ') };
42
+ }
43
+ /** The weight among a shorthand's parts before its size: a number, `bold`, or 400 (`normal`, or none written). */
44
+ function readFontWeight(parts) {
45
+ for (const part of parts) {
46
+ if (FONT_WEIGHT_NUMBER.test(part))
47
+ return Number(part);
48
+ const keyword = part.toLowerCase();
49
+ if (keyword === 'bold')
50
+ return 700;
51
+ if (keyword === 'bolder' || keyword === 'lighter')
52
+ return undefined;
53
+ }
54
+ return 400;
55
+ }
56
+ /** A value split on top-level whitespace, so `--spx(16)/1.3em` stays one part. */
57
+ function splitFontParts(value) {
58
+ const parts = [];
59
+ let depth = 0;
60
+ let current = '';
61
+ for (const char of value) {
62
+ if (char === '(')
63
+ depth++;
64
+ else if (char === ')')
65
+ depth--;
66
+ if (depth === 0 && /\s/.test(char)) {
67
+ if (current)
68
+ parts.push(current);
69
+ current = '';
70
+ }
71
+ else
72
+ current += char;
73
+ }
74
+ if (current)
75
+ parts.push(current);
76
+ return parts;
77
+ }
78
+ /** Whether a style rule sits inside another style rule, through any at-rules between them (`.a { .b { } }`, `.a { @media (…) { .b { } } }`). */
79
+ export function isInsideRule(rule) {
80
+ for (let parent = rule.parent; parent && parent.type !== 'root'; parent = parent.parent)
81
+ if (parent.type === 'rule')
82
+ return true;
83
+ return false;
84
+ }
85
+ /** style.css's rules by their selector's first class, each once, as the import reads them: a rule inside another rule or a `@mixin` is left
86
+ * out (astParser.ts parseStyleRuleAsRecords), and an empty or `@apply`-only rule, which has no line in `page.css`, is in. */
87
+ export function readStyleRules(file) {
88
+ const byClassName = new Map();
89
+ file?.walkRules((rule) => {
90
+ if (isInsideRule(rule) || isInMixin(rule))
91
+ return;
92
+ for (const written of rule.selectors) {
93
+ const { owner, selector } = parseComponentSelector(written);
94
+ if (!owner?.startsWith('.'))
95
+ continue;
96
+ const className = unescapeName(owner.slice(1));
97
+ byClassName.set(className, [...(byClassName.get(className) ?? []), { selector, line: rule.source?.start?.line ?? 1 }]);
98
+ }
99
+ });
100
+ return byClassName;
101
+ }
102
+ /** Whether a rule sits in a `@mixin`, through any at-rules between them. */
103
+ function isInMixin(rule) {
104
+ for (let parent = rule.parent; parent && parent.type !== 'root'; parent = parent.parent)
105
+ if (parent.type === 'atrule' && parent.name === 'mixin')
106
+ return true;
107
+ return false;
108
+ }
109
+ /** A container's children, comments aside; none for a node with no block. */
110
+ export const getCssChildren = (node) => (node.nodes ?? []).filter((child) => child.type !== 'comment');
111
+ /** Whether a property picks a preset (css/utils.ts `isPresetProperty`): `--preset` (the rule's own element) or `--preset-<part path>`. */
112
+ export const isPresetProperty = (prop) => prop === '--preset' || prop.startsWith('--preset-');
113
+ /** The id a `@mixin` or `@apply` names: '--btn' → 'btn' (spaces around aside); undefined when its params aren't `--` and one word. */
114
+ export const getDashedId = (params) => DASHED_ID.exec(params.trim())?.[1];
115
+ /** The id a `@mixin` declares (`--btn` → 'btn'), or null when it isn't one dashed identifier. */
116
+ export function getMixinId(mixin) {
117
+ const id = getDashedId(mixin.params);
118
+ return id !== undefined && isSafeCssIdentifier(id) ? id : null;
119
+ }
120
+ /** Whether a `@scope` names its owner as the import reads it: `(.class)`, one element's class (css/ast/utils.ts parseScopeOwner at converter 0.97.0). */
121
+ export const hasScopeOwner = (scope) => SCOPE_OWNER.test(scope.params.trim());
122
+ /** Whether the import reads this as an identifier (cssSelectors.ts `isCssIdentifier`): letters, digits, - and _, not starting with a digit. */
123
+ export const isCssIdentifier = (id) => CSS_IDENT.test(id);
124
+ /** Whether the import takes this as a name (a mixin id, a preset path's part; cssSelectors.ts `isSafeCssIdentifier`): an identifier, not a reserved name. */
125
+ export const isSafeCssIdentifier = (id) => !RESERVED_IDENTIFIERS.has(id) && isCssIdentifier(id);
126
+ /** The selector's parts, split on spaces outside brackets and quotes, a combinator kept with its sides (cssSelectors.ts splitSegments); null for a list or an unbalanced bracket: the selectors rows'. */
127
+ export function getSelectorSegments(selector) {
128
+ const segments = [];
129
+ let current = '';
130
+ let depth = 0;
131
+ let quote;
132
+ let escaped = false;
133
+ for (const char of selector) {
134
+ if (escaped) {
135
+ current += char;
136
+ escaped = false;
137
+ continue;
138
+ }
139
+ if (char === '\\') {
140
+ current += char;
141
+ escaped = true;
142
+ continue;
143
+ }
144
+ if (quote) {
145
+ if (char === quote)
146
+ quote = undefined;
147
+ }
148
+ else if (char === '"' || char === "'")
149
+ quote = char;
150
+ else if (char === '[' || char === '(')
151
+ depth += 1;
152
+ else if (char === ']' || char === ')')
153
+ depth -= 1;
154
+ else if (char === ',' && depth === 0)
155
+ return null;
156
+ if (depth < 0)
157
+ return null;
158
+ if (/\s/.test(char) && depth === 0 && !quote) {
159
+ if (current)
160
+ segments.push(current);
161
+ current = '';
162
+ }
163
+ else
164
+ current += char;
165
+ }
166
+ if (quote || depth > 0)
167
+ return null;
168
+ if (current)
169
+ segments.push(current);
170
+ return segments.reduce((merged, segment) => {
171
+ const previous = merged.at(-1);
172
+ if (previous !== undefined && (/[>+~]$/.test(previous) || /^[>+~]/.test(segment)))
173
+ merged[merged.length - 1] = `${previous} ${segment}`;
174
+ else
175
+ merged.push(segment);
176
+ return merged;
177
+ }, []);
178
+ }
179
+ /** The selector at its combinators, each kept with the spaces around it, so the odd parts are the combinators: '.a > .b' → ['.a', ' > ', '.b'],
180
+ * as origami-lint master's split; a `>`, `+` or `~` inside an attribute, also in a quoted value, is none ('[data-hook~="x"]', '[data-label="x > [ y"]'), and so is an escaped one.
181
+ * One pass: a long selector costs no more than its length. */
182
+ export function splitAtCombinators(selector) {
183
+ const parts = [];
184
+ let start = 0;
185
+ let inAttribute = false;
186
+ let quote;
187
+ for (let index = 0; index < selector.length; index++) {
188
+ const char = selector[index];
189
+ if (char === '\\')
190
+ index++;
191
+ else if (quote) {
192
+ if (char === quote)
193
+ quote = undefined;
194
+ }
195
+ else if (inAttribute) {
196
+ if (char === '"' || char === "'")
197
+ quote = char;
198
+ else if (char === ']')
199
+ inAttribute = false;
200
+ }
201
+ else if (char === '[')
202
+ inAttribute = true;
203
+ else if (char === '>' || char === '+' || char === '~') {
204
+ let from = index;
205
+ while (from > start && /\s/.test(selector[from - 1]))
206
+ from--;
207
+ let to = index + 1;
208
+ while (to < selector.length && /\s/.test(selector[to]))
209
+ to++;
210
+ parts.push(selector.slice(start, from), selector.slice(from, to));
211
+ start = to;
212
+ index = to - 1;
213
+ }
214
+ }
215
+ parts.push(selector.slice(start));
216
+ return parts;
217
+ }
218
+ /** A part with `&` anywhere outside brackets and quotes, as the import reads it: `&` first, the rest its states (`&&:hover` → `&:hover`,
219
+ * `.x&` → `&.x`; selectorSyntax.ts parseSelectorChain:123 at converter 0.101.0). Any other part as written. */
220
+ export function readAmpersands(segment) {
221
+ let depth = 0;
222
+ let inQuotes = false;
223
+ let rest = '';
224
+ for (const char of segment) {
225
+ if (inQuotes)
226
+ inQuotes = char !== '"';
227
+ else if (char === '"')
228
+ inQuotes = true;
229
+ else if (char === '[' || char === '(')
230
+ depth += 1;
231
+ else if (char === ']' || char === ')')
232
+ depth -= 1;
233
+ else if (char === '&' && depth === 0)
234
+ continue;
235
+ rest += char;
236
+ }
237
+ return rest.length === segment.length ? segment : `&${rest}`;
238
+ }
239
+ /** A segment's base, states and what the import can't read. A functional pseudo-class (`:not(:hover)`) or an attribute (`[data-state~="open"]`)
240
+ * right after the class is part of the class; after a state, after `&` or after a type selector, it isn't read. A class right after a type
241
+ * selector is part of it (`a.link`), as a class glued to a class is; after a state it's a state (`a:hover.open`). */
242
+ export function readSegment(segment) {
243
+ const type = segment.startsWith('&') ? undefined : TYPE_SELECTOR.exec(segment)?.[0];
244
+ const leadingAttribute = LEGACY_ATTRIBUTE.test(segment) ? undefined : ATTRIBUTE_SELECTOR.exec(segment)?.[0];
245
+ let base = segment.startsWith('&') ? '&' : (BASE_CLASS.exec(segment)?.[0] ?? type ?? leadingAttribute);
246
+ const isClass = base !== undefined && base !== '&' && type === undefined;
247
+ const states = [];
248
+ let rest = segment.slice(base?.length ?? 0);
249
+ while (rest) {
250
+ const gluedToClass = isClass && states.length === 0;
251
+ const typeClass = type !== undefined && states.length === 0 ? TYPE_CLASS.exec(rest) : null;
252
+ const functional = gluedToClass ? FUNCTIONAL_PSEUDO.exec(rest) : null;
253
+ const state = functional || typeClass ? null : ((type === undefined ? STATE_CLASS : TYPE_CLASS).exec(rest) ?? PSEUDO_CLASS.exec(rest));
254
+ const attribute = functional || typeClass || state || !gluedToClass ? null : ATTRIBUTE_SELECTOR.exec(rest);
255
+ const token = (typeClass ?? functional ?? state ?? attribute)?.[0];
256
+ if (token === undefined)
257
+ break;
258
+ if (state)
259
+ states.push(token);
260
+ else
261
+ base += token;
262
+ rest = rest.slice(token.length);
263
+ }
264
+ return { base, states, unread: rest, ...(type !== undefined && { type }), ...(leadingAttribute !== undefined && { attribute: leadingAttribute }) };
265
+ }
266
+ /** A segment's class, its states taken out: `&:hover` → `&`; `.label:hover` → `.label`; `.label.open` → `.label`; a type selector's part
267
+ * the same way (`a:hover` → `a`, `a.link:hover` → `a.link`). Null for a segment the import can't parse: a part with no class or type (`[data-ie-name="x"]`, `:hover`
268
+ * alone, `:root`), or `&` or a type followed by anything but a state (`&[x]`, `&:not(…)`, `&a`, `a[x]`). */
269
+ export function getSegmentClass(segment) {
270
+ const { base, unread, attribute } = readSegment(segment);
271
+ return base === undefined || unread || attribute !== undefined ? null : base;
272
+ }
273
+ /**
274
+ * Whether a selector's first segment names a component as the import reads it (parseComponentChain, withStateClasses): its own class, the
275
+ * classes after it its state classes (`.comp-a.comp-a--open`, `.comp-a.constructor`), a safe identifier. `.comp-a[data-x]` isn't: an
276
+ * attribute is part of the class, read whole (the selectors rows').
277
+ */
278
+ export function hasComponentClass(segment) {
279
+ const base = getSegmentClass(segment);
280
+ // a type selector starts no selector (cssSelectors.ts leadingTokensOf:122 at converter 0.103.0): `div`, `span.comp-x` are the selectors rows'
281
+ if (base === null || !base.startsWith('.'))
282
+ return false;
283
+ const className = base.slice(1);
284
+ return isSafeCssIdentifier(/^[^:[\]"]+$/.test(className) ? className.split('.')[0] : className);
285
+ }
286
+ // ── layout.css, as the import reads it (layoutParser.ts) ──
287
+ /** layout.css's rule blocks in order, as the import reads them: at the top level, in each `@media`, and in each `@scope`'s `@media`. The preamble layer is skipped. */
288
+ export function readLayoutRuleBlocks(root) {
289
+ const blocks = [];
290
+ const readRules = (container, media) => {
291
+ for (const node of container.nodes ?? []) {
292
+ if (node.type === 'rule') {
293
+ const element = LAYOUT_CLASS_SELECTOR.exec(node.selector.trim())?.[1];
294
+ if (element)
295
+ blocks.push(readLayoutRuleBlock(element, media, node));
296
+ }
297
+ else if (node.type === 'atrule' && media === null) {
298
+ if (node.name === 'media')
299
+ readRules(node, node.params.trim());
300
+ else if (node.name === 'scope')
301
+ readRules(node, null);
302
+ }
303
+ }
304
+ };
305
+ readRules(root, null);
306
+ return blocks;
307
+ }
308
+ function readLayoutRuleBlock(element, media, rule) {
309
+ const block = { element, media, rule, declarations: [], targets: new Map() };
310
+ for (const node of rule.nodes) {
311
+ if (node.type === 'decl')
312
+ block.declarations.push(node);
313
+ else if (node.type === 'atrule' && node.name === 'origami-target' && node.nodes) {
314
+ const target = node.params.trim();
315
+ block.targets.set(target, [...(block.targets.get(target) ?? []), ...node.nodes.filter((child) => child.type === 'decl')]);
316
+ }
317
+ }
318
+ return block;
319
+ }
320
+ /** The blocks merged per element and breakpoint, the default scopes first (a breakpoint inherits the default's container type); a target's declarations join the rule's. */
321
+ export function mergeLayoutScopes(blocks) {
322
+ const scopes = new Map();
323
+ for (const block of blocks) {
324
+ const key = `${block.media ?? ''}\n${block.element}`;
325
+ const scope = scopes.get(key) ?? { element: block.element, media: block.media, values: new Map(), rulesWithTargets: [] };
326
+ scopes.set(key, scope);
327
+ for (const decl of [...block.declarations, ...[...block.targets.values()].flat()])
328
+ scope.values.set(decl.prop, decl);
329
+ if (block.targets.size)
330
+ scope.rulesWithTargets.push(block.rule);
331
+ }
332
+ return [...scopes.values()].sort((a, b) => Number(a.media !== null) - Number(b.media !== null));
333
+ }
334
+ /** Whether a node sits in the `@layer spx-preamble { … }` block the export writes at the top of every file (PREAMBLE_LAYER), which the import skips. */
335
+ export function isInPreamble(node) {
336
+ for (let parent = node.parent; parent && parent.type !== 'root'; parent = parent.parent) {
337
+ if (parent.type === 'atrule' && parent.name === 'layer' && parent.params.trim() === PREAMBLE_LAYER)
338
+ return true;
339
+ }
340
+ return false;
341
+ }
342
+ // ── which component a selector belongs to (the one of its first `.x`): the page model and readStyleRules read it ──
343
+ /** A selector's owner is its first `.x` or `#x` outside [attribute] brackets (only the first is read): '.comp-x' → '.comp-x', '&';
344
+ * '.comp-x:hover' → '.comp-x', '&:hover'; '.comp-x .label' → '.comp-x', '& .label'; '#comp-x' → '#comp-x', '&'; ':root' → null, ':root'. */
345
+ export function parseComponentSelector(selector) {
346
+ const normalized = selector.replace(/\s+/g, ' ').trim();
347
+ const owner = findOwner(normalized);
348
+ if (!owner)
349
+ return { owner: null, selector: normalized };
350
+ return { owner: owner.text, selector: `${normalized.slice(0, owner.start)}&${normalized.slice(owner.start + owner.text.length)}` };
351
+ }
352
+ /** `a\:b` → 'a:b', `\31 23` → '123': the class name an escaped selector names. */
353
+ export const unescapeName = (name) => name.replace(/\\([0-9a-fA-F]{1,6})\s?|\\(.)/g, (_, hex, char) => (hex ? String.fromCodePoint(parseInt(hex, 16)) : char));
354
+ /** The first `.name` or `#name` outside [ ] (an attribute's value can hold a dot), a quoted value (it can hold a `]`) and ( ) (`:not(.x)`,
355
+ * `:is(.a, .b)` name other elements or a choice, not the one the rule is on). */
356
+ function findOwner(selector) {
357
+ let depth = 0;
358
+ let quote = null;
359
+ for (let index = 0; index < selector.length; index++) {
360
+ const char = selector[index];
361
+ if (quote) {
362
+ if (char === '\\')
363
+ index++;
364
+ else if (char === quote)
365
+ quote = null;
366
+ }
367
+ else if (char === '"' || char === "'")
368
+ quote = char;
369
+ else if (char === '\\')
370
+ index++;
371
+ else if (char === '[' || char === '(')
372
+ depth++;
373
+ else if (char === ']' || char === ')')
374
+ depth--;
375
+ else if (depth === 0 && (char === '.' || char === '#')) {
376
+ const name = CSS_NAME.exec(selector.slice(index + 1))?.[0];
377
+ if (name)
378
+ return { text: `${char}${name}`, start: index };
379
+ }
380
+ }
381
+ return null;
382
+ }
383
+ /** Each `var(--name)` without a fallback in the `style="…"` attributes of a rich text's html: unescaped, split at each `;` outside a quoted
384
+ * string and ( ) (splitDeclarations), in order. */
385
+ export function getRichTextStyleVariables(html) {
386
+ return [...html.matchAll(STYLE_ATTRIBUTE)].flatMap(([, double, single]) => splitDeclarations(unescapeHtml(double ?? single ?? '')).flatMap((declaration) => {
387
+ const colon = declaration.indexOf(':');
388
+ if (colon <= 0)
389
+ return [];
390
+ const value = declaration.slice(colon + 1).trim();
391
+ // a `var(…)` inside a quoted string is text, as the import's csstree reads it
392
+ return [...value.replace(QUOTED_STRING, '""').matchAll(VAR_WITHOUT_FALLBACK)].map(([, name]) => ({ property: declaration.slice(0, colon).trim(), value, name: name }));
393
+ }));
394
+ }
395
+ /** `content: 'a; b'; color: red` → ["content: 'a; b'", ' color: red']: split at each `;` outside a quoted string and ( ), as csstree reads
396
+ * a declaration list (a `;` inside `content: '…'` or `url(…)` is part of the value). */
397
+ function splitDeclarations(style) {
398
+ const declarations = [];
399
+ let start = 0;
400
+ let depth = 0;
401
+ let quote = null;
402
+ for (let index = 0; index < style.length; index++) {
403
+ const char = style[index];
404
+ if (quote) {
405
+ if (char === '\\')
406
+ index++;
407
+ else if (char === quote)
408
+ quote = null;
409
+ }
410
+ else if (char === '"' || char === "'")
411
+ quote = char;
412
+ else if (char === '(')
413
+ depth++;
414
+ else if (char === ')')
415
+ depth--;
416
+ else if (char === ';' && depth === 0) {
417
+ declarations.push(style.slice(start, index));
418
+ start = index + 1;
419
+ }
420
+ }
421
+ return [...declarations, style.slice(start)];
422
+ }
423
+ /** An html attribute's value as the converter reads it (lodash unescape): the five entities it writes. */
424
+ export function unescapeHtml(value) {
425
+ return value.replace(/&(amp|lt|gt|quot|#39);/g, (_, entity) => LINK_HTML_ENTITIES[entity]);
426
+ }
@@ -0,0 +1,16 @@
1
+ /** The selector's compounds, split at its combinators outside parentheses and brackets, each with the combinator before it: `>`, `+`, `~`,
2
+ * ' ' for a descendant, '' for the first. */
3
+ export declare function chainOf(selector: string): {
4
+ combinator: string;
5
+ compound: string;
6
+ }[];
7
+ /** A compound's own ids and classes, `#comp-1` and `.button`, not those in its `:not(…)` or attributes. */
8
+ export declare function namesOf(compound: string): string[];
9
+ /** The element of `elements`, selectors inside a component's (`.dropdown`, `.button.hamburger-open-button .label`), that a selector's
10
+ * compounds past the component's (each its names, namesOf) are nearest to: the one matched at the latest compound, on a tie the one of more
11
+ * compounds, then of more names (the more specific, as DMS's converter picks the element a compound matches exactly:
12
+ * `.button.hamburger-close-button` over `.button`); undefined for none. `end` is the compound it's matched at. */
13
+ export declare function nearestElement(elements: Iterable<string>, compounds: string[][]): {
14
+ selector: string;
15
+ end: number;
16
+ } | undefined;
@@ -0,0 +1,72 @@
1
+ // origami-transforms/elementMatch.js at Origami 76488285 (#919): which of a component's elements a selector names, the way the custom-enums
2
+ // CSS plugin resolves an enum to its element. Copied here: origami-transforms doesn't publish it yet, and the lint must match the build.
3
+ /** The selector's compounds, split at its combinators outside parentheses and brackets, each with the combinator before it: `>`, `+`, `~`,
4
+ * ' ' for a descendant, '' for the first. */
5
+ export function chainOf(selector) {
6
+ const chain = [];
7
+ let combinator = '';
8
+ let compound = '';
9
+ let depth = 0;
10
+ for (const char of selector.trim()) {
11
+ if (char === '(' || char === '[')
12
+ depth++;
13
+ if (char === ')' || char === ']')
14
+ depth--;
15
+ if (depth === 0 && /[\s>+~]/.test(char)) {
16
+ if (compound !== '') {
17
+ chain.push({ combinator, compound });
18
+ compound = '';
19
+ combinator = ' ';
20
+ }
21
+ if (/[>+~]/.test(char))
22
+ combinator = char;
23
+ }
24
+ else
25
+ compound += char;
26
+ }
27
+ if (compound !== '')
28
+ chain.push({ combinator, compound });
29
+ return chain;
30
+ }
31
+ /** A compound's own ids and classes, `#comp-1` and `.button`, not those in its `:not(…)` or attributes. */
32
+ export function namesOf(compound) {
33
+ let own = compound.replace(/\[[^\]]*\]/g, '');
34
+ while (/\([^()]*\)/.test(own))
35
+ own = own.replace(/\([^()]*\)/g, '');
36
+ return own.match(/[.#][\w-]+/g) ?? [];
37
+ }
38
+ /** The last of `compounds` that `element`'s compounds match, each a descendant of the one before, or -1: an element matches a compound that
39
+ * has all its names, `.button.hamburger-open-button` matching `.button.hamburger-open-button.x`. */
40
+ function lastMatch(element, compounds) {
41
+ const covers = (names, wanted) => wanted.every((name) => names.includes(name));
42
+ for (let end = compounds.length - 1; end >= 0; end--) {
43
+ if (!covers(compounds[end], element.at(-1) ?? []))
44
+ continue;
45
+ let matched = 0;
46
+ for (let at = 0; at < end && matched < element.length - 1; at++)
47
+ if (covers(compounds[at], element[matched]))
48
+ matched++;
49
+ if (matched === element.length - 1)
50
+ return end;
51
+ }
52
+ return -1;
53
+ }
54
+ /** The element of `elements`, selectors inside a component's (`.dropdown`, `.button.hamburger-open-button .label`), that a selector's
55
+ * compounds past the component's (each its names, namesOf) are nearest to: the one matched at the latest compound, on a tie the one of more
56
+ * compounds, then of more names (the more specific, as DMS's converter picks the element a compound matches exactly:
57
+ * `.button.hamburger-close-button` over `.button`); undefined for none. `end` is the compound it's matched at. */
58
+ export function nearestElement(elements, compounds) {
59
+ let nearest;
60
+ let rank = [-1, 0, 0];
61
+ for (const selector of new Set(elements)) {
62
+ const element = chainOf(selector).map(({ compound }) => namesOf(compound));
63
+ const end = lastMatch(element, compounds);
64
+ const ranked = [end, element.length, element.flat().length];
65
+ const first = ranked.findIndex((value, at) => value !== rank[at]);
66
+ if (end !== -1 && first !== -1 && ranked[first] > rank[first]) {
67
+ nearest = { selector, end };
68
+ rank = ranked;
69
+ }
70
+ }
71
+ return nearest;
72
+ }
@@ -0,0 +1,2 @@
1
+ import type { FontCatalog } from './types.ts';
2
+ export declare const FONT_WEIGHTS: FontCatalog;