@sloppy-ai/verify 0.0.0-stage → 1.4.0

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.
@@ -0,0 +1,130 @@
1
+ // PostCSS owns CSS syntax (including nesting, comments, strings and at-rules).
2
+ // This checker compares class namespaces, not the full CSS cascade. Different
3
+ // explicit root scopes and CSS Modules are isolated; an unscoped class overlaps
4
+ // every scope with that class. Composed/overlapping scopes still need review.
5
+ export function splitSelectors(value) {
6
+ const parts = []
7
+ let start = 0, depth = 0, quote = null, escaped = false
8
+ for (let i = 0; i < value.length; i++) {
9
+ const char = value[i]
10
+ if (escaped) { escaped = false; continue }
11
+ if (char === '\\') { escaped = true; continue }
12
+ if (quote) { if (char === quote) quote = null; continue }
13
+ if (char === '"' || char === "'") { quote = char; continue }
14
+ if (char === '(' || char === '[') depth++
15
+ else if (char === ')' || char === ']') depth--
16
+ else if (char === ',' && depth === 0) { parts.push(value.slice(start, i).trim()); start = i + 1 }
17
+ }
18
+ parts.push(value.slice(start).trim())
19
+ return parts.filter(Boolean)
20
+ }
21
+
22
+ function withoutConditions(selector) {
23
+ // :not() and :has() filter matches; their argument classes are not classes
24
+ // being styled. Ignore those conditions conservatively when finding a root.
25
+ let result = ''
26
+ for (let i = 0; i < selector.length; i++) {
27
+ const match = selector.slice(i).match(/^:(?:not|has)\(/)
28
+ if (!match) { result += selector[i]; continue }
29
+ i += match[0].length
30
+ let depth = 1, quote = null
31
+ for (; i < selector.length && depth; i++) {
32
+ const char = selector[i]
33
+ if (char === '\\') { i++; continue }
34
+ if (quote) { if (char === quote) quote = null; continue }
35
+ if (char === '"' || char === "'") quote = char
36
+ else if (char === '(') depth++
37
+ else if (char === ')') depth--
38
+ }
39
+ i--
40
+ }
41
+ return result
42
+ }
43
+
44
+ function unwrapAttributeWhere(selector) {
45
+ // A single plain attribute does not branch. Unwrap it, then let the normal
46
+ // attribute stripping below discard it; attribute values are not exclusive
47
+ // namespace roots. Escapes, compounds and selector lists still need review.
48
+ const simple = /^:where\(\s*(\[\s*-?[_a-zA-Z][\w-]*(?:\s*[~|^$*]?=\s*(?:"[^"\\\[\]]*"|'[^'\\\[\]]*'|-?[_a-zA-Z][\w-]*)(?:\s+[is])?)?\s*\])\s*\)/
49
+ let result = '', attributeDepth = 0, quote = null
50
+ for (let i = 0; i < selector.length; i++) {
51
+ const char = selector[i]
52
+ if (char === '\\') { result += selector.slice(i, i + 2); i++; continue }
53
+ if (quote) { result += char; if (char === quote) quote = null; continue }
54
+ if (char === '"' || char === "'") quote = char
55
+ if (!attributeDepth && char === ':') {
56
+ const match = selector.slice(i).match(simple)
57
+ if (match) { result += match[1]; i += match[0].length - 1; continue }
58
+ }
59
+ if (char === '[') attributeDepth++
60
+ else if (char === ']') attributeDepth--
61
+ result += char
62
+ }
63
+ return result
64
+ }
65
+
66
+ export function classDefinitions(css, file, parse) {
67
+ const root = parse(css, { from: file })
68
+ const definitions = []
69
+ const manual = []
70
+ const selectorsFor = (node) => {
71
+ if (!node || node.type === 'root') return ['']
72
+ const parents = selectorsFor(node.parent)
73
+ if (node.type === 'rule') {
74
+ return parents.flatMap((parent) => splitSelectors(node.selector).map((selector) => selector.includes('&') ? selector.replaceAll('&', parent || ':root') : `${parent} ${selector}`.trim()))
75
+ }
76
+ if (node.type === 'atrule' && node.name.toLowerCase() === 'scope') {
77
+ const match = node.params.match(/^\s*\(([^()]*)\)/)
78
+ if (!match) { manual.push(`@scope at ${file}:${node.source.start.line} has a complex/implicit root; inspect its isolation`); return parents }
79
+ return parents.flatMap((parent) => splitSelectors(match[1]).map((scope) => `${parent} ${scope}`.trim()))
80
+ }
81
+ return parents
82
+ }
83
+ root.walkRules((rule) => {
84
+ for (let parent = rule.parent; parent; parent = parent.parent) if (parent.type === 'atrule' && /keyframes$/i.test(parent.name)) return
85
+ // A nesting-only block doesn't itself paint a selector.
86
+ if (!rule.nodes.some((node) => node.type === 'decl')) return
87
+ for (const selector of selectorsFor(rule)) {
88
+ const stripped = withoutConditions(unwrapAttributeWhere(selector))
89
+ const branch = stripped.search(/:(?:is|where)\(/)
90
+ const scopedBranch = branch >= 0 && /[.#](-?[_a-zA-Z][\w-]*)/.test(stripped.slice(0, branch))
91
+ if (/\\|:(?:global|local)\(/.test(stripped) || branch >= 0 && !scopedBranch) manual.push(`selector at ${file}:${rule.source.start.line} uses escapes or branching logic without a clear root; inspect namespace overlap: ${selector}`)
92
+ // Quoted attribute values may contain dots that are not classes.
93
+ const structural = stripped.replace(/\[[^\]]*\]/g, '')
94
+ const classes = [...structural.matchAll(/\.(-?[_a-zA-Z][\w-]*)/g)]
95
+ for (let i = 0; i < classes.length; i++) {
96
+ const name = classes[i][1]
97
+ if (name.startsWith('ss-')) continue
98
+ const before = structural.slice(0, classes[i].index)
99
+ const anchor = before.match(/[.#](-?[_a-zA-Z][\w-]*)/)?.[0] || ''
100
+ definitions.push({ name, scope: /\.module\.css$/i.test(file) && !selector.includes(':global(') ? `module:${file}` : anchor, file, line: rule.source.start.line, selector })
101
+ }
102
+ }
103
+ })
104
+ return { definitions, manual: [...new Set(manual)] }
105
+ }
106
+
107
+ export function findClashes(definitions) {
108
+ const groups = new Map()
109
+ for (const definition of definitions) {
110
+ const list = groups.get(definition.name) || []
111
+ list.push(definition)
112
+ groups.set(definition.name, list)
113
+ }
114
+ const findings = []
115
+ for (const [name, group] of groups) {
116
+ const overlaps = new Map()
117
+ for (let a = 0; a < group.length; a++) for (let b = a + 1; b < group.length; b++) {
118
+ const left = group[a], right = group[b]
119
+ if (left.file === right.file) continue
120
+ // Explicit stylesheet bundles are one component's cascade. They may
121
+ // share selectors internally, but still collide with another bundle.
122
+ if (left.owner && left.owner === right.owner) continue
123
+ if (left.scope.startsWith('module:') || right.scope.startsWith('module:')) continue
124
+ if (left.scope && right.scope && left.scope !== right.scope) continue
125
+ for (const item of [left, right]) overlaps.set(`${item.file}:${item.line}`, item)
126
+ }
127
+ if (overlaps.size) findings.push({ name, definitions: [...overlaps.values()] })
128
+ }
129
+ return findings.sort((a, b) => a.name.localeCompare(b.name))
130
+ }
@@ -0,0 +1,52 @@
1
+ // Classes defined by more than one demo's CSS. Two demos on one page that both
2
+ // define .cp-nav restyle each other, and whichever loads last wins.
3
+ //
4
+ // node scripts/class-clash.mjs this repo's examples, showcase and site demos
5
+ // node scripts/class-clash.mjs src/demos a.css any folders or files in your project
6
+ //
7
+ // Checks namespaces, including nested CSS and @scope. It cannot prove that
8
+ // arbitrarily composed roots never overlap; inspect those on the host page.
9
+ import { readFileSync, statSync, readdirSync, existsSync } from 'node:fs'
10
+ import { resolve, join, sep } from 'node:path'
11
+ import { classDefinitions, findClashes } from './class-clash-core.mjs'
12
+
13
+ const args = process.argv.slice(2)
14
+ if (args.includes('--help')) {
15
+ console.log('usage: node scripts/class-clash.mjs [--bundle directory] [directory|file.css ...]\nDefaults to examples/ and teaching/ when present. --bundle declares one component split across multiple stylesheets; collisions with other components are still checked. Requires postcss. Exit: 0 no overlap detected, 1 potential overlaps, 2 incomplete.')
16
+ process.exit(0)
17
+ }
18
+ const find = (path) => {
19
+ if (statSync(path).isFile()) return path.endsWith('.css') ? [resolve(path)] : []
20
+ return readdirSync(path, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name)).flatMap((entry) => {
21
+ if (entry.isSymbolicLink() || ['node_modules', '.git', 'dist', '.next'].includes(entry.name)) return []
22
+ const child = join(path, entry.name)
23
+ return entry.isDirectory() ? find(child) : entry.isFile() && entry.name.endsWith('.css') ? [resolve(child)] : []
24
+ })
25
+ }
26
+ try {
27
+ const bundles = [], paths = []
28
+ for (let i = 0; i < args.length; i++) {
29
+ if (args[i] === '--bundle') {
30
+ const dir = args[++i]
31
+ if (!dir || dir.startsWith('--') || !statSync(dir).isDirectory()) throw new Error('--bundle needs an existing component directory')
32
+ bundles.push(resolve(dir))
33
+ } else if (args[i].startsWith('--')) throw new Error(`unknown option: ${args[i]}`)
34
+ else paths.push(args[i])
35
+ }
36
+ const { default: postcss } = await import('postcss').catch(() => { throw new Error('PostCSS is missing; install the verification dependencies (npm install -D postcss).') })
37
+ const inputs = paths.length ? paths : ['examples', 'teaching'].filter(existsSync)
38
+ const files = [...new Set(inputs.flatMap(find))]
39
+ if (!files.length) throw new Error('no CSS files found; pass the demo directories to inspect')
40
+ const definitions = [], manual = []
41
+ for (const file of files) {
42
+ const result = classDefinitions(readFileSync(file, 'utf8'), file, postcss.parse)
43
+ const owner = bundles.filter(dir => file.startsWith(`${dir}${sep}`)).sort((a, b) => b.length - a.length)[0]
44
+ definitions.push(...result.definitions.map(definition => ({ ...definition, owner })))
45
+ manual.push(...result.manual)
46
+ }
47
+ const clashes = findClashes(definitions)
48
+ for (const clash of clashes) console.log(`.${clash.name}: ${clash.definitions.map((d) => `${d.file}:${d.line} (${d.selector})`).join(' ')}`)
49
+ for (const line of manual) console.log(`manual: ${line}`)
50
+ console.log(`class clash: ${manual.length ? 'inconclusive' : clashes.length ? 'potential overlaps' : 'no overlapping class namespaces detected'} (${files.length} CSS files, ${bundles.length} explicit bundles); composed scopes need host-page review`)
51
+ process.exitCode = manual.length ? 2 : clashes.length ? 1 : 0
52
+ } catch (error) { console.error(`class clash: incomplete: ${error.message}`); process.exitCode = 2 }