diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index aa61ded969c3..9fd14af60d54 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,6 +21,17 @@ jobs: - run: pip install codespell - run: npx run-s lint-raw codespell + type-definitions: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-node@v6 + with: + node-version: 25 + cache: npm + - run: npm run prepare-monorepo + - run: npx run-s build-types test-type-definitions-ci + karma: runs-on: windows-2022 steps: diff --git a/.gitignore b/.gitignore index c2fcdb0697c5..76340f29e8d9 100644 --- a/.gitignore +++ b/.gitignore @@ -45,15 +45,19 @@ node_modules/ /packages/core-js-pure/proposals/ /packages/core-js-pure/stable/ /packages/core-js-pure/stage/ -/packages/core-js-pure/index.js /packages/core-js-pure/configurator.js +/packages/core-js-pure/index.js /packages/core-js-pure/package.json /packages/core-js-pure/LICENSE +/packages/core-js-types/package.json +/packages/core-js-types/ts* +/packages/core-js-types/LICENSE /tests/**/bundles/ /tests/compat/*.jar /tests/compat/compat-data.js /tests/unit-global/index.js /tests/unit-pure/index.js +/tests/type-definitions/tmp/ /website/templates/ /website/dist/ /website/src/public/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e3066e91127b..706e5f4e8352 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -16,7 +16,7 @@ There is always some ["help wanted" issues](https://github.com/zloirock/core-js/ - For export the polyfill, in all common cases use [`internals/export`](./packages/core-js/modules/export.js) helper. Use something else only if this helper is not applicable - for example, if you want to polyfill accessors. - If the code of the pure version implementation should significantly differ from the global version (*that's not a frequent situation, in most cases [`internals/is-pure`](./packages/core-js/modules/is-pure.js) constant is enough*), you can add it to [`packages/core-js-pure/override`](./packages/core-js-pure/override) directory. The rest parts of `@core-js/pure` will be copied from `core-js` package. - Add the feature detection of the polyfill to [`tests/compat/tests.js`](./tests/compat/tests.js), add the compatibility data to [`packages/core-js-compat/src/data.mjs`](./packages/core-js-compat/src/data.mjs), how to do it [see below](#how-to-update-core-js-compat-data). -- Add it to entries definitions, see [`scripts/build-entries/entries-definitions.mjs`](./scripts/build-entries/entries-definitions.mjs). +- Add it to entries definitions, see [`scripts/build-entries-and-types/entries-definitions.mjs`](scripts/build-entries-and-types/entries-definitions.mjs). - Add unit tests to [`tests/unit-global`](./tests/unit-global) and [`tests/unit-pure`](./tests/unit-pure). - Add tests of entry points to [`tests/entries/unit.mjs`](./tests/entries/unit.mjs). - Make sure that you are following [our coding style](#style-and-standards) and [all tests](#testing) are passed. @@ -65,6 +65,33 @@ engine | how to run tests | base data inherits from | mandatory ch If you have no access to all required browsers / versions of browsers, use [Sauce Labs](https://saucelabs.com/), [BrowserStack](https://www.browserstack.com/) or [Cloud Browser](https://ieonchrome.com/). +## TypeScript type definitions + +- TypeScript definitions should be added to the [`packages/core-js-types/src/base`](./packages/core-js-types/src/base) directory. +- Our type definitions are built on top of ES6. If any related type is missing in ES6, it must be added to the [`packages/core-js-types/src/base/core-js-types`](./packages/core-js-types/src/base/core-js-types) directory and imported via triple-slash directives in your type definition file. +- Place your type definition into the folder that matches its kind ([`packages/core-js-types/src/base/proposals`](./packages/core-js-types/src/base/proposals), [`packages/core-js-types/src/base/web`](./packages/core-js-types/src/base/web)). +- Type definitions for the pure version are either generated from the global version types or created manually in the [`packages/core-js-types/src/base/pure`](./packages/core-js-types/src/base/pure) folder. Type build rules for the pure version can be modified using the `@type-options` directive: + - `no-extends` – do not extend the base type when adding a prefix to the type/interface + - `no-prefix` – do not add a prefix to the type/interface name + - `no-constructor` – use it when the type has no constructor (for example, `Math`) + - `export-base-constructor` – export the base type’s constructor instead of the prefixed one + - `no-export` – do not export this type + - `no-redefine` – do not redefine the type’s constructor + - `prefix-return-type` – add a prefix to the return type +- All type definitions must be covered by TSC tests. Add them to the [`tests/type-definitions`](./tests/type-definitions) directory. +- To build the types, run the command: + ```sh + npm run build-types + ``` +- To test the types, run the command: + ```sh + npm run test-type-definitions-all + ``` +- To run the fast subset of the types test, run the command: + ```sh + npm run test-type-definitions-smoke + ``` + ## Style and standards The coding style should follow our [`eslint.config.js`](./tests/eslint/eslint.config.js). You can test it by calling [`npm run lint`](#testing). Different places have different syntax and standard library limitations: diff --git a/docs/web/docs/features/proposals/accessible-object-prototype-hasownproperty.md b/docs/web/docs/features/proposals/accessible-object-prototype-hasownproperty.md index c0c0469f3070..7349aa74b7ec 100644 --- a/docs/web/docs/features/proposals/accessible-object-prototype-hasownproperty.md +++ b/docs/web/docs/features/proposals/accessible-object-prototype-hasownproperty.md @@ -13,3 +13,6 @@ class Object { ```plaintext core-js/proposals/accessible-object-hasownproperty ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/accessible-object-hasownproperty`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/accessible-object-hasownproperty.d.ts) diff --git a/docs/web/docs/features/proposals/array-deduplication.md b/docs/web/docs/features/proposals/array-deduplication.md index 39d0df81bbc2..81bf9ce6a032 100644 --- a/docs/web/docs/features/proposals/array-deduplication.md +++ b/docs/web/docs/features/proposals/array-deduplication.md @@ -22,6 +22,9 @@ core-js(-pure)/full/array(/prototype)/unique-by core-js/full/typed-array/unique-by ``` +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/array-unique`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/array-unique.d.ts) + ## Examples ```js [1, 2, 3, 2, 1].uniqueBy(); // [1, 2, 3] diff --git a/docs/web/docs/features/proposals/array-filtering.md b/docs/web/docs/features/proposals/array-filtering.md index 8aac455befbf..b030ed3b65c7 100644 --- a/docs/web/docs/features/proposals/array-filtering.md +++ b/docs/web/docs/features/proposals/array-filtering.md @@ -23,6 +23,9 @@ core-js(-pure)/full/array(/prototype)/filter-reject core-js/full/typed-array/filter-reject ``` +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/array-filtering`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/array-filtering.d.ts) + ## Examples ```js [1, 2, 3, 4, 5].filterReject(it => it % 2); // => [2, 4] diff --git a/docs/web/docs/features/proposals/array-find-from-last.md b/docs/web/docs/features/proposals/array-find-from-last.md index 83c11f7fc082..3fb749f92944 100644 --- a/docs/web/docs/features/proposals/array-find-from-last.md +++ b/docs/web/docs/features/proposals/array-find-from-last.md @@ -19,3 +19,6 @@ class %TypedArray% { ```plaintext core-js/proposals/array-find-from-last ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/array-find-from-last`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/array-find-from-last.d.ts) diff --git a/docs/web/docs/features/proposals/array-fromasync.md b/docs/web/docs/features/proposals/array-fromasync.md index d6137c2518ad..5b8c44f99462 100644 --- a/docs/web/docs/features/proposals/array-fromasync.md +++ b/docs/web/docs/features/proposals/array-fromasync.md @@ -13,3 +13,6 @@ class Array { ```plaintext core-js/proposals/array-from-async ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/array-from-async`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/array-from-async.d.ts) diff --git a/docs/web/docs/features/proposals/array-grouping.md b/docs/web/docs/features/proposals/array-grouping.md index e441fedca303..ea21f3c15c6c 100644 --- a/docs/web/docs/features/proposals/array-grouping.md +++ b/docs/web/docs/features/proposals/array-grouping.md @@ -17,3 +17,6 @@ class Map { ```plaintext core-js/proposals/array-grouping-v2 ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/array-grouping`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/array-grouping.d.ts) diff --git a/docs/web/docs/features/proposals/array-istemplateobject.md b/docs/web/docs/features/proposals/array-istemplateobject.md index c3e116d69bce..8fd6cee682fc 100644 --- a/docs/web/docs/features/proposals/array-istemplateobject.md +++ b/docs/web/docs/features/proposals/array-istemplateobject.md @@ -18,6 +18,9 @@ core-js/proposals/array-is-template-object core-js(-pure)/full/array/is-template-object ``` +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/array-is-template-object`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/array-is-template-object.d.ts) + ## Example ```js console.log(Array.isTemplateObject((it => it)`qwe${ 123 }asd`)); // => true diff --git a/docs/web/docs/features/proposals/array-prototype-flat-flatmap.md b/docs/web/docs/features/proposals/array-prototype-flat-flatmap.md index 2bdbeb21076e..8354c8d102c9 100644 --- a/docs/web/docs/features/proposals/array-prototype-flat-flatmap.md +++ b/docs/web/docs/features/proposals/array-prototype-flat-flatmap.md @@ -14,3 +14,6 @@ class Array { ```plaintext core-js/proposals/array-flat-map ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/array-flat-map`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/array-flat-map.d.ts) diff --git a/docs/web/docs/features/proposals/array-prototype-includes.md b/docs/web/docs/features/proposals/array-prototype-includes.md index d725e01f820a..f90d37934fe7 100644 --- a/docs/web/docs/features/proposals/array-prototype-includes.md +++ b/docs/web/docs/features/proposals/array-prototype-includes.md @@ -16,3 +16,6 @@ class %TypedArray% { ```plaintext core-js/proposals/array-includes ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/array-includes`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/array-includes.d.ts) diff --git a/docs/web/docs/features/proposals/arraybuffer-prototype-transfer.md b/docs/web/docs/features/proposals/arraybuffer-prototype-transfer.md index fa0016c7e33e..c4f7ee9938d8 100644 --- a/docs/web/docs/features/proposals/arraybuffer-prototype-transfer.md +++ b/docs/web/docs/features/proposals/arraybuffer-prototype-transfer.md @@ -15,3 +15,6 @@ class ArrayBuffer { ```plaintext core-js/proposals/array-buffer-transfer ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/array-buffer-transfer`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/array-buffer-transfer.d.ts) diff --git a/docs/web/docs/features/proposals/asynciterator-helpers.md b/docs/web/docs/features/proposals/asynciterator-helpers.md index 519eb7491da5..860303818c16 100644 --- a/docs/web/docs/features/proposals/asynciterator-helpers.md +++ b/docs/web/docs/features/proposals/asynciterator-helpers.md @@ -47,6 +47,9 @@ core-js(-pure)/actual|full/async-iterator/to-array core-js(-pure)/actual|full/iterator/to-async ``` +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/async-iterator-helpers`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/async-iterator-helpers.d.ts) + ## Examples ```js await AsyncIterator.from([1, 2, 3, 4, 5, 6, 7]) diff --git a/docs/web/docs/features/proposals/await-dictionary.md b/docs/web/docs/features/proposals/await-dictionary.md index 15b86e9e7d84..3f25366b1f76 100644 --- a/docs/web/docs/features/proposals/await-dictionary.md +++ b/docs/web/docs/features/proposals/await-dictionary.md @@ -19,12 +19,15 @@ class Promise { ``` ## [Entry points]({docs-version}/docs/usage#h-entry-points) -```ts +```plaintext core-js/proposals/promise-all-keyed core-js(-pure)/full/promise/all-keyed core-js(-pure)/full/promise/all-settled-keyed ``` +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/await-dictionary`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/await-dictionary.d.ts) + ## Examples ```js await Promise.allKeyed({ diff --git a/docs/web/docs/features/proposals/change-array-by-copy.md b/docs/web/docs/features/proposals/change-array-by-copy.md index ec65731f418a..e485bda27447 100644 --- a/docs/web/docs/features/proposals/change-array-by-copy.md +++ b/docs/web/docs/features/proposals/change-array-by-copy.md @@ -29,3 +29,6 @@ core-js/es|stable|actual|full/typed-array/to-reversed core-js/es|stable|actual|full/typed-array/to-sorted core-js/es|stable|actual|full/typed-array/with ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/change-array-by-copy`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/change-array-by-copy.d.ts) diff --git a/docs/web/docs/features/proposals/dataview-get-set-uint8clamped.md b/docs/web/docs/features/proposals/dataview-get-set-uint8clamped.md index d870e2f0bdb4..64a94fea8dda 100644 --- a/docs/web/docs/features/proposals/dataview-get-set-uint8clamped.md +++ b/docs/web/docs/features/proposals/dataview-get-set-uint8clamped.md @@ -20,6 +20,9 @@ core-js/full/dataview/get-uint8-clamped core-js/full/dataview/set-uint8-clamped ``` +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/data-view-get-set-uint8-clamped`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/data-view-get-set-uint8-clamped.d.ts) + ## Examples ```js const view = new DataView(new ArrayBuffer(1)); diff --git a/docs/web/docs/features/proposals/error-iserror.md b/docs/web/docs/features/proposals/error-iserror.md index 2ede2ef817a8..531136875c40 100644 --- a/docs/web/docs/features/proposals/error-iserror.md +++ b/docs/web/docs/features/proposals/error-iserror.md @@ -14,5 +14,8 @@ class Error { core-js/proposals/is-error ``` +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/is-error`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/is-error.d.ts) + > [!WARNING] > We have no bulletproof way to polyfill this `Error.isError` / check if the object is an error, so it's an enough naive implementation. diff --git a/docs/web/docs/features/proposals/explicit-resource-management.md b/docs/web/docs/features/proposals/explicit-resource-management.md index ee0079f2de16..4c1c394f4278 100644 --- a/docs/web/docs/features/proposals/explicit-resource-management.md +++ b/docs/web/docs/features/proposals/explicit-resource-management.md @@ -54,3 +54,6 @@ class AsyncIterator { ```plaintext core-js/proposals/explicit-resource-management ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/explicit-resource-management`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/explicit-resource-management.d.ts) diff --git a/docs/web/docs/features/proposals/float16-methods.md b/docs/web/docs/features/proposals/float16-methods.md index 36a8c7d50173..be5132cf3204 100644 --- a/docs/web/docs/features/proposals/float16-methods.md +++ b/docs/web/docs/features/proposals/float16-methods.md @@ -18,3 +18,6 @@ namespace Math { ```plaintext core-js/proposals/float16 ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/float16`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/float16.d.ts) diff --git a/docs/web/docs/features/proposals/function-prototype-demethodize.md b/docs/web/docs/features/proposals/function-prototype-demethodize.md index f2588984a23b..bc0cb24e40b2 100644 --- a/docs/web/docs/features/proposals/function-prototype-demethodize.md +++ b/docs/web/docs/features/proposals/function-prototype-demethodize.md @@ -18,6 +18,9 @@ core-js(-pure)/full/function/demethodize core-js(-pure)/full/function/prototype/demethodize ``` +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/function-demethodize`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/function-demethodize.d.ts) + ## Examples ```js const slice = Array.prototype.slice.demethodize(); diff --git a/docs/web/docs/features/proposals/iterator-chunking.md b/docs/web/docs/features/proposals/iterator-chunking.md index 02074a072f4d..0bf7f8cbc110 100644 --- a/docs/web/docs/features/proposals/iterator-chunking.md +++ b/docs/web/docs/features/proposals/iterator-chunking.md @@ -20,6 +20,9 @@ core-js(-pure)/full/iterator/chunks core-js(-pure)/full/iterator/windows ``` +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/iterator-chunking`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/iterator-chunking.d.ts) + ## Examples ```js const digits = () => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].values(); diff --git a/docs/web/docs/features/proposals/iterator-helpers.md b/docs/web/docs/features/proposals/iterator-helpers.md index 98c2a55c9ed6..b5065a0e4446 100644 --- a/docs/web/docs/features/proposals/iterator-helpers.md +++ b/docs/web/docs/features/proposals/iterator-helpers.md @@ -25,3 +25,6 @@ class Iterator { ```plaintext core-js/proposals/iterator-helpers ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/iterator-helpers`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/iterator-helpers.d.ts) diff --git a/docs/web/docs/features/proposals/iterator-join.md b/docs/web/docs/features/proposals/iterator-join.md index 88cc8df32d94..8b248ba1ce21 100644 --- a/docs/web/docs/features/proposals/iterator-join.md +++ b/docs/web/docs/features/proposals/iterator-join.md @@ -13,11 +13,14 @@ class Iterator { ``` ## [Entry points]({docs-version}/docs/usage#h-entry-points) -```ts +```plaintext core-js/proposals/iterator-join core-js(-pure)/full/iterator/join ``` +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/iterator-join`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/iterator-join.d.ts) + ## Examples ```js const digits = () => [1, 2, 3].values(); diff --git a/docs/web/docs/features/proposals/iterator-range.md b/docs/web/docs/features/proposals/iterator-range.md index bba294de8efb..b455f35a03cc 100644 --- a/docs/web/docs/features/proposals/iterator-range.md +++ b/docs/web/docs/features/proposals/iterator-range.md @@ -19,6 +19,9 @@ core-js/proposals/number-range core-js(-pure)/full/iterator/range ``` +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/iterator-range`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/iterator-range.d.ts) + ## Example ```js for (const i of Iterator.range(1, 10)) { diff --git a/docs/web/docs/features/proposals/iterator-sequencing.md b/docs/web/docs/features/proposals/iterator-sequencing.md index 5f7e8a72d180..2c49e7bc807b 100644 --- a/docs/web/docs/features/proposals/iterator-sequencing.md +++ b/docs/web/docs/features/proposals/iterator-sequencing.md @@ -18,6 +18,9 @@ core-js/proposals/iterator-sequencing core-js(-pure)/es|stable|actual|full/iterator/concat ``` +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/iterator-sequencing`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/iterator-sequencing.d.ts) + ## Example ```js Iterator.concat([0, 1].values(), [2, 3], function * () { diff --git a/docs/web/docs/features/proposals/joint-iteration.md b/docs/web/docs/features/proposals/joint-iteration.md index 124189a6d913..a4e82799d685 100644 --- a/docs/web/docs/features/proposals/joint-iteration.md +++ b/docs/web/docs/features/proposals/joint-iteration.md @@ -32,6 +32,9 @@ core-js(-pure)/actual|full/iterator/zip core-js(-pure)/actual|full/iterator/zip-keyed ``` +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/iterator-joint`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/iterator-joint.d.ts) + ## Example ```js Iterator.zip([ diff --git a/docs/web/docs/features/proposals/json-parse-source-text-access.md b/docs/web/docs/features/proposals/json-parse-source-text-access.md index d5ca28ad48fd..9bac10544a1f 100644 --- a/docs/web/docs/features/proposals/json-parse-source-text-access.md +++ b/docs/web/docs/features/proposals/json-parse-source-text-access.md @@ -26,6 +26,9 @@ core-js(-pure)/es|stable|actual|full/json/raw-json core-js(-pure)/es|stable|actual|full/json/stringify ``` +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/json-parse-with-source`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/json-parse-with-source.d.ts) + ## Examples ```js function digitsToBigInt(key, val, { source }) { diff --git a/docs/web/docs/features/proposals/map-upsert.md b/docs/web/docs/features/proposals/map-upsert.md index 1846ab8f1219..2c954b7396ad 100644 --- a/docs/web/docs/features/proposals/map-upsert.md +++ b/docs/web/docs/features/proposals/map-upsert.md @@ -27,6 +27,9 @@ core-js(-pure)/es|stable|actual|full/weak-map/get-or-insert core-js(-pure)/es|stable|actual|full/weak-map/get-or-insert-computed ``` +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/map-upsert`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/map-upsert.d.ts) + ## Examples ```js const map = new Map([['a', 1]]); diff --git a/docs/web/docs/features/proposals/math-sumprecise.md b/docs/web/docs/features/proposals/math-sumprecise.md index 76229801edbd..6417592a389a 100644 --- a/docs/web/docs/features/proposals/math-sumprecise.md +++ b/docs/web/docs/features/proposals/math-sumprecise.md @@ -13,3 +13,6 @@ namespace Math { ```plaintext core-js/proposals/math-sum ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/math-sum`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/math-sum.d.ts) diff --git a/docs/web/docs/features/proposals/number-prototype-clamp.md b/docs/web/docs/features/proposals/number-prototype-clamp.md index 347106ad29d5..c07a26be77fa 100644 --- a/docs/web/docs/features/proposals/number-prototype-clamp.md +++ b/docs/web/docs/features/proposals/number-prototype-clamp.md @@ -18,6 +18,9 @@ core-js/proposals/math-clamp-v2 core-js(-pure)/full/number/clamp ``` +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/number-clamp`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/number-clamp.d.ts) + ## Example ```js 5.0.clamp(0, 10); // => 5 diff --git a/docs/web/docs/features/proposals/object-fromentries.md b/docs/web/docs/features/proposals/object-fromentries.md index 4d31ca16a316..ed1979bd53de 100644 --- a/docs/web/docs/features/proposals/object-fromentries.md +++ b/docs/web/docs/features/proposals/object-fromentries.md @@ -13,3 +13,6 @@ class Object { ```plaintext core-js/proposals/object-from-entries ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/object-from-entries`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/object-from-entries.d.ts) diff --git a/docs/web/docs/features/proposals/object-getownpropertydescriptors.md b/docs/web/docs/features/proposals/object-getownpropertydescriptors.md index a524b2930af5..567d306163d3 100644 --- a/docs/web/docs/features/proposals/object-getownpropertydescriptors.md +++ b/docs/web/docs/features/proposals/object-getownpropertydescriptors.md @@ -13,3 +13,7 @@ class Object { ```plaintext core-js/proposals/object-getownpropertydescriptors ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/object-get-own-property-descriptors`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/object-get-own-property-descriptors.d.ts) + diff --git a/docs/web/docs/features/proposals/object-values-entries.md b/docs/web/docs/features/proposals/object-values-entries.md index b04ee9ed38f1..4202662c3042 100644 --- a/docs/web/docs/features/proposals/object-values-entries.md +++ b/docs/web/docs/features/proposals/object-values-entries.md @@ -14,3 +14,6 @@ class Object { ```plaintext core-js/proposals/object-values-entries ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/object-values-entries`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/object-values-entries.d.ts) diff --git a/docs/web/docs/features/proposals/of-and-from-methods-on-collections.md b/docs/web/docs/features/proposals/of-and-from-methods-on-collections.md index 43b0ab86dc59..becf164161a0 100644 --- a/docs/web/docs/features/proposals/of-and-from-methods-on-collections.md +++ b/docs/web/docs/features/proposals/of-and-from-methods-on-collections.md @@ -41,6 +41,10 @@ core-js(-pure)/full/weak-map/from core-js(-pure)/full/weak-map/of ``` +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/collection-of-from`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/collection-of-from.d.ts) + + ## Examples ```js Set.of(1, 2, 3, 2, 1); // => Set {1, 2, 3} diff --git a/docs/web/docs/features/proposals/promise-allsettled.md b/docs/web/docs/features/proposals/promise-allsettled.md index 9df12f71a6a6..ece3a0a8d6c0 100644 --- a/docs/web/docs/features/proposals/promise-allsettled.md +++ b/docs/web/docs/features/proposals/promise-allsettled.md @@ -13,3 +13,6 @@ class Promise { ```plaintext core-js/proposals/promise-all-settled ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/promise-all-settled`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/promise-all-settled.d.ts) diff --git a/docs/web/docs/features/proposals/promise-any.md b/docs/web/docs/features/proposals/promise-any.md index 57cbd43fdd96..dd6f813e6c19 100644 --- a/docs/web/docs/features/proposals/promise-any.md +++ b/docs/web/docs/features/proposals/promise-any.md @@ -19,3 +19,6 @@ class Promise { ```plaintext core-js/proposals/promise-any ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/promise-any`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/promise-any.d.ts) diff --git a/docs/web/docs/features/proposals/promise-prototype-finally.md b/docs/web/docs/features/proposals/promise-prototype-finally.md index 907e8b2ce9cb..4b1c0e1a63d7 100644 --- a/docs/web/docs/features/proposals/promise-prototype-finally.md +++ b/docs/web/docs/features/proposals/promise-prototype-finally.md @@ -13,3 +13,6 @@ class Promise { ```plaintext core-js/proposals/promise-finally ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/promise-finally`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/promise-finally.d.ts) diff --git a/docs/web/docs/features/proposals/promise-try.md b/docs/web/docs/features/proposals/promise-try.md index 4847a9db12ba..30c21129f538 100644 --- a/docs/web/docs/features/proposals/promise-try.md +++ b/docs/web/docs/features/proposals/promise-try.md @@ -13,3 +13,6 @@ class Promise { ```plaintext core-js/proposals/promise-try ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/promise-try`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/promise-try.d.ts) diff --git a/docs/web/docs/features/proposals/promise-withresolvers.md b/docs/web/docs/features/proposals/promise-withresolvers.md index 309fad0b38a8..9b0b00364149 100644 --- a/docs/web/docs/features/proposals/promise-withresolvers.md +++ b/docs/web/docs/features/proposals/promise-withresolvers.md @@ -13,3 +13,6 @@ class Promise { ```plaintext core-js/proposals/promise-with-resolvers ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/promise-with-resolvers`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/promise-with-resolvers.d.ts) diff --git a/docs/web/docs/features/proposals/regexp-dotall-flag.md b/docs/web/docs/features/proposals/regexp-dotall-flag.md index 1e7ef92d9e83..d575f5e4784b 100644 --- a/docs/web/docs/features/proposals/regexp-dotall-flag.md +++ b/docs/web/docs/features/proposals/regexp-dotall-flag.md @@ -17,3 +17,6 @@ class RegExp { ```plaintext core-js/proposals/regexp-dotall-flag ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/regexp-dotall-flag`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/regexp-dotall-flag.d.ts) diff --git a/docs/web/docs/features/proposals/regexp-escaping.md b/docs/web/docs/features/proposals/regexp-escaping.md index 3a1b3f8f7e46..57f622e7595c 100644 --- a/docs/web/docs/features/proposals/regexp-escaping.md +++ b/docs/web/docs/features/proposals/regexp-escaping.md @@ -13,3 +13,6 @@ class RegExp { ```plaintext core-js/proposals/regexp-escaping ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/regexp-escaping`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/regexp-escaping.d.ts) diff --git a/docs/web/docs/features/proposals/regexp-named-capture-groups.md b/docs/web/docs/features/proposals/regexp-named-capture-groups.md index 857f127c29ca..58bc1b1694a4 100644 --- a/docs/web/docs/features/proposals/regexp-named-capture-groups.md +++ b/docs/web/docs/features/proposals/regexp-named-capture-groups.md @@ -16,3 +16,6 @@ class RegExp { ```plaintext core-js/proposals/regexp-named-groups ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/regexp-named-groups`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/regexp-named-groups.d.ts) diff --git a/docs/web/docs/features/proposals/relative-indexing-method.md b/docs/web/docs/features/proposals/relative-indexing-method.md index 36d0adf62600..ec1e345c3d79 100644 --- a/docs/web/docs/features/proposals/relative-indexing-method.md +++ b/docs/web/docs/features/proposals/relative-indexing-method.md @@ -21,3 +21,6 @@ class %TypedArray% { ```plaintext core-js/proposals/relative-indexing-method ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/relative-indexing-method`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/relative-indexing-method.d.ts) diff --git a/docs/web/docs/features/proposals/set-methods.md b/docs/web/docs/features/proposals/set-methods.md index 90c28855a0b3..1b7d967b7166 100644 --- a/docs/web/docs/features/proposals/set-methods.md +++ b/docs/web/docs/features/proposals/set-methods.md @@ -19,3 +19,6 @@ class Set { ```plaintext core-js/proposals/set-methods ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/set-methods`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/set-methods.d.ts) diff --git a/docs/web/docs/features/proposals/string-cooked.md b/docs/web/docs/features/proposals/string-cooked.md index b95a484e5a7b..3de4439d95ad 100644 --- a/docs/web/docs/features/proposals/string-cooked.md +++ b/docs/web/docs/features/proposals/string-cooked.md @@ -18,6 +18,9 @@ core-js/proposals/string-cooked core-js(-pure)/full/string/cooked ``` +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/string-cooked`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/string-cooked.d.ts) + ## Example ```js function safePath(strings, ...subs) { diff --git a/docs/web/docs/features/proposals/string-dedent.md b/docs/web/docs/features/proposals/string-dedent.md index 463ddb7a4546..d670db747a2e 100644 --- a/docs/web/docs/features/proposals/string-dedent.md +++ b/docs/web/docs/features/proposals/string-dedent.md @@ -18,6 +18,9 @@ core-js/proposals/string-dedent core-js(-pure)/full/string/dedent ``` +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/string-dedent`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/string-dedent.d.ts) + ## Example ```js const message = 42; diff --git a/docs/web/docs/features/proposals/string-matchall.md b/docs/web/docs/features/proposals/string-matchall.md index d1dd99b0f308..3cb12e9b6927 100644 --- a/docs/web/docs/features/proposals/string-matchall.md +++ b/docs/web/docs/features/proposals/string-matchall.md @@ -12,3 +12,6 @@ class String { ```plaintext core-js/proposals/string-match-all ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/string-match-all`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/string-match-all.d.ts) diff --git a/docs/web/docs/features/proposals/string-padding.md b/docs/web/docs/features/proposals/string-padding.md index b53c46ac1665..b09316b8337a 100644 --- a/docs/web/docs/features/proposals/string-padding.md +++ b/docs/web/docs/features/proposals/string-padding.md @@ -15,3 +15,6 @@ class String { ```plaintext core-js/proposals/string-padding ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/string-padding`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/string-padding.d.ts) diff --git a/docs/web/docs/features/proposals/string-replaceall.md b/docs/web/docs/features/proposals/string-replaceall.md index 3e7b462cf443..c0cf935effd8 100644 --- a/docs/web/docs/features/proposals/string-replaceall.md +++ b/docs/web/docs/features/proposals/string-replaceall.md @@ -13,3 +13,6 @@ class String { ```plaintext core-js/proposals/string-replace-all ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/string-replace-all`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/string-replace-all.d.ts) diff --git a/docs/web/docs/features/proposals/string-trimstart-trimend.md b/docs/web/docs/features/proposals/string-trimstart-trimend.md index 397981e49f72..a0368f834164 100644 --- a/docs/web/docs/features/proposals/string-trimstart-trimend.md +++ b/docs/web/docs/features/proposals/string-trimstart-trimend.md @@ -16,3 +16,6 @@ class String { ```plaintext core-js/proposals/string-left-right-trim ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/string-left-right-trim`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/string-left-right-trim.d.ts) diff --git a/docs/web/docs/features/proposals/symbol-asynciterator.md b/docs/web/docs/features/proposals/symbol-asynciterator.md index e90b3753652b..2b748e3c3257 100644 --- a/docs/web/docs/features/proposals/symbol-asynciterator.md +++ b/docs/web/docs/features/proposals/symbol-asynciterator.md @@ -13,3 +13,6 @@ class Symbol { ```plaintext core-js/proposals/async-iteration ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/async-iteration`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/async-iteration.d.ts) diff --git a/docs/web/docs/features/proposals/symbol-custommatcher-for-extractors.md b/docs/web/docs/features/proposals/symbol-custommatcher-for-extractors.md index 31973e3a2800..11d75a41ad74 100644 --- a/docs/web/docs/features/proposals/symbol-custommatcher-for-extractors.md +++ b/docs/web/docs/features/proposals/symbol-custommatcher-for-extractors.md @@ -17,3 +17,6 @@ class Symbol { core-js/proposals/pattern-extractors core-js(-pure)/full/symbol/custom-matcher ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/pattern-matching`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/pattern-matching.d.ts) diff --git a/docs/web/docs/features/proposals/symbol-custommatcher-pattern-matching.md b/docs/web/docs/features/proposals/symbol-custommatcher-pattern-matching.md index e8e8b2485aa4..01763136fa76 100644 --- a/docs/web/docs/features/proposals/symbol-custommatcher-pattern-matching.md +++ b/docs/web/docs/features/proposals/symbol-custommatcher-pattern-matching.md @@ -17,3 +17,6 @@ class Symbol { core-js/proposals/pattern-matching-v2 core-js(-pure)/full/symbol/custom-matcher ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/pattern-matching`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/pattern-matching.d.ts) diff --git a/docs/web/docs/features/proposals/symbol-metadata.md b/docs/web/docs/features/proposals/symbol-metadata.md index 793364d44679..d789e092259b 100644 --- a/docs/web/docs/features/proposals/symbol-metadata.md +++ b/docs/web/docs/features/proposals/symbol-metadata.md @@ -20,3 +20,6 @@ class Function { core-js/proposals/decorator-metadata core-js(-pure)/actual|full/symbol/metadata ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/decorator-metadata`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/decorator-metadata.d.ts) diff --git a/docs/web/docs/features/proposals/symbol-predicates.md b/docs/web/docs/features/proposals/symbol-predicates.md index 2696a9685250..1cdcdc4ab70e 100644 --- a/docs/web/docs/features/proposals/symbol-predicates.md +++ b/docs/web/docs/features/proposals/symbol-predicates.md @@ -20,6 +20,9 @@ core-js(-pure)/full/symbol/is-registered-symbol core-js(-pure)/full/symbol/is-well-known-symbol ``` +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/symbol-predicates`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/symbol-predicates.d.ts) + ## Example ```js Symbol.isRegisteredSymbol(Symbol.for('key')); // => true diff --git a/docs/web/docs/features/proposals/symbol-prototype-description.md b/docs/web/docs/features/proposals/symbol-prototype-description.md index 5ac8d0abbc31..995118042806 100644 --- a/docs/web/docs/features/proposals/symbol-prototype-description.md +++ b/docs/web/docs/features/proposals/symbol-prototype-description.md @@ -13,3 +13,6 @@ class Symbol { ```plaintext core-js/proposals/symbol-description ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/symbol-description`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/symbol-description.d.ts) diff --git a/docs/web/docs/features/proposals/uint8array-base64-hex.md b/docs/web/docs/features/proposals/uint8array-base64-hex.md index e4ca8b7515b2..dc1cea85b6f5 100644 --- a/docs/web/docs/features/proposals/uint8array-base64-hex.md +++ b/docs/web/docs/features/proposals/uint8array-base64-hex.md @@ -18,3 +18,6 @@ class Uint8Array { ```plaintext core-js/proposals/array-buffer-base64 ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/array-buffer-base64`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/array-buffer-base64.d.ts) diff --git a/docs/web/docs/features/proposals/well-formed-unicode-strings.md b/docs/web/docs/features/proposals/well-formed-unicode-strings.md index a9a11d6838dd..5215cfb07cc6 100644 --- a/docs/web/docs/features/proposals/well-formed-unicode-strings.md +++ b/docs/web/docs/features/proposals/well-formed-unicode-strings.md @@ -14,3 +14,6 @@ class String { ```plaintext core-js/proposals/well-formed-unicode-strings ``` + +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/proposals/well-formed-unicode-strings`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/proposals/well-formed-unicode-strings.d.ts) diff --git a/docs/web/docs/features/web-standards/base64-utility-methods.md b/docs/web/docs/features/web-standards/base64-utility-methods.md index fe007e38c5ed..acbc97e2541f 100644 --- a/docs/web/docs/features/web-standards/base64-utility-methods.md +++ b/docs/web/docs/features/web-standards/base64-utility-methods.md @@ -17,6 +17,9 @@ core-js(-pure)/stable|actual|full/atob core-js(-pure)/stable|actual|full/btoa ``` +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/web/atob-btoa`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/web/atob-btoa.d.ts) + ## Examples ```js btoa('hi, core-js'); // => 'aGksIGNvcmUtanM=' diff --git a/docs/web/docs/features/web-standards/iterable-dom-collections.md b/docs/web/docs/features/web-standards/iterable-dom-collections.md index 2fb3d000e10e..96773688a47a 100644 --- a/docs/web/docs/features/web-standards/iterable-dom-collections.md +++ b/docs/web/docs/features/web-standards/iterable-dom-collections.md @@ -58,6 +58,9 @@ core-js/stable|actual|full/dom-collections/values core-js/stable|actual|full/dom-collections/for-each ``` +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/web/iterable-dom-collections`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/web/iterable-dom-collections.d.ts) + ## Examples ```js for (let { id } of document.querySelectorAll('*')) { diff --git a/docs/web/docs/features/web-standards/queuemicrotask.md b/docs/web/docs/features/web-standards/queuemicrotask.md index 55030826d989..4a0d4a7e8910 100644 --- a/docs/web/docs/features/web-standards/queuemicrotask.md +++ b/docs/web/docs/features/web-standards/queuemicrotask.md @@ -14,6 +14,9 @@ function queueMicrotask(fn: Function): void; core-js(-pure)/stable|actual|full/queue-microtask ``` +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/web/queue-microtask`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/web/queue-microtask.d.ts) + ## Example ```js queueMicrotask(() => console.log('called as microtask')); diff --git a/docs/web/docs/features/web-standards/setimmediate.md b/docs/web/docs/features/web-standards/setimmediate.md index 705c6635ddad..24e9e6fba7b1 100644 --- a/docs/web/docs/features/web-standards/setimmediate.md +++ b/docs/web/docs/features/web-standards/setimmediate.md @@ -15,6 +15,9 @@ core-js(-pure)/stable|actual|full/set-immediate core-js(-pure)/stable|actual|full/clear-immediate ``` +## [TypeScript type definitions]({docs-version}/docs/typescript-type-definitions) +[`@core-js/types/web/efficient-script-yielding`](https://github.com/zloirock/core-js/blob/v4-types/packages/core-js-types/src/base/web/efficient-script-yielding.d.ts) + ## Examples ```js setImmediate((arg1, arg2) => { diff --git a/docs/web/docs/features/web-standards/structured-clone.md b/docs/web/docs/features/web-standards/structured-clone.md index c57fd10ca378..2e70000f73a5 100644 --- a/docs/web/docs/features/web-standards/structured-clone.md +++ b/docs/web/docs/features/web-standards/structured-clone.md @@ -14,6 +14,9 @@ function structuredClone(value: Serializable, { transfer?: Sequence true diff --git a/docs/web/docs/menu.json b/docs/web/docs/menu.json index 0e308cfdbc45..898b36d6f869 100644 --- a/docs/web/docs/menu.json +++ b/docs/web/docs/menu.json @@ -7,6 +7,10 @@ "title": "Supported engines and compatibility data", "url": "{docs-version}/docs/engines" }, + { + "title": "TypeScript type definitions", + "url": "{docs-version}/docs/typescript-type-definitions" + }, { "title": "Features", "children": [ diff --git a/docs/web/docs/typescript-type-definitions.md b/docs/web/docs/typescript-type-definitions.md new file mode 100644 index 000000000000..74ec6ca385c1 --- /dev/null +++ b/docs/web/docs/typescript-type-definitions.md @@ -0,0 +1,130 @@ +# TypeScript Type Definitions + +This package contains types for the global and pure versions of `core-js`. +Although `core-js` is a JavaScript standard library polyfill, the built-in TypeScript types are often not sufficient. +Additional types are needed for: +- features that are already in JavaScript but not yet in TypeScript’s standard types; +- proposals, including those already implemented in JavaScript engines; +- explicit imports of features from the pure version. + +It is shipped as a separate package because we cannot guarantee stable behavior with future TypeScript releases, including minor ones. + +## Installation +```sh +npm install --save @core-js/types@4.0.0-alpha.0 +``` + +## Usage +You must include at least the ES6 types in your `tsconfig.json` because our types are built on top of the ES6 type definitions +and `DOM` lib for the global version if you use something related (see [DOM types](#dom-types) section): +```json +{ + "compilerOptions": { + "lib": [ + "es2025", + "dom" + ], + "types": [ + "@core-js/types" + ] + } +} +``` + +You can also import the types directly into your files instead of specifying `core-js` types in your `tsconfig.json`: +```ts +import '@core-js/types'; +``` + +`@core-js/types` includes all types and entry points for the global version, but it is recommended to select only the subset you actually use. + +### Usage of subsets +There are four main subsets: +- `@core-js/types/actual` - types for all actual features, including stable ECMAScript, web standards and Stage 3 ECMAScript proposals; +- `@core-js/types/es` - types for stable ECMAScript features only; +- `@core-js/types/stable` - types for stable ECMAScript and web standards features; +- `@core-js/types/full` - types for all features, including proposals. + +You can import them the same way as the main package. For example, to use only the stable subset, add this to your `tsconfig.json`: +```json +{ + "compilerOptions": { + "types": [ + "@core-js/types/stable" + ] + } +} +``` +or import it directly in your files: +```ts +import '@core-js/types/stable'; +``` + +### Usage of specific features +If you need types only for specific features, you can import them like this: +```json +{ + "compilerOptions": { + "types": [ + "@core-js/types/proposals/joint-iteration", + "@core-js/types/web/structured-clone" + ] + } +} +``` +or import them directly in your files: +```ts +import '@core-js/types/proposals/joint-iteration'; +import '@core-js/types/web/structured-clone'; +``` +You can find types for specific features on the corresponding pages in the [documentation]({docs-version}/docs/). + +## Types for the pure version +### Base usage +Add this to your `tsconfig.json`, keeping in mind that ES types (at least ES6) are required: +```json +{ + "compilerOptions": { + "lib": [ + "es2025" + ], + "types": [ + "@core-js/types/pure" + ] + } +} +``` +Then, when you import from the pure entry points, the corresponding types are picked up automatically: +```ts +import $findLast from '@core-js/pure/full/array/find-last'; + +$findLast([1, 3, 4, 2], v => v > 2); // => 4 +``` + +### Namespace usage in the pure version +If you need to use multiple methods from the same namespace, you can add `@core-js/types/pure` to `tsconfig.json` and import the entire namespace: +```ts +import $array from '@core-js/pure/full/array'; + +$array.findLast([1, 3, 4, 2], v => v > 2); +$array.flatMap([1, 2, 3], x => [x, x * 2]); +``` +(note that this is not recommended since tree shaking does not properly work in this case) + +## DOM types +Some of the global types for web standards work correctly only with the DOM lib. +You need to add DOM types to the `lib` section of your `tsconfig.json` in addition to `@core-js/types`. For example: +```json +{ + "compilerOptions": { + "types": [ + "@core-js/types" + ], + "lib": [ + "es2025", + "dom" + ] + } +} +``` +In the pure version, you can use these types without adding the DOM lib. diff --git a/package-lock.json b/package-lock.json index a5d00acb5286..199efc7fe28d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1006,6 +1006,10 @@ "resolved": "packages/core-js-pure", "link": true }, + "node_modules/@core-js/types": { + "resolved": "packages/core-js-types", + "link": true + }, "node_modules/@emnapi/core": { "version": "1.8.1", "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.8.1.tgz", @@ -2300,6 +2304,15 @@ "type": "opencollective", "url": "https://opencollective.com/core-js" } + }, + "packages/core-js-types": { + "name": "@core-js/types", + "version": "4.0.0-alpha.0", + "license": "SEE LICENSE IN LICENSE.md", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/core-js" + } } } } diff --git a/package.json b/package.json index 99e5e9aa6650..f5f26ad6eb26 100644 --- a/package.json +++ b/package.json @@ -18,8 +18,9 @@ "zxi": "zx scripts/zxi.mjs", "prepare": "npm run zxi scripts/prepare.mjs", "prepare-monorepo": "node scripts/prepare-monorepo.mjs", - "build-entries": "npm run zxi time scripts/build-entries/index.mjs", + "build-entries": "npm run zxi time scripts/build-entries-and-types/build-entries.mjs", "build-compat": "npm run zxi scripts/build-compat/index.mjs", + "build-types": "npm run zxi time scripts/build-entries-and-types/build-types.mjs", "build-website": "npm run zxi time website/index.mjs", "build-website-local": "npm run zxi time website/build-local.mjs", "bundle": "run-s bundle-package bundle-tests", @@ -39,9 +40,9 @@ "compat-rhino": "npm run zxi tests/compat/rhino-adapter.mjs", "debug-get-dependencies": "npm run zxi time tests/debug-get-dependencies/debug-get-dependencies.mjs", "lint": "run-s prepare lint-raw", - "lint-raw": "run-s test-eslint test-type-definitions bundle-package test-publint", + "lint-raw": "run-s build-types test-eslint bundle-package test-publint", "test": "run-s prepare test-raw", - "test-raw": "run-s lint-raw bundle-tests test-unit test-promises test-entries test-compat-data test-compat-tools test-builder test-babel-plugin check", + "test-raw": "run-s lint-raw test-type-definitions-smoke types-coverage bundle-tests test-unit test-promises test-entries test-compat-data test-compat-tools test-builder test-babel-plugin check", "test-eslint": "npm run zxi time tests/eslint/runner.mjs", "test-publint": "npm run zxi time tests/publint/runner.mjs", "test-unit": "run-s test-unit-karma test-unit-node test-unit-bun", @@ -54,8 +55,12 @@ "test-builder": "npm run zxi tests/builder/builder.mjs", "test-compat-data": "npm run zxi tests/compat-data/index.mjs", "test-compat-tools": "npm run zxi tests/compat-tools/index.mjs", - "test-type-definitions": "npm run zxi time cd tests/type-definitions/runner.mjs", + "test-templates": "npm run zxi tests/templates/templates.mjs", + "test-type-definitions-all": "TYPE_DEFINITIONS_TESTS=ALL npm run zxi time cd tests/type-definitions/runner.mjs", + "test-type-definitions-ci": "TYPE_DEFINITIONS_TESTS=CI npm run zxi time cd tests/type-definitions/runner.mjs", + "test-type-definitions-smoke": "TYPE_DEFINITIONS_TESTS=SMOKE npm run zxi time cd tests/type-definitions/runner.mjs", "test262": "npm run zxi time cd tests/test262/runner.mjs", + "types-coverage": "npm run zxi tests/type-definitions/coverage.mjs", "refresh": "UPDATE_DEPENDENCIES=1 npm run prepare-monorepo && npm run test-raw", "refresh-safe": "npm run prepare-monorepo && npm run test-raw", "downloads": "npm run zxi scripts/downloads-by-versions.mjs", diff --git a/packages/core-js-builder/index.d.ts b/packages/core-js-builder/index.d.ts index e70930b4ebdf..d7764b113f79 100644 --- a/packages/core-js-builder/index.d.ts +++ b/packages/core-js-builder/index.d.ts @@ -30,4 +30,4 @@ type Options = Pick & { declare function builder(options?: Options): Promise; -export = builder; +export default builder; diff --git a/packages/core-js-compat/package.json b/packages/core-js-compat/package.json index 3eb5442efbd9..562871c00222 100644 --- a/packages/core-js-compat/package.json +++ b/packages/core-js-compat/package.json @@ -28,6 +28,56 @@ "sideEffects": false, "main": "index.js", "types": "index.d.ts", + "exports": { + ".": { + "types": "./index.d.ts", + "default": "./index.js" + }, + "./index.js": { + "types": "./index.d.ts", + "default": "./index.js" + }, + "./built-in-definitions": "./built-in-definitions.json", + "./built-in-definitions.json": "./built-in-definitions.json", + "./compat": { + "types": "./compat.d.ts", + "default": "./compat.js" + }, + "./compat.js": { + "types": "./compat.d.ts", + "default": "./compat.js" + }, + "./data": "./data.json", + "./data.json": "./data.json", + "./entries": "./entries.json", + "./entries.json": "./entries.json", + "./entries-by-versions": "./entries-by-versions.json", + "./entries-by-versions.json": "./entries-by-versions.json", + "./external": "./external.json", + "./external.json": "./external.json", + "./get-entries-list-for-target-version": { + "types": "./get-entries-list-for-target-version.d.ts", + "default": "./get-entries-list-for-target-version.js" + }, + "./get-entries-list-for-target-version.js": { + "types": "./get-entries-list-for-target-version.d.ts", + "default": "./get-entries-list-for-target-version.js" + }, + "./get-modules-list-for-target-version": { + "types": "./get-modules-list-for-target-version.d.ts", + "default": "./get-modules-list-for-target-version.js" + }, + "./get-modules-list-for-target-version.js": { + "types": "./get-modules-list-for-target-version.d.ts", + "default": "./get-modules-list-for-target-version.js" + }, + "./modules": "./modules.json", + "./modules.json": "./modules.json", + "./modules-by-versions": "./modules-by-versions.json", + "./modules-by-versions.json": "./modules-by-versions.json", + "./targets-parser": "./targets-parser.js", + "./targets-parser.js": "./targets-parser.js" + }, "dependencies": { "browserslist": "^4.28.1" } diff --git a/packages/core-js-types/.npmignore b/packages/core-js-types/.npmignore new file mode 100644 index 000000000000..cfa39b037d33 --- /dev/null +++ b/packages/core-js-types/.npmignore @@ -0,0 +1,5 @@ +node_modules/ +package.tpl.json +/src/ +*.log +.* diff --git a/packages/core-js-types/README.md b/packages/core-js-types/README.md new file mode 100644 index 000000000000..1bafb8a83e52 --- /dev/null +++ b/packages/core-js-types/README.md @@ -0,0 +1,130 @@ +![logo](https://user-images.githubusercontent.com/2213682/146607186-8e13ddef-26a4-4ebf-befd-5aac9d77c090.png) + +This package contains types for the global and pure versions of `core-js`. +Although `core-js` is a JavaScript standard library polyfill, the built-in TypeScript types are often not sufficient. +Additional types are needed for: +- features that are already in JavaScript but not yet in TypeScript’s standard types; +- proposals, including those already implemented in JavaScript engines; +- explicit imports of features from the pure version. + +It is shipped as a separate package because we cannot guarantee stable behavior with future TypeScript releases, including minor ones. + +# Installation +```bash +npm install --save @core-js/types@4.0.0-alpha.0 +``` + +# Usage +You must include at least the ES6 types in your `tsconfig.json` because our types are built on top of the ES6 type definitions +and `DOM` lib for the global version if you use something related (see [DOM types](#dom-types) section): +```json +{ + "compilerOptions": { + "lib": [ + "es2025", + "dom" + ], + "types": [ + "@core-js/types" + ] + } +} +``` + +You can also import the types directly into your files instead of specifying `core-js` types in your `tsconfig.json`: +```ts +import '@core-js/types'; +``` + +`@core-js/types` includes all types and entry points for the global version, but it is recommended to select only the subset you actually use. + +## Usage of subsets +There are four main subsets: +- `@core-js/types/actual` - types for all actual features, including stable ECMAScript, web standards and Stage 3 ECMAScript proposals; +- `@core-js/types/es` - types for stable ECMAScript features only; +- `@core-js/types/stable` - types for stable ECMAScript and web standards features; +- `@core-js/types/full` - types for all features, including proposals. + +You can import them the same way as the main package. For example, to use only the stable subset, add this to your `tsconfig.json`: +```json +{ + "compilerOptions": { + "types": [ + "@core-js/types/stable" + ] + } +} +``` +or import it directly in your files: +```ts +import '@core-js/types/stable'; +``` + +## Usage of specific features +If you need types only for specific features, you can import them like this: +```json +{ + "compilerOptions": { + "types": [ + "@core-js/types/proposals/joint-iteration", + "@core-js/types/web/structured-clone" + ] + } +} +``` +or import them directly in your files: +```ts +import '@core-js/types/proposals/joint-iteration'; +import '@core-js/types/web/structured-clone'; +``` +You can find types for specific features on the corresponding pages in the [documentation](https://core-js.io/v4/docs/). + +# Types for the pure version +## Base usage +Add this to your `tsconfig.json`, keeping in mind that ES types (at least ES6) are required: +```json +{ + "compilerOptions": { + "lib": [ + "es2025" + ], + "types": [ + "@core-js/types/pure" + ] + } +} +``` +Then, when you import from the pure entry points, the corresponding types are picked up automatically: +```ts +import $findLast from '@core-js/pure/full/array/find-last'; + +$findLast([1, 3, 4, 2], v => v > 2); // => 4 +``` + +## Namespace usage in the pure version +If you need to use multiple methods from the same namespace, you can add `@core-js/types/pure` to `tsconfig.json` and import the entire namespace: +```ts +import $array from '@core-js/pure/full/array'; + +$array.findLast([1, 3, 4, 2], v => v > 2); +$array.flatMap([1, 2, 3], x => [x, x * 2]); +``` +(note that this is not recommended since tree shaking does not properly work in this case) + +# DOM types +Some of the global types for web standards work correctly only with the DOM lib. +You need to add DOM types to the `lib` section of your `tsconfig.json` in addition to `@core-js/types`. For example: +```json +{ + "compilerOptions": { + "types": [ + "@core-js/types" + ], + "lib": [ + "es2025", + "dom" + ] + } +} +``` +In the pure version, you can use these types without adding the DOM lib. diff --git a/packages/core-js-types/package.tpl.json b/packages/core-js-types/package.tpl.json new file mode 100644 index 000000000000..8022d5324de9 --- /dev/null +++ b/packages/core-js-types/package.tpl.json @@ -0,0 +1,29 @@ +{ + "name": "@core-js/types", + "version": "4.0.0-alpha.0", + "publishConfig": { + "access": "public" + }, + "type": "commonjs", + "description": "TypeScript types for core-js", + "repository": { + "type": "git", + "url": "git+https://github.com/zloirock/core-js.git", + "directory": "packages/core-js-types" + }, + "homepage": "https://core-js.io", + "bugs": { + "url": "https://github.com/zloirock/core-js/issues" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/core-js" + }, + "license": "SEE LICENSE IN LICENSE.md", + "author": { + "name": "Denis Pushkarev", + "email": "zloirock@zloirock.ru", + "url": "http://zloirock.ru" + }, + "sideEffects": false +} diff --git a/packages/core-js-types/src/base/annex-b/object-proto.d.ts b/packages/core-js-types/src/base/annex-b/object-proto.d.ts new file mode 100644 index 000000000000..d1142b9d2386 --- /dev/null +++ b/packages/core-js-types/src/base/annex-b/object-proto.d.ts @@ -0,0 +1,7 @@ +interface Object { + /** + * Accessor to [[Prototype]]. + * This is non-standard and deprecated; prefer `{ Object, Reflect }.{ getPrototypeOf, setPrototypeOf }` + */ + __proto__: object | null; +} diff --git a/packages/core-js-types/src/base/annex-b/object-prototype-accessor-methods.d.ts b/packages/core-js-types/src/base/annex-b/object-prototype-accessor-methods.d.ts new file mode 100644 index 000000000000..11a99fd62ff9 --- /dev/null +++ b/packages/core-js-types/src/base/annex-b/object-prototype-accessor-methods.d.ts @@ -0,0 +1,35 @@ +interface Object { + /** + * Defines a getter function for the specified property on this object. + * This method is non-standard and deprecated; prefer `Object.defineProperty`. + * @param prop - The name or symbol of the property. + * @param getter - A function that will be called whenever the property is read. + */ + __defineGetter__(prop: PropertyKey, getter: () => any): void; + + /** + * Defines a setter function for the specified property on this object. + * This method is non-standard and deprecated; prefer `Object.defineProperty`. + * @param prop - The name or symbol of the property. + * @param setter - A function that will be called whenever the property is assigned a value. + */ + __defineSetter__(prop: PropertyKey, setter: (val: any) => void): void; + + /** + * Returns the getter function associated with the specified property, + * or `undefined` if the property has no getter. + * This method is non-standard and deprecated. + * @param prop - The name or symbol of the property. + * @returns The getter function for the property, or `undefined`. + */ + __lookupGetter__(prop: PropertyKey): (() => any) | undefined; + + /** + * Returns the setter function associated with the specified property, + * or `undefined` if the property has no setter. + * This method is non-standard and deprecated. + * @param prop - The name or symbol of the property. + * @returns The setter function for the property, or `undefined`. + */ + __lookupSetter__(prop: PropertyKey): ((val: any) => void) | undefined; +} diff --git a/packages/core-js-types/src/base/configurator-custom.d.ts b/packages/core-js-types/src/base/configurator-custom.d.ts new file mode 100644 index 000000000000..661f01c707db --- /dev/null +++ b/packages/core-js-types/src/base/configurator-custom.d.ts @@ -0,0 +1,3 @@ +declare namespace CoreJS { + export function Configurator(options: Record): void; +} diff --git a/packages/core-js-types/src/base/core-js-modules/url.d.ts b/packages/core-js-types/src/base/core-js-modules/url.d.ts new file mode 100644 index 000000000000..646ac472ae9a --- /dev/null +++ b/packages/core-js-types/src/base/core-js-modules/url.d.ts @@ -0,0 +1,93 @@ +// TODO remove if URL conflict cannot be resolved + +declare module 'core-js/internals/web/url' { + interface URL { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + hash: string; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + host: string; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + hostname: string; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + href: string; + + toString(): string; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) */ + readonly origin: string; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + password: string; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + pathname: string; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + port: string; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + protocol: string; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + search: string; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) */ + readonly searchParams: URLSearchParams; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + username: string; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) */ + toJSON(): string; + } + + interface URLConstructor { + prototype: URL; + + new(url: string | URL, base?: string | URL): URL; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) */ + canParse(url: string | URL, base?: string | URL): boolean; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static) */ + createObjectURL(obj: any): string; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/parse_static) */ + parse(url: string | URL, base?: string | URL): URL | null; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static) */ + revokeObjectURL(url: string): void; + } + + var URL: URLConstructor; + + interface URLSearchParams { + readonly size: number; + append(name: string, value: string): void; + delete(name: string, value?: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string, value?: string): boolean; + set(name: string, value: string): void; + sort(): void; + forEach(callbackfn: (value: string, key: string, parent: URLSearchParams) => void, thisArg?: any): void; + [Symbol.iterator](): URLSearchParamsIterator<[string, string]>; + entries(): URLSearchParamsIterator<[string, string]>; + keys(): URLSearchParamsIterator; + values(): URLSearchParamsIterator; + } + + interface URLSearchParamsConstructor { + prototype: URLSearchParams; + new(init?: string[][] | Record | string | URLSearchParams): URLSearchParams; + } + + var URLSearchParams: URLSearchParamsConstructor; + + interface URLSearchParamsIterator extends IteratorObject { + [Symbol.iterator](): URLSearchParamsIterator; + } +} diff --git a/packages/core-js-types/src/base/core-js-types/async-iterator.d.ts b/packages/core-js-types/src/base/core-js-types/async-iterator.d.ts new file mode 100644 index 000000000000..cc35ba90c022 --- /dev/null +++ b/packages/core-js-types/src/base/core-js-types/async-iterator.d.ts @@ -0,0 +1,22 @@ +interface AsyncIteratorObject extends AsyncIterator { + [Symbol.asyncIterator](): AsyncIteratorObject; +} + +interface AsyncIterableIterator extends AsyncIterator { + [Symbol.asyncIterator](): AsyncIterableIterator; +} + +interface AsyncIterator { + // NOTE: 'next' is defined using a tuple to ensure we report the correct assignability errors in all places. + next(...[value]: [] | [TNext]): Promise>; + return?(value?: TReturn | PromiseLike): Promise>; + throw?(e?: any): Promise>; +} + +interface AsyncIteratorConstructor {} + +declare var AsyncIterator: AsyncIteratorConstructor; + +interface AsyncIterable { + [Symbol.asyncIterator](): AsyncIterator; +} diff --git a/packages/core-js-types/src/base/core-js-types/decorator-metadata-object.d.ts b/packages/core-js-types/src/base/core-js-types/decorator-metadata-object.d.ts new file mode 100644 index 000000000000..178fc4e739a0 --- /dev/null +++ b/packages/core-js-types/src/base/core-js-types/decorator-metadata-object.d.ts @@ -0,0 +1,5 @@ +declare namespace CoreJS { + export type CoreJSDecoratorMetadataObject = typeof globalThis extends { DecoratorMetadataObject: infer O } // from ts 5.2 + ? O + : Record & object; +} diff --git a/packages/core-js-types/src/base/core-js-types/flat-array.d.ts b/packages/core-js-types/src/base/core-js-types/flat-array.d.ts new file mode 100644 index 000000000000..3ddfd5bb2d43 --- /dev/null +++ b/packages/core-js-types/src/base/core-js-types/flat-array.d.ts @@ -0,0 +1,13 @@ +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/2a90a739c1c1e87e3c3d0c93e16f7e5baadf8035/src/lib/es2019.array.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +declare namespace CoreJS { + export type CoreJSFlatArray = typeof globalThis extends { FlatArray: infer O } // from ts 4.4 + ? O + : { + done: Arr; + recur: Arr extends ReadonlyArray ? CoreJSFlatArray + : Arr; + }[Depth extends -1 ? 'done' : 'recur']; +} diff --git a/packages/core-js-types/src/base/core-js-types/iterator-object.d.ts b/packages/core-js-types/src/base/core-js-types/iterator-object.d.ts new file mode 100644 index 000000000000..8356f1a668af --- /dev/null +++ b/packages/core-js-types/src/base/core-js-types/iterator-object.d.ts @@ -0,0 +1,3 @@ +interface IteratorObject extends Iterator { + [Symbol.iterator](): IteratorObject; +} diff --git a/packages/core-js-types/src/base/core-js-types/promise-settled-result.d.ts b/packages/core-js-types/src/base/core-js-types/promise-settled-result.d.ts new file mode 100644 index 000000000000..9fcfeb929a68 --- /dev/null +++ b/packages/core-js-types/src/base/core-js-types/promise-settled-result.d.ts @@ -0,0 +1,7 @@ +declare namespace CoreJS { + interface PromiseFulfilledResult { status: 'fulfilled'; value: T; } + + interface PromiseRejectedResult { status: 'rejected'; reason: unknown; } + + export type CoreJSPromiseSettledResult = PromiseFulfilledResult | PromiseRejectedResult; +} diff --git a/packages/core-js-types/src/base/proposals/accessible-object-hasownproperty.d.ts b/packages/core-js-types/src/base/proposals/accessible-object-hasownproperty.d.ts new file mode 100644 index 000000000000..734205128d83 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/accessible-object-hasownproperty.d.ts @@ -0,0 +1,14 @@ +// https://github.com/tc39/proposal-accessible-object-hasownproperty + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/069de743dbd17b47cc2fc58e1d16da5410911284/src/lib/es2022.object.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface ObjectConstructor { + /** + * Determines whether an object has a property with the specified name. + * @param o - An object. + * @param v - A property name. + */ + hasOwn(o: object, v: PropertyKey): boolean; +} diff --git a/packages/core-js-types/src/base/proposals/array-buffer-base64.d.ts b/packages/core-js-types/src/base/proposals/array-buffer-base64.d.ts new file mode 100644 index 000000000000..96c6bb99e99b --- /dev/null +++ b/packages/core-js-types/src/base/proposals/array-buffer-base64.d.ts @@ -0,0 +1,75 @@ +// https://github.com/tc39/proposal-arraybuffer-base64 + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/d3be7e171bf3149fe93c3ce5a85280f1eba3ef8d/src/lib/esnext.typedarrays.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +type CoreJSAlphabet = 'base64' | 'base64url'; + +type CoreJSLastChunkHandling = 'loose' | 'strict' | 'stop-before-partial'; + +interface CoreJSFromBase64Options { + alphabet?: CoreJSAlphabet; + lastChunkHandling?: CoreJSLastChunkHandling; +} + +interface CoreJSToBase64Options { + alphabet?: CoreJSAlphabet; + omitPadding?: boolean; +} + +interface CoreJSProcessMetadata { + read: number; + written: number; +} + +interface Uint8ArrayConstructor { + /** + * Creates a new `Uint8Array` from a base64-encoded string. + * @param string - The base64-encoded string. + * @param options - If provided, specifies the alphabet and handling of the last chunk. + * @returns A new `Uint8Array` instance. + * @throws SyntaxError If the input string contains characters outside the specified alphabet, or if the last + * chunk is inconsistent with the `lastChunkHandling` option. + */ + fromBase64(string: string, options?: CoreJSFromBase64Options): Uint8Array; + + /** + * Creates a new `Uint8Array` from a base16-encoded string. + * @param string - The base16-encoded string. + * @returns A new `Uint8Array` instance. + */ + fromHex(string: string): Uint8Array; +} + +interface Uint8Array { + /** + * Sets the `Uint8Array` from a base64-encoded string. + * @param string - The base64-encoded string. + * @param options - If provided, specifies the alphabet and handling of the last chunk. + * @returns An object containing the number of bytes read and written. + * @throws SyntaxError If the input string contains characters outside the specified alphabet, or if the last + * chunk is inconsistent with the `lastChunkHandling` option. + */ + setFromBase64(string: string, options?: CoreJSFromBase64Options): CoreJSProcessMetadata; + + /** + * Sets the `Uint8Array` from a base16-encoded string. + * @param string - The base16-encoded string. + * @returns An object containing the number of bytes read and written. + */ + setFromHex(string: string): CoreJSProcessMetadata; + + /** + * Converts the `Uint8Array` to a base64-encoded string. + * @param options - If provided, sets the alphabet and padding behavior used. + * @returns A base64-encoded string. + */ + toBase64(options?: CoreJSToBase64Options): string; + + /** + * Converts the `Uint8Array` to a base16-encoded string. + * @returns A base16-encoded string. + */ + toHex(): string; +} diff --git a/packages/core-js-types/src/base/proposals/array-buffer-transfer.d.ts b/packages/core-js-types/src/base/proposals/array-buffer-transfer.d.ts new file mode 100644 index 000000000000..a94e1b917865 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/array-buffer-transfer.d.ts @@ -0,0 +1,59 @@ +// https://github.com/tc39/proposal-arraybuffer-transfer + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/4a957b74ea4d716356181644d23f6ad5f10824d6/src/lib/es2024.arraybuffer.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface ArrayBuffer { + // TODO hack for modern ts + // get detached(): boolean; + + /** + * Creates a new `ArrayBuffer` with the same byte content as this buffer, then detaches this buffer. + * @param newByteLength - If provided, specifies the `byteLength` of the new `ArrayBuffer` + * @throws RangeError If this `ArrayBuffer` is resizable and newByteLength is greater than the `maxByteLength` of this `ArrayBuffer` + * @throws TypeError If this `ArrayBuffer` is already detached, or if it can only be detached by designated operations + * @returns A new `ArrayBuffer` object + */ + transfer(newByteLength?: number): ArrayBuffer; + + /** + * Creates a new non-resizable `ArrayBuffer` with the same byte content as this buffer, then detaches this buffer. + * @param newByteLength - If provided, specifies the `byteLength` of the new `ArrayBuffer` + * @throws TypeError If this `ArrayBuffer` is already detached, or if it can only be detached by designated operations + * @returns A new `ArrayBuffer` object + */ + transferToFixedLength(newByteLength?: number): ArrayBuffer; +} + +// Type compatibility hack for AllowSharedBufferSource in TypeScript < 5.9 +// https://github.com/microsoft/TypeScript/issues/61480 +interface SharedArrayBuffer { + readonly resizable: boolean; + + readonly detached: boolean; + + /** + * Creates a new `ArrayBuffer` with the same byte content as this buffer, then detaches this buffer. + * @param newByteLength - If provided, specifies the `byteLength` of the new `ArrayBuffer` + * @throws RangeError If this `ArrayBuffer` is resizable and newByteLength is greater than the `maxByteLength` of this `ArrayBuffer` + * @throws TypeError If this `ArrayBuffer` is already detached, or if it can only be detached by designated operations + * @returns A new `ArrayBuffer` object + */ + transfer(newByteLength?: number): ArrayBuffer; + + /** + * Creates a new non-resizable `ArrayBuffer` with the same byte content as this buffer, then detaches this buffer. + * @param newByteLength - If provided, specifies the `byteLength` of the new `ArrayBuffer` + * @throws TypeError If this `ArrayBuffer` is already detached, or if it can only be detached by designated operations + * @returns A new `ArrayBuffer` object + */ + transferToFixedLength(newByteLength?: number): ArrayBuffer; + + /** + * Resizes the ArrayBuffer to the specified size (in bytes). + * + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/resize) + */ + resize(newByteLength?: number): void; +} diff --git a/packages/core-js-types/src/base/proposals/array-filtering.d.ts b/packages/core-js-types/src/base/proposals/array-filtering.d.ts new file mode 100644 index 000000000000..dda2db1b9f71 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/array-filtering.d.ts @@ -0,0 +1,144 @@ +// https://github.com/tc39/proposal-array-filtering + +interface Array { // @type-options: no-redefine + /** + * Removes the items that return true + * @param callbackFn - A function that accepts up to three arguments. The filterReject method calls the + * callbackFn function one time for each element in the array. + * @param thisArg - If provided, it will be used as this value for each invocation of + * callbackFn function. If it is not provided, undefined is used instead. + */ + filterReject(callbackFn: (value: T, index: number, target: T[]) => unknown, thisArg?: any): T[]; +} + +interface ReadonlyArray { // @type-options: no-export + /** + * Removes the items that return true + * @param callbackFn - A function that accepts up to three arguments. The filterReject method calls the + * callbackFn function one time for each element in the array. + * @param thisArg - If provided, it will be used as this value for each invocation of + * callbackFn function. If it is not provided, undefined is used instead. + */ + filterReject(callbackFn: (value: T, index: number, target: readonly T[]) => unknown, thisArg?: any): T[]; +} + +interface Int8Array { // @type-options: no-export + /** + * Removes the items that return true + * @param callbackFn - A function that accepts up to three arguments. The filterReject method calls the + * callbackFn function one time for each element in the array. + * @param thisArg - If provided, it will be used as this value for each invocation of + * callbackFn function. If it is not provided, undefined is used instead. + */ + filterReject(callbackFn: (value: number, index: number, target: Int8Array) => unknown, thisArg?: any): Int8Array; +} + +interface Uint8Array { // @type-options: no-export + /** + * Removes the items that return true + * @param callbackFn - A function that accepts up to three arguments. The filterReject method calls the + * callbackFn function one time for each element in the array. + * @param thisArg - If provided, it will be used as this value for each invocation of + * callbackFn function. If it is not provided, undefined is used instead. + */ + filterReject(callbackFn: (value: number, index: number, target: Uint8Array) => unknown, thisArg?: any): Uint8Array; +} + +interface Uint8ClampedArray { // @type-options: no-export + /** + * Removes the items that return true + * @param callbackFn - A function that accepts up to three arguments. The filterReject method calls the + * callbackFn function one time for each element in the array. + * @param thisArg - If provided, it will be used as this value for each invocation of + * callbackFn function. If it is not provided, undefined is used instead. + */ + filterReject(callbackFn: (value: number, index: number, target: Uint8ClampedArray) => unknown, thisArg?: any): Uint8ClampedArray; +} + +interface Int16Array { // @type-options: no-export + /** + * Removes the items that return true + * @param callbackFn - A function that accepts up to three arguments. The filterReject method calls the + * callbackFn function one time for each element in the array. + * @param thisArg - If provided, it will be used as this value for each invocation of + * callbackFn function. If it is not provided, undefined is used instead. + */ + filterReject(callbackFn: (value: number, index: number, target: Int16Array) => unknown, thisArg?: any): Int16Array; +} + +interface Uint16Array { // @type-options: no-export + /** + * Removes the items that return true + * @param callbackFn - A function that accepts up to three arguments. The filterReject method calls the + * callbackFn function one time for each element in the array. + * @param thisArg - If provided, it will be used as this value for each invocation of + * callbackFn function. If it is not provided, undefined is used instead. + */ + filterReject(callbackFn: (value: number, index: number, target: Uint16Array) => unknown, thisArg?: any): Uint16Array; +} + +interface Int32Array { // @type-options: no-export + /** + * Removes the items that return true + * @param callbackFn - A function that accepts up to three arguments. The filterReject method calls the + * callbackFn function one time for each element in the array. + * @param thisArg - If provided, it will be used as this value for each invocation of + * callbackFn function. If it is not provided, undefined is used instead. + */ + filterReject(callbackFn: (value: number, index: number, target: Int32Array) => unknown, thisArg?: any): Int32Array; +} + +interface Uint32Array { // @type-options: no-export + /** + * Removes the items that return true + * @param callbackFn - A function that accepts up to three arguments. The filterReject method calls the + * callbackFn function one time for each element in the array. + * @param thisArg - If provided, it will be used as this value for each invocation of + * callbackFn function. If it is not provided, undefined is used instead. + */ + filterReject(callbackFn: (value: number, index: number, target: Uint32Array) => unknown, thisArg?: any): Uint32Array; +} + +interface Float32Array { // @type-options: no-export + /** + * Removes the items that return true + * @param callbackFn - A function that accepts up to three arguments. The filterReject method calls the + * callbackFn function one time for each element in the array. + * @param thisArg - If provided, it will be used as this value for each invocation of + * callbackFn function. If it is not provided, undefined is used instead. + */ + filterReject(callbackFn: (value: number, index: number, target: Float32Array) => unknown, thisArg?: any): Float32Array; +} + +interface Float64Array { // @type-options: no-export + /** + * Removes the items that return true + * @param callbackFn - A function that accepts up to three arguments. The filterReject method calls the + * callbackFn function one time for each element in the array. + * @param thisArg - If provided, it will be used as this value for each invocation of + * callbackFn function. If it is not provided, undefined is used instead. + */ + filterReject(callbackFn: (value: number, index: number, target: Float64Array) => unknown, thisArg?: any): Float64Array; +} + +interface BigInt64Array { // @type-options: no-export + /** + * Removes the items that return true + * @param callbackFn - A function that accepts up to three arguments. The filterReject method calls the + * callbackFn function one time for each element in the array. + * @param thisArg - If provided, it will be used as this value for each invocation of + * callbackFn function. If it is not provided, undefined is used instead. + */ + filterReject(callbackFn: (value: bigint, index: number, target: BigInt64Array) => unknown, thisArg?: any): BigInt64Array; +} + +interface BigUint64Array { // @type-options: no-export + /** + * Removes the items that return true + * @param callbackFn - A function that accepts up to three arguments. The filterReject method calls the + * callbackFn function one time for each element in the array. + * @param thisArg - If provided, it will be used as this value for each invocation of + * callbackFn function. If it is not provided, undefined is used instead. + */ + filterReject(callbackFn: (value: bigint, index: number, target: BigUint64Array) => unknown, thisArg?: any): BigUint64Array; +} diff --git a/packages/core-js-types/src/base/proposals/array-find-from-last.d.ts b/packages/core-js-types/src/base/proposals/array-find-from-last.d.ts new file mode 100644 index 000000000000..fb1dfe687bd4 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/array-find-from-last.d.ts @@ -0,0 +1,330 @@ +// https://github.com/tc39/proposal-array-find-from-last + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/069de743dbd17b47cc2fc58e1d16da5410911284/src/lib/es2023.array.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface Array { // @type-options: no-redefine + /** + * Returns the value of the last element in the array where predicate is true, and undefined + * otherwise. + * @param predicate - findLast calls predicate once for each element of the array, in descending + * order, until it finds one where predicate returns true. If such an element is found, findLast + * immediately returns that element value. Otherwise, findLast returns undefined. + * @param thisArg - If provided, it will be used as this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findLast(predicate: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S | undefined; + findLast(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): T | undefined; + + /** + * Returns the index of the last element in the array where predicate is true, and -1 + * otherwise. + * @param predicate - findLastIndex calls predicate once for each element of the array, in descending + * order, until it finds one where predicate returns true. If such an element is found, + * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1. + * @param thisArg - If provided, it will be used as this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findLastIndex(predicate: (value: T, index: number, array: T[]) => unknown, thisArg?: any): number; +} + +interface ReadonlyArray { // @type-options: no-export + /** + * Returns the value of the last element in the array where predicate is true, and undefined + * otherwise. + * @param predicate - findLast calls predicate once for each element of the array, in descending + * order, until it finds one where predicate returns true. If such an element is found, findLast + * immediately returns that element value. Otherwise, findLast returns undefined. + * @param thisArg - If provided, it will be used as this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findLast(predicate: (value: T, index: number, array: readonly T[]) => value is S, thisArg?: any): S | undefined; + findLast(predicate: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any): T | undefined; + + /** + * Returns the index of the last element in the array where predicate is true, and -1 + * otherwise. + * @param predicate - findLastIndex calls predicate once for each element of the array, in descending + * order, until it finds one where predicate returns true. If such an element is found, + * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1. + * @param thisArg - If provided, it will be used as this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findLastIndex(predicate: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any): number; +} + +interface Int8Array { // @type-options: no-export + /** + * Returns the value of the last element in the array where predicate is true, and undefined + * otherwise. + * @param predicate - findLast calls predicate once for each element of the array, in descending + * order, until it finds one where predicate returns true. If such an element is found, findLast + * immediately returns that element value. Otherwise, findLast returns undefined. + * @param thisArg - If provided, it will be used as this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findLast(predicate: (value: number, index: number, array: this) => value is S, thisArg?: any): S | undefined; + findLast(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): number | undefined; + + /** + * Returns the index of the last element in the array where predicate is true, and -1 + * otherwise. + * @param predicate - findLastIndex calls predicate once for each element of the array, in descending + * order, until it finds one where predicate returns true. If such an element is found, + * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1. + * @param thisArg - If provided, it will be used as this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findLastIndex(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): number; +} + +interface Uint8Array { // @type-options: no-export + /** + * Returns the value of the last element in the array where predicate is true, and undefined + * otherwise. + * @param predicate - findLast calls predicate once for each element of the array, in descending + * order, until it finds one where predicate returns true. If such an element is found, findLast + * immediately returns that element value. Otherwise, findLast returns undefined. + * @param thisArg - If provided, it will be used as this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findLast(predicate: (value: number, index: number, array: this) => value is S, thisArg?: any): S | undefined; + findLast(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): number | undefined; + + /** + * Returns the index of the last element in the array where predicate is true, and -1 + * otherwise. + * @param predicate - findLastIndex calls predicate once for each element of the array, in descending + * order, until it finds one where predicate returns true. If such an element is found, + * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1. + * @param thisArg - If provided, it will be used as this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findLastIndex(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): number; +} + +interface Uint8ClampedArray { // @type-options: no-export + /** + * Returns the value of the last element in the array where predicate is true, and undefined + * otherwise. + * @param predicate - findLast calls predicate once for each element of the array, in descending + * order, until it finds one where predicate returns true. If such an element is found, findLast + * immediately returns that element value. Otherwise, findLast returns undefined. + * @param thisArg - If provided, it will be used as this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findLast(predicate: (value: number, index: number, array: this) => value is S, thisArg?: any): S | undefined; + findLast(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): number | undefined; + + /** + * Returns the index of the last element in the array where predicate is true, and -1 + * otherwise. + * @param predicate - findLastIndex calls predicate once for each element of the array, in descending + * order, until it finds one where predicate returns true. If such an element is found, + * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1. + * @param thisArg - If provided, it will be used as this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findLastIndex(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): number; +} + +interface Int16Array { // @type-options: no-export + /** + * Returns the value of the last element in the array where predicate is true, and undefined + * otherwise. + * @param predicate - findLast calls predicate once for each element of the array, in descending + * order, until it finds one where predicate returns true. If such an element is found, findLast + * immediately returns that element value. Otherwise, findLast returns undefined. + * @param thisArg - If provided, it will be used as this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findLast(predicate: (value: number, index: number, array: this) => value is S, thisArg?: any): S | undefined; + findLast(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): number | undefined; + + /** + * Returns the index of the last element in the array where predicate is true, and -1 + * otherwise. + * @param predicate - findLastIndex calls predicate once for each element of the array, in descending + * order, until it finds one where predicate returns true. If such an element is found, + * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1. + * @param thisArg - If provided, it will be used as this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findLastIndex(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): number; +} + +interface Uint16Array { // @type-options: no-export + /** + * Returns the value of the last element in the array where predicate is true, and undefined + * otherwise. + * @param predicate - findLast calls predicate once for each element of the array, in descending + * order, until it finds one where predicate returns true. If such an element is found, findLast + * immediately returns that element value. Otherwise, findLast returns undefined. + * @param thisArg - If provided, it will be used as this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findLast(predicate: (value: number, index: number, array: this) => value is S, thisArg?: any): S | undefined; + findLast(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): number | undefined; + + /** + * Returns the index of the last element in the array where predicate is true, and -1 + * otherwise. + * @param predicate - findLastIndex calls predicate once for each element of the array, in descending + * order, until it finds one where predicate returns true. If such an element is found, + * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1. + * @param thisArg - If provided, it will be used as this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findLastIndex(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): number; +} + +interface Int32Array { // @type-options: no-export + /** + * Returns the value of the last element in the array where predicate is true, and undefined + * otherwise. + * @param predicate - findLast calls predicate once for each element of the array, in descending + * order, until it finds one where predicate returns true. If such an element is found, findLast + * immediately returns that element value. Otherwise, findLast returns undefined. + * @param thisArg - If provided, it will be used as this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findLast(predicate: (value: number, index: number, array: this) => value is S, thisArg?: any): S | undefined; + findLast(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): number | undefined; + + /** + * Returns the index of the last element in the array where predicate is true, and -1 + * otherwise. + * @param predicate - findLastIndex calls predicate once for each element of the array, in descending + * order, until it finds one where predicate returns true. If such an element is found, + * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1. + * @param thisArg - If provided, it will be used as this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findLastIndex(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): number; +} + +interface Uint32Array { // @type-options: no-export + /** + * Returns the value of the last element in the array where predicate is true, and undefined + * otherwise. + * @param predicate - findLast calls predicate once for each element of the array, in descending + * order, until it finds one where predicate returns true. If such an element is found, findLast + * immediately returns that element value. Otherwise, findLast returns undefined. + * @param thisArg - If provided, it will be used as this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findLast(predicate: (value: number, index: number, array: this) => value is S, thisArg?: any): S | undefined; + findLast(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): number | undefined; + + /** + * Returns the index of the last element in the array where predicate is true, and -1 + * otherwise. + * @param predicate - findLastIndex calls predicate once for each element of the array, in descending + * order, until it finds one where predicate returns true. If such an element is found, + * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1. + * @param thisArg - If provided, it will be used as this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findLastIndex(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): number; +} + +interface Float32Array { // @type-options: no-export + /** + * Returns the value of the last element in the array where predicate is true, and undefined + * otherwise. + * @param predicate - findLast calls predicate once for each element of the array, in descending + * order, until it finds one where predicate returns true. If such an element is found, findLast + * immediately returns that element value. Otherwise, findLast returns undefined. + * @param thisArg - If provided, it will be used as this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findLast(predicate: (value: number, index: number, array: this) => value is S, thisArg?: any): S | undefined; + findLast(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): number | undefined; + + /** + * Returns the index of the last element in the array where predicate is true, and -1 + * otherwise. + * @param predicate - findLastIndex calls predicate once for each element of the array, in descending + * order, until it finds one where predicate returns true. If such an element is found, + * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1. + * @param thisArg - If provided, it will be used as this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findLastIndex(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): number; +} + +interface Float64Array { // @type-options: no-export + /** + * Returns the value of the last element in the array where predicate is true, and undefined + * otherwise. + * @param predicate - findLast calls predicate once for each element of the array, in descending + * order, until it finds one where predicate returns true. If such an element is found, findLast + * immediately returns that element value. Otherwise, findLast returns undefined. + * @param thisArg - If provided, it will be used as this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findLast(predicate: (value: number, index: number, array: this) => value is S, thisArg?: any): S | undefined; + findLast(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): number | undefined; + + /** + * Returns the index of the last element in the array where predicate is true, and -1 + * otherwise. + * @param predicate - findLastIndex calls predicate once for each element of the array, in descending + * order, until it finds one where predicate returns true. If such an element is found, + * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1. + * @param thisArg - If provided, it will be used as this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findLastIndex(predicate: (value: number, index: number, array: this) => unknown, thisArg?: any): number; +} + +interface BigInt64Array { // @type-options: no-export + /** + * Returns the value of the last element in the array where predicate is true, and undefined + * otherwise. + * @param predicate - findLast calls predicate once for each element of the array, in descending + * order, until it finds one where predicate returns true. If such an element is found, findLast + * immediately returns that element value. Otherwise, findLast returns undefined. + * @param thisArg - If provided, it will be used as this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findLast(predicate: (value: bigint, index: number, array: this) => value is S, thisArg?: any): S | undefined; + findLast(predicate: (value: bigint, index: number, array: this) => unknown, thisArg?: any): bigint | undefined; + + /** + * Returns the index of the last element in the array where predicate is true, and -1 + * otherwise. + * @param predicate - findLastIndex calls predicate once for each element of the array, in descending + * order, until it finds one where predicate returns true. If such an element is found, + * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1. + * @param thisArg - If provided, it will be used as this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findLastIndex(predicate: (value: bigint, index: number, array: this) => unknown, thisArg?: any): number; +} + +interface BigUint64Array { // @type-options: no-export + /** + * Returns the value of the last element in the array where predicate is true, and undefined + * otherwise. + * @param predicate - findLast calls predicate once for each element of the array, in descending + * order, until it finds one where predicate returns true. If such an element is found, findLast + * immediately returns that element value. Otherwise, findLast returns undefined. + * @param thisArg - If provided, it will be used as this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findLast(predicate: (value: bigint, index: number, array: this) => value is S, thisArg?: any): S | undefined; + findLast(predicate: (value: bigint, index: number, array: this) => unknown, thisArg?: any): bigint | undefined; + + /** + * Returns the index of the last element in the array where predicate is true, and -1 + * otherwise. + * @param predicate - findLastIndex calls predicate once for each element of the array, in descending + * order, until it finds one where predicate returns true. If such an element is found, + * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1. + * @param thisArg - If provided, it will be used as this value for each invocation of + * predicate. If it is not provided, undefined is used instead. + */ + findLastIndex(predicate: (value: bigint, index: number, array: this) => unknown, thisArg?: any): number; +} diff --git a/packages/core-js-types/src/base/proposals/array-flat-map-custom.d.ts b/packages/core-js-types/src/base/proposals/array-flat-map-custom.d.ts new file mode 100644 index 000000000000..194a95d8d73f --- /dev/null +++ b/packages/core-js-types/src/base/proposals/array-flat-map-custom.d.ts @@ -0,0 +1,11 @@ +// Motivation: Custom type needed to keep generics strict + +// https://github.com/tc39/proposal-flatMap + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/069de743dbd17b47cc2fc58e1d16da5410911284/src/lib/es2019.array.d.ts#L46 +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +declare namespace CoreJS { + export type ArrayFlatMap = (callback: (this: This, value: T, index: number, array: T[]) => U | ReadonlyArray, thisArg?: This) => U[]; +} diff --git a/packages/core-js-types/src/base/proposals/array-flat-map.d.ts b/packages/core-js-types/src/base/proposals/array-flat-map.d.ts new file mode 100644 index 000000000000..ffb11c7c69ba --- /dev/null +++ b/packages/core-js-types/src/base/proposals/array-flat-map.d.ts @@ -0,0 +1,47 @@ +/// + +// https://github.com/tc39/proposal-flatMap + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/069de743dbd17b47cc2fc58e1d16da5410911284/src/lib/es2019.array.d.ts#L46 +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface Array { // @type-options: no-redefine + /** + * Calls a defined callback function on each element of an array. Then, flattens the result into + * a new array. + * This is identical to a map followed by flat with depth 1. + * @param callback - A function that accepts up to three arguments. The flatMap method calls the + * callback function one time for each element in the array. + * @param thisArg - An object to which this keyword can refer in the callback function. If + * thisArg is omitted, undefined is used as this value. + */ + flatMap(callback: (this: This, value: T, index: number, array: T[]) => U | ReadonlyArray, thisArg?: This): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * @param depth - The maximum recursion depth + */ + flat(this: A, depth?: D): CoreJS.CoreJSFlatArray[]; +} + +interface ReadonlyArray { // @type-options: no-export + /** + * Calls a defined callback function on each element of an array. Then, flattens the result into + * a new array. + * This is identical to a map followed by flat with depth 1. + * @param callback - A function that accepts up to three arguments. The flatMap method calls the + * callback function one time for each element in the array. + * @param thisArg - An object to which this keyword can refer in the callback function. If + * thisArg is omitted, undefined is used as this value. + */ + flatMap(callback: (this: This, value: T, index: number, array: T[]) => U | ReadonlyArray, thisArg?: This): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * @param depth - The maximum recursion depth + */ + flat(this: A, depth?: D): CoreJS.CoreJSFlatArray[]; +} diff --git a/packages/core-js-types/src/base/proposals/array-from-async.d.ts b/packages/core-js-types/src/base/proposals/array-from-async.d.ts new file mode 100644 index 000000000000..4c5210bfac68 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/array-from-async.d.ts @@ -0,0 +1,25 @@ +/// + +// https://github.com/tc39/proposal-array-from-async + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/069de743dbd17b47cc2fc58e1d16da5410911284/src/lib/esnext.array.d.ts#L6 +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface ArrayConstructor { + /** + * Creates an array from an async iterator or iterable object. + * @param iterableOrArrayLike - An async iterator or array-like object to convert to an array. + */ + fromAsync(iterableOrArrayLike: AsyncIterable | Iterable> | ArrayLike>): Promise; // @type-options: prefix-return-type + + /** + * Creates an array from an async iterator or iterable object. + * + * @param iterableOrArrayLike - An async iterator or array-like object to convert to an array. + * @param mapFn - A mapping function to call on every element of iterableOrArrayLike. + * Each return value is awaited before being added to result array. + * @param thisArg - Value of 'this' used when executing mapFn. + */ + fromAsync(iterableOrArrayLike: AsyncIterable | Iterable | ArrayLike, mapFn: (value: Awaited, index: number) => U, thisArg?: any): Promise[]>; // @type-options: prefix-return-type +} diff --git a/packages/core-js-types/src/base/proposals/array-grouping.d.ts b/packages/core-js-types/src/base/proposals/array-grouping.d.ts new file mode 100644 index 000000000000..4fd8335c8894 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/array-grouping.d.ts @@ -0,0 +1,24 @@ +// https://github.com/tc39/proposal-array-grouping + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/069de743dbd17b47cc2fc58e1d16da5410911284/src/lib/es2024.object.d.ts#L7 +// https://github.com/microsoft/TypeScript/blob/069de743dbd17b47cc2fc58e1d16da5410911284/src/lib/es2024.collection.d.ts#L7 +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface ObjectConstructor { + /** + * Groups members of an iterable according to the return value of the passed callback. + * @param items - An iterable. + * @param keySelector - A callback which will be invoked for each item in items. + */ + groupBy(items: Iterable, keySelector: (item: T, index: number) => K): Partial>; +} + +interface MapConstructor { + /** + * Groups members of an iterable according to the return value of the passed callback. + * @param items - An iterable. + * @param keySelector - A callback which will be invoked for each item in items. + */ + groupBy(items: Iterable, keySelector: (item: T, index: number) => K): Map; // @type-options: prefix-return-type +} diff --git a/packages/core-js-types/src/base/proposals/array-includes.d.ts b/packages/core-js-types/src/base/proposals/array-includes.d.ts new file mode 100644 index 000000000000..60549d7221ca --- /dev/null +++ b/packages/core-js-types/src/base/proposals/array-includes.d.ts @@ -0,0 +1,122 @@ +// https://github.com/tc39/proposal-Array.prototype.includes + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/069de743dbd17b47cc2fc58e1d16da5410911284/src/lib/es2016.array.include.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface Array { // @type-options: no-redefine + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement - The element to search for. + * @param fromIndex - The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: T, fromIndex?: number): boolean; +} + +interface ReadonlyArray { // @type-options: no-export + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement - The element to search for. + * @param fromIndex - The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: T, fromIndex?: number): boolean; +} + +interface Int8Array { // @type-options: no-export + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement - The element to search for. + * @param fromIndex - The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Uint8Array { // @type-options: no-export + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement - The element to search for. + * @param fromIndex - The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Uint8ClampedArray { // @type-options: no-export + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement - The element to search for. + * @param fromIndex - The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Int16Array { // @type-options: no-export + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement - The element to search for. + * @param fromIndex - The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Uint16Array { // @type-options: no-export + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement - The element to search for. + * @param fromIndex - The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Int32Array { // @type-options: no-export + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement - The element to search for. + * @param fromIndex - The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Uint32Array { // @type-options: no-export + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement - The element to search for. + * @param fromIndex - The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Float32Array { // @type-options: no-export + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement - The element to search for. + * @param fromIndex - The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface Float64Array { // @type-options: no-export + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement - The element to search for. + * @param fromIndex - The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: number, fromIndex?: number): boolean; +} + +interface BigInt64Array { // @type-options: no-export + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement - The element to search for. + * @param fromIndex - The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: bigint, fromIndex?: number): boolean; +} + +interface BigUint64Array { // @type-options: no-export + /** + * Determines whether an array includes a certain element, returning true or false as appropriate. + * @param searchElement - The element to search for. + * @param fromIndex - The position in this array at which to begin searching for searchElement. + */ + includes(searchElement: bigint, fromIndex?: number): boolean; +} diff --git a/packages/core-js-types/src/base/proposals/array-is-template-object.d.ts b/packages/core-js-types/src/base/proposals/array-is-template-object.d.ts new file mode 100644 index 000000000000..d15b9c087439 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/array-is-template-object.d.ts @@ -0,0 +1,10 @@ +// https://github.com/tc39/proposal-array-is-template-object + +interface ArrayConstructor { // @type-options: no-export + /** + * Determines whether a `value` is a `TemplateStringsArray` + * @param value - The value to be checked + * @returns `true` if `value` is a `TemplateStringsArray`, otherwise `false` + */ + isTemplateObject(value: any): value is TemplateStringsArray; +} diff --git a/packages/core-js-types/src/base/proposals/array-unique.d.ts b/packages/core-js-types/src/base/proposals/array-unique.d.ts new file mode 100644 index 000000000000..45fb2ae4de0c --- /dev/null +++ b/packages/core-js-types/src/base/proposals/array-unique.d.ts @@ -0,0 +1,131 @@ +// https://github.com/tc39/proposal-array-unique + +interface Array { // @type-options: no-redefine + /** + * Returns a new array with unique items, determined by the resolver function or property key + * @param resolver - A function that resolves the value to check uniqueness against, + * or a property key to compare the value from each item + * @returns A new `Array` with unique items + */ + uniqueBy(resolver?: keyof T | ((value: T) => unknown)): Array; +} + +interface ReadonlyArray { // @type-options: no-export + /** + * Returns a new array with unique items, determined by the resolver function or property key + * @param resolver - A function that resolves the value to check uniqueness against, + * or a property key to compare the value from each item + * @returns A new `Array` with unique items + */ + uniqueBy(resolver?: keyof T | ((value: T) => unknown)): Array; +} + +interface Int8Array { // @type-options: no-export + /** + * Returns a new array with unique items, determined by the resolver function or property key + * @param resolver - A function that resolves the value to check uniqueness against, + * or a property key to compare the value from each item + * @returns A new `Int8Array` with unique items + */ + uniqueBy(resolver?: PropertyKey | ((value: number) => unknown)): Int8Array; +} + +interface Uint8Array { // @type-options: no-export + /** + * Returns a new array with unique items, determined by the resolver function or property key + * @param resolver - A function that resolves the value to check uniqueness against, + * or a property key to compare the value from each item + * @returns A new `Uint8Array` with unique items + */ + uniqueBy(resolver?: PropertyKey | ((value: number) => unknown)): Uint8Array; +} + +interface Uint8ClampedArray { // @type-options: no-export + /** + * Returns a new array with unique items, determined by the resolver function or property key + * @param resolver - A function that resolves the value to check uniqueness against, + * or a property key to compare the value from each item + * @returns A new `Uint8ClampedArray` with unique items + */ + uniqueBy(resolver?: PropertyKey | ((value: number) => unknown)): Uint8ClampedArray; +} + +interface Int16Array { // @type-options: no-export + /** + * Returns a new array with unique items, determined by the resolver function or property key + * @param resolver - A function that resolves the value to check uniqueness against, + * or a property key to compare the value from each item + * @returns A new `Int16Array` with unique items + */ + uniqueBy(resolver?: PropertyKey | ((value: number) => unknown)): Int16Array; +} + +interface Uint16Array { // @type-options: no-export + /** + * Returns a new array with unique items, determined by the resolver function or property key + * @param resolver - A function that resolves the value to check uniqueness against, + * or a property key to compare the value from each item + * @returns A new `Uint16Array` with unique items + */ + uniqueBy(resolver?: PropertyKey | ((value: number) => unknown)): Uint16Array; +} + +interface Int32Array { // @type-options: no-export + /** + * Returns a new array with unique items, determined by the resolver function or property key + * @param resolver - A function that resolves the value to check uniqueness against, + * or a property key to compare the value from each item + * @returns A new `Int32Array` with unique items + */ + uniqueBy(resolver?: PropertyKey | ((value: number) => unknown)): Int32Array; +} + +interface Uint32Array { // @type-options: no-export + /** + * Returns a new array with unique items, determined by the resolver function or property key + * @param resolver - A function that resolves the value to check uniqueness against, + * or a property key to compare the value from each item + * @returns A new `Uint32Array` with unique items + */ + uniqueBy(resolver?: PropertyKey | ((value: number) => unknown)): Uint32Array; +} + +interface Float32Array { // @type-options: no-export + /** + * Returns a new array with unique items, determined by the resolver function or property key + * @param resolver - A function that resolves the value to check uniqueness against, + * or a property key to compare the value from each item + * @returns A new `Float32Array` with unique items + */ + uniqueBy(resolver?: PropertyKey | ((value: number) => unknown)): Float32Array; +} + +interface Float64Array { // @type-options: no-export + /** + * Returns a new array with unique items, determined by the resolver function or property key + * @param resolver - A function that resolves the value to check uniqueness against, + * or a property key to compare the value from each item + * @returns A new `Float64Array` with unique items + */ + uniqueBy(resolver?: PropertyKey | ((value: number) => unknown)): Float64Array; +} + +interface BigInt64Array { // @type-options: no-export + /** + * Returns a new array with unique items, determined by the resolver function or property key + * @param resolver - A function that resolves the value to check uniqueness against, + * or a property key to compare the value from each item + * @returns A new `BigInt64Array` with unique items + */ + uniqueBy(resolver?: PropertyKey | ((value: bigint) => unknown)): BigInt64Array; +} + +interface BigUint64Array { // @type-options: no-export + /** + * Returns a new array with unique items, determined by the resolver function or property key + * @param resolver - A function that resolves the value to check uniqueness against, + * or a property key to compare the value from each item + * @returns A new `BigUint64Array` with unique items + */ + uniqueBy(resolver?: PropertyKey | ((value: bigint) => unknown)): BigUint64Array; +} diff --git a/packages/core-js-types/src/base/proposals/async-iteration.d.ts b/packages/core-js-types/src/base/proposals/async-iteration.d.ts new file mode 100644 index 000000000000..b2774ddeff80 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/async-iteration.d.ts @@ -0,0 +1,13 @@ +// https://github.com/tc39/proposal-async-iteration + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/069de743dbd17b47cc2fc58e1d16da5410911284/src/lib/es2018.asynciterable.d.ts#L4 +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface SymbolConstructor { + /** + * A method that returns the default async iterator for an object. Called by the semantics of + * the for-await-of statement. + */ + readonly asyncIterator: unique symbol; +} diff --git a/packages/core-js-types/src/base/proposals/async-iterator-helpers-custom.d.ts b/packages/core-js-types/src/base/proposals/async-iterator-helpers-custom.d.ts new file mode 100644 index 000000000000..62a19d1f98a5 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/async-iterator-helpers-custom.d.ts @@ -0,0 +1,13 @@ +/// + +// Motivation: Custom type needed to keep generics strict + +// https://github.com/tc39/proposal-async-iterator-helpers + +declare namespace CoreJS { + export type AsyncIteratorFlatMap = (callback: (value: T, index: number) => Iterator | Iterable | AsyncIterator | AsyncIterable) => AsyncIteratorObject; + + export type AsyncIteratorMap = (callbackfn: (value: T, index: number) => U) => AsyncIteratorObject, undefined, unknown>; + + export type AsyncIteratorReduce = (callbackfn: (accumulator: U, value: T, index: number) => U, initialValue?: U) => Promise; +} diff --git a/packages/core-js-types/src/base/proposals/async-iterator-helpers.d.ts b/packages/core-js-types/src/base/proposals/async-iterator-helpers.d.ts new file mode 100644 index 000000000000..f0958ae57800 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/async-iterator-helpers.d.ts @@ -0,0 +1,118 @@ +/// + +// https://github.com/tc39/proposal-async-iterator-helpers + +interface AsyncIteratorConstructor { + /** + * Creates an `AsyncIterator` from an iterable object + * @param iterable - An `AsyncIterable`, `Iterable`, or `AsyncIterator` to convert to an `AsyncIterator` + * @returns A new `AsyncIterator` instance + */ + from(iterable: AsyncIterable | Iterable | AsyncIterator): AsyncIteratorObject; +} + +declare var AsyncIterator: AsyncIteratorConstructor; + +interface AsyncIterator { + /** + * Drops elements from the iterator until the limit is reached + * @param limit - The number of elements to drop + * @returns A new `AsyncIterator` + */ + drop(limit: number): AsyncIteratorObject; + + /** + * Check if every value generated by the iterator passes the `predicate` function. + * @param predicate - A function that tests each element of the iterator + * @returns A `Promise` that resolves to `true` if all elements pass the test, otherwise `false` + */ + every(predicate: (value: T, index: number) => unknown): Promise; + + /** + * Creates a new `AsyncIterator` that contains only the elements that pass the `predicate` function. + * @param predicate - A function that tests each element of the iterator + * @returns A new `AsyncIterator` + */ + filter(predicate: (value: T, index: number) => value is S): AsyncIteratorObject; + filter(predicate: (value: T, index: number) => unknown): AsyncIteratorObject; + + /** + * Finds the first element in the iterator that satisfies the `predicate` function. + * @param predicate - A function that tests each element of the iterator + * @returns A `Promise` that resolves to the found element, or `undefined` if no element satisfies the `predicate` + */ + find(predicate: (value: T, index: number) => value is S): Promise; + find(predicate: (value: T, index: number) => unknown): Promise; + + /** + * Creates a new `AsyncIterator` by applying the `callback` function to each element of the original iterator and flattening the result. + * @param callback - A function that transforms each element of the iterator + * @returns A new `AsyncIterator` + */ + flatMap(callback: (value: T, index: number) => Iterator | Iterable | AsyncIterator | AsyncIterable): AsyncIteratorObject; + + /** + * Executes a provided function once for each element in the iterator. + * @param callbackfn - A function that is called for each element of the iterator + * @returns A `Promise` that resolves when all elements have been processed + */ + forEach(callbackfn: (value: T, index: number) => void | PromiseLike): Promise; + + /** + * Creates a new `AsyncIterator` by applying the `callbackfn` function to each element of the original iterator. + * @param callbackfn - A function that transforms each element of the iterator + * @returns A new `AsyncIterator` + */ + map(callbackfn: (value: T, index: number) => U): AsyncIteratorObject, undefined, unknown>; + + /** + * Reduces the elements of the iterator to a single value using the `callbackfn` function. + * @param callbackfn - A function that combines two elements of the iterator + * @returns A `Promise` that resolves to the reduced value + */ + reduce(callbackfn: (accumulator: T, value: T, index: number) => T): Promise; + + /** + * Reduces the elements of the iterator to a single value using the `callbackfn` function. + * @param callbackfn - A function that combines two elements of the iterator + * @param initialValue - The initial value to start the reduction + * @returns A `Promise` that resolves to the reduced value + */ + reduce(callbackfn: (accumulator: T, value: T, index: number) => T, initialValue: T): Promise; + + /** + * Reduces the elements of the iterator to a single value using the `callbackfn` function. + * @param callbackfn - A function that combines two elements of the iterator + * @param initialValue - The initial value to start the accumulation. Required when the accumulator type differs from the element type. + * @returns A `Promise` that resolves to the reduced value + */ + reduce(callbackfn: (accumulator: U, value: T, index: number) => U, initialValue: U): Promise; + + /** + * Checks if any value in the iterator matches a given `predicate` + * @param predicate - A function that tests each element of the iterator + * @returns A `Promise` that resolves to `true` if any element passes the `predicate`, otherwise `false` + */ + some(predicate: (value: T, index: number) => unknown): Promise; + + /** + * Creates a new `AsyncIterator` that yields only the first `limit` elements from the original iterator. + * @param limit - The maximum number of elements to take + * @returns A new `AsyncIterator` + */ + take(limit: number): AsyncIteratorObject; + + /** + * Collects all elements from the iterator into an array. + * @returns A `Promise` that resolves to an array containing all elements from the iterator + */ + toArray(): Promise; +} + +interface Iterator { + /** + * Creates an `AsyncIterator` from the current `Iterator` + * @returns A new `AsyncIterator` instance + */ + toAsync(): AsyncIteratorObject; +} diff --git a/packages/core-js-types/src/base/proposals/await-dictionary.d.ts b/packages/core-js-types/src/base/proposals/await-dictionary.d.ts new file mode 100644 index 000000000000..9ee99a460241 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/await-dictionary.d.ts @@ -0,0 +1,24 @@ +/// + +// https://github.com/tc39/proposal-await-dictionary + +interface PromiseConstructor { + /** + * Takes an object of promises and returns a single Promise that resolves to an object + * with the same keys and fulfilled values, or rejects as soon as any of the input promises rejects. + * @param promises - An object of promises + * @returns A new `Promise` that resolves to an object of fulfilled values or rejects if any promise rejects. + */ + allKeyed>(promises: D): Promise<{ [k in keyof D]: Awaited }>; + + /** + * Takes an object whose values are promises and returns a single `Promise` that resolves + * to an object with the same keys, after all of the input promises have settled. + * @param promises - An object of promises + * @returns A new `Promise` that resolves to an object with the same keys as the input object, + * where each key maps to the settlement result (`{ status, value }` or `{ status, reason }`) of the corresponding promise. + */ + allSettledKeyed>(promises: D): Promise<{ [k in keyof D]: CoreJS.CoreJSPromiseSettledResult> }>; +} + +declare var Promise: PromiseConstructor; diff --git a/packages/core-js-types/src/base/proposals/change-array-by-copy-custom.d.ts b/packages/core-js-types/src/base/proposals/change-array-by-copy-custom.d.ts new file mode 100644 index 000000000000..c9f5a6cd18ce --- /dev/null +++ b/packages/core-js-types/src/base/proposals/change-array-by-copy-custom.d.ts @@ -0,0 +1,11 @@ +// Motivation: Custom type needed to keep generics strict + +// https://github.com/tc39/proposal-change-array-by-copy + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/6afd0fb73fa18a48021ed54f44a0c51794519bf6/src/lib/es2023.array.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +declare namespace CoreJS { + export type ArrayToSpliced = ((start: number, deleteCount: number, ...items: T[]) => T[]) | ((start: number, deleteCount?: number) => T[]); +} diff --git a/packages/core-js-types/src/base/proposals/change-array-by-copy.d.ts b/packages/core-js-types/src/base/proposals/change-array-by-copy.d.ts new file mode 100644 index 000000000000..e6ce2a27d640 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/change-array-by-copy.d.ts @@ -0,0 +1,403 @@ +// https://github.com/tc39/proposal-change-array-by-copy + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/6afd0fb73fa18a48021ed54f44a0c51794519bf6/src/lib/es2023.array.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface Array { // @type-options: no-redefine + /** + * @returns A copy of an array with its elements reversed. + */ + toReversed(): T[]; + + /** + * Returns a copy of an array with its elements sorted. + * @param compareFn - Function used to determine the order of the elements. It is expected to return + * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive + * value otherwise. If omitted, the elements are sorted in ascending, UTF-16 code unit order. + * ```ts + * [11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22] + * ``` + */ + toSorted(compareFn?: (a: T, b: T) => number): T[]; + + /** + * Copies an array and removes elements and, if necessary, inserts new elements in their place. Returns the copied array. + * @param start - The zero-based location in the array from which to start removing elements. + * @param deleteCount - The number of elements to remove. + * @param items - Elements to insert into the copied array in place of the deleted elements. + * @returns The copied array. + */ + toSpliced(start: number, deleteCount: number, ...items: T[]): T[]; + /** + * Copies an array and removes elements while returning the remaining elements. + * @param start - The zero-based location in the array from which to start removing elements. + * @param deleteCount - The number of elements to remove. + * @returns A copy of the original array with the remaining elements. + */ + toSpliced(start: number, deleteCount?: number): T[]; + + /** + * Copies an array, then overwrites the value at the provided index with the + * given value. If the index is negative, then it replaces from the end + * of the array. + * @param index - The index of the value to overwrite. If the index is + * negative, then it replaces from the end of the array. + * @param value - The value to write into the copied array. + * @returns The copied array with the updated value. + */ + with(index: number, value: T): T[]; +} + +interface ReadonlyArray { // @type-options: no-export + /** + * @returns A copy of an array with its elements reversed. + */ + toReversed(): T[]; + + /** + * Returns a copy of an array with its elements sorted. + * @param compareFn - Function used to determine the order of the elements. It is expected to return + * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive + * value otherwise. If omitted, the elements are sorted in ascending, UTF-16 code unit order. + * ```ts + * [11, 2, 22, 1].toSorted((a, b) => a - b) // [1, 2, 11, 22] + * ``` + */ + toSorted(compareFn?: (a: T, b: T) => number): T[]; + + /** + * Copies an array and removes elements and, if necessary, inserts new elements in their place. Returns the copied array. + * @param start - The zero-based location in the array from which to start removing elements. + * @param deleteCount - The number of elements to remove. + * @param items - Elements to insert into the copied array in place of the deleted elements. + * @returns The copied array. + */ + toSpliced(start: number, deleteCount: number, ...items: T[]): T[]; + /** + * Copies an array and removes elements while returning the remaining elements. + * @param start - The zero-based location in the array from which to start removing elements. + * @param deleteCount - The number of elements to remove. + * @returns A copy of the original array with the remaining elements. + */ + toSpliced(start: number, deleteCount?: number): T[]; + + /** + * Copies an array, then overwrites the value at the provided index with the + * given value. If the index is negative, then it replaces from the end + * of the array. + * @param index - The index of the value to overwrite. If the index is + * negative, then it replaces from the end of the array. + * @param value - The value to write into the copied array. + * @returns The copied array with the updated value. + */ + with(index: number, value: T): T[]; +} + +interface Int8Array { // @type-options: no-export + /** + * @returns A copy of an array with its elements reversed. + */ + toReversed(): Int8Array; + + /** + * Copies and sorts the array. + * @param compareFn - Function used to determine the order of the elements. It is expected to return + * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive + * value otherwise. If omitted, the elements are sorted in ascending order. + * ```ts + * const myNums = Int8Array.from([11, 2, 22, 1]); + * myNums.toSorted((a, b) => a - b) // Int8Array(4) [1, 2, 11, 22] + * ``` + */ + toSorted(compareFn?: (a: number, b: number) => number): Int8Array; + + /** + * Copies the array and inserts the given number at the provided index. + * @param index - The index of the value to overwrite. If the index is + * negative, then it replaces from the end of the array. + * @param value - The value to insert into the copied array. + * @returns A copy of the original array with the inserted value. + */ + with(index: number, value: number): Int8Array; +} + +interface Uint8Array { // @type-options: no-export + /** + * @returns A copy of an array with its elements reversed. + */ + toReversed(): Uint8Array; + + /** + * Copies and sorts the array. + * @param compareFn - Function used to determine the order of the elements. It is expected to return + * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive + * value otherwise. If omitted, the elements are sorted in ascending order. + * ```ts + * const myNums = Uint8Array.from([11, 2, 22, 1]); + * myNums.toSorted((a, b) => a - b) // Uint8Array(4) [1, 2, 11, 22] + * ``` + */ + toSorted(compareFn?: (a: number, b: number) => number): Uint8Array; + + /** + * Copies the array and inserts the given number at the provided index. + * @param index - The index of the value to overwrite. If the index is + * negative, then it replaces from the end of the array. + * @param value - The value to insert into the copied array. + * @returns A copy of the original array with the inserted value. + */ + with(index: number, value: number): Uint8Array; +} + +interface Uint8ClampedArray { // @type-options: no-export + /** + * @returns A copy of an array with its elements reversed. + */ + toReversed(): Uint8ClampedArray; + + /** + * Copies and sorts the array. + * @param compareFn - Function used to determine the order of the elements. It is expected to return + * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive + * value otherwise. If omitted, the elements are sorted in ascending order. + * ```ts + * const myNums = Uint8ClampedArray.from([11, 2, 22, 1]); + * myNums.toSorted((a, b) => a - b) // Uint8ClampedArray(4) [1, 2, 11, 22] + * ``` + */ + toSorted(compareFn?: (a: number, b: number) => number): Uint8ClampedArray; + + /** + * Copies the array and inserts the given number at the provided index. + * @param index - The index of the value to overwrite. If the index is + * negative, then it replaces from the end of the array. + * @param value - The value to insert into the copied array. + * @returns A copy of the original array with the inserted value. + */ + with(index: number, value: number): Uint8ClampedArray; +} + +interface Int16Array { // @type-options: no-export + /** + * @returns A copy of an array with its elements reversed. + */ + toReversed(): Int16Array; + + /** + * Copies and sorts the array. + * @param compareFn - Function used to determine the order of the elements. It is expected to return + * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive + * value otherwise. If omitted, the elements are sorted in ascending order. + * ```ts + * const myNums = Int16Array.from([11, 2, -22, 1]); + * myNums.toSorted((a, b) => a - b) // Int16Array(4) [-22, 1, 2, 11] + * ``` + */ + toSorted(compareFn?: (a: number, b: number) => number): Int16Array; + + /** + * Copies the array and inserts the given number at the provided index. + * @param index - The index of the value to overwrite. If the index is + * negative, then it replaces from the end of the array. + * @param value - The value to insert into the copied array. + * @returns A copy of the original array with the inserted value. + */ + with(index: number, value: number): Int16Array; +} + +interface Uint16Array { // @type-options: no-export + /** + * @returns A copy of an array with its elements reversed. + */ + toReversed(): Uint16Array; + + /** + * Copies and sorts the array. + * @param compareFn - Function used to determine the order of the elements. It is expected to return + * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive + * value otherwise. If omitted, the elements are sorted in ascending order. + * ```ts + * const myNums = Uint16Array.from([11, 2, 22, 1]); + * myNums.toSorted((a, b) => a - b) // Uint16Array(4) [1, 2, 11, 22] + * ``` + */ + toSorted(compareFn?: (a: number, b: number) => number): Uint16Array; + + /** + * Copies the array and inserts the given number at the provided index. + * @param index - The index of the value to overwrite. If the index is + * negative, then it replaces from the end of the array. + * @param value - The value to insert into the copied array. + * @returns A copy of the original array with the inserted value. + */ + with(index: number, value: number): Uint16Array; +} + +interface Int32Array { // @type-options: no-export + /** + * @returns A copy of an array with its elements reversed. + */ + toReversed(): Int32Array; + + /** + * Copies and sorts the array. + * @param compareFn - Function used to determine the order of the elements. It is expected to return + * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive + * value otherwise. If omitted, the elements are sorted in ascending order. + * ```ts + * const myNums = Int32Array.from([11, 2, -22, 1]); + * myNums.toSorted((a, b) => a - b) // Int32Array(4) [-22, 1, 2, 11] + * ``` + */ + toSorted(compareFn?: (a: number, b: number) => number): Int32Array; + + /** + * Copies the array and inserts the given number at the provided index. + * @param index - The index of the value to overwrite. If the index is + * negative, then it replaces from the end of the array. + * @param value - The value to insert into the copied array. + * @returns A copy of the original array with the inserted value. + */ + with(index: number, value: number): Int32Array; +} + +interface Uint32Array { // @type-options: no-export + /** + * @returns A copy of an array with its elements reversed. + */ + toReversed(): Uint32Array; + + /** + * Copies and sorts the array. + * @param compareFn - Function used to determine the order of the elements. It is expected to return + * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive + * value otherwise. If omitted, the elements are sorted in ascending order. + * ```ts + * const myNums = Uint32Array.from([11, 2, 1]); + * myNums.toSorted((a, b) => a - b) // Uint32Array(3) [1, 2, 11] + * ``` + */ + toSorted(compareFn?: (a: number, b: number) => number): Uint32Array; + + /** + * Copies the array and inserts the given number at the provided index. + * @param index - The index of the value to overwrite. If the index is + * negative, then it replaces from the end of the array. + * @param value - The value to insert into the copied array. + * @returns A copy of the original array with the inserted value. + */ + with(index: number, value: number): Uint32Array; +} + +interface Float32Array { // @type-options: no-export + /** + * @returns A copy of an array with its elements reversed. + */ + toReversed(): Float32Array; + + /** + * Copies and sorts the array. + * @param compareFn - Function used to determine the order of the elements. It is expected to return + * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive + * value otherwise. If omitted, the elements are sorted in ascending order. + * ```ts + * const myNums = Float32Array.from([11.25, 2, -22.5, 1]); + * myNums.toSorted((a, b) => a - b) // Float32Array(4) [-22.5, 1, 2, 11.25] + * ``` + */ + toSorted(compareFn?: (a: number, b: number) => number): Float32Array; + + /** + * Copies the array and inserts the given number at the provided index. + * @param index - The index of the value to overwrite. If the index is + * negative, then it replaces from the end of the array. + * @param value - The value to insert into the copied array. + * @returns A copy of the original array with the inserted value. + */ + with(index: number, value: number): Float32Array; +} + +interface Float64Array { // @type-options: no-export + /** + * @returns A copy of an array with its elements reversed. + */ + toReversed(): Float64Array; + + /** + * Copies and sorts the array. + * @param compareFn - Function used to determine the order of the elements. It is expected to return + * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive + * value otherwise. If omitted, the elements are sorted in ascending order. + * ```ts + * const myNums = Float64Array.from([11.25, 2, -22.5, 1]); + * myNums.toSorted((a, b) => a - b) // Float64Array(4) [-22.5, 1, 2, 11.25] + * ``` + */ + toSorted(compareFn?: (a: number, b: number) => number): Float64Array; + + /** + * Copies the array and inserts the given number at the provided index. + * @param index - The index of the value to overwrite. If the index is + * negative, then it replaces from the end of the array. + * @param value - The value to insert into the copied array. + * @returns A copy of the original array with the inserted value. + */ + with(index: number, value: number): Float64Array; +} + +interface BigInt64Array { // @type-options: no-export + /** + * @returns A copy of an array with its elements reversed. + */ + toReversed(): BigInt64Array; + + /** + * Copies and sorts the array. + * @param compareFn - Function used to determine the order of the elements. It is expected to return + * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive + * value otherwise. If omitted, the elements are sorted in ascending order. + * ```ts + * const myNums = BigInt64Array.from([11n, 2n, -22n, 1n]); + * myNums.toSorted((a, b) => Number(a - b)) // BigInt64Array(4) [-22n, 1n, 2n, 11n] + * ``` + */ + toSorted(compareFn?: (a: bigint, b: bigint) => number): BigInt64Array; + + /** + * Copies the array and inserts the given bigint at the provided index. + * @param index - The index of the value to overwrite. If the index is + * negative, then it replaces from the end of the array. + * @param value - The value to insert into the copied array. + * @returns A copy of the original array with the inserted value. + */ + with(index: number, value: bigint): BigInt64Array; +} + +interface BigUint64Array { // @type-options: no-export + /** + * @returns A copy of an array with its elements reversed. + */ + toReversed(): BigUint64Array; + + /** + * Copies and sorts the array. + * @param compareFn - Function used to determine the order of the elements. It is expected to return + * a negative value if the first argument is less than the second argument, zero if they're equal, and a positive + * value otherwise. If omitted, the elements are sorted in ascending order. + * ```ts + * const myNums = BigUint64Array.from([11n, 2n, 22n, 1n]); + * myNums.toSorted((a, b) => Number(a - b)) // BigUint64Array(4) [1n, 2n, 11n, 22n] + * ``` + */ + toSorted(compareFn?: (a: bigint, b: bigint) => number): BigUint64Array; + + /** + * Copies the array and inserts the given bigint at the provided index. + * @param index - The index of the value to overwrite. If the index is + * negative, then it replaces from the end of the array. + * @param value - The value to insert into the copied array. + * @returns A copy of the original array with the inserted value. + */ + with(index: number, value: bigint): BigUint64Array; +} diff --git a/packages/core-js-types/src/base/proposals/collection-of-from.d.ts b/packages/core-js-types/src/base/proposals/collection-of-from.d.ts new file mode 100644 index 000000000000..04d97728a9cb --- /dev/null +++ b/packages/core-js-types/src/base/proposals/collection-of-from.d.ts @@ -0,0 +1,86 @@ +// https://github.com/tc39/proposal-setmap-offrom + +interface MapConstructor { + /** + * Creates a new `Map` instance from an iterable object of [key, value] pairs. + * Optionally, applies a mapping function to each pair. + * @param source - Iterable object of [key, value] pairs. + * @param mapFn - Function to call on every [key, value] pair before adding to the `Map`. + * @param thisArg - Value to use as this when executing mapFn. + * @returns A new `Map` instance. + */ + from(source: Iterable<[K, V]>, mapFn?: (entry: [K, V], index: number) => [KOut, VOut], thisArg?: any): Map; + + /** + * Creates a new `Map` instance from a variable number of arguments, + * where each pair of arguments is interpreted as a key and a value. + * @param items - An even number of arguments representing key-value pairs. + * @returns A new `Map` instance. + */ + of(...items: [K, V][]): Map; +} + +declare var Map: MapConstructor; + +interface SetConstructor { + /** + * Creates a new `Set` instance from an iterable, optionally transforming elements with a mapping function. + * @param source - Iterable whose elements will be added to the new Set. + * @param mapFn - Optional mapping function. Transforms each element before adding to Set. + * @param thisArg - Value to use as `this` when executing `mapFn`. + * @returns A new `Set` instance + */ + from(source: Iterable, mapFn?: (value: T, index: number) => U, thisArg?: any): Set; + + /** + * Creates a new `Set` instance from a variable number of arguments. + * Each argument becomes an element of the Set. + * @param items - Zero or more arguments to add as Set elements. + * @returns A new `Set` instance + */ + of(...items: T[]): Set; +} + +declare var Set: SetConstructor; + +interface WeakMapConstructor { + /** + * Creates a new `WeakMap` instance from an iterable object of [key, value] pairs. + * Optionally, applies a mapping function to each pair. + * @param source - Iterable object of [key, value] pairs. + * @param mapFn - Function to call on every [key, value] pair before adding to the `WeakMap`. + * @param thisArg - Value to use as this when executing mapFn. + * @returns A new `WeakMap` instance. + */ + from(source: Iterable<[K, V]>, mapFn?: (entry: [K, V], index: number) => [KOut, VOut], thisArg?: any): WeakMap; + + /** + * Creates a new `WeakMap` instance from a variable number of arguments, + * where each pair of arguments is interpreted as a key and a value. + * @param items - An even number of arguments representing key-value pairs. + * @returns A new `WeakMap` instance. + */ + of(...items: [K, V][]): WeakMap; +} + +declare var WeakMap: WeakMapConstructor; + +interface WeakSetConstructor { + /** + * Creates a new `WeakSet` instance from an iterable of objects, optionally transforming with mapFn. + * @param source - Iterable of objects to add to WeakSet. + * @param mapFn - Optional mapping function transforming each object. + * @param thisArg - Value to use as `this` in `mapFn`. + * @returns New `WeakSet` instance. + */ + from(source: Iterable, mapFn?: (value: T, index: number) => U, thisArg?: any): WeakSet; + + /** + * Creates a new `WeakSet` instance from object arguments. + * @param items - Zero or more objects to add as WeakSet elements. + * @returns New `WeakSet` instance. + */ + of(...items: T[]): WeakSet; +} + +declare var WeakSet: WeakSetConstructor; diff --git a/packages/core-js-types/src/base/proposals/data-view-get-set-uint8-clamped.d.ts b/packages/core-js-types/src/base/proposals/data-view-get-set-uint8-clamped.d.ts new file mode 100644 index 000000000000..6d4e0504a5af --- /dev/null +++ b/packages/core-js-types/src/base/proposals/data-view-get-set-uint8-clamped.d.ts @@ -0,0 +1,19 @@ +// https://github.com/tc39/proposal-dataview-get-set-uint8clamped + +interface DataView { // @type-options: no-constructor + /** + * Reads an unsigned 8-bit integer at the specified byte offset from the DataView, + * interpreting the byte as a clamped 8-bit unsigned value (same as Uint8ClampedArray). + * @param byteOffset - The offset, in bytes, from the start of the DataView. + * @returns The unsigned 8-bit integer at the given offset. + */ + getUint8Clamped(byteOffset: number): number; + + /** + * Stores a value as an unsigned 8-bit integer at the specified byte offset in the DataView, + * clamping the input to the 0–255 range and rounding to the nearest integer as per Uint8ClampedArray behavior. + * @param byteOffset - The offset, in bytes, from the start of the DataView. + * @param value - The value to store; it will be clamped to the range 0–255 and rounded to the nearest integer. + */ + setUint8Clamped(byteOffset: number, value: number): void; +} diff --git a/packages/core-js-types/src/base/proposals/decorator-metadata.d.ts b/packages/core-js-types/src/base/proposals/decorator-metadata.d.ts new file mode 100644 index 000000000000..93fc1af3f423 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/decorator-metadata.d.ts @@ -0,0 +1,12 @@ +/// + +// https://github.com/tc39/proposal-decorator-metadata + +interface SymbolConstructor { + readonly metadata: unique symbol; +} + +interface Function { + // eslint-disable-next-line es/no-nonstandard-symbol-properties -- safe + [Symbol.metadata]: CoreJS.CoreJSDecoratorMetadataObject | null; +} diff --git a/packages/core-js-types/src/base/proposals/error-cause.d.ts b/packages/core-js-types/src/base/proposals/error-cause.d.ts new file mode 100644 index 000000000000..b89ebbb8d7f0 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/error-cause.d.ts @@ -0,0 +1,69 @@ +// https://github.com/tc39/proposal-error-cause + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/d3be7e171bf3149fe93c3ce5a85280f1eba3ef8d/src/lib/es2022.error.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface ErrorOptions { // @type-options: no-extends, no-prefix, no-redefine + cause?: unknown; +} + +interface Error { + cause?: unknown; // ts <= 4.7 Error | undefined +} + +interface ErrorConstructor { // @type-options: no-redefine + new(message?: string, options?: ErrorOptions): Error; + + (message?: string, options?: ErrorOptions): Error; +} + +interface EvalErrorConstructor { // @type-options: no-export + new(message?: string, options?: ErrorOptions): EvalError; + + (message?: string, options?: ErrorOptions): EvalError; +} + +interface RangeErrorConstructor { // @type-options: no-export + new(message?: string, options?: ErrorOptions): RangeError; + + (message?: string, options?: ErrorOptions): RangeError; +} + +interface ReferenceErrorConstructor { // @type-options: no-export + new(message?: string, options?: ErrorOptions): ReferenceError; + + (message?: string, options?: ErrorOptions): ReferenceError; +} + +interface SyntaxErrorConstructor { // @type-options: no-export + new(message?: string, options?: ErrorOptions): SyntaxError; + + (message?: string, options?: ErrorOptions): SyntaxError; +} + +interface TypeErrorConstructor { // @type-options: no-export + new(message?: string, options?: ErrorOptions): TypeError; + + (message?: string, options?: ErrorOptions): TypeError; +} + +interface URIErrorConstructor { // @type-options: no-export + new(message?: string, options?: ErrorOptions): URIError; + + (message?: string, options?: ErrorOptions): URIError; +} + +interface AggregateError extends Error { // @type-options: no-redefine + errors: any[]; + + cause?: unknown; +} + +interface AggregateErrorConstructor extends ErrorConstructor { + new (errors: Iterable, message?: string, options?: ErrorOptions): AggregateError; + (errors: Iterable, message?: string, options?: ErrorOptions): AggregateError; + readonly prototype: AggregateError; +} + +declare var AggregateError: AggregateErrorConstructor; diff --git a/packages/core-js-types/src/base/proposals/explicit-resource-management.d.ts b/packages/core-js-types/src/base/proposals/explicit-resource-management.d.ts new file mode 100644 index 000000000000..edd81c706bd4 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/explicit-resource-management.d.ts @@ -0,0 +1,176 @@ +// https://github.com/tc39/proposal-explicit-resource-management + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/0a1aa6d6ebdfa16b82f4a6aaf282089b1d484e05/src/lib/esnext.disposable.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface SymbolConstructor { + /** + * A method that is used to release resources held by an object. Called by the semantics of the `using` statement. + */ + readonly dispose: unique symbol; + + /** + * A method that is used to asynchronously release resources held by an object. Called by the semantics of the `await using` statement. + */ + readonly asyncDispose: unique symbol; +} + +interface Disposable { // @type-options: no-constructor + [Symbol.dispose](): void; +} + +interface AsyncDisposable { // @type-options: no-constructor + [Symbol.asyncDispose](): PromiseLike; +} + +interface SuppressedError extends Error { + error: any; + suppressed: any; +} + +interface SuppressedErrorConstructor { + new (error: any, suppressed: any, message?: string): SuppressedError; + + (error: any, suppressed: any, message?: string): SuppressedError; + + readonly prototype: SuppressedError; +} + +declare var SuppressedError: SuppressedErrorConstructor; + +interface DisposableStack { + /** + * Returns a value indicating whether this stack has been disposed. + */ + readonly disposed: boolean; + + /** + * Disposes each resource in the stack in the reverse order that they were added. + */ + dispose(): void; + + /** + * Adds a disposable resource to the stack, returning the resource. + * @param value - The resource to add. `null` and `undefined` will not be added, but will be returned. + * @returns The provided {@link value}. + */ + use(value: T): T; + + /** + * Adds a value and associated disposal callback as a resource to the stack. + * @param value - The value to add. + * @param onDispose - The callback to use in place of a `[Symbol.dispose]()` method. Will be invoked with `value` + * as the first parameter. + * @returns The provided {@link value}. + */ + adopt(value: T, onDispose: (value: T) => void): T; + + /** + * Adds a callback to be invoked when the stack is disposed. + */ + defer(onDispose: () => void): void; + + /** + * Move all resources out of this stack and into a new `DisposableStack`, and marks this stack as disposed. + * @example + * ```ts + * class C { + * #res1: Disposable; + * #res2: Disposable; + * #disposables: DisposableStack; + * constructor() { + * // stack will be disposed when exiting constructor for any reason + * using stack = new DisposableStack(); + * + * // get first resource + * this.#res1 = stack.use(getResource1()); + * + * // get second resource. If this fails, both `stack` and `#res1` will be disposed. + * this.#res2 = stack.use(getResource2()); + * + * // all operations succeeded, move resources out of `stack` so that they aren't disposed + * // when constructor exits + * this.#disposables = stack.move(); + * } + * + * [Symbol.dispose]() { + * this.#disposables.dispose(); + * } + * } + * ``` + */ + move(): DisposableStack; + + [Symbol.dispose](): void; + + readonly [Symbol.toStringTag]: string; +} + +interface DisposableStackConstructor { + new (): DisposableStack; + + readonly prototype: DisposableStack; +} + +declare var DisposableStack: DisposableStackConstructor; + +interface AsyncDisposableStack { + /** + * Returns a value indicating whether this stack has been disposed. + */ + readonly disposed: boolean; + + /** + * Disposes each resource in the stack in the reverse order that they were added. + */ + disposeAsync(): Promise; + + /** + * Adds a disposable resource to the stack, returning the resource. + * @param value - The resource to add. `null` and `undefined` will not be added, but will be returned. + * @returns The provided {@link value}. + */ + use(value: T): T; + + /** + * Adds a value and associated disposal callback as a resource to the stack. + * @param value - The value to add. + * @param onDisposeAsync - The callback to use in place of a `[Symbol.asyncDispose]()` method. Will be invoked with `value` + * as the first parameter. + * @returns The provided {@link value}. + */ + adopt(value: T, onDisposeAsync: (value: T) => PromiseLike | void): T; + + /** + * Adds a callback to be invoked when the stack is disposed. + */ + defer(onDisposeAsync: () => PromiseLike | void): void; + + /** + * Move all resources out of this stack and into a new `AsyncDisposableStack`, and marks this stack as disposed. + */ + move(): AsyncDisposableStack; + + [Symbol.asyncDispose](): Promise; // @type-options: prefix-return-type + + readonly [Symbol.toStringTag]: string; +} + +interface AsyncDisposableStackConstructor { + new (): AsyncDisposableStack; + + readonly prototype: AsyncDisposableStack; +} + +declare var AsyncDisposableStack: AsyncDisposableStackConstructor; + +interface IteratorObject extends Disposable {} // @type-options: no-extends + +interface AsyncIteratorObject extends AsyncDisposable {} // @type-options: no-extends + +interface AsyncIteratorConstructor {} + +declare var AsyncIterator: AsyncIteratorConstructor; + +interface AsyncIterator {} diff --git a/packages/core-js-types/src/base/proposals/float16.d.ts b/packages/core-js-types/src/base/proposals/float16.d.ts new file mode 100644 index 000000000000..c431b98be387 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/float16.d.ts @@ -0,0 +1,31 @@ +// https://github.com/tc39/proposal-float16array + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/d3be7e171bf3149fe93c3ce5a85280f1eba3ef8d/src/lib/esnext.float16.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface Math { // @type-options: no-constructor + /** + * Returns the nearest half precision float representation of a number. + * @param x - A numeric expression. + */ + f16round(x: number): number; +} + +interface DataView { // @type-options: no-constructor + /** + * Gets the Float16 value at the specified byte offset from the start of the view. There is + * no alignment constraint; multibyte values may be fetched from any offset. + * @param byteOffset - The place in the buffer at which the value should be retrieved. + * @param littleEndian - If false or undefined, a big-endian value should be read. + */ + getFloat16(byteOffset: number, littleEndian?: boolean): number; + + /** + * Stores a Float16 value at the specified byte offset from the start of the view. + * @param byteOffset - The place in the buffer at which the value should be set. + * @param value - The value to set. + * @param littleEndian - If false or undefined, a big-endian value should be written. + */ + setFloat16(byteOffset: number, value: number, littleEndian?: boolean): void; +} diff --git a/packages/core-js-types/src/base/proposals/function-demethodize.d.ts b/packages/core-js-types/src/base/proposals/function-demethodize.d.ts new file mode 100644 index 000000000000..e65831a86423 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/function-demethodize.d.ts @@ -0,0 +1,9 @@ +// https://github.com/js-choi/proposal-function-demethodize + +interface Function { // @type-options: no-constructor + /** + * Creates a function that calls the original with its first argument as `this` and the rest as regular arguments. + * @returns A new function that applies the original function with its `this` set to the first argument. + */ + demethodize(this: (this: T, ...args: Args) => R): (thisArg: T, ...args: Args) => R; +} diff --git a/packages/core-js-types/src/base/proposals/is-error.d.ts b/packages/core-js-types/src/base/proposals/is-error.d.ts new file mode 100644 index 000000000000..c69cee1fe3ab --- /dev/null +++ b/packages/core-js-types/src/base/proposals/is-error.d.ts @@ -0,0 +1,12 @@ +// https://github.com/tc39/proposal-is-error + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/4a957b74ea4d716356181644d23f6ad5f10824d6/src/lib/esnext.error.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface ErrorConstructor { // @type-options: no-redefine + /** + * Indicates whether the argument provided is a built-in Error instance or not. + */ + isError(value: any): value is Error; +} diff --git a/packages/core-js-types/src/base/proposals/iterator-chunking.d.ts b/packages/core-js-types/src/base/proposals/iterator-chunking.d.ts new file mode 100644 index 000000000000..7c56fd26ffa7 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/iterator-chunking.d.ts @@ -0,0 +1,21 @@ +/// + +// https://github.com/tc39/proposal-iterator-chunking + +interface Iterator { + /** + * Yields arrays containing up to the specified number of elements + * chunked from the source iterator. + * @param chunkSize - The maximum number of elements per chunk. Must be a positive integer. + * @returns An iterator yielding arrays of at most `chunkSize` elements from the source iterator. + */ + chunks(chunkSize: number): IteratorObject; + + /** + * Yields overlapping arrays (windows) of the given size from the iterator. + * @param windowSize - The size of each window. Must be a positive integer. + * @param undersized - 'only-full' (default) to yield only full windows | 'allow-partial' to yield all windows. + * @returns An iterator yielding arrays of the specified window size. + */ + windows(windowSize: number, undersized?: 'only-full' | 'allow-partial' | undefined): IteratorObject; +} diff --git a/packages/core-js-types/src/base/proposals/iterator-helpers-custom.d.ts b/packages/core-js-types/src/base/proposals/iterator-helpers-custom.d.ts new file mode 100644 index 000000000000..31749fc7ac57 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/iterator-helpers-custom.d.ts @@ -0,0 +1,17 @@ +// Motivation: Custom type needed to keep generics strict + +// https://github.com/tc39/proposal-iterator-helpers + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/d3be7e171bf3149fe93c3ce5a85280f1eba3ef8d/src/lib/esnext.iterator.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +declare namespace CoreJS { + interface IteratorObject extends Iterator {} + + export type IteratorFlatMap = (callback: (value: T, index: number) => Iterator | Iterable) => IteratorObject; + + export type IteratorMap = (callbackfn: (value: T, index: number) => U) => IteratorObject; + + export type IteratorReduce = (callbackfn: (previousValue: U, currentValue: T, currentIndex: number) => U, initialValue?: U) => U; +} diff --git a/packages/core-js-types/src/base/proposals/iterator-helpers.d.ts b/packages/core-js-types/src/base/proposals/iterator-helpers.d.ts new file mode 100644 index 000000000000..033f76342dd2 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/iterator-helpers.d.ts @@ -0,0 +1,109 @@ +/// + +// https://github.com/tc39/proposal-iterator-helpers + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/d3be7e171bf3149fe93c3ce5a85280f1eba3ef8d/src/lib/esnext.iterator.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt +interface Iterator { + /** + * Creates an iterator whose values are the result of applying the callback to the values from this iterator. + * @param callbackfn - A function that accepts up to two arguments to be used to transform values from the underlying iterator. + */ + map(callbackfn: (value: T, index: number) => U): IteratorObject; + + /** + * Creates an iterator whose values are those from this iterator for which the provided predicate returns true. + * @param predicate - A function that accepts up to two arguments to be used to test values from the underlying iterator. + */ + filter(predicate: (value: T, index: number) => value is S): IteratorObject; + /** + * Creates an iterator whose values are those from this iterator for which the provided predicate returns true. + * @param predicate - A function that accepts up to two arguments to be used to test values from the underlying iterator. + */ + filter(predicate: (value: T, index: number) => unknown): IteratorObject; + + /** + * Creates an iterator whose values are the values from this iterator, stopping once the provided limit is reached. + * @param limit - The maximum number of values to yield. + */ + take(limit: number): IteratorObject; + + /** + * Creates an iterator whose values are the values from this iterator after skipping the provided count. + * @param count - The number of values to drop. + */ + drop(count: number): IteratorObject; + + /** + * Creates an iterator whose values are the result of applying the callback to the values from this iterator and then flattening the resulting iterators or iterables. + * @param callback - A function that accepts up to two arguments to be used to transform values from the underlying iterator into new iterators or iterables to be flattened into the result. + */ + flatMap(callback: (value: T, index: number) => Iterator | Iterable): IteratorObject; + + /** + * Calls the specified callback function for all the elements in this iterator. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn - A function that accepts up to three arguments. The reduce method calls the callbackfn function one time for each element in the iterator. + */ + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number) => T): T; + /** + * Calls the specified callback function for all the elements in this iterator. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn - A function that accepts up to three arguments. The reduce method calls the callbackfn function one time for each element in the iterator. + * @param initialValue - If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of a value from the iterator. + */ + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number) => T, initialValue: T): T; + /** + * Calls the specified callback function for all the elements in this iterator. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn - A function that accepts up to three arguments. The reduce method calls the callbackfn function one time for each element in the iterator. + * @param initialValue - If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of a value from the iterator. + */ + reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number) => U, initialValue: U): U; + + /** + * Creates a new array from the values yielded by this iterator. + */ + toArray(): T[]; + + /** + * Performs the specified action for each element in the iterator. + * @param callbackfn - A function that accepts up to two arguments. forEach calls the callbackfn function one time for each element in the iterator. + */ + forEach(callbackfn: (value: T, index: number) => void): void; + + /** + * Determines whether the specified callback function returns true for any element of this iterator. + * @param predicate - A function that accepts up to two arguments. The `some` method calls + * the predicate function for each element in this iterator until the predicate returns a value + * true, or until the end of the iterator. + */ + some(predicate: (value: T, index: number) => unknown): boolean; + + /** + * Determines whether all the members of this iterator satisfy the specified test. + * @param predicate - A function that accepts up to two arguments. The every method calls + * the predicate function for each element in this iterator until the predicate returns + * false, or until the end of this iterator. + */ + every(predicate: (value: T, index: number) => unknown): boolean; + + /** + * Returns the value of the first element in this iterator where predicate is true, and undefined + * otherwise. + * @param predicate - find calls predicate once for each element of this iterator, in + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + */ + find(predicate: (value: T, index: number) => value is S): S | undefined; + find(predicate: (value: T, index: number) => unknown): T | undefined; +} + +interface IteratorConstructor { // @type-options: no-extends + /** + * Creates a native iterator from an iterator or iterable object. + * Returns its input if the input already inherits from the built-in Iterator class. + * @param value - An iterator or iterable object to convert to a native iterator. + */ + from(value: Iterator | Iterable): IteratorObject; +} + +declare var Iterator: IteratorConstructor; diff --git a/packages/core-js-types/src/base/proposals/iterator-join.d.ts b/packages/core-js-types/src/base/proposals/iterator-join.d.ts new file mode 100644 index 000000000000..29fc4f2dda57 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/iterator-join.d.ts @@ -0,0 +1,9 @@ +// https://github.com/bakkot/proposal-iterator-join + +interface Iterator { + /** + * Creates a string by concatenating all elements provided by the iterator, separated by the specified separator. + * @param separator - A string to separate each element. If omitted, the elements are separated by commas. + */ + join(separator?: unknown): string; +} diff --git a/packages/core-js-types/src/base/proposals/iterator-joint.d.ts b/packages/core-js-types/src/base/proposals/iterator-joint.d.ts new file mode 100644 index 000000000000..e70a73fd1803 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/iterator-joint.d.ts @@ -0,0 +1,40 @@ +// https://github.com/tc39/proposal-joint-iteration + +interface ZipOptions { + mode?: 'shortest' | 'longest' | 'strict'; + + padding?: Iterable; +} + +interface ZipKeyedOptions { + mode?: 'shortest' | 'longest' | 'strict'; + + padding?: Record; +} + +interface IteratorConstructor { // @type-options: no-extends + /** + * Takes an iterable of iterables and produces an iterable of arrays where position corresponds + * to position in the passed iterable. + * @param iterables - An Iterable of iterables. + * @param options - Optional object: + * - mode: 'shortest' (default) to stop at the shortest iterable | 'longest' to stop at the longest iterable | 'strict' to throw if iterables are not the same length; + * - padding: an iterable specifying padding values for each position when mode is 'longest'. + * @returns An iterator yielding arrays of values, collected one from each iterable. + */ + zip[]>(iterables: T, options?: ZipOptions): IteratorObject<{ [K in keyof T]: T[K] extends Iterable ? V : never }, undefined, unknown>; // @type-options: prefix-return-type + zip(iterables: Iterable>, options?: ZipOptions): IteratorObject; // @type-options: prefix-return-type + + /** + * Takes an object whose values are iterables and produces an iterable of objects where keys + * correspond to keys in the passed object. + * @param record - An object of iterables. + * @param options - Optional object: + * - mode: 'shortest' (default) to stop at the shortest iterable | 'longest' to stop at the longest iterable | 'strict' to throw if iterables are not the same length; + * - padding: an object specifying padding values for each key when mode is 'longest'. + * @returns An iterator yielding objects with keys from the input record and values from the corresponding iterables. + */ + zipKeyed }>(record: T, options?: ZipKeyedOptions): IteratorObject<{ [K in keyof T]: T[K] extends Iterable ? V : never; }, undefined, unknown>; // @type-options: prefix-return-type +} + +declare var Iterator: IteratorConstructor; diff --git a/packages/core-js-types/src/base/proposals/iterator-range.d.ts b/packages/core-js-types/src/base/proposals/iterator-range.d.ts new file mode 100644 index 000000000000..542c88632f9d --- /dev/null +++ b/packages/core-js-types/src/base/proposals/iterator-range.d.ts @@ -0,0 +1,33 @@ +// https://github.com/tc39/proposal-iterator.range + +interface IteratorRangeOptions { + step?: T; + + inclusive?: boolean; +} + +interface IteratorConstructor { // @type-options: no-extends + /** + * Returns an iterator that generates a sequence of numbers within a range. + * @param start - The starting value of the sequence. + * @param end - The end value of the sequence (exclusive by default). + * @param options - Optional object: + * - step: The difference between consecutive values (default is 1). + * - inclusive: If true, the end value is included in the range (default is false). + * @returns An iterator of numbers. + */ + range(start: number, end: number | typeof Infinity | typeof Number.NEGATIVE_INFINITY, options?: number | IteratorRangeOptions): IteratorObject; // @type-options: prefix-return-type + + /** + * Returns an iterator that generates a sequence of bigints within a range. + * @param start - The starting value of the sequence. + * @param end - The end value of the sequence (exclusive by default). + * @param options - Optional object: + * - step: The difference between consecutive values (default is 1n). + * - inclusive: If true, the end value is included in the range (default is false). + * @returns An iterator of bigints. + */ + range(start: bigint, end: bigint, options?: bigint | IteratorRangeOptions): IteratorObject; // @type-options: prefix-return-type +} + +declare var Iterator: IteratorConstructor; diff --git a/packages/core-js-types/src/base/proposals/iterator-sequencing.d.ts b/packages/core-js-types/src/base/proposals/iterator-sequencing.d.ts new file mode 100644 index 000000000000..73beb4292269 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/iterator-sequencing.d.ts @@ -0,0 +1,14 @@ +/// + +// https://github.com/tc39/proposal-iterator-sequencing + +interface IteratorConstructor { // @type-options: no-extends + /** + * Creates an iterator that sequentially yields values from the provided iterables. + * @param iterators - The iterables to concatenate. + * @returns An iterator yielding values from each input iterable in sequence. + */ + concat[]>(...iterators: T): IteratorObject ? V : never, undefined, unknown>; +} + +declare var Iterator: IteratorConstructor; diff --git a/packages/core-js-types/src/base/proposals/json-parse-with-source.d.ts b/packages/core-js-types/src/base/proposals/json-parse-with-source.d.ts new file mode 100644 index 000000000000..2d56d5e072aa --- /dev/null +++ b/packages/core-js-types/src/base/proposals/json-parse-with-source.d.ts @@ -0,0 +1,40 @@ +// https://github.com/tc39/proposal-json-parse-with-source + +interface CoreJSReviverContext { // @type-options: no-extends, no-prefix + readonly __brand: unique symbol; + + readonly source: string | undefined; +} + +interface CoreJSRawJSON { // @type-options: no-extends, no-prefix + readonly __brand: unique symbol; + + readonly rawJSON: string; +} + +interface JSON { // @type-options: no-constructor + /** + * Determines whether a value is a RawJSON object. + * @param value - The value to check. + * @returns True if the value is a RawJSON object; otherwise, false. + */ + isRawJSON(value: any): value is CoreJSRawJSON; + + /** + * Parses a JSON string, allowing the reviver function to access + * the exact source text and position of each parsed value. + * @param text - The JSON string to parse. + * @param reviver - A function that transforms the results. It is called for each member of the object. + * The function receives three arguments: the key, the value, and a context object + * containing the source text and position. + * @returns Parsed JavaScript value. + */ + parse(text: string, reviver?: (key: string, value: any, context: CoreJSReviverContext) => any): any; + + /** + * Creates a RawJSON object from a JSON string. + * @param value - The JSON string. + * @returns A RawJSON object encapsulating the provided JSON string. + */ + rawJSON(value: string): CoreJSRawJSON; +} diff --git a/packages/core-js-types/src/base/proposals/map-upsert.d.ts b/packages/core-js-types/src/base/proposals/map-upsert.d.ts new file mode 100644 index 000000000000..bfbf2fbd746a --- /dev/null +++ b/packages/core-js-types/src/base/proposals/map-upsert.d.ts @@ -0,0 +1,43 @@ +// https://github.com/tc39/proposal-upsert + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/cdc205d5e6338d96b0fb54657af33d473d480a9c/src/lib/esnext.collection.d.ts#L15 +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface Map { // @type-options: no-redefine + /** + * Returns a specified element from the Map object. + * If no element is associated with the specified key, a new element with the value `defaultValue` will be inserted into the Map and returned. + * @param key - The key of the element to return. + * @param defaultValue - The value to insert if the key is not already associated with an element. + * @returns The element associated with the specified key, which will be `defaultValue` if no element previously existed. + */ + getOrInsert(key: K, defaultValue: V): V; + /** + * Returns a specified element from the Map object. + * If no element is associated with the specified key, the result of passing the specified key to the `callback` function will be inserted into the Map and returned. + * @param key - The key of the element to return. + * @param callback - A function that computes the value to insert if the key is not already associated with an element. It will be passed the key as an argument. + * @returns The element associated with the specified key, which will be the newly computed value if no element previously existed. + */ + getOrInsertComputed(key: K, callback: (key: K) => V): V; +} + +interface WeakMap { // @type-options: no-redefine + /** + * Returns a specified element from the WeakMap object. + * If no element is associated with the specified key, a new element with the value `defaultValue` will be inserted into the WeakMap and returned. + * @param key - The key of the element to return. + * @param defaultValue - The value to insert if the key is not already associated with an element. + * @returns The element associated with the specified key, which will be `defaultValue` if no element previously existed. + */ + getOrInsert(key: K, defaultValue: V): V; + /** + * Returns a specified element from the WeakMap object. + * If no element is associated with the specified key, the result of passing the specified key to the `callback` function will be inserted into the WeakMap and returned. + * @param key - The key of the element to return. + * @param callback - A function that computes the value to insert if the key is not already associated with an element. It will be passed the key as an argument. + * @returns The element associated with the specified key, which will be the newly computed value if no element previously existed. + */ + getOrInsertComputed(key: K, callback: (key: K) => V): V; +} diff --git a/packages/core-js-types/src/base/proposals/math-sum.d.ts b/packages/core-js-types/src/base/proposals/math-sum.d.ts new file mode 100644 index 000000000000..61645f9d8a2b --- /dev/null +++ b/packages/core-js-types/src/base/proposals/math-sum.d.ts @@ -0,0 +1,9 @@ +// https://github.com/tc39/proposal-math-sum +interface Math { // @type-options: no-constructor + /** + * Returns the sum of all given values. + * @param items - An iterable of numbers to sum. + * @returns The sum of all given values. + */ + sumPrecise(items: Iterable): number; +} diff --git a/packages/core-js-types/src/base/proposals/number-clamp.d.ts b/packages/core-js-types/src/base/proposals/number-clamp.d.ts new file mode 100644 index 000000000000..5531ce8facab --- /dev/null +++ b/packages/core-js-types/src/base/proposals/number-clamp.d.ts @@ -0,0 +1,11 @@ +// https://github.com/tc39/proposal-math-clamp + +interface Number { // @type-options: export-base-constructor + /** + * Clamps the number within the inclusive lower and upper bounds. + * @param lower - The lower bound. + * @param upper - The upper bound. + * @returns The clamped number. + */ + clamp(lower: number, upper: number): number; +} diff --git a/packages/core-js-types/src/base/proposals/object-from-entries.d.ts b/packages/core-js-types/src/base/proposals/object-from-entries.d.ts new file mode 100644 index 000000000000..a47651b17412 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/object-from-entries.d.ts @@ -0,0 +1,19 @@ +// https://github.com/tc39/proposal-object-from-entries + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/d8aafb3197ebecd7faf919eaa39e77c5805cbff8/src/lib/es2019.object.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface ObjectConstructor { + /** + * Returns an object created by key-value entries for properties and methods + * @param entries - An iterable object that contains key-value entries for properties and methods. + */ + fromEntries(entries: Iterable): { [k: string]: T; }; + + /** + * Returns an object created by key-value entries for properties and methods + * @param entries - An iterable object that contains key-value entries for properties and methods. + */ + fromEntries(entries: Iterable): any; +} diff --git a/packages/core-js-types/src/base/proposals/object-get-own-property-descriptors.d.ts b/packages/core-js-types/src/base/proposals/object-get-own-property-descriptors.d.ts new file mode 100644 index 000000000000..d4827790665c --- /dev/null +++ b/packages/core-js-types/src/base/proposals/object-get-own-property-descriptors.d.ts @@ -0,0 +1,15 @@ +// https://github.com/tc39/proposal-object-getownpropertydescriptors + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/af3a3779de6bc27619c85077e1b4d1de8feddd35/src/lib/es2017.object.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface ObjectConstructor { + /** + * Returns an object containing all own property descriptors of an object + * @param o - Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. + */ + getOwnPropertyDescriptors(o: T): { [P in keyof T]: TypedPropertyDescriptor; } & { + [x: string]: PropertyDescriptor; + }; +} diff --git a/packages/core-js-types/src/base/proposals/object-keys-length.d.ts b/packages/core-js-types/src/base/proposals/object-keys-length.d.ts new file mode 100644 index 000000000000..1d6054e86821 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/object-keys-length.d.ts @@ -0,0 +1,9 @@ +// https://github.com/tc39/proposal-object-keys-length + +interface ObjectConstructor { + /** + * Returns the number of enumerable own properties of an object + * @param o - Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. + */ + keysLength(o: {}): number; +} diff --git a/packages/core-js-types/src/base/proposals/object-values-entries.d.ts b/packages/core-js-types/src/base/proposals/object-values-entries.d.ts new file mode 100644 index 000000000000..12fb5ad4d235 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/object-values-entries.d.ts @@ -0,0 +1,29 @@ +// https://github.com/tc39/proposal-object-values-entries + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/af3a3779de6bc27619c85077e1b4d1de8feddd35/src/lib/es2017.object.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface ObjectConstructor { + /** + * Returns an array of values of the enumerable own properties of an object + * @param o - Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. + */ + values(o: { [s: string]: T; } | ArrayLike): T[]; + /** + * Returns an array of values of the enumerable own properties of an object + * @param o - Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. + */ + values(o: {}): any[]; + + /** + * Returns an array of key/values of the enumerable own properties of an object + * @param o - Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. + */ + entries(o: { [s: string]: T; } | ArrayLike): [string, T][]; + /** + * Returns an array of key/values of the enumerable own properties of an object + * @param o - Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. + */ + entries(o: {}): [string, any][]; +} diff --git a/packages/core-js-types/src/base/proposals/pattern-matching.d.ts b/packages/core-js-types/src/base/proposals/pattern-matching.d.ts new file mode 100644 index 000000000000..c33c71983bf3 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/pattern-matching.d.ts @@ -0,0 +1,5 @@ +// https://github.com/tc39/proposal-pattern-matching + +interface SymbolConstructor { + readonly customMatcher: unique symbol; +} diff --git a/packages/core-js-types/src/base/proposals/promise-all-settled.d.ts b/packages/core-js-types/src/base/proposals/promise-all-settled.d.ts new file mode 100644 index 000000000000..673706f487eb --- /dev/null +++ b/packages/core-js-types/src/base/proposals/promise-all-settled.d.ts @@ -0,0 +1,25 @@ +/// + +// https://github.com/tc39/proposal-promise-allSettled + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/2a90a739c1c1e87e3c3d0c93e16f7e5baadf8035/src/lib/es2020.promise.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface PromiseConstructor { + /** + * Creates a Promise that is resolved with an array of results when all + * of the provided Promises resolve or reject. + * @param values - An array of Promises. + * @returns A new Promise. + */ + allSettled(values: T): Promise<{ -readonly [P in keyof T]: CoreJS.CoreJSPromiseSettledResult>; }>; + + /** + * Creates a Promise that is resolved with an array of results when all + * of the provided Promises resolve or reject. + * @param values - An array of Promises. + * @returns A new Promise. + */ + allSettled(values: Iterable>): Promise>[]>; +} diff --git a/packages/core-js-types/src/base/proposals/promise-any.d.ts b/packages/core-js-types/src/base/proposals/promise-any.d.ts new file mode 100644 index 000000000000..32cd6357a0bf --- /dev/null +++ b/packages/core-js-types/src/base/proposals/promise-any.d.ts @@ -0,0 +1,33 @@ +// https://github.com/tc39/proposal-promise-any + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/af3a3779de6bc27619c85077e1b4d1de8feddd35/src/lib/es2021.promise.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface PromiseConstructor { + /** + * The any function returns a promise that is fulfilled by the first given promise to be fulfilled, or rejected with an AggregateError containing an array of rejection reasons if all of the given promises are rejected. It resolves all elements of the passed iterable to promises as it runs this algorithm. + * @param values - An array or iterable of Promises. + * @returns A new Promise. + */ + any(values: T): Promise>; + + /** + * The any function returns a promise that is fulfilled by the first given promise to be fulfilled, or rejected with an AggregateError containing an array of rejection reasons if all of the given promises are rejected. It resolves all elements of the passed iterable to promises as it runs this algorithm. + * @param values - An array or iterable of Promises. + * @returns A new Promise. + */ + any(values: Iterable>): Promise>; +} + +interface AggregateError extends Error { + errors: any[]; +} + +interface AggregateErrorConstructor { + new (errors: Iterable, message?: string): AggregateError; + (errors: Iterable, message?: string): AggregateError; + readonly prototype: AggregateError; +} + +declare var AggregateError: AggregateErrorConstructor; diff --git a/packages/core-js-types/src/base/proposals/promise-finally.d.ts b/packages/core-js-types/src/base/proposals/promise-finally.d.ts new file mode 100644 index 000000000000..575869bb8dfd --- /dev/null +++ b/packages/core-js-types/src/base/proposals/promise-finally.d.ts @@ -0,0 +1,15 @@ +// https://github.com/tc39/proposal-promise-finally + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/af3a3779de6bc27619c85077e1b4d1de8feddd35/src/lib/es2018.promise.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface Promise { + /** + * Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The + * resolved value cannot be modified from the callback. + * @param onfinally - The callback to execute when the Promise is settled (fulfilled or rejected). + * @returns A Promise for the completion of the callback. + */ + finally(onfinally?: (() => void) | undefined | null): Promise; +} diff --git a/packages/core-js-types/src/base/proposals/promise-try.d.ts b/packages/core-js-types/src/base/proposals/promise-try.d.ts new file mode 100644 index 000000000000..3e5da259e21f --- /dev/null +++ b/packages/core-js-types/src/base/proposals/promise-try.d.ts @@ -0,0 +1,23 @@ +// https://github.com/tc39/proposal-promise-try + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/af3a3779de6bc27619c85077e1b4d1de8feddd35/src/lib/esnext.promise.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface PromiseConstructor { + /** + * Takes a callback of any kind (returns or throws, synchronously or asynchronously) and wraps its result + * in a Promise. + * + * @param callbackFn - A function that is called synchronously. It can do anything: either return + * a value, throw an error, or return a promise. + * @param args - Additional arguments, that will be passed to the callback. + * + * @returns A Promise that is: + * - Already fulfilled, if the callback synchronously returns a value. + * - Already rejected, if the callback synchronously throws an error. + * - Asynchronously fulfilled or rejected, if the callback returns a promise. + */ + try(callbackFn: (...args: U) => T | PromiseLike, ...args: U): Promise>; +} + diff --git a/packages/core-js-types/src/base/proposals/promise-with-resolvers.d.ts b/packages/core-js-types/src/base/proposals/promise-with-resolvers.d.ts new file mode 100644 index 000000000000..98a34c818dec --- /dev/null +++ b/packages/core-js-types/src/base/proposals/promise-with-resolvers.d.ts @@ -0,0 +1,25 @@ +// https://github.com/tc39/proposal-promise-with-resolvers + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/af3a3779de6bc27619c85077e1b4d1de8feddd35/src/lib/es2024.promise.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface PromiseWithResolvers { + promise: Promise; + + resolve: (value: T | PromiseLike) => void; + + reject: (reason?: any) => void; +} + +interface PromiseConstructor { + /** + * Creates a new Promise and returns it in an object, along with its resolve and reject functions. + * @returns An object with the properties `promise`, `resolve`, and `reject`. + * + * ```ts + * const { promise, resolve, reject } = Promise.withResolvers(); + * ``` + */ + withResolvers(): PromiseWithResolvers; +} diff --git a/packages/core-js-types/src/base/proposals/regexp-dotall-flag.d.ts b/packages/core-js-types/src/base/proposals/regexp-dotall-flag.d.ts new file mode 100644 index 000000000000..ca7bc3950d59 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/regexp-dotall-flag.d.ts @@ -0,0 +1,13 @@ +// https://github.com/tc39/proposal-regexp-dotall-flag + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/f450c1b80ce6dc7b04e81899db00534018932234/src/lib/es2018.regexp.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface RegExp { + /** + * Returns a Boolean value indicating the state of the dotAll flag (s) used with a regular expression. + * Default is false. Read-only. + */ + readonly dotAll: boolean; +} diff --git a/packages/core-js-types/src/base/proposals/regexp-escaping.d.ts b/packages/core-js-types/src/base/proposals/regexp-escaping.d.ts new file mode 100644 index 000000000000..cb71a638fc0a --- /dev/null +++ b/packages/core-js-types/src/base/proposals/regexp-escaping.d.ts @@ -0,0 +1,12 @@ +// https://github.com/tc39/proposal-regex-escaping + +interface RegExpConstructor { + /** + * Escapes a string to be used in a regular expression. + * @param string - The string to escape. + * @returns The escaped string. + */ + escape(string: string): string; +} + +declare var RegExp: RegExpConstructor; diff --git a/packages/core-js-types/src/base/proposals/regexp-named-groups.d.ts b/packages/core-js-types/src/base/proposals/regexp-named-groups.d.ts new file mode 100644 index 000000000000..b6e6f8fc2a8e --- /dev/null +++ b/packages/core-js-types/src/base/proposals/regexp-named-groups.d.ts @@ -0,0 +1,17 @@ +// https://github.com/tc39/proposal-regexp-named-groups + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/f450c1b80ce6dc7b04e81899db00534018932234/src/lib/es2018.regexp.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface RegExpExecArray extends Array { + groups?: { + [key: string]: string; + }; +} + +interface RegExpMatchArray extends Array { + groups?: { + [key: string]: string; + }; +} diff --git a/packages/core-js-types/src/base/proposals/relative-indexing-method.d.ts b/packages/core-js-types/src/base/proposals/relative-indexing-method.d.ts new file mode 100644 index 000000000000..b657a7a19a5a --- /dev/null +++ b/packages/core-js-types/src/base/proposals/relative-indexing-method.d.ts @@ -0,0 +1,118 @@ +// https://github.com/tc39/proposal-relative-indexing-method + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/f450c1b80ce6dc7b04e81899db00534018932234/src/lib/es2022.array.d.ts +// https://github.com/microsoft/TypeScript/blob/f450c1b80ce6dc7b04e81899db00534018932234/src/lib/es2022.string.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface String { + /** + * Returns a new String consisting of the single UTF-16 code unit located at the specified index. + * @param index - The zero-based index of the desired code unit. A negative index will count back from the last item. + */ + at(index: number): string | undefined; +} + +interface Array { + /** + * Returns the item located at the specified index. + * @param index - The zero-based index of the desired code unit. A negative index will count back from the last item. + */ + at(index: number): T | undefined; +} + +interface ReadonlyArray { + /** + * Returns the item located at the specified index. + * @param index - The zero-based index of the desired code unit. A negative index will count back from the last item. + */ + at(index: number): T | undefined; +} + +interface Int8Array { + /** + * Returns the item located at the specified index. + * @param index - The zero-based index of the desired code unit. A negative index will count back from the last item. + */ + at(index: number): number | undefined; +} + +interface Uint8Array { + /** + * Returns the item located at the specified index. + * @param index - The zero-based index of the desired code unit. A negative index will count back from the last item. + */ + at(index: number): number | undefined; +} + +interface Uint8ClampedArray { + /** + * Returns the item located at the specified index. + * @param index - The zero-based index of the desired code unit. A negative index will count back from the last item. + */ + at(index: number): number | undefined; +} + +interface Int16Array { + /** + * Returns the item located at the specified index. + * @param index - The zero-based index of the desired code unit. A negative index will count back from the last item. + */ + at(index: number): number | undefined; +} + +interface Uint16Array { + /** + * Returns the item located at the specified index. + * @param index - The zero-based index of the desired code unit. A negative index will count back from the last item. + */ + at(index: number): number | undefined; +} + +interface Int32Array { + /** + * Returns the item located at the specified index. + * @param index - The zero-based index of the desired code unit. A negative index will count back from the last item. + */ + at(index: number): number | undefined; +} + +interface Uint32Array { + /** + * Returns the item located at the specified index. + * @param index - The zero-based index of the desired code unit. A negative index will count back from the last item. + */ + at(index: number): number | undefined; +} + +interface Float32Array { + /** + * Returns the item located at the specified index. + * @param index - The zero-based index of the desired code unit. A negative index will count back from the last item. + */ + at(index: number): number | undefined; +} + +interface Float64Array { + /** + * Returns the item located at the specified index. + * @param index - The zero-based index of the desired code unit. A negative index will count back from the last item. + */ + at(index: number): number | undefined; +} + +interface BigInt64Array { + /** + * Returns the item located at the specified index. + * @param index - The zero-based index of the desired code unit. A negative index will count back from the last item. + */ + at(index: number): bigint | undefined; +} + +interface BigUint64Array { + /** + * Returns the item located at the specified index. + * @param index - The zero-based index of the desired code unit. A negative index will count back from the last item. + */ + at(index: number): bigint | undefined; +} diff --git a/packages/core-js-types/src/base/proposals/set-methods-custom.d.ts b/packages/core-js-types/src/base/proposals/set-methods-custom.d.ts new file mode 100644 index 000000000000..1f67c0aec7d5 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/set-methods-custom.d.ts @@ -0,0 +1,21 @@ +// Motivation: Custom type needed to keep generics strict + +// https://github.com/tc39/proposal-set-methods + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/f450c1b80ce6dc7b04e81899db00534018932234/src/lib/esnext.collection.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +declare namespace CoreJS { + interface ReadonlySetLike { + keys(): Iterator; + + has(value: T): boolean; + + readonly size: number; + } + + export type SetUnion = (other: ReadonlySetLike) => Set; + + export type SetSymmetricDifference = (other: ReadonlySetLike) => Set; +} diff --git a/packages/core-js-types/src/base/proposals/set-methods.d.ts b/packages/core-js-types/src/base/proposals/set-methods.d.ts new file mode 100644 index 000000000000..658beb4addee --- /dev/null +++ b/packages/core-js-types/src/base/proposals/set-methods.d.ts @@ -0,0 +1,96 @@ +// https://github.com/tc39/proposal-set-methods + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/f450c1b80ce6dc7b04e81899db00534018932234/src/lib/esnext.collection.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface ReadonlySetLike { // @type-options: no-extends, no-prefix + /** + * Despite its name, returns an iterator of the values in the set-like. + */ + keys(): Iterator; + + /** + * @returns a boolean indicating whether an element with the specified value exists in the set-like or not. + */ + has(value: T): boolean; + + /** + * @returns the number of (unique) elements in the set-like. + */ + readonly size: number; +} + +interface Set { // @type-options: no-redefine + /** + * @returns a new Set containing all the elements in this Set and also all the elements in the argument. + */ + union(other: ReadonlySetLike): Set; // @type-options: prefix-return-type + + /** + * @returns a new Set containing all the elements which are both in this Set and in the argument. + */ + intersection(other: ReadonlySetLike): Set; // @type-options: prefix-return-type + + /** + * @returns a new Set containing all the elements in this Set which are not also in the argument. + */ + difference(other: ReadonlySetLike): Set; // @type-options: prefix-return-type + + /** + * @returns a new Set containing all the elements which are in either this Set or in the argument, but not in both. + */ + symmetricDifference(other: ReadonlySetLike): Set; // @type-options: prefix-return-type + + /** + * @returns a boolean indicating whether all the elements in this Set are also in the argument. + */ + isSubsetOf(other: ReadonlySetLike): boolean; + + /** + * @returns a boolean indicating whether all the elements in the argument are also in this Set. + */ + isSupersetOf(other: ReadonlySetLike): boolean; + + /** + * @returns a boolean indicating whether this Set has no elements in common with the argument. + */ + isDisjointFrom(other: ReadonlySetLike): boolean; +} + +interface ReadonlySet { // @type-options: no-redefine + /** + * @returns a new Set containing all the elements in this Set and also all the elements in the argument. + */ + union(other: ReadonlySetLike): Set; // @type-options: prefix-return-type + + /** + * @returns a new Set containing all the elements which are both in this Set and in the argument. + */ + intersection(other: ReadonlySetLike): Set; // @type-options: prefix-return-type + + /** + * @returns a new Set containing all the elements in this Set which are not also in the argument. + */ + difference(other: ReadonlySetLike): Set; // @type-options: prefix-return-type + + /** + * @returns a new Set containing all the elements which are in either this Set or in the argument, but not in both. + */ + symmetricDifference(other: ReadonlySetLike): Set; // @type-options: prefix-return-type + + /** + * @returns a boolean indicating whether all the elements in this Set are also in the argument. + */ + isSubsetOf(other: ReadonlySetLike): boolean; + + /** + * @returns a boolean indicating whether all the elements in the argument are also in this Set. + */ + isSupersetOf(other: ReadonlySetLike): boolean; + + /** + * @returns a boolean indicating whether this Set has no elements in common with the argument. + */ + isDisjointFrom(other: ReadonlySetLike): boolean; +} diff --git a/packages/core-js-types/src/base/proposals/string-cooked.d.ts b/packages/core-js-types/src/base/proposals/string-cooked.d.ts new file mode 100644 index 000000000000..fe8d714a2e16 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/string-cooked.d.ts @@ -0,0 +1,11 @@ +// https://github.com/tc39/proposal-string-cooked + +interface StringConstructor { + /** + * Processes a template literal, interpreting escape sequences. + * @param template - Array of string literals. + * @param substitutions - The substitutions for the template literal. + * @returns The processed string with escape sequences interpreted. + */ + cooked(template: readonly string[], ...substitutions: any[]): string; +} diff --git a/packages/core-js-types/src/base/proposals/string-dedent.d.ts b/packages/core-js-types/src/base/proposals/string-dedent.d.ts new file mode 100644 index 000000000000..e075cea7ee0d --- /dev/null +++ b/packages/core-js-types/src/base/proposals/string-dedent.d.ts @@ -0,0 +1,15 @@ +// https://github.com/tc39/proposal-string-dedent + +type CoreJSTemplateTag = (template: { raw: readonly string[] }, ...values: any[]) => any; + +interface StringConstructor { + /** + * Template tag that removes common leading whitespace from every line in the resulting string, + * preserving relative indentation and blank lines. + * @param template - The template strings array or function. + * @param values - Values to be interpolated into the template string. + * @returns The dedented string. + */ + dedent(template: { raw: readonly string[] }, ...values: any[]): string; + dedent(tag: T): T; +} diff --git a/packages/core-js-types/src/base/proposals/string-left-right-trim.d.ts b/packages/core-js-types/src/base/proposals/string-left-right-trim.d.ts new file mode 100644 index 000000000000..1a33d45774a0 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/string-left-right-trim.d.ts @@ -0,0 +1,23 @@ +// https://github.com/tc39/proposal-string-left-right-trim + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/f450c1b80ce6dc7b04e81899db00534018932234/src/lib/es2019.string.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface String { // @type-options: no-redefine + /** Removes the trailing white space and line terminator characters from a string. */ + trimEnd(): string; + + /** Removes the leading white space and line terminator characters from a string. */ + trimStart(): string; + + /** + * Removes the leading white space and line terminator characters from a string. + */ + trimLeft(): string; + + /** + * Removes the trailing white space and line terminator characters from a string. + */ + trimRight(): string; +} diff --git a/packages/core-js-types/src/base/proposals/string-match-all.d.ts b/packages/core-js-types/src/base/proposals/string-match-all.d.ts new file mode 100644 index 000000000000..68287f3be217 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/string-match-all.d.ts @@ -0,0 +1,22 @@ +// https://github.com/tc39/proposal-string-matchall + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/f450c1b80ce6dc7b04e81899db00534018932234/src/lib/es2020.string.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface RegExpStringIterator extends IteratorObject { + [Symbol.iterator](): RegExpStringIterator; +} + +interface String { + /** + * Matches a string with a regular expression, and returns an iterable of matches + * containing the results of that search. + * @param regexp - A variable name or string literal containing the regular expression pattern and flags. + */ + matchAll(regexp: RegExp): RegExpStringIterator; +} + +interface SymbolConstructor { + readonly matchAll: unique symbol; +} diff --git a/packages/core-js-types/src/base/proposals/string-padding.d.ts b/packages/core-js-types/src/base/proposals/string-padding.d.ts new file mode 100644 index 000000000000..55d1ef2de2b5 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/string-padding.d.ts @@ -0,0 +1,33 @@ +// https://github.com/tc39/proposal-string-pad-start-end + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/f450c1b80ce6dc7b04e81899db00534018932234/src/lib/es2017.string.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface String { // @type-options: no-redefine + /** + * Pads the current string with a given string (possibly repeated) so that the resulting string reaches a given length. + * The padding is applied from the start (left) of the current string. + * + * @param maxLength - The length of the resulting string once the current string has been padded. + * If this parameter is smaller than the current string's length, the current string will be returned as it is. + * + * @param fillString - The string to pad the current string with. + * If this string is too long, it will be truncated and the left-most part will be applied. + * The default value for this parameter is " " (U+0020). + */ + padStart(maxLength: number, fillString?: string): string; + + /** + * Pads the current string with a given string (possibly repeated) so that the resulting string reaches a given length. + * The padding is applied from the end (right) of the current string. + * + * @param maxLength - The length of the resulting string once the current string has been padded. + * If this parameter is smaller than the current string's length, the current string will be returned as it is. + * + * @param fillString - The string to pad the current string with. + * If this string is too long, it will be truncated and the left-most part will be applied. + * The default value for this parameter is " " (U+0020). + */ + padEnd(maxLength: number, fillString?: string): string; +} diff --git a/packages/core-js-types/src/base/proposals/string-replace-all.d.ts b/packages/core-js-types/src/base/proposals/string-replace-all.d.ts new file mode 100644 index 000000000000..005d3712034f --- /dev/null +++ b/packages/core-js-types/src/base/proposals/string-replace-all.d.ts @@ -0,0 +1,15 @@ +// https://github.com/tc39/proposal-string-replaceall + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/4a957b74ea4d716356181644d23f6ad5f10824d6/src/lib/es2021.string.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface String { // @type-options: no-redefine + /** + * Replace all instances of a substring in a string, using a regular expression or search string. + * @param searchValue - A string to search for. + * @param replacer - A string containing the text to replace for every successful match of searchValue in this string + * - or function that returns the replacement text. + */ + replaceAll(searchValue: string | RegExp, replacer: string | ((substring: string, ...args: any[]) => string)): string; +} diff --git a/packages/core-js-types/src/base/proposals/symbol-description.d.ts b/packages/core-js-types/src/base/proposals/symbol-description.d.ts new file mode 100644 index 000000000000..0b5c7bc1dd43 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/symbol-description.d.ts @@ -0,0 +1,12 @@ +// https://github.com/tc39/proposal-Symbol-description + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/f450c1b80ce6dc7b04e81899db00534018932234/src/lib/es2019.symbol.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface Symbol { + /** + * Expose the [[Description]] internal slot of a symbol directly. + */ + readonly description: string | undefined; +} diff --git a/packages/core-js-types/src/base/proposals/symbol-predicates.d.ts b/packages/core-js-types/src/base/proposals/symbol-predicates.d.ts new file mode 100644 index 000000000000..a1ad05b69313 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/symbol-predicates.d.ts @@ -0,0 +1,15 @@ +// https://github.com/tc39/proposal-symbol-predicates + +interface SymbolConstructor { + /** + * Determines whether the given value is a registered symbol. + * @param value - The value to check. + */ + isRegisteredSymbol(value: unknown): value is symbol; + + /** + * Determines whether the given value is a well-known symbol. + * @param value - The value to check. + */ + isWellKnownSymbol(value: unknown): value is symbol; +} diff --git a/packages/core-js-types/src/base/proposals/well-formed-unicode-strings.d.ts b/packages/core-js-types/src/base/proposals/well-formed-unicode-strings.d.ts new file mode 100644 index 000000000000..ea76cab32567 --- /dev/null +++ b/packages/core-js-types/src/base/proposals/well-formed-unicode-strings.d.ts @@ -0,0 +1,17 @@ +// https://github.com/tc39/proposal-is-usv-string + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/f450c1b80ce6dc7b04e81899db00534018932234/src/lib/es2024.string.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface String { // @type-options: no-redefine + /** + * Returns true if all leading surrogates and trailing surrogates appear paired and in order. + */ + isWellFormed(): boolean; + + /** + * Returns a string where all lone or out-of-order surrogates have been replaced by the Unicode replacement character (U+FFFD). + */ + toWellFormed(): string; +} diff --git a/packages/core-js-types/src/base/pure/common/date.d.ts b/packages/core-js-types/src/base/pure/common/date.d.ts new file mode 100644 index 000000000000..ce1e532082ff --- /dev/null +++ b/packages/core-js-types/src/base/pure/common/date.d.ts @@ -0,0 +1,5 @@ +declare namespace CoreJS { + export interface CoreJSDate extends Date {} + + var CoreJSDate: DateConstructor; +} diff --git a/packages/core-js-types/src/base/pure/common/global-this.d.ts b/packages/core-js-types/src/base/pure/common/global-this.d.ts new file mode 100644 index 000000000000..fec053664a61 --- /dev/null +++ b/packages/core-js-types/src/base/pure/common/global-this.d.ts @@ -0,0 +1,3 @@ +declare namespace CoreJS { + var CoreJSglobalThis: typeof globalThis; +} diff --git a/packages/core-js-types/src/base/pure/common/parse-float.d.ts b/packages/core-js-types/src/base/pure/common/parse-float.d.ts new file mode 100644 index 000000000000..8e7a91a4e0a3 --- /dev/null +++ b/packages/core-js-types/src/base/pure/common/parse-float.d.ts @@ -0,0 +1,3 @@ +declare namespace CoreJS { + export function CoreJSparseFloat(string: string): number; +} diff --git a/packages/core-js-types/src/base/pure/common/parse-int.d.ts b/packages/core-js-types/src/base/pure/common/parse-int.d.ts new file mode 100644 index 000000000000..eba4a7aba2be --- /dev/null +++ b/packages/core-js-types/src/base/pure/common/parse-int.d.ts @@ -0,0 +1,3 @@ +declare namespace CoreJS { + export function CoreJSparseInt(string: string, radix?: number): number; +} diff --git a/packages/core-js-types/src/base/pure/common/reflect.d.ts b/packages/core-js-types/src/base/pure/common/reflect.d.ts new file mode 100644 index 000000000000..2d852ad8d462 --- /dev/null +++ b/packages/core-js-types/src/base/pure/common/reflect.d.ts @@ -0,0 +1,136 @@ +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/38d95c8001300f525fd601dd0ce6d0ff5f12baee/src/lib/es2015.reflect.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +declare namespace CoreJS { + interface Reflect { + /** + * Calls the function with the specified object as the this value + * and the elements of specified array as the arguments. + * @param target - The function to call. + * @param thisArgument - The object to be used as the this object. + * @param argumentsList - An array of argument values to be passed to the function. + */ + apply( + target: (this: T, ...args: A) => R, + thisArgument: T, + argumentsList: Readonly, + ): R; + apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; + + /** + * Constructs the target with the elements of specified array as the arguments + * and the specified constructor as the `new.target` value. + * @param target - The constructor to invoke. + * @param argumentsList - An array of argument values to be passed to the constructor. + * @param newTarget - The constructor to be used as the `new.target` object. + */ + construct( + target: new (...args: A) => R, + argumentsList: Readonly, + newTarget?: new (...args: any) => any, + ): R; + construct(target: Function, argumentsList: ArrayLike, newTarget?: Function): any; + + /** + * Adds a property to an object, or modifies attributes of an existing property. + * @param target - Object on which to add or modify the property. This can be a native JavaScript object + * (that is, a user-defined object or a built in object) or a DOM object. + * @param propertyKey - The property name. + * @param attributes - Descriptor for the property. It can be for a data property or an accessor property. + */ + defineProperty(target: object, propertyKey: PropertyKey, attributes: PropertyDescriptor & ThisType): boolean; + + /** + * Removes a property from an object, equivalent to `delete target[propertyKey]`, + * except it won't throw if `target[propertyKey]` is non-configurable. + * @param target - Object from which to remove the own property. + * @param propertyKey - The property name. + */ + deleteProperty(target: object, propertyKey: PropertyKey): boolean; + + /** + * Gets the property of target, equivalent to `target[propertyKey]` when `receiver === target`. + * @param target - Object that contains the property on itself or in its prototype chain. + * @param propertyKey - The property name. + * @param receiver - The reference to use as the `this` value in the getter function, + * if `target[propertyKey]` is an accessor property. + */ + get( + target: T, + propertyKey: P, + receiver?: unknown, + ): P extends keyof T ? T[P] : any; + + /** + * Gets the own property descriptor of the specified object. + * An own property descriptor is one that is defined directly on the object and is not inherited from the object's prototype. + * @param target - Object that contains the property. + * @param propertyKey - The property name. + */ + getOwnPropertyDescriptor( + target: T, + propertyKey: P, + ): TypedPropertyDescriptor

| undefined; + + /** + * Returns the prototype of an object. + * @param target - The object that references the prototype. + */ + getPrototypeOf(target: object): object | null; + + /** + * Equivalent to `propertyKey in target`. + * @param target - Object that contains the property on itself or in its prototype chain. + * @param propertyKey - Name of the property. + */ + has(target: object, propertyKey: PropertyKey): boolean; + + /** + * Returns a value that indicates whether new properties can be added to an object. + * @param target - Object to test. + */ + isExtensible(target: object): boolean; + + /** + * Returns the string and symbol keys of the own properties of an object. The own properties of an object + * are those that are defined directly on that object, and are not inherited from the object's prototype. + * @param target - Object that contains the own properties. + */ + ownKeys(target: object): (string | symbol)[]; + + /** + * Prevents the addition of new properties to an object. + * @param target - Object to make non-extensible. + * @returns Whether the object has been made non-extensible. + */ + preventExtensions(target: object): boolean; + + /** + * Sets the property of target, equivalent to `target[propertyKey] = value` when `receiver === target`. + * @param target - Object that contains the property on itself or in its prototype chain. + * @param propertyKey - Name of the property. + * @param receiver - The reference to use as the `this` value in the setter function, + * if `target[propertyKey]` is an accessor property. + */ + set( + target: T, + propertyKey: P, + value: P extends keyof T ? T[P] : any, + receiver?: any, + ): boolean; + set(target: object, propertyKey: PropertyKey, value: any, receiver?: any): boolean; + + /** + * Sets the prototype of a specified object o to object proto or null. + * @param target - The object to change its prototype. + * @param proto - The value of the new prototype or null. + * @returns Whether setting the prototype was successful. + */ + setPrototypeOf(target: object, proto: object | null): boolean; + } + + interface CoreJSReflect extends Reflect {} + + var CoreJSReflect: CoreJSReflect; +} diff --git a/packages/core-js-types/src/base/pure/core-js-types/aggregate-error.d.ts b/packages/core-js-types/src/base/pure/core-js-types/aggregate-error.d.ts new file mode 100644 index 000000000000..1da5bf1d9f85 --- /dev/null +++ b/packages/core-js-types/src/base/pure/core-js-types/aggregate-error.d.ts @@ -0,0 +1,13 @@ +declare namespace CoreJS { + export interface CoreJSAggregateError extends Error { + errors: any[]; + } + + export interface CoreJSAggregateErrorConstructor { + new (errors: Iterable, message?: string): CoreJSAggregateError; + (errors: Iterable, message?: string): CoreJSAggregateError; + readonly prototype: CoreJSAggregateError; + } + + var CoreJSAggregateError: CoreJSAggregateErrorConstructor; +} diff --git a/packages/core-js-types/src/base/pure/core-js-types/async-iterable.d.ts b/packages/core-js-types/src/base/pure/core-js-types/async-iterable.d.ts new file mode 100644 index 000000000000..aa9d7adf12f9 --- /dev/null +++ b/packages/core-js-types/src/base/pure/core-js-types/async-iterable.d.ts @@ -0,0 +1,3 @@ +declare namespace CoreJS { + export interface CoreJSAsyncIterable {} +} diff --git a/packages/core-js-types/src/base/pure/core-js-types/async-iterator-object.d.ts b/packages/core-js-types/src/base/pure/core-js-types/async-iterator-object.d.ts new file mode 100644 index 000000000000..996ed0827b3a --- /dev/null +++ b/packages/core-js-types/src/base/pure/core-js-types/async-iterator-object.d.ts @@ -0,0 +1,8 @@ +/// +/// + +declare namespace CoreJS { + export interface CoreJSAsyncIteratorObject extends CoreJS.CoreJSAsyncIterator { + [CoreJS.CoreJSSymbol.asyncIterator](): CoreJSAsyncIteratorObject; + } +} diff --git a/packages/core-js-types/src/base/pure/core-js-types/async-iterator.d.ts b/packages/core-js-types/src/base/pure/core-js-types/async-iterator.d.ts new file mode 100644 index 000000000000..99e92cd2df55 --- /dev/null +++ b/packages/core-js-types/src/base/pure/core-js-types/async-iterator.d.ts @@ -0,0 +1,11 @@ +/// + +declare namespace CoreJS { + export interface CoreJSAsyncIterator { + next(...[value]: [] | [TNext]): CoreJS.CoreJSPromise>; + + return?(value?: TReturn | PromiseLike): CoreJS.CoreJSPromise>; + + throw?(e?: any): CoreJS.CoreJSPromise>; + } +} diff --git a/packages/core-js-types/src/base/pure/core-js-types/iterator-object.d.ts b/packages/core-js-types/src/base/pure/core-js-types/iterator-object.d.ts new file mode 100644 index 000000000000..da206c3ddb0f --- /dev/null +++ b/packages/core-js-types/src/base/pure/core-js-types/iterator-object.d.ts @@ -0,0 +1,7 @@ +/// + +declare namespace CoreJS { + export interface CoreJSIteratorObject extends CoreJSIterator { + [Symbol.iterator](): CoreJSIteratorObject; + } +} diff --git a/packages/core-js-types/src/base/pure/core-js-types/map.d.ts b/packages/core-js-types/src/base/pure/core-js-types/map.d.ts new file mode 100644 index 000000000000..c4f513a1fbb0 --- /dev/null +++ b/packages/core-js-types/src/base/pure/core-js-types/map.d.ts @@ -0,0 +1,12 @@ +declare namespace CoreJS { + export interface CoreJSMap extends Map {} + + export interface CoreJSMapConstructor extends MapConstructor { + readonly prototype: CoreJSMap; + + new (): CoreJSMap; + new(entries?: readonly (readonly [K, V])[] | Iterable | null): CoreJSMap; + } + + var CoreJSMap: CoreJSMapConstructor; +} diff --git a/packages/core-js-types/src/base/pure/core-js-types/promise.d.ts b/packages/core-js-types/src/base/pure/core-js-types/promise.d.ts new file mode 100644 index 000000000000..4b7813f85ea3 --- /dev/null +++ b/packages/core-js-types/src/base/pure/core-js-types/promise.d.ts @@ -0,0 +1,148 @@ +/// + +// https://github.com/tc39/proposal-await-dictionary + +// https://github.com/tc39/proposal-promise-allSettled + +// https://github.com/tc39/proposal-promise-any + +// https://github.com/tc39/proposal-promise-try + +// https://github.com/tc39/proposal-promise-with-resolvers + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/2a90a739c1c1e87e3c3d0c93e16f7e5baadf8035/src/lib/es2020.promise.d.ts +// https://github.com/microsoft/TypeScript/blob/347254895823a36a1b1b1c80471422da54ad77de/src/lib/es2021.promise.d.ts +// https://github.com/microsoft/TypeScript/blob/af3a3779de6bc27619c85077e1b4d1de8feddd35/src/lib/es2024.promise.d.ts +// https://github.com/microsoft/TypeScript/blob/347254895823a36a1b1b1c80471422da54ad77de/src/lib/es2025.promise.d.ts +// https://github.com/microsoft/TypeScript/blob/af3a3779de6bc27619c85077e1b4d1de8feddd35/src/lib/esnext.promise.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +declare namespace CoreJS { + interface CoreJSPromiseWithResolvers { + promise: CoreJSPromise; + resolve: (value: T | PromiseLike) => void; + reject: (reason?: any) => void; + } + + export interface CoreJSPromise extends Promise {} + + export interface CoreJSPromiseConstructor { + readonly prototype: CoreJSPromise; + + /** + * Creates a new Promise. + * @param executor - A callback used to initialize the promise. This callback is passed two arguments: + * a resolve callback used to resolve the promise with a value or the result of another promise, + * and a reject callback used to reject the promise with a provided reason or error. + */ + new(executor: (resolve: (value: T | PromiseLike) => void, reject: (reason?: any) => void) => void): CoreJSPromise; + + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises + * resolve, or rejected when any Promise is rejected. + * @param values - An array of Promises. + * @returns A new Promise. + */ + all(values: T): CoreJSPromise<{ -readonly [P in keyof T]: Awaited; }>; + + /** + * Takes an object of promises and returns a single Promise that resolves to an object + * with the same keys and fulfilled values, or rejects as soon as any of the input promises rejects. + * @param promises - An object of promises + * @returns A new `Promise` that resolves to an object of fulfilled values or rejects if any promise rejects. + */ + allKeyed>(promises: D): CoreJSPromise<{ [k in keyof D]: Awaited }>; + + /** + * Takes an object whose values are promises and returns a single `Promise` that resolves + * to an object with the same keys, after all of the input promises have settled. + * @param promises - An object of promises + * @returns A new `Promise` that resolves to an object with the same keys as the input object, + * where each key maps to the settlement result (`{ status, value }` or `{ status, reason }`) of the corresponding promise. + */ + allSettledKeyed>(promises: D): CoreJSPromise<{ [k in keyof D]: CoreJS.CoreJSPromiseSettledResult> }>; + + /** + * Creates a Promise that is resolved with an array of results when all + * of the provided Promises resolve or reject. + * @param values - An array of Promises. + * @returns A new Promise. + */ + allSettled(values: T): CoreJSPromise<{ -readonly [P in keyof T]: CoreJS.CoreJSPromiseSettledResult>; }>; + /** + * Creates a Promise that is resolved with an array of results when all + * of the provided Promises resolve or reject. + * @param values - An array of Promises. + * @returns A new Promise. + */ + allSettled(values: Iterable>): CoreJSPromise>[]>; + + /** + * The any function returns a promise that is fulfilled by the first given promise to be fulfilled, or rejected with an AggregateError containing an array of rejection reasons if all of the given promises are rejected. It resolves all elements of the passed iterable to promises as it runs this algorithm. + * @param values - An array or iterable of Promises. + * @returns A new Promise. + */ + any(values: T): CoreJSPromise>; + /** + * The any function returns a promise that is fulfilled by the first given promise to be fulfilled, or rejected with an AggregateError containing an array of rejection reasons if all of the given promises are rejected. It resolves all elements of the passed iterable to promises as it runs this algorithm. + * @param values - An array or iterable of Promises. + * @returns A new Promise. + */ + any(values: Iterable>): CoreJSPromise>; + + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved + * or rejected. + * @param values - An array of Promises. + * @returns A new Promise. + */ + race(values: T): CoreJSPromise>; + + /** + * Creates a new rejected promise for the provided reason. + * @param reason - The reason the promise was rejected. + * @returns A new rejected Promise. + */ + reject(reason?: any): CoreJSPromise; + + /** + * Creates a new resolved promise. + * @returns A resolved promise. + */ + resolve(): CoreJSPromise; + /** + * Creates a new resolved promise for the provided value. + * @param value - A promise. + * @returns A promise whose internal state matches the provided promise. + */ + resolve(value: T | PromiseLike): CoreJSPromise>; + + /** + * Takes a callback of any kind (returns or throws, synchronously or asynchronously) and wraps its result + * in a Promise. + * + * @param callbackFn - A function that is called synchronously. It can do anything: either return + * a value, throw an error, or return a promise. + * @param args - Additional arguments, that will be passed to the callback. + * + * @returns A Promise that is: + * - Already fulfilled, if the callback synchronously returns a value. + * - Already rejected, if the callback synchronously throws an error. + * - Asynchronously fulfilled or rejected, if the callback returns a promise. + */ + try(callbackFn: (...args: U) => T | PromiseLike, ...args: U): CoreJSPromise>; + + /** + * Creates a new Promise and returns it in an object, along with its resolve and reject functions. + * @returns An object with the properties `promise`, `resolve`, and `reject`. + * + * ```ts + * const { promise, resolve, reject } = Promise.withResolvers(); + * ``` + */ + withResolvers(): CoreJSPromiseWithResolvers; + } + + var CoreJSPromise: CoreJSPromiseConstructor; +} diff --git a/packages/core-js-types/src/base/pure/core-js-types/set.d.ts b/packages/core-js-types/src/base/pure/core-js-types/set.d.ts new file mode 100644 index 000000000000..5d54ecf834cf --- /dev/null +++ b/packages/core-js-types/src/base/pure/core-js-types/set.d.ts @@ -0,0 +1,10 @@ +declare namespace CoreJS { + export interface CoreJSSet extends Set {} + + export interface CoreJSSetConstructor extends SetConstructor { + new(values?: readonly T[] | null): CoreJSSet; + readonly prototype: CoreJSSet; + } + + var CoreJSSet: CoreJSSetConstructor; +} diff --git a/packages/core-js-types/src/base/pure/core-js-types/string-base.d.ts b/packages/core-js-types/src/base/pure/core-js-types/string-base.d.ts new file mode 100644 index 000000000000..1e688110e864 --- /dev/null +++ b/packages/core-js-types/src/base/pure/core-js-types/string-base.d.ts @@ -0,0 +1,4 @@ +declare namespace CoreJS { + // We should use String without the matchAll method to avoid signature conflicts + export type StringBase = Omit; +} diff --git a/packages/core-js-types/src/base/pure/core-js-types/url-search-params.d.ts b/packages/core-js-types/src/base/pure/core-js-types/url-search-params.d.ts new file mode 100644 index 000000000000..eafc7cc8eec0 --- /dev/null +++ b/packages/core-js-types/src/base/pure/core-js-types/url-search-params.d.ts @@ -0,0 +1,65 @@ +/// + +declare namespace CoreJS { + export interface CoreJSURLSearchParams { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/size) */ + readonly size: number; + /** + * Appends a specified key/value pair as a new search parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/append) + */ + append(name: string, value: string): void; + /** + * Deletes the given search parameter, and its associated value, from the list of all search parameters. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/delete) + */ + delete(name: string, value?: string): void; + /** + * Returns the first value associated to the given search parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/get) + */ + get(name: string): string | null; + /** + * Returns all the values association with a given search parameter. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/getAll) + */ + getAll(name: string): string[]; + /** + * Returns a Boolean indicating if such a search parameter exists. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/has) + */ + has(name: string, value?: string): boolean; + /** + * Sets the value associated to a given search parameter to the given value. If there were several values, delete the others. + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/set) + */ + set(name: string, value: string): void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/sort) */ + sort(): void; + /** Returns a string containing a query string suitable for use in a URL. Does not include the question mark. */ + toString(): string; + forEach(callbackfn: (value: string, key: string, parent: CoreJSURLSearchParams) => void, thisArg?: any): void; + + [Symbol.iterator](): CoreJSURLSearchParamsIterator<[string, string]>; + entries(): CoreJSURLSearchParamsIterator<[string, string]>; + keys(): CoreJSURLSearchParamsIterator; + values(): CoreJSURLSearchParamsIterator; + } + + interface CoreJSURLSearchParamsIterator extends CoreJSIteratorObject { + [Symbol.iterator](): CoreJSURLSearchParamsIterator; + } + + export interface CoreJSURLSearchParamsConstructor { + prototype: CoreJSURLSearchParams; + new(init?: string[][] | Record | string | CoreJSURLSearchParams): CoreJSURLSearchParams; + } + + var CoreJSURLSearchParams: CoreJSURLSearchParamsConstructor; +} diff --git a/packages/core-js-types/src/base/pure/core-js-types/url.d.ts b/packages/core-js-types/src/base/pure/core-js-types/url.d.ts new file mode 100644 index 000000000000..41f6e1ac68ae --- /dev/null +++ b/packages/core-js-types/src/base/pure/core-js-types/url.d.ts @@ -0,0 +1,64 @@ +/// + +declare namespace CoreJS { + export interface CoreJSURL { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) */ + hash: string; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) */ + host: string; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) */ + hostname: string; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) */ + href: string; + + toString(): string; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) */ + readonly origin: string; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) */ + password: string; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) */ + pathname: string; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) */ + port: string; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) */ + protocol: string; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) */ + search: string; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) */ + readonly searchParams: CoreJSURLSearchParams; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) */ + username: string; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) */ + toJSON(): string; + } + + export interface CoreJSURLConstructor { + new(url: string | CoreJSURL, base?: string): CoreJSURL; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) */ + canParse(url: string | CoreJSURL, base?: string): boolean; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static) */ + createObjectURL(obj: any): string; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/parse_static) */ + parse(url: string | CoreJSURL, base?: string): CoreJSURL | null; + + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static) */ + revokeObjectURL(url: string): void; + } + + var CoreJSURL: CoreJSURLConstructor; +} diff --git a/packages/core-js-types/src/base/pure/core-js-types/weak-map.d.ts b/packages/core-js-types/src/base/pure/core-js-types/weak-map.d.ts new file mode 100644 index 000000000000..70e1dd133de0 --- /dev/null +++ b/packages/core-js-types/src/base/pure/core-js-types/weak-map.d.ts @@ -0,0 +1,12 @@ +declare namespace CoreJS { + export interface CoreJSWeakMap extends WeakMap {} + + export interface CoreJSWeakMapConstructor extends WeakMapConstructor { + readonly prototype: CoreJSWeakMap; + + new(entries?: readonly (readonly [K, V])[] | null): CoreJSWeakMap; + new(iterable: Iterable): CoreJSWeakMap; + } + + var CoreJSWeakMap: CoreJSWeakMapConstructor; +} diff --git a/packages/core-js-types/src/base/pure/core-js-types/weak-set.d.ts b/packages/core-js-types/src/base/pure/core-js-types/weak-set.d.ts new file mode 100644 index 000000000000..22661eb40969 --- /dev/null +++ b/packages/core-js-types/src/base/pure/core-js-types/weak-set.d.ts @@ -0,0 +1,12 @@ +declare namespace CoreJS { + export interface CoreJSWeakSet extends WeakSet {} + + export interface CoreJSWeakSetConstructor extends WeakSetConstructor { + readonly prototype: CoreJSWeakSet; + + new(values?: readonly T[] | null): CoreJSWeakSet; + new(iterable: Iterable): CoreJSWeakSet; + } + + var CoreJSWeakSet: CoreJSWeakSetConstructor; +} diff --git a/packages/core-js-types/src/base/pure/proposals/array-buffer-base64.d.ts b/packages/core-js-types/src/base/pure/proposals/array-buffer-base64.d.ts new file mode 100644 index 000000000000..078b40cbed27 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/array-buffer-base64.d.ts @@ -0,0 +1,2 @@ +// empty +// Uint8Array isn't used in pure version diff --git a/packages/core-js-types/src/base/pure/proposals/array-buffer-transfer.d.ts b/packages/core-js-types/src/base/pure/proposals/array-buffer-transfer.d.ts new file mode 100644 index 000000000000..41ca5026f973 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/array-buffer-transfer.d.ts @@ -0,0 +1,69 @@ +// Motivation: We can use a readonly properties in the pure version, e.g. ArrayBuffer.detached. +// Motivation: We must create a constructor interface to allow creating our own ArrayBuffer implementation. + +// https://github.com/tc39/proposal-arraybuffer-transfer + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/4a957b74ea4d716356181644d23f6ad5f10824d6/src/lib/es2024.arraybuffer.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +declare namespace CoreJS { + export interface CoreJSArrayBuffer extends ArrayBuffer { + readonly detached: boolean; + + /** + * Creates a new `ArrayBuffer` with the same byte content as this buffer, then detaches this buffer. + * @param newByteLength - If provided, specifies the `byteLength` of the new `ArrayBuffer` + * @throws RangeError If this `ArrayBuffer` is resizable and newByteLength is greater than the `maxByteLength` of this `ArrayBuffer` + * @throws TypeError If this `ArrayBuffer` is already detached, or if it can only be detached by designated operations + * @returns A new `ArrayBuffer` object + */ + transfer(newByteLength?: number): CoreJSArrayBuffer; + + /** + * Creates a new non-resizable `ArrayBuffer` with the same byte content as this buffer, then detaches this buffer. + * @param newByteLength - If provided, specifies the `byteLength` of the new `ArrayBuffer` + * @throws TypeError If this `ArrayBuffer` is already detached, or if it can only be detached by designated operations + * @returns A new `ArrayBuffer` object + */ + transferToFixedLength(newByteLength?: number): CoreJSArrayBuffer; + } + + export interface CoreJSArrayBufferConstructor extends ArrayBufferConstructor { + new (byteLength: number, options?: { maxByteLength?: number; }): CoreJSArrayBuffer; + } + + var CoreJSArrayBuffer: CoreJSArrayBufferConstructor; +} + +// Type compatibility hack for AllowSharedBufferSource in TypeScript < 5.9 +// https://github.com/microsoft/TypeScript/issues/61480 +interface SharedArrayBuffer { + readonly resizable: boolean; + + readonly detached: boolean; + + /** + * Creates a new `ArrayBuffer` with the same byte content as this buffer, then detaches this buffer. + * @param newByteLength - If provided, specifies the `byteLength` of the new `ArrayBuffer` + * @throws RangeError If this `ArrayBuffer` is resizable and newByteLength is greater than the `maxByteLength` of this `ArrayBuffer` + * @throws TypeError If this `ArrayBuffer` is already detached, or if it can only be detached by designated operations + * @returns A new `ArrayBuffer` object + */ + transfer(newByteLength?: number): ArrayBuffer; + + /** + * Creates a new non-resizable `ArrayBuffer` with the same byte content as this buffer, then detaches this buffer. + * @param newByteLength - If provided, specifies the `byteLength` of the new `ArrayBuffer` + * @throws TypeError If this `ArrayBuffer` is already detached, or if it can only be detached by designated operations + * @returns A new `ArrayBuffer` object + */ + transferToFixedLength(newByteLength?: number): ArrayBuffer; + + /** + * Resizes the ArrayBuffer to the specified size (in bytes). + * + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/resize) + */ + resize(newByteLength?: number): void; +} diff --git a/packages/core-js-types/src/base/pure/proposals/array-constructor.d.ts b/packages/core-js-types/src/base/pure/proposals/array-constructor.d.ts new file mode 100644 index 000000000000..98a056555d9d --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/array-constructor.d.ts @@ -0,0 +1,43 @@ +/// +/// + +// Motivation: We must omit methods `fromAsync` and `isTemplateObject` because they cause a signature mismatch error. + +// https://github.com/tc39/proposal-array-is-template-object + +// https://github.com/tc39/proposal-array-from-async + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/069de743dbd17b47cc2fc58e1d16da5410911284/src/lib/esnext.array.d.ts#L6 +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +declare namespace CoreJS { + type ArrayConstructorBase = Omit; + + export interface CoreJSArrayConstructor extends ArrayConstructorBase { + /** + * Creates an array from an async iterator or iterable object. + * @param iterableOrArrayLike - An async iterator or array-like object to convert to an array. + */ + fromAsync(iterableOrArrayLike: CoreJSAsyncIterable | Iterable> | ArrayLike>): CoreJSPromise; + + /** + * Creates an array from an async iterator or iterable object. + * + * @param iterableOrArrayLike - An async iterator or array-like object to convert to an array. + * @param mapFn - A mapping function to call on every element of iterableOrArrayLike. + * Each return value is awaited before being added to result array. + * @param thisArg - Value of 'this' used when executing mapFn. + */ + fromAsync(iterableOrArrayLike: CoreJSAsyncIterable | Iterable | ArrayLike, mapFn: (value: Awaited, index: number) => U, thisArg?: any): CoreJSPromise[]>; + + /** + * Determines whether a `value` is a `TemplateStringsArray` + * @param value - The value to be checked + * @returns `true` if `value` is a `TemplateStringsArray`, otherwise `false` + */ + isTemplateObject(value: any): value is TemplateStringsArray; + } + + var CoreJSArray: CoreJSArrayConstructor; +} diff --git a/packages/core-js-types/src/base/pure/proposals/array-from-async.d.ts b/packages/core-js-types/src/base/pure/proposals/array-from-async.d.ts new file mode 100644 index 000000000000..e1c84e60cb71 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/array-from-async.d.ts @@ -0,0 +1,2 @@ +// empty +// Moved to ./array-constructor.d.ts diff --git a/packages/core-js-types/src/base/pure/proposals/async-iteration.d.ts b/packages/core-js-types/src/base/pure/proposals/async-iteration.d.ts new file mode 100644 index 000000000000..3d883ae22930 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/async-iteration.d.ts @@ -0,0 +1,2 @@ +// empty +// Moved to ./symbol.d.ts diff --git a/packages/core-js-types/src/base/pure/proposals/async-iterator-helpers-custom.d.ts b/packages/core-js-types/src/base/pure/proposals/async-iterator-helpers-custom.d.ts new file mode 100644 index 000000000000..6909a5b8e883 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/async-iterator-helpers-custom.d.ts @@ -0,0 +1,14 @@ +/// +/// + +// Motivation: Using our own type for AsyncIteratorObject + +// https://github.com/tc39/proposal-async-iterator-helpers + +declare namespace CoreJS { + export type AsyncIteratorFlatMap = (callback: (value: T, index: number) => Iterator | Iterable | CoreJS.CoreJSAsyncIterator | CoreJS.CoreJSAsyncIterable) => CoreJS.CoreJSAsyncIteratorObject; + + export type AsyncIteratorMap = (callbackfn: (value: T, index: number) => U) => CoreJS.CoreJSAsyncIteratorObject, undefined, unknown>; + + export type AsyncIteratorReduce = (callbackfn: (accumulator: U, value: T, index: number) => U, initialValue?: U) => CoreJS.CoreJSPromise; +} diff --git a/packages/core-js-types/src/base/pure/proposals/async-iterator-helpers.d.ts b/packages/core-js-types/src/base/pure/proposals/async-iterator-helpers.d.ts new file mode 100644 index 000000000000..d424f90227f3 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/async-iterator-helpers.d.ts @@ -0,0 +1,125 @@ +/// +/// +/// + +// Motivation: Has dependencies on internal types, e.g. AsyncIterable, AsyncIteratorObject + +// https://github.com/tc39/proposal-async-iterator-helpers + +declare namespace CoreJS { + export interface CoreJSAsyncIteratorConstructor { + /** + * Creates an `AsyncIterator` from an iterable object + * @param iterable - An `AsyncIterable`, `Iterable`, or `AsyncIterator` to convert to an `AsyncIterator` + * @returns A new `AsyncIterator` instance + */ + from(iterable: CoreJSAsyncIterable | Iterable | CoreJSAsyncIterator): CoreJSAsyncIteratorObject; + } + + export interface CoreJSAsyncIterator { + + /** + * Drops elements from the iterator until the limit is reached + * @param limit - The number of elements to drop + * @returns A new `AsyncIterator` + */ + drop(limit: number): CoreJSAsyncIteratorObject; + + /** + * Check if every value generated by the iterator passes the `predicate` function. + * @param predicate - A function that tests each element of the iterator + * @returns A `Promise` that resolves to `true` if all elements pass the test, otherwise `false` + */ + every(predicate: (value: T, index: number) => unknown): CoreJSPromise; + + /** + * Creates a new `AsyncIterator` that contains only the elements that pass the `predicate` function. + * @param predicate - A function that tests each element of the iterator + * @returns A new `AsyncIterator` + */ + filter(predicate: (value: T, index: number) => value is S): CoreJSAsyncIteratorObject; + filter(predicate: (value: T, index: number) => unknown): CoreJSAsyncIteratorObject; + + /** + * Finds the first element in the iterator that satisfies the `predicate` function. + * @param predicate - A function that tests each element of the iterator + * @returns A `Promise` that resolves to the found element, or `undefined` if no element satisfies the `predicate` + */ + find(predicate: (value: T, index: number) => value is S): CoreJSPromise; + find(predicate: (value: T, index: number) => unknown): CoreJSPromise; + + /** + * Creates a new `AsyncIterator` by applying the `callback` function to each element of the original iterator and flattening the result. + * @param callback - A function that transforms each element of the iterator + * @returns A new `AsyncIterator` + */ + flatMap(callback: (value: T, index: number) => Iterator | Iterable | CoreJSAsyncIterator | CoreJSAsyncIterable): CoreJSAsyncIteratorObject; + + /** + * Executes a provided function once for each element in the iterator. + * @param callbackfn - A function that is called for each element of the iterator + * @returns A `Promise` that resolves when all elements have been processed + */ + forEach(callbackfn: (value: T, index: number) => void | PromiseLike): CoreJSPromise; + + /** + * Creates a new `AsyncIterator` by applying the `callbackfn` function to each element of the original iterator. + * @param callbackfn - A function that transforms each element of the iterator + * @returns A new `AsyncIterator` + */ + map(callbackfn: (value: T, index: number) => U): CoreJSAsyncIteratorObject, undefined, unknown>; + + /** + * Reduces the elements of the iterator to a single value using the `callbackfn` function. + * @param callbackfn - A function that combines two elements of the iterator + * @returns A `Promise` that resolves to the reduced value + */ + reduce(callbackfn: (accumulator: T, value: T, index: number) => T): CoreJSPromise; + + /** + * Reduces the elements of the iterator to a single value using the `callbackfn` function. + * @param callbackfn - A function that combines two elements of the iterator + * @param initialValue - The initial value to start the reduction + * @returns A `Promise` that resolves to the reduced value + */ + reduce(callbackfn: (accumulator: T, value: T, index: number) => T, initialValue: T): CoreJSPromise; + + /** + * Reduces the elements of the iterator to a single value using the `callbackfn` function. + * @param callbackfn - A function that combines two elements of the iterator + * @param initialValue - The initial value to start the accumulation. Required when the accumulator type differs from the element type. + * @returns A `Promise` that resolves to the reduced value + */ + reduce(callbackfn: (accumulator: U, value: T, index: number) => U, initialValue: U): CoreJSPromise; + + /** + * Checks if any value in the iterator matches a given `predicate` + * @param predicate - A function that tests each element of the iterator + * @returns A `Promise` that resolves to `true` if any element passes the `predicate`, otherwise `false` + */ + some(predicate: (value: T, index: number) => unknown): CoreJSPromise; + + /** + * Creates a new `AsyncIterator` that yields only the first `limit` elements from the original iterator. + * @param limit - The maximum number of elements to take + * @returns A new `AsyncIterator` + */ + take(limit: number): CoreJSAsyncIteratorObject; + + /** + * Collects all elements from the iterator into an array. + * @returns A `Promise` that resolves to an array containing all elements from the iterator + */ + toArray(): CoreJSPromise; + } + + var CoreJSAsyncIterator: CoreJSAsyncIteratorConstructor; + + interface CoreJSIterator extends Iterator { + /** + * Creates an `AsyncIterator` from the current `Iterator` + * @returns A new `AsyncIterator` instance + */ + toAsync(): CoreJSAsyncIteratorObject; + } +} diff --git a/packages/core-js-types/src/base/pure/proposals/await-dictionary.d.ts b/packages/core-js-types/src/base/pure/proposals/await-dictionary.d.ts new file mode 100644 index 000000000000..0bb054ebfc51 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/await-dictionary.d.ts @@ -0,0 +1,2 @@ +// empty +// Moved to ../core-js-types/promise.d.ts diff --git a/packages/core-js-types/src/base/pure/proposals/collection-of-from.d.ts b/packages/core-js-types/src/base/pure/proposals/collection-of-from.d.ts new file mode 100644 index 000000000000..69ae1cac0a47 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/collection-of-from.d.ts @@ -0,0 +1,95 @@ +/// +/// +/// +/// + +// Motivation: import our own Map/Set/WeakMap/WeakSet types & redefine return types + +// https://github.com/tc39/proposal-setmap-offrom + +declare namespace CoreJS { + export interface CoreJSMapConstructor extends MapConstructor { + /** + * Creates a new `Map` instance from an iterable object of [key, value] pairs. + * Optionally, applies a mapping function to each pair. + * @param source - Iterable object of [key, value] pairs. + * @param mapFn - Function to call on every [key, value] pair before adding to the `Map`. + * @param thisArg - Value to use as this when executing mapFn. + * @returns A new `Map` instance. + */ + from(source: Iterable<[K, V]>, mapFn?: (entry: [K, V], index: number) => [KOut, VOut], thisArg?: any): CoreJS.CoreJSMap; + + /** + * Creates a new `Map` instance from a variable number of arguments, + * where each pair of arguments is interpreted as a key and a value. + * @param items - An even number of arguments representing key-value pairs. + * @returns A new `Map` instance. + */ + of(...items: [K, V][]): CoreJS.CoreJSMap; + } + + var CoreJSMap: CoreJSMapConstructor; + + export interface CoreJSSetConstructor extends SetConstructor { + /** + * Creates a new `Set` instance from an iterable, optionally transforming elements with a mapping function. + * @param source - Iterable whose elements will be added to the new Set. + * @param mapFn - Optional mapping function. Transforms each element before adding to Set. + * @param thisArg - Value to use as `this` when executing `mapFn`. + * @returns A new `Set` instance + */ + from(source: Iterable, mapFn?: (value: T, index: number) => U, thisArg?: any): CoreJS.CoreJSSet; + + /** + * Creates a new `Set` instance from a variable number of arguments. + * Each argument becomes an element of the Set. + * @param items - Zero or more arguments to add as Set elements. + * @returns A new `Set` instance + */ + of(...items: T[]): CoreJS.CoreJSSet; + } + + var CoreJSSet: CoreJSSetConstructor; + + export interface CoreJSWeakMapConstructor extends WeakMapConstructor { + /** + * Creates a new `WeakMap` instance from an iterable object of [key, value] pairs. + * Optionally, applies a mapping function to each pair. + * @param source - Iterable object of [key, value] pairs. + * @param mapFn - Function to call on every [key, value] pair before adding to the `WeakMap`. + * @param thisArg - Value to use as this when executing mapFn. + * @returns A new `WeakMap` instance. + */ + from(source: Iterable<[K, V]>, mapFn?: (entry: [K, V], index: number) => [KOut, VOut], thisArg?: any): CoreJS.CoreJSWeakMap; + + /** + * Creates a new `WeakMap` instance from a variable number of arguments, + * where each pair of arguments is interpreted as a key and a value. + * @param items - An even number of arguments representing key-value pairs. + * @returns A new `WeakMap` instance. + */ + of(...items: [K, V][]): CoreJS.CoreJSWeakMap; + } + + var CoreJSWeakMap: CoreJSWeakMapConstructor; + + export interface CoreJSWeakSetConstructor extends WeakSetConstructor { + /** + * Creates a new `WeakSet` instance from an iterable of objects, optionally transforming with mapFn. + * @param source - Iterable of objects to add to WeakSet. + * @param mapFn - Optional mapping function transforming each object. + * @param thisArg - Value to use as `this` in `mapFn`. + * @returns New `WeakSet` instance. + */ + from(source: Iterable, mapFn?: (value: T, index: number) => U, thisArg?: any): CoreJS.CoreJSWeakSet; + + /** + * Creates a new `WeakSet` instance from object arguments. + * @param items - Zero or more objects to add as WeakSet elements. + * @returns New `WeakSet` instance. + */ + of(...items: T[]): CoreJS.CoreJSWeakSet; + } + + var CoreJSWeakSet: CoreJSWeakSetConstructor; +} diff --git a/packages/core-js-types/src/base/pure/proposals/decorator-metadata.d.ts b/packages/core-js-types/src/base/pure/proposals/decorator-metadata.d.ts new file mode 100644 index 000000000000..b78c80bd344d --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/decorator-metadata.d.ts @@ -0,0 +1,15 @@ +/// + +// Motivation: Symbol is replaced with our own + +// https://github.com/tc39/proposal-decorator-metadata + +declare namespace CoreJS { + // Symbol.metadata is moved to ./symbol.d.ts + + var CoreJSFunction: CoreJSFunction; + + export interface CoreJSFunction extends Function { + [CoreJS.CoreJSSymbol.metadata]: Record & object | null; + } +} diff --git a/packages/core-js-types/src/base/pure/proposals/explicit-resource-management.d.ts b/packages/core-js-types/src/base/pure/proposals/explicit-resource-management.d.ts new file mode 100644 index 000000000000..e83d32ee2e06 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/explicit-resource-management.d.ts @@ -0,0 +1,165 @@ +/// +/// + +// Motivation: Symbol is replaced with our own + +// https://github.com/tc39/proposal-explicit-resource-management + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/0a1aa6d6ebdfa16b82f4a6aaf282089b1d484e05/src/lib/esnext.disposable.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +declare namespace CoreJS { + export interface CoreJSDisposable { + [CoreJSSymbol.dispose](): void; + } + + var CoreJSDisposable: CoreJSDisposable; + + export interface CoreJSAsyncDisposable { + [CoreJSSymbol.asyncDispose](): PromiseLike; + } + + var CoreJSAsyncDisposable: CoreJSAsyncDisposable; + + export interface CoreJSSuppressedError extends Error { + error: any; + suppressed: any; + } + + export interface CoreJSSuppressedErrorConstructor { + readonly prototype: CoreJSSuppressedError; + + new(error: any, suppressed: any, message?: string): CoreJSSuppressedError; + + (error: any, suppressed: any, message?: string): CoreJSSuppressedError; + } + + var CoreJSSuppressedError: CoreJSSuppressedErrorConstructor; + + var CoreJSDisposableStack: CoreJSDisposableStackConstructor; + + export interface CoreJSDisposableStack { + /** + * Returns a value indicating whether this stack has been disposed. + */ + readonly disposed: boolean; + readonly [CoreJSSymbol.toStringTag]: string; + + /** + * Disposes each resource in the stack in the reverse order that they were added. + */ + dispose(): void; + + /** + * Adds a disposable resource to the stack, returning the resource. + * @param value - The resource to add. `null` and `undefined` will not be added, but will be returned. + * @returns The provided {@link value}. + */ + use(value: T): T; + + /** + * Adds a value and associated disposal callback as a resource to the stack. + * @param value - The value to add. + * @param onDispose - The callback to use in place of a `[CoreJSSymbol.dispose]()` method. Will be invoked with `value` + * as the first parameter. + * @returns The provided {@link value}. + */ + adopt(value: T, onDispose: (value: T) => void): T; + + /** + * Adds a callback to be invoked when the stack is disposed. + */ + defer(onDispose: () => void): void; + + /** + * Move all resources out of this stack and into a new `DisposableStack`, and marks this stack as disposed. + * @example + * ```ts + * class C { + * #res1: Disposable; + * #res2: Disposable; + * #disposables: DisposableStack; + * constructor() { + * // stack will be disposed when exiting constructor for any reason + * using stack = new DisposableStack(); + * + * // get first resource + * this.#res1 = stack.use(getResource1()); + * + * // get second resource. If this fails, both `stack` and `#res1` will be disposed. + * this.#res2 = stack.use(getResource2()); + * + * // all operations succeeded, move resources out of `stack` so that they aren't disposed + * // when constructor exits + * this.#disposables = stack.move(); + * } + * + * [CoreJSSymbol.dispose]() { + * this.#disposables.dispose(); + * } + * } + * ``` + */ + move(): CoreJSDisposableStack; + + [CoreJSSymbol.dispose](): void; + } + + export interface CoreJSDisposableStackConstructor { + readonly prototype: CoreJSDisposableStack; + + new(): CoreJSDisposableStack; + } + + var CoreJSAsyncDisposableStack: CoreJSAsyncDisposableStackConstructor; + + export interface CoreJSAsyncDisposableStack { + + /** + * Returns a value indicating whether this stack has been disposed. + */ + readonly disposed: boolean; + readonly [CoreJSSymbol.toStringTag]: string; + + /** + * Disposes each resource in the stack in the reverse order that they were added. + */ + disposeAsync(): CoreJS.CoreJSPromise; + + /** + * Adds a disposable resource to the stack, returning the resource. + * @param value - The resource to add. `null` and `undefined` will not be added, but will be returned. + * @returns The provided {@link value}. + */ + use(value: T): T; + + /** + * Adds a value and associated disposal callback as a resource to the stack. + * @param value - The value to add. + * @param onDisposeAsync - The callback to use in place of a `[CoreJSSymbol.asyncDispose]()` method. Will be invoked with `value` + * as the first parameter. + * @returns The provided {@link value}. + */ + adopt(value: T, onDisposeAsync: (value: T) => PromiseLike | void): T; + + /** + * Adds a callback to be invoked when the stack is disposed. + */ + defer(onDisposeAsync: () => PromiseLike | void): void; + + /** + * Move all resources out of this stack and into a new `AsyncDisposableStack`, and marks this stack as disposed. + */ + move(): CoreJSAsyncDisposableStack; + + [CoreJSSymbol.asyncDispose](): CoreJS.CoreJSPromise; + } + + export interface CoreJSAsyncDisposableStackConstructor { + + readonly prototype: CoreJSAsyncDisposableStack; + + new(): CoreJSAsyncDisposableStack; + } +} diff --git a/packages/core-js-types/src/base/pure/proposals/iterator-chunking.d.ts b/packages/core-js-types/src/base/pure/proposals/iterator-chunking.d.ts new file mode 100644 index 000000000000..7da4b2567937 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/iterator-chunking.d.ts @@ -0,0 +1,2 @@ +// empty +// Moved to ./iterator.d.ts diff --git a/packages/core-js-types/src/base/pure/proposals/iterator-helpers-custom.d.ts b/packages/core-js-types/src/base/pure/proposals/iterator-helpers-custom.d.ts new file mode 100644 index 000000000000..0e4e335f2ba7 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/iterator-helpers-custom.d.ts @@ -0,0 +1,17 @@ +/// + +// Motivation: Using our own type for IteratorObject + +// https://github.com/tc39/proposal-iterator-helpers + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/d3be7e171bf3149fe93c3ce5a85280f1eba3ef8d/src/lib/esnext.iterator.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +declare namespace CoreJS { + export type IteratorFlatMap = (callback: (value: T, index: number) => Iterator | Iterable) => CoreJS.CoreJSIteratorObject; + + export type IteratorMap = (callbackfn: (value: T, index: number) => U) => CoreJS.CoreJSIteratorObject; + + export type IteratorReduce = (callbackfn: (previousValue: U, currentValue: T, currentIndex: number) => U, initialValue?: U) => U; +} diff --git a/packages/core-js-types/src/base/pure/proposals/iterator-helpers.d.ts b/packages/core-js-types/src/base/pure/proposals/iterator-helpers.d.ts new file mode 100644 index 000000000000..7da4b2567937 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/iterator-helpers.d.ts @@ -0,0 +1,2 @@ +// empty +// Moved to ./iterator.d.ts diff --git a/packages/core-js-types/src/base/pure/proposals/iterator-join.d.ts b/packages/core-js-types/src/base/pure/proposals/iterator-join.d.ts new file mode 100644 index 000000000000..7da4b2567937 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/iterator-join.d.ts @@ -0,0 +1,2 @@ +// empty +// Moved to ./iterator.d.ts diff --git a/packages/core-js-types/src/base/pure/proposals/iterator-joint.d.ts b/packages/core-js-types/src/base/pure/proposals/iterator-joint.d.ts new file mode 100644 index 000000000000..7da4b2567937 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/iterator-joint.d.ts @@ -0,0 +1,2 @@ +// empty +// Moved to ./iterator.d.ts diff --git a/packages/core-js-types/src/base/pure/proposals/iterator-range.d.ts b/packages/core-js-types/src/base/pure/proposals/iterator-range.d.ts new file mode 100644 index 000000000000..7da4b2567937 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/iterator-range.d.ts @@ -0,0 +1,2 @@ +// empty +// Moved to ./iterator.d.ts diff --git a/packages/core-js-types/src/base/pure/proposals/iterator-sequencing.d.ts b/packages/core-js-types/src/base/pure/proposals/iterator-sequencing.d.ts new file mode 100644 index 000000000000..7da4b2567937 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/iterator-sequencing.d.ts @@ -0,0 +1,2 @@ +// empty +// Moved to ./iterator.d.ts diff --git a/packages/core-js-types/src/base/pure/proposals/iterator.d.ts b/packages/core-js-types/src/base/pure/proposals/iterator.d.ts new file mode 100644 index 000000000000..e9aa8430a169 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/iterator.d.ts @@ -0,0 +1,227 @@ +/// +/// +/// +/// + +// Motivation: Has dependencies on internal types + +// https://github.com/tc39/proposal-iterator-chunking + +// https://github.com/tc39/proposal-iterator-helpers + +// https://github.com/bakkot/proposal-iterator-join + +// https://github.com/tc39/proposal-joint-iteration + +// https://github.com/tc39/proposal-iterator.range + +// https://github.com/tc39/proposal-iterator-sequencing + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/d3be7e171bf3149fe93c3ce5a85280f1eba3ef8d/src/lib/esnext.iterator.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +declare namespace CoreJS { + interface ZipOptions { + mode?: 'shortest' | 'longest' | 'strict'; + + padding?: Iterable; + } + + interface ZipKeyedOptions { + mode?: 'shortest' | 'longest' | 'strict'; + + padding?: Record; + } + + interface IteratorRangeOptions { + step?: T; + + inclusive?: boolean; + } + + export interface CoreJSAsyncIteratorObject extends CoreJS.CoreJSAsyncIterator {} + export interface CoreJSAsyncIteratorObject extends CoreJSAsyncDisposable {} + export interface CoreJSAsyncIterable { + [CoreJSSymbol.asyncIterator](): CoreJS.CoreJSAsyncIterator; + } + + export interface CoreJSIteratorObject extends CoreJSDisposable {} + + export interface CoreJSIterator extends Iterator { + /** + * Yields arrays containing up to the specified number of elements + * chunked from the source iterator. + * @param chunkSize - The maximum number of elements per chunk. Must be a positive integer. + * @returns An iterator yielding arrays of at most `chunkSize` elements from the source iterator. + */ + chunks(chunkSize: number): CoreJSIteratorObject; + + /** + * Yields overlapping arrays (windows) of the given size from the iterator. + * @param windowSize - The size of each window. Must be a positive integer. + * @param undersized - 'only-full' (default) to yield only full windows | 'allow-partial' to yield all windows. + * @returns An iterator yielding arrays of the specified window size. + */ + windows(windowSize: number, undersized?: 'only-full' | 'allow-partial' | undefined): CoreJSIteratorObject; + + /** + * Creates an iterator whose values are the result of applying the callback to the values from this iterator. + * @param callbackfn - A function that accepts up to two arguments to be used to transform values from the underlying iterator. + */ + map(callbackfn: (value: T, index: number) => U): CoreJSIteratorObject; + + /** + * Creates an iterator whose values are those from this iterator for which the provided predicate returns true. + * @param predicate - A function that accepts up to two arguments to be used to test values from the underlying iterator. + */ + filter(predicate: (value: T, index: number) => value is S): CoreJSIteratorObject; + /** + * Creates an iterator whose values are those from this iterator for which the provided predicate returns true. + * @param predicate - A function that accepts up to two arguments to be used to test values from the underlying iterator. + */ + filter(predicate: (value: T, index: number) => unknown): CoreJSIteratorObject; + + /** + * Creates an iterator whose values are the values from this iterator, stopping once the provided limit is reached. + * @param limit - The maximum number of values to yield. + */ + take(limit: number): CoreJSIteratorObject; + + /** + * Creates an iterator whose values are the values from this iterator after skipping the provided count. + * @param count - The number of values to drop. + */ + drop(count: number): CoreJSIteratorObject; + + /** + * Creates an iterator whose values are the result of applying the callback to the values from this iterator and then flattening the resulting iterators or iterables. + * @param callback - A function that accepts up to two arguments to be used to transform values from the underlying iterator into new iterators or iterables to be flattened into the result. + */ + flatMap(callback: (value: T, index: number) => Iterator | Iterable): CoreJSIteratorObject; + + /** + * Calls the specified callback function for all the elements in this iterator. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn - A function that accepts up to three arguments. The reduce method calls the callbackfn function one time for each element in the iterator. + */ + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number) => T): T; + /** + * Calls the specified callback function for all the elements in this iterator. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn - A function that accepts up to three arguments. The reduce method calls the callbackfn function one time for each element in the iterator. + * @param initialValue - If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of a value from the iterator. + */ + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number) => T, initialValue: T): T; + /** + * Calls the specified callback function for all the elements in this iterator. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn - A function that accepts up to three arguments. The reduce method calls the callbackfn function one time for each element in the iterator. + * @param initialValue - If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of a value from the iterator. + */ + reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number) => U, initialValue: U): U; + + /** + * Creates a new array from the values yielded by this iterator. + */ + toArray(): T[]; + + /** + * Performs the specified action for each element in the iterator. + * @param callbackfn - A function that accepts up to two arguments. forEach calls the callbackfn function one time for each element in the iterator. + */ + forEach(callbackfn: (value: T, index: number) => void): void; + + /** + * Determines whether the specified callback function returns true for any element of this iterator. + * @param predicate - A function that accepts up to two arguments. The `some` method calls + * the predicate function for each element in this iterator until the predicate returns a value + * true, or until the end of the iterator. + */ + some(predicate: (value: T, index: number) => unknown): boolean; + + /** + * Determines whether all the members of this iterator satisfy the specified test. + * @param predicate - A function that accepts up to two arguments. The every method calls + * the predicate function for each element in this iterator until the predicate returns + * false, or until the end of this iterator. + */ + every(predicate: (value: T, index: number) => unknown): boolean; + + /** + * Returns the value of the first element in this iterator where predicate is true, and undefined + * otherwise. + * @param predicate - find calls predicate once for each element of this iterator, in + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + */ + find(predicate: (value: T, index: number) => value is S): S | undefined; + find(predicate: (value: T, index: number) => unknown): T | undefined; + + /** + * Creates a string by concatenating all elements provided by the iterator, separated by the specified separator. + * @param separator - A string to separate each element. If omitted, the elements are separated by commas. + */ + join(separator?: unknown): string; + } + + export interface CoreJSIteratorConstructor { + /** + * Creates a native iterator from an iterator or iterable object. + * Returns its input if the input already inherits from the built-in Iterator class. + * @param value - An iterator or iterable object to convert to a native iterator. + */ + from(value: Iterator | Iterable): CoreJSIteratorObject; + + /** + * Takes an iterable of iterables and produces an iterable of arrays where position corresponds + * to position in the passed iterable. + * @param iterables - An Iterable of iterables. + * @param options - Optional object: + * - mode: 'shortest' (default) to stop at the shortest iterable | 'longest' to stop at the longest iterable | 'strict' to throw if iterables are not the same length; + * - padding: an iterable specifying padding values for each position when mode is 'longest'. + * @returns An iterator yielding arrays of values, collected one from each iterable. + */ + zip[]>(iterables: T, options?: ZipOptions): CoreJSIteratorObject<{ [K in keyof T]: T[K] extends Iterable ? V : never }, undefined, unknown>; + zip(iterables: Iterable>, options?: ZipOptions): CoreJSIteratorObject; + + /** + * Takes an object whose values are iterables and produces an iterable of objects where keys + * correspond to keys in the passed object. + * @param record - An object of iterables. + * @param options - Optional object: + * - mode: 'shortest' (default) to stop at the shortest iterable | 'longest' to stop at the longest iterable | 'strict' to throw if iterables are not the same length; + * - padding: an object specifying padding values for each key when mode is 'longest'. + * @returns An iterator yielding objects with keys from the input record and values from the corresponding iterables. + */ + zipKeyed }>(record: T, options?: ZipKeyedOptions): CoreJSIteratorObject<{ [K in keyof T]: T[K] extends Iterable ? V : never; }, undefined, unknown>; + + /** + * Returns an iterator that generates a sequence of numbers within a range. + * @param start - The starting value of the sequence. + * @param end - The end value of the sequence (exclusive by default). + * @param options - Optional object: + * - step: The difference between consecutive values (default is 1). + * - inclusive: If true, the end value is included in the range (default is false). + * @returns An iterator of numbers. + */ + range(start: number, end: number | typeof Infinity | typeof Number.NEGATIVE_INFINITY, options?: number | IteratorRangeOptions): CoreJSIteratorObject; + + /** + * Returns an iterator that generates a sequence of bigints within a range. + * @param start - The starting value of the sequence. + * @param end - The end value of the sequence (exclusive by default). + * @param options - Optional object: + * - step: The difference between consecutive values (default is 1n). + * - inclusive: If true, the end value is included in the range (default is false). + * @returns An iterator of bigints. + */ + range(start: bigint, end: bigint, options?: bigint | IteratorRangeOptions): CoreJSIteratorObject; + + /** + * Creates an iterator that sequentially yields values from the provided iterables. + * @param iterators - The iterables to concatenate. + * @returns An iterator yielding values from each input iterable in sequence. + */ + concat[]>(...iterators: T): CoreJSIteratorObject ? V : never, undefined, unknown>; + } + + var CoreJSIterator: CoreJSIteratorConstructor; +} diff --git a/packages/core-js-types/src/base/pure/proposals/pattern-matching.d.ts b/packages/core-js-types/src/base/pure/proposals/pattern-matching.d.ts new file mode 100644 index 000000000000..3d883ae22930 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/pattern-matching.d.ts @@ -0,0 +1,2 @@ +// empty +// Moved to ./symbol.d.ts diff --git a/packages/core-js-types/src/base/pure/proposals/promise-all-settled.d.ts b/packages/core-js-types/src/base/pure/proposals/promise-all-settled.d.ts new file mode 100644 index 000000000000..0bb054ebfc51 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/promise-all-settled.d.ts @@ -0,0 +1,2 @@ +// empty +// Moved to ../core-js-types/promise.d.ts diff --git a/packages/core-js-types/src/base/pure/proposals/promise-any.d.ts b/packages/core-js-types/src/base/pure/proposals/promise-any.d.ts new file mode 100644 index 000000000000..0bb054ebfc51 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/promise-any.d.ts @@ -0,0 +1,2 @@ +// empty +// Moved to ../core-js-types/promise.d.ts diff --git a/packages/core-js-types/src/base/pure/proposals/promise-try.d.ts b/packages/core-js-types/src/base/pure/proposals/promise-try.d.ts new file mode 100644 index 000000000000..0bb054ebfc51 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/promise-try.d.ts @@ -0,0 +1,2 @@ +// empty +// Moved to ../core-js-types/promise.d.ts diff --git a/packages/core-js-types/src/base/pure/proposals/promise-with-resolvers.d.ts b/packages/core-js-types/src/base/pure/proposals/promise-with-resolvers.d.ts new file mode 100644 index 000000000000..0bb054ebfc51 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/promise-with-resolvers.d.ts @@ -0,0 +1,2 @@ +// empty +// Moved to ../core-js-types/promise.d.ts diff --git a/packages/core-js-types/src/base/pure/proposals/relative-indexing-method.d.ts b/packages/core-js-types/src/base/pure/proposals/relative-indexing-method.d.ts new file mode 100644 index 000000000000..f69f8d3d6f96 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/relative-indexing-method.d.ts @@ -0,0 +1,28 @@ +/// + +// Motivation: We should use String without the matchAll method to avoid signature conflicts + +// https://github.com/tc39/proposal-relative-indexing-method + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/f450c1b80ce6dc7b04e81899db00534018932234/src/lib/es2022.array.d.ts +// https://github.com/microsoft/TypeScript/blob/f450c1b80ce6dc7b04e81899db00534018932234/src/lib/es2022.string.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +declare namespace CoreJS { + interface CoreJSString extends StringBase { + /** + * Returns a new String consisting of the single UTF-16 code unit located at the specified index. + * @param index - The zero-based index of the desired code unit. A negative index will count back from the last item. + */ + at(index: number): string | undefined; + } + + interface CoreJSArray extends Array { + /** + * Returns the item located at the specified index. + * @param index - The zero-based index of the desired code unit. A negative index will count back from the last item. + */ + at(index: number): T | undefined; + } +} diff --git a/packages/core-js-types/src/base/pure/proposals/set-methods-custom.d.ts b/packages/core-js-types/src/base/pure/proposals/set-methods-custom.d.ts new file mode 100644 index 000000000000..53737eddf9f8 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/set-methods-custom.d.ts @@ -0,0 +1,23 @@ +/// + +// Motivation: Custom type needed to keep generics strict & return our CoreJSSet type + +// https://github.com/tc39/proposal-set-methods + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/f450c1b80ce6dc7b04e81899db00534018932234/src/lib/esnext.collection.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +declare namespace CoreJS { + interface ReadonlySetLike { + keys(): Iterator; + + has(value: T): boolean; + + readonly size: number; + } + + export type SetUnion = (other: ReadonlySetLike) => CoreJS.CoreJSSet; + + export type SetSymmetricDifference = (other: ReadonlySetLike) => CoreJS.CoreJSSet; +} diff --git a/packages/core-js-types/src/base/pure/proposals/string-left-right-trim.d.ts b/packages/core-js-types/src/base/pure/proposals/string-left-right-trim.d.ts new file mode 100644 index 000000000000..59bdf0872ff4 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/string-left-right-trim.d.ts @@ -0,0 +1,29 @@ +/// + +// Motivation: We should use String without the matchAll method to avoid signature conflicts + +// https://github.com/tc39/proposal-string-left-right-trim + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/f450c1b80ce6dc7b04e81899db00534018932234/src/lib/es2019.string.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +declare namespace CoreJS { + export interface CoreJSString extends StringBase { + /** Removes the trailing white space and line terminator characters from a string. */ + trimEnd(): string; + + /** Removes the leading white space and line terminator characters from a string. */ + trimStart(): string; + + /** + * Removes the leading white space and line terminator characters from a string. + */ + trimLeft(): string; + + /** + * Removes the trailing white space and line terminator characters from a string. + */ + trimRight(): string; + } +} diff --git a/packages/core-js-types/src/base/pure/proposals/string-match-all.d.ts b/packages/core-js-types/src/base/pure/proposals/string-match-all.d.ts new file mode 100644 index 000000000000..eaef63f867f3 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/string-match-all.d.ts @@ -0,0 +1,32 @@ +/// +/// + +// Motivation: We should use String without the matchAll method to avoid signature conflicts + +// https://github.com/tc39/proposal-string-matchall + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/f450c1b80ce6dc7b04e81899db00534018932234/src/lib/es2020.string.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +declare namespace CoreJS { + interface CoreJSRegExpStringIterator extends CoreJSIteratorObject { + [Symbol.iterator](): CoreJSRegExpStringIterator; + } + + export interface CoreJSString extends StringBase { + + /** + * Matches a string with a regular expression, and returns an iterable of matches + * containing the results of that search. + * @param regexp - A variable name or string literal containing the regular expression pattern and flags. + */ + matchAll(regexp: RegExp): CoreJSRegExpStringIterator; + } + + export interface CoreJSStringConstructor extends StringConstructor { + new(value?: any): CoreJSString; + } + + var CoreJSString: CoreJSStringConstructor; +} diff --git a/packages/core-js-types/src/base/pure/proposals/string-padding.d.ts b/packages/core-js-types/src/base/pure/proposals/string-padding.d.ts new file mode 100644 index 000000000000..495545a0d2e3 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/string-padding.d.ts @@ -0,0 +1,40 @@ +/// + +// Motivation: We should use String without the matchAll method to avoid signature conflicts + +// https://github.com/tc39/proposal-string-pad-start-end + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/f450c1b80ce6dc7b04e81899db00534018932234/src/lib/es2017.string.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +declare namespace CoreJS { + export interface CoreJSString extends StringBase { + + /** + * Pads the current string with a given string (possibly repeated) so that the resulting string reaches a given length. + * The padding is applied from the start (left) of the current string. + * + * @param maxLength - The length of the resulting string once the current string has been padded. + * If this parameter is smaller than the current string's length, the current string will be returned as it is. + * + * @param fillString - The string to pad the current string with. + * If this string is too long, it will be truncated and the left-most part will be applied. + * The default value for this parameter is " " (U+0020). + */ + padStart(maxLength: number, fillString?: string): string; + + /** + * Pads the current string with a given string (possibly repeated) so that the resulting string reaches a given length. + * The padding is applied from the end (right) of the current string. + * + * @param maxLength - The length of the resulting string once the current string has been padded. + * If this parameter is smaller than the current string's length, the current string will be returned as it is. + * + * @param fillString - The string to pad the current string with. + * If this string is too long, it will be truncated and the left-most part will be applied. + * The default value for this parameter is " " (U+0020). + */ + padEnd(maxLength: number, fillString?: string): string; + } +} diff --git a/packages/core-js-types/src/base/pure/proposals/string-replace-all.d.ts b/packages/core-js-types/src/base/pure/proposals/string-replace-all.d.ts new file mode 100644 index 000000000000..884d4c0d23ea --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/string-replace-all.d.ts @@ -0,0 +1,22 @@ +/// + +// Motivation: We should use String without the matchAll method to avoid signature conflicts + +// https://github.com/tc39/proposal-string-replaceall + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/4a957b74ea4d716356181644d23f6ad5f10824d6/src/lib/es2021.string.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +declare namespace CoreJS { + export interface CoreJSString extends StringBase { + + /** + * Replace all instances of a substring in a string, using a regular expression or search string. + * @param searchValue - A string to search for. + * @param replacer - A string containing the text to replace for every successful match of searchValue in this string + * - or function that returns the replacement text. + */ + replaceAll(searchValue: string | RegExp, replacer: string | ((substring: string, ...args: any[]) => string)): string; + } +} diff --git a/packages/core-js-types/src/base/pure/proposals/symbol-description.d.ts b/packages/core-js-types/src/base/pure/proposals/symbol-description.d.ts new file mode 100644 index 000000000000..3d883ae22930 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/symbol-description.d.ts @@ -0,0 +1,2 @@ +// empty +// Moved to ./symbol.d.ts diff --git a/packages/core-js-types/src/base/pure/proposals/symbol-predicates.d.ts b/packages/core-js-types/src/base/pure/proposals/symbol-predicates.d.ts new file mode 100644 index 000000000000..3d883ae22930 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/symbol-predicates.d.ts @@ -0,0 +1,2 @@ +// empty +// Moved to ./symbol.d.ts diff --git a/packages/core-js-types/src/base/pure/proposals/symbol.d.ts b/packages/core-js-types/src/base/pure/proposals/symbol.d.ts new file mode 100644 index 000000000000..2ed9cc30b9c5 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/symbol.d.ts @@ -0,0 +1,92 @@ +// Motivation: We should use all unique symbols in SymbolConstructor with fallback + +// https://github.com/tc39/proposal-explicit-resource-management + +// https://github.com/tc39/proposal-symbol-predicates + +// https://github.com/tc39/proposal-async-iteration + +// https://github.com/tc39/proposal-pattern-matching + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/069de743dbd17b47cc2fc58e1d16da5410911284/src/lib/es2018.asynciterable.d.ts#L4 + +// https://github.com/tc39/proposal-decorator-metadata + +// https://github.com/tc39/proposal-string-matchall + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/f450c1b80ce6dc7b04e81899db00534018932234/src/lib/es2020.string.d.ts + +// https://github.com/tc39/proposal-Symbol-description + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/f450c1b80ce6dc7b04e81899db00534018932234/src/lib/es2019.symbol.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +declare namespace CoreJS { + const CoreJSDisposeSymbol: unique symbol; + const CoreJSAsyncDisposeSymbol: unique symbol; + const CoreJSAsyncIteratorSymbol: unique symbol; + const CoreJSCustomMatcherSymbol: unique symbol; + const CoreJSMetadataSymbol: unique symbol; + const CoreJSMatchAllSymbol: unique symbol; + const CoreJSIteratorSymbol: unique symbol; + + type CoreJSDisposeSymbolType = typeof CoreJSDisposeSymbol; + type CoreJSAsyncDisposeSymbolType = typeof CoreJSAsyncDisposeSymbol; + type CoreJSAsyncIteratorSymbolType = typeof CoreJSAsyncIteratorSymbol; + type CoreJSCustomMatcherSymbolType = typeof CoreJSCustomMatcherSymbol; + type CoreJSMetadataSymbolType = typeof CoreJSMetadataSymbol; + type CoreJSMatchAllSymbolType = typeof CoreJSMatchAllSymbol; + type CoreJSIteratorSymbolType = typeof CoreJSIteratorSymbol; + + type GetNativeWithFallback = K extends keyof T ? T[K] : Fallback; + + export interface CoreJSSymbolConstructor extends SymbolConstructor { + /** + * A method that is used to release resources held by an object. Called by the semantics of the `using` statement. + */ + readonly dispose: GetNativeWithFallback; + + /** + * A method that is used to asynchronously release resources held by an object. Called by the semantics of the `await using` statement. + */ + readonly asyncDispose: GetNativeWithFallback; + + /** + * Determines whether the given value is a registered symbol. + * @param value - The value to check. + */ + isRegisteredSymbol(value: unknown): value is symbol; + + /** + * Determines whether the given value is a well-known symbol. + * @param value - The value to check. + */ + isWellKnownSymbol(value: unknown): value is symbol; + + /** + * A method that returns the default async iterator for an object. Called by the semantics of + * the for-await-of statement. + */ + readonly asyncIterator: GetNativeWithFallback; + + readonly customMatcher: GetNativeWithFallback; + + readonly metadata: GetNativeWithFallback; + + readonly matchAll: GetNativeWithFallback; + + readonly iterator: GetNativeWithFallback; + } + + export interface CoreJSSymbol extends Symbol { + /** + * Expose the [[Description]] internal slot of a symbol directly. + */ + readonly description: string | undefined; + } + + var CoreJSSymbol: CoreJSSymbolConstructor; +} diff --git a/packages/core-js-types/src/base/pure/proposals/typed-arrays.d.ts b/packages/core-js-types/src/base/pure/proposals/typed-arrays.d.ts new file mode 100644 index 000000000000..e6675dad3434 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/typed-arrays.d.ts @@ -0,0 +1,11 @@ +declare namespace CoreJS { + var CoreJSInt8Array: Int8ArrayConstructor; + var CoreJSUint8Array: Uint8ArrayConstructor; + var CoreJSUint8ClampedArray: Uint8ClampedArrayConstructor; + var CoreJSInt16Array: Int16ArrayConstructor; + var CoreJSUint16Array: Uint16ArrayConstructor; + var CoreJSInt32Array: Int32ArrayConstructor; + var CoreJSUint32Array: Uint32ArrayConstructor; + var CoreJSFloat32Array: Float32ArrayConstructor; + var CoreJSFloat64Array: Float64ArrayConstructor; +} diff --git a/packages/core-js-types/src/base/pure/proposals/well-formed-unicode-strings.d.ts b/packages/core-js-types/src/base/pure/proposals/well-formed-unicode-strings.d.ts new file mode 100644 index 000000000000..ed164914a013 --- /dev/null +++ b/packages/core-js-types/src/base/pure/proposals/well-formed-unicode-strings.d.ts @@ -0,0 +1,24 @@ +/// + +// Motivation: We should use String without the matchAll method to avoid signature conflicts + +// https://github.com/tc39/proposal-is-usv-string + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/f450c1b80ce6dc7b04e81899db00534018932234/src/lib/es2024.string.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +declare namespace CoreJS { + export interface CoreJSString extends StringBase { + + /** + * Returns true if all leading surrogates and trailing surrogates appear paired and in order. + */ + isWellFormed(): boolean; + + /** + * Returns a string where all lone or out-of-order surrogates have been replaced by the Unicode replacement character (U+FFFD). + */ + toWellFormed(): string; + } +} diff --git a/packages/core-js-types/src/base/pure/web/dom-exception.d.ts b/packages/core-js-types/src/base/pure/web/dom-exception.d.ts new file mode 100644 index 000000000000..205eb12c9318 --- /dev/null +++ b/packages/core-js-types/src/base/pure/web/dom-exception.d.ts @@ -0,0 +1,72 @@ +declare namespace CoreJS { + interface CoreJSDOMException extends Error { + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */ + readonly message: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */ + readonly name: string; + readonly INDEX_SIZE_ERR: 1; + readonly DOMSTRING_SIZE_ERR: 2; + readonly HIERARCHY_REQUEST_ERR: 3; + readonly WRONG_DOCUMENT_ERR: 4; + readonly INVALID_CHARACTER_ERR: 5; + readonly NO_DATA_ALLOWED_ERR: 6; + readonly NO_MODIFICATION_ALLOWED_ERR: 7; + readonly NOT_FOUND_ERR: 8; + readonly NOT_SUPPORTED_ERR: 9; + readonly INUSE_ATTRIBUTE_ERR: 10; + readonly INVALID_STATE_ERR: 11; + readonly SYNTAX_ERR: 12; + readonly INVALID_MODIFICATION_ERR: 13; + readonly NAMESPACE_ERR: 14; + readonly INVALID_ACCESS_ERR: 15; + readonly VALIDATION_ERR: 16; + readonly TYPE_MISMATCH_ERR: 17; + readonly SECURITY_ERR: 18; + readonly NETWORK_ERR: 19; + readonly ABORT_ERR: 20; + readonly URL_MISMATCH_ERR: 21; + readonly QUOTA_EXCEEDED_ERR: 22; + readonly TIMEOUT_ERR: 23; + readonly INVALID_NODE_TYPE_ERR: 24; + readonly DATA_CLONE_ERR: 25; + } + + interface CoreJSDOMExceptionConstructor { + prototype: CoreJSDOMException; + new(message?: string, name?: string): CoreJSDOMException; + new(message?: string, options?: { name?: string; cause?: unknown }): CoreJSDOMException; + readonly INDEX_SIZE_ERR: 1; + readonly DOMSTRING_SIZE_ERR: 2; + readonly HIERARCHY_REQUEST_ERR: 3; + readonly WRONG_DOCUMENT_ERR: 4; + readonly INVALID_CHARACTER_ERR: 5; + readonly NO_DATA_ALLOWED_ERR: 6; + readonly NO_MODIFICATION_ALLOWED_ERR: 7; + readonly NOT_FOUND_ERR: 8; + readonly NOT_SUPPORTED_ERR: 9; + readonly INUSE_ATTRIBUTE_ERR: 10; + readonly INVALID_STATE_ERR: 11; + readonly SYNTAX_ERR: 12; + readonly INVALID_MODIFICATION_ERR: 13; + readonly NAMESPACE_ERR: 14; + readonly INVALID_ACCESS_ERR: 15; + readonly VALIDATION_ERR: 16; + readonly TYPE_MISMATCH_ERR: 17; + readonly SECURITY_ERR: 18; + readonly NETWORK_ERR: 19; + readonly ABORT_ERR: 20; + readonly URL_MISMATCH_ERR: 21; + readonly QUOTA_EXCEEDED_ERR: 22; + readonly TIMEOUT_ERR: 23; + readonly INVALID_NODE_TYPE_ERR: 24; + readonly DATA_CLONE_ERR: 25; + } + + var CoreJSDOMException: CoreJSDOMExceptionConstructor; +} diff --git a/packages/core-js-types/src/base/pure/web/self.d.ts b/packages/core-js-types/src/base/pure/web/self.d.ts new file mode 100644 index 000000000000..f07d845312aa --- /dev/null +++ b/packages/core-js-types/src/base/pure/web/self.d.ts @@ -0,0 +1,3 @@ +declare namespace CoreJS { + var CoreJSself: typeof globalThis; +} diff --git a/packages/core-js-types/src/base/pure/web/url.d.ts b/packages/core-js-types/src/base/pure/web/url.d.ts new file mode 100644 index 000000000000..638cd455eeb4 --- /dev/null +++ b/packages/core-js-types/src/base/pure/web/url.d.ts @@ -0,0 +1 @@ +/// diff --git a/packages/core-js-types/src/base/web/atob-btoa.d.ts b/packages/core-js-types/src/base/web/atob-btoa.d.ts new file mode 100644 index 000000000000..48748e31123d --- /dev/null +++ b/packages/core-js-types/src/base/web/atob-btoa.d.ts @@ -0,0 +1,14 @@ +/** + * Decodes a string of data which has been encoded using Base64 encoding. + * @param data - A base64-encoded string, using the alphabet produced by btoa(). + * @returns A binary string containing raw bytes decoded from encodedData. + */ +declare function atob(data: string): string; + +/** + * Creates a Base64-encoded ASCII string from a binary string + * (i.e., a string in which each character in the string is treated as a byte of binary data) + * @param data - The binary string to encode + * @returns An ASCII string containing the Base64 representation of data + */ +declare function btoa(data: string): string; diff --git a/packages/core-js-types/src/base/web/dom-exception.d.ts b/packages/core-js-types/src/base/web/dom-exception.d.ts new file mode 100644 index 000000000000..d321c3647593 --- /dev/null +++ b/packages/core-js-types/src/base/web/dom-exception.d.ts @@ -0,0 +1,77 @@ +type _DOMException = typeof globalThis extends { onmessage: any } ? {} : DOMException; +interface DOMException extends Error { + /** + * @deprecated + * + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) + */ + readonly code: number; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) */ + readonly message: string; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) */ + readonly name: string; + readonly INDEX_SIZE_ERR: 1; + readonly DOMSTRING_SIZE_ERR: 2; + readonly HIERARCHY_REQUEST_ERR: 3; + readonly WRONG_DOCUMENT_ERR: 4; + readonly INVALID_CHARACTER_ERR: 5; + readonly NO_DATA_ALLOWED_ERR: 6; + readonly NO_MODIFICATION_ALLOWED_ERR: 7; + readonly NOT_FOUND_ERR: 8; + readonly NOT_SUPPORTED_ERR: 9; + readonly INUSE_ATTRIBUTE_ERR: 10; + readonly INVALID_STATE_ERR: 11; + readonly SYNTAX_ERR: 12; + readonly INVALID_MODIFICATION_ERR: 13; + readonly NAMESPACE_ERR: 14; + readonly INVALID_ACCESS_ERR: 15; + readonly VALIDATION_ERR: 16; + readonly TYPE_MISMATCH_ERR: 17; + readonly SECURITY_ERR: 18; + readonly NETWORK_ERR: 19; + readonly ABORT_ERR: 20; + readonly URL_MISMATCH_ERR: 21; + readonly QUOTA_EXCEEDED_ERR: 22; + readonly TIMEOUT_ERR: 23; + readonly INVALID_NODE_TYPE_ERR: 24; + readonly DATA_CLONE_ERR: 25; +} + +declare global { + interface DOMException extends _DOMException {} + + var DOMException: typeof globalThis extends { onmessage: any; DOMException: infer T } ? T + : { + prototype: DOMException; + new(message?: string, name?: string): DOMException; + // core-js not realize the second argument options-bag, but it's necessary for compatibility with @type/node lib + new(message?: string, options?: { name?: string; cause?: unknown }): DOMException; + readonly INDEX_SIZE_ERR: 1; + readonly DOMSTRING_SIZE_ERR: 2; + readonly HIERARCHY_REQUEST_ERR: 3; + readonly WRONG_DOCUMENT_ERR: 4; + readonly INVALID_CHARACTER_ERR: 5; + readonly NO_DATA_ALLOWED_ERR: 6; + readonly NO_MODIFICATION_ALLOWED_ERR: 7; + readonly NOT_FOUND_ERR: 8; + readonly NOT_SUPPORTED_ERR: 9; + readonly INUSE_ATTRIBUTE_ERR: 10; + readonly INVALID_STATE_ERR: 11; + readonly SYNTAX_ERR: 12; + readonly INVALID_MODIFICATION_ERR: 13; + readonly NAMESPACE_ERR: 14; + readonly INVALID_ACCESS_ERR: 15; + readonly VALIDATION_ERR: 16; + readonly TYPE_MISMATCH_ERR: 17; + readonly SECURITY_ERR: 18; + readonly NETWORK_ERR: 19; + readonly ABORT_ERR: 20; + readonly URL_MISMATCH_ERR: 21; + readonly QUOTA_EXCEEDED_ERR: 22; + readonly TIMEOUT_ERR: 23; + readonly INVALID_NODE_TYPE_ERR: 24; + readonly DATA_CLONE_ERR: 25; + }; +} + +export {}; diff --git a/packages/core-js-types/src/base/web/efficient-script-yielding.d.ts b/packages/core-js-types/src/base/web/efficient-script-yielding.d.ts new file mode 100644 index 000000000000..96e12d494c3b --- /dev/null +++ b/packages/core-js-types/src/base/web/efficient-script-yielding.d.ts @@ -0,0 +1,13 @@ +/** + * Schedules the execution of a function as soon as possible after the current script yields. + * @param handler - The function to execute. + * @param args - Arguments to pass to the handler function. + * @returns An identifier that can be used to cancel the scheduled function. + */ +declare function setImmediate(handler: (...args: any[]) => void, ...args: any[]): number | object; + +/** + * Cancels a function scheduled with setImmediate. + * @param immediate - The identifier of the scheduled function to cancel. + */ +declare function clearImmediate(immediate: number | object | undefined): void; // For compatibility with Node, `undefined` has been added diff --git a/packages/core-js-types/src/base/web/iterable-dom-collections.d.ts b/packages/core-js-types/src/base/web/iterable-dom-collections.d.ts new file mode 100644 index 000000000000..354a6c84f825 --- /dev/null +++ b/packages/core-js-types/src/base/web/iterable-dom-collections.d.ts @@ -0,0 +1,298 @@ +// use only with DOM lib + +// Fallbacks for DOM types +interface Element {} // @type-options: no-export +interface Node {} // @type-options: no-export +interface HTMLOptionElement {} // @type-options: no-export +interface CSSValue {} // @type-options: no-export +interface CSSRule {} // @type-options: no-export +interface ClientRect {} // @type-options: no-export +interface DOMRect {} // @type-options: no-export +interface StyleSheet {} // @type-options: no-export +interface DataTransferItem {} // @type-options: no-export +interface File {} // @type-options: no-export +interface MimeType {} // @type-options: no-export +interface Attr {} // @type-options: no-export +interface PaintRequest {} // @type-options: no-export +interface Plugin {} // @type-options: no-export +interface SVGLength {} // @type-options: no-export +interface SVGNumber {} // @type-options: no-export +interface SVGPathSeg {} // @type-options: no-export +interface DOMPoint {} // @type-options: no-export +interface SVGTransform {} // @type-options: no-export +interface SourceBuffer {} // @type-options: no-export +interface TextTrackCue {} // @type-options: no-export +interface TextTrack {} // @type-options: no-export +interface Touch {} // @type-options: no-export + +interface ArrayIterator extends IteratorObject { // @type-options: no-export + [Symbol.iterator](): ArrayIterator; +} + +interface DOMTokenList { // @type-options: no-export + /** + * Calls a defined callback function on each element of the DOMTokenList, + * passing the element, its index, and the entire DOMTokenList as arguments. + * @param callbackfn - The function to execute for each element. + * @param thisArg - Value to use as this when executing `callbackfn`. + */ + forEach( + callbackfn: (value: string, index: number, collection: DOMTokenList) => void, + thisArg?: any + ): void; + + /** + * Returns an iterable of keys in the DOMTokenList. + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the DOMTokenList. + */ + values(): IterableIterator; + + /** + * Returns an iterable of key, value pairs in the DOMTokenList. + */ + entries(): IterableIterator<[number, string]>; + + [Symbol.iterator](): IterableIterator; +} + +interface NodeList { // @type-options: no-export + /** + * Calls a defined callback function on each element of the NodeList, + * passing the element, its index, and the entire NodeList as arguments. + * @param callbackfn - The function to execute for each element. + * @param thisArg - Value to use as this when executing `callbackfn`. + */ + forEach( + callbackfn: (value: Node, index: number, collection: NodeList) => void, + thisArg?: any + ): void; + + /** + * Returns an iterable of keys in the NodeList. + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the NodeList. + */ + values(): IterableIterator; + + /** + * Returns an iterable of key, value pairs in the NodeList. + */ + entries(): IterableIterator<[number, Node]>; + + /** + * Returns an iterable of values in the NodeList. + */ + [Symbol.iterator](): IterableIterator; +} + +interface CSSRuleList { // @type-options: no-export + /** + * Returns an iterable of CSSRule values. + */ + [Symbol.iterator](): IterableIterator; +} + +interface CSSStyleDeclaration { // @type-options: no-export + /** + * Returns an iterable of string values. + */ + [Symbol.iterator](): IterableIterator; +} + +interface CSSValueList { // @type-options: no-export + /** + * Returns an iterable of CSSValue values. + */ + [Symbol.iterator](): IterableIterator; +} + +interface ClientRectList { // @type-options: no-export + /** + * Returns an iterable of ClientRect values. + */ + [Symbol.iterator](): IterableIterator; +} + +interface DOMRectList { // @type-options: no-export + /** + * Returns an iterable of DOMRect values. + */ + [Symbol.iterator](): IterableIterator; +} + +interface DOMStringList { // @type-options: no-export + /** + * Returns an iterable of string values. + */ + [Symbol.iterator](): IterableIterator; +} + +interface DataTransferItemList { // @type-options: no-export + /** + * Returns an iterable of DataTransferItem values. + */ + [Symbol.iterator](): IterableIterator; +} + +interface FileList { // @type-options: no-export + /** + * Returns an iterable of File values. + */ + [Symbol.iterator](): IterableIterator; +} + +interface HTMLAllCollection { // @type-options: no-export + /** + * Returns an iterable of Element values. + */ + [Symbol.iterator](): IterableIterator; +} + +interface HTMLCollection { // @type-options: no-export + /** + * Returns an iterable of values in the HTMLCollection. + */ + [Symbol.iterator](): ArrayIterator; +} + +interface HTMLFormElement { // @type-options: no-export + /** + * Returns an iterable of values in the HTMLFormElement. + */ + [Symbol.iterator](): IterableIterator; +} + +interface HTMLSelectElement { // @type-options: no-export + /** + * Returns an iterable of values in the HTMLSelectElement. + */ + [Symbol.iterator](): IterableIterator; +} + +interface MediaList { // @type-options: no-export + /** + * Returns an iterable of string values. + */ + [Symbol.iterator](): IterableIterator; +} + +interface MimeTypeArray { // @type-options: no-export + /** + * Returns an iterable of MimeType values. + */ + [Symbol.iterator](): IterableIterator; +} + +interface NamedNodeMap { // @type-options: no-export + /** + * Returns an iterable of Attr values. + */ + [Symbol.iterator](): IterableIterator; +} + +interface PaintRequestList { // @type-options: no-export + /** + * Returns an iterable of PaintRequest values. + */ + [Symbol.iterator](): IterableIterator; +} + +interface Plugin { // @type-options: no-export + /** + * Returns an iterable of MimeType values. + */ + [Symbol.iterator](): IterableIterator; +} + +interface PluginArray { // @type-options: no-export + /** + * Returns an iterable of Plugin values. + */ + [Symbol.iterator](): IterableIterator; +} + +interface SVGLengthList { // @type-options: no-export + /** + * Returns an iterable of SVGLength values. + */ + [Symbol.iterator](): IterableIterator; +} + +interface SVGNumberList { // @type-options: no-export + /** + * Returns an iterable of SVGNumber values. + */ + [Symbol.iterator](): IterableIterator; +} + +interface SVGPathSegList { // @type-options: no-export + /** + * Returns an iterable of SVGPathSeg values. + */ + [Symbol.iterator](): IterableIterator; +} + +interface SVGPointList { // @type-options: no-export + /** + * Returns an iterable of DOMPoint values. + * DOMPoint is used instead of SVGPoint because SVGPoint is deprecated and DOMPoint is its replacement. + */ + [Symbol.iterator](): IterableIterator; +} + +interface SVGStringList { // @type-options: no-export + /** + * Returns an iterable of string values. + */ + [Symbol.iterator](): IterableIterator; +} + +interface SVGTransformList { // @type-options: no-export + /** + * Returns an iterable of SVGTransform values. + */ + [Symbol.iterator](): IterableIterator; +} + +interface SourceBufferList { // @type-options: no-export + /** + * Returns an iterable of SourceBuffer values. + */ + [Symbol.iterator](): IterableIterator; +} + +interface StyleSheetList { // @type-options: no-export + /** + * Returns an iterable of StyleSheet values. + * + */ + [Symbol.iterator](): IterableIterator; +} + +interface TextTrackCueList { // @type-options: no-export + /** + * Returns an iterable of TextTrackCue values. + */ + [Symbol.iterator](): IterableIterator; +} + +interface TextTrackList { // @type-options: no-export + /** + * Returns an iterable of TextTrack values. + */ + [Symbol.iterator](): IterableIterator; +} + +interface TouchList { // @type-options: no-export + /** + * Returns an iterable of Touch values. + */ + [Symbol.iterator](): IterableIterator; +} diff --git a/packages/core-js-types/src/base/web/queue-microtask.d.ts b/packages/core-js-types/src/base/web/queue-microtask.d.ts new file mode 100644 index 000000000000..9fe3babcfc43 --- /dev/null +++ b/packages/core-js-types/src/base/web/queue-microtask.d.ts @@ -0,0 +1,5 @@ +/** + * Queues a microtask to be executed at a later time. + * @param callback - A function to be executed in the microtask. + */ +declare function queueMicrotask(callback: () => void): void; diff --git a/packages/core-js-types/src/base/web/self.d.ts b/packages/core-js-types/src/base/web/self.d.ts new file mode 100644 index 000000000000..c3bc4f88e9df --- /dev/null +++ b/packages/core-js-types/src/base/web/self.d.ts @@ -0,0 +1,5 @@ +declare global { + var self: typeof globalThis extends { onmessage: any; self: infer T } ? T : {}; +} + +export {}; diff --git a/packages/core-js-types/src/base/web/structured-clone.d.ts b/packages/core-js-types/src/base/web/structured-clone.d.ts new file mode 100644 index 000000000000..d750bd6bfc38 --- /dev/null +++ b/packages/core-js-types/src/base/web/structured-clone.d.ts @@ -0,0 +1,14 @@ +interface CoreJSStructuredSerializeOptions { // @type-options: no-extends, no-prefix + readonly __brand?: unique symbol; + + transfer?: any[]; +} + +/** + * Creates a deep clone of a given value using the structured clone algorithm. + * @param value - The value to be cloned. + * @param options - An optional object that may contain a transfer property, + * which is an array of transferable objects to be transferred rather than cloned. + * @returns A deep clone of the provided value. + */ +declare function structuredClone(value: T, options?: CoreJSStructuredSerializeOptions): T; diff --git a/packages/core-js-types/src/base/web/url.d.ts b/packages/core-js-types/src/base/web/url.d.ts new file mode 100644 index 000000000000..00dcefb8a546 --- /dev/null +++ b/packages/core-js-types/src/base/web/url.d.ts @@ -0,0 +1,15 @@ +// URL has conflicts with @types/node +// /// + +// import * as url from 'core-js/internals/web/url'; +// +// declare global { +// interface URL extends url.URL {} +// var URL: typeof globalThis extends { onmessage: any; URL: infer T } ? T : typeof url.URL; +// +// interface URLSearchParams extends url.URLSearchParams {} +// var URLSearchParams: typeof globalThis extends { onmessage: any; URLSearchParams: infer T } ? T +// : typeof url.URLSearchParams; +// } +// +// export {}; diff --git a/packages/core-js-types/src/ts5-2/core-js-types/iterator-object.d.ts b/packages/core-js-types/src/ts5-2/core-js-types/iterator-object.d.ts new file mode 100644 index 000000000000..a43c71459a8d --- /dev/null +++ b/packages/core-js-types/src/ts5-2/core-js-types/iterator-object.d.ts @@ -0,0 +1,7 @@ +// Motivation: Iterator until TS 5.6 used undefined as TNext defaults + +declare namespace CoreJS { + export interface CoreJSIteratorObject extends Iterator { + [Symbol.iterator](): CoreJSIteratorObject; + } +} diff --git a/packages/core-js-types/src/ts5-2/proposals/async-iterator-helpers.d.ts b/packages/core-js-types/src/ts5-2/proposals/async-iterator-helpers.d.ts new file mode 100644 index 000000000000..ec1cd32d4b6b --- /dev/null +++ b/packages/core-js-types/src/ts5-2/proposals/async-iterator-helpers.d.ts @@ -0,0 +1,118 @@ +// Motivation: TS 5.6 changed AsyncIterator’s TNext from undefined to any + +// https://github.com/tc39/proposal-async-iterator-helpers + +interface AsyncIteratorConstructor { + /** + * Creates an `AsyncIterator` from an iterable object + * @param iterable - An `AsyncIterable`, `Iterable`, or `AsyncIterator` to convert to an `AsyncIterator` + * @returns A new `AsyncIterator` instance + */ + from(iterable: AsyncIterable | Iterable | AsyncIterator): AsyncIteratorObject; +} + +declare var AsyncIterator: AsyncIteratorConstructor; + +interface AsyncIterator { + /** + * Drops elements from the iterator until the limit is reached + * @param limit - The number of elements to drop + * @returns A new `AsyncIterator` + */ + drop(limit: number): AsyncIteratorObject; + + /** + * Check if every value generated by the iterator passes the `predicate` function. + * @param predicate - A function that tests each element of the iterator + * @returns A promise that resolves to `true` if all elements pass the test, otherwise `false` + */ + every(predicate: (value: T, index: number) => boolean): Promise; + + /** + * Creates a new `AsyncIterator` that contains only the elements that pass the `predicate` function. + * @param predicate - A function that tests each element of the iterator + * @returns A new `AsyncIterator` + */ + filter(predicate: (value: T, index: number) => boolean): AsyncIteratorObject; + + /** + * Finds the first element in the iterator that satisfies the `predicate` function. + * @param predicate - A function that tests each element of the iterator + * @returns A `Promise` that resolves to the found element, or `undefined` if no element satisfies the `predicate` + */ + find(predicate: (value: T, index: number) => boolean): Promise; + + /** + * Creates a new `AsyncIterator` by applying the `mapper` function to each element of the original iterator and flattening the result. + * @param mapper - A function that transforms each element of the iterator + * @returns A new `AsyncIterator` + */ + flatMap(mapper: (value: T, index: number) => any): AsyncIteratorObject; + + /** + * Executes a provided function once for each element in the iterator. + * @param callbackFn - A function that is called for each element of the iterator + * @returns A `Promise` that resolves when all elements have been processed + */ + forEach(callbackFn: (value: T, index: number) => void): Promise; + + /** + * Creates a new `AsyncIterator` by applying the `mapper` function to each element of the original iterator. + * @param mapper - A function that transforms each element of the iterator + * @returns A new `AsyncIterator` + */ + map(mapper: (value: T, index: number) => any): AsyncIteratorObject>; + + /** + * Reduces the elements of the iterator to a single value using the `reducer` function. + * @param reducer - A function that combines two elements of the iterator + * @param initialValue - The initial value to start the accumulation. Required when the accumulator type differs from the element type. + * @returns A `Promise` that resolves to the reduced value + */ + reduce(reducer: (accumulator: U, value: T, index: number) => U, initialValue: U): Promise; + + /** + * Reduces the elements of the iterator to a single value using the `reducer` function. + * @param reducer - A function that combines two elements of the iterator + * @param initialValue - An optional initial value to start the reduction + * @returns A `Promise` that resolves to the reduced value + */ + reduce(reducer: (accumulator: T, value: T, index: number) => T, initialValue?: T): Promise; + + /** + * Reduces the elements of the iterator to a single value using the `reducer` function. + * For maximum flexibility with any types. + * @param reducer - A function that combines two elements of the iterator + * @param initialValue - An optional initial value to start the reduction + * @returns A `Promise` that resolves to the reduced value + */ + reduce(reducer: (accumulator: any, value: T, index: number) => any, initialValue?: any): Promise; + + /** + * Checks if any value in the iterator matches a given `predicate` + * @param predicate - A function that tests each element of the iterator + * @returns A `Promise` that resolves to `true` if any element passes the `predicate`, otherwise `false` + */ + some(predicate: (value: T, index: number) => boolean): Promise; + + /** + * Creates a new `AsyncIterator` that yields only the first `limit` elements from the original iterator. + * @param limit - The maximum number of elements to take + * @returns A new `AsyncIterator` + */ + take(limit: number): AsyncIteratorObject; + + /** + * Collects all elements from the iterator into an array. + * @returns A `Promise` that resolves to an array containing all elements from the iterator + */ + toArray(): Promise; +} + +interface Iterator { + /** + * Creates an `AsyncIterator` from the current `Iterator` + * @returns A new `AsyncIterator` instance + */ + toAsync(): AsyncIteratorObject; +} diff --git a/packages/core-js-types/src/ts5-2/proposals/explicit-resource-management.d.ts b/packages/core-js-types/src/ts5-2/proposals/explicit-resource-management.d.ts new file mode 100644 index 000000000000..836f1991c46c --- /dev/null +++ b/packages/core-js-types/src/ts5-2/proposals/explicit-resource-management.d.ts @@ -0,0 +1,204 @@ +// Motivation: IteratorObject, AsyncIteratorObject, and AsyncIterator had different signatures until TS 5.6 + +// https://github.com/tc39/proposal-explicit-resource-management + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/0a1aa6d6ebdfa16b82f4a6aaf282089b1d484e05/src/lib/esnext.disposable.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface SymbolConstructor { + /** + * A method that is used to release resources held by an object. Called by the semantics of the `using` statement. + */ + readonly dispose: unique symbol; + + /** + * A method that is used to asynchronously release resources held by an object. Called by the semantics of the `await using` statement. + */ + readonly asyncDispose: unique symbol; +} + +interface Disposable { // @type-options: no-constructor + [Symbol.dispose](): void; +} + +interface AsyncDisposable { // @type-options: no-constructor + [Symbol.asyncDispose](): PromiseLike; +} + +interface SuppressedError extends Error { + error: any; + suppressed: any; +} + +interface SuppressedErrorConstructor { + new (error: any, suppressed: any, message?: string): SuppressedError; + + (error: any, suppressed: any, message?: string): SuppressedError; + + readonly prototype: SuppressedError; +} + +declare var SuppressedError: SuppressedErrorConstructor; + +interface DisposableStack { + /** + * Returns a value indicating whether this stack has been disposed. + */ + readonly disposed: boolean; + + /** + * Disposes each resource in the stack in the reverse order that they were added. + */ + dispose(): void; + + /** + * Adds a disposable resource to the stack, returning the resource. + * @param value - The resource to add. `null` and `undefined` will not be added, but will be returned. + * @returns The provided {@link value}. + */ + use(value: T): T; + + /** + * Adds a value and associated disposal callback as a resource to the stack. + * @param value - The value to add. + * @param onDispose - The callback to use in place of a `[Symbol.dispose]()` method. Will be invoked with `value` + * as the first parameter. + * @returns The provided {@link value}. + */ + adopt(value: T, onDispose: (value: T) => void): T; + + /** + * Adds a callback to be invoked when the stack is disposed. + */ + defer(onDispose: () => void): void; + + /** + * Move all resources out of this stack and into a new `DisposableStack`, and marks this stack as disposed. + * @example + * ```ts + * class C { + * #res1: Disposable; + * #res2: Disposable; + * #disposables: DisposableStack; + * constructor() { + * // stack will be disposed when exiting constructor for any reason + * using stack = new DisposableStack(); + * + * // get first resource + * this.#res1 = stack.use(getResource1()); + * + * // get second resource. If this fails, both `stack` and `#res1` will be disposed. + * this.#res2 = stack.use(getResource2()); + * + * // all operations succeeded, move resources out of `stack` so that they aren't disposed + * // when constructor exits + * this.#disposables = stack.move(); + * } + * + * [Symbol.dispose]() { + * this.#disposables.dispose(); + * } + * } + * ``` + */ + move(): DisposableStack; + + [Symbol.dispose](): void; + + readonly [Symbol.toStringTag]: string; +} + +interface DisposableStackConstructor { + new (): DisposableStack; + + readonly prototype: DisposableStack; +} + +declare var DisposableStack: DisposableStackConstructor; + +interface AsyncDisposableStack { + /** + * Returns a value indicating whether this stack has been disposed. + */ + readonly disposed: boolean; + + /** + * Disposes each resource in the stack in the reverse order that they were added. + */ + disposeAsync(): Promise; // @type-options: prefix-return-type + + /** + * Adds a disposable resource to the stack, returning the resource. + * @param value - The resource to add. `null` and `undefined` will not be added, but will be returned. + * @returns The provided {@link value}. + */ + use(value: T): T; + + /** + * Adds a value and associated disposal callback as a resource to the stack. + * @param value - The value to add. + * @param onDisposeAsync - The callback to use in place of a `[Symbol.asyncDispose]()` method. Will be invoked with `value` + * as the first parameter. + * @returns The provided {@link value}. + */ + adopt(value: T, onDisposeAsync: (value: T) => PromiseLike | void): T; + + /** + * Adds a callback to be invoked when the stack is disposed. + */ + defer(onDisposeAsync: () => PromiseLike | void): void; + + /** + * Move all resources out of this stack and into a new `DisposableStack`, and marks this stack as disposed. + * @example + * ```ts + * class C { + * #res1: Disposable; + * #res2: Disposable; + * #disposables: DisposableStack; + * constructor() { + * // stack will be disposed when exiting constructor for any reason + * using stack = new DisposableStack(); + * + * // get first resource + * this.#res1 = stack.use(getResource1()); + * + * // get second resource. If this fails, both `stack` and `#res1` will be disposed. + * this.#res2 = stack.use(getResource2()); + * + * // all operations succeeded, move resources out of `stack` so that they aren't disposed + * // when constructor exits + * this.#disposables = stack.move(); + * } + * + * [Symbol.dispose]() { + * this.#disposables.dispose(); + * } + * } + * ``` + */ + move(): AsyncDisposableStack; + + [Symbol.asyncDispose](): Promise; + + readonly [Symbol.toStringTag]: string; +} + +interface AsyncDisposableStackConstructor { + new (): AsyncDisposableStack; + + readonly prototype: AsyncDisposableStack; +} + +declare var AsyncDisposableStack: AsyncDisposableStackConstructor; + +interface IteratorObject extends Disposable {} // @type-options: no-extends + +interface AsyncIteratorObject extends AsyncDisposable {} // @type-options: no-extends + +interface AsyncIteratorConstructor {} + +declare var AsyncIterator: AsyncIteratorConstructor; + +interface AsyncIterator {} diff --git a/packages/core-js-types/src/ts5-2/proposals/iterator-helpers.d.ts b/packages/core-js-types/src/ts5-2/proposals/iterator-helpers.d.ts new file mode 100644 index 000000000000..c5b5c0943d18 --- /dev/null +++ b/packages/core-js-types/src/ts5-2/proposals/iterator-helpers.d.ts @@ -0,0 +1,116 @@ +/// + +// Motivation: Iterable until TS 5.6 used only one type parameter + +// https://github.com/tc39/proposal-iterator-helpers + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/d3be7e171bf3149fe93c3ce5a85280f1eba3ef8d/src/lib/esnext.iterator.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +declare global { + interface Iterator { + /** + * Creates an iterator whose values are the result of applying the callback to the values from this iterator. + * @param callbackfn - A function that accepts up to two arguments to be used to transform values from the underlying iterator. + */ + map(callbackfn: (value: T, index: number) => U): CoreJS.CoreJSIteratorObject; + + /** + * Creates an iterator whose values are those from this iterator for which the provided predicate returns true. + * @param predicate - A function that accepts up to two arguments to be used to test values from the underlying iterator. + */ + filter(predicate: (value: T, index: number) => value is S): CoreJS.CoreJSIteratorObject; + /** + * Creates an iterator whose values are those from this iterator for which the provided predicate returns true. + * @param predicate - A function that accepts up to two arguments to be used to test values from the underlying iterator. + */ + filter(predicate: (value: T, index: number) => unknown): CoreJS.CoreJSIteratorObject; + + /** + * Creates an iterator whose values are the values from this iterator, stopping once the provided limit is reached. + * @param limit - The maximum number of values to yield. + */ + take(limit: number): CoreJS.CoreJSIteratorObject; + + /** + * Creates an iterator whose values are the values from this iterator after skipping the provided count. + * @param count - The number of values to drop. + */ + drop(count: number): CoreJS.CoreJSIteratorObject; + + /** + * Creates an iterator whose values are the result of applying the callback to the values from this iterator and then flattening the resulting iterators or iterables. + * @param callback - A function that accepts up to two arguments to be used to transform values from the underlying iterator into new iterators or iterables to be flattened into the result. + */ + flatMap(callback: (value: T, index: number) => Iterator | Iterable): CoreJS.CoreJSIteratorObject; + + /** + * Calls the specified callback function for all the elements in this iterator. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn - A function that accepts up to three arguments. The reduce method calls the callbackfn function one time for each element in the iterator. + */ + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number) => T): T; + /** + * Calls the specified callback function for all the elements in this iterator. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn - A function that accepts up to three arguments. The reduce method calls the callbackfn function one time for each element in the iterator. + * @param initialValue - If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of a value from the iterator. + */ + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number) => T, initialValue: T): T; + /** + * Calls the specified callback function for all the elements in this iterator. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn - A function that accepts up to three arguments. The reduce method calls the callbackfn function one time for each element in the iterator. + * @param initialValue - If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of a value from the iterator. + */ + reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number) => U, initialValue: U): U; + + /** + * Creates a new array from the values yielded by this iterator. + */ + toArray(): T[]; + + /** + * Performs the specified action for each element in the iterator. + * @param callbackfn - A function that accepts up to two arguments. forEach calls the callbackfn function one time for each element in the iterator. + */ + forEach(callbackfn: (value: T, index: number) => void): void; + + /** + * Determines whether the specified callback function returns true for any element of this iterator. + * @param predicate - A function that accepts up to two arguments. The `some` method calls + * the predicate function for each element in this iterator until the predicate returns a value + * true, or until the end of the iterator. + */ + some(predicate: (value: T, index: number) => unknown): boolean; + + /** + * Determines whether all the members of this iterator satisfy the specified test. + * @param predicate - A function that accepts up to two arguments. The every method calls + * the predicate function for each element in this iterator until the predicate returns + * false, or until the end of this iterator. + */ + every(predicate: (value: T, index: number) => unknown): boolean; + + /** + * Returns the value of the first element in this iterator where predicate is true, and undefined + * otherwise. + * @param predicate - find calls predicate once for each element of this iterator, in + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + */ + find(predicate: (value: T, index: number) => value is S): S | undefined; + find(predicate: (value: T, index: number) => unknown): T | undefined; + } + + interface IteratorConstructor { // @type-options: no-extends + /** + * Creates a native iterator from an iterator or iterable object. + * Returns its input if the input already inherits from the built-in Iterator class. + * @param value - An iterator or iterable object to convert a native iterator. + */ + from(value: Iterator | Iterable): CoreJS.CoreJSIteratorObject; + } + + var Iterator: IteratorConstructor; +} + +export {}; diff --git a/packages/core-js-types/src/ts5-2/proposals/string-match-all.d.ts b/packages/core-js-types/src/ts5-2/proposals/string-match-all.d.ts new file mode 100644 index 000000000000..3d3f4ca467c0 --- /dev/null +++ b/packages/core-js-types/src/ts5-2/proposals/string-match-all.d.ts @@ -0,0 +1,24 @@ +// Motivation: BuiltinIteratorReturn available only from TS 5.6 + +// https://github.com/tc39/proposal-string-matchall + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/f450c1b80ce6dc7b04e81899db00534018932234/src/lib/es2020.string.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +interface RegExpStringIterator extends IteratorObject { + [Symbol.iterator](): RegExpStringIterator; +} + +interface String { + /** + * Matches a string with a regular expression, and returns an iterable of matches + * containing the results of that search. + * @param regexp - A variable name or string literal containing the regular expression pattern and flags. + */ + matchAll(regexp: RegExp): RegExpStringIterator; +} + +interface SymbolConstructor { + readonly matchAll: unique symbol; +} diff --git a/packages/core-js-types/src/ts5-2/pure/core-js-types/iterator-object.d.ts b/packages/core-js-types/src/ts5-2/pure/core-js-types/iterator-object.d.ts new file mode 100644 index 000000000000..ae12b90ba61a --- /dev/null +++ b/packages/core-js-types/src/ts5-2/pure/core-js-types/iterator-object.d.ts @@ -0,0 +1,9 @@ +/// + +// Motivation: Iterator until TS 5.6 used undefined as TNext defaults + +declare namespace CoreJS { + export interface CoreJSIteratorObject extends CoreJSIterator { + [Symbol.iterator](): CoreJSIteratorObject; + } +} diff --git a/packages/core-js-types/src/ts5-2/pure/proposals/async-iterator-helpers.d.ts b/packages/core-js-types/src/ts5-2/pure/proposals/async-iterator-helpers.d.ts new file mode 100644 index 000000000000..72e67b57fbbd --- /dev/null +++ b/packages/core-js-types/src/ts5-2/pure/proposals/async-iterator-helpers.d.ts @@ -0,0 +1,128 @@ +/// +/// +/// + +// Motivation: Has dependencies on internal types, e.g. AsyncIterable, AsyncIteratorObject +// Motivation: Iterator until TS 5.6 used undefined as TNext defaults + +// https://github.com/tc39/proposal-async-iterator-helpers + +declare namespace CoreJS { + export interface CoreJSAsyncIteratorConstructor { + /** + * Creates an `AsyncIterator` from an iterable object + * @param iterable - An `AsyncIterable`, `Iterable`, or `AsyncIterator` to convert to an `AsyncIterator` + * @returns A new `AsyncIterator` instance + */ + from(iterable: CoreJSAsyncIterable | Iterable | CoreJSAsyncIteratorObject): CoreJSAsyncIteratorObject; + } + + export interface CoreJSAsyncIterator { + + /** + * Drops elements from the iterator until the limit is reached + * @param limit - The number of elements to drop + * @returns A new `AsyncIterator` + */ + drop(limit: number): CoreJSAsyncIteratorObject; + + /** + * Check if every value generated by the iterator passes the `predicate` function. + * @param predicate - A function that tests each element of the iterator + * @returns A promise that resolves to `true` if all elements pass the test, otherwise `false` + */ + every(predicate: (value: T, index: number) => boolean): CoreJSPromise; + + /** + * Creates a new `AsyncIterator` that contains only the elements that pass the `predicate` function. + * @param predicate - A function that tests each element of the iterator + * @returns A new `AsyncIterator` + */ + filter(predicate: (value: T, index: number) => value is S): CoreJSAsyncIteratorObject; + filter(predicate: (value: T, index: number) => unknown): CoreJSAsyncIteratorObject; + + /** + * Finds the first element in the iterator that satisfies the `predicate` function. + * @param predicate - A function that tests each element of the iterator + * @returns A `Promise` that resolves to the found element, or `undefined` if no element satisfies the `predicate` + */ + find(predicate: (value: T, index: number) => value is S): CoreJSPromise; + find(predicate: (value: T, index: number) => unknown): CoreJSPromise; + + /** + * Creates a new `AsyncIterator` by applying the `mapper` function to each element of the original iterator and flattening the result. + * @param mapper - A function that transforms each element of the iterator + * @returns A new `AsyncIterator` + */ + flatMap(mapper: (value: T, index: number) => Iterable | CoreJSAsyncIterator | CoreJSAsyncIterable): CoreJSAsyncIteratorObject; + + /** + * Executes a provided function once for each element in the iterator. + * @param callbackFn - A function that is called for each element of the iterator + * @returns A `Promise` that resolves when all elements have been processed + */ + forEach(callbackFn: (value: T, index: number) => void): CoreJSPromise; + + /** + * Creates a new `AsyncIterator` by applying the `mapper` function to each element of the original iterator. + * @param mapper - A function that transforms each element of the iterator + * @returns A new `AsyncIterator` + */ + map(mapper: (value: T, index: number) => U): CoreJSAsyncIteratorObject; + + /** + * Reduces the elements of the iterator to a single value using the `reducer` function. + * @param reducer - A function that combines two elements of the iterator + * @param initialValue - The initial value to start the accumulation. Required when the accumulator type differs from the element type. + * @returns A `Promise` that resolves to the reduced value + */ + reduce(reducer: (accumulator: U, value: T, index: number) => U, initialValue: U): CoreJSPromise; + + /** + * Reduces the elements of the iterator to a single value using the `reducer` function. + * @param reducer - A function that combines two elements of the iterator + * @param initialValue - An optional initial value to start the reduction + * @returns A `Promise` that resolves to the reduced value + */ + reduce(reducer: (accumulator: T, value: T, index: number) => T, initialValue?: T): CoreJSPromise; + + /** + * Reduces the elements of the iterator to a single value using the `reducer` function. + * For maximum flexibility with any types. + * @param reducer - A function that combines two elements of the iterator + * @param initialValue - An optional initial value to start the reduction + * @returns A `Promise` that resolves to the reduced value + */ + reduce(reducer: (accumulator: any, value: T, index: number) => any, initialValue?: any): CoreJSPromise; + + /** + * Checks if any value in the iterator matches a given `predicate` + * @param predicate - A function that tests each element of the iterator + * @returns A `Promise` that resolves to `true` if any element passes the `predicate`, otherwise `false` + */ + some(predicate: (value: T, index: number) => boolean): CoreJSPromise; + + /** + * Creates a new `AsyncIterator` that yields only the first `limit` elements from the original iterator. + * @param limit - The maximum number of elements to take + * @returns A new `AsyncIterator` + */ + take(limit: number): CoreJSAsyncIteratorObject; + + /** + * Collects all elements from the iterator into an array. + * @returns A `Promise` that resolves to an array containing all elements from the iterator + */ + toArray(): CoreJSPromise; + } + + var CoreJSAsyncIterator: CoreJSAsyncIteratorConstructor; + + interface CoreJSIterator extends Iterator { + /** + * Creates an `AsyncIterator` from the current `Iterator` + * @returns A new `AsyncIterator` instance + */ + toAsync(): CoreJSAsyncIteratorObject; + } +} diff --git a/packages/core-js-types/src/ts5-2/pure/proposals/iterator.d.ts b/packages/core-js-types/src/ts5-2/pure/proposals/iterator.d.ts new file mode 100644 index 000000000000..3e0f88201120 --- /dev/null +++ b/packages/core-js-types/src/ts5-2/pure/proposals/iterator.d.ts @@ -0,0 +1,228 @@ +/// +/// +/// + +// Motivation: Has dependencies on internal types +// Motivation: Iterable until TS 5.6 used only one type parameter + +// https://github.com/tc39/proposal-iterator-chunking + +// https://github.com/tc39/proposal-iterator-helpers + +// https://github.com/bakkot/proposal-iterator-join + +// https://github.com/tc39/proposal-joint-iteration + +// https://github.com/tc39/proposal-iterator.range + +// https://github.com/tc39/proposal-iterator-sequencing + +// For ensuring compatibility with TypeScript standard types, this code is aligned with: +// https://github.com/microsoft/TypeScript/blob/d3be7e171bf3149fe93c3ce5a85280f1eba3ef8d/src/lib/esnext.iterator.d.ts +// License: https://github.com/microsoft/TypeScript/blob/v5.9.3/LICENSE.txt + +declare namespace CoreJS { + interface ZipOptions { + mode?: 'shortest' | 'longest' | 'strict'; + + padding?: Iterable; + } + + interface ZipKeyedOptions { + mode?: 'shortest' | 'longest' | 'strict'; + + padding?: Record; + } + + interface IteratorRangeOptions { + step?: T; + + inclusive?: boolean; + } + + interface CoreJSAsyncIterator { + next(...[value]: [] | [TNext]): CoreJS.CoreJSPromise>; + return?(value?: TReturn | PromiseLike): CoreJS.CoreJSPromise>; + throw?(e?: any): CoreJS.CoreJSPromise>; + } + + export interface CoreJSAsyncIteratorObject extends CoreJSAsyncIterator {} + export interface CoreJSAsyncIteratorObject extends CoreJSAsyncDisposable {} + export interface CoreJSAsyncIterable { + [CoreJSSymbol.asyncIterator](): CoreJSAsyncIterator; + } + + export interface CoreJSIteratorObject extends CoreJSDisposable {} + + export interface CoreJSIterator extends Iterator { + /** + * Yields arrays containing up to the specified number of elements + * chunked from the source iterator. + * @param chunkSize - The maximum number of elements per chunk. Must be a positive integer. + * @returns An iterator yielding arrays of at most `chunkSize` elements from the source iterator. + */ + chunks(chunkSize: number): CoreJSIteratorObject; + + /** + * Yields overlapping arrays (windows) of the given size from the iterator. + * @param windowSize - The size of each window. Must be a positive integer. + * @param undersized - 'only-full' (default) to yield only full windows | 'allow-partial' to yield all windows. + * @returns An iterator yielding arrays of the specified window size. + */ + windows(windowSize: number, undersized?: 'only-full' | 'allow-partial' | undefined): CoreJSIteratorObject; + + /** + * Creates an iterator whose values are the result of applying the callback to the values from this iterator. + * @param callbackfn - A function that accepts up to two arguments to be used to transform values from the underlying iterator. + */ + map(callbackfn: (value: T, index: number) => U): CoreJSIteratorObject; + + /** + * Creates an iterator whose values are those from this iterator for which the provided predicate returns true. + * @param predicate - A function that accepts up to two arguments to be used to test values from the underlying iterator. + */ + filter(predicate: (value: T, index: number) => value is S): CoreJSIteratorObject; + /** + * Creates an iterator whose values are those from this iterator for which the provided predicate returns true. + * @param predicate - A function that accepts up to two arguments to be used to test values from the underlying iterator. + */ + filter(predicate: (value: T, index: number) => unknown): CoreJSIteratorObject; + + /** + * Creates an iterator whose values are the values from this iterator, stopping once the provided limit is reached. + * @param limit - The maximum number of values to yield. + */ + take(limit: number): CoreJSIteratorObject; + + /** + * Creates an iterator whose values are the values from this iterator after skipping the provided count. + * @param count - The number of values to drop. + */ + drop(count: number): CoreJSIteratorObject; + + /** + * Creates an iterator whose values are the result of applying the callback to the values from this iterator and then flattening the resulting iterators or iterables. + * @param callback - A function that accepts up to two arguments to be used to transform values from the underlying iterator into new iterators or iterables to be flattened into the result. + */ + flatMap(callback: (value: T, index: number) => Iterator | Iterable): CoreJSIteratorObject; // ts < 5.6 Iterable + + /** + * Calls the specified callback function for all the elements in this iterator. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn - A function that accepts up to three arguments. The reduce method calls the callbackfn function one time for each element in the iterator. + */ + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number) => T): T; + /** + * Calls the specified callback function for all the elements in this iterator. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn - A function that accepts up to three arguments. The reduce method calls the callbackfn function one time for each element in the iterator. + * @param initialValue - If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of a value from the iterator. + */ + reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number) => T, initialValue: T): T; + /** + * Calls the specified callback function for all the elements in this iterator. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn - A function that accepts up to three arguments. The reduce method calls the callbackfn function one time for each element in the iterator. + * @param initialValue - If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of a value from the iterator. + */ + reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number) => U, initialValue: U): U; + + /** + * Creates a new array from the values yielded by this iterator. + */ + toArray(): T[]; + + /** + * Performs the specified action for each element in the iterator. + * @param callbackfn - A function that accepts up to two arguments. forEach calls the callbackfn function one time for each element in the iterator. + */ + forEach(callbackfn: (value: T, index: number) => void): void; + + /** + * Determines whether the specified callback function returns true for any element of this iterator. + * @param predicate - A function that accepts up to two arguments. The `some` method calls + * the predicate function for each element in this iterator until the predicate returns a value + * true, or until the end of the iterator. + */ + some(predicate: (value: T, index: number) => unknown): boolean; + + /** + * Determines whether all the members of this iterator satisfy the specified test. + * @param predicate - A function that accepts up to two arguments. The every method calls + * the predicate function for each element in this iterator until the predicate returns + * false, or until the end of this iterator. + */ + every(predicate: (value: T, index: number) => unknown): boolean; + + /** + * Returns the value of the first element in this iterator where predicate is true, and undefined + * otherwise. + * @param predicate - find calls predicate once for each element of this iterator, in + * order, until it finds one where predicate returns true. If such an element is found, find + * immediately returns that element value. Otherwise, find returns undefined. + */ + find(predicate: (value: T, index: number) => value is S): S | undefined; + find(predicate: (value: T, index: number) => unknown): T | undefined; + + join(separator?: unknown): string; + } + + export interface CoreJSIteratorConstructor { + /** + * Creates a native iterator from an iterator or iterable object. + * Returns its input if the input already inherits from the built-in Iterator class. + * @param value - An iterator or iterable object to convert to a native iterator. + */ + from(value: Iterator | Iterable): CoreJSIteratorObject; + + /** + * Takes an iterable of iterables and produces an iterable of arrays where position corresponds + * to position in the passed iterable. + * @param iterables - An Iterable of iterables. + * @param options - Optional object: + * - mode: 'shortest' (default) to stop at the shortest iterable | 'longest' to stop at the longest iterable | 'strict' to throw if iterables are not the same length; + * - padding: an object specifying padding values for each key when mode is 'longest'. + * @returns An iterator yielding objects with keys from the input iterables and values from the corresponding iterables. + */ + zip(iterables: Iterable>, options?: ZipOptions): CoreJSIteratorObject; + + /** + * takes an object whose values are iterables and produces an iterable of objects where keys. + * correspond to keys in the passed object. + * @param record - An object of iterables. + * @param options - Optional object: + * - mode: 'shortest' (default) to stop at the shortest iterable | 'longest' to stop at the longest iterable | 'strict' to throw if iterables are not the same length; + * - padding: an object specifying padding values for each key when mode is 'longest'. + * @returns An iterator yielding objects with keys from the input record and values from the corresponding iterables. + */ + zipKeyed }>(record: T, options?: ZipKeyedOptions): CoreJSIteratorObject<{ [K in keyof T]: T[K] extends Iterable ? V : never; }, undefined, unknown>; + + /** + * Returns an iterator that generates a sequence of numbers within a range. + * @param start - The starting value of the sequence. + * @param end - The end value of the sequence (exclusive by default). + * @param options - Optional object: + * - step: The difference between consecutive values (default is 1). + * - inclusive: If true, the end value is included in the range (default is false). + * @returns An iterator of numbers. + */ + range(start: number, end: number | typeof Infinity | typeof Number.NEGATIVE_INFINITY, options?: number | IteratorRangeOptions): CoreJSIteratorObject; + + /** + * Returns an iterator that generates a sequence of bigints within a range. + * @param start - The starting value of the sequence. + * @param end - The end value of the sequence (exclusive by default). + * @param options - Optional object: + * - step: The difference between consecutive values (default is 1n). + * - inclusive: If true, the end value is included in the range (default is false). + * @returns An iterator of bigints. + */ + range(start: bigint, end: bigint, options?: bigint | IteratorRangeOptions): CoreJSIteratorObject; + + /** + * Creates an iterator that sequentially yields values from the provided iterables. + * @param iterators - The iterables to concatenate. + * @returns An iterator yielding values from each input iterable in sequence. + */ + concat(...iterators: Iterable[]): CoreJSIteratorObject; + } + + var CoreJSIterator: CoreJSIteratorConstructor; +} diff --git a/packages/core-js-types/src/ts5-2/web/iterable-dom-collections.d.ts b/packages/core-js-types/src/ts5-2/web/iterable-dom-collections.d.ts new file mode 100644 index 000000000000..ac7a351c2d3d --- /dev/null +++ b/packages/core-js-types/src/ts5-2/web/iterable-dom-collections.d.ts @@ -0,0 +1,280 @@ +// Fallbacks for DOM types +interface Element {} // @type-options: no-export +interface Node {} // @type-options: no-export +interface HTMLOptionElement {} // @type-options: no-export +interface CSSValue {} // @type-options: no-export +interface CSSRule {} // @type-options: no-export +interface ClientRect {} // @type-options: no-export +interface DOMRect {} // @type-options: no-export +interface StyleSheet {} // @type-options: no-export + +interface ArrayIterator extends IteratorObject { // @type-options: no-export + [Symbol.iterator](): ArrayIterator; +} + +interface DOMTokenList { // @type-options: no-export + /** + * Calls a defined callback function on each element of the DOMTokenList, + * passing the element, its index, and the entire DOMTokenList as arguments. + * @param callbackfn - The function to execute for each element. + * @param thisArg - Value to use as this when executing `callbackfn`. + */ + forEach( + callbackfn: (value: string, index: number, collection: DOMTokenList) => void, + thisArg?: any + ): void; + + /** + * Returns an iterable of keys in the DOMTokenList. + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the DOMTokenList. + */ + values(): IterableIterator; + + /** + * Returns an iterable of key, value pairs in the DOMTokenList. + */ + entries(): IterableIterator<[number, Element]>; + + [Symbol.iterator](): IterableIterator; +} + +interface NodeList { // @type-options: no-export + /** + * Calls a defined callback function on each element of the NodeList, + * passing the element, its index, and the entire NodeList as arguments. + * @param callbackfn - The function to execute for each element. + * @param thisArg - Value to use as this when executing `callbackfn`. + */ + forEach( + callbackfn: (value: Node, index: number, collection: NodeList) => void, + thisArg?: any + ): void; + + /** + * Returns an iterable of keys in the NodeList. + */ + keys(): IterableIterator; + + /** + * Returns an iterable of values in the NodeList. + */ + values(): IterableIterator; + + /** + * Returns an iterable of key, value pairs in the NodeList. + */ + entries(): IterableIterator<[number, Node]>; + + /** + * Returns an iterable of values in the NodeList. + */ + [Symbol.iterator](): IterableIterator; +} + +interface CSSRuleList { // @type-options: no-export + /** + * Returns an iterable of CSSRule values. + */ + [Symbol.iterator](): IterableIterator; +} + +interface CSSStyleDeclaration { // @type-options: no-export + /** + * Returns an iterable of string values. + */ + [Symbol.iterator](): IterableIterator; +} + +interface CSSValueList { // @type-options: no-export + /** + * Returns an iterable of CSSValue values. + */ + [Symbol.iterator](): IterableIterator; +} + +interface ClientRectList { // @type-options: no-export + /** + * Returns an iterable of ClientRect values. + */ + [Symbol.iterator](): IterableIterator; +} + +interface DOMRectList { // @type-options: no-export + /** + * Returns an iterable of DOMRect values. + */ + [Symbol.iterator](): IterableIterator; +} + +interface DOMStringList { // @type-options: no-export + /** + * Returns an iterable of values in the DOMStringList. + */ + [Symbol.iterator](): IterableIterator; +} + +interface DataTransferItemList { // @type-options: no-export + /** + * Returns an iterable of values in the DataTransferItemList. + */ + [Symbol.iterator](): IterableIterator; +} + +interface FileList { // @type-options: no-export + /** + * Returns an iterable of values in the FileList. + */ + [Symbol.iterator](): IterableIterator; +} + +interface HTMLAllCollection { // @type-options: no-export + /** + * Returns an iterable of values in the HTMLAllCollection. + */ + [Symbol.iterator](): IterableIterator; +} + +interface HTMLCollection { // @type-options: no-export + /** + * Returns an iterable of values in the HTMLCollection. + */ + [Symbol.iterator](): ArrayIterator; +} + +interface HTMLFormElement { // @type-options: no-export + /** + * Returns an iterable of values in the HTMLFormElement. + */ + [Symbol.iterator](): IterableIterator; +} + +interface HTMLSelectElement { // @type-options: no-export + /** + * Returns an iterable of values in the HTMLSelectElement. + */ + [Symbol.iterator](): IterableIterator; +} + +interface MediaList { // @type-options: no-export + /** + * Returns an iterable of values in the MediaList. + */ + [Symbol.iterator](): IterableIterator; +} + +interface MimeTypeArray { // @type-options: no-export + /** + * Returns an iterable of values in the MimeTypeArray. + */ + [Symbol.iterator](): IterableIterator; +} + +interface NamedNodeMap { // @type-options: no-export + /** + * Returns an iterable of values in the NamedNodeMap. + */ + [Symbol.iterator](): IterableIterator; +} + +interface PaintRequestList { // @type-options: no-export + /** + * Returns an iterable of values in the PaintRequestList. + */ + [Symbol.iterator](): IterableIterator; +} + +interface Plugin { // @type-options: no-export + /** + * Returns an iterable of values in the Plugin. + */ + [Symbol.iterator](): IterableIterator; +} + +interface PluginArray { // @type-options: no-export + /** + * Returns an iterable of values in the PluginArray. + */ + [Symbol.iterator](): IterableIterator; +} + +interface SVGLengthList { // @type-options: no-export + /** + * Returns an iterable of values in the SVGLengthList. + */ + [Symbol.iterator](): IterableIterator; +} + +interface SVGNumberList { // @type-options: no-export + /** + * Returns an iterable of values in the SVGNumberList. + */ + [Symbol.iterator](): IterableIterator; +} + +interface SVGPathSegList { // @type-options: no-export + /** + * Returns an iterable of values in the SVGPathSegList. + */ + [Symbol.iterator](): IterableIterator; +} + +interface SVGPointList { // @type-options: no-export + /** + * Returns an iterable of values in the SVGPointList. + */ + [Symbol.iterator](): IterableIterator; +} + +interface SVGStringList { // @type-options: no-export + /** + * Returns an iterable of values in the SVGStringList. + */ + [Symbol.iterator](): IterableIterator; +} + +interface SVGTransformList { // @type-options: no-export + /** + * Returns an iterable of values in the SVGTransformList. + */ + [Symbol.iterator](): IterableIterator; +} + +interface SourceBufferList { // @type-options: no-export + /** + * Returns an iterable of values in the SourceBufferList. + */ + [Symbol.iterator](): IterableIterator; +} + +interface StyleSheetList { // @type-options: no-export + /** + * Returns an iterable of StyleSheet values. + * + */ + [Symbol.iterator](): IterableIterator; +} + +interface TextTrackCueList { // @type-options: no-export + /** + * Returns an iterable of values in the TextTrackCueList. + */ + [Symbol.iterator](): IterableIterator; +} + +interface TextTrackList { // @type-options: no-export + /** + * Returns an iterable of values in the TextTrackList. + */ + [Symbol.iterator](): IterableIterator; +} + +interface TouchList { // @type-options: no-export + /** + * Returns an iterable of values in the TouchList. + */ + [Symbol.iterator](): IterableIterator; +} diff --git a/packages/core-js/modules/es.aggregate-error.cause.js b/packages/core-js/modules/es.aggregate-error.cause.js index 5e031dc8363b..dd9d892a01c2 100644 --- a/packages/core-js/modules/es.aggregate-error.cause.js +++ b/packages/core-js/modules/es.aggregate-error.cause.js @@ -1,3 +1,5 @@ +// @types: proposals/promise-any +// @types: proposals/error-cause 'use strict'; var $ = require('../internals/export'); var getBuiltIn = require('../internals/get-built-in'); diff --git a/packages/core-js/modules/es.aggregate-error.constructor.js b/packages/core-js/modules/es.aggregate-error.constructor.js index d8551e9d8922..4d3ae77624f7 100644 --- a/packages/core-js/modules/es.aggregate-error.constructor.js +++ b/packages/core-js/modules/es.aggregate-error.constructor.js @@ -1,3 +1,5 @@ +// @types: proposals/promise-any +// @types: proposals/error-cause 'use strict'; var $ = require('../internals/export'); var isPrototypeOf = require('../internals/object-is-prototype-of'); diff --git a/packages/core-js/modules/es.array-buffer.detached.js b/packages/core-js/modules/es.array-buffer.detached.js index 7431a99048dc..724f4066f98a 100644 --- a/packages/core-js/modules/es.array-buffer.detached.js +++ b/packages/core-js/modules/es.array-buffer.detached.js @@ -1,3 +1,4 @@ +// @types: proposals/array-buffer-transfer 'use strict'; var defineBuiltInAccessor = require('../internals/define-built-in-accessor'); var isDetached = require('../internals/array-buffer-is-detached'); diff --git a/packages/core-js/modules/es.array-buffer.transfer-to-fixed-length.js b/packages/core-js/modules/es.array-buffer.transfer-to-fixed-length.js index aee2a08f8bda..23c684e8fc22 100644 --- a/packages/core-js/modules/es.array-buffer.transfer-to-fixed-length.js +++ b/packages/core-js/modules/es.array-buffer.transfer-to-fixed-length.js @@ -1,3 +1,4 @@ +// @types: proposals/array-buffer-transfer 'use strict'; var $ = require('../internals/export'); var $transfer = require('../internals/array-buffer-transfer'); diff --git a/packages/core-js/modules/es.array-buffer.transfer.js b/packages/core-js/modules/es.array-buffer.transfer.js index ba6102c38127..1780a60f59f3 100644 --- a/packages/core-js/modules/es.array-buffer.transfer.js +++ b/packages/core-js/modules/es.array-buffer.transfer.js @@ -1,3 +1,4 @@ +// @types: proposals/array-buffer-transfer 'use strict'; var $ = require('../internals/export'); var $transfer = require('../internals/array-buffer-transfer'); diff --git a/packages/core-js/modules/es.array.at.js b/packages/core-js/modules/es.array.at.js index c1973582df5f..3c511184e338 100644 --- a/packages/core-js/modules/es.array.at.js +++ b/packages/core-js/modules/es.array.at.js @@ -1,3 +1,4 @@ +// @types: proposals/relative-indexing-method 'use strict'; var $ = require('../internals/export'); var toObject = require('../internals/to-object'); diff --git a/packages/core-js/modules/es.array.find-last-index.js b/packages/core-js/modules/es.array.find-last-index.js index 5ab5abf320a3..5cecffac0ba0 100644 --- a/packages/core-js/modules/es.array.find-last-index.js +++ b/packages/core-js/modules/es.array.find-last-index.js @@ -1,3 +1,4 @@ +// @types: proposals/array-find-from-last 'use strict'; var $ = require('../internals/export'); var $findLastIndex = require('../internals/array-iteration-from-last').findLastIndex; diff --git a/packages/core-js/modules/es.array.find-last.js b/packages/core-js/modules/es.array.find-last.js index 2c00b6046b54..0cea65f315a1 100644 --- a/packages/core-js/modules/es.array.find-last.js +++ b/packages/core-js/modules/es.array.find-last.js @@ -1,3 +1,4 @@ +// @types: proposals/array-find-from-last 'use strict'; var $ = require('../internals/export'); var $findLast = require('../internals/array-iteration-from-last').findLast; diff --git a/packages/core-js/modules/es.array.flat-map.js b/packages/core-js/modules/es.array.flat-map.js index dcb63533b9a1..589a3f0e61eb 100644 --- a/packages/core-js/modules/es.array.flat-map.js +++ b/packages/core-js/modules/es.array.flat-map.js @@ -1,3 +1,4 @@ +// @types: proposals/array-flat-map 'use strict'; // @dependency: es.array.unscopables.flat-map var $ = require('../internals/export'); diff --git a/packages/core-js/modules/es.array.flat.js b/packages/core-js/modules/es.array.flat.js index 0e1db6c00009..6b072db29d81 100644 --- a/packages/core-js/modules/es.array.flat.js +++ b/packages/core-js/modules/es.array.flat.js @@ -1,3 +1,4 @@ +// @types: proposals/array-flat-map 'use strict'; // @dependency: es.array.unscopables.flat var $ = require('../internals/export'); diff --git a/packages/core-js/modules/es.array.from-async.js b/packages/core-js/modules/es.array.from-async.js index 04b7874fdd70..e721bb51a17a 100644 --- a/packages/core-js/modules/es.array.from-async.js +++ b/packages/core-js/modules/es.array.from-async.js @@ -1,3 +1,4 @@ +// @types: proposals/array-from-async 'use strict'; var $ = require('../internals/export'); var bind = require('../internals/function-bind-context'); diff --git a/packages/core-js/modules/es.array.includes.js b/packages/core-js/modules/es.array.includes.js index 467fba27bee9..f151a351e234 100644 --- a/packages/core-js/modules/es.array.includes.js +++ b/packages/core-js/modules/es.array.includes.js @@ -1,3 +1,4 @@ +// @types: proposals/array-includes 'use strict'; var $ = require('../internals/export'); var $includes = require('../internals/array-includes'); diff --git a/packages/core-js/modules/es.array.to-reversed.js b/packages/core-js/modules/es.array.to-reversed.js index dd18d0634719..9ae38dbfe833 100644 --- a/packages/core-js/modules/es.array.to-reversed.js +++ b/packages/core-js/modules/es.array.to-reversed.js @@ -1,3 +1,4 @@ +// @types: proposals/change-array-by-copy 'use strict'; var $ = require('../internals/export'); var toObject = require('../internals/to-object'); diff --git a/packages/core-js/modules/es.array.to-sorted.js b/packages/core-js/modules/es.array.to-sorted.js index 141b005c34da..683ac42ea8c7 100644 --- a/packages/core-js/modules/es.array.to-sorted.js +++ b/packages/core-js/modules/es.array.to-sorted.js @@ -1,3 +1,4 @@ +// @types: proposals/change-array-by-copy 'use strict'; var $ = require('../internals/export'); var uncurryThis = require('../internals/function-uncurry-this'); diff --git a/packages/core-js/modules/es.array.to-spliced.js b/packages/core-js/modules/es.array.to-spliced.js index 3f533a0eee22..2c8ef541e218 100644 --- a/packages/core-js/modules/es.array.to-spliced.js +++ b/packages/core-js/modules/es.array.to-spliced.js @@ -1,3 +1,4 @@ +// @types: proposals/change-array-by-copy 'use strict'; var $ = require('../internals/export'); var addToUnscopables = require('../internals/add-to-unscopables'); diff --git a/packages/core-js/modules/es.array.with.js b/packages/core-js/modules/es.array.with.js index 49d64ba1dcb0..067e5baa1364 100644 --- a/packages/core-js/modules/es.array.with.js +++ b/packages/core-js/modules/es.array.with.js @@ -1,3 +1,4 @@ +// @types: proposals/change-array-by-copy 'use strict'; var $ = require('../internals/export'); var lengthOfArrayLike = require('../internals/length-of-array-like'); diff --git a/packages/core-js/modules/es.async-disposable-stack.constructor.js b/packages/core-js/modules/es.async-disposable-stack.constructor.js index c697b1810ec6..cb388aea86d2 100644 --- a/packages/core-js/modules/es.async-disposable-stack.constructor.js +++ b/packages/core-js/modules/es.async-disposable-stack.constructor.js @@ -1,3 +1,4 @@ +// @types: proposals/explicit-resource-management 'use strict'; // https://github.com/tc39/proposal-async-explicit-resource-management var $ = require('../internals/export'); diff --git a/packages/core-js/modules/es.async-iterator.async-dispose.js b/packages/core-js/modules/es.async-iterator.async-dispose.js index 5b58e53d7ab9..8b8d51cd0f47 100644 --- a/packages/core-js/modules/es.async-iterator.async-dispose.js +++ b/packages/core-js/modules/es.async-iterator.async-dispose.js @@ -1,3 +1,4 @@ +// @types: proposals/explicit-resource-management 'use strict'; // https://github.com/tc39/proposal-async-explicit-resource-management var call = require('../internals/function-call'); diff --git a/packages/core-js/modules/es.data-view.get-float16.js b/packages/core-js/modules/es.data-view.get-float16.js index 0c61792ceca3..f53b106f0d4a 100644 --- a/packages/core-js/modules/es.data-view.get-float16.js +++ b/packages/core-js/modules/es.data-view.get-float16.js @@ -1,3 +1,4 @@ +// @types: proposals/float16 'use strict'; var $ = require('../internals/export'); var uncurryThis = require('../internals/function-uncurry-this'); diff --git a/packages/core-js/modules/es.data-view.set-float16.js b/packages/core-js/modules/es.data-view.set-float16.js index 1cab3a9644d0..900c6ebcc0fd 100644 --- a/packages/core-js/modules/es.data-view.set-float16.js +++ b/packages/core-js/modules/es.data-view.set-float16.js @@ -1,3 +1,4 @@ +// @types: proposals/float16 'use strict'; var $ = require('../internals/export'); var getBuiltInStaticMethod = require('../internals/get-built-in-static-method'); diff --git a/packages/core-js/modules/es.disposable-stack.constructor.js b/packages/core-js/modules/es.disposable-stack.constructor.js index 8375a086d8ca..56e2e385f9c8 100644 --- a/packages/core-js/modules/es.disposable-stack.constructor.js +++ b/packages/core-js/modules/es.disposable-stack.constructor.js @@ -1,3 +1,4 @@ +// @types: proposals/explicit-resource-management 'use strict'; // https://github.com/tc39/proposal-explicit-resource-management var $ = require('../internals/export'); diff --git a/packages/core-js/modules/es.error.cause.js b/packages/core-js/modules/es.error.cause.js index 26a0215eedab..7b74b15a87a9 100644 --- a/packages/core-js/modules/es.error.cause.js +++ b/packages/core-js/modules/es.error.cause.js @@ -1,3 +1,4 @@ +// @types: proposals/error-cause 'use strict'; /* eslint-disable no-unused-vars -- required for functions `.length` */ var $ = require('../internals/export'); diff --git a/packages/core-js/modules/es.error.is-error.js b/packages/core-js/modules/es.error.is-error.js index e8ab5f0b3ba9..e2de15772a57 100644 --- a/packages/core-js/modules/es.error.is-error.js +++ b/packages/core-js/modules/es.error.is-error.js @@ -1,3 +1,4 @@ +// @types: proposals/is-error 'use strict'; var $ = require('../internals/export'); var getBuiltIn = require('../internals/get-built-in'); diff --git a/packages/core-js/modules/es.iterator.concat.js b/packages/core-js/modules/es.iterator.concat.js index b92b25c7e4f4..d3b43b7ff962 100644 --- a/packages/core-js/modules/es.iterator.concat.js +++ b/packages/core-js/modules/es.iterator.concat.js @@ -1,3 +1,4 @@ +// @types: proposals/iterator-sequencing 'use strict'; var $ = require('../internals/export'); var call = require('../internals/function-call'); diff --git a/packages/core-js/modules/es.iterator.constructor.js b/packages/core-js/modules/es.iterator.constructor.js index 063d33c748a8..4478b408b7b6 100644 --- a/packages/core-js/modules/es.iterator.constructor.js +++ b/packages/core-js/modules/es.iterator.constructor.js @@ -1,3 +1,4 @@ +// @types: proposals/iterator-helpers 'use strict'; var $ = require('../internals/export'); var globalThis = require('../internals/global-this'); diff --git a/packages/core-js/modules/es.iterator.dispose.js b/packages/core-js/modules/es.iterator.dispose.js index eb5dda71b2e5..498d7b87c9bd 100644 --- a/packages/core-js/modules/es.iterator.dispose.js +++ b/packages/core-js/modules/es.iterator.dispose.js @@ -1,3 +1,4 @@ +// @types: proposals/explicit-resource-management 'use strict'; // https://github.com/tc39/proposal-explicit-resource-management var call = require('../internals/function-call'); diff --git a/packages/core-js/modules/es.iterator.drop.js b/packages/core-js/modules/es.iterator.drop.js index 6568175a87a4..db688af3037a 100644 --- a/packages/core-js/modules/es.iterator.drop.js +++ b/packages/core-js/modules/es.iterator.drop.js @@ -1,3 +1,4 @@ +// @types: proposals/iterator-helpers 'use strict'; var $ = require('../internals/export'); var call = require('../internals/function-call'); diff --git a/packages/core-js/modules/es.iterator.every.js b/packages/core-js/modules/es.iterator.every.js index 1c477ba01c35..c401c13ce343 100644 --- a/packages/core-js/modules/es.iterator.every.js +++ b/packages/core-js/modules/es.iterator.every.js @@ -1,3 +1,4 @@ +// @types: proposals/iterator-helpers 'use strict'; var $ = require('../internals/export'); var call = require('../internals/function-call'); diff --git a/packages/core-js/modules/es.iterator.filter.js b/packages/core-js/modules/es.iterator.filter.js index a23a6ebf78ad..689f1a8cddbb 100644 --- a/packages/core-js/modules/es.iterator.filter.js +++ b/packages/core-js/modules/es.iterator.filter.js @@ -1,3 +1,4 @@ +// @types: proposals/iterator-helpers 'use strict'; var $ = require('../internals/export'); var call = require('../internals/function-call'); diff --git a/packages/core-js/modules/es.iterator.find.js b/packages/core-js/modules/es.iterator.find.js index 02643692f1d4..05e46bdff74a 100644 --- a/packages/core-js/modules/es.iterator.find.js +++ b/packages/core-js/modules/es.iterator.find.js @@ -1,3 +1,4 @@ +// @types: proposals/iterator-helpers 'use strict'; var $ = require('../internals/export'); var call = require('../internals/function-call'); diff --git a/packages/core-js/modules/es.iterator.flat-map.js b/packages/core-js/modules/es.iterator.flat-map.js index ab8c5d1049ab..ab543194148d 100644 --- a/packages/core-js/modules/es.iterator.flat-map.js +++ b/packages/core-js/modules/es.iterator.flat-map.js @@ -1,3 +1,4 @@ +// @types: proposals/iterator-helpers 'use strict'; var $ = require('../internals/export'); var call = require('../internals/function-call'); diff --git a/packages/core-js/modules/es.iterator.for-each.js b/packages/core-js/modules/es.iterator.for-each.js index 670aaef4902c..08c0d7b4b005 100644 --- a/packages/core-js/modules/es.iterator.for-each.js +++ b/packages/core-js/modules/es.iterator.for-each.js @@ -1,3 +1,4 @@ +// @types: proposals/iterator-helpers 'use strict'; var $ = require('../internals/export'); var call = require('../internals/function-call'); diff --git a/packages/core-js/modules/es.iterator.from.js b/packages/core-js/modules/es.iterator.from.js index a74ae14ce6db..8569c51ad794 100644 --- a/packages/core-js/modules/es.iterator.from.js +++ b/packages/core-js/modules/es.iterator.from.js @@ -1,3 +1,4 @@ +// @types: proposals/iterator-helpers 'use strict'; var $ = require('../internals/export'); var call = require('../internals/function-call'); diff --git a/packages/core-js/modules/es.iterator.map.js b/packages/core-js/modules/es.iterator.map.js index 8fa96df286bd..396cc4f69e0d 100644 --- a/packages/core-js/modules/es.iterator.map.js +++ b/packages/core-js/modules/es.iterator.map.js @@ -1,3 +1,4 @@ +// @types: proposals/iterator-helpers 'use strict'; var $ = require('../internals/export'); var call = require('../internals/function-call'); diff --git a/packages/core-js/modules/es.iterator.reduce.js b/packages/core-js/modules/es.iterator.reduce.js index b0078e78352d..b4914ddcbad3 100644 --- a/packages/core-js/modules/es.iterator.reduce.js +++ b/packages/core-js/modules/es.iterator.reduce.js @@ -1,3 +1,4 @@ +// @types: proposals/iterator-helpers 'use strict'; var $ = require('../internals/export'); var iterate = require('../internals/iterate'); diff --git a/packages/core-js/modules/es.iterator.some.js b/packages/core-js/modules/es.iterator.some.js index a4eda9971d1a..9e80e682a801 100644 --- a/packages/core-js/modules/es.iterator.some.js +++ b/packages/core-js/modules/es.iterator.some.js @@ -1,3 +1,4 @@ +// @types: proposals/iterator-helpers 'use strict'; var $ = require('../internals/export'); var call = require('../internals/function-call'); diff --git a/packages/core-js/modules/es.iterator.take.js b/packages/core-js/modules/es.iterator.take.js index 26e8daf96e40..89fde77ec89d 100644 --- a/packages/core-js/modules/es.iterator.take.js +++ b/packages/core-js/modules/es.iterator.take.js @@ -1,3 +1,4 @@ +// @types: proposals/iterator-helpers 'use strict'; var $ = require('../internals/export'); var call = require('../internals/function-call'); diff --git a/packages/core-js/modules/es.iterator.to-array.js b/packages/core-js/modules/es.iterator.to-array.js index bc74487c2e76..cafb70852c46 100644 --- a/packages/core-js/modules/es.iterator.to-array.js +++ b/packages/core-js/modules/es.iterator.to-array.js @@ -1,3 +1,4 @@ +// @types: proposals/iterator-helpers 'use strict'; var $ = require('../internals/export'); var anObject = require('../internals/an-object'); diff --git a/packages/core-js/modules/es.json.is-raw-json.js b/packages/core-js/modules/es.json.is-raw-json.js index 90290c4853be..1f108e5bc593 100644 --- a/packages/core-js/modules/es.json.is-raw-json.js +++ b/packages/core-js/modules/es.json.is-raw-json.js @@ -1,3 +1,4 @@ +// @types: proposals/json-parse-with-source 'use strict'; var $ = require('../internals/export'); var NATIVE_RAW_JSON = require('../internals/native-raw-json'); diff --git a/packages/core-js/modules/es.json.parse.js b/packages/core-js/modules/es.json.parse.js index 8af7e7e8d4db..e076db0044bb 100644 --- a/packages/core-js/modules/es.json.parse.js +++ b/packages/core-js/modules/es.json.parse.js @@ -1,3 +1,4 @@ +// @types: proposals/json-parse-with-source 'use strict'; var $ = require('../internals/export'); var uncurryThis = require('../internals/function-uncurry-this'); diff --git a/packages/core-js/modules/es.json.raw-json.js b/packages/core-js/modules/es.json.raw-json.js index e5c30dc64081..5dadc9c47a92 100644 --- a/packages/core-js/modules/es.json.raw-json.js +++ b/packages/core-js/modules/es.json.raw-json.js @@ -1,3 +1,4 @@ +// @types: proposals/json-parse-with-source 'use strict'; var $ = require('../internals/export'); var NATIVE_RAW_JSON = require('../internals/native-raw-json'); diff --git a/packages/core-js/modules/es.map.get-or-insert-computed.js b/packages/core-js/modules/es.map.get-or-insert-computed.js index dde93056b820..84c48af2988c 100644 --- a/packages/core-js/modules/es.map.get-or-insert-computed.js +++ b/packages/core-js/modules/es.map.get-or-insert-computed.js @@ -1,3 +1,4 @@ +// @types: proposals/map-upsert 'use strict'; var $ = require('../internals/export'); var aCallable = require('../internals/a-callable'); diff --git a/packages/core-js/modules/es.map.get-or-insert.js b/packages/core-js/modules/es.map.get-or-insert.js index f1461c1336f9..4a3fd1279bcc 100644 --- a/packages/core-js/modules/es.map.get-or-insert.js +++ b/packages/core-js/modules/es.map.get-or-insert.js @@ -1,3 +1,4 @@ +// @types: proposals/map-upsert 'use strict'; var $ = require('../internals/export'); var MapHelpers = require('../internals/map-helpers'); diff --git a/packages/core-js/modules/es.map.group-by.js b/packages/core-js/modules/es.map.group-by.js index eee31dd2aca1..94a7d7aea6cf 100644 --- a/packages/core-js/modules/es.map.group-by.js +++ b/packages/core-js/modules/es.map.group-by.js @@ -1,3 +1,4 @@ +// @types: proposals/array-grouping 'use strict'; var $ = require('../internals/export'); var uncurryThis = require('../internals/function-uncurry-this'); diff --git a/packages/core-js/modules/es.math.f16round.js b/packages/core-js/modules/es.math.f16round.js index 6dad8db170e2..7430ee248b4e 100644 --- a/packages/core-js/modules/es.math.f16round.js +++ b/packages/core-js/modules/es.math.f16round.js @@ -1,3 +1,4 @@ +// @types: proposals/float16 'use strict'; var $ = require('../internals/export'); var sign = require('../internals/math-sign'); diff --git a/packages/core-js/modules/es.math.sum-precise.js b/packages/core-js/modules/es.math.sum-precise.js index 6c1653f086f8..c2c25e56c102 100644 --- a/packages/core-js/modules/es.math.sum-precise.js +++ b/packages/core-js/modules/es.math.sum-precise.js @@ -1,3 +1,4 @@ +// @types: proposals/math-sum 'use strict'; // based on Shewchuk's algorithm for exactly floating point addition // adapted from https://github.com/tc39/proposal-math-sum/blob/3513d58323a1ae25560e8700aa5294500c6c9287/polyfill/polyfill.mjs diff --git a/packages/core-js/modules/es.object.define-getter.js b/packages/core-js/modules/es.object.define-getter.js index 0700a5161711..06b4b1e3e252 100644 --- a/packages/core-js/modules/es.object.define-getter.js +++ b/packages/core-js/modules/es.object.define-getter.js @@ -1,3 +1,4 @@ +// @types: annex-b/object-prototype-accessor-methods 'use strict'; var $ = require('../internals/export'); var FORCED = require('../internals/object-prototype-accessors-forced'); diff --git a/packages/core-js/modules/es.object.define-setter.js b/packages/core-js/modules/es.object.define-setter.js index 75c76d38f6bf..69e7cf2d7abf 100644 --- a/packages/core-js/modules/es.object.define-setter.js +++ b/packages/core-js/modules/es.object.define-setter.js @@ -1,3 +1,4 @@ +// @types: annex-b/object-prototype-accessor-methods 'use strict'; var $ = require('../internals/export'); var FORCED = require('../internals/object-prototype-accessors-forced'); diff --git a/packages/core-js/modules/es.object.entries.js b/packages/core-js/modules/es.object.entries.js index 4735d9251987..a59793058a75 100644 --- a/packages/core-js/modules/es.object.entries.js +++ b/packages/core-js/modules/es.object.entries.js @@ -1,3 +1,4 @@ +// @types: proposals/object-values-entries 'use strict'; var $ = require('../internals/export'); var $entries = require('../internals/object-to-array').entries; diff --git a/packages/core-js/modules/es.object.from-entries.js b/packages/core-js/modules/es.object.from-entries.js index 321ae7d651d7..0bc14216c61a 100644 --- a/packages/core-js/modules/es.object.from-entries.js +++ b/packages/core-js/modules/es.object.from-entries.js @@ -1,3 +1,4 @@ +// @types: proposals/object-from-entries 'use strict'; var $ = require('../internals/export'); var iterate = require('../internals/iterate'); diff --git a/packages/core-js/modules/es.object.get-own-property-descriptors.js b/packages/core-js/modules/es.object.get-own-property-descriptors.js index ed7781a3cbae..76974ac99491 100644 --- a/packages/core-js/modules/es.object.get-own-property-descriptors.js +++ b/packages/core-js/modules/es.object.get-own-property-descriptors.js @@ -1,3 +1,4 @@ +// @types: proposals/object-get-own-property-descriptors 'use strict'; var $ = require('../internals/export'); var ownKeys = require('../internals/own-keys'); diff --git a/packages/core-js/modules/es.object.group-by.js b/packages/core-js/modules/es.object.group-by.js index 67e909329c87..b8aa00981728 100644 --- a/packages/core-js/modules/es.object.group-by.js +++ b/packages/core-js/modules/es.object.group-by.js @@ -1,3 +1,4 @@ +// @types: proposals/array-grouping 'use strict'; var $ = require('../internals/export'); var createProperty = require('../internals/create-property'); diff --git a/packages/core-js/modules/es.object.has-own.js b/packages/core-js/modules/es.object.has-own.js index 974e60c3b609..650443a0d779 100644 --- a/packages/core-js/modules/es.object.has-own.js +++ b/packages/core-js/modules/es.object.has-own.js @@ -1,3 +1,4 @@ +// @types: proposals/accessible-object-hasownproperty 'use strict'; var $ = require('../internals/export'); var hasOwn = require('../internals/has-own-property'); diff --git a/packages/core-js/modules/es.object.lookup-getter.js b/packages/core-js/modules/es.object.lookup-getter.js index 5fef7f074e68..9ca3da686270 100644 --- a/packages/core-js/modules/es.object.lookup-getter.js +++ b/packages/core-js/modules/es.object.lookup-getter.js @@ -1,3 +1,4 @@ +// @types: annex-b/object-prototype-accessor-methods 'use strict'; var $ = require('../internals/export'); var FORCED = require('../internals/object-prototype-accessors-forced'); diff --git a/packages/core-js/modules/es.object.lookup-setter.js b/packages/core-js/modules/es.object.lookup-setter.js index e8af92fc0cf2..e984c9bd2af2 100644 --- a/packages/core-js/modules/es.object.lookup-setter.js +++ b/packages/core-js/modules/es.object.lookup-setter.js @@ -1,3 +1,4 @@ +// @types: annex-b/object-prototype-accessor-methods 'use strict'; var $ = require('../internals/export'); var FORCED = require('../internals/object-prototype-accessors-forced'); diff --git a/packages/core-js/modules/es.object.proto.js b/packages/core-js/modules/es.object.proto.js index dbd88f7fb688..f4a9575f99cd 100644 --- a/packages/core-js/modules/es.object.proto.js +++ b/packages/core-js/modules/es.object.proto.js @@ -1,3 +1,4 @@ +// @types: annex-b/object-proto 'use strict'; var defineBuiltInAccessor = require('../internals/define-built-in-accessor'); var isObject = require('../internals/is-object'); diff --git a/packages/core-js/modules/es.object.values.js b/packages/core-js/modules/es.object.values.js index 349595ddfe2a..80a933ea2079 100644 --- a/packages/core-js/modules/es.object.values.js +++ b/packages/core-js/modules/es.object.values.js @@ -1,3 +1,4 @@ +// @types: proposals/object-values-entries 'use strict'; var $ = require('../internals/export'); var $values = require('../internals/object-to-array').values; diff --git a/packages/core-js/modules/es.promise.all-settled.js b/packages/core-js/modules/es.promise.all-settled.js index c43a66f73112..6701f10ced0e 100644 --- a/packages/core-js/modules/es.promise.all-settled.js +++ b/packages/core-js/modules/es.promise.all-settled.js @@ -1,3 +1,4 @@ +// @types: proposals/promise-all-settled 'use strict'; var $ = require('../internals/export'); var call = require('../internals/function-call'); diff --git a/packages/core-js/modules/es.promise.any.js b/packages/core-js/modules/es.promise.any.js index 5d38fc78ff1b..74c44b87ba1c 100644 --- a/packages/core-js/modules/es.promise.any.js +++ b/packages/core-js/modules/es.promise.any.js @@ -1,3 +1,4 @@ +// @types: proposals/promise-any 'use strict'; var $ = require('../internals/export'); var call = require('../internals/function-call'); diff --git a/packages/core-js/modules/es.promise.finally.js b/packages/core-js/modules/es.promise.finally.js index 7bf599239df2..d668fc91d4b5 100644 --- a/packages/core-js/modules/es.promise.finally.js +++ b/packages/core-js/modules/es.promise.finally.js @@ -1,3 +1,4 @@ +// @types: proposals/promise-finally 'use strict'; var $ = require('../internals/export'); var IS_PURE = require('../internals/is-pure'); diff --git a/packages/core-js/modules/es.promise.try.js b/packages/core-js/modules/es.promise.try.js index 91fc13f50ad4..b4098c3172cd 100644 --- a/packages/core-js/modules/es.promise.try.js +++ b/packages/core-js/modules/es.promise.try.js @@ -1,3 +1,4 @@ +// @types: proposals/promise-try 'use strict'; var $ = require('../internals/export'); var globalThis = require('../internals/global-this'); diff --git a/packages/core-js/modules/es.promise.with-resolvers.js b/packages/core-js/modules/es.promise.with-resolvers.js index 2d33773cbf49..ffd3bafa060e 100644 --- a/packages/core-js/modules/es.promise.with-resolvers.js +++ b/packages/core-js/modules/es.promise.with-resolvers.js @@ -1,3 +1,4 @@ +// @types: proposals/promise-with-resolvers 'use strict'; var $ = require('../internals/export'); var newPromiseCapabilityModule = require('../internals/new-promise-capability'); diff --git a/packages/core-js/modules/es.regexp.constructor.js b/packages/core-js/modules/es.regexp.constructor.js index d86aab5c15db..c593e6bf91d7 100644 --- a/packages/core-js/modules/es.regexp.constructor.js +++ b/packages/core-js/modules/es.regexp.constructor.js @@ -1,3 +1,5 @@ +// @types: proposals/regexp-dotall-flag +// @types: proposals/regexp-named-groups 'use strict'; // @dependency: es.regexp.exec var globalThis = require('../internals/global-this'); diff --git a/packages/core-js/modules/es.regexp.dot-all.js b/packages/core-js/modules/es.regexp.dot-all.js index b6d8895cc6a7..5bbb40ff355e 100644 --- a/packages/core-js/modules/es.regexp.dot-all.js +++ b/packages/core-js/modules/es.regexp.dot-all.js @@ -1,3 +1,4 @@ +// @types: proposals/regexp-dotall-flag 'use strict'; var UNSUPPORTED_DOT_ALL = require('../internals/regexp-unsupported-dot-all'); var classof = require('../internals/classof-raw'); diff --git a/packages/core-js/modules/es.regexp.escape.js b/packages/core-js/modules/es.regexp.escape.js index 38caa454cfc5..8f6986d14de9 100644 --- a/packages/core-js/modules/es.regexp.escape.js +++ b/packages/core-js/modules/es.regexp.escape.js @@ -1,3 +1,4 @@ +// @types: proposals/regexp-escaping 'use strict'; var $ = require('../internals/export'); var getBuiltInPrototypeMethod = require('../internals/get-built-in-prototype-method'); diff --git a/packages/core-js/modules/es.regexp.exec.js b/packages/core-js/modules/es.regexp.exec.js index b2396e5816b6..8401b63d1f79 100644 --- a/packages/core-js/modules/es.regexp.exec.js +++ b/packages/core-js/modules/es.regexp.exec.js @@ -1,3 +1,5 @@ +// @types: proposals/regexp-dotall-flag +// @types: proposals/regexp-named-groups 'use strict'; var $ = require('../internals/export'); var exec = require('../internals/regexp-exec'); diff --git a/packages/core-js/modules/es.regexp.flags.js b/packages/core-js/modules/es.regexp.flags.js index 2d4f6264e0f3..cf5f4f0b0f74 100644 --- a/packages/core-js/modules/es.regexp.flags.js +++ b/packages/core-js/modules/es.regexp.flags.js @@ -1,3 +1,4 @@ +// @types: proposals/regexp-dotall-flag 'use strict'; var defineBuiltInAccessor = require('../internals/define-built-in-accessor'); var regExpFlagsDetection = require('../internals/regexp-flags-detection'); diff --git a/packages/core-js/modules/es.set.difference.js b/packages/core-js/modules/es.set.difference.js index a5e889e9a813..a20ca00acfc4 100644 --- a/packages/core-js/modules/es.set.difference.js +++ b/packages/core-js/modules/es.set.difference.js @@ -1,3 +1,4 @@ +// @types: proposals/set-methods 'use strict'; var $ = require('../internals/export'); var aSet = require('../internals/a-set'); diff --git a/packages/core-js/modules/es.set.intersection.js b/packages/core-js/modules/es.set.intersection.js index 2fd74d5bbb30..f7eaad490b55 100644 --- a/packages/core-js/modules/es.set.intersection.js +++ b/packages/core-js/modules/es.set.intersection.js @@ -1,3 +1,4 @@ +// @types: proposals/set-methods 'use strict'; var $ = require('../internals/export'); var fails = require('../internals/fails'); diff --git a/packages/core-js/modules/es.set.is-disjoint-from.js b/packages/core-js/modules/es.set.is-disjoint-from.js index 685dbe14c88a..88c4ee8b481e 100644 --- a/packages/core-js/modules/es.set.is-disjoint-from.js +++ b/packages/core-js/modules/es.set.is-disjoint-from.js @@ -1,3 +1,4 @@ +// @types: proposals/set-methods 'use strict'; var $ = require('../internals/export'); var aSet = require('../internals/a-set'); diff --git a/packages/core-js/modules/es.set.is-subset-of.js b/packages/core-js/modules/es.set.is-subset-of.js index 9cfa54bf6611..9947f1a471a5 100644 --- a/packages/core-js/modules/es.set.is-subset-of.js +++ b/packages/core-js/modules/es.set.is-subset-of.js @@ -1,3 +1,4 @@ +// @types: proposals/set-methods 'use strict'; var $ = require('../internals/export'); var aSet = require('../internals/a-set'); diff --git a/packages/core-js/modules/es.set.is-superset-of.js b/packages/core-js/modules/es.set.is-superset-of.js index c66056b7648a..bad7af8fd3fb 100644 --- a/packages/core-js/modules/es.set.is-superset-of.js +++ b/packages/core-js/modules/es.set.is-superset-of.js @@ -1,3 +1,4 @@ +// @types: proposals/set-methods 'use strict'; var $ = require('../internals/export'); var aSet = require('../internals/a-set'); diff --git a/packages/core-js/modules/es.set.symmetric-difference.js b/packages/core-js/modules/es.set.symmetric-difference.js index 75ea7a2b5784..a264a53ed538 100644 --- a/packages/core-js/modules/es.set.symmetric-difference.js +++ b/packages/core-js/modules/es.set.symmetric-difference.js @@ -1,3 +1,4 @@ +// @types: proposals/set-methods 'use strict'; var $ = require('../internals/export'); var aSet = require('../internals/a-set'); diff --git a/packages/core-js/modules/es.set.union.js b/packages/core-js/modules/es.set.union.js index e0e1b3412647..6bb9d4cdacd8 100644 --- a/packages/core-js/modules/es.set.union.js +++ b/packages/core-js/modules/es.set.union.js @@ -1,3 +1,4 @@ +// @types: proposals/set-methods 'use strict'; var $ = require('../internals/export'); var aSet = require('../internals/a-set'); diff --git a/packages/core-js/modules/es.string.at.js b/packages/core-js/modules/es.string.at.js index 41377abc15fb..b5c4de109fa6 100644 --- a/packages/core-js/modules/es.string.at.js +++ b/packages/core-js/modules/es.string.at.js @@ -1,3 +1,4 @@ +// @types: proposals/relative-indexing-method 'use strict'; var $ = require('../internals/export'); var requireObjectCoercible = require('../internals/require-object-coercible'); diff --git a/packages/core-js/modules/es.string.is-well-formed.js b/packages/core-js/modules/es.string.is-well-formed.js index f4cb056c692d..69e090531737 100644 --- a/packages/core-js/modules/es.string.is-well-formed.js +++ b/packages/core-js/modules/es.string.is-well-formed.js @@ -1,3 +1,4 @@ +// @types: proposals/well-formed-unicode-strings 'use strict'; var $ = require('../internals/export'); var uncurryThis = require('../internals/function-uncurry-this'); diff --git a/packages/core-js/modules/es.string.match-all.js b/packages/core-js/modules/es.string.match-all.js index a499cdf4ced9..6982adda3359 100644 --- a/packages/core-js/modules/es.string.match-all.js +++ b/packages/core-js/modules/es.string.match-all.js @@ -1,3 +1,4 @@ +// @types: proposals/string-match-all 'use strict'; /* eslint-disable es/no-string-prototype-matchall -- safe */ var $ = require('../internals/export'); diff --git a/packages/core-js/modules/es.string.pad-end.js b/packages/core-js/modules/es.string.pad-end.js index c671bae66897..7395f8d90916 100644 --- a/packages/core-js/modules/es.string.pad-end.js +++ b/packages/core-js/modules/es.string.pad-end.js @@ -1,3 +1,4 @@ +// @types: proposals/string-padding 'use strict'; var $ = require('../internals/export'); var $padEnd = require('../internals/string-pad').end; diff --git a/packages/core-js/modules/es.string.pad-start.js b/packages/core-js/modules/es.string.pad-start.js index b4bc677c4e45..54ba90a8fea7 100644 --- a/packages/core-js/modules/es.string.pad-start.js +++ b/packages/core-js/modules/es.string.pad-start.js @@ -1,3 +1,4 @@ +// @types: proposals/string-padding 'use strict'; var $ = require('../internals/export'); var $padStart = require('../internals/string-pad').start; diff --git a/packages/core-js/modules/es.string.replace-all.js b/packages/core-js/modules/es.string.replace-all.js index 60931f31b0a2..8df12fae509e 100644 --- a/packages/core-js/modules/es.string.replace-all.js +++ b/packages/core-js/modules/es.string.replace-all.js @@ -1,3 +1,4 @@ +// @types: proposals/string-replace-all 'use strict'; var $ = require('../internals/export'); var call = require('../internals/function-call'); diff --git a/packages/core-js/modules/es.string.to-well-formed.js b/packages/core-js/modules/es.string.to-well-formed.js index e16005cecdd4..ecb426dc086f 100644 --- a/packages/core-js/modules/es.string.to-well-formed.js +++ b/packages/core-js/modules/es.string.to-well-formed.js @@ -1,3 +1,4 @@ +// @types: proposals/well-formed-unicode-strings 'use strict'; var $ = require('../internals/export'); var call = require('../internals/function-call'); diff --git a/packages/core-js/modules/es.string.trim-end.js b/packages/core-js/modules/es.string.trim-end.js index 215978f998bd..4b79fe528384 100644 --- a/packages/core-js/modules/es.string.trim-end.js +++ b/packages/core-js/modules/es.string.trim-end.js @@ -1,3 +1,4 @@ +// @types: proposals/string-left-right-trim 'use strict'; var $ = require('../internals/export'); var trimEnd = require('../internals/string-trim-end'); diff --git a/packages/core-js/modules/es.string.trim-left.js b/packages/core-js/modules/es.string.trim-left.js index d40b2951262d..258ee53ac30d 100644 --- a/packages/core-js/modules/es.string.trim-left.js +++ b/packages/core-js/modules/es.string.trim-left.js @@ -1,3 +1,4 @@ +// @types: proposals/string-left-right-trim 'use strict'; var $ = require('../internals/export'); var trimStart = require('../internals/string-trim-start'); diff --git a/packages/core-js/modules/es.string.trim-right.js b/packages/core-js/modules/es.string.trim-right.js index 50232778d204..5f3771059fc1 100644 --- a/packages/core-js/modules/es.string.trim-right.js +++ b/packages/core-js/modules/es.string.trim-right.js @@ -1,3 +1,4 @@ +// @types: proposals/string-left-right-trim 'use strict'; var $ = require('../internals/export'); var trimEnd = require('../internals/string-trim-end'); diff --git a/packages/core-js/modules/es.string.trim-start.js b/packages/core-js/modules/es.string.trim-start.js index 2fcd9f4ad0aa..59153fbabae8 100644 --- a/packages/core-js/modules/es.string.trim-start.js +++ b/packages/core-js/modules/es.string.trim-start.js @@ -1,3 +1,4 @@ +// @types: proposals/string-left-right-trim 'use strict'; var $ = require('../internals/export'); var trimStart = require('../internals/string-trim-start'); diff --git a/packages/core-js/modules/es.suppressed-error.constructor.js b/packages/core-js/modules/es.suppressed-error.constructor.js index 4926fd5edd69..fae65eaab6d6 100644 --- a/packages/core-js/modules/es.suppressed-error.constructor.js +++ b/packages/core-js/modules/es.suppressed-error.constructor.js @@ -1,3 +1,4 @@ +// @types: proposals/explicit-resource-management 'use strict'; var $ = require('../internals/export'); var globalThis = require('../internals/global-this'); diff --git a/packages/core-js/modules/es.symbol.async-dispose.js b/packages/core-js/modules/es.symbol.async-dispose.js index 14a719f64581..0ad0912c8af5 100644 --- a/packages/core-js/modules/es.symbol.async-dispose.js +++ b/packages/core-js/modules/es.symbol.async-dispose.js @@ -1,3 +1,4 @@ +// @types: proposals/explicit-resource-management 'use strict'; var globalThis = require('../internals/global-this'); var defineWellKnownSymbol = require('../internals/well-known-symbol-define'); diff --git a/packages/core-js/modules/es.symbol.async-iterator.js b/packages/core-js/modules/es.symbol.async-iterator.js index 40d1930c1aa0..5c27469ba7a3 100644 --- a/packages/core-js/modules/es.symbol.async-iterator.js +++ b/packages/core-js/modules/es.symbol.async-iterator.js @@ -1,3 +1,4 @@ +// @types: proposals/async-iteration 'use strict'; var defineWellKnownSymbol = require('../internals/well-known-symbol-define'); diff --git a/packages/core-js/modules/es.symbol.constructor.js b/packages/core-js/modules/es.symbol.constructor.js index 23edb3576159..a2f6ca4f0244 100644 --- a/packages/core-js/modules/es.symbol.constructor.js +++ b/packages/core-js/modules/es.symbol.constructor.js @@ -1,3 +1,4 @@ +// @types: proposals/symbol-description 'use strict'; var $ = require('../internals/export'); var globalThis = require('../internals/global-this'); diff --git a/packages/core-js/modules/es.symbol.description.js b/packages/core-js/modules/es.symbol.description.js index b3c8072ba237..3352b3c9e502 100644 --- a/packages/core-js/modules/es.symbol.description.js +++ b/packages/core-js/modules/es.symbol.description.js @@ -1,3 +1,4 @@ +// @types: proposals/symbol-description // `Symbol.prototype.description` getter // https://tc39.es/ecma262/#sec-symbol.prototype.description 'use strict'; diff --git a/packages/core-js/modules/es.symbol.dispose.js b/packages/core-js/modules/es.symbol.dispose.js index 6124e641c75f..737f9fd68672 100644 --- a/packages/core-js/modules/es.symbol.dispose.js +++ b/packages/core-js/modules/es.symbol.dispose.js @@ -1,3 +1,4 @@ +// @types: proposals/explicit-resource-management 'use strict'; var globalThis = require('../internals/global-this'); var defineWellKnownSymbol = require('../internals/well-known-symbol-define'); diff --git a/packages/core-js/modules/es.symbol.match-all.js b/packages/core-js/modules/es.symbol.match-all.js index 19a3bd07bb9d..0afdec7e071e 100644 --- a/packages/core-js/modules/es.symbol.match-all.js +++ b/packages/core-js/modules/es.symbol.match-all.js @@ -1,3 +1,4 @@ +// @types: proposals/string-match-all 'use strict'; var defineWellKnownSymbol = require('../internals/well-known-symbol-define'); diff --git a/packages/core-js/modules/es.typed-array.at.js b/packages/core-js/modules/es.typed-array.at.js index 70a5cecb048f..2aa62db84a62 100644 --- a/packages/core-js/modules/es.typed-array.at.js +++ b/packages/core-js/modules/es.typed-array.at.js @@ -1,3 +1,4 @@ +// @types: proposals/relative-indexing-method 'use strict'; var exportTypedArrayMethod = require('../internals/export-typed-array-method'); var aTypedArray = require('../internals/a-typed-array'); diff --git a/packages/core-js/modules/es.typed-array.find-last-index.js b/packages/core-js/modules/es.typed-array.find-last-index.js index 4691821bb1eb..a6b6eac803c1 100644 --- a/packages/core-js/modules/es.typed-array.find-last-index.js +++ b/packages/core-js/modules/es.typed-array.find-last-index.js @@ -1,3 +1,4 @@ +// @types: proposals/array-find-from-last 'use strict'; var exportTypedArrayMethod = require('../internals/export-typed-array-method'); var aTypedArray = require('../internals/a-typed-array'); diff --git a/packages/core-js/modules/es.typed-array.find-last.js b/packages/core-js/modules/es.typed-array.find-last.js index 186f6bea5e5f..b8f6d0bae8ef 100644 --- a/packages/core-js/modules/es.typed-array.find-last.js +++ b/packages/core-js/modules/es.typed-array.find-last.js @@ -1,3 +1,4 @@ +// @types: proposals/array-find-from-last 'use strict'; var exportTypedArrayMethod = require('../internals/export-typed-array-method'); var aTypedArray = require('../internals/a-typed-array'); diff --git a/packages/core-js/modules/es.typed-array.includes.js b/packages/core-js/modules/es.typed-array.includes.js index e2917486a18b..b87a3fbca055 100644 --- a/packages/core-js/modules/es.typed-array.includes.js +++ b/packages/core-js/modules/es.typed-array.includes.js @@ -1,3 +1,4 @@ +// @types: proposals/array-includes 'use strict'; var exportTypedArrayMethod = require('../internals/export-typed-array-method'); var aTypedArray = require('../internals/a-typed-array'); diff --git a/packages/core-js/modules/es.typed-array.to-reversed.js b/packages/core-js/modules/es.typed-array.to-reversed.js index 7242b54579b0..bc009c7e3c98 100644 --- a/packages/core-js/modules/es.typed-array.to-reversed.js +++ b/packages/core-js/modules/es.typed-array.to-reversed.js @@ -1,3 +1,4 @@ +// @types: proposals/change-array-by-copy 'use strict'; var lengthOfArrayLike = require('../internals/length-of-array-like'); var exportTypedArrayMethod = require('../internals/export-typed-array-method'); diff --git a/packages/core-js/modules/es.typed-array.to-sorted.js b/packages/core-js/modules/es.typed-array.to-sorted.js index c29966fc7822..3aa8114a5a04 100644 --- a/packages/core-js/modules/es.typed-array.to-sorted.js +++ b/packages/core-js/modules/es.typed-array.to-sorted.js @@ -1,3 +1,4 @@ +// @types: proposals/change-array-by-copy 'use strict'; var uncurryThis = require('../internals/function-uncurry-this'); var aCallable = require('../internals/a-callable'); diff --git a/packages/core-js/modules/es.typed-array.with.js b/packages/core-js/modules/es.typed-array.with.js index 2cd87fc9e3c4..0c8a1f4c3e9a 100644 --- a/packages/core-js/modules/es.typed-array.with.js +++ b/packages/core-js/modules/es.typed-array.with.js @@ -1,3 +1,4 @@ +// @types: proposals/change-array-by-copy 'use strict'; var exportTypedArrayMethod = require('../internals/export-typed-array-method'); var aTypedArray = require('../internals/a-typed-array'); diff --git a/packages/core-js/modules/es.uint8-array.from-base64.js b/packages/core-js/modules/es.uint8-array.from-base64.js index aed350b3a67b..e617667aeeb5 100644 --- a/packages/core-js/modules/es.uint8-array.from-base64.js +++ b/packages/core-js/modules/es.uint8-array.from-base64.js @@ -1,3 +1,4 @@ +// @types: proposals/array-buffer-base64 'use strict'; /* eslint-disable es/no-uint8array-frombase64 -- safe */ var $ = require('../internals/export'); diff --git a/packages/core-js/modules/es.uint8-array.from-hex.js b/packages/core-js/modules/es.uint8-array.from-hex.js index efb7d1c6d645..e4549f1d403e 100644 --- a/packages/core-js/modules/es.uint8-array.from-hex.js +++ b/packages/core-js/modules/es.uint8-array.from-hex.js @@ -1,3 +1,4 @@ +// @types: proposals/array-buffer-base64 'use strict'; var $ = require('../internals/export'); var aString = require('../internals/a-string'); diff --git a/packages/core-js/modules/es.uint8-array.set-from-base64.js b/packages/core-js/modules/es.uint8-array.set-from-base64.js index 7f9d314fd6bb..f6a6c0dba893 100644 --- a/packages/core-js/modules/es.uint8-array.set-from-base64.js +++ b/packages/core-js/modules/es.uint8-array.set-from-base64.js @@ -1,3 +1,4 @@ +// @types: proposals/array-buffer-base64 'use strict'; /* eslint-disable es/no-uint8array-prototype-setfrombase64 -- safe */ var $ = require('../internals/export'); diff --git a/packages/core-js/modules/es.uint8-array.set-from-hex.js b/packages/core-js/modules/es.uint8-array.set-from-hex.js index fa3e9ec9483a..4a81c942a2af 100644 --- a/packages/core-js/modules/es.uint8-array.set-from-hex.js +++ b/packages/core-js/modules/es.uint8-array.set-from-hex.js @@ -1,3 +1,4 @@ +// @types: proposals/array-buffer-base64 'use strict'; var $ = require('../internals/export'); var aString = require('../internals/a-string'); diff --git a/packages/core-js/modules/es.uint8-array.to-base64.js b/packages/core-js/modules/es.uint8-array.to-base64.js index 1a9d890b0925..e3c518e44a62 100644 --- a/packages/core-js/modules/es.uint8-array.to-base64.js +++ b/packages/core-js/modules/es.uint8-array.to-base64.js @@ -1,3 +1,4 @@ +// @types: proposals/array-buffer-base64 'use strict'; /* eslint-disable es/no-uint8array-prototype-tobase64 -- safe */ var $ = require('../internals/export'); diff --git a/packages/core-js/modules/es.uint8-array.to-hex.js b/packages/core-js/modules/es.uint8-array.to-hex.js index d96d3b405b5d..d17f4dfaa1fc 100644 --- a/packages/core-js/modules/es.uint8-array.to-hex.js +++ b/packages/core-js/modules/es.uint8-array.to-hex.js @@ -1,3 +1,4 @@ +// @types: proposals/array-buffer-base64 'use strict'; /* eslint-disable es/no-uint8array-prototype-tohex -- safe */ var $ = require('../internals/export'); diff --git a/packages/core-js/modules/es.weak-map.get-or-insert-computed.js b/packages/core-js/modules/es.weak-map.get-or-insert-computed.js index e96e759896a7..2f994de08431 100644 --- a/packages/core-js/modules/es.weak-map.get-or-insert-computed.js +++ b/packages/core-js/modules/es.weak-map.get-or-insert-computed.js @@ -1,3 +1,4 @@ +// @types: proposals/map-upsert 'use strict'; var $ = require('../internals/export'); var aCallable = require('../internals/a-callable'); diff --git a/packages/core-js/modules/es.weak-map.get-or-insert.js b/packages/core-js/modules/es.weak-map.get-or-insert.js index 1d1cac4fca28..1be8965f361f 100644 --- a/packages/core-js/modules/es.weak-map.get-or-insert.js +++ b/packages/core-js/modules/es.weak-map.get-or-insert.js @@ -1,3 +1,4 @@ +// @types: proposals/map-upsert 'use strict'; var $ = require('../internals/export'); var WeakMapHelpers = require('../internals/weak-map-helpers'); diff --git a/packages/core-js/modules/esnext.array.filter-reject.js b/packages/core-js/modules/esnext.array.filter-reject.js index 9e0604e3ef6d..ca2bda0c8043 100644 --- a/packages/core-js/modules/esnext.array.filter-reject.js +++ b/packages/core-js/modules/esnext.array.filter-reject.js @@ -1,3 +1,4 @@ +// @types: proposals/array-filtering 'use strict'; var $ = require('../internals/export'); var $filterReject = require('../internals/array-iteration').filterReject; diff --git a/packages/core-js/modules/esnext.array.is-template-object.js b/packages/core-js/modules/esnext.array.is-template-object.js index 65c26f7e5b3d..6940e7071efa 100644 --- a/packages/core-js/modules/esnext.array.is-template-object.js +++ b/packages/core-js/modules/esnext.array.is-template-object.js @@ -1,3 +1,4 @@ +// @types: proposals/array-is-template-object 'use strict'; var $ = require('../internals/export'); diff --git a/packages/core-js/modules/esnext.array.unique-by.js b/packages/core-js/modules/esnext.array.unique-by.js index efc5b7daeffa..311b85f53a2c 100644 --- a/packages/core-js/modules/esnext.array.unique-by.js +++ b/packages/core-js/modules/esnext.array.unique-by.js @@ -1,3 +1,4 @@ +// @types: proposals/array-unique 'use strict'; var $ = require('../internals/export'); var addToUnscopables = require('../internals/add-to-unscopables'); diff --git a/packages/core-js/modules/esnext.async-iterator.constructor.js b/packages/core-js/modules/esnext.async-iterator.constructor.js index de9ea36c5162..19d0da9b17bd 100644 --- a/packages/core-js/modules/esnext.async-iterator.constructor.js +++ b/packages/core-js/modules/esnext.async-iterator.constructor.js @@ -1,3 +1,4 @@ +// @types: proposals/async-iterator-helpers 'use strict'; var $ = require('../internals/export'); var anInstance = require('../internals/an-instance'); diff --git a/packages/core-js/modules/esnext.async-iterator.drop.js b/packages/core-js/modules/esnext.async-iterator.drop.js index 1f4ee18573f6..878e4f1fd4a1 100644 --- a/packages/core-js/modules/esnext.async-iterator.drop.js +++ b/packages/core-js/modules/esnext.async-iterator.drop.js @@ -1,3 +1,4 @@ +// @types: proposals/async-iterator-helpers 'use strict'; var $ = require('../internals/export'); var call = require('../internals/function-call'); diff --git a/packages/core-js/modules/esnext.async-iterator.every.js b/packages/core-js/modules/esnext.async-iterator.every.js index 7bd692b2656a..a3bb3f5692b5 100644 --- a/packages/core-js/modules/esnext.async-iterator.every.js +++ b/packages/core-js/modules/esnext.async-iterator.every.js @@ -1,3 +1,4 @@ +// @types: proposals/async-iterator-helpers 'use strict'; var $ = require('../internals/export'); var $every = require('../internals/async-iterator-iteration').every; diff --git a/packages/core-js/modules/esnext.async-iterator.filter.js b/packages/core-js/modules/esnext.async-iterator.filter.js index 9b1ace720df2..a0f121386b11 100644 --- a/packages/core-js/modules/esnext.async-iterator.filter.js +++ b/packages/core-js/modules/esnext.async-iterator.filter.js @@ -1,3 +1,4 @@ +// @types: proposals/async-iterator-helpers 'use strict'; var $ = require('../internals/export'); var call = require('../internals/function-call'); diff --git a/packages/core-js/modules/esnext.async-iterator.find.js b/packages/core-js/modules/esnext.async-iterator.find.js index 7af8b67e4001..f905bf19d84b 100644 --- a/packages/core-js/modules/esnext.async-iterator.find.js +++ b/packages/core-js/modules/esnext.async-iterator.find.js @@ -1,3 +1,4 @@ +// @types: proposals/async-iterator-helpers 'use strict'; var $ = require('../internals/export'); var $find = require('../internals/async-iterator-iteration').find; diff --git a/packages/core-js/modules/esnext.async-iterator.flat-map.js b/packages/core-js/modules/esnext.async-iterator.flat-map.js index 0f260a727264..2d0403b3e095 100644 --- a/packages/core-js/modules/esnext.async-iterator.flat-map.js +++ b/packages/core-js/modules/esnext.async-iterator.flat-map.js @@ -1,3 +1,4 @@ +// @types: proposals/async-iterator-helpers 'use strict'; var $ = require('../internals/export'); var call = require('../internals/function-call'); diff --git a/packages/core-js/modules/esnext.async-iterator.for-each.js b/packages/core-js/modules/esnext.async-iterator.for-each.js index 901b310806f1..3608432d9b5a 100644 --- a/packages/core-js/modules/esnext.async-iterator.for-each.js +++ b/packages/core-js/modules/esnext.async-iterator.for-each.js @@ -1,3 +1,4 @@ +// @types: proposals/async-iterator-helpers 'use strict'; var $ = require('../internals/export'); var $forEach = require('../internals/async-iterator-iteration').forEach; diff --git a/packages/core-js/modules/esnext.async-iterator.from.js b/packages/core-js/modules/esnext.async-iterator.from.js index e28915ffd9e3..4772620626d2 100644 --- a/packages/core-js/modules/esnext.async-iterator.from.js +++ b/packages/core-js/modules/esnext.async-iterator.from.js @@ -1,3 +1,4 @@ +// @types: proposals/async-iterator-helpers 'use strict'; var $ = require('../internals/export'); var toObject = require('../internals/to-object'); diff --git a/packages/core-js/modules/esnext.async-iterator.map.js b/packages/core-js/modules/esnext.async-iterator.map.js index 2acb598e92c1..ca5593c78ca5 100644 --- a/packages/core-js/modules/esnext.async-iterator.map.js +++ b/packages/core-js/modules/esnext.async-iterator.map.js @@ -1,3 +1,4 @@ +// @types: proposals/async-iterator-helpers 'use strict'; var $ = require('../internals/export'); var call = require('../internals/function-call'); diff --git a/packages/core-js/modules/esnext.async-iterator.reduce.js b/packages/core-js/modules/esnext.async-iterator.reduce.js index 3e52016ee3ae..3f502f59a470 100644 --- a/packages/core-js/modules/esnext.async-iterator.reduce.js +++ b/packages/core-js/modules/esnext.async-iterator.reduce.js @@ -1,3 +1,4 @@ +// @types: proposals/async-iterator-helpers 'use strict'; var $ = require('../internals/export'); var call = require('../internals/function-call'); diff --git a/packages/core-js/modules/esnext.async-iterator.some.js b/packages/core-js/modules/esnext.async-iterator.some.js index 1586d1726213..751a90fc38c3 100644 --- a/packages/core-js/modules/esnext.async-iterator.some.js +++ b/packages/core-js/modules/esnext.async-iterator.some.js @@ -1,3 +1,4 @@ +// @types: proposals/async-iterator-helpers 'use strict'; var $ = require('../internals/export'); var $some = require('../internals/async-iterator-iteration').some; diff --git a/packages/core-js/modules/esnext.async-iterator.take.js b/packages/core-js/modules/esnext.async-iterator.take.js index c05b3ef98389..7a75bd083801 100644 --- a/packages/core-js/modules/esnext.async-iterator.take.js +++ b/packages/core-js/modules/esnext.async-iterator.take.js @@ -1,3 +1,4 @@ +// @types: proposals/async-iterator-helpers 'use strict'; var $ = require('../internals/export'); var call = require('../internals/function-call'); diff --git a/packages/core-js/modules/esnext.async-iterator.to-array.js b/packages/core-js/modules/esnext.async-iterator.to-array.js index 54b52a38a8eb..8d3f9d8be321 100644 --- a/packages/core-js/modules/esnext.async-iterator.to-array.js +++ b/packages/core-js/modules/esnext.async-iterator.to-array.js @@ -1,3 +1,4 @@ +// @types: proposals/async-iterator-helpers 'use strict'; var $ = require('../internals/export'); var $toArray = require('../internals/async-iterator-iteration').toArray; diff --git a/packages/core-js/modules/esnext.data-view.get-uint8-clamped.js b/packages/core-js/modules/esnext.data-view.get-uint8-clamped.js index 00f08a7b08d2..a6715023b2d5 100644 --- a/packages/core-js/modules/esnext.data-view.get-uint8-clamped.js +++ b/packages/core-js/modules/esnext.data-view.get-uint8-clamped.js @@ -1,3 +1,4 @@ +// @types: proposals/data-view-get-set-uint8-clamped 'use strict'; var $ = require('../internals/export'); var uncurryThis = require('../internals/function-uncurry-this'); diff --git a/packages/core-js/modules/esnext.data-view.set-uint8-clamped.js b/packages/core-js/modules/esnext.data-view.set-uint8-clamped.js index 8b524379ad80..5d906fba56a1 100644 --- a/packages/core-js/modules/esnext.data-view.set-uint8-clamped.js +++ b/packages/core-js/modules/esnext.data-view.set-uint8-clamped.js @@ -1,3 +1,4 @@ +// @types: proposals/data-view-get-set-uint8-clamped 'use strict'; var $ = require('../internals/export'); var uncurryThis = require('../internals/function-uncurry-this'); diff --git a/packages/core-js/modules/esnext.function.demethodize.js b/packages/core-js/modules/esnext.function.demethodize.js index 1d8f9ec11418..1899734ebf86 100644 --- a/packages/core-js/modules/esnext.function.demethodize.js +++ b/packages/core-js/modules/esnext.function.demethodize.js @@ -1,3 +1,4 @@ +// @types: proposals/function-demethodize 'use strict'; var $ = require('../internals/export'); var uncurryThis = require('../internals/function-uncurry-this'); diff --git a/packages/core-js/modules/esnext.function.metadata.js b/packages/core-js/modules/esnext.function.metadata.js index fb2c188c43b2..df25e0e936af 100644 --- a/packages/core-js/modules/esnext.function.metadata.js +++ b/packages/core-js/modules/esnext.function.metadata.js @@ -1,3 +1,4 @@ +// @types: proposals/decorator-metadata 'use strict'; var wellKnownSymbol = require('../internals/well-known-symbol'); diff --git a/packages/core-js/modules/esnext.iterator.chunks.js b/packages/core-js/modules/esnext.iterator.chunks.js index a6f9d2a8e7b3..8e6bafe2fdc5 100644 --- a/packages/core-js/modules/esnext.iterator.chunks.js +++ b/packages/core-js/modules/esnext.iterator.chunks.js @@ -1,3 +1,4 @@ +// @types: proposals/iterator-chunking 'use strict'; var $ = require('../internals/export'); var anObject = require('../internals/an-object'); diff --git a/packages/core-js/modules/esnext.iterator.join.js b/packages/core-js/modules/esnext.iterator.join.js index d49bf3b1621e..ff2fc67f862c 100644 --- a/packages/core-js/modules/esnext.iterator.join.js +++ b/packages/core-js/modules/esnext.iterator.join.js @@ -1,3 +1,4 @@ +// @types: proposals/iterator-join 'use strict'; var $ = require('../internals/export'); var $toString = require('../internals/to-string'); diff --git a/packages/core-js/modules/esnext.iterator.range.js b/packages/core-js/modules/esnext.iterator.range.js index 174b28fa65e4..a3b9d0597157 100644 --- a/packages/core-js/modules/esnext.iterator.range.js +++ b/packages/core-js/modules/esnext.iterator.range.js @@ -1,3 +1,4 @@ +// @types: proposals/iterator-range 'use strict'; /* eslint-disable es/no-bigint -- safe */ var $ = require('../internals/export'); diff --git a/packages/core-js/modules/esnext.iterator.to-async.js b/packages/core-js/modules/esnext.iterator.to-async.js index 684047a20dab..0f657b17541e 100644 --- a/packages/core-js/modules/esnext.iterator.to-async.js +++ b/packages/core-js/modules/esnext.iterator.to-async.js @@ -1,3 +1,4 @@ +// @types: proposals/async-iterator-helpers 'use strict'; var $ = require('../internals/export'); var anObject = require('../internals/an-object'); diff --git a/packages/core-js/modules/esnext.iterator.windows.js b/packages/core-js/modules/esnext.iterator.windows.js index 8baea78c06c7..20a708542a01 100644 --- a/packages/core-js/modules/esnext.iterator.windows.js +++ b/packages/core-js/modules/esnext.iterator.windows.js @@ -1,3 +1,4 @@ +// @types: proposals/iterator-chunking 'use strict'; var $ = require('../internals/export'); var anObject = require('../internals/an-object'); diff --git a/packages/core-js/modules/esnext.iterator.zip-keyed.js b/packages/core-js/modules/esnext.iterator.zip-keyed.js index 1590b617fd35..60dd90490612 100644 --- a/packages/core-js/modules/esnext.iterator.zip-keyed.js +++ b/packages/core-js/modules/esnext.iterator.zip-keyed.js @@ -1,3 +1,4 @@ +// @types: proposals/iterator-joint 'use strict'; var $ = require('../internals/export'); var anObject = require('../internals/an-object'); diff --git a/packages/core-js/modules/esnext.iterator.zip.js b/packages/core-js/modules/esnext.iterator.zip.js index a832d49a0b1d..60017608d40b 100644 --- a/packages/core-js/modules/esnext.iterator.zip.js +++ b/packages/core-js/modules/esnext.iterator.zip.js @@ -1,3 +1,4 @@ +// @types: proposals/iterator-joint 'use strict'; var $ = require('../internals/export'); var anObject = require('../internals/an-object'); diff --git a/packages/core-js/modules/esnext.map.from.js b/packages/core-js/modules/esnext.map.from.js index 48e53210b841..b86335d20454 100644 --- a/packages/core-js/modules/esnext.map.from.js +++ b/packages/core-js/modules/esnext.map.from.js @@ -1,3 +1,4 @@ +// @types: proposals/collection-of-from 'use strict'; var $ = require('../internals/export'); var MapHelpers = require('../internals/map-helpers'); diff --git a/packages/core-js/modules/esnext.map.of.js b/packages/core-js/modules/esnext.map.of.js index 4d0a9a1d5bd0..dc8865331eb2 100644 --- a/packages/core-js/modules/esnext.map.of.js +++ b/packages/core-js/modules/esnext.map.of.js @@ -1,3 +1,4 @@ +// @types: proposals/collection-of-from 'use strict'; var $ = require('../internals/export'); var MapHelpers = require('../internals/map-helpers'); diff --git a/packages/core-js/modules/esnext.number.clamp.js b/packages/core-js/modules/esnext.number.clamp.js index c3730d79a5d5..5347af458310 100644 --- a/packages/core-js/modules/esnext.number.clamp.js +++ b/packages/core-js/modules/esnext.number.clamp.js @@ -1,3 +1,4 @@ +// @types: proposals/number-clamp 'use strict'; var $ = require('../internals/export'); var aNumber = require('../internals/a-number'); diff --git a/packages/core-js/modules/esnext.object.keys-length.js b/packages/core-js/modules/esnext.object.keys-length.js index 58157cbff4c0..4d56d262c870 100644 --- a/packages/core-js/modules/esnext.object.keys-length.js +++ b/packages/core-js/modules/esnext.object.keys-length.js @@ -1,3 +1,4 @@ +// @types: proposals/object-keys-length 'use strict'; var $ = require('../internals/export'); var toObject = require('../internals/to-object'); diff --git a/packages/core-js/modules/esnext.promise.all-keyed.js b/packages/core-js/modules/esnext.promise.all-keyed.js index bf4973bf10b0..8e3a6ced3682 100644 --- a/packages/core-js/modules/esnext.promise.all-keyed.js +++ b/packages/core-js/modules/esnext.promise.all-keyed.js @@ -1,3 +1,4 @@ +// @types: proposals/await-dictionary 'use strict'; var $ = require('../internals/export'); var aCallable = require('../internals/a-callable'); diff --git a/packages/core-js/modules/esnext.promise.all-settled-keyed.js b/packages/core-js/modules/esnext.promise.all-settled-keyed.js index f99a5ce007e0..b5275abfba47 100644 --- a/packages/core-js/modules/esnext.promise.all-settled-keyed.js +++ b/packages/core-js/modules/esnext.promise.all-settled-keyed.js @@ -1,3 +1,4 @@ +// @types: proposals/await-dictionary 'use strict'; var $ = require('../internals/export'); var aCallable = require('../internals/a-callable'); diff --git a/packages/core-js/modules/esnext.set.from.js b/packages/core-js/modules/esnext.set.from.js index dc5f5b50c7b5..5bf3cc3b47e7 100644 --- a/packages/core-js/modules/esnext.set.from.js +++ b/packages/core-js/modules/esnext.set.from.js @@ -1,3 +1,4 @@ +// @types: proposals/collection-of-from 'use strict'; var $ = require('../internals/export'); var SetHelpers = require('../internals/set-helpers'); diff --git a/packages/core-js/modules/esnext.set.of.js b/packages/core-js/modules/esnext.set.of.js index 498a9ea416d7..ae7d1aad9bf7 100644 --- a/packages/core-js/modules/esnext.set.of.js +++ b/packages/core-js/modules/esnext.set.of.js @@ -1,3 +1,4 @@ +// @types: proposals/collection-of-from 'use strict'; var $ = require('../internals/export'); var SetHelpers = require('../internals/set-helpers'); diff --git a/packages/core-js/modules/esnext.string.cooked.js b/packages/core-js/modules/esnext.string.cooked.js index 3b4e9511b176..d4ca65e7c5e2 100644 --- a/packages/core-js/modules/esnext.string.cooked.js +++ b/packages/core-js/modules/esnext.string.cooked.js @@ -1,3 +1,4 @@ +// @types: proposals/string-cooked 'use strict'; var $ = require('../internals/export'); var cooked = require('../internals/string-cooked'); diff --git a/packages/core-js/modules/esnext.string.dedent.js b/packages/core-js/modules/esnext.string.dedent.js index 077ef58e050d..f81c53e532e1 100644 --- a/packages/core-js/modules/esnext.string.dedent.js +++ b/packages/core-js/modules/esnext.string.dedent.js @@ -1,3 +1,4 @@ +// @types: proposals/string-dedent 'use strict'; var $ = require('../internals/export'); var uncurryThis = require('../internals/function-uncurry-this'); diff --git a/packages/core-js/modules/esnext.symbol.custom-matcher.js b/packages/core-js/modules/esnext.symbol.custom-matcher.js index 0950470bffc0..2ddc3a914fd4 100644 --- a/packages/core-js/modules/esnext.symbol.custom-matcher.js +++ b/packages/core-js/modules/esnext.symbol.custom-matcher.js @@ -1,3 +1,4 @@ +// @types: proposals/pattern-matching 'use strict'; var defineWellKnownSymbol = require('../internals/well-known-symbol-define'); diff --git a/packages/core-js/modules/esnext.symbol.is-registered-symbol.js b/packages/core-js/modules/esnext.symbol.is-registered-symbol.js index 7b0ff1656ae1..ca91b552cd47 100644 --- a/packages/core-js/modules/esnext.symbol.is-registered-symbol.js +++ b/packages/core-js/modules/esnext.symbol.is-registered-symbol.js @@ -1,3 +1,4 @@ +// @types: proposals/symbol-predicates 'use strict'; var $ = require('../internals/export'); var getBuiltIn = require('../internals/get-built-in'); diff --git a/packages/core-js/modules/esnext.symbol.is-well-known-symbol.js b/packages/core-js/modules/esnext.symbol.is-well-known-symbol.js index e6d2502af89f..bb1058ba5d4c 100644 --- a/packages/core-js/modules/esnext.symbol.is-well-known-symbol.js +++ b/packages/core-js/modules/esnext.symbol.is-well-known-symbol.js @@ -1,4 +1,4 @@ - +// @types: proposals/symbol-predicates 'use strict'; var $ = require('../internals/export'); var shared = require('../internals/shared'); diff --git a/packages/core-js/modules/esnext.symbol.metadata.js b/packages/core-js/modules/esnext.symbol.metadata.js index 182c9363265c..ff23a5ff083c 100644 --- a/packages/core-js/modules/esnext.symbol.metadata.js +++ b/packages/core-js/modules/esnext.symbol.metadata.js @@ -1,3 +1,4 @@ +// @types: proposals/decorator-metadata 'use strict'; var defineWellKnownSymbol = require('../internals/well-known-symbol-define'); diff --git a/packages/core-js/modules/esnext.typed-array.filter-reject.js b/packages/core-js/modules/esnext.typed-array.filter-reject.js index 0842660a06f5..9b66ff4eaf28 100644 --- a/packages/core-js/modules/esnext.typed-array.filter-reject.js +++ b/packages/core-js/modules/esnext.typed-array.filter-reject.js @@ -1,3 +1,4 @@ +// @types: proposals/array-filtering 'use strict'; var exportTypedArrayMethod = require('../internals/export-typed-array-method'); var aTypedArray = require('../internals/a-typed-array'); diff --git a/packages/core-js/modules/esnext.typed-array.unique-by.js b/packages/core-js/modules/esnext.typed-array.unique-by.js index 49dd23c9b2af..c80233f779c8 100644 --- a/packages/core-js/modules/esnext.typed-array.unique-by.js +++ b/packages/core-js/modules/esnext.typed-array.unique-by.js @@ -1,3 +1,4 @@ +// @types: proposals/array-unique 'use strict'; var uncurryThis = require('../internals/function-uncurry-this'); var exportTypedArrayMethod = require('../internals/export-typed-array-method'); diff --git a/packages/core-js/modules/esnext.weak-map.from.js b/packages/core-js/modules/esnext.weak-map.from.js index cf62a6838ac5..a6321f5c6e46 100644 --- a/packages/core-js/modules/esnext.weak-map.from.js +++ b/packages/core-js/modules/esnext.weak-map.from.js @@ -1,3 +1,4 @@ +// @types: proposals/collection-of-from 'use strict'; var $ = require('../internals/export'); var WeakMapHelpers = require('../internals/weak-map-helpers'); diff --git a/packages/core-js/modules/esnext.weak-map.of.js b/packages/core-js/modules/esnext.weak-map.of.js index 636c11246506..94404e093c62 100644 --- a/packages/core-js/modules/esnext.weak-map.of.js +++ b/packages/core-js/modules/esnext.weak-map.of.js @@ -1,3 +1,4 @@ +// @types: proposals/collection-of-from 'use strict'; var $ = require('../internals/export'); var WeakMapHelpers = require('../internals/weak-map-helpers'); diff --git a/packages/core-js/modules/esnext.weak-set.from.js b/packages/core-js/modules/esnext.weak-set.from.js index d8360bdfd72d..7b11a80dedf3 100644 --- a/packages/core-js/modules/esnext.weak-set.from.js +++ b/packages/core-js/modules/esnext.weak-set.from.js @@ -1,3 +1,4 @@ +// @types: proposals/collection-of-from 'use strict'; var $ = require('../internals/export'); var WeakSetHelpers = require('../internals/weak-set-helpers'); diff --git a/packages/core-js/modules/esnext.weak-set.of.js b/packages/core-js/modules/esnext.weak-set.of.js index d7b439dafdd9..4712a392f73e 100644 --- a/packages/core-js/modules/esnext.weak-set.of.js +++ b/packages/core-js/modules/esnext.weak-set.of.js @@ -1,3 +1,4 @@ +// @types: proposals/collection-of-from 'use strict'; var $ = require('../internals/export'); var WeakSetHelpers = require('../internals/weak-set-helpers'); diff --git a/packages/core-js/modules/web.atob.js b/packages/core-js/modules/web.atob.js index 051b1cbfba23..58dcc4e23695 100644 --- a/packages/core-js/modules/web.atob.js +++ b/packages/core-js/modules/web.atob.js @@ -1,3 +1,4 @@ +// @types: web/atob-btoa 'use strict'; var $ = require('../internals/export'); var globalThis = require('../internals/global-this'); diff --git a/packages/core-js/modules/web.btoa.js b/packages/core-js/modules/web.btoa.js index ac75becfdf68..fe6ad99830d1 100644 --- a/packages/core-js/modules/web.btoa.js +++ b/packages/core-js/modules/web.btoa.js @@ -1,3 +1,4 @@ +// @types: web/atob-btoa 'use strict'; var $ = require('../internals/export'); var globalThis = require('../internals/global-this'); diff --git a/packages/core-js/modules/web.clear-immediate.js b/packages/core-js/modules/web.clear-immediate.js index 2d3a0c731a3a..49a95fabe36e 100644 --- a/packages/core-js/modules/web.clear-immediate.js +++ b/packages/core-js/modules/web.clear-immediate.js @@ -1,3 +1,4 @@ +// @types: web/efficient-script-yielding 'use strict'; var $ = require('../internals/export'); var globalThis = require('../internals/global-this'); diff --git a/packages/core-js/modules/web.dom-collections.entries.js b/packages/core-js/modules/web.dom-collections.entries.js index 565ff5aacf3e..1b8212f558ae 100644 --- a/packages/core-js/modules/web.dom-collections.entries.js +++ b/packages/core-js/modules/web.dom-collections.entries.js @@ -1,3 +1,4 @@ +// @types: web/iterable-dom-collections 'use strict'; var domIterablesDefineMethod = require('../internals/dom-iterables-define-method'); diff --git a/packages/core-js/modules/web.dom-collections.for-each.js b/packages/core-js/modules/web.dom-collections.for-each.js index cc1adfc3b0ad..69c6dc716a62 100644 --- a/packages/core-js/modules/web.dom-collections.for-each.js +++ b/packages/core-js/modules/web.dom-collections.for-each.js @@ -1,3 +1,4 @@ +// @types: web/iterable-dom-collections 'use strict'; var domIterablesDefineMethod = require('../internals/dom-iterables-define-method'); diff --git a/packages/core-js/modules/web.dom-collections.iterator.js b/packages/core-js/modules/web.dom-collections.iterator.js index 33b66156981a..4d69270abc6d 100644 --- a/packages/core-js/modules/web.dom-collections.iterator.js +++ b/packages/core-js/modules/web.dom-collections.iterator.js @@ -1,3 +1,4 @@ +// @types: web/iterable-dom-collections 'use strict'; var domIterablesDefineMethod = require('../internals/dom-iterables-define-method'); var wellKnownSymbol = require('../internals/well-known-symbol'); diff --git a/packages/core-js/modules/web.dom-collections.keys.js b/packages/core-js/modules/web.dom-collections.keys.js index 15c1172b0f70..e1dd198f2f5d 100644 --- a/packages/core-js/modules/web.dom-collections.keys.js +++ b/packages/core-js/modules/web.dom-collections.keys.js @@ -1,3 +1,4 @@ +// @types: web/iterable-dom-collections 'use strict'; var domIterablesDefineMethod = require('../internals/dom-iterables-define-method'); diff --git a/packages/core-js/modules/web.dom-collections.values.js b/packages/core-js/modules/web.dom-collections.values.js index e7e2a84c6354..b5ba531ea1a6 100644 --- a/packages/core-js/modules/web.dom-collections.values.js +++ b/packages/core-js/modules/web.dom-collections.values.js @@ -1,3 +1,4 @@ +// @types: web/iterable-dom-collections 'use strict'; var domIterablesDefineMethod = require('../internals/dom-iterables-define-method'); var wellKnownSymbol = require('../internals/well-known-symbol'); diff --git a/packages/core-js/modules/web.dom-exception.constructor.js b/packages/core-js/modules/web.dom-exception.constructor.js index efc29424ae65..13ae452df48e 100644 --- a/packages/core-js/modules/web.dom-exception.constructor.js +++ b/packages/core-js/modules/web.dom-exception.constructor.js @@ -1,3 +1,4 @@ +// @types: web/dom-exception 'use strict'; var $ = require('../internals/export'); var getBuiltIn = require('../internals/get-built-in'); diff --git a/packages/core-js/modules/web.dom-exception.stack.js b/packages/core-js/modules/web.dom-exception.stack.js index d166b6651504..e0dfb69e0ae3 100644 --- a/packages/core-js/modules/web.dom-exception.stack.js +++ b/packages/core-js/modules/web.dom-exception.stack.js @@ -1,3 +1,4 @@ +// @types: web/dom-exception 'use strict'; var $ = require('../internals/export'); var globalThis = require('../internals/global-this'); diff --git a/packages/core-js/modules/web.dom-exception.to-string-tag.js b/packages/core-js/modules/web.dom-exception.to-string-tag.js index f53c6d50db8f..b5a73a3b85a8 100644 --- a/packages/core-js/modules/web.dom-exception.to-string-tag.js +++ b/packages/core-js/modules/web.dom-exception.to-string-tag.js @@ -1,3 +1,4 @@ +// @types: web/dom-exception 'use strict'; var getBuiltIn = require('../internals/get-built-in'); var setToStringTag = require('../internals/set-to-string-tag'); diff --git a/packages/core-js/modules/web.queue-microtask.js b/packages/core-js/modules/web.queue-microtask.js index 3f20cf2a0d59..cca90ee7bd14 100644 --- a/packages/core-js/modules/web.queue-microtask.js +++ b/packages/core-js/modules/web.queue-microtask.js @@ -1,3 +1,4 @@ +// @types: web/queue-microtask 'use strict'; var $ = require('../internals/export'); var globalThis = require('../internals/global-this'); diff --git a/packages/core-js/modules/web.self.js b/packages/core-js/modules/web.self.js index 596d2d46c5fc..04905346b0f0 100644 --- a/packages/core-js/modules/web.self.js +++ b/packages/core-js/modules/web.self.js @@ -1,3 +1,4 @@ +// @types: web/self 'use strict'; var globalThis = require('../internals/global-this'); var defineBuiltInAccessor = require('../internals/define-built-in-accessor'); diff --git a/packages/core-js/modules/web.set-immediate.js b/packages/core-js/modules/web.set-immediate.js index 23dc9fc795fe..62eb5eee48a9 100644 --- a/packages/core-js/modules/web.set-immediate.js +++ b/packages/core-js/modules/web.set-immediate.js @@ -1,3 +1,4 @@ +// @types: web/efficient-script-yielding 'use strict'; var $ = require('../internals/export'); var globalThis = require('../internals/global-this'); diff --git a/packages/core-js/modules/web.structured-clone.js b/packages/core-js/modules/web.structured-clone.js index 8de9f9874b27..cc1dc578821e 100644 --- a/packages/core-js/modules/web.structured-clone.js +++ b/packages/core-js/modules/web.structured-clone.js @@ -1,3 +1,4 @@ +// @types: web/structured-clone 'use strict'; var IS_PURE = require('../internals/is-pure'); var $ = require('../internals/export'); diff --git a/packages/core-js/modules/web.url-search-params.constructor.js b/packages/core-js/modules/web.url-search-params.constructor.js index 0a2fe6fd68b5..aa3ce401cf55 100644 --- a/packages/core-js/modules/web.url-search-params.constructor.js +++ b/packages/core-js/modules/web.url-search-params.constructor.js @@ -1,3 +1,4 @@ +// @no-types: because of a conflict with lib.dom.d.ts 'use strict'; var $ = require('../internals/export'); var safeGetBuiltIn = require('../internals/safe-get-built-in'); diff --git a/packages/core-js/modules/web.url-search-params.delete.js b/packages/core-js/modules/web.url-search-params.delete.js index 3c3ce235d8de..2b68bcebb2d5 100644 --- a/packages/core-js/modules/web.url-search-params.delete.js +++ b/packages/core-js/modules/web.url-search-params.delete.js @@ -1,3 +1,4 @@ +// @no-types: because of a conflict with lib.dom.d.ts 'use strict'; var defineBuiltIn = require('../internals/define-built-in'); var uncurryThis = require('../internals/function-uncurry-this'); diff --git a/packages/core-js/modules/web.url-search-params.has.js b/packages/core-js/modules/web.url-search-params.has.js index 6e6e3f1e9f50..8cb81fe1a98b 100644 --- a/packages/core-js/modules/web.url-search-params.has.js +++ b/packages/core-js/modules/web.url-search-params.has.js @@ -1,3 +1,4 @@ +// @no-types: because of a conflict with lib.dom.d.ts 'use strict'; var defineBuiltIn = require('../internals/define-built-in'); var uncurryThis = require('../internals/function-uncurry-this'); diff --git a/packages/core-js/modules/web.url-search-params.size.js b/packages/core-js/modules/web.url-search-params.size.js index aabd6d5bb567..c675109c64cd 100644 --- a/packages/core-js/modules/web.url-search-params.size.js +++ b/packages/core-js/modules/web.url-search-params.size.js @@ -1,3 +1,4 @@ +// @no-types: because of a conflict with lib.dom.d.ts 'use strict'; var uncurryThis = require('../internals/function-uncurry-this'); var defineBuiltInAccessor = require('../internals/define-built-in-accessor'); diff --git a/packages/core-js/modules/web.url.can-parse.js b/packages/core-js/modules/web.url.can-parse.js index d969ff8d68d1..ac25797b3bad 100644 --- a/packages/core-js/modules/web.url.can-parse.js +++ b/packages/core-js/modules/web.url.can-parse.js @@ -1,3 +1,4 @@ +// @types: web/url 'use strict'; var $ = require('../internals/export'); var getBuiltIn = require('../internals/get-built-in'); diff --git a/packages/core-js/modules/web.url.constructor.js b/packages/core-js/modules/web.url.constructor.js index 49df2c1a9901..ca3402ec528a 100644 --- a/packages/core-js/modules/web.url.constructor.js +++ b/packages/core-js/modules/web.url.constructor.js @@ -1,3 +1,4 @@ +// @types: web/url 'use strict'; var $ = require('../internals/export'); var USE_NATIVE_URL = require('../internals/url-constructor-detection'); diff --git a/packages/core-js/modules/web.url.parse.js b/packages/core-js/modules/web.url.parse.js index f1757df55a9c..63509951beab 100644 --- a/packages/core-js/modules/web.url.parse.js +++ b/packages/core-js/modules/web.url.parse.js @@ -1,3 +1,4 @@ +// @types: web/url 'use strict'; var $ = require('../internals/export'); var getBuiltIn = require('../internals/get-built-in'); diff --git a/packages/core-js/modules/web.url.to-json.js b/packages/core-js/modules/web.url.to-json.js index 879b80c18f17..5ab149725431 100644 --- a/packages/core-js/modules/web.url.to-json.js +++ b/packages/core-js/modules/web.url.to-json.js @@ -1,3 +1,4 @@ +// @types: web/url 'use strict'; var $ = require('../internals/export'); var uncurryThis = require('../internals/function-uncurry-this'); diff --git a/scripts/build-compat/built-in-definitions.mjs b/scripts/build-compat/built-in-definitions.mjs index 7b47a9a57bee..39788c7ccd50 100644 --- a/scripts/build-compat/built-in-definitions.mjs +++ b/scripts/build-compat/built-in-definitions.mjs @@ -2,7 +2,7 @@ import { Globals, StaticProperties, InstanceProperties, -} from '@core-js/compat/src/built-in-definitions.mjs'; +} from '../../packages/core-js-compat/src/built-in-definitions.mjs'; const entries = new Set(Object.keys(await fs.readJson('packages/core-js-compat/entries.json'))); diff --git a/scripts/build-compat/data.mjs b/scripts/build-compat/data.mjs index a37784c0b679..cc946f83039d 100644 --- a/scripts/build-compat/data.mjs +++ b/scripts/build-compat/data.mjs @@ -1,8 +1,8 @@ /* https://github.com/import-js/eslint-plugin-import/issues/2181 */ -import { dataWithIgnored as data, ignored, modules } from '@core-js/compat/src/data.mjs'; -import external from '@core-js/compat/src/external.mjs'; -import mappings from '@core-js/compat/src/mapping.mjs'; -import helpers from '@core-js/compat/helpers.js'; +import { dataWithIgnored as data, ignored, modules } from '../../packages/core-js-compat/src/data.mjs'; +import external from '../../packages/core-js-compat/src/external.mjs'; +import mappings from '../../packages/core-js-compat/src/mapping.mjs'; +import helpers from '../../packages/core-js-compat/helpers.js'; const { compare, semver, sortObjectByKey } = helpers; const { hasOwn } = Object; diff --git a/scripts/build-compat/modules-by-versions.mjs b/scripts/build-compat/modules-by-versions.mjs index d2439671150e..55dba8050621 100644 --- a/scripts/build-compat/modules-by-versions.mjs +++ b/scripts/build-compat/modules-by-versions.mjs @@ -1,5 +1,5 @@ import coerce from 'semver/functions/coerce.js'; -import { modules } from '@core-js/compat/src/data.mjs'; +import { modules } from '../../packages/core-js-compat/src/data.mjs'; const { version } = await fs.readJson('package.json'); const $version = coerce(version); diff --git a/scripts/build-entries/index.mjs b/scripts/build-entries-and-types/build-entries.mjs similarity index 81% rename from scripts/build-entries/index.mjs rename to scripts/build-entries-and-types/build-entries.mjs index ca1353ebc455..676bb7d9849e 100644 --- a/scripts/build-entries/index.mjs +++ b/scripts/build-entries-and-types/build-entries.mjs @@ -1,23 +1,17 @@ -import { getListOfDependencies, sort } from './get-dependencies.mjs'; +import { getModulesMetadata } from './get-dependencies.mjs'; import { features, proposals } from './entries-definitions.mjs'; -import { $proposal, $path } from './templates.mjs'; -import { modules as AllModules } from '@core-js/compat/src/data.mjs'; +import { $proposal, $path, wrapEntryInStrict } from './templates.mjs'; +import { modules as AllModules } from '../../packages/core-js-compat/src/data.mjs'; +import { expandModules, modulesToStage } from './helpers.mjs'; const { mkdir, writeFile, readJson, writeJson } = fs; const { dirname } = path; const { cyan, green } = chalk; -function modulesToStage(x) { - return sort([ - ...StableModules, - ...Object.values(proposals).flatMap(({ stage, modules }) => stage >= x ? modules : []), - ]); -} - const ESModules = AllModules.filter(it => it.startsWith('es.')); const ESWithProposalsModules = AllModules.filter(it => it.startsWith('es')); const StableModules = AllModules.filter(it => it.match(/^(?:es|web)\./)); -const ActualModules = modulesToStage(3); +const ActualModules = modulesToStage(StableModules, 3); const ESSet = new Set(ESModules); const ESWithProposalsSet = new Set(ESWithProposalsModules); @@ -40,13 +34,6 @@ const entriesMap = AllModules.reduce((memo, it) => { return memo; }, {}); -function expandModules(modules, filter) { - if (!Array.isArray(modules)) modules = [modules]; - modules = modules.flatMap(it => it instanceof RegExp ? AllModules.filter(path => it.test(path)) : [it]); - if (filter) modules = modules.filter(it => typeof it != 'string' || filter.has(it)); - return modules; -} - async function buildEntry(entry, options) { let { entryFromNamespace, @@ -73,22 +60,24 @@ async function buildEntry(entry, options) { filter ??= ESWithProposalsSet; } - if (!enforceEntryCreation && !expandModules(modules[0], filter).length) return; + if (!enforceEntryCreation && !expandModules(modules[0], filter, AllModules).length) return; const rawModules = modules; - modules = expandModules(modules, filter); + modules = expandModules(modules, filter, AllModules); const level = entry.split('/').length - 1; - modules = await getListOfDependencies(modules); + const { dependencies, types } = await getModulesMetadata(modules); + modules = dependencies; + if (filter) modules = modules.filter(it => filter.has(it)); - const file = template({ ...options, modules, rawModules, level, entry }); + const tpl = template({ ...options, modules, rawModules, level, entry, types }); const filepath = `./packages/core-js/${ entry }.js`; await mkdir(dirname(filepath), { recursive: true }); - await writeFile(filepath, file); + await writeFile(filepath, wrapEntryInStrict(tpl.entry)); built++; @@ -125,9 +114,9 @@ for (const [name, definition] of Object.entries(proposals)) { } await buildEntry('stage/3', { template: $path, modules: ActualModules, subset: 'es-stage' }); -await buildEntry('stage/2.7', { template: $path, modules: modulesToStage(2.7), subset: 'es-stage' }); -await buildEntry('stage/2', { template: $path, modules: modulesToStage(2), subset: 'es-stage' }); -await buildEntry('stage/1', { template: $path, modules: modulesToStage(1), subset: 'es-stage' }); +await buildEntry('stage/2.7', { template: $path, modules: modulesToStage(StableModules, 2.7), subset: 'es-stage' }); +await buildEntry('stage/2', { template: $path, modules: modulesToStage(StableModules, 2), subset: 'es-stage' }); +await buildEntry('stage/1', { template: $path, modules: modulesToStage(StableModules, 1), subset: 'es-stage' }); await buildEntry('stage/0', { template: $path, modules: AllModules, subset: 'es-stage' }); await buildEntry('es/index', { template: $path, modules: ESModules, subset: 'es' }); diff --git a/scripts/build-entries-and-types/build-types-pure.mjs b/scripts/build-entries-and-types/build-types-pure.mjs new file mode 100644 index 000000000000..4c8a4e7ff314 --- /dev/null +++ b/scripts/build-entries-and-types/build-types-pure.mjs @@ -0,0 +1,180 @@ +const { outputFile, pathExists, readdir, readFile } = fs; + +const NAMESPACE = 'CoreJS'; + +/** + * @param line - A line of code from the type declaration file, potentially containing a @type-options comment + * @return {{ + * noExtends, // Don’t make interfaces extend the original ones + * noPrefix, // Don’t prefix the interface name with the namespace + * noConstructor, // Don’t emit a backing var (constructor) for the interface + * exportBaseConstructor, // When emitting a constructor for an interface, export the original interface as the type of the constructor + * noExport, // Don’t export the interface at all + * noRedefine, // Don’t emit a backing var (constructor) for the interface + * prefixReturnType // Prefix return types with the namespace + * }} + */ +function parseOptions(line) { + const hasOptions = line.includes('@type-options'); + const optionsStr = hasOptions ? line.match(/@type-options:\s+(?[A-Za-z][\s\w,-]+)$/)?.groups?.options : ''; + return { + noExtends: hasOptions && optionsStr.includes('no-extends'), + noPrefix: hasOptions && optionsStr.includes('no-prefix'), + noConstructor: hasOptions && optionsStr.includes('no-constructor'), + exportBaseConstructor: hasOptions && optionsStr.includes('export-base-constructor'), + noExport: hasOptions && optionsStr.includes('no-export'), + noRedefine: hasOptions && optionsStr.includes('no-redefine'), + prefixReturnType: hasOptions && optionsStr.includes('prefix-return-type'), + }; +} + +function processLines(lines) { + const prefixed = []; + let noExport = false; + return lines + .flatMap(line => { + const options = parseOptions(line); + + if (noExport && /^[^{]*\}/.test(line)) { + noExport = false; + return []; + } + if (noExport) return []; + if (options.noExport) { + if (/^[^{]*$/.test(line) || /\{[^{}]*\}/.test(line)) return []; + noExport = true; + return []; + } + + if (line.includes('export {')) return []; + + // Process interfaces that either don’t need to extend other interfaces or have already been extended + if (/^\s*(?:declare\s+)?interface\s+\w+\s*extends/.test(line) + || options.noExtends && /^\s*(?:declare\s+)?interface\s+\w+(?:<[^>]+>)?\s*\{/.test(line)) { + if (!options.noPrefix) { + const m = line.match(/interface\s+(?\w+)/); + if (m?.groups) { + prefixed.push(m.groups.name); + } + } + return line.replace(/^(?\s*)(?:declare\s+)?interface\s+(?[\s\w,<=>]+)/, + `$export interface ${ !options.noPrefix ? NAMESPACE : '' }$`); + } + + // Process interfaces: prefix name, emit backing var (constructor) and make it extend original + if (!options.noExtends && /^\s*(?:declare\s+)?interface\s+\w+/.test(line)) { + const match = line.match(/^(?\s*)(?:declare\s+)?interface\s+(?\w+)(?<[^>]+>)?/); + const iIndent = match?.groups?.indent ?? ''; + const iName = match?.groups?.name ?? ''; + const iExtend = match?.groups?.extend ?? ''; + if (!options.noPrefix && iName !== '') { + prefixed.push(iName); + } + const genericsForExtends = iExtend.replace(/\sextends\s[^,>]+/g, '').replace(/\s?=\s?\w+/g, ''); + const entityName = `${ !options.noPrefix ? NAMESPACE : '' }${ iName }`; + const isConstructor = iName.includes('Constructor'); + let constructorDeclaration; + if (isConstructor) { + constructorDeclaration = !options.noRedefine ? + `${ iIndent }var ${ entityName.replace('Constructor', '') }: ${ entityName };\n` : ''; + } else { + constructorDeclaration = !options.noRedefine ? `${ iIndent }var ${ entityName }: ${ + options.exportBaseConstructor ? iName : entityName }${ options.noConstructor ? '' : 'Constructor' };\n` : ''; + } + return `${ constructorDeclaration }${ iIndent }export interface ${ + entityName }${ iExtend } extends ${ iName }${ genericsForExtends } {\n`; + } + + // Process function + if (/^\s*(?:declare\s+)?function/.test(line)) { + return line.replace(/^(?\s*)(?:declare\s+)?function\s+(?\w+)/, + `$export function ${ !options.noPrefix ? NAMESPACE : '' }$`); + } + + if (options.prefixReturnType) { + return line.replace(/^(?.*):\s(?[a-z_]\w*)(?<[^;]+);/i, + `$: ${ NAMESPACE }.${ NAMESPACE }$$;`); + } + + // Replace prefixed types in the entire file + if (/:\s*\w/.test(line)) { + prefixed.toSorted((a, b) => b.length - a.length).forEach(item => { + const reg = new RegExp(`(?:) ${ item }(?[,;<)])`, 'g'); + line = line.replace(reg, `$ ${ NAMESPACE }${ item }$`); + }); + } + + // Handle vars: prefix variable name, keep original type + if (/^\s*(?:declare\s+)?var/.test(line)) { + const m = line.match(/^(?\s*)(?:declare\s+)?var\s+(?\w+):\s+(?\w+)/); + return `${ m?.groups?.indent ?? '' }var ${ !options.noPrefix ? NAMESPACE : '' }${ m?.groups?.name ?? '' }: ${ m?.groups?.type };\n`; + } + return line; + }); +} + +function wrapInNamespace(content) { + const lines = content.split('\n'); + const headerLines = []; + + let i = 0; + // Process the header section up to the start of the main content + for (; i < lines.length; i++) { + const line = lines[i]; + + // Update reference paths and add to header + if (/\/\/\/\s* { + if (line.trim() || res.at(-1)?.trim()) res.push(line); + return res; + }, []) + .flatMap(line => line.split('\n')) + .map(line => line ? ` ${ line }` : '') + .join('\n'); + + return `${ headerLines.length ? `${ headerLines.join('\n') }\n` : '' }declare namespace ${ NAMESPACE } {\n${ namespaceBody }\n}\n`; +} + +export async function preparePureTypes(typesPath, initialPath) { + const entries = await readdir(typesPath, { withFileTypes: true }); + for (const entry of entries) { + if (['pure', 'core-js-types.d.ts'].includes(entry.name)) continue; + + if (entry.isDirectory()) { + await preparePureTypes(path.join(typesPath, entry.name), initialPath); + } else { + const typePath = path.join(typesPath, entry.name); + const resultFilePath = typePath.replace(initialPath, `${ initialPath }/pure/`); + + if (await pathExists(resultFilePath)) continue; + + const content = await readFile(typePath, 'utf8'); + + const adjustedContent = content.replace( + /(?\/\/\/\s*[^"]+)(?"\s*\/>)/g, + (...args) => { + const { open, path, close } = args.at(-1); + return `${ open }../${ path }${ close }`; + }, + ); + const result = content.includes('declare namespace') ? adjustedContent : wrapInNamespace(content); + + await outputFile(resultFilePath, result); + } + } +} diff --git a/scripts/build-entries-and-types/build-types.mjs b/scripts/build-entries-and-types/build-types.mjs new file mode 100644 index 000000000000..673c322f14ca --- /dev/null +++ b/scripts/build-entries-and-types/build-types.mjs @@ -0,0 +1,327 @@ +import { features, proposals } from './entries-definitions.mjs'; +import { $functionWithCustomType, $path, $proposal, $typeDummy } from './templates.mjs'; +import { modules as AllModules } from '../../packages/core-js-compat/src/data.mjs'; +import { getModulesMetadata } from './get-dependencies.mjs'; +import { expandModules, modulesToStage } from './helpers.mjs'; +import { preparePureTypes } from './build-types-pure.mjs'; + +const { copy, outputFile, pathExists, readdir, readFile, readJson, remove, writeJson } = fs; +const { green } = chalk; + +const BUILD_DIR = 'packages/core-js-types/'; +const PACKAGE_JSON_DIR = 'packages/core-js-types/'; +const PACKAGE_NAME = 'core-js/'; +const PACKAGE_NAME_PURE = '@core-js/pure/'; +const PACKAGE_TEMPLATE = 'packages/core-js-types/package.tpl.json'; +const SRC_DIR = 'packages/core-js-types/src/'; +const SRC_BASE = 'base'; +const TS_VERSION_BREAKPOINTS = [5.6]; +const TYPE_PREFIX = 'CoreJS.CoreJS'; + +let imports; +let outputFiles = {}; + +function setDefaultNamespacesForImports() { + imports = { + es: new Set(), + stable: new Set(), + actual: new Set(), + full: new Set(), + pure: new Set(), + index: new Set(), + configurator: new Set(), + }; +} + +function addType(tsVersion, subset, template, options) { + const exportGlobalType = options.globalType ?? true; + if (!exportGlobalType && subset !== 'pure') { + return; + } + const filePath = buildFilePath(tsVersion, subset); + if (!outputFiles[filePath]) outputFiles[filePath] = ''; + const entryWithTypes = template(options); + outputFiles[filePath] += `${ entryWithTypes.types }${ entryWithTypes.types ? '\n' : '' }`; +} + +function addEntryTypes(tsVersion, template, options) { + addType(tsVersion, 'index', template, { ...options, packageName: PACKAGE_NAME }); + if (!options.noPure) { + addType(tsVersion, 'pure', template, { ...options, packageName: PACKAGE_NAME_PURE, prefix: TYPE_PREFIX }); + } + if (options.exportForSubset) { + addType(tsVersion, options.subset, template, { ...options, packageName: PACKAGE_NAME }); + } +} + +async function buildType(entry, options) { + let { + entryFromNamespace, + subset = entryFromNamespace ?? 'full', + typeDummy = false, + globalType = true, + noPure = false, + template, templateStable, templateActual, templateFull, filter, modules, enforceEntryCreation, + customType, tsVersion, proposal, types, ownEntryPoint, + } = options; + + let typesFilter = null; + switch (subset) { + case 'es': + filter ??= ESSet; + typesFilter = 'web/'; + break; + case 'stable': + filter ??= StableSet; + template = templateStable ?? template; + break; + case 'actual': + filter ??= ActualSet; + template = templateActual ?? templateStable ?? template; + break; + case 'full': + template = templateFull ?? templateActual ?? templateStable ?? template; + break; + } + + if (typeDummy) { + template = $typeDummy; + } + + const level = entry.split('/').length - 1; + + if (!types) { + types = []; + if (!customType) { + if (!enforceEntryCreation && !expandModules(modules[0], filter, AllModules).length) return; + modules = expandModules(modules, filter, AllModules); + const { types: typePaths } = await getModulesMetadata(modules); + types = typePaths; + } + } + + if (typesFilter) { + types = types.filter(it => !it.includes(typesFilter)); + } + + types.forEach(type => { + if (globalType) { + imports.index.add(type); + imports[subset].add(type); + } + if (!noPure) imports.pure.add(path.join('pure', type)); + }); + + if (customType) { + if (globalType) { + imports.index.add(customType); + imports[subset].add(customType); + } + if (!noPure) imports.pure.add(path.join('pure', customType)); + } + options = { ...options, modules, level, entry, types, subset, noPure }; + + addEntryTypes(tsVersion, template, options); + if (!entry.endsWith('/')) { // add alias with .js ending + addEntryTypes(tsVersion, template, { ...options, entry: `${ entry }.js` }); + } + if (entry.endsWith('/index')) { // add alias to namespace without index + addEntryTypes(tsVersion, template, { ...options, entry: entry.replace(/\/index$/, '') }); + } + + if (proposal || ownEntryPoint) { + const ownFilePath = buildFilePath(tsVersion, entry); + if (!outputFiles[ownFilePath]) outputFiles[ownFilePath] = ''; + const ownImports = buildImports(types, 1); + outputFiles[ownFilePath] = `${ ownImports }\n`; + } +} + +const ESModules = AllModules.filter(it => it.startsWith('es.')); +const StableModules = AllModules.filter(it => it.match(/^(?:es|web)\./)); +const ActualModules = modulesToStage(StableModules, 3); + +const ESSet = new Set(ESModules); +const StableSet = new Set(StableModules); +const ActualSet = new Set(ActualModules); + +function buildFilePath(tsVersion, subset) { + return path.join(BUILD_DIR, tsVersion.toString(), `${ subset }.d.ts`); +} + +function buildImports(importsList, level = 0) { + return Array.from(importsList, it => `/// `).join('\n'); +} + +async function prependImports(version) { + for (const subset of Object.keys(imports)) { + const filePath = buildFilePath(version, subset); + const importLines = buildImports(imports[subset]); + outputFiles[filePath] = `${ importLines }\n${ outputFiles[filePath] ?? '' }`; + } +} + +async function fillCustomImportsForPure(typesPath, initialPath) { + const entries = await readdir(typesPath, { withFileTypes: true }); + for (const entry of entries) { + if (entry.isDirectory()) { + await fillCustomImportsForPure(path.join(typesPath, entry.name), initialPath); + } else { + const filePath = path.join(typesPath, entry.name); + const fileContent = (await readFile(filePath)).toString(); + if (fileContent.startsWith('// empty')) continue; + imports.pure.add(filePath.replace(`${ initialPath }/`, '').replace('.d.ts', '')); + } + } +} + +async function buildAdditionalEntries(dir, tsVersion) { + const dirPath = path.join(BUILD_DIR, tsVersion, 'types', dir); + const entries = await readdir(dirPath, { withFileTypes: true }); + const result = {}; + for (const entry of entries) { + if (entry.isDirectory()) { + continue; + } + const entryName = entry.name.replace('.d.ts', ''); + const entryPath = path.join(dir, entryName); + result[entryName] = { + template: () => ({ types: '' }), + ownEntryPoint: true, + modules: [], + tsVersion, + types: [entryPath], + }; + } + + return result; +} + +async function buildTypesForTSVersion(tsVersion) { + outputFiles = {}; + tsVersion = `ts${ tsVersion.toString().replace('.', '-') }`; + + const bundlePath = path.join(BUILD_DIR, tsVersion); + if (await pathExists(bundlePath)) await remove(bundlePath); + await copy(path.join(SRC_DIR, SRC_BASE), path.join(BUILD_DIR, tsVersion, 'types')); + + const srcPath = path.join(SRC_DIR, tsVersion); + const distTypesPath = path.join(bundlePath, 'types'); + if (await pathExists(srcPath)) { + await copy(srcPath, distTypesPath); + } + + const web = await buildAdditionalEntries('web', tsVersion); + const annexB = await buildAdditionalEntries('annex-b', tsVersion); + + await fillCustomImportsForPure(path.join(bundlePath, 'types', 'pure'), distTypesPath); + await preparePureTypes(bundlePath, distTypesPath); + + for (const [entry, definition] of Object.entries(features)) { + await buildType(`es/${ entry }`, { ...definition, entryFromNamespace: 'es', tsVersion }); + await buildType(`stable/${ entry }`, { ...definition, entryFromNamespace: 'stable', tsVersion }); + await buildType(`actual/${ entry }`, { ...definition, entryFromNamespace: 'actual', tsVersion }); + await buildType(`full/${ entry }`, { ...definition, entryFromNamespace: 'full', tsVersion }); + } + + for (const [name, definition] of Object.entries(proposals)) { + await buildType(`proposals/${ name }`, { ...definition, template: $proposal, tsVersion, proposal: true }); + } + for (const [name, definition] of Object.entries(web)) { + await buildType(`web/${ name }`, definition); + } + for (const [name, definition] of Object.entries(annexB)) { + await buildType(`annex-b/${ name }`, definition); + } + + await buildType('es/index', { template: $path, modules: ESModules, subset: 'es', tsVersion }); + await buildType('stable/index', { template: $path, modules: StableModules, subset: 'stable', tsVersion }); + await buildType('actual/index', { template: $path, modules: ActualModules, subset: 'actual', tsVersion }); + await buildType('full/index', { template: $path, modules: AllModules, tsVersion }); + await buildType('index', { template: $path, modules: ActualModules, subset: 'actual', tsVersion }); + + await buildType('configurator', { + customType: 'configurator-custom', + entryFromNamespace: 'configurator', + template: $functionWithCustomType, + modules: ['configurator'], + name: 'configurator', + tsVersion, + exportForSubset: true, + noPure: true, + }); + + await prependImports(tsVersion); + await saveOutputFiles(); +} + +async function buildPackageJson(breakpoints, namespaces) { + breakpoints = breakpoints.sort().reverse(); + const defaultBreakpoint = Math.max(...breakpoints).toString().replace('.', '-'); + + const packageJson = await readJson(PACKAGE_TEMPLATE); + packageJson.typesVersions = {}; + breakpoints.forEach(breakpoint => { + packageJson.typesVersions[`>=${ breakpoint }`] = { + '*': [`./ts${ breakpoint.toString().replace('.', '-') }/*`], + }; + }); + packageJson.typesVersions['*'] = { '*': [`./ts${ defaultBreakpoint }/*`] }; + + packageJson.exports = {}; + Object.entries(namespaces).forEach(([namespace, options]) => { + const namespaceKey = namespace !== 'index' ? `./${ namespace }${ options.isDir ? '/*' : '' }` : '.'; + packageJson.exports[namespaceKey] = {}; + breakpoints.forEach((breakpoint, index) => { + const isLast = index === breakpoints.length - 1; + const breakpointString = `ts${ breakpoint.toString().replace('.', '-') }`; + packageJson.exports[namespaceKey][`types${ isLast ? '' : `@>=${ breakpoint }` }`] = `./${ breakpointString }/${ namespace }${ options.isDir ? '/*' : '' }.d.ts`; + }); + packageJson.exports[namespaceKey].default = `./ts${ defaultBreakpoint }/${ namespace }${ options.isDir ? '/*' : '' }.d.ts`; + }); + const exportsKeys = Object.keys(packageJson.exports).sort(); + const exports = {}; + exportsKeys.forEach(key => { + exports[key] = packageJson.exports[key]; + }); + packageJson.exports = exports; + + await writeJson(path.join(PACKAGE_JSON_DIR, 'package.json'), packageJson, { spaces: 2 }); +} + +async function clearPackage() { + const entries = await readdir(BUILD_DIR, { withFileTypes: true }); + for (const entry of entries) { + if (/^ts\d{1,3}-\d{1,3}$/.test(entry.name)) { + await remove(path.join(BUILD_DIR, entry.name)); + } + } +} + +async function saveOutputFiles() { + const filePaths = Object.keys(outputFiles); + for (const filePath of filePaths) { + await outputFile(filePath, outputFiles[filePath], { flag: 'w' }); + } +} + +await clearPackage(); + +for (const version of TS_VERSION_BREAKPOINTS) { + setDefaultNamespacesForImports(); + await buildTypesForTSVersion(version); +} + +const namespaces = { + es: { isDir: false }, + stable: { isDir: false }, + actual: { isDir: false }, + full: { isDir: false }, + pure: { isDir: false }, + proposals: { isDir: true }, + index: { isDir: false }, + configurator: { isDir: false }, +}; +await buildPackageJson(TS_VERSION_BREAKPOINTS, namespaces); + +echo(green('types successfully built')); diff --git a/scripts/build-entries/entries-definitions.mjs b/scripts/build-entries-and-types/entries-definitions.mjs similarity index 98% rename from scripts/build-entries/entries-definitions.mjs rename to scripts/build-entries-and-types/entries-definitions.mjs index 6bb1a55d0e29..ea7d821729a1 100644 --- a/scripts/build-entries/entries-definitions.mjs +++ b/scripts/build-entries-and-types/entries-definitions.mjs @@ -1,6 +1,7 @@ import { $uncurried, $uncurriedIterator, + $uncurriedWithCustomType, $prototype, $prototypeIterator, $static, @@ -319,9 +320,11 @@ export const features = { }, 'array/flat-map': { modules: ['es.array.flat-map'], - template: $uncurried, + template: $uncurriedWithCustomType, namespace: 'Array', name: 'flatMap', + customType: 'proposals/array-flat-map-custom', + genericsCount: 3, }, 'array/prototype/flat-map': { modules: ['es.array.flat-map'], @@ -374,12 +377,12 @@ export const features = { 'array/iterator': { modules: ['es.array.iterator'], template: $uncurriedIterator, - source: '[]', + namespace: 'Array', }, 'array/prototype/iterator': { modules: ['es.array.iterator'], template: $prototypeIterator, - source: '[]', + namespace: 'Array', }, 'array/join': { modules: ['es.array.join'], @@ -545,9 +548,11 @@ export const features = { }, 'array/to-spliced': { modules: ['es.array.to-spliced'], - template: $uncurried, + template: $uncurriedWithCustomType, namespace: 'Array', name: 'toSpliced', + customType: 'proposals/change-array-by-copy-custom', + genericsCount: 1, }, 'array/prototype/to-spliced': { modules: ['es.array.to-spliced'], @@ -711,9 +716,11 @@ export const features = { }, 'async-iterator/flat-map': { modules: ['esnext.async-iterator.flat-map'], - template: $uncurried, + template: $uncurriedWithCustomType, namespace: 'AsyncIterator', name: 'flatMap', + customType: 'proposals/async-iterator-helpers-custom', + genericsCount: 2, }, 'async-iterator/prototype/flat-map': { modules: ['esnext.async-iterator.flat-map'], @@ -735,9 +742,11 @@ export const features = { }, 'async-iterator/map': { modules: ['esnext.async-iterator.map'], - template: $uncurried, + template: $uncurriedWithCustomType, namespace: 'AsyncIterator', name: 'map', + customType: 'proposals/async-iterator-helpers-custom', + genericsCount: 2, }, 'async-iterator/prototype/map': { modules: ['esnext.async-iterator.map'], @@ -747,9 +756,11 @@ export const features = { }, 'async-iterator/reduce': { modules: ['esnext.async-iterator.reduce'], - template: $uncurried, + template: $uncurriedWithCustomType, namespace: 'AsyncIterator', name: 'reduce', + customType: 'proposals/async-iterator-helpers-custom', + genericsCount: 2, }, 'async-iterator/prototype/reduce': { modules: ['esnext.async-iterator.reduce'], @@ -1284,9 +1295,11 @@ export const features = { }, 'iterator/flat-map': { modules: ['es.iterator.flat-map'], - template: $uncurried, + template: $uncurriedWithCustomType, namespace: 'Iterator', name: 'flatMap', + customType: 'proposals/iterator-helpers-custom', + genericsCount: 2, }, 'iterator/prototype/flat-map': { modules: ['es.iterator.flat-map'], @@ -1320,9 +1333,11 @@ export const features = { }, 'iterator/map': { modules: ['es.iterator.map'], - template: $uncurried, + template: $uncurriedWithCustomType, namespace: 'Iterator', name: 'map', + customType: 'proposals/iterator-helpers-custom', + genericsCount: 2, }, 'iterator/prototype/map': { modules: ['es.iterator.map'], @@ -1332,9 +1347,11 @@ export const features = { }, 'iterator/reduce': { modules: ['es.iterator.reduce'], - template: $uncurried, + template: $uncurriedWithCustomType, namespace: 'Iterator', name: 'reduce', + customType: 'proposals/iterator-helpers-custom', + genericsCount: 2, }, 'iterator/prototype/reduce': { modules: ['es.iterator.reduce'], @@ -2241,9 +2258,11 @@ export const features = { }, 'set/symmetric-difference': { modules: ['es.set.symmetric-difference'], - template: $uncurried, + template: $uncurriedWithCustomType, namespace: 'Set', name: 'symmetricDifference', + customType: 'proposals/set-methods-custom', + genericsCount: 2, }, 'set/prototype/symmetric-difference': { modules: ['es.set.symmetric-difference'], @@ -2253,9 +2272,11 @@ export const features = { }, 'set/union': { modules: ['es.set.union'], - template: $uncurried, + template: $uncurriedWithCustomType, namespace: 'Set', name: 'union', + customType: 'proposals/set-methods-custom', + genericsCount: 2, }, 'set/prototype/union': { modules: ['es.set.union'], @@ -2445,12 +2466,12 @@ export const features = { 'string/iterator': { modules: ['es.string.iterator'], template: $uncurriedIterator, - source: "''", + namespace: 'String', }, 'string/prototype/iterator': { modules: ['es.string.iterator'], template: $prototypeIterator, - source: "''", + namespace: 'String', }, 'string/link': { modules: ['es.string.link'], @@ -3058,37 +3079,44 @@ export const features = { modules: [/^web\.url(?:-search-params)?\./], template: $namespace, name: 'URL', + globalType: false, }, 'url/constructor': { modules: ['web.url.constructor', 'web.url.to-json', /^web\.url-search-params\./], template: $namespace, name: 'URL', + globalType: false, }, 'url/can-parse': { modules: ['web.url.can-parse'], template: $static, namespace: 'URL', name: 'canParse', + globalType: false, }, 'url/parse': { modules: ['web.url.parse'], template: $static, namespace: 'URL', name: 'parse', + globalType: false, }, 'url/to-json': { modules: ['web.url.to-json'], template: $justImport, + globalType: false, }, 'url-search-params/index': { modules: [/^web\.url-search-params\./], template: $namespace, name: 'URLSearchParams', + globalType: false, }, 'url-search-params/constructor': { modules: [/^web\.url-search-params\./], template: $namespace, name: 'URLSearchParams', + globalType: false, }, 'weak-map/index': { modules: [/^(?:es|esnext)\.weak-map\./], diff --git a/scripts/build-entries/get-dependencies.mjs b/scripts/build-entries-and-types/get-dependencies.mjs similarity index 52% rename from scripts/build-entries/get-dependencies.mjs rename to scripts/build-entries-and-types/get-dependencies.mjs index ad02c0383ee3..62b9be08a7c6 100644 --- a/scripts/build-entries/get-dependencies.mjs +++ b/scripts/build-entries-and-types/get-dependencies.mjs @@ -1,12 +1,13 @@ import konan from 'konan'; -import { modules } from '@core-js/compat/src/data.mjs'; +import { modules } from '../../packages/core-js-compat/src/data.mjs'; const { cyan, red } = chalk; const allModulesSet = new Set(modules); const MODULE_PATH = /\/(?(?:internals|modules)\/[\d\-.a-z]+)$/; -const DIRECTIVE = /^ *\/\/ @dependency: (?(?:es|esnext|web)\.[\d\-.a-z]+)$/gm; +const DEPENDENCY_DIRECTIVE = /^ *\/\/ @dependency: (?(?:es|esnext|web)\.[\d\-.a-z]+)$/gm; +const TYPES_DIRECTIVE = /^ *\/\/ @types: (?[\d\-./a-z]+)$/gm; const cache = new Map(); @@ -28,27 +29,42 @@ function normalizeModulePath(unnormalizedPath) { return path.endsWith('.js') ? path.slice(0, -3) : path; } -async function getSetOfAllDependenciesForModule(path, stack = new Set()) { +async function getModuleMetadata(path, stack = new Set()) { if (cache.has(path)) return cache.get(path); if (stack.has(path)) throw new Error(red(`Circular dependency: ${ cyan(path) }`)); stack.add(path); const module = String(await fs.readFile(`./packages/core-js/${ path }.js`)); const directDependencies = konan(module).strings.map(normalizeModulePath); - const declaredDependencies = [...module.matchAll(DIRECTIVE)].map(it => normalizeModulePath(it.groups.module)); + const declaredDependencies = [...module.matchAll(DEPENDENCY_DIRECTIVE)].map(it => normalizeModulePath(it.groups.module)); const dependencies = unique([...directDependencies, ...declaredDependencies]); - const result = new Set([path]); + const paths = new Set([path]); + const types = new Set(); + for (const it of module.matchAll(TYPES_DIRECTIVE)) { + types.add(it.groups.types); + } for (const dependency of dependencies) { - const dependenciesOfDependency = await getSetOfAllDependenciesForModule(dependency, new Set(stack)); - dependenciesOfDependency.forEach(it => result.add(it)); + const moduleMetadata = await getModuleMetadata(dependency, new Set(stack)); + moduleMetadata.dependencies.forEach(it => paths.add(it)); + moduleMetadata.types.forEach(it => types.add(it)); } + const result = { + dependencies: paths, + types, + }; cache.set(path, result); return result; } -export async function getListOfDependencies(paths) { +export async function getModulesMetadata(paths) { const dependencies = []; + const types = []; for (const module of paths.map(normalizeModulePath)) { - dependencies.push(...await getSetOfAllDependenciesForModule(module)); + const result = await getModuleMetadata(module); + dependencies.push(...result.dependencies); + types.push(...result.types); } - return sort(unique(dependencies).filter(it => it.startsWith('modules/')).map(it => it.slice(8))); + return { + dependencies: sort(unique(dependencies).filter(it => it.startsWith('modules/')).map(it => it.slice(8))), + types: unique(types), + }; } diff --git a/scripts/build-entries-and-types/helpers.mjs b/scripts/build-entries-and-types/helpers.mjs new file mode 100644 index 000000000000..a51cfe999a1f --- /dev/null +++ b/scripts/build-entries-and-types/helpers.mjs @@ -0,0 +1,16 @@ +import { sort } from './get-dependencies.mjs'; +import { proposals } from './entries-definitions.mjs'; + +export function modulesToStage(stableModules, x) { + return sort([ + ...stableModules, + ...Object.values(proposals).flatMap(({ stage, modules }) => stage >= x ? modules : []), + ]); +} + +export function expandModules(modules, filter, allModules) { + if (!Array.isArray(modules)) modules = [modules]; + modules = modules.flatMap(it => it instanceof RegExp ? allModules.filter(path => it.test(path)) : [it]); + if (filter) modules = modules.filter(it => typeof it != 'string' || filter.has(it)); + return modules; +} diff --git a/scripts/build-entries/package-lock.json b/scripts/build-entries-and-types/package-lock.json similarity index 87% rename from scripts/build-entries/package-lock.json rename to scripts/build-entries-and-types/package-lock.json index 91087c985c8a..7cfa1505454c 100644 --- a/scripts/build-entries/package-lock.json +++ b/scripts/build-entries-and-types/package-lock.json @@ -1,10 +1,10 @@ { - "name": "scripts/build-entries", + "name": "scripts/build-entries-and-types", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "scripts/build-entries", + "name": "scripts/build-entries-and-types", "devDependencies": { "dedent": "^1.7.1" } diff --git a/scripts/build-entries/package.json b/scripts/build-entries-and-types/package.json similarity index 54% rename from scripts/build-entries/package.json rename to scripts/build-entries-and-types/package.json index 41aedd403575..6bea28f423c2 100644 --- a/scripts/build-entries/package.json +++ b/scripts/build-entries-and-types/package.json @@ -1,5 +1,5 @@ { - "name": "scripts/build-entries", + "name": "scripts/build-entries-and-types", "devDependencies": { "dedent": "^1.7.1" } diff --git a/scripts/build-entries-and-types/templates.mjs b/scripts/build-entries-and-types/templates.mjs new file mode 100644 index 000000000000..15b481b4a7e4 --- /dev/null +++ b/scripts/build-entries-and-types/templates.mjs @@ -0,0 +1,506 @@ +import { basename } from 'node:path'; +import dedent from 'dedent'; + +const importInternal = (module, level) => `require('${ level ? '../'.repeat(level) : './' }internals/${ module }');`; + +const importModule = (module, level) => `require('${ level ? '../'.repeat(level) : './' }modules/${ module }');`; + +const importModules = ({ modules, level }) => modules.map(module => importModule(module, level)).join('\n'); + +const buildCoreJSTypeName = (namespace, name) => `CoreJS.${ namespace }${ name.charAt(0).toUpperCase() + name.slice(1) }`; + +const buildSelfForNamespace = (namespace, prefix) => `${ prefix && missingNamespacesInES6.includes(namespace) ? prefix : '' }${ namespace }${ getCommonGenericsForNamespace(namespace) }`; + +const buildModulePath = ({ entry, packageName }) => `${ packageName }${ entry }`; + +function isAllowedFunctionName(name) { + try { + // eslint-disable-next-line no-new-func -- safe + Function(`function ${ name }() { /* empty */ }`); + return true; + } catch { + return false; + } +} + +const namespacesWithTwoGeneric = [ + 'Map', + 'ReadonlyMap', + 'WeakMap', +]; + +const namespacesWithOneGeneric = [ + 'Array', + 'ReadonlyArray', + 'Set', + 'ReadonlySet', + 'WeakSet', + 'Promise', + 'Iterator', + 'AsyncIterator', +]; + +const missingNamespacesInES6 = [ + 'AsyncIterator', +]; + +function getGenericsForNamespace(namespace) { + if (namespace === 'WeakMap') { + return ''; + } + if (namespace === 'WeakSet') { + return ''; + } + if (namespacesWithTwoGeneric.includes(namespace)) { + return ''; + } + if (namespacesWithOneGeneric.includes(namespace)) { + return ''; + } + return ''; +} + +function getAnyGenericsForNamespace(namespace) { + if (namespacesWithTwoGeneric.includes(namespace)) { + return ''; + } + if (namespacesWithOneGeneric.includes(namespace)) { + return ''; + } + return ''; +} + +function getCommonGenericsForNamespace(namespace) { + if (namespacesWithTwoGeneric.includes(namespace)) { + return ''; + } + if (namespacesWithOneGeneric.includes(namespace)) { + return ''; + } + return ''; +} + +function getCustomGenerics(count) { + const names = ['T', 'R', 'U']; + return `<${ names.slice(0, count).join(', ') }>`; +} + +export const wrapEntryInStrict = template => `'use strict';\n${ template }\n`; + +export const $justImport = p => ({ + entry: dedent` + ${ importModules(p) } + `, + types: '', +}); + +export const $prototype = p => ({ + entry: dedent` + ${ importModules(p) } + + var getBuiltInPrototypeMethod = ${ importInternal('get-built-in-prototype-method', p.level) } + + module.exports = getBuiltInPrototypeMethod('${ p.namespace }', '${ p.name }'); + `, + types: dedent` + declare module '${ buildModulePath(p) }' { + type methodType${ getGenericsForNamespace(p.namespace) } = ${ p.prefix ?? '' }${ p.namespace }${ getCommonGenericsForNamespace(p.namespace) }['${ p.name }']; + const method: methodType${ getAnyGenericsForNamespace(p.namespace) }; + export = method; + } + `, +}); + +export const $prototypeIterator = p => ({ + entry: dedent` + ${ importModules(p) } + + var getIteratorMethod = ${ importInternal('get-iterator-method', p.level) } + + module.exports = getIteratorMethod(${ p.namespace }()); + `, + types: dedent` + declare module '${ buildModulePath(p) }' { + const method: typeof ${ p.prefix ?? '' }${ p.namespace }.prototype[typeof Symbol.iterator]; + export = method; + } + `, +}); + +export const $uncurried = p => ({ + entry: dedent` + ${ importModules(p) } + + var entryUnbind = ${ importInternal('entry-unbind', p.level) } + + module.exports = entryUnbind('${ p.namespace }', '${ p.name }'); + `, + types: dedent` + declare module '${ buildModulePath(p) }' { + type method${ getGenericsForNamespace(p.namespace) } = ${ p.prefix ?? '' }${ p.namespace }${ getCommonGenericsForNamespace(p.namespace) }['${ p.name }']; + const resultMethod: ${ getGenericsForNamespace(p.namespace) }(self: ${ buildSelfForNamespace(p.namespace, p.prefix) }, ...args: Parameters) => ReturnType; + export = resultMethod; + } + `, +}); + +export const $uncurriedWithCustomType = p => ({ + entry: dedent` + ${ importModules(p) } + + var entryUnbind = ${ importInternal('entry-unbind', p.level) } + + module.exports = entryUnbind('${ p.namespace }', '${ p.name }'); + `, + types: dedent` + declare module '${ buildModulePath(p) }' { + const resultMethod: ${ getCustomGenerics(p.genericsCount) }(self: ${ buildSelfForNamespace(p.namespace, p.prefix) }, ...args: Parameters<${ buildCoreJSTypeName(p.namespace, p.name) }${ getCustomGenerics(p.genericsCount) }>) => ReturnType<${ buildCoreJSTypeName(p.namespace, p.name) }${ getCustomGenerics(p.genericsCount) }>; + export = resultMethod; + } + `, +}); + +export const $uncurriedIterator = p => ({ + entry: dedent` + ${ importModules(p) } + + var uncurryThis = ${ importInternal('function-uncurry-this', p.level) } + var getIteratorMethod = ${ importInternal('get-iterator-method', p.level) } + + module.exports = uncurryThis(getIteratorMethod(${ p.namespace }())); + `, + types: dedent` + declare module '${ buildModulePath(p) }' { + type method${ getGenericsForNamespace(p.namespace) } = ${ p.namespace }${ getGenericsForNamespace(p.namespace) }[typeof Symbol.iterator]; + const resultMethod: ${ getGenericsForNamespace(p.namespace) }(self: ${ p.namespace }${ getCommonGenericsForNamespace(p.namespace) }, ...args: Parameters) => ReturnType; + export = resultMethod; + } + `, +}); + +export const $static = p => ({ + entry: dedent` + ${ importModules(p) } + + var getBuiltInStaticMethod = ${ importInternal('get-built-in-static-method', p.level) } + + module.exports = getBuiltInStaticMethod('${ p.namespace }', '${ p.name }'); + `, + types: dedent` + declare module '${ buildModulePath(p) }' { + const method: typeof ${ p.prefix ?? '' }${ p.namespace }.${ p.name }; + export = method; + } + `, +}); + +export const $staticWithContext = p => ({ + entry: dedent` + ${ importModules(p) } + + var getBuiltIn = ${ importInternal('get-built-in', p.level) } + var getBuiltInStaticMethod = ${ importInternal('get-built-in-static-method', p.level) } + var isCallable = ${ importInternal('is-callable', p.level) } + var apply = ${ importInternal('function-apply', p.level) } + + var method = getBuiltInStaticMethod('${ p.namespace }', '${ p.name }'); + + module.exports = function ${ isAllowedFunctionName(p.name) ? p.name : '' }() { + return apply(method, isCallable(this) ? this : getBuiltIn('${ p.namespace }'), arguments); + }; + `, + types: dedent` + declare module '${ buildModulePath(p) }' { + const method: typeof ${ p.prefix ?? '' }${ p.namespace }.${ p.name }; + export = method; + } + `, +}); + +export const $patchableStatic = p => ({ + entry: dedent` + ${ importModules(p) } + + var getBuiltInStaticMethod = ${ importInternal('get-built-in-static-method', p.level) } + var apply = ${ importInternal('function-apply', p.level) } + + module.exports = function ${ isAllowedFunctionName(p.name) ? p.name : '' }() { + return apply(getBuiltInStaticMethod('${ p.namespace }', '${ p.name }'), this, arguments); + }; + `, + types: dedent` + declare module '${ buildModulePath(p) }' { + const method: typeof ${ p.prefix ?? '' }${ p.namespace }.${ p.name }; + export = method; + } + `, +}); + +export const $namespace = p => ({ + entry: dedent` + ${ importModules(p) } + + var path = ${ importInternal('path', p.level) } + + module.exports = path.${ p.name }; + `, + types: dedent` + declare module '${ buildModulePath(p) }' { + const namespace: typeof ${ p.prefix ?? '' }${ p.name }; + export = namespace; + } + `, +}); + +export const $helper = p => ({ + entry: dedent` + ${ importModules(p) } + + var $export = ${ importInternal(p.helper, p.level) } + + module.exports = $export; + `, + types: dedent` + declare module '${ buildModulePath(p) }' { + const helper: (arg: NonNullable) => any; + export = helper; + } + `, +}); + +export const $path = p => ({ + entry: dedent` + ${ importModules(p) } + + var path = ${ importInternal('path', p.level) } + + module.exports = path; + `, + types: dedent` + declare module '${ buildModulePath(p) }' { + const path: typeof globalThis; + export = path; + } + `, +}); + +export const $instanceArray = p => ({ + entry: dedent` + var isPrototypeOf = require('../../internals/object-is-prototype-of'); + var arrayMethod = require('../array/prototype/${ basename(p.entry) }'); + + var ArrayPrototype = Array.prototype; + + module.exports = function (it) { + var ownProperty = it.${ p.name }; + if (it === ArrayPrototype || (isPrototypeOf(ArrayPrototype, it) && ownProperty === ArrayPrototype.${ p.name })) return arrayMethod; + return ownProperty; + }; + `, + types: dedent` + declare module '${ buildModulePath(p) }' { + const method: (arg: NonNullable) => any; + export = method; + } + `, +}); + +export const $instanceNumber = p => ({ + entry: dedent` + var isPrototypeOf = require('../../internals/object-is-prototype-of'); + var numberMethod = require('../number/prototype/${ basename(p.entry) }'); + + var NumberPrototype = Number.prototype; + + module.exports = function (it) { + var ownProperty = it.${ p.name }; + if (typeof it == 'number' || it === NumberPrototype + || (isPrototypeOf(NumberPrototype, it) && ownProperty === NumberPrototype.${ p.name })) return numberMethod; + return ownProperty; + }; + `, + types: dedent` + declare module '${ buildModulePath(p) }' { + const method: (arg: NonNullable) => any; + export = method; + } + `, +}); + +export const $instanceString = p => ({ + entry: dedent` + var isPrototypeOf = require('../../internals/object-is-prototype-of'); + var stringMethod = require('../string/prototype/${ basename(p.entry) }'); + + var StringPrototype = String.prototype; + + module.exports = function (it) { + var ownProperty = it.${ p.name }; + if (typeof it == 'string' || it === StringPrototype + || (isPrototypeOf(StringPrototype, it) && ownProperty === StringPrototype.${ p.name })) return stringMethod; + return ownProperty; + }; + `, + types: dedent` + declare module '${ buildModulePath(p) }' { + const method: (arg: NonNullable) => any; + export = method; + } + `, +}); + +export const $instanceFunction = p => ({ + entry: dedent` + var isPrototypeOf = require('../../internals/object-is-prototype-of'); + var functionMethod = require('../function/prototype/${ basename(p.entry) }'); + + var FunctionPrototype = Function.prototype; + + module.exports = function (it) { + var ownProperty = it.${ p.name }; + if (it === FunctionPrototype || (isPrototypeOf(FunctionPrototype, it) && ownProperty === FunctionPrototype.${ p.name })) { + return functionMethod; + } return ownProperty; + }; + `, + types: dedent` + declare module '${ buildModulePath(p) }' { + const method: (arg: NonNullable) => any; + export = method; + } + `, +}); + +export const $instanceDOMIterables = p => ({ + entry: dedent` + ${ importModules(p) } + + var classof = require('../../internals/classof'); + var hasOwn = require('../../internals/has-own-property'); + + var arrayMethod = Array.prototype.${ p.name }; + + var DOMIterables = { + DOMTokenList: true, + NodeList: true, + }; + + module.exports = function (it) { + var ownProperty = it.${ p.name }; + if (hasOwn(DOMIterables, classof(it))) return arrayMethod; + return ownProperty; + }; + `, + types: dedent` + declare module '${ buildModulePath(p) }' { + const method: (arg: NonNullable) => any; + export = method; + } + `, +}); + +export const $instanceArrayString = p => ({ + entry: dedent` + var isPrototypeOf = require('../../internals/object-is-prototype-of'); + var arrayMethod = require('../array/prototype/${ basename(p.entry) }'); + var stringMethod = require('../string/prototype/${ basename(p.entry) }'); + + var ArrayPrototype = Array.prototype; + var StringPrototype = String.prototype; + + module.exports = function (it) { + var ownProperty = it.${ p.name }; + if (it === ArrayPrototype || (isPrototypeOf(ArrayPrototype, it) && ownProperty === ArrayPrototype.${ p.name })) return arrayMethod; + if (typeof it == 'string' || it === StringPrototype + || (isPrototypeOf(StringPrototype, it) && ownProperty === StringPrototype.${ p.name })) return stringMethod; + return ownProperty; + }; + `, + types: dedent` + declare module '${ buildModulePath(p) }' { + const method: (arg: NonNullable) => any; + export = method; + } + `, +}); + +export const $instanceArrayDOMIterables = p => ({ + entry: dedent` + ${ importModules(p) } + + var classof = require('../../internals/classof'); + var hasOwn = require('../../internals/has-own-property'); + var isPrototypeOf = require('../../internals/object-is-prototype-of'); + var arrayMethod = require('../array/prototype/${ basename(p.entry) }'); + + var ArrayPrototype = Array.prototype; + + var DOMIterables = { + DOMTokenList: true, + NodeList: true, + }; + + module.exports = function (it) { + var ownProperty = it.${ p.name }; + if (it === ArrayPrototype || ((isPrototypeOf(ArrayPrototype, it) + || hasOwn(DOMIterables, classof(it))) && ownProperty === ArrayPrototype.${ p.name })) return arrayMethod; + return ownProperty; + }; + `, + types: dedent` + declare module '${ buildModulePath(p) }' { + const method: (arg: NonNullable) => any; + export = method; + } + `, +}); + +export const $instanceRegExpFlags = p => ({ + entry: dedent` + ${ importModules(p) } + + var isPrototypeOf = require('../../internals/object-is-prototype-of'); + var flags = require('../regexp/flags'); + + var RegExpPrototype = RegExp.prototype; + + module.exports = function (it) { + return (it === RegExpPrototype || isPrototypeOf(RegExpPrototype, it)) ? flags(it) : it.flags; + }; + `, + types: dedent` + declare module '${ buildModulePath(p) }' { + const method: (arg: NonNullable) => any; + export = method; + } + `, +}); + +export const $proposal = p => ({ + entry: dedent` + // proposal stage: ${ p.stage } + // ${ p.link } + ${ importModules(p) } + `, + types: '', +}); + +export const $typeDummy = p => ({ + entry: '', + types: dedent` + declare module '${ buildModulePath(p) }' { + const method: any; + export = method; + } + `, +}); + +export const $functionWithCustomType = p => ({ + entry: '', + types: dedent` + declare module '${ buildModulePath(p) }' { + const resultFunction: typeof ${ buildCoreJSTypeName('', p.name) }; + export = resultFunction; + } + `, +}); diff --git a/scripts/build-entries/templates.mjs b/scripts/build-entries/templates.mjs deleted file mode 100644 index 01fe99a7a769..000000000000 --- a/scripts/build-entries/templates.mjs +++ /dev/null @@ -1,247 +0,0 @@ -import { basename } from 'node:path'; -import dedent from 'dedent'; - -const t = template => params => `'use strict';\n${ template({ ...params }) }\n`; - -const importInternal = (module, level) => `require('${ level ? '../'.repeat(level) : './' }internals/${ module }');`; - -const importModule = (module, level) => `require('${ level ? '../'.repeat(level) : './' }modules/${ module }');`; - -const importModules = ({ modules, level }) => modules.map(module => importModule(module, level)).join('\n'); - -function isAllowedFunctionName(name) { - try { - // eslint-disable-next-line no-new-func -- safe - Function(`function ${ name }() { /* empty */ }`); - return true; - } catch { - return false; - } -} - -export const $justImport = t(p => importModules(p)); - -export const $prototype = t(p => dedent` - ${ importModules(p) } - - var getBuiltInPrototypeMethod = ${ importInternal('get-built-in-prototype-method', p.level) } - - module.exports = getBuiltInPrototypeMethod('${ p.namespace }', '${ p.name }'); -`); - -export const $prototypeIterator = t(p => dedent` - ${ importModules(p) } - - var getIteratorMethod = ${ importInternal('get-iterator-method', p.level) } - - module.exports = getIteratorMethod(${ p.source }); -`); - -export const $uncurried = t(p => dedent` - ${ importModules(p) } - - var entryUnbind = ${ importInternal('entry-unbind', p.level) } - - module.exports = entryUnbind('${ p.namespace }', '${ p.name }'); -`); - -export const $uncurriedIterator = t(p => dedent` - ${ importModules(p) } - - var uncurryThis = ${ importInternal('function-uncurry-this', p.level) } - var getIteratorMethod = ${ importInternal('get-iterator-method', p.level) } - - module.exports = uncurryThis(getIteratorMethod(${ p.source })); -`); - -export const $static = t(p => dedent` - ${ importModules(p) } - - var getBuiltInStaticMethod = ${ importInternal('get-built-in-static-method', p.level) } - - module.exports = getBuiltInStaticMethod('${ p.namespace }', '${ p.name }'); -`); - -export const $staticWithContext = t(p => dedent` - ${ importModules(p) } - - var getBuiltIn = ${ importInternal('get-built-in', p.level) } - var getBuiltInStaticMethod = ${ importInternal('get-built-in-static-method', p.level) } - var isCallable = ${ importInternal('is-callable', p.level) } - var apply = ${ importInternal('function-apply', p.level) } - - var method = getBuiltInStaticMethod('${ p.namespace }', '${ p.name }'); - - module.exports = function ${ isAllowedFunctionName(p.name) ? p.name : '' }() { - return apply(method, isCallable(this) ? this : getBuiltIn('${ p.namespace }'), arguments); - }; -`); - -export const $patchableStatic = t(p => dedent` - ${ importModules(p) } - - var getBuiltInStaticMethod = ${ importInternal('get-built-in-static-method', p.level) } - var apply = ${ importInternal('function-apply', p.level) } - - module.exports = function ${ isAllowedFunctionName(p.name) ? p.name : '' }() { - return apply(getBuiltInStaticMethod('${ p.namespace }', '${ p.name }'), this, arguments); - }; -`); - -export const $namespace = t(p => dedent` - ${ importModules(p) } - - var path = ${ importInternal('path', p.level) } - - module.exports = path.${ p.name }; -`); - -export const $helper = t(p => dedent` - ${ importModules(p) } - - var $export = ${ importInternal(p.helper, p.level) } - - module.exports = $export; -`); - -export const $path = t(p => dedent` - ${ importModules(p) } - - var path = ${ importInternal('path', p.level) } - - module.exports = path; -`); - -export const $instanceArray = t(p => dedent` - var isPrototypeOf = require('../../internals/object-is-prototype-of'); - var arrayMethod = require('../array/prototype/${ basename(p.entry) }'); - - var ArrayPrototype = Array.prototype; - - module.exports = function (it) { - var ownProperty = it.${ p.name }; - if (it === ArrayPrototype || (isPrototypeOf(ArrayPrototype, it) && ownProperty === ArrayPrototype.${ p.name })) return arrayMethod; - return ownProperty; - }; -`); - -export const $instanceNumber = t(p => dedent` - var isPrototypeOf = require('../../internals/object-is-prototype-of'); - var numberMethod = require('../number/prototype/${ basename(p.entry) }'); - - var NumberPrototype = Number.prototype; - - module.exports = function (it) { - var ownProperty = it.${ p.name }; - if (typeof it == 'number' || it === NumberPrototype - || (isPrototypeOf(NumberPrototype, it) && ownProperty === NumberPrototype.${ p.name })) return numberMethod; - return ownProperty; - }; -`); - -export const $instanceString = t(p => dedent` - var isPrototypeOf = require('../../internals/object-is-prototype-of'); - var stringMethod = require('../string/prototype/${ basename(p.entry) }'); - - var StringPrototype = String.prototype; - - module.exports = function (it) { - var ownProperty = it.${ p.name }; - if (typeof it == 'string' || it === StringPrototype - || (isPrototypeOf(StringPrototype, it) && ownProperty === StringPrototype.${ p.name })) return stringMethod; - return ownProperty; - }; -`); - -export const $instanceFunction = t(p => dedent` - var isPrototypeOf = require('../../internals/object-is-prototype-of'); - var functionMethod = require('../function/prototype/${ basename(p.entry) }'); - - var FunctionPrototype = Function.prototype; - - module.exports = function (it) { - var ownProperty = it.${ p.name }; - if (it === FunctionPrototype || (isPrototypeOf(FunctionPrototype, it) && ownProperty === FunctionPrototype.${ p.name })) { - return functionMethod; - } return ownProperty; - }; -`); - -export const $instanceDOMIterables = t(p => dedent` - ${ importModules(p) } - - var classof = require('../../internals/classof'); - var hasOwn = require('../../internals/has-own-property'); - - var arrayMethod = Array.prototype.${ p.name }; - - var DOMIterables = { - DOMTokenList: true, - NodeList: true, - }; - - module.exports = function (it) { - var ownProperty = it.${ p.name }; - if (hasOwn(DOMIterables, classof(it))) return arrayMethod; - return ownProperty; - }; -`); - -export const $instanceArrayString = t(p => dedent` - var isPrototypeOf = require('../../internals/object-is-prototype-of'); - var arrayMethod = require('../array/prototype/${ basename(p.entry) }'); - var stringMethod = require('../string/prototype/${ basename(p.entry) }'); - - var ArrayPrototype = Array.prototype; - var StringPrototype = String.prototype; - - module.exports = function (it) { - var ownProperty = it.${ p.name }; - if (it === ArrayPrototype || (isPrototypeOf(ArrayPrototype, it) && ownProperty === ArrayPrototype.${ p.name })) return arrayMethod; - if (typeof it == 'string' || it === StringPrototype - || (isPrototypeOf(StringPrototype, it) && ownProperty === StringPrototype.${ p.name })) return stringMethod; - return ownProperty; - }; -`); - -export const $instanceArrayDOMIterables = t(p => dedent` - ${ importModules(p) } - - var classof = require('../../internals/classof'); - var hasOwn = require('../../internals/has-own-property'); - var isPrototypeOf = require('../../internals/object-is-prototype-of'); - var arrayMethod = require('../array/prototype/${ basename(p.entry) }'); - - var ArrayPrototype = Array.prototype; - - var DOMIterables = { - DOMTokenList: true, - NodeList: true, - }; - - module.exports = function (it) { - var ownProperty = it.${ p.name }; - if (it === ArrayPrototype || ((isPrototypeOf(ArrayPrototype, it) - || hasOwn(DOMIterables, classof(it))) && ownProperty === ArrayPrototype.${ p.name })) return arrayMethod; - return ownProperty; - }; -`); - -export const $instanceRegExpFlags = t(p => dedent` - ${ importModules(p) } - - var isPrototypeOf = require('../../internals/object-is-prototype-of'); - var flags = require('../regexp/flags'); - - var RegExpPrototype = RegExp.prototype; - - module.exports = function (it) { - return (it === RegExpPrototype || isPrototypeOf(RegExpPrototype, it)) ? flags(it) : it.flags; - }; -`); - -export const $proposal = t(p => dedent` - // proposal stage: ${ p.stage } - // ${ p.link } - ${ importModules(p) } -`); diff --git a/scripts/check-compat-data-mapping.mjs b/scripts/check-compat-data-mapping.mjs index f34851190b25..0ceae7de8b55 100644 --- a/scripts/check-compat-data-mapping.mjs +++ b/scripts/check-compat-data-mapping.mjs @@ -1,5 +1,5 @@ import semver from 'semver'; -import mapping from '@core-js/compat/src/mapping.mjs'; +import mapping from '../packages/core-js-compat/src/mapping.mjs'; const { coerce, cmp } = semver; let updated = true; diff --git a/scripts/check-unused-modules.mjs b/scripts/check-unused-modules.mjs index a3128ca11629..a73dcada6d45 100644 --- a/scripts/check-unused-modules.mjs +++ b/scripts/check-unused-modules.mjs @@ -1,5 +1,5 @@ import konan from 'konan'; -import { modules, ignored } from '@core-js/compat/src/data.mjs'; +import { modules, ignored } from '../packages/core-js-compat/src/data.mjs'; async function jsModulesFrom(path) { const directory = await fs.readdir(path); diff --git a/scripts/update-version.mjs b/scripts/update-version.mjs index 376e59622c0b..8817bcc6d6c3 100644 --- a/scripts/update-version.mjs +++ b/scripts/update-version.mjs @@ -18,6 +18,7 @@ const CHANGELOG = 'CHANGELOG.md'; const LICENSE = 'LICENSE'; const README = 'README.md'; const README_COMPAT = 'packages/core-js-compat/README.md'; +const README_TYPES = 'packages/core-js-types/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'; @@ -34,6 +35,9 @@ await writeFile(README, readme.replaceAll(PREV_VERSION, NEW_VERSION).replaceAll( const readmeCompat = await readFile(README_COMPAT, 'utf8'); await writeFile(README_COMPAT, readmeCompat.replaceAll(PREV_VERSION_MINOR, NEW_VERSION_MINOR)); +const readmeTypes = await readFile(README_TYPES, 'utf8'); +await writeFile(README_TYPES, readmeTypes.replaceAll(PREV_VERSION_MINOR, NEW_VERSION_MINOR)); + const shared = await readFile(SHARED, 'utf8'); await writeFile(SHARED, shared.replaceAll(PREV_VERSION, NEW_VERSION).replaceAll(OLD_YEAR, CURRENT_YEAR)); @@ -87,6 +91,8 @@ else if (CURRENT_YEAR === OLD_YEAR) echo(red('bump is not required')); await $`npm run build-compat`; +await $`npm run build-types`; + const UNRELEASED_TAG = `${ coerce(PREV_VERSION) }-unreleased`; const modulesByVersions = await readJson('packages/core-js-compat/modules-by-versions.json'); diff --git a/tests/compat-data/tests-coverage.mjs b/tests/compat-data/tests-coverage.mjs index 370821600dc2..9f4daa13f4b9 100644 --- a/tests/compat-data/tests-coverage.mjs +++ b/tests/compat-data/tests-coverage.mjs @@ -1,4 +1,4 @@ -import { modules, ignored } from '@core-js/compat/src/data.mjs'; +import { modules, ignored } from '../../packages/core-js-compat/src/data.mjs'; import '../compat/tests.js'; const modulesSet = new Set([ diff --git a/tests/debug-get-dependencies/debug-get-dependencies.mjs b/tests/debug-get-dependencies/debug-get-dependencies.mjs index 5799f589409c..fe1b85ea3e32 100644 --- a/tests/debug-get-dependencies/debug-get-dependencies.mjs +++ b/tests/debug-get-dependencies/debug-get-dependencies.mjs @@ -1,4 +1,4 @@ -import { modules } from '@core-js/compat/src/data.mjs'; -import { getListOfDependencies } from '../../scripts/build-entries/get-dependencies.mjs'; +import { modules } from '../../packages/core-js-compat/src/data.mjs'; +import { getModulesMetadata } from '../../scripts/build-entries-and-types/get-dependencies.mjs'; -for (const module of modules) console.log(module, await getListOfDependencies([module])); +for (const module of modules) console.log(module, await getModulesMetadata([module])); diff --git a/tests/eslint/eslint.config.js b/tests/eslint/eslint.config.js index 4b36d490dbab..36e033c1ad84 100644 --- a/tests/eslint/eslint.config.js +++ b/tests/eslint/eslint.config.js @@ -1,6 +1,8 @@ +import { fixupPluginRules } from '@eslint/compat'; import globals from 'globals'; import confusingBrowserGlobals from 'confusing-browser-globals'; import * as parserJSONC from 'jsonc-eslint-parser'; +import parserTypeScript from '@typescript-eslint/parser'; import pluginArrayFunc from 'eslint-plugin-array-func'; import pluginASCII from 'eslint-plugin-ascii'; import pluginDepend from 'eslint-plugin-depend'; @@ -21,9 +23,13 @@ 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 pluginTypeScript from '@typescript-eslint/eslint-plugin'; +import $pluginTSDoc from 'eslint-plugin-tsdoc'; import pluginUnicorn from 'eslint-plugin-unicorn'; import { yaml as pluginYaml } from 'eslint-yaml'; +const pluginTSDoc = fixupPluginRules($pluginTSDoc); + const PACKAGES_NODE_VERSIONS = '^20.19'; const DEV_NODE_VERSIONS = '^20.19'; @@ -37,7 +43,157 @@ function disable(rules) { return Object.fromEntries(Object.keys(rules).map(key => [key, OFF])); } +// layout & formatting: +const baseStyle = { + // require or disallow the Unicode Byte Order Mark + 'unicode-bom': [ERROR, NEVER], + // require camel case names + camelcase: [ERROR, { + properties: NEVER, + ignoreDestructuring: true, + ignoreImports: true, + ignoreGlobals: true, + }], + // disallow use of multiline strings + 'no-multi-str': ERROR, + // 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: '', + }], + // 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'], + // 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 }, + }], +}; + const base = { + ...baseStyle, // possible problems: // enforces return statements in callbacks of array's methods 'array-callback-return': ERROR, @@ -132,8 +288,6 @@ const base = { }], // 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 @@ -142,13 +296,6 @@ const base = { // 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 @@ -220,8 +367,6 @@ const base = { '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 @@ -342,132 +487,6 @@ const base = { // 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: '', - }], - // 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, @@ -668,16 +687,6 @@ const base = { '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 @@ -1897,6 +1906,47 @@ const playwright = { 'playwright/require-to-pass-timeout': ERROR, }; +const ts = { + ...disable(base), + ...baseStyle, + // validating that TypeScript doc comments conform to the TSDoc specification + 'tsdoc/syntax': ERROR, + // specify the maximum length of a line in your program + '@stylistic/max-len': [OFF, { ...base['@stylistic/max-len'][1], code: 180 }], + // require consistent spacing around type annotations + '@stylistic/type-annotation-spacing': ERROR, + // enforces consistent spacing inside TypeScript type generics + '@stylistic/type-generic-spacing': ERROR, + // expect space before the type declaration in the named tuple + '@stylistic/type-named-tuple-spacing': ERROR, + // require that function overload signatures be consecutive + '@typescript-eslint/adjacent-overload-signatures': ERROR, + // enforce type definitions to consistently use either `interface` or `type` + '@typescript-eslint/consistent-type-definitions': [ERROR, 'interface'], + // disallow extra non-null assertions + '@typescript-eslint/no-extra-non-null-assertion': ERROR, + // enforce the use of top-level import type qualifier when an import only has specifiers with inline type qualifiers + '@typescript-eslint/no-import-type-side-effects': ERROR, + // disallow explicit type declarations for variables or parameters initialized to a number, string, or boolean + '@typescript-eslint/no-inferrable-types': ERROR, + // disallow unnecessary constraints on generic types + '@typescript-eslint/no-unnecessary-type-constraint': ERROR, + // disallow unsafe declaration merging + '@typescript-eslint/no-unsafe-declaration-merging': ERROR, + // disallow empty exports that don't change anything in a module file + '@typescript-eslint/no-useless-empty-export': ERROR, + // enforce using function types instead of interfaces with call signatures + '@typescript-eslint/prefer-function-type': ERROR, + // require using namespace keyword over module keyword to declare custom TypeScript modules + '@typescript-eslint/prefer-namespace-keyword': ERROR, + // disallow two overloads that could be unified into one with a union or an optional / rest parameter + '@typescript-eslint/unified-signatures': OFF, +}; + +const typeDefinitionsTests = { + ...disable(forbidNonStandardBuiltIns), +}; + const yaml = { // disallow empty mapping values 'yaml/no-empty-mapping-value': ERROR, @@ -2180,6 +2230,7 @@ export default [ 'tests/**/bundles/**', 'tests/compat/compat-data.js', 'tests/unit-@(global|pure)/index.js', + 'tests/type-definitions/tmp/**', 'website/dist/**', 'website/src/public/*', 'website/templates/**', @@ -2202,6 +2253,7 @@ export default [ }, plugins: { '@stylistic': pluginStylistic, + '@typescript-eslint': pluginTypeScript, 'array-func': pluginArrayFunc, ascii: pluginASCII, depend: pluginDepend, @@ -2221,6 +2273,7 @@ export default [ redos: pluginReDoS, regexp: pluginRegExp, sonarjs: pluginSonarJS, + tsdoc: pluginTSDoc, unicorn: pluginUnicorn, yaml: pluginYaml, }, @@ -2365,6 +2418,22 @@ export default [ 'import/first': OFF, }, }, + { + files: [ + 'packages/core-js-types/src/**/*.d.ts', + 'tests/type-definitions/**/*.ts', + ], + languageOptions: { + parser: parserTypeScript, + }, + rules: ts, + }, + { + files: [ + 'tests/type-definitions/**/*.ts', + ], + rules: typeDefinitionsTests, + }, { rules: { // ensure that filenames match a convention diff --git a/tests/eslint/package-lock.json b/tests/eslint/package-lock.json index f17ad719c99f..35dc756a3fd2 100644 --- a/tests/eslint/package-lock.json +++ b/tests/eslint/package-lock.json @@ -7,10 +7,13 @@ "name": "tests/eslint", "devDependencies": { "@eslint-community/eslint-plugin-eslint-comments": "^4.6.0", + "@eslint/compat": "^2.0.2", "@eslint/markdown": "^7.5.1", "@stylistic/eslint-plugin": "^5.9.0", + "@typescript-eslint/eslint-plugin": "^8.56.1", + "@typescript-eslint/parser": "^8.56.1", "confusing-browser-globals": "^1.0.11", - "eslint": "^10.0.1", + "eslint": "^10.0.2", "eslint-plugin-array-func": "^5.1.0", "eslint-plugin-ascii": "^2.0.0", "eslint-plugin-depend": "^1.4.0", @@ -28,6 +31,7 @@ "eslint-plugin-redos": "^4.5.0", "eslint-plugin-regexp": "^3.0.0", "eslint-plugin-sonarjs": "^4.0.0", + "eslint-plugin-tsdoc": "^0.5.1", "eslint-plugin-unicorn": "^63.0.0", "eslint-yaml": "^0.1.0", "globals": "^17.3.0", @@ -147,6 +151,27 @@ "node": "^12.0.0 || ^14.0.0 || >=16.0.0" } }, + "node_modules/@eslint/compat": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/@eslint/compat/-/compat-2.0.2.tgz", + "integrity": "sha512-pR1DoD0h3HfF675QZx0xsyrsU8q70Z/plx7880NOhS02NuWLgBCOMDL787nUeQ7EWLkxv3bPQJaarjcPQb2Dwg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^1.1.0" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "peerDependencies": { + "eslint": "^8.40 || 9 || 10" + }, + "peerDependenciesMeta": { + "eslint": { + "optional": true + } + } + }, "node_modules/@eslint/config-array": { "version": "0.23.2", "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.2.tgz", @@ -175,7 +200,7 @@ "node": "^20.19.0 || ^22.13.0 || >=24" } }, - "node_modules/@eslint/config-helpers/node_modules/@eslint/core": { + "node_modules/@eslint/core": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@eslint/core/-/core-1.1.0.tgz", "integrity": "sha512-/nr9K9wkr3P1EzFTdFdMoLuo1PmIxjmwvPozwoSodjNBdefGujXQUF93u1DDZpEaTuDvMsIQddsd35BwtrW9Xw==", @@ -188,19 +213,6 @@ "node": "^20.19.0 || ^22.13.0 || >=24" } }, - "node_modules/@eslint/core": { - "version": "0.17.0", - "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.17.0.tgz", - "integrity": "sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@types/json-schema": "^7.0.15" - }, - "engines": { - "node": "^18.18.0 || ^20.9.0 || >=21.1.0" - } - }, "node_modules/@eslint/markdown": { "version": "7.5.1", "resolved": "https://registry.npmjs.org/@eslint/markdown/-/markdown-7.5.1.tgz", @@ -225,6 +237,19 @@ "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, + "node_modules/@eslint/markdown/node_modules/@eslint/core": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.17.0.tgz", + "integrity": "sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, "node_modules/@eslint/object-schema": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-3.0.2.tgz", @@ -249,6 +274,19 @@ "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, + "node_modules/@eslint/plugin-kit/node_modules/@eslint/core": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.17.0.tgz", + "integrity": "sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, "node_modules/@humanfs/core": { "version": "0.19.1", "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz", @@ -301,6 +339,50 @@ "url": "https://github.com/sponsors/nzakas" } }, + "node_modules/@microsoft/tsdoc": { + "version": "0.16.0", + "resolved": "https://registry.npmjs.org/@microsoft/tsdoc/-/tsdoc-0.16.0.tgz", + "integrity": "sha512-xgAyonlVVS+q7Vc7qLW0UrJU7rSFcETRWsqdXZtjzRU8dF+6CkozTK4V4y1LwOX7j8r/vHphjDeMeGI4tNGeGA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@microsoft/tsdoc-config": { + "version": "0.18.1", + "resolved": "https://registry.npmjs.org/@microsoft/tsdoc-config/-/tsdoc-config-0.18.1.tgz", + "integrity": "sha512-9brPoVdfN9k9g0dcWkFeA7IH9bbcttzDJlXvkf8b2OBzd5MueR1V2wkKBL0abn0otvmkHJC6aapBOTJDDeMCZg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@microsoft/tsdoc": "0.16.0", + "ajv": "~8.18.0", + "jju": "~1.4.0", + "resolve": "~1.22.2" + } + }, + "node_modules/@microsoft/tsdoc-config/node_modules/ajv": { + "version": "8.18.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz", + "integrity": "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/@microsoft/tsdoc-config/node_modules/json-schema-traverse": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", + "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true, + "license": "MIT" + }, "node_modules/@napi-rs/wasm-runtime": { "version": "0.2.12", "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-0.2.12.tgz", @@ -472,6 +554,142 @@ "dev": true, "license": "MIT" }, + "node_modules/@typescript-eslint/eslint-plugin": { + "version": "8.56.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.56.1.tgz", + "integrity": "sha512-Jz9ZztpB37dNC+HU2HI28Bs9QXpzCz+y/twHOwhyrIRdbuVDxSytJNDl6z/aAKlaRIwC7y8wJdkBv7FxYGgi0A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/regexpp": "^4.12.2", + "@typescript-eslint/scope-manager": "8.56.1", + "@typescript-eslint/type-utils": "8.56.1", + "@typescript-eslint/utils": "8.56.1", + "@typescript-eslint/visitor-keys": "8.56.1", + "ignore": "^7.0.5", + "natural-compare": "^1.4.0", + "ts-api-utils": "^2.4.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "@typescript-eslint/parser": "^8.56.1", + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/parser": { + "version": "8.56.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.56.1.tgz", + "integrity": "sha512-klQbnPAAiGYFyI02+znpBRLyjL4/BrBd0nyWkdC0s/6xFLkXYQ8OoRrSkqacS1ddVxf/LDyODIKbQ5TgKAf/Fg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/scope-manager": "8.56.1", + "@typescript-eslint/types": "8.56.1", + "@typescript-eslint/typescript-estree": "8.56.1", + "@typescript-eslint/visitor-keys": "8.56.1", + "debug": "^4.4.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/project-service": { + "version": "8.56.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.56.1.tgz", + "integrity": "sha512-TAdqQTzHNNvlVFfR+hu2PDJrURiwKsUvxFn1M0h95BB8ah5jejas08jUWG4dBA68jDMI988IvtfdAI53JzEHOQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/tsconfig-utils": "^8.56.1", + "@typescript-eslint/types": "^8.56.1", + "debug": "^4.4.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/scope-manager": { + "version": "8.56.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.56.1.tgz", + "integrity": "sha512-YAi4VDKcIZp0O4tz/haYKhmIDZFEUPOreKbfdAN3SzUDMcPhJ8QI99xQXqX+HoUVq8cs85eRKnD+rne2UAnj2w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.56.1", + "@typescript-eslint/visitor-keys": "8.56.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/tsconfig-utils": { + "version": "8.56.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.56.1.tgz", + "integrity": "sha512-qOtCYzKEeyr3aR9f28mPJqBty7+DBqsdd63eO0yyDwc6vgThj2UjWfJIcsFeSucYydqcuudMOprZ+x1SpF3ZuQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/type-utils": { + "version": "8.56.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.56.1.tgz", + "integrity": "sha512-yB/7dxi7MgTtGhZdaHCemf7PuwrHMenHjmzgUW1aJpO+bBU43OycnM3Wn+DdvDO/8zzA9HlhaJ0AUGuvri4oGg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.56.1", + "@typescript-eslint/typescript-estree": "8.56.1", + "@typescript-eslint/utils": "8.56.1", + "debug": "^4.4.3", + "ts-api-utils": "^2.4.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, "node_modules/@typescript-eslint/types": { "version": "8.56.1", "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.56.1.tgz", @@ -486,6 +704,89 @@ "url": "https://opencollective.com/typescript-eslint" } }, + "node_modules/@typescript-eslint/typescript-estree": { + "version": "8.56.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.56.1.tgz", + "integrity": "sha512-qzUL1qgalIvKWAf9C1HpvBjif+Vm6rcT5wZd4VoMb9+Km3iS3Cv9DY6dMRMDtPnwRAFyAi7YXJpTIEXLvdfPxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/project-service": "8.56.1", + "@typescript-eslint/tsconfig-utils": "8.56.1", + "@typescript-eslint/types": "8.56.1", + "@typescript-eslint/visitor-keys": "8.56.1", + "debug": "^4.4.3", + "minimatch": "^10.2.2", + "semver": "^7.7.3", + "tinyglobby": "^0.2.15", + "ts-api-utils": "^2.4.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/utils": { + "version": "8.56.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.56.1.tgz", + "integrity": "sha512-HPAVNIME3tABJ61siYlHzSWCGtOoeP2RTIaHXFMPqjrQKCGB9OgUVdiNgH7TJS2JNIQ5qQ4RsAUDuGaGme/KOA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.9.1", + "@typescript-eslint/scope-manager": "8.56.1", + "@typescript-eslint/types": "8.56.1", + "@typescript-eslint/typescript-estree": "8.56.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/visitor-keys": { + "version": "8.56.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.56.1.tgz", + "integrity": "sha512-KiROIzYdEV85YygXw6BI/Dx4fnBlFQu6Mq4QE4MOH9fFnhohw6wX/OAvDY2/C+ut0I3RSPKenvZJIVYqJNkhEw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.56.1", + "eslint-visitor-keys": "^5.0.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", + "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, "node_modules/@unrs/resolver-binding-android-arm-eabi": { "version": "1.11.1", "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-android-arm-eabi/-/resolver-binding-android-arm-eabi-1.11.1.tgz", @@ -1246,9 +1547,9 @@ } }, "node_modules/eslint": { - "version": "10.0.1", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.0.1.tgz", - "integrity": "sha512-20MV9SUdeN6Jd84xESsKhRly+/vxI+hwvpBMA93s+9dAcjdCuCojn4IqUGS3lvVaqjVYGYHSRMCpeFtF2rQYxQ==", + "version": "10.0.2", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.0.2.tgz", + "integrity": "sha512-uYixubwmqJZH+KLVYIVKY1JQt7tysXhtj21WSvjcSmU5SVNzMus1bgLe+pAt816yQ8opKfheVVoPLqvVMGejYw==", "dev": true, "license": "MIT", "dependencies": { @@ -1262,7 +1563,7 @@ "@humanwhocodes/module-importer": "^1.0.1", "@humanwhocodes/retry": "^0.4.2", "@types/estree": "^1.0.6", - "ajv": "^6.12.4", + "ajv": "^6.14.0", "cross-spawn": "^7.0.6", "debug": "^4.3.2", "escape-string-regexp": "^4.0.0", @@ -1501,19 +1802,6 @@ "eslint": ">=9.38.0" } }, - "node_modules/eslint-plugin-jsonc/node_modules/@eslint/core": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@eslint/core/-/core-1.1.0.tgz", - "integrity": "sha512-/nr9K9wkr3P1EzFTdFdMoLuo1PmIxjmwvPozwoSodjNBdefGujXQUF93u1DDZpEaTuDvMsIQddsd35BwtrW9Xw==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@types/json-schema": "^7.0.15" - }, - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" - } - }, "node_modules/eslint-plugin-jsonc/node_modules/@eslint/plugin-kit": { "version": "0.6.0", "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.6.0.tgz", @@ -1812,6 +2100,18 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/eslint-plugin-tsdoc": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-tsdoc/-/eslint-plugin-tsdoc-0.5.1.tgz", + "integrity": "sha512-+EFu9XAFzogfoRspo2slmHZZ10amXqLAhmgCG0nbR6RZHNZK2XmsE7gfZ8gBjaO/p6C2DOGn09UpTGOlYy6OdQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@microsoft/tsdoc": "0.16.0", + "@microsoft/tsdoc-config": "0.18.1", + "@typescript-eslint/utils": "~8.56.0" + } + }, "node_modules/eslint-plugin-unicorn": { "version": "63.0.0", "resolved": "https://registry.npmjs.org/eslint-plugin-unicorn/-/eslint-plugin-unicorn-63.0.0.tgz", @@ -1949,19 +2249,6 @@ "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, - "node_modules/eslint/node_modules/@eslint/core": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@eslint/core/-/core-1.1.0.tgz", - "integrity": "sha512-/nr9K9wkr3P1EzFTdFdMoLuo1PmIxjmwvPozwoSodjNBdefGujXQUF93u1DDZpEaTuDvMsIQddsd35BwtrW9Xw==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@types/json-schema": "^7.0.15" - }, - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=24" - } - }, "node_modules/eslint/node_modules/@eslint/plugin-kit": { "version": "0.6.0", "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.6.0.tgz", @@ -2102,6 +2389,23 @@ "dev": true, "license": "MIT" }, + "node_modules/fast-uri": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz", + "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "BSD-3-Clause" + }, "node_modules/fault": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/fault/-/fault-2.0.1.tgz", @@ -2207,6 +2511,16 @@ "node": ">=0.4.x" } }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/functional-red-black-tree": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz", @@ -2307,6 +2621,19 @@ "dev": true, "license": "ISC" }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/hosted-git-info": { "version": "9.0.2", "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-9.0.2.tgz", @@ -2389,6 +2716,22 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/is-core-module": { + "version": "2.16.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz", + "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==", + "dev": true, + "license": "MIT", + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/is-extglob": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", @@ -2432,6 +2775,13 @@ "dev": true, "license": "ISC" }, + "node_modules/jju": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/jju/-/jju-1.4.0.tgz", + "integrity": "sha512-8wb9Yw966OSxApiCt0K3yNJL8pnNeIv+OEq2YMidz4FKP6nonSRoOXc80iXY4JaN2FC11B9qsNmDsm+ZOfMROA==", + "dev": true, + "license": "MIT" + }, "node_modules/jsdoc-type-pratt-parser": { "version": "7.1.1", "resolved": "https://registry.npmjs.org/jsdoc-type-pratt-parser/-/jsdoc-type-pratt-parser-7.1.1.tgz", @@ -3463,9 +3813,9 @@ "license": "MIT" }, "node_modules/minimatch": { - "version": "10.2.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.2.tgz", - "integrity": "sha512-+G4CpNBxa5MprY+04MbgOw1v7So6n5JY166pFi9KfYwT78fxScCeSNQSNzp6dpPSW2rONOps6Ocam1wFhCgoVw==", + "version": "10.2.3", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.3.tgz", + "integrity": "sha512-Rwi3pnapEqirPSbWbrZaa6N3nmqq4Xer/2XooiOKyV3q12ML06f7MOuc5DVH8ONZIFhwIYQ3yzPH4nt7iWHaTg==", "dev": true, "license": "BlueOak-1.0.0", "dependencies": { @@ -3656,6 +4006,13 @@ "node": ">=8" } }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true, + "license": "MIT" + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -3932,6 +4289,16 @@ "regjsparser": "bin/parser" } }, + "node_modules/require-from-string": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", + "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/requireindex": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/requireindex/-/requireindex-1.2.0.tgz", @@ -3942,6 +4309,27 @@ "node": ">=0.10.5" } }, + "node_modules/resolve": { + "version": "1.22.11", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz", + "integrity": "sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-core-module": "^2.16.1", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/resolve-pkg-maps": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", @@ -4135,6 +4523,19 @@ "node": ">=0.10.0" } }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/synckit": { "version": "0.11.12", "resolved": "https://registry.npmjs.org/synckit/-/synckit-0.11.12.tgz", diff --git a/tests/eslint/package.json b/tests/eslint/package.json index 5af03d5c858b..046f8c4e8865 100644 --- a/tests/eslint/package.json +++ b/tests/eslint/package.json @@ -2,11 +2,14 @@ "name": "tests/eslint", "type": "module", "devDependencies": { + "@eslint/compat": "^2.0.2", "@eslint/markdown": "^7.5.1", "@eslint-community/eslint-plugin-eslint-comments": "^4.6.0", "@stylistic/eslint-plugin": "^5.9.0", + "@typescript-eslint/eslint-plugin": "^8.56.1", + "@typescript-eslint/parser": "^8.56.1", "confusing-browser-globals": "^1.0.11", - "eslint": "^10.0.1", + "eslint": "^10.0.2", "eslint-plugin-array-func": "^5.1.0", "eslint-plugin-ascii": "^2.0.0", "eslint-plugin-depend": "^1.4.0", @@ -24,6 +27,7 @@ "eslint-plugin-redos": "^4.5.0", "eslint-plugin-regexp": "^3.0.0", "eslint-plugin-sonarjs": "^4.0.0", + "eslint-plugin-tsdoc": "^0.5.1", "eslint-plugin-unicorn": "^63.0.0", "eslint-yaml": "^0.1.0", "globals": "^17.3.0", diff --git a/tests/templates/templates.mjs b/tests/templates/templates.mjs new file mode 100644 index 000000000000..48c6a56a490a --- /dev/null +++ b/tests/templates/templates.mjs @@ -0,0 +1,96 @@ +import { + $justImport, $patchableStatic, + $uncurried, + $uncurriedIterator, $static, $staticWithContext, + $prototype, + $prototypeIterator, +} from '../../scripts/build-entries-and-types/templates.mjs'; +import { deepEqual } from 'node:assert/strict'; + +const props = { + modules: ['module1', 'module2'], + namespace: 'namespace', + name: 'name', + level: 2, + types: ['type1', 'type2'], + source: 'source', +}; + +deepEqual( + $justImport(props), + { dts: '// it has no exports', entry: "require('../../modules/module1');\nrequire('../../modules/module2');" }, + 'Template $justImport incorrect', +); +deepEqual( + $prototype(props), + { + dts: 'declare const method: typeof namespace.prototype.name;\nexport = method;', + entry: "require('../../modules/module1');\nrequire('../../modules/module2');\n" + + "\nvar getBuiltInPrototypeMethod = require('../../internals/get-built-in-prototype-method');\n\nmodule.exports = getBuiltInPrototypeMethod('namespace', 'name');", + }, + 'Template $prototype incorrect', +); +deepEqual( + $prototypeIterator(props), + { + dts: 'declare const method: typeof namespace.prototype[typeof Symbol.iterator];\nexport = method;', + entry: "require('../../modules/module1');\nrequire('../../modules/module2');\n" + + "\nvar getIteratorMethod = require('../../internals/get-iterator-method');\n\nmodule.exports = getIteratorMethod(source);", + }, + 'Template $prototypeIterator incorrect', +); +deepEqual( + $uncurried(props), + { + dts: 'declare const method: (\n thisArg: any,\n ...args: Parameters\n) => ReturnType;\nexport = method;', + entry: "require('../../modules/module1');\nrequire('../../modules/module2');\n" + + "\nvar entryUnbind = require('../../internals/entry-unbind');\n\nmodule.exports = entryUnbind('namespace', 'name');", + }, + 'Template $uncurried incorrect', +); + +deepEqual( + $uncurriedIterator(props), + { + dts: 'declare const method: (\n thisArg: any,\n ...args: Parameters\n' + + ') => ReturnType;\nexport = method;', + entry: "require('../../modules/module1');\nrequire('../../modules/module2');\n" + + "\nvar uncurryThis = require('../../internals/function-uncurry-this');\nvar getIteratorMethod = require('../../internals/get-iterator-method');\n" + + '\nmodule.exports = uncurryThis(getIteratorMethod(source));', + }, + 'Template $uncurriedIterator incorrect', +); + +deepEqual( + $static(props), + { + dts: 'declare const method: typeof namespace.name;\nexport = method;', + entry: "require('../../modules/module1');\nrequire('../../modules/module2');\n" + + "\nvar getBuiltInStaticMethod = require('../../internals/get-built-in-static-method');\n\nmodule.exports = getBuiltInStaticMethod('namespace', 'name');", + }, + 'Template $static incorrect', +); + +deepEqual( + $staticWithContext(props), { + dts: 'declare const method: (\n this: Function | void,\n ...args: Parameters\n) => ReturnType;\nexport = method;', + entry: "require('../../modules/module1');\nrequire('../../modules/module2');\n\nvar getBuiltIn = require('../../internals/get-built-in');\n" + + "var getBuiltInStaticMethod = require('../../internals/get-built-in-static-method');\nvar isCallable = require('../../internals/is-callable');\n" + + "var apply = require('../../internals/function-apply');\n\nvar method = getBuiltInStaticMethod('namespace', 'name');\n" + + "\nmodule.exports = function name() {\n return apply(method, isCallable(this) ? this : getBuiltIn('namespace'), arguments);\n};", + }, + 'Template $staticWithContext incorrect', +); + +deepEqual( + $patchableStatic(props), + { + dts: 'declare const method: typeof namespace.name;\nexport = method;', + entry: "require('../../modules/module1');\nrequire('../../modules/module2');\n\nvar getBuiltInStaticMethod = require('../../internals/get-built-in-static-method');\n" + + "var apply = require('../../internals/function-apply');\n" + + "\nmodule.exports = function name() {\n return apply(getBuiltInStaticMethod('namespace', 'name'), this, arguments);\n};", + }, + 'Template $patchableStatic incorrect', +); + +echo(chalk.green('templates tested')); diff --git a/tests/type-definitions/coverage.mjs b/tests/type-definitions/coverage.mjs new file mode 100644 index 000000000000..508bbad826ba --- /dev/null +++ b/tests/type-definitions/coverage.mjs @@ -0,0 +1,20 @@ +import { modules as AllModules } from '../../packages/core-js-compat/src/data.mjs'; + +const { readFile } = fs; +const { red } = chalk; + +const MODULES_PATH = 'packages/core-js/modules/'; +const Modules = AllModules.filter(it => it.match(/^(?:esnext|web)\./)); +let hasErrors = false; +for (const moduleName of Modules) { + const modulePath = path.join(MODULES_PATH, `${ moduleName }.js`); + const content = await readFile(modulePath, 'utf8'); + if (!/\/\/ (?:@types:|@no-types)/.test(content)) { + echo(red('No types for module:'), path.resolve(modulePath)); + hasErrors = true; + } +} + +if (hasErrors) { + throw new Error('Some modules have no types'); +} diff --git a/tests/type-definitions/entries/actual/test.ts b/tests/type-definitions/entries/actual/test.ts new file mode 100644 index 000000000000..7ed534129af7 --- /dev/null +++ b/tests/type-definitions/entries/actual/test.ts @@ -0,0 +1,20 @@ +import '@core-js/types/actual'; + +const concat = Iterator.concat([1, 2, 3]); + +structuredClone({ name: 'core-js' }); + +Iterator.zipKeyed({ a: [1, 2], b: [3, 4] }); +Iterator.zip([[1, 2, 3], [4, 5, 6]]); + +// @ts-expect-error +concat.chunks(2); +// @ts-expect-error +concat.windows(3); + +Promise.all([1, 2, 3]); +// @ts-expect-error +Promise.allKeyed({ + a: Promise.resolve(1), + b: Promise.resolve('string'), +}); diff --git a/tests/type-definitions/entries/actual/tsconfig.json b/tests/type-definitions/entries/actual/tsconfig.json new file mode 100644 index 000000000000..af766fab017b --- /dev/null +++ b/tests/type-definitions/entries/actual/tsconfig.json @@ -0,0 +1,6 @@ +{ + "extends": "../../tsconfig.json", + "include": [ + "./test.ts" + ] +} diff --git a/tests/type-definitions/entries/configurator/test.ts b/tests/type-definitions/entries/configurator/test.ts new file mode 100644 index 000000000000..d5b048991c26 --- /dev/null +++ b/tests/type-definitions/entries/configurator/test.ts @@ -0,0 +1,4 @@ +import '@core-js/types/configurator'; +import configurator from 'core-js/configurator'; + +configurator({ something: 'value' }); diff --git a/tests/type-definitions/entries/configurator/tsconfig.json b/tests/type-definitions/entries/configurator/tsconfig.json new file mode 100644 index 000000000000..af766fab017b --- /dev/null +++ b/tests/type-definitions/entries/configurator/tsconfig.json @@ -0,0 +1,6 @@ +{ + "extends": "../../tsconfig.json", + "include": [ + "./test.ts" + ] +} diff --git a/tests/type-definitions/entries/es/test.ts b/tests/type-definitions/entries/es/test.ts new file mode 100644 index 000000000000..67c60625879d --- /dev/null +++ b/tests/type-definitions/entries/es/test.ts @@ -0,0 +1,22 @@ +import '@core-js/types/es'; + +const concat = Iterator.concat([1, 2, 3]); + +structuredClone({ name: 'core-js' }); + +// @ts-expect-error +Iterator.zipKeyed({ a: [1, 2], b: [3, 4] }); +// @ts-expect-error +Iterator.zip([[1, 2, 3], [4, 5, 6]]); + +// @ts-expect-error +concat.chunks(2); +// @ts-expect-error +concat.windows(3); + +Promise.all([1, 2, 3]); +// @ts-expect-error +Promise.allKeyed({ + a: Promise.resolve(1), + b: Promise.resolve('string'), +}); diff --git a/tests/type-definitions/entries/es/tsconfig.json b/tests/type-definitions/entries/es/tsconfig.json new file mode 100644 index 000000000000..af766fab017b --- /dev/null +++ b/tests/type-definitions/entries/es/tsconfig.json @@ -0,0 +1,6 @@ +{ + "extends": "../../tsconfig.json", + "include": [ + "./test.ts" + ] +} diff --git a/tests/type-definitions/entries/full/test.ts b/tests/type-definitions/entries/full/test.ts new file mode 100644 index 000000000000..4b3716a5ba05 --- /dev/null +++ b/tests/type-definitions/entries/full/test.ts @@ -0,0 +1,17 @@ +import '@core-js/types/full'; + +const concat = Iterator.concat([1, 2, 3]); + +structuredClone({ name: 'core-js' }); + +Iterator.zipKeyed({ a: [1, 2], b: [3, 4] }); +Iterator.zip([[1, 2, 3], [4, 5, 6]]); + +concat.chunks(2); +concat.windows(3); + +Promise.all([1, 2, 3]); +Promise.allKeyed({ + a: Promise.resolve(1), + b: Promise.resolve('string'), +}); diff --git a/tests/type-definitions/entries/full/tsconfig.json b/tests/type-definitions/entries/full/tsconfig.json new file mode 100644 index 000000000000..af766fab017b --- /dev/null +++ b/tests/type-definitions/entries/full/tsconfig.json @@ -0,0 +1,6 @@ +{ + "extends": "../../tsconfig.json", + "include": [ + "./test.ts" + ] +} diff --git a/tests/type-definitions/entries/global-imports/test.ts b/tests/type-definitions/entries/global-imports/test.ts new file mode 100644 index 000000000000..672f41d761ce --- /dev/null +++ b/tests/type-definitions/entries/global-imports/test.ts @@ -0,0 +1,20 @@ +import $Math from 'core-js/full/math'; +import $MathIndex from 'core-js/full/math/index'; +import $MathIndexJS from 'core-js/full/math/index.js'; +import $Array from 'core-js/full/array'; +import $ArrayIndex from 'core-js/full/array/index'; +import $ArrayIndexJS from 'core-js/full/array/index.js'; +import chunks from 'core-js/full/iterator/chunks'; +import chunksJS from 'core-js/full/iterator/chunks.js'; + +$Math.f16round(7.9999999); +$MathIndex.f16round(7.9999999); +$MathIndexJS.f16round(7.9999999); + +$Array.from([1, 2, 3]); +$ArrayIndex.from([1, 2, 3]); +$ArrayIndexJS.from([1, 2, 3]); + +declare const num: Iterator; +chunks(num, 2); +chunksJS(num, 2); diff --git a/tests/type-definitions/entries/global-imports/tsconfig.json b/tests/type-definitions/entries/global-imports/tsconfig.json new file mode 100644 index 000000000000..ff4c8fd208b3 --- /dev/null +++ b/tests/type-definitions/entries/global-imports/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tsconfig.json", + "include": [ + "./test.ts" + ], + "compilerOptions": { + "types": ["@core-js/types"] + } +} diff --git a/tests/type-definitions/entries/proposals/test.ts b/tests/type-definitions/entries/proposals/test.ts new file mode 100644 index 000000000000..118f55d7f99a --- /dev/null +++ b/tests/type-definitions/entries/proposals/test.ts @@ -0,0 +1,5 @@ +import '@core-js/types/proposals/array-unique'; +const uniqueArr: number[] = [1, 2, 2, 3, 3, 3].uniqueBy(); + +import '@core-js/types/proposals/array-flat-map'; +const flatMappedArr: number[] = [1, 2, 3].flatMap(x => [x, x * 2]); diff --git a/tests/type-definitions/entries/proposals/tsconfig.json b/tests/type-definitions/entries/proposals/tsconfig.json new file mode 100644 index 000000000000..af766fab017b --- /dev/null +++ b/tests/type-definitions/entries/proposals/tsconfig.json @@ -0,0 +1,6 @@ +{ + "extends": "../../tsconfig.json", + "include": [ + "./test.ts" + ] +} diff --git a/tests/type-definitions/entries/pure-imports/test.ts b/tests/type-definitions/entries/pure-imports/test.ts new file mode 100644 index 000000000000..aec4ea087bc4 --- /dev/null +++ b/tests/type-definitions/entries/pure-imports/test.ts @@ -0,0 +1,20 @@ +import $Math from '@core-js/pure/full/math'; +import $MathIndex from '@core-js/pure/full/math/index'; +import $MathIndexJS from '@core-js/pure/full/math/index.js'; +import $Array from '@core-js/pure/full/array'; +import $ArrayIndex from '@core-js/pure/full/array/index'; +import $ArrayIndexJS from '@core-js/pure/full/array/index.js'; +import chunks from '@core-js/pure/full/iterator/chunks'; +import chunksJS from '@core-js/pure/full/iterator/chunks.js'; + +$Math.f16round(7.9999999); +$MathIndex.f16round(7.9999999); +$MathIndexJS.f16round(7.9999999); + +$Array.from([1, 2, 3]); +$ArrayIndex.from([1, 2, 3]); +$ArrayIndexJS.from([1, 2, 3]); + +declare const num: Iterator; +chunks(num, 2); +chunksJS(num, 2); diff --git a/tests/type-definitions/entries/pure-imports/tsconfig.json b/tests/type-definitions/entries/pure-imports/tsconfig.json new file mode 100644 index 000000000000..36fc3f454b75 --- /dev/null +++ b/tests/type-definitions/entries/pure-imports/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tsconfig.json", + "include": [ + "./test.ts" + ], + "compilerOptions": { + "types": ["@core-js/types/pure"] + } +} diff --git a/tests/type-definitions/entries/pure-pollutions/test.ts b/tests/type-definitions/entries/pure-pollutions/test.ts new file mode 100644 index 000000000000..6baaeb2f3672 --- /dev/null +++ b/tests/type-definitions/entries/pure-pollutions/test.ts @@ -0,0 +1,14 @@ +import '@core-js/types/pure'; + +// no global pollution +// @ts-expect-error +Iterator.chunks([1, 2, 3], 2); +// @ts-expect-error +Iterator.zipKeyed({ a: [1, 2], b: [3, 4] }); +// @ts-expect-error +Iterator.zip([[1, 2, 3], [4, 5, 6]]); +// @ts-expect-error +Promise.allKeyed({ + a: Promise.resolve(1), + b: Promise.resolve('string'), +}); diff --git a/tests/type-definitions/entries/pure-pollutions/tsconfig.json b/tests/type-definitions/entries/pure-pollutions/tsconfig.json new file mode 100644 index 000000000000..36fc3f454b75 --- /dev/null +++ b/tests/type-definitions/entries/pure-pollutions/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tsconfig.json", + "include": [ + "./test.ts" + ], + "compilerOptions": { + "types": ["@core-js/types/pure"] + } +} diff --git a/tests/type-definitions/entries/stable/test.ts b/tests/type-definitions/entries/stable/test.ts new file mode 100644 index 000000000000..e9b2a31d95ec --- /dev/null +++ b/tests/type-definitions/entries/stable/test.ts @@ -0,0 +1,22 @@ +import '@core-js/types/stable'; + +const concat = Iterator.concat([1, 2, 3]); + +structuredClone({ name: 'core-js' }); + +// @ts-expect-error +Iterator.zipKeyed({ a: [1, 2], b: [3, 4] }); +// @ts-expect-error +Iterator.zip([[1, 2, 3], [4, 5, 6]]); + +// @ts-expect-error +concat.chunks(2); +// @ts-expect-error +concat.windows(3); + +Promise.all([1, 2, 3]); +// @ts-expect-error +Promise.allKeyed({ + a: Promise.resolve(1), + b: Promise.resolve('string'), +}); diff --git a/tests/type-definitions/entries/stable/tsconfig.json b/tests/type-definitions/entries/stable/tsconfig.json new file mode 100644 index 000000000000..af766fab017b --- /dev/null +++ b/tests/type-definitions/entries/stable/tsconfig.json @@ -0,0 +1,6 @@ +{ + "extends": "../../tsconfig.json", + "include": [ + "./test.ts" + ] +} diff --git a/tests/type-definitions/global/annex-b/object-proto.test.ts b/tests/type-definitions/global/annex-b/object-proto.test.ts new file mode 100644 index 000000000000..4060b1cd8f69 --- /dev/null +++ b/tests/type-definitions/global/annex-b/object-proto.test.ts @@ -0,0 +1,4 @@ +import 'core-js/full'; + +declare const obj: Object; +const objectProto: object | null = obj.__proto__; diff --git a/tests/type-definitions/global/annex-b/object-prototype-accessor-methods.test.ts b/tests/type-definitions/global/annex-b/object-prototype-accessor-methods.test.ts new file mode 100644 index 000000000000..4f8a6be2fd82 --- /dev/null +++ b/tests/type-definitions/global/annex-b/object-prototype-accessor-methods.test.ts @@ -0,0 +1,7 @@ +import 'core-js/full'; + +declare const obj: Object; +obj.__defineGetter__('num', () => 42); +obj.__defineSetter__('num', (val: number) => {}); +const getter: (() => any) | undefined = obj.__lookupGetter__('num'); +const setter: ((val: number) => any) | undefined = obj.__lookupSetter__('num'); diff --git a/tests/type-definitions/global/proposals/accessible-object-hasownproperty.test.ts b/tests/type-definitions/global/proposals/accessible-object-hasownproperty.test.ts new file mode 100644 index 000000000000..c20ffe587e0c --- /dev/null +++ b/tests/type-definitions/global/proposals/accessible-object-hasownproperty.test.ts @@ -0,0 +1,30 @@ +import 'core-js/es'; +import hasOwn from 'core-js/es/object/has-own'; +import $Object from 'core-js/es/object'; + +$Object.hasOwn({ a: 1 }, 'a'); +hasOwn({ a: 1 }, 'a'); + +// @ts-expect-error +hasOwn(1, 'a'); +// @ts-expect-error +$Object.hasOwn(1, 'a'); + +Object.hasOwn({ a: 1 }, 'a'); +Object.hasOwn([], 0); +Object.hasOwn(new Date(), 'toISOString'); +Object.hasOwn(Object.create(null), Symbol.iterator); +Object.hasOwn(function () {}, 'call'); +Object.hasOwn(Object.prototype, 'toString'); + +// @ts-expect-error +Object.hasOwn(1, 'a'); + +// @ts-expect-error +Object.hasOwn({ a: 1 }, {}); + +// @ts-expect-error +Object.hasOwn({ a: 1 }); + +// @ts-expect-error +Object.hasOwn(); diff --git a/tests/type-definitions/global/proposals/array-buffer-base64.test.ts b/tests/type-definitions/global/proposals/array-buffer-base64.test.ts new file mode 100644 index 000000000000..1d0a06e42faa --- /dev/null +++ b/tests/type-definitions/global/proposals/array-buffer-base64.test.ts @@ -0,0 +1,44 @@ +import 'core-js/es'; +import $Uint8Array from 'core-js/es/typed-array/uint8-array'; + +$Uint8Array.fromBase64('SGVsbG8gd29ybGQ=', { alphabet: 'base64', lastChunkHandling: 'loose' }); + +function acceptUint8Array(v: Uint8Array) {} +function acceptProcessMetadata(v: { read: number; written: number }) {} +function acceptString(v: string) {} + +acceptUint8Array(Uint8Array.fromBase64('SGVsbG8gd29ybGQ=', { alphabet: 'base64', lastChunkHandling: 'loose' })); +acceptUint8Array(Uint8Array.fromHex('ddddeeeassd')); +const ar = new Uint8Array(16); +acceptProcessMetadata(ar.setFromBase64('PGI+ TURO PC9i Pg==', { alphabet: 'base64', lastChunkHandling: 'loose' })); +acceptProcessMetadata(ar.setFromHex('ddddeeeassd')); +acceptString(ar.toBase64({ alphabet: 'base64', omitPadding: true })); +acceptString(ar.toBase64()); +acceptString(ar.toHex()); + +// @ts-expect-error +Uint8Array.fromBase64('SGVsbG8gd29ybGQ', { alphabet: 'some' }); +// @ts-expect-error +Uint8Array.fromBase64('SGVsbG8gd29ybGQ', { lastChunkHandling: 'some' }); +// @ts-expect-error +Uint8Array.fromBase64(123); + +// @ts-expect-error +Uint8Array.fromHex([0, 1]); +// @ts-expect-error +Uint8Array.fromHex(123); + +// @ts-expect-error +ar.setFromBase64(5); +// @ts-expect-error +ar.setFromBase64('PGI+ TURO PC9i Pg==', { alphabet: 'some' }); +// @ts-expect-error +ar.setFromBase64('PGI+ TURO PC9i Pg==', { lastChunkHandling: 'some' }); + +// @ts-expect-error +ar.setFromHex(123); + +// @ts-expect-error +ar.toBase64({ alphabet: 'some' }); +// @ts-expect-error +ar.toBase64({ omitPadding: 'some' }); diff --git a/tests/type-definitions/global/proposals/array-buffer-transfer.test.ts b/tests/type-definitions/global/proposals/array-buffer-transfer.test.ts new file mode 100644 index 000000000000..753572fb1b69 --- /dev/null +++ b/tests/type-definitions/global/proposals/array-buffer-transfer.test.ts @@ -0,0 +1,30 @@ +import 'core-js/es'; +import $ArrayBuffer from 'core-js/es/array-buffer'; + +const abFromNamespace = new $ArrayBuffer(16); +const abFNSTransfer: ArrayBuffer = abFromNamespace.transfer(); + +const ab = new ArrayBuffer(16); +// TODO uncomment when fixed +// const abDetached: boolean = ab.detached; +const abTransfer: ArrayBuffer = ab.transfer(); +const abTransfer2: ArrayBuffer = ab.transfer(32); +const abTransferFixed: ArrayBuffer = ab.transferToFixedLength(); +const abTransferFixed2: ArrayBuffer = ab.transferToFixedLength(64); + +// @ts-expect-error +ab.detached(1); +// @ts-expect-error +ab.detached = true; +// @ts-expect-error +ab.transfer('32'); +// @ts-expect-error +ab.transfer(true); +// @ts-expect-error +ab.transfer(16, 32); +// @ts-expect-error +ab.transferToFixedLength('100'); +// @ts-expect-error +ab.transferToFixedLength(false); +// @ts-expect-error +ab.transferToFixedLength(32, 64); diff --git a/tests/type-definitions/global/proposals/array-filtering.test.ts b/tests/type-definitions/global/proposals/array-filtering.test.ts new file mode 100644 index 000000000000..67dd16dacc8c --- /dev/null +++ b/tests/type-definitions/global/proposals/array-filtering.test.ts @@ -0,0 +1,69 @@ +import 'core-js/full'; +import filterReject from 'core-js/full/array/filter-reject'; +import filterRejectJS from 'core-js/full/array/filter-reject.js'; +import { assertNumberArray } from '../../helpers/helpers.js'; + +filterReject([1, 2, 3], (v, i, arr) => v > 1); +filterRejectJS([1, 2, 3], (v, i, arr) => v > 1); + +// @ts-expect-error +filterReject([1, 2, 3], (x: string) => false); +// @ts-expect-error +filterRejectJS([1, 2, 3], (x: string) => false); + +[1, 2, 3].filterReject((v, i, arr) => v > 1); +['a', 'b'].filterReject((v, i, arr) => v === 'a'); +const arr = [1, 2, 3]; +assertNumberArray(arr.filterReject(function (v) { return v < 2; }, { foo: true })); + +new Int8Array([1, 2, 3]).filterReject((v, i, arr) => v > 1); +new Uint8Array([1, 2, 3]).filterReject((v, i, arr) => v > 1); +new Uint8ClampedArray([1, 2, 3]).filterReject((v, i, arr) => v > 1); +new Int16Array([1, 2, 3]).filterReject((v, i, arr) => v > 1); +new Uint16Array([1, 2, 3]).filterReject((v, i, arr) => v > 1); +new Int32Array([1, 2, 3]).filterReject((v, i, arr) => v > 1); +new Uint32Array([1, 2, 3]).filterReject((v, i, arr) => v > 1); +new Float32Array([1, 2, 3]).filterReject((v, i, arr) => v > 1); +new Float64Array([1, 2, 3]).filterReject((v, i, arr) => v > 1); + +// TODO for es6 +// declare var BigInt: (value: number | string | bigint) => bigint; +// (new BigInt64Array([BigInt(1), BigInt(2), BigInt(3)])).filterReject((v, i, arr) => v > BigInt(1)); +// (new BigUint64Array([BigInt(1), BigInt(2), BigInt(3)])).filterReject((v, i, arr) => v > BigInt(1)); + +// @ts-expect-error +[1, 2, 3].filterReject((x: string) => false); + +// @ts-expect-error +new Int8Array([1, 2, 3]).filterReject((x: string) => false); + +// @ts-expect-error +new Uint8Array([1, 2, 3]).filterReject((x: string) => false); + +// @ts-expect-error +new Uint8ClampedArray([1, 2, 3]).filterReject((x: string) => false); + +// @ts-expect-error +new Int16Array([1, 2, 3]).filterReject((x: string) => false); + +// @ts-expect-error +new Uint16Array([1, 2, 3]).filterReject((x: string) => false); + +// @ts-expect-error +new Int32Array([1, 2, 3]).filterReject((x: string) => false); + +// @ts-expect-error +new Uint32Array([1, 2, 3]).filterReject((x: string) => false); + +// @ts-expect-error +new Float32Array([1, 2, 3]).filterReject((x: string) => false); + +// @ts-expect-error +new Float64Array([1, 2, 3]).filterReject((x: string) => false); + +// TODO for es6 +// // @ts-expect-error +// (new BigInt64Array([BigInt(1), BigInt(2), BigInt(3)])).filterReject((x: number) => false); +// +// // @ts-expect-error +// (new BigUint64Array([BigInt(1), BigInt(2), BigInt(3)])).filterReject((x: number) => false); diff --git a/tests/type-definitions/global/proposals/array-find-from-last.test.ts b/tests/type-definitions/global/proposals/array-find-from-last.test.ts new file mode 100644 index 000000000000..3b1ed3056e1a --- /dev/null +++ b/tests/type-definitions/global/proposals/array-find-from-last.test.ts @@ -0,0 +1,72 @@ +import 'core-js/es'; +import findLast from 'core-js/es/array/find-last'; +import findLastJS from 'core-js/es/array/find-last.js'; +import findLastIndex from 'core-js/es/array/find-last-index'; +import findLastIndexJS from 'core-js/es/array/find-last-index.js'; +import { assertNumber } from '../../helpers/helpers.js'; + +const resNS1: number | undefined = findLast([1, 2, 3], v => v > 1); +const resNS2: number | undefined = findLastJS([1, 2, 3], v => v > 1); +assertNumber(findLastIndex([1, 2, 3], v => v > 1, {})); +assertNumber(findLastIndexJS([1, 2, 3], v => v > 1, {})); + +// @ts-expect-error +findLast([1, 2, 3]); +// @ts-expect-error +findLastJS([1, 2, 3]); +// @ts-expect-error +findLastIndex([1, 2, 3]); +// @ts-expect-error +findLastIndexJS([1, 2, 3]); + +const res: number | undefined = [1, 2, 3].findLast(v => v > 1); +[1, 2, 3].findLast((v): v is 2 => v === 2); +['a', 'b', 'c'].findLast(v => v === 'b'); +['a', 'b', 'c'].findLast((v): v is 'b' => v === 'b'); +[1, 2, 3].findLastIndex(v => v === 2); +const nums: number[] = [1, 2, 3]; +const res2: number | undefined = nums.findLast((v, i, arr) => v > 1 && arr.length > 0, {}); +nums.findLastIndex((v, i, arr) => v > 0, {}); +const m = ['a', 2, 3] as (string | number)[]; +m.findLast((v): v is string => typeof v === 'string'); +new Int8Array([1, 2, 3]).findLast(v => v > 0); +new Int8Array([1, 2, 3]).findLast((v, i, arr) => v == i && arr instanceof Int8Array); +new Int8Array([1, 2, 3]).findLastIndex(v => v > 0); +new Int8Array([1, 2, 3]).findLast((v): v is 2 => v === 2); +new Uint8Array([1, 2, 3]).findLast(v => v > 0); +new Uint8Array([1, 2, 3]).findLastIndex(v => v < 0); +new Float64Array([1, 2, 3]).findLast(v => v > 1.1); +new Float64Array([1, 2, 3]).findLastIndex(v => v > 100); +// TODO for es6 +// (new BigInt64Array([BigInt(1), BigInt(2), BigInt(3)])).findLast(v => v > BigInt(1)); +// (new BigInt64Array([BigInt(1), BigInt(2), BigInt(3)])).findLast((v): v is bigint => v === BigInt(2)); +// (new BigInt64Array([BigInt(1), BigInt(2), BigInt(3)])).findLastIndex(v => v > BigInt(0)); +// (new BigUint64Array([BigInt(1), BigInt(2), BigInt(3)])).findLast(v => v > BigInt(1)); +// (new BigUint64Array([BigInt(1), BigInt(2), BigInt(3)])).findLastIndex(v => v > BigInt(0)); + +// @ts-expect-error +[1, 2, 3].findLast(); + +// @ts-expect-error +[1, 2, 3].findLast('not function'); + +// @ts-expect-error +new Int8Array([1, 2, 3]).findLast(); + +// @ts-expect-error +new Int8Array([1, 2, 3]).findLast('not function'); + +// @ts-expect-error +new Int8Array([1, 2, 3]).findLast((v: string) => false); + +// // @ts-expect-error +// (new BigInt64Array([BigInt(1)])).findLast((v: number) => false); + +// @ts-expect-error +[1, 2, 3].findLastIndex(); + +// @ts-expect-error +new Float64Array([1, 2, 3]).findLastIndex(); + +// @ts-expect-error +new Uint8Array([1, 2, 3]).findLastIndex('not function'); diff --git a/tests/type-definitions/global/proposals/array-flat-map.test.ts b/tests/type-definitions/global/proposals/array-flat-map.test.ts new file mode 100644 index 000000000000..98665c17ead5 --- /dev/null +++ b/tests/type-definitions/global/proposals/array-flat-map.test.ts @@ -0,0 +1,51 @@ +import 'core-js/es'; +import flatMap from 'core-js/es/array/flat-map'; +import flatMapJS from 'core-js/es/array/flat-map.js'; +import { assertNumberArray, assertStringArray } from '../../helpers/helpers.js'; + +assertNumberArray(flatMap([1, 2, 3], x => [x, x * 2])); +assertNumberArray(flatMapJS([1, 2, 3], x => [x, x * 2])); + +// @ts-expect-error +flatMap([1, 2, 3]); +// @ts-expect-error +flatMapJS([1, 2, 3]); + +assertNumberArray([1, 2, 3].flatMap(x => [x, x * 2])); +assertStringArray(['a', 'b', 'c'].flatMap(x => [x, x.toUpperCase()])); +[1, 2, 3].flatMap(x => x > 1 ? [x, x] : []); +[1, 2, 3].flatMap(function (x) { return [this, x]; }, 123); +[1, 2, 3].flatMap((x, i, arr) => arr); + +assertNumberArray([[1], [2], [3]].flat()); +const flatted2: (string[] | string)[] = ['a', ['b', ['c']]].flat(); +[[1], [2], [3]].flat(2); +[1, [2, [3, [4]]]].flat(2); +[1, 2, 3].flat(); +[1, 2, 3].flat(0); + +const arr = [[1, 2], [3, 4], [5, 6]]; +arr.flat(); +arr.flat(1); +arr.flat(2); + +const arr2: (number | number[])[] = [1, [2, 3], 4]; +arr2.flat(); + +const arr3: (string | string[])[] = ['a', ['b', 'c'], 'd']; +arr3.flat(); + +([[[[1]]]] as number[][][][]).flat(3); + +// @ts-expect-error +[1, 2, 3].flatMap(); +// @ts-expect-error +[1, 2, 3].flatMap(123); +// @ts-expect-error +[1, 2, 3].flatMap('not function'); +// @ts-expect-error +([1, 2, 3] as any[]).flat('not a number'); +// @ts-expect-error +[1, 2, 3].flatMap(x => x, 1, 2); +// @ts-expect-error +[1, 2, 3].flat(1, 2); diff --git a/tests/type-definitions/global/proposals/array-from-async.test.ts b/tests/type-definitions/global/proposals/array-from-async.test.ts new file mode 100644 index 000000000000..8083394cd413 --- /dev/null +++ b/tests/type-definitions/global/proposals/array-from-async.test.ts @@ -0,0 +1,63 @@ +import 'core-js/es'; +import fromAsync from 'core-js/es/array/from-async'; +import fromAsyncJS from 'core-js/es/array/from-async.js'; +import $Array from 'core-js/es/array'; +import $ArrayIndex from 'core-js/es/array/index'; +import $ArrayIndexJS from 'core-js/es/array/index.js'; + +const pNS: Promise = fromAsync([1, 2, 3]); +const pNS2: Promise = fromAsyncJS([1, 2, 3]); +const pNS3: Promise = $Array.fromAsync([1, 2, 3]); +const pNS4: Promise = $ArrayIndex.fromAsync([1, 2, 3]); +const pNS5: Promise = $ArrayIndexJS.fromAsync([1, 2, 3]); + +// @ts-expect-error +fromAsync([1, 2, 3], 'not a function'); +// @ts-expect-error +fromAsyncJS([1, 2, 3], 'not a function'); +// @ts-expect-error +$Array.fromAsync([1, 2, 3], 'not a function'); +// @ts-expect-error +$ArrayIndex.fromAsync([1, 2, 3], 'not a function'); +// @ts-expect-error +$ArrayIndexJS.fromAsync([1, 2, 3], 'not a function'); + +const p1: Promise = Array.fromAsync([1, 2, 3]); +const p2: Promise = Array.fromAsync([Promise.resolve(1), 2, 3]); +const p3: Promise = Array.fromAsync((async function * () { yield 1; })()); +const p4: Promise = Array.fromAsync([1, 2, 3], (value: number, index: number) => value.toString()); +const p5: Promise = Array.fromAsync([Promise.resolve(1), 2, 3], (value: number) => value + 1); +const p6: Promise = Array.fromAsync((async function * () { yield 1; })(), function (value: number) { + return value * 2; +}); +const p7: Promise = Array.fromAsync([1, 2, 3], function (this: { foo: string }, value: number) { return value.toString(); }, { foo: 'str' }); + +async function t1() { + const n: number[] = await Array.fromAsync([1, 2, 3]); + const m: number[] = await Array.fromAsync([Promise.resolve(1), 2, 3]); + const s: string[] = await Array.fromAsync([1, 2, 3], (value: number) => value.toString()); +} + +async function t2() { + const bar: number[] = await Array.fromAsync([1, 2, 3], async (v: number) => v + 1); + const foo: string[] = await Array.fromAsync([Promise.resolve(1), 2], async (v: number) => String(v)); +} + +declare const arrLike: { [index: number]: PromiseLike; length: 2 }; +const p8: Promise = Array.fromAsync(arrLike); +const p9: Promise = Array.fromAsync(arrLike, (value: number) => value); + +// @ts-expect-error +Array.fromAsync([1, 2, 3], (value: string) => value); +// @ts-expect-error +Array.fromAsync([1, 2, 3], (value: string) => 1); +// @ts-expect-error +Array.fromAsync(['a', 'b', 'c'], (value: number) => value); +// @ts-expect-error +Array.fromAsync([Promise.resolve(1), 2, 3], (value: string) => value); +// @ts-expect-error +Array.fromAsync((async function * () { yield 'a'; })(), (value: number) => value); + +declare const strArrLike: { [index: number]: string; length: 3 }; +// @ts-expect-error +Array.fromAsync(strArrLike, (value: number) => value); diff --git a/tests/type-definitions/global/proposals/array-grouping.test.ts b/tests/type-definitions/global/proposals/array-grouping.test.ts new file mode 100644 index 000000000000..206451b662c9 --- /dev/null +++ b/tests/type-definitions/global/proposals/array-grouping.test.ts @@ -0,0 +1,44 @@ +import 'core-js/es'; +import objectGroupBy from 'core-js/es/object/group-by'; +import mapGroupBy from 'core-js/es/map/group-by'; + +const arr = [1, 2, 3, 4, 5]; + +const objGroupNS: Partial> = objectGroupBy(arr, x => x % 2 === 0 ? 'even' : 'odd'); +const mapGroupNS2: Map<'even' | 'odd', number[]> = mapGroupBy(arr, x => x % 2 === 0 ? 'even' : 'odd'); + +// @ts-expect-error +objectGroupBy(); +// @ts-expect-error +mapGroupBy(); + +const objGroup: Partial> = Object.groupBy(arr, x => x % 2 === 0 ? 'even' : 'odd'); +const mapGroup: Map<'even' | 'odd', number[]> = Map.groupBy(arr, x => x % 2 === 0 ? 'even' : 'odd'); +const objGroup2: Partial> = Object.groupBy(['foo', 'bar', 'baz'], (s, i) => i > 1 ? s[0] : 'x'); +const mapGroup2: Map = Map.groupBy(['foo', 'bar', 'baz'], (s, i) => i > 1 ? s[0] : 'x'); + +Object.groupBy('test', c => c); +Object.groupBy(new Set([1, 2, 3]), item => item > 2 ? 'big' : 'small'); +Object.groupBy([], _ => 'x'); + +Map.groupBy('hello', c => c.charCodeAt(0)); +Map.groupBy(new Set(['a', 'b', 'c']), (x, i) => i); + +// @ts-expect-error +Object.groupBy(); +// @ts-expect-error +Object.groupBy([1, 2, 3]); +// @ts-expect-error +Object.groupBy([1, 2, 3], 123); +// @ts-expect-error +Object.groupBy(123, x => x); +// @ts-expect-error +Object.groupBy([1, 2, 3], (a, b, c) => a); +// @ts-expect-error +Map.groupBy(); +// @ts-expect-error +Map.groupBy([1, 2, 3]); +// @ts-expect-error +Map.groupBy(123, x => x); +// @ts-expect-error +Map.groupBy([1, 2, 3], (a, b, c) => a); diff --git a/tests/type-definitions/global/proposals/array-includes.test.ts b/tests/type-definitions/global/proposals/array-includes.test.ts new file mode 100644 index 000000000000..0b0ed0efc6bb --- /dev/null +++ b/tests/type-definitions/global/proposals/array-includes.test.ts @@ -0,0 +1,132 @@ +import 'core-js/es'; +import includes from 'core-js/es/array/includes'; +import { assertBool } from '../../helpers/helpers.js'; + +const arr = [1, 2, 3]; + +assertBool(includes(arr, 2)); + +// @ts-expect-error +includes(arr); + +assertBool(arr.includes(2)); +assertBool(arr.includes(2, 1)); + +const strArr: string[] = ['a', 'b', 'c']; +assertBool(strArr.includes('b')); +assertBool(strArr.includes('b', 1)); + +const i8 = new Int8Array([1, 2, 3]); +assertBool(i8.includes(2)); +assertBool(i8.includes(2, 1)); + +const u8 = new Uint8Array([1, 2, 3]); +assertBool(u8.includes(2)); +assertBool(u8.includes(2, 1)); + +const u8c = new Uint8ClampedArray([1, 2, 3]); +assertBool(u8c.includes(2)); +assertBool(u8c.includes(2, 1)); + +const i16 = new Int16Array([1, 2, 3]); +assertBool(i16.includes(2)); +assertBool(i16.includes(2, 1)); + +const u16 = new Uint16Array([1, 2, 3]); +assertBool(u16.includes(2)); +assertBool(u16.includes(2, 1)); + +const i32 = new Int32Array([1, 2, 3]); +assertBool(i32.includes(2)); +assertBool(i32.includes(2, 1)); + +const u32 = new Uint32Array([1, 2, 3]); +assertBool(u32.includes(2)); +assertBool(u32.includes(2, 1)); + +const f32 = new Float32Array([1.5, 2.5, 3.5]); +assertBool(f32.includes(2.5)); +assertBool(f32.includes(2.5, 1)); + +const f64 = new Float64Array([1.5, 2.5, 3.5]); +assertBool(f64.includes(2.5)); +assertBool(f64.includes(2.5, 1)); + +// todo for es6 +// const bi64 = new BigInt64Array([BigInt(1), BigInt(2), BigInt(3)]); +// assertBool(bi64.includes(BigInt(2)); +// assertBool(bi64.includes(BigInt(2), 1); +// +// const bu64 = new BigUint64Array([BigInt(1), BigInt(2), BigInt(3)]); +// assertBool(bu64.includes(BigInt(2)); +// assertBool(bu64.includes(BigInt(2), 1); + +// @ts-expect-error +arr.includes(); +// @ts-expect-error +arr.includes(1, '2'); + +// @ts-expect-error +strArr.includes(2); +// @ts-expect-error +strArr.includes('b', true); + +// @ts-expect-error +i8.includes('2'); +// @ts-expect-error +i8.includes(2, '1'); + +// @ts-expect-error +u8.includes('2'); +// @ts-expect-error +u8.includes(2, true); + +// @ts-expect-error +u8c.includes('2'); +// @ts-expect-error +u8c.includes(2, {}); + +// @ts-expect-error +i16.includes('2'); +// @ts-expect-error +i16.includes(2, []); + +// @ts-expect-error +u16.includes('2'); +// @ts-expect-error +u16.includes(2, ''); + +// @ts-expect-error +i32.includes('2'); +// @ts-expect-error +i32.includes(2, undefined, 42); + +// @ts-expect-error +u32.includes('2'); +// @ts-expect-error +u32.includes(2, 1, 2); + +// @ts-expect-error +f32.includes('2.5'); +// @ts-expect-error +f32.includes(2.5, '1'); + +// @ts-expect-error +f64.includes('2.5'); +// @ts-expect-error +f64.includes(2.5, []); + +// @ts-expect-error +bi64.includes(2); +// // @ts-expect-error +// bi64.includes(2n, '1'); +// // @ts-expect-error +// bi64.includes('2n'); + +// @ts-expect-error +bu64.includes(2); + +// // @ts-expect-error +// bu64.includes(2n, []); +// // @ts-expect-error +// bu64.includes('2n'); diff --git a/tests/type-definitions/global/proposals/array-is-template-object.test.ts b/tests/type-definitions/global/proposals/array-is-template-object.test.ts new file mode 100644 index 000000000000..bc3c423a953b --- /dev/null +++ b/tests/type-definitions/global/proposals/array-is-template-object.test.ts @@ -0,0 +1,25 @@ +import 'core-js/full'; +import isTemplateObject from 'core-js/full/array/is-template-object'; +import { assertBool } from '../../helpers/helpers.js'; + +const res: boolean = isTemplateObject([]); + +// @ts-expect-error +isTemplateObject(); + +assertBool(Array.isTemplateObject([])); +Array.isTemplateObject({}); +Array.isTemplateObject(['a', 'b']); +Array.isTemplateObject(Object.freeze(['foo', 'bar'])); +Array.isTemplateObject(123); +Array.isTemplateObject('str'); +Array.isTemplateObject(Symbol()); + +declare const x: unknown; +if (Array.isTemplateObject(x)) { + x.raw; + const _: readonly string[] = x.raw; +} + +// @ts-expect-error +Array.isTemplateObject(); diff --git a/tests/type-definitions/global/proposals/array-unique.test.ts b/tests/type-definitions/global/proposals/array-unique.test.ts new file mode 100644 index 000000000000..5e4ca1fd83e7 --- /dev/null +++ b/tests/type-definitions/global/proposals/array-unique.test.ts @@ -0,0 +1,148 @@ +import 'core-js/full'; +import uniqueBy from 'core-js/full/array/unique-by'; +import { assertNumberArray } from '../../helpers/helpers.js'; + +const uniqueByNS: number[] = uniqueBy([1, 2, 1, 3]); + +// @ts-expect-error +uniqueBy([1, 2, 3], 123); + +interface Obj { + a: number; + b: string +} +const arr: Obj[] = [{ a: 1, b: 'x' }, { a: 2, b: 'y' }]; +const arrRes: Obj[] = arr.uniqueBy(); +const arrRes2: Obj[] = arr.uniqueBy('a'); +const arrRes3: Obj[] = arr.uniqueBy(obj => obj.b); + +const numArr: number[] = [1, 2, 1, 3]; +assertNumberArray(numArr.uniqueBy()); +assertNumberArray(numArr.uniqueBy(x => x % 2)); + +const i8 = new Int8Array([1, 2, 2, 3]); +const i8Res: Int8Array = i8.uniqueBy(); +const i8Res2: Int8Array = i8.uniqueBy('length'); +const i8Res3: Int8Array = i8.uniqueBy(x => x % 2); + +const u8 = new Uint8Array([1, 2, 2, 3]); +const u8Res: Uint8Array = u8.uniqueBy(); +const u8Res2: Uint8Array = u8.uniqueBy('buffer'); +const u8Res3: Uint8Array = u8.uniqueBy(x => x * 2); + +const u8c = new Uint8ClampedArray([1, 1, 2, 3]); +const u8cRes: Uint8ClampedArray = u8c.uniqueBy(); +const u8cRes2: Uint8ClampedArray = u8c.uniqueBy('byteOffset'); +const u8cRes3: Uint8ClampedArray = u8c.uniqueBy(x => x); + +const i16 = new Int16Array([1, 1, 2, 3]); +const i16Res: Int16Array = i16.uniqueBy(); +const i16Res2: Int16Array = i16.uniqueBy('BYTES_PER_ELEMENT'); +const i16Res3: Int16Array = i16.uniqueBy(x => x); + +const u16 = new Uint16Array([1, 2, 2, 3]); +const u16Res: Uint16Array = u16.uniqueBy(); +const u16Res2: Uint16Array = u16.uniqueBy('buffer'); +const u16Res3: Uint16Array = u16.uniqueBy(x => x + 1); + +const i32 = new Int32Array([1, 2, 2, 3]); +const i32Res: Int32Array = i32.uniqueBy(); +const i32Res2: Int32Array = i32.uniqueBy('byteLength'); +const i32Res3: Int32Array = i32.uniqueBy(x => x); + +const u32 = new Uint32Array([1, 1, 2, 3]); +const u32Res: Uint32Array = u32.uniqueBy(); +const u32Res2: Uint32Array = u32.uniqueBy('length'); +const u32Res3: Uint32Array = u32.uniqueBy(x => x % 2); + +const f32 = new Float32Array([1.5, 2.5, 1.5, 3.5]); +const f32Res: Float32Array = f32.uniqueBy(); +const f32Res2: Float32Array = f32.uniqueBy('constructor'); +const f32Res3: Float32Array = f32.uniqueBy(x => Math.floor(x)); + +const f64 = new Float64Array([1.5, 2.5, 1.5, 3.5]); +const f64Res: Float64Array = f64.uniqueBy(); +const f64Res2: Float64Array = f64.uniqueBy('length'); +const f64Res3: Float64Array = f64.uniqueBy(x => x.toFixed(1)); + +// todo for es6 +// const bi64 = new BigInt64Array([BigInt(1), BigInt(2), BigInt(1), BigInt(3)]); +// const bi64Res: BigInt64Array = bi64.uniqueBy(); +// const bi64Res2: BigInt64Array = bi64.uniqueBy('length'); +// const bi64Res3: BigInt64Array = bi64.uniqueBy(x => (x as bigint) % BigInt(2)); +// +// const bu64 = new BigUint64Array([BigInt(1), BigInt(2), BigInt(1), BigInt(3)]); +// const bu64Res: BigUint64Array = bu64.uniqueBy(); +// const bu64Res2: BigUint64Array = bu64.uniqueBy('length'); +// const bu64Res3: BigUint64Array = bu64.uniqueBy(x => (x as bigint) * BigInt(3)); + +// @ts-expect-error +arr.uniqueBy(123); +// @ts-expect-error +arr.uniqueBy(true); +// @ts-expect-error +arr.uniqueBy({}); +// @ts-expect-error +arr.uniqueBy(['a']); + +// @ts-expect-error +numArr.uniqueBy(1); +// @ts-expect-error +numArr.uniqueBy({}); +// @ts-expect-error +numArr.uniqueBy(true); + +// @ts-expect-error +i8.uniqueBy([]); +// @ts-expect-error +i8.uniqueBy({}); + +// @ts-expect-error +u8.uniqueBy([]); +// @ts-expect-error +u8.uniqueBy(false); + +// @ts-expect-error +u8c.uniqueBy([]); +// @ts-expect-error +u8c.uniqueBy(undefined, 1); + +// @ts-expect-error +i16.uniqueBy([]); +// @ts-expect-error +i16.uniqueBy(function (x: string) { return x; }); + +// @ts-expect-error +u16.uniqueBy([]); +// @ts-expect-error +u16.uniqueBy(false); + +// @ts-expect-error +i32.uniqueBy([]); +// @ts-expect-error +i32.uniqueBy({}); + +// @ts-expect-error +u32.uniqueBy([]); +// @ts-expect-error +u32.uniqueBy(false); + +// @ts-expect-error +f32.uniqueBy([]); +// @ts-expect-error +f32.uniqueBy({}); + +// @ts-expect-error +f64.uniqueBy([]); +// @ts-expect-error +f64.uniqueBy(false); + +// // @ts-expect-error +// bi64.uniqueBy([]); +// // @ts-expect-error +// bi64.uniqueBy({}); +// +// // @ts-expect-error +// bu64.uniqueBy([]); +// // @ts-expect-error +// bu64.uniqueBy({}); diff --git a/tests/type-definitions/global/proposals/async-iteration.test.ts b/tests/type-definitions/global/proposals/async-iteration.test.ts new file mode 100644 index 000000000000..6061830f1a4d --- /dev/null +++ b/tests/type-definitions/global/proposals/async-iteration.test.ts @@ -0,0 +1,8 @@ +import 'core-js/full'; + +const sym: symbol = Symbol.asyncIterator; + +// @ts-expect-error +const bad1: string = Symbol.asyncIterator; +// @ts-expect-error +Symbol['asyncIterator'] = Symbol('other'); diff --git a/tests/type-definitions/global/proposals/async-iterator-helper.es2018.test.ts b/tests/type-definitions/global/proposals/async-iterator-helper.es2018.test.ts new file mode 100644 index 000000000000..13cf8ce18a97 --- /dev/null +++ b/tests/type-definitions/global/proposals/async-iterator-helper.es2018.test.ts @@ -0,0 +1,23 @@ +import 'core-js/full'; + +const aitn = AsyncIterator.from([1]); +for await (const v of aitn) {} + +const ait1 = aitn.filter((v: number, i: number) => v > 0); +for await (const v of ait1) {} + +const ait2 = aitn.flatMap((v: number, i: number) => `${ v }`); +for await (const v of ait2) {} + +const ait3 = aitn.map((v: number, i: number) => v * 2); +for await (const v of ait3) {} + +const ait4 = aitn.take(10); +for await (const v of ait4) {} + +const ait5 = aitn.drop(3); +for await (const v of ait5) {} + +declare const itn: Iterator; +const ait6 = itn.toAsync(); +for await (const v of ait6) {} diff --git a/tests/type-definitions/global/proposals/async-iterator-helper.test.ts b/tests/type-definitions/global/proposals/async-iterator-helper.test.ts new file mode 100644 index 000000000000..0f3864cd2927 --- /dev/null +++ b/tests/type-definitions/global/proposals/async-iterator-helper.test.ts @@ -0,0 +1,106 @@ +import 'core-js/full'; +import from from 'core-js/full/async-iterator/from'; +import drop from 'core-js/full/async-iterator/drop'; +import every from 'core-js/full/async-iterator/every'; +import filter from 'core-js/full/async-iterator/filter'; +import find from 'core-js/full/async-iterator/find'; +import flatMap from 'core-js/full/async-iterator/flat-map'; +import forEach from 'core-js/full/async-iterator/for-each'; +import map from 'core-js/full/async-iterator/map'; +import reduce from 'core-js/full/async-iterator/reduce'; +import some from 'core-js/full/async-iterator/some'; +import take from 'core-js/full/async-iterator/take'; +import toArray from 'core-js/full/async-iterator/to-array'; + +const ait: AsyncIterator = from([1, 2]); +drop(ait, 1); +every(ait, (v: number, i: number) => v > 0); +filter(ait, (v: number, i: number) => v > 0); +find(ait, (v: number, i: number) => v > 0); +flatMap(ait, (v: number, i: number) => [v, v * 2]); +forEach(ait, (v: number, i: number) => { }); +map(ait, (v: number, i: number) => v * 2); +reduce(ait, (acc: number, v: number, i: number) => acc + v, 0); +some(ait, (v: number, i: number) => v > 0); +take(ait, 1); +toArray(ait); + +const res: AsyncIterator = AsyncIterator.from([1, 2, 3]); +const res2: AsyncIterator = AsyncIterator.from(new Set([1, 2, 3])); +AsyncIterator.from((async function * () { + yield 1; + yield 2; +})()); +AsyncIterator.from((function * () { yield 3; })()); +const res3: AsyncIterator = AsyncIterator.from('abc'); + +declare const ain: AsyncIteratorObject; +declare const aio: AsyncIteratorObject<{ x: number }>; +declare const ais: AsyncIteratorObject; +declare const ilb: Iterable; +declare const is: Iterator; +declare const itn: Iterator; +declare const ailb: AsyncIterable; + +AsyncIterator.from(ain); +AsyncIterator.from((async function * () { + yield 1; + yield 2; +})()); +AsyncIterator.from(ilb); +AsyncIterator.from(ailb); +AsyncIterator.from(aio); +AsyncIterator.from(ait); + +// @ts-expect-error +AsyncIterator.from(123); +// @ts-expect-error +AsyncIterator.from({}); +// @ts-expect-error +AsyncIterator.from(); +// @ts-expect-error +AsyncIterator.from({ next: () => 1 }); + +const raits: AsyncIterator = is.toAsync(); +const raitn: AsyncIterator = itn.toAsync(); + +const r1: AsyncIterator = ain.drop(3); +const r2: Promise = ain.every((v: number, i: number) => v > 0); +const r3: AsyncIterator = ain.filter((v: number, i: number) => v > 0); +const r4: Promise = ain.find((v: number, i: number) => v > 0); +const r5: AsyncIterator = ain.flatMap((v: number, i: number) => [v, v * 2]); +const r6: Promise = ain.forEach((v: number, i: number) => { }); +const r7: AsyncIterator = ain.map((v: number, i: number) => v.toString()); +const r8: Promise = ain.reduce((acc: number, v: number, i: number) => acc + v, 0); +const r9: Promise = ain.some((v: number, i: number) => v > 0); +const r10: AsyncIterator = ain.take(10); +const r11: Promise = ain.toArray(); + +// @ts-expect-error +ain.drop(); +// @ts-expect-error +ain.every(); +// @ts-expect-error +ain.filter(); +// @ts-expect-error +ain.find(); +// @ts-expect-error +ain.flatMap(); +// @ts-expect-error +ain.forEach(); +// @ts-expect-error +ain.map(); +// @ts-expect-error +ain.reduce(); +// @ts-expect-error +ain.some(); +// @ts-expect-error +ain.take(); +// @ts-expect-error +ain.toArray(1); + +const s0: Promise = ais.toArray(); +const f0: Promise = ais.find((v: string, i: number) => v.length === 1); + +// @ts-expect-error +ais.map((v: string, i: number) => v.length === 1, 'extra'); diff --git a/tests/type-definitions/global/proposals/await-dictionary.test.ts b/tests/type-definitions/global/proposals/await-dictionary.test.ts new file mode 100644 index 000000000000..e467bb962b72 --- /dev/null +++ b/tests/type-definitions/global/proposals/await-dictionary.test.ts @@ -0,0 +1,71 @@ +import 'core-js/full'; +import allKeyed from 'core-js/full/promise/all-keyed'; +import allSettledKeyed from 'core-js/full/promise/all-settled-keyed'; +import $Promise from 'core-js/full/promise'; + +const sym = Symbol('sym'); +interface CoreJSPromiseResult { + status: string; + value?: T; + reason?: any; +} + +const resNS: Promise<{ a: number, b: string, c: boolean }> = allKeyed({ + a: Promise.resolve(1), + b: Promise.resolve('string'), + c: Promise.resolve(true), +}); +const resNS2: Promise<{ a: number, b: string, c: boolean }> = $Promise.allKeyed({ + a: Promise.resolve(1), + b: Promise.resolve('string'), + c: Promise.resolve(true), +}); +const resNS3: Promise<{ [sym]: CoreJSPromiseResult }> = allSettledKeyed({ + [sym]: Promise.resolve(1), +}); +Promise.allKeyed({ + a: 1, + b: Promise.resolve('string'), + c: 3, +}); + +// @ts-expect-error +allKeyed(); +// @ts-expect-error +allSettledKeyed(); + +const res: Promise<{ a: number, b: string, c: boolean }> = Promise.allKeyed({ + a: Promise.resolve(1), + b: Promise.resolve('string'), + c: Promise.resolve(true), +}); + +const res2: Promise<{ [sym]: number }> = Promise.allKeyed({ + [sym]: Promise.resolve(1), +}); + +// @ts-expect-error +Promise.allKeyed(); +// @ts-expect-error +Promise.allKeyed([Promise.resolve(1), Promise.resolve(2)]); + +const resASK: Promise<{ a: CoreJSPromiseResult, b: CoreJSPromiseResult, c: CoreJSPromiseResult }> = Promise.allSettledKeyed({ + a: Promise.resolve(1), + b: Promise.resolve('string'), + c: Promise.resolve(true), +}); + +const resASK2: Promise<{ [sym]: CoreJSPromiseResult }> = Promise.allSettledKeyed({ + [sym]: Promise.resolve(1), +}); + +Promise.allSettledKeyed({ + a: 1, + b: Promise.resolve('string'), + c: 3, +}); + +// @ts-expect-error +Promise.allSettledKeyed(); +// @ts-expect-error +Promise.allSettledKeyed([Promise.resolve(1), Promise.resolve(2)]); diff --git a/tests/type-definitions/global/proposals/change-array-by-copy.test.ts b/tests/type-definitions/global/proposals/change-array-by-copy.test.ts new file mode 100644 index 000000000000..3a6e7fd0bf81 --- /dev/null +++ b/tests/type-definitions/global/proposals/change-array-by-copy.test.ts @@ -0,0 +1,205 @@ +import 'core-js/es'; +import toSorted from 'core-js/es/array/to-sorted'; +import toSpliced from 'core-js/es/array/to-spliced'; +import toReversed from 'core-js/es/array/to-reversed'; +import withArray from 'core-js/es/array/with'; +import { assertNumberArray, assertStringArray } from '../../helpers/helpers.js'; + +const arr: number[] = [1, 2, 3]; + +assertNumberArray(toSorted(arr)); +assertNumberArray(toSpliced(arr, 1, 1, 4, 5)); +assertNumberArray(toReversed(arr)); +assertNumberArray(withArray(arr, 1, 42)); + +// @ts-expect-error +toSorted(arr, 'not a function'); +// @ts-expect-error +toSpliced(arr, '1', 1); +// @ts-expect-error +toReversed(arr, 1); +// @ts-expect-error +withArray(arr); + +assertNumberArray(arr.toReversed()); +assertNumberArray(arr.toSorted()); +assertNumberArray(arr.toSorted((a, b) => b - a)); +assertNumberArray(arr.toSpliced(1, 1, 4, 5)); +assertNumberArray(arr.toSpliced(1)); +assertNumberArray(arr.toSpliced(1, 2)); +assertNumberArray(arr.with(1, 42)); + +const sarr: string[] = ['a', 'b', 'c']; +assertStringArray(sarr.toReversed()); +assertStringArray(sarr.toSorted()); +assertStringArray(sarr.with(0, 'z')); +assertStringArray(sarr.toSpliced(0, 1, 'x')); + +const i8 = new Int8Array([1, 2, 3]); +const i8Rev: Int8Array = i8.toReversed(); +const i8Sorted: Int8Array = i8.toSorted(); +const i8Sorted2: Int8Array = i8.toSorted((a, b) => b - a); +const i8With: Int8Array = i8.with(0, 10); + +const u8 = new Uint8Array([1, 2, 3]); +const u8Rev: Uint8Array = u8.toReversed(); +const u8Sorted: Uint8Array = u8.toSorted(); +const u8Sorted2: Uint8Array = u8.toSorted((a, b) => a - b); +const u8With: Uint8Array = u8.with(1, 42); + +const u8c = new Uint8ClampedArray([1, 2, 3]); +const u8cRev: Uint8ClampedArray = u8c.toReversed(); +const u8cSorted: Uint8ClampedArray = u8c.toSorted(); +const u8cSorted2: Uint8ClampedArray = u8c.toSorted((a, b) => b - a); +const u8cWith: Uint8ClampedArray = u8c.with(1, 99); + +const i16 = new Int16Array([1, 2, 3]); +const i16Rev: Int16Array = i16.toReversed(); +const i16Sorted: Int16Array = i16.toSorted(); +const i16With: Int16Array = i16.with(1, 2); + +const u16 = new Uint16Array([1, 2, 3]); +const u16Rev: Uint16Array = u16.toReversed(); +const u16Sorted: Uint16Array = u16.toSorted(); +const u16With: Uint16Array = u16.with(1, 2); + +const i32 = new Int32Array([1, 2, 3]); +const i32Rev: Int32Array = i32.toReversed(); +const i32Sorted: Int32Array = i32.toSorted(); +const i32With: Int32Array = i32.with(1, 2); + +const u32 = new Uint32Array([1, 2, 3]); +const u32Rev: Uint32Array = u32.toReversed(); +const u32Sorted: Uint32Array = u32.toSorted(); +const u32With: Uint32Array = u32.with(1, 2); + +const f32 = new Float32Array([1.1, 2.2, 3.3]); +const f32Rev: Float32Array = f32.toReversed(); +const f32Sorted: Float32Array = f32.toSorted(); +const f32With: Float32Array = f32.with(1, 8.8); + +const f64 = new Float64Array([1.1, 2.2, 3.3]); +const f64Rev: Float64Array = f64.toReversed(); +const f64Sorted: Float64Array = f64.toSorted(); +const f64With: Float64Array = f64.with(0, 2.2); + +// todo for es6 +// const bi64 = new (BigInt64Array as { new(arr: ArrayLike): BigInt64Array })([BigInt(1), BigInt(2), BigInt(3)]); +// const bi64Rev: BigInt64Array = bi64.toReversed(); +// const bi64Sorted: BigInt64Array = bi64.toSorted(); +// const bi64Sorted2: BigInt64Array = bi64.toSorted((a, b) => (a > b ? 1 : -1)); +// const bi64With: BigInt64Array = bi64.with(2, BigInt(100)); +// +// const bu64 = new (BigUint64Array as { new(arr: ArrayLike): BigUint64Array })([BigInt(1), BigInt(2), BigInt(3)]); +// const bu64Rev: BigUint64Array = bu64.toReversed(); +// const bu64Sorted: BigUint64Array = bu64.toSorted(); +// const bu64Sorted2: BigUint64Array = bu64.toSorted((a, b) => (a > b ? 1 : -1)); +// const bu64With: BigUint64Array = bu64.with(0, BigInt(50)); + +// @ts-expect-error +arr.toReversed(1); +// @ts-expect-error +arr.toSorted('string'); +// @ts-expect-error +arr.toSorted((a: number, b: string) => 0); +// @ts-expect-error +arr.toSpliced(); +// @ts-expect-error +arr.toSpliced('1', 1); +// @ts-expect-error +arr.toSpliced(1, '1'); +// @ts-expect-error +arr.with(); +// @ts-expect-error +arr.with(1); +// @ts-expect-error +arr.with('1', 2); + +const barr: boolean[] = [true, false]; +// @ts-expect-error +barr.toSorted((a: number, b: number) => 0); +// @ts-expect-error +barr.with(0, 1); + +const arrStr: string[] = ['a', 'b']; +// @ts-expect-error +arrStr.with(0, 1); + +// @ts-expect-error +i8.toReversed(1); +// @ts-expect-error +i8.toSorted(''); +// @ts-expect-error +i8.toSorted((a: string, b: string) => 0); +// @ts-expect-error +i8.with(); +// @ts-expect-error +i8.with('1', 1); +// @ts-expect-error +i8.with(0, '1'); + +// @ts-expect-error +u8.toReversed(1); +// @ts-expect-error +u8.toSorted('str'); +// @ts-expect-error +u8.with(0, 'v'); + +// @ts-expect-error +u8c.toSorted('str'); +// @ts-expect-error +u8c.with(0, '1'); + +// @ts-expect-error +i16.toReversed('1'); +// @ts-expect-error +i16.toSorted((a: string, b: string) => 0); +// @ts-expect-error +i16.with(0, 'a'); + +// @ts-expect-error +u16.toReversed(null); +// @ts-expect-error +u16.toSorted('a'); +// @ts-expect-error +u16.with(0, 'a'); + +// @ts-expect-error +i32.toSorted([]); +// @ts-expect-error +i32.with('test', 1); +// @ts-expect-error +i32.with(1, 'foo'); + +// @ts-expect-error +u32.with('0', 0); +// @ts-expect-error +u32.with(1, 'foo'); + +// @ts-expect-error +f32.toReversed('abc'); +// @ts-expect-error +f32.with(0, 'a'); + +// @ts-expect-error +f64.toSorted(1, 2); +// @ts-expect-error +f64.with('a', 1); + +// // @ts-expect-error +// bi64.toReversed(1); +// // @ts-expect-error +// bi64.toSorted('f'); +// // @ts-expect-error +// bi64.toSorted((a: number, b: number) => 0); +// // @ts-expect-error +// bi64.with(1, 1); +// // @ts-expect-error +// bi64.with('a', BigInt(1)); + +// @ts-expect-error +bu64.toSorted({}); +// @ts-expect-error +bu64.with(0, 1); +// @ts-expect-error +bu64.with('abc', BigInt(1)); diff --git a/tests/type-definitions/global/proposals/collection-of-from.test.ts b/tests/type-definitions/global/proposals/collection-of-from.test.ts new file mode 100644 index 000000000000..94b751ca2ada --- /dev/null +++ b/tests/type-definitions/global/proposals/collection-of-from.test.ts @@ -0,0 +1,97 @@ +import 'core-js/full'; +import mapFrom from 'core-js/full/map/from'; +import mapOf from 'core-js/full/map/of'; +import setFrom from 'core-js/full/set/from'; +import setOf from 'core-js/full/set/of'; +import weakSetFrom from 'core-js/full/weak-set/from'; +import weakSetOf from 'core-js/full/weak-set/of'; +import weakMapFrom from 'core-js/full/weak-map/from'; +import weakMapOf from 'core-js/full/weak-map/of'; + +const arrEntries: Array<[string, number]> = [['a', 1], ['b', 2]]; + +const resNS: Map = mapFrom(arrEntries, ([k, v]) => [k, String(v)]); +const resNS2: Map = mapOf(['a', 1], ['b', 2]); + +const res: Map = Map.from(arrEntries, ([k, v]) => [k, String(v)]); +const res2: Map = Map.from(arrEntries, ([k, v]) => [k, v > 1]); +const res3: Map = Map.from(arrEntries); +const res4: Map = Map.of(['a', 1], ['b', 2]); + +const resNS3: Set = setFrom([1, 2, 3], v => v * 2); +const resNS4: Set = setOf('a', 'b', 'c'); + +const res5: Set = Set.from(['a', 'b', 'c']); +const res6: Set = Set.from([1, 2, 3], v => v * 2); +const res7: Set = Set.from(['a', 'b', 'c'], String); +const res8: Set = Set.of(1, 2, 3); + +const ws1 = {}; +const ws2 = {}; +const wsArr = [ws1, ws2]; + +const resNS5: WeakSet = weakSetFrom(wsArr); +const resNS6: WeakSet = weakSetOf(ws1, ws2); + +const res9: WeakSet<{ a?: number }> = WeakSet.from(wsArr); +const res10: WeakSet = WeakSet.from(wsArr, x => x); +const res11: WeakSet = WeakSet.of(ws1, ws2); + +const wmArr: Array<[object, string]> = [[ws1, 'a'], [ws2, 'b']]; + +const resNS7: WeakMap = weakMapFrom(wmArr); +const resNS8: WeakMap = weakMapOf([ws1, 1], [ws2, 2]); + +const res12: WeakMap = WeakMap.from(wmArr); +const res13: WeakMap = WeakMap.from(wmArr, ([k, v]) => [k, Number(v.length)]); +const res14: WeakMap = WeakMap.of([ws1, 'a'], [ws2, 'b']); + +// @ts-expect-error +Map.from(); +// @ts-expect-error +Map.from(123); +// @ts-expect-error +Map.from([1, 2, 3]); +// @ts-expect-error +Map.from(arrEntries, (a, b, c) => a); +// @ts-expect-error +Map.of(1, 2, 3); +// @ts-expect-error +Map.of(['a', 1], [2, 3, 4]); + +// @ts-expect-error +Set.from(); +// @ts-expect-error +Set.from(123); +// @ts-expect-error +Set.from(['a', 'b'], 42); +// @ts-expect-error +Set.from(['a'], (value, index, extra) => value); +// @ts-expect-error +Set.of(1, 2, {}); + +// @ts-expect-error +WeakSet.from([1, 2]); +// @ts-expect-error +WeakSet.from('notiterable'); +// @ts-expect-error +WeakSet.from(wsArr, 42); +// @ts-expect-error +WeakSet.of(1, 2); +// @ts-expect-error +WeakSet.of('a'); +// @ts-expect-error +WeakSet.of({}, 42); + +// @ts-expect-error +WeakMap.from([[1, 'a'], [2, 'b']]); +// @ts-expect-error +WeakMap.from([['a', 1]]); +// @ts-expect-error +WeakMap.from(wmArr, (v, k, x) => v); +// @ts-expect-error +WeakMap.of([{}, 'a'], [{}, 'b', 3]); +// @ts-expect-error +WeakMap.of([1, 2]); +// @ts-expect-error +WeakMap.of(['a', 'b']); diff --git a/tests/type-definitions/global/proposals/data-view-get-set-uint8-clamped.test.ts b/tests/type-definitions/global/proposals/data-view-get-set-uint8-clamped.test.ts new file mode 100644 index 000000000000..da6e0703bfaa --- /dev/null +++ b/tests/type-definitions/global/proposals/data-view-get-set-uint8-clamped.test.ts @@ -0,0 +1,21 @@ +import 'core-js/full'; + +declare const dv: DataView; + +const rdv: number = dv.getUint8Clamped(0); +dv.setUint8Clamped(0, 255); + +// @ts-expect-error +dv.getUint8Clamped(); +// @ts-expect-error +dv.getUint8Clamped('0'); +// @ts-expect-error +dv.getUint8Clamped(0, 2); +// @ts-expect-error +dv.setUint8Clamped(0); +// @ts-expect-error +dv.setUint8Clamped('0', 2); +// @ts-expect-error +dv.setUint8Clamped(0, '2'); +// @ts-expect-error +dv.setUint8Clamped(); diff --git a/tests/type-definitions/global/proposals/decorator-metadata.test.ts b/tests/type-definitions/global/proposals/decorator-metadata.test.ts new file mode 100644 index 000000000000..0709439a8442 --- /dev/null +++ b/tests/type-definitions/global/proposals/decorator-metadata.test.ts @@ -0,0 +1,18 @@ +import 'core-js/full'; + +const rsmd1: symbol = Symbol.metadata; +const rsmd2: typeof Symbol.metadata = Symbol.metadata; + +interface T { + [Symbol.metadata]?: object; +} + +const obj: T = {}; +obj[Symbol.metadata] = { foo: 1 }; + +const maybeMeta: object | undefined = obj[Symbol.metadata]; + +// @ts-expect-error +Symbol['metadata'] = Symbol('other'); +// @ts-expect-error +obj[Symbol.metadata] = 123; diff --git a/tests/type-definitions/global/proposals/error-cause.test.ts b/tests/type-definitions/global/proposals/error-cause.test.ts new file mode 100644 index 000000000000..95f33ef3bfdc --- /dev/null +++ b/tests/type-definitions/global/proposals/error-cause.test.ts @@ -0,0 +1,35 @@ +import 'core-js/es'; + +const prevError = new Error('Prev error'); + +const resE1: Error = new Error('Error with cause', { cause: prevError }); +const resE2: Error = new Error('Error with cause', { cause: null }); +const resE3: Error = new Error('Error with cause', { cause: 'prev reason' }); + +const resEE1: EvalError = new EvalError('Error with cause', { cause: prevError }); +const resEE2: EvalError = new EvalError('Error with cause', { cause: null }); +const resEE3: EvalError = new EvalError('Error with cause', { cause: 'prev reason' }); + +const resRE1: RangeError = new RangeError('Error with cause', { cause: prevError }); +const resRE2: RangeError = new RangeError('Error with cause', { cause: null }); +const resRE3: RangeError = new RangeError('Error with cause', { cause: 'prev reason' }); + +const resReE1: ReferenceError = new ReferenceError('Error with cause', { cause: prevError }); +const resReE2: ReferenceError = new ReferenceError('Error with cause', { cause: null }); +const resReE3: ReferenceError = new ReferenceError('Error with cause', { cause: 'prev reason' }); + +const resSE1: SyntaxError = new SyntaxError('Error with cause', { cause: prevError }); +const resSE2: SyntaxError = new SyntaxError('Error with cause', { cause: null }); +const resSE3: SyntaxError = new SyntaxError('Error with cause', { cause: 'prev reason' }); + +const resTE1: TypeError = new TypeError('Error with cause', { cause: prevError }); +const resTE2: TypeError = new TypeError('Error with cause', { cause: null }); +const resTE3: TypeError = new TypeError('Error with cause', { cause: 'prev reason' }); + +const resUE1: URIError = new URIError('Error with cause', { cause: prevError }); +const resUE2: URIError = new URIError('Error with cause', { cause: null }); +const resUE3: URIError = new URIError('Error with cause', { cause: 'prev reason' }); + +const resAE1: AggregateError = new AggregateError([resUE1, resUE2], 'Error with cause', { cause: prevError }); +const resAE2: AggregateError = new AggregateError([resUE1, resUE2], 'Error with cause', { cause: null }); +const resAE3: AggregateError = new AggregateError([resUE1, resUE2], 'Error with cause', { cause: 'prev reason' }); diff --git a/tests/type-definitions/global/proposals/explicit-resource-management.test.ts b/tests/type-definitions/global/proposals/explicit-resource-management.test.ts new file mode 100644 index 000000000000..2ca8c02d5bd0 --- /dev/null +++ b/tests/type-definitions/global/proposals/explicit-resource-management.test.ts @@ -0,0 +1,104 @@ +import 'core-js/es'; + +const d: symbol = Symbol.dispose; +const ad: symbol = Symbol.asyncDispose; + +// @ts-expect-error +const wrong: number = Symbol.dispose; +// @ts-expect-error +Symbol['dispose'] = Symbol('foo'); +// @ts-expect-error +Symbol['asyncDispose'] = Symbol('bar'); + +const objD: Disposable = { + [Symbol.dispose]() { /* empty */ }, +}; +objD[Symbol.dispose](); + +// @ts-expect-error +objD.dispose(); + +const objAD: AsyncDisposable = { + [Symbol.asyncDispose]() { return Promise.resolve(); }, +}; +objAD[Symbol.asyncDispose](); + +// @ts-expect-error +objAD.asyncDispose(); + +const err1 = new SuppressedError('err', 'suppressed', 'msg'); +err1.error; +err1.suppressed; +const m1: string = err1.message; +const _: Error = err1; + +const err2 = SuppressedError(123, 456); +err2.error; +err2.suppressed; +err2.message; + +const proto: SuppressedError = SuppressedError.prototype; + +// @ts-expect-error +new SuppressedError(1, 2, 3, 4); + +const protoDS: DisposableStack = DisposableStack.prototype; +const objDS: DisposableStack = new DisposableStack(); +const disposed: boolean = objDS.disposed; +objDS.dispose(); +const ruse1: Disposable = objDS.use(objD); +const ruse2: null = objDS.use(null); +const ruse3: undefined = objDS.use(undefined); +const radopt1: string = objDS.adopt('foo', (value: string) => { /* empty */ }); +objDS.defer(() => { /* empty */ }); +const rmove1: DisposableStack = objDS.move(); +objDS[Symbol.dispose](); +const rts1: string = objDS[Symbol.toStringTag]; + +// @ts-expect-error +objDS.dispose(1); +// @ts-expect-error +objDS.use('foo'); +// @ts-expect-error +objDS.defer('bar'); +// @ts-expect-error +objDS.move(1); +// @ts-expect-error +objDS[Symbol.toStringTag] = 'foo'; + +const protoADS: AsyncDisposableStack = AsyncDisposableStack.prototype; +const objADS: AsyncDisposableStack = new AsyncDisposableStack(); +const disposedASD: boolean = objDS.disposed; +const rda: Promise = objADS.disposeAsync(); +const ruseASD1: AsyncDisposable = objADS.use(objAD); +const ruseASD2: Disposable = objADS.use(objD); +const ruseASD3: null = objADS.use(null); +const ruseASD4: undefined = objADS.use(undefined); +const radoptASD1: string = objADS.adopt('foo', (value: string) => { /* empty */ }); +const radoptASD2: string = objADS.adopt('foo', async (value: string) => { /* empty */ }); +const radoptASD3: string = objADS.adopt('foo', (value: string) => Promise.resolve()); +const radoptASD4: string = objADS.adopt('foo', async (value: string) => Promise.resolve()); +objADS.defer(() => { /* empty */ }); +objADS.defer(async () => { /* empty */ }); +objADS.defer(() => Promise.resolve()); +objADS.defer(async () => Promise.resolve()); +const rmoveASD1: AsyncDisposableStack = objADS.move(); +objADS[Symbol.asyncDispose](); +const rtsASD1: string = objADS[Symbol.toStringTag]; + +// @ts-expect-error +objADS.disposeAsync(1).then(); +// @ts-expect-error +objADS.use('foo').then(); +// @ts-expect-error +objADS.defer('bar'); +// @ts-expect-error +objADS.move(1); +// @ts-expect-error +objADS[Symbol.toStringTag] = 'foo'; + +declare const iter: IteratorObject; +iter[Symbol.dispose](); + +declare const asyncIter: AsyncIteratorObject; +asyncIter[Symbol.asyncDispose](); diff --git a/tests/type-definitions/global/proposals/extractors.test.ts b/tests/type-definitions/global/proposals/extractors.test.ts new file mode 100644 index 000000000000..60ccb33430b5 --- /dev/null +++ b/tests/type-definitions/global/proposals/extractors.test.ts @@ -0,0 +1,9 @@ +import 'core-js/full'; + +const rscs1: symbol = Symbol.customMatcher; +const rscs2: typeof Symbol.customMatcher = Symbol.customMatcher; + +// @ts-expect-error +Symbol['customMatcher'] = Symbol('other'); +// @ts-expect-error +const n: number = Symbol.customMatcher; diff --git a/tests/type-definitions/global/proposals/float16.test.ts b/tests/type-definitions/global/proposals/float16.test.ts new file mode 100644 index 000000000000..61b7f45e50b6 --- /dev/null +++ b/tests/type-definitions/global/proposals/float16.test.ts @@ -0,0 +1,25 @@ +import 'core-js/es'; +import f16round from 'core-js/es/math/f16round'; +import { assertNumber } from '../../helpers/helpers.js'; + +assertNumber(f16round(1)); +// @ts-expect-error +f16round('123'); + +assertNumber(Math.f16round(1)); + +// @ts-expect-error +Math.f16round('123'); + +const view = new DataView(new ArrayBuffer(4)); +view.setFloat16(0, 1.5); +assertNumber(view.getFloat16(0)); + +// @ts-expect-error +view.setFloat16(0, '123'); +// @ts-expect-error +view.getFloat16('123'); +// @ts-expect-error +view.getFloat16(0, '123'); +// @ts-expect-error +view.setFloat16(0, 1.5, '123'); diff --git a/tests/type-definitions/global/proposals/function-demethodize.test.ts b/tests/type-definitions/global/proposals/function-demethodize.test.ts new file mode 100644 index 000000000000..cd4b6f3edac5 --- /dev/null +++ b/tests/type-definitions/global/proposals/function-demethodize.test.ts @@ -0,0 +1,16 @@ +import 'core-js/full'; +import demethodize from 'core-js/full/function/demethodize'; + +function sumTo(this: { base: number }, a: number, b: number): number { + return this.base + a + b; +} +const sumToD = sumTo.demethodize(); +const sumToDNS = demethodize(sumTo); +const rsumd: number = sumToD({ base: 1 }, 2, 3); +// @ts-expect-error +sumToD(2, 3); + +const sliceD: (thisArg: string, start: number, end?: number) => string = String.prototype.slice.demethodize(); +const rs = sliceD('foobar', 1, 3); +// @ts-expect-error +sliceD(); diff --git a/tests/type-definitions/global/proposals/is-error.test.ts b/tests/type-definitions/global/proposals/is-error.test.ts new file mode 100644 index 000000000000..ef0ed8e75201 --- /dev/null +++ b/tests/type-definitions/global/proposals/is-error.test.ts @@ -0,0 +1,18 @@ +import 'core-js/es'; +import isError from 'core-js/es/error/is-error'; +import { assertBool } from '../../helpers/helpers.js'; + +const e = new Error(); +const ne = { foo: 1 }; + +assertBool(isError(e)); +// @ts-expect-error +isError(); + +assertBool(Error.isError(e)); +Error.isError(ne); +Error.isError(undefined); +Error.isError('str'); + +// @ts-expect-error +Error.isError(); diff --git a/tests/type-definitions/global/proposals/iterator-chunking.test.ts b/tests/type-definitions/global/proposals/iterator-chunking.test.ts new file mode 100644 index 000000000000..773f357233fe --- /dev/null +++ b/tests/type-definitions/global/proposals/iterator-chunking.test.ts @@ -0,0 +1,35 @@ +import 'core-js/full'; +import chunks from 'core-js/full/iterator/chunks'; +import windows from 'core-js/full/iterator/windows'; + +declare function getNumberIterator(): Iterator; + +const numbersIter = getNumberIterator(); + +const res1: Iterator = chunks(numbersIter, 2); +const res2: Iterator = windows(numbersIter, 4); + +// @ts-expect-error +chunks(); +// @ts-expect-error +windows(); + +const res3: Iterator = numbersIter.chunks(2); +const res4: Iterator = numbersIter.windows(4); + +const chunkNext = res1.next(); +const windowsNext = res2.next(); + +// @ts-expect-error +numbersIter.chunks(); +// @ts-expect-error +numbersIter.chunks('2'); +// @ts-expect-error +numbersIter.chunks(2, 3); + +// @ts-expect-error +numbersIter.windows(); +// @ts-expect-error +numbersIter.windows({}); +// @ts-expect-error +numbersIter.windows(4, 1); diff --git a/tests/type-definitions/global/proposals/iterator-helpers.test.ts b/tests/type-definitions/global/proposals/iterator-helpers.test.ts new file mode 100644 index 000000000000..e3594e16af43 --- /dev/null +++ b/tests/type-definitions/global/proposals/iterator-helpers.test.ts @@ -0,0 +1,117 @@ +import 'core-js/es'; +import map from 'core-js/es/iterator/map'; +import filter from 'core-js/es/iterator/filter'; +import take from 'core-js/es/iterator/take'; +import drop from 'core-js/es/iterator/drop'; +import flatMap from 'core-js/es/iterator/flat-map'; +import reduce from 'core-js/es/iterator/reduce'; +import forEach from 'core-js/es/iterator/for-each'; +import some from 'core-js/es/iterator/some'; +import every from 'core-js/es/iterator/every'; +import find from 'core-js/es/iterator/find'; +import { assertBool, assertNumber, assertNumberArray, assertString } from '../../helpers/helpers.js'; + +declare const it: Iterator; +declare const itStr: Iterator; +declare const itNumStr: Iterator; + +const mappedNumNS: Iterator = map(it, n => n + 1); + +const mappedStr: Iterator = it.map((v, i) => String(v)); +const mappedNum: Iterator = it.map(n => n + 1); + +// @ts-expect-error +it.map(); +// @ts-expect-error +it.map((v, i, extra) => v + i + extra); + +const onlyEvenNS: Iterator = filter(it, v => v % 2 === 0); + +const onlyEven: Iterator = it.filter(v => v % 2 === 0); +const filtered: Iterator = it.filter((v): v is number => typeof v === 'number'); + +// @ts-expect-error +it.filter(); +// @ts-expect-error +it.filter((v, i, extra) => true); + +const takenNS: Iterator = take(it, 5); + +const taken: Iterator = it.take(5); + +// @ts-expect-error +it.take(); +// @ts-expect-error +it.take('5'); + +const droppedNS: Iterator = drop(it, 3); + +const dropped: Iterator = it.drop(3); + +// @ts-expect-error +it.drop('3'); + +const flatMappedNS: Iterator = flatMap(it, (v, i) => itStr); + +const flatMapped: Iterator = it.flatMap((v, i) => itStr); +const flatMapped2: Iterator = it.flatMap((v, i) => ({ + [Symbol.iterator]: function * () { + yield String(v); + }, +})); + +// @ts-expect-error +it.flatMap(); + +assertNumber(reduce(it, (a, b, c) => a + b + c)); + +assertNumber(it.reduce((a, b, c) => a + b + c)); +assertNumber(it.reduce((a, b, c) => a + b + c, 0)); +assertString(it.reduce( + (acc: string, val) => acc + val, + '', +)); + +// @ts-expect-error +it.reduce(); +// @ts-expect-error +it.reduce((a, b, c, d) => a); + +assertNumberArray(it.toArray()); + +forEach(it, (value, idx) => { + const x: number = value; + const y: number = idx; +}); + +it.forEach((value, idx) => { + const x: number = value; + const y: number = idx; +}); + +// @ts-expect-error +it.forEach(); + +assertBool(some(it, (v, i) => v > 0)); +assertBool(it.some((v, i) => v > 0)); + +// @ts-expect-error +it.some(); +// @ts-expect-error +it.some((v, i, extra) => true); + +assertBool(every(it, (v, i) => v > 0)); +assertBool(it.every((v, i) => v > 0)); + +// @ts-expect-error +it.every(); +// @ts-expect-error +it.every((v, i, extra) => true); + +const found1NS: number | undefined = find(it, (v, i) => v > 5); + +const found1: number | undefined = it.find((v, i) => v > 5); +const findString: string | number | undefined = itNumStr.find((v): v is string => typeof v === 'string'); + +// @ts-expect-error +it.find(); diff --git a/tests/type-definitions/global/proposals/iterator-join.test.ts b/tests/type-definitions/global/proposals/iterator-join.test.ts new file mode 100644 index 000000000000..ddcf677a4274 --- /dev/null +++ b/tests/type-definitions/global/proposals/iterator-join.test.ts @@ -0,0 +1,22 @@ +import 'core-js/full'; +import join from 'core-js/full/iterator/join'; +import { assertString } from '../../helpers/helpers.js'; + +declare const it: Iterator; + +assertString(join(it, ' ')); + +// @ts-expect-error +join(it, '+', '_'); + +assertString(it.join()); +assertString(it.join(' ')); +assertString(it.join(5)); +assertString(it.join(Symbol('x'))); +assertString(it.join(undefined)); +assertString(it.join(null)); + +// @ts-expect-error +it.join('+', '_'); +// @ts-expect-error +const res7: number = it.join(); diff --git a/tests/type-definitions/global/proposals/iterator-joint.test.ts b/tests/type-definitions/global/proposals/iterator-joint.test.ts new file mode 100644 index 000000000000..5782173d9292 --- /dev/null +++ b/tests/type-definitions/global/proposals/iterator-joint.test.ts @@ -0,0 +1,28 @@ +import 'core-js/actual'; +import zip from 'core-js/actual/iterator/zip'; +import zipKeyed from 'core-js/actual/iterator/zip-keyed'; +import $Iterator from 'core-js/actual/iterator'; + +zip([[1, 2, 3], [4, 5, 6]]); +$Iterator.zip([[1, 2, 3], [4, 5, 6]]); +zipKeyed({ a: [1, 2, 3], b: [4, 5, 6] }); +$Iterator.zipKeyed({ a: [1, 2, 3], b: [4, 5, 6] }); + +Iterator.zip([[1, 2, 3], [4, 5, 6]]); +Iterator.zip([['a', 'b', 'c'], ['d', 'e', 'f']]); +Iterator.zip([[1, 2, 3], [4, 5, 6]], { mode: 'shortest' }); +Iterator.zip([[1, 2, 3], [4, 5, 6]], { mode: 'strict' }); +Iterator.zipKeyed({ a: [1, 2, 3], b: [4, 5, 6] }); +Iterator.zipKeyed({ a: ['a', 'b', 'c', 'd'], b: ['e', 'f'] }, { mode: 'shortest' }); +Iterator.zipKeyed({ a: [1, 2, 3], b: [4, 5, 6] }, { mode: 'strict' }); + +// @ts-expect-error +Iterator.zip(true); +// @ts-expect-error +Iterator.zip([[1, 2, 3], [4, 5, 6]], { mode: 'incorrect' }); +// @ts-expect-error +Iterator.zip([[1, 2, 3], [4, 5, 6]], { mode: 'invalid' }); +// @ts-expect-error +Iterator.zipKeyed(42); +// @ts-expect-error +Iterator.zipKeyed({ a: [1, 2, 3], b: [4, 5, 6] }, { foo: 'bar' }); diff --git a/tests/type-definitions/global/proposals/iterator-range.test.ts b/tests/type-definitions/global/proposals/iterator-range.test.ts new file mode 100644 index 000000000000..03ae49f0962a --- /dev/null +++ b/tests/type-definitions/global/proposals/iterator-range.test.ts @@ -0,0 +1,25 @@ +import 'core-js/full'; +import range from 'core-js/full/iterator/range'; + +const res: Iterator = range(1, 10); + +// @ts-expect-error +Iterator.range(0, 'not-a-number'); + +const rir1: Iterator = Iterator.range(1, 10); +Iterator.range(1, 10, 1); +Iterator.range(1, 10, { step: 1 }); +Iterator.range(1, 10, { inclusive: true }); +// TODO for es6 +// const rir2: Iterator< bigint> = Iterator.range(BigInt(0), BigInt(10), { step: BigInt(2), inclusive: true }); + +// @ts-expect-error +Iterator.range(0, 10, 'not-a-number'); +// @ts-expect-error +Iterator.range(0, 10, { step: BigInt(1) }); +// @ts-expect-error +Iterator.range(0, 10, { inclusive: 3 }); +// @ts-expect-error +Iterator.range(0, 10, { step: 'smth' }); +// @ts-expect-error +Iterator.range(0, 10, { foo: 'bar' }); diff --git a/tests/type-definitions/global/proposals/iterator-sequencing.test.ts b/tests/type-definitions/global/proposals/iterator-sequencing.test.ts new file mode 100644 index 000000000000..55bc2d864e84 --- /dev/null +++ b/tests/type-definitions/global/proposals/iterator-sequencing.test.ts @@ -0,0 +1,27 @@ +import 'core-js/es'; +import concat from 'core-js/es/iterator/concat'; + +declare const its1: Iterable; +declare const arrs: string[]; +declare const arrn: number[]; +declare const arrb: boolean[]; +declare const itb1: Iterable; + +const resNS: Iterator = concat(arrn); + +// @ts-expect-error +concat(1); + +const ri1: Iterator = Iterator.concat(its1); +const ri2: Iterator = Iterator.concat(arrs); +const ri3: Iterator = Iterator.concat(arrn); +const ri4: Iterator = Iterator.concat(arrb, itb1); +const ri5: Iterator = Iterator.concat(); +const ri6: Iterator = Iterator.concat(arrs, arrn); + +// @ts-expect-error +Iterator.concat(1); +// @ts-expect-error +Iterator.concat(true); +// @ts-expect-error +Iterator.concat({}); diff --git a/tests/type-definitions/global/proposals/json-parse-with-source.test.ts b/tests/type-definitions/global/proposals/json-parse-with-source.test.ts new file mode 100644 index 000000000000..71c0f00a301d --- /dev/null +++ b/tests/type-definitions/global/proposals/json-parse-with-source.test.ts @@ -0,0 +1,37 @@ +import 'core-js/es'; +import rawJSON from 'core-js/es/json/raw-json'; +import isRawJSON from 'core-js/es/json/is-raw-json'; +import { assertBool } from '../../helpers/helpers.js'; + +const resNS: CoreJSRawJSON = rawJSON('{"a":123}'); +assertBool(isRawJSON(resNS)); + +// @ts-expect-error +rawJSON(); +// @ts-expect-error +isRawJSON(); + +const r: CoreJSRawJSON = JSON.rawJSON('{"a":123}'); + +assertBool(JSON.isRawJSON(r)); +assertBool(JSON.isRawJSON({})); +assertBool(JSON.isRawJSON('abc')); +assertBool(JSON.isRawJSON(undefined)); + +declare const smth: unknown; + +if (JSON.isRawJSON(smth)) { + smth.rawJSON; + const s: string = smth.rawJSON; + // @ts-expect-error + smth.noProp; +} + +// @ts-expect-error +JSON.rawJSON(123); +// @ts-expect-error +JSON.rawJSON(); + +JSON.parse('{"tooBigForNumber":9007199254740993}', (key: string, value: any, context: CoreJSReviverContext) => {}); +// @ts-expect-error +JSON.parse('{"tooBigForNumber":9007199254740993}', (key: string, value: any, context: []) => {}); diff --git a/tests/type-definitions/global/proposals/map-upsert.test.ts b/tests/type-definitions/global/proposals/map-upsert.test.ts new file mode 100644 index 000000000000..894e10c92e5f --- /dev/null +++ b/tests/type-definitions/global/proposals/map-upsert.test.ts @@ -0,0 +1,41 @@ +import 'core-js/es'; +import mapGetOrInsert from 'core-js/es/map/get-or-insert'; +import mapGetOrInsertComputed from 'core-js/es/map/get-or-insert-computed'; +import wMapGetOrInsert from 'core-js/es/weak-map/get-or-insert'; +import wMapGetOrInsertComputed from 'core-js/es/weak-map/get-or-insert-computed'; +import { assertBool, assertNumber } from '../../helpers/helpers.js'; + +declare const map: Map; + +assertNumber(mapGetOrInsert(map, 'a', 10)); +assertNumber(mapGetOrInsertComputed(map, 'b', k => k.length)); + +assertNumber(map.getOrInsert('x', 42)); +assertNumber(map.getOrInsertComputed('y', k => k.length)); + +// @ts-expect-error +mapGetOrInsert(map, 1, 2); +// @ts-expect-error +mapGetOrInsertComputed(map, 'x', (k: number) => k + 1); + +// @ts-expect-error +map.getOrInsert(1, 2); +// @ts-expect-error +map.getOrInsert('x'); +// @ts-expect-error +map.getOrInsertComputed('x', (k: number) => k + 1); + +declare const wmap: WeakMap<{ id: number }, boolean>; + +assertBool(wMapGetOrInsert(wmap, { id: 1 }, true)); +wMapGetOrInsertComputed(wmap, { id: 2 }, obj => obj.id === 2); + +assertBool(wmap.getOrInsert({ id: 1 }, true)); +wmap.getOrInsertComputed({ id: 2 }, obj => obj.id === 2); + +// @ts-expect-error +wmap.getOrInsert(123, true); +// @ts-expect-error +wmap.getOrInsert({ id: 1 }); +// @ts-expect-error +wmap.getOrInsertComputed({ id: 1 }, (obj: string) => true); diff --git a/tests/type-definitions/global/proposals/math-sum.test.ts b/tests/type-definitions/global/proposals/math-sum.test.ts new file mode 100644 index 000000000000..69b00c6486f1 --- /dev/null +++ b/tests/type-definitions/global/proposals/math-sum.test.ts @@ -0,0 +1,19 @@ +import 'core-js/es'; +import sumPrecise from 'core-js/es/math/sum-precise'; +import { assertNumber } from '../../helpers/helpers.js'; + +declare const it: Iterable; + +assertNumber(sumPrecise(it)); + +assertNumber(Math.sumPrecise(it)); +assertNumber(Math.sumPrecise([1, 2])); + +// @ts-expect-error +sumPrecise('10'); + +// @ts-expect-error +Math.sumPrecise('10'); +// @ts-expect-error +Math.sumPrecise(1, 2); + diff --git a/tests/type-definitions/global/proposals/number-clamp.test.ts b/tests/type-definitions/global/proposals/number-clamp.test.ts new file mode 100644 index 000000000000..85db8bdb5837 --- /dev/null +++ b/tests/type-definitions/global/proposals/number-clamp.test.ts @@ -0,0 +1,15 @@ +import 'core-js/full'; +import clamp from 'core-js/full/number/clamp'; +import { assertNumber } from '../../helpers/helpers.js'; + +declare const num: number; + +assertNumber(num.clamp(0, 100)); +assertNumber(clamp(num, 0, 100)); + +// @ts-expect-error +clamp(num); +// @ts-expect-error +num.clamp(); +// @ts-expect-error +num.clamp('1', '2'); diff --git a/tests/type-definitions/global/proposals/object-from-entries.test.ts b/tests/type-definitions/global/proposals/object-from-entries.test.ts new file mode 100644 index 000000000000..6c6fd0dec0c6 --- /dev/null +++ b/tests/type-definitions/global/proposals/object-from-entries.test.ts @@ -0,0 +1,29 @@ +import 'core-js/es'; +import fromEntries from 'core-js/es/object/from-entries'; + +declare const objEntries: Iterable; +declare const mixedEntries: Iterable; +declare const wrongEntries1: Iterable; +declare const wrongEntries2: number; +declare const notIterable: {}; + +const rNS1: { [k: string]: number } = fromEntries(objEntries); + +const r1: { [k: string]: number } = Object.fromEntries(objEntries); +const r2: any = Object.fromEntries(mixedEntries); +const r3: any = Object.fromEntries([['a', 1], ['b', 2]]); +const r4: object = Object.fromEntries(new Map([['x', 1], ['y', 2]])); + +// @ts-expect-error +fromEntries(); + +// @ts-expect-error +Object.fromEntries(); +// @ts-expect-error +Object.fromEntries(123); +// @ts-expect-error +Object.fromEntries(wrongEntries1); +// @ts-expect-error +Object.fromEntries(wrongEntries2); +// @ts-expect-error +Object.fromEntries(notIterable); diff --git a/tests/type-definitions/global/proposals/object-get-own-property-descriptors.test.ts b/tests/type-definitions/global/proposals/object-get-own-property-descriptors.test.ts new file mode 100644 index 000000000000..ed3a30e7b200 --- /dev/null +++ b/tests/type-definitions/global/proposals/object-get-own-property-descriptors.test.ts @@ -0,0 +1,26 @@ +import 'core-js/es'; +import getOwnPropertyDescriptors from 'core-js/es/object/get-own-property-descriptors'; + +const obj = { a: 1, b: 'x', c: true }; + +const objDescsNS: { a: TypedPropertyDescriptor; b: TypedPropertyDescriptor; c: TypedPropertyDescriptor } & + { [x: string]: PropertyDescriptor } = getOwnPropertyDescriptors(obj); + +const objDescs: { a: TypedPropertyDescriptor; b: TypedPropertyDescriptor; c: TypedPropertyDescriptor } & + { [x: string]: PropertyDescriptor } = Object.getOwnPropertyDescriptors(obj); + +class Foo { + bar = 42; + baz() {} +} +const foo = new Foo(); + +const fooDescs: { bar: TypedPropertyDescriptor; baz: TypedPropertyDescriptor<() => void> } & + { [x: string]: PropertyDescriptor } = Object.getOwnPropertyDescriptors(foo); +const descsAny = Object.getOwnPropertyDescriptors({ x: 1, y: 2 }); + +// @ts-expect-error +getOwnPropertyDescriptors(); + +// @ts-expect-error +Object.getOwnPropertyDescriptors(); diff --git a/tests/type-definitions/global/proposals/object-keys-length.test.ts b/tests/type-definitions/global/proposals/object-keys-length.test.ts new file mode 100644 index 000000000000..21d587f56422 --- /dev/null +++ b/tests/type-definitions/global/proposals/object-keys-length.test.ts @@ -0,0 +1,34 @@ +import 'core-js/full'; +import keysLength from 'core-js/full/object/keys-length'; +import { assertNumber } from '../../helpers/helpers.js'; + +const obj = { a: 1, b: 2 }; +const arr = [1, 2, 3]; +const strArr = ['a', 'b', 'c']; +const arrLike: ArrayLike = { 0: 10, 1: 20, length: 2 }; +const emptyObj = {}; +const string = 'abc'; + +assertNumber(keysLength(obj)); +assertNumber(keysLength(arr)); +assertNumber(keysLength(strArr)); +assertNumber(keysLength(arrLike)); +assertNumber(keysLength(emptyObj)); +assertNumber(keysLength(string)); + +assertNumber(Object.keysLength(obj)); +assertNumber(Object.keysLength(arr)); +assertNumber(Object.keysLength(strArr)); +assertNumber(Object.keysLength(arrLike)); +assertNumber(Object.keysLength(emptyObj)); +assertNumber(Object.keysLength(string)); + +// @ts-expect-error +keysLength(); +// @ts-expect-error +keysLength(null); + +// @ts-expect-error +Object.keysLength(); +// @ts-expect-error +Object.keysLength(null); diff --git a/tests/type-definitions/global/proposals/object-values-entries.test.ts b/tests/type-definitions/global/proposals/object-values-entries.test.ts new file mode 100644 index 000000000000..8cae22a00994 --- /dev/null +++ b/tests/type-definitions/global/proposals/object-values-entries.test.ts @@ -0,0 +1,39 @@ +import 'core-js/es'; +import values from 'core-js/es/object/values'; +import entries from 'core-js/es/object/entries'; +import { assertNumberArray, assertStringArray } from '../../helpers/helpers.js'; + +const obj = { a: 1, b: 2 }; +const arr = [1, 2, 3]; +const strArr = ['a', 'b', 'c']; +const arrLike: ArrayLike = { 0: 10, 1: 20, length: 2 }; +const emptyObj = {}; + +assertNumberArray(values(obj)); + +assertNumberArray(Object.values(obj)); +assertNumberArray(Object.values(arr)); +assertStringArray(Object.values(strArr)); +assertNumberArray(Object.values(arrLike)); +const res: any[] = Object.values(emptyObj); + +const entriesNS: [string, number][] = entries(obj); + +const entries1: [string, number][] = Object.entries(obj); +const entries2: [string, number][] = Object.entries(arr); +const entries3: [string, string][] = Object.entries(strArr); +const entries4: [string, number][] = Object.entries(arrLike); +const entries5: [string, any][] = Object.entries(emptyObj); + +const valuesAnyArr: any[] = Object.values({ foo: 123, bar: 'baz' }); +const entriesAnyArr: [string, any][] = Object.entries({ foo: 123, bar: 'baz' }); + +// @ts-expect-error +values(); +// @ts-expect-error +entries(); + +// @ts-expect-error +Object.values(); +// @ts-expect-error +Object.entries(); diff --git a/tests/type-definitions/global/proposals/pattern-matching.test.ts b/tests/type-definitions/global/proposals/pattern-matching.test.ts new file mode 100644 index 000000000000..c5767234a166 --- /dev/null +++ b/tests/type-definitions/global/proposals/pattern-matching.test.ts @@ -0,0 +1,8 @@ +import 'core-js/full'; + +const sym: symbol = Symbol.customMatcher; + +// @ts-expect-error +const bad1: string = Symbol.customMatcher; +// @ts-expect-error +Symbol.customMatcher = Symbol('other'); diff --git a/tests/type-definitions/global/proposals/promise-all-settled.test.ts b/tests/type-definitions/global/proposals/promise-all-settled.test.ts new file mode 100644 index 000000000000..98561fd6dd94 --- /dev/null +++ b/tests/type-definitions/global/proposals/promise-all-settled.test.ts @@ -0,0 +1,52 @@ +import 'core-js/es'; +import allSettled from 'core-js/es/promise/all-settled'; +import $Promise from 'core-js/es/promise'; + +const promises = [Promise.resolve(1), Promise.resolve('foo'), 3] as const; +const arr = [Promise.resolve(1), Promise.resolve(2)]; +const strArr = ['a', 'b', 'c']; +const promiseLike = { then: (cb: (val: number) => void) => cb(42) }; + +interface CoreJSPromiseResult { + status: string; + value?: T; + reason?: any; +} + +const settledNS: Promise[]> = allSettled(strArr); +const settledNS2: Promise[]> = $Promise.allSettled(strArr); + +const settled1: Promise<[ + CoreJSPromiseResult, + CoreJSPromiseResult, + CoreJSPromiseResult, +]> = Promise.allSettled(promises); +const settled2: Promise[]> = Promise.allSettled([Promise.resolve(10), Promise.resolve(20), 30]); +const settled3: Promise[]> = Promise.allSettled(strArr); +const settled4: Promise[]> = Promise.allSettled(new Set([1, 2, 3])); +const settled5: Promise[]> = Promise.allSettled([promiseLike]); + +const emptyTuple: [] = []; +const settled6: Promise<[]> = Promise.allSettled(emptyTuple); + +const mixedTuple = [42, Promise.resolve('bar')] as const; +const settled7: Promise<[ + CoreJSPromiseResult, + CoreJSPromiseResult, +]> = Promise.allSettled(mixedTuple); + +// @ts-expect-error +allSettled(); +// @ts-expect-error +$Promise.allSettled(); + +// @ts-expect-error +Promise.allSettled(); +// @ts-expect-error +Promise.allSettled(5); +// @ts-expect-error +Promise.allSettled({ foo: 123 }); +// @ts-expect-error +Promise.allSettled([1, 2], 123); +// @ts-expect-error +Promise.allSettled([Promise.resolve(1)], 'extra'); diff --git a/tests/type-definitions/global/proposals/promise-any.test.ts b/tests/type-definitions/global/proposals/promise-any.test.ts new file mode 100644 index 000000000000..44b7509fdb45 --- /dev/null +++ b/tests/type-definitions/global/proposals/promise-any.test.ts @@ -0,0 +1,36 @@ +import 'core-js/es'; +import promiseAny from 'core-js/es/promise/any'; + +const arr = [Promise.resolve(1), Promise.resolve('foo'), 3] as const; +const justNumbers = [1, 2, 3]; +const setOfStrings = new Set(['a', 'b', 'c']); +const promiseLike = { then: (cb: (val: number) => void) => cb(123) }; +const emptyTuple: [] = []; +const mixed = [true, Promise.resolve('z')] as const; + +const anyNS: Promise = promiseAny(arr); + +const any1: Promise = Promise.any(arr); +const any2: Promise = Promise.any(['x', 'y', Promise.resolve(5)]); +const any3: Promise = Promise.any(emptyTuple); +const any4: Promise = Promise.any(mixed); + +const any5: Promise = Promise.any(justNumbers); +const any6: Promise = Promise.any(setOfStrings); +const any7: Promise = Promise.any([promiseLike]); +const any8: Promise = Promise.any(new Set([1])); +const any9: Promise = Promise.any([Promise.resolve()]); + +// @ts-expect-error +promiseAny(); + +// @ts-expect-error +Promise.any(); +// @ts-expect-error +Promise.any(123); +// @ts-expect-error +Promise.any({ foo: 42 }); +// @ts-expect-error +Promise.any([1, 2], 3); +// @ts-expect-error +Promise.any(justNumbers, 'extra'); diff --git a/tests/type-definitions/global/proposals/promise-finally.test.ts b/tests/type-definitions/global/proposals/promise-finally.test.ts new file mode 100644 index 000000000000..82a34b36340c --- /dev/null +++ b/tests/type-definitions/global/proposals/promise-finally.test.ts @@ -0,0 +1,39 @@ +import 'core-js/es'; +import promiseFinally from 'core-js/es/promise/finally'; + +const p1 = Promise.resolve(42); + +const pfNS: Promise = promiseFinally(p1); + +const pf1: Promise = p1.finally(); +const pf2: Promise = p1.finally(undefined); +const pf3: Promise = p1.finally(null); +const pf4: Promise = p1.finally(() => {}); +const pf5: Promise = p1.finally(function () {}); + +const p2 = Promise.reject('err'); + +const pf6: Promise = p2.finally(); +const pf7: Promise = p2.finally(() => {}); + +declare function returnsPromise(): Promise; + +const genericF: Promise = returnsPromise().finally(() => {}); + +// @ts-expect-error +promiseFinally(p1, 123); + +// @ts-expect-error +p1.finally(123); +// @ts-expect-error +p1.finally('foo'); +// @ts-expect-error +p1.finally({}); +// @ts-expect-error +p1.finally([]); +// @ts-expect-error +p1.finally(() => {}, 'extra'); +// @ts-expect-error +p1.finally(true); +// @ts-expect-error +p1.finally(Symbol('x')); diff --git a/tests/type-definitions/global/proposals/promise-try.test.ts b/tests/type-definitions/global/proposals/promise-try.test.ts new file mode 100644 index 000000000000..43826a7ac536 --- /dev/null +++ b/tests/type-definitions/global/proposals/promise-try.test.ts @@ -0,0 +1,35 @@ +import 'core-js/es'; +import promiseTry from 'core-js/es/promise/try'; + +const ptNS: Promise = promiseTry(() => 42); + +const pt1: Promise = Promise.try(() => 42); +const pt2: Promise = Promise.try(() => Promise.resolve('hi')); +const pt3: Promise = Promise.try((a: number, b: number) => a + b, 1, 2); +const pt4: Promise = Promise.try((x: string) => x + '!!', 'test'); +const pt5: Promise = Promise.try(() => {}); +const pt6: Promise = Promise.try((b: boolean) => b, false); + +const pt7: Promise = Promise.try((a: number, b: string, c: boolean) => c ? a : Number(b), 10, '100', true); +const pt8: Promise = Promise.try((a: string) => Promise.resolve(a), 'bar'); + +declare function returnsPromise(): Promise; +const pt9: Promise = Promise.try(() => returnsPromise()); + +// @ts-expect-error +promiseTry(); + +// @ts-expect-error +Promise.try(); +// @ts-expect-error +Promise.try(42); +// @ts-expect-error +Promise.try('callback'); +// @ts-expect-error +Promise.try({}); +// @ts-expect-error +Promise.try([]); +// @ts-expect-error +Promise.try(() => 1, 2, 'a', Symbol('x')); +// @ts-expect-error +Promise.try((a: boolean) => a, 123); diff --git a/tests/type-definitions/global/proposals/promise-with-resolvers.test.ts b/tests/type-definitions/global/proposals/promise-with-resolvers.test.ts new file mode 100644 index 000000000000..8b0d38d6550a --- /dev/null +++ b/tests/type-definitions/global/proposals/promise-with-resolvers.test.ts @@ -0,0 +1,40 @@ +import 'core-js/es'; +import promiseWithResolvers from 'core-js/es/promise/with-resolvers'; + +const prNS = promiseWithResolvers(); +const pNS1: Promise = prNS.promise; + +const pr = Promise.withResolvers(); +const pr2 = Promise.withResolvers(); +const pr3 = Promise.withResolvers(); + +const p1: Promise = pr.promise; +const p2: Promise = pr2.promise; +const p3: Promise = pr3.promise; + +pr.resolve(42); +pr.resolve(Promise.resolve(43)); +pr.reject(); +pr.reject('some error'); + +pr2.resolve('test'); +pr2.resolve(Promise.resolve('hi')); +pr2.reject(new Error('fail')); +pr3.resolve(undefined); +pr3.reject(); + +const value: number | PromiseLike = 99; +pr.resolve(value); + +declare function agrees(): PromiseWithResolvers; +const gr: PromiseWithResolvers = agrees(); +gr.resolve(true); +gr.reject(); + +// @ts-expect-error +promiseWithResolvers(123); + +// @ts-expect-error +Promise.withResolvers(123); +// @ts-expect-error +Promise.withResolvers(123); diff --git a/tests/type-definitions/global/proposals/regexp-dotall-flag.test.ts b/tests/type-definitions/global/proposals/regexp-dotall-flag.test.ts new file mode 100644 index 000000000000..286c56a36090 --- /dev/null +++ b/tests/type-definitions/global/proposals/regexp-dotall-flag.test.ts @@ -0,0 +1,15 @@ +import 'core-js/full'; + +const r1 = new RegExp('foo.bar', 's'); +const dotAll: boolean = r1.dotAll; + +// @ts-expect-error +r1.dotAll(); +// @ts-expect-error +r1['dotAll'] = false; +// @ts-expect-error +RegExp.prototype['dotAll'] = true; +// @ts-expect-error +RegExp.prototype.dotAll(); +// @ts-expect-error +const err: string = r1.dotAll; diff --git a/tests/type-definitions/global/proposals/regexp-escaping.test.ts b/tests/type-definitions/global/proposals/regexp-escaping.test.ts new file mode 100644 index 000000000000..57b37ab45dc1 --- /dev/null +++ b/tests/type-definitions/global/proposals/regexp-escaping.test.ts @@ -0,0 +1,27 @@ +import 'core-js/es'; +import escape from 'core-js/es/regexp/escape'; +import { assertString } from '../../helpers/helpers.js'; + +assertString(escape('foo.*+?^${}()|[]\\')); +assertString(RegExp.escape('foo.*+?^${}()|[]\\')); +assertString(RegExp.escape('')); + +// @ts-expect-error +escape(); + +// @ts-expect-error +RegExp.escape(); +// @ts-expect-error +RegExp.escape(123); +// @ts-expect-error +RegExp.escape(); +// @ts-expect-error +RegExp.escape({}); +// @ts-expect-error +RegExp.escape(/abc/); +// @ts-expect-error +RegExp.escape([]); +// @ts-expect-error +const wrong: number = RegExp.escape('boo'); +// @ts-expect-error +RegExp.escape('foo', 'bar'); diff --git a/tests/type-definitions/global/proposals/regexp-named-groups.test.ts b/tests/type-definitions/global/proposals/regexp-named-groups.test.ts new file mode 100644 index 000000000000..61fc6489298b --- /dev/null +++ b/tests/type-definitions/global/proposals/regexp-named-groups.test.ts @@ -0,0 +1,44 @@ +import 'core-js/full'; + +declare const execArr: RegExpExecArray; +declare const matchArr: RegExpMatchArray; + +const execGroups: { [key: string]: string } | undefined = execArr.groups; +const matchGroups: { [key: string]: string } | undefined = matchArr.groups; + +if (execGroups) { + const foo: string | undefined = execGroups.foo; + const bar: string | undefined = execGroups['bar']; +} + +if (matchGroups) { + const baz: string | undefined = matchGroups.baz; + const qr: string | undefined = matchGroups['qr']; +} + +if (execGroups) { + const key = 'dynamic'; + const dyn: string | undefined = execGroups[key]; +} + +const first: string = execArr[0]; +const mfirst: string = matchArr[0]; + +// @ts-expect-error +execArr.groups = { foo: 123 }; +// @ts-expect-error +execArr.groups = 'bad'; +// @ts-expect-error +matchArr.groups = { baz: 123 }; +// @ts-expect-error +matchArr.groups = 42; +// @ts-expect-error +execGroups.foo = 1; +// @ts-expect-error +const n: number = execGroups && execGroups.foo; +// @ts-expect-error +const b: boolean = execArr.groups && execArr.groups.bar; +// @ts-expect-error +const numFirst: number = execArr[0]; +// @ts-expect-error +const arrTest: string[] = execArr.groups; diff --git a/tests/type-definitions/global/proposals/relative-indexing-method.test.ts b/tests/type-definitions/global/proposals/relative-indexing-method.test.ts new file mode 100644 index 000000000000..6ff2e8eafd74 --- /dev/null +++ b/tests/type-definitions/global/proposals/relative-indexing-method.test.ts @@ -0,0 +1,130 @@ +import 'core-js/es'; +import stringAt from 'core-js/es/string/at'; +import arrayAt from 'core-js/es/array/at'; + +const str = 'hello'; + +const res: string | undefined = stringAt(str, 0); + +const s1: string | undefined = str.at(0); +const s2: string | undefined = str.at(-1); + +const arr: number[] = [10, 20, 30]; + +const res2: number | undefined = arrayAt(arr, 1); + +const a1: number | undefined = arr.at(1); +const a2: number | undefined = arr.at(-2); + +const roArr: ReadonlyArray = ['a', 'b', 'c']; +const r1: string | undefined = roArr.at(1); +const r2: string | undefined = roArr.at(-3); + +const i8 = new Int8Array([5, 6, 7]); +const i8$1: number | undefined = i8.at(2); +const i8$2: number | undefined = i8.at(-1); + +const u8 = new Uint8Array([8, 9, 10]); +const u8$1: number | undefined = u8.at(0); + +const u8c = new Uint8ClampedArray([15, 16, 17]); +const u8c$1: number | undefined = u8c.at(2); + +const i16 = new Int16Array([100, 200, 300]); +const i16$1: number | undefined = i16.at(1); + +const u16 = new Uint16Array([400, 500, 600]); +const u16$1: number | undefined = u16.at(-1); + +const i32 = new Int32Array([1, 2, 3]); +const i32$1: number | undefined = i32.at(0); + +const u32 = new Uint32Array([7, 8, 9]); +const u32$1: number | undefined = u32.at(2); + +const f32 = new Float32Array([1.5, 2.5, 3.5]); +const f32$1: number | undefined = f32.at(-1); + +const f64 = new Float64Array([11.1, 22.2, 33.3]); +const f64$1: number | undefined = f64.at(0); + +// TODO for es6 +// const bi64 = new (BigInt64Array as { new(arr: ArrayLike): BigInt64Array })([BigInt(1), BigInt(2), BigInt(3)]); +// const bi64_1: bigint | undefined = bi64.at(2); +// +// const bu64 = new (BigUint64Array as { new(arr: ArrayLike): BigUint64Array })([BigInt(10), BigInt(20)]); +// const bu64_1: bigint | undefined = bu64.at(-1); + +// @ts-expect-error +stringAt(str); + +// @ts-expect-error +str.at(); +// @ts-expect-error +str.at('1'); +// @ts-expect-error +str.at(1, 2); + +// @ts-expect-error +arrayAt(); + +// @ts-expect-error +arr.at(); +// @ts-expect-error +arr.at('1'); +// @ts-expect-error +arr.at({}); +// @ts-expect-error +arr.at(); +// @ts-expect-error +arr.at(1, 1); + +// @ts-expect-error +roArr.at(); +// @ts-expect-error +roArr.at('2'); + +// @ts-expect-error +i8.at(); +// @ts-expect-error +i8.at('0'); +// @ts-expect-error +i8.at(1, 2); + +// @ts-expect-error +u8.at('0'); +// @ts-expect-error +u8.at(); + +// @ts-expect-error +u8c.at(); +// @ts-expect-error +u8c.at({}); +// @ts-expect-error +u8c.at(''); + +// @ts-expect-error +i16.at(); +// @ts-expect-error +i16.at([]); + +// @ts-expect-error +u16.at(() => 42); + +// @ts-expect-error +i32.at(false); + +// @ts-expect-error +u32.at(Symbol()); + +// @ts-expect-error +f32.at('a'); + +// @ts-expect-error +f64.at([]); + +// // @ts-expect-error +// bi64.at('a'); +// +// // @ts-expect-error +// bu64.at({}); diff --git a/tests/type-definitions/global/proposals/set-methods.test.ts b/tests/type-definitions/global/proposals/set-methods.test.ts new file mode 100644 index 000000000000..6883d3a7b9f8 --- /dev/null +++ b/tests/type-definitions/global/proposals/set-methods.test.ts @@ -0,0 +1,118 @@ +import 'core-js/es'; +import setUnion from 'core-js/es/set/union'; +import setIntersection from 'core-js/es/set/intersection'; +import setDifference from 'core-js/es/set/difference'; +import setSymmetricDifference from 'core-js/es/set/symmetric-difference'; +import setIsSubsetOf from 'core-js/es/set/is-subset-of'; +import setIsSupersetOf from 'core-js/es/set/is-superset-of'; +import setIsDisjointFrom from 'core-js/es/set/is-disjoint-from'; + +const setA = new Set([1, 2, 3]); +const setB = new Set(['a', 'b', 'c']); + +const setLike: ReadonlySetLike = { + keys() { return [1, 2, 3][Symbol.iterator](); }, + has(val: number): boolean { return val === 2; }, + size: 3, +}; + +const setLikeStr: ReadonlySetLike = { + keys() { return ['a', 'b'][Symbol.iterator](); }, + has(val: string): boolean { return val === 'a'; }, + size: 2, +}; + +const arrSet: ReadonlySet = new Set([4, 5, 6]); + +const unionABNS: Set = setUnion(setA, setB); + +const unionAB: Set = setA.union(setB); +const unionAN: Set = setA.union(setLike); + +const interABNS: Set = setIntersection(setA, setLike); + +const interAB: Set = setA.intersection(setB); +const interAN: Set = setA.intersection(setLike); + +const diffABNS: Set = setDifference(setA, setB); + +const diffAB: Set = setA.difference(setB); +const diffAN: Set = setA.difference(setLike); + +const symdiffALNS: Set = setSymmetricDifference(setA, setLike); + +const symdiffAB: Set = setA.symmetricDifference(setB); +const symdiffAL: Set = setA.symmetricDifference(setLike); + +const subNS: boolean = setIsSubsetOf(setA, setLikeStr); +const sub: boolean = setA.isSubsetOf(setLikeStr); + +const superSetNS: boolean = setIsSupersetOf(setA, setLikeStr); +const superSet: boolean = setA.isSupersetOf(setLikeStr); + +const isDisjointNS: boolean = setIsDisjointFrom(setA, setLike); +const isDisjoint: boolean = setA.isDisjointFrom(setLike); + +const unionR: Set = arrSet.union(setLike); +const intersectionR: Set = arrSet.intersection(setLike); +const diffR: Set = arrSet.difference(setLike); +const symdiffR: Set = arrSet.symmetricDifference(setLike); + +const subR: boolean = arrSet.isSubsetOf(setLikeStr); +const supR: boolean = arrSet.isSupersetOf(setLikeStr); +const disjR: boolean = arrSet.isDisjointFrom(setLike); + +const numStrUnion: Set = setA.union(setLikeStr); +const numStrInter: Set = setA.intersection(setLikeStr); +const numStrSym: Set = setA.symmetricDifference(setLikeStr); + +// @ts-expect-error +setA.union(); +// @ts-expect-error +setA.union(123); +// @ts-expect-error +setA.union({}); + +// @ts-expect-error +setA.intersection(); +// @ts-expect-error +setA.intersection('a'); +// @ts-expect-error +setA.intersection({ foo: 'bar' }); + +// @ts-expect-error +setA.difference(); +// @ts-expect-error +setA.difference([]); + +// @ts-expect-error +setA.symmetricDifference(); +// @ts-expect-error +setA.symmetricDifference(1); + +// @ts-expect-error +setA.isSubsetOf(); +// @ts-expect-error +setA.isSubsetOf([]); + +// @ts-expect-error +setA.isSupersetOf(); +// @ts-expect-error +setA.isDisjointFrom(); + +// @ts-expect-error +arrSet.union(); +// @ts-expect-error +arrSet.union('a'); + +// @ts-expect-error +arrSet.intersection({}); + +// @ts-expect-error +arrSet.difference({}); + +// @ts-expect-error +arrSet.symmetricDifference({}); + +// @ts-expect-error +arrSet.isSubsetOf(1); diff --git a/tests/type-definitions/global/proposals/string-cooked.test.ts b/tests/type-definitions/global/proposals/string-cooked.test.ts new file mode 100644 index 000000000000..503a71ec84d1 --- /dev/null +++ b/tests/type-definitions/global/proposals/string-cooked.test.ts @@ -0,0 +1,20 @@ +import 'core-js/full'; +import cooked from 'core-js/full/string/cooked'; +import $String from 'core-js/full/string'; +import { assertString } from '../../helpers/helpers.js'; + +assertString(cooked([])); +$String.cooked([]); + +assertString(String.cooked(['foo', 'bar'], 1, 2)); +String.cooked([]); + +// @ts-expect-error +$String.cooked(1); +// @ts-expect-error +cooked(1); + +// @ts-expect-error +String.cooked(1); +// @ts-expect-error +String.cooked(false); diff --git a/tests/type-definitions/global/proposals/string-dedent.test.ts b/tests/type-definitions/global/proposals/string-dedent.test.ts new file mode 100644 index 000000000000..fd3954089e36 --- /dev/null +++ b/tests/type-definitions/global/proposals/string-dedent.test.ts @@ -0,0 +1,31 @@ +import 'core-js/full'; +import dedent from 'core-js/full/string/dedent'; +import { assertString } from '../../helpers/helpers.js'; + +assertString(dedent`foo\nbar`); + +assertString(String.dedent`foo\nbar`); +assertString(String.dedent`line1 + line2 + line3`); + +const tpl = Object.assign(['foo', 'bar'], { raw: ['foo', 'bar'] }); +String.dedent(tpl, 1, 2); + +String.dedent({ raw: ['a\n b\n', '\n c\n'] }, 1, 2); + +const myTag = (strings: { raw: readonly string[] }, ...values: (string | number)[]) => { + return { strings, values } as const; +}; +const myAndDedent = String.dedent(myTag); +myAndDedent`line1 + line2 + line3`; + +// @ts-expect-error +'string\ndedent'.dedent(); + +// @ts-expect-error +dedent(); +// @ts-expect-error +String.dedent(); diff --git a/tests/type-definitions/global/proposals/string-left-right-trim.test.ts b/tests/type-definitions/global/proposals/string-left-right-trim.test.ts new file mode 100644 index 000000000000..e5e890008ed3 --- /dev/null +++ b/tests/type-definitions/global/proposals/string-left-right-trim.test.ts @@ -0,0 +1,33 @@ +import 'core-js/es'; +import trimEnd from 'core-js/es/string/trim-end'; +import trimStart from 'core-js/es/string/trim-start'; +import trimLeft from 'core-js/es/string/trim-left'; +import trimRight from 'core-js/es/string/trim-right'; +import { assertString } from '../../helpers/helpers.js'; + +const s = 'abc'; + +assertString(trimEnd(s)); +assertString(trimStart(s)); +assertString(trimLeft(s)); +assertString(trimRight(s)); + +assertString(s.trimEnd()); +assertString(s.trimStart()); +assertString(s.trimLeft()); +assertString(s.trimRight()); + +// @ts-expect-error +s.trimEnd(123); + +// @ts-expect-error +s.trimStart('a'); + +// @ts-expect-error +s.trimLeft([]); + +// @ts-expect-error +s.trimRight({}); + +// @ts-expect-error +const n: number = s.trimEnd(); diff --git a/tests/type-definitions/global/proposals/string-match-all.test.ts b/tests/type-definitions/global/proposals/string-match-all.test.ts new file mode 100644 index 000000000000..dcd89d1634ae --- /dev/null +++ b/tests/type-definitions/global/proposals/string-match-all.test.ts @@ -0,0 +1,23 @@ +import 'core-js/es'; +import matchAll from 'core-js/es/string/match-all'; + +const s = 'abcabc'; +const re = /abc/g; + +const matchIterNS: RegExpStringIterator = matchAll(s, re); +const matchIter: RegExpStringIterator = s.matchAll(re); + +// @ts-expect-error +matchAll(s); +// @ts-expect-error +s.matchAll(); +// @ts-expect-error +s.matchAll('abc'); +// @ts-expect-error +const n: number = s.matchAll(re); +// @ts-expect-error +s.matchAll({}); +// @ts-expect-error +s.matchAll(123); +// @ts-expect-error +s.matchAll(/abc/g, /def/g); diff --git a/tests/type-definitions/global/proposals/string-padding.test.ts b/tests/type-definitions/global/proposals/string-padding.test.ts new file mode 100644 index 000000000000..5882b05cc416 --- /dev/null +++ b/tests/type-definitions/global/proposals/string-padding.test.ts @@ -0,0 +1,39 @@ +import 'core-js/es'; +import padStart from 'core-js/es/string/pad-start'; +import padEnd from 'core-js/es/string/pad-end'; +import { assertString } from '../../helpers/helpers.js'; + +const s = 'foo'; + +assertString(padStart(s, 5)); +assertString(padEnd(s, 8)); + +assertString(s.padStart(5)); +assertString(s.padStart(10, '0')); +assertString(s.padEnd(8)); +assertString(s.padEnd(4, '-')); + +// @ts-expect-error +padStart(s); +// @ts-expect-error +padEnd(s); +// @ts-expect-error +s.padStart(); +// @ts-expect-error +s.padEnd(); +// @ts-expect-error +s.padStart('10'); +// @ts-expect-error +s.padEnd(true); +// @ts-expect-error +s.padStart(5, 1); +// @ts-expect-error +s.padEnd(3, {}); +// @ts-expect-error +s.padStart(2, [], 'extra'); +// @ts-expect-error +s.padEnd(7, '', undefined); +// @ts-expect-error +const n: number = s.padStart(5); +// @ts-expect-error +const n2: number = s.padEnd(3, '-'); diff --git a/tests/type-definitions/global/proposals/string-replace-all.test.ts b/tests/type-definitions/global/proposals/string-replace-all.test.ts new file mode 100644 index 000000000000..7b6d72de47ac --- /dev/null +++ b/tests/type-definitions/global/proposals/string-replace-all.test.ts @@ -0,0 +1,33 @@ +import 'core-js/es'; +import replaceAll from 'core-js/es/string/replace-all'; +import { assertString } from '../../helpers/helpers.js'; + +const s = 'foo bar foo'; + +assertString(replaceAll(s, 'foo', 'baz')); + +const r1: string = s.replaceAll('foo', 'baz'); +const r2: string = s.replaceAll(/foo/g, 'baz'); +const r3: string = s.replaceAll('bar', (substr: string) => substr); +const r4: string = s.replaceAll(/bar/g, (substr: string) => substr + 'Test'); +const r5: string = s.replaceAll('foo', function (substring: string): string { return substring + '!'; }); +const r6: string = s.replaceAll(/foo/g, (match: string, ...args: any[]) => match + args.length); + +// @ts-expect-error +replaceAll(s); +// @ts-expect-error +s.replaceAll(); +// @ts-expect-error +s.replaceAll('foo'); +// @ts-expect-error +s.replaceAll('foo', 1); +// @ts-expect-error +s.replaceAll('foo', {}); +// @ts-expect-error +s.replaceAll(/foo/, 'bar', 'extra'); +// @ts-expect-error +s.replaceAll(/foo/g, (match: string) => 123); +// @ts-expect-error +s.replaceAll(/foo/g, 5); +// @ts-expect-error +const n: number = s.replaceAll('foo', 'baz'); diff --git a/tests/type-definitions/global/proposals/symbol-description.test.ts b/tests/type-definitions/global/proposals/symbol-description.test.ts new file mode 100644 index 000000000000..94f52767ea83 --- /dev/null +++ b/tests/type-definitions/global/proposals/symbol-description.test.ts @@ -0,0 +1,19 @@ +import 'core-js/full'; + +const sym1 = Symbol('foo'); +const d1: string | undefined = sym1.description; + +const sym2 = Symbol(); +const d2: string | undefined = sym2.description; + +// @ts-expect-error +sym1['description'] = 'bar'; + +// @ts-expect-error +const n: number = sym1.description; + +// @ts-expect-error +sym2.description(); + +// @ts-expect-error +s.description = 123; diff --git a/tests/type-definitions/global/proposals/symbol-predicates.test.ts b/tests/type-definitions/global/proposals/symbol-predicates.test.ts new file mode 100644 index 000000000000..af7cc673700c --- /dev/null +++ b/tests/type-definitions/global/proposals/symbol-predicates.test.ts @@ -0,0 +1,35 @@ +import 'core-js/full'; +import isRegisteredSymbol from 'core-js/full/symbol/is-registered-symbol'; +import isWellKnownSymbol from 'core-js/full/symbol/is-well-known-symbol'; +import $Symbol from 'core-js/full/symbol'; +import { assertBool } from '../../helpers/helpers.js'; + +assertBool(isRegisteredSymbol($Symbol.for('foo'))); +assertBool(isWellKnownSymbol($Symbol.iterator)); +assertBool($Symbol.isRegisteredSymbol($Symbol.for('foo'))); +assertBool($Symbol.isWellKnownSymbol($Symbol.iterator)); + +assertBool(Symbol.isRegisteredSymbol(Symbol.for('foo'))); +assertBool(Symbol.isRegisteredSymbol(undefined)); +assertBool(Symbol.isRegisteredSymbol(Symbol('bar'))); + +assertBool(Symbol.isWellKnownSymbol(Symbol.iterator)); +assertBool(Symbol.isWellKnownSymbol({})); +assertBool(Symbol.isWellKnownSymbol(Symbol('baz'))); + +declare const u: unknown; +Symbol.isRegisteredSymbol(u); +Symbol.isWellKnownSymbol(u); + +// @ts-expect-error +isRegisteredSymbol(); +// @ts-expect-error +$Symbol.isRegisteredSymbol(); +// @ts-expect-error +isWellKnownSymbol(); +// @ts-expect-error +$Symbol.isWellKnownSymbol(); +// @ts-expect-error +Symbol.isRegisteredSymbol(); +// @ts-expect-error +Symbol.isWellKnownSymbol(); diff --git a/tests/type-definitions/global/proposals/well-formed-unicode-strings.test.ts b/tests/type-definitions/global/proposals/well-formed-unicode-strings.test.ts new file mode 100644 index 000000000000..d9ab3a1bd066 --- /dev/null +++ b/tests/type-definitions/global/proposals/well-formed-unicode-strings.test.ts @@ -0,0 +1,35 @@ +import 'core-js/es'; +import isWellFormed from 'core-js/es/string/is-well-formed'; +import toWellFormed from 'core-js/es/string/to-well-formed'; +import { assertBool, assertString } from '../../helpers/helpers.js'; + +const s = 'test'; + +assertBool(isWellFormed(s)); +assertString(toWellFormed(s)); + +assertBool(s.isWellFormed()); +assertString(s.toWellFormed()); + +// @ts-expect-error +isWellFormed(123); +// @ts-expect-error +toWellFormed([]); + +// @ts-expect-error +s.isWellFormed(123); + +// @ts-expect-error +s.isWellFormed('foo'); + +// @ts-expect-error +s.toWellFormed([]); + +// @ts-expect-error +s.toWellFormed(true); + +// @ts-expect-error +const n: number = s.toWellFormed(); + +// @ts-expect-error +const s2: string = s.isWellFormed(); diff --git a/tests/type-definitions/global/tsconfig.dom.json b/tests/type-definitions/global/tsconfig.dom.json new file mode 100644 index 000000000000..b6c25f529ba1 --- /dev/null +++ b/tests/type-definitions/global/tsconfig.dom.json @@ -0,0 +1,7 @@ +{ + "extends": "../tsconfig.json", + "include": ["./**/*.ts"], + "compilerOptions": { + "types": ["@core-js/types"] + } +} diff --git a/tests/type-definitions/global/tsconfig.es6.dom.json b/tests/type-definitions/global/tsconfig.es6.dom.json new file mode 100644 index 000000000000..83daa53abbba --- /dev/null +++ b/tests/type-definitions/global/tsconfig.es6.dom.json @@ -0,0 +1,8 @@ +{ + "extends": "../tsconfig.json", + "include": ["./**/*.ts"], + "exclude": ["./**/*es2018*test.ts"], + "compilerOptions": { + "types": ["@core-js/types"] + } +} diff --git a/tests/type-definitions/global/tsconfig.es6.json b/tests/type-definitions/global/tsconfig.es6.json new file mode 100644 index 000000000000..0166c8be8e39 --- /dev/null +++ b/tests/type-definitions/global/tsconfig.es6.json @@ -0,0 +1,11 @@ +{ + "extends": "../tsconfig.json", + "include": ["./**/*.ts"], + "exclude": [ + "./**/*es2018*test.ts", + "./**/*dom*test.ts" + ], + "compilerOptions": { + "types": ["@core-js/types"] + } +} diff --git a/tests/type-definitions/global/tsconfig.json b/tests/type-definitions/global/tsconfig.json new file mode 100644 index 000000000000..2a9c23e61713 --- /dev/null +++ b/tests/type-definitions/global/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../tsconfig.json", + "include": ["./**/*.ts"], + "exclude": ["./**/*dom*test.ts"], + "compilerOptions": { + "types": [ + "@core-js/types" + ] + } +} diff --git a/tests/type-definitions/global/web/atob.test.ts b/tests/type-definitions/global/web/atob.test.ts new file mode 100644 index 000000000000..128467b7acbd --- /dev/null +++ b/tests/type-definitions/global/web/atob.test.ts @@ -0,0 +1,16 @@ +import 'core-js/stable'; +import $atob from 'core-js/stable/atob'; +import { assertString } from '../../helpers/helpers.js'; + +assertString($atob('SGVsbG8gd29ybGQ=')); + +assertString(atob('SGVsbG8gd29ybGQ=')); + +// @ts-expect-error +$atob(); +// @ts-expect-error +atob(); +// @ts-expect-error +atob(123); +// @ts-expect-error +atob({}); diff --git a/tests/type-definitions/global/web/btoa.test.ts b/tests/type-definitions/global/web/btoa.test.ts new file mode 100644 index 000000000000..d7b951c20610 --- /dev/null +++ b/tests/type-definitions/global/web/btoa.test.ts @@ -0,0 +1,16 @@ +import 'core-js/stable'; +import $btoa from 'core-js/stable/btoa'; +import { assertString } from '../../helpers/helpers.js'; + +assertString($btoa('SGVsbG8gd29ybGQ=')); + +assertString(btoa('SGVsbG8gd29ybGQ=')); + +// @ts-expect-error +$btoa(); +// @ts-expect-error +btoa(); +// @ts-expect-error +btoa(123); +// @ts-expect-error +btoa({}); diff --git a/tests/type-definitions/global/web/dom-exception.test.ts b/tests/type-definitions/global/web/dom-exception.test.ts new file mode 100644 index 000000000000..b57c58ee4abc --- /dev/null +++ b/tests/type-definitions/global/web/dom-exception.test.ts @@ -0,0 +1,10 @@ +import 'core-js/full'; + +const ex1 = new DOMException(); +const ex2 = new DOMException('Some message'); +const ex3 = new DOMException('Some message', 'SyntaxError'); + +// @ts-expect-error +DOMException(); +// @ts-expect-error +DOMException(123); diff --git a/tests/type-definitions/global/web/efficient-script-yielding.test.ts b/tests/type-definitions/global/web/efficient-script-yielding.test.ts new file mode 100644 index 000000000000..cc2dfb5906e4 --- /dev/null +++ b/tests/type-definitions/global/web/efficient-script-yielding.test.ts @@ -0,0 +1,21 @@ +import 'core-js/stable'; +import $setImmediate from 'core-js/stable/set-immediate'; +import $clearImmediate from 'core-js/stable/clear-immediate'; + +const resNS: number | object = $setImmediate(() => 42); +$clearImmediate(resNS); + +const res: number | object = setImmediate(() => 42); +clearImmediate(res); + +// @ts-expect-error +$setImmediate(); +// @ts-expect-error +$clearImmediate('str'); + +// @ts-expect-error +setImmediate(); +// @ts-expect-error +setImmediate(42); +// @ts-expect-error +clearImmediate('str'); diff --git a/tests/type-definitions/global/web/iterable-dom-collections.dom.test.ts b/tests/type-definitions/global/web/iterable-dom-collections.dom.test.ts new file mode 100644 index 000000000000..5cc27fea264e --- /dev/null +++ b/tests/type-definitions/global/web/iterable-dom-collections.dom.test.ts @@ -0,0 +1,138 @@ +import 'core-js/full'; + +declare const nodeList: NodeList; +nodeList.forEach((value: Node, key: number, list: NodeList): void => {}); +nodeList.forEach((value: Node, key: number, list: NodeList): void => {}, []); +// @ts-expect-error +nodeList.forEach(); + +const k1: IterableIterator = nodeList.keys(); +// @ts-expect-error +nodeList.keys('string'); + +const v: IterableIterator = nodeList.values(); +// @ts-expect-error +nodeList.values('string'); + +const e: IterableIterator<[number, Node]> = nodeList.entries(); +// @ts-expect-error +nodeList.entries('string'); + +declare const domTokenList: DOMTokenList; + +domTokenList.forEach((value: string, key: number, list: DOMTokenList): void => {}); +domTokenList.forEach((value: string, key: number, list: DOMTokenList): void => {}, []); +// @ts-expect-error +domTokenList.forEach(); + +const fomKeys: IterableIterator = domTokenList.keys(); +// @ts-expect-error +domTokenList.keys('string'); + +const domValues: IterableIterator = domTokenList.values(); +// @ts-expect-error +domTokenList.values('string'); + +const domEntries: IterableIterator<[number, string]> = domTokenList.entries(); +// @ts-expect-error +domTokenList.entries('string'); + +declare const domStringList: DOMStringList; +const dslIterator: IterableIterator = domStringList[Symbol.iterator](); +// @ts-expect-error +const dslWrong: IterableIterator = domStringList[Symbol.iterator](); + +declare const dataTransferItemList: DataTransferItemList; +const dtilIterator: IterableIterator = dataTransferItemList[Symbol.iterator](); +// @ts-expect-error +const dtilWrong: IterableIterator = dataTransferItemList[Symbol.iterator](); + +declare const fileList: FileList; +const flIterator: IterableIterator = fileList[Symbol.iterator](); +// @ts-expect-error +const flWrong: IterableIterator = fileList[Symbol.iterator](); + +declare const htmlAllCollection: HTMLAllCollection; +const hacIterator: IterableIterator = htmlAllCollection[Symbol.iterator](); +// @ts-expect-error +const hacWrong: IterableIterator = htmlAllCollection[Symbol.iterator](); + +declare const mediaList: MediaList; +const mlIterator: IterableIterator = mediaList[Symbol.iterator](); +// @ts-expect-error +const mlWrong: IterableIterator = mediaList[Symbol.iterator](); + +declare const mimeTypeArray: MimeTypeArray; +const mtaIterator: IterableIterator = mimeTypeArray[Symbol.iterator](); +// @ts-expect-error +const mtaWrong: IterableIterator = mimeTypeArray[Symbol.iterator](); + +declare const namedNodeMap: NamedNodeMap; +const nnmIterator: IterableIterator = namedNodeMap[Symbol.iterator](); +// @ts-expect-error +const nnmWrong: IterableIterator = namedNodeMap[Symbol.iterator](); + +declare const paintRequestList: PaintRequestList; +const prlIterator: IterableIterator = paintRequestList[Symbol.iterator](); +// @ts-expect-error +const prlWrong: IterableIterator = paintRequestList[Symbol.iterator](); + +declare const plugin: Plugin; +const pIterator: IterableIterator = plugin[Symbol.iterator](); +// @ts-expect-error +const pWrong: IterableIterator = plugin[Symbol.iterator](); + +declare const pluginArray: PluginArray; +const paIterator: IterableIterator = pluginArray[Symbol.iterator](); +// @ts-expect-error +const paWrong: IterableIterator = pluginArray[Symbol.iterator](); + +declare const svgLengthList: SVGLengthList; +const sllIterator: IterableIterator = svgLengthList[Symbol.iterator](); +// @ts-expect-error +const sllWrong: IterableIterator = svgLengthList[Symbol.iterator](); + +declare const svgNumberList: SVGNumberList; +const snlIterator: IterableIterator = svgNumberList[Symbol.iterator](); +// @ts-expect-error +const snlWrong: IterableIterator = svgNumberList[Symbol.iterator](); + +declare const svgPathSegList: SVGPathSegList; +const spslIterator: IterableIterator = svgPathSegList[Symbol.iterator](); +// @ts-expect-error +const spslWrong: IterableIterator = svgPathSegList[Symbol.iterator](); + +declare const svgPointList: SVGPointList; +const splIterator: IterableIterator = svgPointList[Symbol.iterator](); +// @ts-expect-error +const splWrong: IterableIterator = svgPointList[Symbol.iterator](); + +declare const svgStringList: SVGStringList; +const sslIterator: IterableIterator = svgStringList[Symbol.iterator](); +// @ts-expect-error +const sslWrong: IterableIterator = svgStringList[Symbol.iterator](); + +declare const svgTransformList: SVGTransformList; +const stlIterator: IterableIterator = svgTransformList[Symbol.iterator](); +// @ts-expect-error +const stlWrong: IterableIterator = svgTransformList[Symbol.iterator](); + +declare const sourceBufferList: SourceBufferList; +const sblIterator: IterableIterator = sourceBufferList[Symbol.iterator](); +// @ts-expect-error +const sblWrong: IterableIterator = sourceBufferList[Symbol.iterator](); + +declare const textTrackCueList: TextTrackCueList; +const ttclIterator: IterableIterator = textTrackCueList[Symbol.iterator](); +// @ts-expect-error +const ttclWrong: IterableIterator = textTrackCueList[Symbol.iterator](); + +declare const textTrackList: TextTrackList; +const ttlIterator: IterableIterator = textTrackList[Symbol.iterator](); +// @ts-expect-error +const ttlWrong: IterableIterator = textTrackList[Symbol.iterator](); + +declare const touchList: TouchList; +const tlIterator: IterableIterator = touchList[Symbol.iterator](); +// @ts-expect-error +const tlWrong: IterableIterator = touchList[Symbol.iterator](); diff --git a/tests/type-definitions/global/web/queue-microtask.test.ts b/tests/type-definitions/global/web/queue-microtask.test.ts new file mode 100644 index 000000000000..1dfaf94520cb --- /dev/null +++ b/tests/type-definitions/global/web/queue-microtask.test.ts @@ -0,0 +1,17 @@ +import 'core-js/stable'; +import $queueMicrotask from 'core-js/stable/queue-microtask'; + +$queueMicrotask((): void => {}); + +queueMicrotask((): void => {}); +queueMicrotask(function (): void {}); + +// @ts-expect-error +$queueMicrotask(); + +// @ts-expect-error +queueMicrotask(); +// @ts-expect-error +queueMicrotask('not a function'); +// @ts-expect-error +queueMicrotask(a => {}); diff --git a/tests/type-definitions/global/web/self.dom.test.ts b/tests/type-definitions/global/web/self.dom.test.ts new file mode 100644 index 000000000000..d2a8903ee604 --- /dev/null +++ b/tests/type-definitions/global/web/self.dom.test.ts @@ -0,0 +1,8 @@ +import 'core-js/full'; + +const ref: typeof globalThis = self; + +// @ts-expect-error +self(); +// @ts-expect-error +self = {}; diff --git a/tests/type-definitions/global/web/structured-clone.test.ts b/tests/type-definitions/global/web/structured-clone.test.ts new file mode 100644 index 000000000000..273d6e81131a --- /dev/null +++ b/tests/type-definitions/global/web/structured-clone.test.ts @@ -0,0 +1,22 @@ +import 'core-js/stable'; +import $structuredClone from 'core-js/stable/structured-clone'; +import { assertNumber, assertString } from '../../helpers/helpers.js'; + +assertNumber($structuredClone(5)); + +assertNumber(structuredClone(5)); +assertString(structuredClone('text')); + +declare const buffer: ArrayBuffer; +const obj = { buffer }; +const cloned: typeof obj = structuredClone(obj, { transfer: [buffer] }); + +// @ts-expect-error +$structuredClone(); + +// @ts-expect-error +structuredClone(); +// @ts-expect-error +structuredClone('text', {}, 'extra'); +// @ts-expect-error +const n2: number = structuredClone('1'); diff --git a/tests/type-definitions/global/web/url-parse.test.ts b/tests/type-definitions/global/web/url-parse.test.ts new file mode 100644 index 000000000000..ce4bae440a05 --- /dev/null +++ b/tests/type-definitions/global/web/url-parse.test.ts @@ -0,0 +1,18 @@ +// URL has conflicts with @types/node +// import 'core-js/full'; +// +// const u1: URL | null = URL.parse('https://example.com/path?name=value#hash'); +// URL.parse('/path', 'https://example.com'); +// +// if (u1) { +// let str: string; +// str = u1.pathname; +// str = u1.hostname; +// str = u1.pathname; +// +// str = u1.toJSON(); +// str = u1.toString(); +// } +// +// // @ts-expect-error +// URL.parse(null); diff --git a/tests/type-definitions/global/web/url-search-params.dom.test.ts b/tests/type-definitions/global/web/url-search-params.dom.test.ts new file mode 100644 index 000000000000..361e93aaf7af --- /dev/null +++ b/tests/type-definitions/global/web/url-search-params.dom.test.ts @@ -0,0 +1,12 @@ +// URL has conflicts with @types/node +// import 'core-js/full'; +// +// const u0 = new URLSearchParams(); +// const u1 = new URLSearchParams('a=1&b=2'); +// const u2 = new URLSearchParams([['a', '1'], ['b', '2']]); +// const u3 = new URLSearchParams({ a: '1', b: '2' }); +// +// // @ts-expect-error +// new URLSearchParams(123); +// // @ts-expect-error +// new URLSearchParams([1, 2, 3]); diff --git a/tests/type-definitions/global/web/url-to-json.dom.test.ts b/tests/type-definitions/global/web/url-to-json.dom.test.ts new file mode 100644 index 000000000000..49812eee97fe --- /dev/null +++ b/tests/type-definitions/global/web/url-to-json.dom.test.ts @@ -0,0 +1,21 @@ +// URL has conflicts with @types/node +// import 'core-js/full'; +// +// declare const urlLike: URL; +// const str: string = urlLike.toJSON(); +// +// // @ts-expect-error +// const num: number = urlLike.toJSON(); +// // @ts-expect-error +// urlLike.toJSON('param'); + +// const url1 = new URL('https://example.com'); +// new URL('page', 'https://example.com'); +// new URL('/path', url1); +// +// // @ts-expect-error +// new URL(); +// // @ts-expect-error +// new URL(123); +// // @ts-expect-error +// new URL('abc', 456); diff --git a/tests/type-definitions/helpers/helpers.pure.ts b/tests/type-definitions/helpers/helpers.pure.ts new file mode 100644 index 000000000000..a1f04db92fef --- /dev/null +++ b/tests/type-definitions/helpers/helpers.pure.ts @@ -0,0 +1,71 @@ +interface CoreJSPromiseLike { + then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): PromiseLike; + + finally(onfinally?: (() => void) | undefined | null): PromiseLike; +} +export function assertCoreJSPromiseLike(value: CoreJSPromiseLike): asserts value is CoreJSPromiseLike {} + +export interface CoreJSMapLike extends Map { + getOrInsert(key: K, defaultValue: V): V; + + getOrInsertComputed(key: K, callback: (key: K) => V): V; +} +export function assertCoreJSMapLike(value: CoreJSMapLike): asserts value is CoreJSMapLike {} + +export interface CoreJSWeakMapLike extends WeakMap { + getOrInsert(key: K, defaultValue: V): V; + + getOrInsertComputed(key: K, callback: (key: K) => V): V; +} +export function assertCoreJSWeakMapLike(value: CoreJSWeakMapLike): asserts value is CoreJSWeakMapLike {} + +export interface CoreJSSetLike extends Set { + union(...args: any[]): CoreJSSetLike; + intersection(...args: any[]): CoreJSSetLike; + difference(...args: any[]): CoreJSSetLike; + symmetricDifference(...args: any[]): CoreJSSetLike; + isSubsetOf(...args: any[]): boolean; + isSupersetOf(...args: any[]): boolean; + isDisjointFrom(...args: any[]): boolean; +} +export function assertCoreJSSetLike(value: CoreJSSetLike): asserts value is CoreJSSetLike {} + +export interface CoreJSWeakSetLike extends WeakSet {} +export function assertCoreJSWeakSetLike(value: CoreJSWeakSetLike): asserts value is CoreJSWeakSetLike {} + +// TNext undefined added because of until TS 5.6 Iterator used undefined as TNext defaults +export interface CoreJSIteratorLike extends Iterator { + chunks(...args: any[]): CoreJSIteratorLike; + windows(...args: any[]): CoreJSIteratorLike; + map(...args: any[]): CoreJSIteratorLike; + filter(...args: any[]): CoreJSIteratorLike; + take(...args: any[]): CoreJSIteratorLike; + drop(...args: any[]): CoreJSIteratorLike; + flatMap(...args: any[]): CoreJSIteratorLike; + reduce(...args: any[]): U; + toArray(): T[]; + forEach(...args: any[]): void; + some(...args: any[]): boolean; + every(...args: any[]): boolean; + find(...args: any[]): T | undefined; + join(...args: any[]): string; +} +export function assertCoreJSIteratorLike(value: CoreJSIteratorLike): asserts value is CoreJSIteratorLike {} + +interface CoreJSAsyncIteratorLike { + drop(...args: any[]): any; + every(...args: any[]): any; + filter(...args: any[]): CoreJSAsyncIteratorLike; + find(...args: any[]): any; + flatMap(...args: any[]): any; + forEach(...args: any[]): any; + map(mapper: (value: T, index: number) => U): CoreJSAsyncIteratorLike; + reduce(...args: any[]): any; + some(...args: any[]): any; + take(limit: number): CoreJSAsyncIteratorLike; + toArray(...args: any[]): any; +} +export function assertCoreJSAsyncIteratorLike(value: CoreJSAsyncIteratorLike): asserts value is CoreJSAsyncIteratorLike {} + +type HasCause = 'cause' extends keyof T ? T : never; +export function assertHasCause(value: T): asserts value is HasCause & { cause: unknown } {} diff --git a/tests/type-definitions/helpers/helpers.ts b/tests/type-definitions/helpers/helpers.ts new file mode 100644 index 000000000000..90d997bcaa0c --- /dev/null +++ b/tests/type-definitions/helpers/helpers.ts @@ -0,0 +1,7 @@ +export function assertNumber(x: number) {} + +export function assertNumberArray(x: number[]) {} + +export function assertString(x: string) {} +export function assertStringArray(x: string[]) {} +export function assertBool(x: boolean) {} diff --git a/tests/type-definitions/package-lock.json b/tests/type-definitions/package-lock.json index f5989ce6d385..d8a3483156f7 100644 --- a/tests/type-definitions/package-lock.json +++ b/tests/type-definitions/package-lock.json @@ -6,22 +6,25 @@ "": { "name": "tests/type-definitions", "devDependencies": { - "typescript": "^5.9.3" + "@types/node": "^25.3.0" } }, - "node_modules/typescript": { - "version": "5.9.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", - "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "node_modules/@types/node": { + "version": "25.3.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.3.0.tgz", + "integrity": "sha512-4K3bqJpXpqfg2XKGK9bpDTc6xO/xoUP/RBWS7AtRMug6zZFaRekiLzjVtAoZMquxoAbzBvy5nxQ7veS5eYzf8A==", "dev": true, - "license": "Apache-2.0", - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=14.17" + "license": "MIT", + "dependencies": { + "undici-types": "~7.18.0" } + }, + "node_modules/undici-types": { + "version": "7.18.2", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz", + "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==", + "dev": true, + "license": "MIT" } } } diff --git a/tests/type-definitions/package.json b/tests/type-definitions/package.json index dffa3cb452e1..b3e5447bace7 100644 --- a/tests/type-definitions/package.json +++ b/tests/type-definitions/package.json @@ -1,6 +1,7 @@ { "name": "tests/type-definitions", + "type": "module", "devDependencies": { - "typescript": "^5.9.3" + "@types/node": "^25.3.0" } } diff --git a/tests/type-definitions/pure/common/date.test.ts b/tests/type-definitions/pure/common/date.test.ts new file mode 100644 index 000000000000..bed02b60a976 --- /dev/null +++ b/tests/type-definitions/pure/common/date.test.ts @@ -0,0 +1,4 @@ +import $Date from '@core-js/pure/full/date/index'; + +new $Date(); +new $Date('2020-01-01'); diff --git a/tests/type-definitions/pure/common/parse-float.test.ts b/tests/type-definitions/pure/common/parse-float.test.ts new file mode 100644 index 000000000000..de75723fe936 --- /dev/null +++ b/tests/type-definitions/pure/common/parse-float.test.ts @@ -0,0 +1,6 @@ +import $parseFloat from '@core-js/pure/full/parse-float'; + +const res: number = $parseFloat('123.45'); + +// @ts-expect-error +$parseFloat(123); diff --git a/tests/type-definitions/pure/common/parse-int.test.ts b/tests/type-definitions/pure/common/parse-int.test.ts new file mode 100644 index 000000000000..ed8e39e43bec --- /dev/null +++ b/tests/type-definitions/pure/common/parse-int.test.ts @@ -0,0 +1,6 @@ +import $parseInt from '@core-js/pure/full/parse-int'; + +const res: number = $parseInt('123'); + +// @ts-expect-error +$parseInt(123); diff --git a/tests/type-definitions/pure/entries.pure.ts b/tests/type-definitions/pure/entries.pure.ts new file mode 100644 index 000000000000..8d6e1f2ec450 --- /dev/null +++ b/tests/type-definitions/pure/entries.pure.ts @@ -0,0 +1,8 @@ +import $Date from '@core-js/pure/full/date/index'; +new $Date(); + +import $Date2 from '@core-js/pure/full/date/index.js'; +new $Date2(); + +import $Date3 from '@core-js/pure/full/date'; +new $Date3(); diff --git a/tests/type-definitions/pure/proposals/accessible-object-hasownproperty.test.ts b/tests/type-definitions/pure/proposals/accessible-object-hasownproperty.test.ts new file mode 100644 index 000000000000..f37738e672c8 --- /dev/null +++ b/tests/type-definitions/pure/proposals/accessible-object-hasownproperty.test.ts @@ -0,0 +1,20 @@ +import objectHasOwn from '@core-js/pure/full/object/has-own'; + +const res: boolean = objectHasOwn({ a: 1 }, 'a'); +objectHasOwn([], 0); +objectHasOwn(new Date(), 'toISOString'); +objectHasOwn(Object.create(null), Symbol.iterator); +objectHasOwn(function () {}, 'call'); +objectHasOwn(Object.prototype, 'toString'); + +// @ts-expect-error +objectHasOwn(1, 'a'); + +// @ts-expect-error +objectHasOwn({ a: 1 }, {}); + +// @ts-expect-error +objectHasOwn({ a: 1 }); + +// @ts-expect-error +objectHasOwn(); diff --git a/tests/type-definitions/pure/proposals/array-filtering.test.ts b/tests/type-definitions/pure/proposals/array-filtering.test.ts new file mode 100644 index 000000000000..5c257715142e --- /dev/null +++ b/tests/type-definitions/pure/proposals/array-filtering.test.ts @@ -0,0 +1,9 @@ +import arrayFilterReject from '@core-js/pure/full/array/filter-reject'; + +const res: number[] = arrayFilterReject([1, 2, 3], (v, i, arr) => v > 1); +arrayFilterReject(['a', 'b'], (v, i, arr) => v === 'a'); +const arr: number[] = [1, 2, 3]; +arrayFilterReject(arr, function (v) { return v < 2; }, { foo: true }); + +// @ts-expect-error +[1, 2, 3].arrayFilterReject((x: string) => false); diff --git a/tests/type-definitions/pure/proposals/array-find-from-last.test.ts b/tests/type-definitions/pure/proposals/array-find-from-last.test.ts new file mode 100644 index 000000000000..d7ad60c91e5f --- /dev/null +++ b/tests/type-definitions/pure/proposals/array-find-from-last.test.ts @@ -0,0 +1,23 @@ +import arrayFindLast from '@core-js/pure/full/array/find-last'; +import arrayFindLastIndex from '@core-js/pure/full/array/find-last-index'; + +const res: number | undefined = arrayFindLast([1, 2, 3], v => v > 1); +arrayFindLast([1, 2, 3], (v): v is 2 => v === 2); +arrayFindLast(['a', 'b', 'c'], v => v === 'b'); +arrayFindLast(['a', 'b', 'c'], (v): v is 'b' => v === 'b'); +arrayFindLastIndex([1, 2, 3], v => v === 2); +const nums: number[] = [1, 2, 3]; +const res2: number | undefined = arrayFindLast(nums, (v, i, arr) => v > 1 && arr.length > 0, {}); +arrayFindLastIndex(nums, (v, i, arr) => v > 0, {}); +const m = ['a', 2, 3] as (string | number)[]; +arrayFindLast(m, (v): v is string => typeof v === 'string'); + +// @ts-expect-error +arrayFindLast([1, 2, 3]); +// @ts-expect-error +arrayFindLast([1, 2, 3], 'not function'); + +// @ts-expect-error +arrayFindLastIndex([1, 2, 3]); +// @ts-expect-error +arrayFindLastIndex([1, 2, 3], 'not function'); diff --git a/tests/type-definitions/pure/proposals/array-flat-map.test.ts b/tests/type-definitions/pure/proposals/array-flat-map.test.ts new file mode 100644 index 000000000000..8cf36ad56e9f --- /dev/null +++ b/tests/type-definitions/pure/proposals/array-flat-map.test.ts @@ -0,0 +1,41 @@ +import arrayFlatMap from '@core-js/pure/full/array/flat-map'; +import arrayFlat from '@core-js/pure/full/array/flat'; + +const flatMapped: number[] = arrayFlatMap([1, 2, 3], x => [x, x * 2]); +const flatMapped2: string[] = arrayFlatMap(['a', 'b', 'c'], x => [x, x.toUpperCase()]); +arrayFlatMap([1, 2, 3], x => x > 1 ? [x, x] : []); +arrayFlatMap([1, 2, 3], function (x) { return [this, x]; }, 123); +arrayFlatMap([1, 2, 3], (x, i, arr) => arr); + +arrayFlat([[1], [2], [3]]); +arrayFlat([[1], [2], [3]], 2); +arrayFlat([1, [2, [3, [4]]]], 2); +arrayFlat(['a', ['b', ['c']]]); +arrayFlat([1, 2, 3]); +arrayFlat([1, 2, 3], 0); + +const arr = [[1, 2], [3, 4], [5, 6]]; +arrayFlat(arr); +arrayFlat(arr, 1); +arrayFlat(arr, 2); + +const arr2: (number | number[])[] = [1, [2, 3], 4]; +arrayFlat(arr2); + +const arr3: (string | string[])[] = ['a', ['b', 'c'], 'd']; +arrayFlat(arr3); + +arrayFlat([[[[1]]]] as number[][][][], 3); + +// @ts-expect-error +arrayFlatMap([1, 2, 3]); +// @ts-expect-error +arrayFlatMap([1, 2, 3], 123); +// @ts-expect-error +arrayFlatMap([1, 2, 3], 'not function'); +// @ts-expect-error +arrayFlat([1, 2, 3] as any[], 'not a number'); +// @ts-expect-error +arrayFlatMap([1, 2, 3], x => x, 1, 2); +// @ts-expect-error +arrayFlat([1, 2, 3], 1, 2); diff --git a/tests/type-definitions/pure/proposals/array-from-async.test.ts b/tests/type-definitions/pure/proposals/array-from-async.test.ts new file mode 100644 index 000000000000..973c75ea42cd --- /dev/null +++ b/tests/type-definitions/pure/proposals/array-from-async.test.ts @@ -0,0 +1,46 @@ +import arrayFromAsync from '@core-js/pure/full/array/from-async'; +import promiseResolve from '@core-js/pure/full/promise/resolve'; +import { assertCoreJSPromiseLike } from '../../helpers/helpers.pure.js'; + +const p1 = arrayFromAsync([1, 2, 3]); +assertCoreJSPromiseLike(p1); +const p2 = arrayFromAsync([promiseResolve(1), 2, 3]); +assertCoreJSPromiseLike(p2); +const p3 = arrayFromAsync([1, 2, 3], (value: number, index: number) => value.toString()); +assertCoreJSPromiseLike(p3); +const p4 = arrayFromAsync([promiseResolve(1), 2, 3], (value: number) => value + 1); +assertCoreJSPromiseLike(p4); +const p5 = arrayFromAsync([1, 2, 3], function (this: { foo: string }, value: number) { return value.toString(); }, { foo: 'str' }); +assertCoreJSPromiseLike(p5); + +async function t1() { + const n: number[] = await arrayFromAsync([1, 2, 3]); + const m: number[] = await arrayFromAsync([Promise.resolve(1), 2, 3]); + const s: string[] = await arrayFromAsync([1, 2, 3], (value: number) => value.toString()); +} + +async function t2() { + const bar: number[] = await arrayFromAsync([1, 2, 3], async (v: number) => v + 1); + const foo: string[] = await arrayFromAsync([Promise.resolve(1), 2], async (v: number) => String(v)); +} + +declare const arrLike: { [index: number]: PromiseLike; length: 2 }; +const p6 = arrayFromAsync(arrLike); +assertCoreJSPromiseLike(p6); +const p7 = arrayFromAsync(arrLike, (value: number) => value); +assertCoreJSPromiseLike(p7); + +// @ts-expect-error +arrayFromAsync([1, 2, 3], (value: string) => value); +// @ts-expect-error +arrayFromAsync([1, 2, 3], (value: string) => 1); +// @ts-expect-error +arrayFromAsync(['a', 'b', 'c'], (value: number) => value); +// @ts-expect-error +arrayFromAsync([Promise.resolve(1), 2, 3], (value: string) => value); +// // @ts-expect-error +// arrayFromAsync((async function* () { yield 'a'; })(), (value: number) => value); + +declare const strArrLike: { [index: number]: string; length: 3 }; +// @ts-expect-error +arrayFromAsync(strArrLike, (value: number) => value); diff --git a/tests/type-definitions/pure/proposals/array-grouping.test.ts b/tests/type-definitions/pure/proposals/array-grouping.test.ts new file mode 100644 index 000000000000..7c2cf93d9c09 --- /dev/null +++ b/tests/type-definitions/pure/proposals/array-grouping.test.ts @@ -0,0 +1,37 @@ +import objectGroupBy from '@core-js/pure/full/object/group-by'; +import mapGroupBy from '@core-js/pure/full/map/group-by'; +import { assertCoreJSMapLike } from '../../helpers/helpers.pure.js'; + +const arr = [1, 2, 3, 4, 5]; +const objGroup: Partial> = objectGroupBy(arr, x => x % 2 === 0 ? 'even' : 'odd'); +const mapGroup = mapGroupBy(arr, x => x % 2 === 0 ? 'even' : 'odd'); +assertCoreJSMapLike<'even' | 'odd', number[]>(mapGroup); +const objGroup2: Partial> = objectGroupBy(['foo', 'bar', 'baz'], (s, i) => i > 1 ? s[0] : 'x'); +const mapGroup2 = mapGroupBy(['foo', 'bar', 'baz'], (s, i) => i > 1 ? s[0] : 'x'); +assertCoreJSMapLike(mapGroup2); + +objectGroupBy('test', c => c); +objectGroupBy(new Set([1, 2, 3]), item => item > 2 ? 'big' : 'small'); +objectGroupBy([], _ => 'x'); + +mapGroupBy('hello', c => c.charCodeAt(0)); +mapGroupBy(new Set(['a', 'b', 'c']), (x, i) => i); + +// @ts-expect-error +objectGroupBy(); +// @ts-expect-error +objectGroupBy([1, 2, 3]); +// @ts-expect-error +objectGroupBy([1, 2, 3], 123); +// @ts-expect-error +objectGroupBy(123, x => x); +// @ts-expect-error +objectGroupBy([1, 2, 3], (a, b, c) => a); +// @ts-expect-error +mapGroupBy(); +// @ts-expect-error +mapGroupBy([1, 2, 3]); +// @ts-expect-error +mapGroupBy(123, x => x); +// @ts-expect-error +mapGroupBy([1, 2, 3], (a, b, c) => a); diff --git a/tests/type-definitions/pure/proposals/array-includes.test.ts b/tests/type-definitions/pure/proposals/array-includes.test.ts new file mode 100644 index 000000000000..107134de0407 --- /dev/null +++ b/tests/type-definitions/pure/proposals/array-includes.test.ts @@ -0,0 +1,19 @@ +import arrayIncludes from '@core-js/pure/full/array/includes'; + +const arr: number[] = [1, 2, 3]; +const arrRes: boolean = arrayIncludes(arr, 2); +const arrRes2: boolean = arrayIncludes(arr, 2, 1); + +const strArr: string[] = ['a', 'b', 'c']; +const strArrRes: boolean = arrayIncludes(strArr, 'b'); +const strArrRes2: boolean = arrayIncludes(strArr, 'b', 1); + +// @ts-expect-error +arrayIncludes(); +// @ts-expect-error +arrayIncludes(1, '2'); + +// @ts-expect-error +arrayIncludes(2); +// @ts-expect-error +arrayIncludes('b', true); diff --git a/tests/type-definitions/pure/proposals/array-is-template-object.test.ts b/tests/type-definitions/pure/proposals/array-is-template-object.test.ts new file mode 100644 index 000000000000..8dcf17c0fed5 --- /dev/null +++ b/tests/type-definitions/pure/proposals/array-is-template-object.test.ts @@ -0,0 +1,17 @@ +import arrayIsTemplateObject from '@core-js/pure/full/array/is-template-object'; +import objectFreeze from '@core-js/pure/full/object/freeze'; +import $Symbol from '@core-js/pure/full/symbol/index'; + +const t: boolean = arrayIsTemplateObject([]); +arrayIsTemplateObject({}); +arrayIsTemplateObject(['a', 'b']); +arrayIsTemplateObject(objectFreeze(['foo', 'bar'])); +arrayIsTemplateObject(123); +arrayIsTemplateObject('str'); +arrayIsTemplateObject($Symbol()); + +declare const x: unknown; +if (arrayIsTemplateObject(x)) { + x.raw; + const _: readonly string[] = x.raw; +} diff --git a/tests/type-definitions/pure/proposals/array-unique.test.ts b/tests/type-definitions/pure/proposals/array-unique.test.ts new file mode 100644 index 000000000000..16491b659180 --- /dev/null +++ b/tests/type-definitions/pure/proposals/array-unique.test.ts @@ -0,0 +1,30 @@ +import arrayUniqueBy from '@core-js/pure/full/array/unique-by'; + +interface Obj { + a: number; + b: string +} +const arr: Obj[] = [{ a: 1, b: 'x' }, { a: 2, b: 'y' }]; +const arrRes: Obj[] = arrayUniqueBy(arr); +const arrRes2: Obj[] = arrayUniqueBy(arr, 'a'); +const arrRes3: Obj[] = arrayUniqueBy(arr, obj => obj.b); + +const numArr: number[] = [1, 2, 1, 3]; +const numArrRes: number[] = arrayUniqueBy(numArr); +const numArrRes2: number[] = arrayUniqueBy(numArr, x => x % 2); + +// @ts-expect-error +arrayUniqueBy(123); +// @ts-expect-error +arrayUniqueBy(true); +// @ts-expect-error +arrayUniqueBy({}); +// @ts-expect-error +arrayUniqueBy(''); + +// @ts-expect-error +arrayUniqueBy(1); +// @ts-expect-error +arrayUniqueBy({}); +// @ts-expect-error +arrayUniqueBy(true); diff --git a/tests/type-definitions/pure/proposals/async-iteration.es2018.test.ts b/tests/type-definitions/pure/proposals/async-iteration.es2018.test.ts new file mode 100644 index 000000000000..cf327adc8455 --- /dev/null +++ b/tests/type-definitions/pure/proposals/async-iteration.es2018.test.ts @@ -0,0 +1,12 @@ +import $Symbol from '@core-js/pure/full/symbol/index'; + +async function * makeAsyncIterable() { + yield 1; + yield 2; +} + +for await (const x of { + [$Symbol.asyncIterator]: makeAsyncIterable, +}) { + const n: number = x; +} diff --git a/tests/type-definitions/pure/proposals/async-iteration.test.ts b/tests/type-definitions/pure/proposals/async-iteration.test.ts new file mode 100644 index 000000000000..888b6f1f98a5 --- /dev/null +++ b/tests/type-definitions/pure/proposals/async-iteration.test.ts @@ -0,0 +1,8 @@ +import $Symbol from '@core-js/pure/full/symbol/index'; + +const sym: symbol = $Symbol.asyncIterator; + +// @ts-expect-error +const bad1: string = $Symbol.asyncIterator; +// @ts-expect-error +$Symbol['asyncIterator'] = $Symbol('other'); diff --git a/tests/type-definitions/pure/proposals/async-iterator-helper.es2018.test.ts b/tests/type-definitions/pure/proposals/async-iterator-helper.es2018.test.ts new file mode 100644 index 000000000000..40aa60f9c955 --- /dev/null +++ b/tests/type-definitions/pure/proposals/async-iterator-helper.es2018.test.ts @@ -0,0 +1,29 @@ +import from from '@core-js/pure/full/async-iterator/from'; +import filter from '@core-js/pure/full/async-iterator/filter'; +import flatMap from '@core-js/pure/full/async-iterator/flat-map'; +import map from '@core-js/pure/full/async-iterator/map'; +import take from '@core-js/pure/full/async-iterator/take'; +import drop from '@core-js/pure/full/async-iterator/drop'; +import toAsync from '@core-js/pure/full/iterator/to-async'; + +const aitn = from([1]); +for await (const v of aitn) {} + +const ait1 = filter(aitn, (v: number, i: number) => v > 0); +for await (const v of ait1) {} + +const ait2 = flatMap(aitn, (v: number, i: number) => `${ v }`); +for await (const v of ait2) {} + +const ait3 = map(aitn, (v: number, i: number) => v * 2); +for await (const v of ait3) {} + +const ait4 = take(aitn, 10); +for await (const v of ait4) {} + +const ait5 = drop(aitn, 3); +for await (const v of ait5) {} + +declare const itn: Iterator; +const ait6 = toAsync(itn); +for await (const v of ait6) {} diff --git a/tests/type-definitions/pure/proposals/async-iterator-helper.test.ts b/tests/type-definitions/pure/proposals/async-iterator-helper.test.ts new file mode 100644 index 000000000000..fd9024de9779 --- /dev/null +++ b/tests/type-definitions/pure/proposals/async-iterator-helper.test.ts @@ -0,0 +1,117 @@ +import drop from '@core-js/pure/full/async-iterator/drop'; +import every from '@core-js/pure/full/async-iterator/every'; +import filter from '@core-js/pure/full/async-iterator/filter'; +import find from '@core-js/pure/full/async-iterator/find'; +import flatMap from '@core-js/pure/full/async-iterator/flat-map'; +import forEach from '@core-js/pure/full/async-iterator/for-each'; +import from from '@core-js/pure/full/async-iterator/from'; +import map from '@core-js/pure/full/async-iterator/map'; +import reduce from '@core-js/pure/full/async-iterator/reduce'; +import some from '@core-js/pure/full/async-iterator/some'; +import take from '@core-js/pure/full/async-iterator/take'; +import toArray from '@core-js/pure/full/async-iterator/to-array'; +import toAsync from '@core-js/pure/full/iterator/to-async'; +import { assertCoreJSAsyncIteratorLike, assertCoreJSPromiseLike } from '../../helpers/helpers.pure.js'; + +const aitn = from([1]); +assertCoreJSAsyncIteratorLike(aitn); +const aiton = from([1, 2, 3]); +aiton.next(); +aiton.toArray(); +from(new Set([1, 2, 3])); +from((function * () { yield 3; })()); +const aitos = from('abc'); + +declare const ilb: Iterable; +declare const is: Iterator; +declare const itn: Iterator; + +from(aiton); +from(ilb); + +// @ts-expect-error +from(123); +// @ts-expect-error +from({}); +// @ts-expect-error +from(); +// @ts-expect-error +from({ next: () => 1 }); + +const r1 = every(aiton, (v: number, i: number) => v > 0); +assertCoreJSPromiseLike(r1); +const r2 = find(aiton, (v: number, i: number) => v > 0); +assertCoreJSPromiseLike(r2); +const r3 = forEach(aiton, (v: number, i: number) => { }); +assertCoreJSPromiseLike(r3); +const reduceNoInit = reduce(aiton, (acc: number, v: number) => acc + v); +assertCoreJSPromiseLike(reduceNoInit); +const r4 = reduce(aiton, (acc: number, v: number, i: number) => acc + v, 0); +assertCoreJSPromiseLike(r4); +const reduceDiffType = reduce(aiton, (acc: string, v: number) => acc + v, ''); +assertCoreJSPromiseLike(reduceDiffType); +const r5 = some(aiton, (v: number, i: number) => v > 0); +assertCoreJSPromiseLike(r5); +const r6 = toArray(aiton); +assertCoreJSPromiseLike(r6); + +const ait1 = filter(aiton, (v: number, i: number) => v > 0); +assertCoreJSAsyncIteratorLike(ait1); +const ait2 = flatMap(aiton, (v: number, i: number) => `${ v }`); +assertCoreJSAsyncIteratorLike(ait2); +const ait3 = map(aiton, (v: number, i: number) => v * 2); +assertCoreJSAsyncIteratorLike(ait3); +const ait4 = take(aiton, 10); +assertCoreJSAsyncIteratorLike(ait4); +const ait5 = drop(aiton, 3); +assertCoreJSAsyncIteratorLike(ait5); +const ait6 = toAsync(itn); +assertCoreJSAsyncIteratorLike(ait6); + +const filterWithNull = filter(aiton, (v: number) => v > 0 ? v : null); +assertCoreJSAsyncIteratorLike(filterWithNull); +const filterWithString = filter(aiton, (v: number) => v > 0 ? 'yes' : ''); +assertCoreJSAsyncIteratorLike(filterWithString); +const filterWithNumber = filter(aiton, (v: number) => v); +assertCoreJSAsyncIteratorLike(filterWithNumber); + +const findWithNull = find(aiton, (v: number) => v > 0 ? v : null); +assertCoreJSPromiseLike(findWithNull); +const findWithString = find(aiton, (v: number) => v > 0 ? 'yes' : ''); +assertCoreJSPromiseLike(findWithString); +const findWithNumber = find(aiton, (v: number) => v); +assertCoreJSPromiseLike(findWithNumber); + +toAsync(is); + +// @ts-expect-error +drop(aitn); +// @ts-expect-error +every(aitn); +// @ts-expect-error +filter(aitn); +// @ts-expect-error +find(aitn); +// @ts-expect-error +flatMap(aitn); +// @ts-expect-error +forEach(aitn); +// @ts-expect-error +map(aitn); +// @ts-expect-error +map(aitos, (v: string, i: number) => v.length === 1, 'extra'); +// @ts-expect-error +reduce(aitn); +// @ts-expect-error +reduce(aiton, (acc: string, v: number) => acc + v, 1); +// @ts-expect-error +some(aitn); +// @ts-expect-error +take(aitn); +// @ts-expect-error +toArray(aitn, 1); + +const s0 = toArray(aiton); +assertCoreJSPromiseLike(s0); +const f0 = find(aitos, (v: string, i: number) => v.length === 1); +assertCoreJSPromiseLike(f0); diff --git a/tests/type-definitions/pure/proposals/await-dictionary.test.ts b/tests/type-definitions/pure/proposals/await-dictionary.test.ts new file mode 100644 index 000000000000..d616ca69a540 --- /dev/null +++ b/tests/type-definitions/pure/proposals/await-dictionary.test.ts @@ -0,0 +1,49 @@ +import promiseAllKeyed from '@core-js/pure/full/promise/all-keyed'; +import promiseAllSettledKeyed from '@core-js/pure/full/promise/all-settled-keyed'; +import promiseResolve from '@core-js/pure/full/promise/resolve'; +import { assertCoreJSPromiseLike } from '../../helpers/helpers.pure.js'; + +const res = promiseAllKeyed({ + a: promiseResolve(1), + b: promiseResolve('string'), + c: promiseResolve(true), +}); +assertCoreJSPromiseLike<{ a: number, b: string, c: boolean }>(res); + +declare const sym: unique symbol; +const res2 = promiseAllKeyed({ + [sym]: promiseResolve(1), +}); +assertCoreJSPromiseLike<{ [sym]: number }>(res2); + +promiseAllKeyed({ + a: 1, + b: promiseResolve('string'), + c: 3, +}); + +// @ts-expect-error +promiseAllKeyed(); +// @ts-expect-error +promiseAllKeyed([promiseResolve(1), promiseResolve(2)]); + +promiseAllSettledKeyed({ + a: Promise.resolve(1), + b: Promise.resolve('string'), + c: Promise.resolve(true), +}); + +promiseAllSettledKeyed({ + [sym]: Promise.resolve(1), +}); + +promiseAllSettledKeyed({ + a: 1, + b: Promise.resolve('string'), + c: 3, +}); + +// @ts-expect-error +promiseAllSettledKeyed(); +// @ts-expect-error +promiseAllSettledKeyed([promiseResolve(1), promiseResolve(2)]); diff --git a/tests/type-definitions/pure/proposals/change-array-by-copy.test.ts b/tests/type-definitions/pure/proposals/change-array-by-copy.test.ts new file mode 100644 index 000000000000..6dfc0494fb9c --- /dev/null +++ b/tests/type-definitions/pure/proposals/change-array-by-copy.test.ts @@ -0,0 +1,48 @@ +import arrayToReversed from '@core-js/pure/full/array/to-reversed'; +import arrayToSorted from '@core-js/pure/full/array/to-sorted'; +import arrayToSpliced from '@core-js/pure/full/array/to-spliced'; +import arrayWith from '@core-js/pure/full/array/with'; + +const arr: number[] = [1, 2, 3]; +const arrRev: number[] = arrayToReversed(arr); +const arrSorted: number[] = arrayToSorted(arr); +const arrSorted2: number[] = arrayToSorted(arr, (a, b) => b - a); +const arrSpliced: number[] = arrayToSpliced(arr, 1, 1, 4, 5); +const arrSpliced2: number[] = arrayToSpliced(arr, 1); +const arrSpliced3: number[] = arrayToSpliced(arr, 1, 2); +const arrWith: number[] = arrayWith(arr, 1, 42); + +const sarr: string[] = ['a', 'b', 'c']; +const sarrRev: string[] = arrayToReversed(sarr); +const sarrSorted: string[] = arrayToSorted(sarr); +const sarrWith: string[] = arrayWith(sarr, 0, 'z'); +const sarrSpliced: string[] = arrayToSpliced(sarr, 0, 1); + +// @ts-expect-error +arrayToReversed(arr, 1); +// @ts-expect-error +arrayToSorted(arr, 'string'); +// @ts-expect-error +arrayToSorted(arr, (a: number, b: string) => 0); +// @ts-expect-error +arrayToSpliced(arr); +// @ts-expect-error +arrayToSpliced(arr, '1', 1); +// @ts-expect-error +arrayToSpliced(arr, 1, '1'); +// @ts-expect-error +arrayWith(arr); +// @ts-expect-error +arrayWith(arr, 1); +// @ts-expect-error +arrayWith(arr, '1', 2); + +const barr: boolean[] = [true, false]; +// @ts-expect-error +arrayToSorted(barr, (a: number, b: number) => 0); +// @ts-expect-error +arrayWith(barr, 0, 1); + +const arrStr: string[] = ['a', 'b']; +// @ts-expect-error +arrayWith(arrStr, 0, 1); diff --git a/tests/type-definitions/pure/proposals/collection-of-from.test.ts b/tests/type-definitions/pure/proposals/collection-of-from.test.ts new file mode 100644 index 000000000000..c37e7952e81b --- /dev/null +++ b/tests/type-definitions/pure/proposals/collection-of-from.test.ts @@ -0,0 +1,88 @@ +import mapFrom from '@core-js/pure/full/map/from'; +import mapOf from '@core-js/pure/full/map/of'; +import setFrom from '@core-js/pure/full/set/from'; +import setOf from '@core-js/pure/full/set/of'; +import weakMapFrom from '@core-js/pure/full/weak-map/from'; +import weakMapOf from '@core-js/pure/full/weak-map/of'; +import weakSetFrom from '@core-js/pure/full/weak-set/from'; +import weakSetOf from '@core-js/pure/full/weak-set/of'; +import { assertCoreJSMapLike, assertCoreJSSetLike, assertCoreJSWeakMapLike, assertCoreJSWeakSetLike } from '../../helpers/helpers.pure.js'; + +const rm = mapFrom([[1, 'a'], [2, 'b']] as [number, string][]); +assertCoreJSMapLike(rm); +const rm2 = mapFrom([[1, 10], [2, 20]] as [number, number][], ([k, v]: [number, number]) => [k, v + k] as [number, number]); +assertCoreJSMapLike(rm2); +mapFrom([[1, 10], [2, 20]] as [number, number][], function (this: { n: number }, [k, v]: [number, number]) { return [k, v + this.n] as [number, number]; }, { n: 2 }); +// @ts-expect-error +mapFrom([['a', 1], ['b', 2]], (v: string, k: number) => v); +// @ts-expect-error +mapFrom([1, 2]); +// @ts-expect-error +mapFrom(); + +mapOf(['a', 1], ['b', 2]); +const rm4 = mapOf(['a', 1], ['b', 2]); +assertCoreJSMapLike(rm4); +// @ts-expect-error +mapOf([1, 2, 3]); +// @ts-expect-error +mapOf(1, 2); + +const rs1 = setFrom([1, 2, 3]); +assertCoreJSSetLike(rs1); +const rs2 = setFrom([1, 2, 3], x => x.toString()); +assertCoreJSSetLike(rs2); +const rs3 = setFrom([['a', 1], ['b', 2]]); +assertCoreJSSetLike<(string | number)[]>(rs3); +setFrom(['a', 'b'], function (this: { s: string }, value: string) { return value + this.s; }, { s: '-' }); +// @ts-expect-error +setFrom([1, 2, 3], (v: string) => v); +// @ts-expect-error +setFrom(); + +const rso1 = setOf(1, 2, 3); +assertCoreJSSetLike(rso1); +const rso2 = setOf('a', 'b', 'c'); +assertCoreJSSetLike(rso2); +// @ts-expect-error +setOf({ foo: 'bar' }, 2); + +const rwm1 = weakMapFrom([[{ a: 1 }, 'x']] as [{ a: number }, string][]); +assertCoreJSWeakMapLike<{ a: number }, string>(rwm1); +const rwm2 = weakMapFrom([[{}, 1], [{}, 2]] as [object, number][], ([k, v]) => [k, v.toString()] as [object, string]); +assertCoreJSWeakMapLike(rwm2); +weakMapFrom([[{}, 1], [{}, 2]] as [object, number][], function (this: { s: string }, [k, v]: [object, number]) { return [k, this.s + v] as [object, string]; }, { s: '-' }); +// @ts-expect-error +weakMapFrom([[1, 2], [2, 3]]); +// @ts-expect-error +weakMapFrom([[{}, 1], [{}, 2]], (v: string, k: string) => v); +// @ts-expect-error +weakMapFrom([1, 2]); +// @ts-expect-error +weakMapFrom(); + +const rwmo1 = weakMapOf([{}, 2]); +assertCoreJSWeakMapLike(rwmo1); +// @ts-expect-error +weakMapOf([1, 2]); +// @ts-expect-error +weakMapOf({}); + +const rws1 = weakSetFrom([{}]); +assertCoreJSWeakSetLike(rws1); +const rws2 = weakSetFrom([{}, {}], x => x); +assertCoreJSWeakSetLike(rws2); +weakSetFrom([{}], function (this: { s: string }, obj: object) { return obj; }, { s: '-' }); +// @ts-expect-error +weakSetFrom([1, 2]); +// @ts-expect-error +weakSetFrom([{}], (v: number) => v); +// @ts-expect-error +weakSetFrom(); +// @ts-expect-error +weakSetFrom([{}], x => 'not-an-object'); + +const rwso1 = weakSetOf({}); +assertCoreJSWeakSetLike(rwso1); +// @ts-expect-error +weakSetOf(1); diff --git a/tests/type-definitions/pure/proposals/decorator-metadata.test.ts b/tests/type-definitions/pure/proposals/decorator-metadata.test.ts new file mode 100644 index 000000000000..eacd41c149fb --- /dev/null +++ b/tests/type-definitions/pure/proposals/decorator-metadata.test.ts @@ -0,0 +1,16 @@ +import metadata from '@core-js/pure/full/symbol/metadata'; + +const rsmd1: symbol = metadata; +const rsmd2: typeof metadata = metadata; + +interface T { + [metadata]?: object; +} + +const obj: T = {}; +obj[metadata] = { foo: 1 }; + +const maybeMeta: object | undefined = obj[metadata]; + +// @ts-expect-error +obj[metadata] = 123; diff --git a/tests/type-definitions/pure/proposals/error-cause.test.ts b/tests/type-definitions/pure/proposals/error-cause.test.ts new file mode 100644 index 000000000000..7636631b02b9 --- /dev/null +++ b/tests/type-definitions/pure/proposals/error-cause.test.ts @@ -0,0 +1,15 @@ +import $AggregateError from '@core-js/pure/full/aggregate-error'; +// import $Error from '@core-js/pure/full/error'; TODO separated entry points +import { assertHasCause } from '../../helpers/helpers.pure.js'; + +const prevError = new Error('Prev error'); +const someError = new Error('Some error'); + +// TODO other errors after separating Error entry points + +const resAE1 = new $AggregateError([someError], 'Error with cause', { cause: prevError }); +assertHasCause(resAE1); +const resAE2 = new $AggregateError([someError], 'Error with cause', { cause: null }); +assertHasCause(resAE2); +const resAE3 = new $AggregateError([someError], 'Error with cause', { cause: 'prev reason' }); +assertHasCause(resAE3); diff --git a/tests/type-definitions/pure/proposals/explicit-resource-management.test.ts b/tests/type-definitions/pure/proposals/explicit-resource-management.test.ts new file mode 100644 index 000000000000..198e5d38aac2 --- /dev/null +++ b/tests/type-definitions/pure/proposals/explicit-resource-management.test.ts @@ -0,0 +1,102 @@ +import promiseResolve from '@core-js/pure/full/promise/resolve'; +import symbolDispose from '@core-js/pure/full/symbol/dispose'; +import symbolAsyncDispose from '@core-js/pure/full/symbol/async-dispose'; +import symbolToStringTag from '@core-js/pure/full/symbol/to-string-tag'; +import iteratorRange from '@core-js/pure/full/iterator/range'; +import asyncIteratorFrom from '@core-js/pure/full/async-iterator/from'; +import $SuppressedError from '@core-js/pure/full/suppressed-error/constructor'; +import $DisposableStack from '@core-js/pure/full/disposable-stack/constructor'; +import $AsyncDisposableStack from '@core-js/pure/full/async-disposable-stack/constructor'; +import { assertCoreJSPromiseLike } from '../../helpers/helpers.pure.js'; + +const d: symbol = symbolDispose; +const ad: symbol = symbolAsyncDispose; + +// @ts-expect-error +const wrong: number = symbolDispose; + +const objD = { + [symbolDispose]() { /* empty */ }, +}; +objD[symbolDispose](); + +const objAD = { + [symbolAsyncDispose]() { return promiseResolve(); }, +}; +const p1 = objAD[symbolAsyncDispose](); +assertCoreJSPromiseLike(p1); + +const err1 = new $SuppressedError('err', 'suppressed', 'msg'); +err1.error; +err1.suppressed; +const m1: string = err1.message; +const _: Error = err1; + +const err2 = $SuppressedError(123, 456); +err2.error; +err2.suppressed; +err2.message; + +// @ts-expect-error +new $SuppressedError(1, 2, 3, 4); + +const objDS = new $DisposableStack(); +const disposed: boolean = objDS.disposed; +objDS.dispose(); +objDS.use(objD); +const ruse2: null = objDS.use(null); +const ruse3: undefined = objDS.use(undefined); +const radopt1: string = objDS.adopt('foo', (value: string) => { /* empty */ }); +objDS.defer(() => { /* empty */ }); +objDS.move(); +objDS[symbolDispose](); +const rts1: string = objDS[symbolToStringTag]; + +// @ts-expect-error +objDS.dispose(1); +// @ts-expect-error +objDS.use('foo'); +// @ts-expect-error +objDS.defer('bar'); +// @ts-expect-error +objDS.move(1); +// @ts-expect-error +objDS[symbolToStringTag] = 'foo'; + +$AsyncDisposableStack.prototype; +const objADS = new $AsyncDisposableStack(); +const disposedASD: boolean = objDS.disposed; +const rda = objADS.disposeAsync(); +assertCoreJSPromiseLike(rda); +objADS.use(objAD); +objADS.use(objD); +const ruseASD3: null = objADS.use(null); +const ruseASD4: undefined = objADS.use(undefined); +const radoptASD1: string = objADS.adopt('foo', (value: string) => { /* empty */ }); +const radoptASD2: string = objADS.adopt('foo', async (value: string) => { /* empty */ }); +const radoptASD3: string = objADS.adopt('foo', (value: string) => promiseResolve()); +const radoptASD4: string = objADS.adopt('foo', async (value: string) => promiseResolve()); +objADS.defer(() => { /* empty */ }); +objADS.defer(async () => { /* empty */ }); +objADS.defer(() => promiseResolve()); +objADS.defer(async () => promiseResolve()); +objADS.move(); +objADS[symbolAsyncDispose](); +const rtsASD1: string = objADS[symbolToStringTag]; + +// @ts-expect-error +objADS.disposeAsync(1).then(); +// @ts-expect-error +objADS.use('foo').then(); +// @ts-expect-error +objADS.defer('bar'); +// @ts-expect-error +objADS.move(1); +// @ts-expect-error +objADS[Symbol.toStringTag] = 'foo'; + +const iter = iteratorRange(1, 3); +iter[symbolDispose](); + +const asyncIter = asyncIteratorFrom([1, 2, 3]); +asyncIter[symbolAsyncDispose](); diff --git a/tests/type-definitions/pure/proposals/extractors.test.ts b/tests/type-definitions/pure/proposals/extractors.test.ts new file mode 100644 index 000000000000..4d79fef7a50e --- /dev/null +++ b/tests/type-definitions/pure/proposals/extractors.test.ts @@ -0,0 +1,10 @@ +import $customMatcher from '@core-js/pure/full/symbol/custom-matcher'; +import $Symbol from '@core-js/pure/full/symbol/index'; + +const rscs1: symbol = $customMatcher; +const rscs2: typeof $customMatcher = $customMatcher; + +// @ts-expect-error +$Symbol['customMatcher'] = $Symbol('other'); +// @ts-expect-error +const n: number = $customMatcher; diff --git a/tests/type-definitions/pure/proposals/float16.test.ts b/tests/type-definitions/pure/proposals/float16.test.ts new file mode 100644 index 000000000000..25baff63f4d9 --- /dev/null +++ b/tests/type-definitions/pure/proposals/float16.test.ts @@ -0,0 +1,6 @@ +import mathF16round from '@core-js/pure/full/math/f16round'; + +const res: number = mathF16round(1); + +// @ts-expect-error +mathF16round('123'); diff --git a/tests/type-definitions/pure/proposals/function-demethodize.test.ts b/tests/type-definitions/pure/proposals/function-demethodize.test.ts new file mode 100644 index 000000000000..5f2ec6d8ca54 --- /dev/null +++ b/tests/type-definitions/pure/proposals/function-demethodize.test.ts @@ -0,0 +1,7 @@ +import $demethodize from '@core-js/pure/full/function/demethodize'; + +function sumTo(this: { base: number }, a: number, b: number): number { + return this.base + a + b; +} + +$demethodize(sumTo); diff --git a/tests/type-definitions/pure/proposals/is-error.test.ts b/tests/type-definitions/pure/proposals/is-error.test.ts new file mode 100644 index 000000000000..8eb56a0f0376 --- /dev/null +++ b/tests/type-definitions/pure/proposals/is-error.test.ts @@ -0,0 +1,12 @@ +import $isError from '@core-js/pure/full/error/is-error'; + +const e = new Error(); +const ne = { foo: 1 }; + +const re1: boolean = $isError(e); +$isError(ne); +$isError(undefined); +$isError('str'); + +// @ts-expect-error +$isError(); diff --git a/tests/type-definitions/pure/proposals/iterator-chunking.test.ts b/tests/type-definitions/pure/proposals/iterator-chunking.test.ts new file mode 100644 index 000000000000..48c2d23add62 --- /dev/null +++ b/tests/type-definitions/pure/proposals/iterator-chunking.test.ts @@ -0,0 +1,29 @@ +import iteratorChunks from '@core-js/pure/full/iterator/chunks'; +import iteratorWindows from '@core-js/pure/full/iterator/windows'; +import { assertCoreJSIteratorLike } from '../../helpers/helpers.pure.js'; + +declare function getNumberIterator(): Iterator; + +const numbersIter = getNumberIterator(); + +const chunksObj = iteratorChunks(numbersIter, 2); +assertCoreJSIteratorLike(chunksObj); +const windowsObj = iteratorWindows(numbersIter, 4); +assertCoreJSIteratorLike(windowsObj); + +const chunkNext = chunksObj.next(); +const windowsNext = windowsObj.next(); + +// @ts-expect-error +iteratorChunks(numbersIter); +// @ts-expect-error +iteratorChunks(numbersIter, '2'); +// @ts-expect-error +iteratorChunks(numbersIter, 2, 3); + +// @ts-expect-error +iteratorWindows(numbersIter); +// @ts-expect-error +iteratorWindows(numbersIter, {}); +// @ts-expect-error +iteratorWindows(numbersIter, 4, 1); diff --git a/tests/type-definitions/pure/proposals/iterator-helpers.test.ts b/tests/type-definitions/pure/proposals/iterator-helpers.test.ts new file mode 100644 index 000000000000..e7f3db54399a --- /dev/null +++ b/tests/type-definitions/pure/proposals/iterator-helpers.test.ts @@ -0,0 +1,106 @@ +import iteratorMap from '@core-js/pure/full/iterator/map'; +import iteratorFilter from '@core-js/pure/full/iterator/filter'; +import iteratorTake from '@core-js/pure/full/iterator/take'; +import iteratorDrop from '@core-js/pure/full/iterator/drop'; +import iteratorFlatMap from '@core-js/pure/full/iterator/flat-map'; +import iteratorReduce from '@core-js/pure/full/iterator/reduce'; +import iteratorToArray from '@core-js/pure/full/iterator/to-array'; +import iteratorForEach from '@core-js/pure/full/iterator/for-each'; +import iteratorSome from '@core-js/pure/full/iterator/some'; +import iteratorEvery from '@core-js/pure/full/iterator/every'; +import iteratorFind from '@core-js/pure/full/iterator/find'; +import { assertCoreJSIteratorLike } from '../../helpers/helpers.pure.js'; + +declare const it: Iterator; +declare const itStr: Iterator; +declare const itNumStr: Iterator; + +const res = iteratorMap(it, (v, i) => String(v)); +assertCoreJSIteratorLike(res); +const mappedNum = iteratorMap(it, n => n + 1); +assertCoreJSIteratorLike(mappedNum); + +// @ts-expect-error +iteratorMap(); +// @ts-expect-error +iteratorMap((v, i, extra) => v + i + extra); + +const onlyEven = iteratorFilter(it, v => v % 2 === 0); +assertCoreJSIteratorLike(onlyEven); +const filtered = iteratorFilter(it, (v): v is number => typeof v === 'number'); +assertCoreJSIteratorLike(filtered); + +// @ts-expect-error +iteratorFilter(); +// @ts-expect-error +iteratorFilter((v, i, extra) => true); + +const taken = iteratorTake(it, 5); +assertCoreJSIteratorLike(taken); + +// @ts-expect-error +iteratorTake(); +// @ts-expect-error +iteratorTake('5'); + +const dropped = iteratorDrop(it, 3); +assertCoreJSIteratorLike(dropped); + +// @ts-expect-error +iteratorDrop('3'); + +const flatMapped = iteratorFlatMap(it, (v, i) => itStr); +assertCoreJSIteratorLike(flatMapped); +const flatMapped2 = iteratorFlatMap(it, (v, i) => ({ + [Symbol.iterator]: function * () { + yield String(v); + }, +})); +assertCoreJSIteratorLike(flatMapped2); + +// @ts-expect-error +iteratorFlatMap(); + +const sum1: number = iteratorReduce(it, (a, b, c) => a + b + c, 0); +const sum2: number = iteratorReduce(it, (a, b, c) => a + b + c, 0); +const strReduce: string = iteratorReduce( + it, + (acc: string, val) => acc + val, + '', +); + +// @ts-expect-error +iteratorReduce(); +// @ts-expect-error +iteratorReduce(it, (a, b, c, d) => a); + +const arr: number[] = iteratorToArray(it); + +iteratorForEach(it, (value, idx) => { + const x: number = value; + const y: number = idx; +}); + +// @ts-expect-error +iteratorForEach(it); + +const hasPositive: boolean = iteratorSome(it, (v, i) => v > 0); + +// @ts-expect-error +iteratorSome(it); +// @ts-expect-error +iteratorSome(it, (v, i, extra) => true); + +const allPositive: boolean = iteratorEvery(it, (v, i) => v > 0); + +// @ts-expect-error +iteratorEvery(it); +// @ts-expect-error +iteratorEvery(it, (v, i, extra) => true); + +const found1: number | undefined = iteratorFind(it, (v, i) => v > 5); +const findString: string | number | undefined = iteratorFind(itNumStr, (v): v is string => typeof v === 'string'); +iteratorFind(itNumStr, (v): v is string => typeof v === 'string'); + +// @ts-expect-error +iteratorFind(it); diff --git a/tests/type-definitions/pure/proposals/iterator-join.test.ts b/tests/type-definitions/pure/proposals/iterator-join.test.ts new file mode 100644 index 000000000000..6738482b3476 --- /dev/null +++ b/tests/type-definitions/pure/proposals/iterator-join.test.ts @@ -0,0 +1,15 @@ +import iteratorJoin from '@core-js/pure/full/iterator/join'; + +declare const it: Iterator; + +const res1: string = iteratorJoin(it); +const res2: string = iteratorJoin(it, ' '); +const res3: string = iteratorJoin(it, 5); +const res4: string = iteratorJoin(it, Symbol('x')); +const res5: string = iteratorJoin(it, undefined); +const res6: string = iteratorJoin(it, null); + +// @ts-expect-error +iteratorJoin(it, '+', '_'); +// @ts-expect-error +const res7: number = iteratorJoin(it); diff --git a/tests/type-definitions/pure/proposals/iterator-joint.test.ts b/tests/type-definitions/pure/proposals/iterator-joint.test.ts new file mode 100644 index 000000000000..24a6f5941068 --- /dev/null +++ b/tests/type-definitions/pure/proposals/iterator-joint.test.ts @@ -0,0 +1,23 @@ +import iteratorZip from '@core-js/pure/full/iterator/zip'; +import iteratorZipKeyed from '@core-js/pure/full/iterator/zip-keyed'; +import { assertCoreJSIteratorLike } from '../../helpers/helpers.pure.js'; + +const zipped1 = iteratorZip([[1, 2, 3], [4, 5, 6]]); +assertCoreJSIteratorLike(zipped1); +const zipped2 = iteratorZip([['a', 'b', 'c'], ['d', 'e', 'f']]); +assertCoreJSIteratorLike(zipped2); +const zipped3 = iteratorZip([[1, 2, 3], [4, 5, 6]], { mode: 'shortest' }); +assertCoreJSIteratorLike(zipped3); +const zipped4 = iteratorZipKeyed({ a: [1, 2, 3], b: [4, 5, 6] }); +assertCoreJSIteratorLike>(zipped4); +const zipped5 = iteratorZipKeyed({ a: ['a', 'b', 'c', 'd'], b: ['e', 'f'] }, { mode: 'shortest' }); +assertCoreJSIteratorLike>(zipped5); + +// @ts-expect-error +iteratorZip(true); +// @ts-expect-error +iteratorZip([[1, 2, 3], [4, 5, 6]], { mode: 'incorrect' }); +// @ts-expect-error +iteratorZipKeyed(42); +// @ts-expect-error +iteratorZipKeyed({ a: [1, 2, 3], b: [4, 5, 6] }, { foo: 'bar' }); diff --git a/tests/type-definitions/pure/proposals/iterator-range.test.ts b/tests/type-definitions/pure/proposals/iterator-range.test.ts new file mode 100644 index 000000000000..fbfd68366442 --- /dev/null +++ b/tests/type-definitions/pure/proposals/iterator-range.test.ts @@ -0,0 +1,17 @@ +import iteratorRange from '@core-js/pure/full/iterator/range'; +import { assertCoreJSIteratorLike } from '../../helpers/helpers.pure.js'; + +const rir1 = iteratorRange(1, 10); +assertCoreJSIteratorLike(rir1); +iteratorRange(1, 10, 1); +iteratorRange(1, 10, { step: 1 }); +iteratorRange(1, 10, { inclusive: true }); + +// @ts-expect-error +iteratorRange(0, 10, 'not-a-number'); +// @ts-expect-error +iteratorRange(0, 10, { inclusive: 3 }); +// @ts-expect-error +iteratorRange(0, 10, { step: 'smth' }); +// @ts-expect-error +iteratorRange(0, 10, { foo: 'bar' }); diff --git a/tests/type-definitions/pure/proposals/iterator-sequencing.test.ts b/tests/type-definitions/pure/proposals/iterator-sequencing.test.ts new file mode 100644 index 000000000000..563a3b26b407 --- /dev/null +++ b/tests/type-definitions/pure/proposals/iterator-sequencing.test.ts @@ -0,0 +1,28 @@ +import iteratorConcat from '@core-js/pure/full/iterator/concat'; +import { assertCoreJSIteratorLike } from '../../helpers/helpers.pure.js'; + +declare const its1: Iterable; +declare const arrs: string[]; +declare const arrn: number[]; +declare const arrb: boolean[]; +declare const itb1: Iterable; + +const ri1 = iteratorConcat(its1); +assertCoreJSIteratorLike(ri1); +const ri2 = iteratorConcat(arrs); +assertCoreJSIteratorLike(ri2); +const ri3 = iteratorConcat(arrn); +assertCoreJSIteratorLike(ri3); +const ri4 = iteratorConcat(arrb, itb1); +assertCoreJSIteratorLike(ri4); +const ri5 = iteratorConcat(); +assertCoreJSIteratorLike(ri5); +const ri6 = iteratorConcat(arrs, arrn); +assertCoreJSIteratorLike(ri6); + +// @ts-expect-error +iteratorConcat(1); +// @ts-expect-error +iteratorConcat(true); +// @ts-expect-error +iteratorConcat({}); diff --git a/tests/type-definitions/pure/proposals/json-parse-with-source.test.ts b/tests/type-definitions/pure/proposals/json-parse-with-source.test.ts new file mode 100644 index 000000000000..6f9e3bda7d9e --- /dev/null +++ b/tests/type-definitions/pure/proposals/json-parse-with-source.test.ts @@ -0,0 +1,36 @@ +import $rawJSON from '@core-js/pure/full/json/raw-json'; +import $isRawJSON from '@core-js/pure/full/json/is-raw-json'; +import $parse from '@core-js/pure/full/json/parse'; + +interface CoreJSRawJSON { + rawJSON: string; +} + +interface CoreJSReviverContext { + source: string | undefined; +} + +const r: CoreJSRawJSON = $rawJSON('{"a":123}'); + +const isr1: boolean = $isRawJSON(r); +const isr2: boolean = $isRawJSON({}); +const isr3: boolean = $isRawJSON('abc'); +const isr4: boolean = $isRawJSON(undefined); + +declare const smth: unknown; + +if ($isRawJSON(smth)) { + smth.rawJSON; + const s: string = smth.rawJSON; + // @ts-expect-error + smth.noProp; +} + +// @ts-expect-error +$rawJSON(123); +// @ts-expect-error +$rawJSON(); + +$parse('{"tooBigForNumber":9007199254740993}', (key: string, value: any, context: CoreJSReviverContext) => {}); +// @ts-expect-error +$parse('{"tooBigForNumber":9007199254740993}', (key: string, value: any, context: []) => {}); diff --git a/tests/type-definitions/pure/proposals/map-upsert.test.ts b/tests/type-definitions/pure/proposals/map-upsert.test.ts new file mode 100644 index 000000000000..d7af7a866d9b --- /dev/null +++ b/tests/type-definitions/pure/proposals/map-upsert.test.ts @@ -0,0 +1,20 @@ +import mapGetOrInsert from '@core-js/pure/full/map/get-or-insert'; +import mapGetOrInsertComputed from '@core-js/pure/full/map/get-or-insert-computed'; +import weakMapGetOrInsert from '@core-js/pure/full/weak-map/get-or-insert'; +import weakMapGetOrInsertComputed from '@core-js/pure/full/weak-map/get-or-insert-computed'; + +declare const map: Map; + +const a: number = mapGetOrInsert(map, 'x', 42); +const b: number = mapGetOrInsertComputed(map, 'y', k => k.length); + +// @ts-expect-error +mapGetOrInsert(map, 'x'); + +declare const wmap: WeakMap<{ id: number }, boolean>; + +const wb: boolean = weakMapGetOrInsert(wmap, { id: 1 }, true); +weakMapGetOrInsertComputed(wmap, { id: 2 }, obj => obj.id === 2); + +// @ts-expect-error +weakMapGetOrInsert(wmap, { id: 1 }); diff --git a/tests/type-definitions/pure/proposals/math-sum.test.ts b/tests/type-definitions/pure/proposals/math-sum.test.ts new file mode 100644 index 000000000000..40399360a62d --- /dev/null +++ b/tests/type-definitions/pure/proposals/math-sum.test.ts @@ -0,0 +1,13 @@ +import mathSumPrecise from '@core-js/pure/full/math/sum-precise'; + +function acceptsNumber(x: number) {} +declare const it: Iterable; + +acceptsNumber(mathSumPrecise(it)); +acceptsNumber(mathSumPrecise([1, 2])); + +// @ts-expect-error +mathSumPrecise('10'); + +// @ts-expect-error +mathSumPrecise(1, 2); diff --git a/tests/type-definitions/pure/proposals/number-clamp.test.ts b/tests/type-definitions/pure/proposals/number-clamp.test.ts new file mode 100644 index 000000000000..744145e1a362 --- /dev/null +++ b/tests/type-definitions/pure/proposals/number-clamp.test.ts @@ -0,0 +1,9 @@ +import numberClamp from '@core-js/pure/full/number/clamp'; + +declare const num: number; +const clamped: number = numberClamp(num, 0, 100); + +// @ts-expect-error +numberClamp(num); +// @ts-expect-error +numberClamp(num, '1', '2'); diff --git a/tests/type-definitions/pure/proposals/object-from-entries.test.ts b/tests/type-definitions/pure/proposals/object-from-entries.test.ts new file mode 100644 index 000000000000..fcf8db04689d --- /dev/null +++ b/tests/type-definitions/pure/proposals/object-from-entries.test.ts @@ -0,0 +1,27 @@ +import objectFromEntries from '@core-js/pure/full/object/from-entries'; + +declare const objEntries: Iterable; +declare const mixedEntries: Iterable; +declare const wrongEntries1: Iterable; +declare const wrongEntries2: number; +declare const notIterable: {}; + +const r1: { [k: string]: number } = objectFromEntries(objEntries); +const r2: any = objectFromEntries(mixedEntries); +const r3: any = objectFromEntries([['a', 1], ['b', 2]]); +const r4: object = objectFromEntries(new Map([['x', 1], ['y', 2]])); + +// @ts-expect-error +objectFromEntries(); + +// @ts-expect-error +objectFromEntries(123); + +// @ts-expect-error +objectFromEntries(wrongEntries1); + +// @ts-expect-error +objectFromEntries(wrongEntries2); + +// @ts-expect-error +objectFromEntries(notIterable); diff --git a/tests/type-definitions/pure/proposals/object-get-own-property-descriptors.test.ts b/tests/type-definitions/pure/proposals/object-get-own-property-descriptors.test.ts new file mode 100644 index 000000000000..a728290039dc --- /dev/null +++ b/tests/type-definitions/pure/proposals/object-get-own-property-descriptors.test.ts @@ -0,0 +1,18 @@ +import objectGetOwnPropertyDescriptors from '@core-js/pure/full/object/get-own-property-descriptors'; + +const obj = { a: 1, b: 'x', c: true }; +const objDescs: { a: TypedPropertyDescriptor; b: TypedPropertyDescriptor; c: TypedPropertyDescriptor } & + { [x: string]: PropertyDescriptor } = objectGetOwnPropertyDescriptors(obj); + +class Foo { + bar = 42; + baz() {} +} +const foo = new Foo(); +const fooDescs: { bar: TypedPropertyDescriptor; baz: TypedPropertyDescriptor<() => void> } & + { [x: string]: PropertyDescriptor } = objectGetOwnPropertyDescriptors(foo); + +const descsAny = objectGetOwnPropertyDescriptors({ x: 1, y: 2 }); + +// @ts-expect-error +objectGetOwnPropertyDescriptors(); diff --git a/tests/type-definitions/pure/proposals/object-keys-length.test.ts b/tests/type-definitions/pure/proposals/object-keys-length.test.ts new file mode 100644 index 000000000000..9879289e820c --- /dev/null +++ b/tests/type-definitions/pure/proposals/object-keys-length.test.ts @@ -0,0 +1,21 @@ +import keysLength from '@core-js/pure/full/object/keys-length'; +import { assertNumber } from '../../helpers/helpers.js'; + +const obj = { a: 1, b: 2 }; +const arr = [1, 2, 3]; +const strArr = ['a', 'b', 'c']; +const arrLike: ArrayLike = { 0: 10, 1: 20, length: 2 }; +const emptyObj = {}; +const string = 'abc'; + +assertNumber(keysLength(obj)); +assertNumber(keysLength(arr)); +assertNumber(keysLength(strArr)); +assertNumber(keysLength(arrLike)); +assertNumber(keysLength(emptyObj)); +assertNumber(keysLength(string)); + +// @ts-expect-error +keysLength(); +// @ts-expect-error +keysLength(null); diff --git a/tests/type-definitions/pure/proposals/object-values-entries.test.ts b/tests/type-definitions/pure/proposals/object-values-entries.test.ts new file mode 100644 index 000000000000..2ac45d2beb76 --- /dev/null +++ b/tests/type-definitions/pure/proposals/object-values-entries.test.ts @@ -0,0 +1,29 @@ +import objectValues from '@core-js/pure/full/object/values'; +import objectEntries from '@core-js/pure/full/object/entries'; + +const obj = { a: 1, b: 2 }; +const arr = [1, 2, 3]; +const strArr = ['a', 'b', 'c']; +const arrLike: ArrayLike = { 0: 10, 1: 20, length: 2 }; +const emptyObj = {}; + +const values1: number[] = objectValues(obj); +const values2: number[] = objectValues(arr); +const values3: string[] = objectValues(strArr); +const values4: number[] = objectValues(arrLike); +const values5: any[] = objectValues(emptyObj); + +const entries1: [string, number][] = objectEntries(obj); +const entries2: [string, number][] = objectEntries(arr); +const entries3: [string, string][] = objectEntries(strArr); +const entries4: [string, number][] = objectEntries(arrLike); +const entries5: [string, any][] = objectEntries(emptyObj); + +const valuesAnyArr: any[] = objectValues({ foo: 123, bar: 'baz' }); +const entriesAnyArr: [string, any][] = objectEntries({ foo: 123, bar: 'baz' }); + +// @ts-expect-error +objectValues(); + +// @ts-expect-error +objectEntries(); diff --git a/tests/type-definitions/pure/proposals/pattern-matching.test.ts b/tests/type-definitions/pure/proposals/pattern-matching.test.ts new file mode 100644 index 000000000000..0b302a7e9f1e --- /dev/null +++ b/tests/type-definitions/pure/proposals/pattern-matching.test.ts @@ -0,0 +1,8 @@ +import $Symbol from '@core-js/pure/full/symbol/index'; + +const sym: symbol = $Symbol.customMatcher; + +// @ts-expect-error +const bad1: string = $Symbol.customMatcher; +// @ts-expect-error +$Symbol.customMatcher = $Symbol('other'); diff --git a/tests/type-definitions/pure/proposals/promise-all-settled.test.ts b/tests/type-definitions/pure/proposals/promise-all-settled.test.ts new file mode 100644 index 000000000000..3a37e3e9d530 --- /dev/null +++ b/tests/type-definitions/pure/proposals/promise-all-settled.test.ts @@ -0,0 +1,42 @@ +import promiseAllSettled from '@core-js/pure/full/promise/all-settled'; +import promiseResolve from '@core-js/pure/full/promise/resolve'; +import { assertCoreJSPromiseLike } from '../../helpers/helpers.pure.js'; + +interface CoreJSPromiseResult { + status: string; + value?: T; + reason?: any; +} + +const promiseLike = { then: (cb: (val: number) => void) => cb(42) }; + +const p1 = promiseAllSettled([promiseResolve(10), promiseResolve(20), 30]); +assertCoreJSPromiseLike<[CoreJSPromiseResult, CoreJSPromiseResult, CoreJSPromiseResult]>(p1); +const p2 = promiseAllSettled(['a', 'b', 'c']); +assertCoreJSPromiseLike<[CoreJSPromiseResult, CoreJSPromiseResult, CoreJSPromiseResult]>(p2); +const p3 = promiseAllSettled(new Set([1, 2, 3])); +assertCoreJSPromiseLike[]>(p3); +promiseAllSettled([promiseLike]); + +const emptyTuple: [] = []; +const settled6 = promiseAllSettled(emptyTuple); +assertCoreJSPromiseLike<[]>(settled6); + +const mixedTuple = [42, promiseResolve('bar')] as const; +const p4 = promiseAllSettled(mixedTuple); +assertCoreJSPromiseLike<[CoreJSPromiseResult, CoreJSPromiseResult]>(p4); + +// @ts-expect-error +promiseAllSettled(); + +// @ts-expect-error +promiseAllSettled(5); + +// @ts-expect-error +promiseAllSettled({ foo: 123 }); + +// @ts-expect-error +promiseAllSettled([1, 2], 123); + +// @ts-expect-error +promiseAllSettled([promiseResolve(1)], 'extra'); diff --git a/tests/type-definitions/pure/proposals/promise-any.test.ts b/tests/type-definitions/pure/proposals/promise-any.test.ts new file mode 100644 index 000000000000..f3cc515496be --- /dev/null +++ b/tests/type-definitions/pure/proposals/promise-any.test.ts @@ -0,0 +1,45 @@ +import promiseAny from '@core-js/pure/full/promise/any'; +import promiseResolve from '@core-js/pure/full/promise/resolve'; +import { assertCoreJSPromiseLike } from '../../helpers/helpers.pure.js'; + +const arr = [promiseResolve(1), promiseResolve('foo'), 3] as const; +const justNumbers = [1, 2, 3]; +const setOfStrings = new Set(['a', 'b', 'c']); +const promiseLike = { then: (cb: (val: number) => void) => cb(123) }; +const emptyTuple: [] = []; +const mixed = [true, promiseResolve('z')] as const; + +const any1 = promiseAny(arr); +assertCoreJSPromiseLike(any1); +const any2 = promiseAny(['x', 'y', promiseResolve(5)]); +assertCoreJSPromiseLike(any2); +const any3 = promiseAny(emptyTuple); +assertCoreJSPromiseLike(any3); +const any4 = promiseAny(mixed); +assertCoreJSPromiseLike(any4); + +const any5 = promiseAny(justNumbers); +assertCoreJSPromiseLike(any5); +const any6 = promiseAny(setOfStrings); +assertCoreJSPromiseLike(any6); +const any7 = promiseAny([promiseLike]); +assertCoreJSPromiseLike(any7); +const any8 = promiseAny(new Set([1])); +assertCoreJSPromiseLike(any8); +const any9 = promiseAny([promiseResolve()]); +assertCoreJSPromiseLike(any9); + +// @ts-expect-error +promiseAny(); + +// @ts-expect-error +promiseAny(123); + +// @ts-expect-error +promiseAny({ foo: 42 }); + +// @ts-expect-error +promiseAny([1, 2], 3); + +// @ts-expect-error +promiseAny(justNumbers, 'extra'); diff --git a/tests/type-definitions/pure/proposals/promise-finally.test.ts b/tests/type-definitions/pure/proposals/promise-finally.test.ts new file mode 100644 index 000000000000..5e91a97d3a4b --- /dev/null +++ b/tests/type-definitions/pure/proposals/promise-finally.test.ts @@ -0,0 +1,47 @@ +import promiseFinally from '@core-js/pure/full/promise/finally'; +import promiseResolve from '@core-js/pure/full/promise/resolve'; +import promiseReject from '@core-js/pure/full/promise/reject'; +import { assertCoreJSPromiseLike } from '../../helpers/helpers.pure.js'; + +const pr1 = promiseResolve(42); +assertCoreJSPromiseLike(pr1); +declare const p1: Promise; +const pf1 = promiseFinally(p1); +assertCoreJSPromiseLike(pf1); +const pf2 = promiseFinally(p1, undefined); +assertCoreJSPromiseLike(pf2); +const pf3 = promiseFinally(p1, null); +assertCoreJSPromiseLike(pf3); +const pf4 = promiseFinally(p1, () => {}); +assertCoreJSPromiseLike(pf4); +const pf5 = promiseFinally(p1, function () {}); +assertCoreJSPromiseLike(pf5); + +const pr2 = promiseReject('err'); +assertCoreJSPromiseLike(pr2); +declare const p2: Promise; +const pf6 = promiseFinally(p2); +assertCoreJSPromiseLike(pf6); +const pf7 = promiseFinally(p2, () => {}); +assertCoreJSPromiseLike(pf7); + +// @ts-expect-error +promiseFinally(p1, 123); + +// @ts-expect-error +promiseFinally(p1, 'foo'); + +// @ts-expect-error +promiseFinally(p1, {}); + +// @ts-expect-error +promiseFinally(p1, []); + +// @ts-expect-error +promiseFinally(p1, () => {}, 'extra'); + +// @ts-expect-error +promiseFinally(p1, true); + +// @ts-expect-error +promiseFinally(p1, Symbol('x')); diff --git a/tests/type-definitions/pure/proposals/promise-try.test.ts b/tests/type-definitions/pure/proposals/promise-try.test.ts new file mode 100644 index 000000000000..e24ecb453256 --- /dev/null +++ b/tests/type-definitions/pure/proposals/promise-try.test.ts @@ -0,0 +1,45 @@ +import promiseTry from '@core-js/pure/full/promise/try'; +import promiseResolve from '@core-js/pure/full/promise/resolve'; +import { assertCoreJSPromiseLike } from '../../helpers/helpers.pure.js'; + +const pt1 = promiseTry(() => 42); +assertCoreJSPromiseLike(pt1); +const pt2 = promiseTry(() => promiseResolve('hi')); +assertCoreJSPromiseLike(pt2); +const pt3 = promiseTry((a: number, b: number) => a + b, 1, 2); +assertCoreJSPromiseLike(pt3); +const pt4 = promiseTry((x: string) => x + '!!', 'test'); +assertCoreJSPromiseLike(pt4); +const pt5 = promiseTry(() => {}); +assertCoreJSPromiseLike(pt5); +const pt6 = promiseTry((b: boolean) => b, false); +assertCoreJSPromiseLike(pt6); + +const pt7 = promiseTry((a: number, b: string, c: boolean) => c ? a : Number(b), 10, '100', true); +assertCoreJSPromiseLike(pt7); +const pt8 = promiseTry((a: string) => promiseResolve(a), 'bar'); +assertCoreJSPromiseLike(pt8); + +const pt9 = promiseTry(() => pt1); +assertCoreJSPromiseLike(pt9); + +// @ts-expect-error +promiseTry(); + +// @ts-expect-error +promiseTry(42); + +// @ts-expect-error +promiseTry('callback'); + +// @ts-expect-error +promiseTry({}); + +// @ts-expect-error +promiseTry([]); + +// @ts-expect-error +promiseTry(() => 1, 2, 'a', Symbol('x')); + +// @ts-expect-error +promiseTry((a: boolean) => a, 123); diff --git a/tests/type-definitions/pure/proposals/promise-with-resolvers.test.ts b/tests/type-definitions/pure/proposals/promise-with-resolvers.test.ts new file mode 100644 index 000000000000..688e15d2a15a --- /dev/null +++ b/tests/type-definitions/pure/proposals/promise-with-resolvers.test.ts @@ -0,0 +1,34 @@ +import promiseWithResolvers from '@core-js/pure/full/promise/with-resolvers'; +import promiseResolve from '@core-js/pure/full/promise/resolve'; +import { assertCoreJSPromiseLike } from '../../helpers/helpers.pure.js'; + +const pr = promiseWithResolvers(); +const pr2 = promiseWithResolvers(); +const pr3 = promiseWithResolvers(); + +const p1 = pr.promise; +assertCoreJSPromiseLike(p1); +const p2 = pr2.promise; +assertCoreJSPromiseLike(p2); +const p3 = pr3.promise; +assertCoreJSPromiseLike(p3); + +pr.resolve(42); +pr.resolve(promiseResolve(43)); +pr.reject(); +pr.reject('some error'); + +pr2.resolve('test'); +pr2.resolve(promiseResolve('hi')); +pr2.reject(new Error('fail')); +pr3.resolve(undefined); +pr3.reject(); + +const value: number | PromiseLike = 99; +pr.resolve(value); + +// @ts-expect-error +promiseWithResolvers(123); + +// @ts-expect-error +promiseWithResolvers(123); diff --git a/tests/type-definitions/pure/proposals/regexp-escaping.test.ts b/tests/type-definitions/pure/proposals/regexp-escaping.test.ts new file mode 100644 index 000000000000..234ac1da5372 --- /dev/null +++ b/tests/type-definitions/pure/proposals/regexp-escaping.test.ts @@ -0,0 +1,23 @@ +import regexpEscape from '@core-js/pure/full/regexp/escape'; + +const escaped1: string = regexpEscape('foo.*+?^${}()|[]\\'); +const escaped2: string = regexpEscape(''); +const s = 'abc'; +const escaped3: string = regexpEscape(s); + +// @ts-expect-error +regexpEscape(); +// @ts-expect-error +regexpEscape(123); +// @ts-expect-error +regexpEscape(); +// @ts-expect-error +regexpEscape({}); +// @ts-expect-error +regexpEscape(/abc/); +// @ts-expect-error +regexpEscape([]); +// @ts-expect-error +const wrong: number = regexpEscape('boo'); +// @ts-expect-error +regexpEscape('foo', 'bar'); diff --git a/tests/type-definitions/pure/proposals/relative-indexing-method.test.ts b/tests/type-definitions/pure/proposals/relative-indexing-method.test.ts new file mode 100644 index 000000000000..07592f654b62 --- /dev/null +++ b/tests/type-definitions/pure/proposals/relative-indexing-method.test.ts @@ -0,0 +1,28 @@ +import stringAt from '@core-js/pure/full/string/at'; +import arrayAt from '@core-js/pure/full/array/at'; + +const str = 'hello'; +const s1: string | undefined = stringAt(str, 0); +const s2: string | undefined = stringAt(str, -1); + +const arr: number[] = [10, 20, 30]; +const a1: number | undefined = arrayAt(arr, 1); +const a2: number | undefined = arrayAt(arr, -2); + +// @ts-expect-error +stringAt(str); +// @ts-expect-error +stringAt(str, '1'); +// @ts-expect-error +stringAt(str, 1, 2); + +// @ts-expect-error +arrayAt(arr); +// @ts-expect-error +arrayAt(arr, '1'); +// @ts-expect-error +arrayAt(arr, {}); +// @ts-expect-error +arrayAt(arr); +// @ts-expect-error +arrayAt(arr, 1, 1); diff --git a/tests/type-definitions/pure/proposals/self.test.ts b/tests/type-definitions/pure/proposals/self.test.ts new file mode 100644 index 000000000000..26246a23ecc6 --- /dev/null +++ b/tests/type-definitions/pure/proposals/self.test.ts @@ -0,0 +1,8 @@ +import $self from '@core-js/pure/full/self'; + +const ref: typeof globalThis = $self; + +// @ts-expect-error +$self(); +// @ts-expect-error +$self = {}; diff --git a/tests/type-definitions/pure/proposals/set-methods.test.ts b/tests/type-definitions/pure/proposals/set-methods.test.ts new file mode 100644 index 000000000000..00732e2c60a0 --- /dev/null +++ b/tests/type-definitions/pure/proposals/set-methods.test.ts @@ -0,0 +1,88 @@ +import $Set from '@core-js/pure/full/set'; +import setUnion from '@core-js/pure/full/set/union'; +import setIntersection from '@core-js/pure/full/set/intersection'; +import setDifference from '@core-js/pure/full/set/difference'; +import setSymmetricDifference from '@core-js/pure/full/set/symmetric-difference'; +import setIsSubsetOf from '@core-js/pure/full/set/is-subset-of'; +import setIsSupersetOf from '@core-js/pure/full/set/is-superset-of'; +import setIsDisjointFrom from '@core-js/pure/full/set/is-disjoint-from'; +import { assertCoreJSSetLike } from '../../helpers/helpers.pure.js'; + +const setA = new $Set([1, 2, 3]); +const setB = new $Set(['a', 'b', 'c']); + +const setLike = { + keys() { return [1, 2, 3][Symbol.iterator](); }, + has(val: number): boolean { return val === 2; }, + size: 3, +}; + +const setLikeStr = { + keys() { return ['a', 'b'][Symbol.iterator](); }, + has(val: string): boolean { return val === 'a'; }, + size: 2, +}; + +const unionAB = setUnion(setA, setB); +assertCoreJSSetLike(unionAB); +const unionAL = setUnion(setA, setLike); +assertCoreJSSetLike(unionAL); +const unionALS = setUnion(setA, setLikeStr); +assertCoreJSSetLike(unionALS); + +const interAB = setIntersection(setA, setB); +assertCoreJSSetLike(interAB); +const interAN = setIntersection(setA, setLike); +assertCoreJSSetLike(interAN); +const intersectionALS = setIntersection(setA, setLikeStr); +assertCoreJSSetLike(intersectionALS); + +const diffAB = setDifference(setA, setB); +assertCoreJSSetLike(diffAB); +const diffAN = setDifference(setA, setLike); +assertCoreJSSetLike(diffAN); +const diffALS = setDifference(setA, setLikeStr); +assertCoreJSSetLike(diffALS); + +const symdiffAB = setSymmetricDifference(setA, setB); +assertCoreJSSetLike(symdiffAB); +const symdiffAL = setSymmetricDifference(setA, setLike); +assertCoreJSSetLike(symdiffAL); + +const sub: boolean = setIsSubsetOf(setA, setLikeStr); +const superSet: boolean = setIsSupersetOf(setA, setLikeStr); +const isDisjoint: boolean = setIsDisjointFrom(setA, setLike); + +// @ts-expect-error +setUnion(setA); +// @ts-expect-error +setUnion(setA, 123); +// @ts-expect-error +setUnion(setA, {}); + +// @ts-expect-error +setIntersection(setA); +// @ts-expect-error +setIntersection(setA, 'a'); +// @ts-expect-error +setIntersection(setA, { foo: 'bar' }); + +// @ts-expect-error +setDifference(setA); +// @ts-expect-error +setDifference(setA, []); + +// @ts-expect-error +setSymmetricDifference(setA); +// @ts-expect-error +setSymmetricDifference(setA, 1); + +// @ts-expect-error +setIsSubsetOf(setA); +// @ts-expect-error +setIsSubsetOf(setA, []); + +// @ts-expect-error +setIsSupersetOf(setA); +// @ts-expect-error +setIsDisjointFrom(setA); diff --git a/tests/type-definitions/pure/proposals/string-cooked.test.ts b/tests/type-definitions/pure/proposals/string-cooked.test.ts new file mode 100644 index 000000000000..46e23805b698 --- /dev/null +++ b/tests/type-definitions/pure/proposals/string-cooked.test.ts @@ -0,0 +1,9 @@ +import stringCooked from '@core-js/pure/full/string/cooked'; + +const rcooked1: string = stringCooked(['foo', 'bar'], 1, 2); +stringCooked([]); + +// @ts-expect-error +stringCooked(1); +// @ts-expect-error +stringCooked(false); diff --git a/tests/type-definitions/pure/proposals/string-dedent.test.ts b/tests/type-definitions/pure/proposals/string-dedent.test.ts new file mode 100644 index 000000000000..4059c9147a27 --- /dev/null +++ b/tests/type-definitions/pure/proposals/string-dedent.test.ts @@ -0,0 +1,22 @@ +import stringDedent from '@core-js/pure/full/string/dedent'; + +const rdedent1: string = stringDedent`foo\nbar`; +const rdedent2: string = stringDedent`line1 + line2 + line3`; + +const tpl = Object.assign(['foo', 'bar'], { raw: ['foo', 'bar'] }); +stringDedent(tpl, 1, 2); + +stringDedent({ raw: ['a\n b\n', '\n c\n'] }, 1, 2); + +const myTag = (strings: { raw: readonly string[] }, ...values: (string | number)[]) => { + return { strings, values } as const; +}; +const myAndDedent = stringDedent(myTag); +myAndDedent`line1 + line2 + line3`; + +// @ts-expect-error +stringDedent(); diff --git a/tests/type-definitions/pure/proposals/string-left-right-trim.test.ts b/tests/type-definitions/pure/proposals/string-left-right-trim.test.ts new file mode 100644 index 000000000000..ac6c29a748ce --- /dev/null +++ b/tests/type-definitions/pure/proposals/string-left-right-trim.test.ts @@ -0,0 +1,25 @@ +import stringTrimLeft from '@core-js/pure/full/string/trim-left'; +import stringTrimStart from '@core-js/pure/full/string/trim-start'; +import stringTrimRight from '@core-js/pure/full/string/trim-right'; +import stringTrimEnd from '@core-js/pure/full/string/trim-end'; + +const s = 'abc'; +const t1: string = stringTrimLeft(s); +const t2: string = stringTrimStart(s); +const t3: string = stringTrimRight(s); +const t4: string = stringTrimEnd(s); + +// @ts-expect-error +stringTrimLeft(s, 123); + +// @ts-expect-error +stringTrimStart(s, 'a'); + +// @ts-expect-error +stringTrimRight(s, []); + +// @ts-expect-error +stringTrimEnd(s, {}); + +// @ts-expect-error +const n: number = stringTrimLeft(s); diff --git a/tests/type-definitions/pure/proposals/string-match-all.test.ts b/tests/type-definitions/pure/proposals/string-match-all.test.ts new file mode 100644 index 000000000000..232afb075d28 --- /dev/null +++ b/tests/type-definitions/pure/proposals/string-match-all.test.ts @@ -0,0 +1,23 @@ +import stringMatchAll from '@core-js/pure/full/string/match-all'; + +const s = 'abcabc'; +const re = /abc/g; +stringMatchAll(s, re); + +// @ts-expect-error +stringMatchAll(s); + +// @ts-expect-error +stringMatchAll(s, 'abc'); + +// @ts-expect-error +const n: number = stringMatchAll(re); + +// @ts-expect-error +stringMatchAll(s, {}); + +// @ts-expect-error +stringMatchAll(s, 123); + +// @ts-expect-error +stringMatchAll(s, /abc/g, /def/g); diff --git a/tests/type-definitions/pure/proposals/string-padding.test.ts b/tests/type-definitions/pure/proposals/string-padding.test.ts new file mode 100644 index 000000000000..40a13b08da8e --- /dev/null +++ b/tests/type-definitions/pure/proposals/string-padding.test.ts @@ -0,0 +1,30 @@ +import stringPadStart from '@core-js/pure/full/string/pad-start'; +import stringPadEnd from '@core-js/pure/full/string/pad-end'; + +const s = 'foo'; +const str = ''; +const p1: string = stringPadStart(s, 5); +const p2: string = stringPadStart(s, 10, '0'); +const p3: string = stringPadEnd(s, 8); +const p4: string = stringPadEnd(s, 4, '-'); + +// @ts-expect-error +stringPadStart(s); +// @ts-expect-error +stringPadEnd(s); +// @ts-expect-error +stringPadStart(s, '10'); +// @ts-expect-error +stringPadEnd(s, true); +// @ts-expect-error +stringPadStart(s, 5, 1); +// @ts-expect-error +stringPadEnd(s, 3, {}); +// @ts-expect-error +stringPadStart(s, 2, [], 'extra'); +// @ts-expect-error +stringPadEnd(s, 7, '', undefined); +// @ts-expect-error +const n: number = stringPadStart(s, 5); +// @ts-expect-error +const n2: number = stringPadEnd(s, 3, '-'); diff --git a/tests/type-definitions/pure/proposals/string-replace-all.test.ts b/tests/type-definitions/pure/proposals/string-replace-all.test.ts new file mode 100644 index 000000000000..cabedf9ad151 --- /dev/null +++ b/tests/type-definitions/pure/proposals/string-replace-all.test.ts @@ -0,0 +1,34 @@ +import stringReplaceAll from '@core-js/pure/full/string/replace-all'; + +const s = 'foo bar foo'; + +const r1: string = stringReplaceAll(s, 'foo', 'baz'); +const r2: string = stringReplaceAll(s, /foo/g, 'baz'); +const r3: string = stringReplaceAll(s, 'bar', (substr: string) => substr); +const r4: string = stringReplaceAll(s, /bar/g, (substr: string) => substr + 'Test'); +const r5: string = stringReplaceAll(s, 'foo', function (substring: string): string { return substring + '!'; }); +const r6: string = stringReplaceAll(s, /foo/g, (match: string, ...args: any[]) => match + args.length); + +// @ts-expect-error +stringReplaceAll(s); + +// @ts-expect-error +stringReplaceAll(s, 'foo'); + +// @ts-expect-error +stringReplaceAll(s, 'foo', 1); + +// @ts-expect-error +stringReplaceAll(s, 'foo', {}); + +// @ts-expect-error +stringReplaceAll(s, /foo/, 'bar', 'extra'); + +// @ts-expect-error +stringReplaceAll(s, /foo/g, (match: string) => 123); + +// @ts-expect-error +stringReplaceAll(s, /foo/g, 5); + +// @ts-expect-error +const n: number = stringReplaceAll(s, 'foo', 'baz'); diff --git a/tests/type-definitions/pure/proposals/symbol-predicates.test.ts b/tests/type-definitions/pure/proposals/symbol-predicates.test.ts new file mode 100644 index 000000000000..18342e17c341 --- /dev/null +++ b/tests/type-definitions/pure/proposals/symbol-predicates.test.ts @@ -0,0 +1,19 @@ +import isRegisteredSymbol from '@core-js/pure/full/symbol/is-registered-symbol'; +import isWellKnownSymbol from '@core-js/pure/full/symbol/is-well-known-symbol'; + +const rsymbol1: boolean = isRegisteredSymbol(Symbol.for('foo')); +const rsymbol2: boolean = isRegisteredSymbol(undefined); +const rsymbol3: boolean = isRegisteredSymbol(Symbol('bar')); + +const rsymbol4: boolean = isWellKnownSymbol(Symbol.iterator); +const rsymbol5: boolean = isWellKnownSymbol({}); +const rsymbol6: boolean = isWellKnownSymbol(Symbol('baz')); + +declare const u: unknown; +isRegisteredSymbol(u); +isWellKnownSymbol(u); + +// @ts-expect-error +isRegisteredSymbol(); +// @ts-expect-error +isWellKnownSymbol(); diff --git a/tests/type-definitions/pure/proposals/well-formed-unicode-strings.test.ts b/tests/type-definitions/pure/proposals/well-formed-unicode-strings.test.ts new file mode 100644 index 000000000000..5abd21abe632 --- /dev/null +++ b/tests/type-definitions/pure/proposals/well-formed-unicode-strings.test.ts @@ -0,0 +1,24 @@ +import stringIsWellFormed from '@core-js/pure/full/string/is-well-formed'; +import stringToWellFormed from '@core-js/pure/full/string/to-well-formed'; + +const s = 'test'; +const b: boolean = stringIsWellFormed(s); +const str: string = stringToWellFormed(s); + +// @ts-expect-error +stringIsWellFormed(s, 123); + +// @ts-expect-error +stringIsWellFormed(s, 'foo'); + +// @ts-expect-error +stringToWellFormed(s, []); + +// @ts-expect-error +stringToWellFormed(s, true); + +// @ts-expect-error +const n: number = stringToWellFormed(s); + +// @ts-expect-error +const s2: string = stringIsWellFormed(s); diff --git a/tests/type-definitions/pure/tsconfig.dom.json b/tests/type-definitions/pure/tsconfig.dom.json new file mode 100644 index 000000000000..3e633c7056c8 --- /dev/null +++ b/tests/type-definitions/pure/tsconfig.dom.json @@ -0,0 +1,7 @@ +{ + "extends": "../tsconfig.json", + "include": ["./**/*.ts"], + "compilerOptions": { + "types": ["@core-js/types/pure"] + } +} diff --git a/tests/type-definitions/pure/tsconfig.es6.dom.json b/tests/type-definitions/pure/tsconfig.es6.dom.json new file mode 100644 index 000000000000..9e1b4ef64d9a --- /dev/null +++ b/tests/type-definitions/pure/tsconfig.es6.dom.json @@ -0,0 +1,8 @@ +{ + "extends": "../tsconfig.json", + "include": ["./**/*.ts"], + "exclude": ["./**/*es2018*test.ts"], + "compilerOptions": { + "types": ["@core-js/types/pure"] + } +} diff --git a/tests/type-definitions/pure/tsconfig.es6.json b/tests/type-definitions/pure/tsconfig.es6.json new file mode 100644 index 000000000000..31e076ae0120 --- /dev/null +++ b/tests/type-definitions/pure/tsconfig.es6.json @@ -0,0 +1,11 @@ +{ + "extends": "../tsconfig.json", + "include": ["./**/*.ts"], + "exclude": [ + "./**/*es2018*test.ts", + "./**/*dom*test.ts" + ], + "compilerOptions": { + "types": ["@core-js/types/pure"] + } +} diff --git a/tests/type-definitions/pure/tsconfig.json b/tests/type-definitions/pure/tsconfig.json new file mode 100644 index 000000000000..6bda323fe73e --- /dev/null +++ b/tests/type-definitions/pure/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../tsconfig.json", + "include": ["./**/*.ts"], + "exclude": ["./**/*dom*test.ts"], + "compilerOptions": { + "types": ["@core-js/types/pure"] + } +} diff --git a/tests/type-definitions/pure/web/atob.test.ts b/tests/type-definitions/pure/web/atob.test.ts new file mode 100644 index 000000000000..7ce44646586b --- /dev/null +++ b/tests/type-definitions/pure/web/atob.test.ts @@ -0,0 +1,10 @@ +import $atob from '@core-js/pure/full/atob'; + +const s: string = $atob('SGVsbG8gd29ybGQ='); + +// @ts-expect-error +$atob(); +// @ts-expect-error +$atob(123); +// @ts-expect-error +$atob({}); diff --git a/tests/type-definitions/pure/web/btoa.test.ts b/tests/type-definitions/pure/web/btoa.test.ts new file mode 100644 index 000000000000..51c535bf5f88 --- /dev/null +++ b/tests/type-definitions/pure/web/btoa.test.ts @@ -0,0 +1,10 @@ +import $btoa from '@core-js/pure/full/btoa'; + +const s: string = $btoa('SGVsbG8gd29ybGQ='); + +// @ts-expect-error +$btoa(); +// @ts-expect-error +$btoa(123); +// @ts-expect-error +$btoa({}); diff --git a/tests/type-definitions/pure/web/efficient-script-yielding.test.ts b/tests/type-definitions/pure/web/efficient-script-yielding.test.ts new file mode 100644 index 000000000000..82dd18c265d0 --- /dev/null +++ b/tests/type-definitions/pure/web/efficient-script-yielding.test.ts @@ -0,0 +1,14 @@ +import setImmediate from '@core-js/pure/full/set-immediate'; +import clearImmediate from '@core-js/pure/full/clear-immediate'; + +const res: number | object = setImmediate(() => 42); +clearImmediate(res); + +// @ts-expect-error +setImmediate(); +// @ts-expect-error +setImmediate(42); +// @ts-expect-error +clearImmediate(); +// @ts-expect-error +clearImmediate('str'); diff --git a/tests/type-definitions/pure/web/queue-microtask.test.ts b/tests/type-definitions/pure/web/queue-microtask.test.ts new file mode 100644 index 000000000000..b485bf35a8fb --- /dev/null +++ b/tests/type-definitions/pure/web/queue-microtask.test.ts @@ -0,0 +1,11 @@ +import $queueMicrotask from '@core-js/pure/full/queue-microtask'; + +$queueMicrotask((): void => {}); +$queueMicrotask(function (): void {}); + +// @ts-expect-error +$queueMicrotask(); +// @ts-expect-error +$queueMicrotask('not a function'); +// @ts-expect-error +$queueMicrotask(a => {}); diff --git a/tests/type-definitions/pure/web/structured-clone.test.ts b/tests/type-definitions/pure/web/structured-clone.test.ts new file mode 100644 index 000000000000..6ce0bd06ed2f --- /dev/null +++ b/tests/type-definitions/pure/web/structured-clone.test.ts @@ -0,0 +1,15 @@ +import $structuredClone from '@core-js/pure/full/structured-clone'; + +const n: number = $structuredClone(5); +const s: string = $structuredClone('text'); + +declare const buffer: ArrayBuffer; +const obj = { buffer }; +const cloned: typeof obj = $structuredClone(obj, { transfer: [buffer] }); + +// @ts-expect-error +$structuredClone(); +// @ts-expect-error +$structuredClone('text', {}, 'extra'); +// @ts-expect-error +const n2: number = $structuredClone('1'); diff --git a/tests/type-definitions/pure/web/url-can-parse.test.ts b/tests/type-definitions/pure/web/url-can-parse.test.ts new file mode 100644 index 000000000000..a3f7ae842c7b --- /dev/null +++ b/tests/type-definitions/pure/web/url-can-parse.test.ts @@ -0,0 +1,7 @@ +import $canParse from '@core-js/pure/full/url/can-parse'; + +const u1: boolean = $canParse('https://example.com/path?name=value#hash'); +const u2: boolean = $canParse('/path', 'https://example.com'); + +// @ts-expect-error +$canParse(null); diff --git a/tests/type-definitions/pure/web/url-parse.test.ts b/tests/type-definitions/pure/web/url-parse.test.ts new file mode 100644 index 000000000000..48239bb7f38e --- /dev/null +++ b/tests/type-definitions/pure/web/url-parse.test.ts @@ -0,0 +1,17 @@ +import $parse from '@core-js/pure/full/url/parse'; + +const u1 = $parse('https://example.com/path?name=value#hash'); +$parse('/path', 'https://example.com'); + +if (u1) { + let str: string; + str = u1.pathname; + str = u1.hostname; + str = u1.pathname; + + str = u1.toJSON(); + str = u1.toString(); +} + +// @ts-expect-error +$parse(null); diff --git a/tests/type-definitions/pure/web/url-search-params.test.ts b/tests/type-definitions/pure/web/url-search-params.test.ts new file mode 100644 index 000000000000..f06c0bc0a2c4 --- /dev/null +++ b/tests/type-definitions/pure/web/url-search-params.test.ts @@ -0,0 +1,36 @@ +import $URLSearchParams from '@core-js/pure/full/url-search-params/index'; + +const ps1 = new $URLSearchParams(); +new $URLSearchParams('a=1&b=2'); +new $URLSearchParams([['a', '1'], ['b', '2']]); +new $URLSearchParams(ps1); +new $URLSearchParams({ foo: 'bar' }); + +// @ts-expect-error +new $URLSearchParams(42); + +ps1.append('k', 'v'); +// @ts-expect-error +ps1.append(); +// @ts-expect-error +ps1.append('a', 5); + +ps1.delete('k'); +// @ts-expect-error +ps1.delete(); + +const getResult: string | null = ps1.get('foo'); + +const allResult: string[] = ps1.getAll('foo'); + +const hasResult: boolean = ps1.has('foo'); + +ps1.set('foo', 'bar'); +// @ts-expect-error +ps1.set('foo', 1); +// @ts-expect-error +ps1.set('foo'); + +ps1.sort(); + +const str: string = ps1.toString(); diff --git a/tests/type-definitions/pure/web/url.dom.test.ts b/tests/type-definitions/pure/web/url.dom.test.ts new file mode 100644 index 000000000000..79bada1fe969 --- /dev/null +++ b/tests/type-definitions/pure/web/url.dom.test.ts @@ -0,0 +1,15 @@ +import $URL from '@core-js/pure/full/url/index'; + +const u1 = new $URL('https://example.com/path?name=value#hash'); +new $URL('/path', 'https://example.com'); + +let str: string; +str = u1.pathname; +str = u1.hostname; +str = u1.pathname; + +str = u1.toJSON(); +str = u1.toString(); + +// @ts-expect-error +new $URL(null); diff --git a/tests/type-definitions/runner.mjs b/tests/type-definitions/runner.mjs index 280f0863e94b..5d5cfdfbbc9d 100644 --- a/tests/type-definitions/runner.mjs +++ b/tests/type-definitions/runner.mjs @@ -1 +1,192 @@ -await $`tsc`; +import { cpus } from 'node:os'; +import { fs } from 'zx'; + +const { mkdir, rm, writeJson } = fs; + +const { TYPE_DEFINITIONS_TESTS } = process.env; + +if (!['ALL', 'CI', 'SMOKE'].includes(TYPE_DEFINITIONS_TESTS)) { + throw new Error('Incorrect or lack of TYPE_DEFINITIONS_TESTS'); +} + +const ALL_TESTS = TYPE_DEFINITIONS_TESTS === 'ALL'; +const CI_TESTS = TYPE_DEFINITIONS_TESTS === 'CI'; +const NUM_CPUS = cpus().length; +const TMP_DIR = './tmp/'; + +const ES_TARGETS = [ + 'esnext', + 'es2022', + 'es6', +]; + +const DEFAULT_TYPE_SCRIPT_VERSION = '5.9'; + +const TYPE_SCRIPT_VERSIONS = [DEFAULT_TYPE_SCRIPT_VERSION, ...ALL_TESTS ? [ + '6.0.0-beta', + '5.8', + '5.7', + '5.6', + // '5.5', // fails with node types: Named property 'next' of types 'AsyncIterator' and 'AsyncIteratorObject' are not identical. + // '5.4', + // '5.3', + // '5.2', +] : CI_TESTS ? [ + '6.0.0-beta', + '5.6', +] : [ + // empty +]]; + +const ENVIRONMENTS = ALL_TESTS ? [ + '@types/node@25', + '@types/node@24', + '@types/node@22', + '@types/node@20', + '@types/node@18', + '@types/node@16', + // '@types/node@15', // fails + // '@types/bun@latest', // ArrayBuffer.resize signature incorrect. Return type ArrayBuffer instead of void. + // '@types/deno@latest', // fails +] : CI_TESTS ? [ + '@types/node@25', + '@types/node@24', + '@types/node@22', + '@types/node@16', +] : [ + '@types/node@25', +]; + +const LIBS = [ + 'dom', +]; + +const CORE_JS_MODES = [ + 'global', + 'pure', +]; + +const TARGET_RULES = { + es6: '**/*es2018*test.ts', +}; + +const LIB_RULES = { + dom: '**/*dom*test.ts', +}; + +let tested = 0; +let failed = 0; + +function getTmpEnvDir(env) { + if (!env) return null; + return path.join(TMP_DIR, env.replaceAll('/', '-').replaceAll('@', '')); +} + +async function runTasksInParallel() { + const limit = Math.max(NUM_CPUS - 1, 1); + let i = 0; + + await Promise.all(Array(limit).fill().map(async () => { + while (i < tasks.length) await runTask(tasks[i++]); + })); +} + +async function runTask({ cwd, ts = DEFAULT_TYPE_SCRIPT_VERSION, config, args = [] }) { + const task = $({ cwd, verbose: false })`npx --package typescript@${ ts } tsc --project ${ config } ${ args }`; + // eslint-disable-next-line no-underscore-dangle -- third-party code + const { cmd } = task._snapshot; + echo`run ${ chalk.cyan(cmd) }`; + tested++; + try { + await task; + echo(chalk.green(`success ${ chalk.cyan(cmd) }`)); + } catch (error) { + failed++; + echo(chalk.red(`fail ${ chalk.cyan(cmd) }:\n${ chalk.grey(error) }`)); + } +} + +function * buildTasks() { + for (const mode of CORE_JS_MODES) { + for (const target of ES_TARGETS) { + for (const ts of TYPE_SCRIPT_VERSIONS) { + for (const env of [null, ...ENVIRONMENTS]) { + for (const lib of [null, ...LIBS]) { + const tsConfigPostfix = `${ TARGET_RULES[target] ? `.${ target }` : '' }${ LIB_RULES[lib] ? `.${ lib }` : '' }`; + const config = env ? `./tsconfig.${ mode }${ tsConfigPostfix }.json` : `${ mode }/tsconfig${ tsConfigPostfix }.json`; + const libWithTarget = lib ? `${ target },${ lib }` : target; + const types = [`@core-js/types${ mode === 'pure' ? '/pure' : '' }`]; + // eslint-disable-next-line max-depth -- ok + if (env) types.push(env.replace(/^(?@?[^@]+)@.+$/, '$')); + const args = [ + '--target', target, + '--lib', libWithTarget, + '--types', types.join(','), + ]; + yield { cwd: getTmpEnvDir(env), ts, config, args }; + } + } + } + } + } +} + +async function clearTmpDir() { + await rm(TMP_DIR, { recursive: true, force: true }); +} + +async function prepareEnvironments() { + await clearTmpDir(); + for (const env of ENVIRONMENTS) { + if (!env) continue; + const tmpEnvDir = getTmpEnvDir(env); + await mkdir(tmpEnvDir, { recursive: true }); + await $({ cwd: tmpEnvDir, verbose: false })`npm init --yes`; + await $({ cwd: tmpEnvDir })`npm install ${ env }`; + for (const mode of CORE_JS_MODES) { + await writeJson(path.join(tmpEnvDir, `tsconfig.${ mode }.json`), { + extends: '../../tsconfig.json', + include: [`../../${ mode }/**/*.ts`], + exclude: [`../../${ mode }/**/${ LIB_RULES.dom }`], + }); + await writeJson(path.join(tmpEnvDir, `tsconfig.${ mode }.dom.json`), { + extends: '../../tsconfig.json', + include: [`../../${ mode }/**/*.ts`], + }); + await writeJson(path.join(tmpEnvDir, `tsconfig.${ mode }.es6.json`), { + extends: '../../tsconfig.json', + include: [`../../${ mode }/**/*.ts`], + exclude: [`../../${ mode }/**/${ TARGET_RULES.es6 }`, `../../${ mode }/${ LIB_RULES.dom }`], + }); + await writeJson(path.join(tmpEnvDir, `tsconfig.${ mode }.es6.dom.json`), { + extends: '../../tsconfig.json', + include: [`../../${ mode }/**/*.ts`], + exclude: [`../../${ mode }/**/${ TARGET_RULES.es6 }`], + }); + } + } +} + +const tasks = [ + { config: 'tools/tsconfig.json' }, + { config: 'templates/tsconfig.json' }, + { config: 'templates/tsconfig.require.json' }, + { config: 'entries/full/tsconfig.json' }, + { config: 'entries/actual/tsconfig.json' }, + { config: 'entries/stable/tsconfig.json' }, + { config: 'entries/es/tsconfig.json' }, + { config: 'entries/proposals/tsconfig.json' }, + { config: 'entries/global-imports/tsconfig.json' }, + { config: 'entries/pure-imports/tsconfig.json' }, + { config: 'entries/configurator/tsconfig.json' }, + { config: 'entries/pure-pollutions/tsconfig.json' }, + ...buildTasks(), +]; + +await prepareEnvironments(); +await runTasksInParallel(); +await clearTmpDir(); + +echo(`Tested: ${ chalk.green(tested) }, Failed: ${ chalk.red(failed) }`); + +if (failed) throw new Error('Some tests have failed'); diff --git a/tests/type-definitions/templates/templates.import.ts b/tests/type-definitions/templates/templates.import.ts new file mode 100644 index 000000000000..5722486d9add --- /dev/null +++ b/tests/type-definitions/templates/templates.import.ts @@ -0,0 +1,142 @@ +// $justImport +import '@core-js/pure/full/array-buffer/detached'; +// @ts-expect-error it has no exports +import detached from '@core-js/pure/full/array-buffer/detached'; + +// $prototype with generics +import at from '@core-js/pure/full/array/prototype/at'; +at.call([1, 2, 3], -2); // we can't save strict result type for prototype methods with generics. It is any here +at.apply([1, 2, 3], [-2]); +// @ts-expect-error +at.call([1, 2, 3], null); +// @ts-expect-error +at.call(123); +// @ts-expect-error +at('string'); +// @ts-expect-error +at(null); + +// $prototype without generics +import stringAt from '@core-js/pure/full/string/prototype/at'; +const stringAtResult: string | undefined = stringAt.call('asd', -2); +stringAt.apply('asd', [-2]); +// @ts-expect-error +stringAt.call('asd', null); +// @ts-expect-error +stringAt.call('asd'); +// @ts-expect-error +stringAt([1]); +// @ts-expect-error +stringAt(null); + +// $prototypeIterator +import arrayVirtualIterator from '@core-js/pure/full/array/prototype/iterator'; +const aviValue1: number = arrayVirtualIterator.call([1]).next().value; +const aviResult1: IterableIterator = arrayVirtualIterator.call([1, 2, 3]); +const aviResult2: IterableIterator = arrayVirtualIterator.call(['a', 'b']); +const aviResult3: IterableIterator = arrayVirtualIterator.call([true, false]); +// @ts-expect-error +arrayVirtualIterator(1); +// @ts-expect-error +arrayVirtualIterator.call([1, 2, 3], 1); + +// $uncurried +import arrayAt from '@core-js/pure/full/array/at'; +const arrayAtResult1: number | undefined = arrayAt([1, 2, 3], -2); +const arrayAtResult2: string | undefined = arrayAt(['a', 'b'], -2); +const arrayAtResult3: undefined = arrayAt([], 1); +// @ts-expect-error +arrayAt([1, 2], 'string'); +// @ts-expect-error +arrayAt(); +// @ts-expect-error +arrayAt(1, 0, 0); + +// $uncurriedIterator +import arrayIterator from '@core-js/pure/full/array/iterator'; +arrayIterator([]).next().value; +// @ts-expect-error +arrayIterator(); + +// $static +import arrayFrom from '@core-js/pure/full/array/from'; +arrayFrom('qwe', it => it.toUpperCase(), {}); +// @ts-expect-error +arrayFrom(1); +// @ts-expect-error +arrayFrom('qwe', 1); + +// $staticWithContext +import allSettled from '@core-js/pure/full/promise/all-settled'; +allSettled([1, 2, 3]); +// @ts-expect-error +allSettled(1); + +// $patchableStatic +import stringify from '@core-js/pure/full/json/stringify'; +stringify({ a: 1, b: 2, c: 'asd' }, (_key, val) => typeof val === 'number' ? val * 2 : val, 4); +// @ts-expect-error +stringify([1], 1); + +// $namespace +import adsConstructor from '@core-js/pure/full/async-disposable-stack/constructor'; +new adsConstructor(); +// @ts-expect-error +adsConstructor.prototype = 1; + +// $helper +import getIterator from '@core-js/pure/full/get-iterator'; +getIterator([]).next().value; +// @ts-expect-error +getIterator(); + +// $path just typed arrays +// import errorConstructor from '@core-js/pure/full/error/constructor'; +// new errorConstructor.Error('er'); +// // @ts-expect-error +// errorConstructor(); + +// $instanceArray +import iConcat from '@core-js/pure/full/instance/concat'; +iConcat({}); +// @ts-expect-error +iConcat(); + +// $instanceString +import iCodePointAt from '@core-js/pure/full/instance/code-point-at'; +iCodePointAt('').call('a', 0); +// @ts-expect-error +iCodePointAt(); + +// $instanceFunction +import iDemethodize from '@core-js/pure/full/instance/demethodize'; +iDemethodize([].slice)([1, 2, 3], 1); +// @ts-expect-error +iDemethodize(); + +// $instanceDOMIterables +import iForEach from '@core-js/pure/full/instance/for-each'; +iForEach({}); +// @ts-expect-error +iForEach(); + +// $instanceArrayString +import iAt from '@core-js/pure/full/instance/at'; +iAt('').call('123', 2); +// @ts-expect-error +iAt(); + +// $instanceArrayDOMIterables +import iEntries from '@core-js/pure/full/instance/entries'; +iEntries([]).call([1, 2, 3]).next().value; +// @ts-expect-error +iEntries(); + +// $instanceRegExpFlags +import iFlags from '@core-js/pure/full/instance/flags'; +iFlags(/./g); +// @ts-expect-error +iFlags(); + +// $proposal +import '@core-js/pure/proposals/accessible-object-hasownproperty'; diff --git a/tests/type-definitions/templates/templates.require.ts b/tests/type-definitions/templates/templates.require.ts new file mode 100644 index 000000000000..0d391c194961 --- /dev/null +++ b/tests/type-definitions/templates/templates.require.ts @@ -0,0 +1,56 @@ +// $justImport +require('@core-js/pure/full/array-buffer/detached'); + +// $prototype +require('@core-js/pure/full/array/prototype/at').call([1, 2, 3], -2); + +// $prototypeIterator +require('@core-js/pure/full/array/prototype/iterator').call([1]).next().value; + +// $uncurried +require('@core-js/pure/full/array/at')([1, 2, 3], -2); + +// $uncurriedIterator +require('@core-js/pure/full/array/iterator')([]).next().value; + +// $static +require('@core-js/pure/full/array/from')('qwe'); + +// $staticWithContext +require('@core-js/pure/full/promise/all-settled')([1, 2, 3]); + +// $patchableStatic +require('@core-js/pure/full/json/stringify')([1]); + +// $namespace +require('@core-js/pure/full/async-disposable-stack/constructor'); + +// $helper +require('@core-js/pure/full/get-iterator')([]); + +// $path +new (require('@core-js/pure/full/error/constructor').Error)(); + +// $instanceArray +require('@core-js/pure/full/instance/concat')(1); + +// $instanceString +require('@core-js/pure/full/instance/code-point-at')(''); + +// $instanceFunction +require('@core-js/pure/full/instance/demethodize')({}); + +// $instanceDOMIterables +require('@core-js/pure/full/instance/for-each')({}); + +// $instanceArrayString +require('@core-js/pure/full/instance/at')(''); + +// $instanceArrayDOMIterables +require('@core-js/pure/full/instance/entries')({}); + +// $instanceRegExpFlags +require('@core-js/pure/full/instance/flags')({}); + +// $proposal +require('@core-js/pure/proposals/accessible-object-hasownproperty'); diff --git a/tests/type-definitions/templates/tsconfig.json b/tests/type-definitions/templates/tsconfig.json new file mode 100644 index 000000000000..d7735c61adee --- /dev/null +++ b/tests/type-definitions/templates/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "types": [ + "@core-js/types/pure" + ] + }, + "include": [ + "./templates.import.ts" + ] +} diff --git a/tests/type-definitions/templates/tsconfig.require.json b/tests/type-definitions/templates/tsconfig.require.json new file mode 100644 index 000000000000..cd0a338ab089 --- /dev/null +++ b/tests/type-definitions/templates/tsconfig.require.json @@ -0,0 +1,12 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "types": [ + "@core-js/types/pure", + "@types/node" + ] + }, + "include": [ + "./templates.require.ts" + ] +} diff --git a/tests/type-definitions/builder.ts b/tests/type-definitions/tools/builder.ts similarity index 85% rename from tests/type-definitions/builder.ts rename to tests/type-definitions/tools/builder.ts index ba7b95ff38a2..179565275b62 100644 --- a/tests/type-definitions/builder.ts +++ b/tests/type-definitions/tools/builder.ts @@ -66,3 +66,18 @@ await builder({ comment: { size: false, modules: true }, }, }); + +// @ts-expect-error +builder({ format: 'amd' }); +// @ts-expect-error +builder({ filename: true }); +// @ts-expect-error +builder({ summary: 'all' }); +// @ts-expect-error +builder({ summary: { console: 'show' } }); +// @ts-expect-error +builder({ summary: { comment: { invalidKey: true } } }); +// @ts-expect-error +builder({ targets: 123 }); +// @ts-expect-error +builder({ invalidOption: true }); diff --git a/tests/type-definitions/compat.ts b/tests/type-definitions/tools/compat.ts similarity index 75% rename from tests/type-definitions/compat.ts rename to tests/type-definitions/tools/compat.ts index a485bacf2d1a..520a18754fe6 100644 --- a/tests/type-definitions/compat.ts +++ b/tests/type-definitions/tools/compat.ts @@ -9,15 +9,29 @@ compat.getEntriesListForTargetVersion('3.0'); getModulesListForTargetVersion('3.0'); compat.getModulesListForTargetVersion('3.0'); -compat.data['es.array.push'].android -compat.data['es.array.push'].firefox +// @ts-expect-error +getEntriesListForTargetVersion(123); +// @ts-expect-error +compat.getEntriesListForTargetVersion(123); +// @ts-expect-error +getModulesListForTargetVersion({ version: true }); +// @ts-expect-error +compat.getModulesListForTargetVersion({ version: true }); + +compat.data['es.array.push'].android; +compat.data['es.array.push'].firefox; + +// @ts-expect-error +compat.entries['es.array.map'][0] = 'not-a-module'; +// @ts-expect-error +compat.data['es.array.map']['notATarget']; if (typeof compat.modules[0] !== 'string') { console.error('Invalid'); } if (!compat.entries['core-js'].includes('es.array.from')) { - console.error('Invalid') + console.error('Invalid'); } compat(); @@ -40,6 +54,15 @@ compat({ targets: { chrome: '26', firefox: 4, esmodules: true, node: 'current', compat({ version: '3.0' }); compat({ inverse: true }); +// @ts-expect-error +compat({ modules: 123 }); +// @ts-expect-error +compat({ inverse: 'incorrect' }); +// @ts-expect-error +compat({ exclude: 123 }); +// @ts-expect-error +compat({ targets: 123 }); + compat.compat(); compat.compat({}); compat.compat({ modules: 'core-js/actual' }); @@ -60,6 +83,15 @@ compat.compat({ targets: { chrome: '26', firefox: 4, esmodules: true, node: 'cur compat.compat({ version: '3.0' }); compat.compat({ inverse: true }); +// @ts-expect-error +compat.compat({ modules: 123 }); +// @ts-expect-error +compat.compat({ inverse: 'incorrect' }); +// @ts-expect-error +compat({ exclude: 123 }); +// @ts-expect-error +compat({ targets: 123 }); + compat2(); compat2({}); compat2({ modules: 'core-js/actual' }); @@ -79,3 +111,12 @@ 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 }); + +// @ts-expect-error +compat2({ modules: 123 }); +// @ts-expect-error +compat2({ inverse: 'incorrect' }); +// @ts-expect-error +compat2({ exclude: 123 }); +// @ts-expect-error +compat2({ targets: 123 }); diff --git a/tests/type-definitions/tools/tsconfig.json b/tests/type-definitions/tools/tsconfig.json new file mode 100644 index 000000000000..f6056948dd92 --- /dev/null +++ b/tests/type-definitions/tools/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../tsconfig.json", + "include": [ + "./builder.ts", + "./compat.ts" + ] +} diff --git a/tests/type-definitions/tsconfig.json b/tests/type-definitions/tsconfig.json index 8809cf496f3e..c2d0dbe5fc5e 100644 --- a/tests/type-definitions/tsconfig.json +++ b/tests/type-definitions/tsconfig.json @@ -2,12 +2,9 @@ "compilerOptions": { "strict": true, "target": "esnext", - "module": "esnext", - "moduleResolution": "node", + "module": "nodenext", "esModuleInterop": true, + "moduleResolution": "nodenext", "noEmit": true - }, - "include": [ - "*.ts" - ] + } } diff --git a/tests/unit-global/esnext.promise.all-keyed.js b/tests/unit-global/esnext.promise.all-keyed.js index 3856f2d67279..a1809771a6ba 100644 --- a/tests/unit-global/esnext.promise.all-keyed.js +++ b/tests/unit-global/esnext.promise.all-keyed.js @@ -6,6 +6,20 @@ QUnit.test('Promise.allKeyed', assert => { assert.true(Promise.allKeyed({}) instanceof Promise, 'returns a promise'); }); +QUnit.test('Promise.allKeyed, resolved with primitives', assert => { + return Promise.allKeyed({ + a: 1, + b: Promise.resolve(2), + c: 3, + }).then(it => { + assert.deepEqual(it, { + a: 1, + b: 2, + c: 3, + }, 'resolved with a correct value'); + }); +}); + QUnit.test('Promise.allKeyed, resolved', assert => { return Promise.allKeyed({ a: Promise.resolve(1), diff --git a/tests/unit-global/esnext.promise.all-settled-keyed.js b/tests/unit-global/esnext.promise.all-settled-keyed.js index debd013b519a..4ad335f6a308 100644 --- a/tests/unit-global/esnext.promise.all-settled-keyed.js +++ b/tests/unit-global/esnext.promise.all-settled-keyed.js @@ -20,6 +20,20 @@ QUnit.test('Promise.allSettledKeyed, resolved', assert => { }); }); +QUnit.test('Promise.allSettledKeyed, resolved with primitives', assert => { + return Promise.allSettledKeyed({ + a: 1, + b: Promise.resolve(2), + c: 3, + }).then(it => { + assert.deepEqual(it, { + a: { value: 1, status: 'fulfilled' }, + b: { value: 2, status: 'fulfilled' }, + c: { value: 3, status: 'fulfilled' }, + }, 'resolved with a correct value'); + }); +}); + QUnit.test('Promise.allSettledKeyed, resolved with rejection', assert => { return Promise.allSettledKeyed({ a: Promise.resolve(1), diff --git a/tests/unit-pure/esnext.promise.all-keyed.js b/tests/unit-pure/esnext.promise.all-keyed.js index a1f9c1907407..052806d3f871 100644 --- a/tests/unit-pure/esnext.promise.all-keyed.js +++ b/tests/unit-pure/esnext.promise.all-keyed.js @@ -22,6 +22,20 @@ QUnit.test('Promise.allKeyed, resolved', assert => { }); }); +QUnit.test('Promise.allKeyed, resolved with primitives', assert => { + return Promise.allKeyed({ + a: 1, + b: Promise.resolve(2), + c: 3, + }).then(it => { + assert.deepEqual(it, { + a: 1, + b: 2, + c: 3, + }, 'resolved with a correct value'); + }); +}); + QUnit.test('Promise.allKeyed, resolved with rejection', assert => { return Promise.allKeyed({ a: Promise.resolve(1), diff --git a/tests/unit-pure/esnext.promise.all-settled-keyed.js b/tests/unit-pure/esnext.promise.all-settled-keyed.js index c7c4938ff043..a3f2c54f970a 100644 --- a/tests/unit-pure/esnext.promise.all-settled-keyed.js +++ b/tests/unit-pure/esnext.promise.all-settled-keyed.js @@ -22,6 +22,20 @@ QUnit.test('Promise.allSettledKeyed, resolved', assert => { }); }); +QUnit.test('Promise.allSettledKeyed, resolved with primitives', assert => { + return Promise.allSettledKeyed({ + a: 1, + b: Promise.resolve(2), + c: 3, + }).then(it => { + assert.deepEqual(it, { + a: { value: 1, status: 'fulfilled' }, + b: { value: 2, status: 'fulfilled' }, + c: { value: 3, status: 'fulfilled' }, + }, 'resolved with a correct value'); + }); +}); + QUnit.test('Promise.allSettledKeyed, resolved with rejection', assert => { return Promise.allSettledKeyed({ a: Promise.resolve(1),