sync: 同步 monkey-ai@weiyuan(ddc5b9443) 的 web/ 到 ui-optimization
- 合入 weiyuan 新功能前端:分佣 V2 / 伙伴工作台、智能路由、企业资金与分析、官网设置与预约演示等, semi-ui 已全部迁移到 antd 6 / @/components/ui,不重新引入 Semi - 分佣二级菜单与页头去重、伙伴入口探测(企业伙伴走企业中心「企业分佣」)、超管侧栏入口恢复 - 适配层 DatePicker / TimePicker 统一 onChange(Date|Date[]|null, 文本) 契约;生产构建剔除调试日志 - 图片链接刷新:同任务请求复用、后台刷新不弹全局错误、离页停止批量请求 - 恢复 bun.lock(与 package-lock.json 共存);docs 规范与 CHANGELOG 更新 - 停止跟踪 .env.playwright.local(本地登录凭据,已加入 .gitignore)
This commit is contained in:
@@ -35,6 +35,11 @@ async function fixture(run) {
|
||||
path.join(dir, 'vite.config.js'),
|
||||
await readFile(path.join(root, 'vite.config.js')),
|
||||
);
|
||||
// vite.config.js 引用的旧内核 @layer 兜底插件(b7bac50b5)需同目录存在
|
||||
await writeFile(
|
||||
path.join(dir, 'vite-plugin-legacy-css-layers.js'),
|
||||
await readFile(path.join(root, 'vite-plugin-legacy-css-layers.js')),
|
||||
);
|
||||
await writeFile(
|
||||
path.join(dir, '.env.development'),
|
||||
'DEV_PROXY_TARGET=http://localhost:13001\nVITE_REACT_APP_SERVER_URL=https://dev.example.com\nVITE_CLOUD_BRAIN_UI_ENABLED=true\nVITE_UMAMI_WEBSITE_ID=dev-id\nVITE_UMAMI_SCRIPT_URL=https://dev.example.com/script.js\n',
|
||||
|
||||
@@ -0,0 +1,424 @@
|
||||
/*
|
||||
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 '../vite-plugin-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, []);
|
||||
});
|
||||
@@ -0,0 +1,333 @@
|
||||
/*
|
||||
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 { readFileSync } from 'node:fs';
|
||||
import test from 'node:test';
|
||||
import vm from 'node:vm';
|
||||
|
||||
// index.html 里的旧内核补丁是手写的内联 ES5 脚本,不经过打包与转译。
|
||||
// 这里把它原样取出,放进一个删掉了对应原生实现的沙箱里执行,模拟旧内核。
|
||||
const html = readFileSync(new URL('../index.html', import.meta.url), 'utf8');
|
||||
const polyfills = /<script id="wl-legacy-polyfills">([\s\S]*?)<\/script>/.exec(
|
||||
html,
|
||||
)[1];
|
||||
|
||||
const STRIP_NATIVES = `
|
||||
var window = this;
|
||||
delete Array.prototype.at;
|
||||
delete String.prototype.at;
|
||||
delete Object.getPrototypeOf(Int8Array).prototype.at;
|
||||
delete Object.hasOwn;
|
||||
`;
|
||||
|
||||
const legacyRealm = () => {
|
||||
// vm 的新上下文只有语言内建对象,没有 structuredClone / DOMException 这类宿主 API
|
||||
const realm = vm.createContext({ DOMException });
|
||||
vm.runInContext(STRIP_NATIVES, realm);
|
||||
vm.runInContext(polyfills, realm);
|
||||
return (code) => vm.runInContext(code, realm);
|
||||
};
|
||||
|
||||
test('polyfills run before every other script on the page', () => {
|
||||
assert.ok(
|
||||
html.indexOf('<script id="wl-legacy-polyfills">') ===
|
||||
html.indexOf('<script'),
|
||||
);
|
||||
});
|
||||
|
||||
test('at() matches the native behaviour on arrays, strings and typed arrays', () => {
|
||||
const run = legacyRealm();
|
||||
assert.equal(run('[1, 2, 3].at(-1)'), 3);
|
||||
assert.equal(run('[1, 2, 3].at(0)'), 1);
|
||||
assert.equal(run('[1, 2, 3].at(3)'), undefined);
|
||||
assert.equal(run('[1, 2, 3].at(-4)'), undefined);
|
||||
assert.equal(run('[1, 2, 3].at(1.9)'), 2);
|
||||
assert.equal(run('[1, 2, 3].at(NaN)'), 1);
|
||||
assert.equal(run('"abc".at(-1)'), 'c');
|
||||
assert.equal(run('new Uint8Array([7, 8, 9]).at(-2)'), 8);
|
||||
});
|
||||
|
||||
// 补到内建原型上的方法必须不可枚举,否则所有对数组做 for-in 的代码都会多遍历出一个 at
|
||||
test('polyfilled methods do not show up in for-in or Object.keys', () => {
|
||||
const run = legacyRealm();
|
||||
assert.equal(
|
||||
run(`
|
||||
var seen = [];
|
||||
for (var i in [7]) seen.push(i);
|
||||
for (var c in 'a') seen.push(c);
|
||||
for (var t in new Uint8Array(1)) seen.push(t);
|
||||
seen.concat(Object.keys(Object)).join();
|
||||
`),
|
||||
'0,0,0',
|
||||
);
|
||||
});
|
||||
|
||||
test('Object.hasOwn ignores inherited keys and rejects null', () => {
|
||||
const run = legacyRealm();
|
||||
assert.equal(run('Object.hasOwn({ a: 1 }, "a")'), true);
|
||||
assert.equal(run('Object.hasOwn({ a: 1 }, "toString")'), false);
|
||||
assert.equal(run('Object.hasOwn(Object.create({ a: 1 }), "a")'), false);
|
||||
assert.equal(
|
||||
run('Object.hasOwn(Object.create(null, { a: { value: 1 } }), "a")'),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
run(
|
||||
'try { Object.hasOwn(null, "a") } catch (e) { e instanceof TypeError }',
|
||||
),
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test('structuredClone deep-copies plain data', () => {
|
||||
const run = legacyRealm();
|
||||
assert.equal(
|
||||
run(`
|
||||
var source = { n: 1, s: 'x', list: [1, { deep: true }], nothing: null };
|
||||
var copy = structuredClone(source);
|
||||
copy.list[1].deep = false;
|
||||
copy.list.push(2);
|
||||
JSON.stringify([source, copy]);
|
||||
`),
|
||||
'[{"n":1,"s":"x","list":[1,{"deep":true}],"nothing":null},' +
|
||||
'{"n":1,"s":"x","list":[1,{"deep":false},2],"nothing":null}]',
|
||||
);
|
||||
});
|
||||
|
||||
test('structuredClone preserves cycles and shared references', () => {
|
||||
const run = legacyRealm();
|
||||
assert.equal(
|
||||
run(`
|
||||
var shared = { v: 1 };
|
||||
var source = { a: shared, b: shared };
|
||||
source.self = source;
|
||||
var copy = structuredClone(source);
|
||||
copy !== source && copy.self === copy && copy.a === copy.b && copy.a !== shared;
|
||||
`),
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test('structuredClone copies Date, RegExp, Map, Set and binary data', () => {
|
||||
const run = legacyRealm();
|
||||
assert.equal(
|
||||
run(`
|
||||
var source = {
|
||||
date: new Date(86400000),
|
||||
re: /a+/gi,
|
||||
map: new Map([['k', { v: 1 }]]),
|
||||
set: new Set([1, 2]),
|
||||
bytes: new Uint8Array([1, 2, 3]).subarray(1),
|
||||
view: new DataView(new ArrayBuffer(8), 2, 4),
|
||||
};
|
||||
var copy = structuredClone(source);
|
||||
[
|
||||
copy.date instanceof Date && copy.date !== source.date && copy.date.getTime() === 86400000,
|
||||
copy.re instanceof RegExp && copy.re.source === 'a+' && copy.re.flags === 'gi',
|
||||
copy.map instanceof Map && copy.map.get('k').v === 1 && copy.map.get('k') !== source.map.get('k'),
|
||||
copy.set instanceof Set && copy.set.has(2) && copy.set.size === 2,
|
||||
copy.bytes instanceof Uint8Array && copy.bytes.length === 2 && copy.bytes[0] === 2 &&
|
||||
copy.bytes.buffer !== source.bytes.buffer,
|
||||
copy.view instanceof DataView && copy.view.byteOffset === 2 && copy.view.byteLength === 4,
|
||||
].join();
|
||||
`),
|
||||
'true,true,true,true,true,true',
|
||||
);
|
||||
});
|
||||
|
||||
test('structuredClone keeps one copy of an object referenced from several places', () => {
|
||||
const run = legacyRealm();
|
||||
assert.equal(
|
||||
run(`
|
||||
var date = new Date(0);
|
||||
var buffer = new ArrayBuffer(8);
|
||||
var source = {
|
||||
a: date,
|
||||
b: date,
|
||||
head: new Uint8Array(buffer, 0, 4),
|
||||
tail: new Uint8Array(buffer, 4, 4),
|
||||
};
|
||||
var copy = structuredClone(source);
|
||||
copy.head[0] = 7;
|
||||
[
|
||||
copy.a === copy.b && copy.a !== date,
|
||||
copy.head.buffer === copy.tail.buffer && copy.head.buffer !== buffer,
|
||||
new Uint8Array(copy.tail.buffer)[0] === 7 && new Uint8Array(buffer)[0] === 0,
|
||||
].join();
|
||||
`),
|
||||
'true,true,true',
|
||||
);
|
||||
});
|
||||
|
||||
// JSON.parse 会把 "__proto__" 落成自有属性;克隆不能把它变成原型改写
|
||||
test('structuredClone copies an own __proto__ key without touching the prototype', () => {
|
||||
const run = legacyRealm();
|
||||
assert.equal(
|
||||
run(`
|
||||
var copy = structuredClone(JSON.parse('{"__proto__":{"polluted":1},"a":2}'));
|
||||
[
|
||||
Object.keys(copy).join('+'),
|
||||
Object.getPrototypeOf(copy) === Object.prototype,
|
||||
copy.polluted,
|
||||
({}).polluted,
|
||||
].join();
|
||||
`),
|
||||
'__proto__+a,true,,',
|
||||
);
|
||||
});
|
||||
|
||||
// 把克隆结果写成一行文本:类型、键与属性描述符、数组长度与空洞、二进制视图的
|
||||
// 偏移与内容、Map/Set 的条目,以及对象之间「谁和谁是同一个」的引用关系
|
||||
const DESCRIBE = `
|
||||
var describe = function (root) {
|
||||
var ids = new Map();
|
||||
var tag = function (x) { return Object.prototype.toString.call(x).slice(8, -1); };
|
||||
var walk = function (x) {
|
||||
if (x === null || typeof x !== 'object') return typeof x + ':' + String(x);
|
||||
if (ids.has(x)) return '#' + ids.get(x);
|
||||
var id = ids.size;
|
||||
ids.set(x, id);
|
||||
var t = tag(x);
|
||||
var body;
|
||||
if (t === 'Date') body = String(x.getTime());
|
||||
else if (t === 'RegExp') body = x.source + '/' + x.flags + '/' + x.lastIndex;
|
||||
else if (t === 'ArrayBuffer') body = Array.prototype.join.call(new Uint8Array(x));
|
||||
else if (ArrayBuffer.isView(x)) {
|
||||
body = x.constructor.name + '@' + x.byteOffset + '+' + x.byteLength + ' of ' + walk(x.buffer);
|
||||
} else if (t === 'Map') {
|
||||
body = [];
|
||||
x.forEach(function (v, k) { body.push(walk(k) + '=>' + walk(v)); });
|
||||
} else if (t === 'Set') {
|
||||
body = [];
|
||||
x.forEach(function (v) { body.push(walk(v)); });
|
||||
} else {
|
||||
var proto = Object.getPrototypeOf(x);
|
||||
body = (t === 'Array' ? 'len=' + x.length + ' ' : '') +
|
||||
Object.getOwnPropertyNames(x)
|
||||
.filter(function (k) { return !(t === 'Array' && k === 'length'); })
|
||||
.map(function (k) {
|
||||
var d = Object.getOwnPropertyDescriptor(x, k);
|
||||
return JSON.stringify(k) + (d.enumerable ? '' : '(hidden)') +
|
||||
(d.writable ? '' : '(readonly)') + ':' + walk(d.value);
|
||||
}) + ' proto=' + (proto === null ? 'null' : tag(proto));
|
||||
}
|
||||
return t + '#' + id + '{' + body + '}';
|
||||
};
|
||||
return walk(root);
|
||||
};
|
||||
`;
|
||||
|
||||
// 各分支逐个对着 Node 原生 structuredClone 比:结构、属性描述符、引用关系都要一致
|
||||
const CLONE_CASES = {
|
||||
'sparse array with trailing holes and a named key':
|
||||
'var a = [1, , 3]; a.length = 6; a.tag = "x"; return a;',
|
||||
'Map with object keys, a value pointing back at its key, and itself as a value':
|
||||
'var m = new Map(); var k = { id: 1 }; m.set(k, { back: k }); m.set("self", m); return m;',
|
||||
'Set containing an object and itself':
|
||||
'var s = new Set(); s.add({ a: 1 }); s.add(s); return s;',
|
||||
'views of different element sizes sharing one buffer at non-zero offsets': `
|
||||
var b = new ArrayBuffer(16);
|
||||
new Uint8Array(b).set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);
|
||||
return { u16: new Uint16Array(b, 4, 3), f32: new Float32Array(b, 8, 2), dv: new DataView(b, 2, 6), raw: b };`,
|
||||
'a view that is reached before its buffer':
|
||||
'var b = new ArrayBuffer(4); return [new Int32Array(b), b, new Uint8Array(b, 1, 2)];',
|
||||
'Date and RegExp referenced twice, RegExp with a lastIndex':
|
||||
'var r = /a+/gi; r.lastIndex = 3; var d = new Date(5); return { r: r, r2: r, d: d, d2: d, bad: new Date(NaN) };',
|
||||
'own keys named __proto__, constructor and length':
|
||||
'return JSON.parse(\'{"__proto__":{"x":1},"constructor":1,"length":2,"a":[{"__proto__":null}]}\');',
|
||||
'class instance with hidden and accessor properties, held by a null-prototype object': `
|
||||
function P() { this.own = 1; }
|
||||
P.prototype.inherited = 2;
|
||||
var o = new P();
|
||||
Object.defineProperty(o, 'hidden', { value: 3, enumerable: false });
|
||||
Object.defineProperty(o, 'calc', { get: function () { return 4; }, enumerable: true });
|
||||
var n = Object.create(null);
|
||||
n.k = o;
|
||||
return n;`,
|
||||
'frozen and sealed containers':
|
||||
'return Object.freeze({ a: Object.freeze([1, Object.seal({ b: 2 })]) });',
|
||||
'primitives of every kind':
|
||||
'return [undefined, null, NaN, -1.5, Infinity, "", "x", true, false, 10n];',
|
||||
'empty containers':
|
||||
'return { o: {}, a: [], m: new Map(), s: new Set(), b: new ArrayBuffer(0), t: new Uint8Array(0) };',
|
||||
'deep nesting':
|
||||
'var root = {}; var cur = root; for (var i = 0; i < 300; i++) { cur.next = [{}]; cur = cur.next[0]; } return root;',
|
||||
};
|
||||
|
||||
test('structuredClone matches the native implementation branch by branch', () => {
|
||||
const realm = vm.createContext({
|
||||
DOMException,
|
||||
nativeClone: structuredClone,
|
||||
});
|
||||
vm.runInContext(STRIP_NATIVES, realm);
|
||||
vm.runInContext(polyfills, realm);
|
||||
vm.runInContext(DESCRIBE, realm);
|
||||
for (const [name, body] of Object.entries(CLONE_CASES)) {
|
||||
const [mine, native, source] = vm.runInContext(
|
||||
`(function () {
|
||||
var make = function () { ${body} };
|
||||
return [describe(structuredClone(make())), describe(nativeClone(make())), describe(make())];
|
||||
})()`,
|
||||
realm,
|
||||
);
|
||||
assert.equal(mine, native, name);
|
||||
// 用例本身得有内容,否则两边都输出空壳也会相等
|
||||
assert.ok(source.length > 20, name);
|
||||
}
|
||||
});
|
||||
|
||||
// 共享内存按规范是共享而非复制;漏掉这个分支时视图会被静默克隆成空数组
|
||||
test('structuredClone shares SharedArrayBuffer memory instead of dropping it', () => {
|
||||
const run = legacyRealm();
|
||||
assert.equal(
|
||||
run(`
|
||||
var sab = new SharedArrayBuffer(8);
|
||||
var view = new Uint8Array(sab, 4, 4);
|
||||
view[0] = 7;
|
||||
var copy = structuredClone({ view: view });
|
||||
copy.view[1] = 9;
|
||||
[copy.view.length, copy.view.byteOffset, copy.view[0], view[1]].join();
|
||||
`),
|
||||
'4,4,7,9',
|
||||
);
|
||||
});
|
||||
|
||||
test('structuredClone rejects functions and symbols like the native one', () => {
|
||||
const run = legacyRealm();
|
||||
for (const value of ['{ f: function () {} }', '[Symbol("s")]']) {
|
||||
assert.equal(
|
||||
run(`try { structuredClone(${value}) } catch (e) { e.name }`),
|
||||
'DataCloneError',
|
||||
value,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('native implementations are left untouched', () => {
|
||||
const native = () => 'native';
|
||||
const realm = vm.createContext({ DOMException, structuredClone: native });
|
||||
vm.runInContext(
|
||||
'var window = this; var nativeAt = Array.prototype.at;',
|
||||
realm,
|
||||
);
|
||||
vm.runInContext(polyfills, realm);
|
||||
assert.equal(vm.runInContext('Array.prototype.at === nativeAt', realm), true);
|
||||
assert.equal(vm.runInContext('structuredClone()', realm), 'native');
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
// 缓存创建按上游实际返回分三桶结算:明确的 5m、明确的 1h,以及上游只给总量没给分档、
|
||||
// 按「默认档位」计价的未分档桶。界面上少露一桶,用户拿 token × 倍率就加不出账单金额。
|
||||
//
|
||||
// 这些源码断言钉的是「哪些字段进了界面、各自的闸门是什么」——组件要真渲染得拉整套
|
||||
// Semi + JSX 工具链,而本仓库的前端测试跑的是裸 node --test。
|
||||
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import test from 'node:test';
|
||||
|
||||
const read = (relative) =>
|
||||
readFileSync(new URL(relative, import.meta.url), 'utf8').replace(/\r\n/g, '\n');
|
||||
|
||||
const table = read('../src/components/table/usage-logs/UsageLogsTable.jsx');
|
||||
const columnDefs = read(
|
||||
'../src/components/table/usage-logs/UsageLogsColumnDefs.jsx',
|
||||
);
|
||||
const render = read('../src/helpers/render.jsx');
|
||||
|
||||
test('计费详情把未分档桶的 token 与倍率都露出来', () => {
|
||||
assert.match(table, /other\.cache_creation_tokens_unlabeled/);
|
||||
assert.match(table, /other\.cache_creation_ratio_unlabeled/);
|
||||
assert.match(table, /t\('未分档缓存创建'\)/);
|
||||
assert.match(table, /t\('未分档缓存倍率'\)/);
|
||||
});
|
||||
|
||||
test('未分档行只在与分档并存时单独成行', () => {
|
||||
// 没有分档时「缓存创建 / 缓存创建倍率」说的就是这一桶,再列一遍是重复
|
||||
assert.match(
|
||||
table,
|
||||
/const showUnlabeledCacheCreation\s*=\s*\n?\s*hasSplitCacheCreation && unlabeledCacheCreation > 0;/,
|
||||
);
|
||||
});
|
||||
|
||||
test('缓存倍率的闸门是缓存命中,不是缓存创建', () => {
|
||||
// cache_ratio 是读倍率。闸门里混入写入 token 会让「只写不读」的请求挂一个
|
||||
// 没有对应 token 的缓存倍率,看着像漏算了一笔钱。
|
||||
assert.match(
|
||||
table,
|
||||
/other\.cache_ratio != null &&\s*\n?\s*other\.cache_tokens > 0 && \{/,
|
||||
);
|
||||
// 旧的三项相加闸门必须已经消失
|
||||
assert.doesNotMatch(table, /const cacheTokens\s*=/);
|
||||
});
|
||||
|
||||
test('明细列的倍率文案把未分档项带上', () => {
|
||||
assert.match(
|
||||
render,
|
||||
/if \(shouldShowCacheCreationUnlabeled\) \{[\s\S]*?未分档缓存创建: \{\{cacheCreationRatioUnlabeled\}\}/,
|
||||
);
|
||||
// 只在有分档时才单列,与计费详情同一套口径
|
||||
assert.match(
|
||||
render,
|
||||
/const shouldShowCacheCreationUnlabeled\s*=\s*\n?\s*hasSplitCacheCreation && cacheCreationTokensUnlabeled > 0;/,
|
||||
);
|
||||
});
|
||||
|
||||
test('renderModelPriceSimple 的未分档实参落在 1h 与 image 之间', () => {
|
||||
// 这是个 18 个位置参数的函数,插在中间的两个参数一旦错位,
|
||||
// 未分档 token 会被当成 image 开关,整列文案静默跑偏。
|
||||
const signature = render.match(
|
||||
/export function renderModelPriceSimple\(([\s\S]*?)\n\) \{/,
|
||||
);
|
||||
assert.ok(signature, 'renderModelPriceSimple 签名未找到');
|
||||
const params = signature[1]
|
||||
.split(',')
|
||||
.map((p) => p.trim().split('=')[0].trim())
|
||||
.filter(Boolean);
|
||||
assert.deepEqual(params.slice(10, 15), [
|
||||
'cacheCreationTokens1h',
|
||||
'cacheCreationRatio1h',
|
||||
'cacheCreationTokensUnlabeled',
|
||||
'cacheCreationRatioUnlabeled',
|
||||
'image',
|
||||
]);
|
||||
|
||||
// Claude 分支按同样的顺序传实参
|
||||
assert.match(
|
||||
columnDefs,
|
||||
/other\.cache_creation_tokens_1h \|\| 0,[\s\S]{0,160}?other\.cache_creation_tokens_unlabeled \|\| 0,\s*\n\s*other\.cache_creation_ratio_unlabeled \|\|/,
|
||||
);
|
||||
// 非 Claude 分支没有缓存创建,三桶全部补 0/1,补少了同样错位
|
||||
assert.match(
|
||||
columnDefs,
|
||||
/other\.cache_ratio \|\| 1\.0,\s*(?:\n\s*0,\s*\n\s*1\.0,){4}\s*\n\s*false,/,
|
||||
);
|
||||
});
|
||||
Reference in New Issue
Block a user