UNPKG

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