index.js 9.4 KB

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