Files
monkey-ai-web/tests/legacy-css-layers.test.js
T
2026-11-18 19:09:00 +08:00

425 lines
15 KiB
JavaScript

/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import assert from 'node:assert/strict';
import test from 'node:test';
import vm from 'node:vm';
import legacyCssLayers, {
flattenCssLayers,
} from '../scripts/vite/legacy-css-layers.js';
// ---------- flattenCssLayers ----------
test('layers are unwrapped and unlayered rules are left out', () => {
const css = flattenCssLayers([
'body{color:red}@layer utils{.w-full{width:100%}}.card{padding:0}',
]);
assert.equal(css, '.w-full{width:100%}');
});
test('output follows layer order, not block position', () => {
const css = flattenCssLayers([
'@layer base,semi,utils;@layer utils{.u{top:0}}@layer base{.b{top:0}}@layer semi{.s{top:0}}',
]);
assert.equal(css, '.b{top:0}.s{top:0}.u{top:0}');
});
// 线上的真实情形:semi-ui.css 的 <link> 排在 index.css 之前,semi 层因此先于
// index.css 里 `@layer tailwind-base, semi, ...;` 的声明出现,成为最低优先级层
test('layer order is decided by first appearance across stylesheets', () => {
const css = flattenCssLayers([
'@layer semi{.s1{top:0}}@layer semi{.s2{top:0}}',
'@layer base,semi,utils;@layer base{.b{top:0}}@layer utils{.u{top:0}}',
]);
assert.equal(css, '.s1{top:0}.s2{top:0}.b{top:0}.u{top:0}');
});
test('anonymous layers stay separate and keep their position', () => {
const css = flattenCssLayers([
'@layer{.a{top:0}}@layer x{.x{top:0}}@layer{.b{top:0}}',
]);
assert.equal(css, '.a{top:0}.x{top:0}.b{top:0}');
});
test('at-rules inside a layer are carried over intact', () => {
const body =
'@media (min-width:1px){.m{top:0}}@keyframes spin{to{top:0}}.last{top:0}';
assert.equal(flattenCssLayers([`@layer utils{${body}}`]), body);
});
test('braces inside strings and escaped selectors do not break block matching', () => {
const rule = ".content-\\[\\'\\}\\'\\]{content:'}'}";
assert.equal(
flattenCssLayers([`@layer utils{${rule}.after{top:0}}`]),
`${rule}.after{top:0}`,
);
});
test('stylesheets without layers produce nothing', () => {
assert.equal(flattenCssLayers(['body{color:red}', '']), '');
});
// Semi 的 @layer 副本与层外全量引入的 semi.css 逐字重复,是兜底表体积的大头
test('layered rules that also exist verbatim outside any layer are dropped', () => {
const css = flattenCssLayers([
'.semi-a{top:0}@media (min-width:1px){.semi-m{top:0}}@layer semi{.semi-a{top:0}.semi-only{top:0}@media (min-width:1px){.semi-m{top:0}}}',
'@layer utils{.semi-late{top:0}.u{top:0}}.semi-late{top:0}',
]);
assert.equal(css, '.semi-only{top:0}.u{top:0}');
});
// 线上 semi-icons 的层内规则正是靠另一份入口表里的副本剔掉的,先后顺序无关
test('the verbatim copy may live in a different stylesheet, before or after', () => {
const layered = '@layer semi{.s{top:0}.t{top:0}}';
assert.equal(flattenCssLayers(['.s{top:0}', layered]), '.t{top:0}');
assert.equal(flattenCssLayers([layered, '.s{top:0}']), '.t{top:0}');
});
test('a layered rule is kept when the unlayered one only looks similar', () => {
const css = flattenCssLayers([
'.a{top:0}@layer x{.a{top:1px}.a:hover{top:0}}',
]);
assert.equal(css, '.a{top:1px}.a:hover{top:0}');
});
// 剔重只比较顶层节点:条件块里的同文规则只在条件成立时生效,不能算副本;
// 声明多一个 !important 也不是同一条规则
test('a rule inside a conditional block or differing in !important is not a copy', () => {
assert.equal(
flattenCssLayers(['@media print{.a{top:0}}@layer x{.a{top:0}}']),
'.a{top:0}',
);
assert.equal(
flattenCssLayers(['.a{top:0}@layer x{.a{top:0!important}}']),
'.a{top:0!important}',
);
});
// at 关键字大小写不敏感,@LAYER 与 @layer 是同一个东西
test('at-rule names are matched case-insensitively', () => {
assert.equal(
flattenCssLayers(['@LAYER a{.x{top:0}}@Layer b{.y{top:0}}']),
'.x{top:0}.y{top:0}',
);
});
// 这些写法的优先级规则各不相同,压平逻辑没有覆盖;宁可构建失败也不悄悄排错顺序
test('layer shapes the flattener does not understand fail loudly', () => {
for (const css of [
'@layer a{.direct{top:0}@layer b{.nested{top:0}}}',
'@layer a.b{.x{top:0}}',
'@layer a.b,c;',
'@media (min-width:1px){@layer a{.x{top:0}}}',
'@supports (top:0){@layer a{.x{top:0}}}',
'@import url(theme.css) layer(theme);',
'@import "theme.css" layer;',
'@layer a{@LAYER b{.nested{top:0}}}',
'@IMPORT url(theme.css) LAYER(theme);',
]) {
assert.throws(() => flattenCssLayers([css]), /legacy-css-layers/, css);
}
});
test('an @import whose file name merely contains "layer" is not rejected', () => {
assert.equal(
flattenCssLayers([
'@import url(https://cdn.example/layer.css);@import "layer/base.css";@layer x{.x{top:0}}',
]),
'.x{top:0}',
);
});
// ---------- 插件:往 index.html 注入兜底 ----------
const LEGACY_FILE = 'assets/legacy-layers-HASH.css';
const link = (href) => `<link rel="stylesheet" crossorigin href="${href}">`;
const page = (...links) =>
`<!doctype html><html><head><title>t</title>${links.join('')}</head><body></body></html>`;
// 用最小的假 bundle 驱动 generateBundle —— 这条路径只有真实构建才会走到,
// 而它一旦失效,新浏览器上没有任何迹象
const build = ({ html, assets, base = '/' }) => {
const bundle = {};
if (html !== undefined) {
bundle['index.html'] = { type: 'asset', source: html };
}
for (const [name, source] of Object.entries(assets)) {
bundle[name] = { type: 'asset', source };
}
const warnings = [];
const plugin = legacyCssLayers();
plugin.configResolved({ base });
plugin.generateBundle.call(
{
// 必须用 name 让 Rollup 生成带内容哈希的文件名;写死 fileName 的话,
// 新版本的兜底表会被浏览器按旧文件名的长缓存命中
emitFile(file) {
assert.deepEqual(Object.keys(file).sort(), ['name', 'source', 'type']);
assert.equal(file.type, 'asset');
assert.equal(file.name, 'legacy-layers.css');
bundle[LEGACY_FILE] = { type: 'asset', source: file.source };
return 'ref';
},
getFileName: () => LEGACY_FILE,
warn: (message) => warnings.push(message),
error(message) {
throw new Error(message);
},
},
{},
bundle,
);
return {
html: bundle['index.html']?.source,
legacy: bundle[LEGACY_FILE]?.source,
warnings,
};
};
test('the loader is injected right before the first entry stylesheet', () => {
const first = link('/assets/vendor-AAA.css');
const second = link('/assets/index-BBB.css');
const { html, legacy } = build({
html: page(first, second),
assets: {
'assets/vendor-AAA.css': '@layer semi{.s{top:0}}',
'assets/index-BBB.css': '@layer base,semi,utils;@layer utils{.u{top:0}}',
},
});
assert.equal(legacy, '.s{top:0}.u{top:0}');
const loaderAt = html.indexOf('wl-probe');
assert.ok(loaderAt > html.indexOf('<title>'));
assert.ok(loaderAt < html.indexOf(first));
assert.ok(html.includes(`href="/${LEGACY_FILE}"`));
// 原有内容一字未动,只多了注入的那段
assert.equal(
html.replace(/<script>[\s\S]*?<\/script>\s*/, ''),
page(first, second),
);
});
test('the legacy href and entry lookup honour a non-root base', () => {
const { html, legacy } = build({
base: '/console/',
html: page(link('/console/assets/index-BBB.css')),
assets: { 'assets/index-BBB.css': '@layer utils{.u{top:0}}' },
});
assert.equal(legacy, '.u{top:0}');
assert.ok(html.includes(`href="/console/${LEGACY_FILE}"`));
});
test('binary asset sources are decoded', () => {
const { legacy } = build({
html: page(link('/assets/index-BBB.css')),
assets: {
'assets/index-BBB.css': new TextEncoder().encode(
'@layer utils{.u{top:0}}',
),
},
});
assert.equal(legacy, '.u{top:0}');
});
// 线上的真实形态:排在最前的入口表(highlight、katex)根本不含层。
// 兜底表必须排在「所有」入口表之前,而不是第一份含层的入口表之前
test('the anchor is the first entry stylesheet even when it has no layers', () => {
const plain = link('/assets/highlight-AAA.css');
const layered = link('/assets/index-BBB.css');
const { html, legacy } = build({
html: page(plain, layered),
assets: {
'assets/highlight-AAA.css': '.hljs{top:0}.s{top:0}',
'assets/index-BBB.css': '@layer semi{.s{top:0}.t{top:0}}',
},
});
// 不含层的入口表同样参与剔重
assert.equal(legacy, '.t{top:0}');
assert.ok(html.indexOf('wl-probe') < html.indexOf(plain));
});
test('external and look-alike stylesheet tags are never used as the anchor', () => {
const external = link('https://fonts.example/css?family=Lato');
const commented = `<!-- ${link('/assets/removed-OLD.css')} -->`;
const entry = link('/assets/index-BBB.css');
const original = page(external, commented, entry);
const { html } = build({
html: original,
assets: { 'assets/index-BBB.css': '@layer utils{.u{top:0}}' },
});
// 注释原样还在(没被注入物劈开),加载器紧贴在入口 <link> 之前
assert.ok(html.includes(commented));
assert.ok(html.indexOf('wl-probe') > html.indexOf(commented));
assert.ok(html.indexOf('wl-probe') < html.indexOf(entry));
assert.equal(html.replace(/<script>[\s\S]*?<\/script>\s*/, ''), original);
});
// 带 media / disabled 的 <link> 只在特定条件下生效:它层外的规则不能拿来给别的表剔重,
// 它层内的规则也不能无条件收进兜底表
test('conditionally applied stylesheets are not treated as entry stylesheets', () => {
const print =
'<link rel="stylesheet" media="print" href="/assets/print-PPP.css">';
const off = '<link rel="stylesheet" href="/assets/alt-QQQ.css" disabled>';
const entry = link('/assets/index-BBB.css');
const { html, legacy, warnings } = build({
html: page(print, off, entry),
assets: {
'assets/print-PPP.css':
'.btn{display:none}@layer utils{.only-print{top:0}}',
'assets/alt-QQQ.css': '.keep{top:0}',
'assets/index-BBB.css': '@layer base{.btn{display:none}.keep{top:0}}',
},
});
assert.equal(legacy, '.btn{display:none}.keep{top:0}');
assert.equal(warnings.length, 1);
assert.match(warnings[0], /print-PPP\.css/);
assert.ok(html.indexOf('wl-probe') > html.indexOf(off));
assert.ok(html.indexOf('wl-probe') < html.indexOf(entry));
});
test('a build without any @layer is left alone', () => {
const html = page(link('/assets/index-BBB.css'));
const result = build({
html,
assets: { 'assets/index-BBB.css': '.u{top:0}' },
});
assert.equal(result.html, html);
assert.equal(result.legacy, undefined);
});
test('nothing is emitted when every layered rule already exists unlayered', () => {
const html = page(link('/assets/index-BBB.css'));
const result = build({
html,
assets: { 'assets/index-BBB.css': '.s{top:0}@layer semi{.s{top:0}}' },
});
assert.equal(result.html, html);
assert.equal(result.legacy, undefined);
});
test('a lazy chunk using @layer is reported, since the fallback cannot cover it', () => {
const { warnings, legacy } = build({
html: page(link('/assets/index-BBB.css')),
assets: {
'assets/index-BBB.css': '@layer utils{.u{top:0}}',
'assets/Lazy-CCC.css': '@layer utils{.lazy{top:0}}',
'assets/Plain-DDD.css': '.plain{top:0}',
},
});
assert.equal(legacy, '.u{top:0}');
assert.equal(warnings.length, 1);
assert.match(warnings[0], /Lazy-CCC\.css/);
});
// 「文本里有 @layer」不等于「有层规则」:懒加载分包的注释或字符串里出现这几个字时,
// 既不该告警,更不该因为「含 @layer 的样式表都不在入口里」而让构建失败
test('a stylesheet that merely mentions @layer is not treated as layered', () => {
const html = page(link('/assets/index-BBB.css'));
const result = build({
html,
assets: {
'assets/index-BBB.css': '.u{top:0}',
'assets/Lazy-CCC.css': '/*! built with @layer */.x{content:"@layer a{}"}',
},
});
assert.equal(result.html, html);
assert.equal(result.legacy, undefined);
assert.deepEqual(result.warnings, []);
});
test('an upper-case @LAYER counts as layered', () => {
const { legacy } = build({
html: page(link('/assets/index-BBB.css')),
assets: { 'assets/index-BBB.css': '@LAYER utils{.u{top:0}}' },
});
assert.equal(legacy, '.u{top:0}');
});
// 兜底覆盖不到的样式表一律告警,不因为「入口表恰好都不含层」就升级成构建失败
test('layers that only exist in lazy chunks are reported, not fatal', () => {
const html = page(link('/assets/index-BBB.css'));
const result = build({
html,
assets: {
'assets/index-BBB.css': '.u{top:0}',
'assets/Lazy-CCC.css': '@layer utils{.lazy{top:0}}',
},
});
assert.equal(result.html, html);
assert.equal(result.legacy, undefined);
assert.equal(result.warnings.length, 1);
assert.match(result.warnings[0], /Lazy-CCC\.css/);
});
// 这两种失败在新浏览器上完全看不出来,必须让构建红掉
test('the build fails when layered CSS exists but the fallback cannot be injected', () => {
const assets = { 'assets/index-BBB.css': '@layer utils{.u{top:0}}' };
assert.throws(() => build({ assets }), /index\.html/);
assert.throws(
() =>
build({
html: page("<link rel='stylesheet' href='/assets/index-BBB.css'>"),
assets,
}),
/入口/,
);
});
// ---------- 注入的内联探测脚本 ----------
const loaderScript = () => {
const { html } = build({
html: page(link('/assets/index-BBB.css')),
assets: { 'assets/index-BBB.css': '@layer utils{.u{top:0}}' },
});
return /<script>([\s\S]*?)<\/script>/.exec(html)[1];
};
// sheet 为 null 模拟内联样式被拦截等异常;ruleCount 为浏览器解析出的规则数
const runLoader = (sheet) => {
const written = [];
const children = [];
const document = {
createElement: () => ({ sheet }),
head: {
appendChild: (node) => children.push(node),
removeChild: (node) => children.splice(children.indexOf(node), 1),
},
write: (markup) => written.push(markup),
};
vm.runInNewContext(loaderScript(), { document });
return { written, leftover: children.length };
};
test('browsers that parse @layer do not load the fallback', () => {
const { written, leftover } = runLoader({ cssRules: { length: 1 } });
assert.deepEqual(written, []);
assert.equal(leftover, 0);
});
test('browsers that drop @layer load the fallback as a parser-inserted link', () => {
const { written, leftover } = runLoader({ cssRules: { length: 0 } });
assert.deepEqual(written, [`<link rel="stylesheet" href="/${LEGACY_FILE}">`]);
assert.equal(leftover, 0);
});
test('a failing probe leaves the page alone', () => {
assert.deepEqual(runLoader(null).written, []);
});