@flatfile/util-kv-store
Version:
A utility for storing data in a persistent key-value store.
2 lines (1 loc) • 12.8 kB
JavaScript
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).UtilKVStore={})}(this,(function(t){"use strict";var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function r(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var o={exports:{}};!function(t,r){var o="undefined"!=typeof globalThis&&globalThis||"undefined"!=typeof self&&self||void 0!==e&&e,n=function(){function t(){this.fetch=!1,this.DOMException=o.DOMException}return t.prototype=o,new t}();!function(t){!function(e){var r=void 0!==t&&t||"undefined"!=typeof self&&self||void 0!==r&&r,o="URLSearchParams"in r,n="Symbol"in r&&"iterator"in Symbol,i="FileReader"in r&&"Blob"in r&&function(){try{return new Blob,!0}catch(t){return!1}}(),s="FormData"in r,a="ArrayBuffer"in r;if(a)var f=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],u=ArrayBuffer.isView||function(t){return t&&f.indexOf(Object.prototype.toString.call(t))>-1};function c(t){if("string"!=typeof t&&(t=String(t)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(t)||""===t)throw new TypeError('Invalid character in header field name: "'+t+'"');return t.toLowerCase()}function h(t){return"string"!=typeof t&&(t=String(t)),t}function l(t){var e={next:function(){var e=t.shift();return{done:void 0===e,value:e}}};return n&&(e[Symbol.iterator]=function(){return e}),e}function d(t){this.map={},t instanceof d?t.forEach((function(t,e){this.append(e,t)}),this):Array.isArray(t)?t.forEach((function(t){this.append(t[0],t[1])}),this):t&&Object.getOwnPropertyNames(t).forEach((function(e){this.append(e,t[e])}),this)}function y(t){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}function p(t){return new Promise((function(e,r){t.onload=function(){e(t.result)},t.onerror=function(){r(t.error)}}))}function b(t){var e=new FileReader,r=p(e);return e.readAsArrayBuffer(t),r}function w(t){if(t.slice)return t.slice(0);var e=new Uint8Array(t.byteLength);return e.set(new Uint8Array(t)),e.buffer}function E(){return this.bodyUsed=!1,this._initBody=function(t){var e;this.bodyUsed=this.bodyUsed,this._bodyInit=t,t?"string"==typeof t?this._bodyText=t:i&&Blob.prototype.isPrototypeOf(t)?this._bodyBlob=t:s&&FormData.prototype.isPrototypeOf(t)?this._bodyFormData=t:o&&URLSearchParams.prototype.isPrototypeOf(t)?this._bodyText=t.toString():a&&i&&((e=t)&&DataView.prototype.isPrototypeOf(e))?(this._bodyArrayBuffer=w(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):a&&(ArrayBuffer.prototype.isPrototypeOf(t)||u(t))?this._bodyArrayBuffer=w(t):this._bodyText=t=Object.prototype.toString.call(t):this._bodyText="",this.headers.get("content-type")||("string"==typeof t?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):o&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},i&&(this.blob=function(){var t=y(this);if(t)return t;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){if(this._bodyArrayBuffer){var t=y(this);return t||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}return this.blob().then(b)}),this.text=function(){var t,e,r,o=y(this);if(o)return o;if(this._bodyBlob)return t=this._bodyBlob,e=new FileReader,r=p(e),e.readAsText(t),r;if(this._bodyArrayBuffer)return Promise.resolve(function(t){for(var e=new Uint8Array(t),r=new Array(e.length),o=0;o<e.length;o++)r[o]=String.fromCharCode(e[o]);return r.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},s&&(this.formData=function(){return this.text().then(v)}),this.json=function(){return this.text().then(JSON.parse)},this}d.prototype.append=function(t,e){t=c(t),e=h(e);var r=this.map[t];this.map[t]=r?r+", "+e:e},d.prototype.delete=function(t){delete this.map[c(t)]},d.prototype.get=function(t){return t=c(t),this.has(t)?this.map[t]:null},d.prototype.has=function(t){return this.map.hasOwnProperty(c(t))},d.prototype.set=function(t,e){this.map[c(t)]=h(e)},d.prototype.forEach=function(t,e){for(var r in this.map)this.map.hasOwnProperty(r)&&t.call(e,this.map[r],r,this)},d.prototype.keys=function(){var t=[];return this.forEach((function(e,r){t.push(r)})),l(t)},d.prototype.values=function(){var t=[];return this.forEach((function(e){t.push(e)})),l(t)},d.prototype.entries=function(){var t=[];return this.forEach((function(e,r){t.push([r,e])})),l(t)},n&&(d.prototype[Symbol.iterator]=d.prototype.entries);var m=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function A(t,e){if(!(this instanceof A))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');var r,o,n=(e=e||{}).body;if(t instanceof A){if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,e.headers||(this.headers=new d(t.headers)),this.method=t.method,this.mode=t.mode,this.signal=t.signal,n||null==t._bodyInit||(n=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=e.credentials||this.credentials||"same-origin",!e.headers&&this.headers||(this.headers=new d(e.headers)),this.method=(r=e.method||this.method||"GET",o=r.toUpperCase(),m.indexOf(o)>-1?o:r),this.mode=e.mode||this.mode||null,this.signal=e.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&n)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(n),!("GET"!==this.method&&"HEAD"!==this.method||"no-store"!==e.cache&&"no-cache"!==e.cache)){var i=/([?&])_=[^&]*/;if(i.test(this.url))this.url=this.url.replace(i,"$1_="+(new Date).getTime());else{this.url+=(/\?/.test(this.url)?"&":"?")+"_="+(new Date).getTime()}}}function v(t){var e=new FormData;return t.trim().split("&").forEach((function(t){if(t){var r=t.split("="),o=r.shift().replace(/\+/g," "),n=r.join("=").replace(/\+/g," ");e.append(decodeURIComponent(o),decodeURIComponent(n))}})),e}function T(t,e){if(!(this instanceof T))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');e||(e={}),this.type="default",this.status=void 0===e.status?200:e.status,this.ok=this.status>=200&&this.status<300,this.statusText=void 0===e.statusText?"":""+e.statusText,this.headers=new d(e.headers),this.url=e.url||"",this._initBody(t)}A.prototype.clone=function(){return new A(this,{body:this._bodyInit})},E.call(A.prototype),E.call(T.prototype),T.prototype.clone=function(){return new T(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new d(this.headers),url:this.url})},T.error=function(){var t=new T(null,{status:0,statusText:""});return t.type="error",t};var _=[301,302,303,307,308];T.redirect=function(t,e){if(-1===_.indexOf(e))throw new RangeError("Invalid status code");return new T(null,{status:e,headers:{location:t}})},e.DOMException=r.DOMException;try{new e.DOMException}catch(t){e.DOMException=function(t,e){this.message=t,this.name=e;var r=Error(t);this.stack=r.stack},e.DOMException.prototype=Object.create(Error.prototype),e.DOMException.prototype.constructor=e.DOMException}function g(t,o){return new Promise((function(n,s){var f=new A(t,o);if(f.signal&&f.signal.aborted)return s(new e.DOMException("Aborted","AbortError"));var u=new XMLHttpRequest;function c(){u.abort()}u.onload=function(){var t,e,r={status:u.status,statusText:u.statusText,headers:(t=u.getAllResponseHeaders()||"",e=new d,t.replace(/\r?\n[\t ]+/g," ").split("\r").map((function(t){return 0===t.indexOf("\n")?t.substr(1,t.length):t})).forEach((function(t){var r=t.split(":"),o=r.shift().trim();if(o){var n=r.join(":").trim();e.append(o,n)}})),e)};r.url="responseURL"in u?u.responseURL:r.headers.get("X-Request-URL");var o="response"in u?u.response:u.responseText;setTimeout((function(){n(new T(o,r))}),0)},u.onerror=function(){setTimeout((function(){s(new TypeError("Network request failed"))}),0)},u.ontimeout=function(){setTimeout((function(){s(new TypeError("Network request failed"))}),0)},u.onabort=function(){setTimeout((function(){s(new e.DOMException("Aborted","AbortError"))}),0)},u.open(f.method,function(t){try{return""===t&&r.location.href?r.location.href:t}catch(e){return t}}(f.url),!0),"include"===f.credentials?u.withCredentials=!0:"omit"===f.credentials&&(u.withCredentials=!1),"responseType"in u&&(i?u.responseType="blob":a&&f.headers.get("Content-Type")&&-1!==f.headers.get("Content-Type").indexOf("application/octet-stream")&&(u.responseType="arraybuffer")),!o||"object"!=typeof o.headers||o.headers instanceof d?f.headers.forEach((function(t,e){u.setRequestHeader(e,t)})):Object.getOwnPropertyNames(o.headers).forEach((function(t){u.setRequestHeader(t,h(o.headers[t]))})),f.signal&&(f.signal.addEventListener("abort",c),u.onreadystatechange=function(){4===u.readyState&&f.signal.removeEventListener("abort",c)}),u.send(void 0===f._bodyInit?null:f._bodyInit)}))}g.polyfill=!0,r.fetch||(r.fetch=g,r.Headers=d,r.Request=A,r.Response=T),e.Headers=d,e.Request=A,e.Response=T,e.fetch=g}({})}(n),n.fetch.ponyfill=!0,delete n.fetch.polyfill;var i=o.fetch?o:n;(r=i.fetch).default=i.fetch,r.fetch=i.fetch,r.Headers=i.Headers,r.Request=i.Request,r.Response=i.Response,t.exports=r}(o,o.exports);var n=r(o.exports);const i=()=>{if(!process.env.FLATFILE_KV_URL)throw new Error("FLATFILE_KV_URL is not set");if(!process.env.FLATFILE_API_KEY)throw new Error("FLATFILE_API_KEY is not set")},s={set:async(t,e)=>{i();try{const r=await n(`${process.env.FLATFILE_KV_URL}/key/${t}`,{method:"POST",body:JSON.stringify({value:JSON.stringify(e)}),headers:{"Content-Type":"application/json",Authorization:`${process.env.FLATFILE_API_KEY}`}});if(!r.ok)throw new Error(await r.text())}catch(r){throw new Error(`KV Store: Failed to set value '${e}' to key '${t}'. Error: ${r}`)}},get:async t=>{i();try{const e=await n(`${process.env.FLATFILE_KV_URL}/key/${t}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`${process.env.FLATFILE_API_KEY}`}});if(!e.ok){if(404===e.status)return null;throw new Error(await e.text())}const r=await async function(t){let e,r=t[0],o=1;for(;o<t.length;){const n=t[o],i=t[o+1];if(o+=2,("optionalAccess"===n||"optionalCall"===n)&&null==r)return;"access"===n||"optionalAccess"===n?(e=r,r=await i(r)):"call"!==n&&"optionalCall"!==n||(r=await i(((...t)=>r.call(e,...t))),e=void 0)}return r}([JSON,"access",async t=>t.parse,"call",async t=>t(await e.text()),"optionalAccess",async t=>t.data]);if(!r)return null;try{return JSON.parse(r)}catch(e){throw new Error(`KV Store: Failed to parse value '${r}' for key '${t}'. Error: ${e}`)}}catch(e){throw new Error(`KV Store: Failed to get value for key '${t}'. Error: ${e}`)}},clear:async t=>{try{return await s.set(t,null)}catch(e){throw new Error(`KV Store: Failed to clear key '${t}'. Error: ${e}`)}},list:{append:async(t,e,r={unique:!1})=>{try{const o=await s.get(t);if(!o)return await s.set(t,[...e]);if(Array.isArray(o)){if(r.unique){const r=e.filter((t=>!o.includes(t)));if(0===r.length)return;return await s.set(t,[...o,...r])}return await s.set(t,[...o,...e])}return await s.set(t,[o,...e])}catch(r){throw new Error(`KV Store: Failed to set values '${e}' to key '${t}'. Error: ${r}`)}},delete:async(t,e)=>{try{const r=await s.get(t);if(!r)return;if(!Array.isArray(r))throw new Error("Value is not an array");const o=r.filter((t=>!e.includes(t)));return await s.set(t,o)}catch(r){throw new Error(`KV Store: Failed to delete values '${e}' from key '${t}'. Error: ${r}`)}},pop:async t=>{try{const e=await s.get(t);if(!e)return null;if(!Array.isArray(e))throw new Error("Value is not an array");const r=e.pop();return await s.set(t,e),r}catch(e){throw new Error(`KV Store: Failed to pop from key '${t}'. Error: ${e}`)}},shift:async t=>{try{const e=await s.get(t);if(!e)return null;if(!Array.isArray(e))throw new Error("Value is not an array");const r=e.shift();return await s.set(t,e),r}catch(e){throw new Error(`KV Store: Failed to shift from key '${t}'. Error: ${e}`)}}}};t.kv=s}));