UNPKG

react-pouch

Version:

The simplest state management library ever. No providers, no flux, no context hell. Just plug-and-play state for React & React Native with 100% test coverage.

862 lines (843 loc) 28.3 kB
'use strict'; var react = require('react'); function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; } function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; } function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function (t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i.return) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine(u), _regeneratorDefine(u, o, "Generator"), _regeneratorDefine(u, n, function () { return this; }), _regeneratorDefine(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function () { return { w: i, m: f }; })(); } function _regeneratorDefine(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine = function (e, r, n, t) { if (r) i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n;else { function o(r, n) { _regeneratorDefine(e, r, function (e) { return this._invoke(r, n, e); }); } o("next", 0), o("throw", 1), o("return", 2); } }, _regeneratorDefine(e, r, n, t); } function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } var PouchImpl = /*#__PURE__*/function () { function PouchImpl(initialValue) { var _this = this; var plugins = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; _classCallCheck(this, PouchImpl); this.listeners = new Set(); this.plugins = plugins; this.value = this.initializeWithPlugins(initialValue); this.plugins.forEach(function (plugin) { if (plugin.setup) { plugin.setup(_this); } }); } return _createClass(PouchImpl, [{ key: "initializeWithPlugins", value: function initializeWithPlugins(initialValue) { var value = initialValue; this.plugins.forEach(function (plugin) { if (plugin.initialize) { value = plugin.initialize(value); } }); return value; } }, { key: "get", value: function get() { return this.value; } }, { key: "set", value: function set(newValue) { var _this2 = this; var oldValue = this.value; if (typeof newValue === "function") { this.value = newValue(this.value); } else { this.value = newValue; } // Let plugins potentially modify the value this.plugins.forEach(function (plugin) { if (plugin.onSet) { var result = plugin.onSet(_this2.value, oldValue); if (result !== undefined) { _this2.value = result; } } }); this.notify(); } }, { key: "subscribe", value: function subscribe(listener) { var _this3 = this; this.listeners.add(listener); return function () { return _this3.listeners["delete"](listener); }; } }, { key: "notify", value: function notify() { this.listeners.forEach(function (listener) { return listener(); }); } }, { key: "use", value: function use() { var _this4 = this; var _useState = react.useState({}), _useState2 = _slicedToArray(_useState, 2), forceUpdate = _useState2[1]; react.useEffect(function () { var unsubscribe = _this4.subscribe(function () { return forceUpdate({}); }); return unsubscribe; }, []); return this.value; } }]); }(); function pouch(initialValue, plugins) { return new PouchImpl(initialValue, plugins || []); } function store(initialValue, plugins) { return pouch(initialValue, plugins || []); } // Helper function for better plugin inference function withPlugins(initialValue, plugins) { return pouch(initialValue, plugins); } function usePouch(pouchInstance) { return pouchInstance.use(); } // Keep useStore as an alias for backward compatibility function useStore(storeInstance) { return storeInstance.use(); } function safeStringify$1(obj) { var seen = new WeakSet(); return JSON.stringify(obj, function (key, val) { if (val != null && _typeof(val) === "object") { if (seen.has(val)) { return "[Circular]"; } seen.add(val); } return val; }); } function persist(key) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var _options$storage = options.storage, storage = _options$storage === void 0 ? "localStorage" : _options$storage, _options$serialize = options.serialize, serialize = _options$serialize === void 0 ? safeStringify$1 : _options$serialize, _options$deserialize = options.deserialize, deserialize = _options$deserialize === void 0 ? JSON.parse : _options$deserialize; return { initialize: function initialize(initialValue) { if (typeof window === "undefined") return initialValue; try { var storageApi = window[storage]; var storedValue = storageApi.getItem(key); if (storedValue !== null) { return deserialize(storedValue); } } catch (error) { console.warn("Failed to load ".concat(key, " from ").concat(storage, ":"), error); } return initialValue; }, onSet: function onSet(newValue) { if (typeof window === "undefined") return; try { var storageApi = window[storage]; storageApi.setItem(key, serialize(newValue)); } catch (error) { console.warn("Failed to save ".concat(key, " to ").concat(storage, ":"), error); } } }; } function safeStringify(obj) { var seen = new WeakSet(); return JSON.stringify(obj, function (key, val) { if (val != null && _typeof(val) === "object") { if (seen.has(val)) { return "[Circular]"; } seen.add(val); } return val; }); } function rnPersist(key) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var _options$serialize = options.serialize, serialize = _options$serialize === void 0 ? safeStringify : _options$serialize, _options$deserialize = options.deserialize, deserialize = _options$deserialize === void 0 ? JSON.parse : _options$deserialize, asyncStorage = options.asyncStorage; // Try to get AsyncStorage from options first, then from @react-native-async-storage/async-storage var AsyncStorage = asyncStorage; if (!AsyncStorage) { try { // Use dynamic import to avoid bundler dependency resolution var packageName = '@react-native-async-storage/async-storage'; AsyncStorage = eval("require('".concat(packageName, "')"))["default"]; } catch (error) { // AsyncStorage not available, plugin will be disabled console.warn('rnPersist: AsyncStorage not available. Install @react-native-async-storage/async-storage or provide asyncStorage option.'); } } return { setup: function setup(pouch) { // Always add storage info method regardless of AsyncStorage availability pouch.getStorageInfo = function () { return { key: key, available: !!AsyncStorage, type: 'AsyncStorage' }; }; // Add clear method (will be no-op if AsyncStorage not available) pouch.clearStorage = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() { var _t; return _regenerator().w(function (_context) { while (1) switch (_context.p = _context.n) { case 0: if (!AsyncStorage) { _context.n = 4; break; } _context.p = 1; _context.n = 2; return AsyncStorage.removeItem(key); case 2: _context.n = 4; break; case 3: _context.p = 3; _t = _context.v; console.error("rnPersist: Failed to clear data for key \"".concat(key, "\":"), _t); case 4: return _context.a(2); } }, _callee, null, [[1, 3]]); })); if (!AsyncStorage) return; // Load data asynchronously after setup AsyncStorage.getItem(key).then(function (stored) { if (stored !== null) { try { var data = deserialize(stored); pouch.set(data); } catch (error) { console.error("rnPersist: Failed to parse stored data for key \"".concat(key, "\":"), error); } } })["catch"](function (error) { console.error("rnPersist: Failed to load data for key \"".concat(key, "\":"), error); }); var originalSet = pouch.set.bind(pouch); pouch.set = function (newValue) { var resolvedValue = typeof newValue === 'function' ? newValue(pouch.get()) : newValue; // Call original set first originalSet(newValue); // Then persist asynchronously try { var serialized = serialize(resolvedValue); AsyncStorage.setItem(key, serialized)["catch"](function (error) { console.error("rnPersist: Failed to save data for key \"".concat(key, "\":"), error); }); } catch (error) { console.error("rnPersist: Failed to serialize data for key \"".concat(key, "\":"), error); } }; } }; } function validate(validator) { return { setup: function setup(pouch) { var originalSet = pouch.set.bind(pouch); pouch.set = function (newValue) { var resolvedValue = typeof newValue === 'function' ? newValue(pouch.get()) : newValue; var validation = validator(resolvedValue); if (!validation.isValid) { throw new Error(validation.error || "Validation failed"); } originalSet(newValue); }; } }; } function logger(name) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var _options$collapsed = options.collapsed, collapsed = _options$collapsed === void 0 ? false : _options$collapsed, _options$timestamp = options.timestamp, timestamp = _options$timestamp === void 0 ? true : _options$timestamp; return { setup: function setup(pouch) { console.log("[".concat(name, "] Pouch initialized with:"), pouch.get()); }, onSet: function onSet(newValue, oldValue) { var time = timestamp ? new Date().toISOString() : ""; var groupMethod = collapsed ? "groupCollapsed" : "group"; console[groupMethod]("[".concat(name, "] State Change ").concat(time)); console.log("Previous:", oldValue); console.log("Current:", newValue); console.log("Type:", _typeof(newValue)); console.groupEnd(); } }; } function computed(computeFn) { var computedValue; return { setup: function setup(pouch) { computedValue = computeFn(pouch.get()); pouch.computed = function () { return computedValue; }; }, onSet: function onSet(newValue) { computedValue = computeFn(newValue); } }; } var _excluded = ["debounce", "onError", "headers"]; function sync(url) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var _options$debounce = options.debounce, debounce = _options$debounce === void 0 ? 500 : _options$debounce, _options$onError = options.onError, onError = _options$onError === void 0 ? console.error : _options$onError, _options$headers = options.headers, headers = _options$headers === void 0 ? {} : _options$headers, fetchOptions = _objectWithoutProperties(options, _excluded); var timeout; return { setup: function setup(pouch) { if (typeof window === "undefined") return; // Use global fetch if available var fetchFn = typeof fetch !== "undefined" ? fetch : global.fetch; if (!fetchFn) return; try { fetchFn(url).then(function (res) { return res.json(); }).then(function (data) { return pouch.set(data); })["catch"](onError); } catch (error) { onError(error); } }, onSet: function onSet(newValue) { if (typeof window === "undefined") return; clearTimeout(timeout); timeout = setTimeout(function () { // Use global fetch if available var fetchFn = typeof fetch !== "undefined" ? fetch : global.fetch; if (!fetchFn) return; try { var requestOptions = _objectSpread2({ method: "POST", body: JSON.stringify(newValue), headers: _objectSpread2({ "Content-Type": "application/json" }, headers) }, fetchOptions); fetchFn(url, requestOptions)["catch"](onError); } catch (error) { onError(error); } }, debounce); } }; } function history() { var maxSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 10; var past = []; var future = []; var isUndoRedoing = false; return { setup: function setup(pouch) { var historyPouch = pouch; var originalSet = pouch.set.bind(pouch); historyPouch.undo = function () { if (past.length > 0) { var current = pouch.get(); var previous = past.pop(); future.unshift(current); isUndoRedoing = true; originalSet(previous); isUndoRedoing = false; } }; historyPouch.redo = function () { if (future.length > 0) { var current = pouch.get(); var next = future.shift(); past.push(current); isUndoRedoing = true; originalSet(next); isUndoRedoing = false; } }; historyPouch.canUndo = function () { return past.length > 0; }; historyPouch.canRedo = function () { return future.length > 0; }; historyPouch.history = { past: past, future: future }; }, onSet: function onSet(newValue, oldValue) { if (!isUndoRedoing) { past.push(oldValue); if (past.length > maxSize) past.shift(); future.length = 0; } } }; } // Simple XOR encryption for demo - use proper encryption in production! function simpleEncrypt(text, key) { return btoa(text.split("").map(function (_char, i) { return String.fromCharCode(_char.charCodeAt(0) ^ key.charCodeAt(i % key.length)); }).join("")); } function simpleDecrypt(encrypted, key) { return atob(encrypted).split("").map(function (_char2, i) { return String.fromCharCode(_char2.charCodeAt(0) ^ key.charCodeAt(i % key.length)); }).join(""); } function encrypt(secretKey) { var PREFIX = "encrypted:"; return { initialize: function initialize(value) { if (typeof value === "string" && value.startsWith(PREFIX)) { try { var decrypted = simpleDecrypt(value.slice(PREFIX.length), secretKey); return JSON.parse(decrypted); } catch (error) { console.error("Failed to decrypt:", error); return value; } } return value; }, onSet: function onSet(newValue) { try { var serialized = JSON.stringify(newValue); if (serialized === undefined) { // Cannot encrypt undefined return newValue; } var encrypted = simpleEncrypt(serialized, secretKey); return PREFIX + encrypted; } catch (error) { console.error("Failed to encrypt:", error); return newValue; } } }; } function throttle(ms) { var lastCall = 0; var pendingValue; var timeout; return { setup: function setup(pouch) { var originalSet = pouch.set.bind(pouch); pouch.set = function (newValue) { var now = Date.now(); if (now - lastCall >= ms) { lastCall = now; originalSet(newValue); clearTimeout(timeout); } else { pendingValue = typeof newValue === "function" ? newValue(pouch.get()) : newValue; clearTimeout(timeout); timeout = setTimeout(function () { if (pendingValue !== undefined) { lastCall = Date.now(); originalSet(pendingValue); pendingValue = undefined; } }, ms - (now - lastCall)); } }; } }; } function debounce(ms) { var timeout; return { setup: function setup(pouch) { var originalSet = pouch.set.bind(pouch); pouch.set = function (newValue) { clearTimeout(timeout); timeout = setTimeout(function () { originalSet(newValue); }, ms); }; } }; } function validateSchema(value, schema) { var path = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ""; for (var _i = 0, _Object$entries = Object.entries(schema); _i < _Object$entries.length; _i++) { var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2), key = _Object$entries$_i[0], expectedType = _Object$entries$_i[1]; var currentPath = path ? "".concat(path, ".").concat(key) : key; var actualValue = value[key]; if (actualValue === undefined) { throw new Error("Missing required field: ".concat(currentPath)); } if (typeof expectedType === "string") { var actualType = Array.isArray(actualValue) ? "array" : _typeof(actualValue); if (actualType !== expectedType) { throw new Error("Invalid type for ".concat(currentPath, ": expected ").concat(expectedType, ", got ").concat(actualType)); } } else { validateSchema(actualValue, expectedType, currentPath); } } } function schema(schemaDefinition) { return { onSet: function onSet(newValue) { validateSchema(newValue, schemaDefinition); } }; } function analytics(eventName) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var _options$trackInitial = options.trackInitial, trackInitial = _options$trackInitial === void 0 ? false : _options$trackInitial, _options$includeTimes = options.includeTimestamp, includeTimestamp = _options$includeTimes === void 0 ? true : _options$includeTimes, _options$sanitize = options.sanitize, sanitize = _options$sanitize === void 0 ? function (v) { return v; } : _options$sanitize; return { setup: function setup(store) { if (trackInitial && typeof window !== "undefined" && window.gtag) { window.gtag("event", "".concat(eventName, "_initialized"), { value: JSON.stringify(sanitize(store.get())), timestamp: includeTimestamp ? new Date().toISOString() : undefined }); } }, onSet: function onSet(newValue, oldValue) { if (typeof window !== "undefined" && window.gtag) { window.gtag("event", eventName, { previous_value: JSON.stringify(sanitize(oldValue)), new_value: JSON.stringify(sanitize(newValue)), timestamp: includeTimestamp ? new Date().toISOString() : undefined }); } } }; } function middleware() { for (var _len = arguments.length, middlewares = new Array(_len), _key = 0; _key < _len; _key++) { middlewares[_key] = arguments[_key]; } return { setup: function setup(store) { var originalSet = store.set.bind(store); store.set = function (newValue) { var value = typeof newValue === "function" ? newValue(store.get()) : newValue; var oldValue = store.get(); for (var _i = 0, _middlewares = middlewares; _i < _middlewares.length; _i++) { var mw = _middlewares[_i]; value = mw(value, oldValue); } originalSet(value); }; } }; } exports.analytics = analytics; exports.computed = computed; exports.debounce = debounce; exports.encrypt = encrypt; exports.history = history; exports.logger = logger; exports.middleware = middleware; exports.persist = persist; exports.pouch = pouch; exports.rnPersist = rnPersist; exports.schema = schema; exports.store = store; exports.sync = sync; exports.throttle = throttle; exports.usePouch = usePouch; exports.useStore = useStore; exports.validate = validate; exports.withPlugins = withPlugins; //# sourceMappingURL=index.js.map