react-wire-persisted 1.0.6 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,232 @@
1
+ import { createWire as b } from "@forminator/react-wire";
2
+ (function() {
3
+ const s = {};
4
+ try {
5
+ if (process) {
6
+ process.env = Object.assign({}, process.env), Object.assign(process.env, s);
7
+ return;
8
+ }
9
+ } catch {
10
+ }
11
+ globalThis.process = { env: s };
12
+ })();
13
+ const m = {}, p = (s) => {
14
+ m[s] = s;
15
+ }, I = (s) => p(s), O = () => m, S = (s, e = null) => {
16
+ const t = e || m;
17
+ return s ? Object.keys(t).reduce((r, n) => ({
18
+ ...r,
19
+ [n]: `${s}.${t[n]}`
20
+ }), {}) : t;
21
+ }, g = {
22
+ getItem: (s) => g[s],
23
+ setItem: (s, e) => {
24
+ g[s] = e;
25
+ },
26
+ removeItem: (s) => {
27
+ delete g[s];
28
+ }
29
+ }, d = (s) => {
30
+ const e = typeof s;
31
+ return s === null ? !0 : Array.isArray(s) || e === "object" ? !1 : e !== "function";
32
+ }, P = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
33
+ __proto__: null,
34
+ addKey: p,
35
+ fakeLocalStorage: g,
36
+ getKeys: O,
37
+ getPrefixedKeys: S,
38
+ isPrimitive: d,
39
+ key: I
40
+ }, Symbol.toStringTag, { value: "Module" }));
41
+ class h {
42
+ /**
43
+ * Initializes the class
44
+ * @param {String} namespace Namespace to prefix all keys with. Mostly used for the logging & reset functions
45
+ * @param {Object} registry (Optional) Initialize the storage provider with an existing registry
46
+ */
47
+ constructor(e, t) {
48
+ if (new.target === h)
49
+ throw TypeError("StorageProvider is abstract. Extend this class to implement it");
50
+ this.namespace = e || null, this.registry = t || /* istanbul ignore next */
51
+ {};
52
+ }
53
+ /**
54
+ * Sets the namespace for this storage provider, and migrates
55
+ * all stored values to the new namespace
56
+ * @param {String} namespace New namespace for this storage provider
57
+ */
58
+ /* istanbul ignore next */
59
+ setNamespace(e) {
60
+ }
61
+ /**
62
+ * Registers an item with it's initial value. This is used for logging, resetting, etc.
63
+ * @param {String} key Storage item's key
64
+ * @param {*} initialValue Storage item's initial value
65
+ */
66
+ register(e, t) {
67
+ this.registry[e] = t;
68
+ }
69
+ /**
70
+ * Reads an item from storage
71
+ * @param {String} key Key for the item to retrieve
72
+ */
73
+ /* istanbul ignore next */
74
+ getItem(e) {
75
+ }
76
+ /**
77
+ * Stores a value
78
+ * @param {String} key Item's storage key
79
+ * @param {String} value Item's value to store
80
+ */
81
+ /* istanbul ignore next */
82
+ setItem(e, t) {
83
+ }
84
+ /**
85
+ * Removes an item from storage
86
+ * @param {String} key Item's storage key
87
+ * @param {Boolean} fromRegistry (Optional) If the item should also be removed from the registry
88
+ */
89
+ /* istanbul ignore next */
90
+ removeItem(e, t = !1) {
91
+ }
92
+ /**
93
+ * Gets all stored keys & values
94
+ * If a `namespace` was set, only keys prefixed with the namespace will be returned
95
+ */
96
+ /* istanbul ignore next */
97
+ getAll() {
98
+ }
99
+ /**
100
+ *
101
+ * @param {Boolean} useInitialValues If values should be replaced with their initial values. If false, keys are removed
102
+ * @param {String[]} excludedKeys (Optional) List of keys to exclude
103
+ * @param {Boolean} clearRegistry (Optional) If the registry should also be cleared
104
+ */
105
+ /* istanbul ignore next */
106
+ _resetAll(e = !0, t = [], r = !1) {
107
+ }
108
+ /**
109
+ * Resets all values to their initial values
110
+ * If a `namespace` is set, only keys prefixed with the namespace will be reset
111
+ * @param {String[]} excludedKeys (Optional) List of keys to exclude
112
+ */
113
+ /* istanbul ignore next */
114
+ resetAll(e = []) {
115
+ }
116
+ /**
117
+ * Removes all items from local storage.
118
+ * If a `namespace` is set, only keys prefixed with the namespace will be removed
119
+ * @param {String[]} excludedKeys (Optional) List of keys to exclude
120
+ */
121
+ /* istanbul ignore next */
122
+ removeAll(e = []) {
123
+ }
124
+ }
125
+ class v extends h {
126
+ constructor(e = null, t = {}) {
127
+ super(e, t), this.storage = this.getStorage();
128
+ }
129
+ getStorage() {
130
+ try {
131
+ return window.localStorage;
132
+ } catch {
133
+ return console.warn("LocalStorageProvider: localStorage not supported"), g;
134
+ }
135
+ }
136
+ setNamespace(e) {
137
+ if (!this.namespace) {
138
+ this.namespace = e;
139
+ return;
140
+ }
141
+ if (this.namespace === e)
142
+ return;
143
+ const t = JSON.parse(JSON.stringify(this.getAll()));
144
+ this.removeAll();
145
+ for (const [r, n] of Object.entries(t)) {
146
+ const o = r.replace(this.namespace, e);
147
+ this.setItem(o, n);
148
+ }
149
+ this.namespace = e;
150
+ }
151
+ getItem(e) {
152
+ const t = this.storage.getItem(e);
153
+ if (t == null)
154
+ return null;
155
+ try {
156
+ return JSON.parse(t);
157
+ } catch {
158
+ return t;
159
+ }
160
+ }
161
+ setItem(e, t) {
162
+ let r = t;
163
+ return r != null && (r = d(t) ? t : JSON.stringify(t)), this.storage.setItem(e, r);
164
+ }
165
+ removeItem(e, t = !1) {
166
+ return t && delete this.registry[e], this.storage.removeItem(e);
167
+ }
168
+ getAll() {
169
+ const e = `${this.namespace}.`;
170
+ return Object.keys(this.storage).reduce((t, r) => ((!this.namespace || r.startsWith(e)) && (t[r] = this.storage.getItem(r)), t), {});
171
+ }
172
+ _resetAll(e = !0, t = [], r = !1) {
173
+ const n = `${this.namespace}.`;
174
+ Object.keys(localStorage).forEach((o) => {
175
+ const l = this.namespace ? o.startsWith(n) : !0, a = (t == null ? void 0 : t.includes(o)) || !1;
176
+ !l || a || (e ? Object.prototype.hasOwnProperty.call(this.registry, o) ? this.storage.setItem(o, this.registry[o]) : this.storage.removeItem(o) : (this.storage.removeItem(o), r && delete this.registry[o]));
177
+ });
178
+ }
179
+ resetAll(e = [], t = !1) {
180
+ this._resetAll(!0, e || [], t);
181
+ }
182
+ removeAll(e = [], t = !1) {
183
+ this._resetAll(!1, e || [], t);
184
+ }
185
+ }
186
+ const A = {
187
+ logging: {
188
+ enabled: !1
189
+ }
190
+ };
191
+ let y = v, i = new y(), u = { ...A }, f = [];
192
+ const w = () => i.namespace, x = () => i, _ = () => u, K = (s) => {
193
+ i.setNamespace(s), i = new y(s || w());
194
+ }, V = (s) => {
195
+ if (u = {
196
+ ...u,
197
+ ...s
198
+ }, u.logging.enabled)
199
+ for (console.info("Flushing", f.length, "pending logs"); f.length; )
200
+ console.log(...f.shift());
201
+ }, N = (...s) => {
202
+ u.logging.enabled ? console.log(...s) : f.push(s);
203
+ }, E = (s, e = null) => {
204
+ if (!s && typeof s != "number")
205
+ throw new Error(
206
+ `createPersistedWire: Key cannot be a falsey value (${s}}`
207
+ );
208
+ i.register(s, e);
209
+ const t = b(e), r = () => t.getValue(), n = (c) => (i.setItem(s, c), t.setValue(c)), o = (c) => {
210
+ t.subscribe(c);
211
+ }, l = i.getItem(s), a = l === null ? e : l;
212
+ return N("react-wire-persisted: create", s, {
213
+ value: e,
214
+ storedValue: l,
215
+ initialValue: a
216
+ }), a !== e && n(a), {
217
+ ...t,
218
+ getValue: r,
219
+ setValue: n,
220
+ subscribe: o
221
+ };
222
+ };
223
+ export {
224
+ E as createPersistedWire,
225
+ A as defaultOptions,
226
+ w as getNamespace,
227
+ _ as getOptions,
228
+ x as getStorage,
229
+ K as setNamespace,
230
+ V as setOptions,
231
+ P as utils
232
+ };
@@ -0,0 +1 @@
1
+ (function(n,a){typeof exports=="object"&&typeof module<"u"?a(exports,require("@forminator/react-wire")):typeof define=="function"&&define.amd?define(["exports","@forminator/react-wire"],a):(n=typeof globalThis<"u"?globalThis:n||self,a(n["react-wire-persisted"]={},n.reactWire))})(this,function(n,a){"use strict";(function(){const s={};try{if(process){process.env=Object.assign({},process.env),Object.assign(process.env,s);return}}catch{}globalThis.process={env:s}})();const p={},y=s=>{p[s]=s},v=s=>y(s),w=()=>p,A=(s,e=null)=>{const t=e||p;return s?Object.keys(t).reduce((r,o)=>({...r,[o]:`${s}.${t[o]}`}),{}):t},c={getItem:s=>c[s],setItem:(s,e)=>{c[s]=e},removeItem:s=>{delete c[s]}},b=s=>{const e=typeof s;return s===null?!0:Array.isArray(s)||e==="object"?!1:e!=="function"},N=Object.freeze(Object.defineProperty({__proto__:null,addKey:y,fakeLocalStorage:c,getKeys:w,getPrefixedKeys:A,isPrimitive:b,key:v},Symbol.toStringTag,{value:"Module"}));class d{constructor(e,t){if(new.target===d)throw TypeError("StorageProvider is abstract. Extend this class to implement it");this.namespace=e||null,this.registry=t||{}}setNamespace(e){}register(e,t){this.registry[e]=t}getItem(e){}setItem(e,t){}removeItem(e,t=!1){}getAll(){}_resetAll(e=!0,t=[],r=!1){}resetAll(e=[]){}removeAll(e=[]){}}class j extends d{constructor(e=null,t={}){super(e,t),this.storage=this.getStorage()}getStorage(){try{return window.localStorage}catch{return console.warn("LocalStorageProvider: localStorage not supported"),c}}setNamespace(e){if(!this.namespace){this.namespace=e;return}if(this.namespace===e)return;const t=JSON.parse(JSON.stringify(this.getAll()));this.removeAll();for(const[r,o]of Object.entries(t)){const i=r.replace(this.namespace,e);this.setItem(i,o)}this.namespace=e}getItem(e){const t=this.storage.getItem(e);if(t==null)return null;try{return JSON.parse(t)}catch{return t}}setItem(e,t){let r=t;return r!=null&&(r=b(t)?t:JSON.stringify(t)),this.storage.setItem(e,r)}removeItem(e,t=!1){return t&&delete this.registry[e],this.storage.removeItem(e)}getAll(){const e=`${this.namespace}.`;return Object.keys(this.storage).reduce((t,r)=>((!this.namespace||r.startsWith(e))&&(t[r]=this.storage.getItem(r)),t),{})}_resetAll(e=!0,t=[],r=!1){const o=`${this.namespace}.`;Object.keys(localStorage).forEach(i=>{const u=this.namespace?i.startsWith(o):!0,f=(t==null?void 0:t.includes(i))||!1;!u||f||(e?Object.prototype.hasOwnProperty.call(this.registry,i)?this.storage.setItem(i,this.registry[i]):this.storage.removeItem(i):(this.storage.removeItem(i),r&&delete this.registry[i]))})}resetAll(e=[],t=!1){this._resetAll(!0,e||[],t)}removeAll(e=[],t=!1){this._resetAll(!1,e||[],t)}}const O={logging:{enabled:!1}};let I=j,l=new I,g={...O},h=[];const S=()=>l.namespace,P=()=>l,W=()=>g,_=s=>{l.setNamespace(s),l=new I(s||S())},K=s=>{if(g={...g,...s},g.logging.enabled)for(console.info("Flushing",h.length,"pending logs");h.length;)console.log(...h.shift())},T=(...s)=>{g.logging.enabled?console.log(...s):h.push(s)},V=(s,e=null)=>{if(!s&&typeof s!="number")throw new Error(`createPersistedWire: Key cannot be a falsey value (${s}}`);l.register(s,e);const t=a.createWire(e),r=()=>t.getValue(),o=m=>(l.setItem(s,m),t.setValue(m)),i=m=>{t.subscribe(m)},u=l.getItem(s),f=u===null?e:u;return T("react-wire-persisted: create",s,{value:e,storedValue:u,initialValue:f}),f!==e&&o(f),{...t,getValue:r,setValue:o,subscribe:i}};n.createPersistedWire=V,n.defaultOptions=O,n.getNamespace=S,n.getOptions=W,n.getStorage=P,n.setNamespace=_,n.setOptions=K,n.utils=N,Object.defineProperty(n,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,52 +1,49 @@
1
1
  {
2
2
  "name": "react-wire-persisted",
3
- "version": "1.0.6",
3
+ "version": "1.3.0",
4
4
  "author": "Wesley Bliss <wesley.bliss@gmail.com>",
5
5
  "license": "MIT",
6
- "main": "lib/react-wire-persisted.js",
6
+ "main": "./dist/react-wire-persisted.umd.cjs",
7
+ "module": "./dist/react-wire-persisted.mjs",
7
8
  "files": [
8
- "lib"
9
+ "src",
10
+ "dist"
9
11
  ],
12
+ "exports": {
13
+ ".": {
14
+ "import": "./dist/react-wire-persisted.mjs",
15
+ "require": "./dist/react-wire-persisted.umd.cjs"
16
+ }
17
+ },
10
18
  "scripts": {
11
- "dev": "NODE_ENV=development webpack serve --config config/webpack.config.js --progress",
12
- "build": "NODE_ENV=production webpack --config config/webpack.config.js --progress",
13
- "test": "jest",
14
- "test:watch": "jest --watch",
15
- "test:watch:all": "jest --watchAll",
16
- "test:watch:coverage": "jest --watch --collectCoverage",
17
- "test:snapshots": "jest --updateSnapshot",
18
- "test:coverage": "jest --collectCoverage",
19
- "test:ci": "jest --runInBand"
19
+ "dev": "vite --host --config config/vite.config.development.js",
20
+ "build": "vite build --config config/vite.config.production.js",
21
+ "test:unit": "NODE_ENV=test vitest run --threads=false",
22
+ "test:unit:only": "NODE_ENV=test vitest run --threads=false -t ",
23
+ "test:unit:coverage": "NODE_ENV=test vitest run --threads=false --no-color --reporter=junit --coverage --outputFile=coverage/report.xml"
20
24
  },
21
25
  "dependencies": {},
22
26
  "devDependencies": {
23
- "@babel/core": "^7.17.5",
24
- "@babel/plugin-transform-runtime": "^7.17.0",
25
- "@babel/preset-env": "^7.16.11",
26
- "@babel/preset-react": "^7.16.7",
27
- "@forminator/react-wire": "^0.5.0-alpha.1",
28
- "@pmmmwh/react-refresh-webpack-plugin": "^0.5.4",
29
- "@testing-library/jest-dom": "^5.16.2",
30
- "@testing-library/react": "^12.1.3",
31
- "babel-jest": "^27.5.1",
32
- "babel-loader": "^8.2.3",
33
- "browserslist": "^4.19.3",
34
- "clean-webpack-plugin": "^4.0.0",
35
- "css-loader": "^6.6.0",
36
- "dotenv-webpack": "^7.1.0",
37
- "esbuild": "^0.14.23",
38
- "html-webpack-plugin": "^5.5.0",
39
- "interpolate-html-plugin": "^4.0.0",
40
- "jest": "^27.5.1",
41
- "react": "^17.0.2",
42
- "react-dom": "^17.0.2",
43
- "snapshot-diff": "^0.9.0",
44
- "style-loader": "^3.3.1",
45
- "webpack": "^5.69.1",
46
- "webpack-bundle-analyzer": "^4.5.0",
47
- "webpack-cli": "^4.9.2",
48
- "webpack-dev-server": "^4.7.4",
49
- "webpack-node-externals": "^3.0.0"
27
+ "@forminator/react-wire": "^0.6.0",
28
+ "@testing-library/jest-dom": "^5.16.5",
29
+ "@testing-library/react": "^14.0.0",
30
+ "@testing-library/user-event": "^14.4.3",
31
+ "@vitejs/plugin-react": "^3.1.0",
32
+ "@vitest/coverage-c8": "^0.28.5",
33
+ "browserslist": "^4.21.5",
34
+ "c8": "^7.13.0",
35
+ "dotenv": "^16.0.3",
36
+ "esbuild": "^0.17.10",
37
+ "jest": "^29.4.3",
38
+ "jest-environment-jsdom": "^29.4.3",
39
+ "np": "^7.6.3",
40
+ "react": "^18.2.0",
41
+ "react-dom": "^18.2.0",
42
+ "rollup-plugin-inject-process-env": "^1.3.1",
43
+ "snapshot-diff": "^0.10.0",
44
+ "vite": "^4.1.4",
45
+ "vite-jest": "^0.1.4",
46
+ "vitest": "^0.28.5"
50
47
  },
51
48
  "peerDependencies": {
52
49
  "@forminator/react-wire": "^0.5.0-alpha.1",
package/src/index.js ADDED
@@ -0,0 +1,4 @@
1
+ import * as utils from './utils'
2
+
3
+ export { utils }
4
+ export * from './react-wire-persisted'
@@ -0,0 +1,152 @@
1
+ import StorageProvider from './StorageProvider'
2
+ import { fakeLocalStorage, isPrimitive } from '../utils'
3
+
4
+ /**
5
+ * A storage provider for `localStorage`
6
+ * @see `StorageProvider.js` for documentation
7
+ */
8
+ class LocalStorageProvider extends StorageProvider {
9
+
10
+ constructor(namespace = null, registry = {}) {
11
+
12
+ super(namespace, registry)
13
+
14
+ this.storage = this.getStorage()
15
+
16
+ }
17
+
18
+ getStorage() {
19
+
20
+ try {
21
+ return window.localStorage
22
+ } catch (e) {
23
+ /* istanbul ignore next */
24
+ console.warn('LocalStorageProvider: localStorage not supported')
25
+ /* istanbul ignore next */
26
+ return fakeLocalStorage
27
+ }
28
+
29
+ }
30
+
31
+ setNamespace(namespace) {
32
+
33
+ if (!this.namespace) {
34
+ this.namespace = namespace
35
+ return
36
+ }
37
+
38
+ if (this.namespace === namespace)
39
+ return
40
+
41
+ const items = JSON.parse(JSON.stringify(this.getAll()))
42
+
43
+ this.removeAll()
44
+
45
+ for (const [key, value] of Object.entries(items)) {
46
+ const newKey = key.replace(this.namespace, namespace)
47
+ this.setItem(newKey, value)
48
+ }
49
+
50
+ this.namespace = namespace
51
+
52
+ }
53
+
54
+ getItem(key) {
55
+
56
+ const val = this.storage.getItem(key)
57
+
58
+ if (val === undefined || val === null)
59
+ return null
60
+
61
+ try {
62
+ return JSON.parse(val)
63
+ } catch (e) {
64
+ return val
65
+ }
66
+
67
+ }
68
+
69
+ setItem(key, value) {
70
+
71
+ let val = value
72
+
73
+ // Don't allow "null" & similar values to be stringified
74
+ if (val !== undefined && val !== null)
75
+ val = isPrimitive(value) ? value : JSON.stringify(value)
76
+
77
+ return this.storage.setItem(key, val)
78
+
79
+ }
80
+
81
+ removeItem(key, fromRegistry = false) {
82
+
83
+ if (fromRegistry)
84
+ delete this.registry[key]
85
+
86
+ return this.storage.removeItem(key)
87
+
88
+ }
89
+
90
+ getAll() {
91
+
92
+ const prefixNs = `${this.namespace}.`
93
+
94
+ return Object.keys(this.storage).reduce((acc, it) => {
95
+
96
+ if (this.namespace ? it.startsWith(prefixNs) : true)
97
+ acc[it] = this.storage.getItem(it)
98
+
99
+ return acc
100
+
101
+ }, {})
102
+
103
+ }
104
+
105
+ _resetAll(
106
+ useInitialValues = true,
107
+ excludedKeys = [],
108
+ clearRegistry = false
109
+ ) {
110
+
111
+ const prefixNs = `${this.namespace}.`
112
+
113
+ Object.keys(localStorage).forEach(it => {
114
+
115
+ const isAppKey = this.namespace ? it.startsWith(prefixNs) : true
116
+ const isExcluded = excludedKeys?.includes(it) || false
117
+
118
+ if (!isAppKey || isExcluded) return
119
+
120
+ if (useInitialValues) {
121
+
122
+ const isRegistered = Object.prototype.hasOwnProperty.call(this.registry, it)
123
+
124
+ if (isRegistered)
125
+ this.storage.setItem(it, this.registry[it])
126
+ else
127
+ this.storage.removeItem(it)
128
+
129
+ } else {
130
+
131
+ this.storage.removeItem(it)
132
+
133
+ if (clearRegistry)
134
+ delete this.registry[it]
135
+
136
+ }
137
+
138
+ })
139
+
140
+ }
141
+
142
+ resetAll(excludedKeys = [], clearRegistry = false) {
143
+ this._resetAll(true, excludedKeys || [], clearRegistry)
144
+ }
145
+
146
+ removeAll(excludedKeys = [], clearRegistry = false) {
147
+ this._resetAll(false, excludedKeys || [], clearRegistry)
148
+ }
149
+
150
+ }
151
+
152
+ export default LocalStorageProvider
@@ -0,0 +1,20 @@
1
+ import LocalStorageProvider from './LocalStorageProvider'
2
+ import { fakeLocalStorage } from '../utils'
3
+
4
+ class MemoryStorageProvider extends LocalStorageProvider {
5
+
6
+ constructor(namespace = null, registry = {}) {
7
+
8
+ super(namespace, registry)
9
+
10
+ }
11
+
12
+ getStorage() {
13
+
14
+ return fakeLocalStorage
15
+
16
+ }
17
+
18
+ }
19
+
20
+ export default MemoryStorageProvider
@@ -0,0 +1,102 @@
1
+
2
+ /**
3
+ * Base class to allow storage access
4
+ * @see `LocalStorageProvider.js` for an example implementation
5
+ */
6
+ class StorageProvider {
7
+
8
+ /**
9
+ * Initializes the class
10
+ * @param {String} namespace Namespace to prefix all keys with. Mostly used for the logging & reset functions
11
+ * @param {Object} registry (Optional) Initialize the storage provider with an existing registry
12
+ */
13
+ constructor(namespace, registry) {
14
+
15
+ // Simulate being an abstract class
16
+ if (new.target === StorageProvider)
17
+ throw TypeError(`StorageProvider is abstract. Extend this class to implement it`)
18
+
19
+ this.namespace = namespace || null
20
+ this.registry = registry || /* istanbul ignore next */ {}
21
+
22
+ }
23
+
24
+ /**
25
+ * Sets the namespace for this storage provider, and migrates
26
+ * all stored values to the new namespace
27
+ * @param {String} namespace New namespace for this storage provider
28
+ */
29
+ /* istanbul ignore next */
30
+ setNamespace(namespace) {}
31
+
32
+ /**
33
+ * Registers an item with it's initial value. This is used for logging, resetting, etc.
34
+ * @param {String} key Storage item's key
35
+ * @param {*} initialValue Storage item's initial value
36
+ */
37
+ register(key, initialValue) {
38
+ this.registry[key] = initialValue
39
+ }
40
+
41
+ /**
42
+ * Reads an item from storage
43
+ * @param {String} key Key for the item to retrieve
44
+ */
45
+ /* istanbul ignore next */
46
+ getItem(key) {}
47
+
48
+ /**
49
+ * Stores a value
50
+ * @param {String} key Item's storage key
51
+ * @param {String} value Item's value to store
52
+ */
53
+ /* istanbul ignore next */
54
+ setItem(key, value) {}
55
+
56
+ /**
57
+ * Removes an item from storage
58
+ * @param {String} key Item's storage key
59
+ * @param {Boolean} fromRegistry (Optional) If the item should also be removed from the registry
60
+ */
61
+ /* istanbul ignore next */
62
+ removeItem(key, fromRegistry = false) {}
63
+
64
+ /**
65
+ * Gets all stored keys & values
66
+ * If a `namespace` was set, only keys prefixed with the namespace will be returned
67
+ */
68
+ /* istanbul ignore next */
69
+ getAll() {}
70
+
71
+ /**
72
+ *
73
+ * @param {Boolean} useInitialValues If values should be replaced with their initial values. If false, keys are removed
74
+ * @param {String[]} excludedKeys (Optional) List of keys to exclude
75
+ * @param {Boolean} clearRegistry (Optional) If the registry should also be cleared
76
+ */
77
+ /* istanbul ignore next */
78
+ _resetAll(
79
+ useInitialValues = true,
80
+ excludedKeys = [],
81
+ clearRegistry = false
82
+ ) {}
83
+
84
+ /**
85
+ * Resets all values to their initial values
86
+ * If a `namespace` is set, only keys prefixed with the namespace will be reset
87
+ * @param {String[]} excludedKeys (Optional) List of keys to exclude
88
+ */
89
+ /* istanbul ignore next */
90
+ resetAll(excludedKeys = []) {}
91
+
92
+ /**
93
+ * Removes all items from local storage.
94
+ * If a `namespace` is set, only keys prefixed with the namespace will be removed
95
+ * @param {String[]} excludedKeys (Optional) List of keys to exclude
96
+ */
97
+ /* istanbul ignore next */
98
+ removeAll(excludedKeys = []) {}
99
+
100
+ }
101
+
102
+ export default StorageProvider
@@ -0,0 +1,115 @@
1
+ import { createWire } from '@forminator/react-wire'
2
+ import LocalStorageProvider from './providers/LocalStorageProvider'
3
+
4
+ export const defaultOptions = {
5
+ logging: {
6
+ enabled: false,
7
+ },
8
+ }
9
+
10
+ let Provider = LocalStorageProvider
11
+ let storage = new Provider()
12
+ let options = { ...defaultOptions }
13
+ let pendingLogs = []
14
+
15
+ /**
16
+ * Gets the namespace of the storage provider
17
+ *
18
+ * @returns {String}
19
+ */
20
+ export const getNamespace = () => storage.namespace
21
+
22
+ /**
23
+ * Gets the current storage provider class instance
24
+ *
25
+ * @returns {StorageProvider}
26
+ */
27
+ export const getStorage = () => storage
28
+
29
+ export const getOptions = () => options
30
+
31
+ /**
32
+ * Sets the namespace for the storage provider
33
+ *
34
+ * @param {String} namespace The namespace for the storage provider
35
+ */
36
+ export const setNamespace = namespace => {
37
+ storage.setNamespace(namespace)
38
+ storage = new Provider(namespace || getNamespace())
39
+ }
40
+
41
+ export const setOptions = value => {
42
+ options = {
43
+ ...options,
44
+ ...value,
45
+ }
46
+ /* istanbul ignore next */
47
+ if (options.logging.enabled) {
48
+ console.info('Flushing', pendingLogs.length, 'pending logs')
49
+ while (pendingLogs.length)
50
+ /* istanbul ignore next */
51
+ console.log(...pendingLogs.shift())
52
+ }
53
+ }
54
+
55
+ const log = (...args) => {
56
+ /* istanbul ignore next */
57
+ if (options.logging.enabled)
58
+ /* istanbul ignore next */
59
+ console.log(...args)
60
+ else
61
+ pendingLogs.push(args)
62
+ }
63
+
64
+ /**
65
+ * Creates a persisted Wire using the `StorageProvider` that is currently set
66
+ * Defaults to `localStorage` via `LocalStorageProvider`
67
+ *
68
+ * @param {String} key Unique key for storing this value
69
+ * @param {*} value Initial value of this Wire
70
+ * @returns A new Wire decorated with localStorage functionality
71
+ */
72
+ export const createPersistedWire = (key, value = null) => {
73
+
74
+ // This check helps ensure no accidental key typos occur
75
+ if (!key && (typeof key) !== 'number') throw new Error(
76
+ `createPersistedWire: Key cannot be a falsey value (${key}}`
77
+ )
78
+
79
+ // Track this writable entry so we can easily clear all
80
+ storage.register(key, value)
81
+
82
+ // The actual Wire backing object
83
+ const wire = createWire(value)
84
+
85
+ const getValue = () => wire.getValue()
86
+
87
+ const setValue = newValue => {
88
+ storage.setItem(key, newValue)
89
+ return wire.setValue(newValue)
90
+ }
91
+
92
+ const subscribe = fn => {
93
+ wire.subscribe(fn)
94
+ }
95
+
96
+ const storedValue = storage.getItem(key)
97
+ const initialValue = storedValue === null ? value : storedValue
98
+
99
+ log('react-wire-persisted: create', key, {
100
+ value,
101
+ storedValue,
102
+ initialValue,
103
+ })
104
+
105
+ if (initialValue !== value)
106
+ setValue(initialValue)
107
+
108
+ return {
109
+ ...wire,
110
+ getValue,
111
+ setValue,
112
+ subscribe,
113
+ }
114
+
115
+ }
@@ -0,0 +1,14 @@
1
+
2
+ const storage = {
3
+ __IS_FAKE_LOCAL_STORAGE__: true,
4
+ }
5
+
6
+ export const fakeLocalStorage = {
7
+ getItem: key => fakeLocalStorage[key],
8
+ setItem: (key, value) => {
9
+ fakeLocalStorage[key] = value
10
+ },
11
+ removeItem: key => {
12
+ delete fakeLocalStorage[key]
13
+ }
14
+ }
@@ -0,0 +1,20 @@
1
+ export * from './keys'
2
+ export * from './fakeLocalStorage'
3
+
4
+ /**
5
+ * Checks if a value is a primitive type
6
+ *
7
+ * @param {*} val Value to check
8
+ * @returns {Boolean} True if value is a primitive type
9
+ */
10
+ export const isPrimitive = val => {
11
+
12
+ const type = typeof val
13
+
14
+ if (val === null) return true
15
+ if (Array.isArray(val)) return false
16
+ if (type === 'object') return false
17
+
18
+ return type !== 'function'
19
+
20
+ }
@@ -0,0 +1,49 @@
1
+
2
+ /**
3
+ * Convenience map of keys
4
+ */
5
+ const storageKeys = {}
6
+
7
+ /**
8
+ * Adds a key to the keys map
9
+ *
10
+ * @param {String} value Key name
11
+ */
12
+ export const addKey = value => {
13
+ storageKeys[value] = value
14
+ }
15
+
16
+ /**
17
+ * Adds a key to the keys map
18
+ * (Alias for `addKey`)
19
+ *
20
+ * @param {String} value Key name
21
+ */
22
+ export const key = value => addKey(value)
23
+
24
+ /**
25
+ * Convenience method to get internally managed storage keys
26
+ *
27
+ * @returns {Object} Storage keys map
28
+ */
29
+ export const getKeys = () => storageKeys
30
+
31
+ /**
32
+ * Helper utility to prefix all keys in a map to use a namespace
33
+ *
34
+ * @param {String} namespace Storage namespace prefix
35
+ * @param {Object} keys (Optional) Storage key/values. Defaults to the internally managed keys map
36
+ */
37
+ export const getPrefixedKeys = (namespace, keys = null) => {
38
+
39
+ const items = keys || storageKeys
40
+
41
+ if (!namespace)
42
+ return items
43
+
44
+ return Object.keys(items).reduce((acc, it) => ({
45
+ ...acc,
46
+ [it]: `${namespace}.${items[it]}`,
47
+ }), {})
48
+
49
+ }
@@ -1 +0,0 @@
1
- !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var r=t();for(var n in r)("object"==typeof exports?exports:e)[n]=r[n]}}(this,(function(){return(()=>{"use strict";var e={253:(e,t,r)=>{r.r(t),r.d(t,{addKey:()=>l,fakeLocalStorage:()=>g,getKeys:()=>p,getPrefixedKeys:()=>v,isPrimitive:()=>y,key:()=>f});const n=require("@babel/runtime/helpers/typeof");var o=r.n(n),i=r(779),a=r.n(i);function s(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function c(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?s(Object(r),!0).forEach((function(t){a()(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):s(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}var u={},l=function(e){u[e]=e},f=function(e){return l(e)},p=function(){return u},v=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,r=t||u;return e?Object.keys(r).reduce((function(t,n){return c(c({},t),{},a()({},n,"".concat(e,".").concat(r[n])))}),{}):r},g={__IS_FAKE_LOCAL_STORAGE__:!0,getItem:function(e){return g[e]},setItem:function(e,t){g[e]=t},removeItem:function(e){delete g[e]}},y=function(e){var t=o()(e);return null===e||!Array.isArray(e)&&("object"!==t&&"function"!==t)}},779:e=>{e.exports=require("@babel/runtime/helpers/defineProperty")}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var i=t[n]={exports:{}};return e[n](i,i.exports,r),i.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};return(()=>{r.r(n),r.d(n,{createPersistedWire:()=>C,defaultOptions:()=>w,getNamespace:()=>x,getOptions:()=>E,getStorage:()=>q,setNamespace:()=>N,setOptions:()=>D,utils:()=>e});var e=r(253);const t=require("@babel/runtime/helpers/toConsumableArray");var o=r.n(t),i=r(779),a=r.n(i);const s=require("@forminator/react-wire"),c=require("@babel/runtime/helpers/slicedToArray");var u=r.n(c);const l=require("@babel/runtime/helpers/classCallCheck");var f=r.n(l);const p=require("@babel/runtime/helpers/createClass");var v=r.n(p);const g=require("@babel/runtime/helpers/inherits");var y=r.n(g);const h=require("@babel/runtime/helpers/possibleConstructorReturn");var m=r.n(h);const b=require("@babel/runtime/helpers/getPrototypeOf");var d=r.n(b);function O(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var r,n=d()(e);if(t){var o=d()(this).constructor;r=Reflect.construct(n,arguments,o)}else r=n.apply(this,arguments);return m()(this,r)}}var j=function(t){y()(n,t);var r=O(n);function n(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return f()(this,n),(e=r.call(this,t,o)).storage=e.getStorage(),e}return v()(n,[{key:"getStorage",value:function(){try{return window.localStorage}catch(t){return console.warn("LocalStorageProvider: localStorage not supported"),e.fakeLocalStorage}}},{key:"setNamespace",value:function(e){if(this.namespace){if(this.namespace!==e){var t=JSON.parse(JSON.stringify(this.getAll()));this.removeAll();for(var r=0,n=Object.entries(t);r<n.length;r++){var o=u()(n[r],2),i=o[0],a=o[1],s=i.replace(this.namespace,e);this.setItem(s,a)}this.namespace=e}}else this.namespace=e}},{key:"getItem",value:function(e){var t=this.storage.getItem(e);if(null==t)return null;try{return JSON.parse(t)}catch(e){return t}}},{key:"setItem",value:function(t,r){var n=r;return null!=n&&(n=(0,e.isPrimitive)(r)?r:JSON.stringify(r)),this.storage.setItem(t,n)}},{key:"removeItem",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return t&&delete this.registry[e],this.storage.removeItem(e)}},{key:"getAll",value:function(){var e=this,t="".concat(this.namespace,".");return Object.keys(this.storage).reduce((function(r,n){return e.namespace&&!n.startsWith(t)||(r[n]=e.storage.getItem(n)),r}),{})}},{key:"_resetAll",value:function(){var e=this,t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],o="".concat(this.namespace,".");Object.keys(localStorage).forEach((function(i){var a=!e.namespace||i.startsWith(o),s=(null==r?void 0:r.includes(i))||!1;a&&!s&&(t?Object.prototype.hasOwnProperty.call(e.registry,i)?e.storage.setItem(i,e.registry[i]):e.storage.removeItem(i):(e.storage.removeItem(i),n&&delete e.registry[i]))}))}},{key:"resetAll",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._resetAll(!0,e||[],t)}},{key:"removeAll",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._resetAll(!1,e||[],t)}}]),n}(function(){function e(t,r){if(f()(this,e),(this instanceof e?this.constructor:void 0)===e)throw TypeError("StorageProvider is abstract. Extend this class to implement it");this.namespace=t||null,this.registry=r||{}}return v()(e,[{key:"setNamespace",value:function(e){}},{key:"register",value:function(e,t){this.registry[e]=t}},{key:"getItem",value:function(e){}},{key:"setItem",value:function(e,t){}},{key:"removeItem",value:function(e){}},{key:"getAll",value:function(){}},{key:"_resetAll",value:function(){}},{key:"resetAll",value:function(){}},{key:"removeAll",value:function(){}}]),e}());function P(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function k(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?P(Object(r),!0).forEach((function(t){a()(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):P(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}var w={logging:!1},S=j,A=new S,I=k({},w),_=[],x=function(){return A.namespace},q=function(){return A},E=function(){return I},N=function(e){A.setNamespace(e),A=new S(e||x())},D=function(e){if((I=k(k({},I),e)).logging)for(console.info("Flushing",_.length,"pending logs");_.length;){var t;(t=console).log.apply(t,o()(_.shift()))}},R=function(){for(var e,t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];I.logging.enabled?(e=console).log.apply(e,r):_.push(r)},C=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;if(!e&&"number"!=typeof e)throw new Error("createPersistedWire: Key cannot be a falsey value (".concat(e,"}"));A.register(e,t);var r=(0,s.createWire)(t),n=function(){return r.getValue()},o=function(t){return A.setItem(e,t),r.setValue(t)},i=function(e){r.subscribe(e)},a=A.getItem(e),c=null===a?t:a;return R("react-wire-persisted: create",e,{value:t,storedValue:a,initialValue:c}),c!==t&&o(c),k(k({},r),{},{getValue:n,setValue:o,subscribe:i})}})(),n})()}));
@@ -1 +0,0 @@
1
- !function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var r=t();for(var n in r)("object"==typeof exports?exports:e)[n]=r[n]}}(this,(function(){return(()=>{"use strict";var e={779:e=>{e.exports=require("@babel/runtime/helpers/defineProperty")}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var i=t[n]={exports:{}};return e[n](i,i.exports,r),i.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};return(()=>{r.r(n),r.d(n,{addKey:()=>a,fakeLocalStorage:()=>y,getKeys:()=>s,getPrefixedKeys:()=>l,isPrimitive:()=>b,key:()=>p});const e=require("@babel/runtime/helpers/typeof");var t=r.n(e),o=r(779),i=r.n(o);function c(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function u(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?c(Object(r),!0).forEach((function(t){i()(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):c(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}var f={},a=function(e){f[e]=e},p=function(e){return a(e)},s=function(){return f},l=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,r=t||f;return e?Object.keys(r).reduce((function(t,n){return u(u({},t),{},i()({},n,"".concat(e,".").concat(r[n])))}),{}):r},y={__IS_FAKE_LOCAL_STORAGE__:!0,getItem:function(e){return y[e]},setItem:function(e,t){y[e]=t},removeItem:function(e){delete y[e]}},b=function(e){var r=t()(e);return null===e||!Array.isArray(e)&&("object"!==r&&"function"!==r)}})(),n})()}));