text: /** remotestorage.js 0.12.1, http://remotestorage.io, MIT-licensed **/
  /**
   * @preserve Copyright (c) 2014 Petka Antonov
   * 
   * Permission is hereby granted, free of charge, to any person obtaining a copy
   * of this software and associated documentation files (the "Software"), to deal
   * in the Software without restriction, including without limitation the rights
   * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   * copies of the Software, and to permit persons to whom the Software is
   * furnished to do so, subject to the following conditions:</p>
   * 
   * The above copyright notice and this permission notice shall be included in
   * all copies or substantial portions of the Software.
   * 
   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   * THE SOFTWARE.
   * 
   */
  !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;"undefined"!=typeof window?t=window:"undefined"!=typeof global?t=global:"undefined"!=typeof self&&(t=self),t.Promise=e()}}(function(){var e,t,r;return function o(e,t,r){function n(s,a){if(!t[s]){if(!e[s]){var c="function"==typeof require&&require;if(!a&&c)return c(s,!0);if(i)return i(s,!0);throw new Error("Cannot find module '"+s+"'")}var u=t[s]={exports:{}};e[s][0].call(u.exports,function(t){var r=e[s][1][t];return n(r?r:t)},u,u.exports,o,e,t,r)}return t[s].exports}for(var i="function"==typeof require&&require,s=0;s<r.length;s++)n(r[s]);return n}({1:[function(e,t,r){/**
   * Copyright (c) 2014 Petka Antonov
   * 
   * Permission is hereby granted, free of charge, to any person obtaining a copy
   * of this software and associated documentation files (the "Software"), to deal
   * in the Software without restriction, including without limitation the rights
   * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   * copies of the Software, and to permit persons to whom the Software is
   * furnished to do so, subject to the following conditions:</p>
   * 
   * The above copyright notice and this permission notice shall be included in
   * all copies or substantial portions of the Software.
   * 
   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   * THE SOFTWARE.
   * 
   */
  "use strict";function o(){this._isTickUsed=!1,this._schedule=n,this._length=0,this._lateBuffer=new i(16),this._functionBuffer=new i(65536);var e=this;this.consumeFunctionBuffer=function(){e._consumeFunctionBuffer()}}var n=e("./schedule.js"),i=e("./queue.js"),s=e("./util.js").errorObj,a=e("./util.js").tryCatch1,c="undefined"!=typeof process?process:void 0;o.prototype.haveItemsQueued=function(){return this._length>0},o.prototype.invokeLater=function(e,t,r){void 0===c||null==c.domain||e.domain||(e=c.domain.bind(e)),this._lateBuffer.push(e,t,r),this._queueTick()},o.prototype.invoke=function(e,t,r){void 0===c||null==c.domain||e.domain||(e=c.domain.bind(e));var o=this._functionBuffer;o.push(e,t,r),this._length=o.length(),this._queueTick()},o.prototype._consumeFunctionBuffer=function(){for(var e=this._functionBuffer;e.length()>0;){var t=e.shift(),r=e.shift(),o=e.shift();t.call(r,o)}this._reset(),this._consumeLateBuffer()},o.prototype._consumeLateBuffer=function(){for(var e=this._lateBuffer;e.length()>0;){var t=e.shift(),r=e.shift(),o=e.shift(),n=a(t,r,o);if(n===s){if(this._queueTick(),null==t.domain)throw n.e;t.domain.emit("error",n.e)}}},o.prototype._queueTick=function(){this._isTickUsed||(this._schedule(this.consumeFunctionBuffer),this._isTickUsed=!0)},o.prototype._reset=function(){this._isTickUsed=!1,this._length=0},t.exports=new o},{"./queue.js":15,"./schedule.js":16,"./util.js":19}],2:[function(e,t,r){/**
   * Copyright (c) 2014 Petka Antonov
   * 
   * Permission is hereby granted, free of charge, to any person obtaining a copy
   * of this software and associated documentation files (the "Software"), to deal
   * in the Software without restriction, including without limitation the rights
   * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   * copies of the Software, and to permit persons to whom the Software is
   * furnished to do so, subject to the following conditions:</p>
   * 
   * The above copyright notice and this permission notice shall be included in
   * all copies or substantial portions of the Software.
   * 
   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   * THE SOFTWARE.
   * 
   */
  "use strict";var o=e("./promise.js")();t.exports=o},{"./promise.js":12}],3:[function(e,t,r){/**
   * Copyright (c) 2014 Petka Antonov
   * 
   * Permission is hereby granted, free of charge, to any person obtaining a copy
   * of this software and associated documentation files (the "Software"), to deal
   * in the Software without restriction, including without limitation the rights
   * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   * copies of the Software, and to permit persons to whom the Software is
   * furnished to do so, subject to the following conditions:</p>
   * 
   * The above copyright notice and this permission notice shall be included in
   * all copies or substantial portions of the Software.
   * 
   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   * THE SOFTWARE.
   * 
   */
  "use strict";t.exports=function(){function t(e){var t;if("function"==typeof e)t="[function "+(e.name||"anonymous")+"]";else{t=e.toString();var o=/\[object [a-zA-Z0-9$_]+\]/;if(o.test(t))try{var n=JSON.stringify(e);t=n}catch(i){}0===t.length&&(t="(empty array)")}return"(<"+r(t)+">, no stack trace)"}function r(e){var t=41;return e.length<t?e:e.substr(0,t-3)+"..."}function o(e,t){this.captureStackTrace(o,t)}var n=e("./util.js").inherits,i=e("./es5.js").defineProperty,s=new RegExp("\\b(?:[a-zA-Z0-9.]+\\$_\\w+|tryCatch(?:1|2|3|4|Apply)|new \\w*PromiseArray|\\w*PromiseArray\\.\\w*PromiseArray|setTimeout|CatchFilter\\$_\\w+|makeNodePromisified|processImmediate|process._tickCallback|nextTick|Async\\$\\w+)\\b"),a=null,c=null;n(o,Error),o.prototype.captureStackTrace=function(e,t){u(this,e,t)},o.possiblyUnhandledRejection=function(e){if("object"==typeof console){var t;if("object"==typeof e||"function"==typeof e){var r=e.stack;t="Possibly unhandled "+c(r,e)}else t="Possibly unhandled "+String(e);"function"==typeof console.error||"object"==typeof console.error?console.error(t):"function"!=typeof console.log&&"object"!=typeof console.log||console.log(t)}},o.combine=function(e,t){for(var r=e.length-1,o=t.length-1;o>=0;--o){var n=t[o];if(e[r]!==n)break;e.pop(),r--}e.push("From previous event:");for(var i=e.concat(t),c=[],o=0,u=i.length;u>o;++o)s.test(i[o])&&a.test(i[o])||o>0&&!a.test(i[o])&&"From previous event:"!==i[o]||c.push(i[o]);return c},o.protectErrorMessageNewlines=function(e){for(var t=0;t<e.length&&!a.test(e[t]);++t);if(!(1>=t)){for(var r=[],o=0;t>o;++o)r.push(e.shift());e.unshift(r.join("\x00"))}},o.isSupported=function(){return"function"==typeof u};var u=function l(){if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){a=/^\s*at\s*/,c=function(e,r){return"string"==typeof e?e:void 0!==r.name&&void 0!==r.message?r.name+". "+r.message:t(r)};var e=Error.captureStackTrace;return function(t,r){e(t,r)}}var r=new Error;if("string"==typeof r.stack&&"function"==typeof"".startsWith&&r.stack.startsWith("stackDetection@")&&"stackDetection"===l.name){i(Error,"stackTraceLimit",{writable:!0,enumerable:!1,configurable:!1,value:25}),a=/@/;var o=/[@\n]/;return c=function(e,r){return"string"==typeof e?r.name+". "+r.message+"\n"+e:void 0!==r.name&&void 0!==r.message?r.name+". "+r.message:t(r)},function(e){for(var t=(new Error).stack,r=t.split(o),n=r.length,i="",s=0;n>s;s+=2)i+=r[s],i+="@",i+=r[s+1],i+="\n";e.stack=i}}return c=function(e,r){return"string"==typeof e?e:"object"!=typeof r&&"function"!=typeof r||void 0===r.name||void 0===r.message?t(r):r.name+". "+r.message},null}();return o}},{"./es5.js":8,"./util.js":19}],4:[function(e,t,r){/**
   * Copyright (c) 2014 Petka Antonov
   * 
   * Permission is hereby granted, free of charge, to any person obtaining a copy
   * of this software and associated documentation files (the "Software"), to deal
   * in the Software without restriction, including without limitation the rights
   * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   * copies of the Software, and to permit persons to whom the Software is
   * furnished to do so, subject to the following conditions:</p>
   * 
   * The above copyright notice and this permission notice shall be included in
   * all copies or substantial portions of the Software.
   * 
   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   * THE SOFTWARE.
   * 
   */
  "use strict";t.exports=function(t){function r(e,t,r){this._instances=e,this._callback=t,this._promise=r}function o(e,t){var r={},o=s(e,r,t);if(o===a)return o;var n=c(r);return n.length?(a.e=new u("Catch filter must inherit from Error or be a simple predicate function"),a):o}var n=e("./util.js"),i=e("./errors.js"),s=n.tryCatch1,a=n.errorObj,c=e("./es5.js").keys,u=i.TypeError;return r.prototype.doFilter=function(e){for(var r=this._callback,n=this._promise,c=n._boundTo,u=0,l=this._instances.length;l>u;++u){var h=this._instances[u],d=h===Error||null!=h&&h.prototype instanceof Error;if(d&&e instanceof h){var f=s(r,c,e);return f===a?(t.e=f.e,t):f}if("function"==typeof h&&!d){var p=o(h,e);if(p===a){var m=i.canAttach(a.e)?a.e:new Error(a.e+"");this._promise._attachExtraTrace(m),e=a.e;break}if(p){var f=s(r,c,e);return f===a?(t.e=f.e,t):f}}}return t.e=e,t},r}},{"./errors.js":6,"./es5.js":8,"./util.js":19}],5:[function(e,t,r){/**
   * Copyright (c) 2014 Petka Antonov
   * 
   * Permission is hereby granted, free of charge, to any person obtaining a copy
   * of this software and associated documentation files (the "Software"), to deal
   * in the Software without restriction, including without limitation the rights
   * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   * copies of the Software, and to permit persons to whom the Software is
   * furnished to do so, subject to the following conditions:</p>
   * 
   * The above copyright notice and this permission notice shall be included in
   * all copies or substantial portions of the Software.
   * 
   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   * THE SOFTWARE.
   * 
   */
  "use strict";var o=e("./util.js"),n=o.isPrimitive,i=o.wrapsPrimitiveReceiver;t.exports=function(e){var t=function(){return this},r=function(){throw this},o=function(e,t){return 1===t?function(){throw e}:2===t?function(){return e}:void 0};e.prototype["return"]=e.prototype.thenReturn=function(e){return i&&n(e)?this._then(o(e,2),void 0,void 0,void 0,void 0):this._then(t,void 0,void 0,e,void 0)},e.prototype["throw"]=e.prototype.thenThrow=function(e){return i&&n(e)?this._then(o(e,1),void 0,void 0,void 0,void 0):this._then(r,void 0,void 0,e,void 0)}}},{"./util.js":19}],6:[function(e,t,r){/**
   * Copyright (c) 2014 Petka Antonov
   * 
   * Permission is hereby granted, free of charge, to any person obtaining a copy
   * of this software and associated documentation files (the "Software"), to deal
   * in the Software without restriction, including without limitation the rights
   * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   * copies of the Software, and to permit persons to whom the Software is
   * furnished to do so, subject to the following conditions:</p>
   * 
   * The above copyright notice and this permission notice shall be included in
   * all copies or substantial portions of the Software.
   * 
   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   * THE SOFTWARE.
   * 
   */
  "use strict";function o(e){try{p(e,"isOperational",!0)}catch(t){}}function n(e){return null==e?!1:e instanceof c||e.isOperational===!0}function i(e){return e instanceof Error}function s(e){return i(e)}function a(e,t){function r(o){return this instanceof r?(this.message="string"==typeof o?o:t,this.name=e,void(Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor))):new r(o)}return f(r,Error),r}function c(e){this.name="OperationalError",this.message=e,this.cause=e,this.isOperational=!0,e instanceof Error?(this.message=e.message,this.stack=e.stack):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}var u,l,h=e("./es5.js").freeze,d=e("./util.js"),f=d.inherits,p=d.notEnumerableProp,m=a("CancellationError","cancellation error"),g=a("TimeoutError","timeout error"),y=a("AggregateError","aggregate error");try{u=TypeError,l=RangeError}catch(v){u=a("TypeError","type error"),l=a("RangeError","range error")}for(var b="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),M=0;M<b.length;++M)"function"==typeof Array.prototype[b[M]]&&(y.prototype[b[M]]=Array.prototype[b[M]]);y.prototype.length=0,y.prototype.isOperational=!0;var _=0;y.prototype.toString=function(){var e=Array(4*_+1).join(" "),t="\n"+e+"AggregateError of:\n";_++,e=Array(4*_+1).join(" ");for(var r=0;r<this.length;++r){for(var o=this[r]===this?"[Circular AggregateError]":this[r]+"",n=o.split("\n"),i=0;i<n.length;++i)n[i]=e+n[i];o=n.join("\n"),t+=o+"\n"}return _--,t},f(c,Error);var w="__BluebirdErrorTypes__",S=Error[w];S||(S=h({CancellationError:m,TimeoutError:g,OperationalError:c,RejectionError:c,AggregateError:y}),p(Error,w,S)),t.exports={Error:Error,TypeError:u,RangeError:l,CancellationError:S.CancellationError,OperationalError:S.OperationalError,TimeoutError:S.TimeoutError,AggregateError:S.AggregateError,originatesFromRejection:n,markAsOriginatingFromRejection:o,canAttach:s}},{"./es5.js":8,"./util.js":19}],7:[function(e,t,r){/**
   * Copyright (c) 2014 Petka Antonov
   * 
   * Permission is hereby granted, free of charge, to any person obtaining a copy
   * of this software and associated documentation files (the "Software"), to deal
   * in the Software without restriction, including without limitation the rights
   * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   * copies of the Software, and to permit persons to whom the Software is
   * furnished to do so, subject to the following conditions:</p>
   * 
   * The above copyright notice and this permission notice shall be included in
   * all copies or substantial portions of the Software.
   * 
   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   * THE SOFTWARE.
   * 
   */
  "use strict";t.exports=function(t){function r(e){var r=new o(e),n=t.rejected(r),i=n._peekContext();return null!=i&&i._attachExtraTrace(r),n}var o=e("./errors.js").TypeError;return r}},{"./errors.js":6}],8:[function(e,t,r){/**
   * Copyright (c) 2014 Petka Antonov
   * 
   * Permission is hereby granted, free of charge, to any person obtaining a copy
   * of this software and associated documentation files (the "Software"), to deal
   * in the Software without restriction, including without limitation the rights
   * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   * copies of the Software, and to permit persons to whom the Software is
   * furnished to do so, subject to the following conditions:</p>
   * 
   * The above copyright notice and this permission notice shall be included in
   * all copies or substantial portions of the Software.
   * 
   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   * THE SOFTWARE.
   * 
   */
  var o=function(){"use strict";return void 0===this}();if(o)t.exports={freeze:Object.freeze,defineProperty:Object.defineProperty,keys:Object.keys,getPrototypeOf:Object.getPrototypeOf,isArray:Array.isArray,isES5:o};else{var n={}.hasOwnProperty,i={}.toString,s={}.constructor.prototype,a=function(e){var t=[];for(var r in e)n.call(e,r)&&t.push(r);return t},c=function(e,t,r){return e[t]=r.value,e},u=function(e){return e},l=function(e){try{return Object(e).constructor.prototype}catch(t){return s}},h=function(e){try{return"[object Array]"===i.call(e)}catch(t){return!1}};t.exports={isArray:h,keys:a,defineProperty:c,freeze:u,getPrototypeOf:l,isES5:o}}},{}],9:[function(e,t,r){/**
   * Copyright (c) 2014 Petka Antonov
   * 
   * Permission is hereby granted, free of charge, to any person obtaining a copy
   * of this software and associated documentation files (the "Software"), to deal
   * in the Software without restriction, including without limitation the rights
   * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   * copies of the Software, and to permit persons to whom the Software is
   * furnished to do so, subject to the following conditions:</p>
   * 
   * The above copyright notice and this permission notice shall be included in
   * all copies or substantial portions of the Software.
   * 
   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   * THE SOFTWARE.
   * 
   */
  "use strict";t.exports=function(t,r,o){function n(){return this}function i(){throw this}function s(e){return function(){return e}}function a(e){return function(){throw e}}function c(e,t,r){var o;return o=d&&f(t)?r?s(t):a(t):r?n:i,e._then(o,p,void 0,t,void 0)}function u(e){var n=this.promise,i=this.handler,s=n._isBound()?i.call(n._boundTo):i();if(void 0!==s){var a=o(s,void 0);if(a instanceof t)return c(a,e,n.isFulfilled())}return n.isRejected()?(r.e=e,r):e}function l(e){var r=this.promise,n=this.handler,i=r._isBound()?n.call(r._boundTo,e):n(e);if(void 0!==i){var s=o(i,void 0);if(s instanceof t)return c(s,e,!0)}return e}var h=e("./util.js"),d=h.wrapsPrimitiveReceiver,f=h.isPrimitive,p=h.thrower;t.prototype._passThroughHandler=function(e,t){if("function"!=typeof e)return this.then();var r={promise:this,handler:e};return this._then(t?u:l,t?u:void 0,void 0,r,void 0)},t.prototype.lastly=t.prototype["finally"]=function(e){return this._passThroughHandler(e,!0)},t.prototype.tap=function(e){return this._passThroughHandler(e,!1)}}},{"./util.js":19}],10:[function(e,t,r){/**
   * Copyright (c) 2014 Petka Antonov
   * 
   * Permission is hereby granted, free of charge, to any person obtaining a copy
   * of this software and associated documentation files (the "Software"), to deal
   * in the Software without restriction, including without limitation the rights
   * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   * copies of the Software, and to permit persons to whom the Software is
   * furnished to do so, subject to the following conditions:</p>
   * 
   * The above copyright notice and this permission notice shall be included in
   * all copies or substantial portions of the Software.
   * 
   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   * THE SOFTWARE.
   * 
   */
  "use strict";t.exports=function(t,r,o,n){var i=e("./util.js"),s=i.canEvaluate,a=i.tryCatch1,c=i.errorObj;if(s){for(var u=function(e){return new Function("value","holder","                             \n            'use strict';                                                    \n            holder.pIndex = value;                                           \n            holder.checkFulfillment(this);                                   \n            ".replace(/Index/g,e))},l=function(e){for(var t=[],r=1;e>=r;++r)t.push("holder.p"+r);return new Function("holder","                                      \n            'use strict';                                                    \n            var callback = holder.fn;                                        \n            return callback(values);                                         \n            ".replace(/values/g,t.join(", ")))},h=[],d=[void 0],f=1;5>=f;++f)h.push(u(f)),d.push(l(f));var p=function(e,t){this.p1=this.p2=this.p3=this.p4=this.p5=null,this.fn=t,this.total=e,this.now=0};p.prototype.callers=d,p.prototype.checkFulfillment=function(e){var t=this.now;t++;var r=this.total;if(t>=r){var o=this.callers[r],n=a(o,void 0,this);n===c?e._rejectUnchecked(n.e):e._tryFollow(n)||e._fulfillUnchecked(n)}else this.now=t}}t.join=function(){var e,i=arguments.length-1;if(i>0&&"function"==typeof arguments[i]&&(e=arguments[i],6>i&&s)){var a=new t(n);a._setTrace(void 0);for(var c=new p(i,e),u=a._reject,l=h,d=0;i>d;++d){var f=o(arguments[d],void 0);f instanceof t?f.isPending()?f._then(l[d],u,void 0,a,c):f.isFulfilled()?l[d].call(a,f._settledValue,c):(a._reject(f._settledValue),f._unsetRejectionIsUnhandled()):l[d].call(a,f,c)}return a}for(var m=arguments.length,g=new Array(m),y=0;m>y;++y)g[y]=arguments[y];var a=new r(g).promise();return void 0!==e?a.spread(e):a}}},{"./util.js":19}],11:[function(e,t,r){/**
   * Copyright (c) 2014 Petka Antonov
   * 
   * Permission is hereby granted, free of charge, to any person obtaining a copy
   * of this software and associated documentation files (the "Software"), to deal
   * in the Software without restriction, including without limitation the rights
   * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   * copies of the Software, and to permit persons to whom the Software is
   * furnished to do so, subject to the following conditions:</p>
   * 
   * The above copyright notice and this permission notice shall be included in
   * all copies or substantial portions of the Software.
   * 
   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   * THE SOFTWARE.
   * 
   */
  "use strict";t.exports=function(t){function r(e){throw e}function o(e,t){if(!s.isArray(e))return n(e,t);var o=s.tryCatchApply(this,[null].concat(e),t);o===l&&a.invokeLater(r,void 0,o.e)}function n(e,t){var o=this,n=void 0===e?u(o,t,null):c(o,t,null,e);n===l&&a.invokeLater(r,void 0,n.e)}function i(e,t){var o=this,n=u(o,t,e);n===l&&a.invokeLater(r,void 0,n.e)}var s=e("./util.js"),a=e("./async.js"),c=s.tryCatch2,u=s.tryCatch1,l=s.errorObj;t.prototype.nodeify=function(e,t){if("function"==typeof e){var r=n;void 0!==t&&Object(t).spread&&(r=o),this._then(r,i,void 0,e,this._boundTo)}return this}}},{"./async.js":1,"./util.js":19}],12:[function(e,t,r){/**
   * Copyright (c) 2014 Petka Antonov
   * 
   * Permission is hereby granted, free of charge, to any person obtaining a copy
   * of this software and associated documentation files (the "Software"), to deal
   * in the Software without restriction, including without limitation the rights
   * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   * copies of the Software, and to permit persons to whom the Software is
   * furnished to do so, subject to the following conditions:</p>
   * 
   * The above copyright notice and this permission notice shall be included in
   * all copies or substantial portions of the Software.
   * 
   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   * THE SOFTWARE.
   * 
   */
  "use strict";function o(e){try{Promise===e&&(Promise=n)}catch(t){}return e}var n;"undefined"!=typeof Promise&&(n=Promise),t.exports=function(){function t(e){if("function"!=typeof e)throw new _("the promise constructor requires a resolver function");if(this.constructor!==t)throw new _("the promise constructor cannot be invoked directly");this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,this._settledValue=void 0,this._boundTo=void 0,e!==a&&this._resolveFromResolver(e)}function r(e){return e[0]}var n=e("./util.js"),i=e("./async.js"),s=e("./errors.js"),a=function(){},c={},u={e:null},l=e("./thenables.js")(t,a),h=e("./promise_array.js")(t,a,l),d=e("./captured_trace.js")(),f=e("./catch_filter.js")(u),p=e("./promise_resolver.js"),m=n.isArray,g=n.errorObj,y=n.tryCatch1,v=n.tryCatch2,b=n.tryCatchApply,M=s.RangeError,_=s.TypeError,w=s.CancellationError,S=s.TimeoutError,j=s.OperationalError,T=s.originatesFromRejection,A=s.markAsOriginatingFromRejection,I=s.canAttach,N=n.thrower,E=e("./errors_api_rejection")(t),R=function(){return new _("circular promise resolution chain")};t.prototype.bind=function(e){var o=l(e,void 0),n=new t(a);if(o instanceof t){var i=o.then(function(e){n._setBoundTo(e)}),s=t.all([this,i]).then(r);n._follow(s)}else n._follow(this),n._setBoundTo(e);return n._propagateFrom(this,3),n},t.prototype.toString=function(){return"[object Promise]"},t.prototype.caught=t.prototype["catch"]=function(e){var r=arguments.length;if(r>1){var o,n=new Array(r-1),i=0;for(o=0;r-1>o;++o){var s=arguments[o];if("function"!=typeof s){var a=new _("A catch filter must be an error constructor or a filter function");return this._attachExtraTrace(a),t.reject(a)}n[i++]=s}n.length=i,e=arguments[o],this._resetTrace();var c=new f(n,e,this);return this._then(void 0,c.doFilter,void 0,c,void 0)}return this._then(void 0,e,void 0,void 0,void 0)},t.prototype.then=function(e,t,r){return this._then(e,t,r,void 0,void 0)},t.prototype.done=function(e,t,r){var o=this._then(e,t,r,void 0,void 0);o._setIsFinal()},t.prototype.spread=function(e,t){return this._then(e,t,void 0,c,void 0)},t.prototype.isCancellable=function(){return!this.isResolved()&&this._cancellable()},t.prototype.toJSON=function(){var e={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(e.fulfillmentValue=this._settledValue,e.isFulfilled=!0):this.isRejected()&&(e.rejectionReason=this._settledValue,e.isRejected=!0),e},t.prototype.all=function(){return new h(this).promise()},t.is=function(e){return e instanceof t},t.all=function(e){return new h(e).promise()},t.prototype.error=function(e){return this.caught(T,e)},t.prototype._resolveFromSyncValue=function(e){if(e===g)this._cleanValues(),this._setRejected(),this._settledValue=e.e,this._ensurePossibleRejectionHandled();else{var r=l(e,void 0);r instanceof t?this._follow(r):(this._cleanValues(),this._setFulfilled(),this._settledValue=e)}},t.method=function(e){if("function"!=typeof e)throw new _("fn must be a function");return function(){var r;switch(arguments.length){case 0:r=y(e,this,void 0);break;case 1:r=y(e,this,arguments[0]);break;case 2:r=v(e,this,arguments[0],arguments[1]);break;default:for(var o=arguments.length,n=new Array(o),i=0;o>i;++i)n[i]=arguments[i];r=b(e,n,this)}var s=new t(a);return s._setTrace(void 0),s._resolveFromSyncValue(r),s}},t.attempt=t["try"]=function(e,r,o){if("function"!=typeof e)return E("fn must be a function");var n=m(r)?b(e,r,o):y(e,o,r),i=new t(a);return i._setTrace(void 0),i._resolveFromSyncValue(n),i},t.defer=t.pending=function(){var e=new t(a);return e._setTrace(void 0),new p(e)},t.bind=function(e){var r=l(e,void 0),o=new t(a);if(o._setTrace(void 0),r instanceof t){var n=r.then(function(e){o._setBoundTo(e)});o._follow(n)}else o._setBoundTo(e),o._setFulfilled();return o},t.cast=function(e){var r=l(e,void 0);if(!(r instanceof t)){var o=r;r=new t(a),r._setTrace(void 0),r._setFulfilled(),r._cleanValues(),r._settledValue=o}return r},t.resolve=t.fulfilled=t.cast,t.reject=t.rejected=function(e){var r=new t(a);if(r._setTrace(void 0),A(e),r._cleanValues(),r._setRejected(),r._settledValue=e,!I(e)){var o=new Error(e+"");r._setCarriedStackTrace(o)}return r._ensurePossibleRejectionHandled(),r},t.onPossiblyUnhandledRejection=function(e){d.possiblyUnhandledRejection="function"==typeof e?e:void 0};var C;t.onUnhandledRejectionHandled=function(e){C="function"==typeof e?e:void 0};var x=!("undefined"==typeof process||"string"!=typeof process.execPath||"object"!=typeof process.env||!process.env.BLUEBIRD_DEBUG&&"development"!==process.env.NODE_ENV);t.longStackTraces=function(){if(i.haveItemsQueued()&&x===!1)throw new Error("cannot enable long stack traces after promises have been created");x=d.isSupported()},t.hasLongStackTraces=function(){return x&&d.isSupported()},t.prototype._then=function(e,r,o,n,s){var c=void 0!==s,u=c?s:new t(a);if(!c){if(x){var l=this._peekContext()===this._traceParent;u._traceParent=l?this._traceParent:this}u._propagateFrom(this,7)}var h=this._addCallbacks(e,r,o,u,n);return this.isResolved()&&i.invoke(this._queueSettleAt,this,h),u},t.prototype._length=function(){return 262143&this._bitField},t.prototype._isFollowingOrFulfilledOrRejected=function(){return(939524096&this._bitField)>0},t.prototype._isFollowing=function(){return 536870912===(536870912&this._bitField)},t.prototype._setLength=function(e){this._bitField=-262144&this._bitField|262143&e},t.prototype._setFulfilled=function(){this._bitField=268435456|this._bitField},t.prototype._setRejected=function(){this._bitField=134217728|this._bitField},t.prototype._setFollowing=function(){this._bitField=536870912|this._bitField},t.prototype._setIsFinal=function(){this._bitField=33554432|this._bitField},t.prototype._isFinal=function(){return(33554432&this._bitField)>0},t.prototype._cancellable=function(){return(67108864&this._bitField)>0},t.prototype._setCancellable=function(){this._bitField=67108864|this._bitField},t.prototype._unsetCancellable=function(){this._bitField=-67108865&this._bitField},t.prototype._setRejectionIsUnhandled=function(){this._bitField=2097152|this._bitField},t.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-2097153&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},t.prototype._isRejectionUnhandled=function(){return(2097152&this._bitField)>0},t.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=524288|this._bitField},t.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-524289&this._bitField},t.prototype._isUnhandledRejectionNotified=function(){return(524288&this._bitField)>0},t.prototype._setCarriedStackTrace=function(e){this._bitField=1048576|this._bitField,this._fulfillmentHandler0=e},t.prototype._unsetCarriedStackTrace=function(){this._bitField=-1048577&this._bitField,this._fulfillmentHandler0=void 0},t.prototype._isCarryingStackTrace=function(){return(1048576&this._bitField)>0},t.prototype._getCarriedStackTrace=function(){return this._isCarryingStackTrace()?this._fulfillmentHandler0:void 0},t.prototype._receiverAt=function(e){var t=0===e?this._receiver0:this[(e<<2)+e-5+4];return this._isBound()&&void 0===t?this._boundTo:t},t.prototype._promiseAt=function(e){return 0===e?this._promise0:this[(e<<2)+e-5+3]},t.prototype._fulfillmentHandlerAt=function(e){return 0===e?this._fulfillmentHandler0:this[(e<<2)+e-5+0]},t.prototype._rejectionHandlerAt=function(e){return 0===e?this._rejectionHandler0:this[(e<<2)+e-5+1]},t.prototype._addCallbacks=function(e,t,r,o,n){var i=this._length();if(i>=262138&&(i=0,this._setLength(0)),0===i)this._promise0=o,void 0!==n&&(this._receiver0=n),"function"!=typeof e||this._isCarryingStackTrace()||(this._fulfillmentHandler0=e),"function"==typeof t&&(this._rejectionHandler0=t),"function"==typeof r&&(this._progressHandler0=r);else{var s=(i<<2)+i-5;this[s+3]=o,this[s+4]=n,this[s+0]="function"==typeof e?e:void 0,this[s+1]="function"==typeof t?t:void 0,this[s+2]="function"==typeof r?r:void 0}return this._setLength(i+1),i},t.prototype._setProxyHandlers=function(e,t){var r=this._length();if(r>=262138&&(r=0,this._setLength(0)),0===r)this._promise0=t,this._receiver0=e;else{var o=(r<<2)+r-5;this[o+3]=t,this[o+4]=e,this[o+0]=this[o+1]=this[o+2]=void 0}this._setLength(r+1)},t.prototype._proxyPromiseArray=function(e,t){this._setProxyHandlers(e,t)},t.prototype._proxyPromise=function(e){e._setProxied(),this._setProxyHandlers(e,-15)},t.prototype._setBoundTo=function(e){void 0!==e?(this._bitField=8388608|this._bitField,this._boundTo=e):this._bitField=-8388609&this._bitField},t.prototype._isBound=function(){return 8388608===(8388608&this._bitField)},t.prototype._resolveFromResolver=function(e){function t(e){o._tryFollow(e)||o._fulfill(e)}function r(e){var t=I(e)?e:new Error(e+"");o._attachExtraTrace(t),A(e),o._reject(e,t===e?void 0:t)}var o=this;this._setTrace(void 0),this._pushContext();var n=v(e,void 0,t,r);if(this._popContext(),void 0!==n&&n===g){var i=n.e,s=I(i)?i:new Error(i+"");o._reject(i,s)}},t.prototype._spreadSlowCase=function(e,t,r,o){var n=new h(r).promise(),i=n._then(function(){return e.apply(o,arguments)},void 0,void 0,c,void 0);t._follow(i)},t.prototype._callSpread=function(e,r,o){var n=this._boundTo;if(m(o))for(var i=0,s=o.length;s>i;++i)if(l(o[i],void 0)instanceof t)return void this._spreadSlowCase(e,r,o,n);return r._pushContext(),b(e,o,n)},t.prototype._callHandler=function(e,t,r,o){var n;return t!==c||this.isRejected()?(r._pushContext(),n=y(e,t,o)):n=this._callSpread(e,r,o),r._popContext(),n},t.prototype._settlePromiseFromHandler=function(e,r,o,n){if(!(n instanceof t))return void e.call(r,o,n);var i=this._callHandler(e,r,n,o);if(!n._isFollowing())if(i===g||i===n||i===u){var s=i===n?R():i.e,a=I(s)?s:new Error(s+"");i!==u&&n._attachExtraTrace(a),n._rejectUnchecked(s,a)}else{var c=l(i,n);if(c instanceof t){if(c.isRejected()&&!c._isCarryingStackTrace()&&!I(c._settledValue)){var a=new Error(c._settledValue+"");n._attachExtraTrace(a),c._setCarriedStackTrace(a)}n._follow(c),n._propagateFrom(c,1)}else n._fulfillUnchecked(i)}},t.prototype._follow=function(e){this._setFollowing(),e.isPending()?(this._propagateFrom(e,1),e._proxyPromise(this)):e.isFulfilled()?this._fulfillUnchecked(e._settledValue):this._rejectUnchecked(e._settledValue,e._getCarriedStackTrace()),e._isRejectionUnhandled()&&e._unsetRejectionIsUnhandled(),x&&null==e._traceParent&&(e._traceParent=this)},t.prototype._tryFollow=function(e){if(this._isFollowingOrFulfilledOrRejected()||e===this)return!1;var r=l(e,void 0);return r instanceof t?(this._follow(r),!0):!1},t.prototype._resetTrace=function(){x&&(this._trace=new d(void 0===this._peekContext()))},t.prototype._setTrace=function(e){if(x){var t=this._peekContext();this._traceParent=t;var r=void 0===t;void 0!==e&&e._traceParent===t?this._trace=e._trace:this._trace=new d(r)}return this},t.prototype._attachExtraTrace=function(e){if(x){var t=this,r=e.stack;r="string"==typeof r?r.split("\n"):[],d.protectErrorMessageNewlines(r);for(var o=1,n=1;null!=t&&null!=t._trace;)r=d.combine(r,t._trace.stack.split("\n")),t=t._traceParent,n++;var i=Error.stackTraceLimit||10,s=(i+o)*n,a=r.length;a>s&&(r.length=s),a>0&&(r[0]=r[0].split("\x00").join("\n")),r.length<=o?e.stack="(No stack trace)":e.stack=r.join("\n")}},t.prototype._cleanValues=function(){this._cancellable()&&(this._cancellationParent=void 0)},t.prototype._propagateFrom=function(e,t){(1&t)>0&&e._cancellable()&&(this._setCancellable(),this._cancellationParent=e),(4&t)>0&&this._setBoundTo(e._boundTo),(2&t)>0&&this._setTrace(e)},t.prototype._fulfill=function(e){this._isFollowingOrFulfilledOrRejected()||this._fulfillUnchecked(e)},t.prototype._reject=function(e,t){this._isFollowingOrFulfilledOrRejected()||this._rejectUnchecked(e,t)},t.prototype._settlePromiseAt=function(e){var r=this.isFulfilled()?this._fulfillmentHandlerAt(e):this._rejectionHandlerAt(e),o=this._settledValue,n=this._receiverAt(e),i=this._promiseAt(e);if("function"==typeof r)this._settlePromiseFromHandler(r,n,o,i);else{var s=!1,a=this.isFulfilled();void 0!==n&&(n instanceof t&&n._isProxied()?(n._unsetProxied(),a?n._fulfillUnchecked(o):n._rejectUnchecked(o,this._getCarriedStackTrace()),s=!0):n instanceof h&&(a?n._promiseFulfilled(o,i):n._promiseRejected(o,i),s=!0)),s||(a?i._fulfill(o):i._reject(o,this._getCarriedStackTrace()))}e>=4&&this._queueGC()},t.prototype._isProxied=function(){return 4194304===(4194304&this._bitField)},t.prototype._setProxied=function(){this._bitField=4194304|this._bitField},t.prototype._unsetProxied=function(){this._bitField=-4194305&this._bitField},t.prototype._isGcQueued=function(){return-1073741824===(-1073741824&this._bitField)},t.prototype._setGcQueued=function(){this._bitField=-1073741824|this._bitField},t.prototype._unsetGcQueued=function(){this._bitField=1073741823&this._bitField},t.prototype._queueGC=function(){this._isGcQueued()||(this._setGcQueued(),i.invokeLater(this._gc,this,void 0))},t.prototype._gc=function(){for(var e=5*this._length()-5,t=0;e>t;t++)delete this[t];this._clearFirstHandlerData(),this._setLength(0),this._unsetGcQueued()},t.prototype._clearFirstHandlerData=function(){this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0},t.prototype._queueSettleAt=function(e){this._isRejectionUnhandled()&&this._unsetRejectionIsUnhandled(),i.invoke(this._settlePromiseAt,this,e)},t.prototype._fulfillUnchecked=function(e){if(this.isPending()){if(e===this){var t=R();return this._attachExtraTrace(t),this._rejectUnchecked(t,void 0)}this._cleanValues(),this._setFulfilled(),this._settledValue=e;var r=this._length();r>0&&i.invoke(this._settlePromises,this,r)}},t.prototype._rejectUncheckedCheckError=function(e){var t=I(e)?e:new Error(e+"");this._rejectUnchecked(e,t===e?void 0:t)},t.prototype._rejectUnchecked=function(e,t){if(this.isPending()){if(e===this){var r=R();return this._attachExtraTrace(r),this._rejectUnchecked(r)}if(this._cleanValues(),this._setRejected(),this._settledValue=e,this._isFinal())return void i.invokeLater(N,void 0,void 0===t?e:t);var o=this._length();void 0!==t&&this._setCarriedStackTrace(t),o>0?i.invoke(this._rejectPromises,this,null):this._ensurePossibleRejectionHandled()}},t.prototype._rejectPromises=function(){this._settlePromises(),this._unsetCarriedStackTrace()},t.prototype._settlePromises=function(){for(var e=this._length(),t=0;e>t;t++)this._settlePromiseAt(t)},t.prototype._ensurePossibleRejectionHandled=function(){this._setRejectionIsUnhandled(),void 0!==d.possiblyUnhandledRejection&&i.invokeLater(this._notifyUnhandledRejection,this,void 0)},t.prototype._notifyUnhandledRejectionIsHandled=function(){"function"==typeof C&&i.invokeLater(C,void 0,this)},t.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var e=this._settledValue,t=this._getCarriedStackTrace();this._setUnhandledRejectionIsNotified(),void 0!==t&&(this._unsetCarriedStackTrace(),e=t),"function"==typeof d.possiblyUnhandledRejection&&d.possiblyUnhandledRejection(e,this)}};var L=[];return t.prototype._peekContext=function(){var e=L.length-1;return e>=0?L[e]:void 0},t.prototype._pushContext=function(){x&&L.push(this)},t.prototype._popContext=function(){x&&L.pop()},t.noConflict=function(){return o(t)},t.setScheduler=function(e){if("function"!=typeof e)throw new _("fn must be a function");i._schedule=e},d.isSupported()||(t.longStackTraces=function(){},x=!1),t._makeSelfResolutionError=R,e("./finally.js")(t,u,l),e("./direct_resolve.js")(t),e("./synchronous_inspection.js")(t),e("./join.js")(t,h,l,a),t.RangeError=M,t.CancellationError=w,t.TimeoutError=S,t.TypeError=_,t.OperationalError=j,t.RejectionError=j,t.AggregateError=s.AggregateError,n.toFastProperties(t),n.toFastProperties(t.prototype),t.Promise=t,e("./nodeify.js")(t),t.prototype=t.prototype,t}},{"./async.js":1,"./captured_trace.js":3,"./catch_filter.js":4,"./direct_resolve.js":5,"./errors.js":6,"./errors_api_rejection":7,"./finally.js":9,"./join.js":10,"./nodeify.js":11,"./promise_array.js":13,"./promise_resolver.js":14,"./synchronous_inspection.js":17,"./thenables.js":18,"./util.js":19}],13:[function(e,t,r){/**
   * Copyright (c) 2014 Petka Antonov
   * 
   * Permission is hereby granted, free of charge, to any person obtaining a copy
   * of this software and associated documentation files (the "Software"), to deal
   * in the Software without restriction, including without limitation the rights
   * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   * copies of the Software, and to permit persons to whom the Software is
   * furnished to do so, subject to the following conditions:</p>
   * 
   * The above copyright notice and this permission notice shall be included in
   * all copies or substantial portions of the Software.
   * 
   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   * THE SOFTWARE.
   * 
   */
  "use strict";t.exports=function(t,r,o){function n(e){switch(e){case-1:return;case-2:return[];case-3:return{}}}function i(e){var o=this._promise=new t(r),n=void 0;e instanceof t&&(n=e,o._propagateFrom(n,5)),o._setTrace(n),this._values=e,this._length=0,this._totalResolved=0,this._init(void 0,-2)}var s=e("./errors.js").canAttach,a=e("./util.js"),c=a.isArray;return i.prototype.length=function(){return this._length},i.prototype.promise=function(){return this._promise},i.prototype._init=function u(e,r){var i=o(this._values,void 0);if(i instanceof t){if(this._values=i,i._setBoundTo(this._promise._boundTo),!i.isFulfilled())return i.isPending()?void i._then(u,this._reject,void 0,this,r):(i._unsetRejectionIsUnhandled(),void this._reject(i._settledValue));if(i=i._settledValue,!c(i)){var s=new t.TypeError("expecting an array, a promise or a thenable");return void this.__hardReject__(s)}}else if(!c(i)){var s=new t.TypeError("expecting an array, a promise or a thenable");return void this.__hardReject__(s)}if(0===i.length)return void(-5===r?this._resolveEmptyArray():this._resolve(n(r)));for(var a=this.getActualLength(i.length),l=a,h=this.shouldCopyValues()?new Array(a):this._values,d=!1,f=0;a>f;++f){var p=o(i[f],void 0);p instanceof t?p.isPending()?p._proxyPromiseArray(this,f):(p._unsetRejectionIsUnhandled(),d=!0):d=!0,h[f]=p}this._values=h,this._length=l,d&&this._scanDirectValues(a)},i.prototype._settlePromiseAt=function(e){var r=this._values[e];r instanceof t?r.isFulfilled()?this._promiseFulfilled(r._settledValue,e):r.isRejected()&&this._promiseRejected(r._settledValue,e):this._promiseFulfilled(r,e)},i.prototype._scanDirectValues=function(e){for(var t=0;e>t&&!this._isResolved();++t)this._settlePromiseAt(t)},i.prototype._isResolved=function(){return null===this._values},i.prototype._resolve=function(e){this._values=null,this._promise._fulfill(e)},i.prototype.__hardReject__=i.prototype._reject=function(e){this._values=null;var t=s(e)?e:new Error(e+"");this._promise._attachExtraTrace(t),this._promise._reject(e,t)},i.prototype._promiseProgressed=function(e,t){this._isResolved()||this._promise._progress({index:t,value:e})},i.prototype._promiseFulfilled=function(e,t){if(!this._isResolved()){this._values[t]=e;var r=++this._totalResolved;r>=this._length&&this._resolve(this._values)}},i.prototype._promiseRejected=function(e,t){this._isResolved()||(this._totalResolved++,this._reject(e))},i.prototype.shouldCopyValues=function(){return!0},i.prototype.getActualLength=function(e){return e},i}},{"./errors.js":6,"./util.js":19}],14:[function(e,t,r){/**
   * Copyright (c) 2014 Petka Antonov
   * 
   * Permission is hereby granted, free of charge, to any person obtaining a copy
   * of this software and associated documentation files (the "Software"), to deal
   * in the Software without restriction, including without limitation the rights
   * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   * copies of the Software, and to permit persons to whom the Software is
   * furnished to do so, subject to the following conditions:</p>
   * 
   * The above copyright notice and this permission notice shall be included in
   * all copies or substantial portions of the Software.
   * 
   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   * THE SOFTWARE.
   * 
   */
  "use strict";function o(e){return e instanceof Error&&p.getPrototypeOf(e)===Error.prototype}function n(e){var t;return t=o(e)?new h(e):e,u.markAsOriginatingFromRejection(t),t}function i(e){function t(t,r){if(null!==e){if(t){var o=n(c(t));e._attachExtraTrace(o),e._reject(o)}else if(arguments.length>2){for(var i=arguments.length,s=new Array(i-1),a=1;i>a;++a)s[a-1]=arguments[a];e._fulfill(s)}else e._fulfill(r);e=null}}return t}var s,a=e("./util.js"),c=a.maybeWrapAsError,u=e("./errors.js"),l=u.TimeoutError,h=u.OperationalError,d=e("./async.js"),f=a.haveGetters,p=e("./es5.js");if(s=f?function(e){this.promise=e}:function(e){this.promise=e,this.asCallback=i(e),this.callback=this.asCallback},f){var m={get:function(){return i(this.promise)}};p.defineProperty(s.prototype,"asCallback",m),p.defineProperty(s.prototype,"callback",m)}s._nodebackForPromise=i,s.prototype.toString=function(){return"[object PromiseResolver]"},s.prototype.resolve=s.prototype.fulfill=function(e){if(!(this instanceof s))throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.");var t=this.promise;t._tryFollow(e)||d.invoke(t._fulfill,t,e)},s.prototype.reject=function(e){if(!(this instanceof s))throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.");var t=this.promise;u.markAsOriginatingFromRejection(e);var r=u.canAttach(e)?e:new Error(e+"");t._attachExtraTrace(r),d.invoke(t._reject,t,e),r!==e&&d.invoke(this._setCarriedStackTrace,this,r)},s.prototype.progress=function(e){if(!(this instanceof s))throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.");d.invoke(this.promise._progress,this.promise,e)},s.prototype.cancel=function(){d.invoke(this.promise.cancel,this.promise,void 0)},s.prototype.timeout=function(){this.reject(new l("timeout"))},s.prototype.isResolved=function(){return this.promise.isResolved()},s.prototype.toJSON=function(){return this.promise.toJSON()},s.prototype._setCarriedStackTrace=function(e){this.promise.isRejected()&&this.promise._setCarriedStackTrace(e)},t.exports=s},{"./async.js":1,"./errors.js":6,"./es5.js":8,"./util.js":19}],15:[function(e,t,r){/**
   * Copyright (c) 2014 Petka Antonov
   * 
   * Permission is hereby granted, free of charge, to any person obtaining a copy
   * of this software and associated documentation files (the "Software"), to deal
   * in the Software without restriction, including without limitation the rights
   * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   * copies of the Software, and to permit persons to whom the Software is
   * furnished to do so, subject to the following conditions:</p>
   * 
   * The above copyright notice and this permission notice shall be included in
   * all copies or substantial portions of the Software.
   * 
   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   * THE SOFTWARE.
   * 
   */
  "use strict";function o(e,t,r,o,n){for(var i=0;n>i;++i)r[i+o]=e[i+t]}function n(e){this._capacity=e,this._length=0,this._front=0,this._makeCapacity()}n.prototype._willBeOverCapacity=function(e){return this._capacity<e},n.prototype._pushOne=function(e){var t=this.length();this._checkCapacity(t+1);var r=this._front+t&this._capacity-1;this[r]=e,this._length=t+1},n.prototype.push=function(e,t,r){var o=this.length()+3;if(this._willBeOverCapacity(o))return this._pushOne(e),this._pushOne(t),void this._pushOne(r);var n=this._front+o-3;this._checkCapacity(o);var i=this._capacity-1;this[n+0&i]=e,this[n+1&i]=t,this[n+2&i]=r,this._length=o},n.prototype.shift=function(){var e=this._front,t=this[e];return this[e]=void 0,this._front=e+1&this._capacity-1,this._length--,t},n.prototype.length=function(){return this._length},n.prototype._makeCapacity=function(){for(var e=this._capacity,t=0;e>t;++t)this[t]=void 0},n.prototype._checkCapacity=function(e){this._capacity<e&&this._resizeTo(this._capacity<<3)},n.prototype._resizeTo=function(e){var t=this._front,r=this._capacity,n=new Array(r),i=this.length();if(o(this,0,n,0,r),this._capacity=e,this._makeCapacity(),this._front=0,r>=t+i)o(n,t,this,0,i);else{var s=i-(t+i&r-1);o(n,t,this,0,s),o(n,0,this,s,i-s)}},t.exports=n},{}],16:[function(e,t,r){/**
   * Copyright (c) 2014 Petka Antonov
   * 
   * Permission is hereby granted, free of charge, to any person obtaining a copy
   * of this software and associated documentation files (the "Software"), to deal
   * in the Software without restriction, including without limitation the rights
   * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   * copies of the Software, and to permit persons to whom the Software is
   * furnished to do so, subject to the following conditions:</p>
   * 
   * The above copyright notice and this permission notice shall be included in
   * all copies or substantial portions of the Software.
   * 
   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   * THE SOFTWARE.
   * 
   */
  "use strict";var o,n;if("object"==typeof process&&"string"==typeof process.version)o=function(e){process.nextTick(e)};else if("undefined"!=typeof MutationObserver&&(n=MutationObserver)||"undefined"!=typeof WebKitMutationObserver&&(n=WebKitMutationObserver))o=function(){var e=document.createElement("div"),t=void 0,r=new n(function(){var e=t;t=void 0,e()});return r.observe(e,{attributes:!0}),function(r){t=r,e.classList.toggle("foo")}}();else{if("undefined"==typeof setTimeout)throw new Error("no async scheduler available");o=function(e){setTimeout(e,0)}}t.exports=o},{}],17:[function(e,t,r){/**
   * Copyright (c) 2014 Petka Antonov
   * 
   * Permission is hereby granted, free of charge, to any person obtaining a copy
   * of this software and associated documentation files (the "Software"), to deal
   * in the Software without restriction, including without limitation the rights
   * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   * copies of the Software, and to permit persons to whom the Software is
   * furnished to do so, subject to the following conditions:</p>
   * 
   * The above copyright notice and this permission notice shall be included in
   * all copies or substantial portions of the Software.
   * 
   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   * THE SOFTWARE.
   * 
   */
  "use strict";t.exports=function(e){function t(e){void 0!==e?(this._bitField=e._bitField,this._settledValue=e.isResolved()?e._settledValue:void 0):(this._bitField=0,this._settledValue=void 0)}t.prototype.isFulfilled=e.prototype.isFulfilled=function(){return(268435456&this._bitField)>0},t.prototype.isRejected=e.prototype.isRejected=function(){return(134217728&this._bitField)>0},t.prototype.isPending=e.prototype.isPending=function(){return 0===(402653184&this._bitField)},t.prototype.value=e.prototype.value=function(){if(!this.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise");return this._settledValue},t.prototype.error=t.prototype.reason=e.prototype.reason=function(){if(!this.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise");return this._settledValue},t.prototype.isResolved=e.prototype.isResolved=function(){return(402653184&this._bitField)>0},e.PromiseInspection=t}},{}],18:[function(e,t,r){/**
   * Copyright (c) 2014 Petka Antonov
   * 
   * Permission is hereby granted, free of charge, to any person obtaining a copy
   * of this software and associated documentation files (the "Software"), to deal
   * in the Software without restriction, including without limitation the rights
   * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   * copies of the Software, and to permit persons to whom the Software is
   * furnished to do so, subject to the following conditions:</p>
   * 
   * The above copyright notice and this permission notice shall be included in
   * all copies or substantial portions of the Software.
   * 
   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   * THE SOFTWARE.
   * 
   */
  "use strict";t.exports=function(t,r){function o(e){try{return e.then}catch(t){return u.e=t,u}}function n(e,n){if(l(e)){if(e instanceof t)return e;if(i(e)){var a=new t(r);return a._setTrace(void 0),e._then(a._fulfillUnchecked,a._rejectUncheckedCheckError,a._progressUnchecked,a,null),a._setFollowing(),a}var h=o(e);if(h===u)return void 0!==n&&c(h.e)&&n._attachExtraTrace(h.e),t.reject(h.e);if("function"==typeof h)return s(e,h,n)}return e}function i(e){return h.call(e,"_promise0")}function s(e,r,o){function n(r){if(!u){if(u=!0,e===r){var n=t._makeSelfResolutionError();return void 0!==o&&o._attachExtraTrace(n),void a.promise._reject(n,void 0)}a.resolve(r)}}function i(e){if(!u){u=!0;var t=c(e)?e:new Error(e+"");void 0!==o&&o._attachExtraTrace(t),a.promise._reject(e,t)}}function s(e){if(!u){var t=a.promise;"function"==typeof t._progress&&t._progress(e)}}var a=t.defer(),u=!1;try{r.call(e,n,i,s)}catch(l){if(!u){u=!0;var h=c(l)?l:new Error(l+"");void 0!==o&&o._attachExtraTrace(h),a.promise._reject(l,h)}}return a.promise}var a=e("./util.js"),c=e("./errors.js").canAttach,u=a.errorObj,l=a.isObject,h={}.hasOwnProperty;return n}},{"./errors.js":6,"./util.js":19}],19:[function(e,t,r){/**
   * Copyright (c) 2014 Petka Antonov
   * 
   * Permission is hereby granted, free of charge, to any person obtaining a copy
   * of this software and associated documentation files (the "Software"), to deal
   * in the Software without restriction, including without limitation the rights
   * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   * copies of the Software, and to permit persons to whom the Software is
   * furnished to do so, subject to the following conditions:</p>
   * 
   * The above copyright notice and this permission notice shall be included in
   * all copies or substantial portions of the Software.
   * 
   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   * THE SOFTWARE.
   * 
   */
  "use strict";function o(e,t,r){try{return e.call(t,r)}catch(o){return S.e=o,S}}function n(e,t,r,o){try{return e.call(t,r,o)}catch(n){return S.e=n,S}}function i(e,t,r,o,n){try{return e.call(t,r,o,n)}catch(i){return S.e=i,S}}function s(e,t,r,o,n,i){try{return e.call(t,r,o,n,i)}catch(s){return S.e=s,S}}function a(e,t,r){try{return e.apply(r,t)}catch(o){return S.e=o,S}}function c(e){return"string"==typeof e?e:""+e}function u(e){return null==e||e===!0||e===!1||"string"==typeof e||"number"==typeof e}function l(e){return!u(e)}function h(e){return u(e)?new Error(c(e)):e}function d(e,t){var r,o=e.length,n=new Array(o+1);for(r=0;o>r;++r)n[r]=e[r];return n[r]=t,n}function f(e,t,r){if(!M.isES5)return{}.hasOwnProperty.call(e,t)?e[t]:void 0;var o=Object.getOwnPropertyDescriptor(e,t);return null!=o?null==o.get&&null==o.set?o.value:r:void 0}function p(e,t,r){if(u(e))return e;var o={value:r,configurable:!0,enumerable:!1,writable:!0};return M.defineProperty(e,t,o),e}function m(e){throw e}function g(e){try{if("function"==typeof e){var t=M.keys(e.prototype);return t.length>0&&!(1===t.length&&"constructor"===t[0])}return!1}catch(r){return!1}}function y(e){function t(){}return t.prototype=e,t}function v(e){return I.test(e)}function b(e,t,r){for(var o=new Array(e),n=0;e>n;++n)o[n]=t+n+r;return o}var M=e("./es5.js"),_=function(){try{var e={};return M.defineProperty(e,"f",{get:function(){return 3}}),3===e.f}catch(t){return!1}}(),w="undefined"==typeof navigator,S={e:{}},j=function(e,t){function r(){this.constructor=e,this.constructor$=t;for(var r in t.prototype)o.call(t.prototype,r)&&"$"!==r.charAt(r.length-1)&&(this[r+"$"]=t.prototype[r])}var o={}.hasOwnProperty;return r.prototype=t.prototype,e.prototype=new r,e.prototype},T=function(){return"string"!==this}.call("string"),A=function(){return M.isES5?function(e,t){for(var r=[],o=Object.create(null),n=Object(t).includeHidden?Object.getOwnPropertyNames:Object.keys;null!=e;){var i;try{i=n(e)}catch(s){return r}for(var a=0;a<i.length;++a){var c=i[a];if(!o[c]){o[c]=!0;var u=Object.getOwnPropertyDescriptor(e,c);null!=u&&null==u.get&&null==u.set&&r.push(c)}}e=M.getPrototypeOf(e)}return r}:function(e){var t=[];for(var r in e)t.push(r);return t}}(),I=/^[a-z$_][a-z$_0-9]*$/i,N={isClass:g,isIdentifier:v,inheritedDataKeys:A,getDataPropertyOrDefault:f,thrower:m,isArray:M.isArray,haveGetters:_,notEnumerableProp:p,isPrimitive:u,isObject:l,canEvaluate:w,errorObj:S,tryCatch1:o,tryCatch2:n,tryCatch3:i,tryCatch4:s,tryCatchApply:a,inherits:j,withAppended:d,asString:c,maybeWrapAsError:h,wrapsPrimitiveReceiver:T,toFastProperties:y,filledRange:b};t.exports=N},{"./es5.js":8}]},{},[2])(2)}),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise),function(e){function t(e){"string"==typeof e?console.error(e):console.error(e.message,e.stack)}function r(e){return 403!==e.statusCode&&401!==e.statusCode||this._emit("error",new i.Unauthorized),Promise.resolve(e)}function o(e){return"dropbox"===this.backend&&e.match(/^\/public\/.*[^\/]$/)}Promise.defer=function(){var e,t,r=new Promise(function(){e=arguments[0],t=arguments[1]});return{resolve:e,reject:t,promise:r}};var n={get:function(e,t){if(this.local){void 0===t&&("object"==typeof this.remote&&this.remote.connected&&this.remote.online?t=2*this.getSyncInterval():(i.log("Not setting default maxAge, because remote is offline or not connected"),t=!1));var r=function(e){return e!==!1&&"number"!=typeof e};return r(t)?Promise.reject("Argument 'maxAge' must be false or a number"):this.local.get(e,t,this.sync.queueGetRequest.bind(this.sync))}return this.remote.get(e)},put:function(e,t,r){return o.bind(this)(e)?n._wrapBusyDone.call(this,this.remote.put(e,t,r)):this.local?this.local.put(e,t,r):n._wrapBusyDone.call(this,this.remote.put(e,t,r))},"delete":function(e){return this.local?this.local["delete"](e):n._wrapBusyDone.call(this,this.remote["delete"](e))},_wrapBusyDone:function(e){var t=this;return this._emit("wire-busy"),e.then(function(e){return t._emit("wire-done",{success:!0}),Promise.resolve(e)},function(e){return t._emit("wire-done",{success:!1}),Promise.reject(e)})}},i=function(e){if("object"==typeof e&&(i.config.logging=!!e.logging,i.config.cordovaRedirectUri=e.cordovaRedirectUri),i.eventHandling(this,"ready","connected","disconnected","not-connected","conflict","error","features-loaded","connecting","authing","wire-busy","wire-done","sync-interval-change"),this._pending=[],this._setGPD({get:this._pendingGPD("get"),put:this._pendingGPD("put"),"delete":this._pendingGPD("delete")}),this._cleanups=[],this._pathHandlers={change:{}},this.apiKeys={},this.localStorageAvailable()){try{this.apiKeys=JSON.parse(localStorage["remotestorage:api-keys"])}catch(t){}this.setBackend(localStorage["remotestorage:backend"]||"remotestorage")}var r=this.on;this.on=function(e,t){return"ready"===e&&this.remote.connected&&this._allLoaded?setTimeout(t,0):"features-loaded"===e&&this._allLoaded&&setTimeout(t,0),r.call(this,e,t)},this._init(),this.fireInitial=function(){this.local&&setTimeout(this.local.fireInitial.bind(this.local),0)}.bind(this),this.on("ready",this.fireInitial.bind(this))};i.SyncedGetPutDelete=n,i.DiscoveryError=function(e){Error.apply(this,arguments),this.message=e},i.DiscoveryError.prototype=Object.create(Error.prototype),i.Unauthorized=function(){Error.apply(this,arguments)},i.Unauthorized.prototype=Object.create(Error.prototype),i.log=function(){i.config.logging&&console.log.apply(console,arguments)},i.config={logging:!1,changeEvents:{local:!0,window:!1,remote:!0,conflict:!0},discoveryTimeout:1e4,cordovaRedirectUri:void 0},i.prototype={connect:function(t,r){if(this.setBackend("remotestorage"),t.indexOf("@")<0)return void this._emit("error",new i.DiscoveryError("User address doesn't contain an @."));if(e.cordova){if("string"!=typeof i.config.cordovaRedirectUri)return void this._emit("error",new i.DiscoveryError("Please supply a custom HTTPS redirect URI for your Cordova app"));if(!e.cordova.InAppBrowser)return void this._emit("error",new i.DiscoveryError("Please include the InAppBrowser Cordova plugin to enable OAuth"))}this.remote.configure({userAddress:t}),this._emit("connecting");var o=setTimeout(function(){this._emit("error",new i.DiscoveryError("No storage information found at that user address."))}.bind(this),i.config.discoveryTimeout);i.Discover(t).then(function(e){if(clearTimeout(o),this._emit("authing"),e.userAddress=t,this.remote.configure(e),!this.remote.connected)if(e.authURL)if("undefined"==typeof r)this.authorize(e.authURL,i.config.cordovaRedirectUri);else{if("string"!=typeof r)throw new Error("Supplied bearer token must be a string");i.log("Skipping authorization sequence and connecting with known token"),this.remote.configure({token:r})}else this.impliedauth()}.bind(this),function(e){this._emit("error",new i.DiscoveryError("Failed to contact storage server."))}.bind(this))},disconnect:function(){this.remote&&this.remote.configure({userAddress:null,href:null,storageApi:null,token:null,properties:null}),this._setGPD({get:this._pendingGPD("get"),put:this._pendingGPD("put"),"delete":this._pendingGPD("delete")});var e=this._cleanups.length,t=0,r=function(){t++,t>=e&&(this._init(),i.log("Done cleaning up, emitting disconnected and disconnect events"),this._emit("disconnected"))}.bind(this);e>0?this._cleanups.forEach(function(e){var t=e(this);"object"==typeof e&&"function"==typeof e.then?t.then(r):r()}.bind(this)):r()},setBackend:function(e){this.backend=e,this.localStorageAvailable()&&(e?localStorage["remotestorage:backend"]=e:delete localStorage["remotestorage:backend"])},onChange:function(e,t){this._pathHandlers.change[e]||(this._pathHandlers.change[e]=[]),this._pathHandlers.change[e].push(t)},enableLog:function(){i.config.logging=!0},disableLog:function(){i.config.logging=!1},log:function(){i.log.apply(i,arguments)},setApiKeys:function(e,t){t?this.apiKeys[e]=t:delete this.apiKeys[e],this.localStorageAvailable()&&(localStorage["remotestorage:api-keys"]=JSON.stringify(this.apiKeys))},setCordovaRedirectUri:function(e){if("string"!=typeof e||!e.match(/http(s)?\:\/\//))throw new Error("Cordova redirect URI must be a URI string");i.config.cordovaRedirectUri=e},_init:function(){function e(){try{o||(r._emit("ready"),o=!0)}catch(e){console.error("'ready' failed: ",e,e.stack),r._emit("error",e)}}var r=this,o=!1;this._loadFeatures(function(o){this.log("[RemoteStorage] All features loaded"),this.local=o.local&&new o.local,this.local&&this.remote?(this._setGPD(n,this),this._bindChange(this.local)):this.remote&&this._setGPD(this.remote,this.remote),this.remote&&(this.remote.on("connected",function(){e(),r._emit("connected")}),this.remote.on("not-connected",function(){e(),r._emit("not-connected")}),this.remote.connected&&(e(),r._emit("connected")),this.hasFeature("Authorize")||this.remote.stopWaitingForToken()),this._collectCleanupFunctions();try{this._allLoaded=!0,this._emit("features-loaded")}catch(i){t(i),this._emit("error",i)}this._processPending()}.bind(this))},_collectCleanupFunctions:function(){for(var e=0;e<this.features.length;e++){var t=this.features[e].cleanup;"function"==typeof t&&this._cleanups.push(t)}},_loadFeatures:function(e){function t(){u++,u===a.length&&setTimeout(function(){c.caching=!!i.Caching,c.sync=!!i.Sync,["IndexedDB","LocalStorage","InMemoryStorage"].some(function(e){return c.some(function(t){return t.name===e})?(c.local=i[e],!0):void 0}),l.features=c,e(c)},0)}function r(e){l.log("[RemoteStorage] [FEATURE "+e+"] initialized."),c.push({name:e,init:i[e]._rs_init,supported:!0,cleanup:i[e]._rs_cleanup}),t()}function o(e,r){l.log("[RemoteStorage] [FEATURE "+e+"] initialization failed ( "+r+")"),t()}function n(e,r){l.log("[RemoteStorage] [FEATURE "+e+"]"+r?"":" not supported"),r||t()}function s(e){var t;try{t=i[e]._rs_init(l)}catch(n){return void o(e,n)}"object"==typeof t&&"function"==typeof t.then?t.then(function(){r(e)},function(t){o(e,t)}):r(e)}var a=["WireClient","I18n","Dropbox","GoogleDrive","Access","Caching","Discover","Authorize","Widget","IndexedDB","LocalStorage","InMemoryStorage","Sync","BaseClient","Env"],c=[],u=0,l=this;a.forEach(function(e){l.log("[RemoteStorage] [FEATURE "+e+"] initializing...");var t,r=i[e];r?(t=!r._rs_supported||r._rs_supported(),"object"==typeof t?t.then(function(){n(e,!0),s(e)},function(){n(e,!1)}):"boolean"==typeof t&&(n(e,t),t&&s(e))):n(e,!1)})},hasFeature:function(e){for(var t=this.features.length-1;t>=0;t--)if(this.features[t].name===e)return this.features[t].supported;return!1},localStorageAvailable:function(){try{return!!e.localStorage}catch(t){return!1}},_setGPD:function(e,t){function o(e){return function(){return e.apply(t,arguments).then(r.bind(this))}}this.get=o(e.get),this.put=o(e.put),this["delete"]=o(e["delete"])},_pendingGPD:function(e){return function(){var t=Promise.defer();return this._pending.push({method:e,args:Array.prototype.slice.call(arguments),promise:t}),t.promise}.bind(this)},_processPending:function(){this._pending.forEach(function(e){try{this[e.method].apply(this,e.args).then(e.promise.resolve,e.promise.reject)}catch(t){e.promise.reject(t)}}.bind(this)),this._pending=[]},_bindChange:function(e){e.on("change",this._dispatchEvent.bind(this,"change"))},_dispatchEvent:function(e,t){var r=this;Object.keys(this._pathHandlers[e]).forEach(function(o){var n=o.length;t.path.substr(0,n)===o&&r._pathHandlers[e][o].forEach(function(e){var n={};for(var i in t)n[i]=t[i];n.relativePath=t.path.replace(new RegExp("^"+o),"");try{e(n)}catch(s){console.error("'change' handler failed: ",s,s.stack),r._emit("error",s)}})})}},Object.defineProperty(i.prototype,"connected",{get:function(){return this.remote.connected}}),"object"==typeof module&&void 0!==typeof module.exports?module.exports=i:e.RemoteStorage=i}("undefined"!=typeof window?window:global),function(){function e(t,r){var o,n,i;if("object"==typeof t&&!Array.isArray(t)&&null!==t)for(o in t)"object"==typeof t[o]&&null!==t[o]&&("[object ArrayBuffer]"===t[o].toString()?(r[o]=new ArrayBuffer(t[o].byteLength),n=new Int8Array(t[o]),i=new Int8Array(r[o]),i.set(n)):e(t[o],r[o]))}RemoteStorage.util={getEventEmitter:function(){var e={},t=Array.prototype.slice.call(arguments);return t.unshift(e),RemoteStorage.eventHandling.apply(RemoteStorage,t),e.emit=e._emit,e},extend:function(e){var t=Array.prototype.slice.call(arguments,1);return t.forEach(function(t){for(var r in t)e[r]=t[r]}),e},asyncEach:function(e,t){return this.asyncMap(e,t).then(function(){return e})},asyncMap:function(e,t){function r(){i++,i===n&&o.resolve(s,a)}var o=Promise.defer(),n=e.length,i=0,s=[],a=[];return e.forEach(function(e,o){var n;try{n=t(e)}catch(i){r(),a[o]=i}"object"==typeof n&&"function"==typeof n.then?n.then(function(e){s[o]=e,r()},function(e){a[o]=e,r()}):(r(),s[o]=n)}),o.promise},containingFolder:function(e){if(""===e)return"/";if(!e)throw"Path not given!";return e.replace(/\/+/g,"/").replace(/[^\/]+\/?$/,"")},isFolder:function(e){return"/"===e.substr(-1)},isDocument:function(e){return"/"!==e.substr(-1)},baseName:function(e){var t=e.split("/");return this.isFolder(e)?t[t.length-2]+"/":t[t.length-1]},cleanPath:function(e){return e.replace(/\/+/g,"/").split("/").map(encodeURIComponent).join("/").replace(/'/g,"%27")},bindAll:function(e){for(var t in this)"function"==typeof e[t]&&(e[t]=e[t].bind(e))},equal:function(e,t,r){var o;if(r=r||[],typeof e!=typeof t)return!1;if("number"==typeof e||"boolean"==typeof e||"string"==typeof e)return e===t;if("function"==typeof e)return e.toString()===t.toString();if(e instanceof ArrayBuffer&&t instanceof ArrayBuffer&&(e=new Uint8Array(e),t=new Uint8Array(t)),e instanceof Array){if(e.length!==t.length)return!1;for(var n=0,i=e.length;i>n;n++)if(!RemoteStorage.util.equal(e[n],t[n],r))return!1}else{for(o in e)if(e.hasOwnProperty(o)&&!(o in t))return!1;for(o in t)if(t.hasOwnProperty(o)){if(!(o in e))return!1;var s;if("object"==typeof t[o]){if(r.indexOf(t[o])>=0)continue;s=r.slice(),s.push(t[o])}if(!RemoteStorage.util.equal(e[o],t[o],s))return!1}}return!0},equalObj:function(e,t){return console.warn("DEPRECATION WARNING: RemoteStorage.util.equalObj has been replaced by RemoteStorage.util.equal."),RemoteStorage.util.equal(e,t)},deepClone:function(t){var r;return void 0===t?void 0:(r=JSON.parse(JSON.stringify(t)),e(t,r),r)},pathsFromRoot:function(e){for(var t=[e],r=e.replace(/\/$/,"").split("/");r.length>1;)r.pop(),t.push(r.join("/")+"/");return t},md5sum:function(e){function t(e,t){var r=e[0],a=e[1],c=e[2],u=e[3];r=o(r,a,c,u,t[0],7,-680876936),u=o(u,r,a,c,t[1],12,-389564586),c=o(c,u,r,a,t[2],17,606105819),a=o(a,c,u,r,t[3],22,-1044525330),r=o(r,a,c,u,t[4],7,-176418897),u=o(u,r,a,c,t[5],12,1200080426),c=o(c,u,r,a,t[6],17,-1473231341),a=o(a,c,u,r,t[7],22,-45705983),r=o(r,a,c,u,t[8],7,1770035416),u=o(u,r,a,c,t[9],12,-1958414417),c=o(c,u,r,a,t[10],17,-42063),a=o(a,c,u,r,t[11],22,-1990404162),r=o(r,a,c,u,t[12],7,1804603682),u=o(u,r,a,c,t[13],12,-40341101),c=o(c,u,r,a,t[14],17,-1502002290),a=o(a,c,u,r,t[15],22,1236535329),r=n(r,a,c,u,t[1],5,-165796510),u=n(u,r,a,c,t[6],9,-1069501632),c=n(c,u,r,a,t[11],14,643717713),a=n(a,c,u,r,t[0],20,-373897302),r=n(r,a,c,u,t[5],5,-701558691),u=n(u,r,a,c,t[10],9,38016083),c=n(c,u,r,a,t[15],14,-660478335),a=n(a,c,u,r,t[4],20,-405537848),r=n(r,a,c,u,t[9],5,568446438),u=n(u,r,a,c,t[14],9,-1019803690),c=n(c,u,r,a,t[3],14,-187363961),a=n(a,c,u,r,t[8],20,1163531501),r=n(r,a,c,u,t[13],5,-1444681467),u=n(u,r,a,c,t[2],9,-51403784),c=n(c,u,r,a,t[7],14,1735328473),a=n(a,c,u,r,t[12],20,-1926607734),r=i(r,a,c,u,t[5],4,-378558),u=i(u,r,a,c,t[8],11,-2022574463),c=i(c,u,r,a,t[11],16,1839030562),a=i(a,c,u,r,t[14],23,-35309556),r=i(r,a,c,u,t[1],4,-1530992060),u=i(u,r,a,c,t[4],11,1272893353),c=i(c,u,r,a,t[7],16,-155497632),a=i(a,c,u,r,t[10],23,-1094730640),r=i(r,a,c,u,t[13],4,681279174),u=i(u,r,a,c,t[0],11,-358537222),c=i(c,u,r,a,t[3],16,-722521979),a=i(a,c,u,r,t[6],23,76029189),r=i(r,a,c,u,t[9],4,-640364487),u=i(u,r,a,c,t[12],11,-421815835),c=i(c,u,r,a,t[15],16,530742520),a=i(a,c,u,r,t[2],23,-995338651),r=s(r,a,c,u,t[0],6,-198630844),u=s(u,r,a,c,t[7],10,1126891415),c=s(c,u,r,a,t[14],15,-1416354905),a=s(a,c,u,r,t[5],21,-57434055),r=s(r,a,c,u,t[12],6,1700485571),u=s(u,r,a,c,t[3],10,-1894986606),c=s(c,u,r,a,t[10],15,-1051523),a=s(a,c,u,r,t[1],21,-2054922799),r=s(r,a,c,u,t[8],6,1873313359),u=s(u,r,a,c,t[15],10,-30611744),c=s(c,u,r,a,t[6],15,-1560198380),a=s(a,c,u,r,t[13],21,1309151649),r=s(r,a,c,u,t[4],6,-145523070),u=s(u,r,a,c,t[11],10,-1120210379),c=s(c,u,r,a,t[2],15,718787259),a=s(a,c,u,r,t[9],21,-343485551),e[0]=f(r,e[0]),e[1]=f(a,e[1]),e[2]=f(c,e[2]),e[3]=f(u,e[3])}function r(e,t,r,o,n,i){return t=f(f(t,e),f(o,i)),f(t<<n|t>>>32-n,r)}function o(e,t,o,n,i,s,a){return r(t&o|~t&n,e,t,i,s,a)}function n(e,t,o,n,i,s,a){return r(t&n|o&~n,e,t,i,s,a)}function i(e,t,o,n,i,s,a){return r(t^o^n,e,t,i,s,a)}function s(e,t,o,n,i,s,a){return r(o^(t|~n),e,t,i,s,a)}function a(e){txt="";var r,o=e.length,n=[1732584193,-271733879,-1732584194,271733878];for(r=64;r<=e.length;r+=64)t(n,c(e.substring(r-64,r)));e=e.substring(r-64);var i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(r=0;r<e.length;r++)i[r>>2]|=e.charCodeAt(r)<<(r%4<<3);if(i[r>>2]|=128<<(r%4<<3),r>55)for(t(n,i),r=0;16>r;r++)i[r]=0;return i[14]=8*o,t(n,i),n}function c(e){var t,r=[];for(t=0;64>t;t+=4)r[t>>2]=e.charCodeAt(t)+(e.charCodeAt(t+1)<<8)+(e.charCodeAt(t+2)<<16)+(e.charCodeAt(t+3)<<24);return r}function u(e){for(var t="",r=0;4>r;r++)t+=d[e>>8*r+4&15]+d[e>>8*r&15];return t}function l(e){for(var t=0;t<e.length;t++)e[t]=u(e[t]);return e.join("")}function h(e){return l(a(e))}var d="0123456789abcdef".split(""),f=function(e,t){return e+t&4294967295};return"5d41402abc4b2a76b9719d911017c592"!==h("hello")&&(f=function(e,t){var r=(65535&e)+(65535&t),o=(e>>16)+(t>>16)+(r>>16);return o<<16|65535&r}),h(e)}},RemoteStorage.prototype.util||Object.defineProperty(RemoteStorage.prototype,"util",{get:function(){return console.log("DEPRECATION WARNING: remoteStorage.util was moved to RemoteStorage.util"),RemoteStorage.util}})}(),function(e){var t={addEventListener:function(e,t){if("string"!=typeof e)throw new Error("Argument eventName should be a string");if("function"!=typeof t)throw new Error("Argument handler should be a function");RemoteStorage.log("[Eventhandling] Adding event listener",e,t),this._validateEvent(e),this._handlers[e].push(t)},removeEventListener:function(e,t){this._validateEvent(e);for(var r=this._handlers[e].length,o=0;r>o;o++)if(this._handlers[e][o]===t)return void this._handlers[e].splice(o,1)},_emit:function(e){this._validateEvent(e);var t=Array.prototype.slice.call(arguments,1);this._handlers[e].forEach(function(e){e.apply(this,t)})},_validateEvent:function(e){if(!(e in this._handlers))throw new Error("Unknown event: "+e)},_delegateEvent:function(e,t){t.on(e,function(t){this._emit(e,t)}.bind(this))},_addEvent:function(e){this._handlers[e]=[]}};t.on=t.addEventListener,RemoteStorage.eventHandling=function(e){var r=Array.prototype.slice.call(arguments,1);for(var o in t)e[o]=t[o];e._handlers={},r.forEach(function(t){e._addEvent(t)})}}("undefined"!=typeof window?window:global),function(e){function t(e){return"string"!=typeof e?e:"*"===e?"*":'"'+e+'"'}function r(e){return"string"!=typeof e?e:e.replace(/^["']|["']$/g,"")}function o(t,r,o){var n;if(e.BlobBuilder=e.BlobBuilder||e.WebKitBlobBuilder,"undefined"!=typeof e.BlobBuilder){var i=new e.BlobBuilder;i.append(t),n=i.getBlob(r)}else n=new Blob([t],{type:r});var s=new FileReader;"function"==typeof s.addEventListener?s.addEventListener("loadend",function(){o(s.result)}):s.onloadend=function(){o(s.result)},s.readAsArrayBuffer(n)}function n(t,r){var o=Promise.defer();if("undefined"==typeof Blob){var n=new Buffer(new Uint8Array(t));o.resolve(n.toString(r))}else{var i;if(e.BlobBuilder=e.BlobBuilder||e.WebKitBlobBuilder,"undefined"!=typeof e.BlobBuilder){var s=new e.BlobBuilder;s.append(t),i=s.getBlob()}else i=new Blob([t]);var a=new FileReader;"function"==typeof a.addEventListener?a.addEventListener("loadend",function(e){o.resolve(e.target.result)}):a.onloadend=function(e){o.resolve(e.target.result)},a.readAsText(i,r)}return o.promise}function i(e){var t,r="UTF-8";return e&&(t=e.match(/charset=(.+)$/),t&&(r=t[1])),r}function s(e){return"http://remotestorage.io/spec/folder-description"===e["@context"]&&"object"==typeof e.items}function a(e){return[201,204,304].indexOf(e)>=0}function c(e){return[401,403,404,412].indexOf(e)>=0}var u,l,h=RemoteStorage,d="remotestorage:wireclient",f=1,p=2,m=3,g=4,y=5,v={"draft-dejong-remotestorage-00":p,"draft-dejong-remotestorage-01":m,"draft-dejong-remotestorage-02":g,"https://www.w3.org/community/rww/wiki/read-write-web-00#simple":f};if("function"==typeof ArrayBufferView)l=function(e){return e&&e instanceof ArrayBufferView};else{var b=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];l=function(e){for(var t=0;8>t;t++)if(e instanceof b[t])return!0;return!1}}var M,_=RemoteStorage.util.isFolder,w=RemoteStorage.util.cleanPath;h.WireClient=function(e){if(this.connected=!1,h.eventHandling(this,"change","connected","wire-busy","wire-done","not-connected"),M=function(e){e instanceof RemoteStorage.Unauthorized&&this.configure({token:null})}.bind(this),e.on("error",M),u){var t;try{t=JSON.parse(localStorage[d])}catch(r){}t&&setTimeout(function(){this.configure(t)}.bind(this),0)}this._revisionCache={},this.connected&&setTimeout(this._emit.bind(this),0,"connected")},h.WireClient.REQUEST_TIMEOUT=3e4,h.WireClient.prototype={_request:function(e,t,o,s,u,l,d){if(("PUT"===e||"DELETE"===e)&&"/"===t[t.length-1])return Promise.reject("Don't "+e+" on directories!");var f,p=this;return o!==RemoteStorage.Authorize.IMPLIED_FAKE_TOKEN&&(s.Authorization="Bearer "+o),this._emit("wire-busy",{method:e,isFolder:_(t)}),h.WireClient.request(e,t,{body:u,headers:s,responseType:"arraybuffer"}).then(function(o){if(p._emit("wire-done",{method:e,isFolder:_(t),success:!0}),p.online=!0,c(o.status))return RemoteStorage.log("[WireClient] Error response status",o.status),f=l?r(o.getResponseHeader("ETag")):void 0,Promise.resolve({statusCode:o.status,revision:f});if(a(o.status)||200===o.status&&"GET"!==e)return f=r(o.getResponseHeader("ETag")),RemoteStorage.log("[WireClient] Successful request",f),Promise.resolve({statusCode:o.status,revision:f});var s=o.getResponseHeader("Content-Type");f=l?r(o.getResponseHeader("ETag")):200===o.status?d:void 0;var u=i(s);return s&&"binary"!==u?n(o.response,u).then(function(e){return RemoteStorage.log("[WireClient] Successful request",f),Promise.resolve({statusCode:o.status,body:e,contentType:s,revision:f})}):(RemoteStorage.log("[WireClient] Successful request with unknown or binary mime-type",f),Promise.resolve({statusCode:o.status,body:o.response,contentType:s,revision:f}))},function(r){return p._emit("wire-done",{method:e,isFolder:_(t),success:!1}),Promise.reject(r)})},configure:function(e){if("object"!=typeof e)throw new Error("WireClient configure settings parameter should be an object");"undefined"!=typeof e.userAddress&&(this.userAddress=e.userAddress),"undefined"!=typeof e.href&&(this.href=e.href),"undefined"!=typeof e.storageApi&&(this.storageApi=e.storageApi),"undefined"!=typeof e.token&&(this.token=e.token),"undefined"!=typeof e.properties&&(this.properties=e.properties),"undefined"!=typeof this.storageApi&&(this._storageApi=v[this.storageApi]||y,this.supportsRevs=this._storageApi>=p),this.href&&this.token?(this.connected=!0,this.online=!0,this._emit("connected")):this.connected=!1,u&&(localStorage[d]=JSON.stringify({userAddress:this.userAddress,href:this.href,storageApi:this.storageApi,token:this.token,properties:this.properties}))},stopWaitingForToken:function(){this.connected||this._emit("not-connected")},get:function(e,r){var o=this;if(!this.connected)return Promise.reject("not connected (path: "+e+")");r||(r={});var n={};if(this.supportsRevs)r.ifNoneMatch&&(n["If-None-Match"]=t(r.ifNoneMatch));else if(r.ifNoneMatch){this._revisionCache[e]}return this._request("GET",this.href+w(e),this.token,n,void 0,this.supportsRevs,this._revisionCache[e]).then(function(t){if(!_(e))return Promise.resolve(t);var r={};if("undefined"!=typeof t.body)try{t.body=JSON.parse(t.body)}catch(n){return Promise.reject("Folder description at "+o.href+w(e)+" is not JSON")}if(200===t.statusCode&&"object"==typeof t.body){if(0===Object.keys(t.body).length)t.statusCode=404;else if(s(t.body)){for(var i in t.body.items)o._revisionCache[e+i]=t.body.items[i].ETag;r=t.body.items}else Object.keys(t.body).forEach(function(n){o._revisionCache[e+n]=t.body[n],r[n]={ETag:t.body[n]}});return t.body=r,Promise.resolve(t)}return Promise.resolve(t)})},put:function(e,r,o,n){if(!this.connected)return Promise.reject("not connected (path: "+e+")");n||(n={}),!o.match(/charset=/)&&(r instanceof ArrayBuffer||l(r))&&(o+="; charset=binary");var i={"Content-Type":o};return this.supportsRevs&&(n.ifMatch&&(i["If-Match"]=t(n.ifMatch)),n.ifNoneMatch&&(i["If-None-Match"]=t(n.ifNoneMatch))),this._request("PUT",this.href+w(e),this.token,i,r,this.supportsRevs)},"delete":function(e,r){if(!this.connected)throw new Error("not connected (path: "+e+")");r||(r={});var o={};return this.supportsRevs&&r.ifMatch&&(o["If-Match"]=t(r.ifMatch)),this._request("DELETE",this.href+w(e),this.token,o,void 0,this.supportsRevs)}},h.WireClient.cleanPath=w,h.WireClient.isArrayBufferView=l,h.WireClient.readBinaryData=o,h.WireClient.request=function(e,t,r){var o=Promise.defer();RemoteStorage.log("[WireClient]",e,t);var n=!1,i=setTimeout(function(){n=!0,o.reject("timeout")},h.WireClient.REQUEST_TIMEOUT),s=new XMLHttpRequest;if(s.open(e,t,!0),r.responseType&&(s.responseType=r.responseType),r.headers)for(var a in r.headers)s.setRequestHeader(a,r.headers[a]);s.onload=function(){n||(clearTimeout(i),o.resolve(s))},s.onerror=function(e){n||(clearTimeout(i),o.reject(e))};var c=r.body;return"object"==typeof c&&!l(c)&&c instanceof ArrayBuffer&&(c=new Uint8Array(c)),s.send(c),o.promise},Object.defineProperty(RemoteStorage.WireClient.prototype,"storageType",{get:function(){if(this.storageApi){var e=this.storageApi.match(/draft-dejong-(remotestorage-\d\d)/);return e?e[1]:"2012.04"}}}),h.WireClient._rs_init=function(e){u=e.localStorageAvailable(),e.remote=new h.WireClient(e),this.online=!0},h.WireClient._rs_supported=function(){return!!e.XMLHttpRequest},h.WireClient._rs_cleanup=function(e){u&&delete localStorage[d],e.removeEventListener("error",M)}}("undefined"!=typeof window?window:global),function(e){var t,r,o="remotestorage:discover",n={};RemoteStorage.Discover=function(e){if(e in n)return Promise.resolve(n[e]);var t=new WebFinger({tls_only:!1,uri_fallback:!0,request_timeout:5e3}),i=Promise.defer();return t.lookup(e,function(t,s){if(t)return i.reject(t.message);if("object"!=typeof s.idx.links.remotestorage||"number"!=typeof s.idx.links.remotestorage.length||s.idx.links.remotestorage.length<=0)return RemoteStorage.log("[Discover] WebFinger record for "+e+" does not have remotestorage defined in the links section ",JSON.stringify(s.json)),i.reject("WebFinger record for "+e+" does not have remotestorage defined in the links section.");var a=s.idx.links.remotestorage[0],c=a.properties["http://tools.ietf.org/html/rfc6749#section-4.2"]||a.properties["auth-endpoint"],u=a.properties["http://remotestorage.io/spec/version"]||a.type;return n[e]={href:a.href,storageType:u,authURL:c,properties:a.properties},r&&(localStorage[o]=JSON.stringify({cache:n})),i.resolve(n[e])}),i.promise},RemoteStorage.Discover._rs_init=function(e){if(r=e.localStorageAvailable()){var t;try{t=JSON.parse(localStorage[o])}catch(i){}t&&(n=t.cache)}},RemoteStorage.Discover._rs_supported=function(){return t=!!e.XMLHttpRequest},RemoteStorage.Discover._rs_cleanup=function(){r&&delete localStorage[o]}}("undefined"!=typeof window?window:global),/*!
   * webfinger.js
   *   version 2.2.1
   *   http://github.com/silverbucket/webfinger.js
   *
   * Developed and Maintained by:
   *   Nick Jennings <nick@silverbucket.net> 2012 - 2014
   *
   * webfinger.js is released under the AGPL (see LICENSE).
   *
   * You don't have to do anything special to choose one license or the other and you don't
   * have to notify anyone which license you are using.
   * Please see the corresponding license file for details of these licenses.
   * You are free to use, modify and distribute this software, but all copyright
   * information must remain.
   *
   */
  "undefined"==typeof XMLHttpRequest&&(XMLHttpRequest=require("xmlhttprequest").XMLHttpRequest),function(e){function t(e){return e.toString=function(){return this.message},e}function r(e){"object"!=typeof e&&(e={}),this.config={tls_only:"undefined"!=typeof e.tls_only?e.tls_only:!0,webfist_fallback:"undefined"!=typeof e.webfist_fallback?e.webfist_fallback:!1,uri_fallback:"undefined"!=typeof e.uri_fallback?e.uri_fallback:!1,request_timeout:"undefined"!=typeof e.request_timeout?e.request_timeout:1e4}}var o={"http://webfist.org/spec/rel":"webfist","http://webfinger.net/rel/avatar":"avatar",remotestorage:"remotestorage","http://tools.ietf.org/id/draft-dejong-remotestorage":"remotestorage",remoteStorage:"remotestorage","http://www.packetizer.com/rel/share":"share","http://webfinger.net/rel/profile-page":"profile",me:"profile",vcard:"vcard",blog:"blog","http://packetizer.com/rel/blog":"blog","http://schemas.google.com/g/2010#updates-from":"updates","https://camlistore.org/rel/server":"camilstore"},n={avatar:[],remotestorage:[],blog:[],vcard:[],updates:[],share:[],profile:[],webfist:[],camlistore:[]},i=["webfinger","host-meta","host-meta.json"];if(r.prototype._fetchJRD=function(e,r){var o=this,n=new XMLHttpRequest;n.onreadystatechange=function(){4===n.readyState&&(200===n.status?o._isValidJSON(n.responseText)?r(null,n.responseText):r(t({message:"invalid json",url:e,status:n.status})):r(404===n.status?t({message:"endpoint unreachable",url:e,status:n.status}):t({message:"error during request",url:e,status:n.status})))},n.open("GET",e,!0),n.setRequestHeader("Accept","application/jrd+json, application/json"),n.send()},r.prototype._isValidJSON=function(e){try{JSON.parse(e)}catch(t){return!1}return!0},r.prototype._isLocalhost=function(e){var t=/^localhost(\.localdomain)?(\:[0-9]+)?$/;return t.test(e)},r.prototype._processJRD=function(r,i){var s=JSON.parse(r);if("object"!=typeof s||"object"!=typeof s.links)return i(t("undefined"!=typeof s.error?{message:s.error}:{message:"unknown response from server"})),!1;var a=s.links,c={object:s,json:r,idx:{}};c.idx.properties={name:e},c.idx.links=JSON.parse(JSON.stringify(n)),a.map(function(e,t){if(o.hasOwnProperty(e.rel)&&c.idx.links[o[e.rel]]){var r={};Object.keys(e).map(function(t,o){r[t]=e[t]}),c.idx.links[o[e.rel]].push(r)}});var u=JSON.parse(r).properties;for(var l in u)u.hasOwnProperty(l)&&"http://packetizer.com/ns/name"===l&&(c.idx.properties.name=u[l]);i(null,c)},r.prototype.lookup=function(e,r){function o(){return h+"://"+u+"/.well-known/"+i[l]+"?resource=acct:"+e}function n(e){if(a.config.uri_fallback&&"webfist.org"!==u&&l!==i.length-1)l+=1,s();else if(a.config.tls_only||"https"!==h){if(!a.config.webfist_fallback||"webfist.org"===u)return r(e),!1;l=0,h="http",u="webfist.org",a._fetchJRD(o(),function(e,t){return e?(r(e),!1):void a._processJRD(t,function(e,t){"object"==typeof t.idx.links.webfist&&"string"==typeof t.idx.links.webfist[0].href&&a._fetchJRD(t.idx.links.webfist[0].href,function(e,t){e?r(e):a._processJRD(t,r)})})})}else l=0,h="http",s()}function s(){a._fetchJRD(o(),function(e,t){e?n(e):a._processJRD(t,r)})}if("string"!=typeof e)throw new Error("first parameter must be a user address");if("function"!=typeof r)throw new Error("second parameter must be a callback");var a=this,c=e.replace(/ /g,"").split("@"),u=c[1],l=0,h="https";return 2!==c.length?(r(t({message:"invalid user address "+e+" ( expected format: user@host.com )"})),!1):(a._isLocalhost(u)&&(h="http"),void setTimeout(s,0))},r.prototype.lookupLink=function(e,t,r){n.hasOwnProperty(t)?this.lookup(e,function(e,o){var n=o.idx.links[t];e?r(e):0===n.length?r('no links found with rel="'+t+'"'):r(null,n[0])}):r("unsupported rel "+t)},"object"==typeof window)window.WebFinger=r;else if("function"==typeof define&&define.amd)define([],function(){return r});else try{module.exports=r}catch(s){}}(),function(e){function t(e){var t,r=e||RemoteStorage.Authorize.getLocation().href,o=r.indexOf("#");if(-1!==o&&(t=r.substring(o+1),-1!==t.indexOf("=")))return t.split("&").reduce(function(e,t){var r=t.split("=");return e[decodeURIComponent(r[0])]=decodeURIComponent(r[1]),e},{})}RemoteStorage.ImpliedAuth=function(e,t){RemoteStorage.log("ImpliedAuth proceeding due to absent authURL; storageApi = "+e+" redirectUri = "+t),remoteStorage.remote.configure({token:RemoteStorage.Authorize.IMPLIED_FAKE_TOKEN}),document.location=t},RemoteStorage.Authorize=function(t,r,o,n){RemoteStorage.log("[Authorize] authURL = ",t,"scope = ",r,"redirectUri = ",o,"clientId = ",n);var i=t,s=o.indexOf("#");return i+=t.indexOf("?")>0?"&":"?",i+="redirect_uri="+encodeURIComponent(o.replace(/#.*$/,"")),i+="&scope="+encodeURIComponent(r),i+="&client_id="+encodeURIComponent(n),-1!==s&&(i+="&state="+encodeURIComponent(o.substring(s+1))),i+="&response_type=token",e.cordova?RemoteStorage.Authorize.openWindow(i,o,"location=yes,clearsessioncache=yes,clearcache=yes").then(function(t){remoteStorage.remote.configure({token:t.access_token}),e.location.reload()}).then(null,function(e){console.error(e),remoteStorage.widget.view.setState("initial")}):void RemoteStorage.Authorize.setLocation(i)},RemoteStorage.Authorize.IMPLIED_FAKE_TOKEN=!1,RemoteStorage.prototype.authorize=function(t,r){this.access.setStorageType(this.remote.storageType);var o=this.access.scopeParameter,n=e.cordova?r:String(RemoteStorage.Authorize.getLocation()),i=n.match(/^(https?:\/\/[^\/]+)/)[0];RemoteStorage.Authorize(t,o,n,i)},RemoteStorage.Authorize.getLocation=function(){return e.document.location},RemoteStorage.Authorize.setLocation=function(t){if("string"==typeof t)e.document.location.href=t;else{if("object"!=typeof t)throw"Invalid location "+t;e.document.location=t}},RemoteStorage.Authorize.openWindow=function(r,o,n){var i=Promise.defer(),s=e.open(r,"_blank",n);if(!s||s.closed)return i.reject("Authorization popup was blocked"),i.promise;var a=function(){i.reject("Authorization was canceled")},c=function(e){if(0===e.url.indexOf(o)){s.removeEventListener("exit",a),s.close();var r=t(e.url);return r?i.resolve(r):i.reject("Authorization error")}};return s.addEventListener("loadstart",c),s.addEventListener("exit",a),i.promise},RemoteStorage.prototype.impliedauth=function(){RemoteStorage.ImpliedAuth(this.remote.storageApi,String(document.location))},RemoteStorage.Authorize._rs_supported=function(){return"undefined"!=typeof document};var r;RemoteStorage.Authorize._rs_init=function(e){r=function(){var t=!1;if(n){if(n.error)throw"Authorization server errored: "+n.error;n.access_token&&(e.remote.configure({token:n.access_token}),t=!0),n.remotestorage&&(e.connect(n.remotestorage),t=!0),n.state&&RemoteStorage.Authorize.setLocation("#"+n.state)}t||e.remote.stopWaitingForToken()};var o,n=t();n&&(o=RemoteStorage.Authorize.getLocation(),o.hash=""),e.on("features-loaded",r)},RemoteStorage.Authorize._rs_cleanup=function(e){e.removeEventListener("features-loaded",r)}}("undefined"!=typeof window?window:global),function(e){RemoteStorage.Access=function(){this.reset()},RemoteStorage.Access.prototype={claim:function(e,t){if("string"!=typeof e||-1!==e.indexOf("/")||0===e.length)throw new Error("Scope should be a non-empty string without forward slashes");if(!t.match(/^rw?$/))throw new Error("Mode should be either 'r' or 'rw'");this._adjustRootPaths(e),this.scopeModeMap[e]=t},get:function(e){return this.scopeModeMap[e]},remove:function(e){var t,r={};for(t in this.scopeModeMap)r[t]=this.scopeModeMap[t];this.reset(),delete r[e];for(t in r)this.set(t,r[t])},checkPermission:function(e,t){var r=this.get(e);return r&&("r"===t||"rw"===r)},checkPathPermission:function(e,t){return this.checkPermission("*",t)?!0:!!this.checkPermission(this._getModuleName(e),t)},reset:function(){this.rootPaths=[],this.scopeModeMap={}},_getModuleName:function(e){if("/"!==e[0])throw new Error("Path should start with a slash");var t=e.replace(/^\/public/,"").match(/^\/([^\/]*)\//);return t?t[1]:"*"},_adjustRootPaths:function(e){"*"in this.scopeModeMap||"*"===e?this.rootPaths=["/"]:e in this.scopeModeMap||(this.rootPaths.push("/"+e+"/"),this.rootPaths.push("/public/"+e+"/"))},_scopeNameForParameter:function(e){if("*"===e.name&&this.storageType){if("2012.04"===this.storageType)return"";if(this.storageType.match(/remotestorage-0[01]/))return"root"}return e.name},setStorageType:function(e){this.storageType=e}},Object.defineProperty(RemoteStorage.Access.prototype,"scopes",{get:function(){return Object.keys(this.scopeModeMap).map(function(e){return{name:e,mode:this.scopeModeMap[e]}}.bind(this))}}),Object.defineProperty(RemoteStorage.Access.prototype,"scopeParameter",{get:function(){return this.scopes.map(function(e){return this._scopeNameForParameter(e)+":"+e.mode}.bind(this)).join(" ")}}),Object.defineProperty(RemoteStorage.prototype,"access",{get:function(){var e=new RemoteStorage.Access;return Object.defineProperty(this,"access",{value:e}),e},configurable:!0}),RemoteStorage.Access._rs_init=function(){}}("undefined"!=typeof window?window:global),function(e){var t=e,r={},o=!1;RemoteStorage.Env=function(){return r},RemoteStorage.Env.isBrowser=function(){return"browser"===t},RemoteStorage.Env.isNode=function(){return"node"===t},RemoteStorage.Env.goBackground=function(){o=!0,RemoteStorage.Env._emit("background")},RemoteStorage.Env.goForeground=function(){o=!1,RemoteStorage.Env._emit("foreground")},RemoteStorage.Env._rs_init=function(e){function o(){document[r.hiddenProperty]?RemoteStorage.Env.goBackground():RemoteStorage.Env.goForeground()}RemoteStorage.eventHandling(RemoteStorage.Env,"background","foreground"),"browser"===t&&("undefined"!=typeof document.hidden?(r.hiddenProperty="hidden",r.visibilityChangeEvent="visibilitychange"):"undefined"!=typeof document.mozHidden?(r.hiddenProperty="mozHidden",r.visibilityChangeEvent="mozvisibilitychange"):"undefined"!=typeof document.msHidden?(r.hiddenProperty="msHidden",r.visibilityChangeEvent="msvisibilitychange"):"undefined"!=typeof document.webkitHidden&&(r.hiddenProperty="webkitHidden",r.visibilityChangeEvent="webkitvisibilitychange"),document.addEventListener(r.visibilityChangeEvent,o,!1),o())},RemoteStorage.Env._rs_cleanup=function(e){}}("undefined"!=typeof window?"browser":"node"),function(){"use strict";var e={view_info:'This app allows you to use your own storage. <a href="http://remotestorage.io/" target="_blank">Learn more!</a>',view_connect:"<strong>Connect</strong> remote storage",view_connecting:"Connecting <strong>%s</strong>",view_offline:"Offline",view_error_occured:"Sorry! An error occured.",view_invalid_key:"Wrong key!",view_confirm_reset:"Are you sure you want to reset everything? This will clear your local data and reload the page.",view_get_me_out:"Get me out of here!",view_error_plz_report:'If this problem persists, please <a href="http://remotestorage.io/community/" target="_blank">let us know</a>!',view_unauthorized:"Unauthorized! Click here to reconnect."};RemoteStorage.I18n={translate:function(){var t=arguments[0],r=Array.prototype.splice.call(arguments,1);if("string"!=typeof e[t])throw"Unknown translation string: "+t;return t=e[t],t.replace(/%s/g,function(){return r.shift()})},getDictionary:function(){return e},setDictionary:function(t){e=t}}}(),RemoteStorage.Assets={cipherIcon:"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaW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TU3LTEuMTMzOSAzLjY4NzQtMC41OTM3bC0wLjcxODcgMS44MTI0IDMuODEyNS0xLjYyNS0xLjYyNS0zLjc4MTJ6Ii8+PHBhdGggZmlsbD0iI2ZmZiIgZD0ibTE0IDUuNTYyNWwtMS42NTYgMC43MTg3czEuNTQxIDMuMTEzNS0xLjY4OCA1LjUzMDhjMCAwLTEuNzI3MiAxLjEzNS0zLjcxODUgMC41OTRsMC43NS0xLjgxMi0zLjgxMjUgMS41OTQgMS41OTM4IDMuODEyIDAuNzgxMi0xLjkwNmMxLjAxMTMgMC4yOTUgMy40NjE1IDAuNzY2IDUuNjU2LTAuOTM4IDAgMCAzLjkyOC0yLjU5NCAyLjA5NC03LjU5MzV6Ii8+Cjwvc3ZnPgo=",widget:'<div class="rs-bubble rs-hidden">   <div class="rs-bubble-text remotestorage-initial remotestorage-error remotestorage-authing remotestorage-offline">     <span class="rs-status-text">{{view_connect}}</span>   </div>   <div class="rs-bubble-expandable">     <!-- error -->     <div class="remotestorage-error">       <pre class="rs-status-text rs-error-msg">{{ERROR_MSG}}</pre>       <button class="remotestorage-reset">{{view_get_me_out}}</button>       <p class="rs-centered-text rs-error-plz-report">{{view_error_plz_report}}</p>     </div>     <!-- connected -->     <div class="rs-bubble-text remotestorage-connected">       <strong class="userAddress">{{USER_ADDRESS}}</strong>       <p class="remotestorage-unauthorized">{{view_unauthorized}}</p>       <p class="remotestorage-invalid-key">{{view_invalid_key}}</p>       <form novalidate class="remotestorage-cipher-form">         <input placeholder="Secret key" name="userSecretKey" novalidate>         <button class="rs-cipher" name="rs-cipher" title="cipher" disabled="disabled">           <img>         </button>         <button class="rs-nocipher" name="rs-nocipher" title="no cipher">           <img>         </button>       </form>     </div>     <div class="rs-content remotestorage-connected">       <button class="rs-sync" title="sync"><img></button>       <button class="rs-disconnect" title="disconnect"><img></button>     </div>     <!-- initial -->     <form novalidate class="remotestorage-initial">       <input type="email" placeholder="user@provider.com" name="userAddress" novalidate>       <button class="connect" name="connect" title="connect" disabled="disabled">         <img>       </button>     </form>     <div class="rs-info-msg remotestorage-initial">{{view_info}}</div>   </div> </div> <img class="rs-dropbox rs-backends rs-action" alt="Connect to Dropbox"> <img class="rs-googledrive rs-backends rs-action" alt="Connect to Google Drive"> <img class="rs-cube rs-action"> ',widgetCss:'/** encoding:utf-8 **/ /* RESET */ #remotestorage-widget{text-align:left;}#remotestorage-widget input, #remotestorage-widget button{font-size:11px;}#remotestorage-widget form input[type=email]{margin-bottom:0;/* HTML5 Boilerplate */}#remotestorage-widget form input[type=submit]{margin-top:0;/* HTML5 Boilerplate */}/* /RESET */ #remotestorage-widget, #remotestorage-widget *{-moz-box-sizing:border-box;box-sizing:border-box;}#remotestorage-widget{position:absolute;right:10px;top:10px;font:normal 16px/100% sans-serif !important;user-select:none;-webkit-user-select:none;-moz-user-select:-moz-none;cursor:default;z-index:10000;}#remotestorage-widget .rs-bubble{background:rgba(80, 80, 80, .7);border-radius:5px 15px 5px 5px;color:white;font-size:0.8em;padding:5px;position:absolute;right:3px;top:9px;min-height:24px;white-space:nowrap;text-decoration:none;}.rs-bubble .rs-bubble-text{padding-right:32px;/* make sure the bubble doesn\'t "jump" when initially opening. */ min-width:182px;}#remotestorage-widget .rs-action{cursor:pointer;}/* less obtrusive cube when connected */ #remotestorage-widget.remotestorage-state-connected .rs-cube, #remotestorage-widget.remotestorage-state-busy .rs-cube{opacity:.3;-webkit-transition:opacity .3s ease;-moz-transition:opacity .3s ease;-ms-transition:opacity .3s ease;-o-transition:opacity .3s ease;transition:opacity .3s ease;}#remotestorage-widget.remotestorage-state-connected:hover .rs-cube, #remotestorage-widget.remotestorage-state-busy:hover .rs-cube, #remotestorage-widget.remotestorage-state-connected .rs-bubble:not(.rs-hidden) + .rs-cube{opacity:1 !important;}#remotestorage-widget .rs-backends{position:relative;top:5px;right:0;}#remotestorage-widget .rs-cube{position:relative;top:5px;right:0;}/* pulsing animation for cube when loading */ #remotestorage-widget .rs-cube.remotestorage-loading{-webkit-animation:remotestorage-loading .5s ease-in-out infinite alternate;-moz-animation:remotestorage-loading .5s ease-in-out infinite alternate;-o-animation:remotestorage-loading .5s ease-in-out infinite alternate;-ms-animation:remotestorage-loading .5s ease-in-out infinite alternate;animation:remotestorage-loading .5s ease-in-out infinite alternate;}@-webkit-keyframes remotestorage-loading{to{opacity:.7}}@-moz-keyframes remotestorage-loading{to{opacity:.7}}@-o-keyframes remotestorage-loading{to{opacity:.7}}@-ms-keyframes remotestorage-loading{to{opacity:.7}}@keyframes remotestorage-loading{to{opacity:.7}}#remotestorage-widget a{text-decoration:underline;color:inherit;}#remotestorage-widget form{margin-top:.7em;position:relative;}#remotestorage-widget form input{display:table-cell;vertical-align:top;border:none;border-radius:6px;font-weight:bold;color:white;outline:none;line-height:1.5em;height:2em;}#remotestorage-widget form input:disabled{color:#999;background:#444 !important;cursor:default !important;}#remotestorage-widget form input[type=email]:focus, #remotestorage-widget form input[type=password]:focus{background:#223;}#remotestorage-widget form input[type=email], #remotestorage-widget form input[type=password]{background:#000;width:100%;height:26px;padding:0 30px 0 5px;border-top:1px solid #111;border-bottom:1px solid #999;}#remotestorage-widget form input[type=email]:focus, #remotestorage-widget form input[type=password]:focus{background:#223;}#remotestorage-widget button:focus, #remotestorage-widget input:focus{box-shadow:0 0 4px #ccc;}#remotestorage-widget form input[type=email]::-webkit-input-placeholder, #remotestorage-widget form input[type=password]::-webkit-input-placeholder{color:#999;}#remotestorage-widget form input[type=email]:-moz-placeholder, #remotestorage-widget form input[type=password]:-moz-placeholder{color:#999;}#remotestorage-widget form input[type=email]::-moz-placeholder, #remotestorage-widget form input[type=password]::-moz-placeholder{color:#999;}#remotestorage-widget form input[type=email]:-ms-input-placeholder, #remotestorage-widget form input[type=password]:-ms-input-placeholder{color:#999;}#remotestorage-widget form input[type=submit]{background:#000;cursor:pointer;padding:0 5px;}#remotestorage-widget form input[type=submit]:hover{background:#333;}#remotestorage-widget .rs-info-msg{font-size:10px;color:#eee;margin-top:0.7em;white-space:normal;}#remotestorage-widget .rs-info-msg.last-synced-message{display:inline;white-space:nowrap;margin-bottom:.7em}#remotestorage-widget .rs-info-msg a:hover, #remotestorage-widget .rs-info-msg a:active{color:#fff;}#remotestorage-widget button img{vertical-align:baseline;}#remotestorage-widget button{border:none;border-radius:6px;font-weight:bold;color:white;outline:none;line-height:1.5em;height:26px;width:26px;background:#000;cursor:pointer;margin:0;padding:5px;}#remotestorage-widget button:hover{background:#333;}#remotestorage-widget .rs-bubble button.connect, #remotestorage-widget .rs-bubble button.rs-cipher, #remotestorage-widget .rs-bubble button.rs-nocipher{display:block;background:none;position:absolute;right:0;top:0;opacity:1;/* increase clickable area of connect, rs-cipher & rs-nocipher buttons */ margin:-5px;padding:10px;width:36px;height:36px;}#remotestorage-widget .rs-bubble button.rs-cipher{width:46px;}#remotestorage-widget .rs-bubble button.rs-nocipher{height:26px;margin:0;padding:4px 5px 5px;right:-32px;width:26px;}#remotestorage-widget .rs-bubble button.connect:not([disabled]):hover, #remotestorage-widget .rs-bubble button.rs-cipher:not([disabled]):hover, #remotestorage-widget .rs-bubble button.rs-nocipher:not([disabled]):hover{background:rgba(150,150,150,.5);}#remotestorage-widget .rs-bubble button.connect[disabled], #remotestorage-widget .rs-bubble button.rs-cipher[disabled]{opacity:.5;cursor:default !important;}#remotestorage-widget .rs-bubble button.rs-sync{position:relative;left:-5px;bottom:-5px;padding:4px 4px 0 4px;background:#555;}#remotestorage-widget .rs-bubble button.rs-sync:hover{background:#444;}#remotestorage-widget .rs-bubble button.rs-disconnect{background:#721;position:absolute;right:0;bottom:0;padding:4px 4px 0 4px;}#remotestorage-widget .rs-bubble button.rs-disconnect:hover{background:#921;}#remotestorage-widget .remotestorage-error-info{color:#f92;}#remotestorage-widget .remotestorage-reset{width:100%;background:#721;}#remotestorage-widget .remotestorage-reset:hover{background:#921;}#remotestorage-widget .rs-bubble .rs-content{margin-top:7px;}#remotestorage-widget pre{user-select:initial;-webkit-user-select:initial;-moz-user-select:text;max-width:27em;margin-top:1em;overflow:auto;}#remotestorage-widget .rs-centered-text{text-align:center;}#remotestorage-widget .rs-bubble.rs-hidden{padding-bottom:2px;border-radius:5px 15px 15px 5px;}#remotestorage-widget .rs-error-msg{min-height:5em;}.rs-bubble.rs-hidden .rs-bubble-expandable{display:none;}.remotestorage-state-connected .rs-bubble.rs-hidden{display:none;}.remotestorage-connected{display:none;}.remotestorage-state-connected .remotestorage-connected{display:block;}.remotestorage-cipher-form{display:none;}.remotestorage-cipher .remotestorage-cipher-form{display:block;}.remotestorage-invalid-key{display:none;}.remotestorage-invalid-key.remotestorage-cipher-error{display:block;}.remotestorage-initial{display:none;}.remotestorage-state-initial .remotestorage-initial{display:block;}.remotestorage-error{display:none;}.remotestorage-state-error .remotestorage-error{display:block;}.remotestorage-state-authing .remotestorage-authing{display:block;}.remotestorage-state-offline .remotestorage-connected, .remotestorage-state-offline .remotestorage-offline{display:block;}.remotestorage-unauthorized{display:none;}.remotestorage-state-unauthorized .rs-bubble.rs-hidden{display:none;}.remotestorage-state-unauthorized .remotestorage-connected, .remotestorage-state-unauthorized .remotestorage-unauthorized{display:block;}.remotestorage-state-unauthorized .rs-sync{display:none;}.remotestorage-state-busy .rs-bubble.rs-hidden{display:none;}.remotestorage-state-busy .rs-bubble{display:block;}.remotestorage-state-busy .remotestorage-connected{display:block;}.remotestorage-state-authing .rs-bubble-expandable{display:none;}'
  },function(e){function t(e,t){return RemoteStorage.log("[Widget] Producing stateSetter for",t),function(){RemoteStorage.log("[Widget] Setting state",t,arguments),n&&(localStorage[i]=t),e.view?(e.rs.remote&&e.view.setUserAddress(e.rs.remote.userAddress),e.view.setState(t,arguments)):e._rememberedState=t}}function r(e){return function(r){var o;r instanceof RemoteStorage.DiscoveryError?(console.error("Discovery failed",r,'"'+r.message+'"'),o=t(e,"initial",[r.message])):r instanceof RemoteStorage.SyncError?o=t(e,"offline",[]):r instanceof RemoteStorage.Unauthorized?o=t(e,"unauthorized"):(RemoteStorage.log("[Widget] Unknown error"),o=t(e,"error",[r])),o.apply()}}function o(e){return"GET"!==e.method||!e.isFolder}var n,i="remotestorage:widget:state",s={initial:!0,connected:!0,offline:!0};RemoteStorage.Widget=function(e){var a=this,c=0;if(this.rs=e,this.rs.remote.on("connected",t(this,"connected")),this.rs.on("disconnected",t(this,"initial")),this.rs.on("connecting",t(this,"authing")),this.rs.on("authing",t(this,"authing")),this.rs.on("error",r(this)),this.rs.remote&&(this.rs.remote.on("wire-busy",function(e){o(e)&&(c++,t(a,"busy")())}),this.rs.remote.on("wire-done",function(e){o(e)&&c--,0>=c&&e.success&&t(a,"connected")()})),n){var u=localStorage[i];u&&s[u]&&(this._rememberedState=u)}},RemoteStorage.Widget.prototype={display:function(e){return"string"==typeof e?e={domID:e}:"undefined"==typeof e&&(e={}),this.view||this.setView(new RemoteStorage.Widget.View(this.rs)),this.view.display(e),this},linkWidgetToSync:function(){"object"==typeof this.rs.sync&&"function"==typeof this.rs.sync.sync?this.view.on("sync",this.rs.sync.sync.bind(this.rs.sync)):(RemoteStorage.log("[Widget] typeof this.rs.sync check fail",this.rs.sync),setTimeout(this.linkWidgetToSync.bind(this),1e3))},setView:function(e){this.view=e,this.view.on("connect",function(e){"string"==typeof e?this.rs.connect(e):e.special&&this.rs[e.special].connect(e)}.bind(this)),this.view.on("secret-entered",function(e){this.view.setUserSecretKey(e),t(this,"ciphered")()}.bind(this)),this.view.on("secret-cancelled",function(){t(this,"notciphered")()}.bind(this)),this.view.on("disconnect",this.rs.disconnect.bind(this.rs)),this.linkWidgetToSync();try{this.view.on("reset",function(){var e=RemoteStorage.Authorize.getLocation();this.rs.on("disconnected",e.reload.bind(e)),this.rs.disconnect()}.bind(this))}catch(r){if(!r.message||!r.message.match(/Unknown event/))throw r}this._rememberedState&&(setTimeout(t(this,this._rememberedState),0),delete this._rememberedState)}},RemoteStorage.prototype.displayWidget=function(e){return this.widget.display(e)},RemoteStorage.Widget._rs_init=function(e){n=e.localStorageAvailable(),e.widget||(e.widget=new RemoteStorage.Widget(e))},RemoteStorage.Widget._rs_supported=function(e){return"undefined"!=typeof document}}("undefined"!=typeof window?window:global),function(e){function t(e,t){return e.classList.remove(t)}function r(e,t){return e.classList.add(t)}function o(e){"function"==typeof e.stopPropagation?e.stopPropagation():e.cancelBubble=!0}function n(e,t,r,o){var n=e.querySelector("."+t);if("undefined"!=typeof r){var i=n.querySelector("img");(i||n).src=RemoteStorage.Assets[r]}return n.addEventListener("click",o),n}function i(e){e.target.value?e.target.nextElementSibling.removeAttribute("disabled"):e.target.nextElementSibling.setAttribute("disabled","disabled")}var s=RemoteStorage.I18n.translate;RemoteStorage.Widget.View=function(e){if(this.rs=e,"undefined"==typeof document)throw"Widget not supported";RemoteStorage.eventHandling(this,"connect","secret-entered","secret-cancelled","disconnect","sync","display","reset");for(var t in this.events)this.events[t]=this.events[t].bind(this);this.hideBubbleOnBodyClick=function(e){for(var t=e.target;t!==document.body;t=t.parentElement)if("remotestorage-widget"===t.id)return;this.hideBubble()}.bind(this)},RemoteStorage.Widget.View.prototype={connectGdrive:function(){this._emit("connect",{special:"googledrive"})},connectDropbox:function(){this._emit("connect",{special:"dropbox"})},setState:function(e,t){RemoteStorage.log("[View] widget.view.setState(",e,",",t,");");var r=this.states[e];if("undefined"==typeof r)throw new Error("Bad State assigned to view: "+e);r.apply(this,t)},setUserAddress:function(e){this.userAddress=e||"";var t;this.div&&(t=this.div.querySelector("form.remotestorage-initial").userAddress)&&(t.value=this.userAddress)},setUserSecretKey:function(e){this.userSecretKey=e},toggleBubble:function(e){this.bubble.className.search("rs-hidden")<0?this.hideBubble(e):this.showBubble(e)},hideBubble:function(){r(this.bubble,"rs-hidden"),document.body.removeEventListener("click",this.hideBubbleOnBodyClick)},showBubble:function(e){t(this.bubble,"rs-hidden"),"undefined"!=typeof e&&o(e),document.body.addEventListener("click",this.hideBubbleOnBodyClick),this.div.querySelector(".remotestorage-connected").classList.contains("remotestorage-cipher")&&!this.userSecretKey?this.bubble.querySelector("form.remotestorage-cipher-form").userSecretKey.focus():this.bubble.querySelector("form.remotestorage-initial").userAddress.focus()},display:function(e){if("undefined"!=typeof this.div)return this.div;var t=document.createElement("div"),r=document.createElement("style");if(r.innerHTML=RemoteStorage.Assets.widgetCss,t.id="remotestorage-widget",t.innerHTML=RemoteStorage.Assets.widget,t.appendChild(r),e.domID){var o=document.getElementById(e.domID);if(!o)throw'Failed to find target DOM element with id="'+e.domID+'"';o.appendChild(t)}else document.body.appendChild(t);n(t,"rs-sync","syncIcon",this.events.sync),n(t,"rs-disconnect","disconnectIcon",this.events.disconnect),n(t,"remotestorage-reset",void 0,this.events.reset);n(t,"connect","connectIcon",this.events.connect);this.form=t.querySelector("form.remotestorage-initial");var s=this.form.userAddress;if(s.addEventListener("load",i),s.addEventListener("keyup",i),this.userAddress&&(s.value=this.userAddress),e.encryption){this.cipher=!0;var a=t.querySelector("form.remotestorage-cipher-form").userSecretKey;a.type="password";n(t,"rs-cipher","cipherIcon",this.events["secret-entered"]);a.addEventListener("load",i),a.addEventListener("keyup",i),n(t,"rs-nocipher","nocipherIcon",this.events["secret-cancelled"])}this.cube=n(t,"rs-cube","remoteStorageIcon",this.toggleBubble.bind(this)),n(t,"rs-dropbox","dropbox",this.connectDropbox.bind(this)),n(t,"rs-googledrive","googledrive",this.connectGdrive.bind(this));var c={INPUT:!0,BUTTON:!0,IMG:!0},u=function(e){c[e.target.tagName]||this.div.classList.contains("remotestorage-state-unauthorized")||this.showBubble(e)}.bind(this);return this.bubble=n(t,"rs-bubble",void 0,u),this.hideBubble(),this.div=t,this.states.initial.call(this),this.events.display.call(this),this.div},states:{initial:function(e){var r=this.cube,o=e||s("view_info");r.src=RemoteStorage.Assets.remoteStorageIcon,this._renderTranslatedInitialContent(),e?(r.src=RemoteStorage.Assets.remoteStorageIconError,t(this.cube,"remotestorage-loading"),this.showBubble(),setTimeout(function(){r.src=RemoteStorage.Assets.remoteStorageIcon},2e3)):this.hideBubble(),this.div.className="remotestorage-state-initial",this.userSecretKey&&delete this.userSecretKey;var n=1;this._activateBackend("dropbox")&&(n+=1),this._activateBackend("googledrive")&&(n+=1),this.div.querySelector(".rs-bubble-text").style.paddingRight=32*n+8+"px";var i=this.div.querySelector(".connect");this.form.userAddress.value&&i.removeAttribute("disabled");var a=this.div.querySelector(".rs-info-msg");a.innerHTML=o,e?a.classList.add("remotestorage-error-info"):a.classList.remove("remotestorage-error-info")},authing:function(){this.div.removeEventListener("click",this.events.connect),this.div.className="remotestorage-state-authing",this.div.querySelector(".rs-status-text").innerHTML=s("view_connecting",this.userAddress),r(this.cube,"remotestorage-loading")},connected:function(){var e=this.cube;this.div.className="remotestorage-state-connected",this.div.querySelector(".userAddress").innerHTML=this.userAddress,e.src=RemoteStorage.Assets.remoteStorageIcon,t(e,"remotestorage-loading"),this.cipher&&(this.userSecretKey?this.userSecretKeyError?(e.src=RemoteStorage.Assets.remoteStorageIconError,r(this.div.querySelector(".remotestorage-connected"),"remotestorage-cipher"),r(this.div.querySelector(".remotestorage-invalid-key"),"remotestorage-cipher-error"),this.showBubble(),setTimeout(function(){e.src=RemoteStorage.Assets.remoteStorageIcon},5e3)):(t(this.div.querySelector(".remotestorage-invalid-key"),"remotestorage-cipher-error"),e.src=RemoteStorage.Assets.remoteStorageIconCiphered):(r(this.div.querySelector(".remotestorage-connected"),"remotestorage-cipher"),this.showBubble()));var o={googledrive:this.div.querySelector(".rs-googledrive"),dropbox:this.div.querySelector(".rs-dropbox")};o.googledrive.style.display=o.dropbox.style.display="none",o[this.rs.backend]?(o[this.rs.backend].style.display="inline-block",this.div.querySelector(".rs-bubble-text").style.paddingRight="72px"):this.div.querySelector(".rs-bubble-text").style.paddingRight="40px"},ciphered:function(){this.div.querySelector("form.remotestorage-cipher-form").userSecretKey.value="",t(this.div.querySelector(".remotestorage-invalid-key"),"remotestorage-cipher-error"),t(this.div.querySelector(".remotestorage-connected"),"remotestorage-cipher"),this.cube.src=RemoteStorage.Assets.remoteStorageIconCiphered,this.hideBubble()},notciphered:function(){this.cipher=!1,t(this.div.querySelector(".remotestorage-invalid-key"),"remotestorage-cipher-error"),t(this.div.querySelector(".remotestorage-connected"),"remotestorage-cipher"),this.hideBubble()},busy:function(){this.div.className="remotestorage-state-busy",r(this.cube,"remotestorage-loading")},offline:function(){this.div.className="remotestorage-state-offline",this.cube.src=RemoteStorage.Assets.remoteStorageIconOffline,this.div.querySelector(".rs-status-text").innerHTML=s("view_offline")},error:function(e){var t=e;this.div.className="remotestorage-state-error",this.div.querySelector(".rs-bubble-text").innerHTML="<strong>"+s("view_error_occured")+"</strong>",e instanceof Error&&(t=e.message+"\n\n"+e.stack),this.div.querySelector(".rs-error-msg").textContent=t,this.cube.src=RemoteStorage.Assets.remoteStorageIconError,this.showBubble()},unauthorized:function(){this.div.className="remotestorage-state-unauthorized",this.cube.src=RemoteStorage.Assets.remoteStorageIconError,this.showBubble(),this.div.addEventListener("click",this.events.connect)}},events:{connect:function(e){o(e),e.preventDefault(),this._emit("connect",this.div.querySelector("form.remotestorage-initial").userAddress.value)},"secret-entered":function(e){o(e),e.preventDefault(),this._emit("secret-entered",this.div.querySelector("form.remotestorage-cipher-form").userSecretKey.value)},"secret-cancelled":function(e){o(e),e.preventDefault(),this._emit("secret-cancelled")},sync:function(e){o(e),e.preventDefault(),this._emit("sync")},disconnect:function(e){o(e),e.preventDefault(),this._emit("disconnect")},reset:function(t){t.preventDefault();var r=e.confirm(s("view_confirm_reset"));r&&this._emit("reset")},display:function(e){e&&e.preventDefault(),this._emit("display")}},_renderTranslatedInitialContent:function(){this.div.querySelector(".rs-status-text").innerHTML=s("view_connect"),this.div.querySelector(".remotestorage-reset").innerHTML=s("view_get_me_out"),this.div.querySelector(".rs-error-plz-report").innerHTML=s("view_error_plz_report"),this.div.querySelector(".remotestorage-unauthorized").innerHTML=s("view_unauthorized"),this.div.querySelector(".remotestorage-invalid-key").innerHTML=s("view_invalid_key")},_activateBackend:function(e){var t="rs-"+e;return this.rs.apiKeys[e]?(this.div.querySelector("."+t).style.display="inline-block",!0):(this.div.querySelector("."+t).style.display="none",!1)}}}("undefined"!=typeof window?window:global),function(e,t){"function"==typeof define&&define.amd?define([],t):"undefined"!=typeof module&&module.exports?module.exports=t():e.tv4=t()}(this,function(){function e(e){return encodeURI(e).replace(/%25[0-9][0-9]/g,function(e){return"%"+e.substring(3)})}function t(t){var r="";d[t.charAt(0)]&&(r=t.charAt(0),t=t.substring(1));var o="",n="",i=!0,s=!1,a=!1;"+"===r?i=!1:"."===r?(n=".",o="."):"/"===r?(n="/",o="/"):"#"===r?(n="#",i=!1):";"===r?(n=";",o=";",s=!0,a=!0):"?"===r?(n="?",o="&",s=!0):"&"===r&&(n="&",o="&",s=!0);for(var c=[],u=t.split(","),l=[],h={},p=0;p<u.length;p++){var m=u[p],g=null;if(-1!==m.indexOf(":")){var y=m.split(":");m=y[0],g=parseInt(y[1],10)}for(var v={};f[m.charAt(m.length-1)];)v[m.charAt(m.length-1)]=!0,m=m.substring(0,m.length-1);var b={truncate:g,name:m,suffices:v};l.push(b),h[m]=b,c.push(m)}var M=function(t){for(var r="",c=0,u=0;u<l.length;u++){var h=l[u],d=t(h.name);if(null===d||void 0===d||Array.isArray(d)&&0===d.length||"object"==typeof d&&0===Object.keys(d).length)c++;else if(r+=u===c?n:o||",",Array.isArray(d)){s&&(r+=h.name+"=");for(var f=0;f<d.length;f++)f>0&&(r+=h.suffices["*"]?o||",":",",h.suffices["*"]&&s&&(r+=h.name+"=")),r+=i?encodeURIComponent(d[f]).replace(/!/g,"%21"):e(d[f])}else if("object"==typeof d){s&&!h.suffices["*"]&&(r+=h.name+"=");var p=!0;for(var m in d)p||(r+=h.suffices["*"]?o||",":","),p=!1,r+=i?encodeURIComponent(m).replace(/!/g,"%21"):e(m),r+=h.suffices["*"]?"=":",",r+=i?encodeURIComponent(d[m]).replace(/!/g,"%21"):e(d[m])}else s&&(r+=h.name,a&&""===d||(r+="=")),null!=h.truncate&&(d=d.substring(0,h.truncate)),r+=i?encodeURIComponent(d).replace(/!/g,"%21"):e(d)}return r};return M.varNames=c,{prefix:n,substitution:M}}function r(e){if(!(this instanceof r))return new r(e);for(var o=e.split("{"),n=[o.shift()],i=[],s=[],a=[];o.length>0;){var c=o.shift(),u=c.split("}")[0],l=c.substring(u.length+1),h=t(u);s.push(h.substitution),i.push(h.prefix),n.push(l),a=a.concat(h.substitution.varNames)}this.fill=function(e){for(var t=n[0],r=0;r<s.length;r++){var o=s[r];t+=o(e),t+=n[r+1]}return t},this.varNames=a,this.template=e}function o(e,t){if(e===t)return!0;if(e&&t&&"object"==typeof e&&"object"==typeof t){if(Array.isArray(e)!==Array.isArray(t))return!1;if(Array.isArray(e)){if(e.length!==t.length)return!1;for(var r=0;r<e.length;r++)if(!o(e[r],t[r]))return!1}else{var n;for(n in e)if(void 0===t[n]&&void 0!==e[n])return!1;for(n in t)if(void 0===e[n]&&void 0!==t[n])return!1;for(n in e)if(!o(e[n],t[n]))return!1}return!0}return!1}function n(e){var t=String(e).replace(/^\s+|\s+$/g,"").match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);return t?{href:t[0]||"",protocol:t[1]||"",authority:t[2]||"",host:t[3]||"",hostname:t[4]||"",port:t[5]||"",pathname:t[6]||"",search:t[7]||"",hash:t[8]||""}:null}function i(e,t){function r(e){var t=[];return e.replace(/^(\.\.?(\/|$))+/,"").replace(/\/(\.(\/|$))+/g,"/").replace(/\/\.\.$/,"/../").replace(/\/?[^\/]*/g,function(e){"/.."===e?t.pop():t.push(e)}),t.join("").replace(/^\//,"/"===e.charAt(0)?"/":"")}return t=n(t||""),e=n(e||""),t&&e?(t.protocol||e.protocol)+(t.protocol||t.authority?t.authority:e.authority)+r(t.protocol||t.authority||"/"===t.pathname.charAt(0)?t.pathname:t.pathname?(e.authority&&!e.pathname?"/":"")+e.pathname.slice(0,e.pathname.lastIndexOf("/")+1)+t.pathname:e.pathname)+(t.protocol||t.authority||t.pathname?t.search:t.search||e.search)+t.hash:null}function s(e){return e.split("#")[0]}function a(e,t){if(e&&"object"==typeof e)if(void 0===t?t=e.id:"string"==typeof e.id&&(t=i(t,e.id),e.id=t),Array.isArray(e))for(var r=0;r<e.length;r++)a(e[r],t);else{"string"==typeof e.$ref&&(e.$ref=i(t,e.$ref));for(var o in e)"enum"!==o&&a(e[o],t)}}function c(e){e=e||"en";var t=_[e];return function(e){var r=t[e.code]||M[e.code];if("string"!=typeof r)return"Unknown error code "+e.code+": "+JSON.stringify(e.messageParams);var o=e.params;return r.replace(/\{([^{}]*)\}/g,function(e,t){var r=o[t];return"string"==typeof r||"number"==typeof r?r:e})}}function u(e,t,r,o,n){if(Error.call(this),void 0===e)throw new Error("No error code supplied: "+o);this.message="",this.params=t,this.code=e,this.dataPath=r||"",this.schemaPath=o||"",this.subErrors=n||null;var i=new Error(this.message);if(this.stack=i.stack||i.stacktrace,!this.stack)try{throw i}catch(i){this.stack=i.stack||i.stacktrace}}function l(e,t){if(t.substring(0,e.length)===e){var r=t.substring(e.length);if(t.length>0&&"/"===t.charAt(e.length-1)||"#"===r.charAt(0)||"?"===r.charAt(0))return!0}return!1}function h(e){var t,r,o=new p,n={setErrorReporter:function(e){return"string"==typeof e?this.language(e):(r=e,!0)},addFormat:function(){o.addFormat.apply(o,arguments)},language:function(e){return e?(_[e]||(e=e.split("-")[0]),_[e]?(t=e,e):!1):t},addLanguage:function(e,t){var r;for(r in y)t[r]&&!t[y[r]]&&(t[y[r]]=t[r]);var o=e.split("-")[0];if(_[o]){_[e]=Object.create(_[o]);for(r in t)"undefined"==typeof _[o][r]&&(_[o][r]=t[r]),_[e][r]=t[r]}else _[e]=t,_[o]=t;return this},freshApi:function(e){var t=h();return e&&t.language(e),t},validate:function(e,n,i,s){var a=c(t),u=r?function(e,t,o){return r(e,t,o)||a(e,t,o)}:a,l=new p(o,!1,u,i,s);"string"==typeof n&&(n={$ref:n}),l.addSchema("",n);var h=l.validateAll(e,n,null,null,"");return!h&&s&&(h=l.banUnknownProperties(e,n)),this.error=h,this.missing=l.missing,this.valid=null===h,this.valid},validateResult:function(){var e={};return this.validate.apply(e,arguments),e},validateMultiple:function(e,n,i,s){var a=c(t),u=r?function(e,t,o){return r(e,t,o)||a(e,t,o)}:a,l=new p(o,!0,u,i,s);"string"==typeof n&&(n={$ref:n}),l.addSchema("",n),l.validateAll(e,n,null,null,""),s&&l.banUnknownProperties(e,n);var h={};return h.errors=l.errors,h.missing=l.missing,h.valid=0===h.errors.length,h},addSchema:function(){return o.addSchema.apply(o,arguments)},getSchema:function(){return o.getSchema.apply(o,arguments)},getSchemaMap:function(){return o.getSchemaMap.apply(o,arguments)},getSchemaUris:function(){return o.getSchemaUris.apply(o,arguments)},getMissingUris:function(){return o.getMissingUris.apply(o,arguments)},dropSchemas:function(){o.dropSchemas.apply(o,arguments)},defineKeyword:function(){o.defineKeyword.apply(o,arguments)},defineError:function(e,t,r){if("string"!=typeof e||!/^[A-Z]+(_[A-Z]+)*$/.test(e))throw new Error("Code name must be a string in UPPER_CASE_WITH_UNDERSCORES");if("number"!=typeof t||t%1!==0||1e4>t)throw new Error("Code number must be an integer > 10000");if("undefined"!=typeof y[e])throw new Error("Error already defined: "+e+" as "+y[e]);if("undefined"!=typeof v[t])throw new Error("Error code already used: "+v[t]+" as "+t);y[e]=t,v[t]=e,M[e]=M[t]=r;for(var o in _){var n=_[o];n[e]&&(n[t]=n[t]||n[e])}},reset:function(){o.reset(),this.error=null,this.missing=[],this.valid=!0},missing:[],error:null,valid:!0,normSchema:a,resolveUrl:i,getDocumentUri:s,errorCodes:y};return n.language(e||"en"),n}Object.keys||(Object.keys=function(){var e=Object.prototype.hasOwnProperty,t=!{toString:null}.propertyIsEnumerable("toString"),r=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],o=r.length;return function(n){if("object"!=typeof n&&"function"!=typeof n||null===n)throw new TypeError("Object.keys called on non-object");var i=[];for(var s in n)e.call(n,s)&&i.push(s);if(t)for(var a=0;o>a;a++)e.call(n,r[a])&&i.push(r[a]);return i}}()),Object.create||(Object.create=function(){function e(){}return function(t){if(1!==arguments.length)throw new Error("Object.create implementation only accepts one parameter.");return e.prototype=t,new e}}()),Array.isArray||(Array.isArray=function(e){return"[object Array]"===Object.prototype.toString.call(e)}),Array.prototype.indexOf||(Array.prototype.indexOf=function(e){if(null===this)throw new TypeError;var t=Object(this),r=t.length>>>0;if(0===r)return-1;var o=0;if(arguments.length>1&&(o=Number(arguments[1]),o!==o?o=0:0!==o&&o!==1/0&&o!==-(1/0)&&(o=(o>0||-1)*Math.floor(Math.abs(o)))),o>=r)return-1;for(var n=o>=0?o:Math.max(r-Math.abs(o),0);r>n;n++)if(n in t&&t[n]===e)return n;return-1}),Object.isFrozen||(Object.isFrozen=function(e){for(var t="tv4_test_frozen_key";e.hasOwnProperty(t);)t+=Math.random();try{return e[t]=!0,delete e[t],!1}catch(r){return!0}});var d={"+":!0,"#":!0,".":!0,"/":!0,";":!0,"?":!0,"&":!0},f={"*":!0};r.prototype={toString:function(){return this.template},fillFromObject:function(e){return this.fill(function(t){return e[t]})}};var p=function(e,t,r,o,n){if(this.missing=[],this.missingMap={},this.formatValidators=e?Object.create(e.formatValidators):{},this.schemas=e?Object.create(e.schemas):{},this.collectMultiple=t,this.errors=[],this.handleError=t?this.collectError:this.returnError,o&&(this.checkRecursive=!0,this.scanned=[],this.scannedFrozen=[],this.scannedFrozenSchemas=[],this.scannedFrozenValidationErrors=[],this.validatedSchemasKey="tv4_validation_id",this.validationErrorsKey="tv4_validation_errors_id"),n&&(this.trackUnknownProperties=!0,this.knownPropertyPaths={},this.unknownPropertyPaths={}),this.errorReporter=r||c("en"),"string"==typeof this.errorReporter)throw new Error("debug");if(this.definedKeywords={},e)for(var i in e.definedKeywords)this.definedKeywords[i]=e.definedKeywords[i].slice(0)};p.prototype.defineKeyword=function(e,t){this.definedKeywords[e]=this.definedKeywords[e]||[],this.definedKeywords[e].push(t)},p.prototype.createError=function(e,t,r,o,n,i,s){var a=new u(e,t,r,o,n);return a.message=this.errorReporter(a,i,s),a},p.prototype.returnError=function(e){return e},p.prototype.collectError=function(e){return e&&this.errors.push(e),null},p.prototype.prefixErrors=function(e,t,r){for(var o=e;o<this.errors.length;o++)this.errors[o]=this.errors[o].prefixWith(t,r);return this},p.prototype.banUnknownProperties=function(e,t){for(var r in this.unknownPropertyPaths){var o=this.createError(y.UNKNOWN_PROPERTY,{path:r},r,"",null,e,t),n=this.handleError(o);if(n)return n}return null},p.prototype.addFormat=function(e,t){if("object"==typeof e){for(var r in e)this.addFormat(r,e[r]);return this}this.formatValidators[e]=t},p.prototype.resolveRefs=function(e,t){if(void 0!==e.$ref){if(t=t||{},t[e.$ref])return this.createError(y.CIRCULAR_REFERENCE,{urls:Object.keys(t).join(", ")},"","",null,void 0,e);t[e.$ref]=!0,e=this.getSchema(e.$ref,t)}return e},p.prototype.getSchema=function(e,t){var r;if(void 0!==this.schemas[e])return r=this.schemas[e],this.resolveRefs(r,t);var o=e,n="";if(-1!==e.indexOf("#")&&(n=e.substring(e.indexOf("#")+1),o=e.substring(0,e.indexOf("#"))),"object"==typeof this.schemas[o]){r=this.schemas[o];var i=decodeURIComponent(n);if(""===i)return this.resolveRefs(r,t);if("/"!==i.charAt(0))return;for(var s=i.split("/").slice(1),a=0;a<s.length;a++){var c=s[a].replace(/~1/g,"/").replace(/~0/g,"~");if(void 0===r[c]){r=void 0;break}r=r[c]}if(void 0!==r)return this.resolveRefs(r,t)}void 0===this.missing[o]&&(this.missing.push(o),this.missing[o]=o,this.missingMap[o]=o)},p.prototype.searchSchemas=function(e,t){if(Array.isArray(e))for(var r=0;r<e.length;r++)this.searchSchemas(e[r],t);else if(e&&"object"==typeof e){"string"==typeof e.id&&l(t,e.id)&&void 0===this.schemas[e.id]&&(this.schemas[e.id]=e);for(var o in e)if("enum"!==o)if("object"==typeof e[o])this.searchSchemas(e[o],t);else if("$ref"===o){var n=s(e[o]);n&&void 0===this.schemas[n]&&void 0===this.missingMap[n]&&(this.missingMap[n]=n)}}},p.prototype.addSchema=function(e,t){if("string"!=typeof e||"undefined"==typeof t){if("object"!=typeof e||"string"!=typeof e.id)return;t=e,e=t.id}e===s(e)+"#"&&(e=s(e)),this.schemas[e]=t,delete this.missingMap[e],a(t,e),this.searchSchemas(t,e)},p.prototype.getSchemaMap=function(){var e={};for(var t in this.schemas)e[t]=this.schemas[t];return e},p.prototype.getSchemaUris=function(e){var t=[];for(var r in this.schemas)e&&!e.test(r)||t.push(r);return t},p.prototype.getMissingUris=function(e){var t=[];for(var r in this.missingMap)e&&!e.test(r)||t.push(r);return t},p.prototype.dropSchemas=function(){this.schemas={},this.reset()},p.prototype.reset=function(){this.missing=[],this.missingMap={},this.errors=[]},p.prototype.validateAll=function(e,t,r,o,n){var i;if(t=this.resolveRefs(t),!t)return null;if(t instanceof u)return this.errors.push(t),t;var s,a=this.errors.length,c=null,l=null;if(this.checkRecursive&&e&&"object"==typeof e){if(i=!this.scanned.length,e[this.validatedSchemasKey]){var h=e[this.validatedSchemasKey].indexOf(t);if(-1!==h)return this.errors=this.errors.concat(e[this.validationErrorsKey][h]),null}if(Object.isFrozen(e)&&(s=this.scannedFrozen.indexOf(e),-1!==s)){var d=this.scannedFrozenSchemas[s].indexOf(t);if(-1!==d)return this.errors=this.errors.concat(this.scannedFrozenValidationErrors[s][d]),null}if(this.scanned.push(e),Object.isFrozen(e))-1===s&&(s=this.scannedFrozen.length,this.scannedFrozen.push(e),this.scannedFrozenSchemas.push([])),c=this.scannedFrozenSchemas[s].length,this.scannedFrozenSchemas[s][c]=t,this.scannedFrozenValidationErrors[s][c]=[];else{if(!e[this.validatedSchemasKey])try{Object.defineProperty(e,this.validatedSchemasKey,{value:[],configurable:!0}),Object.defineProperty(e,this.validationErrorsKey,{value:[],configurable:!0})}catch(f){e[this.validatedSchemasKey]=[],e[this.validationErrorsKey]=[]}l=e[this.validatedSchemasKey].length,e[this.validatedSchemasKey][l]=t,e[this.validationErrorsKey][l]=[]}}var p=this.errors.length,m=this.validateBasic(e,t,n)||this.validateNumeric(e,t,n)||this.validateString(e,t,n)||this.validateArray(e,t,n)||this.validateObject(e,t,n)||this.validateCombinations(e,t,n)||this.validateHypermedia(e,t,n)||this.validateFormat(e,t,n)||this.validateDefinedKeywords(e,t,n)||null;if(i){for(;this.scanned.length;){var g=this.scanned.pop();delete g[this.validatedSchemasKey]}this.scannedFrozen=[],this.scannedFrozenSchemas=[]}if(m||p!==this.errors.length)for(;r&&r.length||o&&o.length;){var y=r&&r.length?""+r.pop():null,v=o&&o.length?""+o.pop():null;m&&(m=m.prefixWith(y,v)),this.prefixErrors(p,y,v)}return null!==c?this.scannedFrozenValidationErrors[s][c]=this.errors.slice(a):null!==l&&(e[this.validationErrorsKey][l]=this.errors.slice(a)),this.handleError(m)},p.prototype.validateFormat=function(e,t){if("string"!=typeof t.format||!this.formatValidators[t.format])return null;var r=this.formatValidators[t.format].call(null,e,t);return"string"==typeof r||"number"==typeof r?this.createError(y.FORMAT_CUSTOM,{message:r},"","/format",null,e,t):r&&"object"==typeof r?this.createError(y.FORMAT_CUSTOM,{message:r.message||"?"},r.dataPath||"",r.schemaPath||"/format",null,e,t):null},p.prototype.validateDefinedKeywords=function(e,t,r){for(var o in this.definedKeywords)if("undefined"!=typeof t[o])for(var n=this.definedKeywords[o],i=0;i<n.length;i++){var s=n[i],a=s(e,t[o],t,r);if("string"==typeof a||"number"==typeof a)return this.createError(y.KEYWORD_CUSTOM,{key:o,message:a},"","",null,e,t).prefixWith(null,o);if(a&&"object"==typeof a){var c=a.code;if("string"==typeof c){if(!y[c])throw new Error("Undefined error code (use defineError): "+c);c=y[c]}else"number"!=typeof c&&(c=y.KEYWORD_CUSTOM);var u="object"==typeof a.message?a.message:{key:o,message:a.message||"?"},l=a.schemaPath||"/"+o.replace(/~/g,"~0").replace(/\//g,"~1");return this.createError(c,u,a.dataPath||null,l,null,e,t)}}return null},p.prototype.validateBasic=function(e,t,r){var o;return(o=this.validateType(e,t,r))?o.prefixWith(null,"type"):(o=this.validateEnum(e,t,r))?o.prefixWith(null,"type"):null},p.prototype.validateType=function(e,t){if(void 0===t.type)return null;var r=typeof e;null===e?r="null":Array.isArray(e)&&(r="array");var o=t.type;Array.isArray(o)||(o=[o]);for(var n=0;n<o.length;n++){var i=o[n];if(i===r||"integer"===i&&"number"===r&&e%1===0)return null}return this.createError(y.INVALID_TYPE,{type:r,expected:o.join("/")},"","",null,e,t)},p.prototype.validateEnum=function(e,t){if(void 0===t["enum"])return null;for(var r=0;r<t["enum"].length;r++){var n=t["enum"][r];if(o(e,n))return null}return this.createError(y.ENUM_MISMATCH,{value:"undefined"!=typeof JSON?JSON.stringify(e):e},"","",null,e,t)},p.prototype.validateNumeric=function(e,t,r){return this.validateMultipleOf(e,t,r)||this.validateMinMax(e,t,r)||this.validateNaN(e,t,r)||null};var m=Math.pow(2,-51),g=1-m;p.prototype.validateMultipleOf=function(e,t){var r=t.multipleOf||t.divisibleBy;if(void 0===r)return null;if("number"==typeof e){var o=e/r%1;if(o>=m&&g>o)return this.createError(y.NUMBER_MULTIPLE_OF,{value:e,multipleOf:r},"","",null,e,t)}return null},p.prototype.validateMinMax=function(e,t){if("number"!=typeof e)return null;if(void 0!==t.minimum){if(e<t.minimum)return this.createError(y.NUMBER_MINIMUM,{value:e,minimum:t.minimum},"","/minimum",null,e,t);if(t.exclusiveMinimum&&e===t.minimum)return this.createError(y.NUMBER_MINIMUM_EXCLUSIVE,{value:e,minimum:t.minimum},"","/exclusiveMinimum",null,e,t)}if(void 0!==t.maximum){if(e>t.maximum)return this.createError(y.NUMBER_MAXIMUM,{value:e,maximum:t.maximum},"","/maximum",null,e,t);if(t.exclusiveMaximum&&e===t.maximum)return this.createError(y.NUMBER_MAXIMUM_EXCLUSIVE,{value:e,maximum:t.maximum},"","/exclusiveMaximum",null,e,t)}return null},p.prototype.validateNaN=function(e,t){return"number"!=typeof e?null:isNaN(e)===!0||e===1/0||e===-(1/0)?this.createError(y.NUMBER_NOT_A_NUMBER,{value:e},"","/type",null,e,t):null},p.prototype.validateString=function(e,t,r){return this.validateStringLength(e,t,r)||this.validateStringPattern(e,t,r)||null},p.prototype.validateStringLength=function(e,t){return"string"!=typeof e?null:void 0!==t.minLength&&e.length<t.minLength?this.createError(y.STRING_LENGTH_SHORT,{length:e.length,minimum:t.minLength},"","/minLength",null,e,t):void 0!==t.maxLength&&e.length>t.maxLength?this.createError(y.STRING_LENGTH_LONG,{length:e.length,maximum:t.maxLength},"","/maxLength",null,e,t):null},p.prototype.validateStringPattern=function(e,t){if("string"!=typeof e||"string"!=typeof t.pattern&&!(t.pattern instanceof RegExp))return null;var r;if(t.pattern instanceof RegExp)r=t.pattern;else{var o,n="",i=t.pattern.match(/^\/(.+)\/([img]*)$/);i?(o=i[1],n=i[2]):o=t.pattern,r=new RegExp(o,n)}return r.test(e)?null:this.createError(y.STRING_PATTERN,{pattern:t.pattern},"","/pattern",null,e,t)},p.prototype.validateArray=function(e,t,r){return Array.isArray(e)?this.validateArrayLength(e,t,r)||this.validateArrayUniqueItems(e,t,r)||this.validateArrayItems(e,t,r)||null:null},p.prototype.validateArrayLength=function(e,t){var r;return void 0!==t.minItems&&e.length<t.minItems&&(r=this.createError(y.ARRAY_LENGTH_SHORT,{length:e.length,minimum:t.minItems},"","/minItems",null,e,t),this.handleError(r))?r:void 0!==t.maxItems&&e.length>t.maxItems&&(r=this.createError(y.ARRAY_LENGTH_LONG,{length:e.length,maximum:t.maxItems},"","/maxItems",null,e,t),this.handleError(r))?r:null},p.prototype.validateArrayUniqueItems=function(e,t){if(t.uniqueItems)for(var r=0;r<e.length;r++)for(var n=r+1;n<e.length;n++)if(o(e[r],e[n])){var i=this.createError(y.ARRAY_UNIQUE,{match1:r,match2:n},"","/uniqueItems",null,e,t);if(this.handleError(i))return i}return null},p.prototype.validateArrayItems=function(e,t,r){if(void 0===t.items)return null;var o,n;if(Array.isArray(t.items)){for(n=0;n<e.length;n++)if(n<t.items.length){if(o=this.validateAll(e[n],t.items[n],[n],["items",n],r+"/"+n))return o}else if(void 0!==t.additionalItems)if("boolean"==typeof t.additionalItems){if(!t.additionalItems&&(o=this.createError(y.ARRAY_ADDITIONAL_ITEMS,{},"/"+n,"/additionalItems",null,e,t),this.handleError(o)))return o}else if(o=this.validateAll(e[n],t.additionalItems,[n],["additionalItems"],r+"/"+n))return o}else for(n=0;n<e.length;n++)if(o=this.validateAll(e[n],t.items,[n],["items"],r+"/"+n))return o;return null},p.prototype.validateObject=function(e,t,r){return"object"!=typeof e||null===e||Array.isArray(e)?null:this.validateObjectMinMaxProperties(e,t,r)||this.validateObjectRequiredProperties(e,t,r)||this.validateObjectProperties(e,t,r)||this.validateObjectDependencies(e,t,r)||null},p.prototype.validateObjectMinMaxProperties=function(e,t){var r,o=Object.keys(e);return void 0!==t.minProperties&&o.length<t.minProperties&&(r=this.createError(y.OBJECT_PROPERTIES_MINIMUM,{
  propertyCount:o.length,minimum:t.minProperties},"","/minProperties",null,e,t),this.handleError(r))?r:void 0!==t.maxProperties&&o.length>t.maxProperties&&(r=this.createError(y.OBJECT_PROPERTIES_MAXIMUM,{propertyCount:o.length,maximum:t.maxProperties},"","/maxProperties",null,e,t),this.handleError(r))?r:null},p.prototype.validateObjectRequiredProperties=function(e,t){if(void 0!==t.required)for(var r=0;r<t.required.length;r++){var o=t.required[r];if(void 0===e[o]){var n=this.createError(y.OBJECT_REQUIRED,{key:o},"","/required/"+r,null,e,t);if(this.handleError(n))return n}}return null},p.prototype.validateObjectProperties=function(e,t,r){var o;for(var n in e){var i=r+"/"+n.replace(/~/g,"~0").replace(/\//g,"~1"),s=!1;if(void 0!==t.properties&&void 0!==t.properties[n]&&(s=!0,o=this.validateAll(e[n],t.properties[n],[n],["properties",n],i)))return o;if(void 0!==t.patternProperties)for(var a in t.patternProperties){var c=new RegExp(a);if(c.test(n)&&(s=!0,o=this.validateAll(e[n],t.patternProperties[a],[n],["patternProperties",a],i)))return o}if(s)this.trackUnknownProperties&&(this.knownPropertyPaths[i]=!0,delete this.unknownPropertyPaths[i]);else if(void 0!==t.additionalProperties){if(this.trackUnknownProperties&&(this.knownPropertyPaths[i]=!0,delete this.unknownPropertyPaths[i]),"boolean"==typeof t.additionalProperties){if(!t.additionalProperties&&(o=this.createError(y.OBJECT_ADDITIONAL_PROPERTIES,{key:n},"","/additionalProperties",null,e,t).prefixWith(n,null),this.handleError(o)))return o}else if(o=this.validateAll(e[n],t.additionalProperties,[n],["additionalProperties"],i))return o}else this.trackUnknownProperties&&!this.knownPropertyPaths[i]&&(this.unknownPropertyPaths[i]=!0)}return null},p.prototype.validateObjectDependencies=function(e,t,r){var o;if(void 0!==t.dependencies)for(var n in t.dependencies)if(void 0!==e[n]){var i=t.dependencies[n];if("string"==typeof i){if(void 0===e[i]&&(o=this.createError(y.OBJECT_DEPENDENCY_KEY,{key:n,missing:i},"","",null,e,t).prefixWith(null,n).prefixWith(null,"dependencies"),this.handleError(o)))return o}else if(Array.isArray(i))for(var s=0;s<i.length;s++){var a=i[s];if(void 0===e[a]&&(o=this.createError(y.OBJECT_DEPENDENCY_KEY,{key:n,missing:a},"","/"+s,null,e,t).prefixWith(null,n).prefixWith(null,"dependencies"),this.handleError(o)))return o}else if(o=this.validateAll(e,i,[],["dependencies",n],r))return o}return null},p.prototype.validateCombinations=function(e,t,r){return this.validateAllOf(e,t,r)||this.validateAnyOf(e,t,r)||this.validateOneOf(e,t,r)||this.validateNot(e,t,r)||null},p.prototype.validateAllOf=function(e,t,r){if(void 0===t.allOf)return null;for(var o,n=0;n<t.allOf.length;n++){var i=t.allOf[n];if(o=this.validateAll(e,i,[],["allOf",n],r))return o}return null},p.prototype.validateAnyOf=function(e,t,r){if(void 0===t.anyOf)return null;var o,n,i=[],s=this.errors.length;this.trackUnknownProperties&&(o=this.unknownPropertyPaths,n=this.knownPropertyPaths);for(var a=!0,c=0;c<t.anyOf.length;c++){this.trackUnknownProperties&&(this.unknownPropertyPaths={},this.knownPropertyPaths={});var u=t.anyOf[c],l=this.errors.length,h=this.validateAll(e,u,[],["anyOf",c],r);if(null===h&&l===this.errors.length){if(this.errors=this.errors.slice(0,s),this.trackUnknownProperties){for(var d in this.knownPropertyPaths)n[d]=!0,delete o[d];for(var f in this.unknownPropertyPaths)n[f]||(o[f]=!0);a=!1;continue}return null}h&&i.push(h.prefixWith(null,""+c).prefixWith(null,"anyOf"))}return this.trackUnknownProperties&&(this.unknownPropertyPaths=o,this.knownPropertyPaths=n),a?(i=i.concat(this.errors.slice(s)),this.errors=this.errors.slice(0,s),this.createError(y.ANY_OF_MISSING,{},"","/anyOf",i,e,t)):void 0},p.prototype.validateOneOf=function(e,t,r){if(void 0===t.oneOf)return null;var o,n,i=null,s=[],a=this.errors.length;this.trackUnknownProperties&&(o=this.unknownPropertyPaths,n=this.knownPropertyPaths);for(var c=0;c<t.oneOf.length;c++){this.trackUnknownProperties&&(this.unknownPropertyPaths={},this.knownPropertyPaths={});var u=t.oneOf[c],l=this.errors.length,h=this.validateAll(e,u,[],["oneOf",c],r);if(null===h&&l===this.errors.length){if(null!==i)return this.errors=this.errors.slice(0,a),this.createError(y.ONE_OF_MULTIPLE,{index1:i,index2:c},"","/oneOf",null,e,t);if(i=c,this.trackUnknownProperties){for(var d in this.knownPropertyPaths)n[d]=!0,delete o[d];for(var f in this.unknownPropertyPaths)n[f]||(o[f]=!0)}}else h&&s.push(h)}return this.trackUnknownProperties&&(this.unknownPropertyPaths=o,this.knownPropertyPaths=n),null===i?(s=s.concat(this.errors.slice(a)),this.errors=this.errors.slice(0,a),this.createError(y.ONE_OF_MISSING,{},"","/oneOf",s,e,t)):(this.errors=this.errors.slice(0,a),null)},p.prototype.validateNot=function(e,t,r){if(void 0===t.not)return null;var o,n,i=this.errors.length;this.trackUnknownProperties&&(o=this.unknownPropertyPaths,n=this.knownPropertyPaths,this.unknownPropertyPaths={},this.knownPropertyPaths={});var s=this.validateAll(e,t.not,null,null,r),a=this.errors.slice(i);return this.errors=this.errors.slice(0,i),this.trackUnknownProperties&&(this.unknownPropertyPaths=o,this.knownPropertyPaths=n),null===s&&0===a.length?this.createError(y.NOT_PASSED,{},"","/not",null,e,t):null},p.prototype.validateHypermedia=function(e,t,o){if(!t.links)return null;for(var n,i=0;i<t.links.length;i++){var s=t.links[i];if("describedby"===s.rel){for(var a=new r(s.href),c=!0,u=0;u<a.varNames.length;u++)if(!(a.varNames[u]in e)){c=!1;break}if(c){var l=a.fillFromObject(e),h={$ref:l};if(n=this.validateAll(e,h,[],["links",i],o))return n}}}};var y={INVALID_TYPE:0,ENUM_MISMATCH:1,ANY_OF_MISSING:10,ONE_OF_MISSING:11,ONE_OF_MULTIPLE:12,NOT_PASSED:13,NUMBER_MULTIPLE_OF:100,NUMBER_MINIMUM:101,NUMBER_MINIMUM_EXCLUSIVE:102,NUMBER_MAXIMUM:103,NUMBER_MAXIMUM_EXCLUSIVE:104,NUMBER_NOT_A_NUMBER:105,STRING_LENGTH_SHORT:200,STRING_LENGTH_LONG:201,STRING_PATTERN:202,OBJECT_PROPERTIES_MINIMUM:300,OBJECT_PROPERTIES_MAXIMUM:301,OBJECT_REQUIRED:302,OBJECT_ADDITIONAL_PROPERTIES:303,OBJECT_DEPENDENCY_KEY:304,ARRAY_LENGTH_SHORT:400,ARRAY_LENGTH_LONG:401,ARRAY_UNIQUE:402,ARRAY_ADDITIONAL_ITEMS:403,FORMAT_CUSTOM:500,KEYWORD_CUSTOM:501,CIRCULAR_REFERENCE:600,UNKNOWN_PROPERTY:1e3},v={};for(var b in y)v[y[b]]=b;var M={INVALID_TYPE:"Invalid type: {type} (expected {expected})",ENUM_MISMATCH:"No enum match for: {value}",ANY_OF_MISSING:'Data does not match any schemas from "anyOf"',ONE_OF_MISSING:'Data does not match any schemas from "oneOf"',ONE_OF_MULTIPLE:'Data is valid against more than one schema from "oneOf": indices {index1} and {index2}',NOT_PASSED:'Data matches schema from "not"',NUMBER_MULTIPLE_OF:"Value {value} is not a multiple of {multipleOf}",NUMBER_MINIMUM:"Value {value} is less than minimum {minimum}",NUMBER_MINIMUM_EXCLUSIVE:"Value {value} is equal to exclusive minimum {minimum}",NUMBER_MAXIMUM:"Value {value} is greater than maximum {maximum}",NUMBER_MAXIMUM_EXCLUSIVE:"Value {value} is equal to exclusive maximum {maximum}",NUMBER_NOT_A_NUMBER:"Value {value} is not a valid number",STRING_LENGTH_SHORT:"String is too short ({length} chars), minimum {minimum}",STRING_LENGTH_LONG:"String is too long ({length} chars), maximum {maximum}",STRING_PATTERN:"String does not match pattern: {pattern}",OBJECT_PROPERTIES_MINIMUM:"Too few properties defined ({propertyCount}), minimum {minimum}",OBJECT_PROPERTIES_MAXIMUM:"Too many properties defined ({propertyCount}), maximum {maximum}",OBJECT_REQUIRED:"Missing required property: {key}",OBJECT_ADDITIONAL_PROPERTIES:"Additional properties not allowed",OBJECT_DEPENDENCY_KEY:"Dependency failed - key must exist: {missing} (due to key: {key})",ARRAY_LENGTH_SHORT:"Array is too short ({length}), minimum {minimum}",ARRAY_LENGTH_LONG:"Array is too long ({length}), maximum {maximum}",ARRAY_UNIQUE:"Array items are not unique (indices {match1} and {match2})",ARRAY_ADDITIONAL_ITEMS:"Additional items not allowed",FORMAT_CUSTOM:"Format validation failed ({message})",KEYWORD_CUSTOM:"Keyword failed: {key} ({message})",CIRCULAR_REFERENCE:"Circular $refs: {urls}",UNKNOWN_PROPERTY:"Unknown property (not in schema)"};u.prototype=Object.create(Error.prototype),u.prototype.constructor=u,u.prototype.name="ValidationError",u.prototype.prefixWith=function(e,t){if(null!==e&&(e=e.replace(/~/g,"~0").replace(/\//g,"~1"),this.dataPath="/"+e+this.dataPath),null!==t&&(t=t.replace(/~/g,"~0").replace(/\//g,"~1"),this.schemaPath="/"+t+this.schemaPath),null!==this.subErrors)for(var r=0;r<this.subErrors.length;r++)this.subErrors[r].prefixWith(e,t);return this};var _={},w=h();return w.addLanguage("en-gb",M),w.tv4=w,w});/*!
    Math.uuid.js (v1.4)
    http://www.broofa.com
    mailto:robert@broofa.com
  
    Copyright (c) 2010 Robert Kieffer
    Dual licensed under the MIT and GPL licenses.
  
    ********
  
    Changes within remoteStorage.js:
    2012-10-31:
    - added AMD wrapper <niklas@unhosted.org>
    - moved extensions for Math object into exported object.
  */
  var CHARS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");Math.uuid=function(e,t){var r,o=CHARS,n=[];if(t=t||o.length,e)for(r=0;e>r;r++)n[r]=o[0|Math.random()*t];else{var i;for(n[8]=n[13]=n[18]=n[23]="-",n[14]="4",r=0;36>r;r++)n[r]||(i=0|16*Math.random(),n[r]=o[19==r?3&i|8:i])}return n.join("")},function(e){function t(e,t){console.log("WARNING: "+e+" is deprecated. Use "+t+" instead.")}var r=RemoteStorage;r.BaseClient=function(e,t){if("/"!==t[t.length-1])throw"Not a folder: "+t;"/"===t&&(this.makePath=function(e){return("/"===e[0]?"":"/")+e}),this.storage=e,this.base=t;var o=this.base.split("/");o.length>2?this.moduleName=o[1]:this.moduleName="root",r.eventHandling(this,"change"),this.on=this.on.bind(this),e.onChange(this.base,this._fireChange.bind(this))},r.BaseClient.prototype={extend:function(e){for(var t in e)this[t]=e[t];return this},scope:function(e){return new r.BaseClient(this.storage,this.makePath(e))},getListing:function(e,t){return"string"!=typeof e?e="":e.length>0&&"/"!==e[e.length-1]&&Promise.reject("Not a folder: "+e),this.storage.get(this.makePath(e),t).then(function(e){return 404===e.statusCode?{}:e.body})},getAll:function(e,t){if("string"!=typeof e)e="";else if(e.length>0&&"/"!==e[e.length-1])return Promise.reject("Not a folder: "+e);return this.storage.get(this.makePath(e),t).then(function(r){if(404===r.statusCode)return{};if("object"==typeof r.body){var o=Object.keys(r.body);if(0===o.length)return{};var n=o.map(function(o){return this.storage.get(this.makePath(e+o),t).then(function(e){if("string"==typeof e.body)try{e.body=JSON.parse(e.body)}catch(t){}"object"==typeof e.body&&(r.body[o]=e.body)})}.bind(this));return Promise.all(n).then(function(){return r.body})}}.bind(this))},getFile:function(e,t){return"string"!=typeof e?Promise.reject("Argument 'path' of baseClient.getFile must be a string"):this.storage.get(this.makePath(e),t).then(function(e){return{data:e.body,contentType:e.contentType,revision:e.revision}})},storeFile:function(e,t,r){return"string"!=typeof e?Promise.reject("Argument 'mimeType' of baseClient.storeFile must be a string"):"string"!=typeof t?Promise.reject("Argument 'path' of baseClient.storeFile must be a string"):"string"!=typeof r&&"object"!=typeof r?Promise.reject("Argument 'body' of baseClient.storeFile must be a string, ArrayBuffer, or ArrayBufferView"):(this.storage.access.checkPathPermission(this.makePath(t),"rw")||console.warn("WARNING: Editing a document to which only read access ('r') was claimed"),this.storage.put(this.makePath(t),r,e).then(function(e){return 200===e.statusCode||201===e.statusCode?e.revision:Promise.reject("Request (PUT "+this.makePath(t)+") failed with status: "+e.statusCode)}.bind(this)))},getObject:function(e,t){return"string"!=typeof e?Promise.reject("Argument 'path' of baseClient.getObject must be a string"):this.storage.get(this.makePath(e),t).then(function(t){if("object"==typeof t.body)return t.body;if("string"==typeof t.body)try{return JSON.parse(t.body)}catch(r){throw"Not valid JSON: "+this.makePath(e)}else if("undefined"!=typeof t.body&&200===t.statusCode)return Promise.reject("Not an object: "+this.makePath(e))}.bind(this))},storeObject:function(e,t,r){if("string"!=typeof e)return Promise.reject("Argument 'typeAlias' of baseClient.storeObject must be a string");if("string"!=typeof t)return Promise.reject("Argument 'path' of baseClient.storeObject must be a string");if("object"!=typeof r)return Promise.reject("Argument 'object' of baseClient.storeObject must be an object");this._attachType(r,e);try{var o=this.validate(r);if(!o.valid)return Promise.reject(o)}catch(n){return Promise.reject(n)}return this.storage.put(this.makePath(t),JSON.stringify(r),"application/json; charset=UTF-8").then(function(e){return 200===e.statusCode||201===e.statusCode?e.revision:Promise.reject("Request (PUT "+this.makePath(t)+") failed with status: "+e.statusCode)}.bind(this))},remove:function(e){return"string"!=typeof e?Promise.reject("Argument 'path' of baseClient.remove must be a string"):(this.storage.access.checkPathPermission(this.makePath(e),"rw")||console.warn("WARNING: Removing a document to which only read access ('r') was claimed"),this.storage["delete"](this.makePath(e)))},cache:function(e,r){if("string"!=typeof e)throw"Argument 'path' of baseClient.cache must be a string";if(r===!1?(t("caching strategy <false>",'<"FLUSH">'),r="FLUSH"):void 0===r?r="ALL":"string"!=typeof r&&(t("that caching strategy",'<"ALL">'),r="ALL"),"FLUSH"!==r&&"SEEN"!==r&&"ALL"!==r)throw'Argument \'strategy\' of baseclient.cache must be one of ["FLUSH", "SEEN", "ALL"]';return this.storage.caching.set(this.makePath(e),r),this},flush:function(e){return this.storage.local.flush(e)},makePath:function(e){return this.base+(e||"")},_fireChange:function(e){RemoteStorage.config.changeEvents[e.origin]&&(["new","old","lastCommon"].forEach(function(t){if((!e[t+"ContentType"]||/^application\/(.*)json(.*)/.exec(e[t+"ContentType"]))&&"string"==typeof e[t+"Value"])try{e[t+"Value"]=JSON.parse(e[t+"Value"])}catch(r){}}),this._emit("change",e))},_cleanPath:RemoteStorage.util.cleanPath,getItemURL:function(e){if("string"!=typeof e)throw"Argument 'path' of baseClient.getItemURL must be a string";return this.storage.connected?(e=this._cleanPath(this.makePath(e)),this.storage.remote.href+e):void 0},uuid:function(){return Math.uuid()}},r.BaseClient._rs_init=function(){r.prototype.scope=function(e){if("string"!=typeof e)throw"Argument 'path' of baseClient.scope must be a string";if(!this.access.checkPathPermission(e,"r")){var t=e.replace(/(['\\])/g,"\\$1");console.warn("WARNING: please call remoteStorage.access.claim('"+t+"', 'r') (read only) or remoteStorage.access.claim('"+t+"', 'rw') (read/write) first")}return new r.BaseClient(this,e)}}}("undefined"!=typeof window?window:global),function(e){RemoteStorage.BaseClient.Types={uris:{},schemas:{},aliases:{},declare:function(e,t,r,o){var n=e+"/"+t;if(o["extends"]){var i,s=o["extends"].split("/");i=1===s.length?e+"/"+s.shift():s.join("/");var a=this.uris[i];if(!a)throw"Type '"+n+"' tries to extend unknown schema '"+i+"'";o["extends"]=this.schemas[a]}this.uris[n]=r,this.aliases[r]=n,this.schemas[r]=o},resolveAlias:function(e){return this.uris[e]},getSchema:function(e){return this.schemas[e]},inScope:function(e){var t=e.length,r={};for(var o in this.uris)if(o.substr(0,t+1)===e+"/"){var n=this.uris[o];r[n]=this.schemas[n]}return r}};var t=function(e){var t=new Error("Schema not found: "+e);return t.name="SchemaNotFound",t};t.prototype=Error.prototype,RemoteStorage.BaseClient.Types.SchemaNotFound=t,RemoteStorage.BaseClient.prototype.extend({declareType:function(e,t,r){r||(r=t,t=this._defaultTypeURI(e)),RemoteStorage.BaseClient.Types.declare(this.moduleName,e,t,r)},validate:function(e){var r=RemoteStorage.BaseClient.Types.getSchema(e["@context"]);if(r)return tv4.validateResult(e,r);throw new t(e["@context"])},_defaultTypeURI:function(e){return"http://remotestorage.io/spec/modules/"+encodeURIComponent(this.moduleName)+"/"+encodeURIComponent(e)},_attachType:function(e,t){e["@context"]=RemoteStorage.BaseClient.Types.resolveAlias(this.moduleName+"/"+t)||this._defaultTypeURI(t)}}),Object.defineProperty(RemoteStorage.BaseClient.prototype,"schemas",{configurable:!0,get:function(){return RemoteStorage.BaseClient.Types.inScope(this.moduleName)}})}("undefined"!=typeof window?window:global),function(e){var t=RemoteStorage.util.containingFolder;RemoteStorage.Caching=function(){this.reset()},RemoteStorage.Caching.prototype={pendingActivations:[],set:function(e,t){if("string"!=typeof e)throw new Error("path should be a string");if(!RemoteStorage.util.isFolder(e))throw new Error("path should be a folder");if(this._remoteStorage&&this._remoteStorage.access&&!this._remoteStorage.access.checkPathPermission(e,"r"))throw new Error('No access to path "'+e+'". You have to claim access to it first.');if(!t.match(/^(FLUSH|SEEN|ALL)$/))throw new Error("strategy should be 'FLUSH', 'SEEN', or 'ALL'");this._rootPaths[e]=t,"ALL"===t&&(this.activateHandler?this.activateHandler(e):this.pendingActivations.push(e))},enable:function(e){this.set(e,"ALL")},disable:function(e){this.set(e,"FLUSH")},onActivate:function(e){var t;for(RemoteStorage.log("[Caching] Setting activate handler",e,this.pendingActivations),this.activateHandler=e,t=0;t<this.pendingActivations.length;t++)e(this.pendingActivations[t]);delete this.pendingActivations},checkPath:function(e){return void 0!==this._rootPaths[e]?this._rootPaths[e]:"/"===e?"SEEN":this.checkPath(t(e))},reset:function(){this._rootPaths={},this._remoteStorage=null}},Object.defineProperty(RemoteStorage.prototype,"caching",{configurable:!0,get:function(){var e=new RemoteStorage.Caching;return Object.defineProperty(this,"caching",{value:e}),e}}),RemoteStorage.Caching._rs_init=function(e){this._remoteStorage=e}}("undefined"!=typeof window?window:global),function(e){function t(e,t,r){return{action:e,path:t,promise:r}}function r(e){return e.remote&&e.remote.revision&&!e.remote.itemsMap&&!e.remote.body}function o(e){return e.common&&e.common.revision}function n(){function e(e){var r,o;r=t.getCurrentSyncInterval(),c=!e,o=t.getCurrentSyncInterval(),t._emit("sync-interval-change",{oldValue:r,newValue:o})}var t=this;RemoteStorage.Env.on("background",function(){e(!1)}),RemoteStorage.Env.on("foreground",function(){e(!0)})}function i(e){return"number"==typeof e&&e>1e3&&36e5>e}var s=1e4,a=6e4,c=!1,u=RemoteStorage.util.isFolder,l=RemoteStorage.util.isDocument,h=RemoteStorage.util.equal,d=RemoteStorage.util.deepClone,f=RemoteStorage.util.pathsFromRoot;RemoteStorage.Sync=function(e,t,r,o){this.local=e,this.local.onDiff(function(e){this.addTask(e),this.doTasks()}.bind(this)),this.remote=t,this.access=r,this.caching=o,this._tasks={},this._running={},this._timeStarted={},RemoteStorage.eventHandling(this,"done","req-done"),this.caching.onActivate(function(e){this.addTask(e),this.doTasks()}.bind(this))},RemoteStorage.Sync.prototype={now:function(){return(new Date).getTime()},queueGetRequest:function(e){var t=Promise.defer();return this.remote.connected?this.remote.online?(this.addTask(e,function(){this.local.get(e).then(function(e){return t.resolve(e)})}.bind(this)),this.doTasks()):t.reject("cannot fulfill maxAge requirement - remote is not online"):t.reject("cannot fulfill maxAge requirement - remote is not connected"),t.promise},corruptServerItemsMap:function(e,t){if("object"!=typeof e||Array.isArray(e))return!0;for(var r in e){var o=e[r];if("object"!=typeof o)return!0;if("string"!=typeof o.ETag)return!0;if(u(r)){if(-1!==r.substring(0,r.length-1).indexOf("/"))return!0}else{if(-1!==r.indexOf("/"))return!0;if(t){if("string"!=typeof o["Content-Type"])return!0;if("number"!=typeof o["Content-Length"])return!0}}}return!1},corruptItemsMap:function(e){if("object"!=typeof e||Array.isArray(e))return!0;for(var t in e)if("boolean"!=typeof e[t])return!0;return!1},corruptRevision:function(e){return"object"!=typeof e||Array.isArray(e)||e.revision&&"string"!=typeof e.revision||e.body&&"string"!=typeof e.body&&"object"!=typeof e.body||e.contentType&&"string"!=typeof e.contentType||e.contentLength&&"number"!=typeof e.contentLength||e.timestamp&&"number"!=typeof e.timestamp||e.itemsMap&&this.corruptItemsMap(e.itemsMap)},isCorrupt:function(e){return"object"!=typeof e||Array.isArray(e)||"string"!=typeof e.path||this.corruptRevision(e.common)||e.local&&this.corruptRevision(e.local)||e.remote&&this.corruptRevision(e.remote)||e.push&&this.corruptRevision(e.push)},hasTasks:function(){return Object.getOwnPropertyNames(this._tasks).length>0},collectDiffTasks:function(){var e=0;return this.local.forAllNodes(function(t){e>100||(this.isCorrupt(t)?(RemoteStorage.log("[Sync] WARNING: corrupt node in local cache",t),"object"==typeof t&&t.path&&(this.addTask(t.path),e++)):this.needsFetch(t)&&this.access.checkPathPermission(t.path,"r")?(this.addTask(t.path),e++):l(t.path)&&this.needsPush(t)&&this.access.checkPathPermission(t.path,"rw")&&(this.addTask(t.path),e++))}.bind(this)).then(function(){return e},function(e){throw e})},inConflict:function(e){return e.local&&e.remote&&(void 0!==e.remote.body||e.remote.itemsMap)},needsRefresh:function(e){return e.common?e.common.timestamp?this.now()-e.common.timestamp>s:!0:!1},needsFetch:function(e){return this.inConflict(e)?!0:e.common&&void 0===e.common.itemsMap&&void 0===e.common.body?!0:!(!e.remote||void 0!==e.remote.itemsMap||void 0!==e.remote.body)},needsPush:function(e){return this.inConflict(e)?!1:e.local&&!e.push?!0:void 0},needsRemotePut:function(e){return e.local&&e.local.body},needsRemoteDelete:function(e){return e.local&&e.local.body===!1},getParentPath:function(e){var t=e.match(/^(.*\/)([^\/]+\/?)$/);if(t)return t[1];throw new Error('Not a valid path: "'+e+'"')},deleteChildPathsFromTasks:function(){for(var e in this._tasks)for(var t=f(e),r=1;r<t.length;r++)this._tasks[t[r]]&&delete this._tasks[e]},collectRefreshTasks:function(){return this.local.forAllNodes(function(e){var t;if(this.needsRefresh(e)){try{t=this.getParentPath(e.path)}catch(r){}t&&this.access.checkPathPermission(t,"r")?this.addTask(t):this.access.checkPathPermission(e.path,"r")&&this.addTask(e.path)}}.bind(this)).then(function(){this.deleteChildPathsFromTasks()}.bind(this),function(e){throw e})},flush:function(e){for(var t in e)"FLUSH"===this.caching.checkPath(t)&&e[t]&&!e[t].local&&(RemoteStorage.log("[Sync] Flushing",t),e[t]=void 0);return e},doTask:function(e){return this.local.getNodes([e]).then(function(n){var i=n[e];return"undefined"==typeof i?t("get",e,this.remote.get(e)):r(i)?t("get",e,this.remote.get(e)):this.needsRemotePut(i)?(i.push=d(i.local),i.push.timestamp=this.now(),this.local.setNodes(this.flush(n)).then(function(){var r;return r=o(i)?{ifMatch:i.common.revision}:{ifNoneMatch:"*"},t("put",e,this.remote.put(e,i.push.body,i.push.contentType,r))}.bind(this))):this.needsRemoteDelete(i)?(i.push={body:!1,timestamp:this.now()},this.local.setNodes(this.flush(n)).then(function(){return o(i)?t("delete",e,this.remote["delete"](e,{ifMatch:i.common.revision})):t("get",e,this.remote.get(e))}.bind(this))):o(i)?t("get",e,this.remote.get(e,{ifNoneMatch:i.common.revision})):t("get",e,this.remote.get(e))}.bind(this))},autoMergeFolder:function(e){if(e.remote.itemsMap&&(e.common=e.remote,delete e.remote,e.common.itemsMap)){for(var t in e.common.itemsMap)e.local.itemsMap[t]||(e.local.itemsMap[t]=!1);h(e.local.itemsMap,e.common.itemsMap)&&delete e.local}return e},autoMergeDocument:function(e){return hasNoRemoteChanges=function(e){return e.remote&&e.remote.revision&&e.remote.revision!==e.common.revision?!1:void 0===e.common.body&&e.remote.body===!1||e.remote.body===e.common.body&&e.remote.contentType===e.common.contentType},mergeMutualDeletion=function(e){return e.remote&&e.remote.body===!1&&e.local&&e.local.body===!1&&delete e.local,e},hasNoRemoteChanges(e)?(e=mergeMutualDeletion(e),delete e.remote):void 0!==e.remote.body&&(RemoteStorage.log("[Sync] Emitting keep/revert"),this.local._emitChange({origin:"conflict",path:e.path,oldValue:e.local.body,newValue:e.remote.body,lastCommonValue:e.common.body,oldContentType:e.local.contentType,newContentType:e.remote.contentType,lastCommonContentType:e.common.contentType}),e.remote.body?e.common=e.remote:e.common={},delete e.remote,delete e.local),e},autoMerge:function(e){if(!e.remote)return void(e.common.body&&this.local._emitChange({origin:"remote",path:e.path,oldValue:e.common.body,newValue:void 0,oldContentType:e.common.contentType,newContentType:void 0}));if(e.local)return u(e.path)?this.autoMergeFolder(e):this.autoMergeDocument(e);if(u(e.path))void 0!==e.remote.itemsMap&&(e.common=e.remote,delete e.remote);else if(void 0!==e.remote.body){var t={origin:"remote",path:e.path,oldValue:e.common.body===!1?void 0:e.common.body,newValue:e.remote.body===!1?void 0:e.remote.body,oldContentType:e.common.contentType,newContentType:e.remote.contentType};if((t.oldValue||t.newValue)&&this.local._emitChange(t),!e.remote.body)return;e.common=e.remote,delete e.remote}return e},updateCommonTimestamp:function(e,t){return this.local.getNodes([e]).then(function(r){return r[e]&&r[e].common&&r[e].common.revision===t&&(r[e].common.timestamp=this.now()),this.local.setNodes(this.flush(r))}.bind(this))},markChildren:function(e,t,r,o){var n=[],i={},s={};for(var a in t)n.push(e+a),i[e+a]=t[a];for(var c in o)n.push(e+c);return this.local.getNodes(n).then(function(t){var n,a,c=function(e,t){return e.common.revision!==t&&(!e.remote||e.remote.revision!==t)};for(var l in t)if(a=t[l],i[l])a&&a.common?c(a,i[l].ETag)&&(r[l]=d(a),r[l].remote={revision:i[l].ETag,timestamp:this.now()},r[l]=this.autoMerge(r[l])):(n=this.caching.checkPath(l),"ALL"===n&&(r[l]={path:l,common:{timestamp:this.now()},remote:{revision:i[l].ETag,timestamp:this.now()}})),r[l]&&i[l]["Content-Type"]&&(r[l].remote.contentType=i[l]["Content-Type"]),r[l]&&i[l]["Content-Length"]&&(r[l].remote.contentLength=i[l]["Content-Length"]);else if(o[l.substring(e.length)]&&a&&a.common){if(a.common.itemsMap)for(var f in a.common.itemsMap)s[l+f]=!0;if(a.local&&a.local.itemsMap)for(var p in a.local.itemsMap)s[l+p]=!0;if(a.remote||u(l))r[l]=void 0;else if(r[l]=this.autoMerge(a),"undefined"==typeof r[l]){var m=this.getParentPath(l),g=r[m],y=l.substring(e.length);g&&g.local&&(delete g.local.itemsMap[y],h(g.local.itemsMap,g.common.itemsMap)&&delete g.local)}}return this.deleteRemoteTrees(Object.keys(s),r).then(function(e){return this.local.setNodes(this.flush(e))}.bind(this))}.bind(this))},deleteRemoteTrees:function(e,t){return 0===e.length?Promise.resolve(t):this.local.getNodes(e).then(function(e){var r={};collectSubPaths=function(e,t){if(e&&e.itemsMap)for(var o in e.itemsMap)r[t+o]=!0};for(var o in e){var n=e[o];n&&(u(o)?(collectSubPaths(n.common,o),collectSubPaths(n.local,o)):n.common&&void 0!==typeof n.common.body&&(t[o]=d(n),t[o].remote={body:!1,timestamp:this.now()},t[o]=this.autoMerge(t[o])))}return this.deleteRemoteTrees(Object.keys(r),t).then(function(e){return this.local.setNodes(this.flush(e))}.bind(this))}.bind(this))},completeFetch:function(e,t,r,o){var n,i,s=f(e);return u(e)?n=[e]:(i=s[1],n=[e,i]),this.local.getNodes(n).then(function(n){var s,a,c={},l=n[e],d=function(e){if(e&&e.itemsMap)for(var r in e.itemsMap)t[r]||(c[r]=!0)};if("object"==typeof l&&l.path===e&&"object"==typeof l.common||(l={path:e,common:{}},n[e]=l),l.remote={revision:o,timestamp:this.now()},u(e)){d(l.common),d(l.remote),l.remote.itemsMap={};for(s in t)l.remote.itemsMap[s]=!0}else l.remote.body=t,l.remote.contentType=r,a=n[i],a&&a.local&&a.local.itemsMap&&(s=e.substring(i.length),a.local.itemsMap[s]=!0,h(a.local.itemsMap,a.common.itemsMap)&&delete a.local);return n[e]=this.autoMerge(l),{toBeSaved:n,missingChildren:c}}.bind(this))},completePush:function(e,t,r,o){return this.local.getNodes([e]).then(function(n){var i=n[e];if(!i.push)throw this.stopped=!0,new Error("completePush called but no push version!");return r?(RemoteStorage.log("[Sync] We have a conflict"),i.remote&&i.remote.revision===o||(i.remote={revision:o||"conflict",timestamp:this.now()},delete i.push),n[e]=this.autoMerge(i)):(i.common={revision:o,timestamp:this.now()},"put"===t?(i.common.body=i.push.body,i.common.contentType=i.push.contentType,h(i.local.body,i.push.body)&&i.local.contentType===i.push.contentType&&delete i.local,delete i.push):"delete"===t&&(i.local.body===!1?n[e]=void 0:delete i.push)),this.local.setNodes(this.flush(n))}.bind(this))},dealWithFailure:function(e,t,r){return this.local.getNodes([e]).then(function(t){return t[e]?(delete t[e].push,this.local.setNodes(this.flush(t))):void 0}.bind(this))},interpretStatus:function(e){if("offline"===e||"timeout"===e)return{successful:!1,networkProblems:!0,statusCode:e};var t=Math.floor(e/100);return{successful:2===t||304===e||412===e||404===e,conflict:412===e,unAuth:401===e&&this.remote.token!==RemoteStorage.Authorize.IMPLIED_FAKE_TOKEN||402===e||403===e,notFound:404===e,changed:304!==e,statusCode:e}},handleGetResponse:function(e,t,r,o,n){return t.notFound&&(r=u(e)?{}:!1),t.changed?this.completeFetch(e,r,o,n).then(function(t){return u(e)?this.corruptServerItemsMap(r)?(RemoteStorage.log("[Sync] WARNING: Discarding corrupt folder description from server for "+e),!1):this.markChildren(e,r,t.toBeSaved,t.missingChildren).then(function(){return!0}):this.local.setNodes(this.flush(t.toBeSaved)).then(function(){return!0})}.bind(this)):this.updateCommonTimestamp(e,n).then(function(){return!0})},handleResponse:function(e,t,r){var o=this.interpretStatus(r.statusCode);if(o.successful){if("get"===t)return this.handleGetResponse(e,o,r.body,r.contentType,r.revision);if("put"===t||"delete"===t)return this.completePush(e,t,o.conflict,r.revision).then(function(){return!0});throw new Error("cannot handle response for unknown action",t)}var n;return o.unAuth?n=new RemoteStorage.Unauthorized:o.networkProblems?(n=new RemoteStorage.SyncError("Network request failed."),this.remote.online=!1):n=new Error("HTTP response code "+o.statusCode+" received."),this.dealWithFailure(e,t,o).then(function(){throw remoteStorage._emit("error",n),n})},numThreads:10,finishTask:function(e){if(void 0===e.action)return void delete this._running[e.path];var t=this;return e.promise.then(function(r){return t.handleResponse(e.path,e.action,r)},function(r){return RemoteStorage.log("[Sync] wireclient rejects its promise!",e.path,e.action,r),t.handleResponse(e.path,e.action,{statusCode:"offline"})}).then(function(r){if(delete t._timeStarted[e.path],delete t._running[e.path],t.remote.online=!0,r&&t._tasks[e.path]){for(var o=0;o<t._tasks[e.path].length;o++)t._tasks[e.path][o]();delete t._tasks[e.path]}t._emit("req-done"),t.collectTasks(!1).then(function(){!t.hasTasks()||t.stopped?(RemoteStorage.log("[Sync] Sync is done! Reschedule?",Object.getOwnPropertyNames(t._tasks).length,t.stopped),t.done||(t.done=!0,t._emit("done"))):setTimeout(function(){t.doTasks()},10)})},function(r){console.error("[Sync] Error",r),delete t._timeStarted[e.path],delete t._running[e.path],t._emit("req-done"),t.done||(t.done=!0,t._emit("done"))})},doTasks:function(){var e,t,r,o=0;if(e=this.remote.connected?this.remote.online?this.numThreads:1:0,t=e-Object.getOwnPropertyNames(this._running).length,0>=t)return!0;for(r in this._tasks)if(!this._running[r]&&(this._timeStarted=this.now(),this._running[r]=this.doTask(r),this._running[r].then(this.finishTask.bind(this)),o++,o>=t))return!0;return o>=t},collectTasks:function(e){return this.hasTasks()||this.stopped?Promise.resolve():this.collectDiffTasks().then(function(t){return t||e===!1?Promise.resolve():this.collectRefreshTasks()}.bind(this),function(e){throw e})},addTask:function(e,t){this._tasks[e]||(this._tasks[e]=[]),"function"==typeof t&&this._tasks[e].push(t)},sync:function(){return this.done=!1,this.doTasks()?Promise.resolve():this.collectTasks().then(function(){try{this.doTasks()}catch(e){console.error("[Sync] doTasks error",e)}}.bind(this),function(e){throw console.error("[Sync] Sync error",e),new Error("Local cache unavailable")})}},RemoteStorage.prototype.getSyncInterval=function(){return s},RemoteStorage.prototype.setSyncInterval=function(e){if(!i(e))throw e+" is not a valid sync interval";var t=s;s=parseInt(e,10),this._emit("sync-interval-change",{oldValue:t,newValue:e})},RemoteStorage.prototype.getBackgroundSyncInterval=function(){return a},RemoteStorage.prototype.setBackgroundSyncInterval=function(e){if(!i(e))throw e+" is not a valid sync interval";var t=a;a=parseInt(e,10),this._emit("sync-interval-change",{oldValue:t,newValue:e})},RemoteStorage.prototype.getCurrentSyncInterval=function(){return c?a:s};var p=function(e){var t="Sync failed: ";t+="object"==typeof e&&"message"in e?e.message:e,this.originalError=e,this.message=t};p.prototype=new Error,p.prototype.constructor=p,RemoteStorage.SyncError=p,RemoteStorage.prototype.syncCycle=function(){this.sync.stopped||(this.sync.on("done",function(){RemoteStorage.log("[Sync] Sync done. Setting timer to",this.getCurrentSyncInterval()),this.sync.stopped||(this._syncTimer&&clearTimeout(this._syncTimer),this._syncTimer=setTimeout(this.sync.sync.bind(this.sync),this.getCurrentSyncInterval()))}.bind(this)),this.sync.sync())},RemoteStorage.prototype.stopSync=function(){this.sync?(RemoteStorage.log("[Sync] Stopping sync"),this.sync.stopped=!0):(RemoteStorage.log("[Sync] Will instantiate sync stopped"),this.syncStopped=!0)},RemoteStorage.prototype.startSync=function(){this.sync.stopped=!1,this.syncStopped=!1,this.sync.sync()};var m;RemoteStorage.Sync._rs_init=function(e){m=function(){RemoteStorage.log("[Sync] syncCycleCb calling syncCycle"),RemoteStorage.Env.isBrowser()&&n.bind(e)(),e.sync||(e.sync=new RemoteStorage.Sync(e.local,e.remote,e.access,e.caching),e.syncStopped&&(RemoteStorage.log("[Sync] Instantiating sync stopped"),e.sync.stopped=!0,delete e.syncStopped)),RemoteStorage.log("[Sync] syncCycleCb calling syncCycle"),e.syncCycle()},e.on("ready",m)},RemoteStorage.Sync._rs_cleanup=function(e){e.stopSync(),e.removeEventListener("ready",m)}}("undefined"!=typeof window?window:global),function(){function e(e){if("object"==typeof e&&"string"==typeof e.path)if(n(e.path)){if(e.local&&e.local.itemsMap)return e.local;if(e.common&&e.common.itemsMap)return e.common}else{if(e.local&&e.local.body&&e.local.contentType)return e.local;if(e.common&&e.common.body&&e.common.contentType)return e.common;if(e.body&&e.contentType)return{body:e.body,contentType:e.contentType}}}function t(t,r){var o;for(o in t){if(t[o]&&t[o].remote)return!0;var n=e(t[o]);if(n&&n.timestamp&&(new Date).getTime()-n.timestamp<=r)return!1;if(!n)return!0}return!0}function r(e){var t={path:e,common:{}};return n(e)&&(t.common.itemsMap={}),t}function o(e,t){return e.common||(e.common={itemsMap:{}}),e.common.itemsMap||(e.common.itemsMap={}),e.local||(e.local=s(e.common)),e.local.itemsMap||(e.local.itemsMap=e.common.itemsMap),e.local.itemsMap[t]=!0,e}var n=RemoteStorage.util.isFolder,i=RemoteStorage.util.isDocument,s=RemoteStorage.util.deepClone,a=RemoteStorage.util.equal,c=RemoteStorage.util.pathsFromRoot,u={get:function(r,o,i){var s=this;return"number"==typeof o?s.getNodes(c(r)).then(function(n){var s=e(n[r]);return t(n,o)?i(r):s?{statusCode:200,body:s.body||s.itemsMap,contentType:s.contentType}:{statusCode:404}}):s.getNodes([r]).then(function(t){var o=e(t[r]);if(o){if(n(r))for(var i in o.itemsMap)o.itemsMap.hasOwnProperty(i)&&o.itemsMap[i]===!1&&delete o.itemsMap[i];return{statusCode:200,body:o.body||o.itemsMap,contentType:o.contentType}}return{statusCode:404}})},put:function(t,n,i){function s(t,s){try{for(var a=0,c=t.length;c>a;a++){var u,l=t[a],h=s[l];if(h||(s[l]=h=r(l)),0===a)u=e(h),h.local={body:n,contentType:i,previousBody:u?u.body:void 0,previousContentType:u?u.contentType:void 0};else{var d=t[a-1].substring(l.length);h=o(h,d)}}return s}catch(f){throw RemoteStorage.log("[Cachinglayer] Error during PUT",s,a,f),f}}var a=c(t);return this._updateNodes(a,s)},"delete":function(t){var r=c(t);return this._updateNodes(r,function(t,r){for(var o=0,n=t.length;n>o;o++){var i=t[o],a=r[i];if(!a)throw new Error("Cannot delete non-existing node "+i);if(0===o)previous=e(a),a.local={body:!1,previousBody:previous?previous.body:void 0,previousContentType:previous?previous.contentType:void 0};else{a.local||(a.local=s(a.common));var c=t[o-1].substring(i.length);if(delete a.local.itemsMap[c],Object.getOwnPropertyNames(a.local.itemsMap).length>0)break}}return r})},flush:function(e){var t=this;return t._getAllDescendentPaths(e).then(function(e){return t.getNodes(e)}).then(function(e){for(var r in e){var o=e[r];o&&o.common&&o.local&&t._emitChange({path:o.path,origin:"local",oldValue:o.local.body===!1?void 0:o.local.body,newValue:o.common.body===!1?void 0:o.common.body}),e[r]=void 0}return t.setNodes(e)})},_emitChange:function(e){RemoteStorage.config.changeEvents[e.origin]&&this._emit("change",e)},fireInitial:function(){if(RemoteStorage.config.changeEvents.local){var t=this;t.forAllNodes(function(r){var o;i(r.path)&&(o=e(r),o&&t._emitChange({path:r.path,origin:"local",oldValue:void 0,oldContentType:void 0,newValue:o.body,newContentType:o.contentType}))}).then(function(){t._emit("local-events-done")})}},onDiff:function(e){this.diffHandler=e},migrate:function(e){return"object"!=typeof e||e.common||(e.common={},"string"==typeof e.path?"/"===e.path.substr(-1)&&"object"==typeof e.body&&(e.common.itemsMap=e.body):(e.local||(e.local={}),e.local.body=e.body,e.local.contentType=e.contentType)),e},_updateNodesRunning:!1,_updateNodesQueued:[],_updateNodes:function(e,t){var r=Promise.defer();return this._doUpdateNodes(e,t,r),r.promise},_doUpdateNodes:function(e,t,r){var o=this;return o._updateNodesRunning?void o._updateNodesQueued.push({paths:e,cb:t,promise:r}):(o._updateNodesRunning=!0,void o.getNodes(e).then(function(n){var c,u=s(n),l=[];n=t(e,n);for(var h in n)c=n[h],a(c,u[h])?delete n[h]:i(h)&&(l.push({path:h,origin:"window",oldValue:c.local.previousBody,newValue:c.local.body===!1?void 0:c.local.body,oldContentType:c.local.previousContentType,newContentType:c.local.contentType}),delete c.local.previousBody,delete c.local.previousContentType);o.setNodes(n).then(function(){o._emitChangeEvents(l),r.resolve({statusCode:200})})}).then(function(){return Promise.resolve()},function(e){r.reject(e)}).then(function(){o._updateNodesRunning=!1;var e=o._updateNodesQueued.shift();e&&o._doUpdateNodes(e.paths,e.cb,e.promise)}))},_emitChangeEvents:function(e){for(var t=0,r=e.length;r>t;t++)this._emitChange(e[t]),this.diffHandler&&this.diffHandler(e[t].path)},_getAllDescendentPaths:function(t){var r=this;return n(t)?r.getNodes([t]).then(function(o){var n=[t],i=e(o[t]),s=Object.keys(i.itemsMap),a=s.map(function(e){return r._getAllDescendentPaths(t+e).then(function(e){for(var t=0,r=e.length;r>t;t++)n.push(e[t])})});return Promise.all(a).then(function(){return n})}):Promise.resolve([t])},_getInternals:function(){return{getLatest:e,makeNode:r,isOutdated:t}}};RemoteStorage.cachingLayer=function(e){for(var t in u)e[t]=u[t]}}(),function(e){var t,r=RemoteStorage,o=2,n="remotestorage";r.IndexedDB=function(e){return this.db=e||t,this.db?(r.cachingLayer(this),r.eventHandling(this,"change","local-events-done"),this.getsRunning=0,this.putsRunning=0,this.changesQueued={},void(this.changesRunning={})):void RemoteStorage.log("[IndexedDB] Failed to open DB")},r.IndexedDB.prototype={getNodes:function(e){for(var t=[],r={},o=0,n=e.length;n>o;o++)void 0!==this.changesQueued[e[o]]?r[e[o]]=RemoteStorage.util.deepClone(this.changesQueued[e[o]]||void 0):void 0!==this.changesRunning[e[o]]?r[e[o]]=RemoteStorage.util.deepClone(this.changesRunning[e[o]]||void 0):t.push(e[o]);return t.length>0?this.getNodesFromDb(t).then(function(e){for(var t in r)e[t]=r[t];return e}):Promise.resolve(r)},setNodes:function(e){for(var t in e)this.changesQueued[t]=e[t]||!1;return this.maybeFlush(),Promise.resolve()},maybeFlush:function(){0===this.putsRunning?this.flushChangesQueued():this.commitSlownessWarning||(this.commitSlownessWarning=setInterval(function(){console.log("WARNING: waited more than 10 seconds for previous commit to finish")},1e4))},flushChangesQueued:function(){this.commitSlownessWarning&&(clearInterval(this.commitSlownessWarning),this.commitSlownessWarning=null),Object.keys(this.changesQueued).length>0&&(this.changesRunning=this.changesQueued,this.changesQueued={},this.setNodesInDb(this.changesRunning).then(this.flushChangesQueued.bind(this)))},getNodesFromDb:function(e){var t=Promise.defer(),r=this.db.transaction(["nodes"],"readonly"),o=r.objectStore("nodes"),n={};(new Date).getTime();return this.getsRunning++,e.map(function(e,t){o.get(e).onsuccess=function(t){n[e]=t.target.result}}),r.oncomplete=function(){t.resolve(n),this.getsRunning--}.bind(this),r.onerror=r.onabort=function(){t.reject("get transaction error/abort"),this.getsRunning--}.bind(this),t.promise},setNodesInDb:function(e){var t=Promise.defer(),r=this.db.transaction(["nodes"],"readwrite"),o=r.objectStore("nodes"),n=(new Date).getTime();
  this.putsRunning++,RemoteStorage.log("[IndexedDB] Starting put",e,this.putsRunning);for(var i in e){var s=e[i];if("object"==typeof s)try{o.put(s)}catch(a){throw RemoteStorage.log("[IndexedDB] Error while putting",s,a),a}else try{o["delete"](i)}catch(a){throw RemoteStorage.log("[IndexedDB] Error while removing",o,s,a),a}}return r.oncomplete=function(){this.putsRunning--,RemoteStorage.log("[IndexedDB] Finished put",e,this.putsRunning,(new Date).getTime()-n+"ms"),t.resolve()}.bind(this),r.onerror=function(){this.putsRunning--,t.reject("transaction error")}.bind(this),r.onabort=function(){t.reject("transaction abort"),this.putsRunning--}.bind(this),t.promise},reset:function(e){var t=this.db.name,o=this;this.db.close(),r.IndexedDB.clean(this.db.name,function(){r.IndexedDB.open(t,function(t,r){t?RemoteStorage.log("[IndexedDB] Error while resetting local storage",t):o.db=r,"function"==typeof e&&e(o)})})},forAllNodes:function(e){var t=Promise.defer(),r=this.db.transaction(["nodes"],"readonly"),o=r.objectStore("nodes").openCursor();return o.onsuccess=function(r){var o=r.target.result;o?(e(this.migrate(o.value)),o["continue"]()):t.resolve()}.bind(this),t.promise},closeDB:function(){this.db.close()}},r.IndexedDB.open=function(e,t){var n=setTimeout(function(){t("timeout trying to open db")},1e4);try{var i=indexedDB.open(e,o);i.onerror=function(){RemoteStorage.log("[IndexedDB] Opening DB failed",i),clearTimeout(n),t(i.error)},i.onupgradeneeded=function(e){var t=i.result;RemoteStorage.log("[IndexedDB] Upgrade: from ",e.oldVersion," to ",e.newVersion),1!==e.oldVersion&&(RemoteStorage.log("[IndexedDB] Creating object store: nodes"),t.createObjectStore("nodes",{keyPath:"path"})),RemoteStorage.log("[IndexedDB] Creating object store: changes"),t.createObjectStore("changes",{keyPath:"path"})},i.onsuccess=function(){clearTimeout(n);var o=i.result;return o.objectStoreNames.contains("nodes")&&o.objectStoreNames.contains("changes")?void t(null,i.result):(RemoteStorage.log("[IndexedDB] Missing object store. Resetting the database."),void r.IndexedDB.clean(e,function(){r.IndexedDB.open(e,t)}))}}catch(s){RemoteStorage.log("[IndexedDB] Failed to open database: "+s),RemoteStorage.log("[IndexedDB] Resetting database and trying again."),clearTimeout(n),r.IndexedDB.clean(e,function(){r.IndexedDB.open(e,t)})}},r.IndexedDB.clean=function(e,t){var r=indexedDB.deleteDatabase(e);r.onsuccess=function(){RemoteStorage.log("[IndexedDB] Done removing DB"),t()},r.onerror=r.onabort=function(t){console.error('Failed to remove database "'+e+'"',t)}},r.IndexedDB._rs_init=function(e){var o=Promise.defer();return r.IndexedDB.open(n,function(r,n){r?o.reject(r):(t=n,n.onerror=function(){e._emit("error",r)},o.resolve())}),o.promise},r.IndexedDB._rs_supported=function(){var t=Promise.defer();e.indexedDB=e.indexedDB||e.webkitIndexedDB||e.mozIndexedDB||e.oIndexedDB||e.msIndexedDB;var r=!1;if("undefined"!=typeof e.navigator&&e.navigator.userAgent.match(/Android (2|3|4\.[0-3])/)&&(navigator.userAgent.match(/Chrome|Firefox/)||(r=!0)),"indexedDB"in e&&!r)try{var o=indexedDB.open("rs-check");o.onerror=function(e){t.reject()},o.onsuccess=function(e){indexedDB.deleteDatabase("rs-check"),t.resolve()}}catch(n){t.reject()}else t.reject();return t.promise},r.IndexedDB._rs_cleanup=function(e){var t=Promise.defer();return e.local&&e.local.closeDB(),r.IndexedDB.clean(n,function(){t.resolve()}),t.promise}}("undefined"!=typeof window?window:global),function(e){function t(e){return e.substr(0,o.length)===o||e.substr(0,n.length)===n}function r(e){return e.substr(0,o.length)===o}var o="remotestorage:cache:nodes:",n="remotestorage:cache:changes:";RemoteStorage.LocalStorage=function(){RemoteStorage.cachingLayer(this),RemoteStorage.log("[LocalStorage] Registering events"),RemoteStorage.eventHandling(this,"change","local-events-done")},RemoteStorage.LocalStorage.prototype={getNodes:function(e){for(var t={},r=0,n=e.length;n>r;r++)try{t[e[r]]=JSON.parse(localStorage[o+e[r]])}catch(i){t[e[r]]=void 0}return Promise.resolve(t)},setNodes:function(e){for(var t in e)localStorage[o+t]=JSON.stringify(e[t]);return Promise.resolve()},forAllNodes:function(e){for(var t,o=0,n=localStorage.length;n>o;o++)if(r(localStorage.key(o))){try{t=this.migrate(JSON.parse(localStorage[localStorage.key(o)]))}catch(i){t=void 0}t&&e(t)}return Promise.resolve()}},RemoteStorage.LocalStorage._rs_init=function(){},RemoteStorage.LocalStorage._rs_supported=function(){return"localStorage"in e},RemoteStorage.LocalStorage._rs_cleanup=function(){for(var e=[],r=0,o=localStorage.length;o>r;r++){var n=localStorage.key(r);t(n)&&e.push(n)}e.forEach(function(e){RemoteStorage.log("[LocalStorage] Removing",e),delete localStorage[e]})}}("undefined"!=typeof window?window:global),function(e){RemoteStorage.InMemoryStorage=function(){RemoteStorage.cachingLayer(this),RemoteStorage.log("[InMemoryStorage] Registering events"),RemoteStorage.eventHandling(this,"change","local-events-done"),this._storage={}},RemoteStorage.InMemoryStorage.prototype={getNodes:function(e){for(var t={},r=0,o=e.length;o>r;r++)t[e[r]]=this._storage[e[r]];return Promise.resolve(t)},setNodes:function(e){for(var t in e)void 0===e[t]?delete this._storage[t]:this._storage[t]=e[t];return Promise.resolve()},forAllNodes:function(e){for(var t in this._storage)e(this.migrate(this._storage[t]));return Promise.resolve()}},RemoteStorage.InMemoryStorage._rs_init=function(){},RemoteStorage.InMemoryStorage._rs_supported=function(){return!0},RemoteStorage.InMemoryStorage._rs_cleanup=function(){}}("undefined"!=typeof window?window:global),function(){RemoteStorage.MODULES={},RemoteStorage.defineModule=function(e,t){if(RemoteStorage.MODULES[e]=t,Object.defineProperty(RemoteStorage.prototype,e,{configurable:!0,get:function(){var t=this._loadModule(e);return Object.defineProperty(this,e,{value:t}),t}}),-1!==e.indexOf("-")){var r=e.replace(/\-[a-z]/g,function(e){return e[1].toUpperCase()});Object.defineProperty(RemoteStorage.prototype,r,{get:function(){return this[e]}})}},RemoteStorage.prototype._loadModule=function(e){var t=RemoteStorage.MODULES[e];if(t){var r=t(new RemoteStorage.BaseClient(this,"/"+e+"/"),new RemoteStorage.BaseClient(this,"/public/"+e+"/"));return r.exports}throw"Unknown module: "+e},RemoteStorage.prototype.defineModule=function(e){console.log("remoteStorage.defineModule is deprecated, use RemoteStorage.defineModule instead!"),RemoteStorage.defineModule.apply(RemoteStorage,arguments)}}(),function(){function e(e,t,r){function o(e,t,r,o){[t,r,o].forEach(function(t){var r=document.createElement("td");r.textContent=t||"",e.appendChild(r)})}function n(e){function r(t,r,i,s){if(200===t){var c=document.createElement("tr");if(a.appendChild(c),o(c,e,i,s),"/"===e[e.length-1])for(var u in r)n(e+u)}}t.connected!==!1&&t.get(e).then(r)}e.setAttribute("border","1"),e.style.margin="8px",e.style.color="white",e.innerHTML="";var i=document.createElement("thead");e.appendChild(i);var s=document.createElement("tr");i.appendChild(s),["Path","Content-Type","Revision"].forEach(function(e){var t=document.createElement("th");t.textContent=e,i.appendChild(t)});var a=document.createElement("tbody");e.appendChild(a),r.forEach(n)}function t(t,r,o,n){var i=document.createElement("div"),s=document.createElement("h2");s.textContent=t,i.appendChild(s);var a=document.createElement("button");if(a.textContent="Refresh",a.onclick=function(){e(r,o,n)},i.appendChild(a),o.reset){var c=document.createElement("button");c.textContent="Reset",c.onclick=function(){o.reset(function(t){o=t,e(r,o,n)})},i.appendChild(c)}return i.appendChild(r),e(r,o,n),i}function r(e){function t(){i.innerHTML="",e.forAllNodes(function(e){if(e.local&&e.local.body){var t=document.createElement("li");t.textContent=JSON.stringify(e.local),i.appendChild(t)}})}var r=document.createElement("div"),o=document.createElement("h2");o.textContent="Outgoing changes",r.appendChild(o);var n=document.createElement("button");n.textContent="Refresh",r.appendChild(n);var i=document.createElement("ul");return i.style.fontFamily="courier",r.appendChild(i),n.onclick=t,t(),r}RemoteStorage.prototype.inspect=function(){var o=document.createElement("div");o.id="remotestorage-inspect",o.style.position="absolute",o.style.top=0,o.style.left=0,o.style.background="black",o.style.color="white",o.style.border="groove 5px #ccc";var n=document.createElement("div");n.style.position="absolute",n.style.top=0,n.style.left=0;var i=document.createElement("strong");i.textContent=" remotestorage.js inspector ",n.appendChild(i);var s;this.local&&(s=document.createElement("button"),s.textContent="Synchronize",n.appendChild(s));var a=document.createElement("button");a.textContent="Close",a.onclick=function(){document.body.removeChild(o)},n.appendChild(a),o.appendChild(n);var c=[];for(var u in this.caching._rootPaths)this.caching._rootPaths.hasOwnProperty(u)&&c.push(u);var l=document.createElement("table"),h=document.createElement("table");o.appendChild(t("Remote",l,this.remote,c)),this.local&&(o.appendChild(t("Local",h,this.local,["/"])),o.appendChild(r(this.local)),s.onclick=function(){this.log("sync clicked"),this.sync.sync().then(function(){this.log("SYNC FINISHED"),e(h,this.local,["/"])}.bind(this),function(e){console.error("SYNC FAILED",e,e.stack)})}.bind(this)),document.body.appendChild(o)}}(),function(e){function t(e){return"/"===e.substr(-1)&&(e=e.substr(0,e.length-1)),decodeURIComponent(e)}function r(e){return e.replace(/[^\/]+\/?$/,"")}function o(e){var t=e.split("/");return"/"===e.substr(-1)?t[t.length-2]+"/":t[t.length-1]}var n=RemoteStorage,i="https://www.googleapis.com",s="https://accounts.google.com/o/oauth2/auth",a="https://www.googleapis.com/auth/drive",c="application/vnd.google-apps.folder",u="application/json; charset=UTF-8",l=function(e){this.maxAge=e,this._items={}};l.prototype={get:function(e){var t=this._items[e],r=(new Date).getTime();return t&&t.t>=r-this.maxAge?t.v:void 0},set:function(e,t){this._items[e]={v:t,t:(new Date).getTime()}}},n.GoogleDrive=function(e,t){n.eventHandling(this,"change","connected","wire-busy","wire-done","not-connected"),this.rs=e,this.clientId=t,this._fileIdCache=new l(300)},n.GoogleDrive.prototype={connected:!1,online:!0,configure:function(e){e.token?(localStorage["remotestorage:googledrive:token"]=e.token,this.token=e.token,this.connected=!0,this._emit("connected")):(this.connected=!1,delete this.token,delete localStorage["remotestorage:googledrive:token"])},connect:function(){this.rs.setBackend("googledrive"),n.Authorize(s,a,String(n.Authorize.getLocation()),this.clientId)},stopWaitingForToken:function(){this.connected||this._emit("not-connected")},get:function(e,t){return"/"===e.substr(-1)?this._getFolder(e,t):this._getFile(e,t)},put:function(e,t,r,o){function n(e){if(e.status>=200&&e.status<300){var t=JSON.parse(e.responseText),r=t.etag.substring(1,t.etag.length-1);return Promise.resolve({statusCode:200,contentType:t.mimeType,revision:r})}return 412===e.status?Promise.resolve({statusCode:412,revision:"conflict"}):Promise.reject("PUT failed with status "+e.status+" ("+e.responseText+")")}var i=this;return i._getFileId(e).then(function(s){return s?o&&"*"===o.ifNoneMatch?n({status:412}):i._updateFile(s,e,t,r,o).then(n):i._createFile(e,t,r,o).then(n)})},"delete":function(e,t){var r=this;return r._getFileId(e).then(function(e){return e?r._getMeta(e).then(function(o){var n;return"object"==typeof o&&"string"==typeof o.etag&&(n=o.etag.substring(1,o.etag.length-1)),t&&t.ifMatch&&t.ifMatch!==n?{statusCode:412,revision:n}:r._request("DELETE",i+"/drive/v2/files/"+e,{}).then(function(e){return 200===e.status||204===e.status?{statusCode:200}:Promise.reject("Delete failed: "+e.status+" ("+e.responseText+")")})}):Promise.resolve({statusCode:200})})},_updateFile:function(e,t,r,o,n){var s=this,a={mimeType:o},c={"Content-Type":"application/json; charset=UTF-8"};return n&&n.ifMatch&&(c["If-Match"]='"'+n.ifMatch+'"'),s._request("PUT",i+"/upload/drive/v2/files/"+e+"?uploadType=resumable",{body:JSON.stringify(a),headers:c}).then(function(e){return 412===e.status?e:s._request("PUT",e.getResponseHeader("Location"),{body:o.match(/^application\/json/)?JSON.stringify(r):r})})},_createFile:function(e,r,n,s){var a=this;return a._getParentId(e).then(function(s){var c=o(e),u={title:t(c),mimeType:n,parents:[{kind:"drive#fileLink",id:s}]};return a._request("POST",i+"/upload/drive/v2/files?uploadType=resumable",{body:JSON.stringify(u),headers:{"Content-Type":"application/json; charset=UTF-8"}}).then(function(e){return a._request("POST",e.getResponseHeader("Location"),{body:n.match(/^application\/json/)?JSON.stringify(r):r})})})},_getFile:function(e,t){var r=this;return r._getFileId(e).then(function(e){return r._getMeta(e).then(function(e){var o;if("object"==typeof e&&"string"==typeof e.etag&&(o=e.etag.substring(1,e.etag.length-1)),t&&t.ifNoneMatch&&o===t.ifNoneMatch)return Promise.resolve({statusCode:304});var n={};if(!e.downloadUrl){if(!e.exportLinks||!e.exportLinks["text/html"])return Promise.resolve({statusCode:200,body:"",contentType:e.mimeType,revision:o});e.mimeType+=";export=text/html",e.downloadUrl=e.exportLinks["text/html"]}return e.mimeType.match(/charset=binary/)&&(n.responseType="blob"),r._request("GET",e.downloadUrl,n).then(function(t){var r=t.response;if(e.mimeType.match(/^application\/json/))try{r=JSON.parse(r)}catch(n){}return Promise.resolve({statusCode:200,body:r,contentType:e.mimeType,revision:o})})})})},_getFolder:function(e,t){var r=this;return r._getFileId(e).then(function(t){var o,n,s,a,l;return t?(o="'"+t+"' in parents",n="items(downloadUrl,etag,fileSize,id,mimeType,title)",r._request("GET",i+"/drive/v2/files?q="+encodeURIComponent(o)+"&fields="+encodeURIComponent(n)+"&maxResults=1000",{}).then(function(t){if(200!==t.status)return Promise.reject("request failed or something: "+t.status);try{s=JSON.parse(t.responseText)}catch(o){return Promise.reject("non-JSON response from GoogleDrive")}l={};for(var n=0,i=s.items.length;i>n;n++)a=s.items[n].etag.substring(1,s.items[n].etag.length-1),s.items[n].mimeType===c?(r._fileIdCache.set(e+s.items[n].title+"/",s.items[n].id),l[s.items[n].title+"/"]={ETag:a}):(r._fileIdCache.set(e+s.items[n].title,s.items[n].id),l[s.items[n].title]={ETag:a,"Content-Type":s.items[n].mimeType,"Content-Length":s.items[n].fileSize});return Promise.resolve({statusCode:200,body:l,contentType:u,revision:void 0})})):Promise.resolve({statusCode:404})})},_getParentId:function(e){var t=r(e),o=this;return o._getFileId(t).then(function(e){return e?Promise.resolve(e):o._createFolder(t)})},_createFolder:function(e){var r=this;return r._getParentId(e).then(function(n){return r._request("POST",i+"/drive/v2/files",{body:JSON.stringify({title:t(o(e)),mimeType:c,parents:[{id:n}]}),headers:{"Content-Type":"application/json; charset=UTF-8"}}).then(function(e){var t=JSON.parse(e.responseText);return Promise.resolve(t.id)})})},_getFileId:function(e){var t,o=this;return"/"===e?Promise.resolve("root"):(t=this._fileIdCache.get(e))?Promise.resolve(t):o._getFolder(r(e)).then(function(){return t=o._fileIdCache.get(e),t?Promise.resolve(t):"/"===e.substr(-1)?o._createFolder(e).then(function(){return o._getFileId(e)}):Promise.resolve()})},_getMeta:function(e){return this._request("GET",i+"/drive/v2/files/"+e,{}).then(function(t){return 200===t.status?Promise.resolve(JSON.parse(t.responseText)):Promise.reject("request (getting metadata for "+e+") failed with status: "+t.status)})},_request:function(e,t,r){var o=this;return r.headers||(r.headers={}),r.headers.Authorization="Bearer "+o.token,n.WireClient.request(e,t,r).then(function(e){return e&&401===e.status?void o.connect():e})}},n.GoogleDrive._rs_init=function(e){var t=e.apiKeys.googledrive;t&&(e.googledrive=new n.GoogleDrive(e,t.clientId),"googledrive"===e.backend&&(e._origRemote=e.remote,e.remote=e.googledrive))},n.GoogleDrive._rs_supported=function(e){return!0},n.GoogleDrive._rs_cleanup=function(e){e.setBackend(void 0),e._origRemote&&(e.remote=e._origRemote,delete e._origRemote)}}(this),function(e){function t(e){this.defaultValue=e,this._storage={},this.set=this.justSet,this["delete"]=this.justDelete}function r(e){e._dropboxOrigSync||(e._dropboxOrigSync=e.sync.bind(e),e.sync=function(){return this.dropbox.fetchDelta.apply(this.dropbox,arguments).then(e._dropboxOrigSync,function(t){e._emit("error",new e.SyncError(t))})})}function o(e){e._dropboxOrigSync&&(e.sync=e._dropboxOrigSync,delete e._dropboxOrigSync)}function n(e){e._origBaseClientGetItemURL||(e._origBaseClientGetItemURL=h.BaseClient.prototype.getItemURL,h.BaseClient.prototype.getItemURL=function(t){var r=e.dropbox._itemRefs[t];return r?r:""})}function i(e){e._origBaseClientGetItemURL&&(h.BaseClient.prototype.getItemURL=e._origBaseClientGetItemURL,delete e._origBaseClientGetItemURL)}function s(e){e._origRemote||(e._origRemote=e.remote,e.remote=e.dropbox)}function a(e){e._origRemote&&(e.remote=e._origRemote,delete e._origRemote)}function c(e){s(e),e.sync&&r(e),n(e)}function u(e){a(e),o(e),i(e)}var l,h=RemoteStorage,d="https://www.dropbox.com/1/oauth2/authorize",f="remotestorage:dropbox",p=h.WireClient.cleanPath;t.prototype={get:function(e){e=e.toLowerCase();var t=this._storage[e];return"undefined"==typeof t&&(t=this.defaultValue,this._storage[e]=t),t},propagateSet:function(e,t){return e=e.toLowerCase(),this._storage[e]===t?t:(this._propagate(e,t),this._storage[e]=t,t)},propagateDelete:function(e){return e=e.toLowerCase(),this._propagate(e,this._storage[e]),delete this._storage[e]},_activatePropagation:function(){return this.set=this.propagateSet,this["delete"]=this.propagateDelete,!0},justSet:function(e,t){return e=e.toLowerCase(),this._storage[e]=t,t},justDelete:function(e,t){return e=e.toLowerCase(),delete this._storage[e]},_propagate:function(e,t){for(var r=e.split("/").slice(0,-1),o="",n=0,i=r.length;i>n;n++)o+=r[n]+"/",t||(t=this._storage[o]+1),this._storage[o]=t}};var m;h.Dropbox=function(e){this.rs=e,this.connected=!1,this.rs=e;var r=this;if(m=function(e){e instanceof RemoteStorage.Unauthorized&&r.configure({userAddress:null,href:null,storageApi:null,token:null,options:null})},h.eventHandling(this,"change","connected","wire-busy","wire-done","not-connected"),e.on("error",m),this.clientId=e.apiKeys.dropbox.appKey,this._revCache=new t("rev"),this._itemRefs={},this._metadataCache={},l){var o;try{o=JSON.parse(localStorage[f])}catch(n){}o&&this.configure(o);try{this._itemRefs=JSON.parse(localStorage[f+":shares"])}catch(n){}}this.connected&&setTimeout(this._emit.bind(this),0,"connected")},h.Dropbox.prototype={online:!0,connect:function(){this.rs.setBackend("dropbox"),this.token?c(this.rs):h.Authorize(d,"",String(h.Authorize.getLocation()),this.clientId)},configure:function(e){"undefined"!=typeof e.userAddress&&(this.userAddress=e.userAddress),"undefined"!=typeof e.token&&(this.token=e.token),this.token?(this.connected=!0,this.userAddress||this.info().then(function(e){this.userAddress=e.display_name,this.rs.widget.view.setUserAddress(this.userAddress),this._emit("connected")}.bind(this))):this.connected=!1,l&&(localStorage[f]=JSON.stringify({userAddress:this.userAddress,token:this.token}))},stopWaitingForToken:function(){this.connected||this._emit("not-connected")},_getFolder:function(e,t){var r="https://api.dropbox.com/1/metadata/auto"+p(e),o=this._revCache,n=this;return this._request("GET",r,{}).then(function(t){var r=t.status;if(304===r)return Promise.resolve({statusCode:r});var i,s,a,c;try{s=JSON.parse(t.responseText)}catch(u){return Promise.reject(u)}return c=n._revCache.get(e),a="application/json; charset=UTF-8",s.contents&&(i=s.contents.reduce(function(t,r){var n=r.path.split("/").slice(-1)[0]+(r.is_dir?"/":"");return r.is_dir?t[n]={ETag:o.get(e+n)}:t[n]={ETag:r.rev},t},{})),Promise.resolve({statusCode:r,body:i,contentType:a,revision:c})})},get:function(e,t){if(!this.connected)return Promise.reject("not connected (path: "+e+")");var r="https://api-content.dropbox.com/1/files/auto"+p(e),o=this,n=this._revCache.get(e);return null===n?Promise.resolve({statusCode:404}):t&&t.ifNoneMatch&&n&&n===t.ifNoneMatch?Promise.resolve({statusCode:304}):"/"===e.substr(-1)?this._getFolder(e,t):this._request("GET",r,{}).then(function(t){var r,n,i,s,a=t.status;if(200!==a)return Promise.resolve({statusCode:a});n=t.responseText;try{r=JSON.parse(t.getResponseHeader("x-dropbox-metadata"))}catch(c){return Promise.reject(c)}if(i=r.mime_type,s=r.rev,o._revCache.set(e,s),o._shareIfNeeded(e),!t.getResponseHeader("Content-Type")||t.getResponseHeader("Content-Type").match(/charset=binary/)){var u=Promise.defer();return h.WireClient.readBinaryData(t.response,i,function(e){u.resolve({statusCode:a,body:e,contentType:i,revision:s})}),u.promise}if(i&&i.search("application/json")>=0,!0)try{n=JSON.parse(n),i="application/json; charset=UTF-8"}catch(c){}return Promise.resolve({statusCode:a,body:n,contentType:i,revision:s})})},put:function(e,t,r,o){var n=this;if(!this.connected)throw new Error("not connected (path: "+e+")");var i=this._revCache.get(e);if(o&&o.ifMatch&&i&&i!==o.ifMatch)return Promise.resolve({statusCode:412,revision:i});if(o&&"*"===o.ifNoneMatch&&i&&"rev"!==i)return Promise.resolve({statusCode:412,revision:i});if(!r.match(/charset=/)&&(t instanceof ArrayBuffer||h.WireClient.isArrayBufferView(t))&&(r+="; charset=binary"),t.length>157286400)return Promise.reject(new Error("Cannot upload file larger than 150MB"));var s,a=o&&(o.ifMatch||"*"===o.ifNoneMatch),c={body:t,contentType:r,path:e};return s=a?this._getMetadata(e).then(function(e){return o&&"*"===o.ifNoneMatch&&e?Promise.resolve({statusCode:412,revision:e.rev}):o&&o.ifMatch&&e&&e.rev!==o.ifMatch?Promise.resolve({statusCode:412,revision:e.rev}):n._uploadSimple(c)}):n._uploadSimple(c),s.then(function(t){return n._shareIfNeeded(e),t})},"delete":function(e,t){var r=this;if(!this.connected)throw new Error("not connected (path: "+e+")");var o=this._revCache.get(e);return t&&t.ifMatch&&o&&t.ifMatch!==o?Promise.resolve({statusCode:412,revision:o}):t&&t.ifMatch?this._getMetadata(e).then(function(o){return t&&t.ifMatch&&o&&o.rev!==t.ifMatch?Promise.resolve({statusCode:412,revision:o.rev}):r._deleteSimple(e)}):r._deleteSimple(e)},_shareIfNeeded:function(e){e.match(/^\/public\/.*[^\/]$/)&&void 0===this._itemRefs[e]&&this.share(e)},share:function(e){var t=this,r="https://api.dropbox.com/1/media/auto/"+p(e);return this._request("POST",r,{}).then(function(o){if(200!==o.status)return Promise.reject(new Error('Invalid Dropbox API response status when sharing "'+e+'":'+o.status));try{o=JSON.parse(o.responseText)}catch(n){return Promise.reject(new Error('Invalid Dropbox API response when sharing "'+e+'": '+o.responseText))}return t._itemRefs[e]=o.url,l&&(localStorage[f+":shares"]=JSON.stringify(t._itemRefs)),Promise.resolve(r)},function(t){return err.message='Sharing dropbox file or folder ("'+e+'") failed.'+err.message,Promise.reject(t)})},info:function(){var e="https://api.dropbox.com/1/account/info";return this._request("GET",e,{}).then(function(e){try{var t=JSON.parse(e.responseText);return Promise.resolve(t)}catch(r){return Promise.reject(r)}})},_request:function(t,r,o){var n=this;return o.headers||(o.headers={}),o.headers.Authorization="Bearer "+this.token,h.WireClient.request.call(this,t,r,o).then(function(i){return i&&503===i.status?e.setTimeout(n._request(t,r,o),3210):Promise.resolve(i)})},fetchDelta:function(){var e=Array.prototype.slice.call(arguments),r=this;return r._request("POST","https://api.dropbox.com/1/delta",{body:r._deltaCursor?"cursor="+encodeURIComponent(r._deltaCursor):"",headers:{"Content-Type":"application/x-www-form-urlencoded"}}).then(function(o){if(200!==o.status)return 400===o.status?(r.rs._emit("error",new RemoteStorage.Unauthorized),Promise.resolve(e)):Promise.reject("dropbox.fetchDelta returned "+o.status+o.responseText);var n;try{n=JSON.parse(o.responseText)}catch(i){return h.log("fetchDeltas can not parse response",i),Promise.reject("can not parse response of fetchDelta : "+i.message)}return n.entries?(n.reset&&(r._revCache=new t("rev")),n.cursor&&(r._deltaCursor=n.cursor),RemoteStorage.log("Delta : ",n.entries),n.entries.forEach(function(e){var t,o=e[0];if(e[1]){if(e[1].is_dir)return;t=e[1].rev}else t=null;r._revCache.set(o,t)}),Promise.resolve(e)):Promise.reject("dropbox.fetchDeltas failed, no entries found")},function(e){this.rs.log("fetchDeltas",e),this.rs._emit("error",new RemoteStorage.SyncError("fetchDeltas failed."+e)),promise.reject(e)}).then(function(){if(r._revCache){var e=Array.prototype.slice.call(arguments);return r._revCache._activatePropagation(),Promise.resolve(e)}})},_getMetadata:function(e,t){var r=this,o=this._metadataCache[e],n="https://api.dropbox.com/1/metadata/auto"+p(e);return n+="?list="+(t&&t.list?"true":"false"),o&&o.hash&&(n+="&hash="+encodeURIComponent(o.hash)),this._request("GET",n,{}).then(function(t){if(304===t.status)return Promise.resolve(o);if(200===t.status){var n=JSON.parse(t.responseText);return r._metadataCache[e]=n,Promise.resolve(n)}return Promise.resolve()})},_uploadSimple:function(e){var t=this,r="https://api-content.dropbox.com/1/files_put/auto"+p(e.path)+"?";return e&&e.ifMatch&&(r+="parent_rev="+encodeURIComponent(e.ifMatch)),t._request("PUT",r,{body:e.body,headers:{"Content-Type":e.contentType}}).then(function(r){if(200!==r.status)return Promise.resolve({statusCode:r.status});var o;try{o=JSON.parse(r.responseText)}catch(n){return Promise.reject(n)}if(o.path!==e.path){var i="https://api.dropbox.com/1/fileops/delete?root=auto&path="+encodeURIComponent(o.path);return t._request("POST",i,{}),t._getMetadata(e.path).then(function(e){return Promise.resolve({statusCode:412,revision:e.rev})})}return t._revCache.propagateSet(e.path,o.rev),Promise.resolve({statusCode:r.status})})},_deleteSimple:function(e){var t=this,r="https://api.dropbox.com/1/fileops/delete?root=auto&path="+encodeURIComponent(e);return t._request("POST",r,{}).then(function(r){return 406===r.status?Promise.reject(new Error("Cannot delete '"+e+"': too many files involved")):(200===r.status&&(t._revCache["delete"](e),delete t._itemRefs[e]),Promise.resolve({statusCode:r.status}))})}},h.Dropbox._rs_init=function(e){l=e.localStorageAvailable(),e.apiKeys.dropbox&&(e.dropbox=new h.Dropbox(e)),"dropbox"===e.backend&&c(e)},h.Dropbox._rs_supported=function(){return!0},h.Dropbox._rs_cleanup=function(e){u(e),l&&delete localStorage[f],e.removeEventListener("error",m),e.setBackend(void 0)}}(this),remoteStorage=new RemoteStorage;