nomadro/apps/miniprogram/weapp/scripts/sanitize-wxss-plugin.cjs
Eric 4ad87fd4ab Ship pending portal, admin, miniprogram, and ebook business updates.
Refresh audience/admin UX, ntfy/track, social paths, and replace ebook chapters with the expanded catalog; keep local SQLite and one-off probe scripts out of tree.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-26 13:40:46 +08:00

515 lines
13 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* WeChat WXSS sanitize for Next→Taro social CSS.
* 目标:尽量保留视觉,不要整段删样式。
* - 展开 :is()/:where()
* - 语义标签 → .as-*(对齐 H5El weapp)
* - 丢掉 :has / 复杂 :not / 裸 * / 空 @media
* - 删除 prefers-reduced-motion(微信无意义且易留空块)
*/
const fs = require('fs')
const path = require('path')
const TAGS = [
'article',
'aside',
'button',
'dialog',
'figcaption',
'figure',
'footer',
'form',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'header',
'label',
'li',
'main',
'nav',
'p',
'section',
'small',
'span',
'strong',
'em',
'i',
'time',
'ul',
'ol',
'a',
'img',
'video',
'canvas',
'input',
'textarea',
'select',
'summary',
'details',
]
const TAG_RE = new RegExp(
`(^|[\\s>+~,(])(${TAGS.join('|')})(?=[\\s>+~,(.:#\\[\\]]|$)`,
'gi',
)
function walkWxss(dir, out = []) {
if (!dir || !fs.existsSync(dir)) return out
for (const name of fs.readdirSync(dir)) {
const full = path.join(dir, name)
let st
try {
st = fs.statSync(full)
} catch {
continue
}
if (st.isDirectory()) walkWxss(full, out)
else if (name.endsWith('.wxss')) out.push(full)
}
return out
}
function skipComment(css, i) {
if (css[i] === '/' && css[i + 1] === '*') {
const end = css.indexOf('*/', i + 2)
return end < 0 ? css.length : end + 2
}
if (css[i] === '/' && css[i + 1] === '/') {
const end = css.indexOf('\n', i + 2)
return end < 0 ? css.length : end + 1
}
return i
}
function findMatchingBrace(css, openIdx) {
let depth = 0
for (let i = openIdx; i < css.length; i += 1) {
const next = skipComment(css, i)
if (next !== i) {
i = next - 1
continue
}
if (css[i] === '{') depth += 1
else if (css[i] === '}') {
depth -= 1
if (depth === 0) return i
}
}
return -1
}
function findMatchingParen(css, openIdx) {
let depth = 0
for (let i = openIdx; i < css.length; i += 1) {
if (css[i] === '(') depth += 1
else if (css[i] === ')') {
depth -= 1
if (depth === 0) return i
}
}
return -1
}
function findAtLayer(css, from = 0) {
let i = from
while (i < css.length) {
const next = skipComment(css, i)
if (next !== i) {
i = next
continue
}
if (css.startsWith('@layer', i) && !/[a-zA-Z-]/.test(css[i + 6] || '')) return i
i += 1
}
return -1
}
function unwrapAtLayers(css) {
let out = css
let guard = 0
while (guard < 40) {
guard += 1
const start = findAtLayer(out)
if (start < 0) break
const brace = out.indexOf('{', start)
if (brace < 0) {
out = out.slice(0, start) + ' ' + out.slice(start + 6)
continue
}
const end = findMatchingBrace(out, brace)
if (end < 0) break
out = out.slice(0, start) + '\n' + out.slice(brace + 1, end) + '\n' + out.slice(end + 1)
}
return out
}
function splitSelectors(sel) {
const parts = []
let cur = ''
let depth = 0
for (let i = 0; i < sel.length; i += 1) {
const ch = sel[i]
if (ch === '(') depth += 1
else if (ch === ')') depth = Math.max(0, depth - 1)
if (ch === ',' && depth === 0) {
if (cur.trim()) parts.push(cur.trim())
cur = ''
continue
}
cur += ch
}
if (cur.trim()) parts.push(cur.trim())
return parts
}
function rewriteTags(sel) {
let s = sel
// html / body → page(小程序无 html)
s = s.replace(/(^|[\s>+~,(])html(?=[\s>+~,(.:#[\]]|$)/gi, '$1page')
s = s.replace(/(^|[\s>+~,(])body(?=[\s>+~,(.:#[\]]|$)/gi, '$1page')
s = s.replace(TAG_RE, (full, pre, tag) => {
const t = tag.toLowerCase()
if (t === 'img') return `${pre}image, ${pre}.social-avatar, ${pre}img`
if (t === 'video') return `${pre}video`
return `${pre}.as-${t}`
})
return s
}
const MAX_EXPAND_PARTS = 48
/**
* 展开单个选择器里的 :is/:where(禁止对整条 selector list 做笛卡尔积)。
* 超限时退化为把 inner 逗号改成「取第一个 + 标签改写」以免爆内存。
*/
function expandIsWhereOne(sel) {
let out = sel
let guard = 0
while (guard < 24) {
guard += 1
const m = out.match(/:(is|where)\s*\(/i)
if (!m) break
const start = m.index
const open = out.indexOf('(', start)
const close = findMatchingParen(out, open)
if (close < 0) break
const inner = out.slice(open + 1, close)
let compoundStart = start
while (compoundStart > 0) {
const ch = out[compoundStart - 1]
if (ch === ' ' || ch === '>' || ch === '+' || ch === '~' || ch === ',') break
compoundStart -= 1
}
const compoundPrefix = out.slice(compoundStart, start)
const before = out.slice(0, compoundStart)
const after = out.slice(close + 1)
const inners = splitSelectors(inner).map((p) => p.trim()).filter(Boolean)
if (!inners.length) {
out = before + after
continue
}
if (inners.length > MAX_EXPAND_PARTS) {
// 过大:只保留前几个,避免 Invalid string length
const limited = inners.slice(0, 8)
out = limited.map((p) => before + compoundPrefix + p + after).join(', ')
continue
}
const parts = inners.map((p) => before + compoundPrefix + p + after)
// 若 after 里还有 :is,继续循环;否则合并
out = parts.join(', ')
if (out.length > 200_000) {
// 兜底:只留第一项,避免爆炸
out = parts[0]
}
}
return out
}
function expandIsWhere(sel) {
// 先按顶层逗号拆开,各自展开,避免列表×列表爆炸
return splitSelectors(sel)
.map((part) => expandIsWhereOne(part.trim()))
.filter(Boolean)
.join(', ')
}
function hasStarSelector(sel) {
const s = String(sel).replace(/"[^"]*"|'[^']*'/g, '')
return /(^|[\s>+~,])\*(::?[a-zA-Z-]+)?/.test(s)
}
/** `*` → view/text;简单 `:not(.class)` 剥掉 :not 保留基选择器 */
function softenUnsupported(sel) {
let s = sel
// .foo > * / *::before → view(weapp 几乎全是 View)
if (hasStarSelector(s)) {
s = s.replace(/(^|[\s>+~,])\*(::?[a-zA-Z-]+)?/g, (_, pre, pseudo = '') => {
return `${pre}view${pseudo || ''}`
})
}
// .card > :not(.art) → .card > view(padding 作用到内容区)
s = s.replace(/\s*>\s*:not\(\s*\.[a-zA-Z0-9_-]+\s*\)/g, ' > view')
// .nav-links:not(.open) / .reveal:not(.visible) → 基选择器
s = s.replace(/:not\(\s*\.[a-zA-Z0-9_-]+\s*\)/g, '')
return s
}
function mustDropSelector(sel) {
// 无法安全改写的::has、复杂 :not()、残留 :is/:where、残留 *
return (
/:has\s*\(/i.test(sel) ||
/:not\s*\(/i.test(sel) ||
/:(is|where)\s*\(/i.test(sel) ||
/::(backdrop|cue|slotted|file-selector-button)\b/i.test(sel) ||
hasStarSelector(sel)
)
}
function isUniversalReset(sel) {
const compact = sel.replace(/\s+/g, ' ').trim()
return compact === '*' || /^\*(\s*,\s*\*(::before|::after)?)+$/.test(compact)
}
function rewriteSelectorList(sel) {
// 顶层拆开 → 各自展开 :is → 标签改写 → 过滤
const top = splitSelectors(sel)
const kept = []
for (const raw of top) {
const expanded = expandIsWhereOne(raw.trim())
for (const part of splitSelectors(expanded)) {
let p = rewriteTags(softenUnsupported(part.trim()))
if (!p) continue
// rewriteTags(img) / soften 可能再引入逗号
for (const piece of splitSelectors(p)) {
let q = piece.trim()
if (!q) continue
q = softenUnsupported(q).trim()
if (!q || /^[,>+~\s]+$/.test(q)) continue
if (isUniversalReset(q)) {
kept.push('page, .soc-taro-root, .soc-taro-root view, .soc-taro-root text')
continue
}
if (mustDropSelector(q)) continue
kept.push(q)
}
}
}
return [...new Set(kept)].join(', ')
}
/** 用括号深度剥掉整段 color-mix(...),避免 var(--x, fallback) 内逗号打爆正则 */
function stripColorMix(css) {
let out = ''
let i = 0
const lower = css.toLowerCase()
while (i < css.length) {
const hit = lower.indexOf('color-mix(', i)
if (hit < 0) {
out += css.slice(i)
break
}
out += css.slice(i, hit)
const open = hit + 'color-mix'.length
// open 指向 '('
const close = findMatchingParen(css, open)
if (close < 0) {
out += css.slice(hit)
break
}
const inner = css.slice(open + 1, close)
// 取第一个色值:跳过 "in srgb," 后到下一个顶层逗号
let depth = 0
let start = 0
const m = /^\s*in\s+[a-z0-9\-]+\s*,\s*/i.exec(inner)
if (m) start = m[0].length
let end = inner.length
for (let j = start; j < inner.length; j += 1) {
const ch = inner[j]
if (ch === '(') depth += 1
else if (ch === ')') depth = Math.max(0, depth - 1)
else if (ch === ',' && depth === 0) {
end = j
break
}
}
let color = inner.slice(start, end).trim()
// 去掉末尾百分比 "var(--x) 82%"
color = color.replace(/\s+\d+(\.\d+)?%\s*$/, '').trim()
out += color || 'transparent'
i = close + 1
}
return out
}
function rewriteDecls(body) {
let b = stripColorMix(body)
b = b.replace(/\boverflow-wrap\s*:\s*anywhere\b/gi, 'overflow-wrap: break-word')
b = b.replace(/\bword-break\s*:\s*break-word\b/gi, 'word-break: break-all')
b = b.replace(/\b100dvh\b/g, '100vh')
b = b.replace(/\b100svh\b/g, '100vh')
b = b.replace(/\b100lvh\b/g, '100vh')
return b
}
function cleanBlock(css) {
let i = 0
let out = ''
const n = css.length
while (i < n) {
const next = skipComment(css, i)
if (next !== i) {
out += ' '
i = next
continue
}
if (/\s/.test(css[i])) {
out += css[i]
i += 1
continue
}
if (css[i] === '@') {
const brace = css.indexOf('{', i)
const semi = css.indexOf(';', i)
const name = ((css.slice(i).match(/^@[a-zA-Z\-]+/) || [''])[0] || '').toLowerCase()
if (brace >= 0 && (semi < 0 || brace < semi)) {
const end = findMatchingBrace(css, brace)
if (end < 0) {
out += css.slice(i)
break
}
if (name === '@layer') {
out += cleanBlock(css.slice(brace + 1, end))
} else if (name === '@media' || name === '@supports') {
const head = css.slice(i, brace)
if (/prefers-reduced-motion/i.test(head)) {
i = end + 1
continue
}
const inner = cleanBlock(css.slice(brace + 1, end))
if (inner.replace(/\/\*[\s\S]*?\*\//g, '').trim()) {
out += head + '{' + inner + '}'
}
} else {
out += css.slice(i, end + 1)
}
i = end + 1
continue
}
if (semi >= 0) {
out += css.slice(i, semi + 1)
i = semi + 1
continue
}
out += css.slice(i)
break
}
const brace = css.indexOf('{', i)
if (brace < 0) {
out += css.slice(i)
break
}
const end = findMatchingBrace(css, brace)
if (end < 0) {
out += css.slice(i)
break
}
const selector = css.slice(i, brace).trim()
const body = rewriteDecls(css.slice(brace + 1, end))
if (!selector) {
i = end + 1
continue
}
const rewritten = rewriteSelectorList(selector)
if (rewritten) out += rewritten + '{' + body + '}'
i = end + 1
}
return out
}
function dropEmptyAtRules(css) {
return css.replace(/@(?:media|supports)\s[^;{]*\{\s*\}/gi, ' ')
}
function quoteAttrSelectors(css) {
// [data-theme=light] → [data-theme="light"]
return css.replace(
/\[([a-zA-Z_:][\w:.-]*)=(?!")([^\s\]"'=<>`]+)\]/g,
'[$1="$2"]',
)
}
function sanitizeWxssSource(css) {
let next = unwrapAtLayers(String(css))
next = cleanBlock(next)
next = dropEmptyAtRules(next)
next = next.replace(/@layer\b[^\n{]*/g, ' ')
// 兜底:若 cleanBlock 漏网,再剥一轮 color-mix / 非法值
next = stripColorMix(next)
next = next.replace(/\boverflow-wrap\s*:\s*anywhere\b/gi, 'overflow-wrap: break-word')
next = quoteAttrSelectors(next)
return next
}
function sanitizeDir(distRoot) {
const files = walkWxss(distRoot)
let changed = 0
for (const file of files) {
// 只洗 social 分包与可能混进的 vendors;其它页不动以免误伤
const rel = path.relative(distRoot, file).replace(/\\/g, '/')
if (!/pages\/social\//.test(rel) && !/common\.wxss$/.test(rel)) continue
const raw = fs.readFileSync(file, 'utf8')
const next = sanitizeWxssSource(raw)
if (next !== raw) {
fs.writeFileSync(file, next)
changed += 1
}
}
return { files: files.length, changed }
}
class SanitizeWxssPlugin {
constructor(opts = {}) {
this.distRoot = opts.distRoot
}
apply(compiler) {
const run = () => {
try {
const { changed, files } = sanitizeDir(this.distRoot)
if (changed > 0) {
console.log(
`[sanitize-wxss] cleaned ${changed}/${files} → ${this.distRoot}`,
)
}
} catch (err) {
console.error('[sanitize-wxss] failed', err)
}
}
compiler.hooks.done.tap('SanitizeWxssPlugin', () => {
run()
setTimeout(run, 400)
setTimeout(run, 1500)
})
}
}
module.exports = {
SanitizeWxssPlugin,
sanitizeDir,
sanitizeWxssSource,
rewriteSelectorList,
}