123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939 |
- (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.PouchAuthentication = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
- (function (process){
- 'use strict';
- var Promise = require(13);
- var urlJoin = require(16);
- function getBaseUrl(db) {
- if (typeof db.getUrl === 'function') { // pouchdb pre-6.0.0
- return db.getUrl().replace(/\/[^\/]+\/?$/, '');
- } else { // pouchdb post-6.0.0
- return db.name.replace(/\/[^\/]+\/?$/, '');
- }
- }
- exports.getUsersUrl = function (db) {
- return urlJoin(getBaseUrl(db), '/_users');
- };
- exports.getSessionUrl = function (db) {
- return urlJoin(getBaseUrl(db), '/_session');
- };
- exports.once = function (fun) {
- var called = false;
- return exports.getArguments(function (args) {
- if (called) {
- console.trace();
- throw new Error('once called more than once');
- } else {
- called = true;
- fun.apply(this, args);
- }
- });
- };
- exports.getArguments = function (fun) {
- return function () {
- var len = arguments.length;
- var args = new Array(len);
- var i = -1;
- while (++i < len) {
- args[i] = arguments[i];
- }
- return fun.call(this, args);
- };
- };
- exports.toPromise = function (func) {
- //create the function we will be returning
- return exports.getArguments(function (args) {
- var self = this;
- var tempCB = (typeof args[args.length - 1] === 'function') ? args.pop() : false;
- // if the last argument is a function, assume its a callback
- var usedCB;
- if (tempCB) {
- // if it was a callback, create a new callback which calls it,
- // but do so async so we don't trap any errors
- usedCB = function (err, resp) {
- process.nextTick(function () {
- tempCB(err, resp);
- });
- };
- }
- var promise = new Promise(function (fulfill, reject) {
- try {
- var callback = exports.once(function (err, mesg) {
- if (err) {
- reject(err);
- } else {
- fulfill(mesg);
- }
- });
- // create a callback for this invocation
- // apply the function in the orig context
- args.push(callback);
- func.apply(self, args);
- } catch (e) {
- reject(e);
- }
- });
- // if there is a callback, call it back
- if (usedCB) {
- promise.then(function (result) {
- usedCB(null, result);
- }, usedCB);
- }
- promise.cancel = function () {
- return this;
- };
- return promise;
- });
- };
- exports.inherits = require(7);
- exports.extend = require(12);
- exports.ajax = require(11);
- exports.clone = function (obj) {
- return exports.extend(true, {}, obj);
- };
- exports.uuid = require(14).uuid;
- exports.Promise = Promise;
- }).call(this,require(15))
- },{"11":11,"12":12,"13":13,"14":14,"15":15,"16":16,"7":7}],2:[function(require,module,exports){
- 'use strict';
- module.exports = argsArray;
- function argsArray(fun) {
- return function () {
- var len = arguments.length;
- if (len) {
- var args = [];
- var i = -1;
- while (++i < len) {
- args[i] = arguments[i];
- }
- return fun.call(this, args);
- } else {
- return fun.call(this, []);
- }
- };
- }
- },{}],3:[function(require,module,exports){
- /**
- * This is the web browser implementation of `debug()`.
- *
- * Expose `debug()` as the module.
- */
- exports = module.exports = require(4);
- exports.log = log;
- exports.formatArgs = formatArgs;
- exports.save = save;
- exports.load = load;
- exports.useColors = useColors;
- exports.storage = 'undefined' != typeof chrome
- && 'undefined' != typeof chrome.storage
- ? chrome.storage.local
- : localstorage();
- /**
- * Colors.
- */
- exports.colors = [
- 'lightseagreen',
- 'forestgreen',
- 'goldenrod',
- 'dodgerblue',
- 'darkorchid',
- 'crimson'
- ];
- /**
- * Currently only WebKit-based Web Inspectors, Firefox >= v31,
- * and the Firebug extension (any Firefox version) are known
- * to support "%c" CSS customizations.
- *
- * TODO: add a `localStorage` variable to explicitly enable/disable colors
- */
- function useColors() {
- // is webkit? http://stackoverflow.com/a/16459606/376773
- return ('WebkitAppearance' in document.documentElement.style) ||
- // is firebug? http://stackoverflow.com/a/398120/376773
- (window.console && (console.firebug || (console.exception && console.table))) ||
- // is firefox >= v31?
- // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
- (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
- }
- /**
- * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
- */
- exports.formatters.j = function(v) {
- return JSON.stringify(v);
- };
- /**
- * Colorize log arguments if enabled.
- *
- * @api public
- */
- function formatArgs() {
- var args = arguments;
- var useColors = this.useColors;
- args[0] = (useColors ? '%c' : '')
- + this.namespace
- + (useColors ? ' %c' : ' ')
- + args[0]
- + (useColors ? '%c ' : ' ')
- + '+' + exports.humanize(this.diff);
- if (!useColors) return args;
- var c = 'color: ' + this.color;
- args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
- // the final "%c" is somewhat tricky, because there could be other
- // arguments passed either before or after the %c, so we need to
- // figure out the correct index to insert the CSS into
- var index = 0;
- var lastC = 0;
- args[0].replace(/%[a-z%]/g, function(match) {
- if ('%%' === match) return;
- index++;
- if ('%c' === match) {
- // we only are interested in the *last* %c
- // (the user may have provided their own)
- lastC = index;
- }
- });
- args.splice(lastC, 0, c);
- return args;
- }
- /**
- * Invokes `console.log()` when available.
- * No-op when `console.log` is not a "function".
- *
- * @api public
- */
- function log() {
- // this hackery is required for IE8/9, where
- // the `console.log` function doesn't have 'apply'
- return 'object' === typeof console
- && console.log
- && Function.prototype.apply.call(console.log, console, arguments);
- }
- /**
- * Save `namespaces`.
- *
- * @param {String} namespaces
- * @api private
- */
- function save(namespaces) {
- try {
- if (null == namespaces) {
- exports.storage.removeItem('debug');
- } else {
- exports.storage.debug = namespaces;
- }
- } catch(e) {}
- }
- /**
- * Load `namespaces`.
- *
- * @return {String} returns the previously persisted debug modes
- * @api private
- */
- function load() {
- var r;
- try {
- r = exports.storage.debug;
- } catch(e) {}
- return r;
- }
- /**
- * Enable namespaces listed in `localStorage.debug` initially.
- */
- exports.enable(load());
- /**
- * Localstorage attempts to return the localstorage.
- *
- * This is necessary because safari throws
- * when a user disables cookies/localstorage
- * and you attempt to access it.
- *
- * @return {LocalStorage}
- * @api private
- */
- function localstorage(){
- try {
- return window.localStorage;
- } catch (e) {}
- }
- },{"4":4}],4:[function(require,module,exports){
- /**
- * This is the common logic for both the Node.js and web browser
- * implementations of `debug()`.
- *
- * Expose `debug()` as the module.
- */
- exports = module.exports = debug;
- exports.coerce = coerce;
- exports.disable = disable;
- exports.enable = enable;
- exports.enabled = enabled;
- exports.humanize = require(10);
- /**
- * The currently active debug mode names, and names to skip.
- */
- exports.names = [];
- exports.skips = [];
- /**
- * Map of special "%n" handling functions, for the debug "format" argument.
- *
- * Valid key names are a single, lowercased letter, i.e. "n".
- */
- exports.formatters = {};
- /**
- * Previously assigned color.
- */
- var prevColor = 0;
- /**
- * Previous log timestamp.
- */
- var prevTime;
- /**
- * Select a color.
- *
- * @return {Number}
- * @api private
- */
- function selectColor() {
- return exports.colors[prevColor++ % exports.colors.length];
- }
- /**
- * Create a debugger with the given `namespace`.
- *
- * @param {String} namespace
- * @return {Function}
- * @api public
- */
- function debug(namespace) {
- // define the `disabled` version
- function disabled() {
- }
- disabled.enabled = false;
- // define the `enabled` version
- function enabled() {
- var self = enabled;
- // set `diff` timestamp
- var curr = +new Date();
- var ms = curr - (prevTime || curr);
- self.diff = ms;
- self.prev = prevTime;
- self.curr = curr;
- prevTime = curr;
- // add the `color` if not set
- if (null == self.useColors) self.useColors = exports.useColors();
- if (null == self.color && self.useColors) self.color = selectColor();
- var args = Array.prototype.slice.call(arguments);
- args[0] = exports.coerce(args[0]);
- if ('string' !== typeof args[0]) {
- // anything else let's inspect with %o
- args = ['%o'].concat(args);
- }
- // apply any `formatters` transformations
- var index = 0;
- args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
- // if we encounter an escaped % then don't increase the array index
- if (match === '%%') return match;
- index++;
- var formatter = exports.formatters[format];
- if ('function' === typeof formatter) {
- var val = args[index];
- match = formatter.call(self, val);
- // now we need to remove `args[index]` since it's inlined in the `format`
- args.splice(index, 1);
- index--;
- }
- return match;
- });
- if ('function' === typeof exports.formatArgs) {
- args = exports.formatArgs.apply(self, args);
- }
- var logFn = enabled.log || exports.log || console.log.bind(console);
- logFn.apply(self, args);
- }
- enabled.enabled = true;
- var fn = exports.enabled(namespace) ? enabled : disabled;
- fn.namespace = namespace;
- return fn;
- }
- /**
- * Enables a debug mode by namespaces. This can include modes
- * separated by a colon and wildcards.
- *
- * @param {String} namespaces
- * @api public
- */
- function enable(namespaces) {
- exports.save(namespaces);
- var split = (namespaces || '').split(/[\s,]+/);
- var len = split.length;
- for (var i = 0; i < len; i++) {
- if (!split[i]) continue; // ignore empty strings
- namespaces = split[i].replace(/\*/g, '.*?');
- if (namespaces[0] === '-') {
- exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
- } else {
- exports.names.push(new RegExp('^' + namespaces + '$'));
- }
- }
- }
- /**
- * Disable debug output.
- *
- * @api public
- */
- function disable() {
- exports.enable('');
- }
- /**
- * Returns true if the given mode name is enabled, false otherwise.
- *
- * @param {String} name
- * @return {Boolean}
- * @api public
- */
- function enabled(name) {
- var i, len;
- for (i = 0, len = exports.skips.length; i < len; i++) {
- if (exports.skips[i].test(name)) {
- return false;
- }
- }
- for (i = 0, len = exports.names.length; i < len; i++) {
- if (exports.names[i].test(name)) {
- return true;
- }
- }
- return false;
- }
- /**
- * Coerce `val`.
- *
- * @param {Mixed} val
- * @return {Mixed}
- * @api private
- */
- function coerce(val) {
- if (val instanceof Error) return val.stack || val.message;
- return val;
- }
- },{"10":10}],5:[function(require,module,exports){
- // Copyright Joyent, Inc. and other Node contributors.
- //
- // 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:
- //
- // 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 EventEmitter() {
- this._events = this._events || {};
- this._maxListeners = this._maxListeners || undefined;
- }
- module.exports = EventEmitter;
- // Backwards-compat with node 0.10.x
- EventEmitter.EventEmitter = EventEmitter;
- EventEmitter.prototype._events = undefined;
- EventEmitter.prototype._maxListeners = undefined;
- // By default EventEmitters will print a warning if more than 10 listeners are
- // added to it. This is a useful default which helps finding memory leaks.
- EventEmitter.defaultMaxListeners = 10;
- // Obviously not all Emitters should be limited to 10. This function allows
- // that to be increased. Set to zero for unlimited.
- EventEmitter.prototype.setMaxListeners = function(n) {
- if (!isNumber(n) || n < 0 || isNaN(n))
- throw TypeError('n must be a positive number');
- this._maxListeners = n;
- return this;
- };
- EventEmitter.prototype.emit = function(type) {
- var er, handler, len, args, i, listeners;
- if (!this._events)
- this._events = {};
- // If there is no 'error' event listener then throw.
- if (type === 'error') {
- if (!this._events.error ||
- (isObject(this._events.error) && !this._events.error.length)) {
- er = arguments[1];
- if (er instanceof Error) {
- throw er; // Unhandled 'error' event
- } else {
- // At least give some kind of context to the user
- var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
- err.context = er;
- throw err;
- }
- }
- }
- handler = this._events[type];
- if (isUndefined(handler))
- return false;
- if (isFunction(handler)) {
- switch (arguments.length) {
- // fast cases
- case 1:
- handler.call(this);
- break;
- case 2:
- handler.call(this, arguments[1]);
- break;
- case 3:
- handler.call(this, arguments[1], arguments[2]);
- break;
- // slower
- default:
- args = Array.prototype.slice.call(arguments, 1);
- handler.apply(this, args);
- }
- } else if (isObject(handler)) {
- args = Array.prototype.slice.call(arguments, 1);
- listeners = handler.slice();
- len = listeners.length;
- for (i = 0; i < len; i++)
- listeners[i].apply(this, args);
- }
- return true;
- };
- EventEmitter.prototype.addListener = function(type, listener) {
- var m;
- if (!isFunction(listener))
- throw TypeError('listener must be a function');
- if (!this._events)
- this._events = {};
- // To avoid recursion in the case that type === "newListener"! Before
- // adding it to the listeners, first emit "newListener".
- if (this._events.newListener)
- this.emit('newListener', type,
- isFunction(listener.listener) ?
- listener.listener : listener);
- if (!this._events[type])
- // Optimize the case of one listener. Don't need the extra array object.
- this._events[type] = listener;
- else if (isObject(this._events[type]))
- // If we've already got an array, just append.
- this._events[type].push(listener);
- else
- // Adding the second element, need to change to array.
- this._events[type] = [this._events[type], listener];
- // Check for listener leak
- if (isObject(this._events[type]) && !this._events[type].warned) {
- if (!isUndefined(this._maxListeners)) {
- m = this._maxListeners;
- } else {
- m = EventEmitter.defaultMaxListeners;
- }
- if (m && m > 0 && this._events[type].length > m) {
- this._events[type].warned = true;
- console.error('(node) warning: possible EventEmitter memory ' +
- 'leak detected. %d listeners added. ' +
- 'Use emitter.setMaxListeners() to increase limit.',
- this._events[type].length);
- if (typeof console.trace === 'function') {
- // not supported in IE 10
- console.trace();
- }
- }
- }
- return this;
- };
- EventEmitter.prototype.on = EventEmitter.prototype.addListener;
- EventEmitter.prototype.once = function(type, listener) {
- if (!isFunction(listener))
- throw TypeError('listener must be a function');
- var fired = false;
- function g() {
- this.removeListener(type, g);
- if (!fired) {
- fired = true;
- listener.apply(this, arguments);
- }
- }
- g.listener = listener;
- this.on(type, g);
- return this;
- };
- // emits a 'removeListener' event iff the listener was removed
- EventEmitter.prototype.removeListener = function(type, listener) {
- var list, position, length, i;
- if (!isFunction(listener))
- throw TypeError('listener must be a function');
- if (!this._events || !this._events[type])
- return this;
- list = this._events[type];
- length = list.length;
- position = -1;
- if (list === listener ||
- (isFunction(list.listener) && list.listener === listener)) {
- delete this._events[type];
- if (this._events.removeListener)
- this.emit('removeListener', type, listener);
- } else if (isObject(list)) {
- for (i = length; i-- > 0;) {
- if (list[i] === listener ||
- (list[i].listener && list[i].listener === listener)) {
- position = i;
- break;
- }
- }
- if (position < 0)
- return this;
- if (list.length === 1) {
- list.length = 0;
- delete this._events[type];
- } else {
- list.splice(position, 1);
- }
- if (this._events.removeListener)
- this.emit('removeListener', type, listener);
- }
- return this;
- };
- EventEmitter.prototype.removeAllListeners = function(type) {
- var key, listeners;
- if (!this._events)
- return this;
- // not listening for removeListener, no need to emit
- if (!this._events.removeListener) {
- if (arguments.length === 0)
- this._events = {};
- else if (this._events[type])
- delete this._events[type];
- return this;
- }
- // emit removeListener for all listeners on all events
- if (arguments.length === 0) {
- for (key in this._events) {
- if (key === 'removeListener') continue;
- this.removeAllListeners(key);
- }
- this.removeAllListeners('removeListener');
- this._events = {};
- return this;
- }
- listeners = this._events[type];
- if (isFunction(listeners)) {
- this.removeListener(type, listeners);
- } else if (listeners) {
- // LIFO order
- while (listeners.length)
- this.removeListener(type, listeners[listeners.length - 1]);
- }
- delete this._events[type];
- return this;
- };
- EventEmitter.prototype.listeners = function(type) {
- var ret;
- if (!this._events || !this._events[type])
- ret = [];
- else if (isFunction(this._events[type]))
- ret = [this._events[type]];
- else
- ret = this._events[type].slice();
- return ret;
- };
- EventEmitter.prototype.listenerCount = function(type) {
- if (this._events) {
- var evlistener = this._events[type];
- if (isFunction(evlistener))
- return 1;
- else if (evlistener)
- return evlistener.length;
- }
- return 0;
- };
- EventEmitter.listenerCount = function(emitter, type) {
- return emitter.listenerCount(type);
- };
- function isFunction(arg) {
- return typeof arg === 'function';
- }
- function isNumber(arg) {
- return typeof arg === 'number';
- }
- function isObject(arg) {
- return typeof arg === 'object' && arg !== null;
- }
- function isUndefined(arg) {
- return arg === void 0;
- }
- },{}],6:[function(require,module,exports){
- (function (global){
- 'use strict';
- var Mutation = global.MutationObserver || global.WebKitMutationObserver;
- var scheduleDrain;
- {
- if (Mutation) {
- var called = 0;
- var observer = new Mutation(nextTick);
- var element = global.document.createTextNode('');
- observer.observe(element, {
- characterData: true
- });
- scheduleDrain = function () {
- element.data = (called = ++called % 2);
- };
- } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
- var channel = new global.MessageChannel();
- channel.port1.onmessage = nextTick;
- scheduleDrain = function () {
- channel.port2.postMessage(0);
- };
- } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
- scheduleDrain = function () {
- // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
- // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
- var scriptEl = global.document.createElement('script');
- scriptEl.onreadystatechange = function () {
- nextTick();
- scriptEl.onreadystatechange = null;
- scriptEl.parentNode.removeChild(scriptEl);
- scriptEl = null;
- };
- global.document.documentElement.appendChild(scriptEl);
- };
- } else {
- scheduleDrain = function () {
- setTimeout(nextTick, 0);
- };
- }
- }
- var draining;
- var queue = [];
- //named nextTick for less confusing stack traces
- function nextTick() {
- draining = true;
- var i, oldQueue;
- var len = queue.length;
- while (len) {
- oldQueue = queue;
- queue = [];
- i = -1;
- while (++i < len) {
- oldQueue[i]();
- }
- len = queue.length;
- }
- draining = false;
- }
- module.exports = immediate;
- function immediate(task) {
- if (queue.push(task) === 1 && !draining) {
- scheduleDrain();
- }
- }
- }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
- },{}],7:[function(require,module,exports){
- if (typeof Object.create === 'function') {
- // implementation from standard node.js 'util' module
- module.exports = function inherits(ctor, superCtor) {
- ctor.super_ = superCtor
- ctor.prototype = Object.create(superCtor.prototype, {
- constructor: {
- value: ctor,
- enumerable: false,
- writable: true,
- configurable: true
- }
- });
- };
- } else {
- // old school shim for old browsers
- module.exports = function inherits(ctor, superCtor) {
- ctor.super_ = superCtor
- var TempCtor = function () {}
- TempCtor.prototype = superCtor.prototype
- ctor.prototype = new TempCtor()
- ctor.prototype.constructor = ctor
- }
- }
- },{}],8:[function(require,module,exports){
- (function(factory) {
- if(typeof exports === 'object') {
- factory(exports);
- } else {
- factory(this);
- }
- }).call(this, function(root) {
- var slice = Array.prototype.slice,
- each = Array.prototype.forEach;
- var extend = function(obj) {
- if(typeof obj !== 'object') throw obj + ' is not an object' ;
- var sources = slice.call(arguments, 1);
- each.call(sources, function(source) {
- if(source) {
- for(var prop in source) {
- if(typeof source[prop] === 'object' && obj[prop]) {
- extend.call(obj, obj[prop], source[prop]);
- } else {
- obj[prop] = source[prop];
- }
- }
- }
- });
- return obj;
- }
- root.extend = extend;
- });
- },{}],9:[function(require,module,exports){
- 'use strict';
- var immediate = require(6);
- /* istanbul ignore next */
- function INTERNAL() {}
- var handlers = {};
- var REJECTED = ['REJECTED'];
- var FULFILLED = ['FULFILLED'];
- var PENDING = ['PENDING'];
- module.exports = Promise;
- function Promise(resolver) {
- if (typeof resolver !== 'function') {
- throw new TypeError('resolver must be a function');
- }
- this.state = PENDING;
- this.queue = [];
- this.outcome = void 0;
- if (resolver !== INTERNAL) {
- safelyResolveThenable(this, resolver);
- }
- }
- Promise.prototype["catch"] = function (onRejected) {
- return this.then(null, onRejected);
- };
- Promise.prototype.then = function (onFulfilled, onRejected) {
- if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||
- typeof onRejected !== 'function' && this.state === REJECTED) {
- return this;
- }
- var promise = new this.constructor(INTERNAL);
- if (this.state !== PENDING) {
- var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
- unwrap(promise, resolver, this.outcome);
- } else {
- this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
- }
- return promise;
- };
- function QueueItem(promise, onFulfilled, onRejected) {
- this.promise = promise;
- if (typeof onFulfilled === 'function') {
- this.onFulfilled = onFulfilled;
- this.callFulfilled = this.otherCallFulfilled;
- }
- if (typeof onRejected === 'function') {
- this.onRejected = onRejected;
- this.callRejected = this.otherCallRejected;
- }
- }
- QueueItem.prototype.callFulfilled = function (value) {
- handlers.resolve(this.promise, value);
- };
- QueueItem.prototype.otherCallFulfilled = function (value) {
- unwrap(this.promise, this.onFulfilled, value);
- };
- QueueItem.prototype.callRejected = function (value) {
- handlers.reject(this.promise, value);
- };
- QueueItem.prototype.otherCallRejected = function (value) {
- unwrap(this.promise, this.onRejected, value);
- };
- function unwrap(promise, func, value) {
- immediate(function () {
- var returnValue;
- try {
- returnValue = func(value);
- } catch (e) {
- return handlers.reject(promise, e);
- }
- if (returnValue === promise) {
- handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));
- } else {
- handlers.resolve(promise, returnValue);
- }
- });
- }
- handlers.resolve = function (self, value) {
- var result = tryCatch(getThen, value);
- if (result.status === 'error') {
- return handlers.reject(self, result.value);
- }
- var thenable = result.value;
- if (thenable) {
- safelyResolveThenable(self, thenable);
- } else {
- self.state = FULFILLED;
- self.outcome = value;
- var i = -1;
- var len = self.queue.length;
- while (++i < len) {
- self.queue[i].callFulfilled(value);
- }
- }
- return self;
- };
- handlers.reject = function (self, error) {
- self.state = REJECTED;
- self.outcome = error;
- var i = -1;
- var len = self.queue.length;
- while (++i < len) {
- self.queue[i].callRejected(error);
- }
- return self;
- };
- function getThen(obj) {
- // Make sure we only access the accessor once as required by the spec
- var then = obj && obj.then;
- if (obj && typeof obj === 'object' && typeof then === 'function') {
- return function appyThen() {
- then.apply(obj, arguments);
- };
- }
- }
- function safelyResolveThenable(self, thenable) {
- // Either fulfill, reject or reject with error
- var called = false;
- function onError(value) {
- if (called) {
- return;
- }
- called = true;
- handlers.reject(self, value);
- }
- function onSuccess(value) {
- if (called) {
- return;
- }
- called = true;
- handlers.resolve(self, value);
- }
- function tryToUnwrap() {
- thenable(onSuccess, onError);
- }
- var result = tryCatch(tryToUnwrap);
- if (result.status === 'error') {
- onError(result.value);
- }
- }
- function tryCatch(func, value) {
- var out = {};
- try {
- out.value = func(value);
- out.status = 'success';
- } catch (e) {
- out.status = 'error';
- out.value = e;
- }
- return out;
- }
- Promise.resolve = resolve;
- function resolve(value) {
- if (value instanceof this) {
- return value;
- }
- return handlers.resolve(new this(INTERNAL), value);
- }
- Promise.reject = reject;
- function reject(reason) {
- var promise = new this(INTERNAL);
- return handlers.reject(promise, reason);
- }
- Promise.all = all;
- function all(iterable) {
- var self = this;
- if (Object.prototype.toString.call(iterable) !== '[object Array]') {
- return this.reject(new TypeError('must be an array'));
- }
- var len = iterable.length;
- var called = false;
- if (!len) {
- return this.resolve([]);
- }
- var values = new Array(len);
- var resolved = 0;
- var i = -1;
- var promise = new this(INTERNAL);
- while (++i < len) {
- allResolver(iterable[i], i);
- }
- return promise;
- function allResolver(value, i) {
- self.resolve(value).then(resolveFromAll, function (error) {
- if (!called) {
- called = true;
- handlers.reject(promise, error);
- }
- });
- function resolveFromAll(outValue) {
- values[i] = outValue;
- if (++resolved === len && !called) {
- called = true;
- handlers.resolve(promise, values);
- }
- }
- }
- }
- Promise.race = race;
- function race(iterable) {
- var self = this;
- if (Object.prototype.toString.call(iterable) !== '[object Array]') {
- return this.reject(new TypeError('must be an array'));
- }
- var len = iterable.length;
- var called = false;
- if (!len) {
- return this.resolve([]);
- }
- var i = -1;
- var promise = new this(INTERNAL);
- while (++i < len) {
- resolver(iterable[i]);
- }
- return promise;
- function resolver(value) {
- self.resolve(value).then(function (response) {
- if (!called) {
- called = true;
- handlers.resolve(promise, response);
- }
- }, function (error) {
- if (!called) {
- called = true;
- handlers.reject(promise, error);
- }
- });
- }
- }
- },{"6":6}],10:[function(require,module,exports){
- /**
- * Helpers.
- */
- var s = 1000;
- var m = s * 60;
- var h = m * 60;
- var d = h * 24;
- var y = d * 365.25;
- /**
- * Parse or format the given `val`.
- *
- * Options:
- *
- * - `long` verbose formatting [false]
- *
- * @param {String|Number} val
- * @param {Object} options
- * @return {String|Number}
- * @api public
- */
- module.exports = function(val, options){
- options = options || {};
- if ('string' == typeof val) return parse(val);
- return options.long
- ? long(val)
- : short(val);
- };
- /**
- * Parse the given `str` and return milliseconds.
- *
- * @param {String} str
- * @return {Number}
- * @api private
- */
- function parse(str) {
- str = '' + str;
- if (str.length > 10000) return;
- var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str);
- if (!match) return;
- var n = parseFloat(match[1]);
- var type = (match[2] || 'ms').toLowerCase();
- switch (type) {
- case 'years':
- case 'year':
- case 'yrs':
- case 'yr':
- case 'y':
- return n * y;
- case 'days':
- case 'day':
- case 'd':
- return n * d;
- case 'hours':
- case 'hour':
- case 'hrs':
- case 'hr':
- case 'h':
- return n * h;
- case 'minutes':
- case 'minute':
- case 'mins':
- case 'min':
- case 'm':
- return n * m;
- case 'seconds':
- case 'second':
- case 'secs':
- case 'sec':
- case 's':
- return n * s;
- case 'milliseconds':
- case 'millisecond':
- case 'msecs':
- case 'msec':
- case 'ms':
- return n;
- }
- }
- /**
- * Short format for `ms`.
- *
- * @param {Number} ms
- * @return {String}
- * @api private
- */
- function short(ms) {
- if (ms >= d) return Math.round(ms / d) + 'd';
- if (ms >= h) return Math.round(ms / h) + 'h';
- if (ms >= m) return Math.round(ms / m) + 'm';
- if (ms >= s) return Math.round(ms / s) + 's';
- return ms + 'ms';
- }
- /**
- * Long format for `ms`.
- *
- * @param {Number} ms
- * @return {String}
- * @api private
- */
- function long(ms) {
- return plural(ms, d, 'day')
- || plural(ms, h, 'hour')
- || plural(ms, m, 'minute')
- || plural(ms, s, 'second')
- || ms + ' ms';
- }
- /**
- * Pluralization helper.
- */
- function plural(ms, n, name) {
- if (ms < n) return;
- if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
- return Math.ceil(ms / n) + ' ' + name + 's';
- }
- },{}],11:[function(require,module,exports){
- 'use strict';
- function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
- var lie = _interopDefault(require(9));
- var jsExtend = require(8);
- var inherits = _interopDefault(require(7));
- var getArguments = _interopDefault(require(2));
- var debug = _interopDefault(require(3));
- var events = require(5);
- // Abstracts constructing a Blob object, so it also works in older
- // browsers that don't support the native Blob constructor (e.g.
- // old QtWebKit versions, Android < 4.4).
- function createBlob(parts, properties) {
- /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
- parts = parts || [];
- properties = properties || {};
- try {
- return new Blob(parts, properties);
- } catch (e) {
- if (e.name !== "TypeError") {
- throw e;
- }
- var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder :
- typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder :
- typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder :
- WebKitBlobBuilder;
- var builder = new Builder();
- for (var i = 0; i < parts.length; i += 1) {
- builder.append(parts[i]);
- }
- return builder.getBlob(properties.type);
- }
- }
- // simplified API. universal browser support is assumed
- function readAsArrayBuffer(blob, callback) {
- if (typeof FileReader === 'undefined') {
- // fix for Firefox in a web worker:
- // https://bugzilla.mozilla.org/show_bug.cgi?id=901097
- return callback(new FileReaderSync().readAsArrayBuffer(blob));
- }
- var reader = new FileReader();
- reader.onloadend = function (e) {
- var result = e.target.result || new ArrayBuffer(0);
- callback(result);
- };
- reader.readAsArrayBuffer(blob);
- }
- /* istanbul ignore next */
- var PouchPromise = typeof Promise === 'function' ? Promise : lie;
- /* global fetch */
- /* global Headers */
- function wrappedFetch() {
- var wrappedPromise = {};
- var promise = new PouchPromise(function (resolve, reject) {
- wrappedPromise.resolve = resolve;
- wrappedPromise.reject = reject;
- });
- var args = new Array(arguments.length);
- for (var i = 0; i < args.length; i++) {
- args[i] = arguments[i];
- }
- wrappedPromise.promise = promise;
- PouchPromise.resolve().then(function () {
- return fetch.apply(null, args);
- }).then(function (response) {
- wrappedPromise.resolve(response);
- }).catch(function (error) {
- wrappedPromise.reject(error);
- });
- return wrappedPromise;
- }
- function fetchRequest(options, callback) {
- var wrappedPromise, timer, response;
- var headers = new Headers();
- var fetchOptions = {
- method: options.method,
- credentials: 'include',
- headers: headers
- };
- if (options.json) {
- headers.set('Accept', 'application/json');
- headers.set('Content-Type', options.headers['Content-Type'] ||
- 'application/json');
- }
- if (options.body && (options.body instanceof Blob)) {
- readAsArrayBuffer(options.body, function (arrayBuffer) {
- fetchOptions.body = arrayBuffer;
- });
- } else if (options.body &&
- options.processData &&
- typeof options.body !== 'string') {
- fetchOptions.body = JSON.stringify(options.body);
- } else if ('body' in options) {
- fetchOptions.body = options.body;
- } else {
- fetchOptions.body = null;
- }
- Object.keys(options.headers).forEach(function (key) {
- if (options.headers.hasOwnProperty(key)) {
- headers.set(key, options.headers[key]);
- }
- });
- wrappedPromise = wrappedFetch(options.url, fetchOptions);
- if (options.timeout > 0) {
- timer = setTimeout(function () {
- wrappedPromise.reject(new Error('Load timeout for resource: ' +
- options.url));
- }, options.timeout);
- }
- wrappedPromise.promise.then(function (fetchResponse) {
- response = {
- statusCode: fetchResponse.status
- };
- if (options.timeout > 0) {
- clearTimeout(timer);
- }
- if (response.statusCode >= 200 && response.statusCode < 300) {
- return options.binary ? fetchResponse.blob() : fetchResponse.text();
- }
- return fetchResponse.json();
- }).then(function (result) {
- if (response.statusCode >= 200 && response.statusCode < 300) {
- callback(null, response, result);
- } else {
- callback(result, response);
- }
- }).catch(function (error) {
- callback(error, response);
- });
- return {abort: wrappedPromise.reject};
- }
- function xhRequest(options, callback) {
- var xhr, timer;
- var timedout = false;
- var abortReq = function () {
- xhr.abort();
- cleanUp();
- };
- var timeoutReq = function () {
- timedout = true;
- xhr.abort();
- cleanUp();
- };
- var ret = {abort: abortReq};
- var cleanUp = function () {
- clearTimeout(timer);
- ret.abort = function () {};
- if (xhr) {
- xhr.onprogress = undefined;
- if (xhr.upload) {
- xhr.upload.onprogress = undefined;
- }
- xhr.onreadystatechange = undefined;
- xhr = undefined;
- }
- };
- if (options.xhr) {
- xhr = new options.xhr();
- } else {
- xhr = new XMLHttpRequest();
- }
- try {
- xhr.open(options.method, options.url);
- } catch (exception) {
- return callback(new Error(exception.name || 'Url is invalid'));
- }
- xhr.withCredentials = ('withCredentials' in options) ?
- options.withCredentials : true;
- if (options.method === 'GET') {
- delete options.headers['Content-Type'];
- } else if (options.json) {
- options.headers.Accept = 'application/json';
- options.headers['Content-Type'] = options.headers['Content-Type'] ||
- 'application/json';
- if (options.body &&
- options.processData &&
- typeof options.body !== "string") {
- options.body = JSON.stringify(options.body);
- }
- }
- if (options.binary) {
- xhr.responseType = 'arraybuffer';
- }
- if (!('body' in options)) {
- options.body = null;
- }
- for (var key in options.headers) {
- if (options.headers.hasOwnProperty(key)) {
- xhr.setRequestHeader(key, options.headers[key]);
- }
- }
- if (options.timeout > 0) {
- timer = setTimeout(timeoutReq, options.timeout);
- xhr.onprogress = function () {
- clearTimeout(timer);
- if(xhr.readyState !== 4) {
- timer = setTimeout(timeoutReq, options.timeout);
- }
- };
- if (typeof xhr.upload !== 'undefined') { // does not exist in ie9
- xhr.upload.onprogress = xhr.onprogress;
- }
- }
- xhr.onreadystatechange = function () {
- if (xhr.readyState !== 4) {
- return;
- }
- var response = {
- statusCode: xhr.status
- };
- if (xhr.status >= 200 && xhr.status < 300) {
- var data;
- if (options.binary) {
- data = createBlob([xhr.response || ''], {
- type: xhr.getResponseHeader('Content-Type')
- });
- } else {
- data = xhr.responseText;
- }
- callback(null, response, data);
- } else {
- var err = {};
- if (timedout) {
- err = new Error('ETIMEDOUT');
- err.code = 'ETIMEDOUT';
- } else if (typeof xhr.response === 'string') {
- try {
- err = JSON.parse(xhr.response);
- } catch(e) {}
- }
- err.status = xhr.status;
- callback(err);
- }
- cleanUp();
- };
- if (options.body && (options.body instanceof Blob)) {
- readAsArrayBuffer(options.body, function (arrayBuffer) {
- xhr.send(arrayBuffer);
- });
- } else {
- xhr.send(options.body);
- }
- return ret;
- }
- function testXhr() {
- try {
- new XMLHttpRequest();
- return true;
- } catch (err) {
- return false;
- }
- }
- var hasXhr = testXhr();
- function ajax$1(options, callback) {
- if (hasXhr || options.xhr) {
- return xhRequest(options, callback);
- } else {
- return fetchRequest(options, callback);
- }
- }
- inherits(PouchError, Error);
- function PouchError(opts) {
- Error.call(this, opts.reason);
- this.status = opts.status;
- this.name = opts.error;
- this.message = opts.reason;
- this.error = true;
- }
- PouchError.prototype.toString = function () {
- return JSON.stringify({
- status: this.status,
- name: this.name,
- message: this.message,
- reason: this.reason
- });
- };
- var UNAUTHORIZED = new PouchError({
- status: 401,
- error: 'unauthorized',
- reason: "Name or password is incorrect."
- });
- var MISSING_BULK_DOCS = new PouchError({
- status: 400,
- error: 'bad_request',
- reason: "Missing JSON list of 'docs'"
- });
- var MISSING_DOC = new PouchError({
- status: 404,
- error: 'not_found',
- reason: 'missing'
- });
- var REV_CONFLICT = new PouchError({
- status: 409,
- error: 'conflict',
- reason: 'Document update conflict'
- });
- var INVALID_ID = new PouchError({
- status: 400,
- error: 'bad_request',
- reason: '_id field must contain a string'
- });
- var MISSING_ID = new PouchError({
- status: 412,
- error: 'missing_id',
- reason: '_id is required for puts'
- });
- var RESERVED_ID = new PouchError({
- status: 400,
- error: 'bad_request',
- reason: 'Only reserved document ids may start with underscore.'
- });
- var NOT_OPEN = new PouchError({
- status: 412,
- error: 'precondition_failed',
- reason: 'Database not open'
- });
- var UNKNOWN_ERROR = new PouchError({
- status: 500,
- error: 'unknown_error',
- reason: 'Database encountered an unknown error'
- });
- var BAD_ARG = new PouchError({
- status: 500,
- error: 'badarg',
- reason: 'Some query argument is invalid'
- });
- var INVALID_REQUEST = new PouchError({
- status: 400,
- error: 'invalid_request',
- reason: 'Request was invalid'
- });
- var QUERY_PARSE_ERROR = new PouchError({
- status: 400,
- error: 'query_parse_error',
- reason: 'Some query parameter is invalid'
- });
- var DOC_VALIDATION = new PouchError({
- status: 500,
- error: 'doc_validation',
- reason: 'Bad special document member'
- });
- var BAD_REQUEST = new PouchError({
- status: 400,
- error: 'bad_request',
- reason: 'Something wrong with the request'
- });
- var NOT_AN_OBJECT = new PouchError({
- status: 400,
- error: 'bad_request',
- reason: 'Document must be a JSON object'
- });
- var DB_MISSING = new PouchError({
- status: 404,
- error: 'not_found',
- reason: 'Database not found'
- });
- var IDB_ERROR = new PouchError({
- status: 500,
- error: 'indexed_db_went_bad',
- reason: 'unknown'
- });
- var WSQ_ERROR = new PouchError({
- status: 500,
- error: 'web_sql_went_bad',
- reason: 'unknown'
- });
- var LDB_ERROR = new PouchError({
- status: 500,
- error: 'levelDB_went_went_bad',
- reason: 'unknown'
- });
- var FORBIDDEN = new PouchError({
- status: 403,
- error: 'forbidden',
- reason: 'Forbidden by design doc validate_doc_update function'
- });
- var INVALID_REV = new PouchError({
- status: 400,
- error: 'bad_request',
- reason: 'Invalid rev format'
- });
- var FILE_EXISTS = new PouchError({
- status: 412,
- error: 'file_exists',
- reason: 'The database could not be created, the file already exists.'
- });
- var MISSING_STUB = new PouchError({
- status: 412,
- error: 'missing_stub'
- });
- var INVALID_URL = new PouchError({
- status: 413,
- error: 'invalid_url',
- reason: 'Provided URL is invalid'
- });
- function generateErrorFromResponse(err) {
- if (typeof err !== 'object') {
- var data = err;
- err = UNKNOWN_ERROR;
- err.data = data;
- }
- if ('error' in err && err.error === 'conflict') {
- err.name = 'conflict';
- err.status = 409;
- }
- if (!('name' in err)) {
- err.name = err.error || 'unknown';
- }
- if (!('status' in err)) {
- err.status = 500;
- }
- if (!('message' in err)) {
- err.message = err.message || err.reason;
- }
- return err;
- }
- function isBinaryObject(object) {
- return (typeof ArrayBuffer !== 'undefined' && object instanceof ArrayBuffer) ||
- (typeof Blob !== 'undefined' && object instanceof Blob);
- }
- function cloneArrayBuffer(buff) {
- if (typeof buff.slice === 'function') {
- return buff.slice(0);
- }
- // IE10-11 slice() polyfill
- var target = new ArrayBuffer(buff.byteLength);
- var targetArray = new Uint8Array(target);
- var sourceArray = new Uint8Array(buff);
- targetArray.set(sourceArray);
- return target;
- }
- function cloneBinaryObject(object) {
- if (object instanceof ArrayBuffer) {
- return cloneArrayBuffer(object);
- }
- var size = object.size;
- var type = object.type;
- // Blob
- if (typeof object.slice === 'function') {
- return object.slice(0, size, type);
- }
- // PhantomJS slice() replacement
- return object.webkitSlice(0, size, type);
- }
- // most of this is borrowed from lodash.isPlainObject:
- // https://github.com/fis-components/lodash.isplainobject/
- // blob/29c358140a74f252aeb08c9eb28bef86f2217d4a/index.js
- var funcToString = Function.prototype.toString;
- var objectCtorString = funcToString.call(Object);
- function isPlainObject(value) {
- var proto = Object.getPrototypeOf(value);
- /* istanbul ignore if */
- if (proto === null) { // not sure when this happens, but I guess it can
- return true;
- }
- var Ctor = proto.constructor;
- return (typeof Ctor == 'function' &&
- Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
- }
- function clone(object) {
- var newObject;
- var i;
- var len;
- if (!object || typeof object !== 'object') {
- return object;
- }
- if (Array.isArray(object)) {
- newObject = [];
- for (i = 0, len = object.length; i < len; i++) {
- newObject[i] = clone(object[i]);
- }
- return newObject;
- }
- // special case: to avoid inconsistencies between IndexedDB
- // and other backends, we automatically stringify Dates
- if (object instanceof Date) {
- return object.toISOString();
- }
- if (isBinaryObject(object)) {
- return cloneBinaryObject(object);
- }
- if (!isPlainObject(object)) {
- return object; // don't clone objects like Workers
- }
- newObject = {};
- for (i in object) {
- /* istanbul ignore else */
- if (Object.prototype.hasOwnProperty.call(object, i)) {
- var value = clone(object[i]);
- if (typeof value !== 'undefined') {
- newObject[i] = value;
- }
- }
- }
- return newObject;
- }
- var log = debug('pouchdb:api');
- // like underscore/lodash _.pick()
- function pick(obj, arr) {
- var res = {};
- for (var i = 0, len = arr.length; i < len; i++) {
- var prop = arr[i];
- if (prop in obj) {
- res[prop] = obj[prop];
- }
- }
- return res;
- }
- function isChromeApp() {
- return (typeof chrome !== "undefined" &&
- typeof chrome.storage !== "undefined" &&
- typeof chrome.storage.local !== "undefined");
- }
- var hasLocal;
- if (isChromeApp()) {
- hasLocal = false;
- } else {
- try {
- localStorage.setItem('_pouch_check_localstorage', 1);
- hasLocal = !!localStorage.getItem('_pouch_check_localstorage');
- } catch (e) {
- hasLocal = false;
- }
- }
- function hasLocalStorage() {
- return hasLocal;
- }
- inherits(Changes, events.EventEmitter);
- /* istanbul ignore next */
- function attachBrowserEvents(self) {
- if (isChromeApp()) {
- chrome.storage.onChanged.addListener(function (e) {
- // make sure it's event addressed to us
- if (e.db_name != null) {
- //object only has oldValue, newValue members
- self.emit(e.dbName.newValue);
- }
- });
- } else if (hasLocalStorage()) {
- if (typeof addEventListener !== 'undefined') {
- addEventListener("storage", function (e) {
- self.emit(e.key);
- });
- } else { // old IE
- window.attachEvent("storage", function (e) {
- self.emit(e.key);
- });
- }
- }
- }
- function Changes() {
- events.EventEmitter.call(this);
- this._listeners = {};
- attachBrowserEvents(this);
- }
- Changes.prototype.addListener = function (dbName, id, db, opts) {
- /* istanbul ignore if */
- if (this._listeners[id]) {
- return;
- }
- var self = this;
- var inprogress = false;
- function eventFunction() {
- /* istanbul ignore if */
- if (!self._listeners[id]) {
- return;
- }
- if (inprogress) {
- inprogress = 'waiting';
- return;
- }
- inprogress = true;
- var changesOpts = pick(opts, [
- 'style', 'include_docs', 'attachments', 'conflicts', 'filter',
- 'doc_ids', 'view', 'since', 'query_params', 'binary'
- ]);
- /* istanbul ignore next */
- function onError() {
- inprogress = false;
- }
- db.changes(changesOpts).on('change', function (c) {
- if (c.seq > opts.since && !opts.cancelled) {
- opts.since = c.seq;
- opts.onChange(c);
- }
- }).on('complete', function () {
- if (inprogress === 'waiting') {
- setTimeout(function (){
- eventFunction();
- },0);
- }
- inprogress = false;
- }).on('error', onError);
- }
- this._listeners[id] = eventFunction;
- this.on(dbName, eventFunction);
- };
- Changes.prototype.removeListener = function (dbName, id) {
- /* istanbul ignore if */
- if (!(id in this._listeners)) {
- return;
- }
- events.EventEmitter.prototype.removeListener.call(this, dbName,
- this._listeners[id]);
- delete this._listeners[id];
- };
- /* istanbul ignore next */
- Changes.prototype.notifyLocalWindows = function (dbName) {
- //do a useless change on a storage thing
- //in order to get other windows's listeners to activate
- if (isChromeApp()) {
- chrome.storage.local.set({dbName: dbName});
- } else if (hasLocalStorage()) {
- localStorage[dbName] = (localStorage[dbName] === "a") ? "b" : "a";
- }
- };
- Changes.prototype.notify = function (dbName) {
- this.emit(dbName);
- this.notifyLocalWindows(dbName);
- };
- // BEGIN Math.uuid.js
- /*!
- Math.uuid.js (v1.4)
- http://www.broofa.com
- mailto:[email protected]
- Copyright (c) 2010 Robert Kieffer
- Dual licensed under the MIT and GPL licenses.
- */
- /*
- * Generate a random uuid.
- *
- * USAGE: Math.uuid(length, radix)
- * length - the desired number of characters
- * radix - the number of allowable values for each character.
- *
- * EXAMPLES:
- * // No arguments - returns RFC4122, version 4 ID
- * >>> Math.uuid()
- * "92329D39-6F5C-4520-ABFC-AAB64544E172"
- *
- * // One argument - returns ID of the specified length
- * >>> Math.uuid(15) // 15 character ID (default base=62)
- * "VcydxgltxrVZSTV"
- *
- * // Two arguments - returns ID of the specified length, and radix.
- * // (Radix must be <= 62)
- * >>> Math.uuid(8, 2) // 8 character ID (base=2)
- * "01001010"
- * >>> Math.uuid(8, 10) // 8 character ID (base=10)
- * "47473046"
- * >>> Math.uuid(8, 16) // 8 character ID (base=16)
- * "098F4D35"
- */
- var chars = (
- '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
- 'abcdefghijklmnopqrstuvwxyz'
- ).split('');
- // the blob already has a type; do nothing
- var res$2 = function () {};
- function defaultBody() {
- return '';
- }
- function ajaxCore(options, callback) {
- options = clone(options);
- var defaultOptions = {
- method : "GET",
- headers: {},
- json: true,
- processData: true,
- timeout: 10000,
- cache: false
- };
- options = jsExtend.extend(defaultOptions, options);
- function onSuccess(obj, resp, cb) {
- if (!options.binary && options.json && typeof obj === 'string') {
- /* istanbul ignore next */
- try {
- obj = JSON.parse(obj);
- } catch (e) {
- // Probably a malformed JSON from server
- return cb(e);
- }
- }
- if (Array.isArray(obj)) {
- obj = obj.map(function (v) {
- if (v.error || v.missing) {
- return generateErrorFromResponse(v);
- } else {
- return v;
- }
- });
- }
- if (options.binary) {
- res$2(obj, resp);
- }
- cb(null, obj, resp);
- }
- if (options.json) {
- if (!options.binary) {
- options.headers.Accept = 'application/json';
- }
- options.headers['Content-Type'] = options.headers['Content-Type'] ||
- 'application/json';
- }
- if (options.binary) {
- options.encoding = null;
- options.json = false;
- }
- if (!options.processData) {
- options.json = false;
- }
- return ajax$1(options, function (err, response, body) {
- if (err) {
- return callback(generateErrorFromResponse(err));
- }
- var error;
- var content_type = response.headers && response.headers['content-type'];
- var data = body || defaultBody();
- // CouchDB doesn't always return the right content-type for JSON data, so
- // we check for ^{ and }$ (ignoring leading/trailing whitespace)
- if (!options.binary && (options.json || !options.processData) &&
- typeof data !== 'object' &&
- (/json/.test(content_type) ||
- (/^[\s]*\{/.test(data) && /\}[\s]*$/.test(data)))) {
- try {
- data = JSON.parse(data.toString());
- } catch (e) {}
- }
- if (response.statusCode >= 200 && response.statusCode < 300) {
- onSuccess(data, response, callback);
- } else {
- error = generateErrorFromResponse(data);
- error.status = response.statusCode;
- callback(error);
- }
- });
- }
- function ajax(opts, callback) {
- // cache-buster, specifically designed to work around IE's aggressive caching
- // see http://www.dashbay.com/2011/05/internet-explorer-caches-ajax/
- // Also Safari caches POSTs, so we need to cache-bust those too.
- var ua = (navigator && navigator.userAgent) ?
- navigator.userAgent.toLowerCase() : '';
- var isSafari = ua.indexOf('safari') !== -1 && ua.indexOf('chrome') === -1;
- var isIE = ua.indexOf('msie') !== -1;
- var isEdge = ua.indexOf('edge') !== -1;
- // it appears the new version of safari also caches GETs,
- // see https://github.com/pouchdb/pouchdb/issues/5010
- var shouldCacheBust = (isSafari ||
- ((isIE || isEdge) && opts.method === 'GET'));
- var cache = 'cache' in opts ? opts.cache : true;
- var isBlobUrl = /^blob:/.test(opts.url); // don't append nonces for blob URLs
- if (!isBlobUrl && (shouldCacheBust || !cache)) {
- var hasArgs = opts.url.indexOf('?') !== -1;
- opts.url += (hasArgs ? '&' : '?') + '_nonce=' + Date.now();
- }
- return ajaxCore(opts, callback);
- }
- module.exports = ajax;
- },{"2":2,"3":3,"5":5,"7":7,"8":8,"9":9}],12:[function(require,module,exports){
- "use strict";
- // Extends method
- // (taken from http://code.jquery.com/jquery-1.9.0.js)
- // Populate the class2type map
- var class2type = {};
- var types = [
- "Boolean", "Number", "String", "Function", "Array",
- "Date", "RegExp", "Object", "Error"
- ];
- for (var i = 0; i < types.length; i++) {
- var typename = types[i];
- class2type["[object " + typename + "]"] = typename.toLowerCase();
- }
- var core_toString = class2type.toString;
- var core_hasOwn = class2type.hasOwnProperty;
- function type(obj) {
- if (obj === null) {
- return String(obj);
- }
- return typeof obj === "object" || typeof obj === "function" ?
- class2type[core_toString.call(obj)] || "object" :
- typeof obj;
- }
- function isWindow(obj) {
- return obj !== null && obj === obj.window;
- }
- function isPlainObject(obj) {
- // Must be an Object.
- // Because of IE, we also have to check the presence of
- // the constructor property.
- // Make sure that DOM nodes and window objects don't pass through, as well
- if (!obj || type(obj) !== "object" || obj.nodeType || isWindow(obj)) {
- return false;
- }
- try {
- // Not own constructor property must be Object
- if (obj.constructor &&
- !core_hasOwn.call(obj, "constructor") &&
- !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) {
- return false;
- }
- } catch ( e ) {
- // IE8,9 Will throw exceptions on certain host objects #9897
- return false;
- }
- // Own properties are enumerated firstly, so to speed up,
- // if last one is own, then all properties are own.
- var key;
- for (key in obj) {}
- return key === undefined || core_hasOwn.call(obj, key);
- }
- function isFunction(obj) {
- return type(obj) === "function";
- }
- var isArray = Array.isArray || function (obj) {
- return type(obj) === "array";
- };
- function extend() {
- // originally extend() was recursive, but this ended up giving us
- // "call stack exceeded", so it's been unrolled to use a literal stack
- // (see https://github.com/pouchdb/pouchdb/issues/2543)
- var stack = [];
- var i = -1;
- var len = arguments.length;
- var args = new Array(len);
- while (++i < len) {
- args[i] = arguments[i];
- }
- var container = {};
- stack.push({args: args, result: {container: container, key: 'key'}});
- var next;
- while ((next = stack.pop())) {
- extendInner(stack, next.args, next.result);
- }
- return container.key;
- }
- function extendInner(stack, args, result) {
- var options, name, src, copy, copyIsArray, clone,
- target = args[0] || {},
- i = 1,
- length = args.length,
- deep = false,
- numericStringRegex = /\d+/,
- optionsIsArray;
- // Handle a deep copy situation
- if (typeof target === "boolean") {
- deep = target;
- target = args[1] || {};
- // skip the boolean and the target
- i = 2;
- }
- // Handle case when target is a string or something (possible in deep copy)
- if (typeof target !== "object" && !isFunction(target)) {
- target = {};
- }
- // extend jQuery itself if only one argument is passed
- if (length === i) {
- /* jshint validthis: true */
- target = this;
- --i;
- }
- for (; i < length; i++) {
- // Only deal with non-null/undefined values
- if ((options = args[i]) != null) {
- optionsIsArray = isArray(options);
- // Extend the base object
- for (name in options) {
- //if (options.hasOwnProperty(name)) {
- if (!(name in Object.prototype)) {
- if (optionsIsArray && !numericStringRegex.test(name)) {
- continue;
- }
- src = target[name];
- copy = options[name];
- // Prevent never-ending loop
- if (target === copy) {
- continue;
- }
- // Recurse if we're merging plain objects or arrays
- if (deep && copy && (isPlainObject(copy) ||
- (copyIsArray = isArray(copy)))) {
- if (copyIsArray) {
- copyIsArray = false;
- clone = src && isArray(src) ? src : [];
- } else {
- clone = src && isPlainObject(src) ? src : {};
- }
- // Never move original objects, clone them
- stack.push({
- args: [deep, clone, copy],
- result: {
- container: target,
- key: name
- }
- });
- // Don't bring in undefined values
- } else if (copy !== undefined) {
- if (!(isArray(options) && isFunction(copy))) {
- target[name] = copy;
- }
- }
- }
- }
- }
- }
- // "Return" the modified object by setting the key
- // on the given container
- result.container[result.key] = target;
- }
- module.exports = extend;
- },{}],13:[function(require,module,exports){
- 'use strict';
- function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
- var lie = _interopDefault(require(9));
- /* istanbul ignore next */
- var PouchPromise = typeof Promise === 'function' ? Promise : lie;
- module.exports = PouchPromise;
- },{"9":9}],14:[function(require,module,exports){
- (function (process){
- 'use strict';
- Object.defineProperty(exports, '__esModule', { value: true });
- function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
- var lie = _interopDefault(require(9));
- var getArguments = _interopDefault(require(2));
- var debug = _interopDefault(require(3));
- var events = require(5);
- var inherits = _interopDefault(require(7));
- /* istanbul ignore next */
- var PouchPromise = typeof Promise === 'function' ? Promise : lie;
- function isBinaryObject(object) {
- return (typeof ArrayBuffer !== 'undefined' && object instanceof ArrayBuffer) ||
- (typeof Blob !== 'undefined' && object instanceof Blob);
- }
- function cloneArrayBuffer(buff) {
- if (typeof buff.slice === 'function') {
- return buff.slice(0);
- }
- // IE10-11 slice() polyfill
- var target = new ArrayBuffer(buff.byteLength);
- var targetArray = new Uint8Array(target);
- var sourceArray = new Uint8Array(buff);
- targetArray.set(sourceArray);
- return target;
- }
- function cloneBinaryObject(object) {
- if (object instanceof ArrayBuffer) {
- return cloneArrayBuffer(object);
- }
- var size = object.size;
- var type = object.type;
- // Blob
- if (typeof object.slice === 'function') {
- return object.slice(0, size, type);
- }
- // PhantomJS slice() replacement
- return object.webkitSlice(0, size, type);
- }
- // most of this is borrowed from lodash.isPlainObject:
- // https://github.com/fis-components/lodash.isplainobject/
- // blob/29c358140a74f252aeb08c9eb28bef86f2217d4a/index.js
- var funcToString = Function.prototype.toString;
- var objectCtorString = funcToString.call(Object);
- function isPlainObject(value) {
- var proto = Object.getPrototypeOf(value);
- /* istanbul ignore if */
- if (proto === null) { // not sure when this happens, but I guess it can
- return true;
- }
- var Ctor = proto.constructor;
- return (typeof Ctor == 'function' &&
- Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);
- }
- function clone(object) {
- var newObject;
- var i;
- var len;
- if (!object || typeof object !== 'object') {
- return object;
- }
- if (Array.isArray(object)) {
- newObject = [];
- for (i = 0, len = object.length; i < len; i++) {
- newObject[i] = clone(object[i]);
- }
- return newObject;
- }
- // special case: to avoid inconsistencies between IndexedDB
- // and other backends, we automatically stringify Dates
- if (object instanceof Date) {
- return object.toISOString();
- }
- if (isBinaryObject(object)) {
- return cloneBinaryObject(object);
- }
- if (!isPlainObject(object)) {
- return object; // don't clone objects like Workers
- }
- newObject = {};
- for (i in object) {
- /* istanbul ignore else */
- if (Object.prototype.hasOwnProperty.call(object, i)) {
- var value = clone(object[i]);
- if (typeof value !== 'undefined') {
- newObject[i] = value;
- }
- }
- }
- return newObject;
- }
- function once(fun) {
- var called = false;
- return getArguments(function (args) {
- /* istanbul ignore if */
- if (called) {
- // this is a smoke test and should never actually happen
- throw new Error('once called more than once');
- } else {
- called = true;
- fun.apply(this, args);
- }
- });
- }
- function toPromise(func) {
- //create the function we will be returning
- return getArguments(function (args) {
- // Clone arguments
- args = clone(args);
- var self = this;
- var tempCB =
- (typeof args[args.length - 1] === 'function') ? args.pop() : false;
- // if the last argument is a function, assume its a callback
- var usedCB;
- if (tempCB) {
- // if it was a callback, create a new callback which calls it,
- // but do so async so we don't trap any errors
- usedCB = function (err, resp) {
- process.nextTick(function () {
- tempCB(err, resp);
- });
- };
- }
- var promise = new PouchPromise(function (fulfill, reject) {
- var resp;
- try {
- var callback = once(function (err, mesg) {
- if (err) {
- reject(err);
- } else {
- fulfill(mesg);
- }
- });
- // create a callback for this invocation
- // apply the function in the orig context
- args.push(callback);
- resp = func.apply(self, args);
- if (resp && typeof resp.then === 'function') {
- fulfill(resp);
- }
- } catch (e) {
- reject(e);
- }
- });
- // if there is a callback, call it back
- if (usedCB) {
- promise.then(function (result) {
- usedCB(null, result);
- }, usedCB);
- }
- return promise;
- });
- }
- var log = debug('pouchdb:api');
- function adapterFun(name, callback) {
- function logApiCall(self, name, args) {
- /* istanbul ignore if */
- if (log.enabled) {
- var logArgs = [self.name, name];
- for (var i = 0; i < args.length - 1; i++) {
- logArgs.push(args[i]);
- }
- log.apply(null, logArgs);
- // override the callback itself to log the response
- var origCallback = args[args.length - 1];
- args[args.length - 1] = function (err, res) {
- var responseArgs = [self.name, name];
- responseArgs = responseArgs.concat(
- err ? ['error', err] : ['success', res]
- );
- log.apply(null, responseArgs);
- origCallback(err, res);
- };
- }
- }
- return toPromise(getArguments(function (args) {
- if (this._closed) {
- return PouchPromise.reject(new Error('database is closed'));
- }
- if (this._destroyed) {
- return PouchPromise.reject(new Error('database is destroyed'));
- }
- var self = this;
- logApiCall(self, name, args);
- if (!this.taskqueue.isReady) {
- return new PouchPromise(function (fulfill, reject) {
- self.taskqueue.addTask(function (failed) {
- if (failed) {
- reject(failed);
- } else {
- fulfill(self[name].apply(self, args));
- }
- });
- });
- }
- return callback.apply(this, args);
- }));
- }
- // like underscore/lodash _.pick()
- function pick(obj, arr) {
- var res = {};
- for (var i = 0, len = arr.length; i < len; i++) {
- var prop = arr[i];
- if (prop in obj) {
- res[prop] = obj[prop];
- }
- }
- return res;
- }
- // Most browsers throttle concurrent requests at 6, so it's silly
- // to shim _bulk_get by trying to launch potentially hundreds of requests
- // and then letting the majority time out. We can handle this ourselves.
- var MAX_NUM_CONCURRENT_REQUESTS = 6;
- function identityFunction(x) {
- return x;
- }
- function formatResultForOpenRevsGet(result) {
- return [{
- ok: result
- }];
- }
- // shim for P/CouchDB adapters that don't directly implement _bulk_get
- function bulkGet(db, opts, callback) {
- var requests = opts.docs;
- // consolidate into one request per doc if possible
- var requestsById = {};
- requests.forEach(function (request) {
- if (request.id in requestsById) {
- requestsById[request.id].push(request);
- } else {
- requestsById[request.id] = [request];
- }
- });
- var numDocs = Object.keys(requestsById).length;
- var numDone = 0;
- var perDocResults = new Array(numDocs);
- function collapseResultsAndFinish() {
- var results = [];
- perDocResults.forEach(function (res) {
- res.docs.forEach(function (info) {
- results.push({
- id: res.id,
- docs: [info]
- });
- });
- });
- callback(null, {results: results});
- }
- function checkDone() {
- if (++numDone === numDocs) {
- collapseResultsAndFinish();
- }
- }
- function gotResult(docIndex, id, docs) {
- perDocResults[docIndex] = {id: id, docs: docs};
- checkDone();
- }
- var allRequests = Object.keys(requestsById);
- var i = 0;
- function nextBatch() {
- if (i >= allRequests.length) {
- return;
- }
- var upTo = Math.min(i + MAX_NUM_CONCURRENT_REQUESTS, allRequests.length);
- var batch = allRequests.slice(i, upTo);
- processBatch(batch, i);
- i += batch.length;
- }
- function processBatch(batch, offset) {
- batch.forEach(function (docId, j) {
- var docIdx = offset + j;
- var docRequests = requestsById[docId];
- // just use the first request as the "template"
- // TODO: The _bulk_get API allows for more subtle use cases than this,
- // but for now it is unlikely that there will be a mix of different
- // "atts_since" or "attachments" in the same request, since it's just
- // replicate.js that is using this for the moment.
- // Also, atts_since is aspirational, since we don't support it yet.
- var docOpts = pick(docRequests[0], ['atts_since', 'attachments']);
- docOpts.open_revs = docRequests.map(function (request) {
- // rev is optional, open_revs disallowed
- return request.rev;
- });
- // remove falsey / undefined revisions
- docOpts.open_revs = docOpts.open_revs.filter(identityFunction);
- var formatResult = identityFunction;
- if (docOpts.open_revs.length === 0) {
- delete docOpts.open_revs;
- // when fetching only the "winning" leaf,
- // transform the result so it looks like an open_revs
- // request
- formatResult = formatResultForOpenRevsGet;
- }
- // globally-supplied options
- ['revs', 'attachments', 'binary', 'ajax'].forEach(function (param) {
- if (param in opts) {
- docOpts[param] = opts[param];
- }
- });
- db.get(docId, docOpts, function (err, res) {
- var result;
- /* istanbul ignore if */
- if (err) {
- result = [{error: err}];
- } else {
- result = formatResult(res);
- }
- gotResult(docIdx, docId, result);
- nextBatch();
- });
- });
- }
- nextBatch();
- }
- function isChromeApp() {
- return (typeof chrome !== "undefined" &&
- typeof chrome.storage !== "undefined" &&
- typeof chrome.storage.local !== "undefined");
- }
- var hasLocal;
- if (isChromeApp()) {
- hasLocal = false;
- } else {
- try {
- localStorage.setItem('_pouch_check_localstorage', 1);
- hasLocal = !!localStorage.getItem('_pouch_check_localstorage');
- } catch (e) {
- hasLocal = false;
- }
- }
- function hasLocalStorage() {
- return hasLocal;
- }
- inherits(Changes, events.EventEmitter);
- /* istanbul ignore next */
- function attachBrowserEvents(self) {
- if (isChromeApp()) {
- chrome.storage.onChanged.addListener(function (e) {
- // make sure it's event addressed to us
- if (e.db_name != null) {
- //object only has oldValue, newValue members
- self.emit(e.dbName.newValue);
- }
- });
- } else if (hasLocalStorage()) {
- if (typeof addEventListener !== 'undefined') {
- addEventListener("storage", function (e) {
- self.emit(e.key);
- });
- } else { // old IE
- window.attachEvent("storage", function (e) {
- self.emit(e.key);
- });
- }
- }
- }
- function Changes() {
- events.EventEmitter.call(this);
- this._listeners = {};
- attachBrowserEvents(this);
- }
- Changes.prototype.addListener = function (dbName, id, db, opts) {
- /* istanbul ignore if */
- if (this._listeners[id]) {
- return;
- }
- var self = this;
- var inprogress = false;
- function eventFunction() {
- /* istanbul ignore if */
- if (!self._listeners[id]) {
- return;
- }
- if (inprogress) {
- inprogress = 'waiting';
- return;
- }
- inprogress = true;
- var changesOpts = pick(opts, [
- 'style', 'include_docs', 'attachments', 'conflicts', 'filter',
- 'doc_ids', 'view', 'since', 'query_params', 'binary'
- ]);
- /* istanbul ignore next */
- function onError() {
- inprogress = false;
- }
- db.changes(changesOpts).on('change', function (c) {
- if (c.seq > opts.since && !opts.cancelled) {
- opts.since = c.seq;
- opts.onChange(c);
- }
- }).on('complete', function () {
- if (inprogress === 'waiting') {
- setTimeout(function (){
- eventFunction();
- },0);
- }
- inprogress = false;
- }).on('error', onError);
- }
- this._listeners[id] = eventFunction;
- this.on(dbName, eventFunction);
- };
- Changes.prototype.removeListener = function (dbName, id) {
- /* istanbul ignore if */
- if (!(id in this._listeners)) {
- return;
- }
- events.EventEmitter.prototype.removeListener.call(this, dbName,
- this._listeners[id]);
- delete this._listeners[id];
- };
- /* istanbul ignore next */
- Changes.prototype.notifyLocalWindows = function (dbName) {
- //do a useless change on a storage thing
- //in order to get other windows's listeners to activate
- if (isChromeApp()) {
- chrome.storage.local.set({dbName: dbName});
- } else if (hasLocalStorage()) {
- localStorage[dbName] = (localStorage[dbName] === "a") ? "b" : "a";
- }
- };
- Changes.prototype.notify = function (dbName) {
- this.emit(dbName);
- this.notifyLocalWindows(dbName);
- };
- function guardedConsole(method) {
- /* istanbul ignore else */
- if (console !== 'undefined' && method in console) {
- var args = Array.prototype.slice.call(arguments, 1);
- console[method].apply(console, args);
- }
- }
- function randomNumber(min, max) {
- var maxTimeout = 600000; // Hard-coded default of 10 minutes
- min = parseInt(min, 10) || 0;
- max = parseInt(max, 10);
- if (max !== max || max <= min) {
- max = (min || 1) << 1; //doubling
- } else {
- max = max + 1;
- }
- // In order to not exceed maxTimeout, pick a random value between half of maxTimeout and maxTimeout
- if(max > maxTimeout) {
- min = maxTimeout >> 1; // divide by two
- max = maxTimeout;
- }
- var ratio = Math.random();
- var range = max - min;
- return ~~(range * ratio + min); // ~~ coerces to an int, but fast.
- }
- function defaultBackOff(min) {
- var max = 0;
- if (!min) {
- max = 2000;
- }
- return randomNumber(min, max);
- }
- // designed to give info to browser users, who are disturbed
- // when they see http errors in the console
- function explainError(status, str) {
- guardedConsole('info', 'The above ' + status + ' is totally normal. ' + str);
- }
- function extendInner(obj, otherObj) {
- for (var key in otherObj) {
- if (otherObj.hasOwnProperty(key)) {
- var value = clone(otherObj[key]);
- if (typeof value !== 'undefined') {
- obj[key] = value;
- }
- }
- }
- }
- function extend(obj, obj2, obj3) {
- extendInner(obj, obj2);
- if (obj3) {
- extendInner(obj, obj3);
- }
- return obj;
- }
- inherits(PouchError, Error);
- function PouchError(opts) {
- Error.call(this, opts.reason);
- this.status = opts.status;
- this.name = opts.error;
- this.message = opts.reason;
- this.error = true;
- }
- PouchError.prototype.toString = function () {
- return JSON.stringify({
- status: this.status,
- name: this.name,
- message: this.message,
- reason: this.reason
- });
- };
- var UNAUTHORIZED = new PouchError({
- status: 401,
- error: 'unauthorized',
- reason: "Name or password is incorrect."
- });
- var MISSING_BULK_DOCS = new PouchError({
- status: 400,
- error: 'bad_request',
- reason: "Missing JSON list of 'docs'"
- });
- var MISSING_DOC = new PouchError({
- status: 404,
- error: 'not_found',
- reason: 'missing'
- });
- var REV_CONFLICT = new PouchError({
- status: 409,
- error: 'conflict',
- reason: 'Document update conflict'
- });
- var INVALID_ID = new PouchError({
- status: 400,
- error: 'bad_request',
- reason: '_id field must contain a string'
- });
- var MISSING_ID = new PouchError({
- status: 412,
- error: 'missing_id',
- reason: '_id is required for puts'
- });
- var RESERVED_ID = new PouchError({
- status: 400,
- error: 'bad_request',
- reason: 'Only reserved document ids may start with underscore.'
- });
- var NOT_OPEN = new PouchError({
- status: 412,
- error: 'precondition_failed',
- reason: 'Database not open'
- });
- var UNKNOWN_ERROR = new PouchError({
- status: 500,
- error: 'unknown_error',
- reason: 'Database encountered an unknown error'
- });
- var BAD_ARG = new PouchError({
- status: 500,
- error: 'badarg',
- reason: 'Some query argument is invalid'
- });
- var INVALID_REQUEST = new PouchError({
- status: 400,
- error: 'invalid_request',
- reason: 'Request was invalid'
- });
- var QUERY_PARSE_ERROR = new PouchError({
- status: 400,
- error: 'query_parse_error',
- reason: 'Some query parameter is invalid'
- });
- var DOC_VALIDATION = new PouchError({
- status: 500,
- error: 'doc_validation',
- reason: 'Bad special document member'
- });
- var BAD_REQUEST = new PouchError({
- status: 400,
- error: 'bad_request',
- reason: 'Something wrong with the request'
- });
- var NOT_AN_OBJECT = new PouchError({
- status: 400,
- error: 'bad_request',
- reason: 'Document must be a JSON object'
- });
- var DB_MISSING = new PouchError({
- status: 404,
- error: 'not_found',
- reason: 'Database not found'
- });
- var IDB_ERROR = new PouchError({
- status: 500,
- error: 'indexed_db_went_bad',
- reason: 'unknown'
- });
- var WSQ_ERROR = new PouchError({
- status: 500,
- error: 'web_sql_went_bad',
- reason: 'unknown'
- });
- var LDB_ERROR = new PouchError({
- status: 500,
- error: 'levelDB_went_went_bad',
- reason: 'unknown'
- });
- var FORBIDDEN = new PouchError({
- status: 403,
- error: 'forbidden',
- reason: 'Forbidden by design doc validate_doc_update function'
- });
- var INVALID_REV = new PouchError({
- status: 400,
- error: 'bad_request',
- reason: 'Invalid rev format'
- });
- var FILE_EXISTS = new PouchError({
- status: 412,
- error: 'file_exists',
- reason: 'The database could not be created, the file already exists.'
- });
- var MISSING_STUB = new PouchError({
- status: 412,
- error: 'missing_stub'
- });
- var INVALID_URL = new PouchError({
- status: 413,
- error: 'invalid_url',
- reason: 'Provided URL is invalid'
- });
- function createError(error, reason) {
- function CustomPouchError(reason) {
- // inherit error properties from our parent error manually
- // so as to allow proper JSON parsing.
- /* jshint ignore:start */
- for (var p in error) {
- if (typeof error[p] !== 'function') {
- this[p] = error[p];
- }
- }
- /* jshint ignore:end */
- if (reason !== undefined) {
- this.reason = reason;
- }
- }
- CustomPouchError.prototype = PouchError.prototype;
- return new CustomPouchError(reason);
- }
- function tryFilter(filter, doc, req) {
- try {
- return !filter(doc, req);
- } catch (err) {
- var msg = 'Filter function threw: ' + err.toString();
- return createError(BAD_REQUEST, msg);
- }
- }
- function filterChange(opts) {
- var req = {};
- var hasFilter = opts.filter && typeof opts.filter === 'function';
- req.query = opts.query_params;
- return function filter(change) {
- if (!change.doc) {
- // CSG sends events on the changes feed that don't have documents,
- // this hack makes a whole lot of existing code robust.
- change.doc = {};
- }
- var filterReturn = hasFilter && tryFilter(opts.filter, change.doc, req);
- if (typeof filterReturn === 'object') {
- return filterReturn;
- }
- if (filterReturn) {
- return false;
- }
- if (!opts.include_docs) {
- delete change.doc;
- } else if (!opts.attachments) {
- for (var att in change.doc._attachments) {
- /* istanbul ignore else */
- if (change.doc._attachments.hasOwnProperty(att)) {
- change.doc._attachments[att].stub = true;
- }
- }
- }
- return true;
- };
- }
- function flatten(arrs) {
- var res = [];
- for (var i = 0, len = arrs.length; i < len; i++) {
- res = res.concat(arrs[i]);
- }
- return res;
- }
- // shim for Function.prototype.name,
- // for browsers that don't support it like IE
- /* istanbul ignore next */
- function f() {}
- var hasName = f.name;
- var res;
- // We dont run coverage in IE
- /* istanbul ignore else */
- if (hasName) {
- res = function (fun) {
- return fun.name;
- };
- } else {
- res = function (fun) {
- return fun.toString().match(/^\s*function\s*(\S*)\s*\(/)[1];
- };
- }
- var functionName = res;
- // Determine id an ID is valid
- // - invalid IDs begin with an underescore that does not begin '_design' or
- // '_local'
- // - any other string value is a valid id
- // Returns the specific error object for each case
- function invalidIdError(id) {
- var err;
- if (!id) {
- err = createError(MISSING_ID);
- } else if (typeof id !== 'string') {
- err = createError(INVALID_ID);
- } else if (/^_/.test(id) && !(/^_(design|local)/).test(id)) {
- err = createError(RESERVED_ID);
- }
- if (err) {
- throw err;
- }
- }
- function isCordova() {
- return (typeof cordova !== "undefined" ||
- typeof PhoneGap !== "undefined" ||
- typeof phonegap !== "undefined");
- }
- function listenerCount(ee, type) {
- return 'listenerCount' in ee ? ee.listenerCount(type) :
- events.EventEmitter.listenerCount(ee, type);
- }
- function parseDesignDocFunctionName(s) {
- if (!s) {
- return null;
- }
- var parts = s.split('/');
- if (parts.length === 2) {
- return parts;
- }
- if (parts.length === 1) {
- return [s, s];
- }
- return null;
- }
- function normalizeDesignDocFunctionName(s) {
- var normalized = parseDesignDocFunctionName(s);
- return normalized ? normalized.join('/') : null;
- }
- // originally parseUri 1.2.2, now patched by us
- // (c) Steven Levithan <stevenlevithan.com>
- // MIT License
- var keys = ["source", "protocol", "authority", "userInfo", "user", "password",
- "host", "port", "relative", "path", "directory", "file", "query", "anchor"];
- var qName ="queryKey";
- var qParser = /(?:^|&)([^&=]*)=?([^&]*)/g;
- // use the "loose" parser
- /* jshint maxlen: false */
- var parser = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
- function parseUri(str) {
- var m = parser.exec(str);
- var uri = {};
- var i = 14;
- while (i--) {
- var key = keys[i];
- var value = m[i] || "";
- var encoded = ['user', 'password'].indexOf(key) !== -1;
- uri[key] = encoded ? decodeURIComponent(value) : value;
- }
- uri[qName] = {};
- uri[keys[12]].replace(qParser, function ($0, $1, $2) {
- if ($1) {
- uri[qName][$1] = $2;
- }
- });
- return uri;
- }
- // this is essentially the "update sugar" function from daleharvey/pouchdb#1388
- // the diffFun tells us what delta to apply to the doc. it either returns
- // the doc, or false if it doesn't need to do an update after all
- function upsert(db, docId, diffFun) {
- return new PouchPromise(function (fulfill, reject) {
- db.get(docId, function (err, doc) {
- if (err) {
- /* istanbul ignore next */
- if (err.status !== 404) {
- return reject(err);
- }
- doc = {};
- }
- // the user might change the _rev, so save it for posterity
- var docRev = doc._rev;
- var newDoc = diffFun(doc);
- if (!newDoc) {
- // if the diffFun returns falsy, we short-circuit as
- // an optimization
- return fulfill({updated: false, rev: docRev});
- }
- // users aren't allowed to modify these values,
- // so reset them here
- newDoc._id = docId;
- newDoc._rev = docRev;
- fulfill(tryAndPut(db, newDoc, diffFun));
- });
- });
- }
- function tryAndPut(db, doc, diffFun) {
- return db.put(doc).then(function (res) {
- return {
- updated: true,
- rev: res.rev
- };
- }, function (err) {
- /* istanbul ignore next */
- if (err.status !== 409) {
- throw err;
- }
- return upsert(db, doc._id, diffFun);
- });
- }
- // BEGIN Math.uuid.js
- /*!
- Math.uuid.js (v1.4)
- http://www.broofa.com
- mailto:[email protected]
- Copyright (c) 2010 Robert Kieffer
- Dual licensed under the MIT and GPL licenses.
- */
- /*
- * Generate a random uuid.
- *
- * USAGE: Math.uuid(length, radix)
- * length - the desired number of characters
- * radix - the number of allowable values for each character.
- *
- * EXAMPLES:
- * // No arguments - returns RFC4122, version 4 ID
- * >>> Math.uuid()
- * "92329D39-6F5C-4520-ABFC-AAB64544E172"
- *
- * // One argument - returns ID of the specified length
- * >>> Math.uuid(15) // 15 character ID (default base=62)
- * "VcydxgltxrVZSTV"
- *
- * // Two arguments - returns ID of the specified length, and radix.
- * // (Radix must be <= 62)
- * >>> Math.uuid(8, 2) // 8 character ID (base=2)
- * "01001010"
- * >>> Math.uuid(8, 10) // 8 character ID (base=10)
- * "47473046"
- * >>> Math.uuid(8, 16) // 8 character ID (base=16)
- * "098F4D35"
- */
- var chars = (
- '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
- 'abcdefghijklmnopqrstuvwxyz'
- ).split('');
- function getValue(radix) {
- return 0 | Math.random() * radix;
- }
- function uuid(len, radix) {
- radix = radix || chars.length;
- var out = '';
- var i = -1;
- if (len) {
- // Compact form
- while (++i < len) {
- out += chars[getValue(radix)];
- }
- return out;
- }
- // rfc4122, version 4 form
- // Fill in random data. At i==19 set the high bits of clock sequence as
- // per rfc4122, sec. 4.1.5
- while (++i < 36) {
- switch (i) {
- case 8:
- case 13:
- case 18:
- case 23:
- out += '-';
- break;
- case 19:
- out += chars[(getValue(16) & 0x3) | 0x8];
- break;
- default:
- out += chars[getValue(16)];
- }
- }
- return out;
- }
- exports.adapterFun = adapterFun;
- exports.bulkGetShim = bulkGet;
- exports.changesHandler = Changes;
- exports.clone = clone;
- exports.defaultBackOff = defaultBackOff;
- exports.explainError = explainError;
- exports.extend = extend;
- exports.filterChange = filterChange;
- exports.flatten = flatten;
- exports.functionName = functionName;
- exports.guardedConsole = guardedConsole;
- exports.hasLocalStorage = hasLocalStorage;
- exports.invalidIdError = invalidIdError;
- exports.isChromeApp = isChromeApp;
- exports.isCordova = isCordova;
- exports.listenerCount = listenerCount;
- exports.normalizeDdocFunctionName = normalizeDesignDocFunctionName;
- exports.once = once;
- exports.parseDdocFunctionName = parseDesignDocFunctionName;
- exports.parseUri = parseUri;
- exports.pick = pick;
- exports.toPromise = toPromise;
- exports.upsert = upsert;
- exports.uuid = uuid;
- }).call(this,require(15))
- },{"15":15,"2":2,"3":3,"5":5,"7":7,"9":9}],15:[function(require,module,exports){
- // shim for using process in browser
- var process = module.exports = {};
- // cached from whatever global is present so that test runners that stub it
- // don't break things. But we need to wrap it in a try catch in case it is
- // wrapped in strict mode code which doesn't define any globals. It's inside a
- // function because try/catches deoptimize in certain engines.
- var cachedSetTimeout;
- var cachedClearTimeout;
- function defaultSetTimout() {
- throw new Error('setTimeout has not been defined');
- }
- function defaultClearTimeout () {
- throw new Error('clearTimeout has not been defined');
- }
- (function () {
- try {
- if (typeof setTimeout === 'function') {
- cachedSetTimeout = setTimeout;
- } else {
- cachedSetTimeout = defaultSetTimout;
- }
- } catch (e) {
- cachedSetTimeout = defaultSetTimout;
- }
- try {
- if (typeof clearTimeout === 'function') {
- cachedClearTimeout = clearTimeout;
- } else {
- cachedClearTimeout = defaultClearTimeout;
- }
- } catch (e) {
- cachedClearTimeout = defaultClearTimeout;
- }
- } ())
- function runTimeout(fun) {
- if (cachedSetTimeout === setTimeout) {
- //normal enviroments in sane situations
- return setTimeout(fun, 0);
- }
- // if setTimeout wasn't available but was latter defined
- if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
- cachedSetTimeout = setTimeout;
- return setTimeout(fun, 0);
- }
- try {
- // when when somebody has screwed with setTimeout but no I.E. maddness
- return cachedSetTimeout(fun, 0);
- } catch(e){
- try {
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
- return cachedSetTimeout.call(null, fun, 0);
- } catch(e){
- // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
- return cachedSetTimeout.call(this, fun, 0);
- }
- }
- }
- function runClearTimeout(marker) {
- if (cachedClearTimeout === clearTimeout) {
- //normal enviroments in sane situations
- return clearTimeout(marker);
- }
- // if clearTimeout wasn't available but was latter defined
- if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
- cachedClearTimeout = clearTimeout;
- return clearTimeout(marker);
- }
- try {
- // when when somebody has screwed with setTimeout but no I.E. maddness
- return cachedClearTimeout(marker);
- } catch (e){
- try {
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
- return cachedClearTimeout.call(null, marker);
- } catch (e){
- // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
- // Some versions of I.E. have different rules for clearTimeout vs setTimeout
- return cachedClearTimeout.call(this, marker);
- }
- }
- }
- var queue = [];
- var draining = false;
- var currentQueue;
- var queueIndex = -1;
- function cleanUpNextTick() {
- if (!draining || !currentQueue) {
- return;
- }
- draining = false;
- if (currentQueue.length) {
- queue = currentQueue.concat(queue);
- } else {
- queueIndex = -1;
- }
- if (queue.length) {
- drainQueue();
- }
- }
- function drainQueue() {
- if (draining) {
- return;
- }
- var timeout = runTimeout(cleanUpNextTick);
- draining = true;
- var len = queue.length;
- while(len) {
- currentQueue = queue;
- queue = [];
- while (++queueIndex < len) {
- if (currentQueue) {
- currentQueue[queueIndex].run();
- }
- }
- queueIndex = -1;
- len = queue.length;
- }
- currentQueue = null;
- draining = false;
- runClearTimeout(timeout);
- }
- process.nextTick = function (fun) {
- var args = new Array(arguments.length - 1);
- if (arguments.length > 1) {
- for (var i = 1; i < arguments.length; i++) {
- args[i - 1] = arguments[i];
- }
- }
- queue.push(new Item(fun, args));
- if (queue.length === 1 && !draining) {
- runTimeout(drainQueue);
- }
- };
- // v8 likes predictible objects
- function Item(fun, array) {
- this.fun = fun;
- this.array = array;
- }
- Item.prototype.run = function () {
- this.fun.apply(null, this.array);
- };
- process.title = 'browser';
- process.browser = true;
- process.env = {};
- process.argv = [];
- process.version = ''; // empty string to avoid regexp issues
- process.versions = {};
- function noop() {}
- process.on = noop;
- process.addListener = noop;
- process.once = noop;
- process.off = noop;
- process.removeListener = noop;
- process.removeAllListeners = noop;
- process.emit = noop;
- process.binding = function (name) {
- throw new Error('process.binding is not supported');
- };
- process.cwd = function () { return '/' };
- process.chdir = function (dir) {
- throw new Error('process.chdir is not supported');
- };
- process.umask = function() { return 0; };
- },{}],16:[function(require,module,exports){
- (function (name, context, definition) {
- if (typeof module !== 'undefined' && module.exports) module.exports = definition();
- else if (typeof define === 'function' && define.amd) define(definition);
- else context[name] = definition();
- })('urljoin', this, function () {
- function normalize (str, options) {
- // make sure protocol is followed by two slashes
- str = str.replace(/:\//g, '://');
- // remove consecutive slashes
- str = str.replace(/([^:\s])\/+/g, '$1/');
- // remove trailing slash before parameters or hash
- str = str.replace(/\/(\?|&|#[^!])/g, '$1');
- // replace ? in parameters with &
- str = str.replace(/(\?.+)\?/g, '$1&');
- return str;
- }
- return function () {
- var input = arguments;
- var options = {};
- if (typeof arguments[0] === 'object') {
- // new syntax with array and options
- input = arguments[0];
- options = arguments[1] || {};
- }
- var joined = [].slice.call(input, 0).join('/');
- return normalize(joined, options);
- };
- });
- },{}],17:[function(require,module,exports){
- 'use strict';
- var utils = require(1);
- function wrapError(callback) {
- // provide more helpful error message
- return function (err, res) {
- if (err) {
- if (err.name === 'unknown_error') {
- err.message = (err.message || '') +
- ' Unknown error! Did you remember to enable CORS?';
- }
- }
- return callback(err, res);
- };
- }
- function putUser(db, user, opts, callback) {
- var reservedWords = ['name', 'password', 'roles', 'type', 'salt', 'metadata'];
- if (opts.metadata) {
- for (var key in opts.metadata) {
- if (opts.hasOwnProperty(key)) {
- if (reservedWords.indexOf(key) !== -1 || key.startsWith('_')) {
- return callback(new AuthError('cannot use reserved word in metadata: "' + key + '"'));
- }
- }
- }
- user = utils.extend(true, user, opts.metadata);
- }
- var url = utils.getUsersUrl(db) + '/' + encodeURIComponent(user._id);
- var ajaxOpts = utils.extend(true, {
- method : 'PUT',
- url : url,
- body : user
- }, opts.ajax || {});
- utils.ajax(ajaxOpts, wrapError(callback));
- }
- exports.signup = utils.toPromise(function (username, password, opts, callback) {
- var db = this;
- if (typeof callback === 'undefined') {
- callback = typeof opts === 'undefined' ? (typeof password === 'undefined' ?
- username : password) : opts;
- opts = {};
- }
- if (['http', 'https'].indexOf(db.type()) === -1) {
- return callback(new AuthError('This plugin only works for the http/https adapter. ' +
- 'So you should use new PouchDB("http://mysite.com:5984/mydb") instead.'));
- } else if (!username) {
- return callback(new AuthError('You must provide a username'));
- } else if (!password) {
- return callback(new AuthError('You must provide a password'));
- }
- var userId = 'org.couchdb.user:' + username;
- var user = {
- name : username,
- password : password,
- roles : opts.roles || [],
- type : 'user',
- _id : userId
- };
- putUser(db, user, opts, callback);
- });
- exports.signUp = exports.signup;
- exports.login = utils.toPromise(function (username, password, opts, callback) {
- var db = this;
- if (typeof callback === 'undefined') {
- callback = opts;
- opts = {};
- }
- if (['http', 'https'].indexOf(db.type()) === -1) {
- return callback(new AuthError('this plugin only works for the http/https adapter'));
- }
- if (!username) {
- return callback(new AuthError('you must provide a username'));
- } else if (!password) {
- return callback(new AuthError('you must provide a password'));
- }
- var ajaxOpts = utils.extend(true, {
- method : 'POST',
- url : utils.getSessionUrl(db),
- headers : {'Content-Type': 'application/json'},
- body : JSON.stringify({name: username, password: password})
- }, opts.ajax || {});
- utils.ajax(ajaxOpts, wrapError(callback));
- });
- exports.logIn = exports.login;
- exports.logout = utils.toPromise(function (opts, callback) {
- var db = this;
- if (typeof callback === 'undefined') {
- callback = opts;
- opts = {};
- }
- var ajaxOpts = utils.extend(true, {
- method : 'DELETE',
- url : utils.getSessionUrl(db)
- }, opts.ajax || {});
- utils.ajax(ajaxOpts, wrapError(callback));
- });
- exports.logOut = exports.logout;
- exports.getSession = utils.toPromise(function (opts, callback) {
- var db = this;
- if (typeof callback === 'undefined') {
- callback = opts;
- opts = {};
- }
- var url = utils.getSessionUrl(db);
- var ajaxOpts = utils.extend(true, {
- method : 'GET',
- url : url
- }, opts.ajax || {});
- utils.ajax(ajaxOpts, wrapError(callback));
- });
- exports.getUser = utils.toPromise(function (username, opts, callback) {
- var db = this;
- if (typeof callback === 'undefined') {
- callback = typeof opts === 'undefined' ? username : opts;
- opts = {};
- }
- if (!username) {
- return callback(new AuthError('you must provide a username'));
- }
- var url = utils.getUsersUrl(db);
- var ajaxOpts = utils.extend(true, {
- method : 'GET',
- url : url + '/' + encodeURIComponent('org.couchdb.user:' + username)
- }, opts.ajax || {});
- utils.ajax(ajaxOpts, wrapError(callback));
- });
- exports.putUser = utils.toPromise(function (username, opts, callback) {
- var db = this;
- if (typeof callback === 'undefined') {
- callback = typeof opts === 'undefined' ? username : opts;
- opts = {};
- }
- if (['http', 'https'].indexOf(db.type()) === -1) {
- return callback(new AuthError('This plugin only works for the http/https adapter. ' +
- 'So you should use new PouchDB("http://mysite.com:5984/mydb") instead.'));
- } else if (!username) {
- return callback(new AuthError('You must provide a username'));
- }
- return db.getUser(username, opts, function (error, user) {
- if (error) {
- return callback(error);
- }
- putUser(db, user, opts, callback);
- });
- });
- exports.changePassword = utils.toPromise(function (username, password, opts, callback) {
- var db = this;
- if (typeof callback === 'undefined') {
- callback = typeof opts === 'undefined' ? (typeof password === 'undefined' ?
- username : password) : opts;
- opts = {};
- }
- if (['http', 'https'].indexOf(db.type()) === -1) {
- return callback(new AuthError('This plugin only works for the http/https adapter. ' +
- 'So you should use new PouchDB("http://mysite.com:5984/mydb") instead.'));
- } else if (!username) {
- return callback(new AuthError('You must provide a username'));
- } else if (!password) {
- return callback(new AuthError('You must provide a password'));
- }
- return db.getUser(username, opts, function (error, user) {
- if (error) {
- return callback(error);
- }
- user.password = password;
- var url = utils.getUsersUrl(db) + '/' + encodeURIComponent(user._id);
- var ajaxOpts = utils.extend(true, {
- method : 'PUT',
- url : url,
- body : user
- }, opts.ajax || {});
- utils.ajax(ajaxOpts, wrapError(callback));
- });
- });
- exports.changeUsername = utils.toPromise(function (oldUsername, newUsername, opts, callback) {
- var db = this;
- var USERNAME_PREFIX = 'org.couchdb.user:';
- var ajax = function (opts) {
- return new utils.Promise(function (resolve, reject) {
- utils.ajax(opts, wrapError(function (err, res) {
- if (err) {
- return reject(err);
- }
- resolve(res);
- }));
- });
- };
- var updateUser = function (user, opts) {
- var url = utils.getUsersUrl(db) + '/' + encodeURIComponent(user._id);
- var updateOpts = utils.extend(true, {
- method : 'PUT',
- url : url,
- body: user
- }, opts.ajax);
- return ajax(updateOpts);
- };
- if (typeof callback === 'undefined') {
- callback = opts;
- opts = {};
- }
- opts.ajax = opts.ajax || {};
- if (['http', 'https'].indexOf(db.type()) === -1) {
- return callback(new AuthError('This plugin only works for the http/https adapter. ' +
- 'So you should use new PouchDB("http://mysite.com:5984/mydb") instead.'));
- }
- if (!newUsername) {
- return callback(new AuthError('You must provide a new username'));
- }
- if (!oldUsername) {
- return callback(new AuthError('You must provide a username to rename'));
- }
- return db.getUser(newUsername, opts)
- .then(function () {
- var error = new AuthError('user already exists');
- error.taken = true;
- throw error;
- }, function () {
- return db.getUser(oldUsername, opts);
- })
- .then(function (user) {
- var newUser = utils.clone(user);
- delete newUser._rev;
- newUser._id = USERNAME_PREFIX + newUsername;
- newUser.name = newUsername;
- newUser.roles = opts.roles || user.roles || {};
- return updateUser(newUser, opts).then(function () {
- user._deleted = true;
- return updateUser(user, opts);
- });
- }).then(function (res) {
- callback(null, res);
- }).catch(callback);
- });
- function AuthError(message) {
- this.status = 400;
- this.name = 'authentication_error';
- this.message = message;
- this.error = true;
- try {
- Error.captureStackTrace(this, AuthError);
- } catch (e) {}
- }
- utils.inherits(AuthError, Error);
- if (typeof window !== 'undefined' && window.PouchDB) {
- window.PouchDB.plugin(exports);
- }
- },{"1":1}]},{},[17])(17)
- });
|