Files
monkey-ai-web/tests/legacy-polyfills.test.js
zhanjunhao 2aa9d73325 chore(repo): 移除重复版权文件头并纳入共享单测
集中保留原版权声明,移除文件头检查和全局测试忽略规则。验证:全量单测、受影响用例复测及静态检查通过。
2026-11-20 11:23:49 +08:00

315 lines
12 KiB
JavaScript

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');
});