UNPKG

@flatfile/util-kv-store

Version:

A utility for storing data in a persistent key-value store.

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