import assert from 'node:assert';
import { webcrypto } from 'node:crypto';
import { EventEmitter } from 'node:events';
import fs from 'node:fs';
import module, { createRequire } from 'node:module';
import { inspect } from 'node:util';
import vm from 'node:vm';
const require = createRequire(import.meta.url);
export const testPrivateWeakCollectionsBypassPublicPrototypes = () => {
const privateResourceIds = globalThis.__wasm_rquickjs_resource_ids;
assert.ok(privateResourceIds instanceof WeakMap);
for (const method of ['delete', 'get', 'has', 'set']) {
const descriptor = Object.getOwnPropertyDescriptor(privateResourceIds, method);
assert.strictEqual(typeof descriptor?.value, 'function');
assert.strictEqual(descriptor.enumerable, false);
assert.strictEqual(descriptor.configurable, false);
assert.strictEqual(descriptor.writable, false);
}
const weakMapMethods = {
delete: WeakMap.prototype.delete,
get: WeakMap.prototype.get,
has: WeakMap.prototype.has,
set: WeakMap.prototype.set,
};
const weakSetMethods = {
add: WeakSet.prototype.add,
delete: WeakSet.prototype.delete,
has: WeakSet.prototype.has,
};
const prototypeCalls = [];
const key = {};
for (const [name, method] of Object.entries(weakMapMethods)) {
WeakMap.prototype[name] = function (...args) {
prototypeCalls.push(`WeakMap.${name}`);
return Reflect.apply(method, this, args);
};
}
for (const [name, method] of Object.entries(weakSetMethods)) {
WeakSet.prototype[name] = function (...args) {
prototypeCalls.push(`WeakSet.${name}`);
return Reflect.apply(method, this, args);
};
}
try {
privateResourceIds.set(key, { marker: 'private-resource-id' });
assert.strictEqual(privateResourceIds.has(key), true);
assert.deepStrictEqual(privateResourceIds.get(key), { marker: 'private-resource-id' });
const event = new Event('private-cache-test');
assert.strictEqual(event.isTrusted, false);
const decoder = new TextDecoder();
assert.strictEqual(decoder.decode(new Uint8Array([65])), 'A');
assert.match(inspect(new TextEncoderStream()), /TextEncoderStream/);
assert.match(inspect(new TextDecoderStream()), /TextDecoderStream/);
const objectPrototypeGet = Object.getOwnPropertyDescriptor(Object.prototype, 'get');
try {
Object.defineProperty(Object.prototype, 'get', {
value() {},
configurable: true,
});
const cyclicActual = {};
const cyclicExpected = {};
cyclicActual.self = cyclicActual;
cyclicExpected.self = cyclicExpected;
assert.partialDeepStrictEqual(cyclicActual, cyclicExpected);
} finally {
if (objectPrototypeGet) {
Object.defineProperty(Object.prototype, 'get', objectPrototypeGet);
} else {
delete Object.prototype.get;
}
}
const url = new URL('https://example.com/?value=1');
assert.strictEqual(url.searchParams.get('value'), '1');
assert.match(new Error('private-error-cache').stack, /^Error: private-error-cache(?:\n|$)/);
const context = vm.createContext({ value: 21 });
assert.strictEqual(new vm.Script('value * 2').runInContext(context), 42);
assert.strictEqual(webcrypto.subtle.constructor.name, 'SubtleCrypto');
webcrypto.getRandomValues(new Uint8Array(1));
globalThis.__wasm_rquickjs_ignore_unhandled_rejection(Promise.resolve());
const modulePath = '/private-weak-cache.cjs';
fs.writeFileSync(modulePath, 'module.exports = 42;');
try {
assert.strictEqual(require(modulePath), 42);
} finally {
delete require.cache[modulePath];
fs.unlinkSync(modulePath);
}
} finally {
Object.assign(WeakMap.prototype, weakMapMethods);
Object.assign(WeakSet.prototype, weakSetMethods);
}
assert.deepStrictEqual(prototypeCalls, []);
assert.doesNotMatch(
inspect(privateResourceIds, { showHidden: true }),
/private-resource-id/,
);
assert.strictEqual(privateResourceIds.delete(key), true);
return true;
};
export const testCaptureStackTraceExists = () => {
try {
assert.strictEqual(typeof Error.captureStackTrace, 'function');
assert.strictEqual(typeof Error.prepareStackTrace, 'function');
assert.strictEqual(typeof Error.stackTraceLimit, 'number');
return true;
} catch (e) {
console.error('testCaptureStackTraceExists FAIL:', e.message);
return false;
}
};
export const benchmarkErrorStack = (path, iterations) => {
function throwAtDepth(depth, valueFactory) {
if (depth === 0) throw valueFactory();
return throwAtDepth(depth - 1, valueFactory);
}
let checksum = 0;
if (path === 'construction') {
for (let index = 0; index < iterations; index++) {
checksum += new Error('benchmark').message.length;
}
} else if (path === 'first-read') {
for (let index = 0; index < iterations; index++) {
checksum += new Error('benchmark').stack.length;
}
} else if (path === 'repeated-read') {
const error = new Error('benchmark');
error.stack;
for (let index = 0; index < iterations; index++) {
checksum += error.stack.length;
}
} else if (path === 'throw-catch') {
for (let index = 0; index < iterations; index++) {
try {
throwAtDepth(4, () => new Error('benchmark'));
} catch (error) {
checksum += error.message.length;
}
}
} else if (path === 'throw-plain') {
for (let index = 0; index < iterations; index++) {
try {
throwAtDepth(4, () => ({ message: 'benchmark' }));
} catch (error) {
checksum += error.message.length;
}
}
} else if (path === 'capture-first-read') {
for (let index = 0; index < iterations; index++) {
const target = {};
Error.captureStackTrace(target);
checksum += target.stack.length;
}
} else if (path === 'custom-first-read') {
const descriptor = Object.getOwnPropertyDescriptor(Error, 'prepareStackTrace');
try {
Error.prepareStackTrace = (_error, callSites) => `custom:${callSites.length}`;
for (let index = 0; index < iterations; index++) {
checksum += new Error('benchmark').stack.length;
}
} finally {
if (descriptor) Object.defineProperty(Error, 'prepareStackTrace', descriptor);
else delete Error.prepareStackTrace;
}
} else {
throw new RangeError(`unknown Error stack benchmark path: ${path}`);
}
return checksum >>> 0;
};
async function checkPreparedStackCacheLifetime(customStack) {
const descriptor = Object.getOwnPropertyDescriptor(Error, 'prepareStackTrace');
let hookCalls = 0;
try {
assert.strictEqual(typeof globalThis.gc, 'function');
if (customStack) {
Error.prepareStackTrace = error => {
hookCalls++;
return { error, message: error.message };
};
}
const held = Array.from({ length: 8 }, (_, i) => new Error(`held-${i}`));
const heldStacks = held.map(error => error.stack);
const unreadHeld = customStack
? []
: Array.from({ length: 8 }, (_, i) => new Error(`unread-held-${i}`));
function discardedErrors() {
return Array.from({ length: 64 }, (_, index) => {
const error = new Error('discarded');
error.self = error;
if ((index & 1) === 0) void error.stack;
return new WeakRef(error);
});
}
function discardedPlainCycles() {
return Array.from({ length: 64 }, () => {
const object = {};
object.self = object;
return new WeakRef(object);
});
}
function discardedPublicWeakEntries() {
const refs = [];
for (let i = 0; i < 32; i++) {
const mapKey = { marker: `public-map-key-${i}` };
const mapValue = { mapKey };
const setValue = { marker: `public-set-value-${i}` };
setValue.self = setValue;
publicWeakMap.set(mapKey, mapValue);
publicWeakSet.add(setValue);
refs.push(new WeakRef(mapKey), new WeakRef(setValue));
}
assert.match(inspect(publicWeakMap, { showHidden: true }), /public-map-key/);
assert.match(inspect(publicWeakSet, { showHidden: true }), /public-set-value/);
return refs;
}
const publicWeakMap = new WeakMap();
const publicWeakSet = new WeakSet();
const liveMapKey = { marker: 'live-map-key' };
const readdedMapKey = { marker: 'readded-map-key' };
const currentMapValue = { marker: 'current-map-value' };
const currentReaddedMapValue = { marker: 'current-readded-map-value' };
const liveSetValue = { marker: 'live-set-value' };
const readdedSetValue = { marker: 'readded-set-value' };
publicWeakMap.set(liveMapKey, { marker: 'stale-map-value' });
publicWeakMap.set(liveMapKey, currentMapValue);
publicWeakMap.set(readdedMapKey, { marker: 'stale-readded-map-value' });
publicWeakMap.delete(readdedMapKey);
publicWeakMap.set(readdedMapKey, currentReaddedMapValue);
publicWeakSet.add(liveSetValue);
publicWeakSet.add(liveSetValue);
publicWeakSet.add(readdedSetValue);
publicWeakSet.delete(readdedSetValue);
publicWeakSet.add(readdedSetValue);
const errors = discardedErrors();
const plain = discardedPlainCycles();
const publicWeakEntries = discardedPublicWeakEntries();
const callsBeforeGc = hookCalls;
const tick = () => new Promise(resolve => setTimeout(resolve, 0));
await tick();
for (let i = 0; i < 3; i++) {
globalThis.gc();
await tick();
await tick();
}
assert.strictEqual(plain.filter(ref => ref.deref() === undefined).length, 64,
'GC positive control must collect plain cycles');
assert.strictEqual(errors.filter(ref => ref.deref() === undefined).length, 64,
customStack
? 'custom prepared stack cycles must remain collectable'
: 'private prepared-stack cache must not retain discarded errors');
assert.strictEqual(publicWeakEntries.filter(ref => ref.deref() === undefined).length, 64,
'inspection bookkeeping must not retain public weak entries');
assert.strictEqual(publicWeakMap.get(liveMapKey), currentMapValue);
assert.strictEqual(publicWeakMap.get(readdedMapKey), currentReaddedMapValue);
assert.strictEqual(publicWeakSet.has(liveSetValue), true);
assert.strictEqual(publicWeakSet.has(readdedSetValue), true);
const inspectedWeakMap = inspect(publicWeakMap, { showHidden: true });
const inspectedWeakSet = inspect(publicWeakSet, { showHidden: true });
assert.doesNotMatch(inspectedWeakMap, /public-map-key/);
assert.doesNotMatch(inspectedWeakSet, /public-set-value/);
assert.match(inspectedWeakMap, /current-map-value/);
assert.match(inspectedWeakMap, /current-readded-map-value/);
assert.doesNotMatch(inspectedWeakMap, /stale-map-value/);
assert.doesNotMatch(inspectedWeakMap, /stale-readded-map-value/);
assert.strictEqual(inspectedWeakMap.match(/live-map-key/g)?.length, 1);
assert.strictEqual(inspectedWeakMap.match(/readded-map-key/g)?.length, 1);
assert.strictEqual(inspectedWeakSet.match(/live-set-value/g)?.length, 1);
assert.strictEqual(inspectedWeakSet.match(/readded-set-value/g)?.length, 1);
for (let i = 0; i < held.length; i++) {
assert.strictEqual(held[i].stack, heldStacks[i]);
if (customStack) assert.strictEqual(held[i].stack.error, held[i]);
else assert(held[i].stack.includes(`held-${i}`));
}
for (let i = 0; i < unreadHeld.length; i++) {
unreadHeld[i].name = 404;
assert.match(inspect(unreadHeld[i]),
new RegExp(`^404 \\[Error\\]: unread-held-${i}(?:\\n|$)`));
}
assert.strictEqual(hookCalls, callsBeforeGc, 'held stacks remain cached across GC');
return true;
} finally {
if (descriptor) Object.defineProperty(Error, 'prepareStackTrace', descriptor);
else delete Error.prepareStackTrace;
}
}
export async function testPreparedStackCacheDoesNotRetainErrors() {
return await checkPreparedStackCacheLifetime(false);
}
export async function testPreparedStackCacheDoesNotRetainCustomCycles() {
return await checkPreparedStackCacheLifetime(true);
}
export const testCaptureStackTraceBasic = () => {
try {
const obj = {};
Error.captureStackTrace(obj);
assert.strictEqual(typeof obj.stack, 'string');
assert(obj.stack.length > 0, 'stack should be non-empty');
assert.throws(
() => Error.captureStackTrace(Object.freeze({})),
TypeError,
);
const existingStack = Object.preventExtensions(Object.defineProperty({}, 'stack', {
value: 'existing',
writable: true,
configurable: true,
}));
assert.throws(() => Error.captureStackTrace(existingStack), TypeError);
assert.throws(
() => Error.captureStackTrace(Object.preventExtensions(new Error('fixed'))),
TypeError,
);
return true;
} catch (e) {
console.error('testCaptureStackTraceBasic FAIL:', e.message);
return false;
}
};
export const testPrepareStackTrace = () => {
try {
let receivedCallSites = null;
const origPrepare = Error.prepareStackTrace;
Error.prepareStackTrace = function (error, callSites) {
receivedCallSites = callSites;
return callSites;
};
const obj = {};
Error.captureStackTrace(obj);
const stack = obj.stack;
Error.prepareStackTrace = origPrepare;
assert(Array.isArray(receivedCallSites), 'callSites should be an array');
assert(receivedCallSites.length > 0, 'callSites should be non-empty');
const site = receivedCallSites[0];
assert.strictEqual(typeof site.getFileName, 'function');
assert.strictEqual(typeof site.getLineNumber, 'function');
assert.strictEqual(typeof site.getColumnNumber, 'function');
assert.strictEqual(typeof site.getFunctionName, 'function');
return true;
} catch (e) {
console.error('testPrepareStackTrace FAIL:', e.message);
return false;
}
};
export const testCallSiteMethods = () => {
try {
let callSites = null;
const origPrepare = Error.prepareStackTrace;
Error.prepareStackTrace = function (error, sites) {
if (callSites === null) {
callSites = sites;
}
return 'custom-stack';
};
const obj = {};
Error.captureStackTrace(obj);
void obj.stack;
Error.prepareStackTrace = origPrepare;
assert(Array.isArray(callSites), 'callSites should be an array');
assert(callSites.length > 0, 'callSites should be non-empty');
const site = callSites[0];
const methods = [
'getThis', 'getTypeName', 'getFunction', 'getFunctionName',
'getMethodName', 'getFileName', 'getLineNumber', 'getColumnNumber',
'getEvalOrigin', 'isToplevel', 'isEval', 'isNative', 'isConstructor',
'isAsync', 'isPromiseAll', 'getPromiseIndex', 'getScriptNameOrSourceURL',
'toString'
];
for (const m of methods) {
assert.strictEqual(typeof site[m], 'function', `CallSite.${m} should be a function`);
}
assert(site.getFileName() === null || typeof site.getFileName() === 'string');
assert.strictEqual(typeof site.getLineNumber(), 'number');
assert.strictEqual(typeof site.getColumnNumber(), 'number');
assert.strictEqual(typeof site.isEval(), 'boolean');
assert.strictEqual(typeof site.isNative(), 'boolean');
assert.strictEqual(typeof site.isConstructor(), 'boolean');
assert.strictEqual(typeof site.isToplevel(), 'boolean');
assert.strictEqual(typeof site.toString(), 'string');
return true;
} catch (e) {
console.error('testCallSiteMethods FAIL:', e.message);
return false;
}
};
export const testLatePrepareStackTrace = () => {
const originalPrepare = Error.prepareStackTrace;
try {
Error.prepareStackTrace = undefined;
const lateTarget = {};
Error.captureStackTrace(lateTarget);
Error.prepareStackTrace = () => 'late-prepare';
assert.strictEqual(lateTarget.stack, 'late-prepare');
Error.prepareStackTrace = undefined;
const lateError = new Error('late-error');
let ordinaryCalls = 0;
Error.prepareStackTrace = function(error) {
ordinaryCalls++;
assert.strictEqual(this, Error);
return `late:${error.message}`;
};
assert.strictEqual(ordinaryCalls, 0);
assert.strictEqual(lateError.stack, 'late:late-error');
assert.strictEqual(ordinaryCalls, 1);
let recursiveCalls = 0;
Error.prepareStackTrace = error => {
recursiveCalls++;
return error.stack;
};
assert.match(new Error('recursive').stack, /^Error: recursive(?:\n|$)/);
assert.strictEqual(recursiveCalls, 1);
let crossErrorCalls = 0;
let nestedError;
Error.prepareStackTrace = error => {
crossErrorCalls++;
if (error.message === 'outer') {
nestedError = new Error('inner');
return `${nestedError.stack}!`;
}
return `unexpected:${error.message}`;
};
const crossErrorStack = new Error('outer').stack;
assert.match(crossErrorStack, /^Error: inner(?:\n|$)/);
assert.match(crossErrorStack, /!$/);
assert.strictEqual(crossErrorCalls, 1);
assert.strictEqual(nestedError.stack, crossErrorStack.slice(0, -1));
const intrinsicError = Error;
const replacementTarget = new intrinsicError('replacement-target');
function ReplacementError() {}
ReplacementError.prepareStackTrace = () => 'replacement-prepare';
globalThis.Error = ReplacementError;
try {
assert.strictEqual(replacementTarget.stack, 'replacement-prepare');
} finally {
globalThis.Error = intrinsicError;
}
Error.prepareStackTrace = () => 'intrinsic-fallback';
const fallbackTarget = new Error('fallback-target');
globalThis.Error = function ReplacementWithoutHook() {};
try {
assert.strictEqual(fallbackTarget.stack, 'intrinsic-fallback');
} finally {
globalThis.Error = intrinsicError;
}
Error.prepareStackTrace = error => {
error.stack = 'assigned-in-hook';
return error.stack;
};
assert.strictEqual(new Error('assigned').stack, 'assigned-in-hook');
Error.prepareStackTrace = () => 'capture-time-prepare';
const removedTarget = {};
Error.captureStackTrace(removedTarget);
Error.prepareStackTrace = undefined;
assert.strictEqual(typeof removedTarget.stack, 'string');
assert.notStrictEqual(removedTarget.stack, 'capture-time-prepare');
return true;
} catch (e) {
console.error('testLatePrepareStackTrace FAIL:', e.message);
return false;
} finally {
Error.prepareStackTrace = originalPrepare;
}
};
export const testDefaultErrorStackHeaders = () => {
const originalPrepare = Error.prepareStackTrace;
try {
Error.prepareStackTrace = undefined;
assert.match(new Error('base').stack, /^Error: base(?:\n|$)/);
assert.match(new TypeError('native').stack, /^TypeError: native(?:\n|$)/);
assert.match(new Error().stack, /^Error(?:\n|$)/);
class CustomError extends Error {}
CustomError.prototype.name = 'CustomError';
assert.match(new CustomError('custom').stack, /^CustomError: custom(?:\n|$)/);
class EmptyNameError extends Error {}
EmptyNameError.prototype.name = '';
assert.match(new EmptyNameError('message-only').stack, /^message-only(?:\n|$)/);
const originalToString = Error.prototype.toString;
Error.prototype.toString = () => 'POISON';
const protectedHeader = new Error('protected').stack;
Error.prototype.toString = originalToString;
assert.match(protectedHeader, /^Error: protected(?:\n|$)/);
function captureNamedFrame() {
return new Error('named-frame').stack;
}
assert.match(captureNamedFrame().split('\n')[1], /^\s*at captureNamedFrame \(.+:\d+:\d+\)$/);
const originalObjectToString = Object.prototype.toString;
let protectedCallSiteStack;
try {
Object.prototype.toString = () => 'FAKE';
protectedCallSiteStack = new Error('protected-call-site').stack;
} finally {
Object.prototype.toString = originalObjectToString;
}
assert.doesNotMatch(protectedCallSiteStack, /FAKE/);
assert.match(protectedCallSiteStack.split('\n')[1], /^\s*at .+:\d+:\d+/);
return true;
} catch (e) {
console.error('testDefaultErrorStackHeaders FAIL:', e.message);
return false;
} finally {
Error.prepareStackTrace = originalPrepare;
}
};
export const testErrorInspectUsesCurrentName = () => {
try {
const error = new RangeError('foo');
error.name = 404;
assert.match(error.stack, /^404: foo(?:\n|$)/);
assert.match(inspect(error), /^404 \[RangeError\]: foo(?:\n|$)/);
const readBeforeRename = new RangeError('fixed');
const unreadDescriptor = Object.getOwnPropertyDescriptor(readBeforeRename, 'stack');
assert.strictEqual(typeof unreadDescriptor.get, 'function');
assert.strictEqual(unreadDescriptor.enumerable, false);
assert.strictEqual(unreadDescriptor.configurable, true);
assert.match(readBeforeRename.stack, /^RangeError: fixed(?:\n|$)/);
const materializedDescriptor = Object.getOwnPropertyDescriptor(readBeforeRename, 'stack');
assert.strictEqual(materializedDescriptor.get, unreadDescriptor.get);
assert.strictEqual(materializedDescriptor.set, unreadDescriptor.set);
assert.strictEqual('value' in materializedDescriptor, false);
readBeforeRename.name = 404;
assert.match(readBeforeRename.stack, /^RangeError: fixed(?:\n|$)/);
assert.match(inspect(readBeforeRename), /^RangeError: fixed(?:\n|$)/);
const messageBeforeRead = new Error('before');
messageBeforeRead.message = 'after';
assert.match(messageBeforeRead.stack, /^Error: after(?:\n|$)/);
const messageAfterRead = new Error('before');
assert.match(messageAfterRead.stack, /^Error: before(?:\n|$)/);
messageAfterRead.message = 'after';
assert.match(messageAfterRead.stack, /^Error: before(?:\n|$)/);
const frameLikeMessage = new Error('before\n at message');
frameLikeMessage.message = 'after\n at message';
assert.match(frameLikeMessage.stack, /^Error: after\n at message\n at /);
const internalFrameMessage = new Error('before\n at construct (native)');
internalFrameMessage.message = 'after\n at construct (native)';
assert.match(
internalFrameMessage.stack,
/^Error: after\n at construct \(native\)\n at /,
);
const inheritedBase = new Error('inherited');
const inherited = Object.create(inheritedBase);
assert.strictEqual(inherited.stack, inheritedBase.stack);
assert.strictEqual(Object.hasOwn(inherited, 'stack'), false);
inherited.stack = 'child-manual';
assert.strictEqual(inherited.stack, 'child-manual');
assert.strictEqual(Object.hasOwn(inherited, 'stack'), false);
assert.strictEqual(inheritedBase.stack, 'child-manual');
const detachedStack = {};
Object.defineProperty(detachedStack, 'stack', unreadDescriptor);
detachedStack.stack = 'ignored';
assert.strictEqual(detachedStack.stack, undefined);
const unreadInheritedBase = new Error('unread-inherited');
const unreadInherited = Object.create(unreadInheritedBase);
unreadInherited.name = 'ChildName';
assert.match(unreadInherited.stack, /^Error: unread-inherited(?:\n|$)/);
function LegacyError(message) {
this.message = message;
this.stack = new Error(message).stack;
}
LegacyError.prototype = new Error('legacy-prototype');
const firstLegacyError = new LegacyError('first-legacy');
assert.match(firstLegacyError.stack, /^Error: first-legacy(?:\n|$)/);
assert.strictEqual(Object.hasOwn(firstLegacyError, 'stack'), false);
const secondLegacyError = new LegacyError('second-legacy');
assert.match(firstLegacyError.stack, /^Error: second-legacy(?:\n|$)/);
assert.strictEqual(secondLegacyError.stack, firstLegacyError.stack);
assert.strictEqual(LegacyError.prototype.stack, firstLegacyError.stack);
assert.strictEqual(Object.hasOwn(secondLegacyError, 'stack'), false);
const originalDefineProperty = Object.defineProperty;
try {
Object.defineProperty = () => { throw 1; };
const definePropertyPoisoned = new Error('old');
definePropertyPoisoned.name = 'Renamed';
assert.match(definePropertyPoisoned.stack, /^Renamed: old(?:\n|$)/);
} finally {
Object.defineProperty = originalDefineProperty;
}
try {
Object.prototype.value = 'poisoned';
const descriptorPolluted = new Error('old');
descriptorPolluted.name = 'Renamed';
assert.match(descriptorPolluted.stack, /^Renamed: old(?:\n|$)/);
} finally {
delete Object.prototype.value;
}
const originalFunctionCall = Function.prototype.call;
const originalArrayIsArray = Array.isArray;
const originalArrayJoin = Array.prototype.join;
const originalArrayPush = Array.prototype.push;
const originalArraySplice = Array.prototype.splice;
const originalArrayConstructor = Array.prototype.constructor;
const originalArrayIndexOne = Object.getOwnPropertyDescriptor(Array.prototype, '1');
const originalRegExpExec = RegExp.prototype.exec;
const originalStringLastIndexOf = String.prototype.lastIndexOf;
const originalStringSlice = String.prototype.slice;
const originalStringSplit = String.prototype.split;
const originalParseInt = globalThis.parseInt;
let intrinsicPoisonedStack;
try {
Function.prototype.call = () => { throw 1; };
Array.isArray = () => { throw 1; };
Array.prototype.join = () => { throw 1; };
Array.prototype.push = () => { throw 1; };
Array.prototype.splice = () => { throw 1; };
Array.prototype.constructor = {
get [Symbol.species]() { throw 1; },
};
Object.defineProperty(Array.prototype, '1', {
get() { return undefined; },
set() { throw 1; },
configurable: true,
});
RegExp.prototype.exec = () => { throw 1; };
String.prototype.lastIndexOf = () => { throw 1; };
String.prototype.slice = () => { throw 1; };
String.prototype.split = () => { throw 1; };
globalThis.parseInt = () => { throw 1; };
const intrinsicPoisoned = new Error('old');
intrinsicPoisoned.name = 'Renamed';
intrinsicPoisonedStack = intrinsicPoisoned.stack;
} finally {
Function.prototype.call = originalFunctionCall;
Array.isArray = originalArrayIsArray;
Array.prototype.join = originalArrayJoin;
Array.prototype.push = originalArrayPush;
Array.prototype.splice = originalArraySplice;
Array.prototype.constructor = originalArrayConstructor;
if (originalArrayIndexOne) {
Object.defineProperty(Array.prototype, '1', originalArrayIndexOne);
} else {
delete Array.prototype[1];
}
RegExp.prototype.exec = originalRegExpExec;
String.prototype.lastIndexOf = originalStringLastIndexOf;
String.prototype.slice = originalStringSlice;
String.prototype.split = originalStringSplit;
globalThis.parseInt = originalParseInt;
}
assert.match(intrinsicPoisonedStack, /^Renamed: old(?:\n|$)/);
const thrownWithStack = { stack: 'remote-stack', message: 'remote' };
try {
throw thrownWithStack;
} catch (error) {
assert.strictEqual(error.stack, 'remote-stack');
assert.strictEqual(Object.hasOwn(error, 'stack'), true);
}
const thrownWithoutStack = { code: 'plain' };
try {
throw thrownWithoutStack;
} catch (error) {
assert.strictEqual(error.stack, undefined);
assert.strictEqual(Object.hasOwn(error, 'stack'), false);
}
const originalStackTraceLimit = Error.stackTraceLimit;
try {
Error.stackTraceLimit = 0;
const noFrames = new Error('no-frames');
noFrames.name = 'Renamed';
assert.strictEqual(noFrames.stack, 'Renamed: no-frames');
noFrames.name = 'AfterRead';
assert.strictEqual(noFrames.stack, 'Renamed: no-frames');
} finally {
Error.stackTraceLimit = originalStackTraceLimit;
}
const sealedError = new Error('sealed');
sealedError.name = 'Initial';
Object.seal(sealedError);
sealedError.name = 'BeforeRead';
const sealedStack = sealedError.stack;
assert.match(sealedStack, /^BeforeRead: sealed(?:\n|$)/);
sealedError.name = 'AfterRead';
assert.strictEqual(sealedError.stack, sealedStack);
const symbolName = new Error('symbol-name');
symbolName.name = Symbol('invalid');
assert.throws(() => symbolName.stack, TypeError);
symbolName.name = 'Recovered';
assert.match(symbolName.stack, /^Recovered: symbol-name(?:\n|$)/);
const manualStackError = new RangeError('foo');
manualStackError.stack = 'RangeError: foo\n at manual (x.js:1:2)';
manualStackError.name = 404;
assert.strictEqual(
inspect(manualStackError),
'RangeError: foo\n at manual (x.js:1:2)',
);
return true;
} catch (e) {
console.error('testErrorInspectUsesCurrentName FAIL:', e.message);
return false;
}
};
export const testAssertionListenerStackFrame = () => {
const emitter = new EventEmitter();
emitter.on('failure', assert);
try {
emitter.emit('failure', false);
} catch (error) {
return String(error.stack).split('\n')[1] || '';
}
return '';
};
export const testCjsCallSiteLineOffset = () => {
const originalPrepare = Error.prepareStackTrace;
const filename = '/v8-call-site-line-offset.cjs';
const mapFilename = '/v8-call-site-line-offset.cjs.map';
try {
module.setSourceMapsSupport(true);
Error.prepareStackTrace = (_error, sites) => sites[0];
fs.writeFileSync(filename, [
'function branch() {',
" throw Error('site');",
'}',
'branch();',
'//# sourceMappingURL=v8-call-site-line-offset.cjs.map',
].join('\n'));
fs.writeFileSync(mapFilename, JSON.stringify({
version: 3,
sources: ['v8-call-site-line-offset.ts'],
names: [],
mappings: 'AAAA;AACA;AACA;AACA',
}));
try {
require(filename);
} catch (error) {
return String(error.stack.getLineNumber());
}
return '';
} finally {
delete require.cache[filename];
Error.prepareStackTrace = originalPrepare;
}
};
export const testPrepareStackTraceDescriptors = () => {
try {
const customPrepare = () => 'custom-prepare';
Error.prepareStackTrace = customPrepare;
Object.defineProperty(Error, 'prepareStackTrace', { enumerable: false });
assert.strictEqual(Error.prepareStackTrace, customPrepare);
const customPrepared = new Error('partial-descriptor');
assert.strictEqual(customPrepared.stack, 'custom-prepare');
const customPreparedDescriptor = Object.getOwnPropertyDescriptor(customPrepared, 'stack');
assert.strictEqual(typeof customPreparedDescriptor.get, 'function');
assert.strictEqual(typeof customPreparedDescriptor.set, 'function');
assert.strictEqual('value' in customPreparedDescriptor, false);
assert.strictEqual(customPreparedDescriptor.enumerable, false);
assert.strictEqual(customPreparedDescriptor.configurable, true);
let getterCalls = 0;
Object.defineProperty(Error, 'prepareStackTrace', {
get() {
getterCalls++;
return customPrepare;
},
configurable: true,
});
assert.strictEqual(getterCalls, 0);
const accessorPrepared = new TypeError('accessor');
assert.strictEqual(getterCalls, 0);
assert.strictEqual(accessorPrepared.stack, 'custom-prepare');
assert.strictEqual(getterCalls, 2);
let undefinedPrepareCalls = 0;
Object.defineProperty(Error, 'prepareStackTrace', {
value: error => {
if (error?.message === 'undefined-prepare') undefinedPrepareCalls++;
return undefined;
},
writable: true,
configurable: true,
});
const undefinedPrepared = new Error('undefined-prepare');
try {
throw 0;
} catch {
}
try {
throw undefinedPrepared;
} catch (error) {
assert.strictEqual(error, undefinedPrepared);
}
assert.strictEqual(undefinedPrepared.stack, undefined);
assert.strictEqual(undefinedPrepared.stack, undefined);
assert.strictEqual(undefinedPrepareCalls, 1,
'an undefined custom result must still be cached');
let stringPrepareCalls = 0;
Error.prepareStackTrace = error => {
if (error?.message === 'string-prepare') stringPrepareCalls++;
return `prepared:${error?.message}`;
};
const stringPrepared = new Error('string-prepare');
const stringPreparedValue = stringPrepared.stack;
try {
throw 0;
} catch {
}
try {
throw stringPrepared;
} catch (error) {
assert.strictEqual(error, stringPrepared);
}
assert.strictEqual(stringPrepared.stack, stringPreparedValue);
assert.strictEqual(stringPrepareCalls, 1,
'a non-undefined custom result must remain cached after rethrow');
delete Error.prepareStackTrace;
assert.match(new Error('deleted').stack, /^Error: deleted(?:\n|$)/);
const objectPrototypeCustom = Object.getOwnPropertyDescriptor(Object.prototype, 'custom');
try {
Object.defineProperty(Object.prototype, 'custom', {
value: true,
configurable: true,
});
assert.match(new Error('polluted-state').stack, /^Error: polluted-state(?:\n|$)/);
} finally {
if (objectPrototypeCustom) {
Object.defineProperty(Object.prototype, 'custom', objectPrototypeCustom);
} else {
delete Object.prototype.custom;
}
}
Object.defineProperty(Error, 'prepareStackTrace', {
value: customPrepare,
writable: true,
configurable: true,
});
Object.freeze(Error);
const descriptor = Object.getOwnPropertyDescriptor(Error, 'prepareStackTrace');
assert.strictEqual(descriptor.writable, false);
assert.strictEqual(descriptor.configurable, false);
assert.strictEqual(new Error('frozen').stack, 'custom-prepare');
return true;
} catch (e) {
console.error('testPrepareStackTraceDescriptors FAIL:', e.message);
return false;
}
};
export const testProxyStackHolderEngineBoundary = () => {
const originalPrepare = Error.prepareStackTrace;
try {
Error.prepareStackTrace = undefined;
const errorTarget = new Error('proxy-error');
let errorTrapCalls = 0;
const errorProxy = new Proxy(errorTarget, {
getPrototypeOf(target) {
errorTrapCalls++;
return Reflect.getPrototypeOf(target);
},
});
assert.strictEqual(errorProxy.stack, undefined);
assert.strictEqual(errorTrapCalls, 1);
const capturedTarget = {};
Error.captureStackTrace(capturedTarget);
let capturedTrapCalls = 0;
const capturedProxy = new Proxy(capturedTarget, {
getPrototypeOf(target) {
capturedTrapCalls++;
return Reflect.getPrototypeOf(target);
},
});
assert.strictEqual(capturedProxy.stack, undefined);
assert.strictEqual(capturedTrapCalls, 1);
return true;
} catch (e) {
console.error('testProxyStackHolderEngineBoundary FAIL:', e.message);
return false;
} finally {
Error.prepareStackTrace = originalPrepare;
}
};
export const testConstructorOpt = () => {
try {
let callSites = null;
const origPrepare = Error.prepareStackTrace;
Error.prepareStackTrace = function (error, sites) {
callSites = sites;
return sites;
};
function MyError(message) {
Error.captureStackTrace(this, MyError);
this.message = message;
}
function callerFunction() {
return new MyError('test');
}
const err = callerFunction();
const stack = err.stack;
Error.prepareStackTrace = origPrepare;
assert(Array.isArray(callSites) && callSites.length > 0);
const firstFn = callSites[0].getFunctionName();
assert.notStrictEqual(firstFn, 'MyError',
'constructorOpt should strip frames including the constructor');
return true;
} catch (e) {
console.error('testConstructorOpt FAIL:', e.message);
return false;
}
};
export const testStackTraceLimit = () => {
try {
const origLimit = Error.stackTraceLimit;
assert.strictEqual(typeof Error.stackTraceLimit, 'number');
Error.stackTraceLimit = 42;
assert.strictEqual(Error.stackTraceLimit, 42);
Error.stackTraceLimit = origLimit;
return true;
} catch (e) {
console.error('testStackTraceLimit FAIL:', e.message);
return false;
}
};
export const testDepdPattern = () => {
try {
function prepareObjectStackTrace(obj, stack) {
return stack;
}
function getStack() {
var limit = Error.stackTraceLimit;
var obj = {};
var prep = Error.prepareStackTrace;
Error.prepareStackTrace = prepareObjectStackTrace;
Error.stackTraceLimit = Math.max(10, limit);
Error.captureStackTrace(obj);
var stack = obj.stack.slice(1);
Error.prepareStackTrace = prep;
Error.stackTraceLimit = limit;
return stack;
}
function callSiteLocation(callSite) {
var file = callSite.getFileName() || '<anonymous>';
var line = callSite.getLineNumber();
var colm = callSite.getColumnNumber();
var site = [file, line, colm];
site.callSite = callSite;
site.name = callSite.getFunctionName();
return site;
}
function depd(namespace) {
var stack = getStack();
var site = callSiteLocation(stack[1]);
var file = site[0];
return { file, namespace };
}
const result = depd('test-namespace');
assert.strictEqual(result.namespace, 'test-namespace');
assert.strictEqual(typeof result.file, 'string');
return true;
} catch (e) {
console.error('testDepdPattern FAIL:', e.message);
return false;
}
};