file_path
stringlengths 3
280
| file_language
stringclasses 66
values | content
stringlengths 1
1.04M
| repo_name
stringlengths 5
92
| repo_stars
int64 0
154k
| repo_description
stringlengths 0
402
| repo_primary_language
stringclasses 108
values | developer_username
stringlengths 1
25
| developer_name
stringlengths 0
30
| developer_company
stringlengths 0
82
|
|---|---|---|---|---|---|---|---|---|---|
scripts/build-compat/index.mjs
|
JavaScript
|
await import('./data.mjs');
await import('./entries.mjs');
await import('./modules-by-versions.mjs');
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
scripts/build-compat/modules-by-versions.mjs
|
JavaScript
|
import { modules } from 'core-js-compat/src/data.mjs';
import modulesByVersions from 'core-js-compat/src/modules-by-versions.mjs';
const defaults = new Set(modules);
for (const version of Object.values(modulesByVersions)) {
for (const module of version) defaults.delete(module);
}
await fs.writeJson('packages/core-js-compat/modules-by-versions.json', {
'3.0': [...defaults],
...modulesByVersions,
}, { spaces: ' ' });
echo(chalk.green('modules-by-versions data rebuilt'));
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
scripts/build-indexes.mjs
|
JavaScript
|
import { modules } from 'core-js-compat/src/data.mjs';
async function generateNamespaceIndex(ns, filter) {
return fs.writeFile(`./packages/core-js/${ ns }/index.js`, `'use strict';\n${ modules
.filter(it => filter.test(it))
.map(it => `require('../modules/${ it }');\n`)
.join('') }\nmodule.exports = require('../internals/path');\n`);
}
async function generateTestsIndex(name, pkg) {
const dir = `tests/${ name }`;
const files = await fs.readdir(dir);
return fs.writeFile(`${ dir }/index.js`, `import '../helpers/qunit-helpers';\n\n${ files
.filter(it => /^(?:es|esnext|web)\./.test(it))
.map(it => `import './${ it.slice(0, -3) }';\n`)
.join('') }${ pkg !== 'core-js' ? `\nimport core from '${ pkg }';\ncore.globalThis.core = core;\n` : '' }`);
}
await generateNamespaceIndex('es', /^es\./);
await generateNamespaceIndex('stable', /^(?:es|web)\./);
await generateNamespaceIndex('full', /^(?:es|esnext|web)\./);
await generateTestsIndex('unit-global', 'core-js');
await generateTestsIndex('unit-pure', 'core-js-pure');
echo(chalk.green('indexes generated'));
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
scripts/bundle-package/bundle-package.mjs
|
JavaScript
|
import { minify } from 'terser';
import builder from 'core-js-builder';
import config from 'core-js-builder/config.js';
const { cyan, green } = chalk;
const DENO = argv._.includes('deno');
const ESMODULES = argv._.includes('esmodules');
const BUNDLED_NAME = argv._.includes('bundled-name') ? argv._[argv._.indexOf('bundled-name') + 1] : 'index';
const MINIFIED_NAME = argv._.includes('minified-name') ? argv._[argv._.indexOf('minified-name') + 1] : 'minified';
const PATH = DENO ? 'deno/corejs/' : 'packages/core-js-bundle/';
function log(kind, name, code) {
const size = (code.length / 1024).toFixed(2);
echo(green(`${ kind }: ${ cyan(`${ PATH }${ name }.js`) }, size: ${ cyan(`${ size }KB`) }`));
}
async function bundle({ bundled, minified, options = {} }) {
const source = await builder(options);
log('bundling', bundled, source);
await fs.writeFile(`${ PATH }${ bundled }.js`, source);
if (!minified) return;
const { code, map } = await minify(source, {
ecma: 3,
ie8: true,
safari10: true,
keep_fnames: true,
compress: {
hoist_funs: true,
hoist_vars: true,
passes: 2,
pure_getters: true,
// document.all detection case
typeofs: false,
unsafe_proto: true,
unsafe_undefined: true,
},
format: {
max_line_len: 32000,
preamble: config.banner,
webkit: true,
// https://v8.dev/blog/preparser#pife
wrap_func_args: false,
},
sourceMap: {
url: `${ minified }.js.map`,
},
});
await fs.writeFile(`${ PATH }${ minified }.js`, code);
await fs.writeFile(`${ PATH }${ minified }.js.map`, map);
log('minification', minified, code);
}
await bundle(DENO ? {
bundled: BUNDLED_NAME,
options: {
targets: { deno: '1.0' },
exclude: [
'esnext.array.filter-out', // obsolete
'esnext.map.update-or-insert', // obsolete
'esnext.map.upsert', // obsolete
'esnext.math.iaddh', // withdrawn
'esnext.math.imulh', // withdrawn
'esnext.math.isubh', // withdrawn
'esnext.math.seeded-prng', // changing of the API, waiting for the spec text
'esnext.math.umulh', // withdrawn
'esnext.object.iterate-entries', // withdrawn
'esnext.object.iterate-keys', // withdrawn
'esnext.object.iterate-values', // withdrawn
'esnext.string.at', // withdrawn
'esnext.symbol.pattern-match', // is not a part of actual proposal, replaced by esnext.symbol.matcher
'esnext.symbol.replace-all', // obsolete
'esnext.typed-array.filter-out', // obsolete
'esnext.weak-map.upsert', // obsolete
],
},
} : {
bundled: BUNDLED_NAME,
minified: MINIFIED_NAME,
options: ESMODULES ? { targets: { esmodules: true } } : {},
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
scripts/bundle-tests/bundle-tests.mjs
|
JavaScript
|
await Promise.all([
['unit-global/index', 'unit-global'],
['unit-pure/index', 'unit-pure'],
].map(([entry, output]) => $`webpack \
--entry ../../tests/${ entry }.js \
--output-filename ${ output }.js \
`));
await Promise.all([
fs.copyFile('../../packages/core-js-bundle/index.js', '../../tests/bundles/core-js-bundle.js'),
fs.copyFile('./node_modules/@slowcheetah/qunitjs-1/qunit/qunit.js', '../../tests/bundles/qunit.js'),
fs.copyFile('./node_modules/@slowcheetah/qunitjs-1/qunit/qunit.css', '../../tests/bundles/qunit.css'),
]);
echo(chalk.green('\ntests bundled, qunit and core-js bundles copied into /tests/bundles/'));
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
scripts/bundle-tests/webpack.config.js
|
JavaScript
|
'use strict';
const { resolve } = require('node:path');
const babelConfig = require('../../babel.config');
module.exports = {
mode: 'none',
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: babelConfig,
},
}],
},
node: false,
target: ['node', 'es5'],
stats: 'errors-warnings',
output: {
hashFunction: 'md5',
path: resolve(__dirname, '../../tests/bundles'),
},
};
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
scripts/check-actions/check-actions.mjs
|
JavaScript
|
await $`actions-up --dry-run`;
echo(chalk.green('actions dependencies checked'));
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
scripts/check-compat-data-mapping.mjs
|
JavaScript
|
import semver from 'semver';
import mapping from 'core-js-compat/src/mapping.mjs';
const { coerce, cmp } = semver;
let updated = true;
async function getJSON(path, ...slice) {
const result = await fetch(path);
const text = await result.text();
return JSON.parse(text.slice(...slice));
}
async function getFromMDN(name, branch = 'mdn/browser-compat-data/main') {
const {
browsers: { [name]: { releases } },
} = await getJSON(`https://raw.githubusercontent.com/${ branch }/browsers/${ name }.json`);
return releases;
}
async function getLatestFromMDN(name, branch) {
const releases = await getFromMDN(name, branch);
const version = Object.keys(releases).reduce((a, b) => {
return releases[b].engine_version && cmp(coerce(b), '>', coerce(a)) ? b : a;
});
return { engine: releases[version].engine_version, version };
}
function modernV8ToChrome(string) {
const version = coerce(string);
return version.major * 10 + version.minor;
}
function latest(array) {
return array[array.length - 1];
}
function assert(condition, engine) {
if (!condition) {
updated = false;
echo(chalk.red(`${ chalk.cyan(engine) } mapping should be updated`));
}
}
const [
[{ v8 }],
electron,
deno,
oculus,
opera,
operaAndroid,
safari,
ios,
samsung,
] = await Promise.all([
getJSON('https://nodejs.org/dist/index.json'),
getJSON('https://raw.githubusercontent.com/Kilian/electron-to-chromium/master/chromium-versions.js', 17, -1),
getLatestFromMDN('deno'),
getLatestFromMDN('oculus'),
getLatestFromMDN('opera'),
getLatestFromMDN('opera_android'),
getFromMDN('safari'),
getLatestFromMDN('safari_ios'),
getLatestFromMDN('samsunginternet_android'),
]);
assert(modernV8ToChrome(v8) <= latest(mapping.ChromeToNode)[0], 'NodeJS');
assert(latest(Object.entries(electron))[0] <= latest(mapping.ChromeToElectron)[0], 'Electron');
assert(modernV8ToChrome(deno.engine) <= latest(mapping.ChromeToDeno)[0], 'Deno');
assert(oculus.engine <= latest(mapping.ChromeAndroidToQuest)[0], 'Meta Quest');
assert(opera.version === String(mapping.ChromeToOpera(opera.engine)), 'Opera');
assert(operaAndroid.engine <= latest(mapping.ChromeAndroidToOperaAndroid)[0], 'Opera for Android');
assert(ios.version === Object.entries(safari).find(([, { engine_version: engine }]) => engine === ios.engine)[0], 'iOS Safari');
assert(samsung.engine <= latest(mapping.ChromeAndroidToSamsung)[0], 'Samsung Internet');
if (updated) echo(chalk.green('updates of compat data mapping not required'));
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
scripts/check-dependencies/check-dependencies.mjs
|
JavaScript
|
const ignore = {
'core-js-builder': [
'mkdirp',
'webpack',
],
'tests/observables': [
'moon-unit',
],
};
const pkgs = await glob([
'package.json',
'website/package.json',
'@(packages|scripts|tests)/*/package.json',
]);
await Promise.all(pkgs.map(async path => {
const { name = 'root', dependencies, devDependencies } = await fs.readJson(path);
if (!dependencies && !devDependencies) return;
const exclude = ignore[name];
const { stdout } = await $({ verbose: false })`updates \
--json \
--file ${ path } \
--exclude ${ Array.isArray(exclude) ? exclude.join(',') : '' } \
`;
const results = JSON.parse(stdout)?.results?.npm;
const obsolete = { ...results?.dependencies, ...results?.devDependencies };
if (Object.keys(obsolete).length) {
echo(chalk.cyan(`${ name }:`));
console.table(obsolete);
}
}));
echo(chalk.green('dependencies checked'));
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
scripts/check-unused-modules.mjs
|
JavaScript
|
import konan from 'konan';
import { modules, ignored } from 'core-js-compat/src/data.mjs';
async function jsModulesFrom(path) {
const directory = await fs.readdir(path);
return new Set(directory.filter(it => it.endsWith('.js')).map(it => it.slice(0, -3)));
}
function log(set, kind) {
if (set.size) {
echo(chalk.red(`found some unused ${ kind }:`));
set.forEach(it => echo(chalk.cyan(it)));
} else echo(chalk.green(`unused ${ kind } not found`));
}
const globalModules = await jsModulesFrom('packages/core-js/modules');
const definedModules = new Set([
...modules,
...ignored,
// TODO: Drop from core-js@4
'esnext.string.at-alternative',
]);
globalModules.forEach(it => definedModules.has(it) && globalModules.delete(it));
log(globalModules, 'modules');
const internalModules = await jsModulesFrom('packages/core-js/internals');
const allModules = await glob('packages/core-js?(-pure)/**/*.js');
await Promise.all(allModules.map(async path => {
for (const dependency of konan(String(await fs.readFile(path, 'utf8'))).strings) {
internalModules.delete(dependency.match(/\/internals\/(?<module>[^/]+)$/)?.groups.module);
}
}));
log(internalModules, 'internal modules');
const pureModules = new Set(await glob('packages/core-js-pure/override/**/*.js'));
await Promise.all([...pureModules].map(async path => {
if (await fs.pathExists(path.replace('-pure/override', ''))) pureModules.delete(path);
}));
log(pureModules, 'pure modules');
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
scripts/clean-and-copy.mjs
|
JavaScript
|
const { copy, ensureFile, lstat, pathExists, rm, writeFile } = fs;
let copied = 0;
function options(overwrite) {
return {
async filter(from, to) {
if ((await lstat(from)).isDirectory()) return true;
if (!overwrite && await pathExists(to)) return false;
return !!++copied;
},
};
}
await Promise.all((await glob([
'tests/**/bundles/*',
// TODO: drop it from `core-js@4`
'packages/core-js/features',
'packages/core-js-pure/!(override|.npmignore|package.json|README.md)',
], { onlyFiles: false })).map(path => rm(path, { force: true, recursive: true })));
echo(chalk.green('old copies removed'));
// TODO: drop it from `core-js@4`
const files = await glob('packages/core-js/full/**/*.js');
for (const filename of files) {
const newFilename = filename.replace('full', 'features');
const href = '../'.repeat(filename.split('').filter(it => it === '/').length - 2) + filename.slice(17, -3).replace(/\/index$/, '');
await ensureFile(newFilename);
await writeFile(newFilename, `'use strict';\nmodule.exports = require('${ href }');\n`);
}
echo(chalk.green('created /features/ entries'));
await copy('packages/core-js', 'packages/core-js-pure', options(false));
const license = [
'deno/corejs/LICENSE',
...(await glob('packages/*/package.json')).map(path => path.replace(/package\.json$/, 'LICENSE')),
];
await Promise.all([
copy('packages/core-js-pure/override', 'packages/core-js-pure', options(true)),
copy('packages/core-js/postinstall.js', 'packages/core-js-bundle/postinstall.js', options(true)),
...license.map(path => copy('LICENSE', path, options(true))),
]);
echo(chalk.green(`copied ${ chalk.cyan(copied) } files`));
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
scripts/downloads-by-versions.mjs
|
JavaScript
|
import semver from 'semver';
const { coerce, cmp } = semver;
const { cyan, green } = chalk;
const ALL = !argv._.includes('main-only');
const downloadsByPatch = {};
const downloadsByMinor = {};
const downloadsByMajor = {};
let total = 0;
async function getStat(pkg) {
const res = await fetch(`https://api.npmjs.org/versions/${ encodeURIComponent(pkg) }/last-week`);
const { downloads } = await res.json();
return downloads;
}
const [core, pure, bundle] = await Promise.all([
getStat('core-js'),
// eslint-disable-next-line unicorn/prefer-top-level-await -- false positive
ALL && getStat('core-js-pure'),
// eslint-disable-next-line unicorn/prefer-top-level-await -- false positive
ALL && getStat('core-js-bundle'),
]);
for (let [patch, downloads] of Object.entries(core)) {
const version = coerce(patch);
const { major } = version;
const minor = `${ major }.${ version.minor }`;
if (ALL) downloads += (pure[patch] ?? 0) + (bundle[patch] ?? 0);
downloadsByPatch[patch] = downloads;
downloadsByMinor[minor] = (downloadsByMinor[minor] ?? 0) + downloads;
downloadsByMajor[major] = (downloadsByMajor[major] ?? 0) + downloads;
total += downloads;
}
function log(kind, map) {
echo(green(`downloads for 7 days by ${ cyan(kind) } releases:`));
console.table(Object.entries(map).toSorted(([a], [b]) => {
return cmp(coerce(a), '>', coerce(b)) ? 1 : -1;
}).reduce((memo, [version, downloads]) => {
memo[version] = { downloads, '%': `${ (downloads / total * 100).toFixed(2).padStart(5) } %` };
return memo;
}, {}));
}
log('patch', downloadsByPatch);
log('minor', downloadsByMinor);
log('major', downloadsByMajor);
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
scripts/prepare-monorepo.mjs
|
JavaScript
|
import childProcess from 'node:child_process';
import { readdir, rm } from 'node:fs/promises';
import { promisify } from 'node:util';
const exec = promisify(childProcess.exec);
const { UPDATE_DEPENDENCIES } = process.env;
const ignore = new Set([
'scripts/check-actions',
'scripts/usage',
'tests/test262',
'tests/unit-bun',
]);
const folders = [''].concat(...await Promise.all([
'packages',
'scripts',
'tests',
].map(async parent => {
const dir = await readdir(parent);
return dir.map(name => `${ parent }/${ name }`);
})));
await Promise.all(folders.map(async folder => {
if (!ignore.has(folder)) try {
if (UPDATE_DEPENDENCIES) await rm(`./${ folder }/package-lock.json`, { force: true });
await rm(`./${ folder }/node_modules`, { force: true, recursive: true });
} catch { /* empty */ }
}));
console.log('\u001B[32mdependencies cleaned\u001B[0m');
await exec(UPDATE_DEPENDENCIES ? 'npm i' : 'npm ci');
console.log('\u001B[32mdependencies installed\u001B[0m');
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
scripts/prepare.mjs
|
JavaScript
|
await import('./build-indexes.mjs');
await import('./clean-and-copy.mjs');
await $`npm run build-compat`;
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
scripts/update-version.mjs
|
JavaScript
|
const { readJson, readFile, writeJson, writeFile } = fs;
const { green, red } = chalk;
const [PREV_VERSION, NEW_VERSION] = (await Promise.all([
readJson('packages/core-js/package.json'),
readJson('package.json'),
])).map(it => it.version);
function getMinorVersion(version) {
return version.match(/^(?<minor>\d+\.\d+)\..*/).groups.minor;
}
const PREV_VERSION_MINOR = getMinorVersion(PREV_VERSION);
const NEW_VERSION_MINOR = getMinorVersion(NEW_VERSION);
const CHANGELOG = 'CHANGELOG.md';
const LICENSE = 'LICENSE';
const README = 'README.md';
const README_COMPAT = 'packages/core-js-compat/README.md';
const README_DENO = 'deno/corejs/README.md';
const SHARED = 'packages/core-js/internals/shared-store.js';
const BUILDER_CONFIG = 'packages/core-js-builder/config.js';
const USAGE = 'docs/web/docs/usage.md';
const NOW = new Date();
const CURRENT_YEAR = NOW.getFullYear();
const license = await readFile(LICENSE, 'utf8');
const OLD_YEAR = +license.match(/2025–(?<year>\d{4}) C/).groups.year;
await writeFile(LICENSE, license.replaceAll(OLD_YEAR, CURRENT_YEAR));
const readme = await readFile(README, 'utf8');
await writeFile(README, readme.replaceAll(PREV_VERSION, NEW_VERSION).replaceAll(PREV_VERSION_MINOR, NEW_VERSION_MINOR));
const readmeCompat = await readFile(README_COMPAT, 'utf8');
await writeFile(README_COMPAT, readmeCompat.replaceAll(PREV_VERSION_MINOR, NEW_VERSION_MINOR));
const readmeDeno = await readFile(README_DENO, 'utf8');
await writeFile(README_DENO, readmeDeno.replaceAll(PREV_VERSION, NEW_VERSION));
const shared = await readFile(SHARED, 'utf8');
await writeFile(SHARED, shared.replaceAll(PREV_VERSION, NEW_VERSION).replaceAll(OLD_YEAR, CURRENT_YEAR));
const builderConfig = await readFile(BUILDER_CONFIG, 'utf8');
await writeFile(BUILDER_CONFIG, builderConfig.replaceAll(OLD_YEAR, CURRENT_YEAR));
const usage = await readFile(USAGE, 'utf8');
await writeFile(USAGE, usage.replaceAll(PREV_VERSION, NEW_VERSION).replaceAll(PREV_VERSION_MINOR, NEW_VERSION_MINOR));
const packages = await Promise.all((await glob('packages/*/package.json')).map(async path => {
const pkg = await readJson(path, 'utf8');
return { path, pkg };
}));
for (const { path, pkg } of packages) {
pkg.version = NEW_VERSION;
for (const field of ['dependencies', 'devDependencies']) {
if (pkg[field]) for (const { pkg: { name } } of packages) {
if (pkg[field][name]) pkg[field][name] = NEW_VERSION;
}
}
await writeJson(path, pkg, { spaces: ' ' });
}
if (NEW_VERSION !== PREV_VERSION) {
const CURRENT_DATE = `${ CURRENT_YEAR }.${ String(NOW.getMonth() + 1).padStart(2, '0') }.${ String(NOW.getDate()).padStart(2, '0') }`;
const NUMBER_OF_COMMITS = Number(await $`git rev-list "v${ PREV_VERSION }"..HEAD --count`) + 1;
const changelog = await readFile(CHANGELOG, 'utf8');
await writeFile(CHANGELOG, changelog.replaceAll('### Unreleased', `### Unreleased\n- Nothing\n\n### [${
NEW_VERSION
} - ${
CURRENT_DATE
}](https://github.com/zloirock/core-js/releases/tag/v${
NEW_VERSION
})\n- Changes [v${
PREV_VERSION
}...v${
NEW_VERSION
}](https://github.com/zloirock/core-js/compare/v${
PREV_VERSION
}...v${
NEW_VERSION
}) (${
NUMBER_OF_COMMITS
} commits)`));
}
if (CURRENT_YEAR !== OLD_YEAR) echo(green('the year updated'));
if (NEW_VERSION !== PREV_VERSION) echo(green('the version updated'));
else if (CURRENT_YEAR === OLD_YEAR) echo(red('bump is not required'));
await $`npm run bundle-package deno`;
await $`npm run build-compat`;
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
scripts/usage/usage.mjs
|
JavaScript
|
import { chromium } from 'playwright-extra';
import StealthPlugin from 'puppeteer-extra-plugin-stealth';
import jszip from 'jszip';
const { cyan, green, gray, red } = chalk;
const agents = [
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36',
'Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko',
];
const protocols = ['http', 'https'];
const limit = argv._[0] ?? 100;
const attempts = new Map();
const start = Date.now();
let tested = 0;
let withCoreJS = 0;
echo(green('downloading and parsing T1M Alexa data, it could take some seconds'));
// https://s3.amazonaws.com/alexa-static/top-1m.csv.zip is no longer provided, so using the last copy of the dataset from my server
// here could be used, for example, Cisco Umbrella statistics - http://s3-us-west-1.amazonaws.com/umbrella-static/top-1m.csv.zip,
// however, it's not so relative to our case like the Alexa list
// makes sense take a look at https://github.com/PeterDaveHello/top-1m-domains
const response = await fetch('http://es6.zloirock.ru/top-1m.csv.zip');
const archive = await jszip.loadAsync(await response.arrayBuffer());
const file = await archive.file('top-1m.csv.deprecated').async('string');
const BANNER_LINES = 8;
const sites = file
.split('\n', limit + BANNER_LINES)
.slice(BANNER_LINES)
.map(line => line.match(/^\d+,(?<site>.+)$/).groups.site)
.reverse();
echo(green(`downloading and parsing the rank took ${ cyan((Date.now() - start) / 1e3) } seconds\n${ gray('-'.repeat(120)) }`));
function timeout(promise, time) {
return Promise.race([promise, new Promise((resolve, reject) => setTimeout(() => reject(new Error('timeout')), time))]);
}
chromium.use(StealthPlugin());
// run in parallel
await Promise.all(Array(Math.ceil(os.cpus().length / 2)).fill().map(async () => {
let browser, site;
async function check() {
let errors = 0;
for (const protocol of protocols) for (const userAgent of agents) try {
const page = await browser.newPage({ userAgent });
page.setDefaultNavigationTimeout(6e4);
await page.goto(`${ protocol }://${ site }`);
// seems js hangs on some sites, so added a time limit
const { core, modern, legacy } = await timeout(page.evaluate(`({
core: !!window['__core-js_shared__'] || !!window.core || !!window._babelPolyfill,
modern: window['__core-js_shared__']?.versions,
legacy: window.core?.version,
})`), 1e4);
const versions = modern ? modern.map(({ version, mode }) => `${ version } (${ mode } mode)`) : legacy ? [legacy] : [];
await page.close();
if (core) return { core, versions };
} catch (error) {
if (++errors === 4) throw error;
} return {};
}
while (site = sites.pop()) try {
await browser?.close();
browser = await chromium.launch();
const { core, versions } = await check();
tested++;
if (core) withCoreJS++;
echo`${ cyan(`${ site }:`) } ${ core
? green(`\`core-js\` is detected, ${ versions.length > 1
? `${ cyan(versions.length) } versions: ${ cyan(versions.join(', ')) }`
: `version ${ cyan(versions[0]) }` }`)
: gray('`core-js` is not detected') }`;
} catch {
const attempting = (attempts.get(site) | 0) + 1;
attempts.set(site, attempting);
if (attempting < 3) sites.push(site);
else echo(red(`${ cyan(`${ site }:`) } problems with access`));
await sleep(3e3);
}
return browser?.close();
}));
echo(green(`\n\`core-js\` is detected on ${ cyan(withCoreJS) } from ${ cyan(tested) } tested websites, ${
cyan(`${ (withCoreJS / tested * 100).toFixed(2) }%`) }, problems with access to ${ cyan(limit - tested) } websites`));
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
scripts/zxi.mjs
|
JavaScript
|
const { dirname, resolve } = path;
const { pathExists } = fs;
const { cwd, env } = process;
const { _: args } = argv;
const { cyan, green } = chalk;
const CD = args.includes('cd');
const TIME = args.includes('time');
if (CD) args.splice(args.indexOf('cd'), 1);
if (TIME) args.splice(args.indexOf('time'), 1);
const FILE = args.shift();
const DIR = dirname(FILE);
$.verbose = true;
if (await pathExists(`${ DIR }/package.json`)) {
await $({ cwd: DIR })`npm install \
--no-audit \
--no-fund \
--lockfile-version=3 \
--loglevel=error \
--force \
`;
$.preferLocal = [resolve(DIR), cwd()];
}
if (CD) cd(DIR);
env.FORCE_COLOR = '1';
const start = Date.now();
await import(`../${ FILE }`);
if (TIME) echo(green(`\n${ FILE } took ${ cyan((Date.now() - start) / 1000) } seconds`));
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/builder/builder.mjs
|
JavaScript
|
import { ok } from 'node:assert/strict';
import builder from 'core-js-builder';
const polyfills = await builder({
modules: 'core-js/actual',
exclude: [/group-by/, 'esnext.typed-array.to-spliced'],
targets: { node: 16 },
format: 'esm',
});
ok(polyfills.includes("import 'core-js/modules/es.error.cause.js';"), 'actual node 16 #1');
ok(polyfills.includes("import 'core-js/modules/es.array.push.js';"), 'actual node 16 #2');
ok(polyfills.includes("import 'core-js/modules/esnext.array.group.js';"), 'actual node 16 #3');
ok(polyfills.includes("import 'core-js/modules/web.structured-clone.js';"), 'actual node 16 #4');
ok(!polyfills.includes("import 'core-js/modules/es.weak-set.js';"), 'actual node 16 #5');
ok(!polyfills.includes("import 'core-js/modules/esnext.weak-set.from.js';"), 'actual node 16 #6');
ok(!polyfills.includes("import 'core-js/modules/esnext.array.group-by.js';"), 'actual node 16 #7');
echo(chalk.green('builder tested'));
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/codespell/runner.mjs
|
JavaScript
|
const skip = [
'*.map',
'package**.json',
'**/node_modules/**',
'./tests/**bundles',
'./packages/core-js-bundle/*.js',
];
const ignoreWords = [
'aNumber',
'larg',
'outLow',
'statics',
];
await $`codespell \
--skip=${ String(skip) } \
--ignore-words-list=${ String(ignoreWords) } \
--enable-colors`;
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/compat-data/index.mjs
|
JavaScript
|
await import('./modules-by-versions.mjs');
await import('./tests-coverage.mjs');
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/compat-data/modules-by-versions.mjs
|
JavaScript
|
import coerce from 'semver/functions/coerce.js';
const { version } = await fs.readJson('package.json');
const { major, minor, patch } = coerce(version);
let ok = true;
if (minor || patch) { // ignore for pre-releases
const zero = `${ major }.0`;
const modulesByVersions = await fs.readJson('packages/core-js-compat/modules-by-versions.json');
const response = await fetch(`https://cdn.jsdelivr.net/npm/core-js-compat@${ major }.0.0/modules-by-versions.json`);
const zeroVersionData = await response.json();
const set = new Set(zeroVersionData[zero]);
for (const mod of modulesByVersions[zero]) {
if (!set.has(mod)) {
ok = false;
echo(chalk.red(`${ chalk.cyan(mod) } should be added to modules-by-versions`));
}
}
}
if (!ok) throw echo(chalk.red('\nmodules-by-versions should be updated'));
echo(chalk.green('modules-by-versions checked'));
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/compat-data/tests-coverage.mjs
|
JavaScript
|
import { modules, ignored } from 'core-js-compat/src/data.mjs';
import '../compat/tests.js';
const modulesSet = new Set([
...modules,
...ignored,
]);
const tested = new Set(Object.keys(globalThis.tests));
const ignore = new Set([
'es.aggregate-error',
'es.data-view',
'es.map',
'es.set',
'es.weak-map',
'es.weak-set',
'esnext.aggregate-error',
'esnext.array.filter-out',
'esnext.array.group',
'esnext.array.group-by',
'esnext.array.group-by-to-map',
'esnext.array.group-to-map',
'esnext.array.last-index',
'esnext.array.last-item',
'esnext.async-iterator.as-indexed-pairs',
'esnext.async-iterator.indexed',
'esnext.bigint.range',
'esnext.function.un-this',
'esnext.iterator.as-indexed-pairs',
'esnext.iterator.indexed',
'esnext.iterator.sliding',
'esnext.map.emplace',
'esnext.map.update-or-insert',
'esnext.map.upsert',
'esnext.math.clamp',
'esnext.math.iaddh',
'esnext.math.imulh',
'esnext.math.isubh',
'esnext.math.seeded-prng',
'esnext.math.umulh',
'esnext.number.range',
'esnext.object.iterate-entries',
'esnext.object.iterate-keys',
'esnext.object.iterate-values',
'esnext.observable',
'esnext.observable.constructor',
'esnext.observable.from',
'esnext.observable.of',
'esnext.reflect.define-metadata',
'esnext.reflect.delete-metadata',
'esnext.reflect.get-metadata',
'esnext.reflect.get-metadata-keys',
'esnext.reflect.get-own-metadata',
'esnext.reflect.get-own-metadata-keys',
'esnext.reflect.has-metadata',
'esnext.reflect.has-own-metadata',
'esnext.reflect.metadata',
'esnext.set.difference',
'esnext.set.intersection',
'esnext.set.is-disjoint-from',
'esnext.set.is-subset-of',
'esnext.set.is-superset-of',
'esnext.set.symmetric-difference',
'esnext.set.union',
'esnext.string.at',
'esnext.symbol.is-registered',
'esnext.symbol.is-well-known',
'esnext.symbol.matcher',
'esnext.symbol.metadata-key',
'esnext.symbol.pattern-match',
'esnext.symbol.replace-all',
'esnext.typed-array.from-async',
'esnext.typed-array.filter-out',
'esnext.typed-array.group-by',
'esnext.typed-array.to-spliced',
'esnext.weak-map.emplace',
'esnext.weak-map.upsert',
'web.url-search-params',
'web.url',
]);
const missed = modules.filter(it => !(tested.has(it) || tested.has(it.replace(/^esnext\./, 'es.')) || ignore.has(it)));
let error = false;
for (const it of tested) {
if (!modulesSet.has(it)) {
echo(chalk.red(`added extra compat data test: ${ chalk.cyan(it) }`));
error = true;
}
}
if (missed.length) {
echo(chalk.red('some of compat data tests missed:'));
for (const it of missed) echo(chalk.cyan(it));
error = true;
} else echo(chalk.green('adding of compat data tests not required'));
if (error) throw new Error(error);
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/compat-tools/compat.mjs
|
JavaScript
|
import { deepEqual, ok } from 'node:assert/strict';
import compat from 'core-js-compat/compat.js';
deepEqual(compat({
modules: [
'core-js/es/math',
'es.array.at',
/^es\.reflect/,
],
exclude: [
'es.reflect.prevent-extensions',
],
targets: 'firefox 27',
}), {
list: [
'es.array.at',
'es.array.iterator',
'es.math.clz32',
'es.math.expm1',
'es.math.f16round',
'es.math.sum-precise',
'es.math.to-string-tag',
'es.reflect.apply',
'es.reflect.construct',
'es.reflect.define-property',
'es.reflect.delete-property',
'es.reflect.get',
'es.reflect.get-own-property-descriptor',
'es.reflect.get-prototype-of',
'es.reflect.has',
'es.reflect.is-extensible',
'es.reflect.own-keys',
'es.reflect.set',
'es.reflect.set-prototype-of',
'es.reflect.to-string-tag',
],
targets: {
'es.array.at': { firefox: '27' },
'es.array.iterator': { firefox: '27' },
'es.math.clz32': { firefox: '27' },
'es.math.expm1': { firefox: '27' },
'es.math.f16round': { firefox: '27' },
'es.math.sum-precise': { firefox: '27' },
'es.math.to-string-tag': { firefox: '27' },
'es.reflect.apply': { firefox: '27' },
'es.reflect.construct': { firefox: '27' },
'es.reflect.define-property': { firefox: '27' },
'es.reflect.delete-property': { firefox: '27' },
'es.reflect.get': { firefox: '27' },
'es.reflect.get-own-property-descriptor': { firefox: '27' },
'es.reflect.get-prototype-of': { firefox: '27' },
'es.reflect.has': { firefox: '27' },
'es.reflect.is-extensible': { firefox: '27' },
'es.reflect.own-keys': { firefox: '27' },
'es.reflect.set': { firefox: '27' },
'es.reflect.set-prototype-of': { firefox: '27' },
'es.reflect.to-string-tag': { firefox: '27' },
},
}, 'basic');
deepEqual(compat({
modules: [
/^es\.math\.a/,
/^es\.math\.c/,
],
exclude: 'es.math.asinh',
}), {
list: [
'es.math.acosh',
'es.math.atanh',
'es.math.cbrt',
'es.math.clz32',
'es.math.cosh',
],
targets: {
'es.math.acosh': {},
'es.math.atanh': {},
'es.math.cbrt': {},
'es.math.clz32': {},
'es.math.cosh': {},
},
}, 'no target');
deepEqual(compat({
modules: /^es\.math\.a/,
}), {
list: [
'es.math.acosh',
'es.math.asinh',
'es.math.atanh',
],
targets: {
'es.math.acosh': {},
'es.math.asinh': {},
'es.math.atanh': {},
},
}, 'no exclude');
deepEqual(
compat({ targets: { chrome: 93 } }),
compat({ modules: 'core-js', targets: { chrome: 93 } }),
'no modules',
);
deepEqual(compat({
modules: 'core-js/es/math',
targets: {
chrome: 40,
firefox: 27,
},
}), {
list: [
'es.array.iterator',
'es.math.acosh',
'es.math.clz32',
'es.math.expm1',
'es.math.f16round',
'es.math.hypot',
'es.math.sum-precise',
'es.math.to-string-tag',
],
targets: {
'es.array.iterator': { chrome: '40', firefox: '27' },
'es.math.acosh': { chrome: '40' },
'es.math.clz32': { firefox: '27' },
'es.math.expm1': { firefox: '27' },
'es.math.f16round': { chrome: '40', firefox: '27' },
'es.math.hypot': { chrome: '40' },
'es.math.sum-precise': { chrome: '40', firefox: '27' },
'es.math.to-string-tag': { chrome: '40', firefox: '27' },
},
}, 'some targets');
const { list: inverted1 } = compat({ targets: { esmodules: true }, inverse: true });
ok(inverted1.includes('es.symbol.iterator'), 'inverse #1');
ok(!inverted1.includes('esnext.iterator.from'), 'inverse #2');
ok(!inverted1.includes('esnext.array.at'), 'inverse #3');
const { list: inverted2 } = compat({ modules: 'core-js/es/math', targets: { esmodules: true }, inverse: true });
ok(inverted2.includes('es.math.acosh'), 'inverse #4');
ok(!inverted2.includes('es.map'), 'inverse #5');
echo(chalk.green('compat tool tested'));
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/compat-tools/get-modules-list-for-target-version.mjs
|
JavaScript
|
import { deepEqual, throws } from 'node:assert/strict';
import getModulesListForTargetVersion from 'core-js-compat/get-modules-list-for-target-version.js';
const modules = await fs.readJson('packages/core-js-compat/modules.json');
const modulesByVersions = await fs.readJson('packages/core-js-compat/modules-by-versions.json');
const modules30 = modulesByVersions['3.0'];
const filter = new Set([...modules30, ...modulesByVersions['3.1']]);
const modules31 = modules.filter(it => filter.has(it));
deepEqual(getModulesListForTargetVersion(3), modules30, 'num 3'); // TODO: Make it throw in core-js@4
deepEqual(getModulesListForTargetVersion('3'), modules30, '3'); // TODO: Make it throw in core-js@4
deepEqual(getModulesListForTargetVersion('3.0'), modules30, '3.0');
deepEqual(getModulesListForTargetVersion('3.0.0'), modules30, '3.0.0');
deepEqual(getModulesListForTargetVersion('3.0.1'), modules30, '3.0.1');
deepEqual(getModulesListForTargetVersion('3.0.0-alpha.1'), modules30, '3.0.0-alpha.1');
deepEqual(getModulesListForTargetVersion('3.1'), modules31, '3.1');
deepEqual(getModulesListForTargetVersion('3.1.0'), modules31, '3.1.0');
deepEqual(getModulesListForTargetVersion('3.1.1'), modules31, '3.1.1');
throws(() => getModulesListForTargetVersion('2.0'), RangeError, '2.0');
throws(() => getModulesListForTargetVersion('4.0'), RangeError, '4.0');
throws(() => getModulesListForTargetVersion('x'), TypeError, 'x');
throws(() => getModulesListForTargetVersion('*'), TypeError, '*');
throws(() => getModulesListForTargetVersion(), TypeError, 'no arg');
echo(chalk.green('get-modules-list-for-target-version tested'));
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/compat-tools/index.mjs
|
JavaScript
|
await import('./compat.mjs');
await import('./targets-parser.mjs');
await import('./get-modules-list-for-target-version.mjs');
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/compat-tools/targets-parser.mjs
|
JavaScript
|
import { deepEqual } from 'node:assert/strict';
import targetsParser from 'core-js-compat/targets-parser.js';
deepEqual(targetsParser('ie 11, chrome 56, ios 12.2'), new Map([
['chrome', '56'],
['ie', '11'],
['ios', '12.2-12.5'],
]), 'browserslist');
deepEqual(targetsParser('baseline 2022 or not and_chr <= 999 or not and_ff <= 999 or ios 15.3 or ie 11'), new Map([
['chrome', '108'],
['edge', '108'],
['firefox', '108'],
['ie', '11'],
['ios', '15.2-15.3'],
['safari', '16.0'],
]), 'browserslist with baseline');
deepEqual(targetsParser({
ie: 11,
chrome: 56,
ios: '12.2',
}), new Map([
['chrome', '56'],
['ie', '11'],
['ios', '12.2'],
]), 'targets object');
deepEqual(targetsParser({ browsers: 'ie 11, chrome 56, ios_saf 12.2' }), new Map([
['chrome', '56'],
['ie', '11'],
['ios', '12.2-12.5'],
]), 'targets.browsers');
deepEqual(targetsParser({ esmodules: true }), new Map([
['android', '61'],
['bun', '0.1.1'],
['chrome', '61'],
['chrome-android', '61'],
['deno', '1.0'],
['edge', '16'],
['firefox', '60'],
['firefox-android', '60'],
['ios', '10.3'],
['node', '13.2'],
['opera', '48'],
['opera-android', '45'],
['quest', '4.0'],
['safari', '10.1'],
['samsung', '8.0'],
]), 'targets.esmodules');
deepEqual(targetsParser({ node: 'current' }), new Map([
['node', process.versions.node],
]), 'targets.node: current');
deepEqual(targetsParser({ node: '14.0' }), new Map([
['node', '14.0'],
]), 'targets.node: version');
deepEqual(targetsParser({
ie_mob: 11,
chromeandroid: 56,
and_ff: 60,
ios_saf: '12.2',
op_mob: 40,
op_mini: 1,
react: '0.70',
random: 42,
}), new Map([
['chrome-android', '56'],
['firefox-android', '60'],
['ie', '11'],
['ios', '12.2'],
['opera-android', '40'],
['react-native', '0.70'],
]), 'normalization');
deepEqual(targetsParser({
esmodules: true,
node: '12.0',
browsers: 'edge 13, safari 5.1, ios 13',
android: '4.2',
chrome: 77,
electron: 1,
ie: 8,
samsung: 4,
ie_mob: 11,
chromeandroid: 56,
and_ff: 65,
ios_saf: '12.2',
op_mob: 40,
'react-native': '0.70',
random: 42,
}), new Map([
['android', '4.2'],
['bun', '0.1.1'],
['chrome', '61'],
['chrome-android', '56'],
['deno', '1.0'],
['edge', '16'],
['electron', '1'],
['firefox', '60'],
['firefox-android', '60'],
['ie', '8'],
['ios', '10.3'],
['node', '12.0'],
['opera', '48'],
['opera-android', '40'],
['quest', '4.0'],
['react-native', '0.70'],
['safari', '10.1'],
['samsung', '4'],
]), 'mixed');
deepEqual(targetsParser({
esmodules: 'intersect',
browsers: 'ie 11, chrome 56',
chrome: 77,
}), new Map([
['chrome', '61'],
]), 'targets.esmodules: intersect, ie removed, chrome raised to esmodules minimum');
deepEqual(targetsParser({
esmodules: 'intersect',
browsers: 'chrome 56, firefox 50, safari 10',
}), new Map([
['chrome', '61'],
['firefox', '60'],
['safari', '10.1'],
]), 'targets.esmodules: intersect, versions raised to esmodules minimum');
deepEqual(targetsParser({
esmodules: 'intersect',
browsers: 'chrome 80, firefox 70',
}), new Map([
['chrome', '80'],
['firefox', '70'],
]), 'targets.esmodules: intersect, versions above esmodules minimum unchanged');
echo(chalk.green('targets parser tested'));
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/compat/browsers-runner.js
|
JavaScript
|
'use strict';
function createElement(name, props) {
var element = document.createElement(name);
if (props) for (var key in props) element[key] = props[key];
return element;
}
var table = document.getElementById('table');
var tests = window.tests;
var data = window.data;
var environments = [
'android',
'bun',
'chrome',
'chrome-android',
'deno',
'edge',
'electron',
'firefox',
'firefox-android',
'hermes',
'ie',
'ios',
'node',
'opera',
'opera-android',
'phantom',
'quest',
'react-native',
'rhino',
'safari',
'samsung'
];
var tableHeader = createElement('tr');
var columnHeaders = ['module', 'current'].concat(environments);
for (var i = 0; i < columnHeaders.length; i++) {
tableHeader.appendChild(createElement('th', {
innerHTML: columnHeaders[i].replace(/-/g, '<br />')
}));
}
table.appendChild(tableHeader);
for (var moduleName in tests) {
var test = tests[moduleName];
var result = true;
try {
if (typeof test == 'function') {
result = !!test();
} else {
for (var t = 0; t < test.length; t++) result = result && !!test[t].call(undefined);
}
} catch (error) {
result = false;
}
var row = createElement('tr');
var rowHeader = createElement('td', {
className: result
});
rowHeader.appendChild(createElement('a', {
href: "https://github.com/zloirock/core-js/blob/master/tests/compat/tests.js#:~:text='" + moduleName.replace(/-/g, '%2D') + "'",
target: '_blank',
innerHTML: moduleName
}));
row.appendChild(rowHeader);
row.appendChild(createElement('td', {
innerHTML: result ? 'not required' : 'required',
className: result + ' data'
}));
var moduleData = data[moduleName];
for (var j = 0; j < environments.length; j++) {
var environmentVersion = moduleData && moduleData[environments[j]];
row.appendChild(createElement('td', {
innerHTML: moduleData ? environmentVersion || 'no' : 'no data',
className: (moduleData ? !!environmentVersion : 'nodata') + ' data'
}));
}
table.appendChild(row);
}
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/compat/bun-runner.js
|
JavaScript
|
'use strict';
require('./tests');
require('./compat-data');
require('./common-runner');
/* global showResults -- safe */
// eslint-disable-next-line no-console -- output
showResults('bun', console.log);
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/compat/common-runner.js
|
JavaScript
|
'use strict';
/* eslint-disable unicorn/prefer-global-this -- required */
var GLOBAL = typeof global != 'undefined' ? global : Function('return this')();
var results = GLOBAL.results = Object.create(null);
var data = GLOBAL.data;
var tests = GLOBAL.tests;
for (var testName in tests) {
var test = tests[testName];
try {
results[testName] = typeof test == 'function' ? !!test() : test.every(function (subTest) {
return subTest();
});
} catch (error) {
results[testName] = false;
}
}
GLOBAL.showResults = function (engine, logger) {
var difference = false;
function logResults(showDifference) {
for (var name in results) {
if (data[name]) {
if (!!data[name][engine] === results[name]) {
if (showDifference) continue;
} else difference = true;
} else if (showDifference) continue;
var filled = name + ' | '.slice(name.length);
if (results[name]) logger('\u001B[32m' + filled + 'not required\u001B[0m');
else logger('\u001B[31m' + filled + 'required\u001B[0m');
}
}
logResults(false);
if (difference) {
logger('\n\u001B[36mchanges:\u001B[0m\n');
logResults(true);
} else logger('\n\u001B[36mno changes\u001B[0m');
};
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/compat/deno-runner.mjs
|
JavaScript
|
/* global Deno -- it's Deno */
import './tests.js';
import './compat-data.js';
import './common-runner.js';
if (Deno.args.includes('json')) {
console.log(JSON.stringify(globalThis.results, null, ' '));
} else globalThis.showResults('deno', console.log);
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/compat/hermes-adapter.mjs
|
JavaScript
|
const [HERMES_PATH] = argv._;
await $`${ HERMES_PATH } -w -commonjs ./tests/compat`;
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/compat/hermes-runner.js
|
JavaScript
|
'use strict';
require('./tests.js');
require('./compat-data.js');
require('./common-runner.js');
/* global showResults -- safe */
/* eslint-disable-next-line no-restricted-globals -- output */
showResults('hermes', print);
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/compat/index.html
|
HTML
|
<!DOCTYPE html>
<meta charset='UTF-8'>
<title>core-js-compat</title>
<style>
th,td {
padding: 0.25em;
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 0.75em;
}
th {
background-color: white;
color: black;
position: -webkit-sticky;
position: sticky;
top: 0;
z-index: 2;
}
td,a {
color: white;
text-decoration: none;
}
.true {
background-color: #00882c;
}
.false {
background-color: #e11;
}
.nodata {
background-color: grey;
}
.data {
text-align: center;
}
</style>
<table id='table'></table>
<script src='./compat-data.js'></script>
<script src='./tests.js'></script>
<script src='./browsers-runner.js'></script>
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/compat/node-runner.js
|
JavaScript
|
'use strict';
/* eslint-disable no-console -- output */
require('./tests');
require('./compat-data');
require('./common-runner');
if (process.argv.indexOf('json') !== -1) {
// eslint-disable-next-line es/no-json -- safe
console.log(JSON.stringify(global.results, null, ' '));
} else global.showResults('node', console.log);
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/compat/rhino-adapter.mjs
|
JavaScript
|
const [path] = argv._;
await $`java -jar ${ path } -require tests/compat/rhino-runner.js`;
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/compat/rhino-runner.js
|
JavaScript
|
'use strict';
require('./tests');
require('./compat-data');
require('./common-runner');
var GLOBAL = typeof global != 'undefined' ? global : Function('return this')();
/* eslint-disable-next-line no-restricted-globals -- output */
GLOBAL.showResults('rhino', print);
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/compat/tests.js
|
JavaScript
|
'use strict';
/* eslint-disable prefer-regex-literals, radix, unicorn/prefer-global-this -- required for testing */
/* eslint-disable regexp/no-empty-capturing-group, regexp/no-lazy-ends, regexp/no-useless-quantifier -- required for testing */
var GLOBAL = typeof global != 'undefined' ? global : Function('return this')();
var WHITESPACES = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u2000\u2001\u2002' +
'\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF';
var NOT_WHITESPACES = '\u200B\u0085\u180E';
var USERAGENT = GLOBAL.navigator && GLOBAL.navigator.userAgent || '';
var process = GLOBAL.process;
var Bun = GLOBAL.Bun;
var Deno = GLOBAL.Deno;
var versions = process && process.versions || Deno && Deno.version;
var v8 = versions && versions.v8;
var match, V8_VERSION;
if (v8) {
match = v8.split('.');
// in old Chrome, versions of V8 isn't V8 = Chrome / 10
// but their correct versions are not interesting for us
V8_VERSION = match[0] > 0 && match[0] < 4 ? 1 : +(match[0] + match[1]);
}
// BrowserFS NodeJS `process` polyfill incorrectly set `.v8` to `0.0`
// so check `userAgent` even if `.v8` exists, but 0
if (!V8_VERSION && USERAGENT) {
match = USERAGENT.match(/Edge\/(\d+)/);
if (!match || match[1] >= 74) {
match = USERAGENT.match(/Chrome\/(\d+)/);
if (match) V8_VERSION = +match[1];
}
}
var IS_BROWSER = typeof window == 'object' && typeof Deno != 'object';
var IS_BUN = typeof Bun == 'function' && Bun && typeof Bun.version == 'string';
var IS_DENO = typeof Deno == 'object' && Deno && typeof Deno.version == 'object';
// var IS_NODE = Object.prototype.toString.call(process) == '[object process]';
var WEBKIT_STRING_PAD_BUG = /Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(USERAGENT);
var DESCRIPTORS_SUPPORT = function () {
return Object.defineProperty({}, 'a', {
get: function () { return 7; }
}).a === 7;
};
var V8_PROTOTYPE_DEFINE_BUG = function () {
return Object.defineProperty(function () { /* empty */ }, 'prototype', {
value: 42,
writable: false
}).prototype === 42;
};
var PROMISES_SUPPORT = function () {
var promise = new Promise(function (resolve) { resolve(1); });
var empty = function () { /* empty */ };
var FakePromise = (promise.constructor = {})[Symbol.species] = function (exec) {
exec(empty, empty);
};
return promise.then(empty) instanceof FakePromise
&& V8_VERSION !== 66
&& (!(IS_BROWSER || IS_DENO) || typeof PromiseRejectionEvent == 'function');
};
var PROMISE_STATICS_ITERATION = function () {
var ITERATION_SUPPORT = false;
try {
var object = {};
object[Symbol.iterator] = function () {
return {
next: function () {
return { done: ITERATION_SUPPORT = true };
}
};
};
Promise.all(object).then(undefined, function () { /* empty */ });
} catch (error) { /* empty */ }
return ITERATION_SUPPORT;
};
var SYMBOLS_SUPPORT = function () {
return Object.getOwnPropertySymbols && String(Symbol('symbol detection')) && !(V8_VERSION && V8_VERSION < 41);
};
var SYMBOL_REGISTRY = [SYMBOLS_SUPPORT, function () {
return Symbol['for'] && Symbol.keyFor;
}];
var URL_AND_URL_SEARCH_PARAMS_SUPPORT = function () {
// eslint-disable-next-line unicorn/relative-url-style -- required for testing
var url = new URL('b?a=1&b=2&c=3', 'https://a');
var searchParams = url.searchParams;
var result = '';
url.pathname = 'c%20d';
searchParams.forEach(function (value, key) {
searchParams['delete']('b');
result += key + value;
});
return searchParams.sort
&& url.href === 'https://a/c%20d?a=1&c=3'
&& searchParams.get('c') === '3'
&& String(new URLSearchParams('?a=1')) === 'a=1'
&& searchParams[Symbol.iterator]
&& new URL('https://a@b').username === 'a'
&& new URLSearchParams(new URLSearchParams('a=b')).get('a') === 'b'
&& new URL('https://тест').host === 'xn--e1aybc'
&& new URL('https://a#б').hash === '#%D0%B1'
&& result === 'a1c3'
&& new URL('https://x', undefined).host === 'x';
};
// eslint-disable-next-line no-proto -- safe
var PROTOTYPE_SETTING_AVAILABLE = Object.setPrototypeOf || {}.__proto__;
var OBJECT_PROTOTYPE_ACCESSORS_SUPPORT = function () {
try {
Object.prototype.__defineSetter__.call(null, Math.random(), function () { /* empty */ });
} catch (error) {
return Object.prototype.__defineSetter__;
}
};
var SAFE_ITERATION_CLOSING_SUPPORT = function () {
var SAFE_CLOSING = false;
try {
var called = 0;
var iteratorWithReturn = {
next: function () {
return { done: !!called++ };
},
'return': function () {
SAFE_CLOSING = true;
}
};
iteratorWithReturn[Symbol.iterator] = function () {
return this;
};
Array.from(iteratorWithReturn, function () { throw new Error('close'); });
} catch (error) {
return SAFE_CLOSING;
}
};
var ARRAY_BUFFER_SUPPORT = function () {
return ArrayBuffer && DataView;
};
var TYPED_ARRAY_CONSTRUCTORS_LIST = {
Int8Array: 1,
Uint8Array: 1,
Uint8ClampedArray: 1,
Int16Array: 2,
Uint16Array: 2,
Int32Array: 4,
Uint32Array: 4,
Float32Array: 4,
Float64Array: 8
};
var ARRAY_BUFFER_VIEWS_SUPPORT = function () {
for (var constructor in TYPED_ARRAY_CONSTRUCTORS_LIST) if (!GLOBAL[constructor]) return false;
return ARRAY_BUFFER_SUPPORT();
};
var TYPED_ARRAY_CONSTRUCTORS_NOT_REQUIRES_WRAPPERS = function () {
try {
return !Int8Array(1);
} catch (error) { /* empty */ }
try {
return !new Int8Array(-1);
} catch (error) { /* empty */ }
new Int8Array();
new Int8Array(null);
new Int8Array(1.5);
var called = 0;
var iterable = {
next: function () {
return { done: !!called++, value: 1 };
}
};
iterable[Symbol.iterator] = function () {
return this;
};
return new Int8Array(iterable)[0] === 1
&& new Int8Array(new ArrayBuffer(2), 1, undefined).length === 1;
};
function NCG_SUPPORT() {
var re = RegExp('(?<a>b)');
return re.exec('b').groups.a === 'b' &&
'b'.replace(re, '$<a>c') === 'bc';
}
function createIsRegExpLogicTest(name) {
return function () {
var regexp = /./;
try {
'/./'[name](regexp);
} catch (error1) {
try {
regexp[Symbol.match] = false;
return '/./'[name](regexp);
} catch (error2) { /* empty */ }
} return false;
};
}
function createStringHTMLMethodTest(METHOD_NAME) {
return function () {
var test = ''[METHOD_NAME]('"');
return test === test.toLowerCase() && test.split('"').length <= 3;
};
}
function createStringTrimMethodTest(METHOD_NAME) {
return function () {
return !WHITESPACES[METHOD_NAME]()
&& NOT_WHITESPACES[METHOD_NAME]() === NOT_WHITESPACES
&& WHITESPACES[METHOD_NAME].name === METHOD_NAME;
};
}
function createSetLike(size) {
return {
size: size,
has: function () {
return false;
},
keys: function () {
return {
next: function () {
return { done: true };
}
};
}
};
}
function createSetLikeWithInfinitySize(size) {
return {
size: size,
has: function () {
return true;
},
keys: function () {
throw new Error('e');
}
};
}
function createSetMethodTest(METHOD_NAME, callback) {
return function () {
try {
new Set()[METHOD_NAME](createSetLike(0));
try {
// late spec change, early WebKit ~ Safari 17.0 beta implementation does not pass it
// https://github.com/tc39/proposal-set-methods/pull/88
new Set()[METHOD_NAME](createSetLike(-1));
return false;
} catch (error2) {
if (!callback) return true;
// early V8 implementation bug
// https://issues.chromium.org/issues/351332634
try {
new Set()[METHOD_NAME](createSetLikeWithInfinitySize(-Infinity));
return false;
} catch (error) {
var set = new Set([1, 2]);
return callback(set[METHOD_NAME](createSetLikeWithInfinitySize(Infinity)));
}
}
} catch (error) {
return false;
}
};
}
function createSetMethodTestShouldGetKeysBeforeCloning(METHOD_NAME) {
return function () {
var baseSet = new Set();
var setLike = {
size: 0,
has: function () { return true; },
keys: function () {
return Object.defineProperty({}, 'next', {
get: function () {
baseSet.clear();
baseSet.add(4);
return function () {
return { done: true };
};
}
});
}
};
var result = baseSet[METHOD_NAME](setLike);
return result.size === 1 && result.values().next().value === 4;
};
}
function NATIVE_RAW_JSON() {
var unsafeInt = '9007199254740993';
var raw = JSON.rawJSON(unsafeInt);
return JSON.isRawJSON(raw) && JSON.stringify(raw) === unsafeInt;
}
function IMMEDIATE() {
return setImmediate && clearImmediate && !(IS_BUN && (function () {
var version = Bun.version.split('.');
return version.length < 3 || version[0] === '0' && (version[1] < 3 || version[1] === '3' && version[2] === '0');
})());
}
function TIMERS() {
return !(/MSIE .\./.test(USERAGENT) || IS_BUN && (function () {
var version = Bun.version.split('.');
return version.length < 3 || version[0] === '0' && (version[1] < 3 || version[1] === '3' && version[2] === '0');
})());
}
// https://github.com/tc39/ecma262/pull/3467
function checkIteratorClosingOnEarlyError(METHOD_NAME, ExpectedError) {
return function () {
var CLOSED = false;
try {
Iterator.prototype[METHOD_NAME].call({
next: function () { return { done: true }; },
'return': function () { CLOSED = true; }
}, -1);
} catch (error) {
// https://bugs.webkit.org/show_bug.cgi?id=291195
if (!(error instanceof ExpectedError)) return;
}
return CLOSED;
};
}
// https://issues.chromium.org/issues/336839115
function iteratorHelperThrowsErrorOnInvalidIterator(methodName, argument) {
return function () {
if (typeof Iterator == 'function' && Iterator.prototype[methodName]) try {
Iterator.prototype[methodName].call({ next: null }, argument).next();
} catch (error) {
return true;
}
};
}
GLOBAL.tests = {
// TODO: Remove this module from `core-js@4` since it's split to modules listed below
'es.symbol': [SYMBOLS_SUPPORT, function () {
var symbol = Symbol('stringify detection');
return Object.getOwnPropertySymbols('qwe')
&& Symbol['for']
&& Symbol.keyFor
&& JSON.stringify([symbol]) === '[null]'
&& JSON.stringify({ a: symbol }) === '{}'
&& JSON.stringify(Object(symbol)) === '{}'
&& Symbol.prototype[Symbol.toPrimitive]
&& Symbol.prototype[Symbol.toStringTag];
}],
'es.symbol.constructor': SYMBOLS_SUPPORT,
'es.symbol.description': function () {
// eslint-disable-next-line symbol-description -- required for testing
return Symbol('description detection').description === 'description detection' && Symbol().description === undefined;
},
'es.symbol.async-dispose': function () {
var descriptor = Object.getOwnPropertyDescriptor(Symbol, 'asyncDispose');
return descriptor.value && !descriptor.enumerable && !descriptor.configurable && !descriptor.writable;
},
'es.symbol.async-iterator': function () {
return Symbol.asyncIterator;
},
'es.symbol.dispose': function () {
var descriptor = Object.getOwnPropertyDescriptor(Symbol, 'dispose');
return descriptor.value && !descriptor.enumerable && !descriptor.configurable && !descriptor.writable;
},
'es.symbol.for': SYMBOL_REGISTRY,
'es.symbol.has-instance': [SYMBOLS_SUPPORT, function () {
return Symbol.hasInstance;
}],
'es.symbol.is-concat-spreadable': [SYMBOLS_SUPPORT, function () {
return Symbol.isConcatSpreadable;
}],
'es.symbol.iterator': [SYMBOLS_SUPPORT, function () {
return Symbol.iterator;
}],
'es.symbol.key-for': SYMBOL_REGISTRY,
'es.symbol.match': [SYMBOLS_SUPPORT, function () {
return Symbol.match;
}],
'es.symbol.match-all': [SYMBOLS_SUPPORT, function () {
return Symbol.matchAll;
}],
'es.symbol.replace': [SYMBOLS_SUPPORT, function () {
return Symbol.replace;
}],
'es.symbol.search': [SYMBOLS_SUPPORT, function () {
return Symbol.search;
}],
'es.symbol.species': [SYMBOLS_SUPPORT, function () {
return Symbol.species;
}],
'es.symbol.split': [SYMBOLS_SUPPORT, function () {
return Symbol.split;
}],
'es.symbol.to-primitive': [SYMBOLS_SUPPORT, function () {
return Symbol.toPrimitive && Symbol.prototype[Symbol.toPrimitive];
}],
'es.symbol.to-string-tag': [SYMBOLS_SUPPORT, function () {
return Symbol.toStringTag && Symbol.prototype[Symbol.toStringTag];
}],
'es.symbol.unscopables': [SYMBOLS_SUPPORT, function () {
return Symbol.unscopables;
}],
'es.error.cause': function () {
return new Error('e', { cause: 7 }).cause === 7
&& !('cause' in Error.prototype);
},
'es.error.is-error': function () {
return PROTOTYPE_SETTING_AVAILABLE &&
(typeof DOMException != 'function' || Error.isError(new DOMException('DOMException'))) &&
Error.isError(new Error('Error', { cause: function () { /* empty */ } })) &&
!Error.isError(Object.create(Error.prototype));
},
'es.error.to-string': function () {
if (DESCRIPTORS_SUPPORT) {
// Chrome 32- incorrectly call accessor
var object = Object.create(Object.defineProperty({}, 'name', { get: function () {
return this === object;
} }));
if (Error.prototype.toString.call(object) !== 'true') return false;
}
// FF10- does not properly handle non-strings
return Error.prototype.toString.call({ message: 1, name: 2 }) === '2: 1'
// IE8 does not properly handle defaults
&& Error.prototype.toString.call({}) === 'Error';
},
'es.aggregate-error.constructor': function () {
return typeof AggregateError == 'function';
},
'es.aggregate-error.cause': function () {
return new AggregateError([1], 'e', { cause: 7 }).cause === 7
&& !('cause' in AggregateError.prototype);
},
'es.suppressed-error.constructor': function () {
return typeof SuppressedError == 'function'
&& SuppressedError.length === 3
&& new SuppressedError(1, 2, 3, { cause: 4 }).cause !== 4;
},
'es.array.at': function () {
return [].at;
},
'es.array.concat': function () {
var array1 = [];
array1[Symbol.isConcatSpreadable] = false;
var array2 = [];
var constructor = array2.constructor = {};
constructor[Symbol.species] = function () {
return { foo: 1 };
};
// eslint-disable-next-line es/no-nonstandard-array-prototype-properties -- @@species
return array1.concat()[0] === array1 && array2.concat().foo === 1;
},
'es.array.copy-within': function () {
return Array.prototype.copyWithin && Array.prototype[Symbol.unscopables].copyWithin;
},
'es.array.every': function () {
try {
Array.prototype.every.call(null, function () { /* empty */ });
return false;
} catch (error) { /* empty */ }
return Array.prototype.every;
},
'es.array.fill': function () {
return Array.prototype.fill && Array.prototype[Symbol.unscopables].fill;
},
'es.array.filter': function () {
var array = [];
var constructor = array.constructor = {};
constructor[Symbol.species] = function () {
return { foo: 1 };
};
// eslint-disable-next-line es/no-nonstandard-array-prototype-properties -- @@species
return array.filter(Boolean).foo === 1;
},
'es.array.find': function () {
var SKIPS_HOLES = true;
Array(1).find(function () { return SKIPS_HOLES = false; });
return !SKIPS_HOLES && Array.prototype[Symbol.unscopables].find;
},
'es.array.find-index': function () {
var SKIPS_HOLES = true;
Array(1).findIndex(function () { return SKIPS_HOLES = false; });
return !SKIPS_HOLES && Array.prototype[Symbol.unscopables].findIndex;
},
'es.array.find-last': function () {
return [].findLast;
},
'es.array.find-last-index': function () {
return [].findLastIndex;
},
'es.array.flat': function () {
return Array.prototype.flat;
},
'es.array.flat-map': function () {
return Array.prototype.flatMap;
},
'es.array.for-each': function () {
try {
Array.prototype.forEach.call(null, function () { /* empty */ });
return false;
} catch (error) { /* empty */ }
return Array.prototype.forEach;
},
'es.array.from': SAFE_ITERATION_CLOSING_SUPPORT,
'es.array.includes': function () {
return Array(1).includes()
&& Array.prototype[Symbol.unscopables].includes;
},
'es.array.index-of': function () {
try {
[].indexOf.call(null);
} catch (error) {
return 1 / [1].indexOf(1, -0) > 0;
}
},
'es.array.is-array': function () {
return Array.isArray;
},
'es.array.iterator': [SYMBOLS_SUPPORT, function () {
return [][Symbol.iterator] === [].values
&& [][Symbol.iterator].name === 'values'
&& [].entries()[Symbol.toStringTag] === 'Array Iterator'
&& [].keys().next()
&& [][Symbol.unscopables].keys
&& [][Symbol.unscopables].values
&& [][Symbol.unscopables].entries;
}],
'es.array.join': function () {
try {
if (!Object.prototype.propertyIsEnumerable.call(Object('z'), 0)) return false;
} catch (error) {
return false;
}
try {
Array.prototype.join.call(null, '');
return false;
} catch (error) { /* empty */ }
return true;
},
'es.array.last-index-of': function () {
try {
[].lastIndexOf.call(null);
} catch (error) {
return 1 / [1].lastIndexOf(1, -0) > 0;
}
},
'es.array.map': function () {
var array = [];
var constructor = array.constructor = {};
constructor[Symbol.species] = function () {
return { foo: 1 };
};
// eslint-disable-next-line es/no-nonstandard-array-prototype-properties -- @@species
return array.map(function () { return true; }).foo === 1;
},
'es.array.of': function () {
function F() { /* empty */ }
return Array.of.call(F) instanceof F;
},
'es.array.push': function () {
if ([].push.call({ length: 0x100000000 }, 1) !== 4294967297) return false;
try {
Object.defineProperty([], 'length', { writable: false }).push();
} catch (error) {
return error instanceof TypeError;
}
},
'es.array.reduce': function () {
try {
Array.prototype.reduce.call(null, function () { /* empty */ }, 1);
} catch (error) {
return Array.prototype.reduce;
}
},
'es.array.reduce-right': function () {
try {
Array.prototype.reduceRight.call(null, function () { /* empty */ }, 1);
} catch (error) {
return Array.prototype.reduceRight;
}
},
'es.array.reverse': function () {
var test = [1, 2];
return String(test) !== String(test.reverse());
},
'es.array.slice': function () {
var array = [];
var constructor = array.constructor = {};
constructor[Symbol.species] = function () {
return { foo: 1 };
};
// eslint-disable-next-line es/no-nonstandard-array-prototype-properties -- @@species
return array.slice().foo === 1;
},
'es.array.some': function () {
try {
Array.prototype.some.call(null, function () { /* empty */ });
} catch (error) {
return Array.prototype.some;
}
},
'es.array.sort': function () {
try {
Array.prototype.sort.call(null);
} catch (error1) {
try {
[1, 2, 3].sort(null);
} catch (error2) {
[1, 2, 3].sort(undefined);
// stable sort
var array = [];
var result = '';
var code, chr, value, index;
// generate an array with more 512 elements (Chakra and old V8 fails only in this case)
for (code = 65; code < 76; code++) {
chr = String.fromCharCode(code);
switch (code) {
case 66: case 69: case 70: case 72: value = 3; break;
case 68: case 71: value = 4; break;
default: value = 2;
}
for (index = 0; index < 47; index++) {
array.push({ k: chr + index, v: value });
}
}
array.sort(function (a, b) { return b.v - a.v; });
for (index = 0; index < array.length; index++) {
chr = array[index].k.charAt(0);
if (result.charAt(result.length - 1) !== chr) result += chr;
}
return result === 'DGBEFHACIJK';
}
}
},
'es.array.species': [SYMBOLS_SUPPORT, function () {
return Array[Symbol.species];
}],
'es.array.splice': function () {
var array = [];
var constructor = array.constructor = {};
constructor[Symbol.species] = function () {
return { foo: 1 };
};
// eslint-disable-next-line es/no-nonstandard-array-prototype-properties -- @@species
return array.splice().foo === 1;
},
'es.array.to-reversed': function () {
return [].toReversed;
},
'es.array.to-sorted': function () {
return [].toSorted;
},
'es.array.to-spliced': function () {
return [].toSpliced;
},
'es.array.unscopables.flat': function () {
return Array.prototype[Symbol.unscopables].flat;
},
'es.array.unscopables.flat-map': function () {
return Array.prototype[Symbol.unscopables].flatMap;
},
'es.array.unshift': function () {
if ([].unshift(0) !== 1) return false;
try {
Object.defineProperty([], 'length', { writable: false }).unshift();
} catch (error) {
return error instanceof TypeError;
}
},
'es.array.with': function () {
// Incorrect exception thrown when index coercion fails in Firefox
try {
[]['with']({ valueOf: function () { throw 4; } }, null);
} catch (error) {
return error === 4;
}
},
'es.array-buffer.constructor': [ARRAY_BUFFER_SUPPORT, function () {
try {
return !ArrayBuffer(1);
} catch (error) { /* empty */ }
try {
return !new ArrayBuffer(-1);
} catch (error) { /* empty */ }
new ArrayBuffer();
new ArrayBuffer(1.5);
new ArrayBuffer(NaN);
return ArrayBuffer.length === 1 && ArrayBuffer.name === 'ArrayBuffer';
}],
'es.array-buffer.is-view': [ARRAY_BUFFER_VIEWS_SUPPORT, function () {
return ArrayBuffer.isView;
}],
'es.array-buffer.slice': [ARRAY_BUFFER_SUPPORT, function () {
return new ArrayBuffer(2).slice(1, undefined).byteLength;
}],
'es.array-buffer.detached': function () {
return 'detached' in ArrayBuffer.prototype;
},
'es.array-buffer.transfer': function () {
return ArrayBuffer.prototype.transfer;
},
'es.array-buffer.transfer-to-fixed-length': function () {
return ArrayBuffer.prototype.transferToFixedLength;
},
'es.data-view.constructor': ARRAY_BUFFER_SUPPORT,
'es.data-view.get-float16': [ARRAY_BUFFER_SUPPORT, function () {
return DataView.prototype.getFloat16;
}],
'es.data-view.set-float16': [ARRAY_BUFFER_SUPPORT, function () {
return DataView.prototype.setFloat16;
}],
'es.date.get-year': function () {
return new Date(16e11).getYear() === 120;
},
// TODO: Remove from `core-js@4`
'es.date.now': function () {
return Date.now;
},
'es.date.set-year': function () {
return Date.prototype.setYear;
},
'es.date.to-gmt-string': function () {
return Date.prototype.toGMTString;
},
'es.date.to-iso-string': function () {
try {
new Date(NaN).toISOString();
} catch (error) {
return new Date(-5e13 - 1).toISOString() === '0385-07-25T07:06:39.999Z';
}
},
'es.date.to-json': function () {
return new Date(NaN).toJSON() === null
&& Date.prototype.toJSON.call({ toISOString: function () { return 1; } }) === 1;
},
'es.date.to-primitive': [SYMBOLS_SUPPORT, function () {
return Date.prototype[Symbol.toPrimitive];
}],
// TODO: Remove from `core-js@4`
'es.date.to-string': function () {
return new Date(NaN).toString() === 'Invalid Date';
},
'es.disposable-stack.constructor': function () {
return typeof DisposableStack == 'function';
},
'es.escape': function () {
return escape;
},
'es.function.bind': function () {
var test = function () { /* empty */ }.bind();
// eslint-disable-next-line no-prototype-builtins -- safe
return typeof test == 'function' && !test.hasOwnProperty('prototype');
},
'es.function.has-instance': [SYMBOLS_SUPPORT, function () {
return Symbol.hasInstance in Function.prototype;
}],
'es.function.name': function () {
return 'name' in Function.prototype;
},
'es.global-this': function () {
return globalThis;
},
'es.iterator.constructor': function () {
try {
Iterator({});
} catch (error) {
return typeof Iterator == 'function'
&& Iterator.prototype === Object.getPrototypeOf(Object.getPrototypeOf([].values()));
}
},
'es.iterator.concat': function () {
return Iterator.concat;
},
'es.iterator.dispose': function () {
return [].keys()[Symbol.dispose];
},
'es.iterator.drop': [
iteratorHelperThrowsErrorOnInvalidIterator('drop', 0),
checkIteratorClosingOnEarlyError('drop', RangeError)
],
'es.iterator.every': checkIteratorClosingOnEarlyError('every', TypeError),
'es.iterator.filter': [
iteratorHelperThrowsErrorOnInvalidIterator('filter', function () { /* empty */ }),
checkIteratorClosingOnEarlyError('filter', TypeError)
],
'es.iterator.find': checkIteratorClosingOnEarlyError('find', TypeError),
'es.iterator.flat-map': [
iteratorHelperThrowsErrorOnInvalidIterator('flatMap', function () { /* empty */ }),
checkIteratorClosingOnEarlyError('flatMap', TypeError),
// Should not throw an error for an iterator without `return` method. Fixed in Safari 26.2
// https://bugs.webkit.org/show_bug.cgi?id=297532
function () {
try {
var it = new Map([[4, 5]]).entries().flatMap(function (v) { return v; });
it.next();
it['return']();
return true;
} catch (error) { /* empty */ }
}
],
'es.iterator.for-each': checkIteratorClosingOnEarlyError('forEach', TypeError),
'es.iterator.from': function () {
Iterator.from({ 'return': null })['return']();
return true;
},
'es.iterator.map': [
iteratorHelperThrowsErrorOnInvalidIterator('map', function () { /* empty */ }),
checkIteratorClosingOnEarlyError('map', TypeError)
],
'es.iterator.reduce': [checkIteratorClosingOnEarlyError('reduce', TypeError), function () {
// fails on undefined initial parameter
// https://bugs.webkit.org/show_bug.cgi?id=291651
[].keys().reduce(function () { /* empty */ }, undefined);
return true;
}],
'es.iterator.some': checkIteratorClosingOnEarlyError('some', TypeError),
'es.iterator.take': checkIteratorClosingOnEarlyError('take', RangeError),
'es.iterator.to-array': function () {
return Iterator.prototype.toArray;
},
'es.json.is-raw-json': NATIVE_RAW_JSON,
'es.json.parse': function () {
var unsafeInt = '9007199254740993';
var source;
JSON.parse(unsafeInt, function (key, value, context) {
source = context.source;
});
return source === unsafeInt;
},
'es.json.raw-json': NATIVE_RAW_JSON,
'es.json.stringify': [NATIVE_RAW_JSON, SYMBOLS_SUPPORT, function () {
var symbol = Symbol('stringify detection');
return JSON.stringify([symbol]) === '[null]'
&& JSON.stringify({ a: symbol }) === '{}'
&& JSON.stringify(Object(symbol)) === '{}'
&& JSON.stringify('\uDF06\uD834') === '"\\udf06\\ud834"'
&& JSON.stringify('\uDEAD') === '"\\udead"';
}],
'es.json.to-string-tag': [SYMBOLS_SUPPORT, function () {
return JSON[Symbol.toStringTag];
}],
'es.map.constructor': [SAFE_ITERATION_CLOSING_SUPPORT, function () {
var called = 0;
var iterable = {
next: function () {
return { done: !!called++, value: [1, 2] };
}
};
iterable[Symbol.iterator] = function () {
return this;
};
var map = new Map(iterable);
return map.forEach
&& map[Symbol.iterator]().next()
&& map.get(1) === 2
&& map.set(-0, 3) === map
&& map.has(0)
&& map[Symbol.toStringTag];
}],
'es.map.group-by': function () {
// https://bugs.webkit.org/show_bug.cgi?id=271524
return Map.groupBy('ab', function (it) {
return it;
}).get('a').length === 1;
},
'es.map.get-or-insert': function () {
return Map.prototype.getOrInsert;
},
'es.map.get-or-insert-computed': function () {
return Map.prototype.getOrInsertComputed;
},
'es.math.acosh': function () {
// V8 bug: https://code.google.com/p/v8/issues/detail?id=3509
return Math.floor(Math.acosh(Number.MAX_VALUE)) === 710
// Tor Browser bug: Math.acosh(Infinity) -> NaN
// eslint-disable-next-line math/no-static-infinity-calculations -- testing
&& Math.acosh(Infinity) === Infinity;
},
'es.math.asinh': function () {
// eslint-disable-next-line math/no-static-infinity-calculations -- testing
return 1 / Math.asinh(0) > 0;
},
'es.math.atanh': function () {
// eslint-disable-next-line math/no-static-infinity-calculations -- testing
return 1 / Math.atanh(-0) < 0;
},
'es.math.cbrt': function () {
return Math.cbrt;
},
'es.math.clz32': function () {
return Math.clz32;
},
'es.math.cosh': function () {
return Math.cosh(710) !== Infinity;
},
'es.math.expm1': function () {
// Old FF bug
// eslint-disable-next-line no-loss-of-precision -- required for old engines
return Math.expm1(10) <= 22025.465794806719 && Math.expm1(10) >= 22025.4657948067165168
// Tor Browser bug
&& Math.expm1(-2e-17) === -2e-17;
},
'es.math.fround': function () {
return Math.fround;
},
'es.math.f16round': function () {
return Math.f16round;
},
'es.math.hypot': function () {
// eslint-disable-next-line math/no-static-infinity-calculations -- testing
return Math.hypot && Math.hypot(Infinity, NaN) === Infinity;
},
'es.math.imul': function () {
return Math.imul(0xFFFFFFFF, 5) === -5 && Math.imul.length === 2;
},
'es.math.log10': function () {
return Math.log10;
},
'es.math.log1p': function () {
return Math.log1p;
},
'es.math.log2': function () {
return Math.log2;
},
'es.math.sign': function () {
return Math.sign;
},
'es.math.sinh': function () {
return Math.sinh(-2e-17) === -2e-17;
},
'es.math.sum-precise': function () {
return Math.sumPrecise;
},
'es.math.tanh': function () {
return Math.tanh;
},
'es.math.to-string-tag': function () {
return Math[Symbol.toStringTag];
},
'es.math.trunc': function () {
return Math.trunc;
},
'es.number.constructor': function () {
// eslint-disable-next-line math/no-static-nan-calculations -- feature detection
return Number(' 0o1') && Number('0b1') && !Number('+0x1');
},
'es.number.epsilon': function () {
return Number.EPSILON;
},
'es.number.is-finite': function () {
return Number.isFinite;
},
'es.number.is-integer': function () {
return Number.isInteger;
},
'es.number.is-nan': function () {
return Number.isNaN;
},
'es.number.is-safe-integer': function () {
return Number.isSafeInteger;
},
'es.number.max-safe-integer': function () {
return Number.MAX_SAFE_INTEGER;
},
'es.number.min-safe-integer': function () {
return Number.MIN_SAFE_INTEGER;
},
'es.number.parse-float': function () {
try {
parseFloat(Object(Symbol.iterator));
} catch (error) {
return Number.parseFloat === parseFloat
&& 1 / parseFloat(WHITESPACES + '-0') === -Infinity;
}
},
'es.number.parse-int': function () {
try {
parseInt(Object(Symbol.iterator));
} catch (error) {
return Number.parseInt === parseInt
&& parseInt(WHITESPACES + '08') === 8
&& parseInt(WHITESPACES + '0x16') === 22;
}
},
'es.number.to-exponential': function () {
try {
1.0.toExponential(Infinity);
} catch (error) {
try {
1.0.toExponential(-Infinity);
} catch (error2) {
Infinity.toExponential(Infinity);
NaN.toExponential(Infinity);
return (-6.9e-11).toExponential(4) === '-6.9000e-11'
&& 1.255.toExponential(2) === '1.25e+0';
// && 25.0.toExponential(0) === '3e+1';
}
}
},
'es.number.to-fixed': function () {
try {
Number.prototype.toFixed.call({});
} catch (error) {
return 0.00008.toFixed(3) === '0.000'
&& 0.9.toFixed(0) === '1'
&& 1.255.toFixed(2) === '1.25'
&& 1000000000000000128.0.toFixed(0) === '1000000000000000128';
}
},
'es.number.to-precision': function () {
try {
Number.prototype.toPrecision.call({});
} catch (error) {
return 1.0.toPrecision(undefined) === '1';
}
},
'es.object.assign': function () {
if (DESCRIPTORS_SUPPORT && Object.assign({ b: 1 }, Object.assign(Object.defineProperty({}, 'a', {
enumerable: true,
get: function () {
Object.defineProperty(this, 'b', {
value: 3,
enumerable: false
});
}
}), { b: 2 })).b !== 1) return false;
var A = {};
var B = {};
var symbol = Symbol('assign detection');
var alphabet = 'abcdefghijklmnopqrst';
A[symbol] = 7;
alphabet.split('').forEach(function (chr) { B[chr] = chr; });
return Object.assign({}, A)[symbol] === 7 && Object.keys(Object.assign({}, B)).join('') === alphabet;
},
// TODO: Remove from `core-js@4`
'es.object.create': function () {
return Object.create;
},
'es.object.define-getter': OBJECT_PROTOTYPE_ACCESSORS_SUPPORT,
'es.object.define-properties': [DESCRIPTORS_SUPPORT, V8_PROTOTYPE_DEFINE_BUG, function () {
return Object.defineProperties;
}],
'es.object.define-property': [DESCRIPTORS_SUPPORT, V8_PROTOTYPE_DEFINE_BUG],
'es.object.define-setter': OBJECT_PROTOTYPE_ACCESSORS_SUPPORT,
'es.object.entries': function () {
return Object.entries;
},
'es.object.freeze': function () {
return Object.freeze(true);
},
'es.object.from-entries': function () {
return Object.fromEntries;
},
'es.object.get-own-property-descriptor': [DESCRIPTORS_SUPPORT, function () {
return Object.getOwnPropertyDescriptor('qwe', '0');
}],
'es.object.get-own-property-descriptors': function () {
return Object.getOwnPropertyDescriptors;
},
'es.object.get-own-property-names': function () {
return Object.getOwnPropertyNames('qwe');
},
'es.object.get-own-property-symbols': [SYMBOLS_SUPPORT, function () {
return Object.getOwnPropertySymbols('qwe');
}],
'es.object.get-prototype-of': function () {
return Object.getPrototypeOf('qwe');
},
'es.object.group-by': function () {
// https://bugs.webkit.org/show_bug.cgi?id=271524
return Object.groupBy('ab', function (it) {
return it;
}).a.length === 1;
},
'es.object.has-own': function () {
return Object.hasOwn;
},
'es.object.is': function () {
return Object.is;
},
'es.object.is-extensible': function () {
return !Object.isExtensible('qwe');
},
'es.object.is-frozen': function () {
return Object.isFrozen('qwe');
},
'es.object.is-sealed': function () {
return Object.isSealed('qwe');
},
'es.object.keys': function () {
return Object.keys('qwe');
},
'es.object.lookup-getter': OBJECT_PROTOTYPE_ACCESSORS_SUPPORT,
'es.object.lookup-setter': OBJECT_PROTOTYPE_ACCESSORS_SUPPORT,
'es.object.prevent-extensions': function () {
return Object.preventExtensions(true);
},
'es.object.proto': function () {
return '__proto__' in Object.prototype;
},
'es.object.seal': function () {
return Object.seal(true);
},
'es.object.set-prototype-of': function () {
return Object.setPrototypeOf;
},
'es.object.to-string': [SYMBOLS_SUPPORT, function () {
var O = {};
O[Symbol.toStringTag] = 'foo';
return String(O) === '[object foo]';
}],
'es.object.values': function () {
return Object.values;
},
'es.parse-float': function () {
try {
parseFloat(Object(Symbol.iterator));
} catch (error) {
return 1 / parseFloat(WHITESPACES + '-0') === -Infinity;
}
},
'es.parse-int': function () {
try {
parseInt(Object(Symbol.iterator));
} catch (error) {
return parseInt(WHITESPACES + '08') === 8
&& parseInt(WHITESPACES + '0x16') === 22;
}
},
// TODO: Remove this module from `core-js@4` since it's split to modules listed below
'es.promise': PROMISES_SUPPORT,
'es.promise.constructor': PROMISES_SUPPORT,
'es.promise.all': [PROMISES_SUPPORT, SAFE_ITERATION_CLOSING_SUPPORT, PROMISE_STATICS_ITERATION, function () {
return Promise.all;
}],
'es.promise.all-settled': [PROMISES_SUPPORT, SAFE_ITERATION_CLOSING_SUPPORT, PROMISE_STATICS_ITERATION, function () {
return Promise.allSettled;
}],
'es.promise.any': [PROMISES_SUPPORT, SAFE_ITERATION_CLOSING_SUPPORT, PROMISE_STATICS_ITERATION, function () {
return Promise.any;
}],
'es.promise.catch': PROMISES_SUPPORT,
'es.promise.finally': [PROMISES_SUPPORT, function () {
// eslint-disable-next-line unicorn/no-thenable -- required for testing
return Promise.prototype['finally'].call({ then: function () { return this; } }, function () { /* empty */ });
}],
'es.promise.race': [PROMISES_SUPPORT, SAFE_ITERATION_CLOSING_SUPPORT, PROMISE_STATICS_ITERATION, function () {
return Promise.race;
}],
'es.promise.reject': PROMISES_SUPPORT,
'es.promise.resolve': PROMISES_SUPPORT,
'es.promise.try': [PROMISES_SUPPORT, function () {
var ACCEPT_ARGUMENTS = false;
Promise['try'](function (argument) {
ACCEPT_ARGUMENTS = argument === 8;
}, 8);
return ACCEPT_ARGUMENTS;
}],
'es.promise.with-resolvers': [PROMISES_SUPPORT, function () {
return Promise.withResolvers;
}],
'es.array.from-async': function () {
// https://bugs.webkit.org/show_bug.cgi?id=271703
var counter = 0;
Array.fromAsync.call(function () {
counter++;
return [];
}, { length: 0 });
return counter === 1;
},
'es.async-disposable-stack.constructor': function () {
// https://github.com/tc39/proposal-explicit-resource-management/issues/256
// can't be detected synchronously
if (V8_VERSION && V8_VERSION < 136) return;
return typeof AsyncDisposableStack == 'function';
},
'es.async-iterator.async-dispose': function () {
return AsyncIterator.prototype[Symbol.asyncDispose];
},
'es.reflect.apply': function () {
try {
return Reflect.apply(function () {
return false;
});
} catch (error) {
return Reflect.apply(function () {
return true;
}, null, []);
}
},
'es.reflect.construct': function () {
try {
return !Reflect.construct(function () { /* empty */ });
} catch (error) { /* empty */ }
function F() { /* empty */ }
return Reflect.construct(function () { /* empty */ }, [], F) instanceof F;
},
'es.reflect.define-property': function () {
return !Reflect.defineProperty(Object.defineProperty({}, 1, { value: 1 }), 1, { value: 2 });
},
'es.reflect.delete-property': function () {
return Reflect.deleteProperty;
},
'es.reflect.get': function () {
return Reflect.get;
},
'es.reflect.get-own-property-descriptor': function () {
return Reflect.getOwnPropertyDescriptor;
},
'es.reflect.get-prototype-of': function () {
return Reflect.getPrototypeOf;
},
'es.reflect.has': function () {
return Reflect.has;
},
'es.reflect.is-extensible': function () {
return Reflect.isExtensible;
},
'es.reflect.own-keys': function () {
return Reflect.ownKeys;
},
'es.reflect.prevent-extensions': function () {
return Reflect.preventExtensions;
},
'es.reflect.set': function () {
var object = Object.defineProperty({}, 'a', { configurable: true });
return Reflect.set(Object.getPrototypeOf(object), 'a', 1, object) === false;
},
'es.reflect.set-prototype-of': function () {
return Reflect.setPrototypeOf;
},
'es.reflect.to-string-tag': function () {
return Reflect[Symbol.toStringTag];
},
'es.regexp.constructor': [NCG_SUPPORT, function () {
var re1 = /a/g;
var re2 = /a/g;
re2[Symbol.match] = false;
// eslint-disable-next-line no-constant-binary-expression -- required for testing
return new RegExp(re1) !== re1
&& RegExp(re1) === re1
&& RegExp(re2) !== re2
&& String(RegExp(re1, 'i')) === '/a/i'
&& new RegExp('a', 'y') // just check that it doesn't throw
&& RegExp('.', 's').exec('\n')
&& RegExp[Symbol.species];
}],
'es.regexp.escape': function () {
return RegExp.escape('ab') === '\\x61b';
},
'es.regexp.dot-all': function () {
return RegExp('.', 's').dotAll;
},
'es.regexp.exec': [NCG_SUPPORT, function () {
var re1 = /a/;
var re2 = /b*/g;
var reSticky = new RegExp('a', 'y');
var reStickyAnchored = new RegExp('^a', 'y');
re1.exec('a');
re2.exec('a');
return re1.lastIndex === 0 && re2.lastIndex === 0
// eslint-disable-next-line regexp/no-empty-group -- required for testing
&& /()??/.exec('')[1] === undefined
&& reSticky.exec('abc')[0] === 'a'
&& reSticky.exec('abc') === null
&& (reSticky.lastIndex = 1)
&& reSticky.exec('bac')[0] === 'a'
&& (reStickyAnchored.lastIndex = 2)
&& reStickyAnchored.exec('cba') === null
&& RegExp('.', 's').exec('\n');
}],
'es.regexp.flags': function () {
var INDICES_SUPPORT = true;
try {
RegExp('.', 'd');
} catch (error) {
INDICES_SUPPORT = false;
}
var O = {};
// modern V8 bug
var calls = '';
var expected = INDICES_SUPPORT ? 'dgimsy' : 'gimsy';
var addGetter = function (key, chr) {
Object.defineProperty(O, key, { get: function () {
calls += chr;
return true;
} });
};
var pairs = {
dotAll: 's',
global: 'g',
ignoreCase: 'i',
multiline: 'm',
sticky: 'y'
};
if (INDICES_SUPPORT) pairs.hasIndices = 'd';
for (var key in pairs) addGetter(key, pairs[key]);
var result = Object.getOwnPropertyDescriptor(RegExp.prototype, 'flags').get.call(O);
return result === expected && calls === expected;
},
'es.regexp.sticky': function () {
return new RegExp('a', 'y').sticky === true;
},
'es.regexp.test': function () {
var execCalled = false;
var re = /[ac]/;
re.exec = function () {
execCalled = true;
return /./.exec.apply(this, arguments);
};
return re.test('abc') === true && execCalled;
},
'es.regexp.to-string': function () {
return RegExp.prototype.toString.call({ source: 'a', flags: 'b' }) === '/a/b'
&& RegExp.prototype.toString.name === 'toString';
},
'es.set.constructor': [SAFE_ITERATION_CLOSING_SUPPORT, function () {
var called = 0;
var iterable = {
next: function () {
return { done: !!called++, value: 1 };
}
};
iterable[Symbol.iterator] = function () {
return this;
};
var set = new Set(iterable);
return set.forEach
&& set[Symbol.iterator]().next()
&& set.has(1)
&& set.add(-0) === set
&& set.has(0)
&& set[Symbol.toStringTag];
}],
'es.set.difference.v2': [createSetMethodTest('difference', function (result) {
return result.size === 0;
}), function () {
// A WebKit bug occurs when `this` is updated while Set.prototype.difference is being executed
// https://bugs.webkit.org/show_bug.cgi?id=288595
var setLike = {
size: 1,
has: function () { return true; },
keys: function () {
var index = 0;
return {
next: function () {
var done = index++ > 1;
if (baseSet.has(1)) baseSet.clear();
return { done: done, value: 2 };
}
};
}
};
var baseSet = new Set([1, 2, 3, 4]);
return baseSet.difference(setLike).size === 3;
}],
'es.set.intersection.v2': [createSetMethodTest('intersection', function (result) {
return result.size === 2 && result.has(1) && result.has(2);
}), function () {
return String(Array.from(new Set([1, 2, 3]).intersection(new Set([3, 2])))) === '3,2';
}],
'es.set.is-disjoint-from.v2': createSetMethodTest('isDisjointFrom', function (result) {
return !result;
}),
'es.set.is-subset-of.v2': createSetMethodTest('isSubsetOf', function (result) {
return result;
}),
'es.set.is-superset-of.v2': createSetMethodTest('isSupersetOf', function (result) {
return !result;
}),
'es.set.symmetric-difference.v2': [
createSetMethodTest('symmetricDifference'),
createSetMethodTestShouldGetKeysBeforeCloning('symmetricDifference')
],
'es.set.union.v2': [
createSetMethodTest('union'),
createSetMethodTestShouldGetKeysBeforeCloning('union')
],
'es.string.at-alternative': function () {
return '𠮷'.at(-2) === '\uD842';
},
'es.string.code-point-at': function () {
return String.prototype.codePointAt;
},
'es.string.ends-with': createIsRegExpLogicTest('endsWith'),
'es.string.from-code-point': function () {
return String.fromCodePoint;
},
'es.string.includes': createIsRegExpLogicTest('includes'),
'es.string.is-well-formed': function () {
return String.prototype.isWellFormed;
},
'es.string.iterator': [SYMBOLS_SUPPORT, function () {
return ''[Symbol.iterator];
}],
'es.string.match': function () {
var O = {};
O[Symbol.match] = function () { return 7; };
var execCalled = false;
var re = /a/;
re.exec = function () {
execCalled = true;
return null;
};
re[Symbol.match]('');
// eslint-disable-next-line regexp/prefer-regexp-exec -- required for testing
return ''.match(O) === 7 && execCalled;
},
'es.string.match-all': function () {
try {
// eslint-disable-next-line regexp/no-missing-g-flag -- required for testing
'a'.matchAll(/./);
} catch (error) {
return 'a'.matchAll(/./g);
}
},
'es.string.pad-end': function () {
return String.prototype.padEnd && !WEBKIT_STRING_PAD_BUG;
},
'es.string.pad-start': function () {
return String.prototype.padStart && !WEBKIT_STRING_PAD_BUG;
},
'es.string.raw': function () {
return String.raw;
},
'es.string.repeat': function () {
return String.prototype.repeat;
},
'es.string.replace': function () {
var O = {};
O[Symbol.replace] = function () { return 7; };
var execCalled = false;
var re = /a/;
re.exec = function () {
execCalled = true;
return null;
};
re[Symbol.replace]('');
var re2 = /./;
re2.exec = function () {
var result = [];
result.groups = { a: '7' };
return result;
};
return ''.replace(O) === 7
&& execCalled
// eslint-disable-next-line regexp/no-useless-dollar-replacements -- false positive
&& ''.replace(re2, '$<a>') === '7'
// eslint-disable-next-line regexp/prefer-escape-replacement-dollar-char -- required for testing
&& 'a'.replace(/./, '$0') === '$0'
&& /./[Symbol.replace]('a', '$0') === '$0';
},
'es.string.replace-all': function () {
return String.prototype.replaceAll;
},
'es.string.search': function () {
var O = {};
O[Symbol.search] = function () { return 7; };
var execCalled = false;
var re = /a/;
re.exec = function () {
execCalled = true;
return null;
};
re[Symbol.search]('');
return ''.search(O) === 7 && execCalled;
},
'es.string.split': function () {
var O = {};
O[Symbol.split] = function () { return 7; };
var execCalled = false;
var re = /a/;
re.exec = function () {
execCalled = true;
return null;
};
re.constructor = {};
re.constructor[Symbol.species] = function () { return re; };
re[Symbol.split]('');
// eslint-disable-next-line regexp/no-empty-group -- required for testing
var re2 = /(?:)/;
var originalExec = re2.exec;
re2.exec = function () { return originalExec.apply(this, arguments); };
var result = 'ab'.split(re2);
return ''.split(O) === 7 && execCalled && result.length === 2 && result[0] === 'a' && result[1] === 'b';
},
'es.string.starts-with': createIsRegExpLogicTest('startsWith'),
'es.string.substr': function () {
return 'ab'.substr(-1) === 'b';
},
'es.string.to-well-formed': function () {
// Safari ToString conversion bug
// https://bugs.webkit.org/show_bug.cgi?id=251757
return String.prototype.toWellFormed.call(1) === '1';
},
'es.string.trim': createStringTrimMethodTest('trim'),
'es.string.trim-end': [createStringTrimMethodTest('trimEnd'), function () {
return String.prototype.trimRight === String.prototype.trimEnd;
}],
'es.string.trim-left': [createStringTrimMethodTest('trimStart'), function () {
return String.prototype.trimLeft === String.prototype.trimStart;
}],
'es.string.trim-right': [createStringTrimMethodTest('trimEnd'), function () {
return String.prototype.trimRight === String.prototype.trimEnd;
}],
'es.string.trim-start': [createStringTrimMethodTest('trimStart'), function () {
return String.prototype.trimLeft === String.prototype.trimStart;
}],
'es.string.anchor': createStringHTMLMethodTest('anchor'),
'es.string.big': createStringHTMLMethodTest('big'),
'es.string.blink': createStringHTMLMethodTest('blink'),
'es.string.bold': createStringHTMLMethodTest('bold'),
'es.string.fixed': createStringHTMLMethodTest('fixed'),
'es.string.fontcolor': createStringHTMLMethodTest('fontcolor'),
'es.string.fontsize': createStringHTMLMethodTest('fontsize'),
'es.string.italics': createStringHTMLMethodTest('italics'),
'es.string.link': createStringHTMLMethodTest('link'),
'es.string.small': createStringHTMLMethodTest('small'),
'es.string.strike': createStringHTMLMethodTest('strike'),
'es.string.sub': createStringHTMLMethodTest('sub'),
'es.string.sup': createStringHTMLMethodTest('sup'),
'es.typed-array.float32-array': [
ARRAY_BUFFER_VIEWS_SUPPORT,
TYPED_ARRAY_CONSTRUCTORS_NOT_REQUIRES_WRAPPERS
],
'es.typed-array.float64-array': [
ARRAY_BUFFER_VIEWS_SUPPORT,
TYPED_ARRAY_CONSTRUCTORS_NOT_REQUIRES_WRAPPERS
],
'es.typed-array.int8-array': [
ARRAY_BUFFER_VIEWS_SUPPORT,
TYPED_ARRAY_CONSTRUCTORS_NOT_REQUIRES_WRAPPERS
],
'es.typed-array.int16-array': [
ARRAY_BUFFER_VIEWS_SUPPORT,
TYPED_ARRAY_CONSTRUCTORS_NOT_REQUIRES_WRAPPERS
],
'es.typed-array.int32-array': [
ARRAY_BUFFER_VIEWS_SUPPORT,
TYPED_ARRAY_CONSTRUCTORS_NOT_REQUIRES_WRAPPERS
],
'es.typed-array.uint8-array': [
ARRAY_BUFFER_VIEWS_SUPPORT,
TYPED_ARRAY_CONSTRUCTORS_NOT_REQUIRES_WRAPPERS
],
'es.typed-array.uint8-clamped-array': [
ARRAY_BUFFER_VIEWS_SUPPORT,
TYPED_ARRAY_CONSTRUCTORS_NOT_REQUIRES_WRAPPERS
],
'es.typed-array.uint16-array': [
ARRAY_BUFFER_VIEWS_SUPPORT,
TYPED_ARRAY_CONSTRUCTORS_NOT_REQUIRES_WRAPPERS
],
'es.typed-array.uint32-array': [
ARRAY_BUFFER_VIEWS_SUPPORT,
TYPED_ARRAY_CONSTRUCTORS_NOT_REQUIRES_WRAPPERS
],
'es.typed-array.at': function () {
return Int8Array.prototype.at;
},
'es.typed-array.copy-within': [ARRAY_BUFFER_VIEWS_SUPPORT, function () {
return Int8Array.prototype.copyWithin;
}],
'es.typed-array.every': [ARRAY_BUFFER_VIEWS_SUPPORT, function () {
return Int8Array.prototype.every;
}],
'es.typed-array.fill': [ARRAY_BUFFER_VIEWS_SUPPORT, function () {
var count = 0;
new Int8Array(2).fill({ valueOf: function () { return count++; } });
return count === 1;
}],
'es.typed-array.filter': [ARRAY_BUFFER_VIEWS_SUPPORT, function () {
return Int8Array.prototype.filter;
}],
'es.typed-array.find': [ARRAY_BUFFER_VIEWS_SUPPORT, function () {
return Int8Array.prototype.find;
}],
'es.typed-array.find-index': [ARRAY_BUFFER_VIEWS_SUPPORT, function () {
return Int8Array.prototype.findIndex;
}],
'es.typed-array.find-last': function () {
return Int8Array.prototype.findLast;
},
'es.typed-array.find-last-index': function () {
return Int8Array.prototype.findLastIndex;
},
'es.typed-array.for-each': [ARRAY_BUFFER_VIEWS_SUPPORT, function () {
return Int8Array.prototype.forEach;
}],
'es.typed-array.from': [
ARRAY_BUFFER_VIEWS_SUPPORT,
TYPED_ARRAY_CONSTRUCTORS_NOT_REQUIRES_WRAPPERS,
function () {
return Int8Array.from;
}
],
'es.typed-array.includes': [ARRAY_BUFFER_VIEWS_SUPPORT, function () {
return Int8Array.prototype.includes;
}],
'es.typed-array.index-of': [ARRAY_BUFFER_VIEWS_SUPPORT, function () {
return Int8Array.prototype.indexOf;
}],
'es.typed-array.iterator': [ARRAY_BUFFER_VIEWS_SUPPORT, function () {
try {
Int8Array.prototype[Symbol.iterator].call([1]);
} catch (error) {
return Int8Array.prototype[Symbol.iterator].name === 'values'
&& Int8Array.prototype[Symbol.iterator] === Int8Array.prototype.values
&& Int8Array.prototype.keys
&& Int8Array.prototype.entries;
}
}],
'es.typed-array.join': [ARRAY_BUFFER_VIEWS_SUPPORT, function () {
return Int8Array.prototype.join;
}],
'es.typed-array.last-index-of': [ARRAY_BUFFER_VIEWS_SUPPORT, function () {
return Int8Array.prototype.lastIndexOf;
}],
'es.typed-array.map': [ARRAY_BUFFER_VIEWS_SUPPORT, function () {
return Int8Array.prototype.map;
}],
'es.typed-array.of': [
ARRAY_BUFFER_VIEWS_SUPPORT,
TYPED_ARRAY_CONSTRUCTORS_NOT_REQUIRES_WRAPPERS,
function () {
return Int8Array.of;
}
],
'es.typed-array.reduce': [ARRAY_BUFFER_VIEWS_SUPPORT, function () {
return Int8Array.prototype.reduce;
}],
'es.typed-array.reduce-right': [ARRAY_BUFFER_VIEWS_SUPPORT, function () {
return Int8Array.prototype.reduceRight;
}],
'es.typed-array.reverse': [ARRAY_BUFFER_VIEWS_SUPPORT, function () {
return Int8Array.prototype.reverse;
}],
'es.typed-array.set': [ARRAY_BUFFER_VIEWS_SUPPORT, function () {
var array = new Uint8ClampedArray(3);
array.set(1);
array.set('2', 1);
Int8Array.prototype.set.call(array, { length: 1, 0: 3 }, 2);
return array[0] === 0 && array[1] === 2 && array[2] === 3;
}],
'es.typed-array.slice': [ARRAY_BUFFER_VIEWS_SUPPORT, function () {
return new Int8Array(1).slice();
}],
'es.typed-array.some': [ARRAY_BUFFER_VIEWS_SUPPORT, function () {
return Int8Array.prototype.some;
}],
'es.typed-array.sort': [ARRAY_BUFFER_VIEWS_SUPPORT, function () {
try {
new Uint16Array(1).sort(null);
new Uint16Array(1).sort({});
return false;
} catch (error) { /* empty */ }
// stable sort
var array = new Uint16Array(516);
var expected = Array(516);
var index, mod;
for (index = 0; index < 516; index++) {
mod = index % 4;
array[index] = 515 - index;
expected[index] = index - 2 * mod + 3;
}
array.sort(function (a, b) {
return (a / 4 | 0) - (b / 4 | 0);
});
for (index = 0; index < 516; index++) {
if (array[index] !== expected[index]) return;
} return true;
}],
'es.typed-array.subarray': [ARRAY_BUFFER_VIEWS_SUPPORT, function () {
return Int8Array.prototype.subarray;
}],
'es.typed-array.to-locale-string': [ARRAY_BUFFER_VIEWS_SUPPORT, function () {
try {
Int8Array.prototype.toLocaleString.call([1, 2]);
} catch (error) {
return [1, 2].toLocaleString() === new Int8Array([1, 2]).toLocaleString();
}
}],
'es.typed-array.to-string': [ARRAY_BUFFER_VIEWS_SUPPORT, function () {
return Int8Array.prototype.toString === Array.prototype.toString;
}],
'es.typed-array.to-reversed': function () {
return Int8Array.prototype.toReversed;
},
'es.typed-array.to-sorted': function () {
return Int8Array.prototype.toSorted;
},
'es.typed-array.with': [function () {
try {
new Int8Array(1)['with'](2, { valueOf: function () { throw 8; } });
} catch (error) {
return error === 8;
}
}, function () {
// WebKit doesn't handle this correctly. It should truncate a negative fractional index to zero, but instead throws an error
// Copyright (C) 2025 André Bargull. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
// https://github.com/tc39/test262/pull/4477/commits/bd47071722d914036280cdd795a6ac6046d1c6f9
var ta = new Int8Array(1);
var result = ta['with'](-0.5, 1);
return result[0] === 1;
}],
'es.uint8-array.from-base64': function () {
try {
Uint8Array.fromBase64('a');
return;
} catch (error) { /* empty */ }
if (!Uint8Array.fromBase64) return false;
try {
Uint8Array.fromBase64('', null);
} catch (error) {
return true;
}
},
'es.uint8-array.from-hex': function () {
return Uint8Array.fromHex;
},
'es.uint8-array.set-from-base64': function () {
var target = new Uint8Array([255, 255, 255, 255, 255]);
try {
target.setFromBase64('', null);
return false;
} catch (error) { /* empty */ }
try {
target.setFromBase64('a');
return;
} catch (error) { /* empty */ }
try {
target.setFromBase64('MjYyZg===');
} catch (error) {
return target[0] === 50 && target[1] === 54 && target[2] === 50 && target[3] === 255 && target[4] === 255;
}
},
'es.uint8-array.set-from-hex': function () {
// Should not throw an error on length-tracking views over ResizableArrayBuffer
// https://issues.chromium.org/issues/454630441
try {
var rab = new ArrayBuffer(16, { maxByteLength: 1024 });
new Uint8Array(rab).setFromHex('cafed00d');
return true;
} catch (error) { /* empty */ }
},
'es.uint8-array.to-base64': function () {
if (!Uint8Array.prototype.toBase64) return false;
try {
var target = new Uint8Array();
target.toBase64(null);
} catch (error) {
return true;
}
},
'es.uint8-array.to-hex': function () {
if (!Uint8Array.prototype.toHex) return false;
try {
var target = new Uint8Array([255, 255, 255, 255, 255, 255, 255, 255]);
return target.toHex() === 'ffffffffffffffff';
} catch (error) {
return false;
}
},
'es.unescape': function () {
return unescape;
},
'es.weak-map.constructor': [SAFE_ITERATION_CLOSING_SUPPORT, function () {
var key = Object.freeze([]);
var called = 0;
var iterable = {
next: function () {
return { done: !!called++, value: [key, 1] };
}
};
iterable[Symbol.iterator] = function () {
return this;
};
var map = new WeakMap(iterable);
// MS IE bug
return map.get(key) === 1
&& map.get(null) === undefined
&& map.set({}, 2) === map
&& map[Symbol.toStringTag]
// MS Edge bug
&& Object.isFrozen(key);
}],
'es.weak-map.get-or-insert': function () {
return WeakMap.prototype.getOrInsert;
},
'es.weak-map.get-or-insert-computed': function () {
if (!WeakMap.prototype.getOrInsertComputed) return;
try {
new WeakMap().getOrInsertComputed(1, function () { throw 1; });
} catch (error) {
// FF144 Nightly - Beta 3 bug
// https://bugzilla.mozilla.org/show_bug.cgi?id=1988369
return error instanceof TypeError;
}
},
'es.weak-set.constructor': [SAFE_ITERATION_CLOSING_SUPPORT, function () {
var key = {};
var called = 0;
var iterable = {
next: function () {
return { done: !!called++, value: key };
}
};
iterable[Symbol.iterator] = function () {
return this;
};
var set = new WeakSet(iterable);
return set.has(key)
&& !set.has(null)
&& set.add({}) === set
&& set[Symbol.toStringTag];
}],
'esnext.array.filter-reject': function () {
return [].filterReject;
},
'esnext.array.is-template-object': function () {
return Array.isTemplateObject;
},
'esnext.array.unique-by': function () {
return [].uniqueBy;
},
'esnext.async-iterator.constructor': function () {
return typeof AsyncIterator == 'function';
},
'esnext.async-iterator.drop': function () {
return AsyncIterator.prototype.drop;
},
'esnext.async-iterator.every': function () {
return AsyncIterator.prototype.every;
},
'esnext.async-iterator.filter': function () {
return AsyncIterator.prototype.filter;
},
'esnext.async-iterator.find': function () {
return AsyncIterator.prototype.find;
},
'esnext.async-iterator.flat-map': function () {
return AsyncIterator.prototype.flatMap;
},
'esnext.async-iterator.for-each': function () {
return AsyncIterator.prototype.forEach;
},
'esnext.async-iterator.from': function () {
return AsyncIterator.from;
},
'esnext.async-iterator.map': function () {
return AsyncIterator.prototype.map;
},
'esnext.async-iterator.reduce': function () {
return AsyncIterator.prototype.reduce;
},
'esnext.async-iterator.some': function () {
return AsyncIterator.prototype.some;
},
'esnext.async-iterator.take': function () {
return AsyncIterator.prototype.take;
},
'esnext.async-iterator.to-array': function () {
return AsyncIterator.prototype.toArray;
},
'esnext.composite-key': function () {
return compositeKey;
},
'esnext.composite-symbol': function () {
return compositeSymbol;
},
'esnext.data-view.get-uint8-clamped': [ARRAY_BUFFER_SUPPORT, function () {
return DataView.prototype.getUint8Clamped;
}],
'esnext.data-view.set-uint8-clamped': [ARRAY_BUFFER_SUPPORT, function () {
return DataView.prototype.setUint8Clamped;
}],
'esnext.function.demethodize': function () {
return Function.prototype.demethodize;
},
'esnext.function.is-callable': function () {
return Function.isCallable;
},
'esnext.function.is-constructor': function () {
return Function.isConstructor;
},
'esnext.function.metadata': function () {
return Function.prototype[Symbol.metadata] === null;
},
'esnext.iterator.chunks': function () {
return Iterator.prototype.chunks;
},
'esnext.iterator.range': function () {
return Iterator.range;
},
'esnext.iterator.to-async': function () {
return Iterator.prototype.toAsync;
},
'esnext.iterator.windows': function () {
return Iterator.prototype.windows;
},
'esnext.iterator.zip': function () {
return Iterator.zip;
},
'esnext.iterator.zip-keyed': function () {
return Iterator.zipKeyed;
},
'esnext.map.delete-all': function () {
return Map.prototype.deleteAll;
},
'esnext.map.every': function () {
return Map.prototype.every;
},
'esnext.map.filter': function () {
return Map.prototype.filter;
},
'esnext.map.find': function () {
return Map.prototype.find;
},
'esnext.map.find-key': function () {
return Map.prototype.findKey;
},
'esnext.map.from': function () {
return Map.from;
},
'esnext.map.includes': function () {
return Map.prototype.includes;
},
'esnext.map.key-by': function () {
return Map.keyBy;
},
'esnext.map.key-of': function () {
return Map.prototype.keyOf;
},
'esnext.map.map-keys': function () {
return Map.prototype.mapKeys;
},
'esnext.map.map-values': function () {
return Map.prototype.mapValues;
},
'esnext.map.merge': function () {
return Map.prototype.merge;
},
'esnext.map.of': function () {
return Map.of;
},
'esnext.map.reduce': function () {
return Map.prototype.reduce;
},
'esnext.map.some': function () {
return Map.prototype.some;
},
'esnext.map.update': function () {
return Map.prototype.update;
},
'esnext.math.deg-per-rad': function () {
return Math.DEG_PER_RAD;
},
'esnext.math.degrees': function () {
return Math.degrees;
},
'esnext.math.fscale': function () {
return Math.fscale;
},
'esnext.math.rad-per-deg': function () {
return Math.RAD_PER_DEG;
},
'esnext.math.radians': function () {
return Math.radians;
},
'esnext.math.scale': function () {
return Math.scale;
},
'esnext.math.signbit': function () {
return Math.signbit;
},
'esnext.number.clamp': function () {
return Number.prototype.clamp;
},
'esnext.number.from-string': function () {
return Number.fromString;
},
'esnext.set.add-all': function () {
return Set.prototype.addAll;
},
'esnext.set.delete-all': function () {
return Set.prototype.deleteAll;
},
'esnext.set.every': function () {
return Set.prototype.every;
},
'esnext.set.filter': function () {
return Set.prototype.filter;
},
'esnext.set.find': function () {
return Set.prototype.find;
},
'esnext.set.from': function () {
return Set.from;
},
'esnext.set.join': function () {
return Set.prototype.join;
},
'esnext.set.map': function () {
return Set.prototype.map;
},
'esnext.set.of': function () {
return Set.of;
},
'esnext.set.reduce': function () {
return Set.prototype.reduce;
},
'esnext.set.some': function () {
return Set.prototype.some;
},
'esnext.string.code-points': function () {
return String.prototype.codePoints;
},
'esnext.string.cooked': function () {
return String.cooked;
},
'esnext.string.dedent': function () {
return String.dedent;
},
'esnext.symbol.custom-matcher': function () {
return Symbol.customMatcher;
},
'esnext.symbol.is-registered-symbol': function () {
return Symbol.isRegisteredSymbol;
},
'esnext.symbol.is-well-known-symbol': function () {
return Symbol.isWellKnownSymbol;
},
'esnext.symbol.metadata': function () {
return Symbol.metadata;
},
'esnext.symbol.observable': function () {
return Symbol.observable;
},
'esnext.typed-array.filter-reject': function () {
return Int8Array.prototype.filterReject;
},
'esnext.typed-array.unique-by': function () {
return Int8Array.prototype.uniqueBy;
},
'esnext.weak-map.delete-all': function () {
return WeakMap.prototype.deleteAll;
},
'esnext.weak-map.from': function () {
return WeakMap.from;
},
'esnext.weak-map.of': function () {
return WeakMap.of;
},
'esnext.weak-set.add-all': function () {
return WeakSet.prototype.addAll;
},
'esnext.weak-set.delete-all': function () {
return WeakSet.prototype.deleteAll;
},
'esnext.weak-set.from': function () {
return WeakSet.from;
},
'esnext.weak-set.of': function () {
return WeakSet.of;
},
'web.atob': function () {
try {
atob();
} catch (error1) {
try {
atob('a');
} catch (error2) {
return atob(' ') === '';
}
}
},
'web.btoa': function () {
try {
btoa();
} catch (error) {
return typeof btoa == 'function';
}
},
'web.clear-immediate': function () {
return setImmediate && clearImmediate;
},
'web.dom-collections.for-each': function () {
return (!GLOBAL.NodeList || (NodeList.prototype.forEach && NodeList.prototype.forEach === [].forEach))
&& (!GLOBAL.DOMTokenList || (DOMTokenList.prototype.forEach && DOMTokenList.prototype.forEach === [].forEach));
},
'web.dom-collections.iterator': function () {
var DOMIterables = {
CSSRuleList: 0,
CSSStyleDeclaration: 0,
CSSValueList: 0,
ClientRectList: 0,
DOMRectList: 0,
DOMStringList: 0,
DOMTokenList: 1,
DataTransferItemList: 0,
FileList: 0,
HTMLAllCollection: 0,
HTMLCollection: 0,
HTMLFormElement: 0,
HTMLSelectElement: 0,
MediaList: 0,
MimeTypeArray: 0,
NamedNodeMap: 0,
NodeList: 1,
PaintRequestList: 0,
Plugin: 0,
PluginArray: 0,
SVGLengthList: 0,
SVGNumberList: 0,
SVGPathSegList: 0,
SVGPointList: 0,
SVGStringList: 0,
SVGTransformList: 0,
SourceBufferList: 0,
StyleSheetList: 0,
TextTrackCueList: 0,
TextTrackList: 0,
TouchList: 0
};
for (var collection in DOMIterables) {
if (GLOBAL[collection]) {
if (
!GLOBAL[collection].prototype[Symbol.iterator] ||
GLOBAL[collection].prototype[Symbol.iterator] !== [].values
) return false;
if (DOMIterables[collection] && (
!GLOBAL[collection].prototype.keys ||
!GLOBAL[collection].prototype.values ||
!GLOBAL[collection].prototype.entries
)) return false;
}
}
return true;
},
'web.dom-exception.constructor': function () {
return new DOMException() instanceof Error
&& new DOMException(1, 'DataCloneError').code === 25
&& String(new DOMException(1, 2)) === '2: 1'
&& DOMException.DATA_CLONE_ERR === 25
&& DOMException.prototype.DATA_CLONE_ERR === 25;
},
'web.dom-exception.stack': function () {
return !('stack' in new Error('1')) || 'stack' in new DOMException();
},
'web.dom-exception.to-string-tag': function () {
return typeof DOMException == 'function'
&& DOMException.prototype[Symbol.toStringTag] === 'DOMException';
},
// TODO: Remove this module from `core-js@4` since it's split to submodules
'web.immediate': IMMEDIATE,
'web.queue-microtask': function () {
return Object.getOwnPropertyDescriptor(GLOBAL, 'queueMicrotask').value.length === 1;
},
'web.self': function () {
// eslint-disable-next-line no-restricted-globals -- safe
if (self !== GLOBAL) return false;
if (!DESCRIPTORS_SUPPORT) return true;
var descriptor = Object.getOwnPropertyDescriptor(GLOBAL, 'self');
return descriptor.get && descriptor.enumerable;
},
'web.set-immediate': IMMEDIATE,
'web.set-interval': TIMERS,
'web.set-timeout': TIMERS,
'web.structured-clone': function () {
function checkErrorsCloning(structuredCloneImplementation, $Error) {
var error = new $Error();
var test = structuredCloneImplementation({ a: error, b: error });
return test && test.a === test.b && test.a instanceof $Error && test.a.stack === error.stack;
}
function checkNewErrorsCloningSemantic(structuredCloneImplementation) {
var test = structuredCloneImplementation(new AggregateError([1], 'message', { cause: 3 }));
return test.name === 'AggregateError' && test.errors[0] === 1 && test.message === 'message' && test.cause === 3;
}
return checkErrorsCloning(structuredClone, Error)
&& checkErrorsCloning(structuredClone, DOMException)
&& checkNewErrorsCloningSemantic(structuredClone);
},
// TODO: Remove this module from `core-js@4` since it's split to submodules
'web.timers': TIMERS,
'web.url.constructor': URL_AND_URL_SEARCH_PARAMS_SUPPORT,
'web.url.can-parse': [URL_AND_URL_SEARCH_PARAMS_SUPPORT, function () {
try {
URL.canParse();
} catch (error) {
return URL.canParse.length === 1;
}
}],
'web.url.parse': [URL_AND_URL_SEARCH_PARAMS_SUPPORT, function () {
return URL.parse;
}],
'web.url.to-json': [URL_AND_URL_SEARCH_PARAMS_SUPPORT, function () {
return URL.prototype.toJSON;
}],
'web.url-search-params.constructor': URL_AND_URL_SEARCH_PARAMS_SUPPORT,
'web.url-search-params.delete': [URL_AND_URL_SEARCH_PARAMS_SUPPORT, function () {
var params = new URLSearchParams('a=1&a=2&b=3');
params['delete']('a', 1);
// `undefined` case is a Chromium 117 bug
// https://bugs.chromium.org/p/v8/issues/detail?id=14222
params['delete']('b', undefined);
return params + '' === 'a=2';
}],
'web.url-search-params.has': [URL_AND_URL_SEARCH_PARAMS_SUPPORT, function () {
var params = new URLSearchParams('a=1');
// `undefined` case is a Chromium 117 bug
// https://bugs.chromium.org/p/v8/issues/detail?id=14222
return params.has('a', 1) && !params.has('a', 2) && params.has('a', undefined);
}],
'web.url-search-params.size': [URL_AND_URL_SEARCH_PARAMS_SUPPORT, function () {
return 'size' in URLSearchParams.prototype;
}]
};
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/entries/content.mjs
|
JavaScript
|
import { deepEqual, ok } from 'node:assert/strict';
import konan from 'konan';
const allModules = await fs.readJson('packages/core-js-compat/modules.json');
const entries = await fs.readJson('packages/core-js-compat/entries.json');
let fail = false;
function filter(regexp) {
return allModules.filter(it => regexp.test(it));
}
function equal(name, required) {
const contains = new Set(entries[name]);
const shouldContain = new Set(Array.isArray(required) ? required : filter(required));
deepEqual(contains, shouldContain);
}
function superset(name, required) {
const contains = new Set(entries[name]);
const shouldContain = Array.isArray(required) ? required : filter(required);
for (const module of shouldContain) {
ok(contains.has(module), module);
}
}
function subset(name, required) {
const contains = entries[name];
const shouldContain = new Set(Array.isArray(required) ? required : filter(required));
for (const module of contains) {
ok(shouldContain.has(module), module);
}
}
equal('core-js', allModules);
equal('core-js/es', /^es\./);
superset('core-js/es/array', /^es\.array\./);
superset('core-js/es/array-buffer', /^es\.array-buffer\./);
superset('core-js/es/data-view', /^es\.data-view\./);
superset('core-js/es/date', /^es\.date\./);
superset('core-js/es/error', /^es\.error\./);
superset('core-js/es/function', /^es\.function\./);
superset('core-js/es/json', /^es\.json\./);
superset('core-js/es/map', /^es\.map/);
superset('core-js/es/math', /^es\.math\./);
superset('core-js/es/number', /^es\.number\./);
superset('core-js/es/object', /^es\.object\./);
superset('core-js/es/promise', /^es\.promise/);
superset('core-js/es/reflect', /^es\.reflect\./);
superset('core-js/es/regexp', /^es\.regexp\./);
superset('core-js/es/set', /^es\.set/);
superset('core-js/es/string', /^es\.string\./);
superset('core-js/es/symbol', /^es\.symbol/);
superset('core-js/es/typed-array', /^es\.typed-array\./);
superset('core-js/es/weak-map', /^es\.weak-map/);
superset('core-js/es/weak-set', /^es\.weak-set/);
equal('core-js/web', /^web\./);
equal('core-js/stable', /^(?:es|web)\./);
superset('core-js/stable/array', /^es\.array\./);
superset('core-js/stable/array-buffer', /^es\.array-buffer\./);
superset('core-js/stable/data-view', /^es\.data-view\./);
superset('core-js/stable/date', /^es\.date\./);
superset('core-js/stable/dom-collections', /^web\.dom-collections\./);
superset('core-js/stable/error', /^es\.error\./);
superset('core-js/stable/function', /^es\.function\./);
superset('core-js/stable/json', /^es\.json\./);
superset('core-js/stable/map', /^es\.map/);
superset('core-js/stable/math', /^es\.math\./);
superset('core-js/stable/number', /^es\.number\./);
superset('core-js/stable/object', /^es\.object\./);
superset('core-js/stable/promise', /^es\.promise/);
superset('core-js/stable/reflect', /^es\.reflect\./);
superset('core-js/stable/regexp', /^es\.regexp\./);
superset('core-js/stable/set', /^es\.set/);
superset('core-js/stable/string', /^es\.string\./);
superset('core-js/stable/symbol', /^es\.symbol/);
superset('core-js/stable/typed-array', /^es\.typed-array\./);
superset('core-js/stable/url', /^web\.url(?:\.|$)/);
superset('core-js/stable/url-search-params', /^web\.url-search-params/);
superset('core-js/stable/weak-map', /^es\.weak-map/);
superset('core-js/stable/weak-set', /^es\.weak-set/);
superset('core-js/actual', /^(?:es|web)\./);
superset('core-js/actual/array', /^es\.array\./);
superset('core-js/actual/array-buffer', /^es\.array-buffer\./);
superset('core-js/actual/data-view', /^es\.data-view\./);
superset('core-js/actual/date', /^es\.date\./);
superset('core-js/actual/dom-collections', /^web\.dom-collections\./);
superset('core-js/actual/function', /^es\.function\./);
superset('core-js/actual/json', /^es\.json\./);
superset('core-js/actual/map', /^es\.map/);
superset('core-js/actual/math', /^es\.math\./);
superset('core-js/actual/number', /^es\.number\./);
superset('core-js/actual/object', /^es\.object\./);
superset('core-js/actual/promise', /^es\.promise/);
superset('core-js/actual/reflect', /^es\.reflect\./);
superset('core-js/actual/regexp', /^es\.regexp\./);
superset('core-js/actual/set', /^es\.set/);
superset('core-js/actual/string', /^es\.string\./);
superset('core-js/actual/symbol', /^es\.symbol/);
superset('core-js/actual/typed-array', /^es\.typed-array\./);
superset('core-js/actual/url', /^web\.url(?:\.|$)/);
superset('core-js/actual/url-search-params', /^web\.url-search-params/);
superset('core-js/actual/weak-map', /^es\.weak-map/);
superset('core-js/actual/weak-set', /^es\.weak-set/);
equal('core-js/full', allModules);
superset('core-js/full/array', /^(?:es|esnext)\.array\./);
superset('core-js/full/array-buffer', /^(?:es|esnext)\.array-buffer\./);
superset('core-js/full/async-iterator', /^(?:es|esnext)\.async-iterator\./);
superset('core-js/full/bigint', /^(?:es|esnext)\.bigint\./);
superset('core-js/full/data-view', /^(?:es|esnext)\.data-view\./);
superset('core-js/full/date', /^(?:es|esnext)\.date\./);
superset('core-js/full/dom-collections', /^web\.dom-collections\./);
superset('core-js/full/error', /^es\.error\./);
superset('core-js/full/function', /^(?:es|esnext)\.function\./);
superset('core-js/full/iterator', /^(?:es|esnext)\.iterator\./);
superset('core-js/full/json', /^(?:es|esnext)\.json\./);
superset('core-js/full/map', /^(?:es|esnext)\.map/);
superset('core-js/full/math', /^(?:es|esnext)\.math\./);
superset('core-js/full/number', /^(?:es|esnext)\.number\./);
superset('core-js/full/object', /^(?:es|esnext)\.object\./);
superset('core-js/full/observable', /^(?:es|esnext)\.observable/);
superset('core-js/full/promise', /^(?:es|esnext)\.promise/);
superset('core-js/full/reflect', /^(?:es|esnext)\.reflect\./);
superset('core-js/full/regexp', /^(?:es|esnext)\.regexp\./);
superset('core-js/full/set', /^(?:es|esnext)\.set/);
superset('core-js/full/string', /^(?:es|esnext)\.string\./);
superset('core-js/full/symbol', /^(?:es|esnext)\.symbol/);
superset('core-js/full/typed-array', /^(?:es|esnext)\.typed-array\./);
superset('core-js/full/url', /^web\.url(?:\.|$)/);
superset('core-js/full/url-search-params', /^web\.url-search-params/);
superset('core-js/full/weak-map', /^(?:es|esnext)\.weak-map/);
superset('core-js/full/weak-set', /^(?:es|esnext)\.weak-set/);
subset('core-js/proposals', /^(?:es\.(?:map|string\.at)|esnext\.|web\.url)/);
subset('core-js/stage', /^(?:es\.(?:map|string\.at)|esnext\.|web\.url)/);
subset('core-js/stage/pre', /^(?:es\.(?:map|string\.at)|esnext\.|web\.url)/);
subset('core-js/stage/0', /^(?:es\.(?:map|string\.at)|esnext\.|web\.url)/);
subset('core-js/stage/1', /^(?:es\.(?:map|string\.at)|esnext\.|web\.url)/);
subset('core-js/stage/2', /^(?:es\.string\.at|esnext\.)/);
subset('core-js/stage/3', /^(?:es\.string\.at|esnext\.)/);
subset('core-js/stage/4', /^(?:es\.string\.at|esnext\.)/);
async function unexpectedInnerNamespace(namespace, unexpected) {
const paths = await glob(`packages/core-js/${ namespace }/**/*.js`);
await Promise.all(paths.map(async path => {
for (const dependency of konan(String(await fs.readFile(path, 'utf8'))).strings) {
if (unexpected.test(dependency)) {
echo(chalk.red(`${ chalk.cyan(path) }: found unexpected dependency: ${ chalk.cyan(dependency) }`));
fail = true;
}
}
}));
}
await Promise.all([
unexpectedInnerNamespace('es', /\/(?:actual|full|stable)\//),
unexpectedInnerNamespace('stable', /\/(?:actual|full)\//),
unexpectedInnerNamespace('actual', /\/(?:es|full)\//),
unexpectedInnerNamespace('full', /\/(?:es|stable)\//),
]);
if (fail) throw new Error('entry points content test failed');
echo(chalk.green('entry points content tested'));
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/entries/index.mjs
|
JavaScript
|
await import('./content.mjs');
await import('./unit.mjs');
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/entries/unit.mjs
|
JavaScript
|
/* eslint-disable import/no-dynamic-require, node/global-require -- required */
import { ok } from 'node:assert/strict';
const entries = await fs.readJson('packages/core-js-compat/entries.json');
const expected = new Set(Object.keys(entries));
const tested = new Set();
let PATH;
function load(...components) {
const path = [PATH, ...components].join('/');
tested.add(path);
expected.delete(path);
return require(path);
}
for (PATH of ['core-js-pure', 'core-js']) {
for (const NS of ['es', 'stable', 'actual', 'full', 'features']) {
let O;
ok(load(NS, 'global-this').Math === Math);
ok(new (load(NS, 'aggregate-error'))([42]).errors[0] === 42);
ok(load(NS, 'object/assign')({ q: 1 }, { w: 2 }).w === 2);
ok(load(NS, 'object/create')(Array.prototype) instanceof Array);
ok(load(NS, 'object/define-property')({}, 'a', { value: 42 }).a === 42);
ok(load(NS, 'object/define-properties')({}, { a: { value: 42 } }).a === 42);
ok(load(NS, 'object/freeze')({}));
ok(load(NS, 'object/get-own-property-descriptor')({ q: 1 }, 'q').enumerable);
ok(load(NS, 'object/get-own-property-names')({ q: 42 })[0] === 'q');
ok(load(NS, 'object/get-own-property-symbols')({ [Symbol('getOwnPropertySymbols test')]: 42 }).length === 1);
ok(load(NS, 'object/get-prototype-of')([]) === Array.prototype);
ok(load(NS, 'object/group-by')([1, 2, 3, 4, 5], it => it % 2 === 0 ? 'even' : 'odd').odd.length === 3);
ok(load(NS, 'object/has-own')({ foo: 42 }, 'foo'));
ok(load(NS, 'object/is')(NaN, NaN));
ok(load(NS, 'object/is-extensible')({}));
ok(!load(NS, 'object/is-frozen')({}));
ok(!load(NS, 'object/is-sealed')({}));
ok(load(NS, 'object/keys')({ q: 0 })[0] === 'q');
ok(load(NS, 'object/prevent-extensions')({}));
load(NS, 'object/proto');
ok(load(NS, 'object/seal')({}));
ok(load(NS, 'object/set-prototype-of')({}, []) instanceof Array);
ok(load(NS, 'object/to-string')([]) === '[object Array]');
ok(load(NS, 'object/entries')({ q: 2 })[0][0] === 'q');
ok(load(NS, 'object/from-entries')([['a', 42]]).a === 42);
ok(load(NS, 'object/values')({ q: 2 })[0] === 2);
ok(load(NS, 'object/get-own-property-descriptors')({ q: 1 }).q.enumerable);
ok(typeof load(NS, 'object/define-getter') == 'function');
ok(typeof load(NS, 'object/define-setter') == 'function');
ok(typeof load(NS, 'object/lookup-getter') == 'function');
ok(typeof load(NS, 'object/lookup-setter') == 'function');
ok('values' in load(NS, 'object'));
ok(load(NS, 'function/bind')(function (a, b) {
return this + a + b;
}, 1, 2)(3) === 6);
ok(load(NS, 'function/virtual/bind').call(function (a, b) {
return this + a + b;
}, 1, 2)(3) === 6);
ok(load(NS, 'function/virtual').bind.call(function (a, b) {
return this + a + b;
}, 1, 2)(3) === 6);
load(NS, 'function/name');
load(NS, 'function/has-instance');
load(NS, 'function');
ok(Array.isArray(load(NS, 'array/from')('qwe')));
ok(typeof load(NS, 'array/from-async') == 'function');
ok(load(NS, 'array/is-array')([]));
ok(Array.isArray(load(NS, 'array/of')('q', 'w', 'e')));
ok(load(NS, 'array/at')([1, 2, 3], -2) === 2);
ok(load(NS, 'array/join')('qwe', 1) === 'q1w1e');
ok(load(NS, 'array/slice')('qwe', 1)[1] === 'e');
ok(load(NS, 'array/sort')([1, 3, 2])[1] === 2);
ok(typeof load(NS, 'array/for-each') == 'function');
ok(typeof load(NS, 'array/map') == 'function');
ok(typeof load(NS, 'array/filter') == 'function');
ok(typeof load(NS, 'array/flat') == 'function');
ok(typeof load(NS, 'array/flat-map') == 'function');
ok(typeof load(NS, 'array/some') == 'function');
ok(typeof load(NS, 'array/every') == 'function');
ok(typeof load(NS, 'array/push') == 'function');
ok(typeof load(NS, 'array/reduce') == 'function');
ok(typeof load(NS, 'array/reduce-right') == 'function');
ok(typeof load(NS, 'array/reverse') == 'function');
ok(typeof load(NS, 'array/index-of') == 'function');
ok(typeof load(NS, 'array/last-index-of') == 'function');
ok(typeof load(NS, 'array/unshift') == 'function');
ok(load(NS, 'array/concat')([1, 2, 3], [4, 5, 6]).length === 6);
ok(load(NS, 'array/copy-within')([1, 2, 3, 4, 5], 0, 3)[0] === 4);
ok('next' in load(NS, 'array/entries')([]));
ok(load(NS, 'array/fill')(Array(5), 2)[0] === 2);
ok(load(NS, 'array/find')([2, 3, 4], it => it % 2) === 3);
ok(load(NS, 'array/find-index')([2, 3, 4], it => it % 2) === 1);
ok(load(NS, 'array/find-last')([1, 2, 3], it => it % 2) === 3);
ok(load(NS, 'array/find-last-index')([1, 2, 3], it => it % 2) === 2);
ok('next' in load(NS, 'array/keys')([]));
ok('next' in load(NS, 'array/values')([]));
ok(load(NS, 'array/includes')([1, 2, 3], 2));
ok('next' in load(NS, 'array/iterator')([]));
ok(load(NS, 'array/with')([1, 2, 3], 1, 4));
ok(load(NS, 'array/to-reversed')([1, 2, 3])[0] === 3);
ok(load(NS, 'array/to-sorted')([3, 2, 1])[0] === 1);
ok(load(NS, 'array/to-spliced')([3, 2, 1], 1, 1, 4, 5).length === 4);
ok(load(NS, 'array/virtual/at').call([1, 2, 3], -2) === 2);
ok(load(NS, 'array/virtual/join').call('qwe', 1) === 'q1w1e');
ok(load(NS, 'array/virtual/slice').call('qwe', 1)[1] === 'e');
ok(load(NS, 'array/virtual/splice').call([1, 2, 3], 1, 2)[0] === 2);
ok(load(NS, 'array/virtual/sort').call([1, 3, 2])[1] === 2);
ok(typeof load(NS, 'array/virtual/for-each') == 'function');
ok(typeof load(NS, 'array/virtual/map') == 'function');
ok(typeof load(NS, 'array/virtual/filter') == 'function');
ok(typeof load(NS, 'array/virtual/flat') == 'function');
ok(typeof load(NS, 'array/virtual/flat-map') == 'function');
ok(typeof load(NS, 'array/virtual/some') == 'function');
ok(typeof load(NS, 'array/virtual/every') == 'function');
ok(typeof load(NS, 'array/virtual/push') == 'function');
ok(typeof load(NS, 'array/virtual/reduce') == 'function');
ok(typeof load(NS, 'array/virtual/reduce-right') == 'function');
ok(typeof load(NS, 'array/virtual/reverse') == 'function');
ok(typeof load(NS, 'array/virtual/index-of') == 'function');
ok(typeof load(NS, 'array/virtual/last-index-of') == 'function');
ok(typeof load(NS, 'array/virtual/unshift') == 'function');
ok(load(NS, 'array/virtual/concat').call([1, 2, 3], [4, 5, 6]).length === 6);
ok(load(NS, 'array/virtual/copy-within').call([1, 2, 3, 4, 5], 0, 3)[0] === 4);
ok('next' in load(NS, 'array/virtual/entries').call([]));
ok(load(NS, 'array/virtual/fill').call(Array(5), 2)[0] === 2);
ok(load(NS, 'array/virtual/find').call([2, 3, 4], it => it % 2) === 3);
ok(load(NS, 'array/virtual/find-index').call([2, 3, 4], it => it % 2) === 1);
ok(load(NS, 'array/virtual/find-last').call([1, 2, 3], it => it % 2) === 3);
ok(load(NS, 'array/virtual/find-last-index').call([1, 2, 3], it => it % 2) === 2);
ok('next' in load(NS, 'array/virtual/keys').call([]));
ok('next' in load(NS, 'array/virtual/values').call([]));
ok(load(NS, 'array/virtual/includes').call([1, 2, 3], 2));
ok('next' in load(NS, 'array/virtual/iterator').call([]));
ok(load(NS, 'array/virtual/with').call([1, 2, 3], 1, 4));
ok(load(NS, 'array/virtual/to-reversed').call([1, 2, 3])[0] === 3);
ok(load(NS, 'array/virtual/to-sorted').call([3, 2, 1])[0] === 1);
ok(load(NS, 'array/virtual/to-spliced').call([3, 2, 1], 1, 1, 4, 5).length === 4);
ok('map' in load(NS, 'array/virtual'));
ok('from' in load(NS, 'array'));
ok(load(NS, 'array/splice')([1, 2, 3], 1, 2)[0] === 2);
ok(new (load(NS, 'error/constructor').Error)(1, { cause: 7 }).cause === 7);
ok(load(NS, 'error/is-error')(new Error()));
ok(typeof load(NS, 'error/to-string') == 'function');
ok(new (load(NS, 'error').Error)(1, { cause: 7 }).cause === 7);
ok(load(NS, 'math/acosh')(1) === 0);
ok(Object.is(load(NS, 'math/asinh')(-0), -0));
ok(load(NS, 'math/atanh')(1) === Infinity);
ok(load(NS, 'math/cbrt')(-8) === -2);
ok(load(NS, 'math/clz32')(0) === 32);
ok(load(NS, 'math/cosh')(0) === 1);
ok(load(NS, 'math/expm1')(-Infinity) === -1);
ok(load(NS, 'math/fround')(0) === 0);
ok(load(NS, 'math/f16round')(1.337) === 1.3369140625);
ok(load(NS, 'math/hypot')(3, 4) === 5);
ok(load(NS, 'math/imul')(2, 2) === 4);
ok(load(NS, 'math/log10')(-0) === -Infinity);
ok(load(NS, 'math/log1p')(-1) === -Infinity);
ok(load(NS, 'math/log2')(1) === 0);
ok(load(NS, 'math/sign')(-2) === -1);
ok(Object.is(load(NS, 'math/sinh')(-0), -0));
ok(load(NS, 'math/sum-precise')([1, 2, 3]) === 6);
ok(load(NS, 'math/tanh')(Infinity) === 1);
ok(load(NS, 'math/to-string-tag') === 'Math');
ok(load(NS, 'math/trunc')(1.5) === 1);
ok('cbrt' in load(NS, 'math'));
ok(load(NS, 'number/constructor')('5') === 5);
ok(load(NS, 'number/epsilon') === 2 ** -52);
ok(load(NS, 'number/is-finite')(42.5));
ok(load(NS, 'number/is-integer')(42.5) === false);
ok(load(NS, 'number/is-nan')(NaN));
ok(load(NS, 'number/is-safe-integer')(42));
ok(load(NS, 'number/max-safe-integer') === 0x1FFFFFFFFFFFFF);
ok(load(NS, 'number/min-safe-integer') === -0x1FFFFFFFFFFFFF);
ok(load(NS, 'number/parse-float')('1.5') === 1.5);
ok(load(NS, 'number/parse-int')('2.1') === 2);
ok(load(NS, 'number/to-exponential')(1, 1) === '1.0e+0');
ok(load(NS, 'number/to-fixed')(1, 1) === '1.0');
ok(load(NS, 'number/to-precision')(1) === '1');
ok(load(NS, 'parse-float')('1.5') === 1.5);
ok(load(NS, 'parse-int')('2.1') === 2);
ok(load(NS, 'number/virtual/to-exponential').call(1, 1) === '1.0e+0');
ok(load(NS, 'number/virtual/to-fixed').call(1, 1) === '1.0');
ok(load(NS, 'number/virtual/to-precision').call(1) === '1');
ok('toPrecision' in load(NS, 'number/virtual'));
ok('isNaN' in load(NS, 'number'));
ok(load(NS, 'reflect/apply')((a, b) => a + b, null, [1, 2]) === 3);
ok(load(NS, 'reflect/construct')(function () {
return this.a = 2;
}, []).a === 2);
load(NS, 'reflect/define-property')(O = {}, 'a', { value: 42 });
ok(O.a === 42);
ok(load(NS, 'reflect/delete-property')({ q: 1 }, 'q'));
ok(load(NS, 'reflect/get')({ q: 1 }, 'q') === 1);
ok(load(NS, 'reflect/get-own-property-descriptor')({ q: 1 }, 'q').enumerable);
ok(load(NS, 'reflect/get-prototype-of')([]) === Array.prototype);
ok(load(NS, 'reflect/has')({ q: 1 }, 'q'));
ok(load(NS, 'reflect/is-extensible')({}));
ok(load(NS, 'reflect/own-keys')({ q: 1 })[0] === 'q');
ok(load(NS, 'reflect/prevent-extensions')({}));
ok(load(NS, 'reflect/set')({}, 'a', 42));
load(NS, 'reflect/set-prototype-of')(O = {}, []);
ok(load(NS, 'reflect/to-string-tag') === 'Reflect');
ok(O instanceof Array);
ok('has' in load(NS, 'reflect'));
ok(load(NS, 'string/from-code-point')(97) === 'a');
ok(load(NS, 'string/raw')({ raw: 'test' }, 0, 1, 2) === 't0e1s2t');
ok(load(NS, 'string/at')('a', 0) === 'a');
ok(load(NS, 'string/trim')(' ab ') === 'ab');
ok(load(NS, 'string/trim-start')(' a ') === 'a ');
ok(load(NS, 'string/trim-end')(' a ') === ' a');
ok(load(NS, 'string/trim-left')(' a ') === 'a ');
ok(load(NS, 'string/trim-right')(' a ') === ' a');
ok(load(NS, 'string/code-point-at')('a', 0) === 97);
ok(load(NS, 'string/ends-with')('qwe', 'we'));
ok(load(NS, 'string/includes')('qwe', 'w'));
ok(load(NS, 'string/repeat')('q', 3) === 'qqq');
ok(load(NS, 'string/starts-with')('qwe', 'qw'));
ok(typeof load(NS, 'string/anchor') == 'function');
ok(typeof load(NS, 'string/big') == 'function');
ok(typeof load(NS, 'string/blink') == 'function');
ok(typeof load(NS, 'string/bold') == 'function');
ok(typeof load(NS, 'string/fixed') == 'function');
ok(typeof load(NS, 'string/fontcolor') == 'function');
ok(typeof load(NS, 'string/fontsize') == 'function');
ok(typeof load(NS, 'string/italics') == 'function');
ok(typeof load(NS, 'string/link') == 'function');
ok(typeof load(NS, 'string/small') == 'function');
ok(typeof load(NS, 'string/strike') == 'function');
ok(typeof load(NS, 'string/sub') == 'function');
ok(load(NS, 'string/substr')('12345', 1, 3) === '234');
ok(typeof load(NS, 'string/sup') == 'function');
ok(typeof load(NS, 'string/replace-all') == 'function');
ok(load(NS, 'string/pad-start')('a', 3) === ' a');
ok(load(NS, 'string/pad-end')('a', 3) === 'a ');
ok(load(NS, 'string/is-well-formed')('a'));
ok(load(NS, 'string/to-well-formed')('a') === 'a');
ok('next' in load(NS, 'string/iterator')('qwe'));
ok(load(NS, 'string/virtual/at').call('a', 0) === 'a');
ok(load(NS, 'string/virtual/code-point-at').call('a', 0) === 97);
ok(load(NS, 'string/virtual/ends-with').call('qwe', 'we'));
ok(load(NS, 'string/virtual/includes').call('qwe', 'w'));
ok(typeof load(NS, 'string/virtual/match-all') == 'function');
ok(typeof load(NS, 'string/virtual/replace-all') == 'function');
ok(load(NS, 'string/virtual/repeat').call('q', 3) === 'qqq');
ok(load(NS, 'string/virtual/starts-with').call('qwe', 'qw'));
ok(load(NS, 'string/virtual/trim').call(' ab ') === 'ab');
ok(load(NS, 'string/virtual/trim-start').call(' a ') === 'a ');
ok(load(NS, 'string/virtual/trim-end').call(' a ') === ' a');
ok(load(NS, 'string/virtual/trim-left').call(' a ') === 'a ');
ok(load(NS, 'string/virtual/trim-right').call(' a ') === ' a');
ok(typeof load(NS, 'string/virtual/anchor') == 'function');
ok(typeof load(NS, 'string/virtual/big') == 'function');
ok(typeof load(NS, 'string/virtual/blink') == 'function');
ok(typeof load(NS, 'string/virtual/bold') == 'function');
ok(typeof load(NS, 'string/virtual/fixed') == 'function');
ok(typeof load(NS, 'string/virtual/fontcolor') == 'function');
ok(typeof load(NS, 'string/virtual/fontsize') == 'function');
ok(typeof load(NS, 'string/virtual/italics') == 'function');
ok(typeof load(NS, 'string/virtual/link') == 'function');
ok(typeof load(NS, 'string/virtual/small') == 'function');
ok(typeof load(NS, 'string/virtual/strike') == 'function');
ok(typeof load(NS, 'string/virtual/sub') == 'function');
ok(load(NS, 'string/virtual/substr').call('12345', 1, 3) === '234');
ok(typeof load(NS, 'string/virtual/sup') == 'function');
ok(load(NS, 'string/virtual/pad-start').call('a', 3) === ' a');
ok(load(NS, 'string/virtual/pad-end').call('a', 3) === 'a ');
ok(load(NS, 'string/virtual/is-well-formed').call('a'));
ok(load(NS, 'string/virtual/to-well-formed').call('a') === 'a');
ok('next' in load(NS, 'string/virtual/iterator').call('qwe'));
ok('padEnd' in load(NS, 'string/virtual'));
ok('raw' in load(NS, 'string'));
ok(String(load(NS, 'regexp/constructor')('a', 'g')) === '/a/g');
ok(load(NS, 'regexp/escape')('10$') === '\\x310\\$');
ok(load(NS, 'regexp/to-string')(/./g) === '/./g');
ok(load(NS, 'regexp/flags')(/./g) === 'g');
ok(typeof load(NS, 'regexp/match') == 'function');
ok(typeof load(NS, 'regexp/replace') == 'function');
ok(typeof load(NS, 'regexp/search') == 'function');
ok(typeof load(NS, 'regexp/split') == 'function');
ok(typeof load(NS, 'regexp/dot-all') == 'function');
ok(typeof load(NS, 'regexp/sticky') == 'function');
ok(typeof load(NS, 'regexp/test') == 'function');
load(NS, 'regexp');
ok(load(NS, 'escape')('!q2ф') === '%21q2%u0444');
ok(load(NS, 'unescape')('%21q2%u0444') === '!q2ф');
ok(load(NS, 'json').stringify([1]) === '[1]');
ok(load(NS, 'json/is-raw-json')({}) === false);
ok(load(NS, 'json/parse')('[42]', (key, value, { source }) => typeof value == 'number' ? source + source : value)[0] === '4242');
ok(typeof load(NS, 'json/raw-json')(42) == 'object');
ok(load(NS, 'json/stringify')([1]) === '[1]');
ok(load(NS, 'json/to-string-tag') === 'JSON');
ok(typeof load(NS, 'date/now')(new Date()) === 'number');
const date = new Date();
ok(load(NS, 'date/get-year')(date) === date.getFullYear() - 1900);
load(NS, 'date/set-year')(date, 1);
ok(date.getFullYear() === 1901);
ok(typeof load(NS, 'date/to-string')(date) === 'string');
ok(load(NS, 'date/to-gmt-string')(date) === date.toUTCString());
ok(typeof load(NS, 'date/to-primitive')(new Date(), 'number') === 'number');
ok(typeof load(NS, 'date/to-iso-string')(new Date()) === 'string');
ok(load(NS, 'date/to-json')(Infinity) === null);
ok(load(NS, 'date'));
ok(typeof load(NS, 'symbol') == 'function');
ok(typeof load(NS, 'symbol/for') == 'function');
ok(typeof load(NS, 'symbol/key-for') == 'function');
ok(Function[load(NS, 'symbol/has-instance')](it => it));
ok(load(NS, 'symbol/is-concat-spreadable'));
ok(load(NS, 'symbol/iterator'));
ok(load(NS, 'symbol/match'));
ok(load(NS, 'symbol/match-all'));
ok(load(NS, 'symbol/replace'));
ok(load(NS, 'symbol/search'));
ok(load(NS, 'symbol/species'));
ok(load(NS, 'symbol/split'));
ok(load(NS, 'symbol/to-primitive'));
ok(load(NS, 'symbol/to-string-tag'));
ok(load(NS, 'symbol/unscopables'));
ok(load(NS, 'symbol/async-iterator'));
load(NS, 'symbol/description');
const Map = load(NS, 'map');
ok(load(NS, 'map/group-by')([], it => it) instanceof load(NS, 'map'));
ok(load(NS, 'map/get-or-insert')(new Map([[1, 2]]), 1, 3) === 2);
ok(load(NS, 'map/get-or-insert-computed')(new Map([[1, 2]]), 1, key => key) === 2);
const Set = load(NS, 'set');
const WeakMap = load(NS, 'weak-map');
ok(load(NS, 'weak-map/get-or-insert')(new WeakMap([[{}, 2]]), {}, 3) === 3);
ok(load(NS, 'weak-map/get-or-insert-computed')(new WeakMap([[{}, 2]]), {}, () => 3) === 3);
const WeakSet = load(NS, 'weak-set');
ok(new Map([[1, 2], [3, 4]]).size === 2);
ok(new Set([1, 2, 3, 2, 1]).size === 3);
ok(new WeakMap([[O = {}, 42]]).get(O) === 42);
ok(new WeakSet([O = {}]).has(O));
ok(load(NS, 'set/difference')(new Set([1, 2, 3]), new Set([3, 4, 5])).size === 2);
ok(load(NS, 'set/intersection')(new Set([1, 2, 3]), new Set([1, 3, 4])).size === 2);
ok(load(NS, 'set/is-disjoint-from')(new Set([1, 2, 3]), new Set([4, 5, 6])));
ok(load(NS, 'set/is-subset-of')(new Set([1, 2, 3]), new Set([1, 2, 3, 4])));
ok(load(NS, 'set/is-superset-of')(new Set([1, 2, 3, 4]), new Set([1, 2, 3])));
ok(load(NS, 'set/symmetric-difference')(new Set([1, 2, 3]), new Set([3, 4, 5])).size === 4);
ok(load(NS, 'set/union')(new Set([1, 2, 3]), new Set([3, 4, 5])).size === 5);
const Promise = load(NS, 'promise');
ok('then' in Promise.prototype);
ok(load(NS, 'promise/all-settled')([1, 2, 3]) instanceof Promise);
ok(load(NS, 'promise/any')([1, 2, 3]) instanceof Promise);
ok(load(NS, 'promise/finally')(new Promise(resolve => resolve), it => it) instanceof Promise);
ok(load(NS, 'promise/try')(() => 42) instanceof Promise);
ok(load(NS, 'promise/with-resolvers')().promise instanceof load(NS, 'promise'));
ok(load(NS, 'is-iterable')([]));
ok(typeof load(NS, 'get-iterator-method')([]) == 'function');
ok('next' in load(NS, 'get-iterator')([]));
ok('Map' in load(NS));
ok(typeof load(NS, 'iterator') == 'function');
ok(load(NS, 'iterator/concat')([2]).next().value === 2);
ok(typeof load(NS, 'iterator/drop') == 'function');
ok(typeof load(NS, 'iterator/every') == 'function');
ok(typeof load(NS, 'iterator/filter') == 'function');
ok(typeof load(NS, 'iterator/find') == 'function');
ok(typeof load(NS, 'iterator/flat-map') == 'function');
ok(typeof load(NS, 'iterator/for-each') == 'function');
ok(typeof load(NS, 'iterator/from') == 'function');
ok(typeof load(NS, 'iterator/map') == 'function');
ok(typeof load(NS, 'iterator/reduce') == 'function');
ok(typeof load(NS, 'iterator/some') == 'function');
ok(typeof load(NS, 'iterator/take') == 'function');
ok(typeof load(NS, 'iterator/to-array') == 'function');
ok(new (load(NS, 'suppressed-error'))(1, 2).suppressed === 2);
ok(typeof load(NS, 'disposable-stack') == 'function');
ok(typeof load(NS, 'disposable-stack/constructor') == 'function');
load(NS, 'iterator/dispose');
ok(load(NS, 'symbol/async-dispose'));
ok(load(NS, 'symbol/dispose'));
load(NS, 'async-iterator');
load(NS, 'async-iterator/async-dispose');
ok(typeof load(NS, 'async-disposable-stack') == 'function');
ok(typeof load(NS, 'async-disposable-stack/constructor') == 'function');
const instanceAt = load(NS, 'instance/at');
ok(typeof instanceAt == 'function');
ok(instanceAt({}) === undefined);
ok(typeof instanceAt([]) == 'function');
ok(typeof instanceAt('') == 'function');
ok(instanceAt([]).call([1, 2, 3], 2) === 3);
ok(instanceAt('').call('123', 2) === '3');
const instanceBind = load(NS, 'instance/bind');
ok(typeof instanceBind == 'function');
ok(instanceBind({}) === undefined);
ok(typeof instanceBind(it => it) == 'function');
ok(instanceBind(it => it).call(it => it, 1, 2)() === 2);
const instanceCodePointAt = load(NS, 'instance/code-point-at');
ok(typeof instanceCodePointAt == 'function');
ok(instanceCodePointAt({}) === undefined);
ok(typeof instanceCodePointAt('') == 'function');
ok(instanceCodePointAt('').call('a', 0) === 97);
const instanceConcat = load(NS, 'instance/concat');
ok(typeof instanceConcat == 'function');
ok(instanceConcat({}) === undefined);
ok(typeof instanceConcat([]) == 'function');
ok(instanceConcat([]).call([1, 2, 3], [4, 5, 6]).length === 6);
const instanceCopyWithin = load(NS, 'instance/copy-within');
ok(typeof instanceCopyWithin == 'function');
ok(instanceCopyWithin({}) === undefined);
ok(typeof instanceCopyWithin([]) == 'function');
ok(instanceCopyWithin([]).call([1, 2, 3, 4, 5], 0, 3)[0] === 4);
const instanceEndsWith = load(NS, 'instance/ends-with');
ok(typeof instanceEndsWith == 'function');
ok(instanceEndsWith({}) === undefined);
ok(typeof instanceEndsWith('') == 'function');
ok(instanceEndsWith('').call('qwe', 'we'));
const instanceEntries = load(NS, 'instance/entries');
ok(typeof instanceEntries == 'function');
ok(instanceEntries({}) === undefined);
ok(typeof instanceEntries([]) == 'function');
ok(instanceEntries([]).call([1, 2, 3]).next().value[1] === 1);
const instanceEvery = load(NS, 'instance/every');
ok(typeof instanceEvery == 'function');
ok(instanceEvery({}) === undefined);
ok(typeof instanceEvery([]) == 'function');
ok(instanceEvery([]).call([1, 2, 3], it => typeof it == 'number'));
const instanceFill = load(NS, 'instance/fill');
ok(typeof instanceFill == 'function');
ok(instanceFill({}) === undefined);
ok(typeof instanceFill([]) == 'function');
ok(instanceFill([]).call(Array(5), 42)[3] === 42);
const instanceFilter = load(NS, 'instance/filter');
ok(typeof instanceFilter == 'function');
ok(instanceFilter({}) === undefined);
ok(typeof instanceFilter([]) == 'function');
ok(instanceFilter([]).call([1, 2, 3], it => it % 2).length === 2);
const instanceFind = load(NS, 'instance/find');
ok(typeof instanceFind == 'function');
ok(instanceFind({}) === undefined);
ok(typeof instanceFind([]) == 'function');
ok(instanceFind([]).call([1, 2, 3], it => it % 2) === 1);
const instanceFindIndex = load(NS, 'instance/find-index');
ok(typeof instanceFindIndex == 'function');
ok(instanceFindIndex({}) === undefined);
ok(typeof instanceFindIndex([]) == 'function');
ok(instanceFindIndex([]).call([1, 2, 3], it => it % 2) === 0);
const instanceFindLast = load(NS, 'instance/find-last');
ok(typeof instanceFindLast == 'function');
ok(instanceFindLast({}) === undefined);
ok(typeof instanceFindLast([]) == 'function');
ok(instanceFindLast([]).call([1, 2, 3], it => it % 2) === 3);
const instanceFindLastIndex = load(NS, 'instance/find-last-index');
ok(typeof instanceFindLastIndex == 'function');
ok(instanceFindLastIndex({}) === undefined);
ok(typeof instanceFindLastIndex([]) == 'function');
ok(instanceFindLastIndex([]).call([1, 2, 3], it => it % 2) === 2);
const instanceFlags = load(NS, 'instance/flags');
ok(typeof instanceFlags == 'function');
ok(instanceFlags({}) === undefined);
ok(instanceFlags(/./g) === 'g');
const instanceFlatMap = load(NS, 'instance/flat-map');
ok(typeof instanceFlatMap == 'function');
ok(instanceFlatMap({}) === undefined);
ok(typeof instanceFlatMap([]) == 'function');
ok(instanceFlatMap([]).call([1, 2, 3], (v, i) => [v, i]).length === 6);
const instanceFlat = load(NS, 'instance/flat');
ok(typeof instanceFlat == 'function');
ok(instanceFlat({}) === undefined);
ok(typeof instanceFlat([]) == 'function');
ok(instanceFlat([]).call([1, [2, 3], [4, [5, [6]]]]).length === 5);
const instanceForEach = load(NS, 'instance/for-each');
ok(typeof instanceForEach == 'function');
ok(instanceForEach({}) === undefined);
ok(typeof instanceForEach([]) == 'function');
const instanceIncludes = load(NS, 'instance/includes');
ok(typeof instanceIncludes == 'function');
ok(instanceIncludes({}) === undefined);
ok(typeof instanceIncludes([]) == 'function');
ok(typeof instanceIncludes('') == 'function');
ok(instanceIncludes([]).call([1, 2, 3], 2));
ok(instanceIncludes('').call('123', '2'));
const instanceIndexOf = load(NS, 'instance/index-of');
ok(typeof instanceIndexOf == 'function');
ok(instanceIndexOf({}) === undefined);
ok(typeof instanceIndexOf([]) == 'function');
ok(instanceIndexOf([]).call([1, 2, 3], 2) === 1);
const instanceKeys = load(NS, 'instance/keys');
ok(typeof instanceKeys == 'function');
ok(instanceKeys({}) === undefined);
ok(typeof instanceKeys([]) == 'function');
ok(instanceKeys([]).call([1, 2, 3]).next().value === 0);
const instanceIsWellFormed = load(NS, 'instance/is-well-formed');
ok(typeof instanceIsWellFormed == 'function');
ok(instanceIsWellFormed({}) === undefined);
ok(typeof instanceIsWellFormed('') == 'function');
ok(instanceIsWellFormed('').call('a'));
const instanceLastIndexOf = load(NS, 'instance/last-index-of');
ok(typeof instanceLastIndexOf == 'function');
ok(instanceLastIndexOf({}) === undefined);
ok(typeof instanceLastIndexOf([]) == 'function');
ok(instanceLastIndexOf([]).call([1, 2, 3], 2) === 1);
const instanceMap = load(NS, 'instance/map');
ok(typeof instanceMap == 'function');
ok(instanceMap({}) === undefined);
ok(typeof instanceMap([]) == 'function');
ok(instanceMap([]).call([1, 2, 3], it => it % 2)[1] === 0);
const instanceMatchAll = load(NS, 'instance/match-all');
ok(typeof instanceMatchAll == 'function');
ok(instanceMatchAll({}) === undefined);
ok(typeof instanceMatchAll('') == 'function');
ok(instanceMatchAll('').call('test1test2', /(?<test>test\d)/g).next().value.groups.test === 'test1');
const instancePadEnd = load(NS, 'instance/pad-end');
ok(typeof instancePadEnd == 'function');
ok(instancePadEnd({}) === undefined);
ok(typeof instancePadEnd('') == 'function');
ok(instancePadEnd('').call('a', 3, 'b') === 'abb');
const instancePadStart = load(NS, 'instance/pad-start');
ok(typeof instancePadStart == 'function');
ok(instancePadStart({}) === undefined);
ok(typeof instancePadStart('') == 'function');
ok(instancePadStart('').call('a', 3, 'b') === 'bba');
const instancePush = load(NS, 'instance/push');
ok(typeof instancePush == 'function');
ok(instancePush({}) === undefined);
ok(typeof instancePush([]) == 'function');
ok(instancePush([]).call([1], 8) === 2);
const instanceReduceRight = load(NS, 'instance/reduce-right');
ok(typeof instanceReduceRight == 'function');
ok(instanceReduceRight({}) === undefined);
ok(typeof instanceReduceRight([]) == 'function');
ok(instanceReduceRight([]).call([1, 2, 3], (memo, it) => it + memo, '') === '123');
const instanceReduce = load(NS, 'instance/reduce');
ok(typeof instanceReduce == 'function');
ok(instanceReduce({}) === undefined);
ok(typeof instanceReduce([]) == 'function');
ok(instanceReduce([]).call([1, 2, 3], (memo, it) => it + memo, '') === '321');
const instanceRepeat = load(NS, 'instance/repeat');
ok(typeof instanceRepeat == 'function');
ok(instanceRepeat({}) === undefined);
ok(typeof instanceRepeat('') == 'function');
ok(instanceRepeat('').call('a', 3) === 'aaa');
const instanceReplaceAll = load(NS, 'instance/replace-all');
ok(typeof instanceReplaceAll == 'function');
ok(instanceReplaceAll({}) === undefined);
ok(typeof instanceReplaceAll('') == 'function');
ok(instanceReplaceAll('').call('aba', 'a', 'c') === 'cbc');
const instanceReverse = load(NS, 'instance/reverse');
ok(typeof instanceReverse == 'function');
ok(instanceReverse({}) === undefined);
ok(typeof instanceReverse([]) == 'function');
const instanceSlice = load(NS, 'instance/slice');
ok(typeof instanceSlice == 'function');
ok(instanceSlice({}) === undefined);
ok(typeof instanceSlice([]) == 'function');
const instanceSome = load(NS, 'instance/some');
ok(typeof instanceSome == 'function');
ok(instanceSome({}) === undefined);
ok(typeof instanceSome([]) == 'function');
ok(instanceSome([]).call([1, 2, 3], it => typeof it == 'number'));
const instanceSort = load(NS, 'instance/sort');
ok(typeof instanceSort == 'function');
ok(instanceSort({}) === undefined);
ok(typeof instanceSort([]) == 'function');
const instanceSplice = load(NS, 'instance/splice');
ok(typeof instanceSplice == 'function');
ok(instanceSplice({}) === undefined);
ok(typeof instanceSplice([]) == 'function');
const instanceStartsWith = load(NS, 'instance/starts-with');
ok(typeof instanceStartsWith == 'function');
ok(instanceStartsWith({}) === undefined);
ok(typeof instanceStartsWith('') == 'function');
ok(instanceStartsWith('').call('qwe', 'qw'));
const instanceToReversed = load(NS, 'instance/to-reversed');
ok(typeof instanceToReversed == 'function');
ok(instanceToReversed({}) === undefined);
ok(typeof instanceToReversed([]) == 'function');
ok(instanceToReversed([]).call([1, 2, 3])[0] === 3);
const instanceToSorted = load(NS, 'instance/to-sorted');
ok(typeof instanceToSorted == 'function');
ok(instanceToSorted({}) === undefined);
ok(typeof instanceToSorted([]) == 'function');
ok(instanceToSorted([]).call([3, 2, 1])[0] === 1);
const instanceToSpliced = load(NS, 'instance/to-spliced');
ok(typeof instanceToSpliced == 'function');
ok(instanceToSpliced({}) === undefined);
ok(typeof instanceToSpliced([]) == 'function');
ok(instanceToSpliced([]).call([3, 2, 1], 1, 1, 4, 5).length === 4);
const instanceToWellFormed = load(NS, 'instance/to-well-formed');
ok(typeof instanceToWellFormed == 'function');
ok(instanceToWellFormed({}) === undefined);
ok(typeof instanceToWellFormed('') == 'function');
ok(instanceToWellFormed('').call('a') === 'a');
const instanceTrimEnd = load(NS, 'instance/trim-end');
ok(typeof instanceTrimEnd == 'function');
ok(instanceTrimEnd({}) === undefined);
ok(typeof instanceTrimEnd('') == 'function');
ok(instanceTrimEnd('').call(' 1 ') === ' 1');
const instanceTrimLeft = load(NS, 'instance/trim-left');
ok(typeof instanceTrimLeft == 'function');
ok(instanceTrimLeft({}) === undefined);
ok(typeof instanceTrimLeft('') == 'function');
ok(instanceTrimLeft('').call(' 1 ') === '1 ');
const instanceTrimRight = load(NS, 'instance/trim-right');
ok(typeof instanceTrimRight == 'function');
ok(instanceTrimRight({}) === undefined);
ok(typeof instanceTrimRight('') == 'function');
ok(instanceTrimRight('').call(' 1 ') === ' 1');
const instanceTrimStart = load(NS, 'instance/trim-start');
ok(typeof instanceTrimStart == 'function');
ok(instanceTrimStart({}) === undefined);
ok(typeof instanceTrimStart('') == 'function');
ok(instanceTrimStart('').call(' 1 ') === '1 ');
const instanceTrim = load(NS, 'instance/trim');
ok(typeof instanceTrim == 'function');
ok(instanceTrim({}) === undefined);
ok(typeof instanceTrim('') == 'function');
ok(instanceTrim('').call(' 1 ') === '1');
const instanceUnshift = load(NS, 'instance/unshift');
ok(typeof instanceUnshift == 'function');
ok(instanceUnshift({}) === undefined);
ok(typeof instanceUnshift([]) == 'function');
const instanceUnshiftTestArray = [1];
ok(instanceUnshift([]).call(instanceUnshiftTestArray, 8));
ok(instanceUnshiftTestArray[0] === 8);
const instanceValues = load(NS, 'instance/values');
ok(typeof instanceValues == 'function');
ok(instanceValues({}) === undefined);
ok(typeof instanceValues([]) == 'function');
ok(instanceValues([]).call([1, 2, 3]).next().value === 1);
const instanceWith = load(NS, 'instance/with');
ok(typeof instanceWith == 'function');
ok(instanceWith({}) === undefined);
ok(typeof instanceWith([]) == 'function');
ok(instanceWith([]).call([1, 2, 3], 1, 4)[1] === 4);
}
for (const NS of ['stable', 'actual', 'full', 'features']) {
ok(load(NS, 'atob')('Zg==') === 'f');
ok(load(NS, 'btoa')('f') === 'Zg==');
ok(typeof load(NS, 'dom-exception/constructor') == 'function');
ok(load(NS, 'dom-exception/to-string-tag') === 'DOMException');
ok(typeof load(NS, 'dom-exception') == 'function');
ok(typeof load(NS, 'dom-collections').iterator == 'function');
ok(typeof load(NS, 'dom-collections/for-each') == 'function');
ok(typeof load(NS, 'dom-collections/iterator') == 'function');
ok(load(NS, 'self').Math === Math);
ok(typeof load(NS, 'set-timeout') == 'function');
ok(typeof load(NS, 'set-interval') == 'function');
ok(typeof load(NS, 'set-immediate') == 'function');
ok(load(NS, 'structured-clone')(42) === 42);
ok(typeof load(NS, 'clear-immediate') == 'function');
ok(typeof load(NS, 'queue-microtask') == 'function');
ok(typeof load(NS, 'url') == 'function');
ok(load(NS, 'url/can-parse')('a:b') === true);
ok(load(NS, 'url/parse')('a:b').href === 'a:b');
load(NS, 'url/to-json');
ok(typeof load(NS, 'url-search-params') == 'function');
}
for (const NS of ['actual', 'full', 'features']) {
ok(typeof load(NS, 'array/group') == 'function');
ok(typeof load(NS, 'array/group-to-map') == 'function');
ok(typeof load(NS, 'array/group-by') == 'function');
ok(typeof load(NS, 'array/group-by-to-map') == 'function');
ok(typeof load(NS, 'array/virtual/group') == 'function');
ok(typeof load(NS, 'array/virtual/group-to-map') == 'function');
ok(typeof load(NS, 'array/virtual/group-by') == 'function');
ok(typeof load(NS, 'array/virtual/group-by-to-map') == 'function');
ok(typeof load(NS, 'async-iterator') == 'function');
ok(typeof load(NS, 'async-iterator/drop') == 'function');
ok(typeof load(NS, 'async-iterator/every') == 'function');
ok(typeof load(NS, 'async-iterator/filter') == 'function');
ok(typeof load(NS, 'async-iterator/find') == 'function');
ok(typeof load(NS, 'async-iterator/flat-map') == 'function');
ok(typeof load(NS, 'async-iterator/for-each') == 'function');
ok(typeof load(NS, 'async-iterator/from') == 'function');
ok(typeof load(NS, 'async-iterator/map') == 'function');
ok(typeof load(NS, 'async-iterator/reduce') == 'function');
ok(typeof load(NS, 'async-iterator/some') == 'function');
ok(typeof load(NS, 'async-iterator/take') == 'function');
ok(typeof load(NS, 'async-iterator/to-array') == 'function');
ok(load(NS, 'function/metadata') === null);
ok(typeof load(NS, 'iterator/to-async') == 'function');
ok(typeof load(NS, 'iterator/zip') == 'function');
ok(typeof load(NS, 'iterator/zip-keyed') == 'function');
ok(load(NS, 'symbol/metadata'));
const instanceGroup = load(NS, 'instance/group');
ok(typeof instanceGroup == 'function');
ok(instanceGroup({}) === undefined);
ok(typeof instanceGroup([]) == 'function');
ok(instanceGroup([]).call([1, 2, 3], it => it % 2)[1].length === 2);
const instanceGroupToMap = load(NS, 'instance/group-to-map');
ok(typeof instanceGroupToMap == 'function');
ok(instanceGroupToMap({}) === undefined);
ok(typeof instanceGroupToMap([]) == 'function');
ok(instanceGroupToMap([]).call([1, 2, 3], it => it % 2).get(1).length === 2);
const instanceGroupBy = load(NS, 'instance/group-by');
ok(typeof instanceGroupBy == 'function');
ok(instanceGroupBy({}) === undefined);
ok(typeof instanceGroupBy([]) == 'function');
ok(instanceGroupBy([]).call([1, 2, 3], it => it % 2)[1].length === 2);
const instanceGroupByToMap = load(NS, 'instance/group-by-to-map');
ok(typeof instanceGroupByToMap == 'function');
ok(instanceGroupByToMap({}) === undefined);
ok(typeof instanceGroupByToMap([]) == 'function');
ok(instanceGroupByToMap([]).call([1, 2, 3], it => it % 2).get(1).length === 2);
}
for (const NS of ['full', 'features']) {
const Map = load(NS, 'map');
const Set = load(NS, 'set');
const WeakMap = load(NS, 'weak-map');
const WeakSet = load(NS, 'weak-set');
ok(typeof load(NS, 'array/filter-out') == 'function');
ok(typeof load(NS, 'array/filter-reject') == 'function');
ok(typeof load(NS, 'array/is-template-object') == 'function');
load(NS, 'array/last-item');
load(NS, 'array/last-index');
ok(typeof load(NS, 'array/unique-by') == 'function');
ok(typeof load(NS, 'array/virtual/filter-out') == 'function');
ok(typeof load(NS, 'array/virtual/filter-reject') == 'function');
ok(typeof load(NS, 'array/virtual/unique-by') == 'function');
ok(typeof load(NS, 'async-iterator/as-indexed-pairs') == 'function');
ok(typeof load(NS, 'async-iterator/indexed') == 'function');
load(NS, 'bigint/range');
load(NS, 'bigint');
load(NS, 'data-view/get-uint8-clamped');
load(NS, 'data-view/set-uint8-clamped');
ok(typeof load(NS, 'composite-key')({}, 1, {}) === 'object');
ok(typeof load(NS, 'composite-symbol')({}, 1, {}) === 'symbol');
ok(load(NS, 'function/demethodize')([].slice)([1, 2, 3], 1)[0] === 2);
ok(load(NS, 'function/virtual/demethodize').call([].slice)([1, 2, 3], 1)[0] === 2);
ok(!load(NS, 'function/is-callable')(class { /* empty */ }));
ok(!load(NS, 'function/is-constructor')(it => it));
ok(load(NS, 'function/un-this')([].slice)([1, 2, 3], 1)[0] === 2);
ok(load(NS, 'function/virtual/un-this').call([].slice)([1, 2, 3], 1)[0] === 2);
ok(typeof load(NS, 'iterator/as-indexed-pairs') == 'function');
ok(typeof load(NS, 'iterator/indexed') == 'function');
ok(load(NS, 'iterator/range')(1, 2).next().value === 1);
ok(typeof load(NS, 'iterator/chunks') == 'function');
ok(typeof load(NS, 'iterator/sliding') == 'function');
ok(typeof load(NS, 'iterator/windows') == 'function');
ok(load(NS, 'map/delete-all')(new Map(), 1, 2) === false);
ok(load(NS, 'map/emplace')(new Map([[1, 2]]), 1, { update: it => it ** 2 }) === 4);
ok(load(NS, 'map/every')(new Map([[1, 2], [2, 3], [3, 4]]), it => it % 2) === false);
ok(load(NS, 'map/filter')(new Map([[1, 2], [2, 3], [3, 4]]), it => it % 2).size === 1);
ok(load(NS, 'map/find')(new Map([[1, 2], [2, 3], [3, 4]]), it => it % 2) === 3);
ok(load(NS, 'map/find-key')(new Map([[1, 2], [2, 3], [3, 4]]), it => it % 2) === 2);
ok(load(NS, 'map/from')([[1, 2], [3, 4]]) instanceof Map);
ok(load(NS, 'map/includes')(new Map([[1, 2]]), 2), true);
ok(load(NS, 'map/key-by')([], it => it) instanceof Map);
ok(load(NS, 'map/key-of')(new Map([[1, 2]]), 2), 1);
ok(load(NS, 'map/map-keys')(new Map([[1, 2], [2, 3], [3, 4]]), it => it).size === 3);
ok(load(NS, 'map/map-values')(new Map([[1, 2], [2, 3], [3, 4]]), it => it).size === 3);
ok(load(NS, 'map/merge')(new Map([[1, 2], [2, 3]]), [[2, 4], [4, 5]]).size === 3);
ok(load(NS, 'map/update-or-insert')(new Map([[1, 2]]), 1, it => it ** 2, () => 42) === 4);
ok(load(NS, 'map/upsert')(new Map([[1, 2]]), 1, it => it ** 2, () => 42) === 4);
ok(load(NS, 'math/clamp')(6, 2, 4) === 4);
ok(load(NS, 'math/deg-per-rad') === Math.PI / 180);
ok(load(NS, 'math/degrees')(Math.PI) === 180);
ok(load(NS, 'math/fscale')(3, 1, 2, 1, 2) === 3);
ok(load(NS, 'math/iaddh')(3, 2, 0xFFFFFFFF, 4) === 7);
ok(load(NS, 'math/isubh')(3, 4, 0xFFFFFFFF, 2) === 1);
ok(load(NS, 'math/imulh')(0xFFFFFFFF, 7) === -1);
ok(load(NS, 'math/rad-per-deg') === 180 / Math.PI);
ok(load(NS, 'math/radians')(180) === Math.PI);
ok(load(NS, 'math/scale')(3, 1, 2, 1, 2) === 3);
ok(typeof load(NS, 'math/seeded-prng')({ seed: 42 }).next().value === 'number');
ok(load(NS, 'math/signbit')(-2) === true);
ok(load(NS, 'math/umulh')(0xFFFFFFFF, 7) === 6);
ok(load(NS, 'map/of')([1, 2], [3, 4]) instanceof Map);
ok(load(NS, 'map/reduce')(new Map([[1, 2], [2, 3], [3, 4]]), (a, b) => a + b) === 9);
ok(load(NS, 'map/some')(new Map([[1, 2], [2, 3], [3, 4]]), it => it % 2) === true);
ok(load(NS, 'map/update')(new Map([[1, 2]]), 1, it => it * 2).get(1) === 4);
ok(load(NS, 'number/clamp')(6, 2, 4) === 4);
ok(load(NS, 'number/virtual/clamp').call(6, 2, 4) === 4);
ok(load(NS, 'number/from-string')('12', 3) === 5);
ok(load(NS, 'number/range')(1, 2).next().value === 1);
ok(typeof load(NS, 'object/iterate-entries')({}).next == 'function');
ok(typeof load(NS, 'object/iterate-keys')({}).next == 'function');
ok(typeof load(NS, 'object/iterate-values')({}).next == 'function');
ok('from' in load(NS, 'observable'));
ok(typeof load(NS, 'reflect/define-metadata') == 'function');
ok(typeof load(NS, 'reflect/delete-metadata') == 'function');
ok(typeof load(NS, 'reflect/get-metadata') == 'function');
ok(typeof load(NS, 'reflect/get-metadata-keys') == 'function');
ok(typeof load(NS, 'reflect/get-own-metadata') == 'function');
ok(typeof load(NS, 'reflect/get-own-metadata-keys') == 'function');
ok(typeof load(NS, 'reflect/has-metadata') == 'function');
ok(typeof load(NS, 'reflect/has-own-metadata') == 'function');
ok(typeof load(NS, 'reflect/metadata') == 'function');
ok(load(NS, 'set/add-all')(new Set([1, 2, 3]), 4, 5).size === 5);
ok(load(NS, 'set/delete-all')(new Set([1, 2, 3]), 4, 5) === false);
ok(load(NS, 'set/every')(new Set([1, 2, 3]), it => typeof it == 'number'));
ok(load(NS, 'set/filter')(new Set([1, 2, 3]), it => it % 2).size === 2);
ok(load(NS, 'set/find')(new Set([2, 3, 4]), it => it % 2) === 3);
ok(load(NS, 'set/from')([1, 2, 3, 2, 1]) instanceof Set);
ok(load(NS, 'set/join')(new Set([1, 2, 3])) === '1,2,3');
ok(load(NS, 'set/map')(new Set([1, 2, 3]), it => it % 2).size === 2);
ok(load(NS, 'set/of')(1, 2, 3, 2, 1) instanceof Set);
ok(load(NS, 'set/reduce')(new Set([1, 2, 3]), (it, v) => it + v) === 6);
ok(load(NS, 'set/some')(new Set([1, 2, 3]), it => typeof it == 'number'));
ok(load(NS, 'string/cooked')`a${ 1 }b` === 'a1b');
ok(load(NS, 'string/dedent')`
a${ 1 }b
` === 'a1b');
ok('next' in load(NS, 'string/code-points')('a'));
ok('next' in load(NS, 'string/virtual/code-points').call('a'));
ok(load(NS, 'symbol/custom-matcher'));
ok(load(NS, 'symbol/is-registered-symbol')(1) === false);
ok(load(NS, 'symbol/is-well-known-symbol')(1) === false);
ok(load(NS, 'symbol/is-registered')(1) === false);
ok(load(NS, 'symbol/is-well-known')(1) === false);
ok(load(NS, 'symbol/matcher'));
ok(load(NS, 'symbol/metadata-key'));
ok(load(NS, 'symbol/observable'));
ok(load(NS, 'symbol/pattern-match'));
ok(load(NS, 'symbol/replace-all'));
ok(load(NS, 'weak-map/delete-all')(new WeakMap(), [], {}) === false);
ok(load(NS, 'weak-map/emplace')(new WeakMap(), {}, { insert: () => ({ a: 42 }) }).a === 42);
ok(load(NS, 'weak-map/upsert')(new WeakMap(), {}, null, () => 42) === 42);
ok(load(NS, 'weak-map/from')([[{}, 1], [[], 2]]) instanceof WeakMap);
ok(load(NS, 'weak-map/of')([{}, 1], [[], 2]) instanceof WeakMap);
ok(load(NS, 'weak-set/add-all')(new WeakSet(), [], {}) instanceof WeakSet);
ok(load(NS, 'weak-set/delete-all')(new WeakSet(), [], {}) === false);
ok(load(NS, 'weak-set/from')([{}, []]) instanceof WeakSet);
ok(load(NS, 'weak-set/of')({}, []) instanceof WeakSet);
const instanceClamp = load(NS, 'instance/clamp');
ok(typeof instanceClamp == 'function');
ok(instanceClamp({}) === undefined);
ok(typeof instanceClamp(6) == 'function');
ok(instanceClamp(6).call(6, 2, 4) === 4);
const instanceCodePoints = load(NS, 'instance/code-points');
ok(typeof instanceCodePoints == 'function');
ok(instanceCodePoints({}) === undefined);
ok(typeof instanceCodePoints('') == 'function');
ok(instanceCodePoints('').call('abc').next().value.codePoint === 97);
const instanceDemethodize = load(NS, 'instance/demethodize');
ok(typeof instanceDemethodize == 'function');
ok(instanceDemethodize({}) === undefined);
ok(typeof instanceDemethodize([].slice) == 'function');
ok(instanceDemethodize([].slice).call([].slice)([1, 2, 3], 1)[0] === 2);
const instanceFilterOut = load(NS, 'instance/filter-out');
ok(typeof instanceFilterOut == 'function');
ok(instanceFilterOut({}) === undefined);
ok(typeof instanceFilterOut([]) == 'function');
ok(instanceFilterOut([]).call([1, 2, 3], it => it % 2).length === 1);
const instanceFilterReject = load(NS, 'instance/filter-reject');
ok(typeof instanceFilterReject == 'function');
ok(instanceFilterReject({}) === undefined);
ok(typeof instanceFilterReject([]) == 'function');
ok(instanceFilterReject([]).call([1, 2, 3], it => it % 2).length === 1);
const instanceUniqueBy = load(NS, 'instance/unique-by');
ok(typeof instanceUniqueBy == 'function');
ok(instanceUniqueBy({}) === undefined);
ok(typeof instanceUniqueBy([]) == 'function');
ok(instanceUniqueBy([]).call([1, 2, 3, 2, 1]).length === 3);
const instanceUnThis = load(NS, 'instance/un-this');
ok(typeof instanceUnThis == 'function');
ok(instanceUnThis({}) === undefined);
ok(typeof instanceUnThis([].slice) == 'function');
ok(instanceUnThis([].slice).call([].slice)([1, 2, 3], 1)[0] === 2);
}
load('proposals/accessible-object-hasownproperty');
load('proposals/array-filtering');
load('proposals/array-filtering-stage-1');
load('proposals/array-find-from-last');
load('proposals/array-flat-map');
load('proposals/array-from-async');
load('proposals/array-from-async-stage-2');
load('proposals/array-grouping');
load('proposals/array-grouping-stage-3');
load('proposals/array-grouping-stage-3-2');
load('proposals/array-grouping-v2');
load('proposals/array-includes');
load('proposals/array-is-template-object');
load('proposals/array-last');
load('proposals/array-unique');
load('proposals/array-buffer-base64');
load('proposals/array-buffer-transfer');
load('proposals/async-explicit-resource-management');
load('proposals/async-iteration');
load('proposals/async-iterator-helpers');
load('proposals/change-array-by-copy');
load('proposals/change-array-by-copy-stage-4');
load('proposals/collection-methods');
load('proposals/collection-of-from');
load('proposals/data-view-get-set-uint8-clamped');
load('proposals/decorator-metadata');
load('proposals/decorator-metadata-v2');
load('proposals/decorators');
load('proposals/efficient-64-bit-arithmetic');
load('proposals/error-cause');
load('proposals/explicit-resource-management');
load('proposals/extractors');
load('proposals/float16');
load('proposals/function-demethodize');
load('proposals/function-is-callable-is-constructor');
load('proposals/function-un-this');
load('proposals/global-this');
load('proposals/is-error');
load('proposals/iterator-helpers');
load('proposals/iterator-helpers-stage-3');
load('proposals/iterator-helpers-stage-3-2');
load('proposals/iterator-range');
load('proposals/iterator-sequencing');
load('proposals/iterator-chunking');
load('proposals/iterator-chunking-v2');
load('proposals/joint-iteration');
load('proposals/json-parse-with-source');
load('proposals/keys-composition');
load('proposals/map-update-or-insert');
load('proposals/map-upsert');
load('proposals/map-upsert-stage-2');
load('proposals/map-upsert-v4');
load('proposals/math-clamp');
load('proposals/math-clamp-v2');
load('proposals/math-extensions');
load('proposals/math-signbit');
load('proposals/math-sum');
load('proposals/number-from-string');
load('proposals/number-range');
load('proposals/object-from-entries');
load('proposals/object-iteration');
load('proposals/object-getownpropertydescriptors');
load('proposals/object-values-entries');
load('proposals/observable');
load('proposals/pattern-matching');
load('proposals/pattern-matching-v2');
load('proposals/promise-all-settled');
load('proposals/promise-any');
load('proposals/promise-finally');
load('proposals/promise-try');
load('proposals/promise-with-resolvers');
load('proposals/reflect-metadata');
load('proposals/regexp-dotall-flag');
load('proposals/regexp-escaping');
load('proposals/regexp-named-groups');
load('proposals/relative-indexing-method');
load('proposals/seeded-random');
load('proposals/set-methods');
load('proposals/set-methods-v2');
load('proposals/string-at');
load('proposals/string-cooked');
load('proposals/string-code-points');
load('proposals/string-dedent');
load('proposals/string-left-right-trim');
load('proposals/string-match-all');
load('proposals/string-padding');
load('proposals/string-replace-all');
load('proposals/string-replace-all-stage-4');
load('proposals/symbol-description');
load('proposals/symbol-predicates');
load('proposals/symbol-predicates-v2');
load('proposals/url');
load('proposals/using-statement');
load('proposals/well-formed-stringify');
load('proposals/well-formed-unicode-strings');
load('proposals');
ok(load('stage/4'));
ok(load('stage/3'));
ok(load('stage/2.7'));
ok(load('stage/2'));
ok(load('stage/1'));
ok(load('stage/0'));
ok(load('stage/pre'));
ok(load('stage'));
ok(load('web/dom-exception'));
ok(load('web/dom-collections'));
ok(load('web/immediate'));
ok(load('web/queue-microtask'));
ok(load('web/structured-clone')(42) === 42);
ok(load('web/timers'));
ok(load('web/url'));
ok(load('web/url-search-params'));
ok(load('web'));
for (const key in entries) {
if (key.startsWith('core-js/modules/')) {
load('modules', key.slice(16));
}
}
ok(load());
}
for (const NS of ['es', 'stable', 'actual', 'full', 'features']) {
ok(typeof load(NS, 'string/match') == 'function');
ok('next' in load(NS, 'string/match-all')('a', /./g));
ok(typeof load(NS, 'string/replace') == 'function');
ok(typeof load(NS, 'string/search') == 'function');
ok(load(NS, 'string/split')('a s d', ' ').length === 3);
ok(typeof load(NS, 'array-buffer') == 'function');
ok(typeof load(NS, 'array-buffer/constructor') == 'function');
ok(typeof load(NS, 'array-buffer/is-view') == 'function');
load(NS, 'array-buffer/slice');
load(NS, 'array-buffer/detached');
load(NS, 'array-buffer/transfer');
load(NS, 'array-buffer/transfer-to-fixed-length');
ok(typeof load(NS, 'data-view') == 'function');
load(NS, 'data-view/get-float16');
load(NS, 'data-view/set-float16');
ok(typeof load(NS, 'typed-array/int8-array') == 'function');
ok(typeof load(NS, 'typed-array/uint8-array') == 'function');
ok(typeof load(NS, 'typed-array/uint8-clamped-array') == 'function');
ok(typeof load(NS, 'typed-array/int16-array') == 'function');
ok(typeof load(NS, 'typed-array/uint16-array') == 'function');
ok(typeof load(NS, 'typed-array/int32-array') == 'function');
ok(typeof load(NS, 'typed-array/uint32-array') == 'function');
ok(typeof load(NS, 'typed-array/float32-array') == 'function');
ok(typeof load(NS, 'typed-array/float64-array') == 'function');
load(NS, 'typed-array/at');
load(NS, 'typed-array/copy-within');
load(NS, 'typed-array/entries');
load(NS, 'typed-array/every');
load(NS, 'typed-array/fill');
load(NS, 'typed-array/filter');
load(NS, 'typed-array/find');
load(NS, 'typed-array/find-index');
load(NS, 'typed-array/find-last');
load(NS, 'typed-array/find-last-index');
load(NS, 'typed-array/for-each');
load(NS, 'typed-array/from');
load(NS, 'typed-array/from-base64');
load(NS, 'typed-array/from-hex');
load(NS, 'typed-array/includes');
load(NS, 'typed-array/index-of');
load(NS, 'typed-array/iterator');
load(NS, 'typed-array/join');
load(NS, 'typed-array/keys');
load(NS, 'typed-array/last-index-of');
load(NS, 'typed-array/map');
load(NS, 'typed-array/of');
load(NS, 'typed-array/reduce');
load(NS, 'typed-array/reduce-right');
load(NS, 'typed-array/reverse');
load(NS, 'typed-array/set');
load(NS, 'typed-array/set-from-base64');
load(NS, 'typed-array/set-from-hex');
load(NS, 'typed-array/slice');
load(NS, 'typed-array/some');
load(NS, 'typed-array/sort');
load(NS, 'typed-array/subarray');
load(NS, 'typed-array/to-base64');
load(NS, 'typed-array/to-hex');
load(NS, 'typed-array/to-locale-string');
load(NS, 'typed-array/to-reversed');
load(NS, 'typed-array/to-sorted');
load(NS, 'typed-array/to-string');
load(NS, 'typed-array/values');
load(NS, 'typed-array/with');
load(NS, 'typed-array/methods');
ok(typeof load(NS, 'typed-array').Uint32Array == 'function');
}
for (const NS of ['actual', 'full', 'features']) {
load(NS, 'typed-array/to-spliced');
}
for (const NS of ['full', 'features']) {
load(NS, 'typed-array/from-async');
load(NS, 'typed-array/filter-out');
load(NS, 'typed-array/filter-reject');
load(NS, 'typed-array/group-by');
load(NS, 'typed-array/unique-by');
}
load('modules/esnext.string.at-alternative');
echo(chalk.green(`tested ${ chalk.cyan(tested.size) } commonjs entry points`));
if (expected.size) {
echo(chalk.red('not tested entries:'));
expected.forEach(it => echo(chalk.cyan(it)));
}
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/eslint/eslint.config.js
|
JavaScript
|
import globals from 'globals';
import confusingBrowserGlobals from 'confusing-browser-globals';
import parserJSONC from 'jsonc-eslint-parser';
import pluginArrayFunc from 'eslint-plugin-array-func';
import pluginASCII from 'eslint-plugin-ascii';
import pluginDepend from 'eslint-plugin-depend';
import pluginESX from 'eslint-plugin-es-x';
import pluginESlintComments from '@eslint-community/eslint-plugin-eslint-comments';
import pluginImport from 'eslint-plugin-import-x';
import pluginJSONC from 'eslint-plugin-jsonc';
import pluginMarkdown from '@eslint/markdown';
import pluginMath from 'eslint-plugin-math';
import pluginN from 'eslint-plugin-n';
import pluginName from 'eslint-plugin-name';
import pluginNodeDependencies from 'eslint-plugin-node-dependencies';
import * as pluginPackageJSON from 'eslint-plugin-package-json';
import pluginPlaywright from 'eslint-plugin-playwright';
import pluginPromise from 'eslint-plugin-promise';
import pluginQUnit from 'eslint-plugin-qunit';
import pluginReDoS from 'eslint-plugin-redos';
import pluginRegExp from 'eslint-plugin-regexp';
import pluginSonarJS from 'eslint-plugin-sonarjs';
import pluginStylistic from '@stylistic/eslint-plugin';
import pluginUnicorn from 'eslint-plugin-unicorn';
import { yaml as pluginYaml } from 'eslint-yaml';
const PACKAGES_NODE_VERSIONS = '8.9.0';
const DEV_NODE_VERSIONS = '^20.19';
const ERROR = 'error';
const OFF = 'off';
const ALWAYS = 'always';
const NEVER = 'never';
const READONLY = 'readonly';
function disable(rules) {
return Object.fromEntries(Object.keys(rules).map(key => [key, OFF]));
}
const base = {
// possible problems:
// enforces return statements in callbacks of array's methods
'array-callback-return': ERROR,
// require `super()` calls in constructors
'constructor-super': ERROR,
// enforce 'for' loop update clause moving the counter in the right direction
'for-direction': ERROR,
// disallow using an async function as a `Promise` executor
'no-async-promise-executor': ERROR,
// disallow reassigning class members
'no-class-assign': ERROR,
// disallow comparing against -0
'no-compare-neg-zero': ERROR,
// disallow reassigning `const` variables
'no-const-assign': ERROR,
// disallows expressions where the operation doesn't affect the value
'no-constant-binary-expression': ERROR,
// disallow constant expressions in conditions
'no-constant-condition': [ERROR, { checkLoops: false }],
// disallow returning value from constructor
'no-constructor-return': ERROR,
// disallow use of debugger
'no-debugger': ERROR,
// disallow duplicate arguments in functions
'no-dupe-args': ERROR,
// disallow duplicate class members
'no-dupe-class-members': ERROR,
// disallow duplicate conditions in if-else-if chains
'no-dupe-else-if': ERROR,
// disallow duplicate keys when creating object literals
'no-dupe-keys': ERROR,
// disallow a duplicate case label
'no-duplicate-case': ERROR,
// disallow duplicate module imports
'no-duplicate-imports': ERROR,
// disallow empty destructuring patterns
'no-empty-pattern': ERROR,
// disallow assigning to the exception in a catch block
'no-ex-assign': ERROR,
// disallow fallthrough of case statements
'no-fallthrough': [ERROR, { commentPattern: 'break omitted' }],
// disallow overwriting functions written as function declarations
'no-func-assign': ERROR,
// disallow assigning to imported bindings
'no-import-assign': ERROR,
// disallow irregular whitespace outside of strings and comments
'no-irregular-whitespace': ERROR,
// disallow literal numbers that lose precision
'no-loss-of-precision': ERROR,
// disallow `new` operators with global non-constructor functions
'no-new-native-nonconstructor': ERROR,
// disallow the use of object properties of the global object (Math and JSON) as functions
'no-obj-calls': ERROR,
// disallow use of Object.prototypes builtins directly
'no-prototype-builtins': ERROR,
// disallow self assignment
'no-self-assign': ERROR,
// disallow comparisons where both sides are exactly the same
'no-self-compare': ERROR,
// disallow sparse arrays
'no-sparse-arrays': ERROR,
// disallow template literal placeholder syntax in regular strings
'no-template-curly-in-string': ERROR,
// disallow `this` / `super` before calling `super()` in constructors
'no-this-before-super': ERROR,
// disallow `let` or `var` variables that are read but never assigned
'no-unassigned-vars': ERROR,
// disallow use of undeclared variables unless mentioned in a /*global */ block
'no-undef': [ERROR, { typeof: false }],
// avoid code that looks like two expressions but is actually one
'no-unexpected-multiline': ERROR,
// disallow unmodified loop conditions
'no-unmodified-loop-condition': ERROR,
// disallow unreachable statements after a return, throw, continue, or break statement
'no-unreachable': ERROR,
// disallow loops with a body that allows only one iteration
'no-unreachable-loop': ERROR,
// disallow control flow statements in `finally` blocks
'no-unsafe-finally': ERROR,
// disallow negation of the left operand of an in expression
'no-unsafe-negation': ERROR,
// disallow use of optional chaining in contexts where the `undefined` value is not allowed
'no-unsafe-optional-chaining': ERROR,
// disallow unused private class members
'no-unused-private-class-members': ERROR,
// disallow declaration of variables that are not used in the code
'no-unused-vars': [ERROR, {
vars: 'all',
args: 'after-used',
caughtErrors: 'none',
ignoreRestSiblings: true,
}],
// disallow variable assignments when the value is not used
'no-useless-assignment': ERROR,
// require or disallow the Unicode Byte Order Mark
'unicode-bom': [ERROR, NEVER],
// disallow comparisons with the value NaN
'use-isnan': ERROR,
// ensure that the results of typeof are compared against a valid string
'valid-typeof': ERROR,
// suggestions:
// enforce the use of variables within the scope they are defined
'block-scoped-var': ERROR,
// require camel case names
camelcase: [ERROR, {
properties: NEVER,
ignoreDestructuring: true,
ignoreImports: true,
ignoreGlobals: true,
}],
// enforce default clauses in switch statements to be last
'default-case-last': ERROR,
// enforce default parameters to be last
'default-param-last': ERROR,
// encourages use of dot notation whenever possible
'dot-notation': [ERROR, { allowKeywords: true }],
// require the use of === and !==
eqeqeq: [ERROR, 'smart'],
// require grouped accessor pairs in object literals and classes
'grouped-accessor-pairs': [ERROR, 'getBeforeSet'],
// require identifiers to match a specified regular expression
'id-match': [ERROR, '^[$A-Za-z]|(?:[A-Z][A-Z\\d_]*[A-Z\\d])|(?:[$A-Za-z]\\w*[A-Za-z\\d])$', {
onlyDeclarations: true,
ignoreDestructuring: true,
}],
// require logical assignment operator shorthand
'logical-assignment-operators': [ERROR, ALWAYS],
// enforce a maximum depth that blocks can be nested
'max-depth': [ERROR, { max: 5 }],
// enforce a maximum depth that callbacks can be nested
'max-nested-callbacks': [ERROR, { max: 4 }],
// specify the maximum number of statement allowed in a function
'max-statements': [ERROR, { max: 50 }],
// require a capital letter for constructors
'new-cap': [ERROR, { newIsCap: true, capIsNew: false }],
// disallow window alert / confirm / prompt calls
'no-alert': ERROR,
// disallow use of arguments.caller or arguments.callee
'no-caller': ERROR,
// disallow lexical declarations in case/default clauses
'no-case-declarations': ERROR,
// disallow use of console
'no-console': ERROR,
// disallow deletion of variables
'no-delete-var': ERROR,
// disallow else after a return in an if
'no-else-return': [ERROR, { allowElseIf: false }],
// disallow empty statements
'no-empty': ERROR,
// disallow empty functions, except for standalone funcs/arrows
'no-empty-function': ERROR,
// disallow empty static blocks
'no-empty-static-block': ERROR,
// disallow `null` comparisons without type-checking operators
'no-eq-null': ERROR,
// disallow use of eval()
'no-eval': ERROR,
// disallow adding to native types
'no-extend-native': ERROR,
// disallow unnecessary function binding
'no-extra-bind': ERROR,
// disallow unnecessary boolean casts
'no-extra-boolean-cast': [ERROR, { enforceForInnerExpressions: true }],
// disallow unnecessary labels
'no-extra-label': ERROR,
// disallow reassignments of native objects
'no-global-assign': ERROR,
// disallow use of eval()-like methods
'no-implied-eval': ERROR,
// disallow usage of __iterator__ property
'no-iterator': ERROR,
// disallow labels that share a name with a variable
'no-label-var': ERROR,
// disallow use of labels for anything other then loops and switches
'no-labels': [ERROR, { allowLoop: false, allowSwitch: false }],
// disallow unnecessary nested blocks
'no-lone-blocks': ERROR,
// disallow `if` as the only statement in an `else` block
'no-lonely-if': ERROR,
// disallow function declarations and expressions inside loop statements
'no-loop-func': OFF,
// disallow use of multiline strings
'no-multi-str': ERROR,
// disallow use of new operator when not part of the assignment or comparison
'no-new': ERROR,
// disallow use of new operator for Function object
'no-new-func': ERROR,
// disallows creating new instances of String, Number, and Boolean
'no-new-wrappers': ERROR,
// disallow `\8` and `\9` escape sequences in string literals
'no-nonoctal-decimal-escape': ERROR,
// disallow calls to the `Object` constructor without an argument
'no-object-constructor': ERROR,
// disallow use of (old style) octal literals
'no-octal': ERROR,
// disallow use of octal escape sequences in string literals, such as var foo = 'Copyright \251';
'no-octal-escape': ERROR,
// disallow usage of __proto__ property
'no-proto': ERROR,
// disallow declaring the same variable more then once
'no-redeclare': [ERROR, { builtinGlobals: false }],
// disallow specific global variables
'no-restricted-globals': [ERROR, ...confusingBrowserGlobals],
// disallow specified syntax
'no-restricted-syntax': [ERROR,
{
selector: 'ForInStatement',
message: '`for-in` loops are disallowed since iterate over the prototype chain',
},
],
// disallow use of `javascript:` urls.
'no-script-url': ERROR,
// disallow use of comma operator
'no-sequences': ERROR,
// disallow declaration of variables already declared in the outer scope
'no-shadow': ERROR,
// disallow shadowing of names such as arguments
'no-shadow-restricted-names': [ERROR, { reportGlobalThis: false }],
// restrict what can be thrown as an exception
'no-throw-literal': ERROR,
// disallow initializing variables to `undefined`
'no-undef-init': ERROR,
// disallow dangling underscores in identifiers
'no-underscore-dangle': ERROR,
// disallow the use of boolean literals in conditional expressions and prefer `a || b` over `a ? a : b`
'no-unneeded-ternary': [ERROR, { defaultAssignment: false }],
// disallow usage of expressions in statement position
'no-unused-expressions': [ERROR, {
allowShortCircuit: true,
allowTernary: true,
allowTaggedTemplates: true,
ignoreDirectives: true,
}],
// disallow unused labels
'no-unused-labels': ERROR,
// disallow unnecessary calls to `.call()` and `.apply()`
'no-useless-call': ERROR,
// disallow unnecessary catch clauses
'no-useless-catch': ERROR,
// disallow unnecessary computed property keys in object literals
'no-useless-computed-key': ERROR,
// disallow useless string concatenation
'no-useless-concat': ERROR,
// disallow unnecessary constructors
'no-useless-constructor': ERROR,
// disallow unnecessary escape characters
'no-useless-escape': ERROR,
// disallow renaming import, export, and destructured assignments to the same name
'no-useless-rename': ERROR,
// disallow redundant return statements
'no-useless-return': ERROR,
// require let or const instead of var
'no-var': ERROR,
// disallow void operators
'no-void': ERROR,
// disallow use of the with statement
'no-with': ERROR,
// require or disallow method and property shorthand syntax for object literals
'object-shorthand': ERROR,
// require assignment operator shorthand where possible
'operator-assignment': [ERROR, 'always'],
// require using arrow functions for callbacks
'prefer-arrow-callback': ERROR,
// require const declarations for variables that are never reassigned after declared
'prefer-const': [ERROR, { destructuring: 'all' }],
// require destructuring from arrays and/or objects
'prefer-destructuring': [ERROR, {
VariableDeclarator: {
array: true,
object: true,
},
AssignmentExpression: {
array: true,
object: false,
},
}, {
enforceForRenamedProperties: false,
}],
// prefer the exponentiation operator over `Math.pow()`
'prefer-exponentiation-operator': ERROR,
// disallow `parseInt()` and `Number.parseInt()` in favor of binary, octal, and hexadecimal literals
'prefer-numeric-literals': ERROR,
// prefer `Object.hasOwn`
'prefer-object-has-own': ERROR,
// disallow use of the `RegExp` constructor in favor of regular expression literals
'prefer-regex-literals': [ERROR, { disallowRedundantWrapping: true }],
// require rest parameters instead of `arguments`
'prefer-rest-params': ERROR,
// require spread operators instead of `.apply()`
'prefer-spread': ERROR,
// require template literals instead of string concatenation
'prefer-template': ERROR,
// require use of the second argument for parseInt()
radix: ERROR,
// disallow generator functions that do not have `yield`
'require-yield': ERROR,
// require strict mode directives
strict: [ERROR, 'global'],
// require symbol descriptions
'symbol-description': ERROR,
// disallow "Yoda" conditions
yoda: [ERROR, NEVER],
// layout & formatting:
// enforce spacing inside array brackets
'@stylistic/array-bracket-spacing': [ERROR, NEVER],
// require parentheses around arrow function arguments
'@stylistic/arrow-parens': [ERROR, 'as-needed'],
// enforce consistent spacing before and after the arrow in arrow functions
'@stylistic/arrow-spacing': ERROR,
// enforce spacing inside single-line blocks
'@stylistic/block-spacing': [ERROR, ALWAYS],
// enforce one true brace style
'@stylistic/brace-style': [ERROR, '1tbs', { allowSingleLine: true }],
// enforce trailing commas in multiline object literals
'@stylistic/comma-dangle': [ERROR, 'always-multiline'],
// enforce spacing after comma
'@stylistic/comma-spacing': ERROR,
// enforce one true comma style
'@stylistic/comma-style': [ERROR, 'last'],
// disallow padding inside computed properties
'@stylistic/computed-property-spacing': [ERROR, NEVER],
// enforce consistent line breaks after opening and before closing braces
'@stylistic/curly-newline': [ERROR, { consistent: true }],
// enforce newline before and after dot
'@stylistic/dot-location': [ERROR, 'property'],
// enforce one newline at the end of files
'@stylistic/eol-last': [ERROR, ALWAYS],
// disallow space between function identifier and application
'@stylistic/function-call-spacing': ERROR,
// require spacing around the `*` in `function *` expressions
'@stylistic/generator-star-spacing': [ERROR, 'both'],
// enforce the location of arrow function bodies
'@stylistic/implicit-arrow-linebreak': [ERROR, 'beside'],
// enforce consistent indentation
'@stylistic/indent': [ERROR, 2, {
ignoredNodes: ['ConditionalExpression'],
SwitchCase: 1,
VariableDeclarator: 'first',
}],
// enforces spacing between keys and values in object literal properties
'@stylistic/key-spacing': [ERROR, { beforeColon: false, afterColon: true }],
// require a space before & after certain keywords
'@stylistic/keyword-spacing': [ERROR, { before: true, after: true }],
// enforce consistent linebreak style
'@stylistic/linebreak-style': [ERROR, 'unix'],
// specify the maximum length of a line in your program
'@stylistic/max-len': [ERROR, {
code: 140,
tabWidth: 2,
ignoreRegExpLiterals: true,
ignoreTemplateLiterals: true,
ignoreUrls: true,
ignorePattern: '<svg[\\s\\S]*?</svg>',
}],
// enforce a maximum number of statements allowed per line
'@stylistic/max-statements-per-line': [ERROR, { max: 2 }],
// require parentheses when invoking a constructor with no arguments
'@stylistic/new-parens': ERROR,
// disallow unnecessary parentheses
'@stylistic/no-extra-parens': [ERROR, 'all', {
nestedBinaryExpressions: false,
nestedConditionalExpressions: false,
ternaryOperandBinaryExpressions: false,
}],
// disallow unnecessary semicolons
'@stylistic/no-extra-semi': ERROR,
// disallow the use of leading or trailing decimal points in numeric literals
'@stylistic/no-floating-decimal': ERROR,
// disallow mixed spaces and tabs for indentation
'@stylistic/no-mixed-spaces-and-tabs': ERROR,
// disallow use of multiple spaces
'@stylistic/no-multi-spaces': [ERROR, { ignoreEOLComments: true }],
// disallow multiple empty lines and only one newline at the end
'@stylistic/no-multiple-empty-lines': [ERROR, { max: 1, maxEOF: 1 }],
// disallow tabs
'@stylistic/no-tabs': ERROR,
// disallow trailing whitespace at the end of lines
'@stylistic/no-trailing-spaces': ERROR,
// disallow whitespace before properties
'@stylistic/no-whitespace-before-property': ERROR,
// enforce the location of single-line statements
'@stylistic/nonblock-statement-body-position': [ERROR, 'beside'],
// enforce consistent line breaks after opening and before closing braces
'@stylistic/object-curly-newline': [ERROR, { consistent: true }],
// enforce spaces inside braces
'@stylistic/object-curly-spacing': [ERROR, ALWAYS],
// require newlines around variable declarations with initializations
'@stylistic/one-var-declaration-per-line': [ERROR, 'initializations'],
// enforce padding within blocks
'@stylistic/padded-blocks': [ERROR, NEVER],
// disallow blank lines after 'use strict'
'@stylistic/padding-line-between-statements': [ERROR, { blankLine: NEVER, prev: 'directive', next: '*' }],
// require or disallow use of quotes around object literal property names
'@stylistic/quote-props': [ERROR, 'as-needed', { keywords: false }],
// specify whether double or single quotes should be used
'@stylistic/quotes': [ERROR, 'single', { avoidEscape: true }],
// enforce spacing between rest and spread operators and their expressions
'@stylistic/rest-spread-spacing': ERROR,
// require or disallow use of semicolons instead of ASI
'@stylistic/semi': [ERROR, ALWAYS],
// enforce spacing before and after semicolons
'@stylistic/semi-spacing': ERROR,
// enforce location of semicolons
'@stylistic/semi-style': [ERROR, 'last'],
// require or disallow space before blocks
'@stylistic/space-before-blocks': ERROR,
// require or disallow space before function opening parenthesis
'@stylistic/space-before-function-paren': [ERROR, { anonymous: ALWAYS, named: NEVER }],
// require or disallow spaces inside parentheses
'@stylistic/space-in-parens': ERROR,
// require spaces around operators
'@stylistic/space-infix-ops': ERROR,
// require or disallow spaces before/after unary operators
'@stylistic/space-unary-ops': ERROR,
// require or disallow a space immediately following the // or /* in a comment
'@stylistic/spaced-comment': [ERROR, ALWAYS, {
line: { exceptions: ['/'] },
block: { exceptions: ['*'] },
}],
// enforce spacing around colons of switch statements
'@stylistic/switch-colon-spacing': ERROR,
// require or disallow spacing around embedded expressions of template strings
'@stylistic/template-curly-spacing': [ERROR, ALWAYS],
// disallow spacing between template tags and their literals
'@stylistic/template-tag-spacing': [ERROR, NEVER],
// require spacing around the `*` in `yield *` expressions
'@stylistic/yield-star-spacing': [ERROR, 'both'],
// ascii
// forbid non-ascii chars in ast node names
'ascii/valid-name': ERROR,
// import:
// forbid any invalid exports, i.e. re-export of the same name
'import/export': ERROR,
// ensure all imports appear before other statements
'import/first': ERROR,
// enforce a newline after import statements
'import/newline-after-import': ERROR,
// forbid import of modules using absolute paths
'import/no-absolute-path': ERROR,
// forbid AMD imports
'import/no-amd': ERROR,
// forbid cycle dependencies
'import/no-cycle': [ERROR, { commonjs: true }],
// disallow importing from the same path more than once
'import/no-duplicates': ERROR,
// forbid `require()` calls with expressions
'import/no-dynamic-require': ERROR,
// forbid empty named import blocks
'import/no-empty-named-blocks': ERROR,
// forbid imports with CommonJS exports
'import/no-import-module-exports': ERROR,
// forbid a module from importing itself
'import/no-self-import': ERROR,
// ensure imports point to files / modules that can be resolved
'import/no-unresolved': [ERROR, { commonjs: true }],
// forbid useless path segments
'import/no-useless-path-segments': ERROR,
// forbid Webpack loader syntax in imports
'import/no-webpack-loader-syntax': ERROR,
// node:
// enforce the style of file extensions in `import` declarations
'node/file-extension-in-import': ERROR,
// require require() calls to be placed at top-level module scope
'node/global-require': ERROR,
// disallow deprecated APIs
'node/no-deprecated-api': ERROR,
// disallow the assignment to `exports`
'node/no-exports-assign': ERROR,
// disallow require calls to be mixed with regular variable declarations
'node/no-mixed-requires': [ERROR, { grouping: true, allowCall: false }],
// disallow new operators with calls to require
'node/no-new-require': ERROR,
// disallow string concatenation with `__dirname` and `__filename`
'node/no-path-concat': ERROR,
// disallow the use of `process.exit()`
'node/no-process-exit': ERROR,
// disallow synchronous methods
'node/no-sync': ERROR,
// prefer `node:` protocol
'node/prefer-node-protocol': ERROR,
// prefer global
'node/prefer-global/buffer': [ERROR, ALWAYS],
'node/prefer-global/console': [ERROR, ALWAYS],
'node/prefer-global/crypto': [ERROR, ALWAYS],
'node/prefer-global/process': [ERROR, ALWAYS],
'node/prefer-global/text-decoder': [ERROR, ALWAYS],
'node/prefer-global/text-encoder': [ERROR, ALWAYS],
'node/prefer-global/timers': [ERROR, ALWAYS],
'node/prefer-global/url-search-params': [ERROR, ALWAYS],
'node/prefer-global/url': [ERROR, ALWAYS],
// prefer promises
'node/prefer-promises/dns': ERROR,
'node/prefer-promises/fs': ERROR,
// array-func:
// avoid reversing the array and running a method on it if there is an equivalent of the method operating on the array from the other end
'array-func/avoid-reverse': ERROR,
// prefer using the `mapFn` callback of `Array.from` over an immediate `.map()` call on the `Array.from` result
'array-func/from-map': ERROR,
// avoid the `this` parameter when providing arrow function as callback in array functions
'array-func/no-unnecessary-this-arg': ERROR,
// promise:
// enforces the use of `catch()` on un-returned promises
'promise/catch-or-return': ERROR,
// avoid calling `cb()` inside of a `then()` or `catch()`
'promise/no-callback-in-promise': ERROR,
// disallow creating new promises with paths that resolve multiple times
'promise/no-multiple-resolved': ERROR,
// avoid nested `then()` or `catch()` statements
'promise/no-nesting': ERROR,
// avoid calling new on a `Promise` static method
'promise/no-new-statics': ERROR,
// avoid using promises inside of callbacks
'promise/no-promise-in-callback': ERROR,
// disallow return statements in `finally()`
'promise/no-return-in-finally': ERROR,
// avoid wrapping values in `Promise.resolve` or `Promise.reject` when not needed
'promise/no-return-wrap': ERROR,
// enforce consistent param names when creating new promises
'promise/param-names': [ERROR, {
resolvePattern: '^resolve',
rejectPattern: '^reject',
}],
// prefer `async` / `await` to the callback pattern
'promise/prefer-await-to-callbacks': ERROR,
// prefer `await` to `then()` / `catch()` / `finally()` for reading `Promise` values
'promise/prefer-await-to-then': [ERROR, { strict: true }],
// prefer catch to `then(a, b)` / `then(null, b)` for handling errors
'promise/prefer-catch': ERROR,
// disallow use of non-standard `Promise` static methods
'promise/spec-only': [OFF, { allowedMethods: [
'prototype', // `eslint-plugin-promise` bug, https://github.com/eslint-community/eslint-plugin-promise/issues/533
'try',
'undefined', // `eslint-plugin-promise` bug, https://github.com/eslint-community/eslint-plugin-promise/issues/534
] }],
// ensures the proper number of arguments are passed to `Promise` functions
'promise/valid-params': ERROR,
// unicorn
// enforce a specific parameter name in `catch` clauses
'unicorn/catch-error-name': [ERROR, { name: ERROR, ignore: [/^err/] }],
// enforce consistent assertion style with `node:assert`
'unicorn/consistent-assert': ERROR,
// prefer passing `Date` directly to the constructor when cloning
'unicorn/consistent-date-clone': ERROR,
// prefer consistent types when spreading a ternary in an array literal
'unicorn/consistent-empty-array-spread': ERROR,
// enforce consistent style for element existence checks with `indexOf()`, `lastIndexOf()`, `findIndex()`, and `findLastIndex()`
'unicorn/consistent-existence-index-check': ERROR,
// enforce correct `Error` subclassing
'unicorn/custom-error-definition': ERROR,
// enforce passing a message value when throwing a built-in error
'unicorn/error-message': ERROR,
// require escape sequences to use uppercase values
'unicorn/escape-case': [ERROR, 'uppercase'],
// enforce a case style for filenames
'unicorn/filename-case': [ERROR, { case: 'kebabCase' }],
// enforce specifying rules to disable in `eslint-disable` comments
'unicorn/no-abusive-eslint-disable': ERROR,
// disallow recursive access to `this` within getters and setters
'unicorn/no-accessor-recursion': ERROR,
// prefer `Array#toReversed()` over `Array#reverse()`
'unicorn/no-array-reverse': ERROR,
// disallow using `await` in `Promise` method parameters
'unicorn/no-await-in-promise-methods': ERROR,
// do not use leading/trailing space between `console.log` parameters
'unicorn/no-console-spaces': ERROR,
// enforce the use of unicode escapes instead of hexadecimal escapes
'unicorn/no-hex-escape': ERROR,
// disallow immediate mutation after variable assignment
// that cause problems with objects in ES3 syntax, but since unicorn team
// don't wanna add an option to allow it, manually disable this rule in such problem cases
// https://github.com/sindresorhus/eslint-plugin-unicorn/issues/2796
'unicorn/no-immediate-mutation': ERROR,
// disallow `instanceof` with built-in objects
'unicorn/no-instanceof-builtins': [ERROR, { strategy: 'loose' }],
// disallow invalid options in `fetch` and `Request`
'unicorn/no-invalid-fetch-options': ERROR,
// prevent calling `EventTarget#removeEventListener()` with the result of an expression
'unicorn/no-invalid-remove-event-listener': ERROR,
// disallow `if` statements as the only statement in `if` blocks without `else`
'unicorn/no-lonely-if': ERROR,
// disallow named usage of default import and export
'unicorn/no-named-default': ERROR,
// disallow negated expression in equality check
'unicorn/no-negation-in-equality-check': ERROR,
// enforce the use of `Buffer.from()` and `Buffer.alloc()` instead of the deprecated `new Buffer()`
'unicorn/no-new-buffer': ERROR,
// disallow passing single-element arrays to `Promise` methods
'unicorn/no-single-promise-in-promise-methods': ERROR,
// forbid classes that only have static members
'unicorn/no-static-only-class': ERROR,
// disallow `then` property
'unicorn/no-thenable': ERROR,
// disallow comparing `undefined` using `typeof` when it's not required
'unicorn/no-typeof-undefined': ERROR,
// disallow using 1 as the depth argument of `Array#flat()`
'unicorn/no-unnecessary-array-flat-depth': ERROR,
// disallow using `.length` or `Infinity` as the `deleteCount` or `skipCount` argument of `Array#{ splice, toSpliced }()`
'unicorn/no-unnecessary-array-splice-count': ERROR,
// disallow awaiting non-promise values
'unicorn/no-unnecessary-await': ERROR,
// disallow using `.length` or `Infinity` as the end argument of `{ Array, String, %TypedArray% }#slice()`
'unicorn/no-unnecessary-slice-end': ERROR,
// disallow unreadable array destructuring
'unicorn/no-unreadable-array-destructuring': ERROR,
// disallow unreadable IIFEs
'unicorn/no-unreadable-iife': ERROR,
// disallow unused object properties
'unicorn/no-unused-properties': ERROR,
// disallow useless values or fallbacks in `Set`, `Map`, `WeakSet`, or `WeakMap`
'unicorn/no-useless-collection-argument': ERROR,
// disallow unnecessary `Error.captureStackTrace()`
'unicorn/no-useless-error-capture-stack-trace': ERROR,
// forbid useless fallback when spreading in object literals
'unicorn/no-useless-fallback-in-spread': ERROR,
// disallow useless array length check
'unicorn/no-useless-length-check': ERROR,
// disallow returning / yielding `Promise.{ resolve, reject }` in async functions or promise callbacks
'unicorn/no-useless-promise-resolve-reject': ERROR,
// disallow useless spread
'unicorn/no-useless-spread': ERROR,
// disallow useless `case` in `switch` statements
'unicorn/no-useless-switch-case': ERROR,
// enforce lowercase identifier and uppercase value for number literals
'unicorn/number-literal-case': [ERROR, { hexadecimalValue: 'uppercase' }],
// enforce the style of numeric separators by correctly grouping digits
'unicorn/numeric-separators-style': [ERROR, {
onlyIfContainsSeparator: true,
number: { minimumDigits: 0, groupLength: 3 },
binary: { minimumDigits: 0, groupLength: 4 },
octal: { minimumDigits: 0, groupLength: 4 },
hexadecimal: { minimumDigits: 0, groupLength: 2 },
}],
// prefer `.find()` over the first element from `.filter()`
'unicorn/prefer-array-find': [ERROR, { checkFromLast: true }],
// use `.flat()` to flatten an array of arrays
'unicorn/prefer-array-flat': ERROR,
// use `.flatMap()` to map and then flatten an array instead of using `.map().flat()`
'unicorn/prefer-array-flat-map': ERROR,
// prefer `Array#indexOf` over `Array#findIndex`` when looking for the index of an item
'unicorn/prefer-array-index-of': ERROR,
// prefer `.some()` over `.filter().length` check and `.find()`
'unicorn/prefer-array-some': ERROR,
// prefer `.at()` method for index access and `String#charAt()`
'unicorn/prefer-at': [ERROR, { checkAllIndexAccess: false }],
// prefer `BigInt` literals over the constructor
'unicorn/prefer-bigint-literals': ERROR,
// prefer `Blob#{ arrayBuffer, text }` over `FileReader#{ readAsArrayBuffer, readAsText }`
'unicorn/prefer-blob-reading-methods': ERROR,
// prefer class field declarations over this assignments in constructors
'unicorn/prefer-class-fields': ERROR,
// prefer using `Element#classList.toggle()` to toggle class names
'unicorn/prefer-classlist-toggle': ERROR,
// prefer `Date.now()` to get the number of milliseconds since the Unix Epoch
'unicorn/prefer-date-now': ERROR,
// prefer default parameters over reassignment
'unicorn/prefer-default-parameters': ERROR,
// prefer `EventTarget` over `EventEmitter`
'unicorn/prefer-event-target': ERROR,
// prefer `globalThis` over `window`, `self`, and `global`
'unicorn/prefer-global-this': ERROR,
// prefer `.includes()` over `.indexOf()` and `Array#some()` when checking for existence or non-existence
'unicorn/prefer-includes': ERROR,
// prefer reading a `JSON` file as a buffer
'unicorn/prefer-json-parse-buffer': ERROR,
// prefer using a logical operator over a ternary
'unicorn/prefer-logical-operator-over-ternary': ERROR,
// prefer `Math.min()` and `Math.max()` over ternaries for simple comparisons
'unicorn/prefer-math-min-max': ERROR,
// prefer modern `Math` APIs over legacy patterns
'unicorn/prefer-modern-math-apis': ERROR,
// prefer negative index over `.length - index` when possible
'unicorn/prefer-negative-index': ERROR,
// prefer using the `node:` protocol when importing Node builtin modules
'unicorn/prefer-node-protocol': ERROR,
// prefer using `Object.fromEntries()` to transform a list of key-value pairs into an object
'unicorn/prefer-object-from-entries': ERROR,
// prefer omitting the `catch` binding parameter
'unicorn/prefer-optional-catch-binding': ERROR,
// prefer `Response.json()` over `new Response(JSON.stringify())`
'unicorn/prefer-response-static-json': ERROR,
// prefer using `structuredClone` to create a deep clone
'unicorn/prefer-structured-clone': ERROR,
// prefer using `Set#size` instead of `Array#length`
'unicorn/prefer-set-size': ERROR,
// enforce combining multiple `Array#push`, `Element#classList.{ add, remove }()` or `importScripts` into one call
'unicorn/prefer-single-call': ERROR,
// prefer `String#replaceAll()` over regex searches with the global flag
'unicorn/prefer-string-replace-all': ERROR,
// prefer `String#{ startsWith, endsWith }()` over `RegExp#test()`
'unicorn/prefer-string-starts-ends-with': ERROR,
// prefer `String#{ trimStart, trimEnd }()` over `String#{ trimLeft, trimRight }()`
'unicorn/prefer-string-trim-start-end': ERROR,
// prefer `switch` over multiple `else-if`
'unicorn/prefer-switch': [ERROR, { minimumCases: 3 }],
// enforce consistent relative `URL` style
'unicorn/relative-url-style': [ERROR, ALWAYS],
// enforce using the separator argument with `Array#join()`
'unicorn/require-array-join-separator': ERROR,
// require non-empty specifier list in import and export statements
'unicorn/require-module-specifiers': ERROR,
// enforce using the digits argument with `Number#toFixed()`
'unicorn/require-number-to-fixed-digits-argument': ERROR,
// enforce using the `targetOrigin`` argument with `window.postMessage()`
'unicorn/require-post-message-target-origin': ERROR,
// forbid braces for case clauses
'unicorn/switch-case-braces': [ERROR, 'avoid'],
// fix whitespace-insensitive template indentation
'unicorn/template-indent': OFF, // waiting for `String.dedent`
// enforce consistent case for text encoding identifiers
'unicorn/text-encoding-identifier-case': ERROR,
// require `new` when throwing an error
'unicorn/throw-new-error': ERROR,
// sonarjs
// alternatives in regular expressions should be grouped when used with anchors
'sonarjs/anchor-precedence': ERROR,
// arguments to built-in functions should match documented types
'sonarjs/argument-type': OFF, // it seems does not work
// bitwise operators should not be used in boolean contexts
'sonarjs/bitwise-operators': ERROR,
// function call arguments should not start on new lines
'sonarjs/call-argument-line': ERROR,
// class names should comply with a naming convention
'sonarjs/class-name': [ERROR, { format: '^[A-Z$][a-zA-Z0-9]*$' }],
// comma and logical `OR` operators should not be used in switch cases
'sonarjs/comma-or-logical-or-case': ERROR,
// cyclomatic complexity of functions should not be too high
'sonarjs/cyclomatic-complexity': [OFF, { threshold: 16 }],
// expressions should not be too complex
'sonarjs/expression-complexity': [OFF, { max: 3 }],
// `in` should not be used with primitive types
'sonarjs/in-operator-type-error': ERROR,
// functions should be called consistently with or without `new`
'sonarjs/inconsistent-function-call': ERROR,
// `new` should only be used with functions and classes
'sonarjs/new-operator-misuse': [ERROR, { considerJSDoc: false }],
// `Array#{ sort, toSorted }` should use a compare function
'sonarjs/no-alphabetical-sort': ERROR,
// `delete` should not be used on arrays
'sonarjs/no-array-delete': ERROR,
// array indexes should be numeric
'sonarjs/no-associative-arrays': ERROR,
// `switch` statements should not contain non-case labels
'sonarjs/no-case-label-in-switch': ERROR,
// collection sizes and array length comparisons should make sense
'sonarjs/no-collection-size-mischeck': ERROR,
// two branches in a conditional structure should not have exactly the same implementation
'sonarjs/no-duplicated-branches': ERROR,
// collection elements should not be replaced unconditionally
'sonarjs/no-element-overwrite': ERROR,
// empty collections should not be accessed or iterated
'sonarjs/no-empty-collection': ERROR,
// function calls should not pass extra arguments
'sonarjs/no-extra-arguments': ERROR,
// `for-in` should not be used with iterables
'sonarjs/no-for-in-iterable': ERROR,
// global `this` object should not be used
'sonarjs/no-global-this': ERROR,
// boolean expressions should not be gratuitous
'sonarjs/no-gratuitous-expressions': ERROR,
// `in` should not be used on arrays
'sonarjs/no-in-misuse': ERROR,
// strings and non-strings should not be added
'sonarjs/no-incorrect-string-concat': ERROR,
// function returns should not be invariant
'sonarjs/no-invariant-returns': ERROR,
// literals should not be used as functions
'sonarjs/no-literal-call': ERROR,
// array-mutating methods should not be used misleadingly
'sonarjs/no-misleading-array-reverse': ERROR,
// assignments should not be redundant
'sonarjs/no-redundant-assignments': ERROR,
// boolean literals should not be redundant
'sonarjs/no-redundant-boolean': ERROR,
// jump statements should not be redundant
'sonarjs/no-redundant-jump': ERROR,
// redundant pairs of parentheses should be removed
'sonarjs/no-redundant-parentheses': ERROR,
// variables should be defined before being used
'sonarjs/no-reference-error': ERROR,
// conditionals should start on new lines
'sonarjs/no-same-line-conditional': ERROR,
// `switch` statements should have at least 3 `case` clauses
'sonarjs/no-small-switch': ERROR,
// promise rejections should not be caught by `try` blocks
'sonarjs/no-try-promise': ERROR,
// `undefined` should not be passed as the value of optional parameters
'sonarjs/no-undefined-argument': ERROR,
// errors should not be created without being thrown
'sonarjs/no-unthrown-error': ERROR,
// collection and array contents should be used
'sonarjs/no-unused-collection': ERROR,
// the output of functions that don't return anything should not be used
'sonarjs/no-use-of-empty-return-value': ERROR,
// values should not be uselessly incremented
'sonarjs/no-useless-increment': ERROR,
// non-existent operators `=+`, `=-` and `=!` should not be used
'sonarjs/non-existent-operator': ERROR,
// properties of variables with `null` or `undefined` values should not be accessed
'sonarjs/null-dereference': ERROR, // it seems does not work
// arithmetic operations should not result in `NaN`
'sonarjs/operation-returning-nan': ERROR,
// local variables should not be declared and then immediately returned or thrown
'sonarjs/prefer-immediate-return': ERROR,
// object literal syntax should be used
'sonarjs/prefer-object-literal': ERROR,
// shorthand promises should be used
'sonarjs/prefer-promise-shorthand': ERROR,
// return of boolean expressions should not be wrapped into an `if-then-else` statement
'sonarjs/prefer-single-boolean-return': ERROR,
// a `while` loop should be used instead of a `for` loop with condition only
'sonarjs/prefer-while': ERROR,
// using slow regular expressions is security-sensitive
'sonarjs/slow-regex': ERROR,
// regular expressions with the global flag should be used with caution
'sonarjs/stateful-regex': ERROR,
// comparison operators should not be used with strings
'sonarjs/strings-comparison': ERROR,
// `super()` should be invoked appropriately
'sonarjs/super-invocation': ERROR,
// results of operations on strings should not be ignored
'sonarjs/useless-string-operation': ERROR,
// values not convertible to numbers should not be used in numeric comparisons
'sonarjs/values-not-convertible-to-numbers': ERROR,
// math
// enforce the conversion to absolute values to be the method you prefer
'math/abs': [ERROR, { prefer: 'Math.abs' }],
// disallow static calculations that go to infinity
'math/no-static-infinity-calculations': ERROR,
// disallow static calculations that go to `NaN`
'math/no-static-nan-calculations': ERROR,
// enforce the use of exponentiation (`**`) operator instead of other calculations
'math/prefer-exponentiation-operator': ERROR,
// enforce the use of `Math.cbrt()` instead of other cube root calculations
'math/prefer-math-cbrt': ERROR,
// enforce the use of `Math.E` instead of other ways
'math/prefer-math-e': ERROR,
// enforce the use of `Math.hypot()` instead of other hypotenuse calculations
'math/prefer-math-hypot': ERROR,
// enforce the use of `Math.LN10` instead of other ways
'math/prefer-math-ln10': ERROR,
// enforce the use of `Math.LN2` instead of other ways
'math/prefer-math-ln2': ERROR,
// enforce the use of `Math.log10` instead of other ways
'math/prefer-math-log10': ERROR,
// enforce the use of `Math.LOG10E` instead of other ways
'math/prefer-math-log10e': ERROR,
// enforce the use of `Math.log2` instead of other ways
'math/prefer-math-log2': ERROR,
// enforce the use of `Math.LOG2E` instead of other ways
'math/prefer-math-log2e': ERROR,
// enforce the use of `Math.PI` instead of literal number
'math/prefer-math-pi': ERROR,
// enforce the use of `Math.sqrt()` instead of other square root calculations
'math/prefer-math-sqrt': ERROR,
// enforce the use of `Math.SQRT1_2` instead of other ways
'math/prefer-math-sqrt1-2': ERROR,
// enforce the use of `Math.SQRT2` instead of other ways
'math/prefer-math-sqrt2': ERROR,
// enforce the use of `Math.sumPrecise()` instead of other summation methods
'math/prefer-math-sum-precise': ERROR,
// enforce the use of `Math.trunc()` instead of other truncations
'math/prefer-math-trunc': [ERROR, { reportBitwise: false }],
// enforce the use of `Number.EPSILON` instead of other ways
'math/prefer-number-epsilon': ERROR,
// enforce the use of `Number.isFinite()` instead of other checking ways
'math/prefer-number-is-finite': ERROR,
// enforce the use of `Number.isInteger()` instead of other checking ways
'math/prefer-number-is-integer': ERROR,
// enforce the use of `Number.isNaN()` instead of other checking ways
'math/prefer-number-is-nan': ERROR,
// enforce the use of `Number.isSafeInteger()` instead of other checking ways
'math/prefer-number-is-safe-integer': ERROR,
// enforce the use of `Number.MAX_SAFE_INTEGER` instead of other ways
'math/prefer-number-max-safe-integer': ERROR,
// enforce the use of `Number.MAX_VALUE` instead of literal number
'math/prefer-number-max-value': ERROR,
// enforce the use of `Number.MIN_SAFE_INTEGER` instead of other ways
'math/prefer-number-min-safe-integer': ERROR,
// enforce the use of `Number.MIN_VALUE` instead of literal number
'math/prefer-number-min-value': ERROR,
// regexp
// disallow confusing quantifiers
'regexp/confusing-quantifier': ERROR,
// enforce consistent escaping of control characters
'regexp/control-character-escape': ERROR,
// enforce single grapheme in string literal
'regexp/grapheme-string-literal': ERROR,
// enforce consistent usage of hexadecimal escape
'regexp/hexadecimal-escape': [ERROR, NEVER],
// enforce into your favorite case
'regexp/letter-case': [ERROR, {
caseInsensitive: 'lowercase',
unicodeEscape: 'uppercase',
}],
// enforce match any character style
'regexp/match-any': [ERROR, { allows: ['[\\S\\s]', 'dotAll'] }],
// enforce use of escapes on negation
'regexp/negation': ERROR,
// disallow elements that contradict assertions
'regexp/no-contradiction-with-assertion': ERROR,
// disallow control characters
'regexp/no-control-character': ERROR,
// disallow duplicate characters in the RegExp character class
'regexp/no-dupe-characters-character-class': ERROR,
// disallow duplicate disjunctions
'regexp/no-dupe-disjunctions': [ERROR, { report: 'all' }],
// disallow alternatives without elements
'regexp/no-empty-alternative': ERROR,
// disallow capturing group that captures empty
'regexp/no-empty-capturing-group': ERROR,
// disallow character classes that match no characters
'regexp/no-empty-character-class': ERROR,
// disallow empty group
'regexp/no-empty-group': ERROR,
// disallow empty lookahead assertion or empty lookbehind assertion
'regexp/no-empty-lookarounds-assertion': ERROR,
// reports empty string literals in character classes
'regexp/no-empty-string-literal': ERROR,
// disallow escape backspace `([\b])`
'regexp/no-escape-backspace': ERROR,
// disallow unnecessary nested lookaround assertions
'regexp/no-extra-lookaround-assertions': ERROR,
// disallow invalid regular expression strings in RegExp constructors
'regexp/no-invalid-regexp': ERROR,
// disallow invisible raw character
'regexp/no-invisible-character': ERROR,
// disallow lazy quantifiers at the end of an expression
'regexp/no-lazy-ends': ERROR,
// disallow legacy RegExp features
'regexp/no-legacy-features': ERROR,
// disallow capturing groups that do not behave as one would expect
'regexp/no-misleading-capturing-group': ERROR,
// disallow multi-code-point characters in character classes and quantifiers
'regexp/no-misleading-unicode-character': ERROR,
// disallow missing `g` flag in patterns used in `String#matchAll` and `String#replaceAll`
'regexp/no-missing-g-flag': ERROR,
// disallow non-standard flags
'regexp/no-non-standard-flag': ERROR,
// disallow obscure character ranges
'regexp/no-obscure-range': ERROR,
// disallow octal escape sequence
'regexp/no-octal': ERROR,
// disallow optional assertions
'regexp/no-optional-assertion': ERROR,
// disallow backreferences that reference a group that might not be matched
'regexp/no-potentially-useless-backreference': ERROR,
// disallow standalone backslashes
'regexp/no-standalone-backslash': ERROR,
// disallow trivially nested assertions
'regexp/no-trivially-nested-assertion': ERROR,
// disallow nested quantifiers that can be rewritten as one quantifier
'regexp/no-trivially-nested-quantifier': ERROR,
// disallow unused capturing group
'regexp/no-unused-capturing-group': ERROR,
// disallow assertions that are known to always accept (or reject)
'regexp/no-useless-assertions': ERROR,
// disallow useless backreferences in regular expressions
'regexp/no-useless-backreference': ERROR,
// disallow character class with one character
'regexp/no-useless-character-class': ERROR,
// disallow useless `$` replacements in replacement string
'regexp/no-useless-dollar-replacements': ERROR,
// disallow unnecessary string escaping
'regexp/no-useless-escape': ERROR,
// disallow unnecessary regex flags
'regexp/no-useless-flag': ERROR,
// disallow unnecessarily non-greedy quantifiers
'regexp/no-useless-lazy': ERROR,
// disallow unnecessary non-capturing group
'regexp/no-useless-non-capturing-group': ERROR,
// disallow quantifiers that can be removed
'regexp/no-useless-quantifier': ERROR,
// disallow unnecessary range of characters by using a hyphen
'regexp/no-useless-range': ERROR,
// reports any unnecessary set operands
'regexp/no-useless-set-operand': ERROR,
// reports the string alternatives of a single character in `\q{...}`, it can be placed outside `\q{...}`
'regexp/no-useless-string-literal': ERROR,
// disallow unnecessary `{n,m}`` quantifier
'regexp/no-useless-two-nums-quantifier': ERROR,
// disallow quantifiers with a maximum of zero
'regexp/no-zero-quantifier': ERROR,
// disallow the alternatives of lookarounds that end with a non-constant quantifier
'regexp/optimal-lookaround-quantifier': ERROR,
// require optimal quantifiers for concatenated quantifiers
'regexp/optimal-quantifier-concatenation': ERROR,
// enforce using character class
'regexp/prefer-character-class': ERROR,
// enforce using `\d`
'regexp/prefer-d': ERROR,
// enforces escape of replacement `$` character (`$$`)
'regexp/prefer-escape-replacement-dollar-char': ERROR,
// prefer lookarounds over capturing group that do not replace
'regexp/prefer-lookaround': [ERROR, { lookbehind: true, strictTypes: true }],
// enforce using named backreferences
'regexp/prefer-named-backreference': ERROR,
// enforce using named capture group in regular expression
'regexp/prefer-named-capture-group': ERROR,
// enforce using named replacement
'regexp/prefer-named-replacement': ERROR,
// enforce using `+` quantifier
'regexp/prefer-plus-quantifier': ERROR,
// prefer predefined assertion over equivalent lookarounds
'regexp/prefer-predefined-assertion': ERROR,
// enforce using quantifier
'regexp/prefer-quantifier': ERROR,
// enforce using `?` quantifier
'regexp/prefer-question-quantifier': ERROR,
// enforce using character class range
'regexp/prefer-range': [ERROR, { target: 'alphanumeric' }],
// enforce that `RegExp#exec` is used instead of `String#match` if no global flag is provided
'regexp/prefer-regexp-exec': ERROR,
// enforce that `RegExp#test` is used instead of `String#match` and `RegExp#exec`
'regexp/prefer-regexp-test': ERROR,
// enforce using result array `.groups``
'regexp/prefer-result-array-groups': ERROR,
// enforce using `*` quantifier
'regexp/prefer-star-quantifier': ERROR,
// enforce use of unicode codepoint escapes
'regexp/prefer-unicode-codepoint-escapes': ERROR,
// enforce using `\w`
'regexp/prefer-w': ERROR,
// aims to optimize patterns by simplifying set operations in character classes (with v flag)
'regexp/simplify-set-operations': ERROR,
// sort alternatives if order doesn't matter
'regexp/sort-alternatives': ERROR,
// enforces elements order in character class
'regexp/sort-character-class-elements': ERROR,
// require regex flags to be sorted
'regexp/sort-flags': ERROR,
// disallow not strictly valid regular expressions
'regexp/strict': ERROR,
// enforce consistent usage of unicode escape or unicode codepoint escape
'regexp/unicode-escape': ERROR,
// use the `i` flag if it simplifies the pattern
'regexp/use-ignore-case': ERROR,
// ReDoS vulnerability check
'redos/no-vulnerable': [ERROR, { timeout: 1e3 }],
// disallow function declarations in if statement clauses without using blocks
'es/no-function-declarations-in-if-statement-clauses-without-block': ERROR,
// disallow initializers in for-in heads
'es/no-initializers-in-for-in': ERROR,
// disallow \u2028 and \u2029 in string literals
'es/no-json-superset': ERROR,
// disallow labelled function declarations
'es/no-labelled-function-declarations': ERROR,
// disallow the `RegExp.prototype.compile` method
'es/no-regexp-prototype-compile': ERROR,
// eslint-comments:
// disallow duplicate `eslint-disable` comments
'eslint-comments/no-duplicate-disable': ERROR,
// disallow `eslint-disable` comments without rule names
'eslint-comments/no-unlimited-disable': ERROR,
// disallow unused `eslint-disable` comments
// it's clearly disabled since result of some rules (like `redos/no-vulnerable`) is non-deterministic
// and anyway it's reported because of `reportUnusedDisableDirectives` option
'eslint-comments/no-unused-disable': OFF,
// disallow unused `eslint-enable` comments
'eslint-comments/no-unused-enable': ERROR,
// require include descriptions in eslint directive-comments
'eslint-comments/require-description': ERROR,
// suggest better alternatives to some dependencies
'depend/ban-dependencies': [ERROR, { allowed: [
'mkdirp', // TODO: drop from `core-js@4`
] }],
};
const noAsyncAwait = {
// prefer `async` / `await` to the callback pattern
'promise/prefer-await-to-callbacks': OFF,
// prefer `await` to `then()` / `catch()` / `finally()` for reading `Promise` values
'promise/prefer-await-to-then': OFF,
};
const useES3Syntax = {
...noAsyncAwait,
// encourages use of dot notation whenever possible
'dot-notation': [ERROR, { allowKeywords: false }],
// disallow logical assignment operator shorthand
'logical-assignment-operators': [ERROR, NEVER],
// disallow function or variable declarations in nested blocks
'no-inner-declarations': ERROR,
// disallow specified syntax
'no-restricted-syntax': OFF,
// require let or const instead of var
'no-var': OFF,
// require or disallow method and property shorthand syntax for object literals
'object-shorthand': OFF,
// require using arrow functions for callbacks
'prefer-arrow-callback': OFF,
// require const declarations for variables that are never reassigned after declared
'prefer-const': OFF,
// require destructuring from arrays and/or objects
'prefer-destructuring': OFF,
// prefer the exponentiation operator over `Math.pow()`
'prefer-exponentiation-operator': OFF,
// require rest parameters instead of `arguments`
'prefer-rest-params': OFF,
// require spread operators instead of `.apply()`
'prefer-spread': OFF,
// require template literals instead of string concatenation
'prefer-template': OFF,
// disallow trailing commas in multiline object literals
'@stylistic/comma-dangle': [ERROR, NEVER],
// require or disallow use of quotes around object literal property names
'@stylistic/quote-props': [ERROR, 'as-needed', { keywords: true }],
// enforce the use of exponentiation (`**`) operator instead of other calculations
'math/prefer-exponentiation-operator': OFF,
// prefer lookarounds over capturing group that do not replace
'regexp/prefer-lookaround': [ERROR, { lookbehind: false, strictTypes: true }],
// enforce using named capture group in regular expression
'regexp/prefer-named-capture-group': OFF,
// prefer class field declarations over this assignments in constructors
'unicorn/prefer-class-fields': OFF,
// prefer default parameters over reassignment
'unicorn/prefer-default-parameters': OFF,
// prefer using a logical operator over a ternary
'unicorn/prefer-logical-operator-over-ternary': OFF,
// prefer omitting the `catch` binding parameter
'unicorn/prefer-optional-catch-binding': OFF,
};
const forbidNonStandardBuiltIns = {
// disallow non-standard built-in methods
'es/no-nonstandard-array-properties': ERROR,
'es/no-nonstandard-array-prototype-properties': ERROR,
'es/no-nonstandard-arraybuffer-properties': ERROR,
'es/no-nonstandard-arraybuffer-prototype-properties': ERROR,
'es/no-nonstandard-asyncdisposablestack-properties': ERROR,
'es/no-nonstandard-asyncdisposablestack-prototype-properties': ERROR,
'es/no-nonstandard-atomics-properties': ERROR,
'es/no-nonstandard-bigint-properties': ERROR,
'es/no-nonstandard-bigint-prototype-properties': ERROR,
'es/no-nonstandard-boolean-properties': ERROR,
'es/no-nonstandard-boolean-prototype-properties': ERROR,
'es/no-nonstandard-dataview-properties': ERROR,
'es/no-nonstandard-dataview-prototype-properties': ERROR,
'es/no-nonstandard-date-properties': ERROR,
'es/no-nonstandard-date-prototype-properties': ERROR,
'es/no-nonstandard-disposablestack-properties': ERROR,
'es/no-nonstandard-disposablestack-prototype-properties': ERROR,
'es/no-nonstandard-error-properties': ERROR,
'es/no-nonstandard-finalizationregistry-properties': ERROR,
'es/no-nonstandard-finalizationregistry-prototype-properties': ERROR,
'es/no-nonstandard-function-properties': ERROR,
'es/no-nonstandard-intl-collator-properties': ERROR,
'es/no-nonstandard-intl-collator-prototype-properties': ERROR,
'es/no-nonstandard-intl-datetimeformat-properties': ERROR,
'es/no-nonstandard-intl-datetimeformat-prototype-properties': ERROR,
'es/no-nonstandard-intl-displaynames-properties': ERROR,
'es/no-nonstandard-intl-displaynames-prototype-properties': ERROR,
'es/no-nonstandard-intl-listformat-properties': ERROR,
'es/no-nonstandard-intl-listformat-prototype-properties': ERROR,
'es/no-nonstandard-intl-locale-properties': ERROR,
'es/no-nonstandard-intl-locale-prototype-properties': ERROR,
'es/no-nonstandard-intl-numberformat-properties': ERROR,
'es/no-nonstandard-intl-numberformat-prototype-properties': ERROR,
'es/no-nonstandard-intl-pluralrules-properties': ERROR,
'es/no-nonstandard-intl-pluralrules-prototype-properties': ERROR,
'es/no-nonstandard-intl-properties': ERROR,
'es/no-nonstandard-intl-relativetimeformat-properties': ERROR,
'es/no-nonstandard-intl-relativetimeformat-prototype-properties': ERROR,
'es/no-nonstandard-intl-segmenter-properties': ERROR,
'es/no-nonstandard-intl-segmenter-prototype-properties': ERROR,
'es/no-nonstandard-iterator-properties': ERROR,
'es/no-nonstandard-iterator-prototype-properties': ERROR,
'es/no-nonstandard-json-properties': ERROR,
'es/no-nonstandard-map-properties': ERROR,
'es/no-nonstandard-map-prototype-properties': ERROR,
'es/no-nonstandard-math-properties': ERROR,
'es/no-nonstandard-number-properties': ERROR,
'es/no-nonstandard-number-prototype-properties': ERROR,
'es/no-nonstandard-object-properties': ERROR,
'es/no-nonstandard-promise-properties': ERROR,
'es/no-nonstandard-promise-prototype-properties': ERROR,
'es/no-nonstandard-proxy-properties': ERROR,
'es/no-nonstandard-reflect-properties': ERROR,
'es/no-nonstandard-regexp-properties': ERROR,
'es/no-nonstandard-regexp-prototype-properties': ERROR,
'es/no-nonstandard-set-properties': ERROR,
'es/no-nonstandard-set-prototype-properties': ERROR,
'es/no-nonstandard-sharedarraybuffer-properties': ERROR,
'es/no-nonstandard-sharedarraybuffer-prototype-properties': ERROR,
'es/no-nonstandard-string-properties': ERROR,
'es/no-nonstandard-string-prototype-properties': ERROR,
'es/no-nonstandard-symbol-properties': [ERROR, { allow: [
'sham', // non-standard flag
] }],
'es/no-nonstandard-symbol-prototype-properties': ERROR,
'es/no-nonstandard-typed-array-properties': ERROR,
'es/no-nonstandard-typed-array-prototype-properties': ERROR,
'es/no-nonstandard-weakmap-properties': ERROR,
'es/no-nonstandard-weakmap-prototype-properties': ERROR,
'es/no-nonstandard-weakref-properties': ERROR,
'es/no-nonstandard-weakref-prototype-properties': ERROR,
'es/no-nonstandard-weakset-properties': ERROR,
'es/no-nonstandard-weakset-prototype-properties': ERROR,
};
const forbidCompletelyNonExistentBuiltIns = {
...forbidNonStandardBuiltIns,
// disallow non-standard built-in methods
'es/no-nonstandard-array-properties': [ERROR, { allow: [
'isTemplateObject',
] }],
'es/no-nonstandard-array-prototype-properties': [ERROR, { allow: [
'filterReject',
'uniqueBy',
// TODO: drop from `core-js@4`
'filterOut',
'group',
'groupBy',
'groupByToMap',
'groupToMap',
'lastIndex',
'lastItem',
] }],
'es/no-nonstandard-bigint-properties': [ERROR, { allow: [
// TODO: drop from `core-js@4`
'range',
] }],
'es/no-nonstandard-dataview-prototype-properties': [ERROR, { allow: [
'getUint8Clamped',
'setUint8Clamped',
] }],
'es/no-nonstandard-function-properties': [ERROR, { allow: [
'isCallable',
'isConstructor',
] }],
'es/no-nonstandard-iterator-properties': [ERROR, { allow: [
'range',
'zip',
'zipKeyed',
] }],
'es/no-nonstandard-iterator-prototype-properties': [ERROR, { allow: [
'chunks',
'sliding',
'toAsync',
'windows',
// TODO: drop from `core-js@4`
'asIndexedPairs',
'indexed',
] }],
'es/no-nonstandard-map-properties': [ERROR, { allow: [
'from',
'of',
// TODO: drop from `core-js@4`
'keyBy',
] }],
'es/no-nonstandard-map-prototype-properties': [ERROR, { allow: [
'getOrInsert',
'getOrInsertComputed',
// TODO: drop from `core-js@4`
'deleteAll',
'emplace',
'every',
'filter',
'find',
'findKey',
'includes',
'keyOf',
'mapKeys',
'mapValues',
'merge',
'reduce',
'some',
'update',
'updateOrInsert',
'upsert',
] }],
'es/no-nonstandard-math-properties': [ERROR, { allow: [
// TODO: drop from `core-js@4`
'DEG_PER_RAD',
'RAD_PER_DEG',
'clamp',
'degrees',
'fscale',
'iaddh',
'imulh',
'isubh',
'radians',
'scale',
'seededPRNG',
'signbit',
'umulh',
] }],
'es/no-nonstandard-number-properties': [ERROR, { allow: [
// TODO: drop from `core-js@4`
'fromString',
'range',
] }],
'es/no-nonstandard-number-prototype-properties': [ERROR, { allow: [
'clamp',
] }],
'es/no-nonstandard-object-properties': [ERROR, { allow: [
// TODO: drop from `core-js@4`
'iterateEntries',
'iterateKeys',
'iterateValues',
] }],
'es/no-nonstandard-reflect-properties': [ERROR, { allow: [
// TODO: drop from `core-js@4`
'defineMetadata',
'deleteMetadata',
'getMetadata',
'getMetadataKeys',
'getOwnMetadata',
'getOwnMetadataKeys',
'hasMetadata',
'hasOwnMetadata',
'metadata',
] }],
'es/no-nonstandard-set-properties': [ERROR, { allow: [
'from',
'of',
] }],
'es/no-nonstandard-set-prototype-properties': [ERROR, { allow: [
// TODO: drop from `core-js@4`
'addAll',
'deleteAll',
'every',
'filter',
'find',
'join',
'map',
'reduce',
'some',
] }],
'es/no-nonstandard-string-properties': [ERROR, { allow: [
'cooked',
'dedent',
] }],
'es/no-nonstandard-string-prototype-properties': [ERROR, { allow: [
// TODO: drop from `core-js@4`
'codePoints',
] }],
'es/no-nonstandard-symbol-properties': [ERROR, { allow: [
'customMatcher',
'isRegisteredSymbol',
'isWellKnownSymbol',
'metadata',
'sham', // non-standard flag
// TODO: drop from `core-js@4`
'isRegistered',
'isWellKnown',
'matcher',
'metadataKey',
'observable',
'patternMatch',
'replaceAll',
'useSetter',
'useSimple',
] }],
'es/no-nonstandard-typed-array-properties': [ERROR, { allow: [
// TODO: drop from `core-js@4`
'fromAsync',
] }],
'es/no-nonstandard-typed-array-prototype-properties': [ERROR, { allow: [
'filterReject',
'uniqueBy',
// TODO: drop from `core-js@4`
'filterOut',
'groupBy',
] }],
'es/no-nonstandard-weakmap-properties': [ERROR, { allow: [
'from',
'of',
] }],
'es/no-nonstandard-weakmap-prototype-properties': [ERROR, { allow: [
'getOrInsert',
'getOrInsertComputed',
// TODO: drop from `core-js@4`
'deleteAll',
'emplace',
'upsert',
] }],
'es/no-nonstandard-weakset-properties': [ERROR, { allow: [
'from',
'of',
] }],
'es/no-nonstandard-weakset-prototype-properties': [ERROR, { allow: [
// TODO: drop from `core-js@4`
'addAll',
'deleteAll',
] }],
};
const forbidESAnnexBBuiltIns = {
'es/no-date-prototype-getyear-setyear': ERROR,
'es/no-date-prototype-togmtstring': ERROR,
'es/no-escape-unescape': ERROR,
'es/no-legacy-object-prototype-accessor-methods': ERROR,
'es/no-string-create-html-methods': ERROR,
'es/no-string-prototype-trimleft-trimright': ERROR,
// prefer `String#slice` over `String#{ substr, substring }`
'unicorn/prefer-string-slice': ERROR,
};
const forbidES5BuiltIns = {
'es/no-array-isarray': ERROR,
'es/no-array-prototype-every': ERROR,
'es/no-array-prototype-filter': ERROR,
'es/no-array-prototype-foreach': ERROR,
'es/no-array-prototype-indexof': ERROR,
'es/no-array-prototype-lastindexof': ERROR,
'es/no-array-prototype-map': ERROR,
'es/no-array-prototype-reduce': ERROR,
'es/no-array-prototype-reduceright': ERROR,
'es/no-array-prototype-some': ERROR,
'es/no-date-now': ERROR,
'es/no-function-prototype-bind': ERROR,
'es/no-json': ERROR,
'es/no-object-create': ERROR,
'es/no-object-defineproperties': ERROR,
'es/no-object-defineproperty': ERROR,
'es/no-object-freeze': ERROR,
'es/no-object-getownpropertydescriptor': ERROR,
'es/no-object-getownpropertynames': ERROR,
'es/no-object-getprototypeof': ERROR,
'es/no-object-isextensible': ERROR,
'es/no-object-isfrozen': ERROR,
'es/no-object-issealed': ERROR,
'es/no-object-keys': ERROR,
'es/no-object-preventextensions': ERROR,
'es/no-object-seal': ERROR,
'es/no-string-prototype-trim': ERROR,
// prefer `Date.now()` to get the number of milliseconds since the Unix Epoch
'unicorn/prefer-date-now': OFF,
// prefer `globalThis` over `window`, `self`, and `global`
'unicorn/prefer-global-this': OFF,
};
const forbidES2015BuiltIns = {
'es/no-array-from': ERROR,
'es/no-array-of': ERROR,
'es/no-array-prototype-copywithin': ERROR,
'es/no-array-prototype-entries': ERROR,
'es/no-array-prototype-fill': ERROR,
'es/no-array-prototype-find': ERROR,
'es/no-array-prototype-findindex': ERROR,
'es/no-array-prototype-keys': ERROR,
'es/no-array-prototype-values': ERROR,
'es/no-map': ERROR,
'es/no-math-acosh': ERROR,
'es/no-math-asinh': ERROR,
'es/no-math-atanh': ERROR,
'es/no-math-cbrt': ERROR,
'es/no-math-clz32': ERROR,
'es/no-math-cosh': ERROR,
'es/no-math-expm1': ERROR,
'es/no-math-fround': ERROR,
'es/no-math-hypot': ERROR,
'es/no-math-imul': ERROR,
'es/no-math-log10': ERROR,
'es/no-math-log1p': ERROR,
'es/no-math-log2': ERROR,
'es/no-math-sign': ERROR,
'es/no-math-sinh': ERROR,
'es/no-math-tanh': ERROR,
'es/no-math-trunc': ERROR,
'es/no-number-epsilon': ERROR,
'es/no-number-isfinite': ERROR,
'es/no-number-isinteger': ERROR,
'es/no-number-isnan': ERROR,
'es/no-number-issafeinteger': ERROR,
'es/no-number-maxsafeinteger': ERROR,
'es/no-number-minsafeinteger': ERROR,
'es/no-number-parsefloat': ERROR,
'es/no-number-parseint': ERROR,
'es/no-object-assign': ERROR,
'es/no-object-getownpropertysymbols': ERROR,
'es/no-object-is': ERROR,
'es/no-object-setprototypeof': ERROR,
'es/no-promise': ERROR,
'es/no-proxy': ERROR,
'es/no-reflect': ERROR,
'es/no-regexp-prototype-flags': ERROR,
'es/no-set': ERROR,
'es/no-string-fromcodepoint': ERROR,
'es/no-string-prototype-codepointat': ERROR,
'es/no-string-prototype-endswith': ERROR,
'es/no-string-prototype-includes': ERROR,
'es/no-string-prototype-normalize': ERROR,
'es/no-string-prototype-repeat': ERROR,
'es/no-string-prototype-startswith': ERROR,
'es/no-string-raw': ERROR,
'es/no-symbol': ERROR,
'es/no-typed-arrays': ERROR,
'es/no-weak-map': ERROR,
'es/no-weak-set': ERROR,
// enforce the use of `Math.cbrt()` instead of other cube root calculations
'math/prefer-math-cbrt': OFF,
// enforce the use of `Math.hypot()` instead of other hypotenuse calculations
'math/prefer-math-hypot': OFF,
// enforce the use of `Math.log10` instead of other ways
'math/prefer-math-log10': OFF,
// enforce the use of `Math.log10` instead of other ways
'math/prefer-math-log2': OFF,
// enforce the use of `Math.trunc()` instead of other truncations
'math/prefer-math-trunc': OFF,
// enforce the use of `Number.EPSILON` instead of other ways
'math/prefer-number-epsilon': OFF,
// enforce the use of `Number.isFinite()` instead of other checking ways
'math/prefer-number-is-finite': OFF,
// enforce the use of `Number.isInteger()` instead of other checking ways
'math/prefer-number-is-integer': OFF,
// enforce the use of `Number.isNaN()` instead of other checking ways
'math/prefer-number-is-nan': OFF,
// enforce the use of `Number.isSafeInteger()` instead of other checking ways
'math/prefer-number-is-safe-integer': OFF,
// enforce the use of `Number.MAX_SAFE_INTEGER` instead of other ways
'math/prefer-number-max-safe-integer': OFF,
// enforce the use of `Number.MIN_SAFE_INTEGER` instead of other ways
'math/prefer-number-min-safe-integer': OFF,
// prefer modern `Math` APIs over legacy patterns
'unicorn/prefer-modern-math-apis': OFF,
// prefer `String#{ startsWith, endsWith }()` over `RegExp#test()`
'unicorn/prefer-string-starts-ends-with': OFF,
};
const forbidES2016BuiltIns = {
'es/no-array-prototype-includes': ERROR,
// prefer `.includes()` over `.indexOf()` and `Array#some()` when checking for existence or non-existence
'unicorn/prefer-includes': OFF,
};
const forbidES2017BuiltIns = {
'es/no-atomics': ERROR,
'es/no-object-entries': ERROR,
'es/no-object-getownpropertydescriptors': ERROR,
'es/no-object-values': ERROR,
'es/no-shared-array-buffer': ERROR,
'es/no-string-prototype-padstart-padend': ERROR,
};
const forbidES2018BuiltIns = {
'es/no-promise-prototype-finally': ERROR,
};
const forbidES2019BuiltIns = {
'es/no-array-prototype-flat': ERROR,
'es/no-object-fromentries': ERROR,
'es/no-string-prototype-trimstart-trimend': ERROR,
'es/no-symbol-prototype-description': ERROR,
// use `.flat()` to flatten an array of arrays
'unicorn/prefer-array-flat': OFF,
// prefer using `Object.fromEntries()` to transform a list of key-value pairs into an object
'unicorn/prefer-object-from-entries': OFF,
// prefer `String#{ trimStart, trimEnd }()` over `String#{ trimLeft, trimRight }()`
'unicorn/prefer-string-trim-start-end': OFF,
};
const forbidES2020BuiltIns = {
'es/no-bigint': ERROR,
'es/no-global-this': ERROR,
'es/no-promise-all-settled': ERROR,
'es/no-regexp-unicode-property-escapes-2020': ERROR,
'es/no-string-prototype-matchall': ERROR,
'es/no-symbol-matchall': ERROR,
// prefer `BigInt` literals over the constructor
'unicorn/prefer-bigint-literals': OFF,
};
const forbidES2021BuiltIns = {
'es/no-promise-any': ERROR,
'es/no-regexp-unicode-property-escapes-2021': ERROR,
'es/no-string-prototype-replaceall': ERROR,
'es/no-weakrefs': ERROR,
// prefer `String#replaceAll()` over regex searches with the global flag
'unicorn/prefer-string-replace-all': OFF,
};
const forbidES2022BuiltIns = {
// prefer `Object.hasOwn`
'prefer-object-has-own': OFF,
'es/no-array-prototype-at': ERROR,
'es/no-error-cause': ERROR,
'es/no-object-hasown': ERROR,
'es/no-regexp-d-flag': ERROR,
'es/no-regexp-unicode-property-escapes-2022': ERROR,
'es/no-string-prototype-at': ERROR,
// prefer `.at()` method for index access and `String#charAt()`
'unicorn/prefer-at': OFF,
};
const forbidES2023BuiltIns = {
'es/no-array-prototype-findlast-findlastindex': ERROR,
'es/no-array-prototype-toreversed': ERROR,
'es/no-array-prototype-tosorted': ERROR,
'es/no-array-prototype-tospliced': ERROR,
'es/no-array-prototype-with': ERROR,
'es/no-regexp-unicode-property-escapes-2023': ERROR,
// prefer `Array#toReversed()` over `Array#reverse()`
'unicorn/no-array-reverse': OFF,
};
const forbidES2024BuiltIns = {
'es/no-arraybuffer-prototype-transfer': ERROR,
'es/no-atomics-waitasync': ERROR,
'es/no-map-groupby': ERROR,
'es/no-object-groupby': ERROR,
'es/no-promise-withresolvers': ERROR,
'es/no-regexp-v-flag': ERROR,
'es/no-resizable-and-growable-arraybuffers': ERROR,
'es/no-string-prototype-iswellformed': ERROR,
'es/no-string-prototype-towellformed': ERROR,
};
const forbidES2025BuiltIns = {
'es/no-dataview-prototype-getfloat16-setfloat16': ERROR,
'es/no-float16array': ERROR,
'es/no-iterator': ERROR,
'es/no-iterator-prototype-drop': ERROR,
'es/no-iterator-prototype-every': ERROR,
'es/no-iterator-prototype-filter': ERROR,
'es/no-iterator-prototype-find': ERROR,
'es/no-iterator-prototype-flatmap': ERROR,
'es/no-iterator-prototype-foreach': ERROR,
'es/no-iterator-prototype-map': ERROR,
'es/no-iterator-prototype-reduce': ERROR,
'es/no-iterator-prototype-some': ERROR,
'es/no-iterator-prototype-take': ERROR,
'es/no-iterator-prototype-toarray': ERROR,
'es/no-math-f16round': ERROR,
'es/no-promise-try': ERROR,
'es/no-set-prototype-difference': ERROR,
'es/no-set-prototype-intersection': ERROR,
'es/no-set-prototype-isdisjointfrom': ERROR,
'es/no-set-prototype-issubsetof': ERROR,
'es/no-set-prototype-issupersetof': ERROR,
'es/no-set-prototype-symmetricdifference': ERROR,
'es/no-set-prototype-union': ERROR,
};
const forbidES2026BuiltIns = {
'es/no-array-fromasync': ERROR,
'es/no-asyncdisposablestack': ERROR,
'es/no-error-iserror': ERROR,
'es/no-iterator-concat': ERROR,
'es/no-json-israwjson': ERROR,
'es/no-json-parse-reviver-context-parameter': ERROR,
'es/no-json-rawjson': ERROR,
'es/no-map-prototype-getorinsert': ERROR,
'es/no-map-prototype-getorinsertcomputed': ERROR,
'es/no-math-sumprecise': ERROR,
'es/no-suppressederror': ERROR,
'es/no-symbol-asyncdispose': ERROR,
'es/no-symbol-dispose': ERROR,
'es/no-uint8array-frombase64': ERROR,
'es/no-uint8array-fromhex': ERROR,
'es/no-uint8array-prototype-setfrombase64': ERROR,
'es/no-uint8array-prototype-setfromhex': ERROR,
'es/no-uint8array-prototype-tobase64': ERROR,
'es/no-uint8array-prototype-tohex': ERROR,
'es/no-weakmap-prototype-getorinsert': ERROR,
'es/no-weakmap-prototype-getorinsertcomputed': ERROR,
// enforce the use of `Math.sumPrecise` instead of other summation methods
'math/prefer-math-sum-precise': OFF,
};
const forbidES2016IntlBuiltIns = {
'es/no-intl-getcanonicallocales': ERROR,
};
const forbidES2017IntlBuiltIns = {
'es/no-intl-datetimeformat-prototype-formattoparts': ERROR,
};
const forbidES2018IntlBuiltIns = {
'es/no-intl-numberformat-prototype-formattoparts': ERROR,
'es/no-intl-pluralrules': ERROR,
};
const forbidES2020IntlBuiltIns = {
'es/no-intl-locale': ERROR,
'es/no-intl-relativetimeformat': ERROR,
};
const forbidES2021IntlBuiltIns = {
'es/no-intl-datetimeformat-prototype-formatrange': ERROR,
'es/no-intl-displaynames': ERROR,
'es/no-intl-listformat': ERROR,
};
const forbidES2022IntlBuiltIns = {
'es/no-intl-segmenter': ERROR,
'es/no-intl-supportedvaluesof': ERROR,
};
const forbidES2023IntlBuiltIns = {
'es/no-intl-numberformat-prototype-formatrange': ERROR,
'es/no-intl-numberformat-prototype-formatrangetoparts': ERROR,
'es/no-intl-pluralrules-prototype-selectrange': ERROR,
};
const forbidES2025IntlBuiltIns = {
'es/no-intl-durationformat': ERROR,
};
const forbidES2026IntlBuiltIns = {
'es/no-intl-locale-prototype-firstdayofweek': ERROR,
'es/no-intl-locale-prototype-getcalendars': ERROR,
'es/no-intl-locale-prototype-getcollations': ERROR,
'es/no-intl-locale-prototype-gethourcycles': ERROR,
'es/no-intl-locale-prototype-getnumberingsystems': ERROR,
'es/no-intl-locale-prototype-gettextinfo': ERROR,
'es/no-intl-locale-prototype-gettimezones': ERROR,
'es/no-intl-locale-prototype-getweekinfo': ERROR,
};
const forbidSomeES2025Syntax = {
'es/no-regexp-duplicate-named-capturing-groups': ERROR,
'es/no-regexp-modifiers': ERROR,
'es/no-import-attributes': ERROR,
'es/no-dynamic-import-options': ERROR,
'es/no-trailing-dynamic-import-commas': ERROR,
'es/no-json-modules': ERROR,
};
const forbidModernBuiltIns = {
...forbidESAnnexBBuiltIns,
...forbidES5BuiltIns,
...forbidES2015BuiltIns,
...forbidES2016BuiltIns,
...forbidES2017BuiltIns,
...forbidES2018BuiltIns,
...forbidES2019BuiltIns,
...forbidES2020BuiltIns,
...forbidES2021BuiltIns,
...forbidES2022BuiltIns,
...forbidES2023BuiltIns,
...forbidES2024BuiltIns,
...forbidES2025BuiltIns,
...forbidES2026BuiltIns,
...forbidES2016IntlBuiltIns,
...forbidES2017IntlBuiltIns,
...forbidES2018IntlBuiltIns,
...forbidES2020IntlBuiltIns,
...forbidES2021IntlBuiltIns,
...forbidES2022IntlBuiltIns,
...forbidES2023IntlBuiltIns,
...forbidES2025IntlBuiltIns,
// prefer using `structuredClone` to create a deep clone
'unicorn/prefer-structured-clone': OFF,
};
const polyfills = {
// prefer `node:` protocol
'node/prefer-node-protocol': OFF,
// enforces the use of `catch()` on un-returned promises
'promise/catch-or-return': OFF,
// avoid nested `then()` or `catch()` statements
'promise/no-nesting': OFF,
// prefer catch to `then(a, b)` / `then(null, b)` for handling errors
'promise/prefer-catch': OFF,
// prefer `RegExp#test()` over `String#match()` and `RegExp#exec()`
// use `RegExp#exec()` since it does not have implicit calls under the hood
'regexp/prefer-regexp-test': OFF,
// shorthand promises should be used
'sonarjs/prefer-promise-shorthand': OFF,
// disallow `instanceof` with built-in objects
'unicorn/no-instanceof-builtins': OFF,
};
const transpiledAndPolyfilled = {
...noAsyncAwait,
// disallow accessor properties
'es/no-accessor-properties': ERROR,
// disallow async functions
'es/no-async-functions': ERROR,
// disallow async iteration
'es/no-async-iteration': ERROR,
// disallow top-level `await`
'es/no-top-level-await': ERROR,
// unpolyfillable es2015 builtins
'es/no-proxy': ERROR,
// disallow duplicate named capture groups
'es/no-regexp-duplicate-named-capturing-groups': OFF,
'es/no-string-prototype-normalize': ERROR,
// unpolyfillable es2017 builtins
'es/no-atomics': ERROR,
'es/no-shared-array-buffer': ERROR,
// unpolyfillable es2020 builtins
'es/no-bigint': ERROR,
// unpolyfillable es2021 builtins
'es/no-weakrefs': ERROR,
// prefer lookarounds over capturing group that do not replace
'regexp/prefer-lookaround': [ERROR, { lookbehind: false, strictTypes: true }],
// enforce using named capture group in regular expression
'regexp/prefer-named-capture-group': OFF,
// prefer `BigInt` literals over the constructor
'unicorn/prefer-bigint-literals': OFF,
...forbidSomeES2025Syntax,
...forbidCompletelyNonExistentBuiltIns,
};
const nodePackages = {
// disallow logical assignment operator shorthand
'logical-assignment-operators': [ERROR, NEVER],
// disallow unsupported ECMAScript built-ins on the specified version
'node/no-unsupported-features/node-builtins': [ERROR, { version: PACKAGES_NODE_VERSIONS, allowExperimental: false }],
// prefer `node:` protocol
'node/prefer-node-protocol': OFF,
// prefer promises
'node/prefer-promises/dns': OFF,
'node/prefer-promises/fs': OFF,
// prefer lookarounds over capturing group that do not replace
'regexp/prefer-lookaround': [ERROR, { lookbehind: false, strictTypes: true }],
// enforce using named capture group in regular expression
'regexp/prefer-named-capture-group': OFF,
// prefer class field declarations over this assignments in constructors
'unicorn/prefer-class-fields': OFF,
// prefer using a logical operator over a ternary
'unicorn/prefer-logical-operator-over-ternary': OFF,
// prefer using the `node:` protocol when importing Node builtin modules
'unicorn/prefer-node-protocol': OFF,
// prefer omitting the `catch` binding parameter
'unicorn/prefer-optional-catch-binding': OFF,
// prefer using `structuredClone` to create a deep clone
'unicorn/prefer-structured-clone': OFF,
...disable(forbidES5BuiltIns),
...disable(forbidES2015BuiltIns),
...disable(forbidES2016BuiltIns),
...disable(forbidES2017BuiltIns),
'es/no-atomics': ERROR,
'es/no-shared-array-buffer': ERROR,
// disallow top-level `await`
'es/no-top-level-await': ERROR,
...forbidES2018BuiltIns,
...forbidES2019BuiltIns,
...forbidES2020BuiltIns,
...forbidES2021BuiltIns,
...forbidES2022BuiltIns,
...forbidES2023BuiltIns,
...forbidES2024BuiltIns,
...forbidES2025BuiltIns,
...forbidES2026BuiltIns,
...disable(forbidES2016IntlBuiltIns),
...disable(forbidES2017IntlBuiltIns),
...forbidES2018IntlBuiltIns,
...forbidES2020IntlBuiltIns,
...forbidES2021IntlBuiltIns,
...forbidES2022IntlBuiltIns,
...forbidES2023IntlBuiltIns,
...forbidES2025IntlBuiltIns,
...forbidES2026IntlBuiltIns,
...forbidSomeES2025Syntax,
};
const nodeDev = {
// disallow unsupported ECMAScript built-ins on the specified version
'node/no-unsupported-features/node-builtins': [ERROR, { version: DEV_NODE_VERSIONS, ignores: ['fetch'], allowExperimental: false }],
...disable(forbidModernBuiltIns),
...forbidES2024BuiltIns,
'es/no-regexp-v-flag': OFF,
'es/no-string-prototype-iswellformed': OFF,
'es/no-string-prototype-towellformed': OFF,
...forbidES2025BuiltIns,
...forbidES2026BuiltIns,
...forbidES2025IntlBuiltIns,
...forbidES2026IntlBuiltIns,
// ReDoS vulnerability check
'redos/no-vulnerable': OFF,
// prefer top-level await
'unicorn/prefer-top-level-await': ERROR,
...forbidSomeES2025Syntax,
};
const tests = {
// relax for testing:
// enforces return statements in callbacks of array's methods
'array-callback-return': OFF,
// specify the maximum number of statement allowed in a function
'max-statements': OFF,
// disallow function declarations and expressions inside loop statements
'no-loop-func': OFF,
// disallow use of new operator when not part of the assignment or comparison
'no-new': OFF,
// disallow use of new operator for Function object
'no-new-func': OFF,
// disallows creating new instances of String, Number, and Boolean
'no-new-wrappers': OFF,
// disallow specified syntax
'no-restricted-syntax': OFF,
// restrict what can be thrown as an exception
'no-throw-literal': OFF,
// disallow usage of expressions in statement position
'no-unused-expressions': OFF,
// disallow dangling underscores in identifiers
'no-underscore-dangle': [ERROR, { allow: [
'__defineGetter__',
'__defineSetter__',
'__lookupGetter__',
'__lookupSetter__',
] }],
// disallow unnecessary calls to `.call()` and `.apply()`
'no-useless-call': OFF,
// specify the maximum length of a line in your program
'@stylistic/max-len': [ERROR, { ...base['@stylistic/max-len'][1], code: 180 }],
// enforces the use of `catch()` on un-returned promises
'promise/catch-or-return': OFF,
// prefer catch to `then(a, b)` / `then(null, b)` for handling errors
'promise/prefer-catch': OFF,
// shorthand promises should be used
'sonarjs/prefer-promise-shorthand': OFF,
// enforce passing a message value when throwing a built-in error
'unicorn/error-message': OFF,
// prefer `Array#toReversed()` over `Array#reverse()`
'unicorn/no-array-reverse': OFF,
// disallow immediate mutation after variable assignment
'unicorn/no-immediate-mutation': OFF,
// disallow `instanceof` with built-in objects
'unicorn/no-instanceof-builtins': OFF,
// prefer `.at()` method for index access and `String#charAt()`
'unicorn/prefer-at': OFF,
// prefer `.includes()` over `.indexOf()` and `Array#some()` when checking for existence or non-existence
'unicorn/prefer-includes': OFF,
// ReDoS vulnerability check
'redos/no-vulnerable': OFF,
// allow Annex B methods for testing
...disable(forbidESAnnexBBuiltIns),
};
const qunit = {
// ensure the correct number of assert arguments is used
'qunit/assert-args': ERROR,
// enforce comparison assertions have arguments in the right order
'qunit/literal-compare-order': ERROR,
// forbid the use of `assert.equal`
'qunit/no-assert-equal': ERROR,
// require use of boolean assertions
'qunit/no-assert-equal-boolean': ERROR,
// disallow binary logical expressions in assert arguments
'qunit/no-assert-logical-expression': ERROR,
// forbid async calls in loops
'qunit/no-async-in-loops': ERROR,
// disallow async module callbacks
'qunit/no-async-module-callbacks': ERROR,
// forbid the use of `asyncTest`
'qunit/no-async-test': ERROR,
// forbid commented tests
'qunit/no-commented-tests': ERROR,
// forbid comparing relational expression to boolean in assertions
'qunit/no-compare-relation-boolean': ERROR,
// prevent early return in a qunit test
'qunit/no-early-return': ERROR,
// forbid the use of global qunit assertions
'qunit/no-global-assertions': ERROR,
// forbid the use of global `expect`
'qunit/no-global-expect': ERROR,
// forbid the use of global `module` / `test` / `asyncTest`
'qunit/no-global-module-test': ERROR,
// forbid use of global `stop` / `start`
'qunit/no-global-stop-start': ERROR,
// disallow the use of hooks from ancestor modules
'qunit/no-hooks-from-ancestor-modules': ERROR,
// forbid identical test and module names
'qunit/no-identical-names': ERROR,
// forbid use of `QUnit.init`
'qunit/no-init': ERROR,
// forbid use of `QUnit.jsDump`
'qunit/no-jsdump': ERROR,
// disallow the use of `assert.equal` / `assert.ok` / `assert.notEqual` / `assert.notOk``
'qunit/no-loose-assertions': ERROR,
// forbid `QUnit.test()` calls inside callback of another `QUnit.test`
'qunit/no-nested-tests': ERROR,
// forbid equality comparisons in `assert.{ ok, notOk }`
'qunit/no-ok-equality': ERROR,
// disallow `QUnit.only`
'qunit/no-only': ERROR,
// forbid the use of `QUnit.push`
'qunit/no-qunit-push': ERROR,
// forbid `QUnit.start` within tests or test hooks
'qunit/no-qunit-start-in-tests': ERROR,
// forbid the use of `QUnit.stop`
'qunit/no-qunit-stop': ERROR,
// forbid overwriting of QUnit logging callbacks
'qunit/no-reassign-log-callbacks': ERROR,
// forbid use of `QUnit.reset`
'qunit/no-reset': ERROR,
// forbid setup / teardown module hooks
'qunit/no-setup-teardown': ERROR,
// forbid expect argument in `QUnit.test`
'qunit/no-test-expect-argument': ERROR,
// forbid assert.throws() with block, string, and message
'qunit/no-throws-string': ERROR,
// enforce use of objects as expected value in `assert.propEqual`
'qunit/require-object-in-propequal': ERROR,
// require that all async calls should be resolved in tests
'qunit/resolve-async': ERROR,
};
const playwright = {
// enforce Playwright APIs to be awaited
'playwright/missing-playwright-await': ERROR,
// disallow usage of `page.$eval()` and `page.$$eval()`
'playwright/no-eval': ERROR,
// disallow using `page.pause()`
'playwright/no-page-pause': ERROR,
// prevent unsafe variable references in `page.evaluate()`
'playwright/no-unsafe-references': ERROR,
// disallow unnecessary awaits for Playwright methods
'playwright/no-useless-await': ERROR,
};
const yaml = {
// disallow empty mapping values
'yaml/no-empty-mapping-value': ERROR,
};
const json = {
// enforce spacing inside array brackets
'jsonc/array-bracket-spacing': [ERROR, NEVER],
// disallow trailing commas in multiline object literals
'jsonc/comma-dangle': [ERROR, NEVER],
// enforce one true comma style
'jsonc/comma-style': [ERROR, 'last'],
// enforce consistent indentation
'jsonc/indent': [ERROR, 2],
// enforces spacing between keys and values in object literal properties
'jsonc/key-spacing': [ERROR, { beforeColon: false, afterColon: true }],
// disallow BigInt literals
'jsonc/no-bigint-literals': ERROR,
// disallow binary expression
'jsonc/no-binary-expression': ERROR,
// disallow binary numeric literals
'jsonc/no-binary-numeric-literals': ERROR,
// disallow comments
'jsonc/no-comments': ERROR,
// disallow duplicate keys when creating object literals
'jsonc/no-dupe-keys': ERROR,
// disallow escape sequences in identifiers.
'jsonc/no-escape-sequence-in-identifier': ERROR,
// disallow leading or trailing decimal points in numeric literals
'jsonc/no-floating-decimal': ERROR,
// disallow hexadecimal numeric literals
'jsonc/no-hexadecimal-numeric-literals': ERROR,
// disallow `Infinity`
'jsonc/no-infinity': ERROR,
// disallow irregular whitespace
'jsonc/no-irregular-whitespace': [ERROR, {}],
// disallow use of multiline strings
'jsonc/no-multi-str': ERROR,
// disallow `NaN`
'jsonc/no-nan': ERROR,
// disallow number property keys
'jsonc/no-number-props': ERROR,
// disallow numeric separators
'jsonc/no-numeric-separators': ERROR,
// disallow use of octal escape sequences in string literals, such as var foo = 'Copyright \251';
'jsonc/no-octal-escape': ERROR,
// disallow octal numeric literals
'jsonc/no-octal-numeric-literals': ERROR,
// disallow legacy octal literals
'jsonc/no-octal': ERROR,
// disallow parentheses around the expression
'jsonc/no-parenthesized': ERROR,
// disallow plus sign
'jsonc/no-plus-sign': ERROR,
// disallow RegExp literals
'jsonc/no-regexp-literals': ERROR,
// disallow sparse arrays
'jsonc/no-sparse-arrays': ERROR,
// disallow template literals
'jsonc/no-template-literals': ERROR,
// disallow `undefined`
'jsonc/no-undefined-value': ERROR,
// disallow Unicode code point escape sequences.
'jsonc/no-unicode-codepoint-escapes': ERROR,
// disallow unnecessary string escaping
'jsonc/no-useless-escape': ERROR,
// enforce consistent line breaks after opening and before closing braces
'jsonc/object-curly-newline': [ERROR, { consistent: true }],
// enforce spaces inside braces
'jsonc/object-curly-spacing': [ERROR, ALWAYS],
// require or disallow use of quotes around object literal property names
'jsonc/quote-props': [ERROR, ALWAYS],
// specify whether double or single quotes should be used
'jsonc/quotes': [ERROR, 'double'],
// require or disallow spaces before/after unary operators
'jsonc/space-unary-ops': ERROR,
// disallow invalid number for JSON
'jsonc/valid-json-number': ERROR,
// specify the maximum length of a line in your program
'@stylistic/max-len': OFF,
// require strict mode directives
strict: OFF,
};
const packageJSON = {
// enforce that names for bin properties are in kebab case
'package-json/bin-name-casing': ERROR,
// enforce consistent format for the exports field (implicit or explicit subpaths)
'package-json/exports-subpaths-style': [ERROR, { prefer: 'explicit' }],
// reports on unnecessary empty arrays and objects
'package-json/no-empty-fields': ERROR,
// prevents adding unnecessary / redundant files
'package-json/no-redundant-files': ERROR,
// warns when `publishConfig.access` is used in unscoped packages
'package-json/no-redundant-publishConfig': ERROR,
// disallows unnecessary properties in private packages
'package-json/restrict-private-properties': ERROR,
// enforce that names for `scripts` are in kebab case (optionally separated by colons)
'package-json/scripts-name-casing': ERROR,
// enforce that package dependencies are unique
'package-json/unique-dependencies': ERROR,
// enforce that the author field is a valid npm author specification
'package-json/valid-author': ERROR,
// enforce that the `bundleDependencies` (or `bundledDependencies`) property is valid
'package-json/valid-bundleDependencies': ERROR,
// enforce that the `bin` property is valid
'package-json/valid-bin': ERROR,
// enforce that the `config` property is valid
'package-json/valid-config': ERROR,
// enforce that the `contributors` property is valid
'package-json/valid-contributors': ERROR,
// enforce that the `cpu` property is valid
'package-json/valid-cpu': ERROR,
// enforce that the `dependencies` property is valid
'package-json/valid-dependencies': ERROR,
// enforce that the `description` property is valid
'package-json/valid-description': ERROR,
// enforce that the `directories` property is valid
'package-json/valid-directories': ERROR,
// enforce that the `engines` property is valid
'package-json/valid-engines': ERROR,
// enforce that the `exports` property is valid
'package-json/valid-exports': ERROR,
// enforce that the `files` property is valid
'package-json/valid-files': ERROR,
// enforce that the `homepage` property is valid
'package-json/valid-homepage': ERROR,
// enforce that the `keywords` property is valid
'package-json/valid-keywords': ERROR,
// enforce that the `license` property is valid
'package-json/valid-license': ERROR,
// enforce that the `main` property is valid
'package-json/valid-main': ERROR,
// enforce that the `man` property is valid
'package-json/valid-man': ERROR,
// enforce that the `module` property is valid
'package-json/valid-module': ERROR,
// enforce that the `os` property is valid
'package-json/valid-os': ERROR,
// enforce that the `private` property is valid
'package-json/valid-private': ERROR,
// enforce that the `publishConfig` property is valid
'package-json/valid-publishConfig': ERROR,
// enforce that the `repository` property is valid
'package-json/valid-repository': ERROR,
// enforce that if repository directory is specified, it matches the path to the package.json file
'package-json/valid-repository-directory': ERROR,
// enforce that the `scripts` property is valid.
'package-json/valid-scripts': ERROR,
// enforce that the `sideEffects` property is valid.
'package-json/valid-sideEffects': ERROR,
// enforce that the `type` property is valid
'package-json/valid-type': ERROR,
// enforce that package versions are valid semver specifiers
'package-json/valid-version': ERROR,
// enforce that the `workspaces` property is valid
'package-json/valid-workspaces': ERROR,
};
const packagesPackageJSON = {
// enforce either object or shorthand declaration for repository
'package-json/repository-shorthand': [ERROR, { form: 'object' }],
// ensures that proper attribution is included, requiring that either `author` or `contributors` is defined,
// and that if `contributors` is present, it should include at least one contributor
'package-json/require-attribution': ERROR,
// requires the `author` property to be present
'package-json/require-author': ERROR,
// requires the `bugs`` property to be present
'package-json/require-bugs': ERROR,
// requires the `description` property to be present
'package-json/require-description': ERROR,
// requires the `engines` property to be present
// TODO: core-js@4
// 'package-json/require-engines': ERROR,
// requires the `exports` property to be present
// TODO: core-js@4
// 'package-json/require-exports': ERROR,
// requires the `homepage` property to be present
'package-json/require-homepage': ERROR,
// requires the `license` property to be present
'package-json/require-license': ERROR,
// requires the `name` property to be present
'package-json/require-name': ERROR,
// requires the `repository` property to be present
'package-json/require-repository': ERROR,
// requires the `sideEffects` property to be present
'package-json/require-sideEffects': ERROR,
// requires the `types` property to be present
// TODO: core-js@4
// 'package-json/require-types': ERROR,
// requires the `version` property to be present
'package-json/require-version': ERROR,
// enforce that package names are valid npm package names
'package-json/valid-name': ERROR,
};
const nodeDependencies = {
// enforce the versions of the engines of the dependencies to be compatible
'node-dependencies/compat-engines': ERROR,
// disallow having dependencies on deprecate packages
'node-dependencies/no-deprecated': ERROR,
// enforce versions that is valid as a semantic version
'node-dependencies/valid-semver': ERROR,
};
const markdown = {
...base,
...disable(forbidModernBuiltIns),
...forbidCompletelyNonExistentBuiltIns,
// allow use of console
'no-console': OFF,
// disallow use of new operator when not part of the assignment or comparison
'no-new': OFF,
// disallow specified syntax
'no-restricted-syntax': OFF,
// disallow use of undeclared variables unless mentioned in a /*global */ block
'no-undef': OFF,
// disallow usage of expressions in statement position
'no-unused-expressions': OFF,
// disallow declaration of variables that are not used in the code
'no-unused-vars': OFF,
// require let or const instead of var
'no-var': OFF,
// require const declarations for variables that are never reassigned after declared
'prefer-const': OFF,
// disallow use of the `RegExp` constructor in favor of regular expression literals
'prefer-regex-literals': OFF,
// disallow top-level `await`
'es/no-top-level-await': OFF,
// ensure imports point to files / modules that can be resolved
'import/no-unresolved': OFF,
// enforces the use of `catch()` on un-returned promises
'promise/catch-or-return': OFF,
// enforce that `RegExp#exec` is used instead of `String#match` if no global flag is provided
'regexp/prefer-regexp-exec': OFF,
// variables should be defined before being used
'sonarjs/no-reference-error': OFF,
// specify the maximum length of a line in your program
'@stylistic/max-len': [ERROR, { ...base['@stylistic/max-len'][1], code: 200 }],
};
const globalsESNext = {
AsyncIterator: READONLY,
compositeKey: READONLY,
compositeSymbol: READONLY,
};
const globalsZX = {
$: READONLY,
__dirname: READONLY,
__filename: READONLY,
argv: READONLY,
cd: READONLY,
chalk: READONLY,
echo: READONLY,
fetch: READONLY,
fs: READONLY,
glob: READONLY,
nothrow: READONLY,
os: READONLY,
path: READONLY,
question: READONLY,
require: READONLY,
sleep: READONLY,
stdin: READONLY,
which: READONLY,
within: READONLY,
YAML: READONLY,
};
export default [
{
ignores: [
'deno/corejs/**',
'docs/**',
'packages/core-js-bundle/!(package.json)',
'packages/core-js-compat/!(package).json',
'packages/core-js-pure/override/**',
'tests/**/bundles/**',
'tests/compat/compat-data.js',
'tests/unit-@(global|pure)/index.js',
'website/dist/**',
'website/src/public/*',
'website/templates/**',
],
},
{
languageOptions: {
ecmaVersion: 'latest',
sourceType: 'script',
// unnecessary global builtins disabled by related rules
globals: {
...globals.builtin,
...globals.browser,
...globals.node,
...globals.worker,
},
},
linterOptions: {
reportUnusedDisableDirectives: true,
},
plugins: {
'@stylistic': pluginStylistic,
'array-func': pluginArrayFunc,
ascii: pluginASCII,
depend: pluginDepend,
es: pluginESX,
'eslint-comments': pluginESlintComments,
import: pluginImport,
jsonc: pluginJSONC,
markdown: pluginMarkdown,
math: pluginMath,
name: pluginName,
node: pluginN,
'node-dependencies': pluginNodeDependencies,
'package-json': pluginPackageJSON,
playwright: pluginPlaywright,
promise: pluginPromise,
qunit: pluginQUnit,
redos: pluginReDoS,
regexp: pluginRegExp,
sonarjs: pluginSonarJS,
unicorn: pluginUnicorn,
yaml: pluginYaml,
},
rules: {
...base,
...forbidNonStandardBuiltIns,
...forbidESAnnexBBuiltIns,
},
settings: {
'es-x': { allowTestedProperty: true },
},
},
{
files: [
'**/*.mjs',
'tests/eslint/**',
],
languageOptions: {
sourceType: 'module',
},
},
{
files: [
'packages/core-js?(-pure)/**',
'tests/@(compat|worker)/*.js',
],
languageOptions: {
ecmaVersion: 3,
},
rules: useES3Syntax,
},
{
files: [
'packages/core-js?(-pure)/**',
'tests/@(helpers|unit-pure|worker)/**',
'tests/compat/@(browsers|hermes|node|rhino)-runner.js',
],
rules: forbidModernBuiltIns,
},
{
files: [
'packages/core-js?(-pure)/**',
],
rules: polyfills,
},
{
files: [
'**/postinstall.js',
],
rules: disable(forbidES5BuiltIns),
},
{
files: [
'packages/core-js?(-pure)/**/instance/**',
],
rules: {
...disable(forbidModernBuiltIns),
...forbidCompletelyNonExistentBuiltIns,
},
},
{
files: [
'tests/@(helpers|unit-@(global|pure)|wpt-url-resources)/**',
],
languageOptions: {
sourceType: 'module',
},
rules: transpiledAndPolyfilled,
},
{
files: [
'tests/**',
],
rules: tests,
},
{
files: [
'tests/compat/tests.js',
],
rules: forbidCompletelyNonExistentBuiltIns,
},
{
files: [
'tests/@(helpers|unit-@(global|pure))/**',
],
languageOptions: {
globals: globals.qunit,
},
rules: qunit,
},
{
files: [
'scripts/usage/**',
],
rules: playwright,
},
{
files: [
'packages/core-js-@(builder|compat)/**',
],
rules: nodePackages,
},
{
files: [
'*.js',
'packages/core-js-compat/src/**',
'scripts/**',
'tests/compat/*.mjs',
'tests/@(compat-@(data|tools)|eslint|entries|observables|promises-aplus|unit-@(karma|node))/**',
'website/runner.mjs',
'website/helpers.mjs',
],
rules: nodeDev,
},
{
files: [
'tests/@(compat|unit-global)/**',
],
languageOptions: {
globals: globalsESNext,
},
},
{
files: [
'@(scripts|tests)/*/**',
],
rules: {
// disable this rule for lazily installed dependencies
'import/no-unresolved': [ERROR, { commonjs: true, ignore: ['^[^.]'] }],
},
},
{
files: [
'packages/core-js-compat/src/**',
'scripts/**',
'tests/**/*.mjs',
'website/**.mjs',
],
languageOptions: {
// zx
globals: globalsZX,
},
rules: {
// allow use of console
'no-console': OFF,
// import used for tasks
'import/first': OFF,
},
},
{
rules: {
// ensure that filenames match a convention
'name/match': [ERROR, /^[\da-z][\d\-.a-z]*[\da-z]$/],
},
},
{
files: [
'packages/core-js?(-pure)/modules/**',
],
rules: {
// ensure that filenames match a convention
'name/match': [ERROR, /^(?:es|esnext|web)(?:\.[a-z][\d\-a-z]*[\da-z])+$/],
},
},
{
files: [
'tests/@(unit-@(global|pure))/**',
],
rules: {
// ensure that filenames match a convention
'name/match': [ERROR, /^(?:es|esnext|helpers|web)(?:\.[a-z][\d\-a-z]*[\da-z])+$/],
},
},
{
language: 'yaml/yaml',
files: ['*.yaml', '*.yml'],
rules: yaml,
},
{
files: ['**/*.json'],
languageOptions: {
parser: parserJSONC,
},
rules: json,
},
{
files: ['**/package.json'],
rules: {
...packageJSON,
...nodeDependencies,
},
},
{
files: ['packages/*/package.json'],
rules: packagesPackageJSON,
},
{
files: ['**/*.md'],
processor: 'markdown/markdown',
},
{
files: ['**/*.md/*.js'],
languageOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
},
rules: markdown,
},
{
files: ['**/*.md/*'],
rules: {
// enforce a case style for filenames
'unicorn/filename-case': OFF,
// ensure that filenames match a convention
'name/match': OFF,
},
},
{
files: [
'website/src/js/*',
],
languageOptions: {
sourceType: 'module',
},
rules: {
...transpiledAndPolyfilled,
'no-restricted-globals': OFF,
'unicorn/prefer-global-this': OFF,
'@stylistic/quotes': [ERROR, 'single', { allowTemplateLiterals: ALWAYS }],
},
},
{
files: [
'website/**',
],
rules: {
'import/no-unresolved': OFF,
},
},
];
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/eslint/runner.mjs
|
JavaScript
|
process.env.ESLINT_USE_FLAT_CONFIG = true;
await $`TIMING=1 eslint --concurrency=auto --config ./tests/eslint/eslint.config.js ./`;
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/helpers/constants.js
|
JavaScript
|
import defineProperty from 'core-js-pure/es/object/define-property';
export const DESCRIPTORS = !!(() => {
try {
return defineProperty({}, 'a', {
get() {
return 7;
},
}).a === 7;
} catch { /* empty */ }
})();
export const GLOBAL = Function('return this')();
export const NATIVE = GLOBAL.NATIVE || false;
export const NODE = typeof Bun == 'undefined' && Object.prototype.toString.call(GLOBAL.process).slice(8, -1) === 'process';
export const BUN = typeof Bun != 'undefined' && Object.prototype.toString.call(GLOBAL.process).slice(8, -1) === 'process';
const $TYPED_ARRAYS = {
Float32Array: 4,
Float64Array: 8,
Int8Array: 1,
Int16Array: 2,
Int32Array: 4,
Uint8Array: 1,
Uint16Array: 2,
Uint32Array: 4,
Uint8ClampedArray: 1,
};
export const TYPED_ARRAYS = [];
for (const name in $TYPED_ARRAYS) TYPED_ARRAYS.push({
name,
TypedArray: GLOBAL[name],
bytes: $TYPED_ARRAYS[name],
$: Number,
});
export const TYPED_ARRAYS_WITH_BIG_INT = [...TYPED_ARRAYS];
for (const name of ['BigInt64Array', 'BigUint64Array']) if (GLOBAL[name]) TYPED_ARRAYS_WITH_BIG_INT.push({
name,
TypedArray: GLOBAL[name],
bytes: 8,
// eslint-disable-next-line es/no-bigint -- safe
$: BigInt,
});
export const LITTLE_ENDIAN = (() => {
try {
return new GLOBAL.Uint8Array(new GLOBAL.Uint16Array([1]).buffer)[0] === 1;
} catch {
return true;
}
})();
// eslint-disable-next-line es/no-object-setprototypeof -- detection
export const PROTO = !!Object.setPrototypeOf || '__proto__' in Object.prototype;
export let REDEFINABLE_PROTO = false;
try {
// Chrome 27- bug, also a bug for native `JSON.parse`
defineProperty({}, '__proto__', { value: 42, writable: true, configurable: true, enumerable: true });
REDEFINABLE_PROTO = true;
} catch { /* empty */ }
export const STRICT_THIS = (function () {
return this;
})();
export const STRICT = !STRICT_THIS;
export const FREEZING = !function () {
try {
// eslint-disable-next-line es/no-object-isextensible, es/no-object-preventextensions -- detection
return Object.isExtensible(Object.preventExtensions({}));
} catch {
return true;
}
}();
export const CORRECT_PROTOTYPE_GETTER = !function () {
try {
function F() { /* empty */ }
F.prototype.constructor = null;
// eslint-disable-next-line es/no-object-getprototypeof -- detection
return Object.getPrototypeOf(new F()) !== F.prototype;
} catch {
return true;
}
}();
// FF < 23 bug
export const REDEFINABLE_ARRAY_LENGTH_DESCRIPTOR = DESCRIPTORS && !function () {
try {
defineProperty([], 'length', { writable: false });
} catch {
return true;
}
}();
export const WHITESPACES = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF';
// eslint-disable-next-line es/no-number-maxsafeinteger -- safe
export const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
// eslint-disable-next-line es/no-number-minsafeinteger -- safe
export const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991;
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/helpers/helpers.js
|
JavaScript
|
import Promise from 'core-js-pure/es/promise';
import ITERATOR from 'core-js-pure/es/symbol/iterator';
import ASYNC_ITERATOR from 'core-js-pure/es/symbol/async-iterator';
export function is(a, b) {
// eslint-disable-next-line no-self-compare -- NaN check
return a === b ? a !== 0 || 1 / a === 1 / b : a !== a && b !== b;
}
export function createIterator(elements, methods) {
let index = 0;
const iterator = {
called: false,
next() {
iterator.called = true;
return {
value: elements[index++],
done: index > elements.length,
};
},
};
if (methods) for (const key in methods) iterator[key] = methods[key];
return iterator;
}
export function createSetLike(elements) {
return {
size: elements.length,
has(it) {
return includes(elements, it);
},
keys() {
return createIterator(elements);
},
};
}
export function createIterable(elements, methods) {
const iterable = {
called: false,
received: false,
[ITERATOR]() {
iterable.received = true;
let index = 0;
const iterator = {
next() {
iterable.called = true;
return {
value: elements[index++],
done: index > elements.length,
};
},
};
if (methods) for (const key in methods) iterator[key] = methods[key];
return iterator;
},
};
return iterable;
}
export function createAsyncIterable(elements, methods) {
const iterable = {
called: false,
received: false,
[ASYNC_ITERATOR]() {
iterable.received = true;
let index = 0;
const iterator = {
next() {
iterable.called = true;
return Promise.resolve({
value: elements[index++],
done: index > elements.length,
});
},
};
if (methods) for (const key in methods) iterator[key] = methods[key];
return iterator;
},
};
return iterable;
}
export function createConversionChecker(value, string) {
const checker = {
$valueOf: 0,
$toString: 0,
valueOf() {
checker.$valueOf++;
return value;
},
toString() {
checker.$toString++;
return string !== undefined ? string : String(value);
},
};
return checker;
}
export function arrayFromArrayLike(source) {
const { length } = source;
const result = Array(length);
for (let index = 0; index < length; index++) {
result[index] = source[index];
} return result;
}
export function includes(target, wanted) {
for (const element of target) if (wanted === element) return true;
return false;
}
export const nativeSubclass = (() => {
try {
if (Function(`
'use strict';
class Subclass extends Object { /* empty */ };
return new Subclass() instanceof Subclass;
`)()) return Function('Parent', `
'use strict';
return class extends Parent { /* empty */ };
`);
} catch { /* empty */ }
})();
export function timeLimitedPromise(time, functionOrPromise) {
return Promise.race([
typeof functionOrPromise == 'function' ? new Promise(functionOrPromise) : functionOrPromise,
new Promise((resolve, reject) => {
setTimeout(reject, time);
}),
]);
}
// This function is used to force RegExp.prototype[Symbol.*] methods
// to not use the native implementation.
export function patchRegExp$exec(run) {
return assert => {
const originalExec = RegExp.prototype.exec;
// eslint-disable-next-line no-extend-native -- required for testing
RegExp.prototype.exec = function (...args) {
return originalExec.apply(this, args);
};
try {
return run(assert);
// eslint-disable-next-line no-useless-catch -- in very old IE try / finally does not work without catch
} catch (error) {
throw error;
} finally {
// eslint-disable-next-line no-extend-native -- required for testing
RegExp.prototype.exec = originalExec;
}
};
}
export function fromSource(source) {
try {
return Function(`return ${ source }`)();
} catch { /* empty */ }
}
export function arrayToBuffer(array) {
const { length } = array;
const buffer = new ArrayBuffer(length);
// eslint-disable-next-line es/no-typed-arrays -- safe
const view = new DataView(buffer);
for (let i = 0; i < length; ++i) {
view.setUint8(i, array[i]);
}
return buffer;
}
export function bufferToArray(buffer) {
const array = [];
// eslint-disable-next-line es/no-typed-arrays -- safe
const view = new DataView(buffer);
for (let i = 0, { byteLength } = view; i < byteLength; ++i) {
array.push(view.getUint8(i));
}
return array;
}
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/helpers/qunit-helpers.js
|
JavaScript
|
import { DESCRIPTORS } from './constants.js';
import assign from 'core-js-pure/es/object/assign';
import create from 'core-js-pure/es/object/create';
import defineProperties from 'core-js-pure/es/object/define-properties';
import getOwnPropertyNames from 'core-js-pure/es/object/get-own-property-names';
import reduce from 'core-js-pure/es/array/reduce';
import isIterable from 'core-js-pure/es/is-iterable';
import ASYNC_ITERATOR from 'core-js-pure/es/symbol/async-iterator';
import { is, arrayFromArrayLike } from './helpers.js';
// for Babel template transform
// eslint-disable-next-line es/no-object-create -- safe
if (!Object.create) Object.create = create;
// eslint-disable-next-line es/no-object-freeze -- safe
if (!Object.freeze) Object.freeze = Object;
// eslint-disable-next-line es/no-object-defineproperties -- safe
if (!DESCRIPTORS) Object.defineProperties = defineProperties;
// eslint-disable-next-line es/no-object-getownpropertydescriptor -- safe
const { getOwnPropertyDescriptor } = Object;
const { toString, propertyIsEnumerable } = Object.prototype;
const { assert } = QUnit;
assign(assert, {
arity(fn, length, message) {
this.same(fn.length, length, message ?? `The arity of the function is ${ length }`);
},
arrayEqual(a, b, message) {
this.deepEqual(arrayFromArrayLike(a), arrayFromArrayLike(b), message);
},
avoid(message = 'It should never be called') {
this.ok(false, message);
},
// TODO: Drop from future `core-js` versions
// available from `qunit@2.21`
closeTo(actual, expected, delta, message) {
if (typeof delta != 'number') throw new TypeError('closeTo() requires a delta argument');
const result = Math.abs(actual - expected) <= delta;
this.pushResult({
result,
actual,
expected,
message: message ?? `The value should be within ${ delta } inclusive`,
});
},
enumerable(O, key, message) {
const result = !DESCRIPTORS || propertyIsEnumerable.call(O, key);
this.pushResult({
result,
actual: result,
expected: 'The property should be enumerable',
message: DESCRIPTORS
? message ?? `${ typeof key == 'symbol' ? 'property' : `'${ key }'` } is enumerable`
: 'Enumerability is not applicable',
});
},
// TODO: Drop from future `core-js` versions
// unavailable in `qunit@1` that's required for testing in IE9-, Chrome 38, etc.
false(value, message = 'The value is `false`') {
this.same(value, false, message);
},
isAsyncIterable(actual, message = 'The value is async iterable') {
this.pushResult({
result: typeof actual == 'object' && typeof actual[ASYNC_ITERATOR] == 'function',
actual,
expected: 'The value should be async iterable',
message,
});
},
isFunction(fn, message) {
this.pushResult({
result: typeof fn == 'function' || toString.call(fn).slice(8, -1) === 'Function',
actual: typeof fn,
expected: 'The value should be a function',
message: message ?? 'The value is a function',
});
},
isIterable(actual, message = 'The value is iterable') {
this.pushResult({
result: isIterable(actual),
actual,
expected: 'The value should be iterable',
message,
});
},
isIterator(actual, message = 'The object is an iterator') {
this.pushResult({
result: typeof actual == 'object' && typeof actual.next == 'function',
actual,
expected: 'The object should be an iterator',
message,
});
},
looksNative(fn, message = 'The function looks like a native') {
const source = Function.prototype.toString.call(fn);
this.pushResult({
result: /native code/.test(source),
actual: source,
expected: 'The function should look like a native',
message,
});
},
name(fn, expected, message) {
const applicable = typeof fn == 'function' && 'name' in fn;
const actual = fn.name;
this.pushResult({
result: applicable ? actual === expected : true,
actual,
expected,
message: applicable
? message ?? `The function name is '${ expected }'`
: 'Function#name property test makes no sense',
});
},
nonConfigurable(O, key, message) {
const result = !DESCRIPTORS || !getOwnPropertyDescriptor(O, key)?.configurable;
this.pushResult({
result,
actual: result,
expected: 'The property should be non-configurable',
message: DESCRIPTORS
? message ?? `${ typeof key == 'symbol' ? 'property' : `'${ key }'` } is non-configurable`
: 'Configurability is not applicable',
});
},
nonEnumerable(O, key, message) {
const result = !DESCRIPTORS || !propertyIsEnumerable.call(O, key);
this.pushResult({
result,
actual: result,
expected: 'The property should be non-enumerable',
message: DESCRIPTORS
? message ?? `${ typeof key == 'symbol' ? 'property' : `'${ key }'` } is non-enumerable`
: 'Enumerability is not applicable',
});
},
nonWritable(O, key, message) {
const result = !DESCRIPTORS || !getOwnPropertyDescriptor(O, key)?.writable;
this.pushResult({
result,
actual: result,
expected: 'The property should be non-writable',
message: DESCRIPTORS
? message ?? `${ typeof key == 'symbol' ? 'property' : `'${ key }'` } is non-writable`
: 'Writability is not applicable',
});
},
notSame(actual, expected, message) {
this.pushResult({
result: !is(actual, expected),
actual,
expected: 'Something different',
message,
});
},
notThrows(fn, message = 'Does not throw') {
let result = false;
let actual;
try {
actual = fn();
result = true;
} catch (error) {
actual = error;
}
this.pushResult({
result,
actual,
expected: 'It should not throw an error',
message,
});
},
required(message = 'It should be called') {
this.ok(true, message);
},
same(actual, expected, message) {
this.pushResult({
result: is(actual, expected),
actual,
expected,
message,
});
},
// TODO: Drop from future `core-js` versions
// unavailable in `qunit@1` that's required for testing in IE9-, Chrome 38, etc.
true(value, message = 'The value is `true`') {
this.same(value, true, message);
},
});
assert.skip = reduce(getOwnPropertyNames(assert), (skip, method) => {
skip[method] = () => { /* empty */ };
return skip;
}, {});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/observables/adapter.mjs
|
JavaScript
|
/* eslint-disable import/no-dynamic-require -- dynamic */
delete globalThis.Observable;
const pkg = argv.pure ? 'core-js-pure' : 'core-js';
// eslint-disable-next-line import/no-unresolved -- generated later
const { runTests } = require('./bundles/observables-tests/default');
globalThis.Symbol = require(`../../packages/${ pkg }/full/symbol`);
globalThis.Promise = require(`../../packages/${ pkg }/full/promise`);
const Observable = require(`../../packages/${ pkg }/full/observable`);
runTests(Observable);
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/observables/runner.mjs
|
JavaScript
|
await $`babel --config-file ../../babel.config.js node_modules/es-observable/test/ -d ./bundles/observables-tests/`;
for (const mode of ['global', 'pure']) {
await $`zx adapter.mjs --${ mode }`;
}
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/promises/adapter.js
|
JavaScript
|
'use strict';
delete globalThis.Promise;
const pkg = process.argv.includes('--pure') ? 'core-js-pure' : 'core-js';
// eslint-disable-next-line import/no-dynamic-require -- dynamic
const Promise = require(`../../packages/${ pkg }/es/promise`);
const assert = require('node:assert');
module.exports = {
deferred() {
const deferred = {};
deferred.promise = new Promise((resolve, reject) => {
deferred.resolve = resolve;
deferred.reject = reject;
});
return deferred;
},
resolved(value) {
return Promise.resolve(value);
},
rejected(reason) {
return Promise.reject(reason);
},
defineGlobalPromise() {
globalThis.Promise = Promise;
globalThis.assert = assert;
},
removeGlobalPromise() {
delete globalThis.Promise;
},
};
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/promises/runner.mjs
|
JavaScript
|
for (const mode of ['global', 'pure']) for (const set of ['aplus', 'es6']) {
await $`promises-${ set }-tests adapter --timeout 1000 --color --${ mode }`;
}
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/publint/runner.mjs
|
JavaScript
|
const pkgs = await glob('packages/*/package.json');
await Promise.all(pkgs.map(async pkg => {
return $`publint ${ pkg.slice(0, -13) }`;
}));
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/test262/preprocessor.js
|
JavaScript
|
'use strict';
const include = [
'Array',
// 'ArrayBuffer',
'ArrayIteratorPrototype',
'Boolean',
// 'DataView',
// 'Date',
'Error',
'Function/prototype',
'Iterator',
'JSON',
'Map',
'MapIteratorPrototype',
'Math',
'NativeErrors',
'Number',
'Object',
'Promise',
'Reflect',
'RegExp',
'RegExpStringIteratorPrototype',
'Set',
'SetIteratorPrototype',
'String',
'StringIteratorPrototype',
'Symbol',
// 'TypedArray',
// 'TypedArrayConstructors',
'WeakMap',
'WeakSet',
'decodeURI',
'decodeURIComponent',
'encodeURI',
'encodeURIComponent',
'escape',
'isFinite',
'isNaN',
'parseFloat',
'parseInt',
'unescape',
];
const exclude = [
'/Function/prototype/toString/',
'/Object/internals/DefineOwnProperty/',
// conflict with iterators helpers proposal
'/Object/prototype/toString/symbol-tag-non-str-builtin',
'/RegExp/property-escapes/',
'detached-buffer',
'detach-typedarray',
// we can't implement this behavior on methods 100% proper and compatible with ES3
// in case of application some hacks this line will be removed
'not-a-constructor',
];
module.exports = test => {
const { file } = test;
if (!include.some(namespace => file.includes(`built-ins/${ namespace }/`))) return null;
if (exclude.some(it => file.includes(it))) return null;
return test;
};
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/test262/runner.mjs
|
JavaScript
|
const featuresExclude = [
'arraybuffer-transfer',
'regexp-duplicate-named-groups',
'regexp-modifiers',
'regexp-v-flag',
'resizable-arraybuffer',
];
await $`test262-harness \
--features-exclude=${ featuresExclude.join(',') } \
--threads=${ os.cpus().length } \
--host-args="--unhandled-rejections=none" \
--preprocessor=preprocessor.js \
--prelude=../../packages/core-js-bundle/index.js \
--test262-dir=node_modules/test262 \
node_modules/test262/test/built-ins/**/*.js \
`;
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/type-definitions/builder.ts
|
TypeScript
|
import builder from 'core-js-builder';
const a: Promise<string> = builder({ targets: { node: 17 } });
const b: string = await builder({ targets: { node: 17 } });
await builder();
await builder({});
await builder({ modules: 'core-js/actual' });
await builder({ modules: 'es.array.push' });
await builder({ modules: /^es\.array\./ });
await builder({ modules: ['core-js/actual', /^es\.array\./] });
await builder({ exclude: 'core-js/actual' });
await builder({ exclude: 'es.array.push' });
await builder({ exclude: /^es\.array\./ });
await builder({ exclude: ['core-js/actual', /^es\.array\./] });
await builder({ modules: 'core-js/actual', exclude: /^es\.array\./ });
await builder({ targets: '> 1%' });
await builder({ targets: ['defaults', 'last 5 versions'] });
await builder({ targets: { esmodules: true, node: 'current', browsers: ['> 1%'] } });
await builder({ targets: { chrome: '26', firefox: 4 } });
await builder({ targets: { browsers: { chrome: '26', firefox: 4 } } });
await builder({ targets: { chrome: '26', firefox: 4, esmodules: true, node: 'current', browsers: ['> 1%'] } });
await builder({ format: 'bundle' });
await builder({ format: 'esm' });
await builder({ format: 'cjs' });
await builder({ filename: '/foo/bar/baz.js' });
await builder({ summary: { comment: true } });
await builder({ summary: { comment: { size: true } } });
await builder({ summary: { comment: { size: false, modules: true } } });
await builder({ summary: { console: true } });
await builder({ summary: { console: { size: true } } });
await builder({ summary: { console: { size: false, modules: true } } });
await builder({ summary: { console: { size: false, modules: true }, comment: { size: false, modules: true } } });
await builder({
modules: 'core-js/actual',
exclude: /^es\.array\./,
targets: {
android: 1,
bun: '1',
chrome: 1,
'chrome-android': '1',
deno: 1,
edge: '1',
electron: 1,
firefox: '1',
'firefox-android': 1,
hermes: '1',
ie: 1,
ios: '1',
opera: 1,
'opera-android': '1',
phantom: 1,
quest: '1',
'react-native': 1,
rhino: '1',
safari: 1,
samsung: '1',
node: 'current',
esmodules: true,
browsers: ['> 1%'],
},
format: 'bundle',
filename: '/foo/bar/baz.js',
summary: {
console: { size: false, modules: true },
comment: { size: false, modules: true },
},
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/type-definitions/compat.ts
|
TypeScript
|
import compat from 'core-js-compat';
import compat2 from 'core-js-compat/compat';
import getModulesListForTargetVersion from 'core-js-compat/get-modules-list-for-target-version';
getModulesListForTargetVersion('3.0');
compat.getModulesListForTargetVersion('3.0');
compat.data['es.array.push'].android
compat.data['es.array.push'].firefox
if (typeof compat.modules[0] !== 'string') {
console.error('Invalid');
}
if (!compat.entries['core-js'].includes('es.array.from')) {
console.error('Invalid')
}
compat();
compat({});
compat({ modules: 'core-js/actual' });
compat({ modules: 'es.array.push' });
compat({ modules: /^es\.array\./ });
compat({ modules: ['core-js/actual', /^es\.array\./] });
compat({ exclude: 'core-js/actual' });
compat({ exclude: 'es.array.push' });
compat({ exclude: /^es\.array\./ });
compat({ exclude: ['core-js/actual', /^es\.array\./] });
compat({ modules: 'core-js/actual', exclude: /^es\.array\./ });
compat({ targets: '> 1%' });
compat({ targets: ['defaults', 'last 5 versions'] });
compat({ targets: { esmodules: true, node: 'current', browsers: ['> 1%'] } });
compat({ targets: { chrome: '26', firefox: 4 } });
compat({ targets: { browsers: { chrome: '26', firefox: 4 } } });
compat({ targets: { chrome: '26', firefox: 4, esmodules: true, node: 'current', browsers: ['> 1%'] } });
compat({ version: '3.0' });
compat({ inverse: true });
compat.compat();
compat.compat({});
compat.compat({ modules: 'core-js/actual' });
compat.compat({ modules: 'es.array.push' });
compat.compat({ modules: /^es\.array\./ });
compat.compat({ modules: ['core-js/actual', /^es\.array\./] });
compat.compat({ exclude: 'core-js/actual' });
compat.compat({ exclude: 'es.array.push' });
compat.compat({ exclude: /^es\.array\./ });
compat.compat({ exclude: ['core-js/actual', /^es\.array\./] });
compat.compat({ modules: 'core-js/actual', exclude: /^es\.array\./ });
compat.compat({ targets: '> 1%' });
compat.compat({ targets: ['defaults', 'last 5 versions'] });
compat.compat({ targets: { esmodules: true, node: 'current', browsers: ['> 1%'] } });
compat.compat({ targets: { chrome: '26', firefox: 4 } });
compat.compat({ targets: { browsers: { chrome: '26', firefox: 4 } } });
compat.compat({ targets: { chrome: '26', firefox: 4, esmodules: true, node: 'current', browsers: ['> 1%'] } });
compat.compat({ version: '3.0' });
compat.compat({ inverse: true });
compat2();
compat2({});
compat2({ modules: 'core-js/actual' });
compat2({ modules: 'es.array.push' });
compat2({ modules: /^es\.array\./ });
compat2({ modules: ['core-js/actual', /^es\.array\./] });
compat2({ exclude: 'core-js/actual' });
compat2({ exclude: 'es.array.push' });
compat2({ exclude: /^es\.array\./ });
compat2({ exclude: ['core-js/actual', /^es\.array\./] });
compat2({ modules: 'core-js/actual', exclude: /^es\.array\./ });
compat2({ targets: '> 1%' });
compat2({ targets: ['defaults', 'last 5 versions'] });
compat2({ targets: { esmodules: true, node: 'current', browsers: ['> 1%'] } });
compat2({ targets: { chrome: '26', firefox: 4 } });
compat2({ targets: { browsers: { chrome: '26', firefox: 4 } } });
compat2({ targets: { chrome: '26', firefox: 4, esmodules: true, node: 'current', browsers: ['> 1%'] } });
compat2({ version: '3.0' });
compat2({ inverse: true });
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/type-definitions/runner.mjs
|
JavaScript
|
await $`tsc`;
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-browser/global.html
|
HTML
|
<!DOCTYPE html>
<meta charset='UTF-8'>
<title>core-js</title>
<link rel='stylesheet' href='../bundles/qunit.css'>
<div id='qunit'></div>
<div id='qunit-fixture'></div>
<script src='../bundles/qunit.js'></script>
<script>
window.USE_FUNCTION_CONSTRUCTOR = true;
</script>
<script src='../bundles/core-js-bundle.js'></script>
<script>
window.inspectSource = window['__core-js_shared__'].inspectSource;
</script>
<script src='../bundles/unit-global.js'></script>
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-browser/pure.html
|
HTML
|
<!DOCTYPE html>
<meta charset='UTF-8'>
<title>core-js-pure</title>
<link rel='stylesheet' href='../bundles/qunit.css'>
<div id='qunit'></div>
<div id='qunit-fixture'></div>
<script src='../bundles/qunit.js'></script>
<script>
window.USE_FUNCTION_CONSTRUCTOR = true;
</script>
<script src='../bundles/unit-pure.js'></script>
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-bun/runner.mjs
|
JavaScript
|
if (await which('bun', { nothrow: true })) {
await Promise.all([
// some cases loading from modules works incorrectly in Bun, so test only bundled core-js version
// ['packages/core-js/index', 'tests/bundles/unit-global'],
['packages/core-js-bundle/index', 'tests/bundles/unit-global'],
['tests/bundles/unit-pure'],
].map(files => $`bun qunit ${ files.map(file => `../../${ file }.js`) }`));
} else echo(chalk.cyan('bun is not found'));
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.aggregate-error.js
|
JavaScript
|
/* eslint-disable unicorn/throw-new-error -- testing */
const { create } = Object;
QUnit.test('AggregateError', assert => {
assert.isFunction(AggregateError);
assert.arity(AggregateError, 2);
assert.name(AggregateError, 'AggregateError');
assert.looksNative(AggregateError);
assert.true(new AggregateError([1]) instanceof AggregateError);
assert.true(new AggregateError([1]) instanceof Error);
assert.true(AggregateError([1]) instanceof AggregateError);
assert.true(AggregateError([1]) instanceof Error);
assert.same(AggregateError([1], 'foo').message, 'foo');
assert.same(AggregateError([1], 123).message, '123');
assert.same(AggregateError([1]).message, '');
assert.deepEqual(AggregateError([1, 2, 3]).errors, [1, 2, 3]);
assert.throws(() => AggregateError([1], Symbol('AggregateError test')), 'throws on symbol as a message');
assert.same({}.toString.call(AggregateError([1])), '[object Error]', 'Object#toString');
assert.same(AggregateError.prototype.constructor, AggregateError, 'prototype constructor');
// eslint-disable-next-line no-prototype-builtins -- safe
assert.false(AggregateError.prototype.hasOwnProperty('cause'), 'prototype has not cause');
assert.true(AggregateError([1], 1) instanceof AggregateError, 'no cause, without new');
assert.true(new AggregateError([1], 1) instanceof AggregateError, 'no cause, with new');
assert.true(AggregateError([1], 1, {}) instanceof AggregateError, 'with options, without new');
assert.true(new AggregateError([1], 1, {}) instanceof AggregateError, 'with options, with new');
assert.true(AggregateError([1], 1, 'foo') instanceof AggregateError, 'non-object options, without new');
assert.true(new AggregateError([1], 1, 'foo') instanceof AggregateError, 'non-object options, with new');
assert.same(AggregateError([1], 1, { cause: 7 }).cause, 7, 'cause, without new');
assert.same(new AggregateError([1], 1, { cause: 7 }).cause, 7, 'cause, with new');
assert.same(AggregateError([1], 1, create({ cause: 7 })).cause, 7, 'prototype cause, without new');
assert.same(new AggregateError([1], 1, create({ cause: 7 })).cause, 7, 'prototype cause, with new');
let error = AggregateError([1], 1, { cause: 7 });
assert.deepEqual(error.errors, [1]);
assert.same(error.name, 'AggregateError', 'instance name');
assert.same(error.message, '1', 'instance message');
assert.same(error.cause, 7, 'instance cause');
// eslint-disable-next-line no-prototype-builtins -- safe
assert.true(error.hasOwnProperty('cause'), 'cause is own');
error = AggregateError([1]);
assert.deepEqual(error.errors, [1]);
assert.same(error.message, '', 'default instance message');
assert.same(error.cause, undefined, 'default instance cause undefined');
// eslint-disable-next-line no-prototype-builtins -- safe
assert.false(error.hasOwnProperty('cause'), 'default instance cause missed');
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array-buffer.constructor.js
|
JavaScript
|
import { DESCRIPTORS, GLOBAL, NATIVE } from '../helpers/constants.js';
QUnit.test('ArrayBuffer', assert => {
const Symbol = GLOBAL.Symbol || {};
// in Safari 5 typeof ArrayBuffer is 'object'
assert.same(ArrayBuffer, Object(ArrayBuffer), 'is object');
// 0 in V8 ~ Chromium 27-
assert.arity(ArrayBuffer, 1);
// Safari 5 bug
assert.name(ArrayBuffer, 'ArrayBuffer');
// Safari 5 bug
if (NATIVE) assert.looksNative(ArrayBuffer);
assert.same(new ArrayBuffer(123).byteLength, 123, 'length');
// fails in Safari
assert.throws(() => new ArrayBuffer(-1), RangeError, 'negative length');
assert.notThrows(() => new ArrayBuffer(0.5), 'fractional length');
assert.notThrows(() => new ArrayBuffer(), 'missed length');
if (DESCRIPTORS) assert.same(ArrayBuffer[Symbol.species], ArrayBuffer, '@@species');
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array-buffer.detached.js
|
JavaScript
|
/* eslint-disable es/no-shared-array-buffer -- testing */
import { DESCRIPTORS } from '../helpers/constants.js';
QUnit.test('ArrayBuffer#detached', assert => {
assert.same(new ArrayBuffer(8).detached, false, 'default');
const detached = new ArrayBuffer(8);
try {
structuredClone(detached, { transfer: [detached] });
} catch { /* empty */ }
if (detached.byteLength === 0) {
// works incorrectly in ancient WebKit
assert.skip.true(detached.detached, true, 'detached');
}
if (DESCRIPTORS) {
const { get, configurable, enumerable } = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, 'detached');
assert.same(configurable, true, 'configurable');
assert.same(enumerable, false, 'non-enumerable');
assert.isFunction(get);
assert.looksNative(get);
assert.throws(() => get.call(null), TypeError, 'non-generic-1');
assert.throws(() => get(), TypeError, 'non-generic-2');
assert.throws(() => get.call(1), TypeError, 'non-generic-3');
assert.throws(() => get.call(true), TypeError, 'non-generic-4');
assert.throws(() => get.call(''), TypeError, 'non-generic-5');
assert.throws(() => get.call({}), TypeError, 'non-generic-6');
if (typeof SharedArrayBuffer == 'function') {
assert.throws(() => get.call(new SharedArrayBuffer(8)), TypeError, 'non-generic-7');
}
}
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array-buffer.is-view.js
|
JavaScript
|
import { TYPED_ARRAYS } from '../helpers/constants.js';
QUnit.test('ArrayBuffer.isView', assert => {
const { isView } = ArrayBuffer;
assert.isFunction(isView);
assert.arity(isView, 1);
assert.name(isView, 'isView');
assert.looksNative(isView);
assert.nonEnumerable(ArrayBuffer, 'isView');
for (const { name, TypedArray } of TYPED_ARRAYS) {
if (TypedArray) {
assert.true(isView(new TypedArray([1])), `${ name } - true`);
}
}
assert.true(isView(new DataView(new ArrayBuffer(1))), 'DataView - true');
assert.false(isView(new ArrayBuffer(1)), 'ArrayBuffer - false');
const examples = [undefined, null, false, true, 0, 1, '', 'qwe', {}, [], function () { /* empty */ }];
for (const example of examples) {
assert.false(isView(example), `${ example } - false`);
}
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array-buffer.slice.js
|
JavaScript
|
import { arrayToBuffer, bufferToArray } from '../helpers/helpers.js';
QUnit.test('ArrayBuffer#slice', assert => {
const { slice } = ArrayBuffer.prototype;
assert.isFunction(slice);
assert.arity(slice, 2);
assert.name(slice, 'slice');
assert.looksNative(slice);
// assert.nonEnumerable(ArrayBuffer.prototype, 'slice');
const buffer = arrayToBuffer([1, 2, 3, 4, 5]);
assert.true(buffer instanceof ArrayBuffer, 'correct buffer');
assert.notSame(buffer.slice(), buffer, 'returns new buffer');
assert.true(buffer.slice() instanceof ArrayBuffer, 'correct instance');
assert.arrayEqual(bufferToArray(buffer.slice()), [1, 2, 3, 4, 5]);
assert.arrayEqual(bufferToArray(buffer.slice(1, 3)), [2, 3]);
assert.arrayEqual(bufferToArray(buffer.slice(1, undefined)), [2, 3, 4, 5]);
assert.arrayEqual(bufferToArray(buffer.slice(1, -1)), [2, 3, 4]);
assert.arrayEqual(bufferToArray(buffer.slice(-2, -1)), [4]);
assert.arrayEqual(bufferToArray(buffer.slice(-2, -3)), []);
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array-buffer.transfer-to-fixed-length.js
|
JavaScript
|
/* eslint-disable es/no-shared-array-buffer -- testing */
import { GLOBAL } from '../helpers/constants.js';
import { arrayToBuffer, bufferToArray } from '../helpers/helpers.js';
const transferToFixedLength = GLOBAL?.ArrayBuffer?.prototype?.transferToFixedLength;
if (transferToFixedLength) QUnit.test('ArrayBuffer#transferToFixedLength', assert => {
assert.isFunction(transferToFixedLength);
assert.arity(transferToFixedLength, 0);
assert.name(transferToFixedLength, 'transferToFixedLength');
assert.looksNative(transferToFixedLength);
assert.nonEnumerable(ArrayBuffer.prototype, 'transferToFixedLength');
const DETACHED = 'detached' in ArrayBuffer.prototype;
const array = [0, 1, 2, 3, 4, 5, 6, 7];
let buffer = arrayToBuffer(array);
let transferred = buffer.transferToFixedLength();
assert.notSame(transferred, buffer, 'returns new buffer 1');
assert.true(transferred instanceof ArrayBuffer, 'returns ArrayBuffer 1');
assert.same(buffer.byteLength, 0, 'original array length 1');
// works incorrectly in ancient WebKit
if (DETACHED) assert.skip.true(buffer.detached, 'original array detached 1');
assert.same(transferred.byteLength, 8, 'proper transferred byteLength 1');
assert.arrayEqual(bufferToArray(transferred), array, 'properly copied 1');
buffer = arrayToBuffer(array);
transferred = buffer.transferToFixedLength(5);
assert.notSame(transferred, buffer, 'returns new buffer 2');
assert.true(transferred instanceof ArrayBuffer, 'returns ArrayBuffer 2');
assert.same(buffer.byteLength, 0, 'original array length 2');
// works incorrectly in ancient WebKit
if (DETACHED) assert.skip.true(buffer.detached, 'original array detached 2');
assert.same(transferred.byteLength, 5, 'proper transferred byteLength 2');
assert.arrayEqual(bufferToArray(transferred), array.slice(0, 5), 'properly copied 2');
buffer = arrayToBuffer(array);
transferred = buffer.transferToFixedLength(16.7);
assert.notSame(transferred, buffer, 'returns new buffer 3');
assert.true(transferred instanceof ArrayBuffer, 'returns ArrayBuffer 3');
assert.same(buffer.byteLength, 0, 'original array length 3');
// works incorrectly in ancient WebKit
if (DETACHED) assert.skip.true(buffer.detached, 'original array detached 3');
assert.same(transferred.byteLength, 16, 'proper transferred byteLength 3');
assert.arrayEqual(bufferToArray(transferred), [...array, 0, 0, 0, 0, 0, 0, 0, 0], 'properly copied 3');
assert.throws(() => arrayToBuffer(array).transferToFixedLength(-1), RangeError, 'negative length');
assert.throws(() => transferToFixedLength.call({}), TypeError, 'non-generic-1');
if (typeof SharedArrayBuffer == 'function') {
assert.throws(() => transferToFixedLength.call(new SharedArrayBuffer(8)), TypeError, 'non-generic-2');
}
if ('resizable' in ArrayBuffer.prototype) {
assert.false(arrayToBuffer(array).transferToFixedLength().resizable, 'non-resizable-1');
assert.false(arrayToBuffer(array).transferToFixedLength(5).resizable, 'non-resizable-2');
buffer = new ArrayBuffer(8, { maxByteLength: 16 });
new Int8Array(buffer).set(array);
transferred = buffer.transferToFixedLength();
assert.arrayEqual(bufferToArray(transferred), array, 'resizable-1');
assert.false(transferred.resizable, 'resizable-2');
buffer = new ArrayBuffer(8, { maxByteLength: 16 });
new Int8Array(buffer).set(array);
transferred = buffer.transferToFixedLength(5);
assert.arrayEqual(bufferToArray(transferred), array.slice(0, 5), 'resizable-3');
assert.false(transferred.resizable, 'resizable-4');
}
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array-buffer.transfer.js
|
JavaScript
|
/* eslint-disable es/no-shared-array-buffer -- testing */
import { GLOBAL } from '../helpers/constants.js';
import { arrayToBuffer, bufferToArray } from '../helpers/helpers.js';
const transfer = GLOBAL?.ArrayBuffer?.prototype?.transfer;
if (transfer) QUnit.test('ArrayBuffer#transfer', assert => {
assert.isFunction(transfer);
assert.arity(transfer, 0);
assert.name(transfer, 'transfer');
assert.looksNative(transfer);
assert.nonEnumerable(ArrayBuffer.prototype, 'transfer');
const DETACHED = 'detached' in ArrayBuffer.prototype;
const array = [0, 1, 2, 3, 4, 5, 6, 7];
let buffer = arrayToBuffer(array);
let transferred = buffer.transfer();
assert.notSame(transferred, buffer, 'returns new buffer 1');
assert.true(transferred instanceof ArrayBuffer, 'returns ArrayBuffer 1');
assert.same(buffer.byteLength, 0, 'original array length 1');
// works incorrectly in ancient WebKit
if (DETACHED) assert.skip.true(buffer.detached, 'original array detached 1');
assert.same(transferred.byteLength, 8, 'proper transferred byteLength 1');
assert.arrayEqual(bufferToArray(transferred), array, 'properly copied 1');
buffer = arrayToBuffer(array);
transferred = buffer.transfer(5);
assert.notSame(transferred, buffer, 'returns new buffer 2');
assert.true(transferred instanceof ArrayBuffer, 'returns ArrayBuffer 2');
assert.same(buffer.byteLength, 0, 'original array length 2');
// works incorrectly in ancient WebKit
if (DETACHED) assert.skip.true(buffer.detached, 'original array detached 2');
assert.same(transferred.byteLength, 5, 'proper transferred byteLength 2');
assert.arrayEqual(bufferToArray(transferred), array.slice(0, 5), 'properly copied 2');
buffer = arrayToBuffer(array);
transferred = buffer.transfer(16.7);
assert.notSame(transferred, buffer, 'returns new buffer 3');
assert.true(transferred instanceof ArrayBuffer, 'returns ArrayBuffer 3');
assert.same(buffer.byteLength, 0, 'original array length 3');
// works incorrectly in ancient WebKit
if (DETACHED) assert.skip.true(buffer.detached, 'original array detached 3');
assert.same(transferred.byteLength, 16, 'proper transferred byteLength 3');
assert.arrayEqual(bufferToArray(transferred), [...array, 0, 0, 0, 0, 0, 0, 0, 0], 'properly copied 3');
assert.throws(() => arrayToBuffer(array).transfer(-1), RangeError, 'negative length');
assert.throws(() => transfer.call({}), TypeError, 'non-generic-1');
if (typeof SharedArrayBuffer == 'function') {
assert.throws(() => transfer.call(new SharedArrayBuffer(8)), TypeError, 'non-generic-2');
}
if ('resizable' in ArrayBuffer.prototype) {
assert.false(arrayToBuffer(array).transfer().resizable, 'non-resizable-1');
assert.false(arrayToBuffer(array).transfer(5).resizable, 'non-resizable-2');
buffer = new ArrayBuffer(8, { maxByteLength: 16 });
new Int8Array(buffer).set(array);
transferred = buffer.transfer();
assert.arrayEqual(bufferToArray(transferred), array, 'resizable-1');
assert.true(transferred.resizable, 'resizable-2');
buffer = new ArrayBuffer(8, { maxByteLength: 16 });
new Int8Array(buffer).set(array);
transferred = buffer.transfer(5);
assert.arrayEqual(bufferToArray(transferred), array.slice(0, 5), 'resizable-3');
assert.true(transferred.resizable, 'resizable-4');
}
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.at.js
|
JavaScript
|
import { STRICT } from '../helpers/constants.js';
QUnit.test('Array#at', assert => {
const { at } = Array.prototype;
assert.isFunction(at);
assert.arity(at, 1);
assert.name(at, 'at');
assert.looksNative(at);
assert.nonEnumerable(Array.prototype, 'at');
assert.same(1, [1, 2, 3].at(0));
assert.same(2, [1, 2, 3].at(1));
assert.same(3, [1, 2, 3].at(2));
assert.same(undefined, [1, 2, 3].at(3));
assert.same(3, [1, 2, 3].at(-1));
assert.same(2, [1, 2, 3].at(-2));
assert.same(1, [1, 2, 3].at(-3));
assert.same(undefined, [1, 2, 3].at(-4));
assert.same(1, [1, 2, 3].at(0.4));
assert.same(1, [1, 2, 3].at(0.5));
assert.same(1, [1, 2, 3].at(0.6));
assert.same(1, [1].at(NaN));
assert.same(1, [1].at());
assert.same(1, [1, 2, 3].at(-0));
assert.same(undefined, Array(1).at(0));
assert.same(1, at.call({ 0: 1, length: 1 }, 0));
if (STRICT) {
assert.throws(() => at.call(null, 0), TypeError);
assert.throws(() => at.call(undefined, 0), TypeError);
}
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.concat.js
|
JavaScript
|
/* eslint-disable no-sparse-arrays, unicorn/prefer-array-flat -- required for testing */
QUnit.test('Array#concat', assert => {
const { concat } = Array.prototype;
assert.isFunction(concat);
assert.arity(concat, 1);
assert.name(concat, 'concat');
assert.looksNative(concat);
assert.nonEnumerable(Array.prototype, 'concat');
let array = [1, 2];
const sparseArray = [1, , 2];
const nonSpreadableArray = [1, 2];
nonSpreadableArray[Symbol.isConcatSpreadable] = false;
const arrayLike = { 0: 1, 1: 2, length: 2 };
const spreadableArrayLike = { 0: 1, 1: 2, length: 2, [Symbol.isConcatSpreadable]: true };
assert.deepEqual(array.concat(), [1, 2], '#1');
assert.deepEqual(sparseArray.concat(), [1, , 2], '#2');
assert.deepEqual(nonSpreadableArray.concat(), [[1, 2]], '#3');
assert.deepEqual(concat.call(arrayLike), [{ 0: 1, 1: 2, length: 2 }], '#4');
assert.deepEqual(concat.call(spreadableArrayLike), [1, 2], '#5');
assert.deepEqual([].concat(array), [1, 2], '#6');
assert.deepEqual([].concat(sparseArray), [1, , 2], '#7');
assert.deepEqual([].concat(nonSpreadableArray), [[1, 2]], '#8');
assert.deepEqual([].concat(arrayLike), [{ 0: 1, 1: 2, length: 2 }], '#9');
assert.deepEqual([].concat(spreadableArrayLike), [1, 2], '#10');
assert.deepEqual(array.concat(sparseArray, nonSpreadableArray, arrayLike, spreadableArrayLike), [
1, 2, 1, , 2, [1, 2], { 0: 1, 1: 2, length: 2 }, 1, 2,
], '#11');
array = [];
// eslint-disable-next-line object-shorthand -- constructor
array.constructor = { [Symbol.species]: function () {
return { foo: 1 };
} };
// https://bugs.webkit.org/show_bug.cgi?id=281061
// eslint-disable-next-line es/no-nonstandard-array-prototype-properties -- @@species
assert.same(array.concat().foo, 1, '@@species');
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.copy-within.js
|
JavaScript
|
import { STRICT } from '../helpers/constants.js';
QUnit.test('Array#copyWithin', assert => {
const { copyWithin } = Array.prototype;
assert.isFunction(copyWithin);
assert.arity(copyWithin, 2);
assert.name(copyWithin, 'copyWithin');
assert.looksNative(copyWithin);
const array = [1];
assert.same(array.copyWithin(0), array);
assert.nonEnumerable(Array.prototype, 'copyWithin');
assert.deepEqual([1, 2, 3, 4, 5].copyWithin(0, 3), [4, 5, 3, 4, 5]);
assert.deepEqual([1, 2, 3, 4, 5].copyWithin(1, 3), [1, 4, 5, 4, 5]);
assert.deepEqual([1, 2, 3, 4, 5].copyWithin(1, 2), [1, 3, 4, 5, 5]);
assert.deepEqual([1, 2, 3, 4, 5].copyWithin(2, 2), [1, 2, 3, 4, 5]);
assert.deepEqual([1, 2, 3, 4, 5].copyWithin(0, 3, 4), [4, 2, 3, 4, 5]);
assert.deepEqual([1, 2, 3, 4, 5].copyWithin(1, 3, 4), [1, 4, 3, 4, 5]);
assert.deepEqual([1, 2, 3, 4, 5].copyWithin(1, 2, 4), [1, 3, 4, 4, 5]);
assert.deepEqual([1, 2, 3, 4, 5].copyWithin(0, -2), [4, 5, 3, 4, 5]);
assert.deepEqual([1, 2, 3, 4, 5].copyWithin(0, -2, -1), [4, 2, 3, 4, 5]);
assert.deepEqual([1, 2, 3, 4, 5].copyWithin(-4, -3, -2), [1, 3, 3, 4, 5]);
assert.deepEqual([1, 2, 3, 4, 5].copyWithin(-4, -3, -1), [1, 3, 4, 4, 5]);
assert.deepEqual([1, 2, 3, 4, 5].copyWithin(-4, -3), [1, 3, 4, 5, 5]);
if (STRICT) {
assert.throws(() => copyWithin.call(null, 0), TypeError);
assert.throws(() => copyWithin.call(undefined, 0), TypeError);
}
assert.true('copyWithin' in Array.prototype[Symbol.unscopables], 'In Array#@@unscopables');
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.every.js
|
JavaScript
|
import { STRICT } from '../helpers/constants.js';
QUnit.test('Array#every', assert => {
const { every } = Array.prototype;
assert.isFunction(every);
assert.arity(every, 1);
assert.name(every, 'every');
assert.looksNative(every);
assert.nonEnumerable(Array.prototype, 'every');
let array = [1];
const context = {};
array.every(function (value, key, that) {
assert.same(arguments.length, 3, 'correct number of callback arguments');
assert.same(value, 1, 'correct value in callback');
assert.same(key, 0, 'correct index in callback');
assert.same(that, array, 'correct link to array in callback');
assert.same(this, context, 'correct callback context');
}, context);
assert.true([1, 2, 3].every(it => typeof it == 'number'));
assert.true([1, 2, 3].every(it => it < 4));
assert.false([1, 2, 3].every(it => it < 3));
assert.false([1, 2, 3].every(it => typeof it == 'string'));
assert.true([1, 2, 3].every(function () {
return +this === 1;
}, 1));
let result = '';
[1, 2, 3].every((value, key) => result += key);
assert.same(result, '012');
array = [1, 2, 3];
assert.true(array.every((value, key, that) => that === array));
if (STRICT) {
assert.throws(() => every.call(null, () => { /* empty */ }), TypeError);
assert.throws(() => every.call(undefined, () => { /* empty */ }), TypeError);
}
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.fill.js
|
JavaScript
|
import { DESCRIPTORS, NATIVE, STRICT } from '../helpers/constants.js';
QUnit.test('Array#fill', assert => {
const { fill } = Array.prototype;
assert.isFunction(fill);
assert.arity(fill, 1);
assert.name(fill, 'fill');
assert.looksNative(fill);
assert.nonEnumerable(Array.prototype, 'fill');
const array = new Array(5);
assert.same(array.fill(5), array);
assert.deepEqual(Array(5).fill(5), [5, 5, 5, 5, 5]);
assert.deepEqual(Array(5).fill(5, 1), [undefined, 5, 5, 5, 5]);
assert.deepEqual(Array(5).fill(5, 1, 4), [undefined, 5, 5, 5, undefined]);
assert.deepEqual(Array(5).fill(5, 6, 1), [undefined, undefined, undefined, undefined, undefined]);
assert.deepEqual(Array(5).fill(5, -3, 4), [undefined, undefined, 5, 5, undefined]);
assert.arrayEqual(fill.call({ length: 5 }, 5), [5, 5, 5, 5, 5]);
if (STRICT) {
assert.throws(() => fill.call(null, 0), TypeError);
assert.throws(() => fill.call(undefined, 0), TypeError);
}
if (NATIVE && DESCRIPTORS) {
assert.notThrows(() => fill.call(Object.defineProperty({
length: -1,
}, 0, {
set() {
throw new Error();
},
})), 'uses ToLength');
}
assert.true('fill' in Array.prototype[Symbol.unscopables], 'In Array#@@unscopables');
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.filter.js
|
JavaScript
|
import { STRICT } from '../helpers/constants.js';
QUnit.test('Array#filter', assert => {
const { filter } = Array.prototype;
assert.isFunction(filter);
assert.arity(filter, 1);
assert.name(filter, 'filter');
assert.looksNative(filter);
assert.nonEnumerable(Array.prototype, 'filter');
let array = [1];
const context = {};
array.filter(function (value, key, that) {
assert.same(arguments.length, 3, 'correct number of callback arguments');
assert.same(value, 1, 'correct value in callback');
assert.same(key, 0, 'correct index in callback');
assert.same(that, array, 'correct link to array in callback');
assert.same(this, context, 'correct callback context');
}, context);
assert.deepEqual([1, 2, 3, 4, 5], [1, 2, 3, 'q', {}, 4, true, 5].filter(it => typeof it == 'number'));
if (STRICT) {
assert.throws(() => filter.call(null, () => { /* empty */ }), TypeError);
assert.throws(() => filter.call(undefined, () => { /* empty */ }), TypeError);
}
array = [];
// eslint-disable-next-line object-shorthand -- constructor
array.constructor = { [Symbol.species]: function () {
return { foo: 1 };
} };
// eslint-disable-next-line es/no-nonstandard-array-prototype-properties -- @@species
assert.same(array.filter(Boolean).foo, 1, '@@species');
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.find-index.js
|
JavaScript
|
import { STRICT } from '../helpers/constants.js';
QUnit.test('Array#findIndex', assert => {
const { findIndex } = Array.prototype;
assert.isFunction(findIndex);
assert.arity(findIndex, 1);
assert.name(findIndex, 'findIndex');
assert.looksNative(findIndex);
assert.nonEnumerable(Array.prototype, 'findIndex');
const array = [1];
const context = {};
array.findIndex(function (value, key, that) {
assert.same(arguments.length, 3, 'correct number of callback arguments');
assert.same(value, 1, 'correct value in callback');
assert.same(key, 0, 'correct index in callback');
assert.same(that, array, 'correct link to array in callback');
assert.same(this, context, 'correct callback context');
}, context);
// eslint-disable-next-line unicorn/prefer-array-index-of -- ignore
assert.same([1, 3, NaN, 42, {}].findIndex(it => it === 42), 3);
// eslint-disable-next-line unicorn/prefer-array-index-of -- ignore
assert.same([1, 3, NaN, 42, {}].findIndex(it => it === 43), -1);
if (STRICT) {
assert.throws(() => findIndex.call(null, 0), TypeError);
assert.throws(() => findIndex.call(undefined, 0), TypeError);
}
assert.notThrows(() => findIndex.call({
length: -1,
0: 1,
}, () => {
throw new Error();
}) === -1, 'uses ToLength');
assert.true('findIndex' in Array.prototype[Symbol.unscopables], 'In Array#@@unscopables');
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.find-last-index.js
|
JavaScript
|
import { STRICT } from '../helpers/constants.js';
QUnit.test('Array#findLastIndex', assert => {
const { findLastIndex } = Array.prototype;
assert.isFunction(findLastIndex);
assert.arity(findLastIndex, 1);
assert.name(findLastIndex, 'findLastIndex');
assert.looksNative(findLastIndex);
assert.nonEnumerable(Array.prototype, 'findLastIndex');
const array = [1];
const context = {};
array.findLastIndex(function (value, key, that) {
assert.same(arguments.length, 3, 'correct number of callback arguments');
assert.same(value, 1, 'correct value in callback');
assert.same(key, 0, 'correct index in callback');
assert.same(that, array, 'correct link to array in callback');
assert.same(this, context, 'correct callback context');
}, context);
assert.same([{}, 2, NaN, 42, 1].findLastIndex(it => !(it % 2)), 3);
assert.same([{}, 2, NaN, 42, 1].findLastIndex(it => it > 42), -1);
let values = '';
let keys = '';
[1, 2, 3].findLastIndex((value, key) => {
values += value;
keys += key;
});
assert.same(values, '321');
assert.same(keys, '210');
if (STRICT) {
assert.throws(() => findLastIndex.call(null, 0), TypeError);
assert.throws(() => findLastIndex.call(undefined, 0), TypeError);
}
assert.notThrows(() => findLastIndex.call({
length: -1,
0: 1,
}, () => {
throw new Error();
}) === -1, 'uses ToLength');
assert.true('findLastIndex' in Array.prototype[Symbol.unscopables], 'In Array#@@unscopables');
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.find-last.js
|
JavaScript
|
import { STRICT } from '../helpers/constants.js';
QUnit.test('Array#findLast', assert => {
const { findLast } = Array.prototype;
assert.isFunction(findLast);
assert.arity(findLast, 1);
assert.name(findLast, 'findLast');
assert.looksNative(findLast);
assert.nonEnumerable(Array.prototype, 'findLast');
const array = [1];
const context = {};
array.findLast(function (value, key, that) {
assert.same(arguments.length, 3, 'correct number of callback arguments');
assert.same(value, 1, 'correct value in callback');
assert.same(key, 0, 'correct index in callback');
assert.same(that, array, 'correct link to array in callback');
assert.same(this, context, 'correct callback context');
}, context);
assert.same([{}, 2, NaN, 42, 1].findLast(it => !(it % 2)), 42);
assert.same([{}, 2, NaN, 42, 1].findLast(it => it === 43), undefined);
let values = '';
let keys = '';
[1, 2, 3].findLast((value, key) => {
values += value;
keys += key;
});
assert.same(values, '321');
assert.same(keys, '210');
if (STRICT) {
assert.throws(() => findLast.call(null, 0), TypeError);
assert.throws(() => findLast.call(undefined, 0), TypeError);
}
assert.notThrows(() => findLast.call({
length: -1,
0: 1,
}, () => {
throw new Error();
}) === undefined, 'uses ToLength');
assert.true('findLast' in Array.prototype[Symbol.unscopables], 'In Array#@@unscopables');
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.find.js
|
JavaScript
|
import { STRICT } from '../helpers/constants.js';
QUnit.test('Array#find', assert => {
const { find } = Array.prototype;
assert.isFunction(find);
assert.arity(find, 1);
assert.name(find, 'find');
assert.looksNative(find);
assert.nonEnumerable(Array.prototype, 'find');
const array = [1];
const context = {};
array.find(function (value, key, that) {
assert.same(arguments.length, 3, 'correct number of callback arguments');
assert.same(value, 1, 'correct value in callback');
assert.same(key, 0, 'correct index in callback');
assert.same(that, array, 'correct link to array in callback');
assert.same(this, context, 'correct callback context');
}, context);
assert.same([1, 3, NaN, 42, {}].find(it => it === 42), 42);
assert.same([1, 3, NaN, 42, {}].find(it => it === 43), undefined);
if (STRICT) {
assert.throws(() => find.call(null, 0), TypeError);
assert.throws(() => find.call(undefined, 0), TypeError);
}
assert.notThrows(() => find.call({
length: -1,
0: 1,
}, () => {
throw new Error();
}) === undefined, 'uses ToLength');
assert.true('find' in Array.prototype[Symbol.unscopables], 'In Array#@@unscopables');
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.flat-map.js
|
JavaScript
|
/* eslint-disable unicorn/prefer-array-flat -- required for testing */
import { STRICT } from '../helpers/constants.js';
QUnit.test('Array#flatMap', assert => {
const { flatMap } = Array.prototype;
assert.isFunction(flatMap);
assert.name(flatMap, 'flatMap');
assert.arity(flatMap, 1);
assert.looksNative(flatMap);
assert.nonEnumerable(Array.prototype, 'flatMap');
assert.deepEqual([].flatMap(it => it), []);
assert.deepEqual([1, 2, 3].flatMap(it => it), [1, 2, 3]);
assert.deepEqual([1, 2, 3].flatMap(it => [it, it]), [1, 1, 2, 2, 3, 3]);
assert.deepEqual([1, 2, 3].flatMap(it => [[it], [it]]), [[1], [1], [2], [2], [3], [3]]);
assert.deepEqual([1, [2, 3]].flatMap(() => 1), [1, 1]);
const array = [1];
const context = {};
array.flatMap(function (value, key, that) {
assert.same(value, 1);
assert.same(key, 0);
assert.same(that, array);
assert.same(this, context);
return value;
}, context);
if (STRICT) {
assert.throws(() => flatMap.call(null, it => it), TypeError);
assert.throws(() => flatMap.call(undefined, it => it), TypeError);
}
assert.notThrows(() => flatMap.call({ length: -1 }, () => {
throw new Error();
}).length === 0, 'uses ToLength');
assert.true('flatMap' in Array.prototype[Symbol.unscopables], 'In Array#@@unscopables');
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.flat.js
|
JavaScript
|
import { DESCRIPTORS, STRICT } from '../helpers/constants.js';
QUnit.test('Array#flat', assert => {
const { flat } = Array.prototype;
const { defineProperty } = Object;
assert.isFunction(flat);
assert.name(flat, 'flat');
assert.arity(flat, 0);
assert.looksNative(flat);
assert.nonEnumerable(Array.prototype, 'flat');
assert.deepEqual([].flat(), []);
const array = [1, [2, 3], [4, [5, 6]]];
assert.deepEqual(array.flat(0), array);
// eslint-disable-next-line unicorn/no-unnecessary-array-flat-depth -- testing
assert.deepEqual(array.flat(1), [1, 2, 3, 4, [5, 6]]);
assert.deepEqual(array.flat(), [1, 2, 3, 4, [5, 6]]);
assert.deepEqual(array.flat(2), [1, 2, 3, 4, 5, 6]);
assert.deepEqual(array.flat(3), [1, 2, 3, 4, 5, 6]);
assert.deepEqual(array.flat(-1), array);
assert.deepEqual(array.flat(Infinity), [1, 2, 3, 4, 5, 6]);
if (STRICT) {
assert.throws(() => flat.call(null), TypeError);
assert.throws(() => flat.call(undefined), TypeError);
}
if (DESCRIPTORS) {
assert.notThrows(() => flat.call(defineProperty({ length: -1 }, 0, {
enumerable: true,
get() {
throw new Error();
},
})).length === 0, 'uses ToLength');
}
assert.true('flat' in Array.prototype[Symbol.unscopables], 'In Array#@@unscopables');
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.for-each.js
|
JavaScript
|
import { STRICT } from '../helpers/constants.js';
QUnit.test('Array#forEach', assert => {
const { forEach } = Array.prototype;
assert.isFunction(forEach);
assert.arity(forEach, 1);
assert.name(forEach, 'forEach');
assert.looksNative(forEach);
assert.nonEnumerable(Array.prototype, 'forEach');
let array = [1];
const context = {};
array.forEach(function (value, key, that) {
assert.same(arguments.length, 3, 'correct number of callback arguments');
assert.same(value, 1, 'correct value in callback');
assert.same(key, 0, 'correct index in callback');
assert.same(that, array, 'correct link to array in callback');
assert.same(this, context, 'correct callback context');
}, context);
let result = '';
[1, 2, 3].forEach(value => {
result += value;
});
assert.same(result, '123');
result = '';
[1, 2, 3].forEach((value, key) => {
result += key;
});
assert.same(result, '012');
result = '';
[1, 2, 3].forEach((value, key, that) => {
result += that;
});
assert.same(result, '1,2,31,2,31,2,3');
result = '';
[1, 2, 3].forEach(function () {
result += this;
}, 1);
assert.same(result, '111');
result = '';
array = [];
array[5] = '';
array.forEach((value, key) => {
result += key;
});
assert.same(result, '5');
if (STRICT) {
assert.throws(() => {
forEach.call(null, () => { /* empty */ });
}, TypeError);
assert.throws(() => {
forEach.call(undefined, () => { /* empty */ });
}, TypeError);
}
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.from-async.js
|
JavaScript
|
import { createAsyncIterable, createIterable/* , createIterator */ } from '../helpers/helpers.js';
import { STRICT_THIS } from '../helpers/constants.js';
QUnit.test('Array.fromAsync', assert => {
const { fromAsync } = Array;
assert.isFunction(fromAsync);
assert.arity(fromAsync, 1);
assert.name(fromAsync, 'fromAsync');
assert.looksNative(fromAsync);
assert.nonEnumerable(Array, 'fromAsync');
let counter = 0;
// eslint-disable-next-line prefer-arrow-callback -- constructor
fromAsync.call(function () {
counter++;
return [];
}, { length: 0 });
assert.same(counter, 1, 'proper number of constructor calling');
function C() { /* empty */ }
// const closableIterator = createIterator([1], {
// return() { this.closed = true; return { value: undefined, done: true }; },
// });
return fromAsync(createAsyncIterable([1, 2, 3]), it => it ** 2).then(it => {
assert.arrayEqual(it, [1, 4, 9], 'async iterable and mapfn');
return fromAsync(createAsyncIterable([1]), function (arg, index) {
assert.same(this, STRICT_THIS, 'this');
assert.same(arguments.length, 2, 'arguments length');
assert.same(arg, 1, 'argument');
assert.same(index, 0, 'index');
});
}).then(() => {
return fromAsync(createAsyncIterable([1, 2, 3]));
}).then(it => {
assert.arrayEqual(it, [1, 2, 3], 'async iterable without mapfn');
return fromAsync(createIterable([1, 2, 3]), arg => arg ** 2);
}).then(it => {
assert.arrayEqual(it, [1, 4, 9], 'iterable and mapfn');
return fromAsync(createIterable([1, 2, 3]), arg => Promise.resolve(arg ** 2));
}).then(it => {
assert.arrayEqual(it, [1, 4, 9], 'iterable and async mapfn');
return fromAsync(createIterable([1]), function (arg, index) {
assert.same(this, STRICT_THIS, 'this');
assert.same(arguments.length, 2, 'arguments length');
assert.same(arg, 1, 'argument');
assert.same(index, 0, 'index');
});
}).then(() => {
return fromAsync(createIterable([1, 2, 3]));
}).then(it => {
assert.arrayEqual(it, [1, 2, 3], 'iterable and without mapfn');
return fromAsync([1, Promise.resolve(2), 3]);
}).then(it => {
assert.arrayEqual(it, [1, 2, 3], 'array');
return fromAsync('123');
}).then(it => {
assert.arrayEqual(it, ['1', '2', '3'], 'string');
return fromAsync.call(C, [1]);
}).then(it => {
assert.true(it instanceof C, 'subclassable');
return fromAsync({ length: 1, 0: 1 });
}).then(it => {
assert.arrayEqual(it, [1], 'non-iterable');
return fromAsync(createIterable([1]), () => { throw 42; });
}).then(() => {
assert.avoid();
}, error => {
assert.same(error, 42, 'rejection on a callback error');
return fromAsync(undefined, () => { /* empty */ });
}).then(() => {
assert.avoid();
}, error => {
assert.true(error instanceof TypeError);
return fromAsync(null, () => { /* empty */ });
}).then(() => {
assert.avoid();
}, error => {
assert.true(error instanceof TypeError);
return fromAsync([1], null);
}).then(() => {
assert.avoid();
}, error => {
assert.true(error instanceof TypeError);
return fromAsync([1], {});
}).then(() => {
assert.avoid();
}, error => {
assert.true(error instanceof TypeError);
// sync iterable: return() should be called through AsyncFromSyncIterator on early termination
const closable = createIterable([1, 2, 3], {
return() {
closable.closed = true;
return { value: undefined, done: true };
},
});
return fromAsync(closable, item => {
if (item === 2) throw 42;
return item;
}).then(() => {
assert.avoid();
}, err => {
assert.same(err, 42, 'sync iterable: rejection on callback error');
assert.true(closable.closed, 'sync iterable: return() called on early termination');
});
});
/* Tests are temporarily disabled due to the lack of proper async feature detection in native implementations.
.then(() => {
return fromAsync(Iterator.from(closableIterator), () => { throw 42; });
}).then(() => {
assert.avoid();
}, error => {
assert.same(error, 42, 'rejection on a callback error');
assert.true(closableIterator.closed, 'doesn\'t close sync iterator on promise rejection');
}); */
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.from.js
|
JavaScript
|
/* eslint-disable prefer-rest-params -- required for testing */
import { DESCRIPTORS, GLOBAL } from '../helpers/constants.js';
import { createIterable } from '../helpers/helpers.js';
QUnit.test('Array.from', assert => {
const Symbol = GLOBAL.Symbol || {};
const { from } = Array;
const { defineProperty } = Object;
assert.isFunction(from);
assert.arity(from, 1);
assert.name(from, 'from');
assert.looksNative(from);
assert.nonEnumerable(Array, 'from');
let types = {
'array-like': {
length: '3',
0: '1',
1: '2',
2: '3',
},
arguments: function () {
return arguments;
}('1', '2', '3'),
array: ['1', '2', '3'],
iterable: createIterable(['1', '2', '3']),
string: '123',
};
for (const type in types) {
const data = types[type];
assert.arrayEqual(from(data), ['1', '2', '3'], `Works with ${ type }`);
assert.arrayEqual(from(data, it => it ** 2), [1, 4, 9], `Works with ${ type } + mapFn`);
}
types = {
'array-like': {
length: 1,
0: 1,
},
arguments: function () {
return arguments;
}(1),
array: [1],
iterable: createIterable([1]),
string: '1',
};
for (const type in types) {
const data = types[type];
const context = {};
assert.arrayEqual(from(data, function (value, key) {
assert.same(this, context, `Works with ${ type }, correct callback context`);
assert.same(value, type === 'string' ? '1' : 1, `Works with ${ type }, correct callback value`);
assert.same(key, 0, `Works with ${ type }, correct callback key`);
assert.same(arguments.length, 2, `Works with ${ type }, correct callback arguments number`);
return 42;
}, context), [42], `Works with ${ type }, correct result`);
}
const primitives = [false, true, 0];
for (const primitive of primitives) {
assert.arrayEqual(from(primitive), [], `Works with ${ primitive }`);
}
assert.throws(() => from(null), TypeError, 'Throws on null');
assert.throws(() => from(undefined), TypeError, 'Throws on undefined');
assert.arrayEqual(from('𠮷𠮷𠮷'), ['𠮷', '𠮷', '𠮷'], 'Uses correct string iterator');
let done = true;
from(createIterable([1, 2, 3], {
return() {
return done = false;
},
}), () => false);
assert.true(done, '.return #default');
done = false;
try {
from(createIterable([1, 2, 3], {
return() {
return done = true;
},
}), () => {
throw new Error();
});
} catch { /* empty */ }
assert.true(done, '.return #throw');
class C { /* empty */ }
let instance = from.call(C, createIterable([1, 2]));
assert.true(instance instanceof C, 'generic, iterable case, instanceof');
assert.arrayEqual(instance, [1, 2], 'generic, iterable case, elements');
instance = from.call(C, {
0: 1,
1: 2,
length: 2,
});
assert.true(instance instanceof C, 'generic, array-like case, instanceof');
assert.arrayEqual(instance, [1, 2], 'generic, array-like case, elements');
let array = [1, 2, 3];
done = false;
// eslint-disable-next-line es/no-nonstandard-array-prototype-properties -- legacy FF case
array['@@iterator'] = undefined;
array[Symbol.iterator] = function () {
done = true;
return [][Symbol.iterator].call(this);
};
assert.arrayEqual(from(array), [1, 2, 3], 'Array with custom iterator, elements');
assert.true(done, 'call @@iterator in Array with custom iterator');
array = [1, 2, 3];
delete array[1];
assert.arrayEqual(from(array, String), ['1', 'undefined', '3'], 'Ignores holes');
assert.notThrows(() => from({
length: -1,
0: 1,
}, () => {
throw new Error();
}).length === 0, 'Uses ToLength');
assert.arrayEqual(from([], undefined), [], 'Works with undefined as second argument');
assert.throws(() => from([], null), TypeError, 'Throws with null as second argument');
assert.throws(() => from([], 0), TypeError, 'Throws with 0 as second argument');
assert.throws(() => from([], ''), TypeError, 'Throws with "" as second argument');
assert.throws(() => from([], false), TypeError, 'Throws with false as second argument');
assert.throws(() => from([], {}), TypeError, 'Throws with {} as second argument');
if (DESCRIPTORS) {
let called = false;
defineProperty(C.prototype, 0, {
set() {
called = true;
},
});
from.call(C, [1, 2, 3]);
assert.false(called, 'Should not call prototype accessors');
}
// iterator should be closed when createProperty fails
if (DESCRIPTORS) {
let returnCalled = false;
const iterable = {
[Symbol.iterator]() {
return {
next() { return { value: 1, done: false }; },
return() { returnCalled = true; return { done: true }; },
};
},
};
const Frozen = function () { return Object.freeze([]); };
assert.throws(() => from.call(Frozen, iterable), TypeError, 'throws when createProperty fails');
assert.true(returnCalled, 'iterator is closed when createProperty throws');
}
// mapfn callable check should happen before ToObject(items)
assert.throws(() => from(null, 42), TypeError, 'non-callable mapfn with null items throws for mapfn');
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.includes.js
|
JavaScript
|
import { STRICT } from '../helpers/constants.js';
QUnit.test('Array#includes', assert => {
const { includes } = Array.prototype;
assert.isFunction(includes);
assert.name(includes, 'includes');
assert.arity(includes, 1);
assert.looksNative(includes);
assert.nonEnumerable(Array.prototype, 'includes');
const object = {};
const array = [1, 2, 3, -0, object];
assert.true(array.includes(1));
assert.true(array.includes(-0));
assert.true(array.includes(0));
assert.true(array.includes(object));
assert.false(array.includes(4));
assert.false(array.includes(-0.5));
assert.false(array.includes({}));
assert.true(Array(1).includes(undefined));
assert.true([NaN].includes(NaN));
if (STRICT) {
assert.throws(() => includes.call(null, 0), TypeError);
assert.throws(() => includes.call(undefined, 0), TypeError);
}
assert.true('includes' in Array.prototype[Symbol.unscopables], 'In Array#@@unscopables');
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.index-of.js
|
JavaScript
|
import { STRICT } from '../helpers/constants.js';
QUnit.test('Array#indexOf', assert => {
const { indexOf } = Array.prototype;
assert.isFunction(indexOf);
assert.arity(indexOf, 1);
assert.name(indexOf, 'indexOf');
assert.looksNative(indexOf);
assert.nonEnumerable(Array.prototype, 'indexOf');
assert.same(0, [1, 1, 1].indexOf(1));
assert.same(-1, [1, 2, 3].indexOf(1, 1));
assert.same(1, [1, 2, 3].indexOf(2, 1));
assert.same(-1, [1, 2, 3].indexOf(2, -1));
assert.same(1, [1, 2, 3].indexOf(2, -2));
assert.same(-1, [NaN].indexOf(NaN));
assert.same(3, Array(2).concat([1, 2, 3]).indexOf(2));
assert.same(-1, Array(1).indexOf(undefined));
assert.same(0, [1].indexOf(1, -0), "shouldn't return negative zero");
if (STRICT) {
assert.throws(() => indexOf.call(null, 0), TypeError);
assert.throws(() => indexOf.call(undefined, 0), TypeError);
}
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.is-array.js
|
JavaScript
|
QUnit.test('Array.isArray', assert => {
const { isArray } = Array;
assert.isFunction(isArray);
assert.arity(isArray, 1);
assert.name(isArray, 'isArray');
assert.looksNative(isArray);
assert.nonEnumerable(Array, 'isArray');
assert.false(isArray({}));
assert.false(isArray(function () {
// eslint-disable-next-line prefer-rest-params -- required for testing
return arguments;
}()));
assert.true(isArray([]));
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.iterator.js
|
JavaScript
|
import { GLOBAL } from '../helpers/constants.js';
const Symbol = GLOBAL.Symbol || {};
QUnit.test('Array#keys', assert => {
const { keys } = Array.prototype;
assert.isFunction(keys);
assert.arity(keys, 0);
assert.name(keys, 'keys');
assert.looksNative(keys);
assert.nonEnumerable(Array.prototype, 'keys');
const iterator = ['q', 'w', 'e'].keys();
assert.isIterator(iterator);
assert.isIterable(iterator);
assert.same(iterator[Symbol.toStringTag], 'Array Iterator');
assert.same(String(iterator), '[object Array Iterator]');
assert.deepEqual(iterator.next(), {
value: 0,
done: false,
});
assert.deepEqual(iterator.next(), {
value: 1,
done: false,
});
assert.deepEqual(iterator.next(), {
value: 2,
done: false,
});
assert.deepEqual(iterator.next(), {
value: undefined,
done: true,
});
/* still not fixed even in modern WebKit
assert.deepEqual(keys.call({
length: -1,
}).next(), {
value: undefined,
done: true,
}, 'uses ToLength');
*/
assert.true('keys' in Array.prototype[Symbol.unscopables], 'In Array#@@unscopables');
});
QUnit.test('Array#values', assert => {
const { values } = Array.prototype;
assert.isFunction(values);
assert.arity(values, 0);
assert.name(values, 'values');
assert.looksNative(values);
assert.nonEnumerable(Array.prototype, 'values');
const iterator = ['q', 'w', 'e'].values();
assert.isIterator(iterator);
assert.isIterable(iterator);
assert.same(iterator[Symbol.toStringTag], 'Array Iterator');
assert.deepEqual(iterator.next(), {
value: 'q',
done: false,
});
assert.deepEqual(iterator.next(), {
value: 'w',
done: false,
});
assert.deepEqual(iterator.next(), {
value: 'e',
done: false,
});
assert.deepEqual(iterator.next(), {
value: undefined,
done: true,
});
/* still not fixed even in modern WebKit
assert.deepEqual(values.call({
length: -1,
}).next(), {
value: undefined,
done: true,
}, 'uses ToLength');
*/
assert.true('values' in Array.prototype[Symbol.unscopables], 'In Array#@@unscopables');
});
QUnit.test('Array#entries', assert => {
const { entries } = Array.prototype;
assert.isFunction(entries);
assert.arity(entries, 0);
assert.name(entries, 'entries');
assert.looksNative(entries);
assert.nonEnumerable(Array.prototype, 'entries');
const iterator = ['q', 'w', 'e'].entries();
assert.isIterator(iterator);
assert.isIterable(iterator);
assert.same(iterator[Symbol.toStringTag], 'Array Iterator');
assert.deepEqual(iterator.next(), {
value: [0, 'q'],
done: false,
});
assert.deepEqual(iterator.next(), {
value: [1, 'w'],
done: false,
});
assert.deepEqual(iterator.next(), {
value: [2, 'e'],
done: false,
});
assert.deepEqual(iterator.next(), {
value: undefined,
done: true,
});
/* still not fixed even in modern WebKit
assert.deepEqual(entries.call({
length: -1,
}).next(), {
value: undefined,
done: true,
}, 'uses ToLength');
*/
assert.true('entries' in Array.prototype[Symbol.unscopables], 'In Array#@@unscopables');
});
QUnit.test('Array#@@iterator', assert => {
assert.isIterable(Array.prototype);
assert.arity(Array.prototype[Symbol.iterator], 0);
assert.name(Array.prototype[Symbol.iterator], 'values');
assert.looksNative(Array.prototype[Symbol.iterator]);
assert.nonEnumerable(Array.prototype, Symbol.iterator);
assert.same(Array.prototype[Symbol.iterator], Array.prototype.values);
const iterator = ['q', 'w', 'e'][Symbol.iterator]();
assert.isIterator(iterator);
assert.isIterable(iterator);
assert.same(iterator[Symbol.toStringTag], 'Array Iterator');
assert.deepEqual(iterator.next(), {
value: 'q',
done: false,
});
assert.deepEqual(iterator.next(), {
value: 'w',
done: false,
});
assert.deepEqual(iterator.next(), {
value: 'e',
done: false,
});
assert.deepEqual(iterator.next(), {
value: undefined,
done: true,
});
/* still not fixed even in modern WebKit
assert.deepEqual(Array.prototype[Symbol.iterator].call({
length: -1,
}).next(), {
value: undefined,
done: true,
}, 'uses ToLength');
*/
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.join.js
|
JavaScript
|
import { STRICT } from '../helpers/constants.js';
QUnit.test('Array#join', assert => {
const { join } = Array.prototype;
assert.isFunction(join);
assert.arity(join, 1);
assert.name(join, 'join');
assert.looksNative(join);
assert.nonEnumerable(Array.prototype, 'join');
assert.same(join.call([1, 2, 3], undefined), '1,2,3');
assert.same(join.call('123'), '1,2,3');
assert.same(join.call('123', '|'), '1|2|3');
if (STRICT) {
assert.throws(() => join.call(null, 0), TypeError);
assert.throws(() => join.call(undefined, 0), TypeError);
}
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.last-index-of.js
|
JavaScript
|
import { STRICT } from '../helpers/constants.js';
QUnit.test('Array#lastIndexOf', assert => {
const { lastIndexOf } = Array.prototype;
assert.isFunction(lastIndexOf);
assert.arity(lastIndexOf, 1);
assert.name(lastIndexOf, 'lastIndexOf');
assert.looksNative(lastIndexOf);
assert.nonEnumerable(Array.prototype, 'lastIndexOf');
assert.same(2, [1, 1, 1].lastIndexOf(1));
assert.same(-1, [1, 2, 3].lastIndexOf(3, 1));
assert.same(1, [1, 2, 3].lastIndexOf(2, 1));
assert.same(-1, [1, 2, 3].lastIndexOf(2, -3));
assert.same(-1, [1, 2, 3].lastIndexOf(1, -4));
assert.same(1, [1, 2, 3].lastIndexOf(2, -2));
assert.same(-1, [NaN].lastIndexOf(NaN));
assert.same(1, [1, 2, 3].concat(Array(2)).lastIndexOf(2));
assert.same(0, [1].lastIndexOf(1, -0), "shouldn't return negative zero");
if (STRICT) {
assert.throws(() => lastIndexOf.call(null, 0), TypeError);
assert.throws(() => lastIndexOf.call(undefined, 0), TypeError);
}
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.map.js
|
JavaScript
|
import { STRICT } from '../helpers/constants.js';
QUnit.test('Array#map', assert => {
const { map } = Array.prototype;
assert.isFunction(map);
assert.arity(map, 1);
assert.name(map, 'map');
assert.looksNative(map);
assert.nonEnumerable(Array.prototype, 'map');
let array = [1];
const context = {};
array.map(function (value, key, that) {
assert.same(arguments.length, 3, 'correct number of callback arguments');
assert.same(value, 1, 'correct value in callback');
assert.same(key, 0, 'correct index in callback');
assert.same(that, array, 'correct link to array in callback');
assert.same(this, context, 'correct callback context');
}, context);
assert.deepEqual([2, 3, 4], [1, 2, 3].map(value => value + 1));
assert.deepEqual([1, 3, 5], [1, 2, 3].map((value, key) => value + key));
assert.deepEqual([2, 2, 2], [1, 2, 3].map(function () {
return +this;
}, 2));
if (STRICT) {
assert.throws(() => map.call(null, () => { /* empty */ }), TypeError);
assert.throws(() => map.call(undefined, () => { /* empty */ }), TypeError);
}
array = [];
// eslint-disable-next-line object-shorthand -- constructor
array.constructor = { [Symbol.species]: function () {
return { foo: 1 };
} };
// eslint-disable-next-line es/no-nonstandard-array-prototype-properties -- @@species
assert.same(array.map(Boolean).foo, 1, '@@species');
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.of.js
|
JavaScript
|
import { DESCRIPTORS } from '../helpers/constants.js';
QUnit.test('Array.of', assert => {
const { defineProperty } = Object;
assert.isFunction(Array.of);
assert.arity(Array.of, 0);
assert.name(Array.of, 'of');
assert.looksNative(Array.of);
assert.nonEnumerable(Array, 'of');
assert.deepEqual(Array.of(1), [1]);
assert.deepEqual(Array.of(1, 2, 3), [1, 2, 3]);
class C { /* empty */ }
const instance = Array.of.call(C, 1, 2);
assert.true(instance instanceof C);
assert.same(instance[0], 1);
assert.same(instance[1], 2);
assert.same(instance.length, 2);
if (DESCRIPTORS) {
let called = false;
defineProperty(C.prototype, 0, {
set() {
called = true;
},
});
Array.of.call(C, 1, 2, 3);
assert.false(called, 'Should not call prototype accessors');
}
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.push.js
|
JavaScript
|
import { REDEFINABLE_ARRAY_LENGTH_DESCRIPTOR, STRICT } from '../helpers/constants.js';
const { defineProperty } = Object;
QUnit.test('Array#push', assert => {
const { push } = Array.prototype;
assert.isFunction(push);
assert.arity(push, 1);
assert.name(push, 'push');
assert.looksNative(push);
assert.nonEnumerable(Array.prototype, 'push');
const object = { length: 0x100000000 };
assert.same(push.call(object, 1), 0x100000001, 'proper ToLength #1');
assert.same(object[0x100000000], 1, 'proper ToLength #2');
if (STRICT) {
if (REDEFINABLE_ARRAY_LENGTH_DESCRIPTOR) {
assert.throws(() => push.call(defineProperty([], 'length', { writable: false }), 1), TypeError, 'non-writable length, with arg');
assert.throws(() => push.call(defineProperty([], 'length', { writable: false })), TypeError, 'non-writable length, without arg');
}
assert.throws(() => push.call(null), TypeError);
assert.throws(() => push.call(undefined), TypeError);
}
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.reduce-right.js
|
JavaScript
|
import { STRICT } from '../helpers/constants.js';
QUnit.test('Array#reduceRight', assert => {
const { reduceRight } = Array.prototype;
assert.isFunction(reduceRight);
assert.arity(reduceRight, 1);
assert.name(reduceRight, 'reduceRight');
assert.looksNative(reduceRight);
assert.nonEnumerable(Array.prototype, 'reduceRight');
const array = [1];
const accumulator = {};
array.reduceRight(function (memo, value, key, that) {
assert.same(arguments.length, 4, 'correct number of callback arguments');
assert.same(memo, accumulator, 'correct callback accumulator');
assert.same(value, 1, 'correct value in callback');
assert.same(key, 0, 'correct index in callback');
assert.same(that, array, 'correct link to array in callback');
}, accumulator);
assert.same([1, 2, 3].reduceRight((a, b) => a + b, 1), 7, 'works with initial accumulator');
[1, 2].reduceRight((memo, value, key) => {
assert.same(memo, 2, 'correct default accumulator');
assert.same(value, 1, 'correct start value without initial accumulator');
assert.same(key, 0, 'correct start index without initial accumulator');
});
assert.same([1, 2, 3].reduceRight((a, b) => a + b), 6, 'works without initial accumulator');
let values = '';
let keys = '';
[1, 2, 3].reduceRight((memo, value, key) => {
values += value;
keys += key;
}, 0);
assert.same(values, '321', 'correct order #1');
assert.same(keys, '210', 'correct order #2');
assert.same(reduceRight.call({
0: 1,
1: 2,
length: 2,
}, (a, b) => a + b), 3, 'generic');
assert.throws(() => reduceRight.call([], () => { /* empty */ }), TypeError);
assert.throws(() => reduceRight.call(Array(5), () => { /* empty */ }), TypeError);
if (STRICT) {
assert.throws(() => reduceRight.call(null, () => { /* empty */ }, 1), TypeError);
assert.throws(() => reduceRight.call(undefined, () => { /* empty */ }, 1), TypeError);
}
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.reduce.js
|
JavaScript
|
import { STRICT } from '../helpers/constants.js';
QUnit.test('Array#reduce', assert => {
const { reduce } = Array.prototype;
assert.isFunction(reduce);
assert.arity(reduce, 1);
assert.name(reduce, 'reduce');
assert.looksNative(reduce);
assert.nonEnumerable(Array.prototype, 'reduce');
const array = [1];
const accumulator = {};
array.reduce(function (memo, value, key, that) {
assert.same(arguments.length, 4, 'correct number of callback arguments');
assert.same(memo, accumulator, 'correct callback accumulator');
assert.same(value, 1, 'correct value in callback');
assert.same(key, 0, 'correct index in callback');
assert.same(that, array, 'correct link to array in callback');
}, accumulator);
assert.same([1, 2, 3].reduce((a, b) => a + b, 1), 7, 'works with initial accumulator');
[1, 2].reduce((memo, value, key) => {
assert.same(memo, 1, 'correct default accumulator');
assert.same(value, 2, 'correct start value without initial accumulator');
assert.same(key, 1, 'correct start index without initial accumulator');
});
assert.same([1, 2, 3].reduce((a, b) => a + b), 6, 'works without initial accumulator');
let values = '';
let keys = '';
[1, 2, 3].reduce((memo, value, key) => {
values += value;
keys += key;
}, 0);
assert.same(values, '123', 'correct order #1');
assert.same(keys, '012', 'correct order #2');
assert.same(reduce.call({
0: 1,
1: 2,
length: 2,
}, (a, b) => a + b), 3, 'generic');
assert.throws(() => reduce.call([], () => { /* empty */ }), TypeError);
assert.throws(() => reduce.call(Array(5), () => { /* empty */ }), TypeError);
if (STRICT) {
assert.throws(() => reduce.call(null, () => { /* empty */ }, 1), TypeError);
assert.throws(() => reduce.call(undefined, () => { /* empty */ }, 1), TypeError);
}
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.reverse.js
|
JavaScript
|
import { STRICT } from '../helpers/constants.js';
QUnit.test('Array#reverse', assert => {
const { reverse } = Array.prototype;
assert.isFunction(reverse);
assert.arity(reverse, 0);
assert.name(reverse, 'reverse');
assert.looksNative(reverse);
assert.nonEnumerable(Array.prototype, 'reverse');
const a = [1, 2.2, 3.3];
function fn() {
+a;
a.reverse();
}
fn();
assert.arrayEqual(a, [3.3, 2.2, 1]);
if (STRICT) {
assert.throws(() => reverse.call(null, () => { /* empty */ }, 1), TypeError);
assert.throws(() => reverse.call(undefined, () => { /* empty */ }, 1), TypeError);
}
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.slice.js
|
JavaScript
|
import { GLOBAL, STRICT } from '../helpers/constants.js';
QUnit.test('Array#slice', assert => {
const { slice } = Array.prototype;
const { isArray } = Array;
assert.isFunction(slice);
assert.arity(slice, 2);
assert.name(slice, 'slice');
assert.looksNative(slice);
assert.nonEnumerable(Array.prototype, 'slice');
let array = ['1', '2', '3', '4', '5'];
assert.deepEqual(array.slice(), array);
assert.deepEqual(array.slice(1, 3), ['2', '3']);
assert.deepEqual(array.slice(1, undefined), ['2', '3', '4', '5']);
assert.deepEqual(array.slice(1, -1), ['2', '3', '4']);
assert.deepEqual(array.slice(-2, -1), ['4']);
assert.deepEqual(array.slice(-2, -3), []);
const string = '12345';
assert.deepEqual(slice.call(string), array);
assert.deepEqual(slice.call(string, 1, 3), ['2', '3']);
assert.deepEqual(slice.call(string, 1, undefined), ['2', '3', '4', '5']);
assert.deepEqual(slice.call(string, 1, -1), ['2', '3', '4']);
assert.deepEqual(slice.call(string, -2, -1), ['4']);
assert.deepEqual(slice.call(string, -2, -3), []);
const list = GLOBAL.document && document.body && document.body.childNodes;
if (list) {
assert.notThrows(() => isArray(slice.call(list)), 'works on NodeList');
}
if (STRICT) {
assert.throws(() => slice.call(null), TypeError);
assert.throws(() => slice.call(undefined), TypeError);
}
array = [];
// eslint-disable-next-line object-shorthand -- constructor
array.constructor = { [Symbol.species]: function () {
return { foo: 1 };
} };
// eslint-disable-next-line es/no-nonstandard-array-prototype-properties -- @@species
assert.same(array.slice().foo, 1, '@@species');
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.some.js
|
JavaScript
|
import { STRICT } from '../helpers/constants.js';
QUnit.test('Array#some', assert => {
const { some } = Array.prototype;
assert.isFunction(some);
assert.arity(some, 1);
assert.name(some, 'some');
assert.looksNative(some);
assert.nonEnumerable(Array.prototype, 'some');
let array = [1];
const context = {};
array.some(function (value, key, that) {
assert.same(arguments.length, 3, 'correct number of callback arguments');
assert.same(value, 1, 'correct value in callback');
assert.same(key, 0, 'correct index in callback');
assert.same(that, array, 'correct link to array in callback');
assert.same(this, context, 'correct callback context');
}, context);
assert.true([1, '2', 3].some(value => typeof value == 'number'));
assert.true([1, 2, 3].some(value => value < 3));
assert.false([1, 2, 3].some(value => value < 0));
assert.false([1, 2, 3].some(value => typeof value == 'string'));
assert.false([1, 2, 3].some(function () {
return +this !== 1;
}, 1));
let result = '';
[1, 2, 3].some((value, key) => {
result += key;
return false;
});
assert.same(result, '012');
array = [1, 2, 3];
assert.false(array.some((value, key, that) => that !== array));
if (STRICT) {
assert.throws(() => some.call(null, () => { /* empty */ }), TypeError);
assert.throws(() => some.call(undefined, () => { /* empty */ }), TypeError);
}
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.sort.js
|
JavaScript
|
import { STRICT } from '../helpers/constants.js';
QUnit.test('Array#sort', assert => {
const { sort } = Array.prototype;
assert.isFunction(sort);
assert.arity(sort, 1);
assert.name(sort, 'sort');
assert.looksNative(sort);
assert.nonEnumerable(Array.prototype, 'sort');
assert.deepEqual([1, 3, 2].sort(), [1, 2, 3], '#1');
assert.deepEqual([1, 3, 2, 11].sort(), [1, 11, 2, 3], '#2');
assert.deepEqual([1, -1, 3, NaN, 2, 0, 11, -0].sort(), [-1, 0, -0, 1, 11, 2, 3, NaN], '#1');
let array = Array(5);
array[0] = 1;
array[2] = 3;
array[4] = 2;
let expected = Array(5);
expected[0] = 1;
expected[1] = 2;
expected[2] = 3;
assert.deepEqual(array.sort(), expected, 'holes');
array = 'zyxwvutsrqponMLKJIHGFEDCBA'.split('');
expected = 'ABCDEFGHIJKLMnopqrstuvwxyz'.split('');
assert.deepEqual(array.sort(), expected, 'alpha #1');
array = 'ёяюэьыъщшчцхфутсрПОНМЛКЙИЗЖЕДГВБА'.split('');
expected = 'АБВГДЕЖЗИЙКЛМНОПрстуфхцчшщъыьэюяё'.split('');
assert.deepEqual(array.sort(), expected, 'alpha #2');
array = [undefined, 1];
assert.notThrows(() => array.sort(() => { throw 1; }), 'undefined #1');
assert.deepEqual(array, [1, undefined], 'undefined #2');
/* Safari TP ~ 17.6 issue
const object = {
valueOf: () => 1,
toString: () => -1,
};
array = {
0: undefined,
1: 2,
2: 1,
3: 'X',
4: -1,
5: 'a',
6: true,
7: object,
8: NaN,
10: Infinity,
length: 11,
};
expected = {
0: -1,
1: object,
2: 1,
3: 2,
4: Infinity,
5: NaN,
6: 'X',
7: 'a',
8: true,
9: undefined,
length: 11,
};
assert.deepEqual(sort.call(array), expected, 'custom generic');
*/
let index, mod, code, chr, value;
expected = Array(516);
array = Array(516);
for (index = 0; index < 516; index++) {
mod = index % 4;
array[index] = 515 - index;
expected[index] = index - 2 * mod + 3;
}
array.sort((a, b) => (a / 4 | 0) - (b / 4 | 0));
assert.true(1 / [0, -0].sort()[0] > 0, '-0');
assert.arrayEqual(array, expected, 'stable #1');
let result = '';
array = [];
// generate an array with more 512 elements (Chakra and old V8 fails only in this case)
for (code = 65; code < 76; code++) {
chr = String.fromCharCode(code);
switch (code) {
case 66: case 69: case 70: case 72: value = 3; break;
case 68: case 71: value = 4; break;
default: value = 2;
}
for (index = 0; index < 47; index++) {
array.push({ k: chr + index, v: value });
}
}
array.sort((a, b) => b.v - a.v);
for (index = 0; index < array.length; index++) {
chr = array[index].k.charAt(0);
if (result.charAt(result.length - 1) !== chr) result += chr;
}
assert.same(result, 'DGBEFHACIJK', 'stable #2');
// default comparator returns 0 for equal string representations
const obj1 = { toString() { return 'a'; } };
const obj2 = { toString() { return 'a'; } };
assert.same([obj1, obj2].sort()[0], obj1, 'stable sort for equal string representations');
assert.notThrows(() => [1, 2, 3].sort(undefined).length === 3, 'works with undefined');
assert.throws(() => [1, 2, 3].sort(null), 'throws on null');
assert.throws(() => [1, 2, 3].sort({}), 'throws on {}');
if (typeof Symbol == 'function' && !Symbol.sham) {
assert.throws(() => [Symbol(1), Symbol(2)].sort(), 'w/o cmp throws on symbols');
}
if (STRICT) {
assert.throws(() => sort.call(null), TypeError, 'ToObject(this)');
assert.throws(() => sort.call(undefined), TypeError, 'ToObject(this)');
}
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.splice.js
|
JavaScript
|
import { REDEFINABLE_ARRAY_LENGTH_DESCRIPTOR, STRICT } from '../helpers/constants.js';
const { defineProperty } = Object;
QUnit.test('Array#splice', assert => {
const { splice } = Array.prototype;
assert.isFunction(splice);
assert.arity(splice, 2);
assert.name(splice, 'splice');
assert.looksNative(splice);
assert.nonEnumerable(Array.prototype, 'splice');
let array = [1, 2, 3, 4, 5];
assert.deepEqual(array.splice(2), [3, 4, 5]);
assert.deepEqual(array, [1, 2]);
array = [1, 2, 3, 4, 5];
assert.deepEqual(array.splice(-2), [4, 5]);
assert.deepEqual(array, [1, 2, 3]);
array = [1, 2, 3, 4, 5];
assert.deepEqual(array.splice(2, 2), [3, 4]);
assert.deepEqual(array, [1, 2, 5]);
array = [1, 2, 3, 4, 5];
assert.deepEqual(array.splice(2, -2), []);
assert.deepEqual(array, [1, 2, 3, 4, 5]);
array = [1, 2, 3, 4, 5];
assert.deepEqual(array.splice(2, 2, 6, 7), [3, 4]);
assert.deepEqual(array, [1, 2, 6, 7, 5]);
// ES6 semantics
array = [0, 1, 2];
assert.deepEqual(array.splice(0), [0, 1, 2]);
array = [0, 1, 2];
assert.deepEqual(array.splice(1), [1, 2]);
array = [0, 1, 2];
assert.deepEqual(array.splice(2), [2]);
if (STRICT) {
if (REDEFINABLE_ARRAY_LENGTH_DESCRIPTOR) {
assert.throws(() => splice.call(defineProperty([1, 2, 3], 'length', { writable: false }), 1, 1), TypeError, 'non-writable length');
}
assert.throws(() => splice.call(null), TypeError);
assert.throws(() => splice.call(undefined), TypeError);
}
array = [];
// eslint-disable-next-line object-shorthand -- constructor
array.constructor = { [Symbol.species]: function () {
return { foo: 1 };
} };
// eslint-disable-next-line es/no-nonstandard-array-prototype-properties -- @@species
assert.same(array.splice().foo, 1, '@@species');
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.to-reversed.js
|
JavaScript
|
import { STRICT } from '../helpers/constants.js';
QUnit.test('Array#toReversed', assert => {
const { toReversed } = Array.prototype;
assert.isFunction(toReversed);
assert.arity(toReversed, 0);
assert.name(toReversed, 'toReversed');
assert.looksNative(toReversed);
assert.nonEnumerable(Array.prototype, 'toReversed');
let array = [1, 2];
assert.notSame(array.toReversed(), array, 'immutable');
assert.deepEqual([1, 2.2, 3.3].toReversed(), [3.3, 2.2, 1], 'basic');
const object = {};
array = {
0: undefined,
1: 2,
2: 1,
3: 'X',
4: -1,
5: 'a',
6: true,
7: object,
8: NaN,
10: Infinity,
length: 11,
};
const expected = [
Infinity,
undefined,
NaN,
object,
true,
'a',
-1,
'X',
1,
2,
undefined,
];
assert.deepEqual(toReversed.call(array), expected, 'non-array target');
array = [1];
// eslint-disable-next-line object-shorthand -- constructor
array.constructor = { [Symbol.species]: function () {
return { foo: 1 };
} };
assert.true(array.toReversed() instanceof Array, 'non-generic');
if (STRICT) {
assert.throws(() => toReversed.call(null, () => { /* empty */ }, 1), TypeError);
assert.throws(() => toReversed.call(undefined, () => { /* empty */ }, 1), TypeError);
}
assert.true('toReversed' in Array.prototype[Symbol.unscopables], 'In Array#@@unscopables');
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.to-sorted.js
|
JavaScript
|
import { STRICT } from '../helpers/constants.js';
QUnit.test('Array#toSorted', assert => {
const { toSorted } = Array.prototype;
assert.isFunction(toSorted);
assert.arity(toSorted, 1);
assert.name(toSorted, 'toSorted');
assert.looksNative(toSorted);
assert.nonEnumerable(Array.prototype, 'toSorted');
let array = [1];
assert.notSame(array.toSorted(), array, 'immutable');
assert.deepEqual([1, 3, 2].toSorted(), [1, 2, 3], '#1');
assert.deepEqual([1, 3, 2, 11].toSorted(), [1, 11, 2, 3], '#2');
assert.deepEqual([1, -1, 3, NaN, 2, 0, 11, -0].toSorted(), [-1, 0, -0, 1, 11, 2, 3, NaN], '#1');
array = Array(5);
array[0] = 1;
array[2] = 3;
array[4] = 2;
let expected = Array(5);
expected[0] = 1;
expected[1] = 2;
expected[2] = 3;
assert.deepEqual(array.toSorted(), expected, 'holes');
array = 'zyxwvutsrqponMLKJIHGFEDCBA'.split('');
expected = 'ABCDEFGHIJKLMnopqrstuvwxyz'.split('');
assert.deepEqual(array.toSorted(), expected, 'alpha #1');
array = 'ёяюэьыъщшчцхфутсрПОНМЛКЙИЗЖЕДГВБА'.split('');
expected = 'АБВГДЕЖЗИЙКЛМНОПрстуфхцчшщъыьэюяё'.split('');
assert.deepEqual(array.toSorted(), expected, 'alpha #2');
array = [undefined, 1];
assert.notThrows(() => array = array.toSorted(() => { throw 1; }), 'undefined #1');
assert.deepEqual(array, [1, undefined], 'undefined #2');
/* Safari TP ~ 17.6 issue
const object = {
valueOf: () => 1,
toString: () => -1,
};
array = {
0: undefined,
1: 2,
2: 1,
3: 'X',
4: -1,
5: 'a',
6: true,
7: object,
8: NaN,
10: Infinity,
length: 11,
};
expected = [
-1,
object,
1,
2,
Infinity,
NaN,
'X',
'a',
true,
undefined,
undefined,
];
assert.deepEqual(toSorted.call(array), expected, 'non-array target');
*/
let index, mod, code, chr, value;
expected = Array(516);
array = Array(516);
for (index = 0; index < 516; index++) {
mod = index % 4;
array[index] = 515 - index;
expected[index] = index - 2 * mod + 3;
}
assert.arrayEqual(array.toSorted((a, b) => (a / 4 | 0) - (b / 4 | 0)), expected, 'stable #1');
assert.true(1 / [0, -0].toSorted()[0] > 0, '-0');
let result = '';
array = [];
// generate an array with more 512 elements (Chakra and old V8 fails only in this case)
for (code = 65; code < 76; code++) {
chr = String.fromCharCode(code);
switch (code) {
case 66: case 69: case 70: case 72: value = 3; break;
case 68: case 71: value = 4; break;
default: value = 2;
}
for (index = 0; index < 47; index++) {
array.push({ k: chr + index, v: value });
}
}
array = array.toSorted((a, b) => b.v - a.v);
for (index = 0; index < array.length; index++) {
chr = array[index].k.charAt(0);
if (result.charAt(result.length - 1) !== chr) result += chr;
}
assert.same(result, 'DGBEFHACIJK', 'stable #2');
assert.notThrows(() => [1, 2, 3].toSorted(undefined).length === 3, 'works with undefined');
assert.throws(() => [1, 2, 3].toSorted(null), 'throws on null');
assert.throws(() => [1, 2, 3].toSorted({}), 'throws on {}');
if (typeof Symbol == 'function' && !Symbol.sham) {
assert.throws(() => [Symbol(1), Symbol(2)].toSorted(), 'w/o cmp throws on symbols');
}
array = [1];
// eslint-disable-next-line object-shorthand -- constructor
array.constructor = { [Symbol.species]: function () {
return { foo: 1 };
} };
assert.true(array.toSorted() instanceof Array, 'non-generic');
if (STRICT) {
assert.throws(() => toSorted.call(null), TypeError, 'ToObject(this)');
assert.throws(() => toSorted.call(undefined), TypeError, 'ToObject(this)');
}
assert.true('toSorted' in Array.prototype[Symbol.unscopables], 'In Array#@@unscopables');
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.to-spliced.js
|
JavaScript
|
import { STRICT } from '../helpers/constants.js';
QUnit.test('Array#toSpliced', assert => {
const { toSpliced } = Array.prototype;
assert.isFunction(toSpliced);
assert.arity(toSpliced, 2);
assert.name(toSpliced, 'toSpliced');
assert.looksNative(toSpliced);
assert.nonEnumerable(Array.prototype, 'toSpliced');
let array = [1, 2, 3, 4, 5];
assert.notSame(array.toSpliced(2), array, 'immutable');
assert.deepEqual([1, 2, 3, 4, 5].toSpliced(2), [1, 2]);
assert.deepEqual([1, 2, 3, 4, 5].toSpliced(-2), [1, 2, 3]);
assert.deepEqual([1, 2, 3, 4, 5].toSpliced(2, 2), [1, 2, 5]);
assert.deepEqual([1, 2, 3, 4, 5].toSpliced(2, -2), [1, 2, 3, 4, 5]);
assert.deepEqual([1, 2, 3, 4, 5].toSpliced(2, 2, 6, 7), [1, 2, 6, 7, 5]);
if (STRICT) {
assert.throws(() => toSpliced.call(null), TypeError);
assert.throws(() => toSpliced.call(undefined), TypeError);
}
array = [];
// eslint-disable-next-line object-shorthand -- constructor
array.constructor = { [Symbol.species]: function () {
return { foo: 1 };
} };
assert.true(array.toSpliced() instanceof Array, 'non-generic');
assert.true('toSpliced' in Array.prototype[Symbol.unscopables], 'In Array#@@unscopables');
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
| |
tests/unit-global/es.array.unshift.js
|
JavaScript
|
import { REDEFINABLE_ARRAY_LENGTH_DESCRIPTOR, STRICT } from '../helpers/constants.js';
const { defineProperty } = Object;
QUnit.test('Array#unshift', assert => {
const { unshift } = Array.prototype;
assert.isFunction(unshift);
assert.arity(unshift, 1);
assert.name(unshift, 'unshift');
assert.looksNative(unshift);
assert.nonEnumerable(Array.prototype, 'unshift');
assert.same(unshift.call([1], 0), 2, 'proper result');
if (STRICT) {
if (REDEFINABLE_ARRAY_LENGTH_DESCRIPTOR) {
assert.throws(() => unshift.call(defineProperty([], 'length', { writable: false }), 1), TypeError, 'non-writable length, with arg');
assert.throws(() => unshift.call(defineProperty([], 'length', { writable: false })), TypeError, 'non-writable length, without arg');
}
assert.throws(() => unshift.call(null), TypeError);
assert.throws(() => unshift.call(undefined), TypeError);
}
});
|
zloirock/core-js
| 25,418
|
Standard Library
|
JavaScript
|
zloirock
|
Denis Pushkarev
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.