From 40c86d7dfa47d994ff260a6dfd717cd76910432e Mon Sep 17 00:00:00 2001 From: Simon Constans Date: Fri, 3 Mar 2017 17:15:07 +0100 Subject: [PATCH] Release v0.1.3 :rocket: --- CHANGELOG.md | 26 +++ dist/cozy-client.js | 326 +++++++++++++++++++++-------------- dist/cozy-client.js.map | 2 +- dist/cozy-client.node.js | 326 +++++++++++++++++++++-------------- dist/cozy-client.node.js.map | 2 +- package.json | 2 +- 6 files changed, 431 insertions(+), 253 deletions(-) create mode 100644 CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..df89fb35 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,26 @@ +# Change Log +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/) +and this project adheres to [Semantic Versioning](http://semver.org/). + +## [Unreleased] +### Changed +- none yet + +### Fixed +- none yet + +### Added +- none yet + +### Removed +- none yet + +## [v0.1.3] - 2017-03-03 +### Changed +- Refactoring on offline to return Promise + + +[Unreleased]: https://github.com/cozy/cozy-ui/compare/v0.1.3...HEAD +[v0.1.3]: https://github.com/cozy/cozy-ui/compare/v0.1.2...v0.1.3 diff --git a/dist/cozy-client.js b/dist/cozy-client.js index d01b678b..6b98d5e4 100644 --- a/dist/cozy-client.js +++ b/dist/cozy-client.js @@ -645,18 +645,21 @@ return /******/ (function(modules) { // webpackBootstrap init: offline.init, getDoctypes: offline.getDoctypes, // database - createDatabase: offline.createDatabase, hasDatabase: offline.hasDatabase, getDatabase: offline.getDatabase, + createDatabase: offline.createDatabase, destroyDatabase: offline.destroyDatabase, destroyAllDatabase: offline.destroyAllDatabase, // replication + hasReplication: offline.hasReplication, replicateFromCozy: offline.replicateFromCozy, - hasSync: offline.hasSync, - startAllSync: offline.startAllSync, - startSync: offline.startSync, - stopAllSync: offline.stopAllSync, - stopSync: offline.stopSync + stopReplication: offline.stopReplication, + stopAllReplication: offline.stopAllReplication, + // repeated replication + hasRepeatedReplication: offline.hasRepeatedReplication, + startRepeatedReplication: offline.startRepeatedReplication, + stopRepeatedReplication: offline.stopRepeatedReplication, + stopAllRepeatedReplication: offline.stopAllRepeatedReplication }; var settingsProto = { @@ -2675,23 +2678,22 @@ return /******/ (function(modules) { // webpackBootstrap Object.defineProperty(exports, "__esModule", { value: true }); - - var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - exports.init = init; - exports.createDatabase = createDatabase; + exports.getDoctypes = getDoctypes; exports.hasDatabase = hasDatabase; exports.getDatabase = getDatabase; + exports.setDatabase = setDatabase; + exports.createDatabase = createDatabase; exports.destroyDatabase = destroyDatabase; exports.destroyAllDatabase = destroyAllDatabase; - exports.getDoctypes = getDoctypes; - exports.startAllSync = startAllSync; - exports.stopAllSync = stopAllSync; - exports.startSync = startSync; - exports.hasSync = hasSync; - exports.stopSync = stopSync; + exports.hasReplication = hasReplication; exports.replicateFromCozy = replicateFromCozy; - exports.replicateFromCozyWithAuth = replicateFromCozyWithAuth; + exports.stopReplication = stopReplication; + exports.stopAllReplication = stopAllReplication; + exports.hasRepeatedReplication = hasRepeatedReplication; + exports.startRepeatedReplication = startRepeatedReplication; + exports.stopRepeatedReplication = stopRepeatedReplication; + exports.stopAllRepeatedReplication = stopAllRepeatedReplication; var _pouchdb = __webpack_require__(15); @@ -2707,12 +2709,21 @@ return /******/ (function(modules) { // webpackBootstrap var pluginLoaded = false; + /* + For each doctype we have some parameters: + cozy._offline[doctype] = { + database: pouchdb database + replication: the pouchdb replication + replicationPromise: promise of replication + interval: repeated replication interval + } + */ + function init(cozy, _ref) { var _ref$options = _ref.options, options = _ref$options === undefined ? {} : _ref$options, _ref$doctypes = _ref.doctypes, - doctypes = _ref$doctypes === undefined ? [] : _ref$doctypes, - timer = _ref.timer; + doctypes = _ref$doctypes === undefined ? [] : _ref$doctypes; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; @@ -2737,163 +2748,228 @@ return /******/ (function(modules) { // webpackBootstrap } } } - - if (timer !== undefined) { - startAllSync(cozy, timer); - } } - function createDatabase(cozy, doctype) { - var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - var timer = arguments[3]; + // helper - if (!pluginLoaded) { - _pouchdb2.default.plugin(_pouchdbFind2.default); - pluginLoaded = true; - } + function getInfo(cozy, doctype) { cozy._offline = cozy._offline || []; cozy._offline[doctype] = cozy._offline[doctype] || {}; - var offline = cozy._offline[doctype]; - if (offline && offline.database) { - return offline.database; - } - offline.database = new _pouchdb2.default(doctype, options); - offline.timer = timer; - offline.autoSync = null; - if (timer !== undefined) { - startSync(cozy, doctype, timer); - } - createIndexes(cozy, offline.database, doctype); - return offline.database; + return cozy._offline[doctype]; + } + + function getDoctypes(cozy) { + cozy._offline = cozy._offline || []; + return Object.keys(cozy._offline); } + // + // DATABASE + // + function hasDatabase(cozy, doctype) { - return cozy._offline !== null && doctype in cozy._offline && cozy._offline[doctype].database !== undefined; + return getDatabase(cozy, doctype) !== undefined; } function getDatabase(cozy, doctype) { + return getInfo(cozy, doctype).database; + } + + function setDatabase(cozy, doctype, database) { + cozy._offline[doctype].database = database; + return getDatabase(cozy, doctype); + } + + function errorDatabase(doctype) { + return new Error('You should add this doctype: ' + doctype + ' to offline.'); + } + + function createDatabase(cozy, doctype) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + if (!pluginLoaded) { + _pouchdb2.default.plugin(_pouchdbFind2.default); + pluginLoaded = true; + } + if (hasDatabase(cozy, doctype)) { - return cozy._offline[doctype].database; + return Promise.resolve(getDatabase(cozy, doctype)); } - return; + + setDatabase(cozy, doctype, new _pouchdb2.default(doctype, options)); + return createIndexes(cozy, doctype).then(function () { + return getDatabase(cozy, doctype); + }); } function destroyDatabase(cozy, doctype) { - if (hasDatabase(cozy, doctype)) { - stopSync(cozy, doctype); - getDatabase(cozy, doctype).destroy(); - delete getDatabase(cozy, doctype); + if (!hasDatabase(cozy, doctype)) { + return Promise.resolve(false); } + + return stopRepeatedReplication(cozy, doctype).then(function () { + return stopReplication(cozy, doctype); + }).then(function () { + return getDatabase(cozy, doctype).destroy(); + }).then(function (response) { + setDatabase(cozy, doctype, undefined); + return response; + }); } function destroyAllDatabase(cozy) { - getDoctypes(cozy).forEach(function (doctype) { + var doctypes = getDoctypes(cozy); + var destroy = function destroy(doctype) { return destroyDatabase(cozy, doctype); - }); + }; + return Promise.all(doctypes.map(destroy)); } - function getDoctypes(cozy) { - if (cozy._offline === null) { - return []; + function createIndexes(cozy, doctype) { + if (doctype === _doctypes.DOCTYPE_FILES) { + return getDatabase(cozy, doctype).createIndex({ index: { fields: ['dir_id'] } }); } - return Object.keys(cozy._offline); + return Promise.resolve(); } // - // SYNC + // REPLICATION // - function startAllSync(cozy, timer) { - if (timer) { - var doctypes = getDoctypes(cozy); - doctypes.forEach(function (doctype) { - startSync(cozy, doctype, timer); - }); - } + function hasReplication(cozy, doctype) { + return getReplication(cozy, doctype) !== undefined; } - function stopAllSync(cozy) { - var doctypes = getDoctypes(cozy); - doctypes.forEach(function (doctype) { - stopSync(cozy, doctype); - }); + function getReplication(cozy, doctype) { + return getInfo(cozy, doctype).replication; } - function startSync(cozy, doctype, timer) { - // TODO: add timer limitation for not flooding Gozy - if (hasDatabase(cozy, doctype)) { - var _ret = function () { - if (hasSync(cozy, doctype)) { - if (timer === cozy._offline[doctype].timer) { - return { - v: void 0 - }; - } - stopSync(cozy, doctype); - } - var offline = cozy._offline[doctype]; - offline.timer = timer; - offline.autoSync = setInterval(function () { - if (offline.replicate === undefined) { - replicateFromCozy(cozy, doctype); - // TODO: add replicationToCozy - } - }, timer * 1000); - }(); + function setReplication(cozy, doctype, replication) { + cozy._offline[doctype].replication = replication; + return getReplication(cozy, doctype); + } - if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; - } + function getReplicationUrl(cozy, doctype) { + return cozy.authorize().then(function (credentials) { + var basic = credentials.token.toBasicAuth(); + return (cozy._url + '/data/' + doctype).replace('//', '//' + basic); + }); } - function hasSync(cozy, doctype) { - return cozy._offline !== null && doctype in cozy._offline && cozy._offline[doctype].autoSync !== null; + function getReplicationPromise(cozy, doctype) { + return getInfo(cozy, doctype).replicationPromise; } - function stopSync(cozy, doctype) { - if (hasSync(cozy, doctype)) { - var offline = cozy._offline[doctype]; - clearInterval(offline.autoSync); - delete offline.autoSync; - if (offline.replication) { - offline.replication.cancel(); - } - } + function setReplicationPromise(cozy, doctype, promise) { + cozy._offline[doctype].replicationPromise = promise; + return getReplicationPromise(cozy, doctype); } function replicateFromCozy(cozy, doctype) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - if (hasDatabase(cozy, doctype)) { - if (options.live === true) { - return Promise.reject(new Error('You can\'t use `live` option with Cozy couchdb.')); + return setReplicationPromise(cozy, doctype, new Promise(function (resolve, reject) { + if (!hasDatabase(cozy, doctype)) { + return reject(errorDatabase(doctype)); } - if (options.manualAuthCredentials) { - return Promise.resolve(replicateFromCozyWithAuth(cozy, doctype, options, options.manualAuthCredentials)); - } else { - return cozy.authorize().then(function (credentials) { - return replicateFromCozyWithAuth(cozy, doctype, options, credentials); + if (options.live === true) { + return reject(new Error('You can\'t use `live` option with Cozy couchdb.')); + } + + getReplicationUrl(cozy, doctype).then(function (url) { + return setReplication(cozy, doctype, getDatabase(cozy, doctype).replicate.from(url, options).on('complete', function (info) { + setReplication(cozy, doctype, undefined); + resolve(info); + }).on('error', function (err) { + console.warn('ReplicateFromCozy \'' + doctype + '\' Error:'); + console.warn(err); + setReplication(cozy, doctype, undefined); + reject(err); + })); + }); + })); + } + + function stopReplication(cozy, doctype) { + if (!getDatabase(cozy, doctype) || !hasReplication(cozy, doctype)) { + return Promise.resolve(); + } + + return new Promise(function (resolve) { + try { + getReplicationPromise(cozy, doctype).then(function () { + resolve(); }); + getReplication(cozy, doctype).cancel(); + // replication is set to undefined by complete replication + } catch (e) { + resolve(); } - } else { - return Promise.reject(new Error('You should add this doctype: ' + doctype + ' to offline.')); - } + }); } - function replicateFromCozyWithAuth(cozy, doctype, options, credentials) { - var basic = credentials.token.toBasicAuth(); - var url = (cozy._url + '/data/' + doctype).replace('//', '//' + basic); - var db = getDatabase(cozy, doctype); - var offline = cozy._offline[doctype]; - offline.replication = db.replicate.from(url, options).on('complete', function () { - offline.replication = undefined; - }); - return offline.replication; + function stopAllReplication(cozy) { + var doctypes = getDoctypes(cozy); + var stop = function stop(doctype) { + return stopReplication(cozy, doctype); + }; + return Promise.all(doctypes.map(stop)); } - function createIndexes(cozy, db, doctype) { - if (doctype === _doctypes.DOCTYPE_FILES) { - db.createIndex({ index: { fields: ['dir_id'] } }); + // + // REPEATED REPLICATION + // + + function getRepeatedReplication(cozy, doctype) { + return getInfo(cozy, doctype).interval; + } + + function setRepeatedReplication(cozy, doctype, interval) { + cozy._offline[doctype].interval = interval; + } + + function hasRepeatedReplication(cozy, doctype) { + return getRepeatedReplication(cozy, doctype) !== undefined; + } + + function startRepeatedReplication(cozy, doctype, timer) { + var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + + // TODO: add timer limitation for not flooding Gozy + if (!hasDatabase(cozy, doctype)) { + return Promise.reject(errorDatabase(doctype)); + } + + if (hasRepeatedReplication(cozy, doctype)) { + return getRepeatedReplication(cozy, doctype); + } + + return setRepeatedReplication(cozy, doctype, setInterval(function () { + if (!hasReplication(cozy, doctype)) { + replicateFromCozy(cozy, doctype, options); + // TODO: add replicationToCozy + } + }, timer * 1000)); + } + + function stopRepeatedReplication(cozy, doctype) { + if (hasRepeatedReplication(cozy, doctype)) { + clearInterval(getRepeatedReplication(cozy, doctype)); + setRepeatedReplication(cozy, doctype, undefined); + } + if (hasReplication(cozy, doctype)) { + return stopReplication(cozy, doctype); } + + return Promise.resolve(); + } + + function stopAllRepeatedReplication(cozy) { + var doctypes = getDoctypes(cozy); + var stop = function stop(doctype) { + return stopRepeatedReplication(cozy, doctype); + }; + return Promise.all(doctypes.map(stop)); } /***/ }, diff --git a/dist/cozy-client.js.map b/dist/cozy-client.js.map index c39c2efe..ac7af9e8 100644 --- a/dist/cozy-client.js.map +++ b/dist/cozy-client.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///webpack/bootstrap 5caf950de796af004bfb","webpack:///./~/isomorphic-fetch/fetch-npm-browserify.js","webpack:///./~/whatwg-fetch/fetch.js","webpack:///./src/index.js","webpack:///./src/utils.js","webpack:///./src/auth_storage.js","webpack:///./src/auth_v2.js","webpack:///./src/auth_v3.js","webpack:///./src/fetch.js","webpack:///./src/jsonapi.js","webpack:///./src/data.js","webpack:///./src/doctypes.js","webpack:///./src/mango.js","webpack:///./src/files.js","webpack:///./src/offline.js","webpack:///external \"pouchdb\"","webpack:///external \"pouchdb-find\"","webpack:///./src/settings.js","webpack:///./src/relations.js"],"names":["auth","data","mango","files","offline","settings","relations","AppTokenV3","AppToken","AccessTokenV3","AccessToken","ClientV3","Client","AuthNone","AuthRunning","AuthError","AuthOK","defaultClientParams","softwareID","dataProto","create","find","update","delete","_delete","updateAttributes","changesFeed","defineIndex","query","addReferencedFiles","listReferencedFiles","destroy","authProto","client","registerClient","updateClient","unregisterClient","getClient","getAuthCodeURL","getAccessToken","refreshToken","filesProto","createDirectory","updateById","updateAttributesById","updateAttributesByPath","trashById","statById","statByPath","downloadById","downloadByPath","getDowloadLink","getArchiveLink","listTrash","clearTrash","restoreById","destroyById","offlineProto","init","getDoctypes","createDatabase","hasDatabase","getDatabase","destroyDatabase","destroyAllDatabase","replicateFromCozy","hasSync","startAllSync","startSync","stopAllSync","stopSync","settingsProto","diskUsage","changePassphrase","getInstance","updateInstance","getClients","deleteClientById","options","AppTokenV2","LocalStorage","MemoryStorage","_inited","_oauth","_token","_authstate","_authcreds","_storage","_version","_offline","token","oauth","Error","storage","_clientParams","Object","assign","clientParams","_onRegistered","onRegistered","nopOnRegistered","url","cozyURL","length","slice","_url","disablePromises","addToProto","state","isV2","then","oauthFlow","Promise","resolve","creds","save","CredsKey","path","pathprefix","fetch","res","ok","json","status","datasystem","undefined","protoify","context","fn","prototyped","args","ctx","obj","proto","attr","module","exports","unpromiser","isPromise","sleep","retry","getFuzzedDelay","getBackedoffDelay","createPath","encodeQuery","decodeQuery","warn","FuzzFactor","value","apply","l","cb","err","time","setTimeout","count","delay","doTry","catch","retryDelay","fuzzingFactor","Math","random","retryCount","pow","cozy","doctype","id","route","encodeURIComponent","q","qname","queryIndex","indexOf","queries","fragIndex","queryStr","parts","split","i","pair","decodeURIComponent","hasOwnProperty","warned","text","push","console","prefix","window","localStorage","key","setItem","JSON","stringify","item","getItem","parse","removeItem","hash","deleted","getAppToken","V2TOKEN_ABORT_TIMEOUT","reject","parent","postMessage","origin","location","intent","action","timeout","receiver","event","appName","e","removeEventListener","clearTimeout","addEventListener","opts","btoa","StateSize","StateKey","clientID","client_id","clientSecret","client_secret","registrationAccessToken","registration_access_token","redirect_uris","redirectURI","software_id","softwareVersion","software_version","clientName","client_name","clientKind","client_kind","clientURI","client_uri","logoURI","logo_uri","policyURI","policy_uri","tokenType","token_type","accessToken","access_token","refresh_token","scope","cli","isRegistered","toRegisterJSON","disableAuth","resetSecret","manualAuthCredentials","createClient","oldClient","newClient","shouldPassRegistration","scopes","generateRandomState","join","pageURL","grantQueries","getGrantCodeFromPageURL","retrieveToken","code","tryCount","clearAndRetry","clear","registerNewClient","all","load","credentials","storedState","isUnauthorized","isNotFound","statePromise","t","body","headers","href","buffer","crypto","getRandomValues","Uint8Array","require","randomBytes","Array","floor","String","fromCharCode","replace","cozyFetch","cozyFetchJSON","fullpath","resp","cozyFetchWithAuth","authorize","handleResponse","toAuthHeader","newToken","saveCredentials","method","handleJSONResponse","contentType","get","FetchError","reason","captureStackTrace","constructor","name","response","indexKey","doc","type","findByRef","resources","ref","handleResource","rawResource","links","resource","_id","_type","_rev","meta","rev","attributes","rels","relationships","isArray","map","handleTopLevel","included","forEach","r","NOREV","docType","changes","tries","normalizeDoctype","DOCTYPE_FILES","KNOWN_DOCTYPES","REVERSE_KNOWN","keys","k","isQualified","known","parseSelector","normalizeSelector","makeMapReduceQuery","fields","defineIndexV2","defineIndexV3","indexRef","queryV2","queryV3","VALUEOPERATORS","LOGICOPERATORS","MAP_TEMPLATE","toLowerCase","emit","FIELDSPLACEHOLDER","toString","COUCHDB_INFINITY","COUCHDB_LOWEST","indexName","capitalize","indexDefinition","makeMapFunction","reduce","use_index","selector","limit","since","descending","sort","f","docs","charAt","toUpperCase","operator","acc","concat","filters","filter","op","field","applySelector","lower","upper","inclusiveEnd","startkey","endkey","inclusive_end","mrquery","firstFreeValueField","normalizedSelector","used","isFreeValue","contentTypeOctetStream","doUpload","ArrayBuffer","isBuffer","isFile","File","isBlob","Blob","isStream","readable","pipe","isString","checksum","lastModifiedDate","ifMatch","Date","toGMTString","dirID","executable","doUpdateAttributes","attrs","db","children","addIsDir","toJsonApi","extractResponseLinkRelated","related","paths","archive","isDir","contents","clone","replicateFromCozyWithAuth","pluginLoaded","doctypes","timer","plugin","database","autoSync","createIndexes","setInterval","replicate","clearInterval","replication","cancel","live","basic","toBasicAuth","from","on","createIndex","index","currentPassPhrase","newPassPhrase","current_passphrase","new_passphrase","instance","ids","refs","makeReferencesPath","file"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mCAAmC;AACnC,CAAC;AACD,O;ACVA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,uBAAe;AACf;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;;;;;;;;;;;;;;ACtCA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACLA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA,MAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,iBAAgB;AAChB;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,QAAO;;AAEP,MAAK;AACL;AACA;AACA,QAAO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,yCAAwC,mBAAmB;AAC3D;AACA;;AAEA;AACA;AACA,mCAAkC,oBAAoB;AACtD;AACA;;AAEA;AACA;AACA,yCAAwC,4BAA4B;AACpE;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,oBAAmB,iBAAiB;AACpC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA,QAAO;AACP;AACA,QAAO;AACP;AACA,QAAO;AACP;AACA,QAAO;AACP;AACA;AACA;AACA,QAAO;AACP;AACA,QAAO;AACP;AACA;;AAEA;AACA;AACA,wDAAuD;AACvD,UAAS;AACT;AACA,UAAS;AACT,+EAA8E;AAC9E;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,UAAS;AACT;AACA,UAAS;AACT;AACA,UAAS;AACT;AACA;AACA;;AAEA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,QAAO;AACP;AACA,QAAO;AACP;AACA,QAAO;AACP;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA,+BAA8B,uBAAuB;AACrD;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;;AAEA;AACA,wCAAuC,0BAA0B;AACjE;AACA;AACA;;AAEA;;AAEA;AACA;AACA;AACA;;AAEA,gCAA+B,0BAA0B,eAAe;AACxE;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,QAAO;;AAEP;AACA,MAAK;AACL;AACA;AACA,EAAC;;;;;;;;;sjBCzcD;;AAEA;;AACA;;AACA;;AACA;;KAAYA,I;;AACZ;;KAAYC,I;;AACZ;;KAAYC,K;;AACZ;;KAAYC,K;;AACZ;;KAAYC,O;;AACZ;;KAAYC,Q;;AACZ;;KAAYC,S;;;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,mB,GAAAA,mB;;AAZhB;;AACA;;AAEO,UAASD,kBAAT,CAA6BwI,IAA7B,EAAmCoJ,GAAnC,EAAwCgJ,GAAxC,EAA6C;AAClD,OAAI,CAAChJ,GAAL,EAAU,MAAM,IAAI7N,KAAJ,CAAU,sBAAV,CAAN;AACV,OAAI,CAACmM,MAAM2C,OAAN,CAAc+H,GAAd,CAAL,EAAyBA,MAAM,CAACA,GAAD,CAAN;;AAEzB,OAAMC,OAAOD,IAAI9H,GAAJ,CAAQ,UAACpK,EAAD;AAAA,YAAS,EAACmJ,6BAAD,EAAsBnJ,IAAIA,EAA1B,EAAT;AAAA,IAAR,CAAb;;AAEA,UAAO,0BAAcF,IAAd,EAAoB,MAApB,EAA4BsS,mBAAmBlJ,GAAnB,CAA5B,EAAqD,EAACxT,MAAMyc,IAAP,EAArD,CAAP;AACD;;AAEM,UAAS5a,mBAAT,CAA8BuI,IAA9B,EAAoCoJ,GAApC,EAAyC;AAC9C,OAAI,CAACA,GAAL,EAAU,MAAM,IAAI7N,KAAJ,CAAU,sBAAV,CAAN;AACV,UAAO,0BAAcyE,IAAd,EAAoB,KAApB,EAA2BsS,mBAAmBlJ,GAAnB,CAA3B,EACJ3M,IADI,CACC,UAAC3G,KAAD;AAAA,YAAWA,MAAMwU,GAAN,CAAU,UAACiI,IAAD;AAAA,cAAUA,KAAK1I,GAAf;AAAA,MAAV,CAAX;AAAA,IADD,CAAP;AAED;;AAED,UAASyI,kBAAT,CAA6BlJ,GAA7B,EAAkC;AAChC,OAAMC,OAAOjJ,mBAAmBgJ,IAAIU,KAAvB,CAAb;AACA,OAAM5J,KAAKE,mBAAmBgJ,IAAIS,GAAvB,CAAX;AACA,qBAAgBR,IAAhB,SAAwBnJ,EAAxB;AACD,E","file":"cozy-client.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory(require(\"pouchdb\"), require(\"pouchdb-find\"));\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine(\"client\", [\"pouchdb\", \"pouchdb-find\"], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"client\"] = factory(require(\"pouchdb\"), require(\"pouchdb-find\"));\n\telse\n\t\troot[\"cozy\"] = root[\"cozy\"] || {}, root[\"cozy\"][\"client\"] = factory(root[\"pouchdb\"], root[\"pouchdb-find\"]);\n})(this, function(__WEBPACK_EXTERNAL_MODULE_15__, __WEBPACK_EXTERNAL_MODULE_16__) {\nreturn \n\n\n// WEBPACK FOOTER //\n// webpack/universalModuleDefinition"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\texports: {},\n \t\t\tid: moduleId,\n \t\t\tloaded: false\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.loaded = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(0);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap 5caf950de796af004bfb","// the whatwg-fetch polyfill installs the fetch() function\n// on the global object (window or self)\n//\n// Return that as the export for use in Webpack, Browserify etc.\nrequire('whatwg-fetch');\nmodule.exports = self.fetch.bind(self);\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/isomorphic-fetch/fetch-npm-browserify.js\n// module id = 1\n// module chunks = 0","(function(self) {\n 'use strict';\n\n if (self.fetch) {\n return\n }\n\n var support = {\n searchParams: 'URLSearchParams' in self,\n iterable: 'Symbol' in self && 'iterator' in Symbol,\n blob: 'FileReader' in self && 'Blob' in self && (function() {\n try {\n new Blob()\n return true\n } catch(e) {\n return false\n }\n })(),\n formData: 'FormData' in self,\n arrayBuffer: 'ArrayBuffer' in self\n }\n\n if (support.arrayBuffer) {\n var viewClasses = [\n '[object Int8Array]',\n '[object Uint8Array]',\n '[object Uint8ClampedArray]',\n '[object Int16Array]',\n '[object Uint16Array]',\n '[object Int32Array]',\n '[object Uint32Array]',\n '[object Float32Array]',\n '[object Float64Array]'\n ]\n\n var isDataView = function(obj) {\n return obj && DataView.prototype.isPrototypeOf(obj)\n }\n\n var isArrayBufferView = ArrayBuffer.isView || function(obj) {\n return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1\n }\n }\n\n function normalizeName(name) {\n if (typeof name !== 'string') {\n name = String(name)\n }\n if (/[^a-z0-9\\-#$%&'*+.\\^_`|~]/i.test(name)) {\n throw new TypeError('Invalid character in header field name')\n }\n return name.toLowerCase()\n }\n\n function normalizeValue(value) {\n if (typeof value !== 'string') {\n value = String(value)\n }\n return value\n }\n\n // Build a destructive iterator for the value list\n function iteratorFor(items) {\n var iterator = {\n next: function() {\n var value = items.shift()\n return {done: value === undefined, value: value}\n }\n }\n\n if (support.iterable) {\n iterator[Symbol.iterator] = function() {\n return iterator\n }\n }\n\n return iterator\n }\n\n function Headers(headers) {\n this.map = {}\n\n if (headers instanceof Headers) {\n headers.forEach(function(value, name) {\n this.append(name, value)\n }, this)\n\n } else if (headers) {\n Object.getOwnPropertyNames(headers).forEach(function(name) {\n this.append(name, headers[name])\n }, this)\n }\n }\n\n Headers.prototype.append = function(name, value) {\n name = normalizeName(name)\n value = normalizeValue(value)\n var oldValue = this.map[name]\n this.map[name] = oldValue ? oldValue+','+value : value\n }\n\n Headers.prototype['delete'] = function(name) {\n delete this.map[normalizeName(name)]\n }\n\n Headers.prototype.get = function(name) {\n name = normalizeName(name)\n return this.has(name) ? this.map[name] : null\n }\n\n Headers.prototype.has = function(name) {\n return this.map.hasOwnProperty(normalizeName(name))\n }\n\n Headers.prototype.set = function(name, value) {\n this.map[normalizeName(name)] = normalizeValue(value)\n }\n\n Headers.prototype.forEach = function(callback, thisArg) {\n for (var name in this.map) {\n if (this.map.hasOwnProperty(name)) {\n callback.call(thisArg, this.map[name], name, this)\n }\n }\n }\n\n Headers.prototype.keys = function() {\n var items = []\n this.forEach(function(value, name) { items.push(name) })\n return iteratorFor(items)\n }\n\n Headers.prototype.values = function() {\n var items = []\n this.forEach(function(value) { items.push(value) })\n return iteratorFor(items)\n }\n\n Headers.prototype.entries = function() {\n var items = []\n this.forEach(function(value, name) { items.push([name, value]) })\n return iteratorFor(items)\n }\n\n if (support.iterable) {\n Headers.prototype[Symbol.iterator] = Headers.prototype.entries\n }\n\n function consumed(body) {\n if (body.bodyUsed) {\n return Promise.reject(new TypeError('Already read'))\n }\n body.bodyUsed = true\n }\n\n function fileReaderReady(reader) {\n return new Promise(function(resolve, reject) {\n reader.onload = function() {\n resolve(reader.result)\n }\n reader.onerror = function() {\n reject(reader.error)\n }\n })\n }\n\n function readBlobAsArrayBuffer(blob) {\n var reader = new FileReader()\n var promise = fileReaderReady(reader)\n reader.readAsArrayBuffer(blob)\n return promise\n }\n\n function readBlobAsText(blob) {\n var reader = new FileReader()\n var promise = fileReaderReady(reader)\n reader.readAsText(blob)\n return promise\n }\n\n function readArrayBufferAsText(buf) {\n var view = new Uint8Array(buf)\n var chars = new Array(view.length)\n\n for (var i = 0; i < view.length; i++) {\n chars[i] = String.fromCharCode(view[i])\n }\n return chars.join('')\n }\n\n function bufferClone(buf) {\n if (buf.slice) {\n return buf.slice(0)\n } else {\n var view = new Uint8Array(buf.byteLength)\n view.set(new Uint8Array(buf))\n return view.buffer\n }\n }\n\n function Body() {\n this.bodyUsed = false\n\n this._initBody = function(body) {\n this._bodyInit = body\n if (!body) {\n this._bodyText = ''\n } else if (typeof body === 'string') {\n this._bodyText = body\n } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {\n this._bodyBlob = body\n } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {\n this._bodyFormData = body\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this._bodyText = body.toString()\n } else if (support.arrayBuffer && support.blob && isDataView(body)) {\n this._bodyArrayBuffer = bufferClone(body.buffer)\n // IE 10-11 can't handle a DataView body.\n this._bodyInit = new Blob([this._bodyArrayBuffer])\n } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {\n this._bodyArrayBuffer = bufferClone(body)\n } else {\n throw new Error('unsupported BodyInit type')\n }\n\n if (!this.headers.get('content-type')) {\n if (typeof body === 'string') {\n this.headers.set('content-type', 'text/plain;charset=UTF-8')\n } else if (this._bodyBlob && this._bodyBlob.type) {\n this.headers.set('content-type', this._bodyBlob.type)\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8')\n }\n }\n }\n\n if (support.blob) {\n this.blob = function() {\n var rejected = consumed(this)\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return Promise.resolve(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(new Blob([this._bodyArrayBuffer]))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as blob')\n } else {\n return Promise.resolve(new Blob([this._bodyText]))\n }\n }\n\n this.arrayBuffer = function() {\n if (this._bodyArrayBuffer) {\n return consumed(this) || Promise.resolve(this._bodyArrayBuffer)\n } else {\n return this.blob().then(readBlobAsArrayBuffer)\n }\n }\n }\n\n this.text = function() {\n var rejected = consumed(this)\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return readBlobAsText(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as text')\n } else {\n return Promise.resolve(this._bodyText)\n }\n }\n\n if (support.formData) {\n this.formData = function() {\n return this.text().then(decode)\n }\n }\n\n this.json = function() {\n return this.text().then(JSON.parse)\n }\n\n return this\n }\n\n // HTTP methods whose capitalization should be normalized\n var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']\n\n function normalizeMethod(method) {\n var upcased = method.toUpperCase()\n return (methods.indexOf(upcased) > -1) ? upcased : method\n }\n\n function Request(input, options) {\n options = options || {}\n var body = options.body\n\n if (typeof input === 'string') {\n this.url = input\n } else {\n if (input.bodyUsed) {\n throw new TypeError('Already read')\n }\n this.url = input.url\n this.credentials = input.credentials\n if (!options.headers) {\n this.headers = new Headers(input.headers)\n }\n this.method = input.method\n this.mode = input.mode\n if (!body && input._bodyInit != null) {\n body = input._bodyInit\n input.bodyUsed = true\n }\n }\n\n this.credentials = options.credentials || this.credentials || 'omit'\n if (options.headers || !this.headers) {\n this.headers = new Headers(options.headers)\n }\n this.method = normalizeMethod(options.method || this.method || 'GET')\n this.mode = options.mode || this.mode || null\n this.referrer = null\n\n if ((this.method === 'GET' || this.method === 'HEAD') && body) {\n throw new TypeError('Body not allowed for GET or HEAD requests')\n }\n this._initBody(body)\n }\n\n Request.prototype.clone = function() {\n return new Request(this, { body: this._bodyInit })\n }\n\n function decode(body) {\n var form = new FormData()\n body.trim().split('&').forEach(function(bytes) {\n if (bytes) {\n var split = bytes.split('=')\n var name = split.shift().replace(/\\+/g, ' ')\n var value = split.join('=').replace(/\\+/g, ' ')\n form.append(decodeURIComponent(name), decodeURIComponent(value))\n }\n })\n return form\n }\n\n function parseHeaders(rawHeaders) {\n var headers = new Headers()\n rawHeaders.split('\\r\\n').forEach(function(line) {\n var parts = line.split(':')\n var key = parts.shift().trim()\n if (key) {\n var value = parts.join(':').trim()\n headers.append(key, value)\n }\n })\n return headers\n }\n\n Body.call(Request.prototype)\n\n function Response(bodyInit, options) {\n if (!options) {\n options = {}\n }\n\n this.type = 'default'\n this.status = 'status' in options ? options.status : 200\n this.ok = this.status >= 200 && this.status < 300\n this.statusText = 'statusText' in options ? options.statusText : 'OK'\n this.headers = new Headers(options.headers)\n this.url = options.url || ''\n this._initBody(bodyInit)\n }\n\n Body.call(Response.prototype)\n\n Response.prototype.clone = function() {\n return new Response(this._bodyInit, {\n status: this.status,\n statusText: this.statusText,\n headers: new Headers(this.headers),\n url: this.url\n })\n }\n\n Response.error = function() {\n var response = new Response(null, {status: 0, statusText: ''})\n response.type = 'error'\n return response\n }\n\n var redirectStatuses = [301, 302, 303, 307, 308]\n\n Response.redirect = function(url, status) {\n if (redirectStatuses.indexOf(status) === -1) {\n throw new RangeError('Invalid status code')\n }\n\n return new Response(null, {status: status, headers: {location: url}})\n }\n\n self.Headers = Headers\n self.Request = Request\n self.Response = Response\n\n self.fetch = function(input, init) {\n return new Promise(function(resolve, reject) {\n var request = new Request(input, init)\n var xhr = new XMLHttpRequest()\n\n xhr.onload = function() {\n var options = {\n status: xhr.status,\n statusText: xhr.statusText,\n headers: parseHeaders(xhr.getAllResponseHeaders() || '')\n }\n options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL')\n var body = 'response' in xhr ? xhr.response : xhr.responseText\n resolve(new Response(body, options))\n }\n\n xhr.onerror = function() {\n reject(new TypeError('Network request failed'))\n }\n\n xhr.ontimeout = function() {\n reject(new TypeError('Network request failed'))\n }\n\n xhr.open(request.method, request.url, true)\n\n if (request.credentials === 'include') {\n xhr.withCredentials = true\n }\n\n if ('responseType' in xhr && support.blob) {\n xhr.responseType = 'blob'\n }\n\n request.headers.forEach(function(value, name) {\n xhr.setRequestHeader(name, value)\n })\n\n xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit)\n })\n }\n self.fetch.polyfill = true\n})(typeof self !== 'undefined' ? self : this);\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/whatwg-fetch/fetch.js\n// module id = 2\n// module chunks = 0","/* global fetch */\n\nimport {unpromiser, retry, warn} from './utils'\nimport {LocalStorage, MemoryStorage} from './auth_storage'\nimport {AppToken as AppTokenV2, getAppToken as getAppTokenV2} from './auth_v2'\nimport * as auth from './auth_v3'\nimport * as data from './data'\nimport * as mango from './mango'\nimport * as files from './files'\nimport * as offline from './offline'\nimport * as settings from './settings'\nimport * as relations from './relations'\n\nconst {\n AppToken: AppTokenV3,\n AccessToken: AccessTokenV3,\n Client: ClientV3\n} = auth\n\nconst AuthNone = 0\nconst AuthRunning = 1\nconst AuthError = 2\nconst AuthOK = 3\n\nconst defaultClientParams = {\n softwareID: 'github.com/cozy/cozy-client-js'\n}\n\nconst dataProto = {\n create: data.create,\n find: data.find,\n update: data.update,\n delete: data._delete,\n updateAttributes: data.updateAttributes,\n changesFeed: data.changesFeed,\n defineIndex: mango.defineIndex,\n query: mango.query,\n addReferencedFiles: relations.addReferencedFiles,\n listReferencedFiles: relations.listReferencedFiles,\n destroy: function (...args) {\n warn('destroy is deprecated, use cozy.data.delete instead.')\n return data._delete(...args)\n }\n}\n\nconst authProto = {\n client: auth.client,\n registerClient: auth.registerClient,\n updateClient: auth.updateClient,\n unregisterClient: auth.unregisterClient,\n getClient: auth.getClient,\n getAuthCodeURL: auth.getAuthCodeURL,\n getAccessToken: auth.getAccessToken,\n refreshToken: auth.refreshToken\n}\n\nconst filesProto = {\n create: files.create,\n createDirectory: files.createDirectory,\n updateById: files.updateById,\n updateAttributesById: files.updateAttributesById,\n updateAttributesByPath: files.updateAttributesByPath,\n trashById: files.trashById,\n statById: files.statById,\n statByPath: files.statByPath,\n downloadById: files.downloadById,\n downloadByPath: files.downloadByPath,\n getDowloadLink: files.getDowloadLink,\n getArchiveLink: files.getArchiveLink,\n listTrash: files.listTrash,\n clearTrash: files.clearTrash,\n restoreById: files.restoreById,\n destroyById: files.destroyById\n}\n\nconst offlineProto = {\n init: offline.init,\n getDoctypes: offline.getDoctypes,\n // database\n createDatabase: offline.createDatabase,\n hasDatabase: offline.hasDatabase,\n getDatabase: offline.getDatabase,\n destroyDatabase: offline.destroyDatabase,\n destroyAllDatabase: offline.destroyAllDatabase,\n // replication\n replicateFromCozy: offline.replicateFromCozy,\n hasSync: offline.hasSync,\n startAllSync: offline.startAllSync,\n startSync: offline.startSync,\n stopAllSync: offline.stopAllSync,\n stopSync: offline.stopSync\n}\n\nconst settingsProto = {\n diskUsage: settings.diskUsage,\n changePassphrase: settings.changePassphrase,\n getInstance: settings.getInstance,\n updateInstance: settings.updateInstance,\n getClients: settings.getClients,\n deleteClientById: settings.deleteClientById\n}\n\nclass Client {\n constructor (options) {\n this.data = {}\n this.files = {}\n this.offline = {}\n this.settings = {}\n this.auth = {\n Client: ClientV3,\n AccessToken: AccessTokenV3,\n AppToken: AppTokenV3,\n AppTokenV2: AppTokenV2,\n LocalStorage: LocalStorage,\n MemoryStorage: MemoryStorage\n }\n this._inited = false\n if (options) {\n this.init(options)\n }\n }\n\n init (options = {}) {\n this._inited = true\n this._oauth = false // is oauth activated or not\n this._token = null // application token\n this._authstate = AuthNone\n this._authcreds = null\n this._storage = null\n this._version = null\n this._offline = null\n\n const token = options.token\n const oauth = options.oauth\n if (token && oauth) {\n throw new Error('Cannot specify an application token with a oauth activated')\n }\n\n if (token) {\n this._token = new AppTokenV3({ token })\n } else if (oauth) {\n this._oauth = true\n this._storage = oauth.storage\n this._clientParams = Object.assign({}, defaultClientParams, oauth.clientParams)\n this._onRegistered = oauth.onRegistered || nopOnRegistered\n }\n\n let url = options.cozyURL || ''\n while (url[url.length - 1] === '/') {\n url = url.slice(0, -1)\n }\n\n this._url = url\n\n const disablePromises = !!options.disablePromises\n addToProto(this, this.data, dataProto, disablePromises)\n addToProto(this, this.auth, authProto, disablePromises)\n addToProto(this, this.files, filesProto, disablePromises)\n addToProto(this, this.offline, offlineProto, disablePromises)\n addToProto(this, this.settings, settingsProto, disablePromises)\n\n if (options.offline) {\n this.offline.init(options.offline)\n }\n }\n\n authorize () {\n const state = this._authstate\n if (state === AuthOK || state === AuthRunning) {\n return this._authcreds\n }\n\n this._authstate = AuthRunning\n this._authcreds = this.isV2().then((isV2) => {\n if (isV2 && this._oauth) {\n throw new Error('OAuth is not supported on the V2 stack')\n }\n if (this._oauth) {\n return auth.oauthFlow(\n this,\n this._storage,\n this._clientParams,\n this._onRegistered\n )\n }\n // we expect to be on a client side application running in a browser\n // with cookie-based authentication.\n if (isV2) {\n return getAppTokenV2()\n } else if (this._token) {\n return Promise.resolve({client: null, token: this._token})\n } else {\n throw new Error('Missing application token')\n }\n })\n\n this._authcreds.then(\n () => { this._authstate = AuthOK },\n () => { this._authstate = AuthError })\n\n return this._authcreds\n }\n\n saveCredentials (client, token) {\n const creds = {client, token}\n if (!this._storage || this._authstate === AuthRunning) {\n return Promise.resolve(creds)\n }\n this._storage.save(auth.CredsKey, creds)\n this._authcreds = Promise.resolve(creds)\n return this._authcreds\n }\n\n fullpath (path) {\n return this.isV2().then((isV2) => {\n const pathprefix = isV2 ? '/ds-api' : ''\n return this._url + pathprefix + path\n })\n }\n\n isV2 () {\n if (!this._version) {\n this._version = retry(() => fetch(`${this._url}/status/`), 3)()\n .then((res) => {\n if (!res.ok) {\n throw new Error('Could not fetch cozy status')\n } else {\n return res.json()\n }\n })\n .then((status) => status.datasystem !== undefined)\n }\n return this._version\n }\n}\n\nfunction nopOnRegistered () {\n throw new Error('Missing onRegistered callback')\n}\n\nfunction protoify (context, fn) {\n return function prototyped (...args) {\n return fn(context, ...args)\n }\n}\n\nfunction addToProto (ctx, obj, proto, disablePromises) {\n for (const attr in proto) {\n let fn = protoify(ctx, proto[attr])\n if (disablePromises) {\n fn = unpromiser(fn)\n }\n obj[attr] = fn\n }\n}\n\nmodule.exports = new Client()\nObject.assign(module.exports, {Client, LocalStorage, MemoryStorage})\n\n\n\n// WEBPACK FOOTER //\n// ./src/index.js","const FuzzFactor = 0.3\n\nexport function unpromiser (fn) {\n return function (...args) {\n const value = fn.apply(this, args)\n if (!isPromise(value)) {\n return value\n }\n const l = args.length\n if (l === 0 || typeof args[l - 1] !== 'function') {\n return\n }\n const cb = args[l - 1]\n value.then(\n (res) => cb(null, res),\n (err) => cb(err, null)\n )\n return\n }\n}\n\nexport function isPromise (value) {\n return !!value && typeof value.then === 'function'\n}\n\nexport function sleep (time, args) {\n return new Promise((resolve) => {\n setTimeout(resolve, time, args)\n })\n}\n\nexport function retry (fn, count, delay = 300) {\n return function doTry (...args) {\n return fn(...args).catch((err) => {\n if (--count < 0) {\n throw err\n }\n return sleep(getBackedoffDelay(delay, count))\n .then(() => doTry(...args))\n })\n }\n}\n\nexport function getFuzzedDelay (retryDelay) {\n const fuzzingFactor = ((Math.random() * 2) - 1) * FuzzFactor\n return retryDelay * (1.0 + fuzzingFactor)\n}\n\nexport function getBackedoffDelay (retryDelay, retryCount = 1) {\n return getFuzzedDelay(retryDelay * Math.pow(2, retryCount - 1))\n}\n\nexport function createPath (cozy, isV2, doctype, id = '', query = null) {\n let route = '/data/'\n if (!isV2) {\n route += `${encodeURIComponent(doctype)}/`\n }\n if (id !== '') {\n route += encodeURIComponent(id)\n }\n const q = encodeQuery(query)\n if (q !== '') {\n route += '?' + q\n }\n return route\n}\n\nexport function encodeQuery (query) {\n if (!query) {\n return ''\n }\n let q = ''\n for (const qname in query) {\n if (q !== '') {\n q += '&'\n }\n q += `${encodeURIComponent(qname)}=${encodeURIComponent(query[qname])}`\n }\n return q\n}\n\nexport function decodeQuery (url) {\n let queryIndex = url.indexOf('?')\n if (queryIndex < 0) {\n queryIndex = url.length\n }\n const queries = {}\n let fragIndex = url.indexOf('#')\n if (fragIndex < 0) {\n fragIndex = url.length\n }\n if (fragIndex < queryIndex) {\n return queries\n }\n const queryStr = url.slice(queryIndex + 1, fragIndex)\n if (queryStr === '') {\n return queries\n }\n const parts = queryStr.split('&')\n for (let i = 0; i < parts.length; i++) {\n let pair = parts[i].split('=')\n if (pair.length === 0 || pair[0] === '') {\n continue\n }\n const qname = decodeURIComponent(pair[0])\n if (queries.hasOwnProperty(qname)) {\n continue\n }\n if (pair.length === 1) {\n queries[qname] = true\n } else if (pair.length === 2) {\n queries[qname] = decodeURIComponent(pair[1])\n } else {\n throw new Error('Malformed URL')\n }\n }\n return queries\n}\n\nconst warned = []\nexport function warn (text) {\n if (warned.indexOf(text) === -1) {\n warned.push(text)\n console.warn('cozy-client-js', text)\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils.js","export class LocalStorage {\n constructor (storage, prefix) {\n if (!storage && typeof window !== 'undefined') {\n storage = window.localStorage\n }\n this.storage = storage\n this.prefix = prefix || 'cozy:oauth:'\n }\n\n save (key, value) {\n return new Promise(resolve => {\n this.storage.setItem(this.prefix + key, JSON.stringify(value))\n resolve(value)\n })\n }\n\n load (key) {\n return new Promise(resolve => {\n const item = this.storage.getItem(this.prefix + key)\n if (!item) {\n resolve()\n } else {\n resolve(JSON.parse(item))\n }\n })\n }\n\n delete (key) {\n return new Promise(resolve => resolve(\n this.storage.removeItem(this.prefix + key)))\n }\n\n clear () {\n return new Promise(resolve => {\n const storage = this.storage\n for (let i = 0; i < storage.length; i++) {\n const key = storage.key(i)\n if (key.indexOf(this.prefix) === 0) {\n storage.removeItem(key)\n }\n }\n resolve()\n })\n }\n}\n\nexport class MemoryStorage {\n constructor () {\n this.hash = Object.create(null)\n }\n\n save (key, value) {\n this.hash[key] = value\n return Promise.resolve(value)\n }\n\n load (key) {\n return Promise.resolve(this.hash[key])\n }\n\n delete (key) {\n const deleted = delete this.hash[key]\n return Promise.resolve(deleted)\n }\n\n clear () {\n this.hash = Object.create(null)\n return Promise.resolve()\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/auth_storage.js","/* global btoa */\nconst V2TOKEN_ABORT_TIMEOUT = 3000\n\nexport function getAppToken () {\n return new Promise(function (resolve, reject) {\n if (typeof window === 'undefined') {\n return reject(new Error('getV2Token should be used in browser'))\n } else if (!window.parent) {\n return reject(new Error('getV2Token should be used in iframe'))\n } else if (!window.parent.postMessage) {\n return reject(new Error('getV2Token should be used in modern browser'))\n }\n const origin = window.location.origin\n const intent = {action: 'getToken'}\n let timeout = null\n const receiver = function (event) {\n let token\n try {\n token = new AppToken({\n appName: event.data.appName,\n token: event.data.token\n })\n } catch (e) {\n reject(e)\n return\n }\n window.removeEventListener('message', receiver)\n clearTimeout(timeout)\n resolve({ client: null, token })\n }\n window.addEventListener('message', receiver, false)\n window.parent.postMessage(intent, origin)\n timeout = setTimeout(() => {\n reject(new Error('No response from parent iframe after 3s'))\n }, V2TOKEN_ABORT_TIMEOUT)\n })\n}\n\nexport class AppToken {\n constructor (opts) {\n this.appName = opts.appName || ''\n this.token = opts.token || ''\n }\n\n toAuthHeader () {\n return 'Basic ' + btoa(`${this.appName}:${this.token}`)\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/auth_v2.js","/* global btoa */\nimport {encodeQuery, decodeQuery} from './utils'\nimport {cozyFetchJSON, FetchError} from './fetch'\n\nconst StateSize = 16\n\nexport const CredsKey = 'creds'\nexport const StateKey = 'state'\n\nexport class Client {\n constructor (opts) {\n this.clientID = opts.clientID || opts.client_id || ''\n this.clientSecret = opts.clientSecret || opts.client_secret || ''\n this.registrationAccessToken = opts.registrationAccessToken || opts.registration_access_token || ''\n\n if (opts.redirect_uris) {\n this.redirectURI = opts.redirect_uris[0] || ''\n } else {\n this.redirectURI = opts.redirectURI || ''\n }\n\n this.softwareID = opts.softwareID || opts.software_id || ''\n this.softwareVersion = opts.softwareVersion || opts.software_version || ''\n this.clientName = opts.clientName || opts.client_name || ''\n this.clientKind = opts.clientKind || opts.client_kind || ''\n this.clientURI = opts.clientURI || opts.client_uri || ''\n\n this.logoURI = opts.logoURI || opts.logo_uri || ''\n this.policyURI = opts.policyURI || opts.policy_uri || ''\n\n if (!this.registrationAccessToken) {\n if (this.redirectURI === '') {\n throw new Error('Missing redirectURI field')\n }\n if (this.softwareID === '') {\n throw new Error('Missing softwareID field')\n }\n if (this.clientName === '') {\n throw new Error('Missing clientName field')\n }\n }\n }\n\n isRegistered () {\n return this.clientID !== ''\n }\n\n toRegisterJSON () {\n return {\n redirect_uris: [this.redirectURI],\n software_id: this.softwareID,\n software_version: this.softwareVersion,\n client_name: this.clientName,\n client_kind: this.clientKind,\n client_uri: this.clientURI,\n logo_uri: this.logoURI,\n policy_uri: this.policyURI\n }\n }\n\n toAuthHeader () {\n return 'Bearer ' + this.registrationAccessToken\n }\n}\n\nexport class AccessToken {\n constructor (opts) {\n this.tokenType = opts.tokenType || opts.token_type\n this.accessToken = opts.accessToken || opts.access_token\n this.refreshToken = opts.refreshToken || opts.refresh_token\n this.scope = opts.scope\n }\n\n toAuthHeader () {\n return 'Bearer ' + this.accessToken\n }\n\n toBasicAuth () {\n return `user:${this.accessToken}@`\n }\n}\n\nexport class AppToken {\n constructor (opts) {\n this.token = opts.token || ''\n }\n\n toAuthHeader () {\n return 'Bearer ' + this.token\n }\n\n toBasicAuth () {\n return `user:${this.token}@`\n }\n}\n\nexport function client (cozy, clientParams) {\n if (!clientParams) {\n clientParams = cozy._clientParams\n }\n if (clientParams instanceof Client) {\n return clientParams\n }\n return new Client(clientParams)\n}\n\nexport function registerClient (cozy, clientParams) {\n const cli = client(cozy, clientParams)\n if (cli.isRegistered()) {\n return Promise.reject(new Error('Client already registered'))\n }\n return cozyFetchJSON(cozy, 'POST', '/auth/register', cli.toRegisterJSON(), {\n disableAuth: true\n })\n .then((data) => new Client(data))\n}\n\nexport function updateClient (cozy, clientParams, resetSecret = false) {\n const cli = client(cozy, clientParams)\n if (!cli.isRegistered()) {\n return Promise.reject(new Error('Client not registered'))\n }\n let data = cli.toRegisterJSON()\n data.client_id = cli.clientID\n if (resetSecret) data.client_secret = cli.clientSecret\n\n return cozyFetchJSON(cozy, 'PUT', `/auth/register/${cli.clientID}`, data, {\n manualAuthCredentials: {\n token: cli\n }\n }).then((data) => createClient(data, cli))\n}\n\nexport function unregisterClient (cozy, clientParams) {\n const cli = client(cozy, clientParams)\n if (!cli.isRegistered()) {\n return Promise.reject(new Error('Client not registered'))\n }\n return cozyFetchJSON(cozy, 'DELETE', `/auth/register/${cli.clientID}`, null, {\n manualAuthCredentials: {\n token: cli\n }\n })\n}\n\n// getClient will retrive the registered client informations from the server.\nexport function getClient (cozy, clientParams) {\n const cli = client(cozy, clientParams)\n if (!cli.isRegistered()) {\n return Promise.reject(new Error('Client not registered'))\n }\n return cozyFetchJSON(cozy, 'GET', `/auth/register/${cli.clientID}`, null, {\n manualAuthCredentials: {\n token: cli\n }\n })\n .then((data) => createClient(data, cli))\n}\n\n// createClient returns a new Client instance given on object containing the\n// data of the client, from the API, and an old instance of the client.\nfunction createClient (data, oldClient) {\n const newClient = new Client(data)\n // we need to keep track of the registrationAccessToken since it is send\n // only on registration. The GET /auth/register/:client-id endpoint does\n // not return this token.\n const shouldPassRegistration = (\n !!oldClient &&\n oldClient.registrationAccessToken !== '' &&\n newClient.registrationAccessToken === ''\n )\n if (shouldPassRegistration) {\n newClient.registrationAccessToken = oldClient.registrationAccessToken\n }\n return newClient\n}\n\n// getAuthCodeURL returns a pair {authURL,state} given a registered client. The\n// state should be stored in order to be checked against on the user validation\n// phase.\nexport function getAuthCodeURL (cozy, client, scopes = []) {\n if (!(client instanceof Client)) {\n client = new Client(client)\n }\n if (!client.isRegistered()) {\n throw new Error('Client not registered')\n }\n const state = generateRandomState()\n const query = {\n 'client_id': client.clientID,\n 'redirect_uri': client.redirectURI,\n 'state': state,\n 'response_type': 'code',\n 'scope': scopes.join(' ')\n }\n return {\n url: cozy._url + `/auth/authorize?${encodeQuery(query)}`,\n state: state\n }\n}\n\n// getAccessToken perform a request on the access_token entrypoint with the\n// authorization_code grant type in order to generate a new access token for a\n// newly registered client.\n//\n// This method extracts the access code and state from the given URL. By\n// default it uses window.location.href. Also, it checks the given state with\n// the one specified in the URL query parameter to prevent CSRF attacks.\nexport function getAccessToken (cozy, client, state, pageURL = '') {\n if (!state) {\n return Promise.reject(new Error('Missing state value'))\n }\n const grantQueries = getGrantCodeFromPageURL(pageURL)\n if (grantQueries === null) {\n return Promise.reject(new Error('Missing states from current URL'))\n }\n if (state !== grantQueries.state) {\n return Promise.reject(new Error('Given state does not match url query state'))\n }\n return retrieveToken(cozy, client, null, {\n 'grant_type': 'authorization_code',\n 'code': grantQueries.code\n })\n}\n\n// refreshToken perform a request on the access_token entrypoint with the\n// refresh_token grant type in order to refresh the given token.\nexport function refreshToken (cozy, client, token) {\n return retrieveToken(cozy, client, token, {\n 'grant_type': 'refresh_token',\n 'refresh_token': token.refreshToken\n })\n}\n\n// oauthFlow performs the stateful registration and access granting of an OAuth\n// client.\nexport function oauthFlow (cozy, storage, clientParams, onRegistered) {\n let tryCount = 0\n\n function clearAndRetry (err) {\n if (tryCount++ > 0) {\n throw err\n }\n return storage.clear().then(() =>\n oauthFlow(cozy, storage, clientParams, onRegistered))\n }\n\n function registerNewClient () {\n return storage.clear()\n .then(() => registerClient(cozy, clientParams))\n .then((client) => {\n const {url, state} = getAuthCodeURL(cozy, client, clientParams.scopes)\n return storage.save(StateKey, {client, url, state})\n })\n }\n\n return Promise.all([\n storage.load(CredsKey),\n storage.load(StateKey)\n ])\n .then(([credentials, storedState]) => {\n // If credentials are cached we re-fetch the registered client with the\n // said token. Fetching the client, if the token is outdated we should try\n // the token is refreshed.\n if (credentials) {\n let oldClient, token\n try {\n oldClient = new Client(credentials.client)\n token = new AccessToken(credentials.token)\n } catch (err) {\n // bad cache, we should clear and retry the process\n return clearAndRetry(err)\n }\n return getClient(cozy, oldClient)\n .then((client) => ({client, token}))\n .catch((err) => {\n // If we fall into an error while fetching the client (because of a\n // bad connectivity for instance), we do not bail the whole process\n // since the client should be able to continue with the persisted\n // client and token.\n //\n // If it is an explicit Unauthorized error though, we bail, clear th\n // cache and retry.\n if (FetchError.isUnauthorized(err) || FetchError.isNotFound(err)) {\n throw new Error('Client has been revoked')\n }\n return { client: oldClient, token }\n })\n }\n\n // Otherwise register a new client if necessary (ie. no client is stored)\n // and call the onRegistered callback to wait for the user to grant the\n // access. Finally fetches to access token on success.\n let statePromise\n if (!storedState) {\n statePromise = registerNewClient()\n } else {\n statePromise = Promise.resolve(storedState)\n }\n\n let client, state, token\n return statePromise\n .then((data) => {\n client = data.client\n state = data.state\n return Promise.resolve(onRegistered(client, data.url))\n })\n .then((pageURL) => getAccessToken(cozy, client, state, pageURL))\n .then((t) => { token = t })\n .then(() => storage.delete(StateKey))\n .then(() => ({client, token}))\n })\n .then(\n (creds) => storage.save(CredsKey, creds),\n (err) => {\n if (FetchError.isUnauthorized(err)) {\n return clearAndRetry(err)\n } else {\n throw err\n }\n })\n}\n\n// retrieveToken perform a request on the access_token entrypoint in order to\n// fetch a token.\nfunction retrieveToken (cozy, client, token, query) {\n if (!(client instanceof Client)) {\n client = new Client(client)\n }\n if (!client.isRegistered()) {\n return Promise.reject(new Error('Client not registered'))\n }\n const body = encodeQuery(Object.assign({}, query, {\n 'client_id': client.clientID,\n 'client_secret': client.clientSecret\n }))\n return cozyFetchJSON(cozy, 'POST', '/auth/access_token', body, {\n disableAuth: (token === null),\n manualAuthCredentials: { client, token },\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' }\n })\n .then((data) => {\n data.refreshToken = data.refreshToken || query.refresh_token\n return new AccessToken(data)\n })\n}\n\n// getGrantCodeFromPageURL extract the state and access_code query parameters\n// from the given url\nfunction getGrantCodeFromPageURL (pageURL = '') {\n if (pageURL === '' && typeof window !== 'undefined') {\n pageURL = window.location.href\n }\n const queries = decodeQuery(pageURL)\n if (!queries.hasOwnProperty('state')) {\n return null\n }\n return {\n state: queries['state'],\n code: queries['access_code']\n }\n}\n\n// generateRandomState will try to generate a 128bits random value from a secure\n// pseudo random generator. It will fallback on Math.random if it cannot find\n// such generator.\nfunction generateRandomState () {\n let buffer\n if (typeof window !== 'undefined' &&\n typeof window.crypto !== 'undefined' &&\n typeof window.crypto.getRandomValues === 'function') {\n buffer = new Uint8Array(StateSize)\n window.crypto.getRandomValues(buffer)\n } else {\n try {\n buffer = require('crypto').randomBytes(StateSize)\n } catch (e) {}\n }\n if (!buffer) {\n buffer = new Array(StateSize)\n for (let i = 0; i < buffer.length; i++) {\n buffer[i] = Math.floor((Math.random() * 255))\n }\n }\n return btoa(String.fromCharCode.apply(null, buffer))\n .replace(/=+$/, '')\n .replace(/\\//g, '_')\n .replace(/\\+/g, '-')\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/auth_v3.js","/* global fetch */\nimport {refreshToken, AccessToken} from './auth_v3'\nimport {retry} from './utils'\nimport jsonapi from './jsonapi'\n\nexport function cozyFetch (cozy, path, options = {}) {\n return cozy.fullpath(path).then((fullpath) => {\n let resp\n if (options.disableAuth) {\n resp = fetch(fullpath, options)\n } else if (options.manualAuthCredentials) {\n resp = cozyFetchWithAuth(cozy, fullpath, options, options.manualAuthCredentials)\n } else {\n resp = cozy.authorize().then((credentials) =>\n cozyFetchWithAuth(cozy, fullpath, options, credentials))\n }\n return resp.then(handleResponse)\n })\n}\n\nfunction cozyFetchWithAuth (cozy, fullpath, options, credentials) {\n if (credentials) {\n options.headers = options.headers || {}\n options.headers['Authorization'] = credentials.token.toAuthHeader()\n }\n\n // the option credentials:include tells fetch to include the cookies in the\n // request even for cross-origin requests\n options.credentials = 'include'\n\n return Promise.all([\n cozy.isV2(),\n fetch(fullpath, options)\n ]).then(([isV2, res]) => {\n if (res.status !== 401 || isV2 || !credentials) {\n return res\n }\n // we try to refresh the token only for OAuth, ie, the client defined\n // and the token is an instance of AccessToken.\n const { client, token } = credentials\n if (!client || !(token instanceof AccessToken)) {\n return res\n }\n return retry(() => refreshToken(cozy, client, token), 3)()\n .then((newToken) => cozy.saveCredentials(client, newToken))\n .then((credentials) => cozyFetchWithAuth(cozy, fullpath, options, credentials))\n })\n}\n\nexport function cozyFetchJSON (cozy, method, path, body, options = {}) {\n options.method = method\n\n const headers = options.headers = options.headers || {}\n\n headers['Accept'] = 'application/json'\n\n if (method !== 'GET' && method !== 'HEAD' && body !== undefined) {\n if (headers['Content-Type']) {\n options.body = body\n } else {\n headers['Content-Type'] = 'application/json'\n options.body = JSON.stringify(body)\n }\n }\n\n return cozyFetch(cozy, path, options)\n .then(handleJSONResponse)\n}\n\nfunction handleResponse (res) {\n if (res.ok) {\n return res\n }\n let data\n const contentType = res.headers.get('content-type')\n if (contentType && contentType.indexOf('json') >= 0) {\n data = res.json()\n } else {\n data = res.text()\n }\n return data.then(err => {\n throw new FetchError(res, err)\n })\n}\n\nfunction handleJSONResponse (res) {\n const contentType = res.headers.get('content-type')\n if (!contentType || contentType.indexOf('json') < 0) {\n return res.text((data) => {\n throw new FetchError(res, new Error('Response is not JSON: ' + data))\n })\n }\n\n const json = res.json()\n if (contentType.indexOf('application/vnd.api+json') === 0) {\n return json.then(jsonapi)\n } else {\n return json\n }\n}\n\nexport class FetchError extends Error {\n constructor (res, reason) {\n super()\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor)\n }\n // XXX We have to hardcode this because babel doesn't play nice when extending Error\n this.name = 'FetchError'\n this.response = res\n this.url = res.url\n this.status = res.status\n this.reason = reason\n }\n}\n\nFetchError.isUnauthorized = function (err) {\n // XXX We can't use err instanceof FetchError because of the caveats of babel\n return err.name === 'FetchError' && err.status === 401\n}\n\nFetchError.isNotFound = function (err) {\n // XXX We can't use err instanceof FetchError because of the caveats of babel\n return err.name === 'FetchError' && err.status === 404\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/fetch.js","function indexKey (doc) {\n return doc.type + '/' + doc.id\n}\n\nfunction findByRef (resources, ref) {\n return resources[indexKey(ref)]\n}\n\nfunction handleResource (rawResource, resources, links) {\n let resource = {\n _id: rawResource.id,\n _type: rawResource.type,\n _rev: (rawResource.meta && rawResource.meta.rev),\n links: Object.assign({}, rawResource.links, links),\n attributes: rawResource.attributes,\n relations: (name) => {\n let rels = rawResource.relationships[name]\n if (rels === undefined || rels.data === undefined) return undefined\n if (rels.data === null) return null\n if (!Array.isArray(rels.data)) return findByRef(resources, rels.data)\n return rels.data.map(ref => findByRef(resources, ref))\n }\n }\n\n resources[indexKey(rawResource)] = resource\n\n return resource\n}\n\nfunction handleTopLevel (doc, resources = {}) {\n // build an index of included resource by Type & ID\n const included = doc.included\n\n if (Array.isArray(included)) {\n included.forEach((r) => handleResource(r, resources, doc.links))\n }\n\n if (Array.isArray(doc.data)) {\n return doc.data.map((r) => handleResource(r, resources, doc.links))\n } else {\n return handleResource(doc.data, resources, doc.links)\n }\n}\n\nexport default handleTopLevel\n\n\n\n// WEBPACK FOOTER //\n// ./src/jsonapi.js","import {createPath} from './utils'\nimport {normalizeDoctype} from './doctypes'\nimport {cozyFetchJSON} from './fetch'\n\nconst NOREV = 'stack-v2-no-rev'\n\nexport function create (cozy, doctype, attributes) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n if (isV2) {\n attributes.docType = doctype\n }\n const path = createPath(cozy, isV2, doctype)\n return cozyFetchJSON(cozy, 'POST', path, attributes).then((resp) => {\n if (isV2) {\n return find(cozy, doctype, resp._id)\n } else {\n return resp.data\n }\n })\n })\n}\n\nexport function find (cozy, doctype, id) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n\n if (!id) {\n return Promise.reject(new Error('Missing id parameter'))\n }\n\n const path = createPath(cozy, isV2, doctype, id)\n return cozyFetchJSON(cozy, 'GET', path).then((resp) => {\n if (isV2) {\n return Object.assign(resp, {_rev: NOREV})\n } else {\n return resp\n }\n })\n })\n}\n\nexport function changesFeed (cozy, doctype, options) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n const path = createPath(cozy, isV2, doctype, '_changes', options)\n return cozyFetchJSON(cozy, 'GET', path)\n })\n}\n\nexport function update (cozy, doctype, doc, changes) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n const {_id, _rev} = doc\n\n if (!_id) {\n return Promise.reject(new Error('Missing _id field in passed document'))\n }\n\n if (!isV2 && !_rev) {\n return Promise.reject(new Error('Missing _rev field in passed document'))\n }\n\n if (isV2) {\n changes = Object.assign({ _id }, changes)\n } else {\n changes = Object.assign({ _id, _rev }, changes)\n }\n\n const path = createPath(cozy, isV2, doctype, _id)\n return cozyFetchJSON(cozy, 'PUT', path, changes).then((resp) => {\n if (isV2) {\n return find(cozy, doctype, _id)\n } else {\n return resp.data\n }\n })\n })\n}\n\nexport function updateAttributes (cozy, doctype, _id, changes, tries = 3) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n return find(cozy, doctype, _id)\n .then((doc) => {\n return update(cozy, doctype, doc, Object.assign({ _id }, doc, changes))\n })\n .catch((err) => {\n if (tries > 0) {\n return updateAttributes(cozy, doctype, _id, changes, tries - 1)\n } else {\n throw err\n }\n })\n })\n}\n\nexport function _delete (cozy, doctype, doc) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n const {_id, _rev} = doc\n\n if (!_id) {\n return Promise.reject(new Error('Missing _id field in passed document'))\n }\n\n if (!isV2 && !_rev) {\n return Promise.reject(new Error('Missing _rev field in passed document'))\n }\n\n const query = isV2 ? null : { rev: _rev }\n const path = createPath(cozy, isV2, doctype, _id, query)\n return cozyFetchJSON(cozy, 'DELETE', path).then((resp) => {\n if (isV2) {\n return {id: _id, rev: NOREV}\n } else {\n return resp\n }\n })\n })\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/data.js","import {warn} from './utils'\n\nexport const DOCTYPE_FILES = 'io.cozy.files'\n\nconst KNOWN_DOCTYPES = {\n 'files': DOCTYPE_FILES,\n 'folder': DOCTYPE_FILES,\n 'contact': 'io.cozy.contacts',\n 'event': 'io.cozy.events',\n 'track': 'io.cozy.labs.music.track',\n 'playlist': 'io.cozy.labs.music.playlist'\n}\n\nconst REVERSE_KNOWN = {}\nObject.keys(KNOWN_DOCTYPES).forEach(k => {\n REVERSE_KNOWN[KNOWN_DOCTYPES[k]] = k\n})\n\nexport function normalizeDoctype (cozy, isV2, doctype) {\n let isQualified = doctype.indexOf('.') !== -1\n if (isV2 && isQualified) {\n let known = REVERSE_KNOWN[doctype]\n if (known) return known\n return doctype.replace(/\\./g, '-')\n }\n if (!isV2 && !isQualified) {\n let known = KNOWN_DOCTYPES[doctype]\n if (known) {\n warn('you are using a non-qualified doctype ' + doctype + ' assumed to be ' + known)\n return known\n }\n throw new Error('Doctype ' + doctype + ' should be qualified.')\n }\n return doctype\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/doctypes.js","import {warn, createPath} from './utils'\nimport {normalizeDoctype} from './doctypes'\nimport {cozyFetchJSON} from './fetch'\n\nexport function defineIndex (cozy, doctype, fields) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n if (!Array.isArray(fields) || fields.length === 0) {\n throw new Error('defineIndex fields should be a non-empty array')\n }\n if (isV2) {\n return defineIndexV2(cozy, doctype, fields)\n } else {\n return defineIndexV3(cozy, doctype, fields)\n }\n })\n}\n\nexport function query (cozy, indexRef, options) {\n return cozy.isV2().then((isV2) => {\n if (!indexRef) {\n throw new Error('query should be passed the indexRef')\n }\n if (isV2) {\n return queryV2(cozy, indexRef, options)\n } else {\n return queryV3(cozy, indexRef, options)\n }\n })\n}\n\n// Internals\n\nconst VALUEOPERATORS = ['$eq', '$gt', '$gte', '$lt', '$lte']\nconst LOGICOPERATORS = ['$or', '$and', '$not']\n\n/* eslint-disable */\nconst MAP_TEMPLATE = (function (doc) {\n if (doc.docType.toLowerCase() === 'DOCTYPEPLACEHOLDER'){\n emit(FIELDSPLACEHOLDER, doc)\n }\n}).toString().replace(/ /g, '').replace(/\\n/g, '')\nconst COUCHDB_INFINITY = {\"\\uFFFF\": \"\\uFFFF\"}\nconst COUCHDB_LOWEST = null\n/* eslint-enable */\n\n// defineIndexV2 is equivalent to defineIndex but only works for V2.\n// It transforms the index fields into a map reduce view.\nfunction defineIndexV2 (cozy, doctype, fields) {\n let indexName = 'by' + fields.map(capitalize).join('')\n let indexDefinition = { map: makeMapFunction(doctype, fields), reduce: '_count' }\n let path = `/request/${doctype}/${indexName}/`\n return cozyFetchJSON(cozy, 'PUT', path, indexDefinition)\n .then(() => ({ doctype: doctype, type: 'mapreduce', name: indexName, fields: fields }))\n}\n\n// defineIndexV2 is equivalent to defineIndex but only works for V2.\n// It transforms the index fields into a map reduce view.\nfunction defineIndexV3 (cozy, doctype, fields) {\n let path = createPath(cozy, false, doctype, '_index')\n let indexDefinition = {'index': {fields}}\n return cozyFetchJSON(cozy, 'POST', path, indexDefinition)\n .then((response) => ({ doctype: doctype, type: 'mango', name: response.id, fields: fields }))\n}\n\n// queryV2 is equivalent to query but only works for V2.\n// It transforms the query into a _views call using makeMapReduceQuery\nfunction queryV2 (cozy, indexRef, options) {\n if (indexRef.type !== 'mapreduce') {\n throw new Error('query indexRef should be the return value of defineIndexV2')\n }\n if (options.fields) {\n warn('query fields will be ignored on v2')\n }\n\n let path = `/request/${indexRef.doctype}/${indexRef.name}/`\n let opts = makeMapReduceQuery(indexRef, options)\n return cozyFetchJSON(cozy, 'POST', path, opts)\n .then((response) => response.map(r => r.value))\n}\n\n// queryV3 is equivalent to query but only works for V3\nfunction queryV3 (cozy, indexRef, options) {\n if (indexRef.type !== 'mango') {\n throw new Error('indexRef should be the return value of defineIndexV3')\n }\n\n let opts = {\n use_index: indexRef.name,\n fields: options.fields,\n selector: options.selector,\n limit: options.limit,\n since: options.since\n }\n\n if (options.descending) {\n opts.sort = indexRef.fields.map(f => ({ [f]: 'desc' }))\n }\n\n let path = createPath(cozy, false, indexRef.doctype, '_find')\n return cozyFetchJSON(cozy, 'POST', path, opts)\n .then((response) => response.docs)\n}\n\n// misc\nfunction capitalize (name) {\n return name.charAt(0).toUpperCase() + name.slice(1)\n}\n\nfunction makeMapFunction (doctype, fields) {\n fields = '[' + fields.map(name => 'doc.' + name).join(',') + ']'\n\n return MAP_TEMPLATE.replace('DOCTYPEPLACEHOLDER', doctype.toLowerCase())\n .replace('FIELDSPLACEHOLDER', fields)\n}\n\n// parseSelector takes a mango selector and returns it as an array of filter\n// a filter is [path, operator, value] array\n// a path is an array of field names\n// This function is only exported so it can be unit tested.\n// Example :\n// parseSelector({\"test\":{\"deep\": {\"$gt\": 3}}})\n// [[['test', 'deep'], '$gt', 3 ]]\nexport function parseSelector (selector, path = [], operator = '$eq') {\n if ((typeof selector) !== 'object') {\n return [[path, operator, selector]]\n }\n\n let keys = Object.keys(selector)\n if (keys.length === 0) {\n throw new Error('empty selector')\n } else {\n return keys.reduce(function (acc, k) {\n if (LOGICOPERATORS.indexOf(k) !== -1) {\n throw new Error('cozy-client-js does not support mango logic ops')\n } else if (VALUEOPERATORS.indexOf(k) !== -1) {\n return acc.concat(parseSelector(selector[k], path, k))\n } else {\n return acc.concat(parseSelector(selector[k], path.concat(k), '$eq'))\n }\n }, [])\n }\n}\n\n// normalizeSelector takes a mango selector and returns it as an object\n// normalized.\n// This function is only exported so it can be unit tested.\n// Example :\n// parseSelector({\"test\":{\"deep\": {\"$gt\": 3}}})\n// {\"test.deep\": {\"$gt\": 3}}\nexport function normalizeSelector (selector) {\n var filters = parseSelector(selector)\n return filters.reduce(function (acc, filter) {\n let [path, op, value] = filter\n let field = path.join('.')\n acc[field] = acc[field] || {}\n acc[field][op] = value\n return acc\n }, {})\n}\n\n// applySelector takes the normalized selector for the current field\n// and append the proper values to opts.startkey, opts.endkey\nfunction applySelector (selector, opts) {\n let value = selector['$eq']\n let lower = COUCHDB_LOWEST\n let upper = COUCHDB_INFINITY\n let inclusiveEnd\n\n if (value) {\n opts.startkey.push(value)\n opts.endkey.push(value)\n return false\n }\n\n value = selector['$gt']\n if (value) {\n throw new Error('operator $gt (strict greater than) not supported')\n }\n\n value = selector['$gte']\n if (value) {\n lower = value\n }\n\n value = selector['$lte']\n if (value) {\n upper = value\n inclusiveEnd = true\n }\n\n value = selector['$lt']\n if (value) {\n upper = value\n inclusiveEnd = false\n }\n\n opts.startkey.push(lower)\n opts.endkey.push(upper)\n if (inclusiveEnd !== undefined) opts.inclusive_end = inclusiveEnd\n return true\n}\n\n// makeMapReduceQuery takes a mango query and generate _views call parameters\n// to obtain same results depending on fields in the passed indexRef.\nexport function makeMapReduceQuery (indexRef, query) {\n let mrquery = {\n startkey: [],\n endkey: [],\n reduce: false\n }\n let firstFreeValueField = null\n let normalizedSelector = normalizeSelector(query.selector)\n\n indexRef.fields.forEach(function (field) {\n let selector = normalizedSelector[field]\n\n if (selector && firstFreeValueField != null) {\n throw new Error('Selector on field ' + field + ', but not on ' + firstFreeValueField + ' which is higher in index fields.')\n } else if (selector) {\n selector.used = true\n let isFreeValue = applySelector(selector, mrquery)\n if (isFreeValue) firstFreeValueField = field\n } else if (firstFreeValueField == null) {\n firstFreeValueField = field\n mrquery.endkey.push(COUCHDB_INFINITY)\n }\n })\n\n Object.keys(normalizedSelector).forEach(function (field) {\n if (!normalizedSelector[field].used) {\n throw new Error('Cant apply selector on ' + field + ', it is not in index')\n }\n })\n\n if (query.descending) {\n mrquery = {\n descending: true,\n reduce: false,\n startkey: mrquery.endkey,\n endkey: mrquery.startkey,\n inclusive_end: mrquery.inclusive_end\n }\n }\n\n return mrquery\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/mango.js","/* global Blob, File */\nimport {cozyFetch, cozyFetchJSON} from './fetch'\nimport jsonapi from './jsonapi'\nimport { DOCTYPE_FILES } from './doctypes'\n\nconst contentTypeOctetStream = 'application/octet-stream'\n\nfunction doUpload (cozy, data, method, path, options) {\n if (!data) {\n throw new Error('missing data argument')\n }\n\n // transform any ArrayBufferView to ArrayBuffer\n if (data.buffer && data.buffer instanceof ArrayBuffer) {\n data = data.buffer\n }\n\n const isBuffer = (typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer)\n const isFile = (typeof File !== 'undefined' && data instanceof File)\n const isBlob = (typeof Blob !== 'undefined' && data instanceof Blob)\n const isStream = (data.readable === true && typeof data.pipe === 'function')\n const isString = (typeof data === 'string')\n\n if (!isBuffer && !isFile && !isBlob && !isStream && !isString) {\n throw new Error('invalid data type')\n }\n\n let {contentType, checksum, lastModifiedDate, ifMatch} = options || {}\n if (!contentType) {\n if (isBuffer) {\n contentType = contentTypeOctetStream\n } else if (isFile) {\n contentType = data.type || contentTypeOctetStream\n if (!lastModifiedDate) {\n lastModifiedDate = data.lastModifiedDate\n }\n } else if (isBlob) {\n contentType = contentTypeOctetStream\n } else if (isStream) {\n contentType = contentTypeOctetStream\n } else if (typeof data === 'string') {\n contentType = 'text/plain'\n }\n }\n\n if (lastModifiedDate && typeof lastModifiedDate === 'string') {\n lastModifiedDate = new Date(lastModifiedDate)\n }\n\n return cozyFetch(cozy, path, {\n method: method,\n headers: {\n 'Content-Type': contentType,\n 'Content-MD5': checksum || '',\n 'Date': lastModifiedDate ? lastModifiedDate.toGMTString() : '',\n 'If-Match': ifMatch || ''\n },\n body: data\n })\n .then((res) => {\n const json = res.json()\n if (!res.ok) {\n return json.then(err => { throw err })\n } else {\n return json.then(jsonapi)\n }\n })\n}\n\nexport function create (cozy, data, options) {\n let {name, dirID, executable} = options || {}\n\n // handle case where data is a file and contains the name\n if (!name && typeof data.name === 'string') {\n name = data.name\n }\n\n if (typeof name !== 'string' || name === '') {\n throw new Error('missing name argument')\n }\n\n if (executable === undefined) {\n executable = false\n }\n\n const path = `/files/${encodeURIComponent(dirID || '')}`\n const query = `?Name=${encodeURIComponent(name)}&Type=file&Executable=${executable}`\n return doUpload(cozy, data, 'POST', `${path}${query}`, options)\n}\n\nexport function createDirectory (cozy, options) {\n let {name, dirID, lastModifiedDate} = options || {}\n\n if (typeof name !== 'string' || name === '') {\n throw new Error('missing name argument')\n }\n\n if (lastModifiedDate && typeof lastModifiedDate === 'string') {\n lastModifiedDate = new Date(lastModifiedDate)\n }\n\n const path = `/files/${encodeURIComponent(dirID || '')}`\n const query = `?Name=${encodeURIComponent(name)}&Type=directory`\n return cozyFetchJSON(cozy, 'POST', `${path}${query}`, undefined, {\n headers: {\n 'Date': lastModifiedDate ? lastModifiedDate.toGMTString() : ''\n }\n })\n}\n\nexport function updateById (cozy, id, data, options) {\n return doUpload(cozy, data, 'PUT', `/files/${encodeURIComponent(id)}`, options)\n}\n\nfunction doUpdateAttributes (cozy, attrs, path, options) {\n if (!attrs || typeof attrs !== 'object') {\n throw new Error('missing attrs argument')\n }\n\n const {ifMatch} = options || {}\n const body = { data: { attributes: attrs } }\n return cozyFetchJSON(cozy, 'PATCH', path, body, {\n headers: {\n 'If-Match': ifMatch || ''\n }\n })\n}\n\nexport function updateAttributesById (cozy, id, attrs, options) {\n return doUpdateAttributes(cozy, attrs,\n `/files/${encodeURIComponent(id)}`, options)\n}\n\nexport function updateAttributesByPath (cozy, path, attrs, options) {\n return doUpdateAttributes(cozy, attrs,\n `/files/metadata?Path=${encodeURIComponent(path)}`, options)\n}\n\nexport function trashById (cozy, id) {\n if (typeof id !== 'string' || id === '') {\n throw new Error('missing id argument')\n }\n return cozyFetchJSON(cozy, 'DELETE', `/files/${encodeURIComponent(id)}`)\n}\n\nexport function statById (cozy, id, offline = true) {\n if (offline && cozy.offline.hasDatabase(DOCTYPE_FILES)) {\n let db = cozy.offline.getDatabase(DOCTYPE_FILES)\n return Promise.all([\n db.get(id),\n db.find({selector: {'dir_id': id}})\n ]).then(([doc, children]) => {\n children = children.docs.map(doc => {\n return addIsDir(toJsonApi(cozy, doc))\n })\n return addIsDir(toJsonApi(cozy, doc, children))\n })\n }\n return cozyFetchJSON(cozy, 'GET', `/files/${encodeURIComponent(id)}`)\n .then(addIsDir)\n}\n\nexport function statByPath (cozy, path) {\n return cozyFetchJSON(cozy, 'GET', `/files/metadata?Path=${encodeURIComponent(path)}`)\n .then(addIsDir)\n}\n\nexport function downloadById (cozy, id) {\n return cozyFetch(cozy, `/files/download/${encodeURIComponent(id)}`)\n}\n\nexport function downloadByPath (cozy, path) {\n return cozyFetch(cozy, `/files/download?Path=${encodeURIComponent(path)}`)\n}\n\nfunction extractResponseLinkRelated (res) {\n let href = res.links && res.links.related\n if (!href) throw new Error('No related link in server response')\n return href\n}\n\nexport function getDowloadLink (cozy, path) {\n return cozyFetchJSON(cozy, 'POST', `/files/downloads?Path=${encodeURIComponent(path)}`)\n .then(extractResponseLinkRelated)\n}\n\nexport function getArchiveLink (cozy, paths, name = 'files') {\n const archive = {\n type: 'io.cozy.archives',\n attributes: {\n name: name,\n files: paths\n }\n }\n return cozyFetchJSON(cozy, 'POST', `/files/archive`, {data: archive})\n .then(extractResponseLinkRelated)\n}\n\nexport function listTrash (cozy) {\n return cozyFetchJSON(cozy, 'GET', `/files/trash`)\n}\n\nexport function clearTrash (cozy) {\n return cozyFetchJSON(cozy, 'DELETE', `/files/trash`)\n}\n\nexport function restoreById (cozy, id) {\n return cozyFetchJSON(cozy, 'POST', `/files/trash/${encodeURIComponent(id)}`)\n}\n\nexport function destroyById (cozy, id) {\n return cozyFetchJSON(cozy, 'DELETE', `/files/trash/${encodeURIComponent(id)}`)\n}\n\nfunction addIsDir (obj) {\n obj.isDir = obj.attributes.type === 'directory'\n return obj\n}\n\nfunction toJsonApi (cozy, doc, contents = []) {\n let clone = JSON.parse(JSON.stringify(doc))\n delete clone._id\n delete clone._rev\n return {\n _id: doc._id,\n _rev: doc._rev,\n _type: DOCTYPE_FILES,\n attributes: clone,\n relations: (name) => {\n if (name === 'contents') {\n return contents\n }\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/files.js","import PouchDB from 'pouchdb'\nimport pouchdbFind from 'pouchdb-find'\nimport { DOCTYPE_FILES } from './doctypes'\n\nlet pluginLoaded = false\n\nexport function init (cozy, { options = {}, doctypes = [], timer }) {\n for (let doctype of doctypes) {\n createDatabase(cozy, doctype, options)\n }\n if (timer !== undefined) { startAllSync(cozy, timer) }\n}\n\nexport function createDatabase (cozy, doctype, options = {}, timer) {\n if (!pluginLoaded) {\n PouchDB.plugin(pouchdbFind)\n pluginLoaded = true\n }\n cozy._offline = cozy._offline || []\n cozy._offline[doctype] = cozy._offline[doctype] || {}\n let offline = cozy._offline[doctype]\n if (offline && offline.database) { return offline.database }\n offline.database = new PouchDB(doctype, options)\n offline.timer = timer\n offline.autoSync = null\n if (timer !== undefined) { startSync(cozy, doctype, timer) }\n createIndexes(cozy, offline.database, doctype)\n return offline.database\n}\n\nexport function hasDatabase (cozy, doctype) {\n return cozy._offline !== null &&\n doctype in cozy._offline &&\n cozy._offline[doctype].database !== undefined\n}\n\nexport function getDatabase (cozy, doctype) {\n if (hasDatabase(cozy, doctype)) {\n return cozy._offline[doctype].database\n }\n return\n}\n\nexport function destroyDatabase (cozy, doctype) {\n if (hasDatabase(cozy, doctype)) {\n stopSync(cozy, doctype)\n getDatabase(cozy, doctype).destroy()\n delete getDatabase(cozy, doctype)\n }\n}\n\nexport function destroyAllDatabase (cozy) {\n getDoctypes(cozy).forEach(doctype => destroyDatabase(cozy, doctype))\n}\n\nexport function getDoctypes (cozy) {\n if (cozy._offline === null) { return [] }\n return Object.keys(cozy._offline)\n}\n\n//\n// SYNC\n//\n\nexport function startAllSync (cozy, timer) {\n if (timer) {\n const doctypes = getDoctypes(cozy)\n doctypes.forEach((doctype) => {\n startSync(cozy, doctype, timer)\n })\n }\n}\n\nexport function stopAllSync (cozy) {\n const doctypes = getDoctypes(cozy)\n doctypes.forEach((doctype) => {\n stopSync(cozy, doctype)\n })\n}\n\nexport function startSync (cozy, doctype, timer) {\n // TODO: add timer limitation for not flooding Gozy\n if (hasDatabase(cozy, doctype)) {\n if (hasSync(cozy, doctype)) {\n if (timer === cozy._offline[doctype].timer) {\n return\n }\n stopSync(cozy, doctype)\n }\n let offline = cozy._offline[doctype]\n offline.timer = timer\n offline.autoSync = setInterval(() => {\n if (offline.replicate === undefined) {\n replicateFromCozy(cozy, doctype)\n // TODO: add replicationToCozy\n }\n }, timer * 1000)\n }\n}\n\nexport function hasSync (cozy, doctype) {\n return cozy._offline !== null &&\n doctype in cozy._offline &&\n cozy._offline[doctype].autoSync !== null\n}\n\nexport function stopSync (cozy, doctype) {\n if (hasSync(cozy, doctype)) {\n let offline = cozy._offline[doctype]\n clearInterval(offline.autoSync)\n delete offline.autoSync\n if (offline.replication) { offline.replication.cancel() }\n }\n}\n\nexport function replicateFromCozy (cozy, doctype, options = {}) {\n if (hasDatabase(cozy, doctype)) {\n if (options.live === true) {\n return Promise.reject(new Error('You can\\'t use `live` option with Cozy couchdb.'))\n }\n if (options.manualAuthCredentials) {\n return Promise.resolve(replicateFromCozyWithAuth(cozy, doctype, options, options.manualAuthCredentials))\n } else {\n return cozy.authorize().then((credentials) => {\n return replicateFromCozyWithAuth(cozy, doctype, options, credentials)\n })\n }\n } else {\n return Promise.reject(new Error(`You should add this doctype: ${doctype} to offline.`))\n }\n}\n\nexport function replicateFromCozyWithAuth (cozy, doctype, options, credentials) {\n let basic = credentials.token.toBasicAuth()\n let url = (cozy._url + '/data/' + doctype).replace('//', `//${basic}`)\n let db = getDatabase(cozy, doctype)\n let offline = cozy._offline[doctype]\n offline.replication = db.replicate.from(url, options).on('complete', () => {\n offline.replication = undefined\n })\n return offline.replication\n}\n\nfunction createIndexes (cozy, db, doctype) {\n if (doctype === DOCTYPE_FILES) {\n db.createIndex({index: {fields: ['dir_id']}})\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/offline.js","module.exports = __WEBPACK_EXTERNAL_MODULE_15__;\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"pouchdb\"\n// module id = 15\n// module chunks = 0","module.exports = __WEBPACK_EXTERNAL_MODULE_16__;\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"pouchdb-find\"\n// module id = 16\n// module chunks = 0","import {cozyFetchJSON} from './fetch'\n\nexport function diskUsage (cozy) {\n return cozyFetchJSON(cozy, 'GET', `/settings/disk-usage`)\n}\n\nexport function changePassphrase (cozy, currentPassPhrase, newPassPhrase) {\n return cozyFetchJSON(cozy, 'PUT', `/settings/passphrase`, {\n current_passphrase: currentPassPhrase,\n new_passphrase: newPassPhrase\n })\n}\n\nexport function getInstance (cozy) {\n return cozyFetchJSON(cozy, 'GET', `/settings/instance`)\n}\n\nexport function updateInstance (cozy, instance) {\n return cozyFetchJSON(cozy, 'PUT', `/settings/instance`, instance)\n}\n\nexport function getClients (cozy) {\n return cozyFetchJSON(cozy, 'GET', `/settings/clients`)\n}\n\nexport function deleteClientById (cozy, id) {\n return cozyFetchJSON(cozy, 'DELETE', `/settings/clients/${id}`)\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/settings.js","import {cozyFetchJSON} from './fetch'\nimport { DOCTYPE_FILES } from './doctypes'\n\nexport function addReferencedFiles (cozy, doc, ids) {\n if (!doc) throw new Error('missing doc argument')\n if (!Array.isArray(ids)) ids = [ids]\n\n const refs = ids.map((id) => ({type: DOCTYPE_FILES, id: id}))\n\n return cozyFetchJSON(cozy, 'POST', makeReferencesPath(doc), {data: refs})\n}\n\nexport function listReferencedFiles (cozy, doc) {\n if (!doc) throw new Error('missing doc argument')\n return cozyFetchJSON(cozy, 'GET', makeReferencesPath(doc))\n .then((files) => files.map((file) => file._id))\n}\n\nfunction makeReferencesPath (doc) {\n const type = encodeURIComponent(doc._type)\n const id = encodeURIComponent(doc._id)\n return `/data/${type}/${id}/relationships/references`\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/relations.js"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack:///webpack/universalModuleDefinition","webpack:///webpack/bootstrap 7e1ab8a2a16d5c7fa7ff","webpack:///./~/isomorphic-fetch/fetch-npm-browserify.js","webpack:///./~/whatwg-fetch/fetch.js","webpack:///./src/index.js","webpack:///./src/utils.js","webpack:///./src/auth_storage.js","webpack:///./src/auth_v2.js","webpack:///./src/auth_v3.js","webpack:///./src/fetch.js","webpack:///./src/jsonapi.js","webpack:///./src/data.js","webpack:///./src/doctypes.js","webpack:///./src/mango.js","webpack:///./src/files.js","webpack:///./src/offline.js","webpack:///external \"pouchdb\"","webpack:///external \"pouchdb-find\"","webpack:///./src/settings.js","webpack:///./src/relations.js"],"names":["auth","data","mango","files","offline","settings","relations","AppTokenV3","AppToken","AccessTokenV3","AccessToken","ClientV3","Client","AuthNone","AuthRunning","AuthError","AuthOK","defaultClientParams","softwareID","dataProto","create","find","update","delete","_delete","updateAttributes","changesFeed","defineIndex","query","addReferencedFiles","listReferencedFiles","destroy","authProto","client","registerClient","updateClient","unregisterClient","getClient","getAuthCodeURL","getAccessToken","refreshToken","filesProto","createDirectory","updateById","updateAttributesById","updateAttributesByPath","trashById","statById","statByPath","downloadById","downloadByPath","getDowloadLink","getArchiveLink","listTrash","clearTrash","restoreById","destroyById","offlineProto","init","getDoctypes","hasDatabase","getDatabase","createDatabase","destroyDatabase","destroyAllDatabase","hasReplication","replicateFromCozy","stopReplication","stopAllReplication","hasRepeatedReplication","startRepeatedReplication","stopRepeatedReplication","stopAllRepeatedReplication","settingsProto","diskUsage","changePassphrase","getInstance","updateInstance","getClients","deleteClientById","options","AppTokenV2","LocalStorage","MemoryStorage","_inited","_oauth","_token","_authstate","_authcreds","_storage","_version","_offline","token","oauth","Error","storage","_clientParams","Object","assign","clientParams","_onRegistered","onRegistered","nopOnRegistered","url","cozyURL","length","slice","_url","disablePromises","addToProto","state","isV2","then","oauthFlow","Promise","resolve","creds","save","CredsKey","path","pathprefix","fetch","res","ok","json","status","datasystem","undefined","protoify","context","fn","prototyped","args","ctx","obj","proto","attr","module","exports","unpromiser","isPromise","sleep","retry","getFuzzedDelay","getBackedoffDelay","createPath","encodeQuery","decodeQuery","warn","FuzzFactor","value","apply","l","cb","err","time","setTimeout","count","delay","doTry","catch","retryDelay","fuzzingFactor","Math","random","retryCount","pow","cozy","doctype","id","route","encodeURIComponent","q","qname","queryIndex","indexOf","queries","fragIndex","queryStr","parts","split","i","pair","decodeURIComponent","hasOwnProperty","warned","text","push","console","prefix","window","localStorage","key","setItem","JSON","stringify","item","getItem","parse","removeItem","hash","deleted","getAppToken","V2TOKEN_ABORT_TIMEOUT","reject","parent","postMessage","origin","location","intent","action","timeout","receiver","event","appName","e","removeEventListener","clearTimeout","addEventListener","opts","btoa","StateSize","StateKey","clientID","client_id","clientSecret","client_secret","registrationAccessToken","registration_access_token","redirect_uris","redirectURI","software_id","softwareVersion","software_version","clientName","client_name","clientKind","client_kind","clientURI","client_uri","logoURI","logo_uri","policyURI","policy_uri","tokenType","token_type","accessToken","access_token","refresh_token","scope","cli","isRegistered","toRegisterJSON","disableAuth","resetSecret","manualAuthCredentials","createClient","oldClient","newClient","shouldPassRegistration","scopes","generateRandomState","join","pageURL","grantQueries","getGrantCodeFromPageURL","retrieveToken","code","tryCount","clearAndRetry","clear","registerNewClient","all","load","credentials","storedState","isUnauthorized","isNotFound","statePromise","t","body","headers","href","buffer","crypto","getRandomValues","Uint8Array","require","randomBytes","Array","floor","String","fromCharCode","replace","cozyFetch","cozyFetchJSON","fullpath","resp","cozyFetchWithAuth","authorize","handleResponse","toAuthHeader","newToken","saveCredentials","method","handleJSONResponse","contentType","get","FetchError","reason","captureStackTrace","constructor","name","response","indexKey","doc","type","findByRef","resources","ref","handleResource","rawResource","links","resource","_id","_type","_rev","meta","rev","attributes","rels","relationships","isArray","map","handleTopLevel","included","forEach","r","NOREV","docType","changes","tries","normalizeDoctype","DOCTYPE_FILES","KNOWN_DOCTYPES","REVERSE_KNOWN","keys","k","isQualified","known","parseSelector","normalizeSelector","makeMapReduceQuery","fields","defineIndexV2","defineIndexV3","indexRef","queryV2","queryV3","VALUEOPERATORS","LOGICOPERATORS","MAP_TEMPLATE","toLowerCase","emit","FIELDSPLACEHOLDER","toString","COUCHDB_INFINITY","COUCHDB_LOWEST","indexName","capitalize","indexDefinition","makeMapFunction","reduce","use_index","selector","limit","since","descending","sort","f","docs","charAt","toUpperCase","operator","acc","concat","filters","filter","op","field","applySelector","lower","upper","inclusiveEnd","startkey","endkey","inclusive_end","mrquery","firstFreeValueField","normalizedSelector","used","isFreeValue","contentTypeOctetStream","doUpload","ArrayBuffer","isBuffer","isFile","File","isBlob","Blob","isStream","readable","pipe","isString","checksum","lastModifiedDate","ifMatch","Date","toGMTString","dirID","executable","doUpdateAttributes","attrs","db","children","addIsDir","toJsonApi","extractResponseLinkRelated","related","paths","archive","isDir","contents","clone","setDatabase","pluginLoaded","doctypes","getInfo","database","errorDatabase","plugin","createIndexes","createIndex","index","getReplication","replication","setReplication","getReplicationUrl","basic","toBasicAuth","getReplicationPromise","replicationPromise","setReplicationPromise","promise","live","replicate","from","on","info","cancel","stop","getRepeatedReplication","interval","setRepeatedReplication","timer","setInterval","clearInterval","currentPassPhrase","newPassPhrase","current_passphrase","new_passphrase","instance","ids","refs","makeReferencesPath","file"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,mCAAmC;AACnC,CAAC;AACD,O;ACVA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,uBAAe;AACf;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;;;;;;;;;;;;;;ACtCA;AACA;AACA;AACA;AACA;AACA;;;;;;;ACLA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA;AACA,MAAK;AACL;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA,iBAAgB;AAChB;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA,QAAO;;AAEP,MAAK;AACL;AACA;AACA,QAAO;AACP;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,yCAAwC,mBAAmB;AAC3D;AACA;;AAEA;AACA;AACA,mCAAkC,oBAAoB;AACtD;AACA;;AAEA;AACA;AACA,yCAAwC,4BAA4B;AACpE;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAK;AACL;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA,oBAAmB,iBAAiB;AACpC;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA,QAAO;AACP;AACA,QAAO;AACP;AACA,QAAO;AACP;AACA,QAAO;AACP;AACA,QAAO;AACP;AACA;AACA;AACA,QAAO;AACP;AACA,QAAO;AACP;AACA;;AAEA;AACA;AACA,wDAAuD;AACvD,UAAS;AACT;AACA,UAAS;AACT,+EAA8E;AAC9E;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,UAAS;AACT;AACA,UAAS;AACT;AACA,UAAS;AACT;AACA;AACA;;AAEA;AACA;AACA;AACA,UAAS;AACT;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA,QAAO;AACP;AACA,QAAO;AACP;AACA,QAAO;AACP;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,MAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA,+BAA8B,uBAAuB;AACrD;;AAEA;AACA;AACA;AACA;AACA;AACA;A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cyE,IAAd,EAAoB,KAApB,EAA2BmT,mBAAmB/J,GAAnB,CAA3B,EACJ3M,IADI,CACC,UAAC7G,KAAD;AAAA,YAAWA,MAAM0U,GAAN,CAAU,UAAC8I,IAAD;AAAA,cAAUA,KAAKvJ,GAAf;AAAA,MAAV,CAAX;AAAA,IADD,CAAP;AAED;;AAED,UAASsJ,kBAAT,CAA6B/J,GAA7B,EAAkC;AAChC,OAAMC,OAAOjJ,mBAAmBgJ,IAAIU,KAAvB,CAAb;AACA,OAAM5J,KAAKE,mBAAmBgJ,IAAIS,GAAvB,CAAX;AACA,qBAAgBR,IAAhB,SAAwBnJ,EAAxB;AACD,E","file":"cozy-client.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory(require(\"pouchdb\"), require(\"pouchdb-find\"));\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine(\"client\", [\"pouchdb\", \"pouchdb-find\"], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"client\"] = factory(require(\"pouchdb\"), require(\"pouchdb-find\"));\n\telse\n\t\troot[\"cozy\"] = root[\"cozy\"] || {}, root[\"cozy\"][\"client\"] = factory(root[\"pouchdb\"], root[\"pouchdb-find\"]);\n})(this, function(__WEBPACK_EXTERNAL_MODULE_15__, __WEBPACK_EXTERNAL_MODULE_16__) {\nreturn \n\n\n// WEBPACK FOOTER //\n// webpack/universalModuleDefinition"," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\texports: {},\n \t\t\tid: moduleId,\n \t\t\tloaded: false\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.loaded = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(0);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap 7e1ab8a2a16d5c7fa7ff","// the whatwg-fetch polyfill installs the fetch() function\n// on the global object (window or self)\n//\n// Return that as the export for use in Webpack, Browserify etc.\nrequire('whatwg-fetch');\nmodule.exports = self.fetch.bind(self);\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/isomorphic-fetch/fetch-npm-browserify.js\n// module id = 1\n// module chunks = 0","(function(self) {\n 'use strict';\n\n if (self.fetch) {\n return\n }\n\n var support = {\n searchParams: 'URLSearchParams' in self,\n iterable: 'Symbol' in self && 'iterator' in Symbol,\n blob: 'FileReader' in self && 'Blob' in self && (function() {\n try {\n new Blob()\n return true\n } catch(e) {\n return false\n }\n })(),\n formData: 'FormData' in self,\n arrayBuffer: 'ArrayBuffer' in self\n }\n\n if (support.arrayBuffer) {\n var viewClasses = [\n '[object Int8Array]',\n '[object Uint8Array]',\n '[object Uint8ClampedArray]',\n '[object Int16Array]',\n '[object Uint16Array]',\n '[object Int32Array]',\n '[object Uint32Array]',\n '[object Float32Array]',\n '[object Float64Array]'\n ]\n\n var isDataView = function(obj) {\n return obj && DataView.prototype.isPrototypeOf(obj)\n }\n\n var isArrayBufferView = ArrayBuffer.isView || function(obj) {\n return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1\n }\n }\n\n function normalizeName(name) {\n if (typeof name !== 'string') {\n name = String(name)\n }\n if (/[^a-z0-9\\-#$%&'*+.\\^_`|~]/i.test(name)) {\n throw new TypeError('Invalid character in header field name')\n }\n return name.toLowerCase()\n }\n\n function normalizeValue(value) {\n if (typeof value !== 'string') {\n value = String(value)\n }\n return value\n }\n\n // Build a destructive iterator for the value list\n function iteratorFor(items) {\n var iterator = {\n next: function() {\n var value = items.shift()\n return {done: value === undefined, value: value}\n }\n }\n\n if (support.iterable) {\n iterator[Symbol.iterator] = function() {\n return iterator\n }\n }\n\n return iterator\n }\n\n function Headers(headers) {\n this.map = {}\n\n if (headers instanceof Headers) {\n headers.forEach(function(value, name) {\n this.append(name, value)\n }, this)\n\n } else if (headers) {\n Object.getOwnPropertyNames(headers).forEach(function(name) {\n this.append(name, headers[name])\n }, this)\n }\n }\n\n Headers.prototype.append = function(name, value) {\n name = normalizeName(name)\n value = normalizeValue(value)\n var oldValue = this.map[name]\n this.map[name] = oldValue ? oldValue+','+value : value\n }\n\n Headers.prototype['delete'] = function(name) {\n delete this.map[normalizeName(name)]\n }\n\n Headers.prototype.get = function(name) {\n name = normalizeName(name)\n return this.has(name) ? this.map[name] : null\n }\n\n Headers.prototype.has = function(name) {\n return this.map.hasOwnProperty(normalizeName(name))\n }\n\n Headers.prototype.set = function(name, value) {\n this.map[normalizeName(name)] = normalizeValue(value)\n }\n\n Headers.prototype.forEach = function(callback, thisArg) {\n for (var name in this.map) {\n if (this.map.hasOwnProperty(name)) {\n callback.call(thisArg, this.map[name], name, this)\n }\n }\n }\n\n Headers.prototype.keys = function() {\n var items = []\n this.forEach(function(value, name) { items.push(name) })\n return iteratorFor(items)\n }\n\n Headers.prototype.values = function() {\n var items = []\n this.forEach(function(value) { items.push(value) })\n return iteratorFor(items)\n }\n\n Headers.prototype.entries = function() {\n var items = []\n this.forEach(function(value, name) { items.push([name, value]) })\n return iteratorFor(items)\n }\n\n if (support.iterable) {\n Headers.prototype[Symbol.iterator] = Headers.prototype.entries\n }\n\n function consumed(body) {\n if (body.bodyUsed) {\n return Promise.reject(new TypeError('Already read'))\n }\n body.bodyUsed = true\n }\n\n function fileReaderReady(reader) {\n return new Promise(function(resolve, reject) {\n reader.onload = function() {\n resolve(reader.result)\n }\n reader.onerror = function() {\n reject(reader.error)\n }\n })\n }\n\n function readBlobAsArrayBuffer(blob) {\n var reader = new FileReader()\n var promise = fileReaderReady(reader)\n reader.readAsArrayBuffer(blob)\n return promise\n }\n\n function readBlobAsText(blob) {\n var reader = new FileReader()\n var promise = fileReaderReady(reader)\n reader.readAsText(blob)\n return promise\n }\n\n function readArrayBufferAsText(buf) {\n var view = new Uint8Array(buf)\n var chars = new Array(view.length)\n\n for (var i = 0; i < view.length; i++) {\n chars[i] = String.fromCharCode(view[i])\n }\n return chars.join('')\n }\n\n function bufferClone(buf) {\n if (buf.slice) {\n return buf.slice(0)\n } else {\n var view = new Uint8Array(buf.byteLength)\n view.set(new Uint8Array(buf))\n return view.buffer\n }\n }\n\n function Body() {\n this.bodyUsed = false\n\n this._initBody = function(body) {\n this._bodyInit = body\n if (!body) {\n this._bodyText = ''\n } else if (typeof body === 'string') {\n this._bodyText = body\n } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {\n this._bodyBlob = body\n } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {\n this._bodyFormData = body\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this._bodyText = body.toString()\n } else if (support.arrayBuffer && support.blob && isDataView(body)) {\n this._bodyArrayBuffer = bufferClone(body.buffer)\n // IE 10-11 can't handle a DataView body.\n this._bodyInit = new Blob([this._bodyArrayBuffer])\n } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {\n this._bodyArrayBuffer = bufferClone(body)\n } else {\n throw new Error('unsupported BodyInit type')\n }\n\n if (!this.headers.get('content-type')) {\n if (typeof body === 'string') {\n this.headers.set('content-type', 'text/plain;charset=UTF-8')\n } else if (this._bodyBlob && this._bodyBlob.type) {\n this.headers.set('content-type', this._bodyBlob.type)\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8')\n }\n }\n }\n\n if (support.blob) {\n this.blob = function() {\n var rejected = consumed(this)\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return Promise.resolve(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(new Blob([this._bodyArrayBuffer]))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as blob')\n } else {\n return Promise.resolve(new Blob([this._bodyText]))\n }\n }\n\n this.arrayBuffer = function() {\n if (this._bodyArrayBuffer) {\n return consumed(this) || Promise.resolve(this._bodyArrayBuffer)\n } else {\n return this.blob().then(readBlobAsArrayBuffer)\n }\n }\n }\n\n this.text = function() {\n var rejected = consumed(this)\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return readBlobAsText(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as text')\n } else {\n return Promise.resolve(this._bodyText)\n }\n }\n\n if (support.formData) {\n this.formData = function() {\n return this.text().then(decode)\n }\n }\n\n this.json = function() {\n return this.text().then(JSON.parse)\n }\n\n return this\n }\n\n // HTTP methods whose capitalization should be normalized\n var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']\n\n function normalizeMethod(method) {\n var upcased = method.toUpperCase()\n return (methods.indexOf(upcased) > -1) ? upcased : method\n }\n\n function Request(input, options) {\n options = options || {}\n var body = options.body\n\n if (typeof input === 'string') {\n this.url = input\n } else {\n if (input.bodyUsed) {\n throw new TypeError('Already read')\n }\n this.url = input.url\n this.credentials = input.credentials\n if (!options.headers) {\n this.headers = new Headers(input.headers)\n }\n this.method = input.method\n this.mode = input.mode\n if (!body && input._bodyInit != null) {\n body = input._bodyInit\n input.bodyUsed = true\n }\n }\n\n this.credentials = options.credentials || this.credentials || 'omit'\n if (options.headers || !this.headers) {\n this.headers = new Headers(options.headers)\n }\n this.method = normalizeMethod(options.method || this.method || 'GET')\n this.mode = options.mode || this.mode || null\n this.referrer = null\n\n if ((this.method === 'GET' || this.method === 'HEAD') && body) {\n throw new TypeError('Body not allowed for GET or HEAD requests')\n }\n this._initBody(body)\n }\n\n Request.prototype.clone = function() {\n return new Request(this, { body: this._bodyInit })\n }\n\n function decode(body) {\n var form = new FormData()\n body.trim().split('&').forEach(function(bytes) {\n if (bytes) {\n var split = bytes.split('=')\n var name = split.shift().replace(/\\+/g, ' ')\n var value = split.join('=').replace(/\\+/g, ' ')\n form.append(decodeURIComponent(name), decodeURIComponent(value))\n }\n })\n return form\n }\n\n function parseHeaders(rawHeaders) {\n var headers = new Headers()\n rawHeaders.split('\\r\\n').forEach(function(line) {\n var parts = line.split(':')\n var key = parts.shift().trim()\n if (key) {\n var value = parts.join(':').trim()\n headers.append(key, value)\n }\n })\n return headers\n }\n\n Body.call(Request.prototype)\n\n function Response(bodyInit, options) {\n if (!options) {\n options = {}\n }\n\n this.type = 'default'\n this.status = 'status' in options ? options.status : 200\n this.ok = this.status >= 200 && this.status < 300\n this.statusText = 'statusText' in options ? options.statusText : 'OK'\n this.headers = new Headers(options.headers)\n this.url = options.url || ''\n this._initBody(bodyInit)\n }\n\n Body.call(Response.prototype)\n\n Response.prototype.clone = function() {\n return new Response(this._bodyInit, {\n status: this.status,\n statusText: this.statusText,\n headers: new Headers(this.headers),\n url: this.url\n })\n }\n\n Response.error = function() {\n var response = new Response(null, {status: 0, statusText: ''})\n response.type = 'error'\n return response\n }\n\n var redirectStatuses = [301, 302, 303, 307, 308]\n\n Response.redirect = function(url, status) {\n if (redirectStatuses.indexOf(status) === -1) {\n throw new RangeError('Invalid status code')\n }\n\n return new Response(null, {status: status, headers: {location: url}})\n }\n\n self.Headers = Headers\n self.Request = Request\n self.Response = Response\n\n self.fetch = function(input, init) {\n return new Promise(function(resolve, reject) {\n var request = new Request(input, init)\n var xhr = new XMLHttpRequest()\n\n xhr.onload = function() {\n var options = {\n status: xhr.status,\n statusText: xhr.statusText,\n headers: parseHeaders(xhr.getAllResponseHeaders() || '')\n }\n options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL')\n var body = 'response' in xhr ? xhr.response : xhr.responseText\n resolve(new Response(body, options))\n }\n\n xhr.onerror = function() {\n reject(new TypeError('Network request failed'))\n }\n\n xhr.ontimeout = function() {\n reject(new TypeError('Network request failed'))\n }\n\n xhr.open(request.method, request.url, true)\n\n if (request.credentials === 'include') {\n xhr.withCredentials = true\n }\n\n if ('responseType' in xhr && support.blob) {\n xhr.responseType = 'blob'\n }\n\n request.headers.forEach(function(value, name) {\n xhr.setRequestHeader(name, value)\n })\n\n xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit)\n })\n }\n self.fetch.polyfill = true\n})(typeof self !== 'undefined' ? self : this);\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./~/whatwg-fetch/fetch.js\n// module id = 2\n// module chunks = 0","/* global fetch */\n\nimport {unpromiser, retry, warn} from './utils'\nimport {LocalStorage, MemoryStorage} from './auth_storage'\nimport {AppToken as AppTokenV2, getAppToken as getAppTokenV2} from './auth_v2'\nimport * as auth from './auth_v3'\nimport * as data from './data'\nimport * as mango from './mango'\nimport * as files from './files'\nimport * as offline from './offline'\nimport * as settings from './settings'\nimport * as relations from './relations'\n\nconst {\n AppToken: AppTokenV3,\n AccessToken: AccessTokenV3,\n Client: ClientV3\n} = auth\n\nconst AuthNone = 0\nconst AuthRunning = 1\nconst AuthError = 2\nconst AuthOK = 3\n\nconst defaultClientParams = {\n softwareID: 'github.com/cozy/cozy-client-js'\n}\n\nconst dataProto = {\n create: data.create,\n find: data.find,\n update: data.update,\n delete: data._delete,\n updateAttributes: data.updateAttributes,\n changesFeed: data.changesFeed,\n defineIndex: mango.defineIndex,\n query: mango.query,\n addReferencedFiles: relations.addReferencedFiles,\n listReferencedFiles: relations.listReferencedFiles,\n destroy: function (...args) {\n warn('destroy is deprecated, use cozy.data.delete instead.')\n return data._delete(...args)\n }\n}\n\nconst authProto = {\n client: auth.client,\n registerClient: auth.registerClient,\n updateClient: auth.updateClient,\n unregisterClient: auth.unregisterClient,\n getClient: auth.getClient,\n getAuthCodeURL: auth.getAuthCodeURL,\n getAccessToken: auth.getAccessToken,\n refreshToken: auth.refreshToken\n}\n\nconst filesProto = {\n create: files.create,\n createDirectory: files.createDirectory,\n updateById: files.updateById,\n updateAttributesById: files.updateAttributesById,\n updateAttributesByPath: files.updateAttributesByPath,\n trashById: files.trashById,\n statById: files.statById,\n statByPath: files.statByPath,\n downloadById: files.downloadById,\n downloadByPath: files.downloadByPath,\n getDowloadLink: files.getDowloadLink,\n getArchiveLink: files.getArchiveLink,\n listTrash: files.listTrash,\n clearTrash: files.clearTrash,\n restoreById: files.restoreById,\n destroyById: files.destroyById\n}\n\nconst offlineProto = {\n init: offline.init,\n getDoctypes: offline.getDoctypes,\n // database\n hasDatabase: offline.hasDatabase,\n getDatabase: offline.getDatabase,\n createDatabase: offline.createDatabase,\n destroyDatabase: offline.destroyDatabase,\n destroyAllDatabase: offline.destroyAllDatabase,\n // replication\n hasReplication: offline.hasReplication,\n replicateFromCozy: offline.replicateFromCozy,\n stopReplication: offline.stopReplication,\n stopAllReplication: offline.stopAllReplication,\n // repeated replication\n hasRepeatedReplication: offline.hasRepeatedReplication,\n startRepeatedReplication: offline.startRepeatedReplication,\n stopRepeatedReplication: offline.stopRepeatedReplication,\n stopAllRepeatedReplication: offline.stopAllRepeatedReplication\n}\n\nconst settingsProto = {\n diskUsage: settings.diskUsage,\n changePassphrase: settings.changePassphrase,\n getInstance: settings.getInstance,\n updateInstance: settings.updateInstance,\n getClients: settings.getClients,\n deleteClientById: settings.deleteClientById\n}\n\nclass Client {\n constructor (options) {\n this.data = {}\n this.files = {}\n this.offline = {}\n this.settings = {}\n this.auth = {\n Client: ClientV3,\n AccessToken: AccessTokenV3,\n AppToken: AppTokenV3,\n AppTokenV2: AppTokenV2,\n LocalStorage: LocalStorage,\n MemoryStorage: MemoryStorage\n }\n this._inited = false\n if (options) {\n this.init(options)\n }\n }\n\n init (options = {}) {\n this._inited = true\n this._oauth = false // is oauth activated or not\n this._token = null // application token\n this._authstate = AuthNone\n this._authcreds = null\n this._storage = null\n this._version = null\n this._offline = null\n\n const token = options.token\n const oauth = options.oauth\n if (token && oauth) {\n throw new Error('Cannot specify an application token with a oauth activated')\n }\n\n if (token) {\n this._token = new AppTokenV3({ token })\n } else if (oauth) {\n this._oauth = true\n this._storage = oauth.storage\n this._clientParams = Object.assign({}, defaultClientParams, oauth.clientParams)\n this._onRegistered = oauth.onRegistered || nopOnRegistered\n }\n\n let url = options.cozyURL || ''\n while (url[url.length - 1] === '/') {\n url = url.slice(0, -1)\n }\n\n this._url = url\n\n const disablePromises = !!options.disablePromises\n addToProto(this, this.data, dataProto, disablePromises)\n addToProto(this, this.auth, authProto, disablePromises)\n addToProto(this, this.files, filesProto, disablePromises)\n addToProto(this, this.offline, offlineProto, disablePromises)\n addToProto(this, this.settings, settingsProto, disablePromises)\n\n if (options.offline) {\n this.offline.init(options.offline)\n }\n }\n\n authorize () {\n const state = this._authstate\n if (state === AuthOK || state === AuthRunning) {\n return this._authcreds\n }\n\n this._authstate = AuthRunning\n this._authcreds = this.isV2().then((isV2) => {\n if (isV2 && this._oauth) {\n throw new Error('OAuth is not supported on the V2 stack')\n }\n if (this._oauth) {\n return auth.oauthFlow(\n this,\n this._storage,\n this._clientParams,\n this._onRegistered\n )\n }\n // we expect to be on a client side application running in a browser\n // with cookie-based authentication.\n if (isV2) {\n return getAppTokenV2()\n } else if (this._token) {\n return Promise.resolve({client: null, token: this._token})\n } else {\n throw new Error('Missing application token')\n }\n })\n\n this._authcreds.then(\n () => { this._authstate = AuthOK },\n () => { this._authstate = AuthError })\n\n return this._authcreds\n }\n\n saveCredentials (client, token) {\n const creds = {client, token}\n if (!this._storage || this._authstate === AuthRunning) {\n return Promise.resolve(creds)\n }\n this._storage.save(auth.CredsKey, creds)\n this._authcreds = Promise.resolve(creds)\n return this._authcreds\n }\n\n fullpath (path) {\n return this.isV2().then((isV2) => {\n const pathprefix = isV2 ? '/ds-api' : ''\n return this._url + pathprefix + path\n })\n }\n\n isV2 () {\n if (!this._version) {\n this._version = retry(() => fetch(`${this._url}/status/`), 3)()\n .then((res) => {\n if (!res.ok) {\n throw new Error('Could not fetch cozy status')\n } else {\n return res.json()\n }\n })\n .then((status) => status.datasystem !== undefined)\n }\n return this._version\n }\n}\n\nfunction nopOnRegistered () {\n throw new Error('Missing onRegistered callback')\n}\n\nfunction protoify (context, fn) {\n return function prototyped (...args) {\n return fn(context, ...args)\n }\n}\n\nfunction addToProto (ctx, obj, proto, disablePromises) {\n for (const attr in proto) {\n let fn = protoify(ctx, proto[attr])\n if (disablePromises) {\n fn = unpromiser(fn)\n }\n obj[attr] = fn\n }\n}\n\nmodule.exports = new Client()\nObject.assign(module.exports, {Client, LocalStorage, MemoryStorage})\n\n\n\n// WEBPACK FOOTER //\n// ./src/index.js","const FuzzFactor = 0.3\n\nexport function unpromiser (fn) {\n return function (...args) {\n const value = fn.apply(this, args)\n if (!isPromise(value)) {\n return value\n }\n const l = args.length\n if (l === 0 || typeof args[l - 1] !== 'function') {\n return\n }\n const cb = args[l - 1]\n value.then(\n (res) => cb(null, res),\n (err) => cb(err, null)\n )\n return\n }\n}\n\nexport function isPromise (value) {\n return !!value && typeof value.then === 'function'\n}\n\nexport function sleep (time, args) {\n return new Promise((resolve) => {\n setTimeout(resolve, time, args)\n })\n}\n\nexport function retry (fn, count, delay = 300) {\n return function doTry (...args) {\n return fn(...args).catch((err) => {\n if (--count < 0) {\n throw err\n }\n return sleep(getBackedoffDelay(delay, count))\n .then(() => doTry(...args))\n })\n }\n}\n\nexport function getFuzzedDelay (retryDelay) {\n const fuzzingFactor = ((Math.random() * 2) - 1) * FuzzFactor\n return retryDelay * (1.0 + fuzzingFactor)\n}\n\nexport function getBackedoffDelay (retryDelay, retryCount = 1) {\n return getFuzzedDelay(retryDelay * Math.pow(2, retryCount - 1))\n}\n\nexport function createPath (cozy, isV2, doctype, id = '', query = null) {\n let route = '/data/'\n if (!isV2) {\n route += `${encodeURIComponent(doctype)}/`\n }\n if (id !== '') {\n route += encodeURIComponent(id)\n }\n const q = encodeQuery(query)\n if (q !== '') {\n route += '?' + q\n }\n return route\n}\n\nexport function encodeQuery (query) {\n if (!query) {\n return ''\n }\n let q = ''\n for (const qname in query) {\n if (q !== '') {\n q += '&'\n }\n q += `${encodeURIComponent(qname)}=${encodeURIComponent(query[qname])}`\n }\n return q\n}\n\nexport function decodeQuery (url) {\n let queryIndex = url.indexOf('?')\n if (queryIndex < 0) {\n queryIndex = url.length\n }\n const queries = {}\n let fragIndex = url.indexOf('#')\n if (fragIndex < 0) {\n fragIndex = url.length\n }\n if (fragIndex < queryIndex) {\n return queries\n }\n const queryStr = url.slice(queryIndex + 1, fragIndex)\n if (queryStr === '') {\n return queries\n }\n const parts = queryStr.split('&')\n for (let i = 0; i < parts.length; i++) {\n let pair = parts[i].split('=')\n if (pair.length === 0 || pair[0] === '') {\n continue\n }\n const qname = decodeURIComponent(pair[0])\n if (queries.hasOwnProperty(qname)) {\n continue\n }\n if (pair.length === 1) {\n queries[qname] = true\n } else if (pair.length === 2) {\n queries[qname] = decodeURIComponent(pair[1])\n } else {\n throw new Error('Malformed URL')\n }\n }\n return queries\n}\n\nconst warned = []\nexport function warn (text) {\n if (warned.indexOf(text) === -1) {\n warned.push(text)\n console.warn('cozy-client-js', text)\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils.js","export class LocalStorage {\n constructor (storage, prefix) {\n if (!storage && typeof window !== 'undefined') {\n storage = window.localStorage\n }\n this.storage = storage\n this.prefix = prefix || 'cozy:oauth:'\n }\n\n save (key, value) {\n return new Promise(resolve => {\n this.storage.setItem(this.prefix + key, JSON.stringify(value))\n resolve(value)\n })\n }\n\n load (key) {\n return new Promise(resolve => {\n const item = this.storage.getItem(this.prefix + key)\n if (!item) {\n resolve()\n } else {\n resolve(JSON.parse(item))\n }\n })\n }\n\n delete (key) {\n return new Promise(resolve => resolve(\n this.storage.removeItem(this.prefix + key)))\n }\n\n clear () {\n return new Promise(resolve => {\n const storage = this.storage\n for (let i = 0; i < storage.length; i++) {\n const key = storage.key(i)\n if (key.indexOf(this.prefix) === 0) {\n storage.removeItem(key)\n }\n }\n resolve()\n })\n }\n}\n\nexport class MemoryStorage {\n constructor () {\n this.hash = Object.create(null)\n }\n\n save (key, value) {\n this.hash[key] = value\n return Promise.resolve(value)\n }\n\n load (key) {\n return Promise.resolve(this.hash[key])\n }\n\n delete (key) {\n const deleted = delete this.hash[key]\n return Promise.resolve(deleted)\n }\n\n clear () {\n this.hash = Object.create(null)\n return Promise.resolve()\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/auth_storage.js","/* global btoa */\nconst V2TOKEN_ABORT_TIMEOUT = 3000\n\nexport function getAppToken () {\n return new Promise(function (resolve, reject) {\n if (typeof window === 'undefined') {\n return reject(new Error('getV2Token should be used in browser'))\n } else if (!window.parent) {\n return reject(new Error('getV2Token should be used in iframe'))\n } else if (!window.parent.postMessage) {\n return reject(new Error('getV2Token should be used in modern browser'))\n }\n const origin = window.location.origin\n const intent = {action: 'getToken'}\n let timeout = null\n const receiver = function (event) {\n let token\n try {\n token = new AppToken({\n appName: event.data.appName,\n token: event.data.token\n })\n } catch (e) {\n reject(e)\n return\n }\n window.removeEventListener('message', receiver)\n clearTimeout(timeout)\n resolve({ client: null, token })\n }\n window.addEventListener('message', receiver, false)\n window.parent.postMessage(intent, origin)\n timeout = setTimeout(() => {\n reject(new Error('No response from parent iframe after 3s'))\n }, V2TOKEN_ABORT_TIMEOUT)\n })\n}\n\nexport class AppToken {\n constructor (opts) {\n this.appName = opts.appName || ''\n this.token = opts.token || ''\n }\n\n toAuthHeader () {\n return 'Basic ' + btoa(`${this.appName}:${this.token}`)\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/auth_v2.js","/* global btoa */\nimport {encodeQuery, decodeQuery} from './utils'\nimport {cozyFetchJSON, FetchError} from './fetch'\n\nconst StateSize = 16\n\nexport const CredsKey = 'creds'\nexport const StateKey = 'state'\n\nexport class Client {\n constructor (opts) {\n this.clientID = opts.clientID || opts.client_id || ''\n this.clientSecret = opts.clientSecret || opts.client_secret || ''\n this.registrationAccessToken = opts.registrationAccessToken || opts.registration_access_token || ''\n\n if (opts.redirect_uris) {\n this.redirectURI = opts.redirect_uris[0] || ''\n } else {\n this.redirectURI = opts.redirectURI || ''\n }\n\n this.softwareID = opts.softwareID || opts.software_id || ''\n this.softwareVersion = opts.softwareVersion || opts.software_version || ''\n this.clientName = opts.clientName || opts.client_name || ''\n this.clientKind = opts.clientKind || opts.client_kind || ''\n this.clientURI = opts.clientURI || opts.client_uri || ''\n\n this.logoURI = opts.logoURI || opts.logo_uri || ''\n this.policyURI = opts.policyURI || opts.policy_uri || ''\n\n if (!this.registrationAccessToken) {\n if (this.redirectURI === '') {\n throw new Error('Missing redirectURI field')\n }\n if (this.softwareID === '') {\n throw new Error('Missing softwareID field')\n }\n if (this.clientName === '') {\n throw new Error('Missing clientName field')\n }\n }\n }\n\n isRegistered () {\n return this.clientID !== ''\n }\n\n toRegisterJSON () {\n return {\n redirect_uris: [this.redirectURI],\n software_id: this.softwareID,\n software_version: this.softwareVersion,\n client_name: this.clientName,\n client_kind: this.clientKind,\n client_uri: this.clientURI,\n logo_uri: this.logoURI,\n policy_uri: this.policyURI\n }\n }\n\n toAuthHeader () {\n return 'Bearer ' + this.registrationAccessToken\n }\n}\n\nexport class AccessToken {\n constructor (opts) {\n this.tokenType = opts.tokenType || opts.token_type\n this.accessToken = opts.accessToken || opts.access_token\n this.refreshToken = opts.refreshToken || opts.refresh_token\n this.scope = opts.scope\n }\n\n toAuthHeader () {\n return 'Bearer ' + this.accessToken\n }\n\n toBasicAuth () {\n return `user:${this.accessToken}@`\n }\n}\n\nexport class AppToken {\n constructor (opts) {\n this.token = opts.token || ''\n }\n\n toAuthHeader () {\n return 'Bearer ' + this.token\n }\n\n toBasicAuth () {\n return `user:${this.token}@`\n }\n}\n\nexport function client (cozy, clientParams) {\n if (!clientParams) {\n clientParams = cozy._clientParams\n }\n if (clientParams instanceof Client) {\n return clientParams\n }\n return new Client(clientParams)\n}\n\nexport function registerClient (cozy, clientParams) {\n const cli = client(cozy, clientParams)\n if (cli.isRegistered()) {\n return Promise.reject(new Error('Client already registered'))\n }\n return cozyFetchJSON(cozy, 'POST', '/auth/register', cli.toRegisterJSON(), {\n disableAuth: true\n })\n .then((data) => new Client(data))\n}\n\nexport function updateClient (cozy, clientParams, resetSecret = false) {\n const cli = client(cozy, clientParams)\n if (!cli.isRegistered()) {\n return Promise.reject(new Error('Client not registered'))\n }\n let data = cli.toRegisterJSON()\n data.client_id = cli.clientID\n if (resetSecret) data.client_secret = cli.clientSecret\n\n return cozyFetchJSON(cozy, 'PUT', `/auth/register/${cli.clientID}`, data, {\n manualAuthCredentials: {\n token: cli\n }\n }).then((data) => createClient(data, cli))\n}\n\nexport function unregisterClient (cozy, clientParams) {\n const cli = client(cozy, clientParams)\n if (!cli.isRegistered()) {\n return Promise.reject(new Error('Client not registered'))\n }\n return cozyFetchJSON(cozy, 'DELETE', `/auth/register/${cli.clientID}`, null, {\n manualAuthCredentials: {\n token: cli\n }\n })\n}\n\n// getClient will retrive the registered client informations from the server.\nexport function getClient (cozy, clientParams) {\n const cli = client(cozy, clientParams)\n if (!cli.isRegistered()) {\n return Promise.reject(new Error('Client not registered'))\n }\n return cozyFetchJSON(cozy, 'GET', `/auth/register/${cli.clientID}`, null, {\n manualAuthCredentials: {\n token: cli\n }\n })\n .then((data) => createClient(data, cli))\n}\n\n// createClient returns a new Client instance given on object containing the\n// data of the client, from the API, and an old instance of the client.\nfunction createClient (data, oldClient) {\n const newClient = new Client(data)\n // we need to keep track of the registrationAccessToken since it is send\n // only on registration. The GET /auth/register/:client-id endpoint does\n // not return this token.\n const shouldPassRegistration = (\n !!oldClient &&\n oldClient.registrationAccessToken !== '' &&\n newClient.registrationAccessToken === ''\n )\n if (shouldPassRegistration) {\n newClient.registrationAccessToken = oldClient.registrationAccessToken\n }\n return newClient\n}\n\n// getAuthCodeURL returns a pair {authURL,state} given a registered client. The\n// state should be stored in order to be checked against on the user validation\n// phase.\nexport function getAuthCodeURL (cozy, client, scopes = []) {\n if (!(client instanceof Client)) {\n client = new Client(client)\n }\n if (!client.isRegistered()) {\n throw new Error('Client not registered')\n }\n const state = generateRandomState()\n const query = {\n 'client_id': client.clientID,\n 'redirect_uri': client.redirectURI,\n 'state': state,\n 'response_type': 'code',\n 'scope': scopes.join(' ')\n }\n return {\n url: cozy._url + `/auth/authorize?${encodeQuery(query)}`,\n state: state\n }\n}\n\n// getAccessToken perform a request on the access_token entrypoint with the\n// authorization_code grant type in order to generate a new access token for a\n// newly registered client.\n//\n// This method extracts the access code and state from the given URL. By\n// default it uses window.location.href. Also, it checks the given state with\n// the one specified in the URL query parameter to prevent CSRF attacks.\nexport function getAccessToken (cozy, client, state, pageURL = '') {\n if (!state) {\n return Promise.reject(new Error('Missing state value'))\n }\n const grantQueries = getGrantCodeFromPageURL(pageURL)\n if (grantQueries === null) {\n return Promise.reject(new Error('Missing states from current URL'))\n }\n if (state !== grantQueries.state) {\n return Promise.reject(new Error('Given state does not match url query state'))\n }\n return retrieveToken(cozy, client, null, {\n 'grant_type': 'authorization_code',\n 'code': grantQueries.code\n })\n}\n\n// refreshToken perform a request on the access_token entrypoint with the\n// refresh_token grant type in order to refresh the given token.\nexport function refreshToken (cozy, client, token) {\n return retrieveToken(cozy, client, token, {\n 'grant_type': 'refresh_token',\n 'refresh_token': token.refreshToken\n })\n}\n\n// oauthFlow performs the stateful registration and access granting of an OAuth\n// client.\nexport function oauthFlow (cozy, storage, clientParams, onRegistered) {\n let tryCount = 0\n\n function clearAndRetry (err) {\n if (tryCount++ > 0) {\n throw err\n }\n return storage.clear().then(() =>\n oauthFlow(cozy, storage, clientParams, onRegistered))\n }\n\n function registerNewClient () {\n return storage.clear()\n .then(() => registerClient(cozy, clientParams))\n .then((client) => {\n const {url, state} = getAuthCodeURL(cozy, client, clientParams.scopes)\n return storage.save(StateKey, {client, url, state})\n })\n }\n\n return Promise.all([\n storage.load(CredsKey),\n storage.load(StateKey)\n ])\n .then(([credentials, storedState]) => {\n // If credentials are cached we re-fetch the registered client with the\n // said token. Fetching the client, if the token is outdated we should try\n // the token is refreshed.\n if (credentials) {\n let oldClient, token\n try {\n oldClient = new Client(credentials.client)\n token = new AccessToken(credentials.token)\n } catch (err) {\n // bad cache, we should clear and retry the process\n return clearAndRetry(err)\n }\n return getClient(cozy, oldClient)\n .then((client) => ({client, token}))\n .catch((err) => {\n // If we fall into an error while fetching the client (because of a\n // bad connectivity for instance), we do not bail the whole process\n // since the client should be able to continue with the persisted\n // client and token.\n //\n // If it is an explicit Unauthorized error though, we bail, clear th\n // cache and retry.\n if (FetchError.isUnauthorized(err) || FetchError.isNotFound(err)) {\n throw new Error('Client has been revoked')\n }\n return { client: oldClient, token }\n })\n }\n\n // Otherwise register a new client if necessary (ie. no client is stored)\n // and call the onRegistered callback to wait for the user to grant the\n // access. Finally fetches to access token on success.\n let statePromise\n if (!storedState) {\n statePromise = registerNewClient()\n } else {\n statePromise = Promise.resolve(storedState)\n }\n\n let client, state, token\n return statePromise\n .then((data) => {\n client = data.client\n state = data.state\n return Promise.resolve(onRegistered(client, data.url))\n })\n .then((pageURL) => getAccessToken(cozy, client, state, pageURL))\n .then((t) => { token = t })\n .then(() => storage.delete(StateKey))\n .then(() => ({client, token}))\n })\n .then(\n (creds) => storage.save(CredsKey, creds),\n (err) => {\n if (FetchError.isUnauthorized(err)) {\n return clearAndRetry(err)\n } else {\n throw err\n }\n })\n}\n\n// retrieveToken perform a request on the access_token entrypoint in order to\n// fetch a token.\nfunction retrieveToken (cozy, client, token, query) {\n if (!(client instanceof Client)) {\n client = new Client(client)\n }\n if (!client.isRegistered()) {\n return Promise.reject(new Error('Client not registered'))\n }\n const body = encodeQuery(Object.assign({}, query, {\n 'client_id': client.clientID,\n 'client_secret': client.clientSecret\n }))\n return cozyFetchJSON(cozy, 'POST', '/auth/access_token', body, {\n disableAuth: (token === null),\n manualAuthCredentials: { client, token },\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' }\n })\n .then((data) => {\n data.refreshToken = data.refreshToken || query.refresh_token\n return new AccessToken(data)\n })\n}\n\n// getGrantCodeFromPageURL extract the state and access_code query parameters\n// from the given url\nfunction getGrantCodeFromPageURL (pageURL = '') {\n if (pageURL === '' && typeof window !== 'undefined') {\n pageURL = window.location.href\n }\n const queries = decodeQuery(pageURL)\n if (!queries.hasOwnProperty('state')) {\n return null\n }\n return {\n state: queries['state'],\n code: queries['access_code']\n }\n}\n\n// generateRandomState will try to generate a 128bits random value from a secure\n// pseudo random generator. It will fallback on Math.random if it cannot find\n// such generator.\nfunction generateRandomState () {\n let buffer\n if (typeof window !== 'undefined' &&\n typeof window.crypto !== 'undefined' &&\n typeof window.crypto.getRandomValues === 'function') {\n buffer = new Uint8Array(StateSize)\n window.crypto.getRandomValues(buffer)\n } else {\n try {\n buffer = require('crypto').randomBytes(StateSize)\n } catch (e) {}\n }\n if (!buffer) {\n buffer = new Array(StateSize)\n for (let i = 0; i < buffer.length; i++) {\n buffer[i] = Math.floor((Math.random() * 255))\n }\n }\n return btoa(String.fromCharCode.apply(null, buffer))\n .replace(/=+$/, '')\n .replace(/\\//g, '_')\n .replace(/\\+/g, '-')\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/auth_v3.js","/* global fetch */\nimport {refreshToken, AccessToken} from './auth_v3'\nimport {retry} from './utils'\nimport jsonapi from './jsonapi'\n\nexport function cozyFetch (cozy, path, options = {}) {\n return cozy.fullpath(path).then((fullpath) => {\n let resp\n if (options.disableAuth) {\n resp = fetch(fullpath, options)\n } else if (options.manualAuthCredentials) {\n resp = cozyFetchWithAuth(cozy, fullpath, options, options.manualAuthCredentials)\n } else {\n resp = cozy.authorize().then((credentials) =>\n cozyFetchWithAuth(cozy, fullpath, options, credentials))\n }\n return resp.then(handleResponse)\n })\n}\n\nfunction cozyFetchWithAuth (cozy, fullpath, options, credentials) {\n if (credentials) {\n options.headers = options.headers || {}\n options.headers['Authorization'] = credentials.token.toAuthHeader()\n }\n\n // the option credentials:include tells fetch to include the cookies in the\n // request even for cross-origin requests\n options.credentials = 'include'\n\n return Promise.all([\n cozy.isV2(),\n fetch(fullpath, options)\n ]).then(([isV2, res]) => {\n if (res.status !== 401 || isV2 || !credentials) {\n return res\n }\n // we try to refresh the token only for OAuth, ie, the client defined\n // and the token is an instance of AccessToken.\n const { client, token } = credentials\n if (!client || !(token instanceof AccessToken)) {\n return res\n }\n return retry(() => refreshToken(cozy, client, token), 3)()\n .then((newToken) => cozy.saveCredentials(client, newToken))\n .then((credentials) => cozyFetchWithAuth(cozy, fullpath, options, credentials))\n })\n}\n\nexport function cozyFetchJSON (cozy, method, path, body, options = {}) {\n options.method = method\n\n const headers = options.headers = options.headers || {}\n\n headers['Accept'] = 'application/json'\n\n if (method !== 'GET' && method !== 'HEAD' && body !== undefined) {\n if (headers['Content-Type']) {\n options.body = body\n } else {\n headers['Content-Type'] = 'application/json'\n options.body = JSON.stringify(body)\n }\n }\n\n return cozyFetch(cozy, path, options)\n .then(handleJSONResponse)\n}\n\nfunction handleResponse (res) {\n if (res.ok) {\n return res\n }\n let data\n const contentType = res.headers.get('content-type')\n if (contentType && contentType.indexOf('json') >= 0) {\n data = res.json()\n } else {\n data = res.text()\n }\n return data.then(err => {\n throw new FetchError(res, err)\n })\n}\n\nfunction handleJSONResponse (res) {\n const contentType = res.headers.get('content-type')\n if (!contentType || contentType.indexOf('json') < 0) {\n return res.text((data) => {\n throw new FetchError(res, new Error('Response is not JSON: ' + data))\n })\n }\n\n const json = res.json()\n if (contentType.indexOf('application/vnd.api+json') === 0) {\n return json.then(jsonapi)\n } else {\n return json\n }\n}\n\nexport class FetchError extends Error {\n constructor (res, reason) {\n super()\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor)\n }\n // XXX We have to hardcode this because babel doesn't play nice when extending Error\n this.name = 'FetchError'\n this.response = res\n this.url = res.url\n this.status = res.status\n this.reason = reason\n }\n}\n\nFetchError.isUnauthorized = function (err) {\n // XXX We can't use err instanceof FetchError because of the caveats of babel\n return err.name === 'FetchError' && err.status === 401\n}\n\nFetchError.isNotFound = function (err) {\n // XXX We can't use err instanceof FetchError because of the caveats of babel\n return err.name === 'FetchError' && err.status === 404\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/fetch.js","function indexKey (doc) {\n return doc.type + '/' + doc.id\n}\n\nfunction findByRef (resources, ref) {\n return resources[indexKey(ref)]\n}\n\nfunction handleResource (rawResource, resources, links) {\n let resource = {\n _id: rawResource.id,\n _type: rawResource.type,\n _rev: (rawResource.meta && rawResource.meta.rev),\n links: Object.assign({}, rawResource.links, links),\n attributes: rawResource.attributes,\n relations: (name) => {\n let rels = rawResource.relationships[name]\n if (rels === undefined || rels.data === undefined) return undefined\n if (rels.data === null) return null\n if (!Array.isArray(rels.data)) return findByRef(resources, rels.data)\n return rels.data.map(ref => findByRef(resources, ref))\n }\n }\n\n resources[indexKey(rawResource)] = resource\n\n return resource\n}\n\nfunction handleTopLevel (doc, resources = {}) {\n // build an index of included resource by Type & ID\n const included = doc.included\n\n if (Array.isArray(included)) {\n included.forEach((r) => handleResource(r, resources, doc.links))\n }\n\n if (Array.isArray(doc.data)) {\n return doc.data.map((r) => handleResource(r, resources, doc.links))\n } else {\n return handleResource(doc.data, resources, doc.links)\n }\n}\n\nexport default handleTopLevel\n\n\n\n// WEBPACK FOOTER //\n// ./src/jsonapi.js","import {createPath} from './utils'\nimport {normalizeDoctype} from './doctypes'\nimport {cozyFetchJSON} from './fetch'\n\nconst NOREV = 'stack-v2-no-rev'\n\nexport function create (cozy, doctype, attributes) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n if (isV2) {\n attributes.docType = doctype\n }\n const path = createPath(cozy, isV2, doctype)\n return cozyFetchJSON(cozy, 'POST', path, attributes).then((resp) => {\n if (isV2) {\n return find(cozy, doctype, resp._id)\n } else {\n return resp.data\n }\n })\n })\n}\n\nexport function find (cozy, doctype, id) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n\n if (!id) {\n return Promise.reject(new Error('Missing id parameter'))\n }\n\n const path = createPath(cozy, isV2, doctype, id)\n return cozyFetchJSON(cozy, 'GET', path).then((resp) => {\n if (isV2) {\n return Object.assign(resp, {_rev: NOREV})\n } else {\n return resp\n }\n })\n })\n}\n\nexport function changesFeed (cozy, doctype, options) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n const path = createPath(cozy, isV2, doctype, '_changes', options)\n return cozyFetchJSON(cozy, 'GET', path)\n })\n}\n\nexport function update (cozy, doctype, doc, changes) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n const {_id, _rev} = doc\n\n if (!_id) {\n return Promise.reject(new Error('Missing _id field in passed document'))\n }\n\n if (!isV2 && !_rev) {\n return Promise.reject(new Error('Missing _rev field in passed document'))\n }\n\n if (isV2) {\n changes = Object.assign({ _id }, changes)\n } else {\n changes = Object.assign({ _id, _rev }, changes)\n }\n\n const path = createPath(cozy, isV2, doctype, _id)\n return cozyFetchJSON(cozy, 'PUT', path, changes).then((resp) => {\n if (isV2) {\n return find(cozy, doctype, _id)\n } else {\n return resp.data\n }\n })\n })\n}\n\nexport function updateAttributes (cozy, doctype, _id, changes, tries = 3) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n return find(cozy, doctype, _id)\n .then((doc) => {\n return update(cozy, doctype, doc, Object.assign({ _id }, doc, changes))\n })\n .catch((err) => {\n if (tries > 0) {\n return updateAttributes(cozy, doctype, _id, changes, tries - 1)\n } else {\n throw err\n }\n })\n })\n}\n\nexport function _delete (cozy, doctype, doc) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n const {_id, _rev} = doc\n\n if (!_id) {\n return Promise.reject(new Error('Missing _id field in passed document'))\n }\n\n if (!isV2 && !_rev) {\n return Promise.reject(new Error('Missing _rev field in passed document'))\n }\n\n const query = isV2 ? null : { rev: _rev }\n const path = createPath(cozy, isV2, doctype, _id, query)\n return cozyFetchJSON(cozy, 'DELETE', path).then((resp) => {\n if (isV2) {\n return {id: _id, rev: NOREV}\n } else {\n return resp\n }\n })\n })\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/data.js","import {warn} from './utils'\n\nexport const DOCTYPE_FILES = 'io.cozy.files'\n\nconst KNOWN_DOCTYPES = {\n 'files': DOCTYPE_FILES,\n 'folder': DOCTYPE_FILES,\n 'contact': 'io.cozy.contacts',\n 'event': 'io.cozy.events',\n 'track': 'io.cozy.labs.music.track',\n 'playlist': 'io.cozy.labs.music.playlist'\n}\n\nconst REVERSE_KNOWN = {}\nObject.keys(KNOWN_DOCTYPES).forEach(k => {\n REVERSE_KNOWN[KNOWN_DOCTYPES[k]] = k\n})\n\nexport function normalizeDoctype (cozy, isV2, doctype) {\n let isQualified = doctype.indexOf('.') !== -1\n if (isV2 && isQualified) {\n let known = REVERSE_KNOWN[doctype]\n if (known) return known\n return doctype.replace(/\\./g, '-')\n }\n if (!isV2 && !isQualified) {\n let known = KNOWN_DOCTYPES[doctype]\n if (known) {\n warn('you are using a non-qualified doctype ' + doctype + ' assumed to be ' + known)\n return known\n }\n throw new Error('Doctype ' + doctype + ' should be qualified.')\n }\n return doctype\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/doctypes.js","import {warn, createPath} from './utils'\nimport {normalizeDoctype} from './doctypes'\nimport {cozyFetchJSON} from './fetch'\n\nexport function defineIndex (cozy, doctype, fields) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n if (!Array.isArray(fields) || fields.length === 0) {\n throw new Error('defineIndex fields should be a non-empty array')\n }\n if (isV2) {\n return defineIndexV2(cozy, doctype, fields)\n } else {\n return defineIndexV3(cozy, doctype, fields)\n }\n })\n}\n\nexport function query (cozy, indexRef, options) {\n return cozy.isV2().then((isV2) => {\n if (!indexRef) {\n throw new Error('query should be passed the indexRef')\n }\n if (isV2) {\n return queryV2(cozy, indexRef, options)\n } else {\n return queryV3(cozy, indexRef, options)\n }\n })\n}\n\n// Internals\n\nconst VALUEOPERATORS = ['$eq', '$gt', '$gte', '$lt', '$lte']\nconst LOGICOPERATORS = ['$or', '$and', '$not']\n\n/* eslint-disable */\nconst MAP_TEMPLATE = (function (doc) {\n if (doc.docType.toLowerCase() === 'DOCTYPEPLACEHOLDER'){\n emit(FIELDSPLACEHOLDER, doc)\n }\n}).toString().replace(/ /g, '').replace(/\\n/g, '')\nconst COUCHDB_INFINITY = {\"\\uFFFF\": \"\\uFFFF\"}\nconst COUCHDB_LOWEST = null\n/* eslint-enable */\n\n// defineIndexV2 is equivalent to defineIndex but only works for V2.\n// It transforms the index fields into a map reduce view.\nfunction defineIndexV2 (cozy, doctype, fields) {\n let indexName = 'by' + fields.map(capitalize).join('')\n let indexDefinition = { map: makeMapFunction(doctype, fields), reduce: '_count' }\n let path = `/request/${doctype}/${indexName}/`\n return cozyFetchJSON(cozy, 'PUT', path, indexDefinition)\n .then(() => ({ doctype: doctype, type: 'mapreduce', name: indexName, fields: fields }))\n}\n\n// defineIndexV2 is equivalent to defineIndex but only works for V2.\n// It transforms the index fields into a map reduce view.\nfunction defineIndexV3 (cozy, doctype, fields) {\n let path = createPath(cozy, false, doctype, '_index')\n let indexDefinition = {'index': {fields}}\n return cozyFetchJSON(cozy, 'POST', path, indexDefinition)\n .then((response) => ({ doctype: doctype, type: 'mango', name: response.id, fields: fields }))\n}\n\n// queryV2 is equivalent to query but only works for V2.\n// It transforms the query into a _views call using makeMapReduceQuery\nfunction queryV2 (cozy, indexRef, options) {\n if (indexRef.type !== 'mapreduce') {\n throw new Error('query indexRef should be the return value of defineIndexV2')\n }\n if (options.fields) {\n warn('query fields will be ignored on v2')\n }\n\n let path = `/request/${indexRef.doctype}/${indexRef.name}/`\n let opts = makeMapReduceQuery(indexRef, options)\n return cozyFetchJSON(cozy, 'POST', path, opts)\n .then((response) => response.map(r => r.value))\n}\n\n// queryV3 is equivalent to query but only works for V3\nfunction queryV3 (cozy, indexRef, options) {\n if (indexRef.type !== 'mango') {\n throw new Error('indexRef should be the return value of defineIndexV3')\n }\n\n let opts = {\n use_index: indexRef.name,\n fields: options.fields,\n selector: options.selector,\n limit: options.limit,\n since: options.since\n }\n\n if (options.descending) {\n opts.sort = indexRef.fields.map(f => ({ [f]: 'desc' }))\n }\n\n let path = createPath(cozy, false, indexRef.doctype, '_find')\n return cozyFetchJSON(cozy, 'POST', path, opts)\n .then((response) => response.docs)\n}\n\n// misc\nfunction capitalize (name) {\n return name.charAt(0).toUpperCase() + name.slice(1)\n}\n\nfunction makeMapFunction (doctype, fields) {\n fields = '[' + fields.map(name => 'doc.' + name).join(',') + ']'\n\n return MAP_TEMPLATE.replace('DOCTYPEPLACEHOLDER', doctype.toLowerCase())\n .replace('FIELDSPLACEHOLDER', fields)\n}\n\n// parseSelector takes a mango selector and returns it as an array of filter\n// a filter is [path, operator, value] array\n// a path is an array of field names\n// This function is only exported so it can be unit tested.\n// Example :\n// parseSelector({\"test\":{\"deep\": {\"$gt\": 3}}})\n// [[['test', 'deep'], '$gt', 3 ]]\nexport function parseSelector (selector, path = [], operator = '$eq') {\n if ((typeof selector) !== 'object') {\n return [[path, operator, selector]]\n }\n\n let keys = Object.keys(selector)\n if (keys.length === 0) {\n throw new Error('empty selector')\n } else {\n return keys.reduce(function (acc, k) {\n if (LOGICOPERATORS.indexOf(k) !== -1) {\n throw new Error('cozy-client-js does not support mango logic ops')\n } else if (VALUEOPERATORS.indexOf(k) !== -1) {\n return acc.concat(parseSelector(selector[k], path, k))\n } else {\n return acc.concat(parseSelector(selector[k], path.concat(k), '$eq'))\n }\n }, [])\n }\n}\n\n// normalizeSelector takes a mango selector and returns it as an object\n// normalized.\n// This function is only exported so it can be unit tested.\n// Example :\n// parseSelector({\"test\":{\"deep\": {\"$gt\": 3}}})\n// {\"test.deep\": {\"$gt\": 3}}\nexport function normalizeSelector (selector) {\n var filters = parseSelector(selector)\n return filters.reduce(function (acc, filter) {\n let [path, op, value] = filter\n let field = path.join('.')\n acc[field] = acc[field] || {}\n acc[field][op] = value\n return acc\n }, {})\n}\n\n// applySelector takes the normalized selector for the current field\n// and append the proper values to opts.startkey, opts.endkey\nfunction applySelector (selector, opts) {\n let value = selector['$eq']\n let lower = COUCHDB_LOWEST\n let upper = COUCHDB_INFINITY\n let inclusiveEnd\n\n if (value) {\n opts.startkey.push(value)\n opts.endkey.push(value)\n return false\n }\n\n value = selector['$gt']\n if (value) {\n throw new Error('operator $gt (strict greater than) not supported')\n }\n\n value = selector['$gte']\n if (value) {\n lower = value\n }\n\n value = selector['$lte']\n if (value) {\n upper = value\n inclusiveEnd = true\n }\n\n value = selector['$lt']\n if (value) {\n upper = value\n inclusiveEnd = false\n }\n\n opts.startkey.push(lower)\n opts.endkey.push(upper)\n if (inclusiveEnd !== undefined) opts.inclusive_end = inclusiveEnd\n return true\n}\n\n// makeMapReduceQuery takes a mango query and generate _views call parameters\n// to obtain same results depending on fields in the passed indexRef.\nexport function makeMapReduceQuery (indexRef, query) {\n let mrquery = {\n startkey: [],\n endkey: [],\n reduce: false\n }\n let firstFreeValueField = null\n let normalizedSelector = normalizeSelector(query.selector)\n\n indexRef.fields.forEach(function (field) {\n let selector = normalizedSelector[field]\n\n if (selector && firstFreeValueField != null) {\n throw new Error('Selector on field ' + field + ', but not on ' + firstFreeValueField + ' which is higher in index fields.')\n } else if (selector) {\n selector.used = true\n let isFreeValue = applySelector(selector, mrquery)\n if (isFreeValue) firstFreeValueField = field\n } else if (firstFreeValueField == null) {\n firstFreeValueField = field\n mrquery.endkey.push(COUCHDB_INFINITY)\n }\n })\n\n Object.keys(normalizedSelector).forEach(function (field) {\n if (!normalizedSelector[field].used) {\n throw new Error('Cant apply selector on ' + field + ', it is not in index')\n }\n })\n\n if (query.descending) {\n mrquery = {\n descending: true,\n reduce: false,\n startkey: mrquery.endkey,\n endkey: mrquery.startkey,\n inclusive_end: mrquery.inclusive_end\n }\n }\n\n return mrquery\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/mango.js","/* global Blob, File */\nimport {cozyFetch, cozyFetchJSON} from './fetch'\nimport jsonapi from './jsonapi'\nimport { DOCTYPE_FILES } from './doctypes'\n\nconst contentTypeOctetStream = 'application/octet-stream'\n\nfunction doUpload (cozy, data, method, path, options) {\n if (!data) {\n throw new Error('missing data argument')\n }\n\n // transform any ArrayBufferView to ArrayBuffer\n if (data.buffer && data.buffer instanceof ArrayBuffer) {\n data = data.buffer\n }\n\n const isBuffer = (typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer)\n const isFile = (typeof File !== 'undefined' && data instanceof File)\n const isBlob = (typeof Blob !== 'undefined' && data instanceof Blob)\n const isStream = (data.readable === true && typeof data.pipe === 'function')\n const isString = (typeof data === 'string')\n\n if (!isBuffer && !isFile && !isBlob && !isStream && !isString) {\n throw new Error('invalid data type')\n }\n\n let {contentType, checksum, lastModifiedDate, ifMatch} = options || {}\n if (!contentType) {\n if (isBuffer) {\n contentType = contentTypeOctetStream\n } else if (isFile) {\n contentType = data.type || contentTypeOctetStream\n if (!lastModifiedDate) {\n lastModifiedDate = data.lastModifiedDate\n }\n } else if (isBlob) {\n contentType = contentTypeOctetStream\n } else if (isStream) {\n contentType = contentTypeOctetStream\n } else if (typeof data === 'string') {\n contentType = 'text/plain'\n }\n }\n\n if (lastModifiedDate && typeof lastModifiedDate === 'string') {\n lastModifiedDate = new Date(lastModifiedDate)\n }\n\n return cozyFetch(cozy, path, {\n method: method,\n headers: {\n 'Content-Type': contentType,\n 'Content-MD5': checksum || '',\n 'Date': lastModifiedDate ? lastModifiedDate.toGMTString() : '',\n 'If-Match': ifMatch || ''\n },\n body: data\n })\n .then((res) => {\n const json = res.json()\n if (!res.ok) {\n return json.then(err => { throw err })\n } else {\n return json.then(jsonapi)\n }\n })\n}\n\nexport function create (cozy, data, options) {\n let {name, dirID, executable} = options || {}\n\n // handle case where data is a file and contains the name\n if (!name && typeof data.name === 'string') {\n name = data.name\n }\n\n if (typeof name !== 'string' || name === '') {\n throw new Error('missing name argument')\n }\n\n if (executable === undefined) {\n executable = false\n }\n\n const path = `/files/${encodeURIComponent(dirID || '')}`\n const query = `?Name=${encodeURIComponent(name)}&Type=file&Executable=${executable}`\n return doUpload(cozy, data, 'POST', `${path}${query}`, options)\n}\n\nexport function createDirectory (cozy, options) {\n let {name, dirID, lastModifiedDate} = options || {}\n\n if (typeof name !== 'string' || name === '') {\n throw new Error('missing name argument')\n }\n\n if (lastModifiedDate && typeof lastModifiedDate === 'string') {\n lastModifiedDate = new Date(lastModifiedDate)\n }\n\n const path = `/files/${encodeURIComponent(dirID || '')}`\n const query = `?Name=${encodeURIComponent(name)}&Type=directory`\n return cozyFetchJSON(cozy, 'POST', `${path}${query}`, undefined, {\n headers: {\n 'Date': lastModifiedDate ? lastModifiedDate.toGMTString() : ''\n }\n })\n}\n\nexport function updateById (cozy, id, data, options) {\n return doUpload(cozy, data, 'PUT', `/files/${encodeURIComponent(id)}`, options)\n}\n\nfunction doUpdateAttributes (cozy, attrs, path, options) {\n if (!attrs || typeof attrs !== 'object') {\n throw new Error('missing attrs argument')\n }\n\n const {ifMatch} = options || {}\n const body = { data: { attributes: attrs } }\n return cozyFetchJSON(cozy, 'PATCH', path, body, {\n headers: {\n 'If-Match': ifMatch || ''\n }\n })\n}\n\nexport function updateAttributesById (cozy, id, attrs, options) {\n return doUpdateAttributes(cozy, attrs,\n `/files/${encodeURIComponent(id)}`, options)\n}\n\nexport function updateAttributesByPath (cozy, path, attrs, options) {\n return doUpdateAttributes(cozy, attrs,\n `/files/metadata?Path=${encodeURIComponent(path)}`, options)\n}\n\nexport function trashById (cozy, id) {\n if (typeof id !== 'string' || id === '') {\n throw new Error('missing id argument')\n }\n return cozyFetchJSON(cozy, 'DELETE', `/files/${encodeURIComponent(id)}`)\n}\n\nexport function statById (cozy, id, offline = true) {\n if (offline && cozy.offline.hasDatabase(DOCTYPE_FILES)) {\n let db = cozy.offline.getDatabase(DOCTYPE_FILES)\n return Promise.all([\n db.get(id),\n db.find({selector: {'dir_id': id}})\n ]).then(([doc, children]) => {\n children = children.docs.map(doc => {\n return addIsDir(toJsonApi(cozy, doc))\n })\n return addIsDir(toJsonApi(cozy, doc, children))\n })\n }\n return cozyFetchJSON(cozy, 'GET', `/files/${encodeURIComponent(id)}`)\n .then(addIsDir)\n}\n\nexport function statByPath (cozy, path) {\n return cozyFetchJSON(cozy, 'GET', `/files/metadata?Path=${encodeURIComponent(path)}`)\n .then(addIsDir)\n}\n\nexport function downloadById (cozy, id) {\n return cozyFetch(cozy, `/files/download/${encodeURIComponent(id)}`)\n}\n\nexport function downloadByPath (cozy, path) {\n return cozyFetch(cozy, `/files/download?Path=${encodeURIComponent(path)}`)\n}\n\nfunction extractResponseLinkRelated (res) {\n let href = res.links && res.links.related\n if (!href) throw new Error('No related link in server response')\n return href\n}\n\nexport function getDowloadLink (cozy, path) {\n return cozyFetchJSON(cozy, 'POST', `/files/downloads?Path=${encodeURIComponent(path)}`)\n .then(extractResponseLinkRelated)\n}\n\nexport function getArchiveLink (cozy, paths, name = 'files') {\n const archive = {\n type: 'io.cozy.archives',\n attributes: {\n name: name,\n files: paths\n }\n }\n return cozyFetchJSON(cozy, 'POST', `/files/archive`, {data: archive})\n .then(extractResponseLinkRelated)\n}\n\nexport function listTrash (cozy) {\n return cozyFetchJSON(cozy, 'GET', `/files/trash`)\n}\n\nexport function clearTrash (cozy) {\n return cozyFetchJSON(cozy, 'DELETE', `/files/trash`)\n}\n\nexport function restoreById (cozy, id) {\n return cozyFetchJSON(cozy, 'POST', `/files/trash/${encodeURIComponent(id)}`)\n}\n\nexport function destroyById (cozy, id) {\n return cozyFetchJSON(cozy, 'DELETE', `/files/trash/${encodeURIComponent(id)}`)\n}\n\nfunction addIsDir (obj) {\n obj.isDir = obj.attributes.type === 'directory'\n return obj\n}\n\nfunction toJsonApi (cozy, doc, contents = []) {\n let clone = JSON.parse(JSON.stringify(doc))\n delete clone._id\n delete clone._rev\n return {\n _id: doc._id,\n _rev: doc._rev,\n _type: DOCTYPE_FILES,\n attributes: clone,\n relations: (name) => {\n if (name === 'contents') {\n return contents\n }\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/files.js","import PouchDB from 'pouchdb'\nimport pouchdbFind from 'pouchdb-find'\nimport { DOCTYPE_FILES } from './doctypes'\n\nlet pluginLoaded = false\n\n/*\n For each doctype we have some parameters:\n cozy._offline[doctype] = {\n database: pouchdb database\n replication: the pouchdb replication\n replicationPromise: promise of replication\n interval: repeated replication interval\n }\n*/\n\nexport function init (cozy, { options = {}, doctypes = [] }) {\n for (let doctype of doctypes) {\n createDatabase(cozy, doctype, options)\n }\n}\n\n// helper\n\nfunction getInfo (cozy, doctype) {\n cozy._offline = cozy._offline || []\n cozy._offline[doctype] = cozy._offline[doctype] || {}\n return cozy._offline[doctype]\n}\n\nexport function getDoctypes (cozy) {\n cozy._offline = cozy._offline || []\n return Object.keys(cozy._offline)\n}\n\n//\n// DATABASE\n//\n\nexport function hasDatabase (cozy, doctype) {\n return getDatabase(cozy, doctype) !== undefined\n}\n\nexport function getDatabase (cozy, doctype) {\n return getInfo(cozy, doctype).database\n}\n\nexport function setDatabase (cozy, doctype, database) {\n cozy._offline[doctype].database = database\n return getDatabase(cozy, doctype)\n}\n\nfunction errorDatabase (doctype) {\n return new Error(`You should add this doctype: ${doctype} to offline.`)\n}\n\nexport function createDatabase (cozy, doctype, options = {}) {\n if (!pluginLoaded) {\n PouchDB.plugin(pouchdbFind)\n pluginLoaded = true\n }\n\n if (hasDatabase(cozy, doctype)) {\n return Promise.resolve(getDatabase(cozy, doctype))\n }\n\n setDatabase(cozy, doctype, new PouchDB(doctype, options))\n return createIndexes(cozy, doctype).then(() => getDatabase(cozy, doctype))\n}\n\nexport function destroyDatabase (cozy, doctype) {\n if (!hasDatabase(cozy, doctype)) {\n return Promise.resolve(false)\n }\n\n return stopRepeatedReplication(cozy, doctype)\n .then(() => stopReplication(cozy, doctype))\n .then(() => getDatabase(cozy, doctype).destroy())\n .then(response => {\n setDatabase(cozy, doctype, undefined)\n return response\n })\n}\n\nexport function destroyAllDatabase (cozy) {\n const doctypes = getDoctypes(cozy)\n const destroy = (doctype) => destroyDatabase(cozy, doctype)\n return Promise.all(doctypes.map(destroy))\n}\n\nfunction createIndexes (cozy, doctype) {\n if (doctype === DOCTYPE_FILES) {\n return getDatabase(cozy, doctype).createIndex({index: {fields: ['dir_id']}})\n }\n return Promise.resolve()\n}\n\n//\n// REPLICATION\n//\n\nexport function hasReplication (cozy, doctype) {\n return getReplication(cozy, doctype) !== undefined\n}\n\nfunction getReplication (cozy, doctype) {\n return getInfo(cozy, doctype).replication\n}\n\nfunction setReplication (cozy, doctype, replication) {\n cozy._offline[doctype].replication = replication\n return getReplication(cozy, doctype)\n}\n\nfunction getReplicationUrl (cozy, doctype) {\n return cozy.authorize()\n .then(credentials => {\n const basic = credentials.token.toBasicAuth()\n return (cozy._url + '/data/' + doctype).replace('//', `//${basic}`)\n })\n}\n\nfunction getReplicationPromise (cozy, doctype) {\n return getInfo(cozy, doctype).replicationPromise\n}\n\nfunction setReplicationPromise (cozy, doctype, promise) {\n cozy._offline[doctype].replicationPromise = promise\n return getReplicationPromise(cozy, doctype)\n}\n\nexport function replicateFromCozy (cozy, doctype, options = {}) {\n return setReplicationPromise(cozy, doctype, new Promise((resolve, reject) => {\n if (!hasDatabase(cozy, doctype)) {\n return reject(errorDatabase(doctype))\n }\n if (options.live === true) {\n return reject(new Error('You can\\'t use `live` option with Cozy couchdb.'))\n }\n\n getReplicationUrl(cozy, doctype)\n .then(url => setReplication(cozy, doctype,\n getDatabase(cozy, doctype).replicate.from(url, options).on('complete', (info) => {\n setReplication(cozy, doctype, undefined)\n resolve(info)\n }).on('error', (err) => {\n console.warn(`ReplicateFromCozy '${doctype}' Error:`)\n console.warn(err)\n setReplication(cozy, doctype, undefined)\n reject(err)\n })\n ))\n }))\n}\n\nexport function stopReplication (cozy, doctype) {\n if (!getDatabase(cozy, doctype) || !hasReplication(cozy, doctype)) {\n return Promise.resolve()\n }\n\n return new Promise(resolve => {\n try {\n getReplicationPromise(cozy, doctype).then(() => {\n resolve()\n })\n getReplication(cozy, doctype).cancel()\n // replication is set to undefined by complete replication\n } catch (e) {\n resolve()\n }\n })\n}\n\nexport function stopAllReplication (cozy) {\n const doctypes = getDoctypes(cozy)\n const stop = (doctype) => stopReplication(cozy, doctype)\n return Promise.all(doctypes.map(stop))\n}\n\n//\n// REPEATED REPLICATION\n//\n\nfunction getRepeatedReplication (cozy, doctype) {\n return getInfo(cozy, doctype).interval\n}\n\nfunction setRepeatedReplication (cozy, doctype, interval) {\n cozy._offline[doctype].interval = interval\n}\n\nexport function hasRepeatedReplication (cozy, doctype) {\n return getRepeatedReplication(cozy, doctype) !== undefined\n}\n\nexport function startRepeatedReplication (cozy, doctype, timer, options = {}) {\n // TODO: add timer limitation for not flooding Gozy\n if (!hasDatabase(cozy, doctype)) {\n return Promise.reject(errorDatabase(doctype))\n }\n\n if (hasRepeatedReplication(cozy, doctype)) {\n return getRepeatedReplication(cozy, doctype)\n }\n\n return setRepeatedReplication(cozy, doctype, setInterval(() => {\n if (!hasReplication(cozy, doctype)) {\n replicateFromCozy(cozy, doctype, options)\n // TODO: add replicationToCozy\n }\n }, timer * 1000))\n}\n\nexport function stopRepeatedReplication (cozy, doctype) {\n if (hasRepeatedReplication(cozy, doctype)) {\n clearInterval(getRepeatedReplication(cozy, doctype))\n setRepeatedReplication(cozy, doctype, undefined)\n }\n if (hasReplication(cozy, doctype)) {\n return stopReplication(cozy, doctype)\n }\n\n return Promise.resolve()\n}\n\nexport function stopAllRepeatedReplication (cozy) {\n const doctypes = getDoctypes(cozy)\n const stop = (doctype) => stopRepeatedReplication(cozy, doctype)\n return Promise.all(doctypes.map(stop))\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/offline.js","module.exports = __WEBPACK_EXTERNAL_MODULE_15__;\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"pouchdb\"\n// module id = 15\n// module chunks = 0","module.exports = __WEBPACK_EXTERNAL_MODULE_16__;\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"pouchdb-find\"\n// module id = 16\n// module chunks = 0","import {cozyFetchJSON} from './fetch'\n\nexport function diskUsage (cozy) {\n return cozyFetchJSON(cozy, 'GET', `/settings/disk-usage`)\n}\n\nexport function changePassphrase (cozy, currentPassPhrase, newPassPhrase) {\n return cozyFetchJSON(cozy, 'PUT', `/settings/passphrase`, {\n current_passphrase: currentPassPhrase,\n new_passphrase: newPassPhrase\n })\n}\n\nexport function getInstance (cozy) {\n return cozyFetchJSON(cozy, 'GET', `/settings/instance`)\n}\n\nexport function updateInstance (cozy, instance) {\n return cozyFetchJSON(cozy, 'PUT', `/settings/instance`, instance)\n}\n\nexport function getClients (cozy) {\n return cozyFetchJSON(cozy, 'GET', `/settings/clients`)\n}\n\nexport function deleteClientById (cozy, id) {\n return cozyFetchJSON(cozy, 'DELETE', `/settings/clients/${id}`)\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/settings.js","import {cozyFetchJSON} from './fetch'\nimport { DOCTYPE_FILES } from './doctypes'\n\nexport function addReferencedFiles (cozy, doc, ids) {\n if (!doc) throw new Error('missing doc argument')\n if (!Array.isArray(ids)) ids = [ids]\n\n const refs = ids.map((id) => ({type: DOCTYPE_FILES, id: id}))\n\n return cozyFetchJSON(cozy, 'POST', makeReferencesPath(doc), {data: refs})\n}\n\nexport function listReferencedFiles (cozy, doc) {\n if (!doc) throw new Error('missing doc argument')\n return cozyFetchJSON(cozy, 'GET', makeReferencesPath(doc))\n .then((files) => files.map((file) => file._id))\n}\n\nfunction makeReferencesPath (doc) {\n const type = encodeURIComponent(doc._type)\n const id = encodeURIComponent(doc._id)\n return `/data/${type}/${id}/relationships/references`\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/relations.js"],"sourceRoot":""} \ No newline at end of file diff --git a/dist/cozy-client.node.js b/dist/cozy-client.node.js index c34e6bee..3ce9fe29 100644 --- a/dist/cozy-client.node.js +++ b/dist/cozy-client.node.js @@ -165,18 +165,21 @@ init: offline.init, getDoctypes: offline.getDoctypes, // database - createDatabase: offline.createDatabase, hasDatabase: offline.hasDatabase, getDatabase: offline.getDatabase, + createDatabase: offline.createDatabase, destroyDatabase: offline.destroyDatabase, destroyAllDatabase: offline.destroyAllDatabase, // replication + hasReplication: offline.hasReplication, replicateFromCozy: offline.replicateFromCozy, - hasSync: offline.hasSync, - startAllSync: offline.startAllSync, - startSync: offline.startSync, - stopAllSync: offline.stopAllSync, - stopSync: offline.stopSync + stopReplication: offline.stopReplication, + stopAllReplication: offline.stopAllReplication, + // repeated replication + hasRepeatedReplication: offline.hasRepeatedReplication, + startRepeatedReplication: offline.startRepeatedReplication, + stopRepeatedReplication: offline.stopRepeatedReplication, + stopAllRepeatedReplication: offline.stopAllRepeatedReplication }; var settingsProto = { @@ -2209,23 +2212,22 @@ Object.defineProperty(exports, "__esModule", { value: true }); - - var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - exports.init = init; - exports.createDatabase = createDatabase; + exports.getDoctypes = getDoctypes; exports.hasDatabase = hasDatabase; exports.getDatabase = getDatabase; + exports.setDatabase = setDatabase; + exports.createDatabase = createDatabase; exports.destroyDatabase = destroyDatabase; exports.destroyAllDatabase = destroyAllDatabase; - exports.getDoctypes = getDoctypes; - exports.startAllSync = startAllSync; - exports.stopAllSync = stopAllSync; - exports.startSync = startSync; - exports.hasSync = hasSync; - exports.stopSync = stopSync; + exports.hasReplication = hasReplication; exports.replicateFromCozy = replicateFromCozy; - exports.replicateFromCozyWithAuth = replicateFromCozyWithAuth; + exports.stopReplication = stopReplication; + exports.stopAllReplication = stopAllReplication; + exports.hasRepeatedReplication = hasRepeatedReplication; + exports.startRepeatedReplication = startRepeatedReplication; + exports.stopRepeatedReplication = stopRepeatedReplication; + exports.stopAllRepeatedReplication = stopAllRepeatedReplication; var _pouchdb = __webpack_require__(16); @@ -2241,12 +2243,21 @@ var pluginLoaded = false; + /* + For each doctype we have some parameters: + cozy._offline[doctype] = { + database: pouchdb database + replication: the pouchdb replication + replicationPromise: promise of replication + interval: repeated replication interval + } + */ + function init(cozy, _ref) { var _ref$options = _ref.options, options = _ref$options === undefined ? {} : _ref$options, _ref$doctypes = _ref.doctypes, - doctypes = _ref$doctypes === undefined ? [] : _ref$doctypes, - timer = _ref.timer; + doctypes = _ref$doctypes === undefined ? [] : _ref$doctypes; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; @@ -2271,163 +2282,228 @@ } } } - - if (timer !== undefined) { - startAllSync(cozy, timer); - } } - function createDatabase(cozy, doctype) { - var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - var timer = arguments[3]; + // helper - if (!pluginLoaded) { - _pouchdb2.default.plugin(_pouchdbFind2.default); - pluginLoaded = true; - } + function getInfo(cozy, doctype) { cozy._offline = cozy._offline || []; cozy._offline[doctype] = cozy._offline[doctype] || {}; - var offline = cozy._offline[doctype]; - if (offline && offline.database) { - return offline.database; - } - offline.database = new _pouchdb2.default(doctype, options); - offline.timer = timer; - offline.autoSync = null; - if (timer !== undefined) { - startSync(cozy, doctype, timer); - } - createIndexes(cozy, offline.database, doctype); - return offline.database; + return cozy._offline[doctype]; + } + + function getDoctypes(cozy) { + cozy._offline = cozy._offline || []; + return Object.keys(cozy._offline); } + // + // DATABASE + // + function hasDatabase(cozy, doctype) { - return cozy._offline !== null && doctype in cozy._offline && cozy._offline[doctype].database !== undefined; + return getDatabase(cozy, doctype) !== undefined; } function getDatabase(cozy, doctype) { + return getInfo(cozy, doctype).database; + } + + function setDatabase(cozy, doctype, database) { + cozy._offline[doctype].database = database; + return getDatabase(cozy, doctype); + } + + function errorDatabase(doctype) { + return new Error('You should add this doctype: ' + doctype + ' to offline.'); + } + + function createDatabase(cozy, doctype) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + if (!pluginLoaded) { + _pouchdb2.default.plugin(_pouchdbFind2.default); + pluginLoaded = true; + } + if (hasDatabase(cozy, doctype)) { - return cozy._offline[doctype].database; + return Promise.resolve(getDatabase(cozy, doctype)); } - return; + + setDatabase(cozy, doctype, new _pouchdb2.default(doctype, options)); + return createIndexes(cozy, doctype).then(function () { + return getDatabase(cozy, doctype); + }); } function destroyDatabase(cozy, doctype) { - if (hasDatabase(cozy, doctype)) { - stopSync(cozy, doctype); - getDatabase(cozy, doctype).destroy(); - delete getDatabase(cozy, doctype); + if (!hasDatabase(cozy, doctype)) { + return Promise.resolve(false); } + + return stopRepeatedReplication(cozy, doctype).then(function () { + return stopReplication(cozy, doctype); + }).then(function () { + return getDatabase(cozy, doctype).destroy(); + }).then(function (response) { + setDatabase(cozy, doctype, undefined); + return response; + }); } function destroyAllDatabase(cozy) { - getDoctypes(cozy).forEach(function (doctype) { + var doctypes = getDoctypes(cozy); + var destroy = function destroy(doctype) { return destroyDatabase(cozy, doctype); - }); + }; + return Promise.all(doctypes.map(destroy)); } - function getDoctypes(cozy) { - if (cozy._offline === null) { - return []; + function createIndexes(cozy, doctype) { + if (doctype === _doctypes.DOCTYPE_FILES) { + return getDatabase(cozy, doctype).createIndex({ index: { fields: ['dir_id'] } }); } - return Object.keys(cozy._offline); + return Promise.resolve(); } // - // SYNC + // REPLICATION // - function startAllSync(cozy, timer) { - if (timer) { - var doctypes = getDoctypes(cozy); - doctypes.forEach(function (doctype) { - startSync(cozy, doctype, timer); - }); - } + function hasReplication(cozy, doctype) { + return getReplication(cozy, doctype) !== undefined; } - function stopAllSync(cozy) { - var doctypes = getDoctypes(cozy); - doctypes.forEach(function (doctype) { - stopSync(cozy, doctype); - }); + function getReplication(cozy, doctype) { + return getInfo(cozy, doctype).replication; } - function startSync(cozy, doctype, timer) { - // TODO: add timer limitation for not flooding Gozy - if (hasDatabase(cozy, doctype)) { - var _ret = function () { - if (hasSync(cozy, doctype)) { - if (timer === cozy._offline[doctype].timer) { - return { - v: void 0 - }; - } - stopSync(cozy, doctype); - } - var offline = cozy._offline[doctype]; - offline.timer = timer; - offline.autoSync = setInterval(function () { - if (offline.replicate === undefined) { - replicateFromCozy(cozy, doctype); - // TODO: add replicationToCozy - } - }, timer * 1000); - }(); + function setReplication(cozy, doctype, replication) { + cozy._offline[doctype].replication = replication; + return getReplication(cozy, doctype); + } - if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; - } + function getReplicationUrl(cozy, doctype) { + return cozy.authorize().then(function (credentials) { + var basic = credentials.token.toBasicAuth(); + return (cozy._url + '/data/' + doctype).replace('//', '//' + basic); + }); } - function hasSync(cozy, doctype) { - return cozy._offline !== null && doctype in cozy._offline && cozy._offline[doctype].autoSync !== null; + function getReplicationPromise(cozy, doctype) { + return getInfo(cozy, doctype).replicationPromise; } - function stopSync(cozy, doctype) { - if (hasSync(cozy, doctype)) { - var offline = cozy._offline[doctype]; - clearInterval(offline.autoSync); - delete offline.autoSync; - if (offline.replication) { - offline.replication.cancel(); - } - } + function setReplicationPromise(cozy, doctype, promise) { + cozy._offline[doctype].replicationPromise = promise; + return getReplicationPromise(cozy, doctype); } function replicateFromCozy(cozy, doctype) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - if (hasDatabase(cozy, doctype)) { - if (options.live === true) { - return Promise.reject(new Error('You can\'t use `live` option with Cozy couchdb.')); + return setReplicationPromise(cozy, doctype, new Promise(function (resolve, reject) { + if (!hasDatabase(cozy, doctype)) { + return reject(errorDatabase(doctype)); } - if (options.manualAuthCredentials) { - return Promise.resolve(replicateFromCozyWithAuth(cozy, doctype, options, options.manualAuthCredentials)); - } else { - return cozy.authorize().then(function (credentials) { - return replicateFromCozyWithAuth(cozy, doctype, options, credentials); + if (options.live === true) { + return reject(new Error('You can\'t use `live` option with Cozy couchdb.')); + } + + getReplicationUrl(cozy, doctype).then(function (url) { + return setReplication(cozy, doctype, getDatabase(cozy, doctype).replicate.from(url, options).on('complete', function (info) { + setReplication(cozy, doctype, undefined); + resolve(info); + }).on('error', function (err) { + console.warn('ReplicateFromCozy \'' + doctype + '\' Error:'); + console.warn(err); + setReplication(cozy, doctype, undefined); + reject(err); + })); + }); + })); + } + + function stopReplication(cozy, doctype) { + if (!getDatabase(cozy, doctype) || !hasReplication(cozy, doctype)) { + return Promise.resolve(); + } + + return new Promise(function (resolve) { + try { + getReplicationPromise(cozy, doctype).then(function () { + resolve(); }); + getReplication(cozy, doctype).cancel(); + // replication is set to undefined by complete replication + } catch (e) { + resolve(); } - } else { - return Promise.reject(new Error('You should add this doctype: ' + doctype + ' to offline.')); - } + }); } - function replicateFromCozyWithAuth(cozy, doctype, options, credentials) { - var basic = credentials.token.toBasicAuth(); - var url = (cozy._url + '/data/' + doctype).replace('//', '//' + basic); - var db = getDatabase(cozy, doctype); - var offline = cozy._offline[doctype]; - offline.replication = db.replicate.from(url, options).on('complete', function () { - offline.replication = undefined; - }); - return offline.replication; + function stopAllReplication(cozy) { + var doctypes = getDoctypes(cozy); + var stop = function stop(doctype) { + return stopReplication(cozy, doctype); + }; + return Promise.all(doctypes.map(stop)); } - function createIndexes(cozy, db, doctype) { - if (doctype === _doctypes.DOCTYPE_FILES) { - db.createIndex({ index: { fields: ['dir_id'] } }); + // + // REPEATED REPLICATION + // + + function getRepeatedReplication(cozy, doctype) { + return getInfo(cozy, doctype).interval; + } + + function setRepeatedReplication(cozy, doctype, interval) { + cozy._offline[doctype].interval = interval; + } + + function hasRepeatedReplication(cozy, doctype) { + return getRepeatedReplication(cozy, doctype) !== undefined; + } + + function startRepeatedReplication(cozy, doctype, timer) { + var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + + // TODO: add timer limitation for not flooding Gozy + if (!hasDatabase(cozy, doctype)) { + return Promise.reject(errorDatabase(doctype)); + } + + if (hasRepeatedReplication(cozy, doctype)) { + return getRepeatedReplication(cozy, doctype); + } + + return setRepeatedReplication(cozy, doctype, setInterval(function () { + if (!hasReplication(cozy, doctype)) { + replicateFromCozy(cozy, doctype, options); + // TODO: add replicationToCozy + } + }, timer * 1000)); + } + + function stopRepeatedReplication(cozy, doctype) { + if (hasRepeatedReplication(cozy, doctype)) { + clearInterval(getRepeatedReplication(cozy, doctype)); + setRepeatedReplication(cozy, doctype, undefined); + } + if (hasReplication(cozy, doctype)) { + return stopReplication(cozy, doctype); } + + return Promise.resolve(); + } + + function stopAllRepeatedReplication(cozy) { + var doctypes = getDoctypes(cozy); + var stop = function stop(doctype) { + return stopRepeatedReplication(cozy, doctype); + }; + return Promise.all(doctypes.map(stop)); } /***/ }, diff --git a/dist/cozy-client.node.js.map b/dist/cozy-client.node.js.map index 868080f2..86798983 100644 --- a/dist/cozy-client.node.js.map +++ b/dist/cozy-client.node.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack:///webpack/bootstrap caf7b1559e5630948f31","webpack:///external \"isomorphic-fetch\"","webpack:///./src/index.js","webpack:///./src/utils.js","webpack:///./src/auth_storage.js","webpack:///./src/auth_v2.js","webpack:///external \"btoa\"","webpack:///./src/auth_v3.js","webpack:///./src/fetch.js","webpack:///./src/jsonapi.js","webpack:///external \"crypto\"","webpack:///./src/data.js","webpack:///./src/doctypes.js","webpack:///./src/mango.js","webpack:///./src/files.js","webpack:///./src/offline.js","webpack:///external \"pouchdb\"","webpack:///external \"pouchdb-find\"","webpack:///./src/settings.js","webpack:///./src/relations.js"],"names":["auth","data","mango","files","offline","settings","relations","AppTokenV3","AppToken","AccessTokenV3","AccessToken","ClientV3","Client","AuthNone","AuthRunning","AuthError","AuthOK","defaultClientParams","softwareID","dataProto","create","find","update","delete","_delete","updateAttributes","changesFeed","defineIndex","query","addReferencedFiles","listReferencedFiles","destroy","authProto","client","registerClient","updateClient","unregisterClient","getClient","getAuthCodeURL","getAccessToken","refreshToken","filesProto","createDirectory","updateById","updateAttributesById","updateAttributesByPath","trashById","statById","statByPath","downloadById","downloadByPath","getDowloadLink","getArchiveLink","listTrash","clearTrash","restoreById","destroyById","offlineProto","init","getDoctypes","createDatabase","hasDatabase","getDatabase","destroyDatabase","destroyAllDatabase","replicateFromCozy","hasSync","startAllSync","startSync","stopAllSync","stopSync","settingsProto","diskUsage","changePassphrase","getInstance","updateInstance","getClients","deleteClientById","options","AppTokenV2","LocalStorage","MemoryStorage","_inited","_oauth","_token","_authstate","_authcreds","_storage","_version","_offline","token","oauth","Error","storage","_clientParams","Object","assign","clientParams","_onRegistered","onRegistered","nopOnRegistered","url","cozyURL","length","slice","_url","disablePromises","addToProto","state","isV2","then","oauthFlow","Promise","resolve","creds","save","CredsKey","path","pathprefix","fetch","res","ok","json","status","datasystem","undefined","protoify","context","fn","prototyped","args","ctx","obj","proto","attr","module","exports","unpromiser","isPromise","sleep","retry","getFuzzedDelay","getBackedoffDelay","createPath","encodeQuery","decodeQuery","warn","FuzzFactor","value","apply","l","cb","err","time","setTimeout","count","delay","doTry","catch","retryDelay","fuzzingFactor","Math","random","retryCount","pow","cozy","doctype","id","route","encodeURIComponent","q","qname","queryIndex","indexOf","queries","fragIndex","queryStr","parts","split","i","pair","decodeURIComponent","hasOwnProperty","warned","text","push","console","prefix","window","localStorage","key","setItem","JSON","stringify","item","getItem","parse","removeItem","hash","deleted","getAppToken","V2TOKEN_ABORT_TIMEOUT","reject","parent","postMessage","origin","location","intent","action","timeout","receiver","event","appName","e","removeEventListener","clearTimeout","addEventListener","opts","btoa","StateSize","StateKey","clientID","client_id","clientSecret","client_secret","registrationAccessToken","registration_access_token","redirect_uris","redirectURI","software_id","softwareVersion","software_version","clientName","client_name","clientKind","client_kind","clientURI","client_uri","logoURI","logo_uri","policyURI","policy_uri","tokenType","token_type","accessToken","access_token","refresh_token","scope","cli","isRegistered","toRegisterJSON","disableAuth","resetSecret","manualAuthCredentials","createClient","oldClient","newClient","shouldPassRegistration","scopes","generateRandomState","join","pageURL","grantQueries","getGrantCodeFromPageURL","retrieveToken","code","tryCount","clearAndRetry","clear","registerNewClient","all","load","credentials","storedState","isUnauthorized","isNotFound","statePromise","t","body","headers","href","buffer","crypto","getRandomValues","Uint8Array","require","randomBytes","Array","floor","String","fromCharCode","replace","cozyFetch","cozyFetchJSON","fullpath","resp","cozyFetchWithAuth","authorize","handleResponse","toAuthHeader","newToken","saveCredentials","method","handleJSONResponse","contentType","get","FetchError","reason","captureStackTrace","constructor","name","response","indexKey","doc","type","findByRef","resources","ref","handleResource","rawResource","links","resource","_id","_type","_rev","meta","rev","attributes","rels","relationships","isArray","map","handleTopLevel","included","forEach","r","NOREV","docType","changes","tries","normalizeDoctype","DOCTYPE_FILES","KNOWN_DOCTYPES","REVERSE_KNOWN","keys","k","isQualified","known","parseSelector","normalizeSelector","makeMapReduceQuery","fields","defineIndexV2","defineIndexV3","indexRef","queryV2","queryV3","VALUEOPERATORS","LOGICOPERATORS","MAP_TEMPLATE","toLowerCase","emit","FIELDSPLACEHOLDER","toString","COUCHDB_INFINITY","COUCHDB_LOWEST","indexName","capitalize","indexDefinition","makeMapFunction","reduce","use_index","selector","limit","since","descending","sort","f","docs","charAt","toUpperCase","operator","acc","concat","filters","filter","op","field","applySelector","lower","upper","inclusiveEnd","startkey","endkey","inclusive_end","mrquery","firstFreeValueField","normalizedSelector","used","isFreeValue","contentTypeOctetStream","doUpload","ArrayBuffer","isBuffer","isFile","File","isBlob","Blob","isStream","readable","pipe","isString","checksum","lastModifiedDate","ifMatch","Date","toGMTString","dirID","executable","doUpdateAttributes","attrs","db","children","addIsDir","toJsonApi","extractResponseLinkRelated","related","paths","archive","isDir","contents","clone","replicateFromCozyWithAuth","pluginLoaded","doctypes","timer","plugin","database","autoSync","createIndexes","setInterval","replicate","clearInterval","replication","cancel","live","basic","toBasicAuth","from","on","createIndex","index","currentPassPhrase","newPassPhrase","current_passphrase","new_passphrase","instance","ids","refs","makeReferencesPath","file"],"mappings":";AAAA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,uBAAe;AACf;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;;;;;;;;;;;;;;ACtCA,8C;;;;;;;;sjBCAA;;AAEA;;AACA;;AACA;;AACA;;KAAYA,I;;AACZ;;KAAYC,I;;AACZ;;KAAYC,K;;AACZ;;KAAYC,K;;AACZ;;KAAYC,O;;AACZ;;KAAYC,Q;;AACZ;;KAAYC,S;;;;;;KAGAC,U,GAGRP,I,CAHFQ,Q;KACaC,a,GAEXT,I,CAFFU,W;KACQC,Q,GACNX,I,CADFY,M;;;AAGF,KAAMC,WAAW,CAAjB;AACA,KAAMC,cAAc,CAApB;AACA,KAAMC,YAAY,CAAlB;AACA,KAAMC,SAAS,CAAf;;AAEA,KAAMC,sBAAsB;AAC1BC,eAAY;AADc,EAA5B;;AAIA,KAAMC,YAAY;AAChBC,WAAQnB,KAAKmB,MADG;AAEhBC,SAAMpB,KAAKoB,IAFK;AAGhBC,WAAQrB,KAAKqB,MAHG;AAIhBC,WAAQtB,KAAKuB,OAJG;AAKhBC,qBAAkBxB,KAAKwB,gBALP;AAMhBC,gBAAazB,KAAKyB,WANF;AAOhBC,gBAAazB,MAAMyB,WAPH;AAQhBC,UAAO1B,MAAM0B,KARG;AAShBC,uBAAoBvB,UAAUuB,kBATd;AAUhBC,wBAAqBxB,UAAUwB,mBAVf;AAWhBC,YAAS,mBAAmB;AAC1B,sBAAK,sDAAL;AACA,YAAO9B,KAAKuB,OAAL,uBAAP;AACD;AAde,EAAlB;;AAiBA,KAAMQ,YAAY;AAChBC,WAAQjC,KAAKiC,MADG;AAEhBC,mBAAgBlC,KAAKkC,cAFL;AAGhBC,iBAAcnC,KAAK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M,IADI,CACC,UAAC3G,KAAD;AAAA,YAAWA,MAAMwU,GAAN,CAAU,UAACiI,IAAD;AAAA,cAAUA,KAAK1I,GAAf;AAAA,MAAV,CAAX;AAAA,IADD,CAAP;AAED;;AAED,UAASyI,kBAAT,CAA6BlJ,GAA7B,EAAkC;AAChC,OAAMC,OAAOjJ,mBAAmBgJ,IAAIU,KAAvB,CAAb;AACA,OAAM5J,KAAKE,mBAAmBgJ,IAAIS,GAAvB,CAAX;AACA,qBAAgBR,IAAhB,SAAwBnJ,EAAxB;AACD,E","file":"cozy-client.node.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\texports: {},\n \t\t\tid: moduleId,\n \t\t\tloaded: false\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.loaded = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(0);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap caf7b1559e5630948f31","module.exports = require(\"isomorphic-fetch\");\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"isomorphic-fetch\"\n// module id = 1\n// module chunks = 0","/* global fetch */\n\nimport {unpromiser, retry, warn} from './utils'\nimport {LocalStorage, MemoryStorage} from './auth_storage'\nimport {AppToken as AppTokenV2, getAppToken as getAppTokenV2} from './auth_v2'\nimport * as auth from './auth_v3'\nimport * as data from './data'\nimport * as mango from './mango'\nimport * as files from './files'\nimport * as offline from './offline'\nimport * as settings from './settings'\nimport * as relations from './relations'\n\nconst {\n AppToken: AppTokenV3,\n AccessToken: AccessTokenV3,\n Client: ClientV3\n} = auth\n\nconst AuthNone = 0\nconst AuthRunning = 1\nconst AuthError = 2\nconst AuthOK = 3\n\nconst defaultClientParams = {\n softwareID: 'github.com/cozy/cozy-client-js'\n}\n\nconst dataProto = {\n create: data.create,\n find: data.find,\n update: data.update,\n delete: data._delete,\n updateAttributes: data.updateAttributes,\n changesFeed: data.changesFeed,\n defineIndex: mango.defineIndex,\n query: mango.query,\n addReferencedFiles: relations.addReferencedFiles,\n listReferencedFiles: relations.listReferencedFiles,\n destroy: function (...args) {\n warn('destroy is deprecated, use cozy.data.delete instead.')\n return data._delete(...args)\n }\n}\n\nconst authProto = {\n client: auth.client,\n registerClient: auth.registerClient,\n updateClient: auth.updateClient,\n unregisterClient: auth.unregisterClient,\n getClient: auth.getClient,\n getAuthCodeURL: auth.getAuthCodeURL,\n getAccessToken: auth.getAccessToken,\n refreshToken: auth.refreshToken\n}\n\nconst filesProto = {\n create: files.create,\n createDirectory: files.createDirectory,\n updateById: files.updateById,\n updateAttributesById: files.updateAttributesById,\n updateAttributesByPath: files.updateAttributesByPath,\n trashById: files.trashById,\n statById: files.statById,\n statByPath: files.statByPath,\n downloadById: files.downloadById,\n downloadByPath: files.downloadByPath,\n getDowloadLink: files.getDowloadLink,\n getArchiveLink: files.getArchiveLink,\n listTrash: files.listTrash,\n clearTrash: files.clearTrash,\n restoreById: files.restoreById,\n destroyById: files.destroyById\n}\n\nconst offlineProto = {\n init: offline.init,\n getDoctypes: offline.getDoctypes,\n // database\n createDatabase: offline.createDatabase,\n hasDatabase: offline.hasDatabase,\n getDatabase: offline.getDatabase,\n destroyDatabase: offline.destroyDatabase,\n destroyAllDatabase: offline.destroyAllDatabase,\n // replication\n replicateFromCozy: offline.replicateFromCozy,\n hasSync: offline.hasSync,\n startAllSync: offline.startAllSync,\n startSync: offline.startSync,\n stopAllSync: offline.stopAllSync,\n stopSync: offline.stopSync\n}\n\nconst settingsProto = {\n diskUsage: settings.diskUsage,\n changePassphrase: settings.changePassphrase,\n getInstance: settings.getInstance,\n updateInstance: settings.updateInstance,\n getClients: settings.getClients,\n deleteClientById: settings.deleteClientById\n}\n\nclass Client {\n constructor (options) {\n this.data = {}\n this.files = {}\n this.offline = {}\n this.settings = {}\n this.auth = {\n Client: ClientV3,\n AccessToken: AccessTokenV3,\n AppToken: AppTokenV3,\n AppTokenV2: AppTokenV2,\n LocalStorage: LocalStorage,\n MemoryStorage: MemoryStorage\n }\n this._inited = false\n if (options) {\n this.init(options)\n }\n }\n\n init (options = {}) {\n this._inited = true\n this._oauth = false // is oauth activated or not\n this._token = null // application token\n this._authstate = AuthNone\n this._authcreds = null\n this._storage = null\n this._version = null\n this._offline = null\n\n const token = options.token\n const oauth = options.oauth\n if (token && oauth) {\n throw new Error('Cannot specify an application token with a oauth activated')\n }\n\n if (token) {\n this._token = new AppTokenV3({ token })\n } else if (oauth) {\n this._oauth = true\n this._storage = oauth.storage\n this._clientParams = Object.assign({}, defaultClientParams, oauth.clientParams)\n this._onRegistered = oauth.onRegistered || nopOnRegistered\n }\n\n let url = options.cozyURL || ''\n while (url[url.length - 1] === '/') {\n url = url.slice(0, -1)\n }\n\n this._url = url\n\n const disablePromises = !!options.disablePromises\n addToProto(this, this.data, dataProto, disablePromises)\n addToProto(this, this.auth, authProto, disablePromises)\n addToProto(this, this.files, filesProto, disablePromises)\n addToProto(this, this.offline, offlineProto, disablePromises)\n addToProto(this, this.settings, settingsProto, disablePromises)\n\n if (options.offline) {\n this.offline.init(options.offline)\n }\n }\n\n authorize () {\n const state = this._authstate\n if (state === AuthOK || state === AuthRunning) {\n return this._authcreds\n }\n\n this._authstate = AuthRunning\n this._authcreds = this.isV2().then((isV2) => {\n if (isV2 && this._oauth) {\n throw new Error('OAuth is not supported on the V2 stack')\n }\n if (this._oauth) {\n return auth.oauthFlow(\n this,\n this._storage,\n this._clientParams,\n this._onRegistered\n )\n }\n // we expect to be on a client side application running in a browser\n // with cookie-based authentication.\n if (isV2) {\n return getAppTokenV2()\n } else if (this._token) {\n return Promise.resolve({client: null, token: this._token})\n } else {\n throw new Error('Missing application token')\n }\n })\n\n this._authcreds.then(\n () => { this._authstate = AuthOK },\n () => { this._authstate = AuthError })\n\n return this._authcreds\n }\n\n saveCredentials (client, token) {\n const creds = {client, token}\n if (!this._storage || this._authstate === AuthRunning) {\n return Promise.resolve(creds)\n }\n this._storage.save(auth.CredsKey, creds)\n this._authcreds = Promise.resolve(creds)\n return this._authcreds\n }\n\n fullpath (path) {\n return this.isV2().then((isV2) => {\n const pathprefix = isV2 ? '/ds-api' : ''\n return this._url + pathprefix + path\n })\n }\n\n isV2 () {\n if (!this._version) {\n this._version = retry(() => fetch(`${this._url}/status/`), 3)()\n .then((res) => {\n if (!res.ok) {\n throw new Error('Could not fetch cozy status')\n } else {\n return res.json()\n }\n })\n .then((status) => status.datasystem !== undefined)\n }\n return this._version\n }\n}\n\nfunction nopOnRegistered () {\n throw new Error('Missing onRegistered callback')\n}\n\nfunction protoify (context, fn) {\n return function prototyped (...args) {\n return fn(context, ...args)\n }\n}\n\nfunction addToProto (ctx, obj, proto, disablePromises) {\n for (const attr in proto) {\n let fn = protoify(ctx, proto[attr])\n if (disablePromises) {\n fn = unpromiser(fn)\n }\n obj[attr] = fn\n }\n}\n\nmodule.exports = new Client()\nObject.assign(module.exports, {Client, LocalStorage, MemoryStorage})\n\n\n\n// WEBPACK FOOTER //\n// ./src/index.js","const FuzzFactor = 0.3\n\nexport function unpromiser (fn) {\n return function (...args) {\n const value = fn.apply(this, args)\n if (!isPromise(value)) {\n return value\n }\n const l = args.length\n if (l === 0 || typeof args[l - 1] !== 'function') {\n return\n }\n const cb = args[l - 1]\n value.then(\n (res) => cb(null, res),\n (err) => cb(err, null)\n )\n return\n }\n}\n\nexport function isPromise (value) {\n return !!value && typeof value.then === 'function'\n}\n\nexport function sleep (time, args) {\n return new Promise((resolve) => {\n setTimeout(resolve, time, args)\n })\n}\n\nexport function retry (fn, count, delay = 300) {\n return function doTry (...args) {\n return fn(...args).catch((err) => {\n if (--count < 0) {\n throw err\n }\n return sleep(getBackedoffDelay(delay, count))\n .then(() => doTry(...args))\n })\n }\n}\n\nexport function getFuzzedDelay (retryDelay) {\n const fuzzingFactor = ((Math.random() * 2) - 1) * FuzzFactor\n return retryDelay * (1.0 + fuzzingFactor)\n}\n\nexport function getBackedoffDelay (retryDelay, retryCount = 1) {\n return getFuzzedDelay(retryDelay * Math.pow(2, retryCount - 1))\n}\n\nexport function createPath (cozy, isV2, doctype, id = '', query = null) {\n let route = '/data/'\n if (!isV2) {\n route += `${encodeURIComponent(doctype)}/`\n }\n if (id !== '') {\n route += encodeURIComponent(id)\n }\n const q = encodeQuery(query)\n if (q !== '') {\n route += '?' + q\n }\n return route\n}\n\nexport function encodeQuery (query) {\n if (!query) {\n return ''\n }\n let q = ''\n for (const qname in query) {\n if (q !== '') {\n q += '&'\n }\n q += `${encodeURIComponent(qname)}=${encodeURIComponent(query[qname])}`\n }\n return q\n}\n\nexport function decodeQuery (url) {\n let queryIndex = url.indexOf('?')\n if (queryIndex < 0) {\n queryIndex = url.length\n }\n const queries = {}\n let fragIndex = url.indexOf('#')\n if (fragIndex < 0) {\n fragIndex = url.length\n }\n if (fragIndex < queryIndex) {\n return queries\n }\n const queryStr = url.slice(queryIndex + 1, fragIndex)\n if (queryStr === '') {\n return queries\n }\n const parts = queryStr.split('&')\n for (let i = 0; i < parts.length; i++) {\n let pair = parts[i].split('=')\n if (pair.length === 0 || pair[0] === '') {\n continue\n }\n const qname = decodeURIComponent(pair[0])\n if (queries.hasOwnProperty(qname)) {\n continue\n }\n if (pair.length === 1) {\n queries[qname] = true\n } else if (pair.length === 2) {\n queries[qname] = decodeURIComponent(pair[1])\n } else {\n throw new Error('Malformed URL')\n }\n }\n return queries\n}\n\nconst warned = []\nexport function warn (text) {\n if (warned.indexOf(text) === -1) {\n warned.push(text)\n console.warn('cozy-client-js', text)\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils.js","export class LocalStorage {\n constructor (storage, prefix) {\n if (!storage && typeof window !== 'undefined') {\n storage = window.localStorage\n }\n this.storage = storage\n this.prefix = prefix || 'cozy:oauth:'\n }\n\n save (key, value) {\n return new Promise(resolve => {\n this.storage.setItem(this.prefix + key, JSON.stringify(value))\n resolve(value)\n })\n }\n\n load (key) {\n return new Promise(resolve => {\n const item = this.storage.getItem(this.prefix + key)\n if (!item) {\n resolve()\n } else {\n resolve(JSON.parse(item))\n }\n })\n }\n\n delete (key) {\n return new Promise(resolve => resolve(\n this.storage.removeItem(this.prefix + key)))\n }\n\n clear () {\n return new Promise(resolve => {\n const storage = this.storage\n for (let i = 0; i < storage.length; i++) {\n const key = storage.key(i)\n if (key.indexOf(this.prefix) === 0) {\n storage.removeItem(key)\n }\n }\n resolve()\n })\n }\n}\n\nexport class MemoryStorage {\n constructor () {\n this.hash = Object.create(null)\n }\n\n save (key, value) {\n this.hash[key] = value\n return Promise.resolve(value)\n }\n\n load (key) {\n return Promise.resolve(this.hash[key])\n }\n\n delete (key) {\n const deleted = delete this.hash[key]\n return Promise.resolve(deleted)\n }\n\n clear () {\n this.hash = Object.create(null)\n return Promise.resolve()\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/auth_storage.js","/* global btoa */\nconst V2TOKEN_ABORT_TIMEOUT = 3000\n\nexport function getAppToken () {\n return new Promise(function (resolve, reject) {\n if (typeof window === 'undefined') {\n return reject(new Error('getV2Token should be used in browser'))\n } else if (!window.parent) {\n return reject(new Error('getV2Token should be used in iframe'))\n } else if (!window.parent.postMessage) {\n return reject(new Error('getV2Token should be used in modern browser'))\n }\n const origin = window.location.origin\n const intent = {action: 'getToken'}\n let timeout = null\n const receiver = function (event) {\n let token\n try {\n token = new AppToken({\n appName: event.data.appName,\n token: event.data.token\n })\n } catch (e) {\n reject(e)\n return\n }\n window.removeEventListener('message', receiver)\n clearTimeout(timeout)\n resolve({ client: null, token })\n }\n window.addEventListener('message', receiver, false)\n window.parent.postMessage(intent, origin)\n timeout = setTimeout(() => {\n reject(new Error('No response from parent iframe after 3s'))\n }, V2TOKEN_ABORT_TIMEOUT)\n })\n}\n\nexport class AppToken {\n constructor (opts) {\n this.appName = opts.appName || ''\n this.token = opts.token || ''\n }\n\n toAuthHeader () {\n return 'Basic ' + btoa(`${this.appName}:${this.token}`)\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/auth_v2.js","module.exports = require(\"btoa\");\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"btoa\"\n// module id = 6\n// module chunks = 0","/* global btoa */\nimport {encodeQuery, decodeQuery} from './utils'\nimport {cozyFetchJSON, FetchError} from './fetch'\n\nconst StateSize = 16\n\nexport const CredsKey = 'creds'\nexport const StateKey = 'state'\n\nexport class Client {\n constructor (opts) {\n this.clientID = opts.clientID || opts.client_id || ''\n this.clientSecret = opts.clientSecret || opts.client_secret || ''\n this.registrationAccessToken = opts.registrationAccessToken || opts.registration_access_token || ''\n\n if (opts.redirect_uris) {\n this.redirectURI = opts.redirect_uris[0] || ''\n } else {\n this.redirectURI = opts.redirectURI || ''\n }\n\n this.softwareID = opts.softwareID || opts.software_id || ''\n this.softwareVersion = opts.softwareVersion || opts.software_version || ''\n this.clientName = opts.clientName || opts.client_name || ''\n this.clientKind = opts.clientKind || opts.client_kind || ''\n this.clientURI = opts.clientURI || opts.client_uri || ''\n\n this.logoURI = opts.logoURI || opts.logo_uri || ''\n this.policyURI = opts.policyURI || opts.policy_uri || ''\n\n if (!this.registrationAccessToken) {\n if (this.redirectURI === '') {\n throw new Error('Missing redirectURI field')\n }\n if (this.softwareID === '') {\n throw new Error('Missing softwareID field')\n }\n if (this.clientName === '') {\n throw new Error('Missing clientName field')\n }\n }\n }\n\n isRegistered () {\n return this.clientID !== ''\n }\n\n toRegisterJSON () {\n return {\n redirect_uris: [this.redirectURI],\n software_id: this.softwareID,\n software_version: this.softwareVersion,\n client_name: this.clientName,\n client_kind: this.clientKind,\n client_uri: this.clientURI,\n logo_uri: this.logoURI,\n policy_uri: this.policyURI\n }\n }\n\n toAuthHeader () {\n return 'Bearer ' + this.registrationAccessToken\n }\n}\n\nexport class AccessToken {\n constructor (opts) {\n this.tokenType = opts.tokenType || opts.token_type\n this.accessToken = opts.accessToken || opts.access_token\n this.refreshToken = opts.refreshToken || opts.refresh_token\n this.scope = opts.scope\n }\n\n toAuthHeader () {\n return 'Bearer ' + this.accessToken\n }\n\n toBasicAuth () {\n return `user:${this.accessToken}@`\n }\n}\n\nexport class AppToken {\n constructor (opts) {\n this.token = opts.token || ''\n }\n\n toAuthHeader () {\n return 'Bearer ' + this.token\n }\n\n toBasicAuth () {\n return `user:${this.token}@`\n }\n}\n\nexport function client (cozy, clientParams) {\n if (!clientParams) {\n clientParams = cozy._clientParams\n }\n if (clientParams instanceof Client) {\n return clientParams\n }\n return new Client(clientParams)\n}\n\nexport function registerClient (cozy, clientParams) {\n const cli = client(cozy, clientParams)\n if (cli.isRegistered()) {\n return Promise.reject(new Error('Client already registered'))\n }\n return cozyFetchJSON(cozy, 'POST', '/auth/register', cli.toRegisterJSON(), {\n disableAuth: true\n })\n .then((data) => new Client(data))\n}\n\nexport function updateClient (cozy, clientParams, resetSecret = false) {\n const cli = client(cozy, clientParams)\n if (!cli.isRegistered()) {\n return Promise.reject(new Error('Client not registered'))\n }\n let data = cli.toRegisterJSON()\n data.client_id = cli.clientID\n if (resetSecret) data.client_secret = cli.clientSecret\n\n return cozyFetchJSON(cozy, 'PUT', `/auth/register/${cli.clientID}`, data, {\n manualAuthCredentials: {\n token: cli\n }\n }).then((data) => createClient(data, cli))\n}\n\nexport function unregisterClient (cozy, clientParams) {\n const cli = client(cozy, clientParams)\n if (!cli.isRegistered()) {\n return Promise.reject(new Error('Client not registered'))\n }\n return cozyFetchJSON(cozy, 'DELETE', `/auth/register/${cli.clientID}`, null, {\n manualAuthCredentials: {\n token: cli\n }\n })\n}\n\n// getClient will retrive the registered client informations from the server.\nexport function getClient (cozy, clientParams) {\n const cli = client(cozy, clientParams)\n if (!cli.isRegistered()) {\n return Promise.reject(new Error('Client not registered'))\n }\n return cozyFetchJSON(cozy, 'GET', `/auth/register/${cli.clientID}`, null, {\n manualAuthCredentials: {\n token: cli\n }\n })\n .then((data) => createClient(data, cli))\n}\n\n// createClient returns a new Client instance given on object containing the\n// data of the client, from the API, and an old instance of the client.\nfunction createClient (data, oldClient) {\n const newClient = new Client(data)\n // we need to keep track of the registrationAccessToken since it is send\n // only on registration. The GET /auth/register/:client-id endpoint does\n // not return this token.\n const shouldPassRegistration = (\n !!oldClient &&\n oldClient.registrationAccessToken !== '' &&\n newClient.registrationAccessToken === ''\n )\n if (shouldPassRegistration) {\n newClient.registrationAccessToken = oldClient.registrationAccessToken\n }\n return newClient\n}\n\n// getAuthCodeURL returns a pair {authURL,state} given a registered client. The\n// state should be stored in order to be checked against on the user validation\n// phase.\nexport function getAuthCodeURL (cozy, client, scopes = []) {\n if (!(client instanceof Client)) {\n client = new Client(client)\n }\n if (!client.isRegistered()) {\n throw new Error('Client not registered')\n }\n const state = generateRandomState()\n const query = {\n 'client_id': client.clientID,\n 'redirect_uri': client.redirectURI,\n 'state': state,\n 'response_type': 'code',\n 'scope': scopes.join(' ')\n }\n return {\n url: cozy._url + `/auth/authorize?${encodeQuery(query)}`,\n state: state\n }\n}\n\n// getAccessToken perform a request on the access_token entrypoint with the\n// authorization_code grant type in order to generate a new access token for a\n// newly registered client.\n//\n// This method extracts the access code and state from the given URL. By\n// default it uses window.location.href. Also, it checks the given state with\n// the one specified in the URL query parameter to prevent CSRF attacks.\nexport function getAccessToken (cozy, client, state, pageURL = '') {\n if (!state) {\n return Promise.reject(new Error('Missing state value'))\n }\n const grantQueries = getGrantCodeFromPageURL(pageURL)\n if (grantQueries === null) {\n return Promise.reject(new Error('Missing states from current URL'))\n }\n if (state !== grantQueries.state) {\n return Promise.reject(new Error('Given state does not match url query state'))\n }\n return retrieveToken(cozy, client, null, {\n 'grant_type': 'authorization_code',\n 'code': grantQueries.code\n })\n}\n\n// refreshToken perform a request on the access_token entrypoint with the\n// refresh_token grant type in order to refresh the given token.\nexport function refreshToken (cozy, client, token) {\n return retrieveToken(cozy, client, token, {\n 'grant_type': 'refresh_token',\n 'refresh_token': token.refreshToken\n })\n}\n\n// oauthFlow performs the stateful registration and access granting of an OAuth\n// client.\nexport function oauthFlow (cozy, storage, clientParams, onRegistered) {\n let tryCount = 0\n\n function clearAndRetry (err) {\n if (tryCount++ > 0) {\n throw err\n }\n return storage.clear().then(() =>\n oauthFlow(cozy, storage, clientParams, onRegistered))\n }\n\n function registerNewClient () {\n return storage.clear()\n .then(() => registerClient(cozy, clientParams))\n .then((client) => {\n const {url, state} = getAuthCodeURL(cozy, client, clientParams.scopes)\n return storage.save(StateKey, {client, url, state})\n })\n }\n\n return Promise.all([\n storage.load(CredsKey),\n storage.load(StateKey)\n ])\n .then(([credentials, storedState]) => {\n // If credentials are cached we re-fetch the registered client with the\n // said token. Fetching the client, if the token is outdated we should try\n // the token is refreshed.\n if (credentials) {\n let oldClient, token\n try {\n oldClient = new Client(credentials.client)\n token = new AccessToken(credentials.token)\n } catch (err) {\n // bad cache, we should clear and retry the process\n return clearAndRetry(err)\n }\n return getClient(cozy, oldClient)\n .then((client) => ({client, token}))\n .catch((err) => {\n // If we fall into an error while fetching the client (because of a\n // bad connectivity for instance), we do not bail the whole process\n // since the client should be able to continue with the persisted\n // client and token.\n //\n // If it is an explicit Unauthorized error though, we bail, clear th\n // cache and retry.\n if (FetchError.isUnauthorized(err) || FetchError.isNotFound(err)) {\n throw new Error('Client has been revoked')\n }\n return { client: oldClient, token }\n })\n }\n\n // Otherwise register a new client if necessary (ie. no client is stored)\n // and call the onRegistered callback to wait for the user to grant the\n // access. Finally fetches to access token on success.\n let statePromise\n if (!storedState) {\n statePromise = registerNewClient()\n } else {\n statePromise = Promise.resolve(storedState)\n }\n\n let client, state, token\n return statePromise\n .then((data) => {\n client = data.client\n state = data.state\n return Promise.resolve(onRegistered(client, data.url))\n })\n .then((pageURL) => getAccessToken(cozy, client, state, pageURL))\n .then((t) => { token = t })\n .then(() => storage.delete(StateKey))\n .then(() => ({client, token}))\n })\n .then(\n (creds) => storage.save(CredsKey, creds),\n (err) => {\n if (FetchError.isUnauthorized(err)) {\n return clearAndRetry(err)\n } else {\n throw err\n }\n })\n}\n\n// retrieveToken perform a request on the access_token entrypoint in order to\n// fetch a token.\nfunction retrieveToken (cozy, client, token, query) {\n if (!(client instanceof Client)) {\n client = new Client(client)\n }\n if (!client.isRegistered()) {\n return Promise.reject(new Error('Client not registered'))\n }\n const body = encodeQuery(Object.assign({}, query, {\n 'client_id': client.clientID,\n 'client_secret': client.clientSecret\n }))\n return cozyFetchJSON(cozy, 'POST', '/auth/access_token', body, {\n disableAuth: (token === null),\n manualAuthCredentials: { client, token },\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' }\n })\n .then((data) => {\n data.refreshToken = data.refreshToken || query.refresh_token\n return new AccessToken(data)\n })\n}\n\n// getGrantCodeFromPageURL extract the state and access_code query parameters\n// from the given url\nfunction getGrantCodeFromPageURL (pageURL = '') {\n if (pageURL === '' && typeof window !== 'undefined') {\n pageURL = window.location.href\n }\n const queries = decodeQuery(pageURL)\n if (!queries.hasOwnProperty('state')) {\n return null\n }\n return {\n state: queries['state'],\n code: queries['access_code']\n }\n}\n\n// generateRandomState will try to generate a 128bits random value from a secure\n// pseudo random generator. It will fallback on Math.random if it cannot find\n// such generator.\nfunction generateRandomState () {\n let buffer\n if (typeof window !== 'undefined' &&\n typeof window.crypto !== 'undefined' &&\n typeof window.crypto.getRandomValues === 'function') {\n buffer = new Uint8Array(StateSize)\n window.crypto.getRandomValues(buffer)\n } else {\n try {\n buffer = require('crypto').randomBytes(StateSize)\n } catch (e) {}\n }\n if (!buffer) {\n buffer = new Array(StateSize)\n for (let i = 0; i < buffer.length; i++) {\n buffer[i] = Math.floor((Math.random() * 255))\n }\n }\n return btoa(String.fromCharCode.apply(null, buffer))\n .replace(/=+$/, '')\n .replace(/\\//g, '_')\n .replace(/\\+/g, '-')\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/auth_v3.js","/* global fetch */\nimport {refreshToken, AccessToken} from './auth_v3'\nimport {retry} from './utils'\nimport jsonapi from './jsonapi'\n\nexport function cozyFetch (cozy, path, options = {}) {\n return cozy.fullpath(path).then((fullpath) => {\n let resp\n if (options.disableAuth) {\n resp = fetch(fullpath, options)\n } else if (options.manualAuthCredentials) {\n resp = cozyFetchWithAuth(cozy, fullpath, options, options.manualAuthCredentials)\n } else {\n resp = cozy.authorize().then((credentials) =>\n cozyFetchWithAuth(cozy, fullpath, options, credentials))\n }\n return resp.then(handleResponse)\n })\n}\n\nfunction cozyFetchWithAuth (cozy, fullpath, options, credentials) {\n if (credentials) {\n options.headers = options.headers || {}\n options.headers['Authorization'] = credentials.token.toAuthHeader()\n }\n\n // the option credentials:include tells fetch to include the cookies in the\n // request even for cross-origin requests\n options.credentials = 'include'\n\n return Promise.all([\n cozy.isV2(),\n fetch(fullpath, options)\n ]).then(([isV2, res]) => {\n if (res.status !== 401 || isV2 || !credentials) {\n return res\n }\n // we try to refresh the token only for OAuth, ie, the client defined\n // and the token is an instance of AccessToken.\n const { client, token } = credentials\n if (!client || !(token instanceof AccessToken)) {\n return res\n }\n return retry(() => refreshToken(cozy, client, token), 3)()\n .then((newToken) => cozy.saveCredentials(client, newToken))\n .then((credentials) => cozyFetchWithAuth(cozy, fullpath, options, credentials))\n })\n}\n\nexport function cozyFetchJSON (cozy, method, path, body, options = {}) {\n options.method = method\n\n const headers = options.headers = options.headers || {}\n\n headers['Accept'] = 'application/json'\n\n if (method !== 'GET' && method !== 'HEAD' && body !== undefined) {\n if (headers['Content-Type']) {\n options.body = body\n } else {\n headers['Content-Type'] = 'application/json'\n options.body = JSON.stringify(body)\n }\n }\n\n return cozyFetch(cozy, path, options)\n .then(handleJSONResponse)\n}\n\nfunction handleResponse (res) {\n if (res.ok) {\n return res\n }\n let data\n const contentType = res.headers.get('content-type')\n if (contentType && contentType.indexOf('json') >= 0) {\n data = res.json()\n } else {\n data = res.text()\n }\n return data.then(err => {\n throw new FetchError(res, err)\n })\n}\n\nfunction handleJSONResponse (res) {\n const contentType = res.headers.get('content-type')\n if (!contentType || contentType.indexOf('json') < 0) {\n return res.text((data) => {\n throw new FetchError(res, new Error('Response is not JSON: ' + data))\n })\n }\n\n const json = res.json()\n if (contentType.indexOf('application/vnd.api+json') === 0) {\n return json.then(jsonapi)\n } else {\n return json\n }\n}\n\nexport class FetchError extends Error {\n constructor (res, reason) {\n super()\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor)\n }\n // XXX We have to hardcode this because babel doesn't play nice when extending Error\n this.name = 'FetchError'\n this.response = res\n this.url = res.url\n this.status = res.status\n this.reason = reason\n }\n}\n\nFetchError.isUnauthorized = function (err) {\n // XXX We can't use err instanceof FetchError because of the caveats of babel\n return err.name === 'FetchError' && err.status === 401\n}\n\nFetchError.isNotFound = function (err) {\n // XXX We can't use err instanceof FetchError because of the caveats of babel\n return err.name === 'FetchError' && err.status === 404\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/fetch.js","function indexKey (doc) {\n return doc.type + '/' + doc.id\n}\n\nfunction findByRef (resources, ref) {\n return resources[indexKey(ref)]\n}\n\nfunction handleResource (rawResource, resources, links) {\n let resource = {\n _id: rawResource.id,\n _type: rawResource.type,\n _rev: (rawResource.meta && rawResource.meta.rev),\n links: Object.assign({}, rawResource.links, links),\n attributes: rawResource.attributes,\n relations: (name) => {\n let rels = rawResource.relationships[name]\n if (rels === undefined || rels.data === undefined) return undefined\n if (rels.data === null) return null\n if (!Array.isArray(rels.data)) return findByRef(resources, rels.data)\n return rels.data.map(ref => findByRef(resources, ref))\n }\n }\n\n resources[indexKey(rawResource)] = resource\n\n return resource\n}\n\nfunction handleTopLevel (doc, resources = {}) {\n // build an index of included resource by Type & ID\n const included = doc.included\n\n if (Array.isArray(included)) {\n included.forEach((r) => handleResource(r, resources, doc.links))\n }\n\n if (Array.isArray(doc.data)) {\n return doc.data.map((r) => handleResource(r, resources, doc.links))\n } else {\n return handleResource(doc.data, resources, doc.links)\n }\n}\n\nexport default handleTopLevel\n\n\n\n// WEBPACK FOOTER //\n// ./src/jsonapi.js","module.exports = require(\"crypto\");\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"crypto\"\n// module id = 10\n// module chunks = 0","import {createPath} from './utils'\nimport {normalizeDoctype} from './doctypes'\nimport {cozyFetchJSON} from './fetch'\n\nconst NOREV = 'stack-v2-no-rev'\n\nexport function create (cozy, doctype, attributes) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n if (isV2) {\n attributes.docType = doctype\n }\n const path = createPath(cozy, isV2, doctype)\n return cozyFetchJSON(cozy, 'POST', path, attributes).then((resp) => {\n if (isV2) {\n return find(cozy, doctype, resp._id)\n } else {\n return resp.data\n }\n })\n })\n}\n\nexport function find (cozy, doctype, id) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n\n if (!id) {\n return Promise.reject(new Error('Missing id parameter'))\n }\n\n const path = createPath(cozy, isV2, doctype, id)\n return cozyFetchJSON(cozy, 'GET', path).then((resp) => {\n if (isV2) {\n return Object.assign(resp, {_rev: NOREV})\n } else {\n return resp\n }\n })\n })\n}\n\nexport function changesFeed (cozy, doctype, options) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n const path = createPath(cozy, isV2, doctype, '_changes', options)\n return cozyFetchJSON(cozy, 'GET', path)\n })\n}\n\nexport function update (cozy, doctype, doc, changes) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n const {_id, _rev} = doc\n\n if (!_id) {\n return Promise.reject(new Error('Missing _id field in passed document'))\n }\n\n if (!isV2 && !_rev) {\n return Promise.reject(new Error('Missing _rev field in passed document'))\n }\n\n if (isV2) {\n changes = Object.assign({ _id }, changes)\n } else {\n changes = Object.assign({ _id, _rev }, changes)\n }\n\n const path = createPath(cozy, isV2, doctype, _id)\n return cozyFetchJSON(cozy, 'PUT', path, changes).then((resp) => {\n if (isV2) {\n return find(cozy, doctype, _id)\n } else {\n return resp.data\n }\n })\n })\n}\n\nexport function updateAttributes (cozy, doctype, _id, changes, tries = 3) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n return find(cozy, doctype, _id)\n .then((doc) => {\n return update(cozy, doctype, doc, Object.assign({ _id }, doc, changes))\n })\n .catch((err) => {\n if (tries > 0) {\n return updateAttributes(cozy, doctype, _id, changes, tries - 1)\n } else {\n throw err\n }\n })\n })\n}\n\nexport function _delete (cozy, doctype, doc) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n const {_id, _rev} = doc\n\n if (!_id) {\n return Promise.reject(new Error('Missing _id field in passed document'))\n }\n\n if (!isV2 && !_rev) {\n return Promise.reject(new Error('Missing _rev field in passed document'))\n }\n\n const query = isV2 ? null : { rev: _rev }\n const path = createPath(cozy, isV2, doctype, _id, query)\n return cozyFetchJSON(cozy, 'DELETE', path).then((resp) => {\n if (isV2) {\n return {id: _id, rev: NOREV}\n } else {\n return resp\n }\n })\n })\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/data.js","import {warn} from './utils'\n\nexport const DOCTYPE_FILES = 'io.cozy.files'\n\nconst KNOWN_DOCTYPES = {\n 'files': DOCTYPE_FILES,\n 'folder': DOCTYPE_FILES,\n 'contact': 'io.cozy.contacts',\n 'event': 'io.cozy.events',\n 'track': 'io.cozy.labs.music.track',\n 'playlist': 'io.cozy.labs.music.playlist'\n}\n\nconst REVERSE_KNOWN = {}\nObject.keys(KNOWN_DOCTYPES).forEach(k => {\n REVERSE_KNOWN[KNOWN_DOCTYPES[k]] = k\n})\n\nexport function normalizeDoctype (cozy, isV2, doctype) {\n let isQualified = doctype.indexOf('.') !== -1\n if (isV2 && isQualified) {\n let known = REVERSE_KNOWN[doctype]\n if (known) return known\n return doctype.replace(/\\./g, '-')\n }\n if (!isV2 && !isQualified) {\n let known = KNOWN_DOCTYPES[doctype]\n if (known) {\n warn('you are using a non-qualified doctype ' + doctype + ' assumed to be ' + known)\n return known\n }\n throw new Error('Doctype ' + doctype + ' should be qualified.')\n }\n return doctype\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/doctypes.js","import {warn, createPath} from './utils'\nimport {normalizeDoctype} from './doctypes'\nimport {cozyFetchJSON} from './fetch'\n\nexport function defineIndex (cozy, doctype, fields) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n if (!Array.isArray(fields) || fields.length === 0) {\n throw new Error('defineIndex fields should be a non-empty array')\n }\n if (isV2) {\n return defineIndexV2(cozy, doctype, fields)\n } else {\n return defineIndexV3(cozy, doctype, fields)\n }\n })\n}\n\nexport function query (cozy, indexRef, options) {\n return cozy.isV2().then((isV2) => {\n if (!indexRef) {\n throw new Error('query should be passed the indexRef')\n }\n if (isV2) {\n return queryV2(cozy, indexRef, options)\n } else {\n return queryV3(cozy, indexRef, options)\n }\n })\n}\n\n// Internals\n\nconst VALUEOPERATORS = ['$eq', '$gt', '$gte', '$lt', '$lte']\nconst LOGICOPERATORS = ['$or', '$and', '$not']\n\n/* eslint-disable */\nconst MAP_TEMPLATE = (function (doc) {\n if (doc.docType.toLowerCase() === 'DOCTYPEPLACEHOLDER'){\n emit(FIELDSPLACEHOLDER, doc)\n }\n}).toString().replace(/ /g, '').replace(/\\n/g, '')\nconst COUCHDB_INFINITY = {\"\\uFFFF\": \"\\uFFFF\"}\nconst COUCHDB_LOWEST = null\n/* eslint-enable */\n\n// defineIndexV2 is equivalent to defineIndex but only works for V2.\n// It transforms the index fields into a map reduce view.\nfunction defineIndexV2 (cozy, doctype, fields) {\n let indexName = 'by' + fields.map(capitalize).join('')\n let indexDefinition = { map: makeMapFunction(doctype, fields), reduce: '_count' }\n let path = `/request/${doctype}/${indexName}/`\n return cozyFetchJSON(cozy, 'PUT', path, indexDefinition)\n .then(() => ({ doctype: doctype, type: 'mapreduce', name: indexName, fields: fields }))\n}\n\n// defineIndexV2 is equivalent to defineIndex but only works for V2.\n// It transforms the index fields into a map reduce view.\nfunction defineIndexV3 (cozy, doctype, fields) {\n let path = createPath(cozy, false, doctype, '_index')\n let indexDefinition = {'index': {fields}}\n return cozyFetchJSON(cozy, 'POST', path, indexDefinition)\n .then((response) => ({ doctype: doctype, type: 'mango', name: response.id, fields: fields }))\n}\n\n// queryV2 is equivalent to query but only works for V2.\n// It transforms the query into a _views call using makeMapReduceQuery\nfunction queryV2 (cozy, indexRef, options) {\n if (indexRef.type !== 'mapreduce') {\n throw new Error('query indexRef should be the return value of defineIndexV2')\n }\n if (options.fields) {\n warn('query fields will be ignored on v2')\n }\n\n let path = `/request/${indexRef.doctype}/${indexRef.name}/`\n let opts = makeMapReduceQuery(indexRef, options)\n return cozyFetchJSON(cozy, 'POST', path, opts)\n .then((response) => response.map(r => r.value))\n}\n\n// queryV3 is equivalent to query but only works for V3\nfunction queryV3 (cozy, indexRef, options) {\n if (indexRef.type !== 'mango') {\n throw new Error('indexRef should be the return value of defineIndexV3')\n }\n\n let opts = {\n use_index: indexRef.name,\n fields: options.fields,\n selector: options.selector,\n limit: options.limit,\n since: options.since\n }\n\n if (options.descending) {\n opts.sort = indexRef.fields.map(f => ({ [f]: 'desc' }))\n }\n\n let path = createPath(cozy, false, indexRef.doctype, '_find')\n return cozyFetchJSON(cozy, 'POST', path, opts)\n .then((response) => response.docs)\n}\n\n// misc\nfunction capitalize (name) {\n return name.charAt(0).toUpperCase() + name.slice(1)\n}\n\nfunction makeMapFunction (doctype, fields) {\n fields = '[' + fields.map(name => 'doc.' + name).join(',') + ']'\n\n return MAP_TEMPLATE.replace('DOCTYPEPLACEHOLDER', doctype.toLowerCase())\n .replace('FIELDSPLACEHOLDER', fields)\n}\n\n// parseSelector takes a mango selector and returns it as an array of filter\n// a filter is [path, operator, value] array\n// a path is an array of field names\n// This function is only exported so it can be unit tested.\n// Example :\n// parseSelector({\"test\":{\"deep\": {\"$gt\": 3}}})\n// [[['test', 'deep'], '$gt', 3 ]]\nexport function parseSelector (selector, path = [], operator = '$eq') {\n if ((typeof selector) !== 'object') {\n return [[path, operator, selector]]\n }\n\n let keys = Object.keys(selector)\n if (keys.length === 0) {\n throw new Error('empty selector')\n } else {\n return keys.reduce(function (acc, k) {\n if (LOGICOPERATORS.indexOf(k) !== -1) {\n throw new Error('cozy-client-js does not support mango logic ops')\n } else if (VALUEOPERATORS.indexOf(k) !== -1) {\n return acc.concat(parseSelector(selector[k], path, k))\n } else {\n return acc.concat(parseSelector(selector[k], path.concat(k), '$eq'))\n }\n }, [])\n }\n}\n\n// normalizeSelector takes a mango selector and returns it as an object\n// normalized.\n// This function is only exported so it can be unit tested.\n// Example :\n// parseSelector({\"test\":{\"deep\": {\"$gt\": 3}}})\n// {\"test.deep\": {\"$gt\": 3}}\nexport function normalizeSelector (selector) {\n var filters = parseSelector(selector)\n return filters.reduce(function (acc, filter) {\n let [path, op, value] = filter\n let field = path.join('.')\n acc[field] = acc[field] || {}\n acc[field][op] = value\n return acc\n }, {})\n}\n\n// applySelector takes the normalized selector for the current field\n// and append the proper values to opts.startkey, opts.endkey\nfunction applySelector (selector, opts) {\n let value = selector['$eq']\n let lower = COUCHDB_LOWEST\n let upper = COUCHDB_INFINITY\n let inclusiveEnd\n\n if (value) {\n opts.startkey.push(value)\n opts.endkey.push(value)\n return false\n }\n\n value = selector['$gt']\n if (value) {\n throw new Error('operator $gt (strict greater than) not supported')\n }\n\n value = selector['$gte']\n if (value) {\n lower = value\n }\n\n value = selector['$lte']\n if (value) {\n upper = value\n inclusiveEnd = true\n }\n\n value = selector['$lt']\n if (value) {\n upper = value\n inclusiveEnd = false\n }\n\n opts.startkey.push(lower)\n opts.endkey.push(upper)\n if (inclusiveEnd !== undefined) opts.inclusive_end = inclusiveEnd\n return true\n}\n\n// makeMapReduceQuery takes a mango query and generate _views call parameters\n// to obtain same results depending on fields in the passed indexRef.\nexport function makeMapReduceQuery (indexRef, query) {\n let mrquery = {\n startkey: [],\n endkey: [],\n reduce: false\n }\n let firstFreeValueField = null\n let normalizedSelector = normalizeSelector(query.selector)\n\n indexRef.fields.forEach(function (field) {\n let selector = normalizedSelector[field]\n\n if (selector && firstFreeValueField != null) {\n throw new Error('Selector on field ' + field + ', but not on ' + firstFreeValueField + ' which is higher in index fields.')\n } else if (selector) {\n selector.used = true\n let isFreeValue = applySelector(selector, mrquery)\n if (isFreeValue) firstFreeValueField = field\n } else if (firstFreeValueField == null) {\n firstFreeValueField = field\n mrquery.endkey.push(COUCHDB_INFINITY)\n }\n })\n\n Object.keys(normalizedSelector).forEach(function (field) {\n if (!normalizedSelector[field].used) {\n throw new Error('Cant apply selector on ' + field + ', it is not in index')\n }\n })\n\n if (query.descending) {\n mrquery = {\n descending: true,\n reduce: false,\n startkey: mrquery.endkey,\n endkey: mrquery.startkey,\n inclusive_end: mrquery.inclusive_end\n }\n }\n\n return mrquery\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/mango.js","/* global Blob, File */\nimport {cozyFetch, cozyFetchJSON} from './fetch'\nimport jsonapi from './jsonapi'\nimport { DOCTYPE_FILES } from './doctypes'\n\nconst contentTypeOctetStream = 'application/octet-stream'\n\nfunction doUpload (cozy, data, method, path, options) {\n if (!data) {\n throw new Error('missing data argument')\n }\n\n // transform any ArrayBufferView to ArrayBuffer\n if (data.buffer && data.buffer instanceof ArrayBuffer) {\n data = data.buffer\n }\n\n const isBuffer = (typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer)\n const isFile = (typeof File !== 'undefined' && data instanceof File)\n const isBlob = (typeof Blob !== 'undefined' && data instanceof Blob)\n const isStream = (data.readable === true && typeof data.pipe === 'function')\n const isString = (typeof data === 'string')\n\n if (!isBuffer && !isFile && !isBlob && !isStream && !isString) {\n throw new Error('invalid data type')\n }\n\n let {contentType, checksum, lastModifiedDate, ifMatch} = options || {}\n if (!contentType) {\n if (isBuffer) {\n contentType = contentTypeOctetStream\n } else if (isFile) {\n contentType = data.type || contentTypeOctetStream\n if (!lastModifiedDate) {\n lastModifiedDate = data.lastModifiedDate\n }\n } else if (isBlob) {\n contentType = contentTypeOctetStream\n } else if (isStream) {\n contentType = contentTypeOctetStream\n } else if (typeof data === 'string') {\n contentType = 'text/plain'\n }\n }\n\n if (lastModifiedDate && typeof lastModifiedDate === 'string') {\n lastModifiedDate = new Date(lastModifiedDate)\n }\n\n return cozyFetch(cozy, path, {\n method: method,\n headers: {\n 'Content-Type': contentType,\n 'Content-MD5': checksum || '',\n 'Date': lastModifiedDate ? lastModifiedDate.toGMTString() : '',\n 'If-Match': ifMatch || ''\n },\n body: data\n })\n .then((res) => {\n const json = res.json()\n if (!res.ok) {\n return json.then(err => { throw err })\n } else {\n return json.then(jsonapi)\n }\n })\n}\n\nexport function create (cozy, data, options) {\n let {name, dirID, executable} = options || {}\n\n // handle case where data is a file and contains the name\n if (!name && typeof data.name === 'string') {\n name = data.name\n }\n\n if (typeof name !== 'string' || name === '') {\n throw new Error('missing name argument')\n }\n\n if (executable === undefined) {\n executable = false\n }\n\n const path = `/files/${encodeURIComponent(dirID || '')}`\n const query = `?Name=${encodeURIComponent(name)}&Type=file&Executable=${executable}`\n return doUpload(cozy, data, 'POST', `${path}${query}`, options)\n}\n\nexport function createDirectory (cozy, options) {\n let {name, dirID, lastModifiedDate} = options || {}\n\n if (typeof name !== 'string' || name === '') {\n throw new Error('missing name argument')\n }\n\n if (lastModifiedDate && typeof lastModifiedDate === 'string') {\n lastModifiedDate = new Date(lastModifiedDate)\n }\n\n const path = `/files/${encodeURIComponent(dirID || '')}`\n const query = `?Name=${encodeURIComponent(name)}&Type=directory`\n return cozyFetchJSON(cozy, 'POST', `${path}${query}`, undefined, {\n headers: {\n 'Date': lastModifiedDate ? lastModifiedDate.toGMTString() : ''\n }\n })\n}\n\nexport function updateById (cozy, id, data, options) {\n return doUpload(cozy, data, 'PUT', `/files/${encodeURIComponent(id)}`, options)\n}\n\nfunction doUpdateAttributes (cozy, attrs, path, options) {\n if (!attrs || typeof attrs !== 'object') {\n throw new Error('missing attrs argument')\n }\n\n const {ifMatch} = options || {}\n const body = { data: { attributes: attrs } }\n return cozyFetchJSON(cozy, 'PATCH', path, body, {\n headers: {\n 'If-Match': ifMatch || ''\n }\n })\n}\n\nexport function updateAttributesById (cozy, id, attrs, options) {\n return doUpdateAttributes(cozy, attrs,\n `/files/${encodeURIComponent(id)}`, options)\n}\n\nexport function updateAttributesByPath (cozy, path, attrs, options) {\n return doUpdateAttributes(cozy, attrs,\n `/files/metadata?Path=${encodeURIComponent(path)}`, options)\n}\n\nexport function trashById (cozy, id) {\n if (typeof id !== 'string' || id === '') {\n throw new Error('missing id argument')\n }\n return cozyFetchJSON(cozy, 'DELETE', `/files/${encodeURIComponent(id)}`)\n}\n\nexport function statById (cozy, id, offline = true) {\n if (offline && cozy.offline.hasDatabase(DOCTYPE_FILES)) {\n let db = cozy.offline.getDatabase(DOCTYPE_FILES)\n return Promise.all([\n db.get(id),\n db.find({selector: {'dir_id': id}})\n ]).then(([doc, children]) => {\n children = children.docs.map(doc => {\n return addIsDir(toJsonApi(cozy, doc))\n })\n return addIsDir(toJsonApi(cozy, doc, children))\n })\n }\n return cozyFetchJSON(cozy, 'GET', `/files/${encodeURIComponent(id)}`)\n .then(addIsDir)\n}\n\nexport function statByPath (cozy, path) {\n return cozyFetchJSON(cozy, 'GET', `/files/metadata?Path=${encodeURIComponent(path)}`)\n .then(addIsDir)\n}\n\nexport function downloadById (cozy, id) {\n return cozyFetch(cozy, `/files/download/${encodeURIComponent(id)}`)\n}\n\nexport function downloadByPath (cozy, path) {\n return cozyFetch(cozy, `/files/download?Path=${encodeURIComponent(path)}`)\n}\n\nfunction extractResponseLinkRelated (res) {\n let href = res.links && res.links.related\n if (!href) throw new Error('No related link in server response')\n return href\n}\n\nexport function getDowloadLink (cozy, path) {\n return cozyFetchJSON(cozy, 'POST', `/files/downloads?Path=${encodeURIComponent(path)}`)\n .then(extractResponseLinkRelated)\n}\n\nexport function getArchiveLink (cozy, paths, name = 'files') {\n const archive = {\n type: 'io.cozy.archives',\n attributes: {\n name: name,\n files: paths\n }\n }\n return cozyFetchJSON(cozy, 'POST', `/files/archive`, {data: archive})\n .then(extractResponseLinkRelated)\n}\n\nexport function listTrash (cozy) {\n return cozyFetchJSON(cozy, 'GET', `/files/trash`)\n}\n\nexport function clearTrash (cozy) {\n return cozyFetchJSON(cozy, 'DELETE', `/files/trash`)\n}\n\nexport function restoreById (cozy, id) {\n return cozyFetchJSON(cozy, 'POST', `/files/trash/${encodeURIComponent(id)}`)\n}\n\nexport function destroyById (cozy, id) {\n return cozyFetchJSON(cozy, 'DELETE', `/files/trash/${encodeURIComponent(id)}`)\n}\n\nfunction addIsDir (obj) {\n obj.isDir = obj.attributes.type === 'directory'\n return obj\n}\n\nfunction toJsonApi (cozy, doc, contents = []) {\n let clone = JSON.parse(JSON.stringify(doc))\n delete clone._id\n delete clone._rev\n return {\n _id: doc._id,\n _rev: doc._rev,\n _type: DOCTYPE_FILES,\n attributes: clone,\n relations: (name) => {\n if (name === 'contents') {\n return contents\n }\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/files.js","import PouchDB from 'pouchdb'\nimport pouchdbFind from 'pouchdb-find'\nimport { DOCTYPE_FILES } from './doctypes'\n\nlet pluginLoaded = false\n\nexport function init (cozy, { options = {}, doctypes = [], timer }) {\n for (let doctype of doctypes) {\n createDatabase(cozy, doctype, options)\n }\n if (timer !== undefined) { startAllSync(cozy, timer) }\n}\n\nexport function createDatabase (cozy, doctype, options = {}, timer) {\n if (!pluginLoaded) {\n PouchDB.plugin(pouchdbFind)\n pluginLoaded = true\n }\n cozy._offline = cozy._offline || []\n cozy._offline[doctype] = cozy._offline[doctype] || {}\n let offline = cozy._offline[doctype]\n if (offline && offline.database) { return offline.database }\n offline.database = new PouchDB(doctype, options)\n offline.timer = timer\n offline.autoSync = null\n if (timer !== undefined) { startSync(cozy, doctype, timer) }\n createIndexes(cozy, offline.database, doctype)\n return offline.database\n}\n\nexport function hasDatabase (cozy, doctype) {\n return cozy._offline !== null &&\n doctype in cozy._offline &&\n cozy._offline[doctype].database !== undefined\n}\n\nexport function getDatabase (cozy, doctype) {\n if (hasDatabase(cozy, doctype)) {\n return cozy._offline[doctype].database\n }\n return\n}\n\nexport function destroyDatabase (cozy, doctype) {\n if (hasDatabase(cozy, doctype)) {\n stopSync(cozy, doctype)\n getDatabase(cozy, doctype).destroy()\n delete getDatabase(cozy, doctype)\n }\n}\n\nexport function destroyAllDatabase (cozy) {\n getDoctypes(cozy).forEach(doctype => destroyDatabase(cozy, doctype))\n}\n\nexport function getDoctypes (cozy) {\n if (cozy._offline === null) { return [] }\n return Object.keys(cozy._offline)\n}\n\n//\n// SYNC\n//\n\nexport function startAllSync (cozy, timer) {\n if (timer) {\n const doctypes = getDoctypes(cozy)\n doctypes.forEach((doctype) => {\n startSync(cozy, doctype, timer)\n })\n }\n}\n\nexport function stopAllSync (cozy) {\n const doctypes = getDoctypes(cozy)\n doctypes.forEach((doctype) => {\n stopSync(cozy, doctype)\n })\n}\n\nexport function startSync (cozy, doctype, timer) {\n // TODO: add timer limitation for not flooding Gozy\n if (hasDatabase(cozy, doctype)) {\n if (hasSync(cozy, doctype)) {\n if (timer === cozy._offline[doctype].timer) {\n return\n }\n stopSync(cozy, doctype)\n }\n let offline = cozy._offline[doctype]\n offline.timer = timer\n offline.autoSync = setInterval(() => {\n if (offline.replicate === undefined) {\n replicateFromCozy(cozy, doctype)\n // TODO: add replicationToCozy\n }\n }, timer * 1000)\n }\n}\n\nexport function hasSync (cozy, doctype) {\n return cozy._offline !== null &&\n doctype in cozy._offline &&\n cozy._offline[doctype].autoSync !== null\n}\n\nexport function stopSync (cozy, doctype) {\n if (hasSync(cozy, doctype)) {\n let offline = cozy._offline[doctype]\n clearInterval(offline.autoSync)\n delete offline.autoSync\n if (offline.replication) { offline.replication.cancel() }\n }\n}\n\nexport function replicateFromCozy (cozy, doctype, options = {}) {\n if (hasDatabase(cozy, doctype)) {\n if (options.live === true) {\n return Promise.reject(new Error('You can\\'t use `live` option with Cozy couchdb.'))\n }\n if (options.manualAuthCredentials) {\n return Promise.resolve(replicateFromCozyWithAuth(cozy, doctype, options, options.manualAuthCredentials))\n } else {\n return cozy.authorize().then((credentials) => {\n return replicateFromCozyWithAuth(cozy, doctype, options, credentials)\n })\n }\n } else {\n return Promise.reject(new Error(`You should add this doctype: ${doctype} to offline.`))\n }\n}\n\nexport function replicateFromCozyWithAuth (cozy, doctype, options, credentials) {\n let basic = credentials.token.toBasicAuth()\n let url = (cozy._url + '/data/' + doctype).replace('//', `//${basic}`)\n let db = getDatabase(cozy, doctype)\n let offline = cozy._offline[doctype]\n offline.replication = db.replicate.from(url, options).on('complete', () => {\n offline.replication = undefined\n })\n return offline.replication\n}\n\nfunction createIndexes (cozy, db, doctype) {\n if (doctype === DOCTYPE_FILES) {\n db.createIndex({index: {fields: ['dir_id']}})\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/offline.js","module.exports = require(\"pouchdb\");\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"pouchdb\"\n// module id = 16\n// module chunks = 0","module.exports = require(\"pouchdb-find\");\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"pouchdb-find\"\n// module id = 17\n// module chunks = 0","import {cozyFetchJSON} from './fetch'\n\nexport function diskUsage (cozy) {\n return cozyFetchJSON(cozy, 'GET', `/settings/disk-usage`)\n}\n\nexport function changePassphrase (cozy, currentPassPhrase, newPassPhrase) {\n return cozyFetchJSON(cozy, 'PUT', `/settings/passphrase`, {\n current_passphrase: currentPassPhrase,\n new_passphrase: newPassPhrase\n })\n}\n\nexport function getInstance (cozy) {\n return cozyFetchJSON(cozy, 'GET', `/settings/instance`)\n}\n\nexport function updateInstance (cozy, instance) {\n return cozyFetchJSON(cozy, 'PUT', `/settings/instance`, instance)\n}\n\nexport function getClients (cozy) {\n return cozyFetchJSON(cozy, 'GET', `/settings/clients`)\n}\n\nexport function deleteClientById (cozy, id) {\n return cozyFetchJSON(cozy, 'DELETE', `/settings/clients/${id}`)\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/settings.js","import {cozyFetchJSON} from './fetch'\nimport { DOCTYPE_FILES } from './doctypes'\n\nexport function addReferencedFiles (cozy, doc, ids) {\n if (!doc) throw new Error('missing doc argument')\n if (!Array.isArray(ids)) ids = [ids]\n\n const refs = ids.map((id) => ({type: DOCTYPE_FILES, id: id}))\n\n return cozyFetchJSON(cozy, 'POST', makeReferencesPath(doc), {data: refs})\n}\n\nexport function listReferencedFiles (cozy, doc) {\n if (!doc) throw new Error('missing doc argument')\n return cozyFetchJSON(cozy, 'GET', makeReferencesPath(doc))\n .then((files) => files.map((file) => file._id))\n}\n\nfunction makeReferencesPath (doc) {\n const type = encodeURIComponent(doc._type)\n const id = encodeURIComponent(doc._id)\n return `/data/${type}/${id}/relationships/references`\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/relations.js"],"sourceRoot":""} \ No newline at end of file +{"version":3,"sources":["webpack:///webpack/bootstrap 9fb56e9c1587c70b1ae8","webpack:///external \"isomorphic-fetch\"","webpack:///./src/index.js","webpack:///./src/utils.js","webpack:///./src/auth_storage.js","webpack:///./src/auth_v2.js","webpack:///external \"btoa\"","webpack:///./src/auth_v3.js","webpack:///./src/fetch.js","webpack:///./src/jsonapi.js","webpack:///external \"crypto\"","webpack:///./src/data.js","webpack:///./src/doctypes.js","webpack:///./src/mango.js","webpack:///./src/files.js","webpack:///./src/offline.js","webpack:///external \"pouchdb\"","webpack:///external \"pouchdb-find\"","webpack:///./src/settings.js","webpack:///./src/relations.js"],"names":["auth","data","mango","files","offline","settings","relations","AppTokenV3","AppToken","AccessTokenV3","AccessToken","ClientV3","Client","AuthNone","AuthRunning","AuthError","AuthOK","defaultClientParams","softwareID","dataProto","create","find","update","delete","_delete","updateAttributes","changesFeed","defineIndex","query","addReferencedFiles","listReferencedFiles","destroy","authProto","client","registerClient","updateClient","unregisterClient","getClient","getAuthCodeURL","getAccessToken","refreshToken","filesProto","createDirectory","updateById","updateAttributesById","updateAttributesByPath","trashById","statById","statByPath","downloadById","downloadByPath","getDowloadLink","getArchiveLink","listTrash","clearTrash","restoreById","destroyById","offlineProto","init","getDoctypes","hasDatabase","getDatabase","createDatabase","destroyDatabase","destroyAllDatabase","hasReplication","replicateFromCozy","stopReplication","stopAllReplication","hasRepeatedReplication","startRepeatedReplication","stopRepeatedReplication","stopAllRepeatedReplication","settingsProto","diskUsage","changePassphrase","getInstance","updateInstance","getClients","deleteClientById","options","AppTokenV2","LocalStorage","MemoryStorage","_inited","_oauth","_token","_authstate","_authcreds","_storage","_version","_offline","token","oauth","Error","storage","_clientParams","Object","assign","clientParams","_onRegistered","onRegistered","nopOnRegistered","url","cozyURL","length","slice","_url","disablePromises","addToProto","state","isV2","then","oauthFlow","Promise","resolve","creds","save","CredsKey","path","pathprefix","fetch","res","ok","json","status","datasystem","undefined","protoify","context","fn","prototyped","args","ctx","obj","proto","attr","module","exports","unpromiser","isPromise","sleep","retry","getFuzzedDelay","getBackedoffDelay","createPath","encodeQuery","decodeQuery","warn","FuzzFactor","value","apply","l","cb","err","time","setTimeout","count","delay","doTry","catch","retryDelay","fuzzingFactor","Math","random","retryCount","pow","cozy","doctype","id","route","encodeURIComponent","q","qname","queryIndex","indexOf","queries","fragIndex","queryStr","parts","split","i","pair","decodeURIComponent","hasOwnProperty","warned","text","push","console","prefix","window","localStorage","key","setItem","JSON","stringify","item","getItem","parse","removeItem","hash","deleted","getAppToken","V2TOKEN_ABORT_TIMEOUT","reject","parent","postMessage","origin","location","intent","action","timeout","receiver","event","appName","e","removeEventListener","clearTimeout","addEventListener","opts","btoa","StateSize","StateKey","clientID","client_id","clientSecret","client_secret","registrationAccessToken","registration_access_token","redirect_uris","redirectURI","software_id","softwareVersion","software_version","clientName","client_name","clientKind","client_kind","clientURI","client_uri","logoURI","logo_uri","policyURI","policy_uri","tokenType","token_type","accessToken","access_token","refresh_token","scope","cli","isRegistered","toRegisterJSON","disableAuth","resetSecret","manualAuthCredentials","createClient","oldClient","newClient","shouldPassRegistration","scopes","generateRandomState","join","pageURL","grantQueries","getGrantCodeFromPageURL","retrieveToken","code","tryCount","clearAndRetry","clear","registerNewClient","all","load","credentials","storedState","isUnauthorized","isNotFound","statePromise","t","body","headers","href","buffer","crypto","getRandomValues","Uint8Array","require","randomBytes","Array","floor","String","fromCharCode","replace","cozyFetch","cozyFetchJSON","fullpath","resp","cozyFetchWithAuth","authorize","handleResponse","toAuthHeader","newToken","saveCredentials","method","handleJSONResponse","contentType","get","FetchError","reason","captureStackTrace","constructor","name","response","indexKey","doc","type","findByRef","resources","ref","handleResource","rawResource","links","resource","_id","_type","_rev","meta","rev","attributes","rels","relationships","isArray","map","handleTopLevel","included","forEach","r","NOREV","docType","changes","tries","normalizeDoctype","DOCTYPE_FILES","KNOWN_DOCTYPES","REVERSE_KNOWN","keys","k","isQualified","known","parseSelector","normalizeSelector","makeMapReduceQuery","fields","defineIndexV2","defineIndexV3","indexRef","queryV2","queryV3","VALUEOPERATORS","LOGICOPERATORS","MAP_TEMPLATE","toLowerCase","emit","FIELDSPLACEHOLDER","toString","COUCHDB_INFINITY","COUCHDB_LOWEST","indexName","capitalize","indexDefinition","makeMapFunction","reduce","use_index","selector","limit","since","descending","sort","f","docs","charAt","toUpperCase","operator","acc","concat","filters","filter","op","field","applySelector","lower","upper","inclusiveEnd","startkey","endkey","inclusive_end","mrquery","firstFreeValueField","normalizedSelector","used","isFreeValue","contentTypeOctetStream","doUpload","ArrayBuffer","isBuffer","isFile","File","isBlob","Blob","isStream","readable","pipe","isString","checksum","lastModifiedDate","ifMatch","Date","toGMTString","dirID","executable","doUpdateAttributes","attrs","db","children","addIsDir","toJsonApi","extractResponseLinkRelated","related","paths","archive","isDir","contents","clone","setDatabase","pluginLoaded","doctypes","getInfo","database","errorDatabase","plugin","createIndexes","createIndex","index","getReplication","replication","setReplication","getReplicationUrl","basic","toBasicAuth","getReplicationPromise","replicationPromise","setReplicationPromise","promise","live","replicate","from","on","info","cancel","stop","getRepeatedReplication","interval","setRepeatedReplication","timer","setInterval","clearInterval","currentPassPhrase","newPassPhrase","current_passphrase","new_passphrase","instance","ids","refs","makeReferencesPath","file"],"mappings":";AAAA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA,uBAAe;AACf;AACA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;;;AAGA;AACA;;AAEA;AACA;;AAEA;AACA;;AAEA;AACA;;;;;;;;;;;;;;;ACtCA,8C;;;;;;;;sjBCAA;;AAEA;;AACA;;AACA;;AACA;;KAAYA,I;;AACZ;;KAAYC,I;;AACZ;;KAAYC,K;;AACZ;;KAAYC,K;;AACZ;;KAAYC,O;;AACZ;;KAAYC,Q;;AACZ;;KAAYC,S;;;;;;KAGAC,U,GAGRP,I,CAHFQ,Q;KACaC,a,GAEXT,I,CAFFU,W;KACQC,Q,GACNX,I,CADFY,M;;;AAGF,KAAMC,WAAW,CAAjB;AACA,KAAMC,cAAc,CAApB;AACA,KAAMC,YAAY,CAAlB;AACA,KAAMC,SAAS,CAAf;;AAEA,KAAMC,sBAAsB;AAC1BC,eAAY;AADc,EAA5B;;AAIA,KAAMC,YAAY;AAChBC,WAAQnB,KAAKmB,MADG;AAEhBC,SAAMpB,KAAKoB,IAFK;AAGhBC,WAAQrB,KAAKqB,MAHG;AAIhBC,WAAQtB,KAAKuB,OAJG;AAKhBC,qBAAkBxB,KAAKwB,gBALP;AAMhBC,gBAAazB,KAAKyB,WANF;AAOhBC,gBAAazB,MAAMyB,WAPH;AAQhBC,UAAO1B,MAAM0B,KARG;AAShBC,uBAAoBvB,UAAUuB,kBATd;AAUhBC,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d,EAAoB,KAApB,EAA2BmT,mBAAmB/J,GAAnB,CAA3B,EACJ3M,IADI,CACC,UAAC7G,KAAD;AAAA,YAAWA,MAAM0U,GAAN,CAAU,UAAC8I,IAAD;AAAA,cAAUA,KAAKvJ,GAAf;AAAA,MAAV,CAAX;AAAA,IADD,CAAP;AAED;;AAED,UAASsJ,kBAAT,CAA6B/J,GAA7B,EAAkC;AAChC,OAAMC,OAAOjJ,mBAAmBgJ,IAAIU,KAAvB,CAAb;AACA,OAAM5J,KAAKE,mBAAmBgJ,IAAIS,GAAvB,CAAX;AACA,qBAAgBR,IAAhB,SAAwBnJ,EAAxB;AACD,E","file":"cozy-client.node.js","sourcesContent":[" \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId])\n \t\t\treturn installedModules[moduleId].exports;\n\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\texports: {},\n \t\t\tid: moduleId,\n \t\t\tloaded: false\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.loaded = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"\";\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(0);\n\n\n\n// WEBPACK FOOTER //\n// webpack/bootstrap 9fb56e9c1587c70b1ae8","module.exports = require(\"isomorphic-fetch\");\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"isomorphic-fetch\"\n// module id = 1\n// module chunks = 0","/* global fetch */\n\nimport {unpromiser, retry, warn} from './utils'\nimport {LocalStorage, MemoryStorage} from './auth_storage'\nimport {AppToken as AppTokenV2, getAppToken as getAppTokenV2} from './auth_v2'\nimport * as auth from './auth_v3'\nimport * as data from './data'\nimport * as mango from './mango'\nimport * as files from './files'\nimport * as offline from './offline'\nimport * as settings from './settings'\nimport * as relations from './relations'\n\nconst {\n AppToken: AppTokenV3,\n AccessToken: AccessTokenV3,\n Client: ClientV3\n} = auth\n\nconst AuthNone = 0\nconst AuthRunning = 1\nconst AuthError = 2\nconst AuthOK = 3\n\nconst defaultClientParams = {\n softwareID: 'github.com/cozy/cozy-client-js'\n}\n\nconst dataProto = {\n create: data.create,\n find: data.find,\n update: data.update,\n delete: data._delete,\n updateAttributes: data.updateAttributes,\n changesFeed: data.changesFeed,\n defineIndex: mango.defineIndex,\n query: mango.query,\n addReferencedFiles: relations.addReferencedFiles,\n listReferencedFiles: relations.listReferencedFiles,\n destroy: function (...args) {\n warn('destroy is deprecated, use cozy.data.delete instead.')\n return data._delete(...args)\n }\n}\n\nconst authProto = {\n client: auth.client,\n registerClient: auth.registerClient,\n updateClient: auth.updateClient,\n unregisterClient: auth.unregisterClient,\n getClient: auth.getClient,\n getAuthCodeURL: auth.getAuthCodeURL,\n getAccessToken: auth.getAccessToken,\n refreshToken: auth.refreshToken\n}\n\nconst filesProto = {\n create: files.create,\n createDirectory: files.createDirectory,\n updateById: files.updateById,\n updateAttributesById: files.updateAttributesById,\n updateAttributesByPath: files.updateAttributesByPath,\n trashById: files.trashById,\n statById: files.statById,\n statByPath: files.statByPath,\n downloadById: files.downloadById,\n downloadByPath: files.downloadByPath,\n getDowloadLink: files.getDowloadLink,\n getArchiveLink: files.getArchiveLink,\n listTrash: files.listTrash,\n clearTrash: files.clearTrash,\n restoreById: files.restoreById,\n destroyById: files.destroyById\n}\n\nconst offlineProto = {\n init: offline.init,\n getDoctypes: offline.getDoctypes,\n // database\n hasDatabase: offline.hasDatabase,\n getDatabase: offline.getDatabase,\n createDatabase: offline.createDatabase,\n destroyDatabase: offline.destroyDatabase,\n destroyAllDatabase: offline.destroyAllDatabase,\n // replication\n hasReplication: offline.hasReplication,\n replicateFromCozy: offline.replicateFromCozy,\n stopReplication: offline.stopReplication,\n stopAllReplication: offline.stopAllReplication,\n // repeated replication\n hasRepeatedReplication: offline.hasRepeatedReplication,\n startRepeatedReplication: offline.startRepeatedReplication,\n stopRepeatedReplication: offline.stopRepeatedReplication,\n stopAllRepeatedReplication: offline.stopAllRepeatedReplication\n}\n\nconst settingsProto = {\n diskUsage: settings.diskUsage,\n changePassphrase: settings.changePassphrase,\n getInstance: settings.getInstance,\n updateInstance: settings.updateInstance,\n getClients: settings.getClients,\n deleteClientById: settings.deleteClientById\n}\n\nclass Client {\n constructor (options) {\n this.data = {}\n this.files = {}\n this.offline = {}\n this.settings = {}\n this.auth = {\n Client: ClientV3,\n AccessToken: AccessTokenV3,\n AppToken: AppTokenV3,\n AppTokenV2: AppTokenV2,\n LocalStorage: LocalStorage,\n MemoryStorage: MemoryStorage\n }\n this._inited = false\n if (options) {\n this.init(options)\n }\n }\n\n init (options = {}) {\n this._inited = true\n this._oauth = false // is oauth activated or not\n this._token = null // application token\n this._authstate = AuthNone\n this._authcreds = null\n this._storage = null\n this._version = null\n this._offline = null\n\n const token = options.token\n const oauth = options.oauth\n if (token && oauth) {\n throw new Error('Cannot specify an application token with a oauth activated')\n }\n\n if (token) {\n this._token = new AppTokenV3({ token })\n } else if (oauth) {\n this._oauth = true\n this._storage = oauth.storage\n this._clientParams = Object.assign({}, defaultClientParams, oauth.clientParams)\n this._onRegistered = oauth.onRegistered || nopOnRegistered\n }\n\n let url = options.cozyURL || ''\n while (url[url.length - 1] === '/') {\n url = url.slice(0, -1)\n }\n\n this._url = url\n\n const disablePromises = !!options.disablePromises\n addToProto(this, this.data, dataProto, disablePromises)\n addToProto(this, this.auth, authProto, disablePromises)\n addToProto(this, this.files, filesProto, disablePromises)\n addToProto(this, this.offline, offlineProto, disablePromises)\n addToProto(this, this.settings, settingsProto, disablePromises)\n\n if (options.offline) {\n this.offline.init(options.offline)\n }\n }\n\n authorize () {\n const state = this._authstate\n if (state === AuthOK || state === AuthRunning) {\n return this._authcreds\n }\n\n this._authstate = AuthRunning\n this._authcreds = this.isV2().then((isV2) => {\n if (isV2 && this._oauth) {\n throw new Error('OAuth is not supported on the V2 stack')\n }\n if (this._oauth) {\n return auth.oauthFlow(\n this,\n this._storage,\n this._clientParams,\n this._onRegistered\n )\n }\n // we expect to be on a client side application running in a browser\n // with cookie-based authentication.\n if (isV2) {\n return getAppTokenV2()\n } else if (this._token) {\n return Promise.resolve({client: null, token: this._token})\n } else {\n throw new Error('Missing application token')\n }\n })\n\n this._authcreds.then(\n () => { this._authstate = AuthOK },\n () => { this._authstate = AuthError })\n\n return this._authcreds\n }\n\n saveCredentials (client, token) {\n const creds = {client, token}\n if (!this._storage || this._authstate === AuthRunning) {\n return Promise.resolve(creds)\n }\n this._storage.save(auth.CredsKey, creds)\n this._authcreds = Promise.resolve(creds)\n return this._authcreds\n }\n\n fullpath (path) {\n return this.isV2().then((isV2) => {\n const pathprefix = isV2 ? '/ds-api' : ''\n return this._url + pathprefix + path\n })\n }\n\n isV2 () {\n if (!this._version) {\n this._version = retry(() => fetch(`${this._url}/status/`), 3)()\n .then((res) => {\n if (!res.ok) {\n throw new Error('Could not fetch cozy status')\n } else {\n return res.json()\n }\n })\n .then((status) => status.datasystem !== undefined)\n }\n return this._version\n }\n}\n\nfunction nopOnRegistered () {\n throw new Error('Missing onRegistered callback')\n}\n\nfunction protoify (context, fn) {\n return function prototyped (...args) {\n return fn(context, ...args)\n }\n}\n\nfunction addToProto (ctx, obj, proto, disablePromises) {\n for (const attr in proto) {\n let fn = protoify(ctx, proto[attr])\n if (disablePromises) {\n fn = unpromiser(fn)\n }\n obj[attr] = fn\n }\n}\n\nmodule.exports = new Client()\nObject.assign(module.exports, {Client, LocalStorage, MemoryStorage})\n\n\n\n// WEBPACK FOOTER //\n// ./src/index.js","const FuzzFactor = 0.3\n\nexport function unpromiser (fn) {\n return function (...args) {\n const value = fn.apply(this, args)\n if (!isPromise(value)) {\n return value\n }\n const l = args.length\n if (l === 0 || typeof args[l - 1] !== 'function') {\n return\n }\n const cb = args[l - 1]\n value.then(\n (res) => cb(null, res),\n (err) => cb(err, null)\n )\n return\n }\n}\n\nexport function isPromise (value) {\n return !!value && typeof value.then === 'function'\n}\n\nexport function sleep (time, args) {\n return new Promise((resolve) => {\n setTimeout(resolve, time, args)\n })\n}\n\nexport function retry (fn, count, delay = 300) {\n return function doTry (...args) {\n return fn(...args).catch((err) => {\n if (--count < 0) {\n throw err\n }\n return sleep(getBackedoffDelay(delay, count))\n .then(() => doTry(...args))\n })\n }\n}\n\nexport function getFuzzedDelay (retryDelay) {\n const fuzzingFactor = ((Math.random() * 2) - 1) * FuzzFactor\n return retryDelay * (1.0 + fuzzingFactor)\n}\n\nexport function getBackedoffDelay (retryDelay, retryCount = 1) {\n return getFuzzedDelay(retryDelay * Math.pow(2, retryCount - 1))\n}\n\nexport function createPath (cozy, isV2, doctype, id = '', query = null) {\n let route = '/data/'\n if (!isV2) {\n route += `${encodeURIComponent(doctype)}/`\n }\n if (id !== '') {\n route += encodeURIComponent(id)\n }\n const q = encodeQuery(query)\n if (q !== '') {\n route += '?' + q\n }\n return route\n}\n\nexport function encodeQuery (query) {\n if (!query) {\n return ''\n }\n let q = ''\n for (const qname in query) {\n if (q !== '') {\n q += '&'\n }\n q += `${encodeURIComponent(qname)}=${encodeURIComponent(query[qname])}`\n }\n return q\n}\n\nexport function decodeQuery (url) {\n let queryIndex = url.indexOf('?')\n if (queryIndex < 0) {\n queryIndex = url.length\n }\n const queries = {}\n let fragIndex = url.indexOf('#')\n if (fragIndex < 0) {\n fragIndex = url.length\n }\n if (fragIndex < queryIndex) {\n return queries\n }\n const queryStr = url.slice(queryIndex + 1, fragIndex)\n if (queryStr === '') {\n return queries\n }\n const parts = queryStr.split('&')\n for (let i = 0; i < parts.length; i++) {\n let pair = parts[i].split('=')\n if (pair.length === 0 || pair[0] === '') {\n continue\n }\n const qname = decodeURIComponent(pair[0])\n if (queries.hasOwnProperty(qname)) {\n continue\n }\n if (pair.length === 1) {\n queries[qname] = true\n } else if (pair.length === 2) {\n queries[qname] = decodeURIComponent(pair[1])\n } else {\n throw new Error('Malformed URL')\n }\n }\n return queries\n}\n\nconst warned = []\nexport function warn (text) {\n if (warned.indexOf(text) === -1) {\n warned.push(text)\n console.warn('cozy-client-js', text)\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils.js","export class LocalStorage {\n constructor (storage, prefix) {\n if (!storage && typeof window !== 'undefined') {\n storage = window.localStorage\n }\n this.storage = storage\n this.prefix = prefix || 'cozy:oauth:'\n }\n\n save (key, value) {\n return new Promise(resolve => {\n this.storage.setItem(this.prefix + key, JSON.stringify(value))\n resolve(value)\n })\n }\n\n load (key) {\n return new Promise(resolve => {\n const item = this.storage.getItem(this.prefix + key)\n if (!item) {\n resolve()\n } else {\n resolve(JSON.parse(item))\n }\n })\n }\n\n delete (key) {\n return new Promise(resolve => resolve(\n this.storage.removeItem(this.prefix + key)))\n }\n\n clear () {\n return new Promise(resolve => {\n const storage = this.storage\n for (let i = 0; i < storage.length; i++) {\n const key = storage.key(i)\n if (key.indexOf(this.prefix) === 0) {\n storage.removeItem(key)\n }\n }\n resolve()\n })\n }\n}\n\nexport class MemoryStorage {\n constructor () {\n this.hash = Object.create(null)\n }\n\n save (key, value) {\n this.hash[key] = value\n return Promise.resolve(value)\n }\n\n load (key) {\n return Promise.resolve(this.hash[key])\n }\n\n delete (key) {\n const deleted = delete this.hash[key]\n return Promise.resolve(deleted)\n }\n\n clear () {\n this.hash = Object.create(null)\n return Promise.resolve()\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/auth_storage.js","/* global btoa */\nconst V2TOKEN_ABORT_TIMEOUT = 3000\n\nexport function getAppToken () {\n return new Promise(function (resolve, reject) {\n if (typeof window === 'undefined') {\n return reject(new Error('getV2Token should be used in browser'))\n } else if (!window.parent) {\n return reject(new Error('getV2Token should be used in iframe'))\n } else if (!window.parent.postMessage) {\n return reject(new Error('getV2Token should be used in modern browser'))\n }\n const origin = window.location.origin\n const intent = {action: 'getToken'}\n let timeout = null\n const receiver = function (event) {\n let token\n try {\n token = new AppToken({\n appName: event.data.appName,\n token: event.data.token\n })\n } catch (e) {\n reject(e)\n return\n }\n window.removeEventListener('message', receiver)\n clearTimeout(timeout)\n resolve({ client: null, token })\n }\n window.addEventListener('message', receiver, false)\n window.parent.postMessage(intent, origin)\n timeout = setTimeout(() => {\n reject(new Error('No response from parent iframe after 3s'))\n }, V2TOKEN_ABORT_TIMEOUT)\n })\n}\n\nexport class AppToken {\n constructor (opts) {\n this.appName = opts.appName || ''\n this.token = opts.token || ''\n }\n\n toAuthHeader () {\n return 'Basic ' + btoa(`${this.appName}:${this.token}`)\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/auth_v2.js","module.exports = require(\"btoa\");\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"btoa\"\n// module id = 6\n// module chunks = 0","/* global btoa */\nimport {encodeQuery, decodeQuery} from './utils'\nimport {cozyFetchJSON, FetchError} from './fetch'\n\nconst StateSize = 16\n\nexport const CredsKey = 'creds'\nexport const StateKey = 'state'\n\nexport class Client {\n constructor (opts) {\n this.clientID = opts.clientID || opts.client_id || ''\n this.clientSecret = opts.clientSecret || opts.client_secret || ''\n this.registrationAccessToken = opts.registrationAccessToken || opts.registration_access_token || ''\n\n if (opts.redirect_uris) {\n this.redirectURI = opts.redirect_uris[0] || ''\n } else {\n this.redirectURI = opts.redirectURI || ''\n }\n\n this.softwareID = opts.softwareID || opts.software_id || ''\n this.softwareVersion = opts.softwareVersion || opts.software_version || ''\n this.clientName = opts.clientName || opts.client_name || ''\n this.clientKind = opts.clientKind || opts.client_kind || ''\n this.clientURI = opts.clientURI || opts.client_uri || ''\n\n this.logoURI = opts.logoURI || opts.logo_uri || ''\n this.policyURI = opts.policyURI || opts.policy_uri || ''\n\n if (!this.registrationAccessToken) {\n if (this.redirectURI === '') {\n throw new Error('Missing redirectURI field')\n }\n if (this.softwareID === '') {\n throw new Error('Missing softwareID field')\n }\n if (this.clientName === '') {\n throw new Error('Missing clientName field')\n }\n }\n }\n\n isRegistered () {\n return this.clientID !== ''\n }\n\n toRegisterJSON () {\n return {\n redirect_uris: [this.redirectURI],\n software_id: this.softwareID,\n software_version: this.softwareVersion,\n client_name: this.clientName,\n client_kind: this.clientKind,\n client_uri: this.clientURI,\n logo_uri: this.logoURI,\n policy_uri: this.policyURI\n }\n }\n\n toAuthHeader () {\n return 'Bearer ' + this.registrationAccessToken\n }\n}\n\nexport class AccessToken {\n constructor (opts) {\n this.tokenType = opts.tokenType || opts.token_type\n this.accessToken = opts.accessToken || opts.access_token\n this.refreshToken = opts.refreshToken || opts.refresh_token\n this.scope = opts.scope\n }\n\n toAuthHeader () {\n return 'Bearer ' + this.accessToken\n }\n\n toBasicAuth () {\n return `user:${this.accessToken}@`\n }\n}\n\nexport class AppToken {\n constructor (opts) {\n this.token = opts.token || ''\n }\n\n toAuthHeader () {\n return 'Bearer ' + this.token\n }\n\n toBasicAuth () {\n return `user:${this.token}@`\n }\n}\n\nexport function client (cozy, clientParams) {\n if (!clientParams) {\n clientParams = cozy._clientParams\n }\n if (clientParams instanceof Client) {\n return clientParams\n }\n return new Client(clientParams)\n}\n\nexport function registerClient (cozy, clientParams) {\n const cli = client(cozy, clientParams)\n if (cli.isRegistered()) {\n return Promise.reject(new Error('Client already registered'))\n }\n return cozyFetchJSON(cozy, 'POST', '/auth/register', cli.toRegisterJSON(), {\n disableAuth: true\n })\n .then((data) => new Client(data))\n}\n\nexport function updateClient (cozy, clientParams, resetSecret = false) {\n const cli = client(cozy, clientParams)\n if (!cli.isRegistered()) {\n return Promise.reject(new Error('Client not registered'))\n }\n let data = cli.toRegisterJSON()\n data.client_id = cli.clientID\n if (resetSecret) data.client_secret = cli.clientSecret\n\n return cozyFetchJSON(cozy, 'PUT', `/auth/register/${cli.clientID}`, data, {\n manualAuthCredentials: {\n token: cli\n }\n }).then((data) => createClient(data, cli))\n}\n\nexport function unregisterClient (cozy, clientParams) {\n const cli = client(cozy, clientParams)\n if (!cli.isRegistered()) {\n return Promise.reject(new Error('Client not registered'))\n }\n return cozyFetchJSON(cozy, 'DELETE', `/auth/register/${cli.clientID}`, null, {\n manualAuthCredentials: {\n token: cli\n }\n })\n}\n\n// getClient will retrive the registered client informations from the server.\nexport function getClient (cozy, clientParams) {\n const cli = client(cozy, clientParams)\n if (!cli.isRegistered()) {\n return Promise.reject(new Error('Client not registered'))\n }\n return cozyFetchJSON(cozy, 'GET', `/auth/register/${cli.clientID}`, null, {\n manualAuthCredentials: {\n token: cli\n }\n })\n .then((data) => createClient(data, cli))\n}\n\n// createClient returns a new Client instance given on object containing the\n// data of the client, from the API, and an old instance of the client.\nfunction createClient (data, oldClient) {\n const newClient = new Client(data)\n // we need to keep track of the registrationAccessToken since it is send\n // only on registration. The GET /auth/register/:client-id endpoint does\n // not return this token.\n const shouldPassRegistration = (\n !!oldClient &&\n oldClient.registrationAccessToken !== '' &&\n newClient.registrationAccessToken === ''\n )\n if (shouldPassRegistration) {\n newClient.registrationAccessToken = oldClient.registrationAccessToken\n }\n return newClient\n}\n\n// getAuthCodeURL returns a pair {authURL,state} given a registered client. The\n// state should be stored in order to be checked against on the user validation\n// phase.\nexport function getAuthCodeURL (cozy, client, scopes = []) {\n if (!(client instanceof Client)) {\n client = new Client(client)\n }\n if (!client.isRegistered()) {\n throw new Error('Client not registered')\n }\n const state = generateRandomState()\n const query = {\n 'client_id': client.clientID,\n 'redirect_uri': client.redirectURI,\n 'state': state,\n 'response_type': 'code',\n 'scope': scopes.join(' ')\n }\n return {\n url: cozy._url + `/auth/authorize?${encodeQuery(query)}`,\n state: state\n }\n}\n\n// getAccessToken perform a request on the access_token entrypoint with the\n// authorization_code grant type in order to generate a new access token for a\n// newly registered client.\n//\n// This method extracts the access code and state from the given URL. By\n// default it uses window.location.href. Also, it checks the given state with\n// the one specified in the URL query parameter to prevent CSRF attacks.\nexport function getAccessToken (cozy, client, state, pageURL = '') {\n if (!state) {\n return Promise.reject(new Error('Missing state value'))\n }\n const grantQueries = getGrantCodeFromPageURL(pageURL)\n if (grantQueries === null) {\n return Promise.reject(new Error('Missing states from current URL'))\n }\n if (state !== grantQueries.state) {\n return Promise.reject(new Error('Given state does not match url query state'))\n }\n return retrieveToken(cozy, client, null, {\n 'grant_type': 'authorization_code',\n 'code': grantQueries.code\n })\n}\n\n// refreshToken perform a request on the access_token entrypoint with the\n// refresh_token grant type in order to refresh the given token.\nexport function refreshToken (cozy, client, token) {\n return retrieveToken(cozy, client, token, {\n 'grant_type': 'refresh_token',\n 'refresh_token': token.refreshToken\n })\n}\n\n// oauthFlow performs the stateful registration and access granting of an OAuth\n// client.\nexport function oauthFlow (cozy, storage, clientParams, onRegistered) {\n let tryCount = 0\n\n function clearAndRetry (err) {\n if (tryCount++ > 0) {\n throw err\n }\n return storage.clear().then(() =>\n oauthFlow(cozy, storage, clientParams, onRegistered))\n }\n\n function registerNewClient () {\n return storage.clear()\n .then(() => registerClient(cozy, clientParams))\n .then((client) => {\n const {url, state} = getAuthCodeURL(cozy, client, clientParams.scopes)\n return storage.save(StateKey, {client, url, state})\n })\n }\n\n return Promise.all([\n storage.load(CredsKey),\n storage.load(StateKey)\n ])\n .then(([credentials, storedState]) => {\n // If credentials are cached we re-fetch the registered client with the\n // said token. Fetching the client, if the token is outdated we should try\n // the token is refreshed.\n if (credentials) {\n let oldClient, token\n try {\n oldClient = new Client(credentials.client)\n token = new AccessToken(credentials.token)\n } catch (err) {\n // bad cache, we should clear and retry the process\n return clearAndRetry(err)\n }\n return getClient(cozy, oldClient)\n .then((client) => ({client, token}))\n .catch((err) => {\n // If we fall into an error while fetching the client (because of a\n // bad connectivity for instance), we do not bail the whole process\n // since the client should be able to continue with the persisted\n // client and token.\n //\n // If it is an explicit Unauthorized error though, we bail, clear th\n // cache and retry.\n if (FetchError.isUnauthorized(err) || FetchError.isNotFound(err)) {\n throw new Error('Client has been revoked')\n }\n return { client: oldClient, token }\n })\n }\n\n // Otherwise register a new client if necessary (ie. no client is stored)\n // and call the onRegistered callback to wait for the user to grant the\n // access. Finally fetches to access token on success.\n let statePromise\n if (!storedState) {\n statePromise = registerNewClient()\n } else {\n statePromise = Promise.resolve(storedState)\n }\n\n let client, state, token\n return statePromise\n .then((data) => {\n client = data.client\n state = data.state\n return Promise.resolve(onRegistered(client, data.url))\n })\n .then((pageURL) => getAccessToken(cozy, client, state, pageURL))\n .then((t) => { token = t })\n .then(() => storage.delete(StateKey))\n .then(() => ({client, token}))\n })\n .then(\n (creds) => storage.save(CredsKey, creds),\n (err) => {\n if (FetchError.isUnauthorized(err)) {\n return clearAndRetry(err)\n } else {\n throw err\n }\n })\n}\n\n// retrieveToken perform a request on the access_token entrypoint in order to\n// fetch a token.\nfunction retrieveToken (cozy, client, token, query) {\n if (!(client instanceof Client)) {\n client = new Client(client)\n }\n if (!client.isRegistered()) {\n return Promise.reject(new Error('Client not registered'))\n }\n const body = encodeQuery(Object.assign({}, query, {\n 'client_id': client.clientID,\n 'client_secret': client.clientSecret\n }))\n return cozyFetchJSON(cozy, 'POST', '/auth/access_token', body, {\n disableAuth: (token === null),\n manualAuthCredentials: { client, token },\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' }\n })\n .then((data) => {\n data.refreshToken = data.refreshToken || query.refresh_token\n return new AccessToken(data)\n })\n}\n\n// getGrantCodeFromPageURL extract the state and access_code query parameters\n// from the given url\nfunction getGrantCodeFromPageURL (pageURL = '') {\n if (pageURL === '' && typeof window !== 'undefined') {\n pageURL = window.location.href\n }\n const queries = decodeQuery(pageURL)\n if (!queries.hasOwnProperty('state')) {\n return null\n }\n return {\n state: queries['state'],\n code: queries['access_code']\n }\n}\n\n// generateRandomState will try to generate a 128bits random value from a secure\n// pseudo random generator. It will fallback on Math.random if it cannot find\n// such generator.\nfunction generateRandomState () {\n let buffer\n if (typeof window !== 'undefined' &&\n typeof window.crypto !== 'undefined' &&\n typeof window.crypto.getRandomValues === 'function') {\n buffer = new Uint8Array(StateSize)\n window.crypto.getRandomValues(buffer)\n } else {\n try {\n buffer = require('crypto').randomBytes(StateSize)\n } catch (e) {}\n }\n if (!buffer) {\n buffer = new Array(StateSize)\n for (let i = 0; i < buffer.length; i++) {\n buffer[i] = Math.floor((Math.random() * 255))\n }\n }\n return btoa(String.fromCharCode.apply(null, buffer))\n .replace(/=+$/, '')\n .replace(/\\//g, '_')\n .replace(/\\+/g, '-')\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/auth_v3.js","/* global fetch */\nimport {refreshToken, AccessToken} from './auth_v3'\nimport {retry} from './utils'\nimport jsonapi from './jsonapi'\n\nexport function cozyFetch (cozy, path, options = {}) {\n return cozy.fullpath(path).then((fullpath) => {\n let resp\n if (options.disableAuth) {\n resp = fetch(fullpath, options)\n } else if (options.manualAuthCredentials) {\n resp = cozyFetchWithAuth(cozy, fullpath, options, options.manualAuthCredentials)\n } else {\n resp = cozy.authorize().then((credentials) =>\n cozyFetchWithAuth(cozy, fullpath, options, credentials))\n }\n return resp.then(handleResponse)\n })\n}\n\nfunction cozyFetchWithAuth (cozy, fullpath, options, credentials) {\n if (credentials) {\n options.headers = options.headers || {}\n options.headers['Authorization'] = credentials.token.toAuthHeader()\n }\n\n // the option credentials:include tells fetch to include the cookies in the\n // request even for cross-origin requests\n options.credentials = 'include'\n\n return Promise.all([\n cozy.isV2(),\n fetch(fullpath, options)\n ]).then(([isV2, res]) => {\n if (res.status !== 401 || isV2 || !credentials) {\n return res\n }\n // we try to refresh the token only for OAuth, ie, the client defined\n // and the token is an instance of AccessToken.\n const { client, token } = credentials\n if (!client || !(token instanceof AccessToken)) {\n return res\n }\n return retry(() => refreshToken(cozy, client, token), 3)()\n .then((newToken) => cozy.saveCredentials(client, newToken))\n .then((credentials) => cozyFetchWithAuth(cozy, fullpath, options, credentials))\n })\n}\n\nexport function cozyFetchJSON (cozy, method, path, body, options = {}) {\n options.method = method\n\n const headers = options.headers = options.headers || {}\n\n headers['Accept'] = 'application/json'\n\n if (method !== 'GET' && method !== 'HEAD' && body !== undefined) {\n if (headers['Content-Type']) {\n options.body = body\n } else {\n headers['Content-Type'] = 'application/json'\n options.body = JSON.stringify(body)\n }\n }\n\n return cozyFetch(cozy, path, options)\n .then(handleJSONResponse)\n}\n\nfunction handleResponse (res) {\n if (res.ok) {\n return res\n }\n let data\n const contentType = res.headers.get('content-type')\n if (contentType && contentType.indexOf('json') >= 0) {\n data = res.json()\n } else {\n data = res.text()\n }\n return data.then(err => {\n throw new FetchError(res, err)\n })\n}\n\nfunction handleJSONResponse (res) {\n const contentType = res.headers.get('content-type')\n if (!contentType || contentType.indexOf('json') < 0) {\n return res.text((data) => {\n throw new FetchError(res, new Error('Response is not JSON: ' + data))\n })\n }\n\n const json = res.json()\n if (contentType.indexOf('application/vnd.api+json') === 0) {\n return json.then(jsonapi)\n } else {\n return json\n }\n}\n\nexport class FetchError extends Error {\n constructor (res, reason) {\n super()\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor)\n }\n // XXX We have to hardcode this because babel doesn't play nice when extending Error\n this.name = 'FetchError'\n this.response = res\n this.url = res.url\n this.status = res.status\n this.reason = reason\n }\n}\n\nFetchError.isUnauthorized = function (err) {\n // XXX We can't use err instanceof FetchError because of the caveats of babel\n return err.name === 'FetchError' && err.status === 401\n}\n\nFetchError.isNotFound = function (err) {\n // XXX We can't use err instanceof FetchError because of the caveats of babel\n return err.name === 'FetchError' && err.status === 404\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/fetch.js","function indexKey (doc) {\n return doc.type + '/' + doc.id\n}\n\nfunction findByRef (resources, ref) {\n return resources[indexKey(ref)]\n}\n\nfunction handleResource (rawResource, resources, links) {\n let resource = {\n _id: rawResource.id,\n _type: rawResource.type,\n _rev: (rawResource.meta && rawResource.meta.rev),\n links: Object.assign({}, rawResource.links, links),\n attributes: rawResource.attributes,\n relations: (name) => {\n let rels = rawResource.relationships[name]\n if (rels === undefined || rels.data === undefined) return undefined\n if (rels.data === null) return null\n if (!Array.isArray(rels.data)) return findByRef(resources, rels.data)\n return rels.data.map(ref => findByRef(resources, ref))\n }\n }\n\n resources[indexKey(rawResource)] = resource\n\n return resource\n}\n\nfunction handleTopLevel (doc, resources = {}) {\n // build an index of included resource by Type & ID\n const included = doc.included\n\n if (Array.isArray(included)) {\n included.forEach((r) => handleResource(r, resources, doc.links))\n }\n\n if (Array.isArray(doc.data)) {\n return doc.data.map((r) => handleResource(r, resources, doc.links))\n } else {\n return handleResource(doc.data, resources, doc.links)\n }\n}\n\nexport default handleTopLevel\n\n\n\n// WEBPACK FOOTER //\n// ./src/jsonapi.js","module.exports = require(\"crypto\");\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"crypto\"\n// module id = 10\n// module chunks = 0","import {createPath} from './utils'\nimport {normalizeDoctype} from './doctypes'\nimport {cozyFetchJSON} from './fetch'\n\nconst NOREV = 'stack-v2-no-rev'\n\nexport function create (cozy, doctype, attributes) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n if (isV2) {\n attributes.docType = doctype\n }\n const path = createPath(cozy, isV2, doctype)\n return cozyFetchJSON(cozy, 'POST', path, attributes).then((resp) => {\n if (isV2) {\n return find(cozy, doctype, resp._id)\n } else {\n return resp.data\n }\n })\n })\n}\n\nexport function find (cozy, doctype, id) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n\n if (!id) {\n return Promise.reject(new Error('Missing id parameter'))\n }\n\n const path = createPath(cozy, isV2, doctype, id)\n return cozyFetchJSON(cozy, 'GET', path).then((resp) => {\n if (isV2) {\n return Object.assign(resp, {_rev: NOREV})\n } else {\n return resp\n }\n })\n })\n}\n\nexport function changesFeed (cozy, doctype, options) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n const path = createPath(cozy, isV2, doctype, '_changes', options)\n return cozyFetchJSON(cozy, 'GET', path)\n })\n}\n\nexport function update (cozy, doctype, doc, changes) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n const {_id, _rev} = doc\n\n if (!_id) {\n return Promise.reject(new Error('Missing _id field in passed document'))\n }\n\n if (!isV2 && !_rev) {\n return Promise.reject(new Error('Missing _rev field in passed document'))\n }\n\n if (isV2) {\n changes = Object.assign({ _id }, changes)\n } else {\n changes = Object.assign({ _id, _rev }, changes)\n }\n\n const path = createPath(cozy, isV2, doctype, _id)\n return cozyFetchJSON(cozy, 'PUT', path, changes).then((resp) => {\n if (isV2) {\n return find(cozy, doctype, _id)\n } else {\n return resp.data\n }\n })\n })\n}\n\nexport function updateAttributes (cozy, doctype, _id, changes, tries = 3) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n return find(cozy, doctype, _id)\n .then((doc) => {\n return update(cozy, doctype, doc, Object.assign({ _id }, doc, changes))\n })\n .catch((err) => {\n if (tries > 0) {\n return updateAttributes(cozy, doctype, _id, changes, tries - 1)\n } else {\n throw err\n }\n })\n })\n}\n\nexport function _delete (cozy, doctype, doc) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n const {_id, _rev} = doc\n\n if (!_id) {\n return Promise.reject(new Error('Missing _id field in passed document'))\n }\n\n if (!isV2 && !_rev) {\n return Promise.reject(new Error('Missing _rev field in passed document'))\n }\n\n const query = isV2 ? null : { rev: _rev }\n const path = createPath(cozy, isV2, doctype, _id, query)\n return cozyFetchJSON(cozy, 'DELETE', path).then((resp) => {\n if (isV2) {\n return {id: _id, rev: NOREV}\n } else {\n return resp\n }\n })\n })\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/data.js","import {warn} from './utils'\n\nexport const DOCTYPE_FILES = 'io.cozy.files'\n\nconst KNOWN_DOCTYPES = {\n 'files': DOCTYPE_FILES,\n 'folder': DOCTYPE_FILES,\n 'contact': 'io.cozy.contacts',\n 'event': 'io.cozy.events',\n 'track': 'io.cozy.labs.music.track',\n 'playlist': 'io.cozy.labs.music.playlist'\n}\n\nconst REVERSE_KNOWN = {}\nObject.keys(KNOWN_DOCTYPES).forEach(k => {\n REVERSE_KNOWN[KNOWN_DOCTYPES[k]] = k\n})\n\nexport function normalizeDoctype (cozy, isV2, doctype) {\n let isQualified = doctype.indexOf('.') !== -1\n if (isV2 && isQualified) {\n let known = REVERSE_KNOWN[doctype]\n if (known) return known\n return doctype.replace(/\\./g, '-')\n }\n if (!isV2 && !isQualified) {\n let known = KNOWN_DOCTYPES[doctype]\n if (known) {\n warn('you are using a non-qualified doctype ' + doctype + ' assumed to be ' + known)\n return known\n }\n throw new Error('Doctype ' + doctype + ' should be qualified.')\n }\n return doctype\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/doctypes.js","import {warn, createPath} from './utils'\nimport {normalizeDoctype} from './doctypes'\nimport {cozyFetchJSON} from './fetch'\n\nexport function defineIndex (cozy, doctype, fields) {\n return cozy.isV2().then((isV2) => {\n doctype = normalizeDoctype(cozy, isV2, doctype)\n if (!Array.isArray(fields) || fields.length === 0) {\n throw new Error('defineIndex fields should be a non-empty array')\n }\n if (isV2) {\n return defineIndexV2(cozy, doctype, fields)\n } else {\n return defineIndexV3(cozy, doctype, fields)\n }\n })\n}\n\nexport function query (cozy, indexRef, options) {\n return cozy.isV2().then((isV2) => {\n if (!indexRef) {\n throw new Error('query should be passed the indexRef')\n }\n if (isV2) {\n return queryV2(cozy, indexRef, options)\n } else {\n return queryV3(cozy, indexRef, options)\n }\n })\n}\n\n// Internals\n\nconst VALUEOPERATORS = ['$eq', '$gt', '$gte', '$lt', '$lte']\nconst LOGICOPERATORS = ['$or', '$and', '$not']\n\n/* eslint-disable */\nconst MAP_TEMPLATE = (function (doc) {\n if (doc.docType.toLowerCase() === 'DOCTYPEPLACEHOLDER'){\n emit(FIELDSPLACEHOLDER, doc)\n }\n}).toString().replace(/ /g, '').replace(/\\n/g, '')\nconst COUCHDB_INFINITY = {\"\\uFFFF\": \"\\uFFFF\"}\nconst COUCHDB_LOWEST = null\n/* eslint-enable */\n\n// defineIndexV2 is equivalent to defineIndex but only works for V2.\n// It transforms the index fields into a map reduce view.\nfunction defineIndexV2 (cozy, doctype, fields) {\n let indexName = 'by' + fields.map(capitalize).join('')\n let indexDefinition = { map: makeMapFunction(doctype, fields), reduce: '_count' }\n let path = `/request/${doctype}/${indexName}/`\n return cozyFetchJSON(cozy, 'PUT', path, indexDefinition)\n .then(() => ({ doctype: doctype, type: 'mapreduce', name: indexName, fields: fields }))\n}\n\n// defineIndexV2 is equivalent to defineIndex but only works for V2.\n// It transforms the index fields into a map reduce view.\nfunction defineIndexV3 (cozy, doctype, fields) {\n let path = createPath(cozy, false, doctype, '_index')\n let indexDefinition = {'index': {fields}}\n return cozyFetchJSON(cozy, 'POST', path, indexDefinition)\n .then((response) => ({ doctype: doctype, type: 'mango', name: response.id, fields: fields }))\n}\n\n// queryV2 is equivalent to query but only works for V2.\n// It transforms the query into a _views call using makeMapReduceQuery\nfunction queryV2 (cozy, indexRef, options) {\n if (indexRef.type !== 'mapreduce') {\n throw new Error('query indexRef should be the return value of defineIndexV2')\n }\n if (options.fields) {\n warn('query fields will be ignored on v2')\n }\n\n let path = `/request/${indexRef.doctype}/${indexRef.name}/`\n let opts = makeMapReduceQuery(indexRef, options)\n return cozyFetchJSON(cozy, 'POST', path, opts)\n .then((response) => response.map(r => r.value))\n}\n\n// queryV3 is equivalent to query but only works for V3\nfunction queryV3 (cozy, indexRef, options) {\n if (indexRef.type !== 'mango') {\n throw new Error('indexRef should be the return value of defineIndexV3')\n }\n\n let opts = {\n use_index: indexRef.name,\n fields: options.fields,\n selector: options.selector,\n limit: options.limit,\n since: options.since\n }\n\n if (options.descending) {\n opts.sort = indexRef.fields.map(f => ({ [f]: 'desc' }))\n }\n\n let path = createPath(cozy, false, indexRef.doctype, '_find')\n return cozyFetchJSON(cozy, 'POST', path, opts)\n .then((response) => response.docs)\n}\n\n// misc\nfunction capitalize (name) {\n return name.charAt(0).toUpperCase() + name.slice(1)\n}\n\nfunction makeMapFunction (doctype, fields) {\n fields = '[' + fields.map(name => 'doc.' + name).join(',') + ']'\n\n return MAP_TEMPLATE.replace('DOCTYPEPLACEHOLDER', doctype.toLowerCase())\n .replace('FIELDSPLACEHOLDER', fields)\n}\n\n// parseSelector takes a mango selector and returns it as an array of filter\n// a filter is [path, operator, value] array\n// a path is an array of field names\n// This function is only exported so it can be unit tested.\n// Example :\n// parseSelector({\"test\":{\"deep\": {\"$gt\": 3}}})\n// [[['test', 'deep'], '$gt', 3 ]]\nexport function parseSelector (selector, path = [], operator = '$eq') {\n if ((typeof selector) !== 'object') {\n return [[path, operator, selector]]\n }\n\n let keys = Object.keys(selector)\n if (keys.length === 0) {\n throw new Error('empty selector')\n } else {\n return keys.reduce(function (acc, k) {\n if (LOGICOPERATORS.indexOf(k) !== -1) {\n throw new Error('cozy-client-js does not support mango logic ops')\n } else if (VALUEOPERATORS.indexOf(k) !== -1) {\n return acc.concat(parseSelector(selector[k], path, k))\n } else {\n return acc.concat(parseSelector(selector[k], path.concat(k), '$eq'))\n }\n }, [])\n }\n}\n\n// normalizeSelector takes a mango selector and returns it as an object\n// normalized.\n// This function is only exported so it can be unit tested.\n// Example :\n// parseSelector({\"test\":{\"deep\": {\"$gt\": 3}}})\n// {\"test.deep\": {\"$gt\": 3}}\nexport function normalizeSelector (selector) {\n var filters = parseSelector(selector)\n return filters.reduce(function (acc, filter) {\n let [path, op, value] = filter\n let field = path.join('.')\n acc[field] = acc[field] || {}\n acc[field][op] = value\n return acc\n }, {})\n}\n\n// applySelector takes the normalized selector for the current field\n// and append the proper values to opts.startkey, opts.endkey\nfunction applySelector (selector, opts) {\n let value = selector['$eq']\n let lower = COUCHDB_LOWEST\n let upper = COUCHDB_INFINITY\n let inclusiveEnd\n\n if (value) {\n opts.startkey.push(value)\n opts.endkey.push(value)\n return false\n }\n\n value = selector['$gt']\n if (value) {\n throw new Error('operator $gt (strict greater than) not supported')\n }\n\n value = selector['$gte']\n if (value) {\n lower = value\n }\n\n value = selector['$lte']\n if (value) {\n upper = value\n inclusiveEnd = true\n }\n\n value = selector['$lt']\n if (value) {\n upper = value\n inclusiveEnd = false\n }\n\n opts.startkey.push(lower)\n opts.endkey.push(upper)\n if (inclusiveEnd !== undefined) opts.inclusive_end = inclusiveEnd\n return true\n}\n\n// makeMapReduceQuery takes a mango query and generate _views call parameters\n// to obtain same results depending on fields in the passed indexRef.\nexport function makeMapReduceQuery (indexRef, query) {\n let mrquery = {\n startkey: [],\n endkey: [],\n reduce: false\n }\n let firstFreeValueField = null\n let normalizedSelector = normalizeSelector(query.selector)\n\n indexRef.fields.forEach(function (field) {\n let selector = normalizedSelector[field]\n\n if (selector && firstFreeValueField != null) {\n throw new Error('Selector on field ' + field + ', but not on ' + firstFreeValueField + ' which is higher in index fields.')\n } else if (selector) {\n selector.used = true\n let isFreeValue = applySelector(selector, mrquery)\n if (isFreeValue) firstFreeValueField = field\n } else if (firstFreeValueField == null) {\n firstFreeValueField = field\n mrquery.endkey.push(COUCHDB_INFINITY)\n }\n })\n\n Object.keys(normalizedSelector).forEach(function (field) {\n if (!normalizedSelector[field].used) {\n throw new Error('Cant apply selector on ' + field + ', it is not in index')\n }\n })\n\n if (query.descending) {\n mrquery = {\n descending: true,\n reduce: false,\n startkey: mrquery.endkey,\n endkey: mrquery.startkey,\n inclusive_end: mrquery.inclusive_end\n }\n }\n\n return mrquery\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/mango.js","/* global Blob, File */\nimport {cozyFetch, cozyFetchJSON} from './fetch'\nimport jsonapi from './jsonapi'\nimport { DOCTYPE_FILES } from './doctypes'\n\nconst contentTypeOctetStream = 'application/octet-stream'\n\nfunction doUpload (cozy, data, method, path, options) {\n if (!data) {\n throw new Error('missing data argument')\n }\n\n // transform any ArrayBufferView to ArrayBuffer\n if (data.buffer && data.buffer instanceof ArrayBuffer) {\n data = data.buffer\n }\n\n const isBuffer = (typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer)\n const isFile = (typeof File !== 'undefined' && data instanceof File)\n const isBlob = (typeof Blob !== 'undefined' && data instanceof Blob)\n const isStream = (data.readable === true && typeof data.pipe === 'function')\n const isString = (typeof data === 'string')\n\n if (!isBuffer && !isFile && !isBlob && !isStream && !isString) {\n throw new Error('invalid data type')\n }\n\n let {contentType, checksum, lastModifiedDate, ifMatch} = options || {}\n if (!contentType) {\n if (isBuffer) {\n contentType = contentTypeOctetStream\n } else if (isFile) {\n contentType = data.type || contentTypeOctetStream\n if (!lastModifiedDate) {\n lastModifiedDate = data.lastModifiedDate\n }\n } else if (isBlob) {\n contentType = contentTypeOctetStream\n } else if (isStream) {\n contentType = contentTypeOctetStream\n } else if (typeof data === 'string') {\n contentType = 'text/plain'\n }\n }\n\n if (lastModifiedDate && typeof lastModifiedDate === 'string') {\n lastModifiedDate = new Date(lastModifiedDate)\n }\n\n return cozyFetch(cozy, path, {\n method: method,\n headers: {\n 'Content-Type': contentType,\n 'Content-MD5': checksum || '',\n 'Date': lastModifiedDate ? lastModifiedDate.toGMTString() : '',\n 'If-Match': ifMatch || ''\n },\n body: data\n })\n .then((res) => {\n const json = res.json()\n if (!res.ok) {\n return json.then(err => { throw err })\n } else {\n return json.then(jsonapi)\n }\n })\n}\n\nexport function create (cozy, data, options) {\n let {name, dirID, executable} = options || {}\n\n // handle case where data is a file and contains the name\n if (!name && typeof data.name === 'string') {\n name = data.name\n }\n\n if (typeof name !== 'string' || name === '') {\n throw new Error('missing name argument')\n }\n\n if (executable === undefined) {\n executable = false\n }\n\n const path = `/files/${encodeURIComponent(dirID || '')}`\n const query = `?Name=${encodeURIComponent(name)}&Type=file&Executable=${executable}`\n return doUpload(cozy, data, 'POST', `${path}${query}`, options)\n}\n\nexport function createDirectory (cozy, options) {\n let {name, dirID, lastModifiedDate} = options || {}\n\n if (typeof name !== 'string' || name === '') {\n throw new Error('missing name argument')\n }\n\n if (lastModifiedDate && typeof lastModifiedDate === 'string') {\n lastModifiedDate = new Date(lastModifiedDate)\n }\n\n const path = `/files/${encodeURIComponent(dirID || '')}`\n const query = `?Name=${encodeURIComponent(name)}&Type=directory`\n return cozyFetchJSON(cozy, 'POST', `${path}${query}`, undefined, {\n headers: {\n 'Date': lastModifiedDate ? lastModifiedDate.toGMTString() : ''\n }\n })\n}\n\nexport function updateById (cozy, id, data, options) {\n return doUpload(cozy, data, 'PUT', `/files/${encodeURIComponent(id)}`, options)\n}\n\nfunction doUpdateAttributes (cozy, attrs, path, options) {\n if (!attrs || typeof attrs !== 'object') {\n throw new Error('missing attrs argument')\n }\n\n const {ifMatch} = options || {}\n const body = { data: { attributes: attrs } }\n return cozyFetchJSON(cozy, 'PATCH', path, body, {\n headers: {\n 'If-Match': ifMatch || ''\n }\n })\n}\n\nexport function updateAttributesById (cozy, id, attrs, options) {\n return doUpdateAttributes(cozy, attrs,\n `/files/${encodeURIComponent(id)}`, options)\n}\n\nexport function updateAttributesByPath (cozy, path, attrs, options) {\n return doUpdateAttributes(cozy, attrs,\n `/files/metadata?Path=${encodeURIComponent(path)}`, options)\n}\n\nexport function trashById (cozy, id) {\n if (typeof id !== 'string' || id === '') {\n throw new Error('missing id argument')\n }\n return cozyFetchJSON(cozy, 'DELETE', `/files/${encodeURIComponent(id)}`)\n}\n\nexport function statById (cozy, id, offline = true) {\n if (offline && cozy.offline.hasDatabase(DOCTYPE_FILES)) {\n let db = cozy.offline.getDatabase(DOCTYPE_FILES)\n return Promise.all([\n db.get(id),\n db.find({selector: {'dir_id': id}})\n ]).then(([doc, children]) => {\n children = children.docs.map(doc => {\n return addIsDir(toJsonApi(cozy, doc))\n })\n return addIsDir(toJsonApi(cozy, doc, children))\n })\n }\n return cozyFetchJSON(cozy, 'GET', `/files/${encodeURIComponent(id)}`)\n .then(addIsDir)\n}\n\nexport function statByPath (cozy, path) {\n return cozyFetchJSON(cozy, 'GET', `/files/metadata?Path=${encodeURIComponent(path)}`)\n .then(addIsDir)\n}\n\nexport function downloadById (cozy, id) {\n return cozyFetch(cozy, `/files/download/${encodeURIComponent(id)}`)\n}\n\nexport function downloadByPath (cozy, path) {\n return cozyFetch(cozy, `/files/download?Path=${encodeURIComponent(path)}`)\n}\n\nfunction extractResponseLinkRelated (res) {\n let href = res.links && res.links.related\n if (!href) throw new Error('No related link in server response')\n return href\n}\n\nexport function getDowloadLink (cozy, path) {\n return cozyFetchJSON(cozy, 'POST', `/files/downloads?Path=${encodeURIComponent(path)}`)\n .then(extractResponseLinkRelated)\n}\n\nexport function getArchiveLink (cozy, paths, name = 'files') {\n const archive = {\n type: 'io.cozy.archives',\n attributes: {\n name: name,\n files: paths\n }\n }\n return cozyFetchJSON(cozy, 'POST', `/files/archive`, {data: archive})\n .then(extractResponseLinkRelated)\n}\n\nexport function listTrash (cozy) {\n return cozyFetchJSON(cozy, 'GET', `/files/trash`)\n}\n\nexport function clearTrash (cozy) {\n return cozyFetchJSON(cozy, 'DELETE', `/files/trash`)\n}\n\nexport function restoreById (cozy, id) {\n return cozyFetchJSON(cozy, 'POST', `/files/trash/${encodeURIComponent(id)}`)\n}\n\nexport function destroyById (cozy, id) {\n return cozyFetchJSON(cozy, 'DELETE', `/files/trash/${encodeURIComponent(id)}`)\n}\n\nfunction addIsDir (obj) {\n obj.isDir = obj.attributes.type === 'directory'\n return obj\n}\n\nfunction toJsonApi (cozy, doc, contents = []) {\n let clone = JSON.parse(JSON.stringify(doc))\n delete clone._id\n delete clone._rev\n return {\n _id: doc._id,\n _rev: doc._rev,\n _type: DOCTYPE_FILES,\n attributes: clone,\n relations: (name) => {\n if (name === 'contents') {\n return contents\n }\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/files.js","import PouchDB from 'pouchdb'\nimport pouchdbFind from 'pouchdb-find'\nimport { DOCTYPE_FILES } from './doctypes'\n\nlet pluginLoaded = false\n\n/*\n For each doctype we have some parameters:\n cozy._offline[doctype] = {\n database: pouchdb database\n replication: the pouchdb replication\n replicationPromise: promise of replication\n interval: repeated replication interval\n }\n*/\n\nexport function init (cozy, { options = {}, doctypes = [] }) {\n for (let doctype of doctypes) {\n createDatabase(cozy, doctype, options)\n }\n}\n\n// helper\n\nfunction getInfo (cozy, doctype) {\n cozy._offline = cozy._offline || []\n cozy._offline[doctype] = cozy._offline[doctype] || {}\n return cozy._offline[doctype]\n}\n\nexport function getDoctypes (cozy) {\n cozy._offline = cozy._offline || []\n return Object.keys(cozy._offline)\n}\n\n//\n// DATABASE\n//\n\nexport function hasDatabase (cozy, doctype) {\n return getDatabase(cozy, doctype) !== undefined\n}\n\nexport function getDatabase (cozy, doctype) {\n return getInfo(cozy, doctype).database\n}\n\nexport function setDatabase (cozy, doctype, database) {\n cozy._offline[doctype].database = database\n return getDatabase(cozy, doctype)\n}\n\nfunction errorDatabase (doctype) {\n return new Error(`You should add this doctype: ${doctype} to offline.`)\n}\n\nexport function createDatabase (cozy, doctype, options = {}) {\n if (!pluginLoaded) {\n PouchDB.plugin(pouchdbFind)\n pluginLoaded = true\n }\n\n if (hasDatabase(cozy, doctype)) {\n return Promise.resolve(getDatabase(cozy, doctype))\n }\n\n setDatabase(cozy, doctype, new PouchDB(doctype, options))\n return createIndexes(cozy, doctype).then(() => getDatabase(cozy, doctype))\n}\n\nexport function destroyDatabase (cozy, doctype) {\n if (!hasDatabase(cozy, doctype)) {\n return Promise.resolve(false)\n }\n\n return stopRepeatedReplication(cozy, doctype)\n .then(() => stopReplication(cozy, doctype))\n .then(() => getDatabase(cozy, doctype).destroy())\n .then(response => {\n setDatabase(cozy, doctype, undefined)\n return response\n })\n}\n\nexport function destroyAllDatabase (cozy) {\n const doctypes = getDoctypes(cozy)\n const destroy = (doctype) => destroyDatabase(cozy, doctype)\n return Promise.all(doctypes.map(destroy))\n}\n\nfunction createIndexes (cozy, doctype) {\n if (doctype === DOCTYPE_FILES) {\n return getDatabase(cozy, doctype).createIndex({index: {fields: ['dir_id']}})\n }\n return Promise.resolve()\n}\n\n//\n// REPLICATION\n//\n\nexport function hasReplication (cozy, doctype) {\n return getReplication(cozy, doctype) !== undefined\n}\n\nfunction getReplication (cozy, doctype) {\n return getInfo(cozy, doctype).replication\n}\n\nfunction setReplication (cozy, doctype, replication) {\n cozy._offline[doctype].replication = replication\n return getReplication(cozy, doctype)\n}\n\nfunction getReplicationUrl (cozy, doctype) {\n return cozy.authorize()\n .then(credentials => {\n const basic = credentials.token.toBasicAuth()\n return (cozy._url + '/data/' + doctype).replace('//', `//${basic}`)\n })\n}\n\nfunction getReplicationPromise (cozy, doctype) {\n return getInfo(cozy, doctype).replicationPromise\n}\n\nfunction setReplicationPromise (cozy, doctype, promise) {\n cozy._offline[doctype].replicationPromise = promise\n return getReplicationPromise(cozy, doctype)\n}\n\nexport function replicateFromCozy (cozy, doctype, options = {}) {\n return setReplicationPromise(cozy, doctype, new Promise((resolve, reject) => {\n if (!hasDatabase(cozy, doctype)) {\n return reject(errorDatabase(doctype))\n }\n if (options.live === true) {\n return reject(new Error('You can\\'t use `live` option with Cozy couchdb.'))\n }\n\n getReplicationUrl(cozy, doctype)\n .then(url => setReplication(cozy, doctype,\n getDatabase(cozy, doctype).replicate.from(url, options).on('complete', (info) => {\n setReplication(cozy, doctype, undefined)\n resolve(info)\n }).on('error', (err) => {\n console.warn(`ReplicateFromCozy '${doctype}' Error:`)\n console.warn(err)\n setReplication(cozy, doctype, undefined)\n reject(err)\n })\n ))\n }))\n}\n\nexport function stopReplication (cozy, doctype) {\n if (!getDatabase(cozy, doctype) || !hasReplication(cozy, doctype)) {\n return Promise.resolve()\n }\n\n return new Promise(resolve => {\n try {\n getReplicationPromise(cozy, doctype).then(() => {\n resolve()\n })\n getReplication(cozy, doctype).cancel()\n // replication is set to undefined by complete replication\n } catch (e) {\n resolve()\n }\n })\n}\n\nexport function stopAllReplication (cozy) {\n const doctypes = getDoctypes(cozy)\n const stop = (doctype) => stopReplication(cozy, doctype)\n return Promise.all(doctypes.map(stop))\n}\n\n//\n// REPEATED REPLICATION\n//\n\nfunction getRepeatedReplication (cozy, doctype) {\n return getInfo(cozy, doctype).interval\n}\n\nfunction setRepeatedReplication (cozy, doctype, interval) {\n cozy._offline[doctype].interval = interval\n}\n\nexport function hasRepeatedReplication (cozy, doctype) {\n return getRepeatedReplication(cozy, doctype) !== undefined\n}\n\nexport function startRepeatedReplication (cozy, doctype, timer, options = {}) {\n // TODO: add timer limitation for not flooding Gozy\n if (!hasDatabase(cozy, doctype)) {\n return Promise.reject(errorDatabase(doctype))\n }\n\n if (hasRepeatedReplication(cozy, doctype)) {\n return getRepeatedReplication(cozy, doctype)\n }\n\n return setRepeatedReplication(cozy, doctype, setInterval(() => {\n if (!hasReplication(cozy, doctype)) {\n replicateFromCozy(cozy, doctype, options)\n // TODO: add replicationToCozy\n }\n }, timer * 1000))\n}\n\nexport function stopRepeatedReplication (cozy, doctype) {\n if (hasRepeatedReplication(cozy, doctype)) {\n clearInterval(getRepeatedReplication(cozy, doctype))\n setRepeatedReplication(cozy, doctype, undefined)\n }\n if (hasReplication(cozy, doctype)) {\n return stopReplication(cozy, doctype)\n }\n\n return Promise.resolve()\n}\n\nexport function stopAllRepeatedReplication (cozy) {\n const doctypes = getDoctypes(cozy)\n const stop = (doctype) => stopRepeatedReplication(cozy, doctype)\n return Promise.all(doctypes.map(stop))\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/offline.js","module.exports = require(\"pouchdb\");\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"pouchdb\"\n// module id = 16\n// module chunks = 0","module.exports = require(\"pouchdb-find\");\n\n\n//////////////////\n// WEBPACK FOOTER\n// external \"pouchdb-find\"\n// module id = 17\n// module chunks = 0","import {cozyFetchJSON} from './fetch'\n\nexport function diskUsage (cozy) {\n return cozyFetchJSON(cozy, 'GET', `/settings/disk-usage`)\n}\n\nexport function changePassphrase (cozy, currentPassPhrase, newPassPhrase) {\n return cozyFetchJSON(cozy, 'PUT', `/settings/passphrase`, {\n current_passphrase: currentPassPhrase,\n new_passphrase: newPassPhrase\n })\n}\n\nexport function getInstance (cozy) {\n return cozyFetchJSON(cozy, 'GET', `/settings/instance`)\n}\n\nexport function updateInstance (cozy, instance) {\n return cozyFetchJSON(cozy, 'PUT', `/settings/instance`, instance)\n}\n\nexport function getClients (cozy) {\n return cozyFetchJSON(cozy, 'GET', `/settings/clients`)\n}\n\nexport function deleteClientById (cozy, id) {\n return cozyFetchJSON(cozy, 'DELETE', `/settings/clients/${id}`)\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/settings.js","import {cozyFetchJSON} from './fetch'\nimport { DOCTYPE_FILES } from './doctypes'\n\nexport function addReferencedFiles (cozy, doc, ids) {\n if (!doc) throw new Error('missing doc argument')\n if (!Array.isArray(ids)) ids = [ids]\n\n const refs = ids.map((id) => ({type: DOCTYPE_FILES, id: id}))\n\n return cozyFetchJSON(cozy, 'POST', makeReferencesPath(doc), {data: refs})\n}\n\nexport function listReferencedFiles (cozy, doc) {\n if (!doc) throw new Error('missing doc argument')\n return cozyFetchJSON(cozy, 'GET', makeReferencesPath(doc))\n .then((files) => files.map((file) => file._id))\n}\n\nfunction makeReferencesPath (doc) {\n const type = encodeURIComponent(doc._type)\n const id = encodeURIComponent(doc._id)\n return `/data/${type}/${id}/relationships/references`\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/relations.js"],"sourceRoot":""} \ No newline at end of file diff --git a/package.json b/package.json index c182dff3..5c39f969 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "cozy-client-js", - "version": "0.1.2", + "version": "0.1.3", "description": "Javascript library to interact with a cozy", "main": "dist/cozy-client.node.js", "browser": "dist/cozy-client.js",