UNPKG

db-to-cloud

Version:

Synchronize your database with a cloud drive i.e. Dropbox, Google Drive, OneDrive, Github, etc.

3 lines (2 loc) 25.1 kB
var dbToCloud=function(t){"use strict";function e(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n<e;n++)r[n]=t[n];return r}function n(t,e,n,r,o,i,a){try{var c=t[i](a),u=c.value}catch(t){return void n(t)}c.done?e(u):Promise.resolve(u).then(r,o)}function r(t){return function(){var e=this,r=arguments;return new Promise((function(o,i){var a=t.apply(e,r);function c(t){n(a,o,i,c,u,"next",t)}function u(t){n(a,o,i,c,u,"throw",t)}c(void 0)}))}}function o(t,e){var n="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(!n){if(Array.isArray(t)||(n=s(t))||e&&t&&"number"==typeof t.length){n&&(t=n);var r=0,o=function(){};return{s:o,n:function(){return r>=t.length?{done:!0}:{done:!1,value:t[r++]}},e:function(t){throw t},f:o}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,a=!0,c=!1;return{s:function(){n=n.call(t)},n:function(){var t=n.next();return a=t.done,t},e:function(t){c=!0,i=t},f:function(){try{a||null==n.return||n.return()}finally{if(c)throw i}}}}function i(t,e,n){return(e=function(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var n=t[Symbol.toPrimitive];if(void 0!==n){var r=n.call(t,e||"default");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function a(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),n.push.apply(n,r)}return n}function c(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?a(Object(n),!0).forEach((function(e){i(t,e,n[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):a(Object(n)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))}))}return t}function u(t,e){if(null==t)return{};var n,r,o=function(t,e){if(null==t)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(-1!==e.indexOf(r))continue;n[r]=t[r]}return n}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(r=0;r<i.length;r++)n=i[r],-1===e.indexOf(n)&&{}.propertyIsEnumerable.call(t,n)&&(o[n]=t[n])}return o}function l(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var r,o,i,a,c=[],u=!0,l=!1;try{if(i=(n=n.call(t)).next,0===e){if(Object(n)!==n)return;u=!1}else for(;!(u=(r=i.call(n)).done)&&(c.push(r.value),c.length!==e);u=!0);}catch(t){l=!0,o=t}finally{try{if(!u&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(l)throw o}}return c}}(t,e)||s(t,e)||function(){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 s(t,n){if(t){if("string"==typeof t)return e(t,n);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?e(t,n):void 0}}function p({maxActiveReader:t=1/0}={}){var e,n,r=0,o={read:t=>i(t,!1),write:t=>i(t,!0),length:0};return o;function i(t,r){var i=function({fn:t,block:e=!1,prev:n,next:r,q:o=a(),q2:i=(t.length?a():null)}){return{fn:t,block:e,prev:n,next:r,q:o,q2:i}}({fn:t,block:r});return n?(n.next=i,i.prev=n,n=i,e||(e=n)):e=n=i,o.length++,c(),i.q.promise}function a(){var t={};return t.promise=new Promise(((e,n)=>{t.resolve=e,t.reject=n})),t}function c(){var i=e;if(!(!i||i.block&&i.prev||i.prev&&i.prev.block||r>=t)){var a;i.block||r++,e=i.next;try{a=i.fn(i.q2&&i.q2.resolve)}catch(t){return i.q.reject(t),void l()}if(i.q2&&i.q2.promise.then(s),a&&a.then){var u=a.then(i.q.resolve,i.q.reject);i.q2||u.then(l)}else if(i.q.resolve(a),!i.q2)return void l();c()}function l(){s()}function s(t){i.prev&&(i.prev.next=i.next),i.next&&(i.next.prev=i.prev),n===i&&(n=i.prev),i.block||r--,o.length--,t&&t(),c()}}}class f extends Error{constructor(t){super("The database is locked. Will expire at ".concat(new Date(t).toLocaleString())),this.expire=t,this.name="LockError",Error.captureStackTrace&&Error.captureStackTrace(this,f)}}function h(t){var e,n=0;return()=>{var t;return n&&clearTimeout(n),n=setTimeout(r),e||((t={}).promise=new Promise(((e,n)=>{t.resolve=e,t.reject=n})),e=t),e.promise};function r(){Promise.resolve(t()).then(e.resolve,e.reject),n=0,e=null}}function d(t){return new Promise((e=>setTimeout(e,t)))}function y(t){var e=Array.prototype.filter.call(t.childNodes,(t=>1===t.nodeType));if(!e.length)return t.textContent;var n,r={},i=o(e);try{for(i.s();!(n=i.n()).done;){var a=n.value,c=y(a);if(r[a.localName])if(Array.isArray(r[a.localName]))r[a.localName].push(c);else{var u=[r[a.localName]];u.push(c),r[a.localName]=u}else r[a.localName]=c}}catch(t){i.e(t)}finally{i.f()}return r}function v(t){var e;return function(n){return e||(e=new t),y(e.parseFromString(n,"application/xml"))}}function g(t){return String.fromCharCode(parseInt(t.slice(1),16))}function m(t){return btoa(encodeURIComponent(t).replace(/%[0-9A-F]{2}/g,g))}function w(t){return"%".concat("00".concat(t.charCodeAt(0).toString(16)).slice(-2))}function b(t){return decodeURIComponent(Array.from(atob(t),w).join(""))}var T=["path","contentType","headers","format","raw"];class E extends Error{constructor(t,e,n=e&&e.status){super(t),this.code=n,this.origin=e,Error.captureStackTrace&&Error.captureStackTrace(this,E)}}function j({fetch:t,cooldown:e=0,getAccessToken:n,username:o,password:i}){var a=p(),l=o||i?"Basic ".concat(m("".concat(o,":").concat(i))):null;return t=>a.write(function(){var n=r((function*(n){try{return yield function(t){return s.apply(this,arguments)}(t)}finally{e&&t.method&&"GET"!==t.method?setTimeout(n,e):n()}}));return function(t){return n.apply(this,arguments)}}());function s(){return(s=r((function*(e){var r=e.path,o=e.contentType,i=e.headers,a=e.format,s=e.raw,p=void 0!==s&&s,f=u(e,T),h={};for(n&&(h.Authorization="Bearer ".concat(yield n())),l&&(h.Authorization=l),o&&(h["Content-Type"]=o),Object.assign(h,i);;){var y=yield t(r,c({headers:h},f));if(!y.ok){var v=y.headers.get("Retry-After");if(v){var g=Number(v);if(g){yield d(1e3*g);continue}}var m=yield y.text();throw new E("failed to fetch [".concat(y.status,"]: ").concat(m),y)}if(p)return y;if(a)return yield y[a]();var w=y.headers.get("Content-Type");return/application\/json/.test(w)?yield y.json():yield y.text()}}))).apply(this,arguments)}}var O=["path","body"];function k(t){var e=t.replace(/[/\\][^/\\]+\/?$/,"");return e===t?".":e}function x(t){var e=t.match(/([^/\\]+)[/\\]*$/);return e?e[1]:""}var S=["path"];function C(t){return Array.isArray(t)?t:[t]}var P=Object.freeze({__proto__:null,fsDrive:()=>{},github:function({userAgent:t="db-to-cloud",owner:e,repo:n,getAccessToken:i,fetch:a=("undefined"!=typeof self?self:global).fetch}){var c=j({fetch:a,getAccessToken:i,cooldown:1e3}),u=new Map;return{name:"github",get:p,put:h,post:function(t,e){return h(t,e,!1)},delete:function(t){return y.apply(this,arguments)},list:function(t){return s.apply(this,arguments)},shaCache:u};function l(e){return e.headers||(e.headers={}),e.headers["User-Agent"]||(e.headers["User-Agent"]=t),e.headers.Accept||(e.headers.Accept="application/vnd.github.v3+json"),e.path="https://api.github.com".concat(e.path),c(e)}function s(){return(s=r((function*(t){var r,i=[],a=o(yield l({path:"/repos/".concat(e,"/").concat(n,"/contents/").concat(t)}));try{for(a.s();!(r=a.n()).done;){var c=r.value;i.push(c.name),u.set(c.path,c.sha)}}catch(t){a.e(t)}finally{a.f()}return i}))).apply(this,arguments)}function p(t){return f.apply(this,arguments)}function f(){return(f=r((function*(t){var r=yield l({path:"/repos/".concat(e,"/").concat(n,"/contents/").concat(t)});return u.set(r.path,r.sha),b(r.content)}))).apply(this,arguments)}function h(t,e){return d.apply(this,arguments)}function d(){return(d=r((function*(t,r,o=!0){var i={message:"",content:m(r)};o&&u.has(t)&&(i.sha=u.get(t));for(var a,c={method:"PUT",path:"/repos/".concat(e,"/").concat(n,"/contents/").concat(t),contentType:"application/json",body:JSON.stringify(i)},s=!1;!a;){try{a=yield l(c)}catch(e){if(422!==e.code||!e.message.includes('\\"sha\\" wasn\'t supplied'))throw e;if(!o||s)throw e.code="EEXIST",e;yield p(t)}s=!0}u.set(t,a.content.sha)}))).apply(this,arguments)}function y(){return(y=r((function*(t){try{var r=u.get(t);r||(yield p(t),r=u.get(t)),yield l({method:"DELETE",path:"/repos/".concat(e,"/").concat(n,"/contents/").concat(t),body:JSON.stringify({message:"",sha:r})})}catch(t){if(404===t.code)return;throw t}}))).apply(this,arguments)}},dropbox:function({getAccessToken:t,fetch:e=("undefined"!=typeof self?self:global).fetch}){var n=j({fetch:e,getAccessToken:t});return{name:"dropbox",get:function(t){return s.apply(this,arguments)},put:p,post:function(t,e){return h.apply(this,arguments)},delete:function(t){return d.apply(this,arguments)},list:function(t){return a.apply(this,arguments)}};function i(t){var e=t.path,r=t.body,o=u(t,O);return n(c({method:"POST",path:"https://api.dropboxapi.com/2/".concat(e),contentType:"application/json",body:JSON.stringify(r)},o))}function a(){return(a=r((function*(t){var e,n=[],r=yield i({path:"files/list_folder",body:{path:"/".concat(t)}}),a=o(r.entries);try{for(a.s();!(e=a.n()).done;){var c=e.value;n.push(c.name)}}catch(t){a.e(t)}finally{a.f()}if(!r.has_more)return n;for(;r.has_more;){var u,l=o((r=yield i({path:"files/list_folder/continue",body:{cursor:r.cursor}})).entries);try{for(l.s();!(u=l.n()).done;){var s=u.value;n.push(s.name)}}catch(t){l.e(t)}finally{l.f()}}return n}))).apply(this,arguments)}function l(t){var e=new URLSearchParams;return e.set("arg",JSON.stringify(t)),e.toString()}function s(){return(s=r((function*(t){var e={path:"/".concat(t)};try{return yield n({path:"https://content.dropboxapi.com/2/files/download?".concat(l(e)),format:"text"})}catch(t){throw 409===t.code&&t.message.includes("not_found")&&(t.code="ENOENT"),t}}))).apply(this,arguments)}function p(t,e){return f.apply(this,arguments)}function f(){return(f=r((function*(t,e,r="overwrite"){var o={path:"/".concat(t),mode:r,autorename:!1,mute:!0};yield n({path:"https://content.dropboxapi.com/2/files/upload?".concat(l(o)),method:"POST",contentType:"application/octet-stream",body:e})}))).apply(this,arguments)}function h(){return(h=r((function*(t,e){try{return yield p(t,e,"add")}catch(t){throw 409===t.code&&t.message.includes("conflict")&&(t.code="EEXIST"),t}}))).apply(this,arguments)}function d(){return(d=r((function*(t){try{yield i({path:"files/delete_v2",body:{path:"/".concat(t)}})}catch(t){if(409===t.code&&t.message.includes("not_found"))return;throw t}}))).apply(this,arguments)}},onedrive:function({getAccessToken:t,fetch:e=("undefined"!=typeof self?self:global).fetch}){var n=j({fetch:e,getAccessToken:t});return{name:"onedrive",get:function(t){return c.apply(this,arguments)},put:function(t,e){return u.apply(this,arguments)},post:function(t,e){return l.apply(this,arguments)},delete:function(t){return s.apply(this,arguments)},list:function(t){return a.apply(this,arguments)}};function o(t){return i.apply(this,arguments)}function i(){return(i=r((function*(t){return t.path="https://graph.microsoft.com/v1.0/me/drive/special/approot".concat(t.path),yield n(t)}))).apply(this,arguments)}function a(){return(a=r((function*(t){t&&(t=":/".concat(t,":"));for(var e=yield o({path:"".concat(t,"/children?select=name")}),r=e.value.map((t=>t.name));e["@odata.nextLink"];)e=yield n({path:e["@odata.nextLink"]}),r=r.concat(e.value.map((t=>t.name)));return r}))).apply(this,arguments)}function c(){return(c=r((function*(t){return yield o({path:":/".concat(t,":/content"),format:"text"})}))).apply(this,arguments)}function u(){return(u=r((function*(t,e){yield o({method:"PUT",path:":/".concat(t,":/content"),headers:{"Content-Type":"text/plain"},body:e})}))).apply(this,arguments)}function l(){return(l=r((function*(t,e){try{yield o({method:"PUT",path:":/".concat(t,":/content?@microsoft.graph.conflictBehavior=fail"),headers:{"Content-Type":"text/plain"},body:e})}catch(t){throw 409===t.code&&t.message.includes("nameAlreadyExists")&&(t.code="EEXIST"),t}}))).apply(this,arguments)}function s(){return(s=r((function*(t){try{yield o({method:"DELETE",path:":/".concat(t,":")})}catch(t){if(404===t.code)return;throw t}}))).apply(this,arguments)}},google:function({getAccessToken:t,fetch:e=("undefined"!=typeof self?self:global).fetch,FormData:n=("undefined"!=typeof self?self:global).FormData,Blob:i=("undefined"!=typeof self?self:global).Blob}){var a,c=j({fetch:e,getAccessToken:t}),u=new Map;return{name:"google",get:function(t){return O.apply(this,arguments)},put:function(t,e){return k.apply(this,arguments)},post:x,delete:function(t){return C.apply(this,arguments)},list:function(t){return T.apply(this,arguments)},init:function(){return b.apply(this,arguments)},acquireLock:function(t){return p.apply(this,arguments)},releaseLock:function(){return h.apply(this,arguments)},fileMetaCache:u};function l(t,e){return s.apply(this,arguments)}function s(){return(s=r((function*(t,e){yield c({method:"DELETE",path:"https://www.googleapis.com/drive/v3/files/".concat(t,"/revisions/").concat(e)})}))).apply(this,arguments)}function p(){return(p=r((function*(t){var e=u.get("lock.json"),n=(yield v(e.id,JSON.stringify({expire:Date.now()+60*t*1e3}),{keepRevisionForever:!0})).headRevisionId;try{for(var r=yield c({path:"https://www.googleapis.com/drive/v3/files/".concat(e.id,"/revisions?fields=revisions(id)")}),o=1;o<r.revisions.length;o++){var i=r.revisions[o].id;if(i===n)return void(a=n);var s=JSON.parse(yield c({path:"https://www.googleapis.com/drive/v3/files/".concat(e.id,"/revisions/").concat(i,"?alt=media")}));if(s.expire>Date.now())throw new f(s.expire);yield l(e.id,i)}throw new Error("cannot find lock revision")}catch(t){throw yield l(e.id,n),t}}))).apply(this,arguments)}function h(){return(h=r((function*(){var t=u.get("lock.json");yield l(t.id,a),a=null}))).apply(this,arguments)}function d(t,e){return y.apply(this,arguments)}function y(){return(y=r((function*(t,e){t="https://www.googleapis.com/drive/v3/files?spaces=appDataFolder&fields=nextPageToken,files(id,name,headRevisionId)"+(t?"&"+t:"");var n=yield c({path:t});for(e(n);n.nextPageToken;)e(n=yield c({path:"".concat(t,"&pageToken=").concat(n.nextPageToken)}))}))).apply(this,arguments)}function v(t,e,n){return g.apply(this,arguments)}function g(){return(g=r((function*(t,e,n){var r="https://www.googleapis.com/upload/drive/v3/files/".concat(t,"?uploadType=media&fields=headRevisionId");return n&&(r+="&".concat(new URLSearchParams(n).toString())),yield c({method:"PATCH",path:r,headers:{"Content-Type":"text/plain"},body:e})}))).apply(this,arguments)}function m(t){return w.apply(this,arguments)}function w(){return(w=r((function*(t){t&&(t="q=".concat(encodeURIComponent(t))),yield d(t,(t=>{var e,n=o(t.files);try{for(n.s();!(e=n.n()).done;){var r=e.value;u.set(r.name,r)}}catch(t){n.e(t)}finally{n.f()}}))}))).apply(this,arguments)}function b(){return(b=r((function*(){yield m(),u.has("lock.json")||(yield x("lock.json","{}")),u.has("meta.json")||(yield x("meta.json","{}"))}))).apply(this,arguments)}function T(){return(T=r((function*(t){return[...u.values()].filter((e=>e.name.startsWith(t+"/"))).map((t=>t.name.split("/")[1]))}))).apply(this,arguments)}function O(){return(O=r((function*(t){var e=u.get(t);if(!(e||(yield m("name = '".concat(t,"'")),e=u.get(t))))throw new E("metaCache doesn't contain ".concat(t),null,"ENOENT");try{return yield c({path:"https://www.googleapis.com/drive/v3/files/".concat(e.id,"?alt=media")})}catch(t){throw 404===t.code&&(t.code="ENOENT"),t}}))).apply(this,arguments)}function k(){return(k=r((function*(t,e){if(!u.has(t))return yield x(t,e);var n=u.get(t),r=yield v(n.id,e);n.headRevisionId=r.headRevisionId}))).apply(this,arguments)}function x(t,e){return S.apply(this,arguments)}function S(){return(S=r((function*(t,e){var r=new n,o={name:t,parents:["appDataFolder"]};r.append("metadata",new i([JSON.stringify(o)],{type:"application/json; charset=UTF-8"})),r.append("media",new i([e],{type:"text/plain"}));var a=yield c({method:"POST",path:"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id,name,headRevisionId",body:r});u.set(a.name,a)}))).apply(this,arguments)}function C(){return(C=r((function*(t){var e=u.get(t);if(e)try{yield c({method:"DELETE",path:"https://www.googleapis.com/drive/v3/files/".concat(e.id)})}catch(t){if(404===t.code)return;throw t}}))).apply(this,arguments)}},webdav:function({username:t,password:e,url:n,fetch:i=("undefined"!=typeof self?self:global).fetch,DOMParser:a=("undefined"!=typeof self?self:global).DOMParser,parseXML:l=v(a)}){n.endsWith("/")||(n+="/");var s=j({fetch:i,username:t,password:e});return{name:"webdav",get:function(t){return d.apply(this,arguments)},put:function(t,e){return y.apply(this,arguments)},post:function(t,e){return w.apply(this,arguments)},delete:function(t){return b.apply(this,arguments)},list:function(t){return h.apply(this,arguments)}};function p(t){return f.apply(this,arguments)}function f(){return(f=r((function*(t){var e=t.path,r=u(t,S),i=yield s(c({path:"".concat(n).concat(e)},r));if(r.format||"string"!=typeof i||!i)return i;var a=yield l(i);if(a.error)throw new Error("Failed requesting DAV at ".concat(n).concat(e,": ").concat(JSON.stringify(a.error)));if(a.multistatus){a.multistatus.response=C(a.multistatus.response);var p,f=o(a.multistatus.response);try{for(f.s();!(p=f.n()).done;){var h=p.value;if(h.error)throw new Error("Failed requesting DAV at ".concat(n).concat(e,": ").concat(h.href," ").concat(h.error))}}catch(t){f.e(t)}finally{f.f()}}return a}))).apply(this,arguments)}function h(){return(h=r((function*(t){t.endsWith("/")||(t+="/");var e,r=[],i=o(C((yield p({method:"PROPFIND",path:t,contentType:"application/xml",body:'<?xml version="1.0" encoding="utf-8" ?> \n <propfind xmlns="DAV:">\n <allprop/>\n </propfind>',headers:{Depth:"1"}})).multistatus.response));try{for(i.s();!(e=i.n()).done;){var a=e.value;if(!C(a.propstat).some((t=>t.prop.resourcetype&&void 0!==t.prop.resourcetype.collection))){var c="".concat(n).concat(t),u=x(new URL(a.href,c).href);r.push(u)}}}catch(t){i.e(t)}finally{i.f()}return r}))).apply(this,arguments)}function d(){return(d=r((function*(t){return yield p({method:"GET",path:t,format:"text"})}))).apply(this,arguments)}function y(){return(y=r((function*(t,e){return yield g(k(t),(()=>p({method:"PUT",path:t,contentType:"application/octet-stream",body:e})))}))).apply(this,arguments)}function g(t,e){return m.apply(this,arguments)}function m(){return(m=r((function*(t,e){try{return yield e()}catch(e){if(409!==e.code&&404!==e.code||"."===t)throw e}return yield g(k(t),(()=>p({method:"MKCOL",path:t}))),yield e()}))).apply(this,arguments)}function w(){return(w=r((function*(t,e){try{return yield g(k(t),(()=>p({method:"PUT",path:t,body:e,contentType:"octet-stream",headers:{"If-None-Match":"*"}})))}catch(t){throw 412===t.code&&(t.code="EEXIST"),t}}))).apply(this,arguments)}function b(){return(b=r((function*(t){try{yield p({method:"DELETE",path:t})}catch(t){if(404===t.code)return;throw t}}))).apply(this,arguments)}}});return t.dbToCloud=function({onGet:t,onPut:e,onDelete:n,onFirstSync:i,onWarn:a=console.error,onProgress:c,compareRevision:u,getState:s,setState:y,lockExpire:v=60,retryMaxAttempts:g=5,retryExp:m=1.5,retryDelay:w=10}){var b,T,E,j=new Map,O=h((()=>y(b,T))),k=new Map,x=p();return{use:function(t){b=function(t){var e=Object.create(t);return e.get=function(){var e=r((function*(e){return JSON.parse(yield t.get(e))}));return function(t){return e.apply(this,arguments)}}(),e.put=function(){var e=r((function*(e,n){return yield t.put(e,JSON.stringify(n))}));return function(t,n){return e.apply(this,arguments)}}(),e.post=function(){var e=r((function*(e,n){return yield t.post(e,JSON.stringify(n))}));return function(t,n){return e.apply(this,arguments)}}(),e.isInit=!1,e.acquireLock||(e.acquireLock=function(t){return n.apply(this,arguments)},e.releaseLock=function(){return o.apply(this,arguments)}),e.getMeta||(e.getMeta=function(){return i.apply(this,arguments)},e.putMeta=function(t){return a.apply(this,arguments)}),e.peekChanges||(e.peekChanges=function(t){return c.apply(this,arguments)}),e;function n(){return(n=r((function*(t){try{yield this.post("lock.json",{expire:Date.now()+60*t*1e3})}catch(t){if("EEXIST"!==t.code)throw t;var e=yield this.get("lock.json");if(Date.now()>e.expire)throw yield this.delete("lock.json"),new Error("Found expired lock, please try again");throw new f(e.expire)}}))).apply(this,arguments)}function o(){return(o=r((function*(){yield this.delete("lock.json")}))).apply(this,arguments)}function i(){return(i=r((function*(){try{return yield this.get("meta.json")}catch(t){if("ENOENT"===t.code||404===t.code)return{};throw t}}))).apply(this,arguments)}function a(){return(a=r((function*(t){yield this.put("meta.json",t)}))).apply(this,arguments)}function c(){return(c=r((function*(t){return(yield this.getMeta()).lastChange!==t.lastChange}))).apply(this,arguments)}}(t)},init:function(){return x.write(r((function*(){if(!T||!T.enabled){if(!b)throw new Error("cloud drive is undefined");(T=(yield s(b))||{}).enabled=!0,T.queue||(T.queue=[])}})))},uninit:function(){return x.write(r((function*(){T&&T.enabled&&(T=E=null,j.clear(),k.clear(),b.uninit&&b.isInit&&(yield b.uninit(),b.isInit=!1),yield O())})))},put:function(t,e){if(!T||!T.enabled)return;T.queue.push({_id:t,_rev:e,action:"put"}),O()},delete:function(t,e){if(!T||!T.enabled)return;T.queue.push({_id:t,_rev:e,action:"delete"}),O()},syncNow:function(t){return x.write(r((function*(){if(!T||!T.enabled)throw new Error("Cannot sync now, the sync is not enabled");b.init&&!b.isInit&&(yield b.init(),b.isInit=!0),null==T.lastChange&&(yield i()),yield function(){return q.apply(this,arguments)}(t)})))},drive:()=>b,isInit:()=>Boolean(T&&T.enabled)};function S(){return C.apply(this,arguments)}function C(){return(C=r((function*(){if((E=yield b.getMeta()).lastChange&&E.lastChange!==T.lastChange){var t=[];if(T.lastChange){for(var r=Math.floor((E.lastChange-1)/100),i=Math.floor(T.lastChange/100);i<=r;){var u=yield b.get("changes/".concat(i,".json"));j.set(i,u),t=t.concat(u),i++}t=t.slice(T.lastChange%100)}else t=(yield b.list("docs")).map((t=>({action:"put",_id:t.slice(0,-5)})));var s,p=new Map,f=o(t);try{for(f.s();!(s=f.n()).done;){var h=s.value;p.set(h._id,h)}}catch(t){f.e(t)}finally{f.f()}var d,y=0,v=o(p);try{for(v.s();!(d=v.n()).done;){var g=l(d.value,2),m=g[0],w=g[1],x=void 0,S=void 0;if(c&&c({phase:"pull",total:p.size,loaded:y,change:w}),"delete"===w.action)yield n(m,w._rev);else if("put"===w.action){try{var C=yield b.get("docs/".concat(m,".json"));x=C.doc,S=C._rev}catch(t){if("ENOENT"===t.code||404===t.code){a("Cannot find ".concat(m,". Is it deleted without updating the history?")),y++;continue}throw t}yield e(x)}var P=w._rev||S;P&&k.set(m,P),y++}}catch(t){v.e(t)}finally{v.f()}T.lastChange=E.lastChange,yield O()}}))).apply(this,arguments)}function P(){return A.apply(this,arguments)}function A(){return(A=r((function*(){if(T.queue.length){var e,n=T.queue.slice(),r=new Map,i=o(n);try{for(i.s();!(e=i.n()).done;){var a=e.value;r.set(a._id,a)}}catch(t){i.e(t)}finally{i.f()}var l,s=[],p=o(r.values());try{for(p.s();!(l=p.n()).done;){var f=l.value,h=k.get(f._id);void 0!==h&&u(f._rev,h)<=0||s.push(f)}}catch(t){p.e(t)}finally{p.f()}for(var d,y,v=0,g=0,m=s;g<m.length;g++){var w=m[g];if(c&&c({phase:"push",loaded:v,total:s.length,change:w}),"delete"===w.action)yield b.delete("docs/".concat(w._id,".json"));else if("put"===w.action){var x=yield t(w._id,w._rev);yield b.put("docs/".concat(w._id,".json"),{doc:x,_rev:w._rev})}k.set(w._id,w._rev),v++}if(E.lastChange){y=Math.floor(E.lastChange/100);var S=E.lastChange%100;d=(d=S?j.get(y)||(yield b.get("changes/".concat(y,".json"))):[]).slice(0,S).concat(s)}else y=0,d=s;for(var C=0;100*C<d.length;C++){var P=d.slice(100*C,100*(C+1));yield b.put("changes/".concat(y+C,".json"),P),j.set(y+C,P)}E.lastChange=(E.lastChange||0)+s.length,yield b.putMeta(E),T.queue=T.queue.slice(n.length),T.lastChange=E.lastChange,yield O()}}))).apply(this,arguments)}function N(){return _.apply(this,arguments)}function _(){return(_=r((function*(){for(var t,e=0,n=w;;){try{yield b.acquireLock(v);break}catch(e){if("LockError"!==e.name)throw e;t=e}if(++e>=g)throw t;yield d(1e3*n),n*=m}try{yield S(),yield P()}finally{yield b.releaseLock()}}))).apply(this,arguments)}function q(){return(q=r((function*(t=!0){c&&c({phase:"start"});try{if(!T.queue.length&&t&&E)if(!(yield b.peekChanges(E)))return;yield N()}finally{c&&c({phase:"end"})}}))).apply(this,arguments)}},t.drive=P,Object.defineProperty(t,"__esModule",{value:!0}),t}({}); //# sourceMappingURL=db-to-cloud.min.js.map