UNPKG

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