UNPKG

gm-storage

Version:

An ES6 Map wrapper for the synchronous userscript storage API

3 lines (2 loc) 2.15 kB
/* gm-storage 4.1.1. @copyright 2020 chocolateboy. @license MIT */ var e,t;e=this,t=function(e){"use strict";const t=["GM_deleteValue","GM_getValue","GM_listValues","GM_setValue"],s=Symbol(),r={strict:!0};class GMStorageBase{constructor(e=r){if(e.strict)for(const e of t){const t=globalThis[e];if(!t)throw new ReferenceError(`${e} is not defined`);if("function"!=typeof t)throw new TypeError(`${e} is not a function`)}}_has(e){return GM_getValue(e,s)!==s}clear(){const e=GM_listValues();for(let t=0;t<e.length;++t)GM_deleteValue(e[t])}delete(e){const t=this.stringify(e);return this._has(t)&&(GM_deleteValue(t),!0)}*entries(){const e=GM_listValues();for(let t=0;t<e.length;++t){const s=e[t];yield[this.parse(s),GM_getValue(s)]}}forEach(e,t=void 0){for(const[s,r]of this.entries())e.call(t,r,s,this)}get(e,t=void 0){return GM_getValue(this.stringify(e),t)}has(e){return this._has(this.stringify(e))}*keys(){const e=GM_listValues();for(let t=0;t<e.length;++t)yield this.parse(e[t])}set(e,t){return GM_setValue(this.stringify(e),t),this}setAll(e=[]){for(const[t,s]of e)this.set(t,s);return this}get size(){return GM_listValues().length}*values(){const e=GM_listValues();for(let t=0;t<e.length;++t)yield GM_getValue(e[t])}}Object.assign(GMStorageBase.prototype,{[Symbol.iterator]:GMStorageBase.prototype.entries});const o=e=>e;class GMStorage extends GMStorageBase{parse=o;stringify=o}const i={...r,canonical:!0},n={}.toString,l=(e,t)=>{if((e=>"[object Object]"===n.call(e)&&(e.constructor||Object)===Object)(t)){const e=Object.keys(t).sort(),s={};for(let r=0;r<e.length;++r){const o=e[r];s[o]=t[o]}return s}return t},{parse:a}=JSON,c=e=>JSON.stringify(e,l);class JSONKeyStore extends GMStorageBase{stringify;constructor(e=i){super(e),this.stringify=e.canonical?c:JSON.stringify}parse=a}e.GMStorage=GMStorage,e.GMStore=GMStorage,e.JSONKeyStorage=JSONKeyStore,e.JSONKeyStore=JSONKeyStore,e.default=GMStorage,Object.defineProperty(e,"__esModule",{value:!0})},"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).GMStorage={});