index.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('lodash.merge')) :
  3. typeof define === 'function' && define.amd ? define(['exports', 'lodash.merge'], factory) :
  4. (global = global || self, factory(global.VuexPersistence = {}, global._.merge));
  5. }(this, (function (exports, lodashMerge) { 'use strict';
  6. lodashMerge = lodashMerge && lodashMerge.hasOwnProperty('default') ? lodashMerge['default'] : lodashMerge;
  7. /**
  8. * Created by championswimmer on 22/07/17.
  9. */
  10. // tslint:disable: variable-name
  11. var SimplePromiseQueue = /** @class */ (function () {
  12. function SimplePromiseQueue() {
  13. this._queue = [];
  14. this._flushing = false;
  15. }
  16. SimplePromiseQueue.prototype.enqueue = function (promise) {
  17. this._queue.push(promise);
  18. if (!this._flushing) {
  19. return this.flushQueue();
  20. }
  21. return Promise.resolve();
  22. };
  23. SimplePromiseQueue.prototype.flushQueue = function () {
  24. var _this = this;
  25. this._flushing = true;
  26. var chain = function () {
  27. var nextTask = _this._queue.shift();
  28. if (nextTask) {
  29. return nextTask.then(chain);
  30. }
  31. else {
  32. _this._flushing = false;
  33. }
  34. };
  35. return Promise.resolve(chain());
  36. };
  37. return SimplePromiseQueue;
  38. }());
  39. function merge(into, from) {
  40. return lodashMerge({}, into, from);
  41. }
  42. var FlattedJSON = JSON;
  43. /**
  44. * A class that implements the vuex persistence.
  45. * @type S type of the 'state' inside the store (default: any)
  46. */
  47. var VuexPersistence = /** @class */ (function () {
  48. /**
  49. * Create a {@link VuexPersistence} object.
  50. * Use the <code>plugin</code> function of this class as a
  51. * Vuex plugin.
  52. * @param {PersistOptions} options
  53. */
  54. function VuexPersistence(options) {
  55. var _this = this;
  56. // tslint:disable-next-line:variable-name
  57. this._mutex = new SimplePromiseQueue();
  58. /**
  59. * Creates a subscriber on the store. automatically is used
  60. * when this is used a vuex plugin. Not for manual usage.
  61. * @param store
  62. */
  63. this.subscriber = function (store) {
  64. return function (handler) { return store.subscribe(handler); };
  65. };
  66. if (typeof options === 'undefined')
  67. options = {};
  68. this.key = ((options.key != null) ? options.key : 'vuex');
  69. this.subscribed = false;
  70. this.supportCircular = options.supportCircular || false;
  71. if (this.supportCircular) {
  72. FlattedJSON = require('flatted');
  73. }
  74. // @ts-ignore
  75. {
  76. // @ts-ignore
  77. {
  78. // If UMD module, then we will only be having localStorage
  79. this.storage = options.storage || window.localStorage;
  80. }
  81. }
  82. /**
  83. * How this works is -
  84. * 1. If there is options.reducer function, we use that, if not;
  85. * 2. We check options.modules;
  86. * 1. If there is no options.modules array, we use entire state in reducer
  87. * 2. Otherwise, we create a reducer that merges all those state modules that are
  88. * defined in the options.modules[] array
  89. * @type {((state: S) => {}) | ((state: S) => S) | ((state: any) => {})}
  90. */
  91. this.reducer = ((options.reducer != null)
  92. ? options.reducer
  93. : ((options.modules == null)
  94. ? (function (state) { return state; })
  95. : (function (state) {
  96. return options.modules.reduce(function (a, i) {
  97. var _a;
  98. return merge(a, (_a = {}, _a[i] = state[i], _a));
  99. }, { /* start empty accumulator*/});
  100. })));
  101. this.filter = options.filter || (function (mutation) { return true; });
  102. this.strictMode = options.strictMode || false;
  103. this.RESTORE_MUTATION = function RESTORE_MUTATION(state, savedState) {
  104. var mergedState = merge(state, savedState || {});
  105. for (var _i = 0, _a = Object.keys(mergedState); _i < _a.length; _i++) {
  106. var propertyName = _a[_i];
  107. this._vm.$set(state, propertyName, mergedState[propertyName]);
  108. }
  109. };
  110. this.asyncStorage = options.asyncStorage || false;
  111. if (this.asyncStorage) {
  112. /**
  113. * Async {@link #VuexPersistence.restoreState} implementation
  114. * @type {((key: string, storage?: Storage) =>
  115. * (Promise<S> | S)) | ((key: string, storage: AsyncStorage) => Promise<any>)}
  116. */
  117. this.restoreState = ((options.restoreState != null)
  118. ? options.restoreState
  119. : (function (key, storage) {
  120. return (storage).getItem(key)
  121. .then(function (value) {
  122. return typeof value === 'string' // If string, parse, or else, just return
  123. ? (_this.supportCircular
  124. ? FlattedJSON.parse(value || '{}')
  125. : JSON.parse(value || '{}'))
  126. : (value || {});
  127. });
  128. }));
  129. /**
  130. * Async {@link #VuexPersistence.saveState} implementation
  131. * @type {((key: string, state: {}, storage?: Storage) =>
  132. * (Promise<void> | void)) | ((key: string, state: {}, storage?: Storage) => Promise<void>)}
  133. */
  134. this.saveState = ((options.saveState != null)
  135. ? options.saveState
  136. : (function (key, state, storage) {
  137. return (storage).setItem(key, // Second argument is state _object_ if asyc storage, stringified otherwise
  138. // do not stringify the state if the storage type is async
  139. (_this.asyncStorage
  140. ? merge({}, state || {})
  141. : (_this.supportCircular
  142. ? FlattedJSON.stringify(state)
  143. : JSON.stringify(state))));
  144. }));
  145. /**
  146. * Async version of plugin
  147. * @param {Store<S>} store
  148. */
  149. this.plugin = function (store) {
  150. /**
  151. * For async stores, we're capturing the Promise returned
  152. * by the `restoreState()` function in a `restored` property
  153. * on the store itself. This would allow app developers to
  154. * determine when and if the store's state has indeed been
  155. * refreshed. This approach was suggested by GitHub user @hotdogee.
  156. * See https://github.com/championswimmer/vuex-persist/pull/118#issuecomment-500914963
  157. * @since 2.1.0
  158. */
  159. store.restored = (_this.restoreState(_this.key, _this.storage)).then(function (savedState) {
  160. /**
  161. * If in strict mode, do only via mutation
  162. */
  163. if (_this.strictMode) {
  164. store.commit('RESTORE_MUTATION', savedState);
  165. }
  166. else {
  167. store.replaceState(merge(store.state, savedState || {}));
  168. }
  169. _this.subscriber(store)(function (mutation, state) {
  170. if (_this.filter(mutation)) {
  171. _this._mutex.enqueue(_this.saveState(_this.key, _this.reducer(state), _this.storage));
  172. }
  173. });
  174. _this.subscribed = true;
  175. });
  176. };
  177. }
  178. else {
  179. /**
  180. * Sync {@link #VuexPersistence.restoreState} implementation
  181. * @type {((key: string, storage?: Storage) =>
  182. * (Promise<S> | S)) | ((key: string, storage: Storage) => (any | string | {}))}
  183. */
  184. this.restoreState = ((options.restoreState != null)
  185. ? options.restoreState
  186. : (function (key, storage) {
  187. var value = (storage).getItem(key);
  188. if (typeof value === 'string') { // If string, parse, or else, just return
  189. return (_this.supportCircular
  190. ? FlattedJSON.parse(value || '{}')
  191. : JSON.parse(value || '{}'));
  192. }
  193. else {
  194. return (value || {});
  195. }
  196. }));
  197. /**
  198. * Sync {@link #VuexPersistence.saveState} implementation
  199. * @type {((key: string, state: {}, storage?: Storage) =>
  200. * (Promise<void> | void)) | ((key: string, state: {}, storage?: Storage) => Promise<void>)}
  201. */
  202. this.saveState = ((options.saveState != null)
  203. ? options.saveState
  204. : (function (key, state, storage) {
  205. return (storage).setItem(key, // Second argument is state _object_ if localforage, stringified otherwise
  206. (_this.supportCircular
  207. ? FlattedJSON.stringify(state)
  208. : JSON.stringify(state)));
  209. }));
  210. /**
  211. * Sync version of plugin
  212. * @param {Store<S>} store
  213. */
  214. this.plugin = function (store) {
  215. var savedState = _this.restoreState(_this.key, _this.storage);
  216. if (_this.strictMode) {
  217. store.commit('RESTORE_MUTATION', savedState);
  218. }
  219. else {
  220. store.replaceState(merge(store.state, savedState || {}));
  221. }
  222. _this.subscriber(store)(function (mutation, state) {
  223. if (_this.filter(mutation)) {
  224. _this.saveState(_this.key, _this.reducer(state), _this.storage);
  225. }
  226. });
  227. _this.subscribed = true;
  228. };
  229. }
  230. }
  231. return VuexPersistence;
  232. }());
  233. exports.VuexPersistence = VuexPersistence;
  234. exports.default = VuexPersistence;
  235. Object.defineProperty(exports, '__esModule', { value: true });
  236. })));
  237. //# sourceMappingURL=index.js.map