UNPKG

25.1 kBJavaScriptView Raw
1(function (global, factory) {
2typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3typeof define === 'function' && define.amd ? define(['exports'], factory) :
4(global = global || self, factory(global.Redux = {}));
5}(this, function (exports) { 'use strict';
6
7function symbolObservablePonyfill(root) {
8 var result;
9 var Symbol = root.Symbol;
10
11 if (typeof Symbol === 'function') {
12 if (Symbol.observable) {
13 result = Symbol.observable;
14 } else {
15 result = Symbol('observable');
16 Symbol.observable = result;
17 }
18 } else {
19 result = '@@observable';
20 }
21
22 return result;
23}
24
25/* global window */
26
27var root;
28
29if (typeof self !== 'undefined') {
30 root = self;
31} else if (typeof window !== 'undefined') {
32 root = window;
33} else if (typeof global !== 'undefined') {
34 root = global;
35} else if (typeof module !== 'undefined') {
36 root = module;
37} else {
38 root = Function('return this')();
39}
40
41var result = symbolObservablePonyfill(root);
42
43/**
44 * These are private action types reserved by Redux.
45 * For any unknown actions, you must return the current state.
46 * If the current state is undefined, you must return the initial state.
47 * Do not reference these action types directly in your code.
48 */
49var randomString = function randomString() {
50 return Math.random().toString(36).substring(7).split('').join('.');
51};
52
53var ActionTypes = {
54 INIT: "@@redux/INIT" + randomString(),
55 REPLACE: "@@redux/REPLACE" + randomString(),
56 PROBE_UNKNOWN_ACTION: function PROBE_UNKNOWN_ACTION() {
57 return "@@redux/PROBE_UNKNOWN_ACTION" + randomString();
58 }
59};
60
61/**
62 * @param {any} obj The object to inspect.
63 * @returns {boolean} True if the argument appears to be a plain object.
64 */
65function isPlainObject(obj) {
66 if (typeof obj !== 'object' || obj === null) return false;
67 var proto = obj;
68
69 while (Object.getPrototypeOf(proto) !== null) {
70 proto = Object.getPrototypeOf(proto);
71 }
72
73 return Object.getPrototypeOf(obj) === proto;
74}
75
76/**
77 * Creates a Redux store that holds the state tree.
78 * The only way to change the data in the store is to call `dispatch()` on it.
79 *
80 * There should only be a single store in your app. To specify how different
81 * parts of the state tree respond to actions, you may combine several reducers
82 * into a single reducer function by using `combineReducers`.
83 *
84 * @param {Function} reducer A function that returns the next state tree, given
85 * the current state tree and the action to handle.
86 *
87 * @param {any} [preloadedState] The initial state. You may optionally specify it
88 * to hydrate the state from the server in universal apps, or to restore a
89 * previously serialized user session.
90 * If you use `combineReducers` to produce the root reducer function, this must be
91 * an object with the same shape as `combineReducers` keys.
92 *
93 * @param {Function} [enhancer] The store enhancer. You may optionally specify it
94 * to enhance the store with third-party capabilities such as middleware,
95 * time travel, persistence, etc. The only store enhancer that ships with Redux
96 * is `applyMiddleware()`.
97 *
98 * @returns {Store} A Redux store that lets you read the state, dispatch actions
99 * and subscribe to changes.
100 */
101
102function createStore(reducer, preloadedState, enhancer) {
103 var _ref2;
104
105 if (typeof preloadedState === 'function' && typeof enhancer === 'function' || typeof enhancer === 'function' && typeof arguments[3] === 'function') {
106 throw new Error('It looks like you are passing several store enhancers to ' + 'createStore(). This is not supported. Instead, compose them ' + 'together to a single function.');
107 }
108
109 if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
110 enhancer = preloadedState;
111 preloadedState = undefined;
112 }
113
114 if (typeof enhancer !== 'undefined') {
115 if (typeof enhancer !== 'function') {
116 throw new Error('Expected the enhancer to be a function.');
117 }
118
119 return enhancer(createStore)(reducer, preloadedState);
120 }
121
122 if (typeof reducer !== 'function') {
123 throw new Error('Expected the reducer to be a function.');
124 }
125
126 var currentReducer = reducer;
127 var currentState = preloadedState;
128 var currentListeners = [];
129 var nextListeners = currentListeners;
130 var isDispatching = false;
131 /**
132 * This makes a shallow copy of currentListeners so we can use
133 * nextListeners as a temporary list while dispatching.
134 *
135 * This prevents any bugs around consumers calling
136 * subscribe/unsubscribe in the middle of a dispatch.
137 */
138
139 function ensureCanMutateNextListeners() {
140 if (nextListeners === currentListeners) {
141 nextListeners = currentListeners.slice();
142 }
143 }
144 /**
145 * Reads the state tree managed by the store.
146 *
147 * @returns {any} The current state tree of your application.
148 */
149
150
151 function getState() {
152 if (isDispatching) {
153 throw new Error('You may not call store.getState() while the reducer is executing. ' + 'The reducer has already received the state as an argument. ' + 'Pass it down from the top reducer instead of reading it from the store.');
154 }
155
156 return currentState;
157 }
158 /**
159 * Adds a change listener. It will be called any time an action is dispatched,
160 * and some part of the state tree may potentially have changed. You may then
161 * call `getState()` to read the current state tree inside the callback.
162 *
163 * You may call `dispatch()` from a change listener, with the following
164 * caveats:
165 *
166 * 1. The subscriptions are snapshotted just before every `dispatch()` call.
167 * If you subscribe or unsubscribe while the listeners are being invoked, this
168 * will not have any effect on the `dispatch()` that is currently in progress.
169 * However, the next `dispatch()` call, whether nested or not, will use a more
170 * recent snapshot of the subscription list.
171 *
172 * 2. The listener should not expect to see all state changes, as the state
173 * might have been updated multiple times during a nested `dispatch()` before
174 * the listener is called. It is, however, guaranteed that all subscribers
175 * registered before the `dispatch()` started will be called with the latest
176 * state by the time it exits.
177 *
178 * @param {Function} listener A callback to be invoked on every dispatch.
179 * @returns {Function} A function to remove this change listener.
180 */
181
182
183 function subscribe(listener) {
184 if (typeof listener !== 'function') {
185 throw new Error('Expected the listener to be a function.');
186 }
187
188 if (isDispatching) {
189 throw new Error('You may not call store.subscribe() while the reducer is executing. ' + 'If you would like to be notified after the store has been updated, subscribe from a ' + 'component and invoke store.getState() in the callback to access the latest state. ' + 'See https://redux.js.org/api-reference/store#subscribelistener for more details.');
190 }
191
192 var isSubscribed = true;
193 ensureCanMutateNextListeners();
194 nextListeners.push(listener);
195 return function unsubscribe() {
196 if (!isSubscribed) {
197 return;
198 }
199
200 if (isDispatching) {
201 throw new Error('You may not unsubscribe from a store listener while the reducer is executing. ' + 'See https://redux.js.org/api-reference/store#subscribelistener for more details.');
202 }
203
204 isSubscribed = false;
205 ensureCanMutateNextListeners();
206 var index = nextListeners.indexOf(listener);
207 nextListeners.splice(index, 1);
208 currentListeners = null;
209 };
210 }
211 /**
212 * Dispatches an action. It is the only way to trigger a state change.
213 *
214 * The `reducer` function, used to create the store, will be called with the
215 * current state tree and the given `action`. Its return value will
216 * be considered the **next** state of the tree, and the change listeners
217 * will be notified.
218 *
219 * The base implementation only supports plain object actions. If you want to
220 * dispatch a Promise, an Observable, a thunk, or something else, you need to
221 * wrap your store creating function into the corresponding middleware. For
222 * example, see the documentation for the `redux-thunk` package. Even the
223 * middleware will eventually dispatch plain object actions using this method.
224 *
225 * @param {Object} action A plain object representing “what changed”. It is
226 * a good idea to keep actions serializable so you can record and replay user
227 * sessions, or use the time travelling `redux-devtools`. An action must have
228 * a `type` property which may not be `undefined`. It is a good idea to use
229 * string constants for action types.
230 *
231 * @returns {Object} For convenience, the same action object you dispatched.
232 *
233 * Note that, if you use a custom middleware, it may wrap `dispatch()` to
234 * return something else (for example, a Promise you can await).
235 */
236
237
238 function dispatch(action) {
239 if (!isPlainObject(action)) {
240 throw new Error('Actions must be plain objects. ' + 'Use custom middleware for async actions.');
241 }
242
243 if (typeof action.type === 'undefined') {
244 throw new Error('Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?');
245 }
246
247 if (isDispatching) {
248 throw new Error('Reducers may not dispatch actions.');
249 }
250
251 try {
252 isDispatching = true;
253 currentState = currentReducer(currentState, action);
254 } finally {
255 isDispatching = false;
256 }
257
258 var listeners = currentListeners = nextListeners;
259
260 for (var i = 0; i < listeners.length; i++) {
261 var listener = listeners[i];
262 listener();
263 }
264
265 return action;
266 }
267 /**
268 * Replaces the reducer currently used by the store to calculate the state.
269 *
270 * You might need this if your app implements code splitting and you want to
271 * load some of the reducers dynamically. You might also need this if you
272 * implement a hot reloading mechanism for Redux.
273 *
274 * @param {Function} nextReducer The reducer for the store to use instead.
275 * @returns {void}
276 */
277
278
279 function replaceReducer(nextReducer) {
280 if (typeof nextReducer !== 'function') {
281 throw new Error('Expected the nextReducer to be a function.');
282 }
283
284 currentReducer = nextReducer; // This action has a similiar effect to ActionTypes.INIT.
285 // Any reducers that existed in both the new and old rootReducer
286 // will receive the previous state. This effectively populates
287 // the new state tree with any relevant data from the old one.
288
289 dispatch({
290 type: ActionTypes.REPLACE
291 });
292 }
293 /**
294 * Interoperability point for observable/reactive libraries.
295 * @returns {observable} A minimal observable of state changes.
296 * For more information, see the observable proposal:
297 * https://github.com/tc39/proposal-observable
298 */
299
300
301 function observable() {
302 var _ref;
303
304 var outerSubscribe = subscribe;
305 return _ref = {
306 /**
307 * The minimal observable subscription method.
308 * @param {Object} observer Any object that can be used as an observer.
309 * The observer object should have a `next` method.
310 * @returns {subscription} An object with an `unsubscribe` method that can
311 * be used to unsubscribe the observable from the store, and prevent further
312 * emission of values from the observable.
313 */
314 subscribe: function subscribe(observer) {
315 if (typeof observer !== 'object' || observer === null) {
316 throw new TypeError('Expected the observer to be an object.');
317 }
318
319 function observeState() {
320 if (observer.next) {
321 observer.next(getState());
322 }
323 }
324
325 observeState();
326 var unsubscribe = outerSubscribe(observeState);
327 return {
328 unsubscribe: unsubscribe
329 };
330 }
331 }, _ref[result] = function () {
332 return this;
333 }, _ref;
334 } // When a store is created, an "INIT" action is dispatched so that every
335 // reducer returns their initial state. This effectively populates
336 // the initial state tree.
337
338
339 dispatch({
340 type: ActionTypes.INIT
341 });
342 return _ref2 = {
343 dispatch: dispatch,
344 subscribe: subscribe,
345 getState: getState,
346 replaceReducer: replaceReducer
347 }, _ref2[result] = observable, _ref2;
348}
349
350/**
351 * Prints a warning in the console if it exists.
352 *
353 * @param {String} message The warning message.
354 * @returns {void}
355 */
356function warning(message) {
357 /* eslint-disable no-console */
358 if (typeof console !== 'undefined' && typeof console.error === 'function') {
359 console.error(message);
360 }
361 /* eslint-enable no-console */
362
363
364 try {
365 // This error was thrown as a convenience so that if you enable
366 // "break on all exceptions" in your console,
367 // it would pause the execution at this line.
368 throw new Error(message);
369 } catch (e) {} // eslint-disable-line no-empty
370
371}
372
373function getUndefinedStateErrorMessage(key, action) {
374 var actionType = action && action.type;
375 var actionDescription = actionType && "action \"" + String(actionType) + "\"" || 'an action';
376 return "Given " + actionDescription + ", reducer \"" + key + "\" returned undefined. " + "To ignore an action, you must explicitly return the previous state. " + "If you want this reducer to hold no value, you can return null instead of undefined.";
377}
378
379function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) {
380 var reducerKeys = Object.keys(reducers);
381 var argumentName = action && action.type === ActionTypes.INIT ? 'preloadedState argument passed to createStore' : 'previous state received by the reducer';
382
383 if (reducerKeys.length === 0) {
384 return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.';
385 }
386
387 if (!isPlainObject(inputState)) {
388 return "The " + argumentName + " has unexpected type of \"" + {}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + "\". Expected argument to be an object with the following " + ("keys: \"" + reducerKeys.join('", "') + "\"");
389 }
390
391 var unexpectedKeys = Object.keys(inputState).filter(function (key) {
392 return !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key];
393 });
394 unexpectedKeys.forEach(function (key) {
395 unexpectedKeyCache[key] = true;
396 });
397 if (action && action.type === ActionTypes.REPLACE) return;
398
399 if (unexpectedKeys.length > 0) {
400 return "Unexpected " + (unexpectedKeys.length > 1 ? 'keys' : 'key') + " " + ("\"" + unexpectedKeys.join('", "') + "\" found in " + argumentName + ". ") + "Expected to find one of the known reducer keys instead: " + ("\"" + reducerKeys.join('", "') + "\". Unexpected keys will be ignored.");
401 }
402}
403
404function assertReducerShape(reducers) {
405 Object.keys(reducers).forEach(function (key) {
406 var reducer = reducers[key];
407 var initialState = reducer(undefined, {
408 type: ActionTypes.INIT
409 });
410
411 if (typeof initialState === 'undefined') {
412 throw new Error("Reducer \"" + key + "\" returned undefined during initialization. " + "If the state passed to the reducer is undefined, you must " + "explicitly return the initial state. The initial state may " + "not be undefined. If you don't want to set a value for this reducer, " + "you can use null instead of undefined.");
413 }
414
415 if (typeof reducer(undefined, {
416 type: ActionTypes.PROBE_UNKNOWN_ACTION()
417 }) === 'undefined') {
418 throw new Error("Reducer \"" + key + "\" returned undefined when probed with a random type. " + ("Don't try to handle " + ActionTypes.INIT + " or other actions in \"redux/*\" ") + "namespace. They are considered private. Instead, you must return the " + "current state for any unknown actions, unless it is undefined, " + "in which case you must return the initial state, regardless of the " + "action type. The initial state may not be undefined, but can be null.");
419 }
420 });
421}
422/**
423 * Turns an object whose values are different reducer functions, into a single
424 * reducer function. It will call every child reducer, and gather their results
425 * into a single state object, whose keys correspond to the keys of the passed
426 * reducer functions.
427 *
428 * @param {Object} reducers An object whose values correspond to different
429 * reducer functions that need to be combined into one. One handy way to obtain
430 * it is to use ES6 `import * as reducers` syntax. The reducers may never return
431 * undefined for any action. Instead, they should return their initial state
432 * if the state passed to them was undefined, and the current state for any
433 * unrecognized action.
434 *
435 * @returns {Function} A reducer function that invokes every reducer inside the
436 * passed object, and builds a state object with the same shape.
437 */
438
439
440function combineReducers(reducers) {
441 var reducerKeys = Object.keys(reducers);
442 var finalReducers = {};
443
444 for (var i = 0; i < reducerKeys.length; i++) {
445 var key = reducerKeys[i];
446
447 {
448 if (typeof reducers[key] === 'undefined') {
449 warning("No reducer provided for key \"" + key + "\"");
450 }
451 }
452
453 if (typeof reducers[key] === 'function') {
454 finalReducers[key] = reducers[key];
455 }
456 }
457
458 var finalReducerKeys = Object.keys(finalReducers); // This is used to make sure we don't warn about the same
459 // keys multiple times.
460
461 var unexpectedKeyCache;
462
463 {
464 unexpectedKeyCache = {};
465 }
466
467 var shapeAssertionError;
468
469 try {
470 assertReducerShape(finalReducers);
471 } catch (e) {
472 shapeAssertionError = e;
473 }
474
475 return function combination(state, action) {
476 if (state === void 0) {
477 state = {};
478 }
479
480 if (shapeAssertionError) {
481 throw shapeAssertionError;
482 }
483
484 {
485 var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache);
486
487 if (warningMessage) {
488 warning(warningMessage);
489 }
490 }
491
492 var hasChanged = false;
493 var nextState = {};
494
495 for (var _i = 0; _i < finalReducerKeys.length; _i++) {
496 var _key = finalReducerKeys[_i];
497 var reducer = finalReducers[_key];
498 var previousStateForKey = state[_key];
499 var nextStateForKey = reducer(previousStateForKey, action);
500
501 if (typeof nextStateForKey === 'undefined') {
502 var errorMessage = getUndefinedStateErrorMessage(_key, action);
503 throw new Error(errorMessage);
504 }
505
506 nextState[_key] = nextStateForKey;
507 hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
508 }
509
510 hasChanged = hasChanged || finalReducerKeys.length !== Object.keys(state).length;
511 return hasChanged ? nextState : state;
512 };
513}
514
515function bindActionCreator(actionCreator, dispatch) {
516 return function () {
517 return dispatch(actionCreator.apply(this, arguments));
518 };
519}
520/**
521 * Turns an object whose values are action creators, into an object with the
522 * same keys, but with every function wrapped into a `dispatch` call so they
523 * may be invoked directly. This is just a convenience method, as you can call
524 * `store.dispatch(MyActionCreators.doSomething())` yourself just fine.
525 *
526 * For convenience, you can also pass an action creator as the first argument,
527 * and get a dispatch wrapped function in return.
528 *
529 * @param {Function|Object} actionCreators An object whose values are action
530 * creator functions. One handy way to obtain it is to use ES6 `import * as`
531 * syntax. You may also pass a single function.
532 *
533 * @param {Function} dispatch The `dispatch` function available on your Redux
534 * store.
535 *
536 * @returns {Function|Object} The object mimicking the original object, but with
537 * every action creator wrapped into the `dispatch` call. If you passed a
538 * function as `actionCreators`, the return value will also be a single
539 * function.
540 */
541
542
543function bindActionCreators(actionCreators, dispatch) {
544 if (typeof actionCreators === 'function') {
545 return bindActionCreator(actionCreators, dispatch);
546 }
547
548 if (typeof actionCreators !== 'object' || actionCreators === null) {
549 throw new Error("bindActionCreators expected an object or a function, instead received " + (actionCreators === null ? 'null' : typeof actionCreators) + ". " + "Did you write \"import ActionCreators from\" instead of \"import * as ActionCreators from\"?");
550 }
551
552 var boundActionCreators = {};
553
554 for (var key in actionCreators) {
555 var actionCreator = actionCreators[key];
556
557 if (typeof actionCreator === 'function') {
558 boundActionCreators[key] = bindActionCreator(actionCreator, dispatch);
559 }
560 }
561
562 return boundActionCreators;
563}
564
565function _defineProperty(obj, key, value) {
566 if (key in obj) {
567 Object.defineProperty(obj, key, {
568 value: value,
569 enumerable: true,
570 configurable: true,
571 writable: true
572 });
573 } else {
574 obj[key] = value;
575 }
576
577 return obj;
578}
579
580function ownKeys(object, enumerableOnly) {
581 var keys = Object.keys(object);
582
583 if (Object.getOwnPropertySymbols) {
584 keys.push.apply(keys, Object.getOwnPropertySymbols(object));
585 }
586
587 if (enumerableOnly) keys = keys.filter(function (sym) {
588 return Object.getOwnPropertyDescriptor(object, sym).enumerable;
589 });
590 return keys;
591}
592
593function _objectSpread2(target) {
594 for (var i = 1; i < arguments.length; i++) {
595 var source = arguments[i] != null ? arguments[i] : {};
596
597 if (i % 2) {
598 ownKeys(source, true).forEach(function (key) {
599 _defineProperty(target, key, source[key]);
600 });
601 } else if (Object.getOwnPropertyDescriptors) {
602 Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
603 } else {
604 ownKeys(source).forEach(function (key) {
605 Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
606 });
607 }
608 }
609
610 return target;
611}
612
613/**
614 * Composes single-argument functions from right to left. The rightmost
615 * function can take multiple arguments as it provides the signature for
616 * the resulting composite function.
617 *
618 * @param {...Function} funcs The functions to compose.
619 * @returns {Function} A function obtained by composing the argument functions
620 * from right to left. For example, compose(f, g, h) is identical to doing
621 * (...args) => f(g(h(...args))).
622 */
623function compose() {
624 for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) {
625 funcs[_key] = arguments[_key];
626 }
627
628 if (funcs.length === 0) {
629 return function (arg) {
630 return arg;
631 };
632 }
633
634 if (funcs.length === 1) {
635 return funcs[0];
636 }
637
638 return funcs.reduce(function (a, b) {
639 return function () {
640 return a(b.apply(void 0, arguments));
641 };
642 });
643}
644
645/**
646 * Creates a store enhancer that applies middleware to the dispatch method
647 * of the Redux store. This is handy for a variety of tasks, such as expressing
648 * asynchronous actions in a concise manner, or logging every action payload.
649 *
650 * See `redux-thunk` package as an example of the Redux middleware.
651 *
652 * Because middleware is potentially asynchronous, this should be the first
653 * store enhancer in the composition chain.
654 *
655 * Note that each middleware will be given the `dispatch` and `getState` functions
656 * as named arguments.
657 *
658 * @param {...Function} middlewares The middleware chain to be applied.
659 * @returns {Function} A store enhancer applying the middleware.
660 */
661
662function applyMiddleware() {
663 for (var _len = arguments.length, middlewares = new Array(_len), _key = 0; _key < _len; _key++) {
664 middlewares[_key] = arguments[_key];
665 }
666
667 return function (createStore) {
668 return function () {
669 var store = createStore.apply(void 0, arguments);
670
671 var _dispatch = function dispatch() {
672 throw new Error('Dispatching while constructing your middleware is not allowed. ' + 'Other middleware would not be applied to this dispatch.');
673 };
674
675 var middlewareAPI = {
676 getState: store.getState,
677 dispatch: function dispatch() {
678 return _dispatch.apply(void 0, arguments);
679 }
680 };
681 var chain = middlewares.map(function (middleware) {
682 return middleware(middlewareAPI);
683 });
684 _dispatch = compose.apply(void 0, chain)(store.dispatch);
685 return _objectSpread2({}, store, {
686 dispatch: _dispatch
687 });
688 };
689 };
690}
691
692/*
693 * This is a dummy function to check if the function name has been altered by minification.
694 * If the function has been minified and NODE_ENV !== 'production', warn the user.
695 */
696
697function isCrushed() {}
698
699if ( typeof isCrushed.name === 'string' && isCrushed.name !== 'isCrushed') {
700 warning('You are currently using minified code outside of NODE_ENV === "production". ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or setting mode to production in webpack (https://webpack.js.org/concepts/mode/) ' + 'to ensure you have the correct code for your production build.');
701}
702
703exports.__DO_NOT_USE__ActionTypes = ActionTypes;
704exports.applyMiddleware = applyMiddleware;
705exports.bindActionCreators = bindActionCreators;
706exports.combineReducers = combineReducers;
707exports.compose = compose;
708exports.createStore = createStore;
709
710Object.defineProperty(exports, '__esModule', { value: true });
711
712}));