master
Thomas Chazot 2 years ago
parent 3db293983e
commit 383cd72d77

@ -10,6 +10,7 @@
"@react-navigation/bottom-tabs@^6.5.4",
"@react-navigation/native@^6.1.3",
"@react-navigation/stack@^6.3.12",
"@reduxjs/toolkit@^1.9.3",
"@types/react-native@~0.70.6",
"@types/react@~18.0.14",
"expo-cli@^6.1.0",
@ -20,7 +21,9 @@
"react-native-safe-area-context@^4.5.0",
"react-native-web@~0.18.9",
"react-native@0.70.5",
"react-redux@^8.0.5",
"react@18.1.0",
"redux@^4.2.1",
"typescript@^4.6.3"
],
"lockfileEntries": {
@ -230,9 +233,11 @@
"@babel/register@^7.13.16": "https://registry.npmjs.org/@babel/register/-/register-7.18.9.tgz",
"@babel/runtime@7.9.0": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.9.0.tgz",
"@babel/runtime@^7.0.0": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.20.13.tgz",
"@babel/runtime@^7.12.1": "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.21.0.tgz#5b55c9d394e5fcf304909a8b00c07dc217b56673",
"@babel/runtime@^7.14.0": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.20.13.tgz",
"@babel/runtime@^7.18.6": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.20.13.tgz",
"@babel/runtime@^7.8.4": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.20.13.tgz",
"@babel/runtime@^7.9.2": "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.21.0.tgz#5b55c9d394e5fcf304909a8b00c07dc217b56673",
"@babel/template@^7.0.0": "https://registry.npmjs.org/@babel/template/-/template-7.20.7.tgz",
"@babel/template@^7.18.10": "https://registry.npmjs.org/@babel/template/-/template-7.20.7.tgz",
"@babel/template@^7.20.7": "https://registry.npmjs.org/@babel/template/-/template-7.20.7.tgz",
@ -340,12 +345,13 @@
"@react-native/normalize-color@2.0.0": "https://registry.npmjs.org/@react-native/normalize-color/-/normalize-color-2.0.0.tgz",
"@react-native/normalize-color@^2.0.0": "https://registry.npmjs.org/@react-native/normalize-color/-/normalize-color-2.1.0.tgz",
"@react-native/polyfills@2.0.0": "https://registry.npmjs.org/@react-native/polyfills/-/polyfills-2.0.0.tgz",
"@react-navigation/bottom-tabs@^6.5.4": "https://registry.yarnpkg.com/@react-navigation/bottom-tabs/-/bottom-tabs-6.5.4.tgz#f123705fbc093de900c37501c6ab9ab646c04d50",
"@react-navigation/core@^6.4.6": "https://registry.yarnpkg.com/@react-navigation/core/-/core-6.4.6.tgz#b0738667dec5927b01c4c496c2f4c73ef8a5e4dd",
"@react-navigation/elements@^1.3.14": "https://registry.yarnpkg.com/@react-navigation/elements/-/elements-1.3.14.tgz#ee9ef7f57e0877700ebb359947728b255bbb9c65",
"@react-navigation/native@^6.1.3": "https://registry.yarnpkg.com/@react-navigation/native/-/native-6.1.3.tgz#06064c5e49c417a3dbe210b3f00841beefd326c5",
"@react-navigation/routers@^6.1.6": "https://registry.yarnpkg.com/@react-navigation/routers/-/routers-6.1.6.tgz#f57f2a73855d329255aa225fdad75ae8e7700c6d",
"@react-navigation/bottom-tabs@^6.5.4": "https://registry.npmjs.org/@react-navigation/bottom-tabs/-/bottom-tabs-6.5.4.tgz",
"@react-navigation/core@^6.4.6": "https://registry.npmjs.org/@react-navigation/core/-/core-6.4.6.tgz",
"@react-navigation/elements@^1.3.14": "https://registry.npmjs.org/@react-navigation/elements/-/elements-1.3.14.tgz",
"@react-navigation/native@^6.1.3": "https://registry.npmjs.org/@react-navigation/native/-/native-6.1.3.tgz",
"@react-navigation/routers@^6.1.6": "https://registry.npmjs.org/@react-navigation/routers/-/routers-6.1.6.tgz",
"@react-navigation/stack@^6.3.12": "https://registry.yarnpkg.com/@react-navigation/stack/-/stack-6.3.12.tgz#8e3779efd0b2ad015f62b89193b9eacecb41fab2",
"@reduxjs/toolkit@^1.9.3": "https://registry.yarnpkg.com/@reduxjs/toolkit/-/toolkit-1.9.3.tgz#27e1a33072b5a312e4f7fa19247fec160bbb2df9",
"@segment/loosely-validate-event@^2.0.0": "https://registry.npmjs.org/@segment/loosely-validate-event/-/loosely-validate-event-2.0.0.tgz",
"@sideway/address@^4.1.3": "https://registry.npmjs.org/@sideway/address/-/address-4.1.4.tgz",
"@sideway/formula@^3.0.0": "https://registry.npmjs.org/@sideway/formula/-/formula-3.0.1.tgz",
@ -358,6 +364,7 @@
"@types/cacheable-request@^6.0.1": "https://registry.npmjs.org/@types/cacheable-request/-/cacheable-request-6.0.3.tgz",
"@types/glob@^7.1.1": "https://registry.npmjs.org/@types/glob/-/glob-7.2.0.tgz",
"@types/hammerjs@^2.0.36": "https://registry.npmjs.org/@types/hammerjs/-/hammerjs-2.0.41.tgz",
"@types/hoist-non-react-statics@^3.3.1": "https://registry.yarnpkg.com/@types/hoist-non-react-statics/-/hoist-non-react-statics-3.3.1.tgz#1124aafe5118cb591977aeb1ceaaed1070eb039f",
"@types/html-minifier-terser@^5.0.0": "https://registry.npmjs.org/@types/html-minifier-terser/-/html-minifier-terser-5.1.2.tgz",
"@types/http-cache-semantics@*": "https://registry.npmjs.org/@types/http-cache-semantics/-/http-cache-semantics-4.0.1.tgz",
"@types/istanbul-lib-coverage@*": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.4.tgz",
@ -381,6 +388,7 @@
"@types/tapable@^1": "https://registry.npmjs.org/@types/tapable/-/tapable-1.0.8.tgz",
"@types/tapable@^1.0.5": "https://registry.npmjs.org/@types/tapable/-/tapable-1.0.8.tgz",
"@types/uglify-js@*": "https://registry.npmjs.org/@types/uglify-js/-/uglify-js-3.17.1.tgz",
"@types/use-sync-external-store@^0.0.3": "https://registry.yarnpkg.com/@types/use-sync-external-store/-/use-sync-external-store-0.0.3.tgz#b6725d5f4af24ace33b36fafd295136e75509f43",
"@types/webpack-sources@*": "https://registry.npmjs.org/@types/webpack-sources/-/webpack-sources-3.2.0.tgz",
"@types/webpack@^4.4.31": "https://registry.npmjs.org/@types/webpack/-/webpack-4.41.33.tgz",
"@types/webpack@^4.41.8": "https://registry.npmjs.org/@types/webpack/-/webpack-4.41.33.tgz",
@ -1022,6 +1030,7 @@
"hex-color-regex@^1.1.0": "https://registry.npmjs.org/hex-color-regex/-/hex-color-regex-1.1.0.tgz",
"hmac-drbg@^1.0.1": "https://registry.npmjs.org/hmac-drbg/-/hmac-drbg-1.0.1.tgz",
"hoist-non-react-statics@^3.3.0": "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-3.3.2.tgz",
"hoist-non-react-statics@^3.3.2": "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-3.3.2.tgz",
"hosted-git-info@^2.6.0": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.8.9.tgz",
"hosted-git-info@^3.0.2": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-3.0.8.tgz",
"hpack.js@^2.1.6": "https://registry.npmjs.org/hpack.js/-/hpack.js-2.1.6.tgz",
@ -1061,6 +1070,7 @@
"image-size@^0.6.0": "https://registry.npmjs.org/image-size/-/image-size-0.6.3.tgz",
"image-size@^1.0.0": "https://registry.npmjs.org/image-size/-/image-size-1.0.2.tgz",
"immer@8.0.1": "https://registry.npmjs.org/immer/-/immer-8.0.1.tgz",
"immer@^9.0.16": "https://registry.yarnpkg.com/immer/-/immer-9.0.19.tgz#67fb97310555690b5f9cd8380d38fc0aabb6b38b",
"import-fresh@^2.0.0": "https://registry.npmjs.org/import-fresh/-/import-fresh-2.0.0.tgz",
"import-local@^2.0.0": "https://registry.npmjs.org/import-local/-/import-local-2.0.0.tgz",
"imurmurhash@^0.1.4": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz",
@ -1278,7 +1288,7 @@
"md5@~2.2.0": "https://registry.npmjs.org/md5/-/md5-2.2.1.tgz",
"md5hex@1.0.0": "https://registry.npmjs.org/md5hex/-/md5hex-1.0.0.tgz",
"md5hex@^1.0.0": "https://registry.npmjs.org/md5hex/-/md5hex-1.0.0.tgz",
"mdn-data@2.0.14": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.0.14.tgz",
"mdn-data@2.0.14": "https://registry.yarnpkg.com/mdn-data/-/mdn-data-2.0.14.tgz#7113fc4281917d63ce29b43446f701e68c25ba50",
"mdn-data@2.0.4": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.0.4.tgz",
"media-typer@0.3.0": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
"memoize-one@^5.0.0": "https://registry.npmjs.org/memoize-one/-/memoize-one-5.2.1.tgz",
@ -1633,12 +1643,14 @@
"react-is@^16.13.1": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
"react-is@^16.7.0": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
"react-is@^17.0.1": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
"react-is@^18.0.0": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz",
"react-native-codegen@^0.70.6": "https://registry.npmjs.org/react-native-codegen/-/react-native-codegen-0.70.6.tgz",
"react-native-gesture-handler@^2.9.0": "https://registry.yarnpkg.com/react-native-gesture-handler/-/react-native-gesture-handler-2.9.0.tgz#2f63812e523c646f25b9ad660fc6f75948e51241",
"react-native-gradle-plugin@^0.70.3": "https://registry.npmjs.org/react-native-gradle-plugin/-/react-native-gradle-plugin-0.70.3.tgz",
"react-native-safe-area-context@^4.5.0": "https://registry.npmjs.org/react-native-safe-area-context/-/react-native-safe-area-context-4.5.0.tgz",
"react-native-web@~0.18.9": "https://registry.npmjs.org/react-native-web/-/react-native-web-0.18.11.tgz",
"react-native@0.70.5": "https://registry.npmjs.org/react-native/-/react-native-0.70.5.tgz",
"react-redux@^8.0.5": "https://registry.yarnpkg.com/react-redux/-/react-redux-8.0.5.tgz#e5fb8331993a019b8aaf2e167a93d10af469c7bd",
"react-refresh@^0.4.0": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.4.3.tgz",
"react-shallow-renderer@^16.15.0": "https://registry.npmjs.org/react-shallow-renderer/-/react-shallow-renderer-16.15.0.tgz",
"react@18.1.0": "https://registry.npmjs.org/react/-/react-18.1.0.tgz",
@ -1661,6 +1673,9 @@
"readline@^1.3.0": "https://registry.npmjs.org/readline/-/readline-1.3.0.tgz",
"recast@^0.20.4": "https://registry.npmjs.org/recast/-/recast-0.20.5.tgz",
"recursive-readdir@2.2.2": "https://registry.npmjs.org/recursive-readdir/-/recursive-readdir-2.2.2.tgz",
"redux-thunk@^2.4.2": "https://registry.yarnpkg.com/redux-thunk/-/redux-thunk-2.4.2.tgz#b9d05d11994b99f7a91ea223e8b04cf0afa5ef3b",
"redux@^4.2.0": "https://registry.yarnpkg.com/redux/-/redux-4.2.1.tgz#c08f4306826c49b5e9dc901dee0452ea8fce6197",
"redux@^4.2.1": "https://registry.yarnpkg.com/redux/-/redux-4.2.1.tgz#c08f4306826c49b5e9dc901dee0452ea8fce6197",
"regenerate-unicode-properties@^10.1.0": "https://registry.npmjs.org/regenerate-unicode-properties/-/regenerate-unicode-properties-10.1.0.tgz",
"regenerate@^1.4.2": "https://registry.npmjs.org/regenerate/-/regenerate-1.4.2.tgz",
"regenerator-runtime@^0.13.11": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz",
@ -1691,6 +1706,7 @@
"requireg@^0.2.2": "https://registry.npmjs.org/requireg/-/requireg-0.2.2.tgz",
"requires-port@^1.0.0": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz",
"reselect@^4.0.0": "https://registry.npmjs.org/reselect/-/reselect-4.1.7.tgz",
"reselect@^4.1.7": "https://registry.npmjs.org/reselect/-/reselect-4.1.7.tgz",
"resolve-alpn@^1.0.0": "https://registry.npmjs.org/resolve-alpn/-/resolve-alpn-1.2.1.tgz",
"resolve-cwd@^2.0.0": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-2.0.0.tgz",
"resolve-from@^3.0.0": "https://registry.npmjs.org/resolve-from/-/resolve-from-3.0.0.tgz",

@ -1,54 +0,0 @@
# 1.0.0 - 2016-01-07
- Removed: unused speed test
- Added: Automatic routing between previously unsupported conversions
([#27](https://github.com/Qix-/color-convert/pull/27))
- Removed: `xxx2xxx()` and `xxx2xxxRaw()` functions
([#27](https://github.com/Qix-/color-convert/pull/27))
- Removed: `convert()` class
([#27](https://github.com/Qix-/color-convert/pull/27))
- Changed: all functions to lookup dictionary
([#27](https://github.com/Qix-/color-convert/pull/27))
- Changed: `ansi` to `ansi256`
([#27](https://github.com/Qix-/color-convert/pull/27))
- Fixed: argument grouping for functions requiring only one argument
([#27](https://github.com/Qix-/color-convert/pull/27))
# 0.6.0 - 2015-07-23
- Added: methods to handle
[ANSI](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors) 16/256 colors:
- rgb2ansi16
- rgb2ansi
- hsl2ansi16
- hsl2ansi
- hsv2ansi16
- hsv2ansi
- hwb2ansi16
- hwb2ansi
- cmyk2ansi16
- cmyk2ansi
- keyword2ansi16
- keyword2ansi
- ansi162rgb
- ansi162hsl
- ansi162hsv
- ansi162hwb
- ansi162cmyk
- ansi162keyword
- ansi2rgb
- ansi2hsl
- ansi2hsv
- ansi2hwb
- ansi2cmyk
- ansi2keyword
([#18](https://github.com/harthur/color-convert/pull/18))
# 0.5.3 - 2015-06-02
- Fixed: hsl2hsv does not return `NaN` anymore when using `[0,0,0]`
([#15](https://github.com/harthur/color-convert/issues/15))
---
Check out commit logs for older releases

@ -1,68 +0,0 @@
# color-convert
[![Build Status](https://travis-ci.org/Qix-/color-convert.svg?branch=master)](https://travis-ci.org/Qix-/color-convert)
Color-convert is a color conversion library for JavaScript and node.
It converts all ways between `rgb`, `hsl`, `hsv`, `hwb`, `cmyk`, `ansi`, `ansi16`, `hex` strings, and CSS `keyword`s (will round to closest):
```js
var convert = require('color-convert');
convert.rgb.hsl(140, 200, 100); // [96, 48, 59]
convert.keyword.rgb('blue'); // [0, 0, 255]
var rgbChannels = convert.rgb.channels; // 3
var cmykChannels = convert.cmyk.channels; // 4
var ansiChannels = convert.ansi16.channels; // 1
```
# Install
```console
$ npm install color-convert
```
# API
Simply get the property of the _from_ and _to_ conversion that you're looking for.
All functions have a rounded and unrounded variant. By default, return values are rounded. To get the unrounded (raw) results, simply tack on `.raw` to the function.
All 'from' functions have a hidden property called `.channels` that indicates the number of channels the function expects (not including alpha).
```js
var convert = require('color-convert');
// Hex to LAB
convert.hex.lab('DEADBF'); // [ 76, 21, -2 ]
convert.hex.lab.raw('DEADBF'); // [ 75.56213190997677, 20.653827952644754, -2.290532499330533 ]
// RGB to CMYK
convert.rgb.cmyk(167, 255, 4); // [ 35, 0, 98, 0 ]
convert.rgb.cmyk.raw(167, 255, 4); // [ 34.509803921568626, 0, 98.43137254901961, 0 ]
```
### Arrays
All functions that accept multiple arguments also support passing an array.
Note that this does **not** apply to functions that convert from a color that only requires one value (e.g. `keyword`, `ansi256`, `hex`, etc.)
```js
var convert = require('color-convert');
convert.rgb.hex(123, 45, 67); // '7B2D43'
convert.rgb.hex([123, 45, 67]); // '7B2D43'
```
## Routing
Conversions that don't have an _explicitly_ defined conversion (in [conversions.js](conversions.js)), but can be converted by means of sub-conversions (e.g. XYZ -> **RGB** -> CMYK), are automatically routed together. This allows just about any color model supported by `color-convert` to be converted to any other model, so long as a sub-conversion path exists. This is also true for conversions requiring more than one step in between (e.g. LCH -> **LAB** -> **XYZ** -> **RGB** -> Hex).
Keep in mind that extensive conversions _may_ result in a loss of precision, and exist only to be complete. For a list of "direct" (single-step) conversions, see [conversions.js](conversions.js).
# Contribute
If there is a new model you would like to support, or want to add a direct conversion between two existing models, please send us a pull request.
# License
Copyright © 2011-2016, Heather Arthur and Josh Junon. Licensed under the [MIT License](LICENSE).

@ -1,839 +0,0 @@
/* MIT license */
/* eslint-disable no-mixed-operators */
const cssKeywords = require('color-name');
// NOTE: conversions should only return primitive values (i.e. arrays, or
// values that give correct `typeof` results).
// do not use box values types (i.e. Number(), String(), etc.)
const reverseKeywords = {};
for (const key of Object.keys(cssKeywords)) {
reverseKeywords[cssKeywords[key]] = key;
}
const convert = {
rgb: {channels: 3, labels: 'rgb'},
hsl: {channels: 3, labels: 'hsl'},
hsv: {channels: 3, labels: 'hsv'},
hwb: {channels: 3, labels: 'hwb'},
cmyk: {channels: 4, labels: 'cmyk'},
xyz: {channels: 3, labels: 'xyz'},
lab: {channels: 3, labels: 'lab'},
lch: {channels: 3, labels: 'lch'},
hex: {channels: 1, labels: ['hex']},
keyword: {channels: 1, labels: ['keyword']},
ansi16: {channels: 1, labels: ['ansi16']},
ansi256: {channels: 1, labels: ['ansi256']},
hcg: {channels: 3, labels: ['h', 'c', 'g']},
apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
gray: {channels: 1, labels: ['gray']}
};
module.exports = convert;
// Hide .channels and .labels properties
for (const model of Object.keys(convert)) {
if (!('channels' in convert[model])) {
throw new Error('missing channels property: ' + model);
}
if (!('labels' in convert[model])) {
throw new Error('missing channel labels property: ' + model);
}
if (convert[model].labels.length !== convert[model].channels) {
throw new Error('channel and label counts mismatch: ' + model);
}
const {channels, labels} = convert[model];
delete convert[model].channels;
delete convert[model].labels;
Object.defineProperty(convert[model], 'channels', {value: channels});
Object.defineProperty(convert[model], 'labels', {value: labels});
}
convert.rgb.hsl = function (rgb) {
const r = rgb[0] / 255;
const g = rgb[1] / 255;
const b = rgb[2] / 255;
const min = Math.min(r, g, b);
const max = Math.max(r, g, b);
const delta = max - min;
let h;
let s;
if (max === min) {
h = 0;
} else if (r === max) {
h = (g - b) / delta;
} else if (g === max) {
h = 2 + (b - r) / delta;
} else if (b === max) {
h = 4 + (r - g) / delta;
}
h = Math.min(h * 60, 360);
if (h < 0) {
h += 360;
}
const l = (min + max) / 2;
if (max === min) {
s = 0;
} else if (l <= 0.5) {
s = delta / (max + min);
} else {
s = delta / (2 - max - min);
}
return [h, s * 100, l * 100];
};
convert.rgb.hsv = function (rgb) {
let rdif;
let gdif;
let bdif;
let h;
let s;
const r = rgb[0] / 255;
const g = rgb[1] / 255;
const b = rgb[2] / 255;
const v = Math.max(r, g, b);
const diff = v - Math.min(r, g, b);
const diffc = function (c) {
return (v - c) / 6 / diff + 1 / 2;
};
if (diff === 0) {
h = 0;
s = 0;
} else {
s = diff / v;
rdif = diffc(r);
gdif = diffc(g);
bdif = diffc(b);
if (r === v) {
h = bdif - gdif;
} else if (g === v) {
h = (1 / 3) + rdif - bdif;
} else if (b === v) {
h = (2 / 3) + gdif - rdif;
}
if (h < 0) {
h += 1;
} else if (h > 1) {
h -= 1;
}
}
return [
h * 360,
s * 100,
v * 100
];
};
convert.rgb.hwb = function (rgb) {
const r = rgb[0];
const g = rgb[1];
let b = rgb[2];
const h = convert.rgb.hsl(rgb)[0];
const w = 1 / 255 * Math.min(r, Math.min(g, b));
b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
return [h, w * 100, b * 100];
};
convert.rgb.cmyk = function (rgb) {
const r = rgb[0] / 255;
const g = rgb[1] / 255;
const b = rgb[2] / 255;
const k = Math.min(1 - r, 1 - g, 1 - b);
const c = (1 - r - k) / (1 - k) || 0;
const m = (1 - g - k) / (1 - k) || 0;
const y = (1 - b - k) / (1 - k) || 0;
return [c * 100, m * 100, y * 100, k * 100];
};
function comparativeDistance(x, y) {
/*
See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
*/
return (
((x[0] - y[0]) ** 2) +
((x[1] - y[1]) ** 2) +
((x[2] - y[2]) ** 2)
);
}
convert.rgb.keyword = function (rgb) {
const reversed = reverseKeywords[rgb];
if (reversed) {
return reversed;
}
let currentClosestDistance = Infinity;
let currentClosestKeyword;
for (const keyword of Object.keys(cssKeywords)) {
const value = cssKeywords[keyword];
// Compute comparative distance
const distance = comparativeDistance(rgb, value);
// Check if its less, if so set as closest
if (distance < currentClosestDistance) {
currentClosestDistance = distance;
currentClosestKeyword = keyword;
}
}
return currentClosestKeyword;
};
convert.keyword.rgb = function (keyword) {
return cssKeywords[keyword];
};
convert.rgb.xyz = function (rgb) {
let r = rgb[0] / 255;
let g = rgb[1] / 255;
let b = rgb[2] / 255;
// Assume sRGB
r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92);
g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92);
b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92);
const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
return [x * 100, y * 100, z * 100];
};
convert.rgb.lab = function (rgb) {
const xyz = convert.rgb.xyz(rgb);
let x = xyz[0];
let y = xyz[1];
let z = xyz[2];
x /= 95.047;
y /= 100;
z /= 108.883;
x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
const l = (116 * y) - 16;
const a = 500 * (x - y);
const b = 200 * (y - z);
return [l, a, b];
};
convert.hsl.rgb = function (hsl) {
const h = hsl[0] / 360;
const s = hsl[1] / 100;
const l = hsl[2] / 100;
let t2;
let t3;
let val;
if (s === 0) {
val = l * 255;
return [val, val, val];
}
if (l < 0.5) {
t2 = l * (1 + s);
} else {
t2 = l + s - l * s;
}
const t1 = 2 * l - t2;
const rgb = [0, 0, 0];
for (let i = 0; i < 3; i++) {
t3 = h + 1 / 3 * -(i - 1);
if (t3 < 0) {
t3++;
}
if (t3 > 1) {
t3--;
}
if (6 * t3 < 1) {
val = t1 + (t2 - t1) * 6 * t3;
} else if (2 * t3 < 1) {
val = t2;
} else if (3 * t3 < 2) {
val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
} else {
val = t1;
}
rgb[i] = val * 255;
}
return rgb;
};
convert.hsl.hsv = function (hsl) {
const h = hsl[0];
let s = hsl[1] / 100;
let l = hsl[2] / 100;
let smin = s;
const lmin = Math.max(l, 0.01);
l *= 2;
s *= (l <= 1) ? l : 2 - l;
smin *= lmin <= 1 ? lmin : 2 - lmin;
const v = (l + s) / 2;
const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
return [h, sv * 100, v * 100];
};
convert.hsv.rgb = function (hsv) {
const h = hsv[0] / 60;
const s = hsv[1] / 100;
let v = hsv[2] / 100;
const hi = Math.floor(h) % 6;
const f = h - Math.floor(h);
const p = 255 * v * (1 - s);
const q = 255 * v * (1 - (s * f));
const t = 255 * v * (1 - (s * (1 - f)));
v *= 255;
switch (hi) {
case 0:
return [v, t, p];
case 1:
return [q, v, p];
case 2:
return [p, v, t];
case 3:
return [p, q, v];
case 4:
return [t, p, v];
case 5:
return [v, p, q];
}
};
convert.hsv.hsl = function (hsv) {
const h = hsv[0];
const s = hsv[1] / 100;
const v = hsv[2] / 100;
const vmin = Math.max(v, 0.01);
let sl;
let l;
l = (2 - s) * v;
const lmin = (2 - s) * vmin;
sl = s * vmin;
sl /= (lmin <= 1) ? lmin : 2 - lmin;
sl = sl || 0;
l /= 2;
return [h, sl * 100, l * 100];
};
// http://dev.w3.org/csswg/css-color/#hwb-to-rgb
convert.hwb.rgb = function (hwb) {
const h = hwb[0] / 360;
let wh = hwb[1] / 100;
let bl = hwb[2] / 100;
const ratio = wh + bl;
let f;
// Wh + bl cant be > 1
if (ratio > 1) {
wh /= ratio;
bl /= ratio;
}
const i = Math.floor(6 * h);
const v = 1 - bl;
f = 6 * h - i;
if ((i & 0x01) !== 0) {
f = 1 - f;
}
const n = wh + f * (v - wh); // Linear interpolation
let r;
let g;
let b;
/* eslint-disable max-statements-per-line,no-multi-spaces */
switch (i) {
default:
case 6:
case 0: r = v; g = n; b = wh; break;
case 1: r = n; g = v; b = wh; break;
case 2: r = wh; g = v; b = n; break;
case 3: r = wh; g = n; b = v; break;
case 4: r = n; g = wh; b = v; break;
case 5: r = v; g = wh; b = n; break;
}
/* eslint-enable max-statements-per-line,no-multi-spaces */
return [r * 255, g * 255, b * 255];
};
convert.cmyk.rgb = function (cmyk) {
const c = cmyk[0] / 100;
const m = cmyk[1] / 100;
const y = cmyk[2] / 100;
const k = cmyk[3] / 100;
const r = 1 - Math.min(1, c * (1 - k) + k);
const g = 1 - Math.min(1, m * (1 - k) + k);
const b = 1 - Math.min(1, y * (1 - k) + k);
return [r * 255, g * 255, b * 255];
};
convert.xyz.rgb = function (xyz) {
const x = xyz[0] / 100;
const y = xyz[1] / 100;
const z = xyz[2] / 100;
let r;
let g;
let b;
r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
// Assume sRGB
r = r > 0.0031308
? ((1.055 * (r ** (1.0 / 2.4))) - 0.055)
: r * 12.92;
g = g > 0.0031308
? ((1.055 * (g ** (1.0 / 2.4))) - 0.055)
: g * 12.92;
b = b > 0.0031308
? ((1.055 * (b ** (1.0 / 2.4))) - 0.055)
: b * 12.92;
r = Math.min(Math.max(0, r), 1);
g = Math.min(Math.max(0, g), 1);
b = Math.min(Math.max(0, b), 1);
return [r * 255, g * 255, b * 255];
};
convert.xyz.lab = function (xyz) {
let x = xyz[0];
let y = xyz[1];
let z = xyz[2];
x /= 95.047;
y /= 100;
z /= 108.883;
x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
const l = (116 * y) - 16;
const a = 500 * (x - y);
const b = 200 * (y - z);
return [l, a, b];
};
convert.lab.xyz = function (lab) {
const l = lab[0];
const a = lab[1];
const b = lab[2];
let x;
let y;
let z;
y = (l + 16) / 116;
x = a / 500 + y;
z = y - b / 200;
const y2 = y ** 3;
const x2 = x ** 3;
const z2 = z ** 3;
y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
x *= 95.047;
y *= 100;
z *= 108.883;
return [x, y, z];
};
convert.lab.lch = function (lab) {
const l = lab[0];
const a = lab[1];
const b = lab[2];
let h;
const hr = Math.atan2(b, a);
h = hr * 360 / 2 / Math.PI;
if (h < 0) {
h += 360;
}
const c = Math.sqrt(a * a + b * b);
return [l, c, h];
};
convert.lch.lab = function (lch) {
const l = lch[0];
const c = lch[1];
const h = lch[2];
const hr = h / 360 * 2 * Math.PI;
const a = c * Math.cos(hr);
const b = c * Math.sin(hr);
return [l, a, b];
};
convert.rgb.ansi16 = function (args, saturation = null) {
const [r, g, b] = args;
let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization
value = Math.round(value / 50);
if (value === 0) {
return 30;
}
let ansi = 30
+ ((Math.round(b / 255) << 2)
| (Math.round(g / 255) << 1)
| Math.round(r / 255));
if (value === 2) {
ansi += 60;
}
return ansi;
};
convert.hsv.ansi16 = function (args) {
// Optimization here; we already know the value and don't need to get
// it converted for us.
return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
};
convert.rgb.ansi256 = function (args) {
const r = args[0];
const g = args[1];
const b = args[2];
// We use the extended greyscale palette here, with the exception of
// black and white. normal palette only has 4 greyscale shades.
if (r === g && g === b) {
if (r < 8) {
return 16;
}
if (r > 248) {
return 231;
}
return Math.round(((r - 8) / 247) * 24) + 232;
}
const ansi = 16
+ (36 * Math.round(r / 255 * 5))
+ (6 * Math.round(g / 255 * 5))
+ Math.round(b / 255 * 5);
return ansi;
};
convert.ansi16.rgb = function (args) {
let color = args % 10;
// Handle greyscale
if (color === 0 || color === 7) {
if (args > 50) {
color += 3.5;
}
color = color / 10.5 * 255;
return [color, color, color];
}
const mult = (~~(args > 50) + 1) * 0.5;
const r = ((color & 1) * mult) * 255;
const g = (((color >> 1) & 1) * mult) * 255;
const b = (((color >> 2) & 1) * mult) * 255;
return [r, g, b];
};
convert.ansi256.rgb = function (args) {
// Handle greyscale
if (args >= 232) {
const c = (args - 232) * 10 + 8;
return [c, c, c];
}
args -= 16;
let rem;
const r = Math.floor(args / 36) / 5 * 255;
const g = Math.floor((rem = args % 36) / 6) / 5 * 255;
const b = (rem % 6) / 5 * 255;
return [r, g, b];
};
convert.rgb.hex = function (args) {
const integer = ((Math.round(args[0]) & 0xFF) << 16)
+ ((Math.round(args[1]) & 0xFF) << 8)
+ (Math.round(args[2]) & 0xFF);
const string = integer.toString(16).toUpperCase();
return '000000'.substring(string.length) + string;
};
convert.hex.rgb = function (args) {
const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
if (!match) {
return [0, 0, 0];
}
let colorString = match[0];
if (match[0].length === 3) {
colorString = colorString.split('').map(char => {
return char + char;
}).join('');
}
const integer = parseInt(colorString, 16);
const r = (integer >> 16) & 0xFF;
const g = (integer >> 8) & 0xFF;
const b = integer & 0xFF;
return [r, g, b];
};
convert.rgb.hcg = function (rgb) {
const r = rgb[0] / 255;
const g = rgb[1] / 255;
const b = rgb[2] / 255;
const max = Math.max(Math.max(r, g), b);
const min = Math.min(Math.min(r, g), b);
const chroma = (max - min);
let grayscale;
let hue;
if (chroma < 1) {
grayscale = min / (1 - chroma);
} else {
grayscale = 0;
}
if (chroma <= 0) {
hue = 0;
} else
if (max === r) {
hue = ((g - b) / chroma) % 6;
} else
if (max === g) {
hue = 2 + (b - r) / chroma;
} else {
hue = 4 + (r - g) / chroma;
}
hue /= 6;
hue %= 1;
return [hue * 360, chroma * 100, grayscale * 100];
};
convert.hsl.hcg = function (hsl) {
const s = hsl[1] / 100;
const l = hsl[2] / 100;
const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l));
let f = 0;
if (c < 1.0) {
f = (l - 0.5 * c) / (1.0 - c);
}
return [hsl[0], c * 100, f * 100];
};
convert.hsv.hcg = function (hsv) {
const s = hsv[1] / 100;
const v = hsv[2] / 100;
const c = s * v;
let f = 0;
if (c < 1.0) {
f = (v - c) / (1 - c);
}
return [hsv[0], c * 100, f * 100];
};
convert.hcg.rgb = function (hcg) {
const h = hcg[0] / 360;
const c = hcg[1] / 100;
const g = hcg[2] / 100;
if (c === 0.0) {
return [g * 255, g * 255, g * 255];
}
const pure = [0, 0, 0];
const hi = (h % 1) * 6;
const v = hi % 1;
const w = 1 - v;
let mg = 0;
/* eslint-disable max-statements-per-line */
switch (Math.floor(hi)) {
case 0:
pure[0] = 1; pure[1] = v; pure[2] = 0; break;
case 1:
pure[0] = w; pure[1] = 1; pure[2] = 0; break;
case 2:
pure[0] = 0; pure[1] = 1; pure[2] = v; break;
case 3:
pure[0] = 0; pure[1] = w; pure[2] = 1; break;
case 4:
pure[0] = v; pure[1] = 0; pure[2] = 1; break;
default:
pure[0] = 1; pure[1] = 0; pure[2] = w;
}
/* eslint-enable max-statements-per-line */
mg = (1.0 - c) * g;
return [
(c * pure[0] + mg) * 255,
(c * pure[1] + mg) * 255,
(c * pure[2] + mg) * 255
];
};
convert.hcg.hsv = function (hcg) {
const c = hcg[1] / 100;
const g = hcg[2] / 100;
const v = c + g * (1.0 - c);
let f = 0;
if (v > 0.0) {
f = c / v;
}
return [hcg[0], f * 100, v * 100];
};
convert.hcg.hsl = function (hcg) {
const c = hcg[1] / 100;
const g = hcg[2] / 100;
const l = g * (1.0 - c) + 0.5 * c;
let s = 0;
if (l > 0.0 && l < 0.5) {
s = c / (2 * l);
} else
if (l >= 0.5 && l < 1.0) {
s = c / (2 * (1 - l));
}
return [hcg[0], s * 100, l * 100];
};
convert.hcg.hwb = function (hcg) {
const c = hcg[1] / 100;
const g = hcg[2] / 100;
const v = c + g * (1.0 - c);
return [hcg[0], (v - c) * 100, (1 - v) * 100];
};
convert.hwb.hcg = function (hwb) {
const w = hwb[1] / 100;
const b = hwb[2] / 100;
const v = 1 - b;
const c = v - w;
let g = 0;
if (c < 1) {
g = (v - c) / (1 - c);
}
return [hwb[0], c * 100, g * 100];
};
convert.apple.rgb = function (apple) {
return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
};
convert.rgb.apple = function (rgb) {
return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
};
convert.gray.rgb = function (args) {
return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
};
convert.gray.hsl = function (args) {
return [0, 0, args[0]];
};
convert.gray.hsv = convert.gray.hsl;
convert.gray.hwb = function (gray) {
return [0, 100, gray[0]];
};
convert.gray.cmyk = function (gray) {
return [0, 0, 0, gray[0]];
};
convert.gray.lab = function (gray) {
return [gray[0], 0, 0];
};
convert.gray.hex = function (gray) {
const val = Math.round(gray[0] / 100 * 255) & 0xFF;
const integer = (val << 16) + (val << 8) + val;
const string = integer.toString(16).toUpperCase();
return '000000'.substring(string.length) + string;
};
convert.rgb.gray = function (rgb) {
const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
return [val / 255 * 100];
};

@ -1,81 +0,0 @@
const conversions = require('./conversions');
const route = require('./route');
const convert = {};
const models = Object.keys(conversions);
function wrapRaw(fn) {
const wrappedFn = function (...args) {
const arg0 = args[0];
if (arg0 === undefined || arg0 === null) {
return arg0;
}
if (arg0.length > 1) {
args = arg0;
}
return fn(args);
};
// Preserve .conversion property if there is one
if ('conversion' in fn) {
wrappedFn.conversion = fn.conversion;
}
return wrappedFn;
}
function wrapRounded(fn) {
const wrappedFn = function (...args) {
const arg0 = args[0];
if (arg0 === undefined || arg0 === null) {
return arg0;
}
if (arg0.length > 1) {
args = arg0;
}
const result = fn(args);
// We're assuming the result is an array here.
// see notice in conversions.js; don't use box types
// in conversion functions.
if (typeof result === 'object') {
for (let len = result.length, i = 0; i < len; i++) {
result[i] = Math.round(result[i]);
}
}
return result;
};
// Preserve .conversion property if there is one
if ('conversion' in fn) {
wrappedFn.conversion = fn.conversion;
}
return wrappedFn;
}
models.forEach(fromModel => {
convert[fromModel] = {};
Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});
Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});
const routes = route(fromModel);
const routeModels = Object.keys(routes);
routeModels.forEach(toModel => {
const fn = routes[toModel];
convert[fromModel][toModel] = wrapRounded(fn);
convert[fromModel][toModel].raw = wrapRaw(fn);
});
});
module.exports = convert;

@ -1,48 +0,0 @@
{
"name": "color-convert",
"description": "Plain color conversion functions",
"version": "2.0.1",
"author": "Heather Arthur <fayearthur@gmail.com>",
"license": "MIT",
"repository": "Qix-/color-convert",
"scripts": {
"pretest": "xo",
"test": "node test/basic.js"
},
"engines": {
"node": ">=7.0.0"
},
"keywords": [
"color",
"colour",
"convert",
"converter",
"conversion",
"rgb",
"hsl",
"hsv",
"hwb",
"cmyk",
"ansi",
"ansi16"
],
"files": [
"index.js",
"conversions.js",
"route.js"
],
"xo": {
"rules": {
"default-case": 0,
"no-inline-comments": 0,
"operator-linebreak": 0
}
},
"devDependencies": {
"chalk": "^2.4.2",
"xo": "^0.24.0"
},
"dependencies": {
"color-name": "~1.1.4"
}
}

@ -1,97 +0,0 @@
const conversions = require('./conversions');
/*
This function routes a model to all other models.
all functions that are routed have a property `.conversion` attached
to the returned synthetic function. This property is an array
of strings, each with the steps in between the 'from' and 'to'
color models (inclusive).
conversions that are not possible simply are not included.
*/
function buildGraph() {
const graph = {};
// https://jsperf.com/object-keys-vs-for-in-with-closure/3
const models = Object.keys(conversions);
for (let len = models.length, i = 0; i < len; i++) {
graph[models[i]] = {
// http://jsperf.com/1-vs-infinity
// micro-opt, but this is simple.
distance: -1,
parent: null
};
}
return graph;
}
// https://en.wikipedia.org/wiki/Breadth-first_search
function deriveBFS(fromModel) {
const graph = buildGraph();
const queue = [fromModel]; // Unshift -> queue -> pop
graph[fromModel].distance = 0;
while (queue.length) {
const current = queue.pop();
const adjacents = Object.keys(conversions[current]);
for (let len = adjacents.length, i = 0; i < len; i++) {
const adjacent = adjacents[i];
const node = graph[adjacent];
if (node.distance === -1) {
node.distance = graph[current].distance + 1;
node.parent = current;
queue.unshift(adjacent);
}
}
}
return graph;
}
function link(from, to) {
return function (args) {
return to(from(args));
};
}
function wrapConversion(toModel, graph) {
const path = [graph[toModel].parent, toModel];
let fn = conversions[graph[toModel].parent][toModel];
let cur = graph[toModel].parent;
while (graph[cur].parent) {
path.unshift(graph[cur].parent);
fn = link(conversions[graph[cur].parent][cur], fn);
cur = graph[cur].parent;
}
fn.conversion = path;
return fn;
}
module.exports = function (fromModel) {
const graph = deriveBFS(fromModel);
const conversion = {};
const models = Object.keys(graph);
for (let len = models.length, i = 0; i < len; i++) {
const toModel = models[i];
const node = graph[toModel];
if (node.parent === null) {
// No possible conversion, or this node is the source model.
continue;
}
conversion[toModel] = wrapConversion(toModel, graph);
}
return conversion;
};

@ -1,123 +0,0 @@
# color
> JavaScript library for immutable color conversion and manipulation with support for CSS color strings.
```js
const color = Color('#7743CE').alpha(0.5).lighten(0.5);
console.log(color.hsl().string()); // 'hsla(262, 59%, 81%, 0.5)'
console.log(color.cmyk().round().array()); // [ 16, 25, 0, 8, 0.5 ]
console.log(color.ansi256().object()); // { ansi256: 183, alpha: 0.5 }
```
## Install
```console
$ npm install color
```
## Usage
```js
const Color = require('color');
```
### Constructors
```js
const color = Color('rgb(255, 255, 255)')
const color = Color({r: 255, g: 255, b: 255})
const color = Color.rgb(255, 255, 255)
const color = Color.rgb([255, 255, 255])
```
Set the values for individual channels with `alpha`, `red`, `green`, `blue`, `hue`, `saturationl` (hsl), `saturationv` (hsv), `lightness`, `whiteness`, `blackness`, `cyan`, `magenta`, `yellow`, `black`
String constructors are handled by [color-string](https://www.npmjs.com/package/color-string)
### Getters
```js
color.hsl();
```
Convert a color to a different space (`hsl()`, `cmyk()`, etc.).
```js
color.object(); // {r: 255, g: 255, b: 255}
```
Get a hash of the color value. Reflects the color's current model (see above).
```js
color.rgb().array() // [255, 255, 255]
```
Get an array of the values with `array()`. Reflects the color's current model (see above).
```js
color.rgbNumber() // 16777215 (0xffffff)
```
Get the rgb number value.
```js
color.hex() // #ffffff
```
Get the hex value. (**NOTE:** `.hex()` does not return alpha values; use `.hexa()` for an RGBA representation)
```js
color.red() // 255
```
Get the value for an individual channel.
### CSS Strings
```js
color.hsl().string() // 'hsl(320, 50%, 100%)'
```
Calling `.string()` with a number rounds the numbers to that decimal place. It defaults to 1.
### Luminosity
```js
color.luminosity(); // 0.412
```
The [WCAG luminosity](http://www.w3.org/TR/WCAG20/#relativeluminancedef) of the color. 0 is black, 1 is white.
```js
color.contrast(Color("blue")) // 12
```
The [WCAG contrast ratio](http://www.w3.org/TR/WCAG20/#contrast-ratiodef) to another color, from 1 (same color) to 21 (contrast b/w white and black).
```js
color.isLight(); // true
color.isDark(); // false
```
Get whether the color is "light" or "dark", useful for deciding text color.
### Manipulation
```js
color.negate() // rgb(0, 100, 255) -> rgb(255, 155, 0)
color.lighten(0.5) // hsl(100, 50%, 50%) -> hsl(100, 50%, 75%)
color.lighten(0.5) // hsl(100, 50%, 0) -> hsl(100, 50%, 0)
color.darken(0.5) // hsl(100, 50%, 50%) -> hsl(100, 50%, 25%)
color.darken(0.5) // hsl(100, 50%, 0) -> hsl(100, 50%, 0)
color.lightness(50) // hsl(100, 50%, 10%) -> hsl(100, 50%, 50%)
color.saturate(0.5) // hsl(100, 50%, 50%) -> hsl(100, 75%, 50%)
color.desaturate(0.5) // hsl(100, 50%, 50%) -> hsl(100, 25%, 50%)
color.grayscale() // #5CBF54 -> #969696
color.whiten(0.5) // hwb(100, 50%, 50%) -> hwb(100, 75%, 50%)
color.blacken(0.5) // hwb(100, 50%, 50%) -> hwb(100, 50%, 75%)
color.fade(0.5) // rgba(10, 10, 10, 0.8) -> rgba(10, 10, 10, 0.4)
color.opaquer(0.5) // rgba(10, 10, 10, 0.8) -> rgba(10, 10, 10, 1.0)
color.rotate(180) // hsl(60, 20%, 20%) -> hsl(240, 20%, 20%)
color.rotate(-90) // hsl(60, 20%, 20%) -> hsl(330, 20%, 20%)
color.mix(Color("yellow")) // cyan -> rgb(128, 255, 128)
color.mix(Color("yellow"), 0.3) // cyan -> rgb(77, 255, 179)
// chaining
color.green(100).grayscale().lighten(0.6)
```
## Propers
The API was inspired by [color-js](https://github.com/brehaut/color-js). Manipulation functions by CSS tools like Sass, LESS, and Stylus.

@ -1,496 +0,0 @@
const colorString = require('color-string');
const convert = require('color-convert');
const skippedModels = [
// To be honest, I don't really feel like keyword belongs in color convert, but eh.
'keyword',
// Gray conflicts with some method names, and has its own method defined.
'gray',
// Shouldn't really be in color-convert either...
'hex',
];
const hashedModelKeys = {};
for (const model of Object.keys(convert)) {
hashedModelKeys[[...convert[model].labels].sort().join('')] = model;
}
const limiters = {};
function Color(object, model) {
if (!(this instanceof Color)) {
return new Color(object, model);
}
if (model && model in skippedModels) {
model = null;
}
if (model && !(model in convert)) {
throw new Error('Unknown model: ' + model);
}
let i;
let channels;
if (object == null) { // eslint-disable-line no-eq-null,eqeqeq
this.model = 'rgb';
this.color = [0, 0, 0];
this.valpha = 1;
} else if (object instanceof Color) {
this.model = object.model;
this.color = [...object.color];
this.valpha = object.valpha;
} else if (typeof object === 'string') {
const result = colorString.get(object);
if (result === null) {
throw new Error('Unable to parse color from string: ' + object);
}
this.model = result.model;
channels = convert[this.model].channels;
this.color = result.value.slice(0, channels);
this.valpha = typeof result.value[channels] === 'number' ? result.value[channels] : 1;
} else if (object.length > 0) {
this.model = model || 'rgb';
channels = convert[this.model].channels;
const newArray = Array.prototype.slice.call(object, 0, channels);
this.color = zeroArray(newArray, channels);
this.valpha = typeof object[channels] === 'number' ? object[channels] : 1;
} else if (typeof object === 'number') {
// This is always RGB - can be converted later on.
this.model = 'rgb';
this.color = [
(object >> 16) & 0xFF,
(object >> 8) & 0xFF,
object & 0xFF,
];
this.valpha = 1;
} else {
this.valpha = 1;
const keys = Object.keys(object);
if ('alpha' in object) {
keys.splice(keys.indexOf('alpha'), 1);
this.valpha = typeof object.alpha === 'number' ? object.alpha : 0;
}
const hashedKeys = keys.sort().join('');
if (!(hashedKeys in hashedModelKeys)) {
throw new Error('Unable to parse color from object: ' + JSON.stringify(object));
}
this.model = hashedModelKeys[hashedKeys];
const {labels} = convert[this.model];
const color = [];
for (i = 0; i < labels.length; i++) {
color.push(object[labels[i]]);
}
this.color = zeroArray(color);
}
// Perform limitations (clamping, etc.)
if (limiters[this.model]) {
channels = convert[this.model].channels;
for (i = 0; i < channels; i++) {
const limit = limiters[this.model][i];
if (limit) {
this.color[i] = limit(this.color[i]);
}
}
}
this.valpha = Math.max(0, Math.min(1, this.valpha));
if (Object.freeze) {
Object.freeze(this);
}
}
Color.prototype = {
toString() {
return this.string();
},
toJSON() {
return this[this.model]();
},
string(places) {
let self = this.model in colorString.to ? this : this.rgb();
self = self.round(typeof places === 'number' ? places : 1);
const args = self.valpha === 1 ? self.color : [...self.color, this.valpha];
return colorString.to[self.model](args);
},
percentString(places) {
const self = this.rgb().round(typeof places === 'number' ? places : 1);
const args = self.valpha === 1 ? self.color : [...self.color, this.valpha];
return colorString.to.rgb.percent(args);
},
array() {
return this.valpha === 1 ? [...this.color] : [...this.color, this.valpha];
},
object() {
const result = {};
const {channels} = convert[this.model];
const {labels} = convert[this.model];
for (let i = 0; i < channels; i++) {
result[labels[i]] = this.color[i];
}
if (this.valpha !== 1) {
result.alpha = this.valpha;
}
return result;
},
unitArray() {
const rgb = this.rgb().color;
rgb[0] /= 255;
rgb[1] /= 255;
rgb[2] /= 255;
if (this.valpha !== 1) {
rgb.push(this.valpha);
}
return rgb;
},
unitObject() {
const rgb = this.rgb().object();
rgb.r /= 255;
rgb.g /= 255;
rgb.b /= 255;
if (this.valpha !== 1) {
rgb.alpha = this.valpha;
}
return rgb;
},
round(places) {
places = Math.max(places || 0, 0);
return new Color([...this.color.map(roundToPlace(places)), this.valpha], this.model);
},
alpha(value) {
if (value !== undefined) {
return new Color([...this.color, Math.max(0, Math.min(1, value))], this.model);
}
return this.valpha;
},
// Rgb
red: getset('rgb', 0, maxfn(255)),
green: getset('rgb', 1, maxfn(255)),
blue: getset('rgb', 2, maxfn(255)),
hue: getset(['hsl', 'hsv', 'hsl', 'hwb', 'hcg'], 0, value => ((value % 360) + 360) % 360),
saturationl: getset('hsl', 1, maxfn(100)),
lightness: getset('hsl', 2, maxfn(100)),
saturationv: getset('hsv', 1, maxfn(100)),
value: getset('hsv', 2, maxfn(100)),
chroma: getset('hcg', 1, maxfn(100)),
gray: getset('hcg', 2, maxfn(100)),
white: getset('hwb', 1, maxfn(100)),
wblack: getset('hwb', 2, maxfn(100)),
cyan: getset('cmyk', 0, maxfn(100)),
magenta: getset('cmyk', 1, maxfn(100)),
yellow: getset('cmyk', 2, maxfn(100)),
black: getset('cmyk', 3, maxfn(100)),
x: getset('xyz', 0, maxfn(95.047)),
y: getset('xyz', 1, maxfn(100)),
z: getset('xyz', 2, maxfn(108.833)),
l: getset('lab', 0, maxfn(100)),
a: getset('lab', 1),
b: getset('lab', 2),
keyword(value) {
if (value !== undefined) {
return new Color(value);
}
return convert[this.model].keyword(this.color);
},
hex(value) {
if (value !== undefined) {
return new Color(value);
}
return colorString.to.hex(this.rgb().round().color);
},
hexa(value) {
if (value !== undefined) {
return new Color(value);
}
const rgbArray = this.rgb().round().color;
let alphaHex = Math.round(this.valpha * 255).toString(16).toUpperCase();
if (alphaHex.length === 1) {
alphaHex = '0' + alphaHex;
}
return colorString.to.hex(rgbArray) + alphaHex;
},
rgbNumber() {
const rgb = this.rgb().color;
return ((rgb[0] & 0xFF) << 16) | ((rgb[1] & 0xFF) << 8) | (rgb[2] & 0xFF);
},
luminosity() {
// http://www.w3.org/TR/WCAG20/#relativeluminancedef
const rgb = this.rgb().color;
const lum = [];
for (const [i, element] of rgb.entries()) {
const chan = element / 255;
lum[i] = (chan <= 0.04045) ? chan / 12.92 : ((chan + 0.055) / 1.055) ** 2.4;
}
return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2];
},
contrast(color2) {
// http://www.w3.org/TR/WCAG20/#contrast-ratiodef
const lum1 = this.luminosity();
const lum2 = color2.luminosity();
if (lum1 > lum2) {
return (lum1 + 0.05) / (lum2 + 0.05);
}
return (lum2 + 0.05) / (lum1 + 0.05);
},
level(color2) {
// https://www.w3.org/TR/WCAG/#contrast-enhanced
const contrastRatio = this.contrast(color2);
if (contrastRatio >= 7) {
return 'AAA';
}
return (contrastRatio >= 4.5) ? 'AA' : '';
},
isDark() {
// YIQ equation from http://24ways.org/2010/calculating-color-contrast
const rgb = this.rgb().color;
const yiq = (rgb[0] * 2126 + rgb[1] * 7152 + rgb[2] * 722) / 10000;
return yiq < 128;
},
isLight() {
return !this.isDark();
},
negate() {
const rgb = this.rgb();
for (let i = 0; i < 3; i++) {
rgb.color[i] = 255 - rgb.color[i];
}
return rgb;
},
lighten(ratio) {
const hsl = this.hsl();
hsl.color[2] += hsl.color[2] * ratio;
return hsl;
},
darken(ratio) {
const hsl = this.hsl();
hsl.color[2] -= hsl.color[2] * ratio;
return hsl;
},
saturate(ratio) {
const hsl = this.hsl();
hsl.color[1] += hsl.color[1] * ratio;
return hsl;
},
desaturate(ratio) {
const hsl = this.hsl();
hsl.color[1] -= hsl.color[1] * ratio;
return hsl;
},
whiten(ratio) {
const hwb = this.hwb();
hwb.color[1] += hwb.color[1] * ratio;
return hwb;
},
blacken(ratio) {
const hwb = this.hwb();
hwb.color[2] += hwb.color[2] * ratio;
return hwb;
},
grayscale() {
// http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
const rgb = this.rgb().color;
const value = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11;
return Color.rgb(value, value, value);
},
fade(ratio) {
return this.alpha(this.valpha - (this.valpha * ratio));
},
opaquer(ratio) {
return this.alpha(this.valpha + (this.valpha * ratio));
},
rotate(degrees) {
const hsl = this.hsl();
let hue = hsl.color[0];
hue = (hue + degrees) % 360;
hue = hue < 0 ? 360 + hue : hue;
hsl.color[0] = hue;
return hsl;
},
mix(mixinColor, weight) {
// Ported from sass implementation in C
// https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209
if (!mixinColor || !mixinColor.rgb) {
throw new Error('Argument to "mix" was not a Color instance, but rather an instance of ' + typeof mixinColor);
}
const color1 = mixinColor.rgb();
const color2 = this.rgb();
const p = weight === undefined ? 0.5 : weight;
const w = 2 * p - 1;
const a = color1.alpha() - color2.alpha();
const w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2;
const w2 = 1 - w1;
return Color.rgb(
w1 * color1.red() + w2 * color2.red(),
w1 * color1.green() + w2 * color2.green(),
w1 * color1.blue() + w2 * color2.blue(),
color1.alpha() * p + color2.alpha() * (1 - p));
},
};
// Model conversion methods and static constructors
for (const model of Object.keys(convert)) {
if (skippedModels.includes(model)) {
continue;
}
const {channels} = convert[model];
// Conversion methods
Color.prototype[model] = function (...args) {
if (this.model === model) {
return new Color(this);
}
if (args.length > 0) {
return new Color(args, model);
}
return new Color([...assertArray(convert[this.model][model].raw(this.color)), this.valpha], model);
};
// 'static' construction methods
Color[model] = function (...args) {
let color = args[0];
if (typeof color === 'number') {
color = zeroArray(args, channels);
}
return new Color(color, model);
};
}
function roundTo(number, places) {
return Number(number.toFixed(places));
}
function roundToPlace(places) {
return function (number) {
return roundTo(number, places);
};
}
function getset(model, channel, modifier) {
model = Array.isArray(model) ? model : [model];
for (const m of model) {
(limiters[m] || (limiters[m] = []))[channel] = modifier;
}
model = model[0];
return function (value) {
let result;
if (value !== undefined) {
if (modifier) {
value = modifier(value);
}
result = this[model]();
result.color[channel] = value;
return result;
}
result = this[model]().color[channel];
if (modifier) {
result = modifier(result);
}
return result;
};
}
function maxfn(max) {
return function (v) {
return Math.max(0, Math.min(max, v));
};
}
function assertArray(value) {
return Array.isArray(value) ? value : [value];
}
function zeroArray(array, length) {
for (let i = 0; i < length; i++) {
if (typeof array[i] !== 'number') {
array[i] = 0;
}
}
return array;
}
module.exports = Color;

@ -1,47 +0,0 @@
{
"name": "color",
"version": "4.2.3",
"description": "Color conversion and manipulation with CSS string support",
"sideEffects": false,
"keywords": [
"color",
"colour",
"css"
],
"authors": [
"Josh Junon <josh@junon.me>",
"Heather Arthur <fayearthur@gmail.com>",
"Maxime Thirouin"
],
"license": "MIT",
"repository": "Qix-/color",
"xo": {
"rules": {
"no-cond-assign": 0,
"new-cap": 0,
"unicorn/prefer-module": 0,
"no-mixed-operators": 0,
"complexity": 0,
"unicorn/numeric-separators-style": 0
}
},
"files": [
"LICENSE",
"index.js"
],
"scripts": {
"pretest": "xo",
"test": "mocha"
},
"engines": {
"node": ">=12.5.0"
},
"dependencies": {
"color-convert": "^2.0.1",
"color-string": "^1.9.0"
},
"devDependencies": {
"mocha": "9.0.2",
"xo": "0.42.0"
}
}

@ -1,18 +0,0 @@
/**
Escape RegExp special characters.
You can also use this to escape a string that is inserted into the middle of a regex, for example, into a character class.
@example
```
import escapeStringRegexp = require('escape-string-regexp');
const escapedString = escapeStringRegexp('How much $ for a 🦄?');
//=> 'How much \\$ for a 🦄\\?'
new RegExp(escapedString);
```
*/
declare const escapeStringRegexp: (string: string) => string;
export = escapeStringRegexp;

@ -1,13 +0,0 @@
'use strict';
module.exports = string => {
if (typeof string !== 'string') {
throw new TypeError('Expected a string');
}
// Escape characters with special meaning either inside or outside character sets.
// Use a simple backslash escape when its always valid, and a \unnnn escape when the simpler form would be disallowed by Unicode patterns stricter grammar.
return string
.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
.replace(/-/g, '\\x2d');
};

@ -1,9 +0,0 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

@ -1,38 +0,0 @@
{
"name": "escape-string-regexp",
"version": "4.0.0",
"description": "Escape RegExp special characters",
"license": "MIT",
"repository": "sindresorhus/escape-string-regexp",
"funding": "https://github.com/sponsors/sindresorhus",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "https://sindresorhus.com"
},
"engines": {
"node": ">=10"
},
"scripts": {
"test": "xo && ava && tsd"
},
"files": [
"index.js",
"index.d.ts"
],
"keywords": [
"escape",
"regex",
"regexp",
"regular",
"expression",
"string",
"special",
"characters"
],
"devDependencies": {
"ava": "^1.4.1",
"tsd": "^0.11.0",
"xo": "^0.28.3"
}
}

@ -1,34 +0,0 @@
# escape-string-regexp [![Build Status](https://travis-ci.org/sindresorhus/escape-string-regexp.svg?branch=master)](https://travis-ci.org/sindresorhus/escape-string-regexp)
> Escape RegExp special characters
## Install
```
$ npm install escape-string-regexp
```
## Usage
```js
const escapeStringRegexp = require('escape-string-regexp');
const escapedString = escapeStringRegexp('How much $ for a 🦄?');
//=> 'How much \\$ for a 🦄\\?'
new RegExp(escapedString);
```
You can also use this to escape a string that is inserted into the middle of a regex, for example, into a character class.
---
<div align="center">
<b>
<a href="https://tidelift.com/subscription/pkg/npm-escape-string-regexp?utm_source=npm-escape-string-regexp&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
</b>
<br>
<sub>
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
</sub>
</div>

@ -1,8 +0,0 @@
{
"branch": "pull/18344",
"buildNumber": "106499",
"checksum": "7fe5a2e",
"commit": "da834083c",
"environment": "ci",
"reactVersion": "16.12.0-da834083c"
}

@ -1,15 +0,0 @@
/** @license React v16.13.1
* react-is.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';var b="function"===typeof Symbol&&Symbol.for,c=b?Symbol.for("react.element"):60103,d=b?Symbol.for("react.portal"):60106,e=b?Symbol.for("react.fragment"):60107,f=b?Symbol.for("react.strict_mode"):60108,g=b?Symbol.for("react.profiler"):60114,h=b?Symbol.for("react.provider"):60109,k=b?Symbol.for("react.context"):60110,l=b?Symbol.for("react.async_mode"):60111,m=b?Symbol.for("react.concurrent_mode"):60111,n=b?Symbol.for("react.forward_ref"):60112,p=b?Symbol.for("react.suspense"):60113,q=b?
Symbol.for("react.suspense_list"):60120,r=b?Symbol.for("react.memo"):60115,t=b?Symbol.for("react.lazy"):60116,v=b?Symbol.for("react.block"):60121,w=b?Symbol.for("react.fundamental"):60117,x=b?Symbol.for("react.responder"):60118,y=b?Symbol.for("react.scope"):60119;
function z(a){if("object"===typeof a&&null!==a){var u=a.$$typeof;switch(u){case c:switch(a=a.type,a){case l:case m:case e:case g:case f:case p:return a;default:switch(a=a&&a.$$typeof,a){case k:case n:case t:case r:case h:return a;default:return u}}case d:return u}}}function A(a){return z(a)===m}exports.AsyncMode=l;exports.ConcurrentMode=m;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=n;exports.Fragment=e;exports.Lazy=t;exports.Memo=r;exports.Portal=d;
exports.Profiler=g;exports.StrictMode=f;exports.Suspense=p;exports.isAsyncMode=function(a){return A(a)||z(a)===l};exports.isConcurrentMode=A;exports.isContextConsumer=function(a){return z(a)===k};exports.isContextProvider=function(a){return z(a)===h};exports.isElement=function(a){return"object"===typeof a&&null!==a&&a.$$typeof===c};exports.isForwardRef=function(a){return z(a)===n};exports.isFragment=function(a){return z(a)===e};exports.isLazy=function(a){return z(a)===t};
exports.isMemo=function(a){return z(a)===r};exports.isPortal=function(a){return z(a)===d};exports.isProfiler=function(a){return z(a)===g};exports.isStrictMode=function(a){return z(a)===f};exports.isSuspense=function(a){return z(a)===p};
exports.isValidElementType=function(a){return"string"===typeof a||"function"===typeof a||a===e||a===m||a===g||a===f||a===p||a===q||"object"===typeof a&&null!==a&&(a.$$typeof===t||a.$$typeof===r||a.$$typeof===h||a.$$typeof===k||a.$$typeof===n||a.$$typeof===w||a.$$typeof===x||a.$$typeof===y||a.$$typeof===v)};exports.typeOf=z;

@ -1,13 +0,0 @@
/** @license React v16.13.1
* react-is.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';(function(b,d){"object"===typeof exports&&"undefined"!==typeof module?d(exports):"function"===typeof define&&define.amd?define(["exports"],d):(b=b||self,d(b.ReactIs={}))})(this,function(b){function d(a){if("object"===typeof a&&null!==a){var b=a.$$typeof;switch(b){case r:switch(a=a.type,a){case t:case e:case f:case g:case h:case k:return a;default:switch(a=a&&a.$$typeof,a){case l:case m:case n:case p:case q:return a;default:return b}}case u:return b}}}function v(a){return d(a)===e}var c=
"function"===typeof Symbol&&Symbol.for,r=c?Symbol.for("react.element"):60103,u=c?Symbol.for("react.portal"):60106,f=c?Symbol.for("react.fragment"):60107,h=c?Symbol.for("react.strict_mode"):60108,g=c?Symbol.for("react.profiler"):60114,q=c?Symbol.for("react.provider"):60109,l=c?Symbol.for("react.context"):60110,t=c?Symbol.for("react.async_mode"):60111,e=c?Symbol.for("react.concurrent_mode"):60111,m=c?Symbol.for("react.forward_ref"):60112,k=c?Symbol.for("react.suspense"):60113,w=c?Symbol.for("react.suspense_list"):
60120,p=c?Symbol.for("react.memo"):60115,n=c?Symbol.for("react.lazy"):60116,x=c?Symbol.for("react.block"):60121,y=c?Symbol.for("react.fundamental"):60117,z=c?Symbol.for("react.responder"):60118,A=c?Symbol.for("react.scope"):60119;b.AsyncMode=t;b.ConcurrentMode=e;b.ContextConsumer=l;b.ContextProvider=q;b.Element=r;b.ForwardRef=m;b.Fragment=f;b.Lazy=n;b.Memo=p;b.Portal=u;b.Profiler=g;b.StrictMode=h;b.Suspense=k;b.isAsyncMode=function(a){return v(a)||d(a)===t};b.isConcurrentMode=v;b.isContextConsumer=
function(a){return d(a)===l};b.isContextProvider=function(a){return d(a)===q};b.isElement=function(a){return"object"===typeof a&&null!==a&&a.$$typeof===r};b.isForwardRef=function(a){return d(a)===m};b.isFragment=function(a){return d(a)===f};b.isLazy=function(a){return d(a)===n};b.isMemo=function(a){return d(a)===p};b.isPortal=function(a){return d(a)===u};b.isProfiler=function(a){return d(a)===g};b.isStrictMode=function(a){return d(a)===h};b.isSuspense=function(a){return d(a)===k};b.isValidElementType=
function(a){return"string"===typeof a||"function"===typeof a||a===f||a===e||a===g||a===h||a===k||a===w||"object"===typeof a&&null!==a&&(a.$$typeof===n||a.$$typeof===p||a.$$typeof===q||a.$$typeof===l||a.$$typeof===m||a.$$typeof===y||a.$$typeof===z||a.$$typeof===A||a.$$typeof===x)};b.typeOf=d});

@ -1,18 +0,0 @@
/**
Escape RegExp special characters.
You can also use this to escape a string that is inserted into the middle of a regex, for example, into a character class.
@example
```
import escapeStringRegexp = require('escape-string-regexp');
const escapedString = escapeStringRegexp('How much $ for a 🦄?');
//=> 'How much \\$ for a 🦄\\?'
new RegExp(escapedString);
```
*/
declare const escapeStringRegexp: (string: string) => string;
export = escapeStringRegexp;

@ -1,13 +0,0 @@
'use strict';
module.exports = string => {
if (typeof string !== 'string') {
throw new TypeError('Expected a string');
}
// Escape characters with special meaning either inside or outside character sets.
// Use a simple backslash escape when its always valid, and a \unnnn escape when the simpler form would be disallowed by Unicode patterns stricter grammar.
return string
.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')
.replace(/-/g, '\\x2d');
};

@ -1,9 +0,0 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

@ -1,38 +0,0 @@
{
"name": "escape-string-regexp",
"version": "4.0.0",
"description": "Escape RegExp special characters",
"license": "MIT",
"repository": "sindresorhus/escape-string-regexp",
"funding": "https://github.com/sponsors/sindresorhus",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "https://sindresorhus.com"
},
"engines": {
"node": ">=10"
},
"scripts": {
"test": "xo && ava && tsd"
},
"files": [
"index.js",
"index.d.ts"
],
"keywords": [
"escape",
"regex",
"regexp",
"regular",
"expression",
"string",
"special",
"characters"
],
"devDependencies": {
"ava": "^1.4.1",
"tsd": "^0.11.0",
"xo": "^0.28.3"
}
}

@ -1,34 +0,0 @@
# escape-string-regexp [![Build Status](https://travis-ci.org/sindresorhus/escape-string-regexp.svg?branch=master)](https://travis-ci.org/sindresorhus/escape-string-regexp)
> Escape RegExp special characters
## Install
```
$ npm install escape-string-regexp
```
## Usage
```js
const escapeStringRegexp = require('escape-string-regexp');
const escapedString = escapeStringRegexp('How much $ for a 🦄?');
//=> 'How much \\$ for a 🦄\\?'
new RegExp(escapedString);
```
You can also use this to escape a string that is inserted into the middle of a regex, for example, into a character class.
---
<div align="center">
<b>
<a href="https://tidelift.com/subscription/pkg/npm-escape-string-regexp?utm_source=npm-escape-string-regexp&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
</b>
<br>
<sub>
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
</sub>
</div>

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018 Mark Erikson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

@ -0,0 +1,98 @@
# Redux Toolkit
![GitHub Workflow Status](https://img.shields.io/github/workflow/status/reduxjs/redux-toolkit/CI?style=flat-square)
[![npm version](https://img.shields.io/npm/v/@reduxjs/toolkit.svg?style=flat-square)](https://www.npmjs.com/package/@reduxjs/toolkit)
[![npm downloads](https://img.shields.io/npm/dm/@reduxjs/toolkit.svg?style=flat-square&label=RTK+downloads)](https://www.npmjs.com/package/@reduxjs/toolkit)
**The official, opinionated, batteries-included toolset for efficient Redux development**
(Formerly known as "Redux Starter Kit")
## Installation
### Using Create React App
The recommended way to start new apps with React and Redux Toolkit is by using the [official Redux+JS template](https://github.com/reduxjs/cra-template-redux) for [Create React App](https://github.com/facebook/create-react-app), which takes advantage of React Redux's integration with React components.
```sh
npx create-react-app my-app --template redux
```
Or if you are a TypeScript user, use [cra-template-redux-typescript](https://github.com/reduxjs/cra-template-redux-typescript), which is based on that template
```sh
npx create-react-app my-app --template redux-typescript
```
### An Existing App
Redux Toolkit is available as a package on NPM for use with a module bundler or in a Node application:
```bash
# NPM
npm install @reduxjs/toolkit
# Yarn
yarn add @reduxjs/toolkit
```
It is also available as a precompiled UMD package that defines a `window.RTK` global variable.
The UMD package can be used as a [`<script>` tag](https://unpkg.com/@reduxjs/toolkit/dist/redux-toolkit.umd.js) directly.
## Purpose
The **Redux Toolkit** package is intended to be the standard way to write Redux logic. It was originally created to help address three common concerns about Redux:
- "Configuring a Redux store is too complicated"
- "I have to add a lot of packages to get Redux to do anything useful"
- "Redux requires too much boilerplate code"
We can't solve every use case, but in the spirit of [`create-react-app`](https://github.com/facebook/create-react-app), we can try to provide some tools that abstract over the setup process and handle the most common use cases, as well as include some useful utilities that will let the user simplify their application code.
Because of that, this package is deliberately limited in scope. It does _not_ address concepts like "reusable encapsulated Redux modules", folder or file structures, managing entity relationships in the store, and so on.
Redux Toolkit also includes a powerful data fetching and caching capability that we've dubbed "RTK Query". It's included in the package as a separate set of entry points. It's optional, but can eliminate the need to hand-write data fetching logic yourself.
## What's Included
Redux Toolkit includes these APIs:
- `configureStore()`: wraps `createStore` to provide simplified configuration options and good defaults. It can automatically combine your slice reducers, add whatever Redux middleware you supply, includes `redux-thunk` by default, and enables use of the Redux DevTools Extension.
- `createReducer()`: lets you supply a lookup table of action types to case reducer functions, rather than writing switch statements. In addition, it automatically uses the [`immer` library](https://github.com/mweststrate/immer) to let you write simpler immutable updates with normal mutative code, like `state.todos[3].completed = true`.
- `createAction()`: generates an action creator function for the given action type string. The function itself has `toString()` defined, so that it can be used in place of the type constant.
- `createSlice()`: combines `createReducer()` + `createAction()`. Accepts an object of reducer functions, a slice name, and an initial state value, and automatically generates a slice reducer with corresponding action creators and action types.
- `createListenerMiddleware()`: lets you define "listener" entries that contain an "effect" callback with additional logic, and a way to specify when that callback should run based on dispatched actions or state changes. A lightweight alternative to Redux async middleware like sagas and observables.
- `createAsyncThunk()`: accepts an action type string and a function that returns a promise, and generates a thunk that dispatches `pending/resolved/rejected` action types based on that promise
- `createEntityAdapter()`: generates a set of reusable reducers and selectors to manage normalized data in the store
- The `createSelector()` utility from the [Reselect](https://github.com/reduxjs/reselect) library, re-exported for ease of use.
## RTK Query
**RTK Query** is provided as an optional addon within the `@reduxjs/toolkit` package. It is purpose-built to solve the use case of data fetching and caching, supplying a compact, but powerful toolset to define an API interface layer for your app. It is intended to simplify common cases for loading data in a web application, eliminating the need to hand-write data fetching & caching logic yourself.
RTK Query is built on top of the Redux Toolkit core for its implementation, using [Redux](https://redux.js.org/) internally for its architecture. Although knowledge of Redux and RTK are not required to use RTK Query, you should explore all of the additional global store management capabilities they provide, as well as installing the [Redux DevTools browser extension](https://github.com/reduxjs/redux-devtools), which works flawlessly with RTK Query to traverse and replay a timeline of your request & cache behavior.
RTK Query is included within the installation of the core Redux Toolkit package. It is available via either of the two entry points below:
```ts no-transpile
import { createApi } from '@reduxjs/toolkit/query'
/* React-specific entry point that automatically generates
hooks corresponding to the defined endpoints */
import { createApi } from '@reduxjs/toolkit/query/react'
```
### What's included
RTK Query includes these APIs:
- `createApi()`: The core of RTK Query's functionality. It allows you to define a set of endpoints describe how to retrieve data from a series of endpoints, including configuration of how to fetch and transform that data. In most cases, you should use this once per app, with "one API slice per base URL" as a rule of thumb.
- `fetchBaseQuery()`: A small wrapper around fetch that aims to simplify requests. Intended as the recommended baseQuery to be used in createApi for the majority of users.
- `<ApiProvider />`: Can be used as a Provider if you do not already have a Redux store.
- `setupListeners()`: A utility used to enable refetchOnMount and refetchOnReconnect behaviors.
See the [**RTK Query Overview**](https://redux-toolkit.js.org/rtk-query/overview) page for more details on what RTK Query is, what problems it solves, and how to use it.
## Documentation
The Redux Toolkit docs are available at **https://redux-toolkit.js.org**.

@ -0,0 +1,40 @@
import type { StoreEnhancer } from 'redux';
export declare const SHOULD_AUTOBATCH = "RTK_autoBatch";
export declare const prepareAutoBatched: <T>() => (payload: T) => {
payload: T;
meta: unknown;
};
export declare type AutoBatchOptions = {
type: 'tick';
} | {
type: 'timer';
timeout: number;
} | {
type: 'raf';
} | {
type: 'callback';
queueNotification: (notify: () => void) => void;
};
/**
* A Redux store enhancer that watches for "low-priority" actions, and delays
* notifying subscribers until either the queued callback executes or the
* next "standard-priority" action is dispatched.
*
* This allows dispatching multiple "low-priority" actions in a row with only
* a single subscriber notification to the UI after the sequence of actions
* is finished, thus improving UI re-render performance.
*
* Watches for actions with the `action.meta[SHOULD_AUTOBATCH]` attribute.
* This can be added to `action.meta` manually, or by using the
* `prepareAutoBatched` helper.
*
* By default, it will queue a notification for the end of the event loop tick.
* However, you can pass several other options to configure the behavior:
* - `{type: 'tick'}: queues using `queueMicrotask` (default)
* - `{type: 'timer, timeout: number}`: queues using `setTimeout`
* - `{type: 'raf'}`: queues using `requestAnimationFrame`
* - `{type: 'callback', queueNotification: (notify: () => void) => void}: lets you provide your own callback
*
*
*/
export declare const autoBatchEnhancer: (options?: AutoBatchOptions) => StoreEnhancer;

@ -0,0 +1,81 @@
import type { Reducer, ReducersMapObject, Middleware, Action, AnyAction, StoreEnhancer, Store, Dispatch, PreloadedState, CombinedState } from 'redux';
import type { DevToolsEnhancerOptions as DevToolsOptions } from './devtoolsExtension';
import type { ThunkMiddlewareFor, CurriedGetDefaultMiddleware } from './getDefaultMiddleware';
import type { NoInfer, ExtractDispatchExtensions, ExtractStoreExtensions } from './tsHelpers';
/**
* Callback function type, to be used in `ConfigureStoreOptions.enhancers`
*
* @public
*/
export declare type ConfigureEnhancersCallback<E extends Enhancers = Enhancers> = (defaultEnhancers: readonly StoreEnhancer[]) => [...E];
/**
* Options for `configureStore()`.
*
* @public
*/
export interface ConfigureStoreOptions<S = any, A extends Action = AnyAction, M extends Middlewares<S> = Middlewares<S>, E extends Enhancers = Enhancers> {
/**
* A single reducer function that will be used as the root reducer, or an
* object of slice reducers that will be passed to `combineReducers()`.
*/
reducer: Reducer<S, A> | ReducersMapObject<S, A>;
/**
* An array of Redux middleware to install. If not supplied, defaults to
* the set of middleware returned by `getDefaultMiddleware()`.
*
* @example `middleware: (gDM) => gDM().concat(logger, apiMiddleware, yourCustomMiddleware)`
* @see https://redux-toolkit.js.org/api/getDefaultMiddleware#intended-usage
*/
middleware?: ((getDefaultMiddleware: CurriedGetDefaultMiddleware<S>) => M) | M;
/**
* Whether to enable Redux DevTools integration. Defaults to `true`.
*
* Additional configuration can be done by passing Redux DevTools options
*/
devTools?: boolean | DevToolsOptions;
/**
* The initial state, same as Redux's createStore.
* You may optionally specify it to hydrate the state
* from the server in universal apps, or to restore a previously serialized
* user session. If you use `combineReducers()` to produce the root reducer
* function (either directly or indirectly by passing an object as `reducer`),
* this must be an object with the same shape as the reducer map keys.
*/
preloadedState?: PreloadedState<CombinedState<NoInfer<S>>>;
/**
* The store enhancers to apply. See Redux's `createStore()`.
* All enhancers will be included before the DevTools Extension enhancer.
* If you need to customize the order of enhancers, supply a callback
* function that will receive the original array (ie, `[applyMiddleware]`),
* and should return a new array (such as `[applyMiddleware, offline]`).
* If you only need to add middleware, you can use the `middleware` parameter instead.
*/
enhancers?: E | ConfigureEnhancersCallback<E>;
}
declare type Middlewares<S> = ReadonlyArray<Middleware<{}, S>>;
declare type Enhancers = ReadonlyArray<StoreEnhancer>;
export interface ToolkitStore<S = any, A extends Action = AnyAction, M extends Middlewares<S> = Middlewares<S>> extends Store<S, A> {
/**
* The `dispatch` method of your store, enhanced by all its middlewares.
*
* @inheritdoc
*/
dispatch: ExtractDispatchExtensions<M> & Dispatch<A>;
}
/**
* A Redux store returned by `configureStore()`. Supports dispatching
* side-effectful _thunks_ in addition to plain actions.
*
* @public
*/
export declare type EnhancedStore<S = any, A extends Action = AnyAction, M extends Middlewares<S> = Middlewares<S>, E extends Enhancers = Enhancers> = ToolkitStore<S, A, M> & ExtractStoreExtensions<E>;
/**
* A friendly abstraction over the standard Redux `createStore()` function.
*
* @param options The store configuration.
* @returns A configured Redux store.
*
* @public
*/
export declare function configureStore<S = any, A extends Action = AnyAction, M extends Middlewares<S> = [ThunkMiddlewareFor<S>], E extends Enhancers = [StoreEnhancer]>(options: ConfigureStoreOptions<S, A, M, E>): EnhancedStore<S, A, M, E>;
export {};

@ -0,0 +1,196 @@
import type { Action } from 'redux';
import type { IsUnknownOrNonInferrable, IfMaybeUndefined, IfVoid, IsAny } from './tsHelpers';
/**
* An action with a string type and an associated payload. This is the
* type of action returned by `createAction()` action creators.
*
* @template P The type of the action's payload.
* @template T the type used for the action type.
* @template M The type of the action's meta (optional)
* @template E The type of the action's error (optional)
*
* @public
*/
export declare type PayloadAction<P = void, T extends string = string, M = never, E = never> = {
payload: P;
type: T;
} & ([M] extends [never] ? {} : {
meta: M;
}) & ([E] extends [never] ? {} : {
error: E;
});
/**
* A "prepare" method to be used as the second parameter of `createAction`.
* Takes any number of arguments and returns a Flux Standard Action without
* type (will be added later) that *must* contain a payload (might be undefined).
*
* @public
*/
export declare type PrepareAction<P> = ((...args: any[]) => {
payload: P;
}) | ((...args: any[]) => {
payload: P;
meta: any;
}) | ((...args: any[]) => {
payload: P;
error: any;
}) | ((...args: any[]) => {
payload: P;
meta: any;
error: any;
});
/**
* Internal version of `ActionCreatorWithPreparedPayload`. Not to be used externally.
*
* @internal
*/
export declare type _ActionCreatorWithPreparedPayload<PA extends PrepareAction<any> | void, T extends string = string> = PA extends PrepareAction<infer P> ? ActionCreatorWithPreparedPayload<Parameters<PA>, P, T, ReturnType<PA> extends {
error: infer E;
} ? E : never, ReturnType<PA> extends {
meta: infer M;
} ? M : never> : void;
/**
* Basic type for all action creators.
*
* @inheritdoc {redux#ActionCreator}
*/
export interface BaseActionCreator<P, T extends string, M = never, E = never> {
type: T;
match: (action: Action<unknown>) => action is PayloadAction<P, T, M, E>;
}
/**
* An action creator that takes multiple arguments that are passed
* to a `PrepareAction` method to create the final Action.
* @typeParam Args arguments for the action creator function
* @typeParam P `payload` type
* @typeParam T `type` name
* @typeParam E optional `error` type
* @typeParam M optional `meta` type
*
* @inheritdoc {redux#ActionCreator}
*
* @public
*/
export interface ActionCreatorWithPreparedPayload<Args extends unknown[], P, T extends string = string, E = never, M = never> extends BaseActionCreator<P, T, M, E> {
/**
* Calling this {@link redux#ActionCreator} with `Args` will return
* an Action with a payload of type `P` and (depending on the `PrepareAction`
* method used) a `meta`- and `error` property of types `M` and `E` respectively.
*/
(...args: Args): PayloadAction<P, T, M, E>;
}
/**
* An action creator of type `T` that takes an optional payload of type `P`.
*
* @inheritdoc {redux#ActionCreator}
*
* @public
*/
export interface ActionCreatorWithOptionalPayload<P, T extends string = string> extends BaseActionCreator<P, T> {
/**
* Calling this {@link redux#ActionCreator} with an argument will
* return a {@link PayloadAction} of type `T` with a payload of `P`.
* Calling it without an argument will return a PayloadAction with a payload of `undefined`.
*/
(payload?: P): PayloadAction<P, T>;
}
/**
* An action creator of type `T` that takes no payload.
*
* @inheritdoc {redux#ActionCreator}
*
* @public
*/
export interface ActionCreatorWithoutPayload<T extends string = string> extends BaseActionCreator<undefined, T> {
/**
* Calling this {@link redux#ActionCreator} will
* return a {@link PayloadAction} of type `T` with a payload of `undefined`
*/
(noArgument: void): PayloadAction<undefined, T>;
}
/**
* An action creator of type `T` that requires a payload of type P.
*
* @inheritdoc {redux#ActionCreator}
*
* @public
*/
export interface ActionCreatorWithPayload<P, T extends string = string> extends BaseActionCreator<P, T> {
/**
* Calling this {@link redux#ActionCreator} with an argument will
* return a {@link PayloadAction} of type `T` with a payload of `P`
*/
(payload: P): PayloadAction<P, T>;
}
/**
* An action creator of type `T` whose `payload` type could not be inferred. Accepts everything as `payload`.
*
* @inheritdoc {redux#ActionCreator}
*
* @public
*/
export interface ActionCreatorWithNonInferrablePayload<T extends string = string> extends BaseActionCreator<unknown, T> {
/**
* Calling this {@link redux#ActionCreator} with an argument will
* return a {@link PayloadAction} of type `T` with a payload
* of exactly the type of the argument.
*/
<PT extends unknown>(payload: PT): PayloadAction<PT, T>;
}
/**
* An action creator that produces actions with a `payload` attribute.
*
* @typeParam P the `payload` type
* @typeParam T the `type` of the resulting action
* @typeParam PA if the resulting action is preprocessed by a `prepare` method, the signature of said method.
*
* @public
*/
export declare type PayloadActionCreator<P = void, T extends string = string, PA extends PrepareAction<P> | void = void> = IfPrepareActionMethodProvided<PA, _ActionCreatorWithPreparedPayload<PA, T>, IsAny<P, ActionCreatorWithPayload<any, T>, IsUnknownOrNonInferrable<P, ActionCreatorWithNonInferrablePayload<T>, IfVoid<P, ActionCreatorWithoutPayload<T>, IfMaybeUndefined<P, ActionCreatorWithOptionalPayload<P, T>, ActionCreatorWithPayload<P, T>>>>>>;
/**
* A utility function to create an action creator for the given action type
* string. The action creator accepts a single argument, which will be included
* in the action object as a field called payload. The action creator function
* will also have its toString() overriden so that it returns the action type,
* allowing it to be used in reducer logic that is looking for that action type.
*
* @param type The action type to use for created actions.
* @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.
* If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.
*
* @public
*/
export declare function createAction<P = void, T extends string = string>(type: T): PayloadActionCreator<P, T>;
/**
* A utility function to create an action creator for the given action type
* string. The action creator accepts a single argument, which will be included
* in the action object as a field called payload. The action creator function
* will also have its toString() overriden so that it returns the action type,
* allowing it to be used in reducer logic that is looking for that action type.
*
* @param type The action type to use for created actions.
* @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.
* If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.
*
* @public
*/
export declare function createAction<PA extends PrepareAction<any>, T extends string = string>(type: T, prepareAction: PA): PayloadActionCreator<ReturnType<PA>['payload'], T, PA>;
export declare function isFSA(action: unknown): action is {
type: string;
payload?: unknown;
error?: unknown;
meta?: unknown;
};
/**
* Returns the action type of the actions created by the passed
* `createAction()`-generated action creator (arbitrary action creators
* are not supported).
*
* @param action The action creator whose action type to get.
* @returns The action type used by the action creator.
*
* @public
*/
export declare function getType<T extends string>(actionCreator: PayloadActionCreator<any, T>): T;
declare type IfPrepareActionMethodProvided<PA extends PrepareAction<any> | void, True, False> = PA extends (...args: any[]) => any ? True : False;
export {};

@ -0,0 +1,243 @@
import type { Dispatch, AnyAction } from 'redux';
import type { ActionCreatorWithPreparedPayload } from './createAction';
import type { ThunkDispatch } from 'redux-thunk';
import type { FallbackIfUnknown, Id, IsAny, IsUnknown } from './tsHelpers';
export declare type BaseThunkAPI<S, E, D extends Dispatch = Dispatch, RejectedValue = undefined, RejectedMeta = unknown, FulfilledMeta = unknown> = {
dispatch: D;
getState: () => S;
extra: E;
requestId: string;
signal: AbortSignal;
abort: (reason?: string) => void;
rejectWithValue: IsUnknown<RejectedMeta, (value: RejectedValue) => RejectWithValue<RejectedValue, RejectedMeta>, (value: RejectedValue, meta: RejectedMeta) => RejectWithValue<RejectedValue, RejectedMeta>>;
fulfillWithValue: IsUnknown<FulfilledMeta, <FulfilledValue>(value: FulfilledValue) => FulfilledValue, <FulfilledValue>(value: FulfilledValue, meta: FulfilledMeta) => FulfillWithMeta<FulfilledValue, FulfilledMeta>>;
};
/**
* @public
*/
export interface SerializedError {
name?: string;
message?: string;
stack?: string;
code?: string;
}
declare class RejectWithValue<Payload, RejectedMeta> {
readonly payload: Payload;
readonly meta: RejectedMeta;
private readonly _type;
constructor(payload: Payload, meta: RejectedMeta);
}
declare class FulfillWithMeta<Payload, FulfilledMeta> {
readonly payload: Payload;
readonly meta: FulfilledMeta;
private readonly _type;
constructor(payload: Payload, meta: FulfilledMeta);
}
/**
* Serializes an error into a plain object.
* Reworked from https://github.com/sindresorhus/serialize-error
*
* @public
*/
export declare const miniSerializeError: (value: any) => SerializedError;
declare type AsyncThunkConfig = {
state?: unknown;
dispatch?: Dispatch;
extra?: unknown;
rejectValue?: unknown;
serializedErrorType?: unknown;
pendingMeta?: unknown;
fulfilledMeta?: unknown;
rejectedMeta?: unknown;
};
declare type GetState<ThunkApiConfig> = ThunkApiConfig extends {
state: infer State;
} ? State : unknown;
declare type GetExtra<ThunkApiConfig> = ThunkApiConfig extends {
extra: infer Extra;
} ? Extra : unknown;
declare type GetDispatch<ThunkApiConfig> = ThunkApiConfig extends {
dispatch: infer Dispatch;
} ? FallbackIfUnknown<Dispatch, ThunkDispatch<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, AnyAction>> : ThunkDispatch<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, AnyAction>;
declare type GetThunkAPI<ThunkApiConfig> = BaseThunkAPI<GetState<ThunkApiConfig>, GetExtra<ThunkApiConfig>, GetDispatch<ThunkApiConfig>, GetRejectValue<ThunkApiConfig>, GetRejectedMeta<ThunkApiConfig>, GetFulfilledMeta<ThunkApiConfig>>;
declare type GetRejectValue<ThunkApiConfig> = ThunkApiConfig extends {
rejectValue: infer RejectValue;
} ? RejectValue : unknown;
declare type GetPendingMeta<ThunkApiConfig> = ThunkApiConfig extends {
pendingMeta: infer PendingMeta;
} ? PendingMeta : unknown;
declare type GetFulfilledMeta<ThunkApiConfig> = ThunkApiConfig extends {
fulfilledMeta: infer FulfilledMeta;
} ? FulfilledMeta : unknown;
declare type GetRejectedMeta<ThunkApiConfig> = ThunkApiConfig extends {
rejectedMeta: infer RejectedMeta;
} ? RejectedMeta : unknown;
declare type GetSerializedErrorType<ThunkApiConfig> = ThunkApiConfig extends {
serializedErrorType: infer GetSerializedErrorType;
} ? GetSerializedErrorType : SerializedError;
declare type MaybePromise<T> = T | Promise<T> | (T extends any ? Promise<T> : never);
/**
* A type describing the return value of the `payloadCreator` argument to `createAsyncThunk`.
* Might be useful for wrapping `createAsyncThunk` in custom abstractions.
*
* @public
*/
export declare type AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig extends AsyncThunkConfig> = MaybePromise<IsUnknown<GetFulfilledMeta<ThunkApiConfig>, Returned, FulfillWithMeta<Returned, GetFulfilledMeta<ThunkApiConfig>>> | RejectWithValue<GetRejectValue<ThunkApiConfig>, GetRejectedMeta<ThunkApiConfig>>>;
/**
* A type describing the `payloadCreator` argument to `createAsyncThunk`.
* Might be useful for wrapping `createAsyncThunk` in custom abstractions.
*
* @public
*/
export declare type AsyncThunkPayloadCreator<Returned, ThunkArg = void, ThunkApiConfig extends AsyncThunkConfig = {}> = (arg: ThunkArg, thunkAPI: GetThunkAPI<ThunkApiConfig>) => AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig>;
/**
* A ThunkAction created by `createAsyncThunk`.
* Dispatching it returns a Promise for either a
* fulfilled or rejected action.
* Also, the returned value contains an `abort()` method
* that allows the asyncAction to be cancelled from the outside.
*
* @public
*/
export declare type AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = (dispatch: GetDispatch<ThunkApiConfig>, getState: () => GetState<ThunkApiConfig>, extra: GetExtra<ThunkApiConfig>) => Promise<ReturnType<AsyncThunkFulfilledActionCreator<Returned, ThunkArg>> | ReturnType<AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>>> & {
abort: (reason?: string) => void;
requestId: string;
arg: ThunkArg;
unwrap: () => Promise<Returned>;
};
declare type AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = IsAny<ThunkArg, (arg: ThunkArg) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>, unknown extends ThunkArg ? (arg: ThunkArg) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> : [ThunkArg] extends [void] | [undefined] ? () => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> : [void] extends [ThunkArg] ? (arg?: ThunkArg) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> : [undefined] extends [ThunkArg] ? WithStrictNullChecks<(arg?: ThunkArg) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>, (arg: ThunkArg) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>> : (arg: ThunkArg) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>>;
/**
* Options object for `createAsyncThunk`.
*
* @public
*/
export declare type AsyncThunkOptions<ThunkArg = void, ThunkApiConfig extends AsyncThunkConfig = {}> = {
/**
* A method to control whether the asyncThunk should be executed. Has access to the
* `arg`, `api.getState()` and `api.extra` arguments.
*
* @returns `false` if it should be skipped
*/
condition?(arg: ThunkArg, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): MaybePromise<boolean | undefined>;
/**
* If `condition` returns `false`, the asyncThunk will be skipped.
* This option allows you to control whether a `rejected` action with `meta.condition == false`
* will be dispatched or not.
*
* @default `false`
*/
dispatchConditionRejection?: boolean;
serializeError?: (x: unknown) => GetSerializedErrorType<ThunkApiConfig>;
/**
* A function to use when generating the `requestId` for the request sequence.
*
* @default `nanoid`
*/
idGenerator?: (arg: ThunkArg) => string;
} & IsUnknown<GetPendingMeta<ThunkApiConfig>, {
/**
* A method to generate additional properties to be added to `meta` of the pending action.
*
* Using this optional overload will not modify the types correctly, this overload is only in place to support JavaScript users.
* Please use the `ThunkApiConfig` parameter `pendingMeta` to get access to a correctly typed overload
*/
getPendingMeta?(base: {
arg: ThunkArg;
requestId: string;
}, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): GetPendingMeta<ThunkApiConfig>;
}, {
/**
* A method to generate additional properties to be added to `meta` of the pending action.
*/
getPendingMeta(base: {
arg: ThunkArg;
requestId: string;
}, api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>): GetPendingMeta<ThunkApiConfig>;
}>;
export declare type AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[
string,
ThunkArg,
GetPendingMeta<ThunkApiConfig>?
], undefined, string, never, {
arg: ThunkArg;
requestId: string;
requestStatus: 'pending';
} & GetPendingMeta<ThunkApiConfig>>;
export declare type AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[
Error | null,
string,
ThunkArg,
GetRejectValue<ThunkApiConfig>?,
GetRejectedMeta<ThunkApiConfig>?
], GetRejectValue<ThunkApiConfig> | undefined, string, GetSerializedErrorType<ThunkApiConfig>, {
arg: ThunkArg;
requestId: string;
requestStatus: 'rejected';
aborted: boolean;
condition: boolean;
} & (({
rejectedWithValue: false;
} & {
[K in keyof GetRejectedMeta<ThunkApiConfig>]?: undefined;
}) | ({
rejectedWithValue: true;
} & GetRejectedMeta<ThunkApiConfig>))>;
export declare type AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig = {}> = ActionCreatorWithPreparedPayload<[
Returned,
string,
ThunkArg,
GetFulfilledMeta<ThunkApiConfig>?
], Returned, string, never, {
arg: ThunkArg;
requestId: string;
requestStatus: 'fulfilled';
} & GetFulfilledMeta<ThunkApiConfig>>;
/**
* A type describing the return value of `createAsyncThunk`.
* Might be useful for wrapping `createAsyncThunk` in custom abstractions.
*
* @public
*/
export declare type AsyncThunk<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig> = AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig> & {
pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig>;
rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>;
fulfilled: AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig>;
typePrefix: string;
};
declare type OverrideThunkApiConfigs<OldConfig, NewConfig> = Id<NewConfig & Omit<OldConfig, keyof NewConfig>>;
declare type CreateAsyncThunk<CurriedThunkApiConfig extends AsyncThunkConfig> = {
/**
*
* @param typePrefix
* @param payloadCreator
* @param options
*
* @public
*/
<Returned, ThunkArg = void>(typePrefix: string, payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, CurriedThunkApiConfig>, options?: AsyncThunkOptions<ThunkArg, CurriedThunkApiConfig>): AsyncThunk<Returned, ThunkArg, CurriedThunkApiConfig>;
/**
*
* @param typePrefix
* @param payloadCreator
* @param options
*
* @public
*/
<Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig>(typePrefix: string, payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>, options?: AsyncThunkOptions<ThunkArg, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>): AsyncThunk<Returned, ThunkArg, OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;
withTypes<ThunkApiConfig extends AsyncThunkConfig>(): CreateAsyncThunk<OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>>;
};
export declare const createAsyncThunk: CreateAsyncThunk<AsyncThunkConfig>;
interface UnwrappableAction {
payload: any;
meta?: any;
error?: any;
}
declare type UnwrappedActionPayload<T extends UnwrappableAction> = Exclude<T, {
error: any;
}>['payload'];
/**
* @public
*/
export declare function unwrapResult<R extends UnwrappableAction>(action: R): UnwrappedActionPayload<R>;
declare type WithStrictNullChecks<True, False> = undefined extends boolean ? False : True;
export {};

@ -0,0 +1,9 @@
import { createSelector } from 'reselect';
/**
* "Draft-Safe" version of `reselect`'s `createSelector`:
* If an `immer`-drafted object is passed into the resulting selector's first argument,
* the selector will act on the current draft value, instead of returning a cached value
* that might be possibly outdated if the draft has been modified since.
* @public
*/
export declare const createDraftSafeSelector: typeof createSelector;

@ -0,0 +1,176 @@
import type { Draft } from 'immer';
import type { AnyAction, Action, Reducer } from 'redux';
import type { ActionReducerMapBuilder } from './mapBuilders';
import type { NoInfer } from './tsHelpers';
/**
* Defines a mapping from action types to corresponding action object shapes.
*
* @deprecated This should not be used manually - it is only used for internal
* inference purposes and should not have any further value.
* It might be removed in the future.
* @public
*/
export declare type Actions<T extends keyof any = string> = Record<T, Action>;
/**
* @deprecated use `TypeGuard` instead
*/
export interface ActionMatcher<A extends AnyAction> {
(action: AnyAction): action is A;
}
export declare type ActionMatcherDescription<S, A extends AnyAction> = {
matcher: ActionMatcher<A>;
reducer: CaseReducer<S, NoInfer<A>>;
};
export declare type ReadonlyActionMatcherDescriptionCollection<S> = ReadonlyArray<ActionMatcherDescription<S, any>>;
export declare type ActionMatcherDescriptionCollection<S> = Array<ActionMatcherDescription<S, any>>;
/**
* A *case reducer* is a reducer function for a specific action type. Case
* reducers can be composed to full reducers using `createReducer()`.
*
* Unlike a normal Redux reducer, a case reducer is never called with an
* `undefined` state to determine the initial state. Instead, the initial
* state is explicitly specified as an argument to `createReducer()`.
*
* In addition, a case reducer can choose to mutate the passed-in `state`
* value directly instead of returning a new state. This does not actually
* cause the store state to be mutated directly; instead, thanks to
* [immer](https://github.com/mweststrate/immer), the mutations are
* translated to copy operations that result in a new state.
*
* @public
*/
export declare type CaseReducer<S = any, A extends Action = AnyAction> = (state: Draft<S>, action: A) => NoInfer<S> | void | Draft<NoInfer<S>>;
/**
* A mapping from action types to case reducers for `createReducer()`.
*
* @deprecated This should not be used manually - it is only used
* for internal inference purposes and using it manually
* would lead to type erasure.
* It might be removed in the future.
* @public
*/
export declare type CaseReducers<S, AS extends Actions> = {
[T in keyof AS]: AS[T] extends Action ? CaseReducer<S, AS[T]> : void;
};
export declare type NotFunction<T> = T extends Function ? never : T;
export declare type ReducerWithInitialState<S extends NotFunction<any>> = Reducer<S> & {
getInitialState: () => S;
};
/**
* A utility function that allows defining a reducer as a mapping from action
* type to *case reducer* functions that handle these action types. The
* reducer's initial state is passed as the first argument.
*
* @remarks
* The body of every case reducer is implicitly wrapped with a call to
* `produce()` from the [immer](https://github.com/mweststrate/immer) library.
* This means that rather than returning a new state object, you can also
* mutate the passed-in state object directly; these mutations will then be
* automatically and efficiently translated into copies, giving you both
* convenience and immutability.
*
* @overloadSummary
* This overload accepts a callback function that receives a `builder` object as its argument.
* That builder provides `addCase`, `addMatcher` and `addDefaultCase` functions that may be
* called to define what actions this reducer will handle.
*
* @param initialState - `State | (() => State)`: The initial state that should be used when the reducer is called the first time. This may also be a "lazy initializer" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.
* @param builderCallback - `(builder: Builder) => void` A callback that receives a *builder* object to define
* case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.
* @example
```ts
import {
createAction,
createReducer,
AnyAction,
PayloadAction,
} from "@reduxjs/toolkit";
const increment = createAction<number>("increment");
const decrement = createAction<number>("decrement");
function isActionWithNumberPayload(
action: AnyAction
): action is PayloadAction<number> {
return typeof action.payload === "number";
}
const reducer = createReducer(
{
counter: 0,
sumOfNumberPayloads: 0,
unhandledActions: 0,
},
(builder) => {
builder
.addCase(increment, (state, action) => {
// action is inferred correctly here
state.counter += action.payload;
})
// You can chain calls, or have separate `builder.addCase()` lines each time
.addCase(decrement, (state, action) => {
state.counter -= action.payload;
})
// You can apply a "matcher function" to incoming actions
.addMatcher(isActionWithNumberPayload, (state, action) => {})
// and provide a default case if no other handlers matched
.addDefaultCase((state, action) => {});
}
);
```
* @public
*/
export declare function createReducer<S extends NotFunction<any>>(initialState: S | (() => S), builderCallback: (builder: ActionReducerMapBuilder<S>) => void): ReducerWithInitialState<S>;
/**
* A utility function that allows defining a reducer as a mapping from action
* type to *case reducer* functions that handle these action types. The
* reducer's initial state is passed as the first argument.
*
* The body of every case reducer is implicitly wrapped with a call to
* `produce()` from the [immer](https://github.com/mweststrate/immer) library.
* This means that rather than returning a new state object, you can also
* mutate the passed-in state object directly; these mutations will then be
* automatically and efficiently translated into copies, giving you both
* convenience and immutability.
*
* @overloadSummary
* This overload accepts an object where the keys are string action types, and the values
* are case reducer functions to handle those action types.
*
* @param initialState - `State | (() => State)`: The initial state that should be used when the reducer is called the first time. This may also be a "lazy initializer" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.
* @param actionsMap - An object mapping from action types to _case reducers_, each of which handles one specific action type.
* @param actionMatchers - An array of matcher definitions in the form `{matcher, reducer}`.
* All matching reducers will be executed in order, independently if a case reducer matched or not.
* @param defaultCaseReducer - A "default case" reducer that is executed if no case reducer and no matcher
* reducer was executed for this action.
*
* @example
```js
const counterReducer = createReducer(0, {
increment: (state, action) => state + action.payload,
decrement: (state, action) => state - action.payload
})
// Alternately, use a "lazy initializer" to provide the initial state
// (works with either form of createReducer)
const initialState = () => 0
const counterReducer = createReducer(initialState, {
increment: (state, action) => state + action.payload,
decrement: (state, action) => state - action.payload
})
```
* Action creators that were generated using [`createAction`](./createAction) may be used directly as the keys here, using computed property syntax:
```js
const increment = createAction('increment')
const decrement = createAction('decrement')
const counterReducer = createReducer(0, {
[increment]: (state, action) => state + action.payload,
[decrement.type]: (state, action) => state - action.payload
})
```
* @public
*/
export declare function createReducer<S extends NotFunction<any>, CR extends CaseReducers<S, any> = CaseReducers<S, any>>(initialState: S | (() => S), actionsMap: CR, actionMatchers?: ActionMatcherDescriptionCollection<S>, defaultCaseReducer?: CaseReducer<S>): ReducerWithInitialState<S>;

@ -0,0 +1,196 @@
import type { Reducer } from 'redux';
import type { ActionCreatorWithoutPayload, PayloadAction, PayloadActionCreator, PrepareAction, _ActionCreatorWithPreparedPayload } from './createAction';
import type { CaseReducer, CaseReducers } from './createReducer';
import type { ActionReducerMapBuilder } from './mapBuilders';
import type { NoInfer } from './tsHelpers';
/**
* An action creator attached to a slice.
*
* @deprecated please use PayloadActionCreator directly
*
* @public
*/
export declare type SliceActionCreator<P> = PayloadActionCreator<P>;
/**
* The return value of `createSlice`
*
* @public
*/
export interface Slice<State = any, CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string> {
/**
* The slice name.
*/
name: Name;
/**
* The slice's reducer.
*/
reducer: Reducer<State>;
/**
* Action creators for the types of actions that are handled by the slice
* reducer.
*/
actions: CaseReducerActions<CaseReducers, Name>;
/**
* The individual case reducer functions that were passed in the `reducers` parameter.
* This enables reuse and testing if they were defined inline when calling `createSlice`.
*/
caseReducers: SliceDefinedCaseReducers<CaseReducers>;
/**
* Provides access to the initial state value given to the slice.
* If a lazy state initializer was provided, it will be called and a fresh value returned.
*/
getInitialState: () => State;
}
/**
* Options for `createSlice()`.
*
* @public
*/
export interface CreateSliceOptions<State = any, CR extends SliceCaseReducers<State> = SliceCaseReducers<State>, Name extends string = string> {
/**
* The slice's name. Used to namespace the generated action types.
*/
name: Name;
/**
* The initial state that should be used when the reducer is called the first time. This may also be a "lazy initializer" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.
*/
initialState: State | (() => State);
/**
* A mapping from action types to action-type-specific *case reducer*
* functions. For every action type, a matching action creator will be
* generated using `createAction()`.
*/
reducers: ValidateSliceCaseReducers<State, CR>;
/**
* A callback that receives a *builder* object to define
* case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.
*
* Alternatively, a mapping from action types to action-type-specific *case reducer*
* functions. These reducers should have existing action types used
* as the keys, and action creators will _not_ be generated.
*
* @example
```ts
import { createAction, createSlice, Action, AnyAction } from '@reduxjs/toolkit'
const incrementBy = createAction<number>('incrementBy')
const decrement = createAction('decrement')
interface RejectedAction extends Action {
error: Error
}
function isRejectedAction(action: AnyAction): action is RejectedAction {
return action.type.endsWith('rejected')
}
createSlice({
name: 'counter',
initialState: 0,
reducers: {},
extraReducers: builder => {
builder
.addCase(incrementBy, (state, action) => {
// action is inferred correctly here if using TS
})
// You can chain calls, or have separate `builder.addCase()` lines each time
.addCase(decrement, (state, action) => {})
// You can match a range of action types
.addMatcher(
isRejectedAction,
// `action` will be inferred as a RejectedAction due to isRejectedAction being defined as a type guard
(state, action) => {}
)
// and provide a default case if no other handlers matched
.addDefaultCase((state, action) => {})
}
})
```
*/
extraReducers?: CaseReducers<NoInfer<State>, any> | ((builder: ActionReducerMapBuilder<NoInfer<State>>) => void);
}
/**
* A CaseReducer with a `prepare` method.
*
* @public
*/
export declare type CaseReducerWithPrepare<State, Action extends PayloadAction> = {
reducer: CaseReducer<State, Action>;
prepare: PrepareAction<Action['payload']>;
};
/**
* The type describing a slice's `reducers` option.
*
* @public
*/
export declare type SliceCaseReducers<State> = {
[K: string]: CaseReducer<State, PayloadAction<any>> | CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>>;
};
declare type SliceActionType<SliceName extends string, ActionName extends keyof any> = ActionName extends string | number ? `${SliceName}/${ActionName}` : string;
/**
* Derives the slice's `actions` property from the `reducers` options
*
* @public
*/
export declare type CaseReducerActions<CaseReducers extends SliceCaseReducers<any>, SliceName extends string> = {
[Type in keyof CaseReducers]: CaseReducers[Type] extends {
prepare: any;
} ? ActionCreatorForCaseReducerWithPrepare<CaseReducers[Type], SliceActionType<SliceName, Type>> : ActionCreatorForCaseReducer<CaseReducers[Type], SliceActionType<SliceName, Type>>;
};
/**
* Get a `PayloadActionCreator` type for a passed `CaseReducerWithPrepare`
*
* @internal
*/
declare type ActionCreatorForCaseReducerWithPrepare<CR extends {
prepare: any;
}, Type extends string> = _ActionCreatorWithPreparedPayload<CR['prepare'], Type>;
/**
* Get a `PayloadActionCreator` type for a passed `CaseReducer`
*
* @internal
*/
declare type ActionCreatorForCaseReducer<CR, Type extends string> = CR extends (state: any, action: infer Action) => any ? Action extends {
payload: infer P;
} ? PayloadActionCreator<P, Type> : ActionCreatorWithoutPayload<Type> : ActionCreatorWithoutPayload<Type>;
/**
* Extracts the CaseReducers out of a `reducers` object, even if they are
* tested into a `CaseReducerWithPrepare`.
*
* @internal
*/
declare type SliceDefinedCaseReducers<CaseReducers extends SliceCaseReducers<any>> = {
[Type in keyof CaseReducers]: CaseReducers[Type] extends {
reducer: infer Reducer;
} ? Reducer : CaseReducers[Type];
};
/**
* Used on a SliceCaseReducers object.
* Ensures that if a CaseReducer is a `CaseReducerWithPrepare`, that
* the `reducer` and the `prepare` function use the same type of `payload`.
*
* Might do additional such checks in the future.
*
* This type is only ever useful if you want to write your own wrapper around
* `createSlice`. Please don't use it otherwise!
*
* @public
*/
export declare type ValidateSliceCaseReducers<S, ACR extends SliceCaseReducers<S>> = ACR & {
[T in keyof ACR]: ACR[T] extends {
reducer(s: S, action?: infer A): any;
} ? {
prepare(...a: never[]): Omit<A, 'type'>;
} : {};
};
/**
* A function that accepts an initial state, an object full of reducer
* functions, and a "slice name", and automatically generates
* action creators and action types that correspond to the
* reducers and state.
*
* The `reducer` argument is passed to `createReducer()`.
*
* @public
*/
export declare function createSlice<State, CaseReducers extends SliceCaseReducers<State>, Name extends string = string>(options: CreateSliceOptions<State, CaseReducers, Name>): Slice<State, CaseReducers, Name>;
export {};

@ -0,0 +1,229 @@
import type { Action, ActionCreator, StoreEnhancer } from 'redux';
import { compose } from 'redux';
/**
* @public
*/
export interface DevToolsEnhancerOptions {
/**
* the instance name to be showed on the monitor page. Default value is `document.title`.
* If not specified and there's no document title, it will consist of `tabId` and `instanceId`.
*/
name?: string;
/**
* action creators functions to be available in the Dispatcher.
*/
actionCreators?: ActionCreator<any>[] | {
[key: string]: ActionCreator<any>;
};
/**
* if more than one action is dispatched in the indicated interval, all new actions will be collected and sent at once.
* It is the joint between performance and speed. When set to `0`, all actions will be sent instantly.
* Set it to a higher value when experiencing perf issues (also `maxAge` to a lower value).
*
* @default 500 ms.
*/
latency?: number;
/**
* (> 1) - maximum allowed actions to be stored in the history tree. The oldest actions are removed once maxAge is reached. It's critical for performance.
*
* @default 50
*/
maxAge?: number;
/**
* Customizes how actions and state are serialized and deserialized. Can be a boolean or object. If given a boolean, the behavior is the same as if you
* were to pass an object and specify `options` as a boolean. Giving an object allows fine-grained customization using the `replacer` and `reviver`
* functions.
*/
serialize?: boolean | {
/**
* - `undefined` - will use regular `JSON.stringify` to send data (it's the fast mode).
* - `false` - will handle also circular references.
* - `true` - will handle also date, regex, undefined, error objects, symbols, maps, sets and functions.
* - object, which contains `date`, `regex`, `undefined`, `error`, `symbol`, `map`, `set` and `function` keys.
* For each of them you can indicate if to include (by setting as `true`).
* For `function` key you can also specify a custom function which handles serialization.
* See [`jsan`](https://github.com/kolodny/jsan) for more details.
*/
options?: undefined | boolean | {
date?: true;
regex?: true;
undefined?: true;
error?: true;
symbol?: true;
map?: true;
set?: true;
function?: true | ((fn: (...args: any[]) => any) => string);
};
/**
* [JSON replacer function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter) used for both actions and states stringify.
* In addition, you can specify a data type by adding a [`__serializedType__`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/helpers/index.js#L4)
* key. So you can deserialize it back while importing or persisting data.
* Moreover, it will also [show a nice preview showing the provided custom type](https://cloud.githubusercontent.com/assets/7957859/21814330/a17d556a-d761-11e6-85ef-159dd12f36c5.png):
*/
replacer?: (key: string, value: unknown) => any;
/**
* [JSON `reviver` function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Using_the_reviver_parameter)
* used for parsing the imported actions and states. See [`remotedev-serialize`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/immutable/serialize.js#L8-L41)
* as an example on how to serialize special data types and get them back.
*/
reviver?: (key: string, value: unknown) => any;
/**
* Automatically serialize/deserialize immutablejs via [remotedev-serialize](https://github.com/zalmoxisus/remotedev-serialize).
* Just pass the Immutable library. It will support all ImmutableJS structures. You can even export them into a file and get them back.
* The only exception is `Record` class, for which you should pass this in addition the references to your classes in `refs`.
*/
immutable?: any;
/**
* ImmutableJS `Record` classes used to make possible restore its instances back when importing, persisting...
*/
refs?: any;
};
/**
* function which takes `action` object and id number as arguments, and should return `action` object back.
*/
actionSanitizer?: <A extends Action>(action: A, id: number) => A;
/**
* function which takes `state` object and index as arguments, and should return `state` object back.
*/
stateSanitizer?: <S>(state: S, index: number) => S;
/**
* *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).
* If `actionsWhitelist` specified, `actionsBlacklist` is ignored.
* @deprecated Use actionsDenylist instead.
*/
actionsBlacklist?: string | string[];
/**
* *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).
* If `actionsWhitelist` specified, `actionsBlacklist` is ignored.
* @deprecated Use actionsAllowlist instead.
*/
actionsWhitelist?: string | string[];
/**
* *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).
* If `actionsAllowlist` specified, `actionsDenylist` is ignored.
*/
actionsDenylist?: string | string[];
/**
* *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).
* If `actionsAllowlist` specified, `actionsDenylist` is ignored.
*/
actionsAllowlist?: string | string[];
/**
* called for every action before sending, takes `state` and `action` object, and returns `true` in case it allows sending the current data to the monitor.
* Use it as a more advanced version of `actionsDenylist`/`actionsAllowlist` parameters.
*/
predicate?: <S, A extends Action>(state: S, action: A) => boolean;
/**
* if specified as `false`, it will not record the changes till clicking on `Start recording` button.
* Available only for Redux enhancer, for others use `autoPause`.
*
* @default true
*/
shouldRecordChanges?: boolean;
/**
* if specified, whenever clicking on `Pause recording` button and there are actions in the history log, will add this action type.
* If not specified, will commit when paused. Available only for Redux enhancer.
*
* @default "@@PAUSED""
*/
pauseActionType?: string;
/**
* auto pauses when the extensions window is not opened, and so has zero impact on your app when not in use.
* Not available for Redux enhancer (as it already does it but storing the data to be sent).
*
* @default false
*/
autoPause?: boolean;
/**
* if specified as `true`, it will not allow any non-monitor actions to be dispatched till clicking on `Unlock changes` button.
* Available only for Redux enhancer.
*
* @default false
*/
shouldStartLocked?: boolean;
/**
* if set to `false`, will not recompute the states on hot reloading (or on replacing the reducers). Available only for Redux enhancer.
*
* @default true
*/
shouldHotReload?: boolean;
/**
* if specified as `true`, whenever there's an exception in reducers, the monitors will show the error message, and next actions will not be dispatched.
*
* @default false
*/
shouldCatchErrors?: boolean;
/**
* If you want to restrict the extension, specify the features you allow.
* If not specified, all of the features are enabled. When set as an object, only those included as `true` will be allowed.
* Note that except `true`/`false`, `import` and `export` can be set as `custom` (which is by default for Redux enhancer), meaning that the importing/exporting occurs on the client side.
* Otherwise, you'll get/set the data right from the monitor part.
*/
features?: {
/**
* start/pause recording of dispatched actions
*/
pause?: boolean;
/**
* lock/unlock dispatching actions and side effects
*/
lock?: boolean;
/**
* persist states on page reloading
*/
persist?: boolean;
/**
* export history of actions in a file
*/
export?: boolean | 'custom';
/**
* import history of actions from a file
*/
import?: boolean | 'custom';
/**
* jump back and forth (time travelling)
*/
jump?: boolean;
/**
* skip (cancel) actions
*/
skip?: boolean;
/**
* drag and drop actions in the history list
*/
reorder?: boolean;
/**
* dispatch custom actions or action creators
*/
dispatch?: boolean;
/**
* generate tests for the selected actions
*/
test?: boolean;
};
/**
* Set to true or a stacktrace-returning function to record call stack traces for dispatched actions.
* Defaults to false.
*/
trace?: boolean | (<A extends Action>(action: A) => string);
/**
* The maximum number of stack trace entries to record per action. Defaults to 10.
*/
traceLimit?: number;
}
declare type Compose = typeof compose;
interface ComposeWithDevTools {
(options: DevToolsEnhancerOptions): Compose;
<StoreExt>(...funcs: StoreEnhancer<StoreExt>[]): StoreEnhancer<StoreExt>;
}
/**
* @public
*/
export declare const composeWithDevTools: ComposeWithDevTools;
/**
* @public
*/
export declare const devToolsEnhancer: {
(options: DevToolsEnhancerOptions): StoreEnhancer<any>;
};
export {};

@ -0,0 +1,11 @@
import type { Comparer, IdSelector, EntityAdapter } from './models';
/**
*
* @param options
*
* @public
*/
export declare function createEntityAdapter<T>(options?: {
selectId?: IdSelector<T>;
sortComparer?: false | Comparer<T>;
}): EntityAdapter<T>;

@ -0,0 +1,8 @@
import type { EntityState } from './models';
export declare function getInitialEntityState<V>(): EntityState<V>;
export declare function createInitialStateFactory<V>(): {
getInitialState: {
(): EntityState<V>;
<S extends object>(additionalState: S): EntityState<V> & S;
};
};

@ -0,0 +1,2 @@
export { createEntityAdapter } from './create_adapter';
export type { Dictionary, EntityState, EntityAdapter, Update, IdSelector, Comparer, } from './models';

@ -0,0 +1,97 @@
import type { PayloadAction } from '../createAction';
import type { IsAny } from '../tsHelpers';
/**
* @public
*/
export declare type EntityId = number | string;
/**
* @public
*/
export declare type Comparer<T> = (a: T, b: T) => number;
/**
* @public
*/
export declare type IdSelector<T> = (model: T) => EntityId;
/**
* @public
*/
export interface DictionaryNum<T> {
[id: number]: T | undefined;
}
/**
* @public
*/
export interface Dictionary<T> extends DictionaryNum<T> {
[id: string]: T | undefined;
}
/**
* @public
*/
export declare type Update<T> = {
id: EntityId;
changes: Partial<T>;
};
/**
* @public
*/
export interface EntityState<T> {
ids: EntityId[];
entities: Dictionary<T>;
}
/**
* @public
*/
export interface EntityDefinition<T> {
selectId: IdSelector<T>;
sortComparer: false | Comparer<T>;
}
export declare type PreventAny<S, T> = IsAny<S, EntityState<T>, S>;
/**
* @public
*/
export interface EntityStateAdapter<T> {
addOne<S extends EntityState<T>>(state: PreventAny<S, T>, entity: T): S;
addOne<S extends EntityState<T>>(state: PreventAny<S, T>, action: PayloadAction<T>): S;
addMany<S extends EntityState<T>>(state: PreventAny<S, T>, entities: readonly T[] | Record<EntityId, T>): S;
addMany<S extends EntityState<T>>(state: PreventAny<S, T>, entities: PayloadAction<readonly T[] | Record<EntityId, T>>): S;
setOne<S extends EntityState<T>>(state: PreventAny<S, T>, entity: T): S;
setOne<S extends EntityState<T>>(state: PreventAny<S, T>, action: PayloadAction<T>): S;
setMany<S extends EntityState<T>>(state: PreventAny<S, T>, entities: readonly T[] | Record<EntityId, T>): S;
setMany<S extends EntityState<T>>(state: PreventAny<S, T>, entities: PayloadAction<readonly T[] | Record<EntityId, T>>): S;
setAll<S extends EntityState<T>>(state: PreventAny<S, T>, entities: readonly T[] | Record<EntityId, T>): S;
setAll<S extends EntityState<T>>(state: PreventAny<S, T>, entities: PayloadAction<readonly T[] | Record<EntityId, T>>): S;
removeOne<S extends EntityState<T>>(state: PreventAny<S, T>, key: EntityId): S;
removeOne<S extends EntityState<T>>(state: PreventAny<S, T>, key: PayloadAction<EntityId>): S;
removeMany<S extends EntityState<T>>(state: PreventAny<S, T>, keys: readonly EntityId[]): S;
removeMany<S extends EntityState<T>>(state: PreventAny<S, T>, keys: PayloadAction<readonly EntityId[]>): S;
removeAll<S extends EntityState<T>>(state: PreventAny<S, T>): S;
updateOne<S extends EntityState<T>>(state: PreventAny<S, T>, update: Update<T>): S;
updateOne<S extends EntityState<T>>(state: PreventAny<S, T>, update: PayloadAction<Update<T>>): S;
updateMany<S extends EntityState<T>>(state: PreventAny<S, T>, updates: ReadonlyArray<Update<T>>): S;
updateMany<S extends EntityState<T>>(state: PreventAny<S, T>, updates: PayloadAction<ReadonlyArray<Update<T>>>): S;
upsertOne<S extends EntityState<T>>(state: PreventAny<S, T>, entity: T): S;
upsertOne<S extends EntityState<T>>(state: PreventAny<S, T>, entity: PayloadAction<T>): S;
upsertMany<S extends EntityState<T>>(state: PreventAny<S, T>, entities: readonly T[] | Record<EntityId, T>): S;
upsertMany<S extends EntityState<T>>(state: PreventAny<S, T>, entities: PayloadAction<readonly T[] | Record<EntityId, T>>): S;
}
/**
* @public
*/
export interface EntitySelectors<T, V> {
selectIds: (state: V) => EntityId[];
selectEntities: (state: V) => Dictionary<T>;
selectAll: (state: V) => T[];
selectTotal: (state: V) => number;
selectById: (state: V, id: EntityId) => T | undefined;
}
/**
* @public
*/
export interface EntityAdapter<T> extends EntityStateAdapter<T> {
selectId: IdSelector<T>;
sortComparer: false | Comparer<T>;
getInitialState(): EntityState<T>;
getInitialState<S extends object>(state: S): EntityState<T> & S;
getSelectors(): EntitySelectors<T, EntityState<T>>;
getSelectors<V>(selectState: (state: V) => EntityState<T>): EntitySelectors<T, V>;
}

@ -0,0 +1,2 @@
import type { IdSelector, Comparer, EntityStateAdapter } from './models';
export declare function createSortedStateAdapter<T>(selectId: IdSelector<T>, sort: Comparer<T>): EntityStateAdapter<T>;

@ -0,0 +1,5 @@
import type { EntityState, PreventAny } from './models';
import type { PayloadAction } from '../createAction';
import { IsAny } from '../tsHelpers';
export declare function createSingleArgumentStateOperator<V>(mutator: (state: EntityState<V>) => void): <S extends EntityState<V>>(state: IsAny<S, EntityState<V>, S>) => S;
export declare function createStateOperator<V, R>(mutator: (arg: R, state: EntityState<V>) => void): <S extends EntityState<V>>(state: S, arg: R | PayloadAction<R>) => S;

@ -0,0 +1,7 @@
import type { EntityState, EntitySelectors } from './models';
export declare function createSelectorsFactory<T>(): {
getSelectors: {
(): EntitySelectors<T, EntityState<T>>;
<V>(selectState: (state: V) => EntityState<T>): EntitySelectors<T, V>;
};
};

@ -0,0 +1,2 @@
import type { EntityStateAdapter, IdSelector } from './models';
export declare function createUnsortedStateAdapter<T>(selectId: IdSelector<T>): EntityStateAdapter<T>;

@ -0,0 +1,4 @@
import type { EntityState, IdSelector, Update, EntityId } from './models';
export declare function selectIdValue<T>(entity: T, selectId: IdSelector<T>): EntityId;
export declare function ensureEntitiesArray<T>(entities: readonly T[] | Record<EntityId, T>): readonly T[];
export declare function splitAddedUpdatedEntities<T>(newEntities: readonly T[] | Record<EntityId, T>, selectId: IdSelector<T>, state: EntityState<T>): [T[], Update<T>[]];

@ -0,0 +1,45 @@
import type { AnyAction } from 'redux';
import type { ThunkMiddleware } from 'redux-thunk';
import type { ImmutableStateInvariantMiddlewareOptions } from './immutableStateInvariantMiddleware';
import type { SerializableStateInvariantMiddlewareOptions } from './serializableStateInvariantMiddleware';
import type { ExcludeFromTuple } from './tsHelpers';
import { MiddlewareArray } from './utils';
interface ThunkOptions<E = any> {
extraArgument: E;
}
interface GetDefaultMiddlewareOptions {
thunk?: boolean | ThunkOptions;
immutableCheck?: boolean | ImmutableStateInvariantMiddlewareOptions;
serializableCheck?: boolean | SerializableStateInvariantMiddlewareOptions;
}
export declare type ThunkMiddlewareFor<S, O extends GetDefaultMiddlewareOptions = {}> = O extends {
thunk: false;
} ? never : O extends {
thunk: {
extraArgument: infer E;
};
} ? ThunkMiddleware<S, AnyAction, E> : ThunkMiddleware<S, AnyAction>;
export declare type CurriedGetDefaultMiddleware<S = any> = <O extends Partial<GetDefaultMiddlewareOptions> = {
thunk: true;
immutableCheck: true;
serializableCheck: true;
}>(options?: O) => MiddlewareArray<ExcludeFromTuple<[ThunkMiddlewareFor<S, O>], never>>;
export declare function curryGetDefaultMiddleware<S = any>(): CurriedGetDefaultMiddleware<S>;
/**
* Returns any array containing the default middleware installed by
* `configureStore()`. Useful if you want to configure your store with a custom
* `middleware` array but still keep the default set.
*
* @return The default middleware used by `configureStore()`.
*
* @public
*
* @deprecated Prefer to use the callback notation for the `middleware` option in `configureStore`
* to access a pre-typed `getDefaultMiddleware` instead.
*/
export declare function getDefaultMiddleware<S = any, O extends Partial<GetDefaultMiddlewareOptions> = {
thunk: true;
immutableCheck: true;
serializableCheck: true;
}>(options?: O): MiddlewareArray<ExcludeFromTuple<[ThunkMiddlewareFor<S, O>], never>>;
export {};

@ -0,0 +1,49 @@
import type { Middleware } from 'redux';
/**
* The default `isImmutable` function.
*
* @public
*/
export declare function isImmutableDefault(value: unknown): boolean;
export declare function trackForMutations(isImmutable: IsImmutableFunc, ignorePaths: IgnorePaths | undefined, obj: any): {
detectMutations(): {
wasMutated: boolean;
path?: string | undefined;
};
};
declare type IgnorePaths = readonly (string | RegExp)[];
declare type IsImmutableFunc = (value: any) => boolean;
/**
* Options for `createImmutableStateInvariantMiddleware()`.
*
* @public
*/
export interface ImmutableStateInvariantMiddlewareOptions {
/**
Callback function to check if a value is considered to be immutable.
This function is applied recursively to every value contained in the state.
The default implementation will return true for primitive types
(like numbers, strings, booleans, null and undefined).
*/
isImmutable?: IsImmutableFunc;
/**
An array of dot-separated path strings that match named nodes from
the root state to ignore when checking for immutability.
Defaults to undefined
*/
ignoredPaths?: IgnorePaths;
/** Print a warning if checks take longer than N ms. Default: 32ms */
warnAfter?: number;
ignore?: string[];
}
/**
* Creates a middleware that checks whether any state was mutated in between
* dispatches or during a dispatch. If any mutations are detected, an error is
* thrown.
*
* @param options Middleware options.
*
* @public
*/
export declare function createImmutableStateInvariantMiddleware(options?: ImmutableStateInvariantMiddlewareOptions): Middleware;
export {};

@ -0,0 +1,36 @@
export * from 'redux';
export { default as createNextState, current, freeze, original, isDraft, } from 'immer';
export type { Draft } from 'immer';
export { createSelector } from 'reselect';
export type { Selector, OutputParametricSelector, OutputSelector, ParametricSelector, } from 'reselect';
export { createDraftSafeSelector } from './createDraftSafeSelector';
export type { ThunkAction, ThunkDispatch, ThunkMiddleware } from 'redux-thunk';
export { configureStore, } from './configureStore';
export type { ConfigureEnhancersCallback, ConfigureStoreOptions, EnhancedStore, } from './configureStore';
export type { DevToolsEnhancerOptions } from './devtoolsExtension';
export { createAction, getType, } from './createAction';
export type { PayloadAction, PayloadActionCreator, ActionCreatorWithNonInferrablePayload, ActionCreatorWithOptionalPayload, ActionCreatorWithPayload, ActionCreatorWithoutPayload, ActionCreatorWithPreparedPayload, PrepareAction, } from './createAction';
export { createReducer, } from './createReducer';
export type { Actions, CaseReducer, CaseReducers, } from './createReducer';
export { createSlice, } from './createSlice';
export type { CreateSliceOptions, Slice, CaseReducerActions, SliceCaseReducers, ValidateSliceCaseReducers, CaseReducerWithPrepare, SliceActionCreator, } from './createSlice';
export { createImmutableStateInvariantMiddleware, isImmutableDefault, } from './immutableStateInvariantMiddleware';
export type { ImmutableStateInvariantMiddlewareOptions, } from './immutableStateInvariantMiddleware';
export { createSerializableStateInvariantMiddleware, findNonSerializableValue, isPlain, } from './serializableStateInvariantMiddleware';
export type { SerializableStateInvariantMiddlewareOptions, } from './serializableStateInvariantMiddleware';
export { getDefaultMiddleware, } from './getDefaultMiddleware';
export type { ActionReducerMapBuilder, } from './mapBuilders';
export { MiddlewareArray } from './utils';
export { createEntityAdapter } from './entities/create_adapter';
export type { Dictionary, EntityState, EntityAdapter, EntitySelectors, EntityStateAdapter, EntityId, Update, IdSelector, Comparer, } from './entities/models';
export { createAsyncThunk, unwrapResult, miniSerializeError, } from './createAsyncThunk';
export type { AsyncThunk, AsyncThunkOptions, AsyncThunkAction, AsyncThunkPayloadCreatorReturnValue, AsyncThunkPayloadCreator, SerializedError, } from './createAsyncThunk';
export { isAllOf, isAnyOf, isPending, isRejected, isFulfilled, isAsyncThunkAction, isRejectedWithValue, } from './matchers';
export type { ActionMatchingAllOf, ActionMatchingAnyOf, } from './matchers';
export { nanoid } from './nanoid';
export { default as isPlainObject } from './isPlainObject';
export type { ListenerEffect, ListenerMiddleware, ListenerEffectAPI, ListenerMiddlewareInstance, CreateListenerMiddlewareOptions, ListenerErrorHandler, TypedStartListening, TypedAddListener, TypedStopListening, TypedRemoveListener, UnsubscribeListener, UnsubscribeListenerOptions, ForkedTaskExecutor, ForkedTask, ForkedTaskAPI, AsyncTaskExecutor, SyncTaskExecutor, TaskCancelled, TaskRejected, TaskResolved, TaskResult, } from './listenerMiddleware/index';
export type { AnyListenerPredicate } from './listenerMiddleware/types';
export { createListenerMiddleware, addListener, removeListener, clearAllListeners, TaskAbortError, } from './listenerMiddleware/index';
export { SHOULD_AUTOBATCH, prepareAutoBatched, autoBatchEnhancer, } from './autoBatchEnhancer';
export type { AutoBatchOptions } from './autoBatchEnhancer';

@ -0,0 +1,6 @@
'use strict'
if (process.env.NODE_ENV === 'production') {
module.exports = require('./redux-toolkit.cjs.production.min.js')
} else {
module.exports = require('./redux-toolkit.cjs.development.js')
}

@ -0,0 +1,11 @@
/**
* Returns true if the passed value is "plain" object, i.e. an object whose
* prototype is the root `Object.prototype`. This includes objects created
* using object literals, but not for instance for class instances.
*
* @param {any} value The value to inspect.
* @returns {boolean} True if the argument appears to be a plain object.
*
* @public
*/
export default function isPlainObject(value: unknown): value is object;

@ -0,0 +1,11 @@
import type { SerializedError } from '@reduxjs/toolkit';
export declare const taskCancelled: "task-cancelled";
export declare const taskCompleted: "task-completed";
export declare const listenerCancelled: "listener-cancelled";
export declare const listenerCompleted: "listener-completed";
export declare class TaskAbortError implements SerializedError {
code: string | undefined;
name: string;
message: string;
constructor(code: string | undefined);
}

@ -0,0 +1,23 @@
import type { Dispatch, AnyAction } from 'redux';
import type { ThunkDispatch } from 'redux-thunk';
import type { ListenerMiddlewareInstance, CreateListenerMiddlewareOptions, TypedAddListener, TypedCreateListenerEntry, ListenerEntry, TypedRemoveListener } from './types';
export { TaskAbortError } from './exceptions';
export type { ListenerEffect, ListenerMiddleware, ListenerEffectAPI, ListenerMiddlewareInstance, CreateListenerMiddlewareOptions, ListenerErrorHandler, TypedStartListening, TypedAddListener, TypedStopListening, TypedRemoveListener, UnsubscribeListener, UnsubscribeListenerOptions, ForkedTaskExecutor, ForkedTask, ForkedTaskAPI, AsyncTaskExecutor, SyncTaskExecutor, TaskCancelled, TaskRejected, TaskResolved, TaskResult, } from './types';
/** Accepts the possible options for creating a listener, and returns a formatted listener entry */
export declare const createListenerEntry: TypedCreateListenerEntry<unknown>;
/**
* @public
*/
export declare const addListener: TypedAddListener<unknown, ThunkDispatch<unknown, unknown, AnyAction>, unknown, ListenerEntry<unknown, ThunkDispatch<unknown, unknown, AnyAction>>, "listenerMiddleware/add">;
/**
* @public
*/
export declare const clearAllListeners: import("../createAction").ActionCreatorWithoutPayload<string>;
/**
* @public
*/
export declare const removeListener: TypedRemoveListener<unknown, ThunkDispatch<unknown, unknown, AnyAction>, ListenerEntry<unknown, ThunkDispatch<unknown, unknown, AnyAction>>, "listenerMiddleware/remove">;
/**
* @public
*/
export declare function createListenerMiddleware<S = unknown, D extends Dispatch<AnyAction> = ThunkDispatch<S, unknown, AnyAction>, ExtraArgument = unknown>(middlewareOptions?: CreateListenerMiddlewareOptions<ExtraArgument>): ListenerMiddlewareInstance<S, D, ExtraArgument>;

@ -0,0 +1,37 @@
import type { AbortSignalWithReason, TaskResult } from './types';
/**
* Synchronously raises {@link TaskAbortError} if the task tied to the input `signal` has been cancelled.
* @param signal
* @param reason
* @see {TaskAbortError}
*/
export declare const validateActive: (signal: AbortSignal) => void;
/**
* Generates a race between the promise(s) and the AbortSignal
* This avoids `Promise.race()`-related memory leaks:
* https://github.com/nodejs/node/issues/17469#issuecomment-349794909
*/
export declare function raceWithSignal<T>(signal: AbortSignalWithReason<string>, promise: Promise<T>): Promise<T>;
/**
* Runs a task and returns promise that resolves to {@link TaskResult}.
* Second argument is an optional `cleanUp` function that always runs after task.
*
* **Note:** `runTask` runs the executor in the next microtask.
* @returns
*/
export declare const runTask: <T>(task: () => Promise<T>, cleanUp?: (() => void) | undefined) => Promise<TaskResult<T>>;
/**
* Given an input `AbortSignal` and a promise returns another promise that resolves
* as soon the input promise is provided or rejects as soon as
* `AbortSignal.abort` is `true`.
* @param signal
* @returns
*/
export declare const createPause: <T>(signal: AbortSignal) => (promise: Promise<T>) => Promise<T>;
/**
* Given an input `AbortSignal` and `timeoutMs` returns a promise that resolves
* after `timeoutMs` or rejects as soon as `AbortSignal.abort` is `true`.
* @param signal
* @returns
*/
export declare const createDelay: (signal: AbortSignal) => (timeoutMs: number) => Promise<void>;

@ -0,0 +1,381 @@
import type { PayloadAction, BaseActionCreator } from '../createAction';
import type { Dispatch as ReduxDispatch, AnyAction, MiddlewareAPI, Middleware, Action as ReduxAction } from 'redux';
import type { ThunkDispatch } from 'redux-thunk';
import type { TaskAbortError } from './exceptions';
/**
* @internal
* At the time of writing `lib.dom.ts` does not provide `abortSignal.reason`.
*/
export declare type AbortSignalWithReason<T> = AbortSignal & {
reason?: T;
};
/**
* Types copied from RTK
*/
/** @internal */
export interface TypedActionCreator<Type extends string> {
(...args: any[]): ReduxAction<Type>;
type: Type;
match: MatchFunction<any>;
}
/** @internal */
export declare type AnyListenerPredicate<State> = (action: AnyAction, currentState: State, originalState: State) => boolean;
/** @public */
export declare type ListenerPredicate<Action extends AnyAction, State> = (action: AnyAction, currentState: State, originalState: State) => action is Action;
/** @public */
export interface ConditionFunction<State> {
(predicate: AnyListenerPredicate<State>, timeout?: number): Promise<boolean>;
(predicate: AnyListenerPredicate<State>, timeout?: number): Promise<boolean>;
(predicate: () => boolean, timeout?: number): Promise<boolean>;
}
/** @internal */
export declare type MatchFunction<T> = (v: any) => v is T;
/** @public */
export interface ForkedTaskAPI {
/**
* Returns a promise that resolves when `waitFor` resolves or
* rejects if the task or the parent listener has been cancelled or is completed.
*/
pause<W>(waitFor: Promise<W>): Promise<W>;
/**
* Returns a promise that resolves after `timeoutMs` or
* rejects if the task or the parent listener has been cancelled or is completed.
* @param timeoutMs
*/
delay(timeoutMs: number): Promise<void>;
/**
* An abort signal whose `aborted` property is set to `true`
* if the task execution is either aborted or completed.
* @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
*/
signal: AbortSignal;
}
/** @public */
export interface AsyncTaskExecutor<T> {
(forkApi: ForkedTaskAPI): Promise<T>;
}
/** @public */
export interface SyncTaskExecutor<T> {
(forkApi: ForkedTaskAPI): T;
}
/** @public */
export declare type ForkedTaskExecutor<T> = AsyncTaskExecutor<T> | SyncTaskExecutor<T>;
/** @public */
export declare type TaskResolved<T> = {
readonly status: 'ok';
readonly value: T;
};
/** @public */
export declare type TaskRejected = {
readonly status: 'rejected';
readonly error: unknown;
};
/** @public */
export declare type TaskCancelled = {
readonly status: 'cancelled';
readonly error: TaskAbortError;
};
/** @public */
export declare type TaskResult<Value> = TaskResolved<Value> | TaskRejected | TaskCancelled;
/** @public */
export interface ForkedTask<T> {
/**
* A promise that resolves when the task is either completed or cancelled or rejects
* if parent listener execution is cancelled or completed.
*
* ### Example
* ```ts
* const result = await fork(async (forkApi) => Promise.resolve(4)).result
*
* if(result.status === 'ok') {
* console.log(result.value) // logs 4
* }}
* ```
*/
result: Promise<TaskResult<T>>;
/**
* Cancel task if it is in progress or not yet started,
* it is noop otherwise.
*/
cancel(): void;
}
/** @public */
export interface ListenerEffectAPI<State, Dispatch extends ReduxDispatch<AnyAction>, ExtraArgument = unknown> extends MiddlewareAPI<Dispatch, State> {
/**
* Returns the store state as it existed when the action was originally dispatched, _before_ the reducers ran.
*
* ### Synchronous invocation
*
* This function can **only** be invoked **synchronously**, it throws error otherwise.
*
* @example
*
* ```ts
* middleware.startListening({
* predicate: () => true,
* async effect(_, { getOriginalState }) {
* getOriginalState(); // sync: OK!
*
* setTimeout(getOriginalState, 0); // async: throws Error
*
* await Promise().resolve();
*
* getOriginalState() // async: throws Error
* }
* })
* ```
*/
getOriginalState: () => State;
/**
* Removes the listener entry from the middleware and prevent future instances of the listener from running.
*
* It does **not** cancel any active instances.
*/
unsubscribe(): void;
/**
* It will subscribe a listener if it was previously removed, noop otherwise.
*/
subscribe(): void;
/**
* Returns a promise that resolves when the input predicate returns `true` or
* rejects if the listener has been cancelled or is completed.
*
* The return value is `true` if the predicate succeeds or `false` if a timeout is provided and expires first.
*
* ### Example
*
* ```ts
* const updateBy = createAction<number>('counter/updateBy');
*
* middleware.startListening({
* actionCreator: updateBy,
* async effect(_, { condition }) {
* // wait at most 3s for `updateBy` actions.
* if(await condition(updateBy.match, 3_000)) {
* // `updateBy` has been dispatched twice in less than 3s.
* }
* }
* })
* ```
*/
condition: ConditionFunction<State>;
/**
* Returns a promise that resolves when the input predicate returns `true` or
* rejects if the listener has been cancelled or is completed.
*
* The return value is the `[action, currentState, previousState]` combination that the predicate saw as arguments.
*
* The promise resolves to null if a timeout is provided and expires first,
*
* ### Example
*
* ```ts
* const updateBy = createAction<number>('counter/updateBy');
*
* middleware.startListening({
* actionCreator: updateBy,
* async effect(_, { take }) {
* const [{ payload }] = await take(updateBy.match);
* console.log(payload); // logs 5;
* }
* })
*
* store.dispatch(updateBy(5));
* ```
*/
take: TakePattern<State>;
/**
* Cancels all other running instances of this same listener except for the one that made this call.
*/
cancelActiveListeners: () => void;
/**
* An abort signal whose `aborted` property is set to `true`
* if the listener execution is either aborted or completed.
* @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal
*/
signal: AbortSignal;
/**
* Returns a promise that resolves after `timeoutMs` or
* rejects if the listener has been cancelled or is completed.
*/
delay(timeoutMs: number): Promise<void>;
/**
* Queues in the next microtask the execution of a task.
* @param executor
*/
fork<T>(executor: ForkedTaskExecutor<T>): ForkedTask<T>;
/**
* Returns a promise that resolves when `waitFor` resolves or
* rejects if the listener has been cancelled or is completed.
* @param promise
*/
pause<M>(promise: Promise<M>): Promise<M>;
extra: ExtraArgument;
}
/** @public */
export declare type ListenerEffect<Action extends AnyAction, State, Dispatch extends ReduxDispatch<AnyAction>, ExtraArgument = unknown> = (action: Action, api: ListenerEffectAPI<State, Dispatch, ExtraArgument>) => void | Promise<void>;
/**
* @public
* Additional infos regarding the error raised.
*/
export interface ListenerErrorInfo {
/**
* Which function has generated the exception.
*/
raisedBy: 'effect' | 'predicate';
}
/**
* @public
* Gets notified with synchronous and asynchronous errors raised by `listeners` or `predicates`.
* @param error The thrown error.
* @param errorInfo Additional information regarding the thrown error.
*/
export interface ListenerErrorHandler {
(error: unknown, errorInfo: ListenerErrorInfo): void;
}
/** @public */
export interface CreateListenerMiddlewareOptions<ExtraArgument = unknown> {
extra?: ExtraArgument;
/**
* Receives synchronous errors that are raised by `listener` and `listenerOption.predicate`.
*/
onError?: ListenerErrorHandler;
}
/** @public */
export declare type ListenerMiddleware<State = unknown, Dispatch extends ThunkDispatch<State, unknown, AnyAction> = ThunkDispatch<State, unknown, AnyAction>, ExtraArgument = unknown> = Middleware<{
(action: ReduxAction<'listenerMiddleware/add'>): UnsubscribeListener;
}, State, Dispatch>;
/** @public */
export interface ListenerMiddlewareInstance<State = unknown, Dispatch extends ThunkDispatch<State, unknown, AnyAction> = ThunkDispatch<State, unknown, AnyAction>, ExtraArgument = unknown> {
middleware: ListenerMiddleware<State, Dispatch, ExtraArgument>;
startListening: AddListenerOverloads<UnsubscribeListener, State, Dispatch, ExtraArgument>;
stopListening: RemoveListenerOverloads<State, Dispatch>;
/**
* Unsubscribes all listeners, cancels running listeners and tasks.
*/
clearListeners: () => void;
}
/**
* API Function Overloads
*/
/** @public */
export declare type TakePatternOutputWithoutTimeout<State, Predicate extends AnyListenerPredicate<State>> = Predicate extends MatchFunction<infer Action> ? Promise<[Action, State, State]> : Promise<[AnyAction, State, State]>;
/** @public */
export declare type TakePatternOutputWithTimeout<State, Predicate extends AnyListenerPredicate<State>> = Predicate extends MatchFunction<infer Action> ? Promise<[Action, State, State] | null> : Promise<[AnyAction, State, State] | null>;
/** @public */
export interface TakePattern<State> {
<Predicate extends AnyListenerPredicate<State>>(predicate: Predicate): TakePatternOutputWithoutTimeout<State, Predicate>;
<Predicate extends AnyListenerPredicate<State>>(predicate: Predicate, timeout: number): TakePatternOutputWithTimeout<State, Predicate>;
<Predicate extends AnyListenerPredicate<State>>(predicate: Predicate, timeout?: number | undefined): TakePatternOutputWithTimeout<State, Predicate>;
}
/** @public */
export interface UnsubscribeListenerOptions {
cancelActive?: true;
}
/** @public */
export declare type UnsubscribeListener = (unsubscribeOptions?: UnsubscribeListenerOptions) => void;
/**
* @public
* The possible overloads and options for defining a listener. The return type of each function is specified as a generic arg, so the overloads can be reused for multiple different functions
*/
export interface AddListenerOverloads<Return, State = unknown, Dispatch extends ReduxDispatch = ThunkDispatch<State, unknown, AnyAction>, ExtraArgument = unknown, AdditionalOptions = unknown> {
/** Accepts a "listener predicate" that is also a TS type predicate for the action*/
<MA extends AnyAction, LP extends ListenerPredicate<MA, State>>(options: {
actionCreator?: never;
type?: never;
matcher?: never;
predicate: LP;
effect: ListenerEffect<ListenerPredicateGuardedActionType<LP>, State, Dispatch, ExtraArgument>;
} & AdditionalOptions): Return;
/** Accepts an RTK action creator, like `incrementByAmount` */
<C extends TypedActionCreator<any>>(options: {
actionCreator: C;
type?: never;
matcher?: never;
predicate?: never;
effect: ListenerEffect<ReturnType<C>, State, Dispatch, ExtraArgument>;
} & AdditionalOptions): Return;
/** Accepts a specific action type string */
<T extends string>(options: {
actionCreator?: never;
type: T;
matcher?: never;
predicate?: never;
effect: ListenerEffect<ReduxAction<T>, State, Dispatch, ExtraArgument>;
} & AdditionalOptions): Return;
/** Accepts an RTK matcher function, such as `incrementByAmount.match` */
<MA extends AnyAction, M extends MatchFunction<MA>>(options: {
actionCreator?: never;
type?: never;
matcher: M;
predicate?: never;
effect: ListenerEffect<GuardedType<M>, State, Dispatch, ExtraArgument>;
} & AdditionalOptions): Return;
/** Accepts a "listener predicate" that just returns a boolean, no type assertion */
<LP extends AnyListenerPredicate<State>>(options: {
actionCreator?: never;
type?: never;
matcher?: never;
predicate: LP;
effect: ListenerEffect<AnyAction, State, Dispatch, ExtraArgument>;
} & AdditionalOptions): Return;
}
/** @public */
export declare type RemoveListenerOverloads<State = unknown, Dispatch extends ReduxDispatch = ThunkDispatch<State, unknown, AnyAction>> = AddListenerOverloads<boolean, State, Dispatch, any, UnsubscribeListenerOptions>;
/** @public */
export interface RemoveListenerAction<Action extends AnyAction, State, Dispatch extends ReduxDispatch<AnyAction>> {
type: 'listenerMiddleware/remove';
payload: {
type: string;
listener: ListenerEffect<Action, State, Dispatch>;
};
}
/**
* @public
* A "pre-typed" version of `addListenerAction`, so the listener args are well-typed */
export declare type TypedAddListener<State, Dispatch extends ReduxDispatch<AnyAction> = ThunkDispatch<State, unknown, AnyAction>, ExtraArgument = unknown, Payload = ListenerEntry<State, Dispatch>, T extends string = 'listenerMiddleware/add'> = BaseActionCreator<Payload, T> & AddListenerOverloads<PayloadAction<Payload, T>, State, Dispatch, ExtraArgument>;
/**
* @public
* A "pre-typed" version of `removeListenerAction`, so the listener args are well-typed */
export declare type TypedRemoveListener<State, Dispatch extends ReduxDispatch<AnyAction> = ThunkDispatch<State, unknown, AnyAction>, Payload = ListenerEntry<State, Dispatch>, T extends string = 'listenerMiddleware/remove'> = BaseActionCreator<Payload, T> & AddListenerOverloads<PayloadAction<Payload, T>, State, Dispatch, any, UnsubscribeListenerOptions>;
/**
* @public
* A "pre-typed" version of `middleware.startListening`, so the listener args are well-typed */
export declare type TypedStartListening<State, Dispatch extends ReduxDispatch<AnyAction> = ThunkDispatch<State, unknown, AnyAction>, ExtraArgument = unknown> = AddListenerOverloads<UnsubscribeListener, State, Dispatch, ExtraArgument>;
/** @public
* A "pre-typed" version of `middleware.stopListening`, so the listener args are well-typed */
export declare type TypedStopListening<State, Dispatch extends ReduxDispatch<AnyAction> = ThunkDispatch<State, unknown, AnyAction>> = RemoveListenerOverloads<State, Dispatch>;
/** @public
* A "pre-typed" version of `createListenerEntry`, so the listener args are well-typed */
export declare type TypedCreateListenerEntry<State, Dispatch extends ReduxDispatch<AnyAction> = ThunkDispatch<State, unknown, AnyAction>> = AddListenerOverloads<ListenerEntry<State, Dispatch>, State, Dispatch>;
/**
* Internal Types
*/
/** @internal An single listener entry */
export declare type ListenerEntry<State = unknown, Dispatch extends ReduxDispatch<AnyAction> = ReduxDispatch<AnyAction>> = {
id: string;
effect: ListenerEffect<any, State, Dispatch>;
unsubscribe: () => void;
pending: Set<AbortController>;
type?: string;
predicate: ListenerPredicate<AnyAction, State>;
};
/**
* @internal
* A shorthand form of the accepted args, solely so that `createListenerEntry` has validly-typed conditional logic when checking the options contents
*/
export declare type FallbackAddListenerOptions = {
actionCreator?: TypedActionCreator<string>;
type?: string;
matcher?: MatchFunction<any>;
predicate?: ListenerPredicate<any, any>;
} & {
effect: ListenerEffect<any, any, any>;
};
/**
* Utility Types
*/
/** @public */
export declare type GuardedType<T> = T extends (x: any, ...args: unknown[]) => x is infer T ? T : never;
/** @public */
export declare type ListenerPredicateGuardedActionType<T> = T extends ListenerPredicate<infer Action, any> ? Action : never;

@ -0,0 +1,15 @@
export declare const assertFunction: (func: unknown, expected: string) => asserts func is (...args: unknown[]) => unknown;
export declare const noop: () => void;
export declare const catchRejection: <T>(promise: Promise<T>, onError?: () => void) => Promise<T>;
export declare const addAbortSignalListener: (abortSignal: AbortSignal, callback: (evt: Event) => void) => () => void;
/**
* Calls `abortController.abort(reason)` and patches `signal.reason`.
* if it is not supported.
*
* At the time of writing `signal.reason` is available in FF chrome, edge node 17 and deno.
* @param abortController
* @param reason
* @returns
* @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/reason
*/
export declare const abortControllerWithReason: <T>(abortController: AbortController, reason: T) => void;

@ -0,0 +1,112 @@
import type { Action, AnyAction } from 'redux';
import type { CaseReducer, CaseReducers, ActionMatcherDescriptionCollection } from './createReducer';
import type { TypeGuard } from './tsHelpers';
export interface TypedActionCreator<Type extends string> {
(...args: any[]): Action<Type>;
type: Type;
}
/**
* A builder for an action <-> reducer map.
*
* @public
*/
export interface ActionReducerMapBuilder<State> {
/**
* Adds a case reducer to handle a single exact action type.
* @remarks
* All calls to `builder.addCase` must come before any calls to `builder.addMatcher` or `builder.addDefaultCase`.
* @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.
* @param reducer - The actual case reducer function.
*/
addCase<ActionCreator extends TypedActionCreator<string>>(actionCreator: ActionCreator, reducer: CaseReducer<State, ReturnType<ActionCreator>>): ActionReducerMapBuilder<State>;
/**
* Adds a case reducer to handle a single exact action type.
* @remarks
* All calls to `builder.addCase` must come before any calls to `builder.addMatcher` or `builder.addDefaultCase`.
* @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.
* @param reducer - The actual case reducer function.
*/
addCase<Type extends string, A extends Action<Type>>(type: Type, reducer: CaseReducer<State, A>): ActionReducerMapBuilder<State>;
/**
* Allows you to match your incoming actions against your own filter function instead of only the `action.type` property.
* @remarks
* If multiple matcher reducers match, all of them will be executed in the order
* they were defined in - even if a case reducer already matched.
* All calls to `builder.addMatcher` must come after any calls to `builder.addCase` and before any calls to `builder.addDefaultCase`.
* @param matcher - A matcher function. In TypeScript, this should be a [type predicate](https://www.typescriptlang.org/docs/handbook/advanced-types.html#using-type-predicates)
* function
* @param reducer - The actual case reducer function.
*
* @example
```ts
import {
createAction,
createReducer,
AsyncThunk,
AnyAction,
} from "@reduxjs/toolkit";
type GenericAsyncThunk = AsyncThunk<unknown, unknown, any>;
type PendingAction = ReturnType<GenericAsyncThunk["pending"]>;
type RejectedAction = ReturnType<GenericAsyncThunk["rejected"]>;
type FulfilledAction = ReturnType<GenericAsyncThunk["fulfilled"]>;
const initialState: Record<string, string> = {};
const resetAction = createAction("reset-tracked-loading-state");
function isPendingAction(action: AnyAction): action is PendingAction {
return action.type.endsWith("/pending");
}
const reducer = createReducer(initialState, (builder) => {
builder
.addCase(resetAction, () => initialState)
// matcher can be defined outside as a type predicate function
.addMatcher(isPendingAction, (state, action) => {
state[action.meta.requestId] = "pending";
})
.addMatcher(
// matcher can be defined inline as a type predicate function
(action): action is RejectedAction => action.type.endsWith("/rejected"),
(state, action) => {
state[action.meta.requestId] = "rejected";
}
)
// matcher can just return boolean and the matcher can receive a generic argument
.addMatcher<FulfilledAction>(
(action) => action.type.endsWith("/fulfilled"),
(state, action) => {
state[action.meta.requestId] = "fulfilled";
}
);
});
```
*/
addMatcher<A>(matcher: TypeGuard<A> | ((action: any) => boolean), reducer: CaseReducer<State, A extends AnyAction ? A : A & AnyAction>): Omit<ActionReducerMapBuilder<State>, 'addCase'>;
/**
* Adds a "default case" reducer that is executed if no case reducer and no matcher
* reducer was executed for this action.
* @param reducer - The fallback "default case" reducer function.
*
* @example
```ts
import { createReducer } from '@reduxjs/toolkit'
const initialState = { otherActions: 0 }
const reducer = createReducer(initialState, builder => {
builder
// .addCase(...)
// .addMatcher(...)
.addDefaultCase((state, action) => {
state.otherActions++
})
})
```
*/
addDefaultCase(reducer: CaseReducer<State, AnyAction>): {};
}
export declare function executeReducerBuilderCallback<S>(builderCallback: (builder: ActionReducerMapBuilder<S>) => void): [
CaseReducers<S, any>,
ActionMatcherDescriptionCollection<S>,
CaseReducer<S, AnyAction> | undefined
];

@ -0,0 +1,171 @@
import type { ActionFromMatcher, Matcher, UnionToIntersection } from './tsHelpers';
import type { AsyncThunk, AsyncThunkFulfilledActionCreator, AsyncThunkPendingActionCreator, AsyncThunkRejectedActionCreator } from './createAsyncThunk';
/** @public */
export declare type ActionMatchingAnyOf<Matchers extends [...Matcher<any>[]]> = ActionFromMatcher<Matchers[number]>;
/** @public */
export declare type ActionMatchingAllOf<Matchers extends [...Matcher<any>[]]> = UnionToIntersection<ActionMatchingAnyOf<Matchers>>;
/**
* A higher-order function that returns a function that may be used to check
* whether an action matches any one of the supplied type guards or action
* creators.
*
* @param matchers The type guards or action creators to match against.
*
* @public
*/
export declare function isAnyOf<Matchers extends [...Matcher<any>[]]>(...matchers: Matchers): (action: any) => action is ActionFromMatcher<Matchers[number]>;
/**
* A higher-order function that returns a function that may be used to check
* whether an action matches all of the supplied type guards or action
* creators.
*
* @param matchers The type guards or action creators to match against.
*
* @public
*/
export declare function isAllOf<Matchers extends [...Matcher<any>[]]>(...matchers: Matchers): (action: any) => action is UnionToIntersection<ActionFromMatcher<Matchers[number]>>;
/**
* @param action A redux action
* @param validStatus An array of valid meta.requestStatus values
*
* @internal
*/
export declare function hasExpectedRequestMetadata(action: any, validStatus: readonly string[]): boolean;
export declare type UnknownAsyncThunkPendingAction = ReturnType<AsyncThunkPendingActionCreator<unknown>>;
export declare type PendingActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['pending']>;
/**
* A higher-order function that returns a function that may be used to check
* whether an action was created by an async thunk action creator, and that
* the action is pending.
*
* @public
*/
export declare function isPending(): (action: any) => action is UnknownAsyncThunkPendingAction;
/**
* A higher-order function that returns a function that may be used to check
* whether an action belongs to one of the provided async thunk action creators,
* and that the action is pending.
*
* @param asyncThunks (optional) The async thunk action creators to match against.
*
* @public
*/
export declare function isPending<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is PendingActionFromAsyncThunk<AsyncThunks[number]>;
/**
* Tests if `action` is a pending thunk action
* @public
*/
export declare function isPending(action: any): action is UnknownAsyncThunkPendingAction;
export declare type UnknownAsyncThunkRejectedAction = ReturnType<AsyncThunkRejectedActionCreator<unknown, unknown>>;
export declare type RejectedActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['rejected']>;
/**
* A higher-order function that returns a function that may be used to check
* whether an action was created by an async thunk action creator, and that
* the action is rejected.
*
* @public
*/
export declare function isRejected(): (action: any) => action is UnknownAsyncThunkRejectedAction;
/**
* A higher-order function that returns a function that may be used to check
* whether an action belongs to one of the provided async thunk action creators,
* and that the action is rejected.
*
* @param asyncThunks (optional) The async thunk action creators to match against.
*
* @public
*/
export declare function isRejected<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is RejectedActionFromAsyncThunk<AsyncThunks[number]>;
/**
* Tests if `action` is a rejected thunk action
* @public
*/
export declare function isRejected(action: any): action is UnknownAsyncThunkRejectedAction;
export declare type UnknownAsyncThunkRejectedWithValueAction = ReturnType<AsyncThunkRejectedActionCreator<unknown, unknown>>;
export declare type RejectedWithValueActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['rejected']> & (T extends AsyncThunk<any, any, {
rejectValue: infer RejectedValue;
}> ? {
payload: RejectedValue;
} : unknown);
/**
* A higher-order function that returns a function that may be used to check
* whether an action was created by an async thunk action creator, and that
* the action is rejected with value.
*
* @public
*/
export declare function isRejectedWithValue(): (action: any) => action is UnknownAsyncThunkRejectedAction;
/**
* A higher-order function that returns a function that may be used to check
* whether an action belongs to one of the provided async thunk action creators,
* and that the action is rejected with value.
*
* @param asyncThunks (optional) The async thunk action creators to match against.
*
* @public
*/
export declare function isRejectedWithValue<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is RejectedWithValueActionFromAsyncThunk<AsyncThunks[number]>;
/**
* Tests if `action` is a rejected thunk action with value
* @public
*/
export declare function isRejectedWithValue(action: any): action is UnknownAsyncThunkRejectedAction;
export declare type UnknownAsyncThunkFulfilledAction = ReturnType<AsyncThunkFulfilledActionCreator<unknown, unknown>>;
export declare type FulfilledActionFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['fulfilled']>;
/**
* A higher-order function that returns a function that may be used to check
* whether an action was created by an async thunk action creator, and that
* the action is fulfilled.
*
* @public
*/
export declare function isFulfilled(): (action: any) => action is UnknownAsyncThunkFulfilledAction;
/**
* A higher-order function that returns a function that may be used to check
* whether an action belongs to one of the provided async thunk action creators,
* and that the action is fulfilled.
*
* @param asyncThunks (optional) The async thunk action creators to match against.
*
* @public
*/
export declare function isFulfilled<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is FulfilledActionFromAsyncThunk<AsyncThunks[number]>;
/**
* Tests if `action` is a fulfilled thunk action
* @public
*/
export declare function isFulfilled(action: any): action is UnknownAsyncThunkFulfilledAction;
export declare type UnknownAsyncThunkAction = UnknownAsyncThunkPendingAction | UnknownAsyncThunkRejectedAction | UnknownAsyncThunkFulfilledAction;
export declare type AnyAsyncThunk = {
pending: {
match: (action: any) => action is any;
};
fulfilled: {
match: (action: any) => action is any;
};
rejected: {
match: (action: any) => action is any;
};
};
export declare type ActionsFromAsyncThunk<T extends AnyAsyncThunk> = ActionFromMatcher<T['pending']> | ActionFromMatcher<T['fulfilled']> | ActionFromMatcher<T['rejected']>;
/**
* A higher-order function that returns a function that may be used to check
* whether an action was created by an async thunk action creator.
*
* @public
*/
export declare function isAsyncThunkAction(): (action: any) => action is UnknownAsyncThunkAction;
/**
* A higher-order function that returns a function that may be used to check
* whether an action belongs to one of the provided async thunk action creators.
*
* @param asyncThunks (optional) The async thunk action creators to match against.
*
* @public
*/
export declare function isAsyncThunkAction<AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]]>(...asyncThunks: AsyncThunks): (action: any) => action is ActionsFromAsyncThunk<AsyncThunks[number]>;
/**
* Tests if `action` is a thunk action
* @public
*/
export declare function isAsyncThunkAction(action: any): action is UnknownAsyncThunkAction;

@ -0,0 +1,5 @@
/**
*
* @public
*/
export declare let nanoid: (size?: number) => string;

@ -0,0 +1,5 @@
export declare class HandledError {
readonly value: any;
readonly meta: any;
constructor(value: any, meta?: any);
}

@ -0,0 +1,41 @@
import type { EndpointDefinitions, EndpointBuilder, EndpointDefinition, ReplaceTagTypes } from './endpointDefinitions';
import type { UnionToIntersection, NoInfer, WithRequiredProp } from './tsHelpers';
import type { CoreModule } from './core/module';
import type { CreateApiOptions } from './createApi';
import type { BaseQueryFn } from './baseQueryTypes';
import type { CombinedState } from './core/apiState';
import type { AnyAction } from '@reduxjs/toolkit';
export interface ApiModules<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string> {
}
export declare type ModuleName = keyof ApiModules<any, any, any, any>;
export declare type Module<Name extends ModuleName> = {
name: Name;
init<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string>(api: Api<BaseQuery, EndpointDefinitions, ReducerPath, TagTypes, ModuleName>, options: WithRequiredProp<CreateApiOptions<BaseQuery, Definitions, ReducerPath, TagTypes>, 'reducerPath' | 'serializeQueryArgs' | 'keepUnusedDataFor' | 'refetchOnMountOrArgChange' | 'refetchOnFocus' | 'refetchOnReconnect' | 'tagTypes'>, context: ApiContext<Definitions>): {
injectEndpoint(endpointName: string, definition: EndpointDefinition<any, any, any, any>): void;
};
};
export interface ApiContext<Definitions extends EndpointDefinitions> {
apiUid: string;
endpointDefinitions: Definitions;
batch(cb: () => void): void;
extractRehydrationInfo: (action: AnyAction) => CombinedState<any, any, any> | undefined;
hasRehydrationInfo: (action: AnyAction) => boolean;
}
export declare type Api<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string, Enhancers extends ModuleName = CoreModule> = UnionToIntersection<ApiModules<BaseQuery, Definitions, ReducerPath, TagTypes>[Enhancers]> & {
/**
* A function to inject the endpoints into the original API, but also give you that same API with correct types for these endpoints back. Useful with code-splitting.
*/
injectEndpoints<NewDefinitions extends EndpointDefinitions>(_: {
endpoints: (build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>) => NewDefinitions;
overrideExisting?: boolean;
}): Api<BaseQuery, Definitions & NewDefinitions, ReducerPath, TagTypes, Enhancers>;
/**
*A function to enhance a generated API with additional information. Useful with code-generation.
*/
enhanceEndpoints<NewTagTypes extends string = never>(_: {
addTagTypes?: readonly NewTagTypes[];
endpoints?: ReplaceTagTypes<Definitions, TagTypes | NoInfer<NewTagTypes>> extends infer NewDefinitions ? {
[K in keyof NewDefinitions]?: Partial<NewDefinitions[K]> | ((definition: NewDefinitions[K]) => void);
} : never;
}): Api<BaseQuery, ReplaceTagTypes<Definitions, TagTypes | NewTagTypes>, ReducerPath, TagTypes | NewTagTypes, Enhancers>;
};

@ -0,0 +1,40 @@
import type { ThunkDispatch } from '@reduxjs/toolkit';
import type { MaybePromise, UnwrapPromise } from './tsHelpers';
export interface BaseQueryApi {
signal: AbortSignal;
abort: (reason?: string) => void;
dispatch: ThunkDispatch<any, any, any>;
getState: () => unknown;
extra: unknown;
endpoint: string;
type: 'query' | 'mutation';
/**
* Only available for queries: indicates if a query has been forced,
* i.e. it would have been fetched even if there would already be a cache entry
* (this does not mean that there is already a cache entry though!)
*
* This can be used to for example add a `Cache-Control: no-cache` header for
* invalidated queries.
*/
forced?: boolean;
}
export declare type QueryReturnValue<T = unknown, E = unknown, M = unknown> = {
error: E;
data?: undefined;
meta?: M;
} | {
error?: undefined;
data: T;
meta?: M;
};
export declare type BaseQueryFn<Args = any, Result = unknown, Error = unknown, DefinitionExtraOptions = {}, Meta = {}> = (args: Args, api: BaseQueryApi, extraOptions: DefinitionExtraOptions) => MaybePromise<QueryReturnValue<Result, Error, Meta>>;
export declare type BaseQueryEnhancer<AdditionalArgs = unknown, AdditionalDefinitionExtraOptions = unknown, Config = void> = <BaseQuery extends BaseQueryFn>(baseQuery: BaseQuery, config: Config) => BaseQueryFn<BaseQueryArg<BaseQuery> & AdditionalArgs, BaseQueryResult<BaseQuery>, BaseQueryError<BaseQuery>, BaseQueryExtraOptions<BaseQuery> & AdditionalDefinitionExtraOptions, NonNullable<BaseQueryMeta<BaseQuery>>>;
export declare type BaseQueryResult<BaseQuery extends BaseQueryFn> = UnwrapPromise<ReturnType<BaseQuery>> extends infer Unwrapped ? Unwrapped extends {
data: any;
} ? Unwrapped['data'] : never : never;
export declare type BaseQueryMeta<BaseQuery extends BaseQueryFn> = UnwrapPromise<ReturnType<BaseQuery>>['meta'];
export declare type BaseQueryError<BaseQuery extends BaseQueryFn> = Exclude<UnwrapPromise<ReturnType<BaseQuery>>, {
error?: undefined;
}>['error'];
export declare type BaseQueryArg<T extends (arg: any, ...args: any[]) => any> = T extends (arg: infer A, ...args: any[]) => any ? A : any;
export declare type BaseQueryExtraOptions<BaseQuery extends BaseQueryFn> = Parameters<BaseQuery>[2];

@ -0,0 +1,198 @@
import type { SerializedError } from '@reduxjs/toolkit';
import type { BaseQueryError } from '../baseQueryTypes';
import type { QueryDefinition, MutationDefinition, EndpointDefinitions, BaseEndpointDefinition, ResultTypeFrom, QueryArgFrom } from '../endpointDefinitions';
import type { Id, WithRequiredProp } from '../tsHelpers';
export declare type QueryCacheKey = string & {
_type: 'queryCacheKey';
};
export declare type QuerySubstateIdentifier = {
queryCacheKey: QueryCacheKey;
};
export declare type MutationSubstateIdentifier = {
requestId: string;
fixedCacheKey?: string;
} | {
requestId?: string;
fixedCacheKey: string;
};
export declare type RefetchConfigOptions = {
refetchOnMountOrArgChange: boolean | number;
refetchOnReconnect: boolean;
refetchOnFocus: boolean;
};
/**
* Strings describing the query state at any given time.
*/
export declare enum QueryStatus {
uninitialized = "uninitialized",
pending = "pending",
fulfilled = "fulfilled",
rejected = "rejected"
}
export declare type RequestStatusFlags = {
status: QueryStatus.uninitialized;
isUninitialized: true;
isLoading: false;
isSuccess: false;
isError: false;
} | {
status: QueryStatus.pending;
isUninitialized: false;
isLoading: true;
isSuccess: false;
isError: false;
} | {
status: QueryStatus.fulfilled;
isUninitialized: false;
isLoading: false;
isSuccess: true;
isError: false;
} | {
status: QueryStatus.rejected;
isUninitialized: false;
isLoading: false;
isSuccess: false;
isError: true;
};
export declare function getRequestStatusFlags(status: QueryStatus): RequestStatusFlags;
export declare type SubscriptionOptions = {
/**
* How frequently to automatically re-fetch data (in milliseconds). Defaults to `0` (off).
*/
pollingInterval?: number;
/**
* Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.
*
* If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
*
* Note: requires [`setupListeners`](./setupListeners) to have been called.
*/
refetchOnReconnect?: boolean;
/**
* Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after the application window regains focus.
*
* If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
*
* Note: requires [`setupListeners`](./setupListeners) to have been called.
*/
refetchOnFocus?: boolean;
};
export declare type Subscribers = {
[requestId: string]: SubscriptionOptions;
};
export declare type QueryKeys<Definitions extends EndpointDefinitions> = {
[K in keyof Definitions]: Definitions[K] extends QueryDefinition<any, any, any, any> ? K : never;
}[keyof Definitions];
export declare type MutationKeys<Definitions extends EndpointDefinitions> = {
[K in keyof Definitions]: Definitions[K] extends MutationDefinition<any, any, any, any> ? K : never;
}[keyof Definitions];
declare type BaseQuerySubState<D extends BaseEndpointDefinition<any, any, any>> = {
/**
* The argument originally passed into the hook or `initiate` action call
*/
originalArgs: QueryArgFrom<D>;
/**
* A unique ID associated with the request
*/
requestId: string;
/**
* The received data from the query
*/
data?: ResultTypeFrom<D>;
/**
* The received error if applicable
*/
error?: SerializedError | (D extends QueryDefinition<any, infer BaseQuery, any, any> ? BaseQueryError<BaseQuery> : never);
/**
* The name of the endpoint associated with the query
*/
endpointName: string;
/**
* Time that the latest query started
*/
startedTimeStamp: number;
/**
* Time that the latest query was fulfilled
*/
fulfilledTimeStamp?: number;
};
export declare type QuerySubState<D extends BaseEndpointDefinition<any, any, any>> = Id<({
status: QueryStatus.fulfilled;
} & WithRequiredProp<BaseQuerySubState<D>, 'data' | 'fulfilledTimeStamp'> & {
error: undefined;
}) | ({
status: QueryStatus.pending;
} & BaseQuerySubState<D>) | ({
status: QueryStatus.rejected;
} & WithRequiredProp<BaseQuerySubState<D>, 'error'>) | {
status: QueryStatus.uninitialized;
originalArgs?: undefined;
data?: undefined;
error?: undefined;
requestId?: undefined;
endpointName?: string;
startedTimeStamp?: undefined;
fulfilledTimeStamp?: undefined;
}>;
declare type BaseMutationSubState<D extends BaseEndpointDefinition<any, any, any>> = {
requestId: string;
data?: ResultTypeFrom<D>;
error?: SerializedError | (D extends MutationDefinition<any, infer BaseQuery, any, any> ? BaseQueryError<BaseQuery> : never);
endpointName: string;
startedTimeStamp: number;
fulfilledTimeStamp?: number;
};
export declare type MutationSubState<D extends BaseEndpointDefinition<any, any, any>> = (({
status: QueryStatus.fulfilled;
} & WithRequiredProp<BaseMutationSubState<D>, 'data' | 'fulfilledTimeStamp'>) & {
error: undefined;
}) | (({
status: QueryStatus.pending;
} & BaseMutationSubState<D>) & {
data?: undefined;
}) | ({
status: QueryStatus.rejected;
} & WithRequiredProp<BaseMutationSubState<D>, 'error'>) | {
requestId?: undefined;
status: QueryStatus.uninitialized;
data?: undefined;
error?: undefined;
endpointName?: string;
startedTimeStamp?: undefined;
fulfilledTimeStamp?: undefined;
};
export declare type CombinedState<D extends EndpointDefinitions, E extends string, ReducerPath extends string> = {
queries: QueryState<D>;
mutations: MutationState<D>;
provided: InvalidationState<E>;
subscriptions: SubscriptionState;
config: ConfigState<ReducerPath>;
};
export declare type InvalidationState<TagTypes extends string> = {
[_ in TagTypes]: {
[id: string]: Array<QueryCacheKey>;
[id: number]: Array<QueryCacheKey>;
};
};
export declare type QueryState<D extends EndpointDefinitions> = {
[queryCacheKey: string]: QuerySubState<D[string]> | undefined;
};
export declare type SubscriptionState = {
[queryCacheKey: string]: Subscribers | undefined;
};
export declare type ConfigState<ReducerPath> = RefetchConfigOptions & {
reducerPath: ReducerPath;
online: boolean;
focused: boolean;
middlewareRegistered: boolean | 'conflict';
} & ModifiableConfigState;
export declare type ModifiableConfigState = {
keepUnusedDataFor: number;
} & RefetchConfigOptions;
export declare type MutationState<D extends EndpointDefinitions> = {
[requestId: string]: MutationSubState<D[string]> | undefined;
};
export declare type RootState<Definitions extends EndpointDefinitions, TagTypes extends string, ReducerPath extends string> = {
[P in ReducerPath]: CombinedState<Definitions, TagTypes, P>;
};
export {};

@ -0,0 +1,152 @@
import type { EndpointDefinitions, QueryDefinition, MutationDefinition, QueryArgFrom, ResultTypeFrom } from '../endpointDefinitions';
import type { QueryThunk, MutationThunk, QueryThunkArg } from './buildThunks';
import type { AnyAction, ThunkAction, SerializedError } from '@reduxjs/toolkit';
import type { SubscriptionOptions } from './apiState';
import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';
import type { Api, ApiContext } from '../apiTypes';
import type { BaseQueryError, QueryReturnValue } from '../baseQueryTypes';
import type { QueryResultSelectorResult } from './buildSelectors';
import type { Dispatch } from 'redux';
declare module './module' {
interface ApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> {
initiate: StartQueryActionCreator<Definition>;
}
interface ApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> {
initiate: StartMutationActionCreator<Definition>;
}
}
export declare const forceQueryFnSymbol: unique symbol;
export declare const isUpsertQuery: (arg: QueryThunkArg) => boolean;
export interface StartQueryActionCreatorOptions {
subscribe?: boolean;
forceRefetch?: boolean | number;
subscriptionOptions?: SubscriptionOptions;
[forceQueryFnSymbol]?: () => QueryReturnValue;
}
declare type StartQueryActionCreator<D extends QueryDefinition<any, any, any, any, any>> = (arg: QueryArgFrom<D>, options?: StartQueryActionCreatorOptions) => ThunkAction<QueryActionCreatorResult<D>, any, any, AnyAction>;
export declare type QueryActionCreatorResult<D extends QueryDefinition<any, any, any, any>> = Promise<QueryResultSelectorResult<D>> & {
arg: QueryArgFrom<D>;
requestId: string;
subscriptionOptions: SubscriptionOptions | undefined;
abort(): void;
unwrap(): Promise<ResultTypeFrom<D>>;
unsubscribe(): void;
refetch(): QueryActionCreatorResult<D>;
updateSubscriptionOptions(options: SubscriptionOptions): void;
queryCacheKey: string;
};
declare type StartMutationActionCreator<D extends MutationDefinition<any, any, any, any>> = (arg: QueryArgFrom<D>, options?: {
/**
* If this mutation should be tracked in the store.
* If you just want to manually trigger this mutation using `dispatch` and don't care about the
* result, state & potential errors being held in store, you can set this to false.
* (defaults to `true`)
*/
track?: boolean;
fixedCacheKey?: string;
}) => ThunkAction<MutationActionCreatorResult<D>, any, any, AnyAction>;
export declare type MutationActionCreatorResult<D extends MutationDefinition<any, any, any, any>> = Promise<{
data: ResultTypeFrom<D>;
} | {
error: Exclude<BaseQueryError<D extends MutationDefinition<any, infer BaseQuery, any, any> ? BaseQuery : never>, undefined> | SerializedError;
}> & {
/** @internal */
arg: {
/**
* The name of the given endpoint for the mutation
*/
endpointName: string;
/**
* The original arguments supplied to the mutation call
*/
originalArgs: QueryArgFrom<D>;
/**
* Whether the mutation is being tracked in the store.
*/
track?: boolean;
fixedCacheKey?: string;
};
/**
* A unique string generated for the request sequence
*/
requestId: string;
/**
* A method to cancel the mutation promise. Note that this is not intended to prevent the mutation
* that was fired off from reaching the server, but only to assist in handling the response.
*
* Calling `abort()` prior to the promise resolving will force it to reach the error state with
* the serialized error:
* `{ name: 'AbortError', message: 'Aborted' }`
*
* @example
* ```ts
* const [updateUser] = useUpdateUserMutation();
*
* useEffect(() => {
* const promise = updateUser(id);
* promise
* .unwrap()
* .catch((err) => {
* if (err.name === 'AbortError') return;
* // else handle the unexpected error
* })
*
* return () => {
* promise.abort();
* }
* }, [id, updateUser])
* ```
*/
abort(): void;
/**
* Unwraps a mutation call to provide the raw response/error.
*
* @remarks
* If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().
*
* @example
* ```ts
* // codeblock-meta title="Using .unwrap"
* addPost({ id: 1, name: 'Example' })
* .unwrap()
* .then((payload) => console.log('fulfilled', payload))
* .catch((error) => console.error('rejected', error));
* ```
*
* @example
* ```ts
* // codeblock-meta title="Using .unwrap with async await"
* try {
* const payload = await addPost({ id: 1, name: 'Example' }).unwrap();
* console.log('fulfilled', payload)
* } catch (error) {
* console.error('rejected', error);
* }
* ```
*/
unwrap(): Promise<ResultTypeFrom<D>>;
/**
* A method to manually unsubscribe from the mutation call, meaning it will be removed from cache after the usual caching grace period.
The value returned by the hook will reset to `isUninitialized` afterwards.
*/
reset(): void;
/** @deprecated has been renamed to `reset` */
unsubscribe(): void;
};
export declare function buildInitiate({ serializeQueryArgs, queryThunk, mutationThunk, api, context, }: {
serializeQueryArgs: InternalSerializeQueryArgs;
queryThunk: QueryThunk;
mutationThunk: MutationThunk;
api: Api<any, EndpointDefinitions, any, any>;
context: ApiContext<EndpointDefinitions>;
}): {
buildInitiateQuery: (endpointName: string, endpointDefinition: QueryDefinition<any, any, any, any>) => StartQueryActionCreator<any>;
buildInitiateMutation: (endpointName: string) => StartMutationActionCreator<any>;
getRunningQueryThunk: (endpointName: string, queryArgs: any) => (dispatch: Dispatch) => QueryActionCreatorResult<never> | undefined;
getRunningMutationThunk: (_endpointName: string, fixedCacheKeyOrRequestId: string) => (dispatch: Dispatch) => MutationActionCreatorResult<never> | undefined;
getRunningQueriesThunk: () => (dispatch: Dispatch) => QueryActionCreatorResult<any>[];
getRunningMutationsThunk: () => (dispatch: Dispatch) => MutationActionCreatorResult<any>[];
getRunningOperationPromises: () => (QueryActionCreatorResult<any> | MutationActionCreatorResult<any>)[];
removalWarning: () => never;
};
export {};

@ -0,0 +1,5 @@
import type { InternalHandlerBuilder } from './types';
export declare const buildBatchedActionsHandler: InternalHandlerBuilder<[
actionShouldContinue: boolean,
subscriptionExists: boolean
]>;

@ -0,0 +1,16 @@
import type { BaseQueryFn } from '../../baseQueryTypes';
import type { InternalHandlerBuilder } from './types';
export declare type ReferenceCacheCollection = never;
declare module '../../endpointDefinitions' {
interface QueryExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> {
/**
* Overrides the api-wide definition of `keepUnusedDataFor` for this endpoint only. _(This value is in seconds.)_
*
* This is how long RTK Query will keep your data cached for **after** the last component unsubscribes. For example, if you query an endpoint, then unmount the component, then mount another component that makes the same request within the given time frame, the most recent value will be served from the cache.
*/
keepUnusedDataFor?: number;
}
}
export declare const THIRTY_TWO_BIT_MAX_INT = 2147483647;
export declare const THIRTY_TWO_BIT_MAX_TIMER_SECONDS: number;
export declare const buildCacheCollectionHandler: InternalHandlerBuilder;

@ -0,0 +1,95 @@
import type { AnyAction } from 'redux';
import type { ThunkDispatch } from 'redux-thunk';
import type { BaseQueryFn, BaseQueryMeta } from '../../baseQueryTypes';
import type { RootState } from '../apiState';
import type { MutationResultSelectorResult, QueryResultSelectorResult } from '../buildSelectors';
import type { PatchCollection, Recipe } from '../buildThunks';
import type { InternalHandlerBuilder, PromiseWithKnownReason } from './types';
export declare type ReferenceCacheLifecycle = never;
declare module '../../endpointDefinitions' {
interface QueryBaseLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends LifecycleApi<ReducerPath> {
/**
* Gets the current value of this cache entry.
*/
getCacheEntry(): QueryResultSelectorResult<{
type: DefinitionType.query;
} & BaseEndpointDefinition<QueryArg, BaseQuery, ResultType>>;
/**
* Updates the current cache entry value.
* For documentation see `api.util.updateQueryData`.
*/
updateCachedData(updateRecipe: Recipe<ResultType>): PatchCollection;
}
interface MutationBaseLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends LifecycleApi<ReducerPath> {
/**
* Gets the current value of this cache entry.
*/
getCacheEntry(): MutationResultSelectorResult<{
type: DefinitionType.mutation;
} & BaseEndpointDefinition<QueryArg, BaseQuery, ResultType>>;
}
interface LifecycleApi<ReducerPath extends string = string> {
/**
* The dispatch method for the store
*/
dispatch: ThunkDispatch<any, any, AnyAction>;
/**
* A method to get the current state
*/
getState(): RootState<any, any, ReducerPath>;
/**
* `extra` as provided as `thunk.extraArgument` to the `configureStore` `getDefaultMiddleware` option.
*/
extra: unknown;
/**
* A unique ID generated for the mutation
*/
requestId: string;
}
interface CacheLifecyclePromises<ResultType = unknown, MetaType = unknown> {
/**
* Promise that will resolve with the first value for this cache key.
* This allows you to `await` until an actual value is in cache.
*
* If the cache entry is removed from the cache before any value has ever
* been resolved, this Promise will reject with
* `new Error('Promise never resolved before cacheEntryRemoved.')`
* to prevent memory leaks.
* You can just re-throw that error (or not handle it at all) -
* it will be caught outside of `cacheEntryAdded`.
*
* If you don't interact with this promise, it will not throw.
*/
cacheDataLoaded: PromiseWithKnownReason<{
/**
* The (transformed) query result.
*/
data: ResultType;
/**
* The `meta` returned by the `baseQuery`
*/
meta: MetaType;
}, typeof neverResolvedError>;
/**
* Promise that allows you to wait for the point in time when the cache entry
* has been removed from the cache, by not being used/subscribed to any more
* in the application for too long or by dispatching `api.util.resetApiState`.
*/
cacheEntryRemoved: Promise<void>;
}
interface QueryCacheLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>, CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>> {
}
interface MutationCacheLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends MutationBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>, CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>> {
}
interface QueryExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> {
onCacheEntryAdded?(arg: QueryArg, api: QueryCacheLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;
}
interface MutationExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> {
onCacheEntryAdded?(arg: QueryArg, api: MutationCacheLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;
}
}
declare const neverResolvedError: Error & {
message: 'Promise never resolved before cacheEntryRemoved.';
};
export declare const buildCacheLifecycleHandler: InternalHandlerBuilder;
export {};

@ -0,0 +1,2 @@
import type { InternalHandlerBuilder } from './types';
export declare const buildDevCheckHandler: InternalHandlerBuilder;

@ -0,0 +1,10 @@
import type { AnyAction, Middleware, ThunkDispatch } from '@reduxjs/toolkit';
import type { EndpointDefinitions, FullTagDescription } from '../../endpointDefinitions';
import type { RootState } from '../apiState';
import type { BuildMiddlewareInput } from './types';
export declare function buildMiddleware<Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string>(input: BuildMiddlewareInput<Definitions, ReducerPath, TagTypes>): {
middleware: Middleware<{}, RootState<Definitions, string, ReducerPath>, ThunkDispatch<any, any, AnyAction>>;
actions: {
invalidateTags: import("@reduxjs/toolkit").ActionCreatorWithPayload<(TagTypes | FullTagDescription<TagTypes>)[], string>;
};
};

@ -0,0 +1,2 @@
import type { InternalHandlerBuilder } from './types';
export declare const buildInvalidationByTagsHandler: InternalHandlerBuilder;

@ -0,0 +1,2 @@
import type { InternalHandlerBuilder } from './types';
export declare const buildPollingHandler: InternalHandlerBuilder;

@ -0,0 +1,142 @@
import type { BaseQueryError, BaseQueryFn, BaseQueryMeta } from '../../baseQueryTypes';
import type { PromiseWithKnownReason, InternalHandlerBuilder } from './types';
export declare type ReferenceQueryLifecycle = never;
declare module '../../endpointDefinitions' {
interface QueryLifecyclePromises<ResultType, BaseQuery extends BaseQueryFn> {
/**
* Promise that will resolve with the (transformed) query result.
*
* If the query fails, this promise will reject with the error.
*
* This allows you to `await` for the query to finish.
*
* If you don't interact with this promise, it will not throw.
*/
queryFulfilled: PromiseWithKnownReason<{
/**
* The (transformed) query result.
*/
data: ResultType;
/**
* The `meta` returned by the `baseQuery`
*/
meta: BaseQueryMeta<BaseQuery>;
}, QueryFulfilledRejectionReason<BaseQuery>>;
}
type QueryFulfilledRejectionReason<BaseQuery extends BaseQueryFn> = {
error: BaseQueryError<BaseQuery>;
/**
* If this is `false`, that means this error was returned from the `baseQuery` or `queryFn` in a controlled manner.
*/
isUnhandledError: false;
/**
* The `meta` returned by the `baseQuery`
*/
meta: BaseQueryMeta<BaseQuery>;
} | {
error: unknown;
meta?: undefined;
/**
* If this is `true`, that means that this error is the result of `baseQueryFn`, `queryFn`, `transformResponse` or `transformErrorResponse` throwing an error instead of handling it properly.
* There can not be made any assumption about the shape of `error`.
*/
isUnhandledError: true;
};
interface QueryExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> {
/**
* A function that is called when the individual query is started. The function is called with a lifecycle api object containing properties such as `queryFulfilled`, allowing code to be run when a query is started, when it succeeds, and when it fails (i.e. throughout the lifecycle of an individual query/mutation call).
*
* Can be used to perform side-effects throughout the lifecycle of the query.
*
* @example
* ```ts
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
* import { messageCreated } from './notificationsSlice
* export interface Post {
* id: number
* name: string
* }
*
* const api = createApi({
* baseQuery: fetchBaseQuery({
* baseUrl: '/',
* }),
* endpoints: (build) => ({
* getPost: build.query<Post, number>({
* query: (id) => `post/${id}`,
* async onQueryStarted(id, { dispatch, queryFulfilled }) {
* // `onStart` side-effect
* dispatch(messageCreated('Fetching posts...'))
* try {
* const { data } = await queryFulfilled
* // `onSuccess` side-effect
* dispatch(messageCreated('Posts received!'))
* } catch (err) {
* // `onError` side-effect
* dispatch(messageCreated('Error fetching posts!'))
* }
* }
* }),
* }),
* })
* ```
*/
onQueryStarted?(arg: QueryArg, api: QueryLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;
}
interface MutationExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> {
/**
* A function that is called when the individual mutation is started. The function is called with a lifecycle api object containing properties such as `queryFulfilled`, allowing code to be run when a query is started, when it succeeds, and when it fails (i.e. throughout the lifecycle of an individual query/mutation call).
*
* Can be used for `optimistic updates`.
*
* @example
*
* ```ts
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
* export interface Post {
* id: number
* name: string
* }
*
* const api = createApi({
* baseQuery: fetchBaseQuery({
* baseUrl: '/',
* }),
* tagTypes: ['Post'],
* endpoints: (build) => ({
* getPost: build.query<Post, number>({
* query: (id) => `post/${id}`,
* providesTags: ['Post'],
* }),
* updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({
* query: ({ id, ...patch }) => ({
* url: `post/${id}`,
* method: 'PATCH',
* body: patch,
* }),
* invalidatesTags: ['Post'],
* async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {
* const patchResult = dispatch(
* api.util.updateQueryData('getPost', id, (draft) => {
* Object.assign(draft, patch)
* })
* )
* try {
* await queryFulfilled
* } catch {
* patchResult.undo()
* }
* },
* }),
* }),
* })
* ```
*/
onQueryStarted?(arg: QueryArg, api: MutationLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>): Promise<void> | void;
}
interface QueryLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>, QueryLifecyclePromises<ResultType, BaseQuery> {
}
interface MutationLifecycleApi<QueryArg, BaseQuery extends BaseQueryFn, ResultType, ReducerPath extends string = string> extends MutationBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>, QueryLifecyclePromises<ResultType, BaseQuery> {
}
}
export declare const buildQueryLifecycleHandler: InternalHandlerBuilder;

@ -0,0 +1,54 @@
import type { AnyAction, AsyncThunkAction, Dispatch, Middleware, MiddlewareAPI, ThunkDispatch } from '@reduxjs/toolkit';
import type { Api, ApiContext } from '../../apiTypes';
import type { AssertTagTypes, EndpointDefinitions } from '../../endpointDefinitions';
import type { QueryStatus, QuerySubState, RootState, SubscriptionState } from '../apiState';
import type { MutationThunk, QueryThunk, QueryThunkArg, ThunkResult } from '../buildThunks';
export declare type QueryStateMeta<T> = Record<string, undefined | T>;
export declare type TimeoutId = ReturnType<typeof setTimeout>;
export interface InternalMiddlewareState {
currentSubscriptions: SubscriptionState;
}
export interface BuildMiddlewareInput<Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string> {
reducerPath: ReducerPath;
context: ApiContext<Definitions>;
queryThunk: QueryThunk;
mutationThunk: MutationThunk;
api: Api<any, Definitions, ReducerPath, TagTypes>;
assertTagType: AssertTagTypes;
}
export declare type SubMiddlewareApi = MiddlewareAPI<ThunkDispatch<any, any, AnyAction>, RootState<EndpointDefinitions, string, string>>;
export interface BuildSubMiddlewareInput extends BuildMiddlewareInput<EndpointDefinitions, string, string> {
internalState: InternalMiddlewareState;
refetchQuery(querySubState: Exclude<QuerySubState<any>, {
status: QueryStatus.uninitialized;
}>, queryCacheKey: string, override?: Partial<QueryThunkArg>): AsyncThunkAction<ThunkResult, QueryThunkArg, {}>;
}
export declare type SubMiddlewareBuilder = (input: BuildSubMiddlewareInput) => Middleware<{}, RootState<EndpointDefinitions, string, string>, ThunkDispatch<any, any, AnyAction>>;
export declare type ApiMiddlewareInternalHandler<ReturnType = void> = (action: AnyAction, mwApi: SubMiddlewareApi & {
next: Dispatch<AnyAction>;
}, prevState: RootState<EndpointDefinitions, string, string>) => ReturnType;
export declare type InternalHandlerBuilder<ReturnType = void> = (input: BuildSubMiddlewareInput) => ApiMiddlewareInternalHandler<ReturnType>;
export interface PromiseConstructorWithKnownReason {
/**
* Creates a new Promise with a known rejection reason.
* @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 <T, R>(executor: (resolve: (value: T | PromiseLike<T>) => void, reject: (reason?: R) => void) => void): PromiseWithKnownReason<T, R>;
}
export interface PromiseWithKnownReason<T, R> extends Omit<Promise<T>, 'then' | 'catch'> {
/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
* @param onfulfilled The callback to execute when the Promise is resolved.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: R) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;
/**
* Attaches a callback for only the rejection of the Promise.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of the callback.
*/
catch<TResult = never>(onrejected?: ((reason: R) => TResult | PromiseLike<TResult>) | undefined | null): Promise<T | TResult>;
}

@ -0,0 +1,2 @@
import type { InternalHandlerBuilder } from './types';
export declare const buildWindowEventHandler: InternalHandlerBuilder;

@ -0,0 +1,63 @@
import type { MutationSubState, QuerySubState, RootState as _RootState, RequestStatusFlags, QueryCacheKey } from './apiState';
import type { EndpointDefinitions, QueryDefinition, MutationDefinition, QueryArgFrom, TagTypesFrom, ReducerPathFrom, TagDescription } from '../endpointDefinitions';
import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';
export declare type SkipToken = typeof skipToken;
/**
* Can be passed into `useQuery`, `useQueryState` or `useQuerySubscription`
* instead of the query argument to get the same effect as if setting
* `skip: true` in the query options.
*
* Useful for scenarios where a query should be skipped when `arg` is `undefined`
* and TypeScript complains about it because `arg` is not allowed to be passed
* in as `undefined`, such as
*
* ```ts
* // codeblock-meta title="will error if the query argument is not allowed to be undefined" no-transpile
* useSomeQuery(arg, { skip: !!arg })
* ```
*
* ```ts
* // codeblock-meta title="using skipToken instead" no-transpile
* useSomeQuery(arg ?? skipToken)
* ```
*
* If passed directly into a query or mutation selector, that selector will always
* return an uninitialized state.
*/
export declare const skipToken: unique symbol;
/** @deprecated renamed to `skipToken` */
export declare const skipSelector: symbol;
declare module './module' {
interface ApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> {
select: QueryResultSelectorFactory<Definition, _RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;
}
interface ApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> {
select: MutationResultSelectorFactory<Definition, _RootState<Definitions, TagTypesFrom<Definition>, ReducerPathFrom<Definition>>>;
}
}
declare type QueryResultSelectorFactory<Definition extends QueryDefinition<any, any, any, any>, RootState> = (queryArg: QueryArgFrom<Definition> | SkipToken) => (state: RootState) => QueryResultSelectorResult<Definition>;
export declare type QueryResultSelectorResult<Definition extends QueryDefinition<any, any, any, any>> = QuerySubState<Definition> & RequestStatusFlags;
declare type MutationResultSelectorFactory<Definition extends MutationDefinition<any, any, any, any>, RootState> = (requestId: string | {
requestId: string | undefined;
fixedCacheKey: string | undefined;
} | SkipToken) => (state: RootState) => MutationResultSelectorResult<Definition>;
export declare type MutationResultSelectorResult<Definition extends MutationDefinition<any, any, any, any>> = MutationSubState<Definition> & RequestStatusFlags;
export declare function buildSelectors<Definitions extends EndpointDefinitions, ReducerPath extends string>({ serializeQueryArgs, reducerPath, }: {
serializeQueryArgs: InternalSerializeQueryArgs;
reducerPath: ReducerPath;
}): {
buildQuerySelector: (endpointName: string, endpointDefinition: QueryDefinition<any, any, any, any>) => QueryResultSelectorFactory<any, {
[x: string]: import("./apiState").CombinedState<Definitions, string, string>;
}>;
buildMutationSelector: () => MutationResultSelectorFactory<any, {
[x: string]: import("./apiState").CombinedState<Definitions, string, string>;
}>;
selectInvalidatedBy: (state: {
[x: string]: import("./apiState").CombinedState<Definitions, string, string>;
}, tags: ReadonlyArray<TagDescription<string>>) => Array<{
endpointName: string;
originalArgs: any;
queryCacheKey: QueryCacheKey;
}>;
};
export {};

@ -0,0 +1,51 @@
import type { AnyAction } from '@reduxjs/toolkit';
import type { CombinedState as CombinedQueryState, QuerySubstateIdentifier, MutationSubstateIdentifier, Subscribers, ConfigState } from './apiState';
import type { MutationThunk, QueryThunk } from './buildThunks';
import type { AssertTagTypes, EndpointDefinitions } from '../endpointDefinitions';
import type { Patch } from 'immer';
import type { ApiContext } from '../apiTypes';
export declare function getMutationCacheKey(id: MutationSubstateIdentifier | {
requestId: string;
arg: {
fixedCacheKey?: string | undefined;
};
}): string;
export declare function getMutationCacheKey(id: {
fixedCacheKey?: string;
requestId?: string;
}): string | undefined;
export declare function buildSlice({ reducerPath, queryThunk, mutationThunk, context: { endpointDefinitions: definitions, apiUid, extractRehydrationInfo, hasRehydrationInfo, }, assertTagType, config, }: {
reducerPath: string;
queryThunk: QueryThunk;
mutationThunk: MutationThunk;
context: ApiContext<EndpointDefinitions>;
assertTagType: AssertTagTypes;
config: Omit<ConfigState<string>, 'online' | 'focused' | 'middlewareRegistered'>;
}): {
reducer: import("redux").Reducer<import("redux").CombinedState<CombinedQueryState<any, string, string>>, AnyAction>;
actions: {
/** @deprecated has been renamed to `removeMutationResult` */
unsubscribeMutationResult: import("@reduxjs/toolkit").ActionCreatorWithPreparedPayload<[payload: MutationSubstateIdentifier], MutationSubstateIdentifier, `${string}/removeMutationResult`, never, unknown>;
resetApiState: import("@reduxjs/toolkit").ActionCreatorWithoutPayload<string>;
removeMutationResult: import("@reduxjs/toolkit").ActionCreatorWithPreparedPayload<[payload: MutationSubstateIdentifier], MutationSubstateIdentifier, `${string}/removeMutationResult`, never, unknown>;
subscriptionsUpdated: import("@reduxjs/toolkit").ActionCreatorWithPayload<Patch[], `${string}/subscriptionsUpdated`>;
updateSubscriptionOptions: import("@reduxjs/toolkit").ActionCreatorWithPayload<{
endpointName: string;
requestId: string;
options: Subscribers[number];
} & QuerySubstateIdentifier, `${string}/updateSubscriptionOptions`>;
unsubscribeQueryResult: import("@reduxjs/toolkit").ActionCreatorWithPayload<{
requestId: string;
} & QuerySubstateIdentifier, `${string}/unsubscribeQueryResult`>;
internal_probeSubscription: import("@reduxjs/toolkit").ActionCreatorWithPayload<{
queryCacheKey: string;
requestId: string;
}, `${string}/internal_probeSubscription`>;
removeQueryResult: import("@reduxjs/toolkit").ActionCreatorWithPreparedPayload<[payload: QuerySubstateIdentifier], QuerySubstateIdentifier, `${string}/removeQueryResult`, never, unknown>;
queryResultPatched: import("@reduxjs/toolkit").ActionCreatorWithPayload<QuerySubstateIdentifier & {
patches: readonly Patch[];
}, `${string}/queryResultPatched`>;
middlewareRegistered: import("@reduxjs/toolkit").ActionCreatorWithPayload<string, `${string}/middlewareRegistered`>;
};
};
export declare type SliceActions = ReturnType<typeof buildSlice>['actions'];

@ -0,0 +1,140 @@
import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs';
import type { Api, ApiContext } from '../apiTypes';
import type { BaseQueryFn, BaseQueryError } from '../baseQueryTypes';
import type { RootState, QueryKeys, QuerySubstateIdentifier } from './apiState';
import type { StartQueryActionCreatorOptions, QueryActionCreatorResult } from './buildInitiate';
import type { AssertTagTypes, EndpointDefinition, EndpointDefinitions, MutationDefinition, QueryArgFrom, QueryDefinition, ResultTypeFrom } from '../endpointDefinitions';
import type { Draft } from '@reduxjs/toolkit';
import type { Patch } from 'immer';
import type { AnyAction, ThunkAction, AsyncThunk } from '@reduxjs/toolkit';
import { SHOULD_AUTOBATCH } from '@reduxjs/toolkit';
import type { PrefetchOptions } from './module';
import type { UnwrapPromise } from '../tsHelpers';
declare module './module' {
interface ApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> extends Matchers<QueryThunk, Definition> {
}
interface ApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> extends Matchers<MutationThunk, Definition> {
}
}
declare type EndpointThunk<Thunk extends QueryThunk | MutationThunk, Definition extends EndpointDefinition<any, any, any, any>> = Definition extends EndpointDefinition<infer QueryArg, infer BaseQueryFn, any, infer ResultType> ? Thunk extends AsyncThunk<unknown, infer ATArg, infer ATConfig> ? AsyncThunk<ResultType, ATArg & {
originalArgs: QueryArg;
}, ATConfig & {
rejectValue: BaseQueryError<BaseQueryFn>;
}> : never : never;
export declare type PendingAction<Thunk extends QueryThunk | MutationThunk, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['pending']>;
export declare type FulfilledAction<Thunk extends QueryThunk | MutationThunk, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['fulfilled']>;
export declare type RejectedAction<Thunk extends QueryThunk | MutationThunk, Definition extends EndpointDefinition<any, any, any, any>> = ReturnType<EndpointThunk<Thunk, Definition>['rejected']>;
export declare type Matcher<M> = (value: any) => value is M;
export interface Matchers<Thunk extends QueryThunk | MutationThunk, Definition extends EndpointDefinition<any, any, any, any>> {
matchPending: Matcher<PendingAction<Thunk, Definition>>;
matchFulfilled: Matcher<FulfilledAction<Thunk, Definition>>;
matchRejected: Matcher<RejectedAction<Thunk, Definition>>;
}
export interface QueryThunkArg extends QuerySubstateIdentifier, StartQueryActionCreatorOptions {
type: 'query';
originalArgs: unknown;
endpointName: string;
}
export interface MutationThunkArg {
type: 'mutation';
originalArgs: unknown;
endpointName: string;
track?: boolean;
fixedCacheKey?: string;
}
export declare type ThunkResult = unknown;
export declare type ThunkApiMetaConfig = {
pendingMeta: {
startedTimeStamp: number;
[SHOULD_AUTOBATCH]: true;
};
fulfilledMeta: {
fulfilledTimeStamp: number;
baseQueryMeta: unknown;
[SHOULD_AUTOBATCH]: true;
};
rejectedMeta: {
baseQueryMeta: unknown;
[SHOULD_AUTOBATCH]: true;
};
};
export declare type QueryThunk = AsyncThunk<ThunkResult, QueryThunkArg, ThunkApiMetaConfig>;
export declare type MutationThunk = AsyncThunk<ThunkResult, MutationThunkArg, ThunkApiMetaConfig>;
export declare type MaybeDrafted<T> = T | Draft<T>;
export declare type Recipe<T> = (data: MaybeDrafted<T>) => void | MaybeDrafted<T>;
export declare type UpsertRecipe<T> = (data: MaybeDrafted<T> | undefined) => void | MaybeDrafted<T>;
export declare type PatchQueryDataThunk<Definitions extends EndpointDefinitions, PartialState> = <EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, args: QueryArgFrom<Definitions[EndpointName]>, patches: readonly Patch[]) => ThunkAction<void, PartialState, any, AnyAction>;
export declare type UpdateQueryDataThunk<Definitions extends EndpointDefinitions, PartialState> = <EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, args: QueryArgFrom<Definitions[EndpointName]>, updateRecipe: Recipe<ResultTypeFrom<Definitions[EndpointName]>>) => ThunkAction<PatchCollection, PartialState, any, AnyAction>;
export declare type UpsertQueryDataThunk<Definitions extends EndpointDefinitions, PartialState> = <EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, args: QueryArgFrom<Definitions[EndpointName]>, value: ResultTypeFrom<Definitions[EndpointName]>) => ThunkAction<QueryActionCreatorResult<Definitions[EndpointName] extends QueryDefinition<any, any, any, any> ? Definitions[EndpointName] : never>, PartialState, any, AnyAction>;
/**
* An object returned from dispatching a `api.util.updateQueryData` call.
*/
export declare type PatchCollection = {
/**
* An `immer` Patch describing the cache update.
*/
patches: Patch[];
/**
* An `immer` Patch to revert the cache update.
*/
inversePatches: Patch[];
/**
* A function that will undo the cache update.
*/
undo: () => void;
};
export declare function buildThunks<BaseQuery extends BaseQueryFn, ReducerPath extends string, Definitions extends EndpointDefinitions>({ reducerPath, baseQuery, context: { endpointDefinitions }, serializeQueryArgs, api, }: {
baseQuery: BaseQuery;
reducerPath: ReducerPath;
context: ApiContext<Definitions>;
serializeQueryArgs: InternalSerializeQueryArgs;
api: Api<BaseQuery, Definitions, ReducerPath, any>;
}): {
queryThunk: AsyncThunk<unknown, QueryThunkArg, {
pendingMeta: {
startedTimeStamp: number;
RTK_autoBatch: true;
};
fulfilledMeta: {
fulfilledTimeStamp: number;
baseQueryMeta: unknown;
RTK_autoBatch: true;
};
rejectedMeta: {
baseQueryMeta: unknown;
RTK_autoBatch: true;
};
state: RootState<any, string, ReducerPath>;
extra?: unknown;
dispatch?: import("redux").Dispatch<AnyAction> | undefined;
rejectValue?: unknown;
serializedErrorType?: unknown;
}>;
mutationThunk: AsyncThunk<unknown, MutationThunkArg, {
pendingMeta: {
startedTimeStamp: number;
RTK_autoBatch: true;
};
fulfilledMeta: {
fulfilledTimeStamp: number;
baseQueryMeta: unknown;
RTK_autoBatch: true;
};
rejectedMeta: {
baseQueryMeta: unknown;
RTK_autoBatch: true;
};
state: RootState<any, string, ReducerPath>;
extra?: unknown;
dispatch?: import("redux").Dispatch<AnyAction> | undefined;
rejectValue?: unknown;
serializedErrorType?: unknown;
}>;
prefetch: <EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, arg: any, options: PrefetchOptions) => ThunkAction<void, any, any, AnyAction>;
updateQueryData: UpdateQueryDataThunk<EndpointDefinitions, { [P in ReducerPath]: import("./apiState").CombinedState<any, string, P>; }>;
upsertQueryData: UpsertQueryDataThunk<Definitions, { [P in ReducerPath]: import("./apiState").CombinedState<any, string, P>; }>;
patchQueryData: PatchQueryDataThunk<EndpointDefinitions, { [P in ReducerPath]: import("./apiState").CombinedState<any, string, P>; }>;
buildMatchThunkActions: <Thunk extends AsyncThunk<any, QueryThunkArg, ThunkApiMetaConfig> | AsyncThunk<any, MutationThunkArg, ThunkApiMetaConfig>>(thunk: Thunk, endpointName: string) => Matchers<Thunk, any>;
};
export declare function calculateProvidedByThunk(action: UnwrapPromise<ReturnType<ReturnType<QueryThunk>> | ReturnType<ReturnType<MutationThunk>>>, type: 'providesTags' | 'invalidatesTags', endpointDefinitions: EndpointDefinitions, assertTagType: AssertTagTypes): readonly import("../endpointDefinitions").FullTagDescription<string>[];
export {};

@ -0,0 +1,4 @@
import { CreateApi } from '../createApi';
import { coreModule, coreModuleName } from './module';
declare const createApi: CreateApi<typeof coreModuleName>;
export { createApi, coreModule };

@ -0,0 +1,334 @@
/**
* Note: this file should import all other files for type discovery and declaration merging
*/
import type { PatchQueryDataThunk, UpdateQueryDataThunk, UpsertQueryDataThunk } from './buildThunks';
import './buildThunks';
import type { ActionCreatorWithPayload, AnyAction, Middleware, Reducer, ThunkAction, ThunkDispatch } from '@reduxjs/toolkit';
import type { EndpointDefinitions, QueryArgFrom, QueryDefinition, MutationDefinition, TagDescription } from '../endpointDefinitions';
import type { CombinedState, QueryKeys, MutationKeys, RootState } from './apiState';
import type { Module } from '../apiTypes';
import { onFocus, onFocusLost, onOnline, onOffline } from './setupListeners';
import './buildSelectors';
import type { MutationActionCreatorResult, QueryActionCreatorResult } from './buildInitiate';
import './buildInitiate';
import type { SliceActions } from './buildSlice';
import type { BaseQueryFn } from '../baseQueryTypes';
import type { ReferenceCacheLifecycle } from './buildMiddleware/cacheLifecycle';
import type { ReferenceQueryLifecycle } from './buildMiddleware/queryLifecycle';
import type { ReferenceCacheCollection } from './buildMiddleware/cacheCollection';
/**
* `ifOlderThan` - (default: `false` | `number`) - _number is value in seconds_
* - If specified, it will only run the query if the difference between `new Date()` and the last `fulfilledTimeStamp` is greater than the given value
*
* @overloadSummary
* `force`
* - If `force: true`, it will ignore the `ifOlderThan` value if it is set and the query will be run even if it exists in the cache.
*/
export declare type PrefetchOptions = {
ifOlderThan?: false | number;
} | {
force?: boolean;
};
export declare const coreModuleName: unique symbol;
export declare type CoreModule = typeof coreModuleName | ReferenceCacheLifecycle | ReferenceQueryLifecycle | ReferenceCacheCollection;
export interface ThunkWithReturnValue<T> extends ThunkAction<T, any, any, AnyAction> {
}
declare module '../apiTypes' {
interface ApiModules<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string> {
[coreModuleName]: {
/**
* This api's reducer should be mounted at `store[api.reducerPath]`.
*
* @example
* ```ts
* configureStore({
* reducer: {
* [api.reducerPath]: api.reducer,
* },
* middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
* })
* ```
*/
reducerPath: ReducerPath;
/**
* Internal actions not part of the public API. Note: These are subject to change at any given time.
*/
internalActions: InternalActions;
/**
* A standard redux reducer that enables core functionality. Make sure it's included in your store.
*
* @example
* ```ts
* configureStore({
* reducer: {
* [api.reducerPath]: api.reducer,
* },
* middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
* })
* ```
*/
reducer: Reducer<CombinedState<Definitions, TagTypes, ReducerPath>, AnyAction>;
/**
* This is a standard redux middleware and is responsible for things like polling, garbage collection and a handful of other things. Make sure it's included in your store.
*
* @example
* ```ts
* configureStore({
* reducer: {
* [api.reducerPath]: api.reducer,
* },
* middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),
* })
* ```
*/
middleware: Middleware<{}, RootState<Definitions, string, ReducerPath>, ThunkDispatch<any, any, AnyAction>>;
/**
* A collection of utility thunks for various situations.
*/
util: {
/**
* This method had to be removed due to a conceptual bug in RTK.
*
* Despite TypeScript errors, it will continue working in the "buggy" way it did
* before in production builds and will be removed in the next major release.
*
* Nonetheless, you should immediately replace it with the new recommended approach.
* See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for new guidance on SSR.
*
* Please see https://github.com/reduxjs/redux-toolkit/pull/2481 for details.
* @deprecated
*/
getRunningOperationPromises: never;
/**
* This method had to be removed due to a conceptual bug in RTK.
* It has been replaced by `api.util.getRunningQueryThunk` and `api.util.getRunningMutationThunk`.
* Please see https://github.com/reduxjs/redux-toolkit/pull/2481 for details.
* @deprecated
*/
getRunningOperationPromise: never;
/**
* A thunk that (if dispatched) will return a specific running query, identified
* by `endpointName` and `args`.
* If that query is not running, dispatching the thunk will result in `undefined`.
*
* Can be used to await a specific query triggered in any way,
* including via hook calls or manually dispatching `initiate` actions.
*
* See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
*/
getRunningQueryThunk<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, args: QueryArgFrom<Definitions[EndpointName]>): ThunkWithReturnValue<QueryActionCreatorResult<Definitions[EndpointName] & {
type: 'query';
}> | undefined>;
/**
* A thunk that (if dispatched) will return a specific running mutation, identified
* by `endpointName` and `fixedCacheKey` or `requestId`.
* If that mutation is not running, dispatching the thunk will result in `undefined`.
*
* Can be used to await a specific mutation triggered in any way,
* including via hook trigger functions or manually dispatching `initiate` actions.
*
* See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
*/
getRunningMutationThunk<EndpointName extends MutationKeys<Definitions>>(endpointName: EndpointName, fixedCacheKeyOrRequestId: string): ThunkWithReturnValue<MutationActionCreatorResult<Definitions[EndpointName] & {
type: 'mutation';
}> | undefined>;
/**
* A thunk that (if dispatched) will return all running queries.
*
* Useful for SSR scenarios to await all running queries triggered in any way,
* including via hook calls or manually dispatching `initiate` actions.
*
* See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
*/
getRunningQueriesThunk(): ThunkWithReturnValue<Array<QueryActionCreatorResult<any>>>;
/**
* A thunk that (if dispatched) will return all running mutations.
*
* Useful for SSR scenarios to await all running mutations triggered in any way,
* including via hook calls or manually dispatching `initiate` actions.
*
* See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.
*/
getRunningMutationsThunk(): ThunkWithReturnValue<Array<MutationActionCreatorResult<any>>>;
/**
* A Redux thunk that can be used to manually trigger pre-fetching of data.
*
* The thunk accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and a set of options used to determine if the data actually should be re-fetched based on cache staleness.
*
* React Hooks users will most likely never need to use this directly, as the `usePrefetch` hook will dispatch this thunk internally as needed when you call the prefetching function supplied by the hook.
*
* @example
*
* ```ts no-transpile
* dispatch(api.util.prefetch('getPosts', undefined, { force: true }))
* ```
*/
prefetch<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, arg: QueryArgFrom<Definitions[EndpointName]>, options: PrefetchOptions): ThunkAction<void, any, any, AnyAction>;
/**
* A Redux thunk action creator that, when dispatched, creates and applies a set of JSON diff/patch objects to the current state. This immediately updates the Redux state with those changes.
*
* The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and an `updateRecipe` callback function. The callback receives an Immer-wrapped `draft` of the current state, and may modify the draft to match the expected results after the mutation completes successfully.
*
* The thunk executes _synchronously_, and returns an object containing `{patches: Patch[], inversePatches: Patch[], undo: () => void}`. The `patches` and `inversePatches` are generated using Immer's [`produceWithPatches` method](https://immerjs.github.io/immer/patches).
*
* This is typically used as the first step in implementing optimistic updates. The generated `inversePatches` can be used to revert the updates by calling `dispatch(patchQueryData(endpointName, args, inversePatches))`. Alternatively, the `undo` method can be called directly to achieve the same effect.
*
* Note that the first two arguments (`endpointName` and `args`) are used to determine which existing cache entry to update. If no existing cache entry is found, the `updateRecipe` callback will not run.
*
* @example
*
* ```ts
* const patchCollection = dispatch(
* api.util.updateQueryData('getPosts', undefined, (draftPosts) => {
* draftPosts.push({ id: 1, name: 'Teddy' })
* })
* )
* ```
*/
updateQueryData: UpdateQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;
/** @deprecated renamed to `updateQueryData` */
updateQueryResult: UpdateQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;
/**
* A Redux thunk action creator that, when dispatched, acts as an artificial API request to upsert a value into the cache.
*
* The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and the data to upsert.
*
* If no cache entry for that cache key exists, a cache entry will be created and the data added. If a cache entry already exists, this will _overwrite_ the existing cache entry data.
*
* The thunk executes _asynchronously_, and returns a promise that resolves when the store has been updated.
*
* If dispatched while an actual request is in progress, both the upsert and request will be handled as soon as they resolve, resulting in a "last result wins" update behavior.
*
* @example
*
* ```ts
* await dispatch(
* api.util.upsertQueryData('getPost', {id: 1}, {id: 1, text: "Hello!"})
* )
* ```
*/
upsertQueryData: UpsertQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;
/**
* A Redux thunk that applies a JSON diff/patch array to the cached data for a given query result. This immediately updates the Redux state with those changes.
*
* The thunk accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and a JSON diff/patch array as produced by Immer's `produceWithPatches`.
*
* This is typically used as the second step in implementing optimistic updates. If a request fails, the optimistically-applied changes can be reverted by dispatching `patchQueryData` with the `inversePatches` that were generated by `updateQueryData` earlier.
*
* In cases where it is desired to simply revert the previous changes, it may be preferable to call the `undo` method returned from dispatching `updateQueryData` instead.
*
* @example
* ```ts
* const patchCollection = dispatch(
* api.util.updateQueryData('getPosts', undefined, (draftPosts) => {
* draftPosts.push({ id: 1, name: 'Teddy' })
* })
* )
*
* // later
* dispatch(
* api.util.patchQueryData('getPosts', undefined, patchCollection.inversePatches)
* )
*
* // or
* patchCollection.undo()
* ```
*/
patchQueryData: PatchQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;
/** @deprecated renamed to `patchQueryData` */
patchQueryResult: PatchQueryDataThunk<Definitions, RootState<Definitions, string, ReducerPath>>;
/**
* A Redux action creator that can be dispatched to manually reset the api state completely. This will immediately remove all existing cache entries, and all queries will be considered 'uninitialized'.
*
* @example
*
* ```ts
* dispatch(api.util.resetApiState())
* ```
*/
resetApiState: SliceActions['resetApiState'];
/**
* A Redux action creator that can be used to manually invalidate cache tags for [automated re-fetching](../../usage/automated-refetching.mdx).
*
* The action creator accepts one argument: the cache tags to be invalidated. It returns an action with those tags as a payload, and the corresponding `invalidateTags` action type for the api.
*
* Dispatching the result of this action creator will [invalidate](../../usage/automated-refetching.mdx#invalidating-cache-data) the given tags, causing queries to automatically re-fetch if they are subscribed to cache data that [provides](../../usage/automated-refetching.mdx#providing-cache-data) the corresponding tags.
*
* The array of tags provided to the action creator should be in one of the following formats, where `TagType` is equal to a string provided to the [`tagTypes`](../createApi.mdx#tagtypes) property of the api:
*
* - `[TagType]`
* - `[{ type: TagType }]`
* - `[{ type: TagType, id: number | string }]`
*
* @example
*
* ```ts
* dispatch(api.util.invalidateTags(['Post']))
* dispatch(api.util.invalidateTags([{ type: 'Post', id: 1 }]))
* dispatch(
* api.util.invalidateTags([
* { type: 'Post', id: 1 },
* { type: 'Post', id: 'LIST' },
* ])
* )
* ```
*/
invalidateTags: ActionCreatorWithPayload<Array<TagDescription<TagTypes>>, string>;
/**
* A function to select all `{ endpointName, originalArgs, queryCacheKey }` combinations that would be invalidated by a specific set of tags.
*
* Can be used for mutations that want to do optimistic updates instead of invalidating a set of tags, but don't know exactly what they need to update.
*/
selectInvalidatedBy: (state: RootState<Definitions, string, ReducerPath>, tags: ReadonlyArray<TagDescription<TagTypes>>) => Array<{
endpointName: string;
originalArgs: any;
queryCacheKey: string;
}>;
};
/**
* Endpoints based on the input endpoints provided to `createApi`, containing `select` and `action matchers`.
*/
endpoints: {
[K in keyof Definitions]: Definitions[K] extends QueryDefinition<any, any, any, any, any> ? ApiEndpointQuery<Definitions[K], Definitions> : Definitions[K] extends MutationDefinition<any, any, any, any, any> ? ApiEndpointMutation<Definitions[K], Definitions> : never;
};
};
}
}
export interface ApiEndpointQuery<Definition extends QueryDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> {
name: string;
/**
* All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
*/
Types: NonNullable<Definition['Types']>;
}
export interface ApiEndpointMutation<Definition extends MutationDefinition<any, any, any, any, any>, Definitions extends EndpointDefinitions> {
name: string;
/**
* All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
*/
Types: NonNullable<Definition['Types']>;
}
export declare type ListenerActions = {
/**
* Will cause the RTK Query middleware to trigger any refetchOnReconnect-related behavior
* @link https://rtk-query-docs.netlify.app/api/setupListeners
*/
onOnline: typeof onOnline;
onOffline: typeof onOffline;
/**
* Will cause the RTK Query middleware to trigger any refetchOnFocus-related behavior
* @link https://rtk-query-docs.netlify.app/api/setupListeners
*/
onFocus: typeof onFocus;
onFocusLost: typeof onFocusLost;
};
export declare type InternalActions = SliceActions & ListenerActions;
/**
* Creates a module containing the basic redux logic for use with `buildCreateApi`.
*
* @example
* ```ts
* const createBaseApi = buildCreateApi(coreModule());
* ```
*/
export declare const coreModule: () => Module<CoreModule>;

@ -0,0 +1,27 @@
import type { ThunkDispatch, ActionCreatorWithoutPayload } from '@reduxjs/toolkit';
export declare const onFocus: ActionCreatorWithoutPayload<"__rtkq/focused">;
export declare const onFocusLost: ActionCreatorWithoutPayload<"__rtkq/unfocused">;
export declare const onOnline: ActionCreatorWithoutPayload<"__rtkq/online">;
export declare const onOffline: ActionCreatorWithoutPayload<"__rtkq/offline">;
/**
* A utility used to enable `refetchOnMount` and `refetchOnReconnect` behaviors.
* It requires the dispatch method from your store.
* Calling `setupListeners(store.dispatch)` will configure listeners with the recommended defaults,
* but you have the option of providing a callback for more granular control.
*
* @example
* ```ts
* setupListeners(store.dispatch)
* ```
*
* @param dispatch - The dispatch method from your store
* @param customHandler - An optional callback for more granular control over listener behavior
* @returns Return value of the handler.
* The default handler returns an `unsubscribe` method that can be called to remove the listeners.
*/
export declare function setupListeners(dispatch: ThunkDispatch<any, any, any>, customHandler?: (dispatch: ThunkDispatch<any, any, any>, actions: {
onFocus: typeof onFocus;
onFocusLost: typeof onFocusLost;
onOnline: typeof onOnline;
onOffline: typeof onOffline;
}) => () => void): () => void;

@ -0,0 +1,194 @@
import type { Api, Module, ModuleName } from './apiTypes';
import type { CombinedState } from './core/apiState';
import type { BaseQueryArg, BaseQueryFn } from './baseQueryTypes';
import type { SerializeQueryArgs } from './defaultSerializeQueryArgs';
import type { EndpointBuilder, EndpointDefinitions } from './endpointDefinitions';
import type { AnyAction } from '@reduxjs/toolkit';
import type { NoInfer } from './tsHelpers';
export interface CreateApiOptions<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string = 'api', TagTypes extends string = never> {
/**
* The base query used by each endpoint if no `queryFn` option is specified. RTK Query exports a utility called [fetchBaseQuery](./fetchBaseQuery) as a lightweight wrapper around `fetch` for common use-cases. See [Customizing Queries](../../rtk-query/usage/customizing-queries) if `fetchBaseQuery` does not handle your requirements.
*
* @example
*
* ```ts
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
*
* const api = createApi({
* // highlight-start
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* // highlight-end
* endpoints: (build) => ({
* // ...endpoints
* }),
* })
* ```
*/
baseQuery: BaseQuery;
/**
* An array of string tag type names. Specifying tag types is optional, but you should define them so that they can be used for caching and invalidation. When defining a tag type, you will be able to [provide](../../rtk-query/usage/automated-refetching#providing-tags) them with `providesTags` and [invalidate](../../rtk-query/usage/automated-refetching#invalidating-tags) them with `invalidatesTags` when configuring [endpoints](#endpoints).
*
* @example
*
* ```ts
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'
*
* const api = createApi({
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* // highlight-start
* tagTypes: ['Post', 'User'],
* // highlight-end
* endpoints: (build) => ({
* // ...endpoints
* }),
* })
* ```
*/
tagTypes?: readonly TagTypes[];
/**
* The `reducerPath` is a _unique_ key that your service will be mounted to in your store. If you call `createApi` more than once in your application, you will need to provide a unique value each time. Defaults to `'api'`.
*
* @example
*
* ```ts
* // codeblock-meta title="apis.js"
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query';
*
* const apiOne = createApi({
* // highlight-start
* reducerPath: 'apiOne',
* // highlight-end
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* endpoints: (builder) => ({
* // ...endpoints
* }),
* });
*
* const apiTwo = createApi({
* // highlight-start
* reducerPath: 'apiTwo',
* // highlight-end
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* endpoints: (builder) => ({
* // ...endpoints
* }),
* });
* ```
*/
reducerPath?: ReducerPath;
/**
* Accepts a custom function if you have a need to change the creation of cache keys for any reason.
*/
serializeQueryArgs?: SerializeQueryArgs<BaseQueryArg<BaseQuery>>;
/**
* Endpoints are just a set of operations that you want to perform against your server. You define them as an object using the builder syntax. There are two basic endpoint types: [`query`](../../rtk-query/usage/queries) and [`mutation`](../../rtk-query/usage/mutations).
*/
endpoints(build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>): Definitions;
/**
* Defaults to `60` _(this value is in seconds)_. This is how long RTK Query will keep your data cached for **after** the last component unsubscribes. For example, if you query an endpoint, then unmount the component, then mount another component that makes the same request within the given time frame, the most recent value will be served from the cache.
*
* ```ts
* // codeblock-meta title="keepUnusedDataFor example"
*
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
* interface Post {
* id: number
* name: string
* }
* type PostsResponse = Post[]
*
* const api = createApi({
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* endpoints: (build) => ({
* getPosts: build.query<PostsResponse, void>({
* query: () => 'posts',
* // highlight-start
* keepUnusedDataFor: 5
* // highlight-end
* })
* })
* })
* ```
*/
keepUnusedDataFor?: number;
/**
* Defaults to `false`. This setting allows you to control whether if a cached result is already available RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.
* - `false` - Will not cause a query to be performed _unless_ it does not exist yet.
* - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.
* - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.
*
* If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
*/
refetchOnMountOrArgChange?: boolean | number;
/**
* Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after the application window regains focus.
*
* If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
*
* Note: requires [`setupListeners`](./setupListeners) to have been called.
*/
refetchOnFocus?: boolean;
/**
* Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.
*
* If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
*
* Note: requires [`setupListeners`](./setupListeners) to have been called.
*/
refetchOnReconnect?: boolean;
/**
* A function that is passed every dispatched action. If this returns something other than `undefined`,
* that return value will be used to rehydrate fulfilled & errored queries.
*
* @example
*
* ```ts
* // codeblock-meta title="next-redux-wrapper rehydration example"
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
* import { HYDRATE } from 'next-redux-wrapper'
*
* export const api = createApi({
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* // highlight-start
* extractRehydrationInfo(action, { reducerPath }) {
* if (action.type === HYDRATE) {
* return action.payload[reducerPath]
* }
* },
* // highlight-end
* endpoints: (build) => ({
* // omitted
* }),
* })
* ```
*/
extractRehydrationInfo?: (action: AnyAction, { reducerPath, }: {
reducerPath: ReducerPath;
}) => undefined | CombinedState<NoInfer<Definitions>, NoInfer<TagTypes>, NoInfer<ReducerPath>>;
}
export declare type CreateApi<Modules extends ModuleName> = {
/**
* Creates a service to use in your application. Contains only the basic redux logic (the core module).
*
* @link https://rtk-query-docs.netlify.app/api/createApi
*/
<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string = 'api', TagTypes extends string = never>(options: CreateApiOptions<BaseQuery, Definitions, ReducerPath, TagTypes>): Api<BaseQuery, Definitions, ReducerPath, TagTypes, Modules>;
};
/**
* Builds a `createApi` method based on the provided `modules`.
*
* @link https://rtk-query-docs.netlify.app/concepts/customizing-create-api
*
* @example
* ```ts
* const MyContext = React.createContext<ReactReduxContextValue>(null as any);
* const customCreateApi = buildCreateApi(
* coreModule(),
* reactHooksModule({ useDispatch: createDispatchHook(MyContext) })
* );
* ```
*
* @param modules - A variable number of modules that customize how the `createApi` method handles endpoints
* @returns A `createApi` method using the provided `modules`.
*/
export declare function buildCreateApi<Modules extends [Module<any>, ...Module<any>[]]>(...modules: Modules): CreateApi<Modules[number]['name']>;

@ -0,0 +1,13 @@
import type { QueryCacheKey } from './core/apiState';
import type { EndpointDefinition } from './endpointDefinitions';
export declare const defaultSerializeQueryArgs: SerializeQueryArgs<any>;
export declare type SerializeQueryArgs<QueryArgs, ReturnType = string> = (_: {
queryArgs: QueryArgs;
endpointDefinition: EndpointDefinition<any, any, any, any>;
endpointName: string;
}) => ReturnType;
export declare type InternalSerializeQueryArgs = (_: {
queryArgs: any;
endpointDefinition: EndpointDefinition<any, any, any, any>;
endpointName: string;
}) => QueryCacheKey;

@ -0,0 +1,535 @@
import type { AnyAction, ThunkDispatch } from '@reduxjs/toolkit';
import type { SerializeQueryArgs } from './defaultSerializeQueryArgs';
import type { QuerySubState, RootState } from './core/apiState';
import type { BaseQueryExtraOptions, BaseQueryFn, BaseQueryResult, BaseQueryArg, BaseQueryApi, QueryReturnValue, BaseQueryError, BaseQueryMeta } from './baseQueryTypes';
import type { HasRequiredProps, MaybePromise, OmitFromUnion, CastAny } from './tsHelpers';
import type { NEVER } from './fakeBaseQuery';
declare const resultType: unique symbol;
declare const baseQuery: unique symbol;
interface EndpointDefinitionWithQuery<QueryArg, BaseQuery extends BaseQueryFn, ResultType> {
/**
* `query` can be a function that returns either a `string` or an `object` which is passed to your `baseQuery`. If you are using [fetchBaseQuery](./fetchBaseQuery), this can return either a `string` or an `object` of properties in `FetchArgs`. If you use your own custom [`baseQuery`](../../rtk-query/usage/customizing-queries), you can customize this behavior to your liking.
*
* @example
*
* ```ts
* // codeblock-meta title="query example"
*
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
* interface Post {
* id: number
* name: string
* }
* type PostsResponse = Post[]
*
* const api = createApi({
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* tagTypes: ['Post'],
* endpoints: (build) => ({
* getPosts: build.query<PostsResponse, void>({
* // highlight-start
* query: () => 'posts',
* // highlight-end
* }),
* addPost: build.mutation<Post, Partial<Post>>({
* // highlight-start
* query: (body) => ({
* url: `posts`,
* method: 'POST',
* body,
* }),
* // highlight-end
* invalidatesTags: [{ type: 'Post', id: 'LIST' }],
* }),
* })
* })
* ```
*/
query(arg: QueryArg): BaseQueryArg<BaseQuery>;
queryFn?: never;
/**
* A function to manipulate the data returned by a query or mutation.
*/
transformResponse?(baseQueryReturnValue: BaseQueryResult<BaseQuery>, meta: BaseQueryMeta<BaseQuery>, arg: QueryArg): ResultType | Promise<ResultType>;
/**
* A function to manipulate the data returned by a failed query or mutation.
*/
transformErrorResponse?(baseQueryReturnValue: BaseQueryError<BaseQuery>, meta: BaseQueryMeta<BaseQuery>, arg: QueryArg): unknown;
/**
* Defaults to `true`.
*
* Most apps should leave this setting on. The only time it can be a performance issue
* is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and
* you're unable to paginate it.
*
* For details of how this works, please see the below. When it is set to `false`,
* every request will cause subscribed components to rerender, even when the data has not changed.
*
* @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing
*/
structuralSharing?: boolean;
}
interface EndpointDefinitionWithQueryFn<QueryArg, BaseQuery extends BaseQueryFn, ResultType> {
/**
* Can be used in place of `query` as an inline function that bypasses `baseQuery` completely for the endpoint.
*
* @example
* ```ts
* // codeblock-meta title="Basic queryFn example"
*
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
* interface Post {
* id: number
* name: string
* }
* type PostsResponse = Post[]
*
* const api = createApi({
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* endpoints: (build) => ({
* getPosts: build.query<PostsResponse, void>({
* query: () => 'posts',
* }),
* flipCoin: build.query<'heads' | 'tails', void>({
* // highlight-start
* queryFn(arg, queryApi, extraOptions, baseQuery) {
* const randomVal = Math.random()
* if (randomVal < 0.45) {
* return { data: 'heads' }
* }
* if (randomVal < 0.9) {
* return { data: 'tails' }
* }
* return { error: { status: 500, statusText: 'Internal Server Error', data: "Coin landed on it's edge!" } }
* }
* // highlight-end
* })
* })
* })
* ```
*/
queryFn(arg: QueryArg, api: BaseQueryApi, extraOptions: BaseQueryExtraOptions<BaseQuery>, baseQuery: (arg: Parameters<BaseQuery>[0]) => ReturnType<BaseQuery>): MaybePromise<QueryReturnValue<ResultType, BaseQueryError<BaseQuery>>>;
query?: never;
transformResponse?: never;
transformErrorResponse?: never;
/**
* Defaults to `true`.
*
* Most apps should leave this setting on. The only time it can be a performance issue
* is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and
* you're unable to paginate it.
*
* For details of how this works, please see the below. When it is set to `false`,
* every request will cause subscribed components to rerender, even when the data has not changed.
*
* @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing
*/
structuralSharing?: boolean;
}
export interface BaseEndpointTypes<QueryArg, BaseQuery extends BaseQueryFn, ResultType> {
QueryArg: QueryArg;
BaseQuery: BaseQuery;
ResultType: ResultType;
}
export declare type BaseEndpointDefinition<QueryArg, BaseQuery extends BaseQueryFn, ResultType> = (([CastAny<BaseQueryResult<BaseQuery>, {}>] extends [NEVER] ? never : EndpointDefinitionWithQuery<QueryArg, BaseQuery, ResultType>) | EndpointDefinitionWithQueryFn<QueryArg, BaseQuery, ResultType>) & {
[resultType]?: ResultType;
[baseQuery]?: BaseQuery;
} & HasRequiredProps<BaseQueryExtraOptions<BaseQuery>, {
extraOptions: BaseQueryExtraOptions<BaseQuery>;
}, {
extraOptions?: BaseQueryExtraOptions<BaseQuery>;
}>;
export declare enum DefinitionType {
query = "query",
mutation = "mutation"
}
export declare type GetResultDescriptionFn<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = (result: ResultType | undefined, error: ErrorType | undefined, arg: QueryArg, meta: MetaType) => ReadonlyArray<TagDescription<TagTypes>>;
export declare type FullTagDescription<TagType> = {
type: TagType;
id?: number | string;
};
export declare type TagDescription<TagType> = TagType | FullTagDescription<TagType>;
export declare type ResultDescription<TagTypes extends string, ResultType, QueryArg, ErrorType, MetaType> = ReadonlyArray<TagDescription<TagTypes>> | GetResultDescriptionFn<TagTypes, ResultType, QueryArg, ErrorType, MetaType>;
/** @deprecated please use `onQueryStarted` instead */
export interface QueryApi<ReducerPath extends string, Context extends {}> {
/** @deprecated please use `onQueryStarted` instead */
dispatch: ThunkDispatch<any, any, AnyAction>;
/** @deprecated please use `onQueryStarted` instead */
getState(): RootState<any, any, ReducerPath>;
/** @deprecated please use `onQueryStarted` instead */
extra: unknown;
/** @deprecated please use `onQueryStarted` instead */
requestId: string;
/** @deprecated please use `onQueryStarted` instead */
context: Context;
}
export interface QueryTypes<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string> extends BaseEndpointTypes<QueryArg, BaseQuery, ResultType> {
/**
* The endpoint definition type. To be used with some internal generic types.
* @example
* ```ts
* const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...
* ```
*/
QueryDefinition: QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;
TagTypes: TagTypes;
ReducerPath: ReducerPath;
}
export interface QueryExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> {
type: DefinitionType.query;
/**
* Used by `query` endpoints. Determines which 'tag' is attached to the cached data returned by the query.
* Expects an array of tag type strings, an array of objects of tag types with ids, or a function that returns such an array.
* 1. `['Post']` - equivalent to `2`
* 2. `[{ type: 'Post' }]` - equivalent to `1`
* 3. `[{ type: 'Post', id: 1 }]`
* 4. `(result, error, arg) => ['Post']` - equivalent to `5`
* 5. `(result, error, arg) => [{ type: 'Post' }]` - equivalent to `4`
* 6. `(result, error, arg) => [{ type: 'Post', id: 1 }]`
*
* @example
*
* ```ts
* // codeblock-meta title="providesTags example"
*
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
* interface Post {
* id: number
* name: string
* }
* type PostsResponse = Post[]
*
* const api = createApi({
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* tagTypes: ['Posts'],
* endpoints: (build) => ({
* getPosts: build.query<PostsResponse, void>({
* query: () => 'posts',
* // highlight-start
* providesTags: (result) =>
* result
* ? [
* ...result.map(({ id }) => ({ type: 'Posts' as const, id })),
* { type: 'Posts', id: 'LIST' },
* ]
* : [{ type: 'Posts', id: 'LIST' }],
* // highlight-end
* })
* })
* })
* ```
*/
providesTags?: ResultDescription<TagTypes, ResultType, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;
/**
* Not to be used. A query should not invalidate tags in the cache.
*/
invalidatesTags?: never;
/**
* Can be provided to return a custom cache key value based on the query arguments.
*
* This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key. It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.
*
* Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean. If it returns a string, that value will be used as the cache key directly. If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`. This simplifies the use case of stripping out args you don't want included in the cache key.
*
*
* @example
*
* ```ts
* // codeblock-meta title="serializeQueryArgs : exclude value"
*
* import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'
* interface Post {
* id: number
* name: string
* }
*
* interface MyApiClient {
* fetchPost: (id: string) => Promise<Post>
* }
*
* createApi({
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* endpoints: (build) => ({
* // Example: an endpoint with an API client passed in as an argument,
* // but only the item ID should be used as the cache key
* getPost: build.query<Post, { id: string; client: MyApiClient }>({
* queryFn: async ({ id, client }) => {
* const post = await client.fetchPost(id)
* return { data: post }
* },
* // highlight-start
* serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {
* const { id } = queryArgs
* // This can return a string, an object, a number, or a boolean.
* // If it returns an object, number or boolean, that value
* // will be serialized automatically via `defaultSerializeQueryArgs`
* return { id } // omit `client` from the cache key
*
* // Alternately, you can use `defaultSerializeQueryArgs` yourself:
* // return defaultSerializeQueryArgs({
* // endpointName,
* // queryArgs: { id },
* // endpointDefinition
* // })
* // Or create and return a string yourself:
* // return `getPost(${id})`
* },
* // highlight-end
* }),
* }),
*})
* ```
*/
serializeQueryArgs?: SerializeQueryArgs<QueryArg, string | number | boolean | Record<any, any>>;
/**
* Can be provided to merge an incoming response value into the current cache data.
* If supplied, no automatic structural sharing will be applied - it's up to
* you to update the cache appropriately.
*
* Since RTKQ normally replaces cache entries with the new response, you will usually
* need to use this with the `serializeQueryArgs` or `forceRefetch` options to keep
* an existing cache entry so that it can be updated.
*
* Since this is wrapped with Immer, you , you may either mutate the `currentCacheValue` directly,
* or return a new value, but _not_ both at once.
*
* Will only be called if the existing `currentCacheData` is _not_ `undefined` - on first response,
* the cache entry will just save the response data directly.
*
* Useful if you don't want a new request to completely override the current cache value,
* maybe because you have manually updated it from another source and don't want those
* updates to get lost.
*
*
* @example
*
* ```ts
* // codeblock-meta title="merge: pagination"
*
* import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'
* interface Post {
* id: number
* name: string
* }
*
* createApi({
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* endpoints: (build) => ({
* listItems: build.query<string[], number>({
* query: (pageNumber) => `/listItems?page=${pageNumber}`,
* // Only have one cache entry because the arg always maps to one string
* serializeQueryArgs: ({ endpointName }) => {
* return endpointName
* },
* // Always merge incoming data to the cache entry
* merge: (currentCache, newItems) => {
* currentCache.push(...newItems)
* },
* // Refetch when the page arg changes
* forceRefetch({ currentArg, previousArg }) {
* return currentArg !== previousArg
* },
* }),
* }),
*})
* ```
*/
merge?(currentCacheData: ResultType, responseData: ResultType, otherArgs: {
arg: QueryArg;
baseQueryMeta: BaseQueryMeta<BaseQuery>;
requestId: string;
fulfilledTimeStamp: number;
}): ResultType | void;
/**
* Check to see if the endpoint should force a refetch in cases where it normally wouldn't.
* This is primarily useful for "infinite scroll" / pagination use cases where
* RTKQ is keeping a single cache entry that is added to over time, in combination
* with `serializeQueryArgs` returning a fixed cache key and a `merge` callback
* set to add incoming data to the cache entry each time.
*
* @example
*
* ```ts
* // codeblock-meta title="forceRefresh: pagination"
*
* import { createApi, fetchBaseQuery, defaultSerializeQueryArgs } from '@reduxjs/toolkit/query/react'
* interface Post {
* id: number
* name: string
* }
*
* createApi({
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* endpoints: (build) => ({
* listItems: build.query<string[], number>({
* query: (pageNumber) => `/listItems?page=${pageNumber}`,
* // Only have one cache entry because the arg always maps to one string
* serializeQueryArgs: ({ endpointName }) => {
* return endpointName
* },
* // Always merge incoming data to the cache entry
* merge: (currentCache, newItems) => {
* currentCache.push(...newItems)
* },
* // Refetch when the page arg changes
* forceRefetch({ currentArg, previousArg }) {
* return currentArg !== previousArg
* },
* }),
* }),
*})
* ```
*/
forceRefetch?(params: {
currentArg: QueryArg | undefined;
previousArg: QueryArg | undefined;
state: RootState<any, any, string>;
endpointState?: QuerySubState<any>;
}): boolean;
/**
* All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
*/
Types?: QueryTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;
}
export declare type QueryDefinition<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string> = BaseEndpointDefinition<QueryArg, BaseQuery, ResultType> & QueryExtraOptions<TagTypes, ResultType, QueryArg, BaseQuery, ReducerPath>;
export interface MutationTypes<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string> extends BaseEndpointTypes<QueryArg, BaseQuery, ResultType> {
/**
* The endpoint definition type. To be used with some internal generic types.
* @example
* ```ts
* const useMyWrappedHook: UseMutation<typeof api.endpoints.query.Types.MutationDefinition> = ...
* ```
*/
MutationDefinition: MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;
TagTypes: TagTypes;
ReducerPath: ReducerPath;
}
export interface MutationExtraOptions<TagTypes extends string, ResultType, QueryArg, BaseQuery extends BaseQueryFn, ReducerPath extends string = string> {
type: DefinitionType.mutation;
/**
* Used by `mutation` endpoints. Determines which cached data should be either re-fetched or removed from the cache.
* Expects the same shapes as `providesTags`.
*
* @example
*
* ```ts
* // codeblock-meta title="invalidatesTags example"
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
* interface Post {
* id: number
* name: string
* }
* type PostsResponse = Post[]
*
* const api = createApi({
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* tagTypes: ['Posts'],
* endpoints: (build) => ({
* getPosts: build.query<PostsResponse, void>({
* query: () => 'posts',
* providesTags: (result) =>
* result
* ? [
* ...result.map(({ id }) => ({ type: 'Posts' as const, id })),
* { type: 'Posts', id: 'LIST' },
* ]
* : [{ type: 'Posts', id: 'LIST' }],
* }),
* addPost: build.mutation<Post, Partial<Post>>({
* query(body) {
* return {
* url: `posts`,
* method: 'POST',
* body,
* }
* },
* // highlight-start
* invalidatesTags: [{ type: 'Posts', id: 'LIST' }],
* // highlight-end
* }),
* })
* })
* ```
*/
invalidatesTags?: ResultDescription<TagTypes, ResultType, QueryArg, BaseQueryError<BaseQuery>, BaseQueryMeta<BaseQuery>>;
/**
* Not to be used. A mutation should not provide tags to the cache.
*/
providesTags?: never;
/**
* All of these are `undefined` at runtime, purely to be used in TypeScript declarations!
*/
Types?: MutationTypes<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;
}
export declare type MutationDefinition<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string> = BaseEndpointDefinition<QueryArg, BaseQuery, ResultType> & MutationExtraOptions<TagTypes, ResultType, QueryArg, BaseQuery, ReducerPath>;
export declare type EndpointDefinition<QueryArg, BaseQuery extends BaseQueryFn, TagTypes extends string, ResultType, ReducerPath extends string = string> = QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath> | MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;
export declare type EndpointDefinitions = Record<string, EndpointDefinition<any, any, any, any>>;
export declare function isQueryDefinition(e: EndpointDefinition<any, any, any, any>): e is QueryDefinition<any, any, any, any>;
export declare function isMutationDefinition(e: EndpointDefinition<any, any, any, any>): e is MutationDefinition<any, any, any, any>;
export declare type EndpointBuilder<BaseQuery extends BaseQueryFn, TagTypes extends string, ReducerPath extends string> = {
/**
* An endpoint definition that retrieves data, and may provide tags to the cache.
*
* @example
* ```js
* // codeblock-meta title="Example of all query endpoint options"
* const api = createApi({
* baseQuery,
* endpoints: (build) => ({
* getPost: build.query({
* query: (id) => ({ url: `post/${id}` }),
* // Pick out data and prevent nested properties in a hook or selector
* transformResponse: (response) => response.data,
* // Pick out error and prevent nested properties in a hook or selector
* transformErrorResponse: (response) => response.error,
* // `result` is the server response
* providesTags: (result, error, id) => [{ type: 'Post', id }],
* // trigger side effects or optimistic updates
* onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry, updateCachedData }) {},
* // handle subscriptions etc
* onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry, updateCachedData }) {},
* }),
* }),
*});
*```
*/
query<ResultType, QueryArg>(definition: OmitFromUnion<QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>, 'type'>): QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;
/**
* An endpoint definition that alters data on the server or will possibly invalidate the cache.
*
* @example
* ```js
* // codeblock-meta title="Example of all mutation endpoint options"
* const api = createApi({
* baseQuery,
* endpoints: (build) => ({
* updatePost: build.mutation({
* query: ({ id, ...patch }) => ({ url: `post/${id}`, method: 'PATCH', body: patch }),
* // Pick out data and prevent nested properties in a hook or selector
* transformResponse: (response) => response.data,
* // Pick out error and prevent nested properties in a hook or selector
* transformErrorResponse: (response) => response.error,
* // `result` is the server response
* invalidatesTags: (result, error, id) => [{ type: 'Post', id }],
* // trigger side effects or optimistic updates
* onQueryStarted(id, { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry }) {},
* // handle subscriptions etc
* onCacheEntryAdded(id, { dispatch, getState, extra, requestId, cacheEntryRemoved, cacheDataLoaded, getCacheEntry }) {},
* }),
* }),
* });
* ```
*/
mutation<ResultType, QueryArg>(definition: OmitFromUnion<MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>, 'type'>): MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>;
};
export declare type AssertTagTypes = <T extends FullTagDescription<string>>(t: T) => T;
export declare function calculateProvidedBy<ResultType, QueryArg, ErrorType, MetaType>(description: ResultDescription<string, ResultType, QueryArg, ErrorType, MetaType> | undefined, result: ResultType | undefined, error: ErrorType | undefined, queryArg: QueryArg, meta: MetaType | undefined, assertTagTypes: AssertTagTypes): readonly FullTagDescription<string>[];
export declare function expandTagDescription(description: TagDescription<string>): FullTagDescription<string>;
export declare type QueryArgFrom<D extends BaseEndpointDefinition<any, any, any>> = D extends BaseEndpointDefinition<infer QA, any, any> ? QA : unknown;
export declare type ResultTypeFrom<D extends BaseEndpointDefinition<any, any, any>> = D extends BaseEndpointDefinition<any, any, infer RT> ? RT : unknown;
export declare type ReducerPathFrom<D extends EndpointDefinition<any, any, any, any, any>> = D extends EndpointDefinition<any, any, any, any, infer RP> ? RP : unknown;
export declare type TagTypesFrom<D extends EndpointDefinition<any, any, any, any>> = D extends EndpointDefinition<any, any, infer RP, any> ? RP : unknown;
export declare type ReplaceTagTypes<Definitions extends EndpointDefinitions, NewTagTypes extends string> = {
[K in keyof Definitions]: Definitions[K] extends QueryDefinition<infer QueryArg, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? QueryDefinition<QueryArg, BaseQuery, NewTagTypes, ResultType, ReducerPath> : Definitions[K] extends MutationDefinition<infer QueryArg, infer BaseQuery, any, infer ResultType, infer ReducerPath> ? MutationDefinition<QueryArg, BaseQuery, NewTagTypes, ResultType, ReducerPath> : never;
};
export {};

@ -0,0 +1,9 @@
import type { BaseQueryFn } from './baseQueryTypes';
declare const _NEVER: unique symbol;
export declare type NEVER = typeof _NEVER;
/**
* Creates a "fake" baseQuery to be used if your api *only* uses the `queryFn` definition syntax.
* This also allows you to specify a specific error type to be shared by all your `queryFn` definitions.
*/
export declare function fakeBaseQuery<ErrorType>(): BaseQueryFn<void, NEVER, ErrorType, {}>;
export {};

@ -0,0 +1,135 @@
import type { BaseQueryApi, BaseQueryFn } from './baseQueryTypes';
import type { MaybePromise, Override } from './tsHelpers';
export declare type ResponseHandler = 'content-type' | 'json' | 'text' | ((response: Response) => Promise<any>);
declare type CustomRequestInit = Override<RequestInit, {
headers?: Headers | string[][] | Record<string, string | undefined> | undefined;
}>;
export interface FetchArgs extends CustomRequestInit {
url: string;
params?: Record<string, any>;
body?: any;
responseHandler?: ResponseHandler;
validateStatus?: (response: Response, body: any) => boolean;
/**
* A number in milliseconds that represents that maximum time a request can take before timing out.
*/
timeout?: number;
}
export declare type FetchBaseQueryError = {
/**
* * `number`:
* HTTP status code
*/
status: number;
data: unknown;
} | {
/**
* * `"FETCH_ERROR"`:
* An error that occurred during execution of `fetch` or the `fetchFn` callback option
**/
status: 'FETCH_ERROR';
data?: undefined;
error: string;
} | {
/**
* * `"PARSING_ERROR"`:
* An error happened during parsing.
* Most likely a non-JSON-response was returned with the default `responseHandler` "JSON",
* or an error occurred while executing a custom `responseHandler`.
**/
status: 'PARSING_ERROR';
originalStatus: number;
data: string;
error: string;
} | {
/**
* * `"TIMEOUT_ERROR"`:
* Request timed out
**/
status: 'TIMEOUT_ERROR';
data?: undefined;
error: string;
} | {
/**
* * `"CUSTOM_ERROR"`:
* A custom error type that you can return from your `queryFn` where another error might not make sense.
**/
status: 'CUSTOM_ERROR';
data?: unknown;
error: string;
};
export declare type FetchBaseQueryArgs = {
baseUrl?: string;
prepareHeaders?: (headers: Headers, api: Pick<BaseQueryApi, 'getState' | 'extra' | 'endpoint' | 'type' | 'forced'>) => MaybePromise<Headers | void>;
fetchFn?: (input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>;
paramsSerializer?: (params: Record<string, any>) => string;
/**
* By default, we only check for 'application/json' and 'application/vnd.api+json' as the content-types for json. If you need to support another format, you can pass
* in a predicate function for your given api to get the same automatic stringifying behavior
* @example
* ```ts
* const isJsonContentType = (headers: Headers) => ["application/vnd.api+json", "application/json", "application/vnd.hal+json"].includes(headers.get("content-type")?.trim());
* ```
*/
isJsonContentType?: (headers: Headers) => boolean;
/**
* Defaults to `application/json`;
*/
jsonContentType?: string;
/**
* Custom replacer function used when calling `JSON.stringify()`;
*/
jsonReplacer?: (this: any, key: string, value: any) => any;
} & RequestInit & Pick<FetchArgs, 'responseHandler' | 'validateStatus' | 'timeout'>;
export declare type FetchBaseQueryMeta = {
request: Request;
response?: Response;
};
/**
* This is a very small wrapper around fetch that aims to simplify requests.
*
* @example
* ```ts
* const baseQuery = fetchBaseQuery({
* baseUrl: 'https://api.your-really-great-app.com/v1/',
* prepareHeaders: (headers, { getState }) => {
* const token = (getState() as RootState).auth.token;
* // If we have a token set in state, let's assume that we should be passing it.
* if (token) {
* headers.set('authorization', `Bearer ${token}`);
* }
* return headers;
* },
* })
* ```
*
* @param {string} baseUrl
* The base URL for an API service.
* Typically in the format of https://example.com/
*
* @param {(headers: Headers, api: { getState: () => unknown; extra: unknown; endpoint: string; type: 'query' | 'mutation'; forced: boolean; }) => Headers} prepareHeaders
* An optional function that can be used to inject headers on requests.
* Provides a Headers object, as well as most of the `BaseQueryApi` (`dispatch` is not available).
* Useful for setting authentication or headers that need to be set conditionally.
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/Headers
*
* @param {(input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>} fetchFn
* Accepts a custom `fetch` function if you do not want to use the default on the window.
* Useful in SSR environments if you need to use a library such as `isomorphic-fetch` or `cross-fetch`
*
* @param {(params: Record<string, unknown>) => string} paramsSerializer
* An optional function that can be used to stringify querystring parameters.
*
* @param {(headers: Headers) => boolean} isJsonContentType
* An optional predicate function to determine if `JSON.stringify()` should be called on the `body` arg of `FetchArgs`
*
* @param {string} jsonContentType Used when automatically setting the content-type header for a request with a jsonifiable body that does not have an explicit content-type header. Defaults to `application/json`.
*
* @param {(this: any, key: string, value: any) => any} jsonReplacer Custom replacer function used when calling `JSON.stringify()`.
*
* @param {number} timeout
* A number in milliseconds that represents the maximum time a request can take before timing out.
*/
export declare function fetchBaseQuery({ baseUrl, prepareHeaders, fetchFn, paramsSerializer, isJsonContentType, jsonContentType, jsonReplacer, timeout: defaultTimeout, validateStatus: globalValidateStatus, ...baseFetchOptions }?: FetchBaseQueryArgs): BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta>;
export {};

@ -0,0 +1,16 @@
export { QueryStatus } from './core/apiState';
export type { Api, Module, ApiModules } from './apiTypes';
export type { BaseQueryApi, BaseQueryEnhancer, BaseQueryFn, } from './baseQueryTypes';
export type { EndpointDefinitions, EndpointDefinition, QueryDefinition, MutationDefinition, TagDescription, } from './endpointDefinitions';
export { fetchBaseQuery } from './fetchBaseQuery';
export type { FetchBaseQueryError, FetchBaseQueryMeta, FetchArgs, } from './fetchBaseQuery';
export { retry } from './retry';
export { setupListeners } from './core/setupListeners';
export { skipSelector, skipToken } from './core/buildSelectors';
export type { SkipToken } from './core/buildSelectors';
export type { CreateApi, CreateApiOptions } from './createApi';
export { buildCreateApi } from './createApi';
export { fakeBaseQuery } from './fakeBaseQuery';
export { copyWithStructuralSharing } from './utils/copyWithStructuralSharing';
export { createApi, coreModule } from './core';
export { defaultSerializeQueryArgs } from './defaultSerializeQueryArgs';

@ -0,0 +1,6 @@
'use strict'
if (process.env.NODE_ENV === 'production') {
module.exports = require('./rtk-query.cjs.production.min.js')
} else {
module.exports = require('./rtk-query.cjs.development.js')
}

@ -0,0 +1,34 @@
import type { Context } from 'react';
import type { ReactReduxContextValue } from 'react-redux';
import { setupListeners } from '@reduxjs/toolkit/query';
import type { Api } from '@reduxjs/toolkit/dist/query/apiTypes';
/**
* Can be used as a `Provider` if you **do not already have a Redux store**.
*
* @example
* ```tsx
* // codeblock-meta title="Basic usage - wrap your App with ApiProvider"
* import * as React from 'react';
* import { ApiProvider } from '@reduxjs/toolkit/query/react';
* import { Pokemon } from './features/Pokemon';
*
* function App() {
* return (
* <ApiProvider api={api}>
* <Pokemon />
* </ApiProvider>
* );
* }
* ```
*
* @remarks
* Using this together with an existing redux store, both will
* conflict with each other - please use the traditional redux setup
* in that case.
*/
export declare function ApiProvider<A extends Api<any, {}, any, any>>(props: {
children: any;
api: A;
setupListeners?: Parameters<typeof setupListeners>[1] | false;
context?: Context<ReactReduxContextValue>;
}): JSX.Element;

@ -0,0 +1,375 @@
import { useEffect } from 'react';
import { QueryStatus } from '@reduxjs/toolkit/query';
import type { QuerySubState, SubscriptionOptions, QueryKeys } from '@reduxjs/toolkit/dist/query/core/apiState';
import type { EndpointDefinitions, MutationDefinition, QueryDefinition, QueryArgFrom, ResultTypeFrom } from '@reduxjs/toolkit/dist/query/endpointDefinitions';
import type { MutationResultSelectorResult, SkipToken } from '@reduxjs/toolkit/dist/query/core/buildSelectors';
import type { QueryActionCreatorResult, MutationActionCreatorResult } from '@reduxjs/toolkit/dist/query/core/buildInitiate';
import type { SerializeQueryArgs } from '@reduxjs/toolkit/dist/query/defaultSerializeQueryArgs';
import type { Api, ApiContext } from '@reduxjs/toolkit/dist/query/apiTypes';
import type { Id, NoInfer, Override } from '@reduxjs/toolkit/dist/query/tsHelpers';
import type { CoreModule, PrefetchOptions } from '@reduxjs/toolkit/dist/query/core/module';
import type { ReactHooksModuleOptions } from './module';
import type { UninitializedValue } from './constants';
import type { BaseQueryFn } from '../baseQueryTypes';
export declare const useIsomorphicLayoutEffect: typeof useEffect;
export interface QueryHooks<Definition extends QueryDefinition<any, any, any, any, any>> {
useQuery: UseQuery<Definition>;
useLazyQuery: UseLazyQuery<Definition>;
useQuerySubscription: UseQuerySubscription<Definition>;
useLazyQuerySubscription: UseLazyQuerySubscription<Definition>;
useQueryState: UseQueryState<Definition>;
}
export interface MutationHooks<Definition extends MutationDefinition<any, any, any, any, any>> {
useMutation: UseMutation<Definition>;
}
/**
* A React hook that automatically triggers fetches of data from an endpoint, 'subscribes' the component to the cached data, and reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available.
*
* The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already, and the hook will return the data for that query arg once it's available.
*
* This hook combines the functionality of both [`useQueryState`](#usequerystate) and [`useQuerySubscription`](#usequerysubscription) together, and is intended to be used in the majority of situations.
*
* #### Features
*
* - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
* - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
* - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
* - Returns the latest request status and cached data from the Redux store
* - Re-renders as the request status changes and data becomes available
*/
export declare type UseQuery<D extends QueryDefinition<any, any, any, any>> = <R extends Record<string, any> = UseQueryStateDefaultResult<D>>(arg: QueryArgFrom<D> | SkipToken, options?: UseQuerySubscriptionOptions & UseQueryStateOptions<D, R>) => UseQueryHookResult<D, R>;
export declare type UseQueryHookResult<D extends QueryDefinition<any, any, any, any>, R = UseQueryStateDefaultResult<D>> = UseQueryStateResult<D, R> & UseQuerySubscriptionResult<D>;
/**
* Helper type to manually type the result
* of the `useQuery` hook in userland code.
*/
export declare type TypedUseQueryHookResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = TypedUseQueryStateResult<ResultType, QueryArg, BaseQuery, R> & TypedUseQuerySubscriptionResult<ResultType, QueryArg, BaseQuery>;
interface UseQuerySubscriptionOptions extends SubscriptionOptions {
/**
* Prevents a query from automatically running.
*
* @remarks
* When `skip` is true (or `skipToken` is passed in as `arg`):
*
* - **If the query has cached data:**
* * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed
* * The query will have a status of `uninitialized`
* * If `skip: false` is set after the initial load, the cached result will be used
* - **If the query does not have cached data:**
* * The query will have a status of `uninitialized`
* * The query will not exist in the state when viewed with the dev tools
* * The query will not automatically fetch on mount
* * The query will not automatically run when additional components with the same query are added that do run
*
* @example
* ```tsx
* // codeblock-meta title="Skip example"
* const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {
* const { data, error, status } = useGetPokemonByNameQuery(name, {
* skip,
* });
*
* return (
* <div>
* {name} - {status}
* </div>
* );
* };
* ```
*/
skip?: boolean;
/**
* Defaults to `false`. This setting allows you to control whether if a cached result is already available, RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.
* - `false` - Will not cause a query to be performed _unless_ it does not exist yet.
* - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.
* - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.
*
* If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
*/
refetchOnMountOrArgChange?: boolean | number;
}
/**
* A React hook that automatically triggers fetches of data from an endpoint, and 'subscribes' the component to the cached data.
*
* The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already.
*
* Note that this hook does not return a request status or cached data. For that use-case, see [`useQuery`](#usequery) or [`useQueryState`](#usequerystate).
*
* #### Features
*
* - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
* - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
* - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
*/
export declare type UseQuerySubscription<D extends QueryDefinition<any, any, any, any>> = (arg: QueryArgFrom<D> | SkipToken, options?: UseQuerySubscriptionOptions) => UseQuerySubscriptionResult<D>;
export declare type UseQuerySubscriptionResult<D extends QueryDefinition<any, any, any, any>> = Pick<QueryActionCreatorResult<D>, 'refetch'>;
/**
* Helper type to manually type the result
* of the `useQuerySubscription` hook in userland code.
*/
export declare type TypedUseQuerySubscriptionResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuerySubscriptionResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
export declare type UseLazyQueryLastPromiseInfo<D extends QueryDefinition<any, any, any, any>> = {
lastArg: QueryArgFrom<D>;
};
/**
* A React hook similar to [`useQuery`](#usequery), but with manual control over when the data fetching occurs.
*
* This hook includes the functionality of [`useLazyQuerySubscription`](#uselazyquerysubscription).
*
* #### Features
*
* - Manual control over firing a request to retrieve data
* - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
* - Returns the latest request status and cached data from the Redux store
* - Re-renders as the request status changes and data becomes available
* - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met and the fetch has been manually called at least once
*
* #### Note
*
* When the trigger function returned from a LazyQuery is called, it always initiates a new request to the server even if there is cached data. Set `preferCacheValue`(the second argument to the function) as `true` if you want it to immediately return a cached value if one exists.
*/
export declare type UseLazyQuery<D extends QueryDefinition<any, any, any, any>> = <R extends Record<string, any> = UseQueryStateDefaultResult<D>>(options?: SubscriptionOptions & Omit<UseQueryStateOptions<D, R>, 'skip'>) => [
LazyQueryTrigger<D>,
UseQueryStateResult<D, R>,
UseLazyQueryLastPromiseInfo<D>
];
export declare type LazyQueryTrigger<D extends QueryDefinition<any, any, any, any>> = {
/**
* Triggers a lazy query.
*
* By default, this will start a new request even if there is already a value in the cache.
* If you want to use the cache value and only start a request if there is no cache value, set the second argument to `true`.
*
* @remarks
* If you need to access the error or success payload immediately after a lazy query, you can chain .unwrap().
*
* @example
* ```ts
* // codeblock-meta title="Using .unwrap with async await"
* try {
* const payload = await getUserById(1).unwrap();
* console.log('fulfilled', payload)
* } catch (error) {
* console.error('rejected', error);
* }
* ```
*/
(arg: QueryArgFrom<D>, preferCacheValue?: boolean): QueryActionCreatorResult<D>;
};
/**
* A React hook similar to [`useQuerySubscription`](#usequerysubscription), but with manual control over when the data fetching occurs.
*
* Note that this hook does not return a request status or cached data. For that use-case, see [`useLazyQuery`](#uselazyquery).
*
* #### Features
*
* - Manual control over firing a request to retrieve data
* - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
* - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met and the fetch has been manually called at least once
*/
export declare type UseLazyQuerySubscription<D extends QueryDefinition<any, any, any, any>> = (options?: SubscriptionOptions) => readonly [LazyQueryTrigger<D>, QueryArgFrom<D> | UninitializedValue];
export declare type QueryStateSelector<R extends Record<string, any>, D extends QueryDefinition<any, any, any, any>> = (state: UseQueryStateDefaultResult<D>) => R;
/**
* A React hook that reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available.
*
* Note that this hook does not trigger fetching new data. For that use-case, see [`useQuery`](#usequery) or [`useQuerySubscription`](#usequerysubscription).
*
* #### Features
*
* - Returns the latest request status and cached data from the Redux store
* - Re-renders as the request status changes and data becomes available
*/
export declare type UseQueryState<D extends QueryDefinition<any, any, any, any>> = <R extends Record<string, any> = UseQueryStateDefaultResult<D>>(arg: QueryArgFrom<D> | SkipToken, options?: UseQueryStateOptions<D, R>) => UseQueryStateResult<D, R>;
export declare type UseQueryStateOptions<D extends QueryDefinition<any, any, any, any>, R extends Record<string, any>> = {
/**
* Prevents a query from automatically running.
*
* @remarks
* When skip is true:
*
* - **If the query has cached data:**
* * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed
* * The query will have a status of `uninitialized`
* * If `skip: false` is set after skipping the initial load, the cached result will be used
* - **If the query does not have cached data:**
* * The query will have a status of `uninitialized`
* * The query will not exist in the state when viewed with the dev tools
* * The query will not automatically fetch on mount
* * The query will not automatically run when additional components with the same query are added that do run
*
* @example
* ```ts
* // codeblock-meta title="Skip example"
* const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {
* const { data, error, status } = useGetPokemonByNameQuery(name, {
* skip,
* });
*
* return (
* <div>
* {name} - {status}
* </div>
* );
* };
* ```
*/
skip?: boolean;
/**
* `selectFromResult` allows you to get a specific segment from a query result in a performant manner.
* When using this feature, the component will not rerender unless the underlying data of the selected item has changed.
* If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection.
*
* @example
* ```ts
* // codeblock-meta title="Using selectFromResult to extract a single result"
* function PostsList() {
* const { data: posts } = api.useGetPostsQuery();
*
* return (
* <ul>
* {posts?.data?.map((post) => (
* <PostById key={post.id} id={post.id} />
* ))}
* </ul>
* );
* }
*
* function PostById({ id }: { id: number }) {
* // Will select the post with the given id, and will only rerender if the given posts data changes
* const { post } = api.useGetPostsQuery(undefined, {
* selectFromResult: ({ data }) => ({ post: data?.find((post) => post.id === id) }),
* });
*
* return <li>{post?.name}</li>;
* }
* ```
*/
selectFromResult?: QueryStateSelector<R, D>;
};
export declare type UseQueryStateResult<_ extends QueryDefinition<any, any, any, any>, R> = NoInfer<R>;
/**
* Helper type to manually type the result
* of the `useQueryState` hook in userland code.
*/
export declare type TypedUseQueryStateResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = NoInfer<R>;
declare type UseQueryStateBaseResult<D extends QueryDefinition<any, any, any, any>> = QuerySubState<D> & {
/**
* Where `data` tries to hold data as much as possible, also re-using
* data from the last arguments passed into the hook, this property
* will always contain the received data from the query, for the current query arguments.
*/
currentData?: ResultTypeFrom<D>;
/**
* Query has not started yet.
*/
isUninitialized: false;
/**
* Query is currently loading for the first time. No data yet.
*/
isLoading: false;
/**
* Query is currently fetching, but might have data from an earlier request.
*/
isFetching: false;
/**
* Query has data from a successful load.
*/
isSuccess: false;
/**
* Query is currently in "error" state.
*/
isError: false;
};
declare type UseQueryStateDefaultResult<D extends QueryDefinition<any, any, any, any>> = Id<Override<Extract<UseQueryStateBaseResult<D>, {
status: QueryStatus.uninitialized;
}>, {
isUninitialized: true;
}> | Override<UseQueryStateBaseResult<D>, {
isLoading: true;
isFetching: boolean;
data: undefined;
} | ({
isSuccess: true;
isFetching: true;
error: undefined;
} & Required<Pick<UseQueryStateBaseResult<D>, 'data' | 'fulfilledTimeStamp'>>) | ({
isSuccess: true;
isFetching: false;
error: undefined;
} & Required<Pick<UseQueryStateBaseResult<D>, 'data' | 'fulfilledTimeStamp' | 'currentData'>>) | ({
isError: true;
} & Required<Pick<UseQueryStateBaseResult<D>, 'error'>>)>> & {
/**
* @deprecated will be removed in the next version
* please use the `isLoading`, `isFetching`, `isSuccess`, `isError`
* and `isUninitialized` flags instead
*/
status: QueryStatus;
};
export declare type MutationStateSelector<R extends Record<string, any>, D extends MutationDefinition<any, any, any, any>> = (state: MutationResultSelectorResult<D>) => R;
export declare type UseMutationStateOptions<D extends MutationDefinition<any, any, any, any>, R extends Record<string, any>> = {
selectFromResult?: MutationStateSelector<R, D>;
fixedCacheKey?: string;
};
export declare type UseMutationStateResult<D extends MutationDefinition<any, any, any, any>, R> = NoInfer<R> & {
originalArgs?: QueryArgFrom<D>;
/**
* Resets the hook state to it's initial `uninitialized` state.
* This will also remove the last result from the cache.
*/
reset: () => void;
};
/**
* Helper type to manually type the result
* of the `useMutation` hook in userland code.
*/
export declare type TypedUseMutationResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = MutationResultSelectorResult<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = UseMutationStateResult<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>, R>;
/**
* A React hook that lets you trigger an update request for a given endpoint, and subscribes the component to read the request status from the Redux store. The component will re-render as the loading status changes.
*
* #### Features
*
* - Manual control over firing a request to alter data on the server or possibly invalidate the cache
* - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
* - Returns the latest request status and cached data from the Redux store
* - Re-renders as the request status changes and data becomes available
*/
export declare type UseMutation<D extends MutationDefinition<any, any, any, any>> = <R extends Record<string, any> = MutationResultSelectorResult<D>>(options?: UseMutationStateOptions<D, R>) => readonly [MutationTrigger<D>, UseMutationStateResult<D, R>];
export declare type MutationTrigger<D extends MutationDefinition<any, any, any, any>> = {
/**
* Triggers the mutation and returns a Promise.
* @remarks
* If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().
*
* @example
* ```ts
* // codeblock-meta title="Using .unwrap with async await"
* try {
* const payload = await addPost({ id: 1, name: 'Example' }).unwrap();
* console.log('fulfilled', payload)
* } catch (error) {
* console.error('rejected', error);
* }
* ```
*/
(arg: QueryArgFrom<D>): MutationActionCreatorResult<D>;
};
/**
*
* @param opts.api - An API with defined endpoints to create hooks for
* @param opts.moduleOptions.batch - The version of the `batchedUpdates` function to be used
* @param opts.moduleOptions.useDispatch - The version of the `useDispatch` hook to be used
* @param opts.moduleOptions.useSelector - The version of the `useSelector` hook to be used
* @returns An object containing functions to generate hooks based on an endpoint
*/
export declare function buildHooks<Definitions extends EndpointDefinitions>({ api, moduleOptions: { batch, useDispatch, useSelector, useStore, unstable__sideEffectsInRender, }, serializeQueryArgs, context, }: {
api: Api<any, Definitions, any, any, CoreModule>;
moduleOptions: Required<ReactHooksModuleOptions>;
serializeQueryArgs: SerializeQueryArgs<any>;
context: ApiContext<Definitions>;
}): {
buildQueryHooks: (name: string) => QueryHooks<any>;
buildMutationHook: (name: string) => UseMutation<any>;
usePrefetch: <EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, defaultOptions?: PrefetchOptions | undefined) => (arg: any, options?: PrefetchOptions | undefined) => void;
};
export {};

@ -0,0 +1,2 @@
export declare const UNINITIALIZED_VALUE: unique symbol;
export declare type UninitializedValue = typeof UNINITIALIZED_VALUE;

@ -0,0 +1,7 @@
import { CreateApi } from '@reduxjs/toolkit/query';
import { reactHooksModule, reactHooksModuleName } from './module';
export * from '@reduxjs/toolkit/query';
export { ApiProvider } from './ApiProvider';
declare const createApi: CreateApi<typeof import("@reduxjs/toolkit/dist/query/core/module").coreModuleName | typeof reactHooksModuleName>;
export type { TypedUseQueryHookResult, TypedUseQueryStateResult, TypedUseQuerySubscriptionResult, TypedUseMutationResult, } from './buildHooks';
export { createApi, reactHooksModule };

@ -0,0 +1,6 @@
'use strict'
if (process.env.NODE_ENV === 'production') {
module.exports = require('./rtk-query-react.cjs.production.min.js')
} else {
module.exports = require('./rtk-query-react.cjs.development.js')
}

@ -0,0 +1,79 @@
import type { MutationHooks, QueryHooks } from './buildHooks';
import type { EndpointDefinitions, QueryDefinition, MutationDefinition, QueryArgFrom } from '@reduxjs/toolkit/dist/query/endpointDefinitions';
import type { Module } from '../apiTypes';
import type { BaseQueryFn } from '@reduxjs/toolkit/dist/query/baseQueryTypes';
import type { HooksWithUniqueNames } from './namedHooks';
import type { QueryKeys } from '../core/apiState';
import type { PrefetchOptions } from '../core/module';
export declare const reactHooksModuleName: unique symbol;
export declare type ReactHooksModule = typeof reactHooksModuleName;
declare module '@reduxjs/toolkit/dist/query/apiTypes' {
interface ApiModules<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string> {
[reactHooksModuleName]: {
/**
* Endpoints based on the input endpoints provided to `createApi`, containing `select`, `hooks` and `action matchers`.
*/
endpoints: {
[K in keyof Definitions]: Definitions[K] extends QueryDefinition<any, any, any, any, any> ? QueryHooks<Definitions[K]> : Definitions[K] extends MutationDefinition<any, any, any, any, any> ? MutationHooks<Definitions[K]> : never;
};
/**
* A hook that accepts a string endpoint name, and provides a callback that when called, pre-fetches the data for that endpoint.
*/
usePrefetch<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, options?: PrefetchOptions): (arg: QueryArgFrom<Definitions[EndpointName]>, options?: PrefetchOptions) => void;
} & HooksWithUniqueNames<Definitions>;
}
}
declare type RR = typeof import('react-redux');
export interface ReactHooksModuleOptions {
/**
* The version of the `batchedUpdates` function to be used
*/
batch?: RR['batch'];
/**
* The version of the `useDispatch` hook to be used
*/
useDispatch?: RR['useDispatch'];
/**
* The version of the `useSelector` hook to be used
*/
useSelector?: RR['useSelector'];
/**
* The version of the `useStore` hook to be used
*/
useStore?: RR['useStore'];
/**
* Enables performing asynchronous tasks immediately within a render.
*
* @example
*
* ```ts
* import {
* buildCreateApi,
* coreModule,
* reactHooksModule
* } from '@reduxjs/toolkit/query/react'
*
* const createApi = buildCreateApi(
* coreModule(),
* reactHooksModule({ unstable__sideEffectsInRender: true })
* )
* ```
*/
unstable__sideEffectsInRender?: boolean;
}
/**
* Creates a module that generates react hooks from endpoints, for use with `buildCreateApi`.
*
* @example
* ```ts
* const MyContext = React.createContext<ReactReduxContextValue>(null as any);
* const customCreateApi = buildCreateApi(
* coreModule(),
* reactHooksModule({ useDispatch: createDispatchHook(MyContext) })
* );
* ```
*
* @returns A module for use with `buildCreateApi`
*/
export declare const reactHooksModule: ({ batch, useDispatch, useSelector, useStore, unstable__sideEffectsInRender, }?: ReactHooksModuleOptions) => Module<ReactHooksModule>;
export {};

@ -0,0 +1,13 @@
import type { UseMutation, UseLazyQuery, UseQuery } from './buildHooks';
import type { DefinitionType, EndpointDefinitions, MutationDefinition, QueryDefinition } from '@reduxjs/toolkit/dist/query/endpointDefinitions';
export declare type HooksWithUniqueNames<Definitions extends EndpointDefinitions> = keyof Definitions extends infer Keys ? Keys extends string ? Definitions[Keys] extends {
type: DefinitionType.query;
} ? {
[K in Keys as `use${Capitalize<K>}Query`]: UseQuery<Extract<Definitions[K], QueryDefinition<any, any, any, any>>>;
} & {
[K in Keys as `useLazy${Capitalize<K>}Query`]: UseLazyQuery<Extract<Definitions[K], QueryDefinition<any, any, any, any>>>;
} : Definitions[Keys] extends {
type: DefinitionType.mutation;
} ? {
[K in Keys as `use${Capitalize<K>}Mutation`]: UseMutation<Extract<Definitions[K], MutationDefinition<any, any, any, any>>>;
} : never : never : never;

@ -0,0 +1,490 @@
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
var __create = Object.create;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = function (obj, key, value) { return key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value: value }) : obj[key] = value; };
var __spreadValues = function (a, b) {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var _i = 0, _c = __getOwnPropSymbols(b); _i < _c.length; _i++) {
var prop = _c[_i];
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = function (a, b) { return __defProps(a, __getOwnPropDescs(b)); };
var __markAsModule = function (target) { return __defProp(target, "__esModule", { value: true }); };
var __export = function (target, all) {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __reExport = function (target, module2, desc) {
if (module2 && typeof module2 === "object" || typeof module2 === "function") {
var _loop_1 = function (key) {
if (!__hasOwnProp.call(target, key) && key !== "default")
__defProp(target, key, { get: function () { return module2[key]; }, enumerable: !(desc = __getOwnPropDesc(module2, key)) || desc.enumerable });
};
for (var _i = 0, _c = __getOwnPropNames(module2); _i < _c.length; _i++) {
var key = _c[_i];
_loop_1(key);
}
}
return target;
};
var __toModule = function (module2) {
return __reExport(__markAsModule(__defProp(module2 != null ? __create(__getProtoOf(module2)) : {}, "default", module2 && module2.__esModule && "default" in module2 ? { get: function () { return module2.default; }, enumerable: true } : { value: module2, enumerable: true })), module2);
};
// src/query/react/index.ts
__markAsModule(exports);
__export(exports, {
ApiProvider: function () { return ApiProvider; },
createApi: function () { return createApi; },
reactHooksModule: function () { return reactHooksModule; }
});
var import_query3 = __toModule(require("@reduxjs/toolkit/query"));
// src/query/react/buildHooks.ts
var import_toolkit2 = __toModule(require("@reduxjs/toolkit"));
var import_react3 = __toModule(require("react"));
var import_query = __toModule(require("@reduxjs/toolkit/query"));
var import_react_redux2 = __toModule(require("react-redux"));
// src/query/react/useSerializedStableValue.ts
var import_react = __toModule(require("react"));
function useStableQueryArgs(queryArgs, serialize, endpointDefinition, endpointName) {
var incoming = (0, import_react.useMemo)(function () { return ({
queryArgs: queryArgs,
serialized: typeof queryArgs == "object" ? serialize({ queryArgs: queryArgs, endpointDefinition: endpointDefinition, endpointName: endpointName }) : queryArgs
}); }, [queryArgs, serialize, endpointDefinition, endpointName]);
var cache2 = (0, import_react.useRef)(incoming);
(0, import_react.useEffect)(function () {
if (cache2.current.serialized !== incoming.serialized) {
cache2.current = incoming;
}
}, [incoming]);
return cache2.current.serialized === incoming.serialized ? cache2.current.queryArgs : queryArgs;
}
// src/query/react/constants.ts
var UNINITIALIZED_VALUE = Symbol();
// src/query/react/useShallowStableValue.ts
var import_react2 = __toModule(require("react"));
var import_react_redux = __toModule(require("react-redux"));
function useShallowStableValue(value) {
var cache2 = (0, import_react2.useRef)(value);
(0, import_react2.useEffect)(function () {
if (!(0, import_react_redux.shallowEqual)(cache2.current, value)) {
cache2.current = value;
}
}, [value]);
return (0, import_react_redux.shallowEqual)(cache2.current, value) ? cache2.current : value;
}
// src/query/defaultSerializeQueryArgs.ts
var import_toolkit = __toModule(require("@reduxjs/toolkit"));
var cache = WeakMap ? new WeakMap() : void 0;
var defaultSerializeQueryArgs = function (_c) {
var endpointName = _c.endpointName, queryArgs = _c.queryArgs;
var serialized = "";
var cached = cache == null ? void 0 : cache.get(queryArgs);
if (typeof cached === "string") {
serialized = cached;
}
else {
var stringified = JSON.stringify(queryArgs, function (key, value) { return (0, import_toolkit.isPlainObject)(value) ? Object.keys(value).sort().reduce(function (acc, key2) {
acc[key2] = value[key2];
return acc;
}, {}) : value; });
if ((0, import_toolkit.isPlainObject)(queryArgs)) {
cache == null ? void 0 : cache.set(queryArgs, stringified);
}
serialized = stringified;
}
return endpointName + "(" + serialized + ")";
};
// src/query/react/buildHooks.ts
var useIsomorphicLayoutEffect = typeof window !== "undefined" && !!window.document && !!window.document.createElement ? import_react3.useLayoutEffect : import_react3.useEffect;
var defaultMutationStateSelector = function (x) { return x; };
var noPendingQueryStateSelector = function (selected) {
if (selected.isUninitialized) {
return __spreadProps(__spreadValues({}, selected), {
isUninitialized: false,
isFetching: true,
isLoading: selected.data !== void 0 ? false : true,
status: import_query.QueryStatus.pending
});
}
return selected;
};
function buildHooks(_c) {
var api = _c.api, _d = _c.moduleOptions, batch = _d.batch, useDispatch = _d.useDispatch, useSelector = _d.useSelector, useStore = _d.useStore, unstable__sideEffectsInRender = _d.unstable__sideEffectsInRender, serializeQueryArgs = _c.serializeQueryArgs, context = _c.context;
var usePossiblyImmediateEffect = unstable__sideEffectsInRender ? function (cb) { return cb(); } : import_react3.useEffect;
return { buildQueryHooks: buildQueryHooks, buildMutationHook: buildMutationHook, usePrefetch: usePrefetch };
function queryStatePreSelector(currentState, lastResult, queryArgs) {
if ((lastResult == null ? void 0 : lastResult.endpointName) && currentState.isUninitialized) {
var endpointName = lastResult.endpointName;
var endpointDefinition = context.endpointDefinitions[endpointName];
if (serializeQueryArgs({
queryArgs: lastResult.originalArgs,
endpointDefinition: endpointDefinition,
endpointName: endpointName
}) === serializeQueryArgs({
queryArgs: queryArgs,
endpointDefinition: endpointDefinition,
endpointName: endpointName
}))
lastResult = void 0;
}
var data = currentState.isSuccess ? currentState.data : lastResult == null ? void 0 : lastResult.data;
if (data === void 0)
data = currentState.data;
var hasData = data !== void 0;
var isFetching = currentState.isLoading;
var isLoading = !hasData && isFetching;
var isSuccess = currentState.isSuccess || isFetching && hasData;
return __spreadProps(__spreadValues({}, currentState), {
data: data,
currentData: currentState.data,
isFetching: isFetching,
isLoading: isLoading,
isSuccess: isSuccess
});
}
function usePrefetch(endpointName, defaultOptions) {
var dispatch = useDispatch();
var stableDefaultOptions = useShallowStableValue(defaultOptions);
return (0, import_react3.useCallback)(function (arg, options) { return dispatch(api.util.prefetch(endpointName, arg, __spreadValues(__spreadValues({}, stableDefaultOptions), options))); }, [endpointName, dispatch, stableDefaultOptions]);
}
function buildQueryHooks(name) {
var useQuerySubscription = function (arg, _c) {
var _d = _c === void 0 ? {} : _c, refetchOnReconnect = _d.refetchOnReconnect, refetchOnFocus = _d.refetchOnFocus, refetchOnMountOrArgChange = _d.refetchOnMountOrArgChange, _e = _d.skip, skip = _e === void 0 ? false : _e, _f = _d.pollingInterval, pollingInterval = _f === void 0 ? 0 : _f;
var initiate = api.endpoints[name].initiate;
var dispatch = useDispatch();
var stableArg = useStableQueryArgs(skip ? import_query.skipToken : arg, defaultSerializeQueryArgs, context.endpointDefinitions[name], name);
var stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect: refetchOnReconnect,
refetchOnFocus: refetchOnFocus,
pollingInterval: pollingInterval
});
var lastRenderHadSubscription = (0, import_react3.useRef)(false);
var promiseRef = (0, import_react3.useRef)();
var _g = promiseRef.current || {}, queryCacheKey = _g.queryCacheKey, requestId = _g.requestId;
var currentRenderHasSubscription = false;
if (queryCacheKey && requestId) {
var returnedValue = dispatch(api.internalActions.internal_probeSubscription({
queryCacheKey: queryCacheKey,
requestId: requestId
}));
if (true) {
if (typeof returnedValue !== "boolean") {
throw new Error("Warning: Middleware for RTK-Query API at reducerPath \"" + api.reducerPath + "\" has not been added to the store.\n You must add the middleware for RTK-Query to function correctly!");
}
}
currentRenderHasSubscription = !!returnedValue;
}
var subscriptionRemoved = !currentRenderHasSubscription && lastRenderHadSubscription.current;
usePossiblyImmediateEffect(function () {
lastRenderHadSubscription.current = currentRenderHasSubscription;
});
usePossiblyImmediateEffect(function () {
if (subscriptionRemoved) {
promiseRef.current = void 0;
}
}, [subscriptionRemoved]);
usePossiblyImmediateEffect(function () {
var _a;
var lastPromise = promiseRef.current;
if (typeof process !== "undefined" && false) {
console.log(subscriptionRemoved);
}
if (stableArg === import_query.skipToken) {
lastPromise == null ? void 0 : lastPromise.unsubscribe();
promiseRef.current = void 0;
return;
}
var lastSubscriptionOptions = (_a = promiseRef.current) == null ? void 0 : _a.subscriptionOptions;
if (!lastPromise || lastPromise.arg !== stableArg) {
lastPromise == null ? void 0 : lastPromise.unsubscribe();
var promise = dispatch(initiate(stableArg, {
subscriptionOptions: stableSubscriptionOptions,
forceRefetch: refetchOnMountOrArgChange
}));
promiseRef.current = promise;
}
else if (stableSubscriptionOptions !== lastSubscriptionOptions) {
lastPromise.updateSubscriptionOptions(stableSubscriptionOptions);
}
}, [
dispatch,
initiate,
refetchOnMountOrArgChange,
stableArg,
stableSubscriptionOptions,
subscriptionRemoved
]);
(0, import_react3.useEffect)(function () {
return function () {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = void 0;
};
}, []);
return (0, import_react3.useMemo)(function () { return ({
refetch: function () {
var _a;
if (!promiseRef.current)
throw new Error("Cannot refetch a query that has not been started yet.");
return (_a = promiseRef.current) == null ? void 0 : _a.refetch();
}
}); }, []);
};
var useLazyQuerySubscription = function (_c) {
var _d = _c === void 0 ? {} : _c, refetchOnReconnect = _d.refetchOnReconnect, refetchOnFocus = _d.refetchOnFocus, _e = _d.pollingInterval, pollingInterval = _e === void 0 ? 0 : _e;
var initiate = api.endpoints[name].initiate;
var dispatch = useDispatch();
var _f = (0, import_react3.useState)(UNINITIALIZED_VALUE), arg = _f[0], setArg = _f[1];
var promiseRef = (0, import_react3.useRef)();
var stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect: refetchOnReconnect,
refetchOnFocus: refetchOnFocus,
pollingInterval: pollingInterval
});
usePossiblyImmediateEffect(function () {
var _a, _b;
var lastSubscriptionOptions = (_a = promiseRef.current) == null ? void 0 : _a.subscriptionOptions;
if (stableSubscriptionOptions !== lastSubscriptionOptions) {
(_b = promiseRef.current) == null ? void 0 : _b.updateSubscriptionOptions(stableSubscriptionOptions);
}
}, [stableSubscriptionOptions]);
var subscriptionOptionsRef = (0, import_react3.useRef)(stableSubscriptionOptions);
usePossiblyImmediateEffect(function () {
subscriptionOptionsRef.current = stableSubscriptionOptions;
}, [stableSubscriptionOptions]);
var trigger = (0, import_react3.useCallback)(function (arg2, preferCacheValue) {
if (preferCacheValue === void 0) { preferCacheValue = false; }
var promise;
batch(function () {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = promise = dispatch(initiate(arg2, {
subscriptionOptions: subscriptionOptionsRef.current,
forceRefetch: !preferCacheValue
}));
setArg(arg2);
});
return promise;
}, [dispatch, initiate]);
(0, import_react3.useEffect)(function () {
return function () {
var _a;
(_a = promiseRef == null ? void 0 : promiseRef.current) == null ? void 0 : _a.unsubscribe();
};
}, []);
(0, import_react3.useEffect)(function () {
if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {
trigger(arg, true);
}
}, [arg, trigger]);
return (0, import_react3.useMemo)(function () { return [trigger, arg]; }, [trigger, arg]);
};
var useQueryState = function (arg, _c) {
var _d = _c === void 0 ? {} : _c, _e = _d.skip, skip = _e === void 0 ? false : _e, selectFromResult = _d.selectFromResult;
var select = api.endpoints[name].select;
var stableArg = useStableQueryArgs(skip ? import_query.skipToken : arg, serializeQueryArgs, context.endpointDefinitions[name], name);
var lastValue = (0, import_react3.useRef)();
var selectDefaultResult = (0, import_react3.useMemo)(function () { return (0, import_toolkit2.createSelector)([
select(stableArg),
function (_, lastResult) { return lastResult; },
function (_) { return stableArg; }
], queryStatePreSelector); }, [select, stableArg]);
var querySelector = (0, import_react3.useMemo)(function () { return selectFromResult ? (0, import_toolkit2.createSelector)([selectDefaultResult], selectFromResult) : selectDefaultResult; }, [selectDefaultResult, selectFromResult]);
var currentState = useSelector(function (state) { return querySelector(state, lastValue.current); }, import_react_redux2.shallowEqual);
var store = useStore();
var newLastValue = selectDefaultResult(store.getState(), lastValue.current);
useIsomorphicLayoutEffect(function () {
lastValue.current = newLastValue;
}, [newLastValue]);
return currentState;
};
return {
useQueryState: useQueryState,
useQuerySubscription: useQuerySubscription,
useLazyQuerySubscription: useLazyQuerySubscription,
useLazyQuery: function (options) {
var _c = useLazyQuerySubscription(options), trigger = _c[0], arg = _c[1];
var queryStateResults = useQueryState(arg, __spreadProps(__spreadValues({}, options), {
skip: arg === UNINITIALIZED_VALUE
}));
var info = (0, import_react3.useMemo)(function () { return ({ lastArg: arg }); }, [arg]);
return (0, import_react3.useMemo)(function () { return [trigger, queryStateResults, info]; }, [trigger, queryStateResults, info]);
},
useQuery: function (arg, options) {
var querySubscriptionResults = useQuerySubscription(arg, options);
var queryStateResults = useQueryState(arg, __spreadValues({
selectFromResult: arg === import_query.skipToken || (options == null ? void 0 : options.skip) ? void 0 : noPendingQueryStateSelector
}, options));
var data = queryStateResults.data, status = queryStateResults.status, isLoading = queryStateResults.isLoading, isSuccess = queryStateResults.isSuccess, isError = queryStateResults.isError, error = queryStateResults.error;
(0, import_react3.useDebugValue)({ data: data, status: status, isLoading: isLoading, isSuccess: isSuccess, isError: isError, error: error });
return (0, import_react3.useMemo)(function () { return __spreadValues(__spreadValues({}, queryStateResults), querySubscriptionResults); }, [queryStateResults, querySubscriptionResults]);
}
};
}
function buildMutationHook(name) {
return function (_c) {
var _d = _c === void 0 ? {} : _c, _e = _d.selectFromResult, selectFromResult = _e === void 0 ? defaultMutationStateSelector : _e, fixedCacheKey = _d.fixedCacheKey;
var _f = api.endpoints[name], select = _f.select, initiate = _f.initiate;
var dispatch = useDispatch();
var _g = (0, import_react3.useState)(), promise = _g[0], setPromise = _g[1];
(0, import_react3.useEffect)(function () { return function () {
if (!(promise == null ? void 0 : promise.arg.fixedCacheKey)) {
promise == null ? void 0 : promise.reset();
}
}; }, [promise]);
var triggerMutation = (0, import_react3.useCallback)(function (arg) {
var promise2 = dispatch(initiate(arg, { fixedCacheKey: fixedCacheKey }));
setPromise(promise2);
return promise2;
}, [dispatch, initiate, fixedCacheKey]);
var requestId = (promise || {}).requestId;
var mutationSelector = (0, import_react3.useMemo)(function () { return (0, import_toolkit2.createSelector)([select({ fixedCacheKey: fixedCacheKey, requestId: promise == null ? void 0 : promise.requestId })], selectFromResult); }, [select, promise, selectFromResult, fixedCacheKey]);
var currentState = useSelector(mutationSelector, import_react_redux2.shallowEqual);
var originalArgs = fixedCacheKey == null ? promise == null ? void 0 : promise.arg.originalArgs : void 0;
var reset = (0, import_react3.useCallback)(function () {
batch(function () {
if (promise) {
setPromise(void 0);
}
if (fixedCacheKey) {
dispatch(api.internalActions.removeMutationResult({
requestId: requestId,
fixedCacheKey: fixedCacheKey
}));
}
});
}, [dispatch, fixedCacheKey, promise, requestId]);
var endpointName = currentState.endpointName, data = currentState.data, status = currentState.status, isLoading = currentState.isLoading, isSuccess = currentState.isSuccess, isError = currentState.isError, error = currentState.error;
(0, import_react3.useDebugValue)({
endpointName: endpointName,
data: data,
status: status,
isLoading: isLoading,
isSuccess: isSuccess,
isError: isError,
error: error
});
var finalState = (0, import_react3.useMemo)(function () { return __spreadProps(__spreadValues({}, currentState), { originalArgs: originalArgs, reset: reset }); }, [currentState, originalArgs, reset]);
return (0, import_react3.useMemo)(function () { return [triggerMutation, finalState]; }, [triggerMutation, finalState]);
};
}
}
// src/query/endpointDefinitions.ts
var DefinitionType;
(function (DefinitionType2) {
DefinitionType2["query"] = "query";
DefinitionType2["mutation"] = "mutation";
})(DefinitionType || (DefinitionType = {}));
function isQueryDefinition(e) {
return e.type === DefinitionType.query;
}
function isMutationDefinition(e) {
return e.type === DefinitionType.mutation;
}
// src/query/utils/capitalize.ts
function capitalize(str) {
return str.replace(str[0], str[0].toUpperCase());
}
// src/query/tsHelpers.ts
function safeAssign(target) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
Object.assign.apply(Object, __spreadArray([target], args));
}
// src/query/react/module.ts
var import_react_redux3 = __toModule(require("react-redux"));
var reactHooksModuleName = /* @__PURE__ */ Symbol();
var reactHooksModule = function (_c) {
var _d = _c === void 0 ? {} : _c, _e = _d.batch, batch = _e === void 0 ? import_react_redux3.batch : _e, _f = _d.useDispatch, useDispatch = _f === void 0 ? import_react_redux3.useDispatch : _f, _g = _d.useSelector, useSelector = _g === void 0 ? import_react_redux3.useSelector : _g, _h = _d.useStore, useStore = _h === void 0 ? import_react_redux3.useStore : _h, _j = _d.unstable__sideEffectsInRender, unstable__sideEffectsInRender = _j === void 0 ? false : _j;
return ({
name: reactHooksModuleName,
init: function (api, _c, context) {
var serializeQueryArgs = _c.serializeQueryArgs;
var anyApi = api;
var _d = buildHooks({
api: api,
moduleOptions: {
batch: batch,
useDispatch: useDispatch,
useSelector: useSelector,
useStore: useStore,
unstable__sideEffectsInRender: unstable__sideEffectsInRender
},
serializeQueryArgs: serializeQueryArgs,
context: context
}), buildQueryHooks = _d.buildQueryHooks, buildMutationHook = _d.buildMutationHook, usePrefetch = _d.usePrefetch;
safeAssign(anyApi, { usePrefetch: usePrefetch });
safeAssign(context, { batch: batch });
return {
injectEndpoint: function (endpointName, definition) {
if (isQueryDefinition(definition)) {
var _c = buildQueryHooks(endpointName), useQuery = _c.useQuery, useLazyQuery = _c.useLazyQuery, useLazyQuerySubscription = _c.useLazyQuerySubscription, useQueryState = _c.useQueryState, useQuerySubscription = _c.useQuerySubscription;
safeAssign(anyApi.endpoints[endpointName], {
useQuery: useQuery,
useLazyQuery: useLazyQuery,
useLazyQuerySubscription: useLazyQuerySubscription,
useQueryState: useQueryState,
useQuerySubscription: useQuerySubscription
});
api["use" + capitalize(endpointName) + "Query"] = useQuery;
api["useLazy" + capitalize(endpointName) + "Query"] = useLazyQuery;
}
else if (isMutationDefinition(definition)) {
var useMutation = buildMutationHook(endpointName);
safeAssign(anyApi.endpoints[endpointName], {
useMutation: useMutation
});
api["use" + capitalize(endpointName) + "Mutation"] = useMutation;
}
}
};
}
});
};
// src/query/react/index.ts
__reExport(exports, __toModule(require("@reduxjs/toolkit/query")));
// src/query/react/ApiProvider.tsx
var import_toolkit3 = __toModule(require("@reduxjs/toolkit"));
var import_react4 = __toModule(require("react"));
var import_react5 = __toModule(require("react"));
var import_react_redux4 = __toModule(require("react-redux"));
var import_query2 = __toModule(require("@reduxjs/toolkit/query"));
function ApiProvider(props) {
var store = import_react5.default.useState(function () {
var _c;
return (0, import_toolkit3.configureStore)({
reducer: (_c = {},
_c[props.api.reducerPath] = props.api.reducer,
_c),
middleware: function (gDM) { return gDM().concat(props.api.middleware); }
});
})[0];
(0, import_react4.useEffect)(function () { return props.setupListeners === false ? void 0 : (0, import_query2.setupListeners)(store.dispatch, props.setupListeners); }, [props.setupListeners, store.dispatch]);
return /* @__PURE__ */ import_react5.default.createElement(import_react_redux4.Provider, {
store: store,
context: props.context
}, props.children);
}
// src/query/react/index.ts
var createApi = /* @__PURE__ */ (0, import_query3.buildCreateApi)((0, import_query3.coreModule)(), reactHooksModule());
//# sourceMappingURL=rtk-query-react.cjs.development.js.map

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

@ -0,0 +1,460 @@
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = function (obj, key, value) { return key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value: value }) : obj[key] = value; };
var __spreadValues = function (a, b) {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var _i = 0, _c = __getOwnPropSymbols(b); _i < _c.length; _i++) {
var prop = _c[_i];
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = function (a, b) { return __defProps(a, __getOwnPropDescs(b)); };
// src/query/react/index.ts
import { coreModule, buildCreateApi } from "@reduxjs/toolkit/query";
// src/query/react/buildHooks.ts
import { createSelector } from "@reduxjs/toolkit";
import { useCallback, useDebugValue, useEffect as useEffect3, useLayoutEffect, useMemo as useMemo2, useRef as useRef3, useState } from "react";
import { QueryStatus, skipToken } from "@reduxjs/toolkit/query";
import { shallowEqual as shallowEqual2 } from "react-redux";
// src/query/react/useSerializedStableValue.ts
import { useEffect, useRef, useMemo } from "react";
function useStableQueryArgs(queryArgs, serialize, endpointDefinition, endpointName) {
var incoming = useMemo(function () { return ({
queryArgs: queryArgs,
serialized: typeof queryArgs == "object" ? serialize({ queryArgs: queryArgs, endpointDefinition: endpointDefinition, endpointName: endpointName }) : queryArgs
}); }, [queryArgs, serialize, endpointDefinition, endpointName]);
var cache2 = useRef(incoming);
useEffect(function () {
if (cache2.current.serialized !== incoming.serialized) {
cache2.current = incoming;
}
}, [incoming]);
return cache2.current.serialized === incoming.serialized ? cache2.current.queryArgs : queryArgs;
}
// src/query/react/constants.ts
var UNINITIALIZED_VALUE = Symbol();
// src/query/react/useShallowStableValue.ts
import { useEffect as useEffect2, useRef as useRef2 } from "react";
import { shallowEqual } from "react-redux";
function useShallowStableValue(value) {
var cache2 = useRef2(value);
useEffect2(function () {
if (!shallowEqual(cache2.current, value)) {
cache2.current = value;
}
}, [value]);
return shallowEqual(cache2.current, value) ? cache2.current : value;
}
// src/query/defaultSerializeQueryArgs.ts
import { isPlainObject } from "@reduxjs/toolkit";
var cache = WeakMap ? new WeakMap() : void 0;
var defaultSerializeQueryArgs = function (_c) {
var endpointName = _c.endpointName, queryArgs = _c.queryArgs;
var serialized = "";
var cached = cache == null ? void 0 : cache.get(queryArgs);
if (typeof cached === "string") {
serialized = cached;
}
else {
var stringified = JSON.stringify(queryArgs, function (key, value) { return isPlainObject(value) ? Object.keys(value).sort().reduce(function (acc, key2) {
acc[key2] = value[key2];
return acc;
}, {}) : value; });
if (isPlainObject(queryArgs)) {
cache == null ? void 0 : cache.set(queryArgs, stringified);
}
serialized = stringified;
}
return endpointName + "(" + serialized + ")";
};
// src/query/react/buildHooks.ts
var useIsomorphicLayoutEffect = typeof window !== "undefined" && !!window.document && !!window.document.createElement ? useLayoutEffect : useEffect3;
var defaultMutationStateSelector = function (x) { return x; };
var noPendingQueryStateSelector = function (selected) {
if (selected.isUninitialized) {
return __spreadProps(__spreadValues({}, selected), {
isUninitialized: false,
isFetching: true,
isLoading: selected.data !== void 0 ? false : true,
status: QueryStatus.pending
});
}
return selected;
};
function buildHooks(_c) {
var api = _c.api, _d = _c.moduleOptions, batch = _d.batch, useDispatch = _d.useDispatch, useSelector = _d.useSelector, useStore = _d.useStore, unstable__sideEffectsInRender = _d.unstable__sideEffectsInRender, serializeQueryArgs = _c.serializeQueryArgs, context = _c.context;
var usePossiblyImmediateEffect = unstable__sideEffectsInRender ? function (cb) { return cb(); } : useEffect3;
return { buildQueryHooks: buildQueryHooks, buildMutationHook: buildMutationHook, usePrefetch: usePrefetch };
function queryStatePreSelector(currentState, lastResult, queryArgs) {
if ((lastResult == null ? void 0 : lastResult.endpointName) && currentState.isUninitialized) {
var endpointName = lastResult.endpointName;
var endpointDefinition = context.endpointDefinitions[endpointName];
if (serializeQueryArgs({
queryArgs: lastResult.originalArgs,
endpointDefinition: endpointDefinition,
endpointName: endpointName
}) === serializeQueryArgs({
queryArgs: queryArgs,
endpointDefinition: endpointDefinition,
endpointName: endpointName
}))
lastResult = void 0;
}
var data = currentState.isSuccess ? currentState.data : lastResult == null ? void 0 : lastResult.data;
if (data === void 0)
data = currentState.data;
var hasData = data !== void 0;
var isFetching = currentState.isLoading;
var isLoading = !hasData && isFetching;
var isSuccess = currentState.isSuccess || isFetching && hasData;
return __spreadProps(__spreadValues({}, currentState), {
data: data,
currentData: currentState.data,
isFetching: isFetching,
isLoading: isLoading,
isSuccess: isSuccess
});
}
function usePrefetch(endpointName, defaultOptions) {
var dispatch = useDispatch();
var stableDefaultOptions = useShallowStableValue(defaultOptions);
return useCallback(function (arg, options) { return dispatch(api.util.prefetch(endpointName, arg, __spreadValues(__spreadValues({}, stableDefaultOptions), options))); }, [endpointName, dispatch, stableDefaultOptions]);
}
function buildQueryHooks(name) {
var useQuerySubscription = function (arg, _c) {
var _d = _c === void 0 ? {} : _c, refetchOnReconnect = _d.refetchOnReconnect, refetchOnFocus = _d.refetchOnFocus, refetchOnMountOrArgChange = _d.refetchOnMountOrArgChange, _e = _d.skip, skip = _e === void 0 ? false : _e, _f = _d.pollingInterval, pollingInterval = _f === void 0 ? 0 : _f;
var initiate = api.endpoints[name].initiate;
var dispatch = useDispatch();
var stableArg = useStableQueryArgs(skip ? skipToken : arg, defaultSerializeQueryArgs, context.endpointDefinitions[name], name);
var stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect: refetchOnReconnect,
refetchOnFocus: refetchOnFocus,
pollingInterval: pollingInterval
});
var lastRenderHadSubscription = useRef3(false);
var promiseRef = useRef3();
var _g = promiseRef.current || {}, queryCacheKey = _g.queryCacheKey, requestId = _g.requestId;
var currentRenderHasSubscription = false;
if (queryCacheKey && requestId) {
var returnedValue = dispatch(api.internalActions.internal_probeSubscription({
queryCacheKey: queryCacheKey,
requestId: requestId
}));
if (process.env.NODE_ENV !== "production") {
if (typeof returnedValue !== "boolean") {
throw new Error("Warning: Middleware for RTK-Query API at reducerPath \"" + api.reducerPath + "\" has not been added to the store.\n You must add the middleware for RTK-Query to function correctly!");
}
}
currentRenderHasSubscription = !!returnedValue;
}
var subscriptionRemoved = !currentRenderHasSubscription && lastRenderHadSubscription.current;
usePossiblyImmediateEffect(function () {
lastRenderHadSubscription.current = currentRenderHasSubscription;
});
usePossiblyImmediateEffect(function () {
if (subscriptionRemoved) {
promiseRef.current = void 0;
}
}, [subscriptionRemoved]);
usePossiblyImmediateEffect(function () {
var _a;
var lastPromise = promiseRef.current;
if (typeof process !== "undefined" && process.env.NODE_ENV === "removeMeOnCompilation") {
console.log(subscriptionRemoved);
}
if (stableArg === skipToken) {
lastPromise == null ? void 0 : lastPromise.unsubscribe();
promiseRef.current = void 0;
return;
}
var lastSubscriptionOptions = (_a = promiseRef.current) == null ? void 0 : _a.subscriptionOptions;
if (!lastPromise || lastPromise.arg !== stableArg) {
lastPromise == null ? void 0 : lastPromise.unsubscribe();
var promise = dispatch(initiate(stableArg, {
subscriptionOptions: stableSubscriptionOptions,
forceRefetch: refetchOnMountOrArgChange
}));
promiseRef.current = promise;
}
else if (stableSubscriptionOptions !== lastSubscriptionOptions) {
lastPromise.updateSubscriptionOptions(stableSubscriptionOptions);
}
}, [
dispatch,
initiate,
refetchOnMountOrArgChange,
stableArg,
stableSubscriptionOptions,
subscriptionRemoved
]);
useEffect3(function () {
return function () {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = void 0;
};
}, []);
return useMemo2(function () { return ({
refetch: function () {
var _a;
if (!promiseRef.current)
throw new Error("Cannot refetch a query that has not been started yet.");
return (_a = promiseRef.current) == null ? void 0 : _a.refetch();
}
}); }, []);
};
var useLazyQuerySubscription = function (_c) {
var _d = _c === void 0 ? {} : _c, refetchOnReconnect = _d.refetchOnReconnect, refetchOnFocus = _d.refetchOnFocus, _e = _d.pollingInterval, pollingInterval = _e === void 0 ? 0 : _e;
var initiate = api.endpoints[name].initiate;
var dispatch = useDispatch();
var _f = useState(UNINITIALIZED_VALUE), arg = _f[0], setArg = _f[1];
var promiseRef = useRef3();
var stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect: refetchOnReconnect,
refetchOnFocus: refetchOnFocus,
pollingInterval: pollingInterval
});
usePossiblyImmediateEffect(function () {
var _a, _b;
var lastSubscriptionOptions = (_a = promiseRef.current) == null ? void 0 : _a.subscriptionOptions;
if (stableSubscriptionOptions !== lastSubscriptionOptions) {
(_b = promiseRef.current) == null ? void 0 : _b.updateSubscriptionOptions(stableSubscriptionOptions);
}
}, [stableSubscriptionOptions]);
var subscriptionOptionsRef = useRef3(stableSubscriptionOptions);
usePossiblyImmediateEffect(function () {
subscriptionOptionsRef.current = stableSubscriptionOptions;
}, [stableSubscriptionOptions]);
var trigger = useCallback(function (arg2, preferCacheValue) {
if (preferCacheValue === void 0) { preferCacheValue = false; }
var promise;
batch(function () {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = promise = dispatch(initiate(arg2, {
subscriptionOptions: subscriptionOptionsRef.current,
forceRefetch: !preferCacheValue
}));
setArg(arg2);
});
return promise;
}, [dispatch, initiate]);
useEffect3(function () {
return function () {
var _a;
(_a = promiseRef == null ? void 0 : promiseRef.current) == null ? void 0 : _a.unsubscribe();
};
}, []);
useEffect3(function () {
if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {
trigger(arg, true);
}
}, [arg, trigger]);
return useMemo2(function () { return [trigger, arg]; }, [trigger, arg]);
};
var useQueryState = function (arg, _c) {
var _d = _c === void 0 ? {} : _c, _e = _d.skip, skip = _e === void 0 ? false : _e, selectFromResult = _d.selectFromResult;
var select = api.endpoints[name].select;
var stableArg = useStableQueryArgs(skip ? skipToken : arg, serializeQueryArgs, context.endpointDefinitions[name], name);
var lastValue = useRef3();
var selectDefaultResult = useMemo2(function () { return createSelector([
select(stableArg),
function (_, lastResult) { return lastResult; },
function (_) { return stableArg; }
], queryStatePreSelector); }, [select, stableArg]);
var querySelector = useMemo2(function () { return selectFromResult ? createSelector([selectDefaultResult], selectFromResult) : selectDefaultResult; }, [selectDefaultResult, selectFromResult]);
var currentState = useSelector(function (state) { return querySelector(state, lastValue.current); }, shallowEqual2);
var store = useStore();
var newLastValue = selectDefaultResult(store.getState(), lastValue.current);
useIsomorphicLayoutEffect(function () {
lastValue.current = newLastValue;
}, [newLastValue]);
return currentState;
};
return {
useQueryState: useQueryState,
useQuerySubscription: useQuerySubscription,
useLazyQuerySubscription: useLazyQuerySubscription,
useLazyQuery: function (options) {
var _c = useLazyQuerySubscription(options), trigger = _c[0], arg = _c[1];
var queryStateResults = useQueryState(arg, __spreadProps(__spreadValues({}, options), {
skip: arg === UNINITIALIZED_VALUE
}));
var info = useMemo2(function () { return ({ lastArg: arg }); }, [arg]);
return useMemo2(function () { return [trigger, queryStateResults, info]; }, [trigger, queryStateResults, info]);
},
useQuery: function (arg, options) {
var querySubscriptionResults = useQuerySubscription(arg, options);
var queryStateResults = useQueryState(arg, __spreadValues({
selectFromResult: arg === skipToken || (options == null ? void 0 : options.skip) ? void 0 : noPendingQueryStateSelector
}, options));
var data = queryStateResults.data, status = queryStateResults.status, isLoading = queryStateResults.isLoading, isSuccess = queryStateResults.isSuccess, isError = queryStateResults.isError, error = queryStateResults.error;
useDebugValue({ data: data, status: status, isLoading: isLoading, isSuccess: isSuccess, isError: isError, error: error });
return useMemo2(function () { return __spreadValues(__spreadValues({}, queryStateResults), querySubscriptionResults); }, [queryStateResults, querySubscriptionResults]);
}
};
}
function buildMutationHook(name) {
return function (_c) {
var _d = _c === void 0 ? {} : _c, _e = _d.selectFromResult, selectFromResult = _e === void 0 ? defaultMutationStateSelector : _e, fixedCacheKey = _d.fixedCacheKey;
var _f = api.endpoints[name], select = _f.select, initiate = _f.initiate;
var dispatch = useDispatch();
var _g = useState(), promise = _g[0], setPromise = _g[1];
useEffect3(function () { return function () {
if (!(promise == null ? void 0 : promise.arg.fixedCacheKey)) {
promise == null ? void 0 : promise.reset();
}
}; }, [promise]);
var triggerMutation = useCallback(function (arg) {
var promise2 = dispatch(initiate(arg, { fixedCacheKey: fixedCacheKey }));
setPromise(promise2);
return promise2;
}, [dispatch, initiate, fixedCacheKey]);
var requestId = (promise || {}).requestId;
var mutationSelector = useMemo2(function () { return createSelector([select({ fixedCacheKey: fixedCacheKey, requestId: promise == null ? void 0 : promise.requestId })], selectFromResult); }, [select, promise, selectFromResult, fixedCacheKey]);
var currentState = useSelector(mutationSelector, shallowEqual2);
var originalArgs = fixedCacheKey == null ? promise == null ? void 0 : promise.arg.originalArgs : void 0;
var reset = useCallback(function () {
batch(function () {
if (promise) {
setPromise(void 0);
}
if (fixedCacheKey) {
dispatch(api.internalActions.removeMutationResult({
requestId: requestId,
fixedCacheKey: fixedCacheKey
}));
}
});
}, [dispatch, fixedCacheKey, promise, requestId]);
var endpointName = currentState.endpointName, data = currentState.data, status = currentState.status, isLoading = currentState.isLoading, isSuccess = currentState.isSuccess, isError = currentState.isError, error = currentState.error;
useDebugValue({
endpointName: endpointName,
data: data,
status: status,
isLoading: isLoading,
isSuccess: isSuccess,
isError: isError,
error: error
});
var finalState = useMemo2(function () { return __spreadProps(__spreadValues({}, currentState), { originalArgs: originalArgs, reset: reset }); }, [currentState, originalArgs, reset]);
return useMemo2(function () { return [triggerMutation, finalState]; }, [triggerMutation, finalState]);
};
}
}
// src/query/endpointDefinitions.ts
var DefinitionType;
(function (DefinitionType2) {
DefinitionType2["query"] = "query";
DefinitionType2["mutation"] = "mutation";
})(DefinitionType || (DefinitionType = {}));
function isQueryDefinition(e) {
return e.type === DefinitionType.query;
}
function isMutationDefinition(e) {
return e.type === DefinitionType.mutation;
}
// src/query/utils/capitalize.ts
function capitalize(str) {
return str.replace(str[0], str[0].toUpperCase());
}
// src/query/tsHelpers.ts
function safeAssign(target) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
Object.assign.apply(Object, __spreadArray([target], args));
}
// src/query/react/module.ts
import { useDispatch as rrUseDispatch, useSelector as rrUseSelector, useStore as rrUseStore, batch as rrBatch } from "react-redux";
var reactHooksModuleName = /* @__PURE__ */ Symbol();
var reactHooksModule = function (_c) {
var _d = _c === void 0 ? {} : _c, _e = _d.batch, batch = _e === void 0 ? rrBatch : _e, _f = _d.useDispatch, useDispatch = _f === void 0 ? rrUseDispatch : _f, _g = _d.useSelector, useSelector = _g === void 0 ? rrUseSelector : _g, _h = _d.useStore, useStore = _h === void 0 ? rrUseStore : _h, _j = _d.unstable__sideEffectsInRender, unstable__sideEffectsInRender = _j === void 0 ? false : _j;
return ({
name: reactHooksModuleName,
init: function (api, _c, context) {
var serializeQueryArgs = _c.serializeQueryArgs;
var anyApi = api;
var _d = buildHooks({
api: api,
moduleOptions: {
batch: batch,
useDispatch: useDispatch,
useSelector: useSelector,
useStore: useStore,
unstable__sideEffectsInRender: unstable__sideEffectsInRender
},
serializeQueryArgs: serializeQueryArgs,
context: context
}), buildQueryHooks = _d.buildQueryHooks, buildMutationHook = _d.buildMutationHook, usePrefetch = _d.usePrefetch;
safeAssign(anyApi, { usePrefetch: usePrefetch });
safeAssign(context, { batch: batch });
return {
injectEndpoint: function (endpointName, definition) {
if (isQueryDefinition(definition)) {
var _c = buildQueryHooks(endpointName), useQuery = _c.useQuery, useLazyQuery = _c.useLazyQuery, useLazyQuerySubscription = _c.useLazyQuerySubscription, useQueryState = _c.useQueryState, useQuerySubscription = _c.useQuerySubscription;
safeAssign(anyApi.endpoints[endpointName], {
useQuery: useQuery,
useLazyQuery: useLazyQuery,
useLazyQuerySubscription: useLazyQuerySubscription,
useQueryState: useQueryState,
useQuerySubscription: useQuerySubscription
});
api["use" + capitalize(endpointName) + "Query"] = useQuery;
api["useLazy" + capitalize(endpointName) + "Query"] = useLazyQuery;
}
else if (isMutationDefinition(definition)) {
var useMutation = buildMutationHook(endpointName);
safeAssign(anyApi.endpoints[endpointName], {
useMutation: useMutation
});
api["use" + capitalize(endpointName) + "Mutation"] = useMutation;
}
}
};
}
});
};
// src/query/react/index.ts
export * from "@reduxjs/toolkit/query";
// src/query/react/ApiProvider.tsx
import { configureStore } from "@reduxjs/toolkit";
import { useEffect as useEffect4 } from "react";
import React from "react";
import { Provider } from "react-redux";
import { setupListeners } from "@reduxjs/toolkit/query";
function ApiProvider(props) {
var store = React.useState(function () {
var _c;
return configureStore({
reducer: (_c = {},
_c[props.api.reducerPath] = props.api.reducer,
_c),
middleware: function (gDM) { return gDM().concat(props.api.middleware); }
});
})[0];
useEffect4(function () { return props.setupListeners === false ? void 0 : setupListeners(store.dispatch, props.setupListeners); }, [props.setupListeners, store.dispatch]);
return /* @__PURE__ */ React.createElement(Provider, {
store: store,
context: props.context
}, props.children);
}
// src/query/react/index.ts
var createApi = /* @__PURE__ */ buildCreateApi(coreModule(), reactHooksModule());
export { ApiProvider, createApi, reactHooksModule };
//# sourceMappingURL=rtk-query-react.esm.js.map

File diff suppressed because one or more lines are too long

@ -0,0 +1,437 @@
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
// src/query/react/index.ts
import { coreModule, buildCreateApi } from "@reduxjs/toolkit/query";
// src/query/react/buildHooks.ts
import { createSelector } from "@reduxjs/toolkit";
import { useCallback, useDebugValue, useEffect as useEffect3, useLayoutEffect, useMemo as useMemo2, useRef as useRef3, useState } from "react";
import { QueryStatus, skipToken } from "@reduxjs/toolkit/query";
import { shallowEqual as shallowEqual2 } from "react-redux";
// src/query/react/useSerializedStableValue.ts
import { useEffect, useRef, useMemo } from "react";
function useStableQueryArgs(queryArgs, serialize, endpointDefinition, endpointName) {
const incoming = useMemo(() => ({
queryArgs,
serialized: typeof queryArgs == "object" ? serialize({ queryArgs, endpointDefinition, endpointName }) : queryArgs
}), [queryArgs, serialize, endpointDefinition, endpointName]);
const cache2 = useRef(incoming);
useEffect(() => {
if (cache2.current.serialized !== incoming.serialized) {
cache2.current = incoming;
}
}, [incoming]);
return cache2.current.serialized === incoming.serialized ? cache2.current.queryArgs : queryArgs;
}
// src/query/react/constants.ts
var UNINITIALIZED_VALUE = Symbol();
// src/query/react/useShallowStableValue.ts
import { useEffect as useEffect2, useRef as useRef2 } from "react";
import { shallowEqual } from "react-redux";
function useShallowStableValue(value) {
const cache2 = useRef2(value);
useEffect2(() => {
if (!shallowEqual(cache2.current, value)) {
cache2.current = value;
}
}, [value]);
return shallowEqual(cache2.current, value) ? cache2.current : value;
}
// src/query/defaultSerializeQueryArgs.ts
import { isPlainObject } from "@reduxjs/toolkit";
var cache = WeakMap ? new WeakMap() : void 0;
var defaultSerializeQueryArgs = ({ endpointName, queryArgs }) => {
let serialized = "";
const cached = cache == null ? void 0 : cache.get(queryArgs);
if (typeof cached === "string") {
serialized = cached;
}
else {
const stringified = JSON.stringify(queryArgs, (key, value) => isPlainObject(value) ? Object.keys(value).sort().reduce((acc, key2) => {
acc[key2] = value[key2];
return acc;
}, {}) : value);
if (isPlainObject(queryArgs)) {
cache == null ? void 0 : cache.set(queryArgs, stringified);
}
serialized = stringified;
}
return `${endpointName}(${serialized})`;
};
// src/query/react/buildHooks.ts
var useIsomorphicLayoutEffect = typeof window !== "undefined" && !!window.document && !!window.document.createElement ? useLayoutEffect : useEffect3;
var defaultMutationStateSelector = (x) => x;
var noPendingQueryStateSelector = (selected) => {
if (selected.isUninitialized) {
return __spreadProps(__spreadValues({}, selected), {
isUninitialized: false,
isFetching: true,
isLoading: selected.data !== void 0 ? false : true,
status: QueryStatus.pending
});
}
return selected;
};
function buildHooks({ api, moduleOptions: { batch, useDispatch, useSelector, useStore, unstable__sideEffectsInRender }, serializeQueryArgs, context }) {
const usePossiblyImmediateEffect = unstable__sideEffectsInRender ? (cb) => cb() : useEffect3;
return { buildQueryHooks, buildMutationHook, usePrefetch };
function queryStatePreSelector(currentState, lastResult, queryArgs) {
if ((lastResult == null ? void 0 : lastResult.endpointName) && currentState.isUninitialized) {
const { endpointName } = lastResult;
const endpointDefinition = context.endpointDefinitions[endpointName];
if (serializeQueryArgs({
queryArgs: lastResult.originalArgs,
endpointDefinition,
endpointName
}) === serializeQueryArgs({
queryArgs,
endpointDefinition,
endpointName
}))
lastResult = void 0;
}
let data = currentState.isSuccess ? currentState.data : lastResult == null ? void 0 : lastResult.data;
if (data === void 0)
data = currentState.data;
const hasData = data !== void 0;
const isFetching = currentState.isLoading;
const isLoading = !hasData && isFetching;
const isSuccess = currentState.isSuccess || isFetching && hasData;
return __spreadProps(__spreadValues({}, currentState), {
data,
currentData: currentState.data,
isFetching,
isLoading,
isSuccess
});
}
function usePrefetch(endpointName, defaultOptions) {
const dispatch = useDispatch();
const stableDefaultOptions = useShallowStableValue(defaultOptions);
return useCallback((arg, options) => dispatch(api.util.prefetch(endpointName, arg, __spreadValues(__spreadValues({}, stableDefaultOptions), options))), [endpointName, dispatch, stableDefaultOptions]);
}
function buildQueryHooks(name) {
const useQuerySubscription = (arg, { refetchOnReconnect, refetchOnFocus, refetchOnMountOrArgChange, skip = false, pollingInterval = 0 } = {}) => {
const { initiate } = api.endpoints[name];
const dispatch = useDispatch();
const stableArg = useStableQueryArgs(skip ? skipToken : arg, defaultSerializeQueryArgs, context.endpointDefinitions[name], name);
const stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect,
refetchOnFocus,
pollingInterval
});
const lastRenderHadSubscription = useRef3(false);
const promiseRef = useRef3();
let { queryCacheKey, requestId } = promiseRef.current || {};
let currentRenderHasSubscription = false;
if (queryCacheKey && requestId) {
const returnedValue = dispatch(api.internalActions.internal_probeSubscription({
queryCacheKey,
requestId
}));
if (true) {
if (typeof returnedValue !== "boolean") {
throw new Error(`Warning: Middleware for RTK-Query API at reducerPath "${api.reducerPath}" has not been added to the store.
You must add the middleware for RTK-Query to function correctly!`);
}
}
currentRenderHasSubscription = !!returnedValue;
}
const subscriptionRemoved = !currentRenderHasSubscription && lastRenderHadSubscription.current;
usePossiblyImmediateEffect(() => {
lastRenderHadSubscription.current = currentRenderHasSubscription;
});
usePossiblyImmediateEffect(() => {
if (subscriptionRemoved) {
promiseRef.current = void 0;
}
}, [subscriptionRemoved]);
usePossiblyImmediateEffect(() => {
var _a;
const lastPromise = promiseRef.current;
if (typeof process !== "undefined" && false) {
console.log(subscriptionRemoved);
}
if (stableArg === skipToken) {
lastPromise == null ? void 0 : lastPromise.unsubscribe();
promiseRef.current = void 0;
return;
}
const lastSubscriptionOptions = (_a = promiseRef.current) == null ? void 0 : _a.subscriptionOptions;
if (!lastPromise || lastPromise.arg !== stableArg) {
lastPromise == null ? void 0 : lastPromise.unsubscribe();
const promise = dispatch(initiate(stableArg, {
subscriptionOptions: stableSubscriptionOptions,
forceRefetch: refetchOnMountOrArgChange
}));
promiseRef.current = promise;
}
else if (stableSubscriptionOptions !== lastSubscriptionOptions) {
lastPromise.updateSubscriptionOptions(stableSubscriptionOptions);
}
}, [
dispatch,
initiate,
refetchOnMountOrArgChange,
stableArg,
stableSubscriptionOptions,
subscriptionRemoved
]);
useEffect3(() => {
return () => {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = void 0;
};
}, []);
return useMemo2(() => ({
refetch: () => {
var _a;
if (!promiseRef.current)
throw new Error("Cannot refetch a query that has not been started yet.");
return (_a = promiseRef.current) == null ? void 0 : _a.refetch();
}
}), []);
};
const useLazyQuerySubscription = ({ refetchOnReconnect, refetchOnFocus, pollingInterval = 0 } = {}) => {
const { initiate } = api.endpoints[name];
const dispatch = useDispatch();
const [arg, setArg] = useState(UNINITIALIZED_VALUE);
const promiseRef = useRef3();
const stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect,
refetchOnFocus,
pollingInterval
});
usePossiblyImmediateEffect(() => {
var _a, _b;
const lastSubscriptionOptions = (_a = promiseRef.current) == null ? void 0 : _a.subscriptionOptions;
if (stableSubscriptionOptions !== lastSubscriptionOptions) {
(_b = promiseRef.current) == null ? void 0 : _b.updateSubscriptionOptions(stableSubscriptionOptions);
}
}, [stableSubscriptionOptions]);
const subscriptionOptionsRef = useRef3(stableSubscriptionOptions);
usePossiblyImmediateEffect(() => {
subscriptionOptionsRef.current = stableSubscriptionOptions;
}, [stableSubscriptionOptions]);
const trigger = useCallback(function (arg2, preferCacheValue = false) {
let promise;
batch(() => {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = promise = dispatch(initiate(arg2, {
subscriptionOptions: subscriptionOptionsRef.current,
forceRefetch: !preferCacheValue
}));
setArg(arg2);
});
return promise;
}, [dispatch, initiate]);
useEffect3(() => {
return () => {
var _a;
(_a = promiseRef == null ? void 0 : promiseRef.current) == null ? void 0 : _a.unsubscribe();
};
}, []);
useEffect3(() => {
if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {
trigger(arg, true);
}
}, [arg, trigger]);
return useMemo2(() => [trigger, arg], [trigger, arg]);
};
const useQueryState = (arg, { skip = false, selectFromResult } = {}) => {
const { select } = api.endpoints[name];
const stableArg = useStableQueryArgs(skip ? skipToken : arg, serializeQueryArgs, context.endpointDefinitions[name], name);
const lastValue = useRef3();
const selectDefaultResult = useMemo2(() => createSelector([
select(stableArg),
(_, lastResult) => lastResult,
(_) => stableArg
], queryStatePreSelector), [select, stableArg]);
const querySelector = useMemo2(() => selectFromResult ? createSelector([selectDefaultResult], selectFromResult) : selectDefaultResult, [selectDefaultResult, selectFromResult]);
const currentState = useSelector((state) => querySelector(state, lastValue.current), shallowEqual2);
const store = useStore();
const newLastValue = selectDefaultResult(store.getState(), lastValue.current);
useIsomorphicLayoutEffect(() => {
lastValue.current = newLastValue;
}, [newLastValue]);
return currentState;
};
return {
useQueryState,
useQuerySubscription,
useLazyQuerySubscription,
useLazyQuery(options) {
const [trigger, arg] = useLazyQuerySubscription(options);
const queryStateResults = useQueryState(arg, __spreadProps(__spreadValues({}, options), {
skip: arg === UNINITIALIZED_VALUE
}));
const info = useMemo2(() => ({ lastArg: arg }), [arg]);
return useMemo2(() => [trigger, queryStateResults, info], [trigger, queryStateResults, info]);
},
useQuery(arg, options) {
const querySubscriptionResults = useQuerySubscription(arg, options);
const queryStateResults = useQueryState(arg, __spreadValues({
selectFromResult: arg === skipToken || (options == null ? void 0 : options.skip) ? void 0 : noPendingQueryStateSelector
}, options));
const { data, status, isLoading, isSuccess, isError, error } = queryStateResults;
useDebugValue({ data, status, isLoading, isSuccess, isError, error });
return useMemo2(() => __spreadValues(__spreadValues({}, queryStateResults), querySubscriptionResults), [queryStateResults, querySubscriptionResults]);
}
};
}
function buildMutationHook(name) {
return ({ selectFromResult = defaultMutationStateSelector, fixedCacheKey } = {}) => {
const { select, initiate } = api.endpoints[name];
const dispatch = useDispatch();
const [promise, setPromise] = useState();
useEffect3(() => () => {
if (!(promise == null ? void 0 : promise.arg.fixedCacheKey)) {
promise == null ? void 0 : promise.reset();
}
}, [promise]);
const triggerMutation = useCallback(function (arg) {
const promise2 = dispatch(initiate(arg, { fixedCacheKey }));
setPromise(promise2);
return promise2;
}, [dispatch, initiate, fixedCacheKey]);
const { requestId } = promise || {};
const mutationSelector = useMemo2(() => createSelector([select({ fixedCacheKey, requestId: promise == null ? void 0 : promise.requestId })], selectFromResult), [select, promise, selectFromResult, fixedCacheKey]);
const currentState = useSelector(mutationSelector, shallowEqual2);
const originalArgs = fixedCacheKey == null ? promise == null ? void 0 : promise.arg.originalArgs : void 0;
const reset = useCallback(() => {
batch(() => {
if (promise) {
setPromise(void 0);
}
if (fixedCacheKey) {
dispatch(api.internalActions.removeMutationResult({
requestId,
fixedCacheKey
}));
}
});
}, [dispatch, fixedCacheKey, promise, requestId]);
const { endpointName, data, status, isLoading, isSuccess, isError, error } = currentState;
useDebugValue({
endpointName,
data,
status,
isLoading,
isSuccess,
isError,
error
});
const finalState = useMemo2(() => __spreadProps(__spreadValues({}, currentState), { originalArgs, reset }), [currentState, originalArgs, reset]);
return useMemo2(() => [triggerMutation, finalState], [triggerMutation, finalState]);
};
}
}
// src/query/endpointDefinitions.ts
var DefinitionType;
(function (DefinitionType2) {
DefinitionType2["query"] = "query";
DefinitionType2["mutation"] = "mutation";
})(DefinitionType || (DefinitionType = {}));
function isQueryDefinition(e) {
return e.type === DefinitionType.query;
}
function isMutationDefinition(e) {
return e.type === DefinitionType.mutation;
}
// src/query/utils/capitalize.ts
function capitalize(str) {
return str.replace(str[0], str[0].toUpperCase());
}
// src/query/tsHelpers.ts
function safeAssign(target, ...args) {
Object.assign(target, ...args);
}
// src/query/react/module.ts
import { useDispatch as rrUseDispatch, useSelector as rrUseSelector, useStore as rrUseStore, batch as rrBatch } from "react-redux";
var reactHooksModuleName = /* @__PURE__ */ Symbol();
var reactHooksModule = ({ batch = rrBatch, useDispatch = rrUseDispatch, useSelector = rrUseSelector, useStore = rrUseStore, unstable__sideEffectsInRender = false } = {}) => ({
name: reactHooksModuleName,
init(api, { serializeQueryArgs }, context) {
const anyApi = api;
const { buildQueryHooks, buildMutationHook, usePrefetch } = buildHooks({
api,
moduleOptions: {
batch,
useDispatch,
useSelector,
useStore,
unstable__sideEffectsInRender
},
serializeQueryArgs,
context
});
safeAssign(anyApi, { usePrefetch });
safeAssign(context, { batch });
return {
injectEndpoint(endpointName, definition) {
if (isQueryDefinition(definition)) {
const { useQuery, useLazyQuery, useLazyQuerySubscription, useQueryState, useQuerySubscription } = buildQueryHooks(endpointName);
safeAssign(anyApi.endpoints[endpointName], {
useQuery,
useLazyQuery,
useLazyQuerySubscription,
useQueryState,
useQuerySubscription
});
api[`use${capitalize(endpointName)}Query`] = useQuery;
api[`useLazy${capitalize(endpointName)}Query`] = useLazyQuery;
}
else if (isMutationDefinition(definition)) {
const useMutation = buildMutationHook(endpointName);
safeAssign(anyApi.endpoints[endpointName], {
useMutation
});
api[`use${capitalize(endpointName)}Mutation`] = useMutation;
}
}
};
}
});
// src/query/react/index.ts
export * from "@reduxjs/toolkit/query";
// src/query/react/ApiProvider.tsx
import { configureStore } from "@reduxjs/toolkit";
import { useEffect as useEffect4 } from "react";
import React from "react";
import { Provider } from "react-redux";
import { setupListeners } from "@reduxjs/toolkit/query";
function ApiProvider(props) {
const [store] = React.useState(() => configureStore({
reducer: {
[props.api.reducerPath]: props.api.reducer
},
middleware: (gDM) => gDM().concat(props.api.middleware)
}));
useEffect4(() => props.setupListeners === false ? void 0 : setupListeners(store.dispatch, props.setupListeners), [props.setupListeners, store.dispatch]);
return /* @__PURE__ */ React.createElement(Provider, {
store,
context: props.context
}, props.children);
}
// src/query/react/index.ts
var createApi = /* @__PURE__ */ buildCreateApi(coreModule(), reactHooksModule());
export { ApiProvider, createApi, reactHooksModule };
//# sourceMappingURL=rtk-query-react.modern.development.js.map

File diff suppressed because one or more lines are too long

@ -0,0 +1,437 @@
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
// src/query/react/index.ts
import { coreModule, buildCreateApi } from "@reduxjs/toolkit/query";
// src/query/react/buildHooks.ts
import { createSelector } from "@reduxjs/toolkit";
import { useCallback, useDebugValue, useEffect as useEffect3, useLayoutEffect, useMemo as useMemo2, useRef as useRef3, useState } from "react";
import { QueryStatus, skipToken } from "@reduxjs/toolkit/query";
import { shallowEqual as shallowEqual2 } from "react-redux";
// src/query/react/useSerializedStableValue.ts
import { useEffect, useRef, useMemo } from "react";
function useStableQueryArgs(queryArgs, serialize, endpointDefinition, endpointName) {
const incoming = useMemo(() => ({
queryArgs,
serialized: typeof queryArgs == "object" ? serialize({ queryArgs, endpointDefinition, endpointName }) : queryArgs
}), [queryArgs, serialize, endpointDefinition, endpointName]);
const cache2 = useRef(incoming);
useEffect(() => {
if (cache2.current.serialized !== incoming.serialized) {
cache2.current = incoming;
}
}, [incoming]);
return cache2.current.serialized === incoming.serialized ? cache2.current.queryArgs : queryArgs;
}
// src/query/react/constants.ts
var UNINITIALIZED_VALUE = Symbol();
// src/query/react/useShallowStableValue.ts
import { useEffect as useEffect2, useRef as useRef2 } from "react";
import { shallowEqual } from "react-redux";
function useShallowStableValue(value) {
const cache2 = useRef2(value);
useEffect2(() => {
if (!shallowEqual(cache2.current, value)) {
cache2.current = value;
}
}, [value]);
return shallowEqual(cache2.current, value) ? cache2.current : value;
}
// src/query/defaultSerializeQueryArgs.ts
import { isPlainObject } from "@reduxjs/toolkit";
var cache = WeakMap ? new WeakMap() : void 0;
var defaultSerializeQueryArgs = ({ endpointName, queryArgs }) => {
let serialized = "";
const cached = cache == null ? void 0 : cache.get(queryArgs);
if (typeof cached === "string") {
serialized = cached;
}
else {
const stringified = JSON.stringify(queryArgs, (key, value) => isPlainObject(value) ? Object.keys(value).sort().reduce((acc, key2) => {
acc[key2] = value[key2];
return acc;
}, {}) : value);
if (isPlainObject(queryArgs)) {
cache == null ? void 0 : cache.set(queryArgs, stringified);
}
serialized = stringified;
}
return `${endpointName}(${serialized})`;
};
// src/query/react/buildHooks.ts
var useIsomorphicLayoutEffect = typeof window !== "undefined" && !!window.document && !!window.document.createElement ? useLayoutEffect : useEffect3;
var defaultMutationStateSelector = (x) => x;
var noPendingQueryStateSelector = (selected) => {
if (selected.isUninitialized) {
return __spreadProps(__spreadValues({}, selected), {
isUninitialized: false,
isFetching: true,
isLoading: selected.data !== void 0 ? false : true,
status: QueryStatus.pending
});
}
return selected;
};
function buildHooks({ api, moduleOptions: { batch, useDispatch, useSelector, useStore, unstable__sideEffectsInRender }, serializeQueryArgs, context }) {
const usePossiblyImmediateEffect = unstable__sideEffectsInRender ? (cb) => cb() : useEffect3;
return { buildQueryHooks, buildMutationHook, usePrefetch };
function queryStatePreSelector(currentState, lastResult, queryArgs) {
if ((lastResult == null ? void 0 : lastResult.endpointName) && currentState.isUninitialized) {
const { endpointName } = lastResult;
const endpointDefinition = context.endpointDefinitions[endpointName];
if (serializeQueryArgs({
queryArgs: lastResult.originalArgs,
endpointDefinition,
endpointName
}) === serializeQueryArgs({
queryArgs,
endpointDefinition,
endpointName
}))
lastResult = void 0;
}
let data = currentState.isSuccess ? currentState.data : lastResult == null ? void 0 : lastResult.data;
if (data === void 0)
data = currentState.data;
const hasData = data !== void 0;
const isFetching = currentState.isLoading;
const isLoading = !hasData && isFetching;
const isSuccess = currentState.isSuccess || isFetching && hasData;
return __spreadProps(__spreadValues({}, currentState), {
data,
currentData: currentState.data,
isFetching,
isLoading,
isSuccess
});
}
function usePrefetch(endpointName, defaultOptions) {
const dispatch = useDispatch();
const stableDefaultOptions = useShallowStableValue(defaultOptions);
return useCallback((arg, options) => dispatch(api.util.prefetch(endpointName, arg, __spreadValues(__spreadValues({}, stableDefaultOptions), options))), [endpointName, dispatch, stableDefaultOptions]);
}
function buildQueryHooks(name) {
const useQuerySubscription = (arg, { refetchOnReconnect, refetchOnFocus, refetchOnMountOrArgChange, skip = false, pollingInterval = 0 } = {}) => {
const { initiate } = api.endpoints[name];
const dispatch = useDispatch();
const stableArg = useStableQueryArgs(skip ? skipToken : arg, defaultSerializeQueryArgs, context.endpointDefinitions[name], name);
const stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect,
refetchOnFocus,
pollingInterval
});
const lastRenderHadSubscription = useRef3(false);
const promiseRef = useRef3();
let { queryCacheKey, requestId } = promiseRef.current || {};
let currentRenderHasSubscription = false;
if (queryCacheKey && requestId) {
const returnedValue = dispatch(api.internalActions.internal_probeSubscription({
queryCacheKey,
requestId
}));
if (process.env.NODE_ENV !== "production") {
if (typeof returnedValue !== "boolean") {
throw new Error(`Warning: Middleware for RTK-Query API at reducerPath "${api.reducerPath}" has not been added to the store.
You must add the middleware for RTK-Query to function correctly!`);
}
}
currentRenderHasSubscription = !!returnedValue;
}
const subscriptionRemoved = !currentRenderHasSubscription && lastRenderHadSubscription.current;
usePossiblyImmediateEffect(() => {
lastRenderHadSubscription.current = currentRenderHasSubscription;
});
usePossiblyImmediateEffect(() => {
if (subscriptionRemoved) {
promiseRef.current = void 0;
}
}, [subscriptionRemoved]);
usePossiblyImmediateEffect(() => {
var _a;
const lastPromise = promiseRef.current;
if (typeof process !== "undefined" && process.env.NODE_ENV === "removeMeOnCompilation") {
console.log(subscriptionRemoved);
}
if (stableArg === skipToken) {
lastPromise == null ? void 0 : lastPromise.unsubscribe();
promiseRef.current = void 0;
return;
}
const lastSubscriptionOptions = (_a = promiseRef.current) == null ? void 0 : _a.subscriptionOptions;
if (!lastPromise || lastPromise.arg !== stableArg) {
lastPromise == null ? void 0 : lastPromise.unsubscribe();
const promise = dispatch(initiate(stableArg, {
subscriptionOptions: stableSubscriptionOptions,
forceRefetch: refetchOnMountOrArgChange
}));
promiseRef.current = promise;
}
else if (stableSubscriptionOptions !== lastSubscriptionOptions) {
lastPromise.updateSubscriptionOptions(stableSubscriptionOptions);
}
}, [
dispatch,
initiate,
refetchOnMountOrArgChange,
stableArg,
stableSubscriptionOptions,
subscriptionRemoved
]);
useEffect3(() => {
return () => {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = void 0;
};
}, []);
return useMemo2(() => ({
refetch: () => {
var _a;
if (!promiseRef.current)
throw new Error("Cannot refetch a query that has not been started yet.");
return (_a = promiseRef.current) == null ? void 0 : _a.refetch();
}
}), []);
};
const useLazyQuerySubscription = ({ refetchOnReconnect, refetchOnFocus, pollingInterval = 0 } = {}) => {
const { initiate } = api.endpoints[name];
const dispatch = useDispatch();
const [arg, setArg] = useState(UNINITIALIZED_VALUE);
const promiseRef = useRef3();
const stableSubscriptionOptions = useShallowStableValue({
refetchOnReconnect,
refetchOnFocus,
pollingInterval
});
usePossiblyImmediateEffect(() => {
var _a, _b;
const lastSubscriptionOptions = (_a = promiseRef.current) == null ? void 0 : _a.subscriptionOptions;
if (stableSubscriptionOptions !== lastSubscriptionOptions) {
(_b = promiseRef.current) == null ? void 0 : _b.updateSubscriptionOptions(stableSubscriptionOptions);
}
}, [stableSubscriptionOptions]);
const subscriptionOptionsRef = useRef3(stableSubscriptionOptions);
usePossiblyImmediateEffect(() => {
subscriptionOptionsRef.current = stableSubscriptionOptions;
}, [stableSubscriptionOptions]);
const trigger = useCallback(function (arg2, preferCacheValue = false) {
let promise;
batch(() => {
var _a;
(_a = promiseRef.current) == null ? void 0 : _a.unsubscribe();
promiseRef.current = promise = dispatch(initiate(arg2, {
subscriptionOptions: subscriptionOptionsRef.current,
forceRefetch: !preferCacheValue
}));
setArg(arg2);
});
return promise;
}, [dispatch, initiate]);
useEffect3(() => {
return () => {
var _a;
(_a = promiseRef == null ? void 0 : promiseRef.current) == null ? void 0 : _a.unsubscribe();
};
}, []);
useEffect3(() => {
if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {
trigger(arg, true);
}
}, [arg, trigger]);
return useMemo2(() => [trigger, arg], [trigger, arg]);
};
const useQueryState = (arg, { skip = false, selectFromResult } = {}) => {
const { select } = api.endpoints[name];
const stableArg = useStableQueryArgs(skip ? skipToken : arg, serializeQueryArgs, context.endpointDefinitions[name], name);
const lastValue = useRef3();
const selectDefaultResult = useMemo2(() => createSelector([
select(stableArg),
(_, lastResult) => lastResult,
(_) => stableArg
], queryStatePreSelector), [select, stableArg]);
const querySelector = useMemo2(() => selectFromResult ? createSelector([selectDefaultResult], selectFromResult) : selectDefaultResult, [selectDefaultResult, selectFromResult]);
const currentState = useSelector((state) => querySelector(state, lastValue.current), shallowEqual2);
const store = useStore();
const newLastValue = selectDefaultResult(store.getState(), lastValue.current);
useIsomorphicLayoutEffect(() => {
lastValue.current = newLastValue;
}, [newLastValue]);
return currentState;
};
return {
useQueryState,
useQuerySubscription,
useLazyQuerySubscription,
useLazyQuery(options) {
const [trigger, arg] = useLazyQuerySubscription(options);
const queryStateResults = useQueryState(arg, __spreadProps(__spreadValues({}, options), {
skip: arg === UNINITIALIZED_VALUE
}));
const info = useMemo2(() => ({ lastArg: arg }), [arg]);
return useMemo2(() => [trigger, queryStateResults, info], [trigger, queryStateResults, info]);
},
useQuery(arg, options) {
const querySubscriptionResults = useQuerySubscription(arg, options);
const queryStateResults = useQueryState(arg, __spreadValues({
selectFromResult: arg === skipToken || (options == null ? void 0 : options.skip) ? void 0 : noPendingQueryStateSelector
}, options));
const { data, status, isLoading, isSuccess, isError, error } = queryStateResults;
useDebugValue({ data, status, isLoading, isSuccess, isError, error });
return useMemo2(() => __spreadValues(__spreadValues({}, queryStateResults), querySubscriptionResults), [queryStateResults, querySubscriptionResults]);
}
};
}
function buildMutationHook(name) {
return ({ selectFromResult = defaultMutationStateSelector, fixedCacheKey } = {}) => {
const { select, initiate } = api.endpoints[name];
const dispatch = useDispatch();
const [promise, setPromise] = useState();
useEffect3(() => () => {
if (!(promise == null ? void 0 : promise.arg.fixedCacheKey)) {
promise == null ? void 0 : promise.reset();
}
}, [promise]);
const triggerMutation = useCallback(function (arg) {
const promise2 = dispatch(initiate(arg, { fixedCacheKey }));
setPromise(promise2);
return promise2;
}, [dispatch, initiate, fixedCacheKey]);
const { requestId } = promise || {};
const mutationSelector = useMemo2(() => createSelector([select({ fixedCacheKey, requestId: promise == null ? void 0 : promise.requestId })], selectFromResult), [select, promise, selectFromResult, fixedCacheKey]);
const currentState = useSelector(mutationSelector, shallowEqual2);
const originalArgs = fixedCacheKey == null ? promise == null ? void 0 : promise.arg.originalArgs : void 0;
const reset = useCallback(() => {
batch(() => {
if (promise) {
setPromise(void 0);
}
if (fixedCacheKey) {
dispatch(api.internalActions.removeMutationResult({
requestId,
fixedCacheKey
}));
}
});
}, [dispatch, fixedCacheKey, promise, requestId]);
const { endpointName, data, status, isLoading, isSuccess, isError, error } = currentState;
useDebugValue({
endpointName,
data,
status,
isLoading,
isSuccess,
isError,
error
});
const finalState = useMemo2(() => __spreadProps(__spreadValues({}, currentState), { originalArgs, reset }), [currentState, originalArgs, reset]);
return useMemo2(() => [triggerMutation, finalState], [triggerMutation, finalState]);
};
}
}
// src/query/endpointDefinitions.ts
var DefinitionType;
(function (DefinitionType2) {
DefinitionType2["query"] = "query";
DefinitionType2["mutation"] = "mutation";
})(DefinitionType || (DefinitionType = {}));
function isQueryDefinition(e) {
return e.type === DefinitionType.query;
}
function isMutationDefinition(e) {
return e.type === DefinitionType.mutation;
}
// src/query/utils/capitalize.ts
function capitalize(str) {
return str.replace(str[0], str[0].toUpperCase());
}
// src/query/tsHelpers.ts
function safeAssign(target, ...args) {
Object.assign(target, ...args);
}
// src/query/react/module.ts
import { useDispatch as rrUseDispatch, useSelector as rrUseSelector, useStore as rrUseStore, batch as rrBatch } from "react-redux";
var reactHooksModuleName = /* @__PURE__ */ Symbol();
var reactHooksModule = ({ batch = rrBatch, useDispatch = rrUseDispatch, useSelector = rrUseSelector, useStore = rrUseStore, unstable__sideEffectsInRender = false } = {}) => ({
name: reactHooksModuleName,
init(api, { serializeQueryArgs }, context) {
const anyApi = api;
const { buildQueryHooks, buildMutationHook, usePrefetch } = buildHooks({
api,
moduleOptions: {
batch,
useDispatch,
useSelector,
useStore,
unstable__sideEffectsInRender
},
serializeQueryArgs,
context
});
safeAssign(anyApi, { usePrefetch });
safeAssign(context, { batch });
return {
injectEndpoint(endpointName, definition) {
if (isQueryDefinition(definition)) {
const { useQuery, useLazyQuery, useLazyQuerySubscription, useQueryState, useQuerySubscription } = buildQueryHooks(endpointName);
safeAssign(anyApi.endpoints[endpointName], {
useQuery,
useLazyQuery,
useLazyQuerySubscription,
useQueryState,
useQuerySubscription
});
api[`use${capitalize(endpointName)}Query`] = useQuery;
api[`useLazy${capitalize(endpointName)}Query`] = useLazyQuery;
}
else if (isMutationDefinition(definition)) {
const useMutation = buildMutationHook(endpointName);
safeAssign(anyApi.endpoints[endpointName], {
useMutation
});
api[`use${capitalize(endpointName)}Mutation`] = useMutation;
}
}
};
}
});
// src/query/react/index.ts
export * from "@reduxjs/toolkit/query";
// src/query/react/ApiProvider.tsx
import { configureStore } from "@reduxjs/toolkit";
import { useEffect as useEffect4 } from "react";
import React from "react";
import { Provider } from "react-redux";
import { setupListeners } from "@reduxjs/toolkit/query";
function ApiProvider(props) {
const [store] = React.useState(() => configureStore({
reducer: {
[props.api.reducerPath]: props.api.reducer
},
middleware: (gDM) => gDM().concat(props.api.middleware)
}));
useEffect4(() => props.setupListeners === false ? void 0 : setupListeners(store.dispatch, props.setupListeners), [props.setupListeners, store.dispatch]);
return /* @__PURE__ */ React.createElement(Provider, {
store,
context: props.context
}, props.children);
}
// src/query/react/index.ts
var createApi = /* @__PURE__ */ buildCreateApi(coreModule(), reactHooksModule());
export { ApiProvider, createApi, reactHooksModule };
//# sourceMappingURL=rtk-query-react.modern.js.map

File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save