UI for Zipcoin Blue

localforage.js 73KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301
  1. /*!
  2. localForage -- Offline Storage, Improved
  3. Version 1.4.3
  4. https://mozilla.github.io/localForage
  5. (c) 2013-2016 Mozilla, Apache License 2.0
  6. */
  7. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.localforage = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw (f.code="MODULE_NOT_FOUND", f)}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
  8. 'use strict';
  9. var immediate = _dereq_(2);
  10. /* istanbul ignore next */
  11. function INTERNAL() {}
  12. var handlers = {};
  13. var REJECTED = ['REJECTED'];
  14. var FULFILLED = ['FULFILLED'];
  15. var PENDING = ['PENDING'];
  16. module.exports = exports = Promise;
  17. function Promise(resolver) {
  18. if (typeof resolver !== 'function') {
  19. throw new TypeError('resolver must be a function');
  20. }
  21. this.state = PENDING;
  22. this.queue = [];
  23. this.outcome = void 0;
  24. if (resolver !== INTERNAL) {
  25. safelyResolveThenable(this, resolver);
  26. }
  27. }
  28. Promise.prototype["catch"] = function (onRejected) {
  29. return this.then(null, onRejected);
  30. };
  31. Promise.prototype.then = function (onFulfilled, onRejected) {
  32. if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||
  33. typeof onRejected !== 'function' && this.state === REJECTED) {
  34. return this;
  35. }
  36. var promise = new this.constructor(INTERNAL);
  37. if (this.state !== PENDING) {
  38. var resolver = this.state === FULFILLED ? onFulfilled : onRejected;
  39. unwrap(promise, resolver, this.outcome);
  40. } else {
  41. this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
  42. }
  43. return promise;
  44. };
  45. function QueueItem(promise, onFulfilled, onRejected) {
  46. this.promise = promise;
  47. if (typeof onFulfilled === 'function') {
  48. this.onFulfilled = onFulfilled;
  49. this.callFulfilled = this.otherCallFulfilled;
  50. }
  51. if (typeof onRejected === 'function') {
  52. this.onRejected = onRejected;
  53. this.callRejected = this.otherCallRejected;
  54. }
  55. }
  56. QueueItem.prototype.callFulfilled = function (value) {
  57. handlers.resolve(this.promise, value);
  58. };
  59. QueueItem.prototype.otherCallFulfilled = function (value) {
  60. unwrap(this.promise, this.onFulfilled, value);
  61. };
  62. QueueItem.prototype.callRejected = function (value) {
  63. handlers.reject(this.promise, value);
  64. };
  65. QueueItem.prototype.otherCallRejected = function (value) {
  66. unwrap(this.promise, this.onRejected, value);
  67. };
  68. function unwrap(promise, func, value) {
  69. immediate(function () {
  70. var returnValue;
  71. try {
  72. returnValue = func(value);
  73. } catch (e) {
  74. return handlers.reject(promise, e);
  75. }
  76. if (returnValue === promise) {
  77. handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));
  78. } else {
  79. handlers.resolve(promise, returnValue);
  80. }
  81. });
  82. }
  83. handlers.resolve = function (self, value) {
  84. var result = tryCatch(getThen, value);
  85. if (result.status === 'error') {
  86. return handlers.reject(self, result.value);
  87. }
  88. var thenable = result.value;
  89. if (thenable) {
  90. safelyResolveThenable(self, thenable);
  91. } else {
  92. self.state = FULFILLED;
  93. self.outcome = value;
  94. var i = -1;
  95. var len = self.queue.length;
  96. while (++i < len) {
  97. self.queue[i].callFulfilled(value);
  98. }
  99. }
  100. return self;
  101. };
  102. handlers.reject = function (self, error) {
  103. self.state = REJECTED;
  104. self.outcome = error;
  105. var i = -1;
  106. var len = self.queue.length;
  107. while (++i < len) {
  108. self.queue[i].callRejected(error);
  109. }
  110. return self;
  111. };
  112. function getThen(obj) {
  113. // Make sure we only access the accessor once as required by the spec
  114. var then = obj && obj.then;
  115. if (obj && typeof obj === 'object' && typeof then === 'function') {
  116. return function appyThen() {
  117. then.apply(obj, arguments);
  118. };
  119. }
  120. }
  121. function safelyResolveThenable(self, thenable) {
  122. // Either fulfill, reject or reject with error
  123. var called = false;
  124. function onError(value) {
  125. if (called) {
  126. return;
  127. }
  128. called = true;
  129. handlers.reject(self, value);
  130. }
  131. function onSuccess(value) {
  132. if (called) {
  133. return;
  134. }
  135. called = true;
  136. handlers.resolve(self, value);
  137. }
  138. function tryToUnwrap() {
  139. thenable(onSuccess, onError);
  140. }
  141. var result = tryCatch(tryToUnwrap);
  142. if (result.status === 'error') {
  143. onError(result.value);
  144. }
  145. }
  146. function tryCatch(func, value) {
  147. var out = {};
  148. try {
  149. out.value = func(value);
  150. out.status = 'success';
  151. } catch (e) {
  152. out.status = 'error';
  153. out.value = e;
  154. }
  155. return out;
  156. }
  157. exports.resolve = resolve;
  158. function resolve(value) {
  159. if (value instanceof this) {
  160. return value;
  161. }
  162. return handlers.resolve(new this(INTERNAL), value);
  163. }
  164. exports.reject = reject;
  165. function reject(reason) {
  166. var promise = new this(INTERNAL);
  167. return handlers.reject(promise, reason);
  168. }
  169. exports.all = all;
  170. function all(iterable) {
  171. var self = this;
  172. if (Object.prototype.toString.call(iterable) !== '[object Array]') {
  173. return this.reject(new TypeError('must be an array'));
  174. }
  175. var len = iterable.length;
  176. var called = false;
  177. if (!len) {
  178. return this.resolve([]);
  179. }
  180. var values = new Array(len);
  181. var resolved = 0;
  182. var i = -1;
  183. var promise = new this(INTERNAL);
  184. while (++i < len) {
  185. allResolver(iterable[i], i);
  186. }
  187. return promise;
  188. function allResolver(value, i) {
  189. self.resolve(value).then(resolveFromAll, function (error) {
  190. if (!called) {
  191. called = true;
  192. handlers.reject(promise, error);
  193. }
  194. });
  195. function resolveFromAll(outValue) {
  196. values[i] = outValue;
  197. if (++resolved === len && !called) {
  198. called = true;
  199. handlers.resolve(promise, values);
  200. }
  201. }
  202. }
  203. }
  204. exports.race = race;
  205. function race(iterable) {
  206. var self = this;
  207. if (Object.prototype.toString.call(iterable) !== '[object Array]') {
  208. return this.reject(new TypeError('must be an array'));
  209. }
  210. var len = iterable.length;
  211. var called = false;
  212. if (!len) {
  213. return this.resolve([]);
  214. }
  215. var i = -1;
  216. var promise = new this(INTERNAL);
  217. while (++i < len) {
  218. resolver(iterable[i]);
  219. }
  220. return promise;
  221. function resolver(value) {
  222. self.resolve(value).then(function (response) {
  223. if (!called) {
  224. called = true;
  225. handlers.resolve(promise, response);
  226. }
  227. }, function (error) {
  228. if (!called) {
  229. called = true;
  230. handlers.reject(promise, error);
  231. }
  232. });
  233. }
  234. }
  235. },{"2":2}],2:[function(_dereq_,module,exports){
  236. (function (global){
  237. 'use strict';
  238. var Mutation = global.MutationObserver || global.WebKitMutationObserver;
  239. var scheduleDrain;
  240. {
  241. if (Mutation) {
  242. var called = 0;
  243. var observer = new Mutation(nextTick);
  244. var element = global.document.createTextNode('');
  245. observer.observe(element, {
  246. characterData: true
  247. });
  248. scheduleDrain = function () {
  249. element.data = (called = ++called % 2);
  250. };
  251. } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
  252. var channel = new global.MessageChannel();
  253. channel.port1.onmessage = nextTick;
  254. scheduleDrain = function () {
  255. channel.port2.postMessage(0);
  256. };
  257. } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
  258. scheduleDrain = function () {
  259. // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
  260. // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
  261. var scriptEl = global.document.createElement('script');
  262. scriptEl.onreadystatechange = function () {
  263. nextTick();
  264. scriptEl.onreadystatechange = null;
  265. scriptEl.parentNode.removeChild(scriptEl);
  266. scriptEl = null;
  267. };
  268. global.document.documentElement.appendChild(scriptEl);
  269. };
  270. } else {
  271. scheduleDrain = function () {
  272. setTimeout(nextTick, 0);
  273. };
  274. }
  275. }
  276. var draining;
  277. var queue = [];
  278. //named nextTick for less confusing stack traces
  279. function nextTick() {
  280. draining = true;
  281. var i, oldQueue;
  282. var len = queue.length;
  283. while (len) {
  284. oldQueue = queue;
  285. queue = [];
  286. i = -1;
  287. while (++i < len) {
  288. oldQueue[i]();
  289. }
  290. len = queue.length;
  291. }
  292. draining = false;
  293. }
  294. module.exports = immediate;
  295. function immediate(task) {
  296. if (queue.push(task) === 1 && !draining) {
  297. scheduleDrain();
  298. }
  299. }
  300. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  301. },{}],3:[function(_dereq_,module,exports){
  302. (function (global){
  303. 'use strict';
  304. if (typeof global.Promise !== 'function') {
  305. global.Promise = _dereq_(1);
  306. }
  307. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  308. },{"1":1}],4:[function(_dereq_,module,exports){
  309. 'use strict';
  310. 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; };
  311. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  312. function getIDB() {
  313. /* global indexedDB,webkitIndexedDB,mozIndexedDB,OIndexedDB,msIndexedDB */
  314. try {
  315. if (typeof indexedDB !== 'undefined') {
  316. return indexedDB;
  317. }
  318. if (typeof webkitIndexedDB !== 'undefined') {
  319. return webkitIndexedDB;
  320. }
  321. if (typeof mozIndexedDB !== 'undefined') {
  322. return mozIndexedDB;
  323. }
  324. if (typeof OIndexedDB !== 'undefined') {
  325. return OIndexedDB;
  326. }
  327. if (typeof msIndexedDB !== 'undefined') {
  328. return msIndexedDB;
  329. }
  330. } catch (e) {}
  331. }
  332. var idb = getIDB();
  333. function isIndexedDBValid() {
  334. try {
  335. // Initialize IndexedDB; fall back to vendor-prefixed versions
  336. // if needed.
  337. if (!idb) {
  338. return false;
  339. }
  340. // We mimic PouchDB here; just UA test for Safari (which, as of
  341. // iOS 8/Yosemite, doesn't properly support IndexedDB).
  342. // IndexedDB support is broken and different from Blink's.
  343. // This is faster than the test case (and it's sync), so we just
  344. // do this. *SIGH*
  345. // http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/
  346. //
  347. // We test for openDatabase because IE Mobile identifies itself
  348. // as Safari. Oh the lulz...
  349. if (typeof openDatabase !== 'undefined' && typeof navigator !== 'undefined' && navigator.userAgent && /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent)) {
  350. return false;
  351. }
  352. return idb && typeof idb.open === 'function' &&
  353. // Some Samsung/HTC Android 4.0-4.3 devices
  354. // have older IndexedDB specs; if this isn't available
  355. // their IndexedDB is too old for us to use.
  356. // (Replaces the onupgradeneeded test.)
  357. typeof IDBKeyRange !== 'undefined';
  358. } catch (e) {
  359. return false;
  360. }
  361. }
  362. function isWebSQLValid() {
  363. return typeof openDatabase === 'function';
  364. }
  365. function isLocalStorageValid() {
  366. try {
  367. return typeof localStorage !== 'undefined' && 'setItem' in localStorage && localStorage.setItem;
  368. } catch (e) {
  369. return false;
  370. }
  371. }
  372. // Abstracts constructing a Blob object, so it also works in older
  373. // browsers that don't support the native Blob constructor. (i.e.
  374. // old QtWebKit versions, at least).
  375. // Abstracts constructing a Blob object, so it also works in older
  376. // browsers that don't support the native Blob constructor. (i.e.
  377. // old QtWebKit versions, at least).
  378. function createBlob(parts, properties) {
  379. /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */
  380. parts = parts || [];
  381. properties = properties || {};
  382. try {
  383. return new Blob(parts, properties);
  384. } catch (e) {
  385. if (e.name !== 'TypeError') {
  386. throw e;
  387. }
  388. var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : WebKitBlobBuilder;
  389. var builder = new Builder();
  390. for (var i = 0; i < parts.length; i += 1) {
  391. builder.append(parts[i]);
  392. }
  393. return builder.getBlob(properties.type);
  394. }
  395. }
  396. // This is CommonJS because lie is an external dependency, so Rollup
  397. // can just ignore it.
  398. if (typeof Promise === 'undefined' && typeof _dereq_ !== 'undefined') {
  399. _dereq_(3);
  400. }
  401. var Promise$1 = Promise;
  402. function executeCallback(promise, callback) {
  403. if (callback) {
  404. promise.then(function (result) {
  405. callback(null, result);
  406. }, function (error) {
  407. callback(error);
  408. });
  409. }
  410. }
  411. function executeTwoCallbacks(promise, callback, errorCallback) {
  412. if (typeof callback === 'function') {
  413. promise.then(callback);
  414. }
  415. if (typeof errorCallback === 'function') {
  416. promise["catch"](errorCallback);
  417. }
  418. }
  419. // Some code originally from async_storage.js in
  420. // [Gaia](https://github.com/mozilla-b2g/gaia).
  421. var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';
  422. var supportsBlobs;
  423. var dbContexts;
  424. var toString = Object.prototype.toString;
  425. // Transform a binary string to an array buffer, because otherwise
  426. // weird stuff happens when you try to work with the binary string directly.
  427. // It is known.
  428. // From http://stackoverflow.com/questions/14967647/ (continues on next line)
  429. // encode-decode-image-with-base64-breaks-image (2013-04-21)
  430. function _binStringToArrayBuffer(bin) {
  431. var length = bin.length;
  432. var buf = new ArrayBuffer(length);
  433. var arr = new Uint8Array(buf);
  434. for (var i = 0; i < length; i++) {
  435. arr[i] = bin.charCodeAt(i);
  436. }
  437. return buf;
  438. }
  439. //
  440. // Blobs are not supported in all versions of IndexedDB, notably
  441. // Chrome <37 and Android <5. In those versions, storing a blob will throw.
  442. //
  443. // Various other blob bugs exist in Chrome v37-42 (inclusive).
  444. // Detecting them is expensive and confusing to users, and Chrome 37-42
  445. // is at very low usage worldwide, so we do a hacky userAgent check instead.
  446. //
  447. // content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120
  448. // 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916
  449. // FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836
  450. //
  451. // Code borrowed from PouchDB. See:
  452. // https://github.com/pouchdb/pouchdb/blob/9c25a23/src/adapters/idb/blobSupport.js
  453. //
  454. function _checkBlobSupportWithoutCaching(txn) {
  455. return new Promise$1(function (resolve) {
  456. var blob = createBlob(['']);
  457. txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');
  458. txn.onabort = function (e) {
  459. // If the transaction aborts now its due to not being able to
  460. // write to the database, likely due to the disk being full
  461. e.preventDefault();
  462. e.stopPropagation();
  463. resolve(false);
  464. };
  465. txn.oncomplete = function () {
  466. var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/);
  467. var matchedEdge = navigator.userAgent.match(/Edge\//);
  468. // MS Edge pretends to be Chrome 42:
  469. // https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx
  470. resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43);
  471. };
  472. })["catch"](function () {
  473. return false; // error, so assume unsupported
  474. });
  475. }
  476. function _checkBlobSupport(idb) {
  477. if (typeof supportsBlobs === 'boolean') {
  478. return Promise$1.resolve(supportsBlobs);
  479. }
  480. return _checkBlobSupportWithoutCaching(idb).then(function (value) {
  481. supportsBlobs = value;
  482. return supportsBlobs;
  483. });
  484. }
  485. function _deferReadiness(dbInfo) {
  486. var dbContext = dbContexts[dbInfo.name];
  487. // Create a deferred object representing the current database operation.
  488. var deferredOperation = {};
  489. deferredOperation.promise = new Promise$1(function (resolve) {
  490. deferredOperation.resolve = resolve;
  491. });
  492. // Enqueue the deferred operation.
  493. dbContext.deferredOperations.push(deferredOperation);
  494. // Chain its promise to the database readiness.
  495. if (!dbContext.dbReady) {
  496. dbContext.dbReady = deferredOperation.promise;
  497. } else {
  498. dbContext.dbReady = dbContext.dbReady.then(function () {
  499. return deferredOperation.promise;
  500. });
  501. }
  502. }
  503. function _advanceReadiness(dbInfo) {
  504. var dbContext = dbContexts[dbInfo.name];
  505. // Dequeue a deferred operation.
  506. var deferredOperation = dbContext.deferredOperations.pop();
  507. // Resolve its promise (which is part of the database readiness
  508. // chain of promises).
  509. if (deferredOperation) {
  510. deferredOperation.resolve();
  511. }
  512. }
  513. function _getConnection(dbInfo, upgradeNeeded) {
  514. return new Promise$1(function (resolve, reject) {
  515. if (dbInfo.db) {
  516. if (upgradeNeeded) {
  517. _deferReadiness(dbInfo);
  518. dbInfo.db.close();
  519. } else {
  520. return resolve(dbInfo.db);
  521. }
  522. }
  523. var dbArgs = [dbInfo.name];
  524. if (upgradeNeeded) {
  525. dbArgs.push(dbInfo.version);
  526. }
  527. var openreq = idb.open.apply(idb, dbArgs);
  528. if (upgradeNeeded) {
  529. openreq.onupgradeneeded = function (e) {
  530. var db = openreq.result;
  531. try {
  532. db.createObjectStore(dbInfo.storeName);
  533. if (e.oldVersion <= 1) {
  534. // Added when support for blob shims was added
  535. db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
  536. }
  537. } catch (ex) {
  538. if (ex.name === 'ConstraintError') {
  539. console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.');
  540. } else {
  541. throw ex;
  542. }
  543. }
  544. };
  545. }
  546. openreq.onerror = function () {
  547. reject(openreq.error);
  548. };
  549. openreq.onsuccess = function () {
  550. resolve(openreq.result);
  551. _advanceReadiness(dbInfo);
  552. };
  553. });
  554. }
  555. function _getOriginalConnection(dbInfo) {
  556. return _getConnection(dbInfo, false);
  557. }
  558. function _getUpgradedConnection(dbInfo) {
  559. return _getConnection(dbInfo, true);
  560. }
  561. function _isUpgradeNeeded(dbInfo, defaultVersion) {
  562. if (!dbInfo.db) {
  563. return true;
  564. }
  565. var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);
  566. var isDowngrade = dbInfo.version < dbInfo.db.version;
  567. var isUpgrade = dbInfo.version > dbInfo.db.version;
  568. if (isDowngrade) {
  569. // If the version is not the default one
  570. // then warn for impossible downgrade.
  571. if (dbInfo.version !== defaultVersion) {
  572. console.warn('The database "' + dbInfo.name + '"' + ' can\'t be downgraded from version ' + dbInfo.db.version + ' to version ' + dbInfo.version + '.');
  573. }
  574. // Align the versions to prevent errors.
  575. dbInfo.version = dbInfo.db.version;
  576. }
  577. if (isUpgrade || isNewStore) {
  578. // If the store is new then increment the version (if needed).
  579. // This will trigger an "upgradeneeded" event which is required
  580. // for creating a store.
  581. if (isNewStore) {
  582. var incVersion = dbInfo.db.version + 1;
  583. if (incVersion > dbInfo.version) {
  584. dbInfo.version = incVersion;
  585. }
  586. }
  587. return true;
  588. }
  589. return false;
  590. }
  591. // encode a blob for indexeddb engines that don't support blobs
  592. function _encodeBlob(blob) {
  593. return new Promise$1(function (resolve, reject) {
  594. var reader = new FileReader();
  595. reader.onerror = reject;
  596. reader.onloadend = function (e) {
  597. var base64 = btoa(e.target.result || '');
  598. resolve({
  599. __local_forage_encoded_blob: true,
  600. data: base64,
  601. type: blob.type
  602. });
  603. };
  604. reader.readAsBinaryString(blob);
  605. });
  606. }
  607. // decode an encoded blob
  608. function _decodeBlob(encodedBlob) {
  609. var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));
  610. return createBlob([arrayBuff], { type: encodedBlob.type });
  611. }
  612. // is this one of our fancy encoded blobs?
  613. function _isEncodedBlob(value) {
  614. return value && value.__local_forage_encoded_blob;
  615. }
  616. // Specialize the default `ready()` function by making it dependent
  617. // on the current database operations. Thus, the driver will be actually
  618. // ready when it's been initialized (default) *and* there are no pending
  619. // operations on the database (initiated by some other instances).
  620. function _fullyReady(callback) {
  621. var self = this;
  622. var promise = self._initReady().then(function () {
  623. var dbContext = dbContexts[self._dbInfo.name];
  624. if (dbContext && dbContext.dbReady) {
  625. return dbContext.dbReady;
  626. }
  627. });
  628. executeTwoCallbacks(promise, callback, callback);
  629. return promise;
  630. }
  631. // Open the IndexedDB database (automatically creates one if one didn't
  632. // previously exist), using any options set in the config.
  633. function _initStorage(options) {
  634. var self = this;
  635. var dbInfo = {
  636. db: null
  637. };
  638. if (options) {
  639. for (var i in options) {
  640. dbInfo[i] = options[i];
  641. }
  642. }
  643. // Initialize a singleton container for all running localForages.
  644. if (!dbContexts) {
  645. dbContexts = {};
  646. }
  647. // Get the current context of the database;
  648. var dbContext = dbContexts[dbInfo.name];
  649. // ...or create a new context.
  650. if (!dbContext) {
  651. dbContext = {
  652. // Running localForages sharing a database.
  653. forages: [],
  654. // Shared database.
  655. db: null,
  656. // Database readiness (promise).
  657. dbReady: null,
  658. // Deferred operations on the database.
  659. deferredOperations: []
  660. };
  661. // Register the new context in the global container.
  662. dbContexts[dbInfo.name] = dbContext;
  663. }
  664. // Register itself as a running localForage in the current context.
  665. dbContext.forages.push(self);
  666. // Replace the default `ready()` function with the specialized one.
  667. if (!self._initReady) {
  668. self._initReady = self.ready;
  669. self.ready = _fullyReady;
  670. }
  671. // Create an array of initialization states of the related localForages.
  672. var initPromises = [];
  673. function ignoreErrors() {
  674. // Don't handle errors here,
  675. // just makes sure related localForages aren't pending.
  676. return Promise$1.resolve();
  677. }
  678. for (var j = 0; j < dbContext.forages.length; j++) {
  679. var forage = dbContext.forages[j];
  680. if (forage !== self) {
  681. // Don't wait for itself...
  682. initPromises.push(forage._initReady()["catch"](ignoreErrors));
  683. }
  684. }
  685. // Take a snapshot of the related localForages.
  686. var forages = dbContext.forages.slice(0);
  687. // Initialize the connection process only when
  688. // all the related localForages aren't pending.
  689. return Promise$1.all(initPromises).then(function () {
  690. dbInfo.db = dbContext.db;
  691. // Get the connection or open a new one without upgrade.
  692. return _getOriginalConnection(dbInfo);
  693. }).then(function (db) {
  694. dbInfo.db = db;
  695. if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) {
  696. // Reopen the database for upgrading.
  697. return _getUpgradedConnection(dbInfo);
  698. }
  699. return db;
  700. }).then(function (db) {
  701. dbInfo.db = dbContext.db = db;
  702. self._dbInfo = dbInfo;
  703. // Share the final connection amongst related localForages.
  704. for (var k = 0; k < forages.length; k++) {
  705. var forage = forages[k];
  706. if (forage !== self) {
  707. // Self is already up-to-date.
  708. forage._dbInfo.db = dbInfo.db;
  709. forage._dbInfo.version = dbInfo.version;
  710. }
  711. }
  712. });
  713. }
  714. function getItem(key, callback) {
  715. var self = this;
  716. // Cast the key to a string, as that's all we can set as a key.
  717. if (typeof key !== 'string') {
  718. console.warn(key + ' used as a key, but it is not a string.');
  719. key = String(key);
  720. }
  721. var promise = new Promise$1(function (resolve, reject) {
  722. self.ready().then(function () {
  723. var dbInfo = self._dbInfo;
  724. var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
  725. var req = store.get(key);
  726. req.onsuccess = function () {
  727. var value = req.result;
  728. if (value === undefined) {
  729. value = null;
  730. }
  731. if (_isEncodedBlob(value)) {
  732. value = _decodeBlob(value);
  733. }
  734. resolve(value);
  735. };
  736. req.onerror = function () {
  737. reject(req.error);
  738. };
  739. })["catch"](reject);
  740. });
  741. executeCallback(promise, callback);
  742. return promise;
  743. }
  744. // Iterate over all items stored in database.
  745. function iterate(iterator, callback) {
  746. var self = this;
  747. var promise = new Promise$1(function (resolve, reject) {
  748. self.ready().then(function () {
  749. var dbInfo = self._dbInfo;
  750. var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
  751. var req = store.openCursor();
  752. var iterationNumber = 1;
  753. req.onsuccess = function () {
  754. var cursor = req.result;
  755. if (cursor) {
  756. var value = cursor.value;
  757. if (_isEncodedBlob(value)) {
  758. value = _decodeBlob(value);
  759. }
  760. var result = iterator(value, cursor.key, iterationNumber++);
  761. if (result !== void 0) {
  762. resolve(result);
  763. } else {
  764. cursor["continue"]();
  765. }
  766. } else {
  767. resolve();
  768. }
  769. };
  770. req.onerror = function () {
  771. reject(req.error);
  772. };
  773. })["catch"](reject);
  774. });
  775. executeCallback(promise, callback);
  776. return promise;
  777. }
  778. function setItem(key, value, callback) {
  779. var self = this;
  780. // Cast the key to a string, as that's all we can set as a key.
  781. if (typeof key !== 'string') {
  782. console.warn(key + ' used as a key, but it is not a string.');
  783. key = String(key);
  784. }
  785. var promise = new Promise$1(function (resolve, reject) {
  786. var dbInfo;
  787. self.ready().then(function () {
  788. dbInfo = self._dbInfo;
  789. if (toString.call(value) === '[object Blob]') {
  790. return _checkBlobSupport(dbInfo.db).then(function (blobSupport) {
  791. if (blobSupport) {
  792. return value;
  793. }
  794. return _encodeBlob(value);
  795. });
  796. }
  797. return value;
  798. }).then(function (value) {
  799. var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
  800. var store = transaction.objectStore(dbInfo.storeName);
  801. // The reason we don't _save_ null is because IE 10 does
  802. // not support saving the `null` type in IndexedDB. How
  803. // ironic, given the bug below!
  804. // See: https://github.com/mozilla/localForage/issues/161
  805. if (value === null) {
  806. value = undefined;
  807. }
  808. transaction.oncomplete = function () {
  809. // Cast to undefined so the value passed to
  810. // callback/promise is the same as what one would get out
  811. // of `getItem()` later. This leads to some weirdness
  812. // (setItem('foo', undefined) will return `null`), but
  813. // it's not my fault localStorage is our baseline and that
  814. // it's weird.
  815. if (value === undefined) {
  816. value = null;
  817. }
  818. resolve(value);
  819. };
  820. transaction.onabort = transaction.onerror = function () {
  821. var err = req.error ? req.error : req.transaction.error;
  822. reject(err);
  823. };
  824. var req = store.put(value, key);
  825. })["catch"](reject);
  826. });
  827. executeCallback(promise, callback);
  828. return promise;
  829. }
  830. function removeItem(key, callback) {
  831. var self = this;
  832. // Cast the key to a string, as that's all we can set as a key.
  833. if (typeof key !== 'string') {
  834. console.warn(key + ' used as a key, but it is not a string.');
  835. key = String(key);
  836. }
  837. var promise = new Promise$1(function (resolve, reject) {
  838. self.ready().then(function () {
  839. var dbInfo = self._dbInfo;
  840. var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
  841. var store = transaction.objectStore(dbInfo.storeName);
  842. // We use a Grunt task to make this safe for IE and some
  843. // versions of Android (including those used by Cordova).
  844. // Normally IE won't like `.delete()` and will insist on
  845. // using `['delete']()`, but we have a build step that
  846. // fixes this for us now.
  847. var req = store["delete"](key);
  848. transaction.oncomplete = function () {
  849. resolve();
  850. };
  851. transaction.onerror = function () {
  852. reject(req.error);
  853. };
  854. // The request will be also be aborted if we've exceeded our storage
  855. // space.
  856. transaction.onabort = function () {
  857. var err = req.error ? req.error : req.transaction.error;
  858. reject(err);
  859. };
  860. })["catch"](reject);
  861. });
  862. executeCallback(promise, callback);
  863. return promise;
  864. }
  865. function clear(callback) {
  866. var self = this;
  867. var promise = new Promise$1(function (resolve, reject) {
  868. self.ready().then(function () {
  869. var dbInfo = self._dbInfo;
  870. var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
  871. var store = transaction.objectStore(dbInfo.storeName);
  872. var req = store.clear();
  873. transaction.oncomplete = function () {
  874. resolve();
  875. };
  876. transaction.onabort = transaction.onerror = function () {
  877. var err = req.error ? req.error : req.transaction.error;
  878. reject(err);
  879. };
  880. })["catch"](reject);
  881. });
  882. executeCallback(promise, callback);
  883. return promise;
  884. }
  885. function length(callback) {
  886. var self = this;
  887. var promise = new Promise$1(function (resolve, reject) {
  888. self.ready().then(function () {
  889. var dbInfo = self._dbInfo;
  890. var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
  891. var req = store.count();
  892. req.onsuccess = function () {
  893. resolve(req.result);
  894. };
  895. req.onerror = function () {
  896. reject(req.error);
  897. };
  898. })["catch"](reject);
  899. });
  900. executeCallback(promise, callback);
  901. return promise;
  902. }
  903. function key(n, callback) {
  904. var self = this;
  905. var promise = new Promise$1(function (resolve, reject) {
  906. if (n < 0) {
  907. resolve(null);
  908. return;
  909. }
  910. self.ready().then(function () {
  911. var dbInfo = self._dbInfo;
  912. var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
  913. var advanced = false;
  914. var req = store.openCursor();
  915. req.onsuccess = function () {
  916. var cursor = req.result;
  917. if (!cursor) {
  918. // this means there weren't enough keys
  919. resolve(null);
  920. return;
  921. }
  922. if (n === 0) {
  923. // We have the first key, return it if that's what they
  924. // wanted.
  925. resolve(cursor.key);
  926. } else {
  927. if (!advanced) {
  928. // Otherwise, ask the cursor to skip ahead n
  929. // records.
  930. advanced = true;
  931. cursor.advance(n);
  932. } else {
  933. // When we get here, we've got the nth key.
  934. resolve(cursor.key);
  935. }
  936. }
  937. };
  938. req.onerror = function () {
  939. reject(req.error);
  940. };
  941. })["catch"](reject);
  942. });
  943. executeCallback(promise, callback);
  944. return promise;
  945. }
  946. function keys(callback) {
  947. var self = this;
  948. var promise = new Promise$1(function (resolve, reject) {
  949. self.ready().then(function () {
  950. var dbInfo = self._dbInfo;
  951. var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);
  952. var req = store.openCursor();
  953. var keys = [];
  954. req.onsuccess = function () {
  955. var cursor = req.result;
  956. if (!cursor) {
  957. resolve(keys);
  958. return;
  959. }
  960. keys.push(cursor.key);
  961. cursor["continue"]();
  962. };
  963. req.onerror = function () {
  964. reject(req.error);
  965. };
  966. })["catch"](reject);
  967. });
  968. executeCallback(promise, callback);
  969. return promise;
  970. }
  971. var asyncStorage = {
  972. _driver: 'asyncStorage',
  973. _initStorage: _initStorage,
  974. iterate: iterate,
  975. getItem: getItem,
  976. setItem: setItem,
  977. removeItem: removeItem,
  978. clear: clear,
  979. length: length,
  980. key: key,
  981. keys: keys
  982. };
  983. // Sadly, the best way to save binary data in WebSQL/localStorage is serializing
  984. // it to Base64, so this is how we store it to prevent very strange errors with less
  985. // verbose ways of binary <-> string data storage.
  986. var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  987. var BLOB_TYPE_PREFIX = '~~local_forage_type~';
  988. var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
  989. var SERIALIZED_MARKER = '__lfsc__:';
  990. var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;
  991. // OMG the serializations!
  992. var TYPE_ARRAYBUFFER = 'arbf';
  993. var TYPE_BLOB = 'blob';
  994. var TYPE_INT8ARRAY = 'si08';
  995. var TYPE_UINT8ARRAY = 'ui08';
  996. var TYPE_UINT8CLAMPEDARRAY = 'uic8';
  997. var TYPE_INT16ARRAY = 'si16';
  998. var TYPE_INT32ARRAY = 'si32';
  999. var TYPE_UINT16ARRAY = 'ur16';
  1000. var TYPE_UINT32ARRAY = 'ui32';
  1001. var TYPE_FLOAT32ARRAY = 'fl32';
  1002. var TYPE_FLOAT64ARRAY = 'fl64';
  1003. var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length;
  1004. var toString$1 = Object.prototype.toString;
  1005. function stringToBuffer(serializedString) {
  1006. // Fill the string into a ArrayBuffer.
  1007. var bufferLength = serializedString.length * 0.75;
  1008. var len = serializedString.length;
  1009. var i;
  1010. var p = 0;
  1011. var encoded1, encoded2, encoded3, encoded4;
  1012. if (serializedString[serializedString.length - 1] === '=') {
  1013. bufferLength--;
  1014. if (serializedString[serializedString.length - 2] === '=') {
  1015. bufferLength--;
  1016. }
  1017. }
  1018. var buffer = new ArrayBuffer(bufferLength);
  1019. var bytes = new Uint8Array(buffer);
  1020. for (i = 0; i < len; i += 4) {
  1021. encoded1 = BASE_CHARS.indexOf(serializedString[i]);
  1022. encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]);
  1023. encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]);
  1024. encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]);
  1025. /*jslint bitwise: true */
  1026. bytes[p++] = encoded1 << 2 | encoded2 >> 4;
  1027. bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
  1028. bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
  1029. }
  1030. return buffer;
  1031. }
  1032. // Converts a buffer to a string to store, serialized, in the backend
  1033. // storage library.
  1034. function bufferToString(buffer) {
  1035. // base64-arraybuffer
  1036. var bytes = new Uint8Array(buffer);
  1037. var base64String = '';
  1038. var i;
  1039. for (i = 0; i < bytes.length; i += 3) {
  1040. /*jslint bitwise: true */
  1041. base64String += BASE_CHARS[bytes[i] >> 2];
  1042. base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];
  1043. base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];
  1044. base64String += BASE_CHARS[bytes[i + 2] & 63];
  1045. }
  1046. if (bytes.length % 3 === 2) {
  1047. base64String = base64String.substring(0, base64String.length - 1) + '=';
  1048. } else if (bytes.length % 3 === 1) {
  1049. base64String = base64String.substring(0, base64String.length - 2) + '==';
  1050. }
  1051. return base64String;
  1052. }
  1053. // Serialize a value, afterwards executing a callback (which usually
  1054. // instructs the `setItem()` callback/promise to be executed). This is how
  1055. // we store binary data with localStorage.
  1056. function serialize(value, callback) {
  1057. var valueType = '';
  1058. if (value) {
  1059. valueType = toString$1.call(value);
  1060. }
  1061. // Cannot use `value instanceof ArrayBuffer` or such here, as these
  1062. // checks fail when running the tests using casper.js...
  1063. //
  1064. // TODO: See why those tests fail and use a better solution.
  1065. if (value && (valueType === '[object ArrayBuffer]' || value.buffer && toString$1.call(value.buffer) === '[object ArrayBuffer]')) {
  1066. // Convert binary arrays to a string and prefix the string with
  1067. // a special marker.
  1068. var buffer;
  1069. var marker = SERIALIZED_MARKER;
  1070. if (value instanceof ArrayBuffer) {
  1071. buffer = value;
  1072. marker += TYPE_ARRAYBUFFER;
  1073. } else {
  1074. buffer = value.buffer;
  1075. if (valueType === '[object Int8Array]') {
  1076. marker += TYPE_INT8ARRAY;
  1077. } else if (valueType === '[object Uint8Array]') {
  1078. marker += TYPE_UINT8ARRAY;
  1079. } else if (valueType === '[object Uint8ClampedArray]') {
  1080. marker += TYPE_UINT8CLAMPEDARRAY;
  1081. } else if (valueType === '[object Int16Array]') {
  1082. marker += TYPE_INT16ARRAY;
  1083. } else if (valueType === '[object Uint16Array]') {
  1084. marker += TYPE_UINT16ARRAY;
  1085. } else if (valueType === '[object Int32Array]') {
  1086. marker += TYPE_INT32ARRAY;
  1087. } else if (valueType === '[object Uint32Array]') {
  1088. marker += TYPE_UINT32ARRAY;
  1089. } else if (valueType === '[object Float32Array]') {
  1090. marker += TYPE_FLOAT32ARRAY;
  1091. } else if (valueType === '[object Float64Array]') {
  1092. marker += TYPE_FLOAT64ARRAY;
  1093. } else {
  1094. callback(new Error('Failed to get type for BinaryArray'));
  1095. }
  1096. }
  1097. callback(marker + bufferToString(buffer));
  1098. } else if (valueType === '[object Blob]') {
  1099. // Conver the blob to a binaryArray and then to a string.
  1100. var fileReader = new FileReader();
  1101. fileReader.onload = function () {
  1102. // Backwards-compatible prefix for the blob type.
  1103. var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result);
  1104. callback(SERIALIZED_MARKER + TYPE_BLOB + str);
  1105. };
  1106. fileReader.readAsArrayBuffer(value);
  1107. } else {
  1108. try {
  1109. callback(JSON.stringify(value));
  1110. } catch (e) {
  1111. console.error("Couldn't convert value into a JSON string: ", value);
  1112. callback(null, e);
  1113. }
  1114. }
  1115. }
  1116. // Deserialize data we've inserted into a value column/field. We place
  1117. // special markers into our strings to mark them as encoded; this isn't
  1118. // as nice as a meta field, but it's the only sane thing we can do whilst
  1119. // keeping localStorage support intact.
  1120. //
  1121. // Oftentimes this will just deserialize JSON content, but if we have a
  1122. // special marker (SERIALIZED_MARKER, defined above), we will extract
  1123. // some kind of arraybuffer/binary data/typed array out of the string.
  1124. function deserialize(value) {
  1125. // If we haven't marked this string as being specially serialized (i.e.
  1126. // something other than serialized JSON), we can just return it and be
  1127. // done with it.
  1128. if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
  1129. return JSON.parse(value);
  1130. }
  1131. // The following code deals with deserializing some kind of Blob or
  1132. // TypedArray. First we separate out the type of data we're dealing
  1133. // with from the data itself.
  1134. var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
  1135. var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);
  1136. var blobType;
  1137. // Backwards-compatible blob type serialization strategy.
  1138. // DBs created with older versions of localForage will simply not have the blob type.
  1139. if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
  1140. var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
  1141. blobType = matcher[1];
  1142. serializedString = serializedString.substring(matcher[0].length);
  1143. }
  1144. var buffer = stringToBuffer(serializedString);
  1145. // Return the right type based on the code/type set during
  1146. // serialization.
  1147. switch (type) {
  1148. case TYPE_ARRAYBUFFER:
  1149. return buffer;
  1150. case TYPE_BLOB:
  1151. return createBlob([buffer], { type: blobType });
  1152. case TYPE_INT8ARRAY:
  1153. return new Int8Array(buffer);
  1154. case TYPE_UINT8ARRAY:
  1155. return new Uint8Array(buffer);
  1156. case TYPE_UINT8CLAMPEDARRAY:
  1157. return new Uint8ClampedArray(buffer);
  1158. case TYPE_INT16ARRAY:
  1159. return new Int16Array(buffer);
  1160. case TYPE_UINT16ARRAY:
  1161. return new Uint16Array(buffer);
  1162. case TYPE_INT32ARRAY:
  1163. return new Int32Array(buffer);
  1164. case TYPE_UINT32ARRAY:
  1165. return new Uint32Array(buffer);
  1166. case TYPE_FLOAT32ARRAY:
  1167. return new Float32Array(buffer);
  1168. case TYPE_FLOAT64ARRAY:
  1169. return new Float64Array(buffer);
  1170. default:
  1171. throw new Error('Unkown type: ' + type);
  1172. }
  1173. }
  1174. var localforageSerializer = {
  1175. serialize: serialize,
  1176. deserialize: deserialize,
  1177. stringToBuffer: stringToBuffer,
  1178. bufferToString: bufferToString
  1179. };
  1180. /*
  1181. * Includes code from:
  1182. *
  1183. * base64-arraybuffer
  1184. * https://github.com/niklasvh/base64-arraybuffer
  1185. *
  1186. * Copyright (c) 2012 Niklas von Hertzen
  1187. * Licensed under the MIT license.
  1188. */
  1189. // Open the WebSQL database (automatically creates one if one didn't
  1190. // previously exist), using any options set in the config.
  1191. function _initStorage$1(options) {
  1192. var self = this;
  1193. var dbInfo = {
  1194. db: null
  1195. };
  1196. if (options) {
  1197. for (var i in options) {
  1198. dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i];
  1199. }
  1200. }
  1201. var dbInfoPromise = new Promise$1(function (resolve, reject) {
  1202. // Open the database; the openDatabase API will automatically
  1203. // create it for us if it doesn't exist.
  1204. try {
  1205. dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);
  1206. } catch (e) {
  1207. return reject(e);
  1208. }
  1209. // Create our key/value table if it doesn't exist.
  1210. dbInfo.db.transaction(function (t) {
  1211. t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function () {
  1212. self._dbInfo = dbInfo;
  1213. resolve();
  1214. }, function (t, error) {
  1215. reject(error);
  1216. });
  1217. });
  1218. });
  1219. dbInfo.serializer = localforageSerializer;
  1220. return dbInfoPromise;
  1221. }
  1222. function getItem$1(key, callback) {
  1223. var self = this;
  1224. // Cast the key to a string, as that's all we can set as a key.
  1225. if (typeof key !== 'string') {
  1226. console.warn(key + ' used as a key, but it is not a string.');
  1227. key = String(key);
  1228. }
  1229. var promise = new Promise$1(function (resolve, reject) {
  1230. self.ready().then(function () {
  1231. var dbInfo = self._dbInfo;
  1232. dbInfo.db.transaction(function (t) {
  1233. t.executeSql('SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) {
  1234. var result = results.rows.length ? results.rows.item(0).value : null;
  1235. // Check to see if this is serialized content we need to
  1236. // unpack.
  1237. if (result) {
  1238. result = dbInfo.serializer.deserialize(result);
  1239. }
  1240. resolve(result);
  1241. }, function (t, error) {
  1242. reject(error);
  1243. });
  1244. });
  1245. })["catch"](reject);
  1246. });
  1247. executeCallback(promise, callback);
  1248. return promise;
  1249. }
  1250. function iterate$1(iterator, callback) {
  1251. var self = this;
  1252. var promise = new Promise$1(function (resolve, reject) {
  1253. self.ready().then(function () {
  1254. var dbInfo = self._dbInfo;
  1255. dbInfo.db.transaction(function (t) {
  1256. t.executeSql('SELECT * FROM ' + dbInfo.storeName, [], function (t, results) {
  1257. var rows = results.rows;
  1258. var length = rows.length;
  1259. for (var i = 0; i < length; i++) {
  1260. var item = rows.item(i);
  1261. var result = item.value;
  1262. // Check to see if this is serialized content
  1263. // we need to unpack.
  1264. if (result) {
  1265. result = dbInfo.serializer.deserialize(result);
  1266. }
  1267. result = iterator(result, item.key, i + 1);
  1268. // void(0) prevents problems with redefinition
  1269. // of `undefined`.
  1270. if (result !== void 0) {
  1271. resolve(result);
  1272. return;
  1273. }
  1274. }
  1275. resolve();
  1276. }, function (t, error) {
  1277. reject(error);
  1278. });
  1279. });
  1280. })["catch"](reject);
  1281. });
  1282. executeCallback(promise, callback);
  1283. return promise;
  1284. }
  1285. function setItem$1(key, value, callback) {
  1286. var self = this;
  1287. // Cast the key to a string, as that's all we can set as a key.
  1288. if (typeof key !== 'string') {
  1289. console.warn(key + ' used as a key, but it is not a string.');
  1290. key = String(key);
  1291. }
  1292. var promise = new Promise$1(function (resolve, reject) {
  1293. self.ready().then(function () {
  1294. // The localStorage API doesn't return undefined values in an
  1295. // "expected" way, so undefined is always cast to null in all
  1296. // drivers. See: https://github.com/mozilla/localForage/pull/42
  1297. if (value === undefined) {
  1298. value = null;
  1299. }
  1300. // Save the original value to pass to the callback.
  1301. var originalValue = value;
  1302. var dbInfo = self._dbInfo;
  1303. dbInfo.serializer.serialize(value, function (value, error) {
  1304. if (error) {
  1305. reject(error);
  1306. } else {
  1307. dbInfo.db.transaction(function (t) {
  1308. t.executeSql('INSERT OR REPLACE INTO ' + dbInfo.storeName + ' (key, value) VALUES (?, ?)', [key, value], function () {
  1309. resolve(originalValue);
  1310. }, function (t, error) {
  1311. reject(error);
  1312. });
  1313. }, function (sqlError) {
  1314. // The transaction failed; check
  1315. // to see if it's a quota error.
  1316. if (sqlError.code === sqlError.QUOTA_ERR) {
  1317. // We reject the callback outright for now, but
  1318. // it's worth trying to re-run the transaction.
  1319. // Even if the user accepts the prompt to use
  1320. // more storage on Safari, this error will
  1321. // be called.
  1322. //
  1323. // TODO: Try to re-run the transaction.
  1324. reject(sqlError);
  1325. }
  1326. });
  1327. }
  1328. });
  1329. })["catch"](reject);
  1330. });
  1331. executeCallback(promise, callback);
  1332. return promise;
  1333. }
  1334. function removeItem$1(key, callback) {
  1335. var self = this;
  1336. // Cast the key to a string, as that's all we can set as a key.
  1337. if (typeof key !== 'string') {
  1338. console.warn(key + ' used as a key, but it is not a string.');
  1339. key = String(key);
  1340. }
  1341. var promise = new Promise$1(function (resolve, reject) {
  1342. self.ready().then(function () {
  1343. var dbInfo = self._dbInfo;
  1344. dbInfo.db.transaction(function (t) {
  1345. t.executeSql('DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () {
  1346. resolve();
  1347. }, function (t, error) {
  1348. reject(error);
  1349. });
  1350. });
  1351. })["catch"](reject);
  1352. });
  1353. executeCallback(promise, callback);
  1354. return promise;
  1355. }
  1356. // Deletes every item in the table.
  1357. // TODO: Find out if this resets the AUTO_INCREMENT number.
  1358. function clear$1(callback) {
  1359. var self = this;
  1360. var promise = new Promise$1(function (resolve, reject) {
  1361. self.ready().then(function () {
  1362. var dbInfo = self._dbInfo;
  1363. dbInfo.db.transaction(function (t) {
  1364. t.executeSql('DELETE FROM ' + dbInfo.storeName, [], function () {
  1365. resolve();
  1366. }, function (t, error) {
  1367. reject(error);
  1368. });
  1369. });
  1370. })["catch"](reject);
  1371. });
  1372. executeCallback(promise, callback);
  1373. return promise;
  1374. }
  1375. // Does a simple `COUNT(key)` to get the number of items stored in
  1376. // localForage.
  1377. function length$1(callback) {
  1378. var self = this;
  1379. var promise = new Promise$1(function (resolve, reject) {
  1380. self.ready().then(function () {
  1381. var dbInfo = self._dbInfo;
  1382. dbInfo.db.transaction(function (t) {
  1383. // Ahhh, SQL makes this one soooooo easy.
  1384. t.executeSql('SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) {
  1385. var result = results.rows.item(0).c;
  1386. resolve(result);
  1387. }, function (t, error) {
  1388. reject(error);
  1389. });
  1390. });
  1391. })["catch"](reject);
  1392. });
  1393. executeCallback(promise, callback);
  1394. return promise;
  1395. }
  1396. // Return the key located at key index X; essentially gets the key from a
  1397. // `WHERE id = ?`. This is the most efficient way I can think to implement
  1398. // this rarely-used (in my experience) part of the API, but it can seem
  1399. // inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so
  1400. // the ID of each key will change every time it's updated. Perhaps a stored
  1401. // procedure for the `setItem()` SQL would solve this problem?
  1402. // TODO: Don't change ID on `setItem()`.
  1403. function key$1(n, callback) {
  1404. var self = this;
  1405. var promise = new Promise$1(function (resolve, reject) {
  1406. self.ready().then(function () {
  1407. var dbInfo = self._dbInfo;
  1408. dbInfo.db.transaction(function (t) {
  1409. t.executeSql('SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) {
  1410. var result = results.rows.length ? results.rows.item(0).key : null;
  1411. resolve(result);
  1412. }, function (t, error) {
  1413. reject(error);
  1414. });
  1415. });
  1416. })["catch"](reject);
  1417. });
  1418. executeCallback(promise, callback);
  1419. return promise;
  1420. }
  1421. function keys$1(callback) {
  1422. var self = this;
  1423. var promise = new Promise$1(function (resolve, reject) {
  1424. self.ready().then(function () {
  1425. var dbInfo = self._dbInfo;
  1426. dbInfo.db.transaction(function (t) {
  1427. t.executeSql('SELECT key FROM ' + dbInfo.storeName, [], function (t, results) {
  1428. var keys = [];
  1429. for (var i = 0; i < results.rows.length; i++) {
  1430. keys.push(results.rows.item(i).key);
  1431. }
  1432. resolve(keys);
  1433. }, function (t, error) {
  1434. reject(error);
  1435. });
  1436. });
  1437. })["catch"](reject);
  1438. });
  1439. executeCallback(promise, callback);
  1440. return promise;
  1441. }
  1442. var webSQLStorage = {
  1443. _driver: 'webSQLStorage',
  1444. _initStorage: _initStorage$1,
  1445. iterate: iterate$1,
  1446. getItem: getItem$1,
  1447. setItem: setItem$1,
  1448. removeItem: removeItem$1,
  1449. clear: clear$1,
  1450. length: length$1,
  1451. key: key$1,
  1452. keys: keys$1
  1453. };
  1454. // Config the localStorage backend, using options set in the config.
  1455. function _initStorage$2(options) {
  1456. var self = this;
  1457. var dbInfo = {};
  1458. if (options) {
  1459. for (var i in options) {
  1460. dbInfo[i] = options[i];
  1461. }
  1462. }
  1463. dbInfo.keyPrefix = dbInfo.name + '/';
  1464. if (dbInfo.storeName !== self._defaultConfig.storeName) {
  1465. dbInfo.keyPrefix += dbInfo.storeName + '/';
  1466. }
  1467. self._dbInfo = dbInfo;
  1468. dbInfo.serializer = localforageSerializer;
  1469. return Promise$1.resolve();
  1470. }
  1471. // Remove all keys from the datastore, effectively destroying all data in
  1472. // the app's key/value store!
  1473. function clear$2(callback) {
  1474. var self = this;
  1475. var promise = self.ready().then(function () {
  1476. var keyPrefix = self._dbInfo.keyPrefix;
  1477. for (var i = localStorage.length - 1; i >= 0; i--) {
  1478. var key = localStorage.key(i);
  1479. if (key.indexOf(keyPrefix) === 0) {
  1480. localStorage.removeItem(key);
  1481. }
  1482. }
  1483. });
  1484. executeCallback(promise, callback);
  1485. return promise;
  1486. }
  1487. // Retrieve an item from the store. Unlike the original async_storage
  1488. // library in Gaia, we don't modify return values at all. If a key's value
  1489. // is `undefined`, we pass that value to the callback function.
  1490. function getItem$2(key, callback) {
  1491. var self = this;
  1492. // Cast the key to a string, as that's all we can set as a key.
  1493. if (typeof key !== 'string') {
  1494. console.warn(key + ' used as a key, but it is not a string.');
  1495. key = String(key);
  1496. }
  1497. var promise = self.ready().then(function () {
  1498. var dbInfo = self._dbInfo;
  1499. var result = localStorage.getItem(dbInfo.keyPrefix + key);
  1500. // If a result was found, parse it from the serialized
  1501. // string into a JS object. If result isn't truthy, the key
  1502. // is likely undefined and we'll pass it straight to the
  1503. // callback.
  1504. if (result) {
  1505. result = dbInfo.serializer.deserialize(result);
  1506. }
  1507. return result;
  1508. });
  1509. executeCallback(promise, callback);
  1510. return promise;
  1511. }
  1512. // Iterate over all items in the store.
  1513. function iterate$2(iterator, callback) {
  1514. var self = this;
  1515. var promise = self.ready().then(function () {
  1516. var dbInfo = self._dbInfo;
  1517. var keyPrefix = dbInfo.keyPrefix;
  1518. var keyPrefixLength = keyPrefix.length;
  1519. var length = localStorage.length;
  1520. // We use a dedicated iterator instead of the `i` variable below
  1521. // so other keys we fetch in localStorage aren't counted in
  1522. // the `iterationNumber` argument passed to the `iterate()`
  1523. // callback.
  1524. //
  1525. // See: github.com/mozilla/localForage/pull/435#discussion_r38061530
  1526. var iterationNumber = 1;
  1527. for (var i = 0; i < length; i++) {
  1528. var key = localStorage.key(i);
  1529. if (key.indexOf(keyPrefix) !== 0) {
  1530. continue;
  1531. }
  1532. var value = localStorage.getItem(key);
  1533. // If a result was found, parse it from the serialized
  1534. // string into a JS object. If result isn't truthy, the
  1535. // key is likely undefined and we'll pass it straight
  1536. // to the iterator.
  1537. if (value) {
  1538. value = dbInfo.serializer.deserialize(value);
  1539. }
  1540. value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);
  1541. if (value !== void 0) {
  1542. return value;
  1543. }
  1544. }
  1545. });
  1546. executeCallback(promise, callback);
  1547. return promise;
  1548. }
  1549. // Same as localStorage's key() method, except takes a callback.
  1550. function key$2(n, callback) {
  1551. var self = this;
  1552. var promise = self.ready().then(function () {
  1553. var dbInfo = self._dbInfo;
  1554. var result;
  1555. try {
  1556. result = localStorage.key(n);
  1557. } catch (error) {
  1558. result = null;
  1559. }
  1560. // Remove the prefix from the key, if a key is found.
  1561. if (result) {
  1562. result = result.substring(dbInfo.keyPrefix.length);
  1563. }
  1564. return result;
  1565. });
  1566. executeCallback(promise, callback);
  1567. return promise;
  1568. }
  1569. function keys$2(callback) {
  1570. var self = this;
  1571. var promise = self.ready().then(function () {
  1572. var dbInfo = self._dbInfo;
  1573. var length = localStorage.length;
  1574. var keys = [];
  1575. for (var i = 0; i < length; i++) {
  1576. if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) {
  1577. keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length));
  1578. }
  1579. }
  1580. return keys;
  1581. });
  1582. executeCallback(promise, callback);
  1583. return promise;
  1584. }
  1585. // Supply the number of keys in the datastore to the callback function.
  1586. function length$2(callback) {
  1587. var self = this;
  1588. var promise = self.keys().then(function (keys) {
  1589. return keys.length;
  1590. });
  1591. executeCallback(promise, callback);
  1592. return promise;
  1593. }
  1594. // Remove an item from the store, nice and simple.
  1595. function removeItem$2(key, callback) {
  1596. var self = this;
  1597. // Cast the key to a string, as that's all we can set as a key.
  1598. if (typeof key !== 'string') {
  1599. console.warn(key + ' used as a key, but it is not a string.');
  1600. key = String(key);
  1601. }
  1602. var promise = self.ready().then(function () {
  1603. var dbInfo = self._dbInfo;
  1604. localStorage.removeItem(dbInfo.keyPrefix + key);
  1605. });
  1606. executeCallback(promise, callback);
  1607. return promise;
  1608. }
  1609. // Set a key's value and run an optional callback once the value is set.
  1610. // Unlike Gaia's implementation, the callback function is passed the value,
  1611. // in case you want to operate on that value only after you're sure it
  1612. // saved, or something like that.
  1613. function setItem$2(key, value, callback) {
  1614. var self = this;
  1615. // Cast the key to a string, as that's all we can set as a key.
  1616. if (typeof key !== 'string') {
  1617. console.warn(key + ' used as a key, but it is not a string.');
  1618. key = String(key);
  1619. }
  1620. var promise = self.ready().then(function () {
  1621. // Convert undefined values to null.
  1622. // https://github.com/mozilla/localForage/pull/42
  1623. if (value === undefined) {
  1624. value = null;
  1625. }
  1626. // Save the original value to pass to the callback.
  1627. var originalValue = value;
  1628. return new Promise$1(function (resolve, reject) {
  1629. var dbInfo = self._dbInfo;
  1630. dbInfo.serializer.serialize(value, function (value, error) {
  1631. if (error) {
  1632. reject(error);
  1633. } else {
  1634. try {
  1635. localStorage.setItem(dbInfo.keyPrefix + key, value);
  1636. resolve(originalValue);
  1637. } catch (e) {
  1638. // localStorage capacity exceeded.
  1639. // TODO: Make this a specific error/event.
  1640. if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
  1641. reject(e);
  1642. }
  1643. reject(e);
  1644. }
  1645. }
  1646. });
  1647. });
  1648. });
  1649. executeCallback(promise, callback);
  1650. return promise;
  1651. }
  1652. var localStorageWrapper = {
  1653. _driver: 'localStorageWrapper',
  1654. _initStorage: _initStorage$2,
  1655. // Default API, from Gaia/localStorage.
  1656. iterate: iterate$2,
  1657. getItem: getItem$2,
  1658. setItem: setItem$2,
  1659. removeItem: removeItem$2,
  1660. clear: clear$2,
  1661. length: length$2,
  1662. key: key$2,
  1663. keys: keys$2
  1664. };
  1665. // Custom drivers are stored here when `defineDriver()` is called.
  1666. // They are shared across all instances of localForage.
  1667. var CustomDrivers = {};
  1668. var DriverType = {
  1669. INDEXEDDB: 'asyncStorage',
  1670. LOCALSTORAGE: 'localStorageWrapper',
  1671. WEBSQL: 'webSQLStorage'
  1672. };
  1673. var DefaultDriverOrder = [DriverType.INDEXEDDB, DriverType.WEBSQL, DriverType.LOCALSTORAGE];
  1674. var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem'];
  1675. var DefaultConfig = {
  1676. description: '',
  1677. driver: DefaultDriverOrder.slice(),
  1678. name: 'localforage',
  1679. // Default DB size is _JUST UNDER_ 5MB, as it's the highest size
  1680. // we can use without a prompt.
  1681. size: 4980736,
  1682. storeName: 'keyvaluepairs',
  1683. version: 1.0
  1684. };
  1685. var driverSupport = {};
  1686. // Check to see if IndexedDB is available and if it is the latest
  1687. // implementation; it's our preferred backend library. We use "_spec_test"
  1688. // as the name of the database because it's not the one we'll operate on,
  1689. // but it's useful to make sure its using the right spec.
  1690. // See: https://github.com/mozilla/localForage/issues/128
  1691. driverSupport[DriverType.INDEXEDDB] = isIndexedDBValid();
  1692. driverSupport[DriverType.WEBSQL] = isWebSQLValid();
  1693. driverSupport[DriverType.LOCALSTORAGE] = isLocalStorageValid();
  1694. var isArray = Array.isArray || function (arg) {
  1695. return Object.prototype.toString.call(arg) === '[object Array]';
  1696. };
  1697. function callWhenReady(localForageInstance, libraryMethod) {
  1698. localForageInstance[libraryMethod] = function () {
  1699. var _args = arguments;
  1700. return localForageInstance.ready().then(function () {
  1701. return localForageInstance[libraryMethod].apply(localForageInstance, _args);
  1702. });
  1703. };
  1704. }
  1705. function extend() {
  1706. for (var i = 1; i < arguments.length; i++) {
  1707. var arg = arguments[i];
  1708. if (arg) {
  1709. for (var key in arg) {
  1710. if (arg.hasOwnProperty(key)) {
  1711. if (isArray(arg[key])) {
  1712. arguments[0][key] = arg[key].slice();
  1713. } else {
  1714. arguments[0][key] = arg[key];
  1715. }
  1716. }
  1717. }
  1718. }
  1719. }
  1720. return arguments[0];
  1721. }
  1722. function isLibraryDriver(driverName) {
  1723. for (var driver in DriverType) {
  1724. if (DriverType.hasOwnProperty(driver) && DriverType[driver] === driverName) {
  1725. return true;
  1726. }
  1727. }
  1728. return false;
  1729. }
  1730. var LocalForage = function () {
  1731. function LocalForage(options) {
  1732. _classCallCheck(this, LocalForage);
  1733. this.INDEXEDDB = DriverType.INDEXEDDB;
  1734. this.LOCALSTORAGE = DriverType.LOCALSTORAGE;
  1735. this.WEBSQL = DriverType.WEBSQL;
  1736. this._defaultConfig = extend({}, DefaultConfig);
  1737. this._config = extend({}, this._defaultConfig, options);
  1738. this._driverSet = null;
  1739. this._initDriver = null;
  1740. this._ready = false;
  1741. this._dbInfo = null;
  1742. this._wrapLibraryMethodsWithReady();
  1743. this.setDriver(this._config.driver);
  1744. }
  1745. // Set any config values for localForage; can be called anytime before
  1746. // the first API call (e.g. `getItem`, `setItem`).
  1747. // We loop through options so we don't overwrite existing config
  1748. // values.
  1749. LocalForage.prototype.config = function config(options) {
  1750. // If the options argument is an object, we use it to set values.
  1751. // Otherwise, we return either a specified config value or all
  1752. // config values.
  1753. if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') {
  1754. // If localforage is ready and fully initialized, we can't set
  1755. // any new configuration values. Instead, we return an error.
  1756. if (this._ready) {
  1757. return new Error("Can't call config() after localforage " + 'has been used.');
  1758. }
  1759. for (var i in options) {
  1760. if (i === 'storeName') {
  1761. options[i] = options[i].replace(/\W/g, '_');
  1762. }
  1763. this._config[i] = options[i];
  1764. }
  1765. // after all config options are set and
  1766. // the driver option is used, try setting it
  1767. if ('driver' in options && options.driver) {
  1768. this.setDriver(this._config.driver);
  1769. }
  1770. return true;
  1771. } else if (typeof options === 'string') {
  1772. return this._config[options];
  1773. } else {
  1774. return this._config;
  1775. }
  1776. };
  1777. // Used to define a custom driver, shared across all instances of
  1778. // localForage.
  1779. LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) {
  1780. var promise = new Promise$1(function (resolve, reject) {
  1781. try {
  1782. var driverName = driverObject._driver;
  1783. var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver');
  1784. var namingError = new Error('Custom driver name already in use: ' + driverObject._driver);
  1785. // A driver name should be defined and not overlap with the
  1786. // library-defined, default drivers.
  1787. if (!driverObject._driver) {
  1788. reject(complianceError);
  1789. return;
  1790. }
  1791. if (isLibraryDriver(driverObject._driver)) {
  1792. reject(namingError);
  1793. return;
  1794. }
  1795. var customDriverMethods = LibraryMethods.concat('_initStorage');
  1796. for (var i = 0; i < customDriverMethods.length; i++) {
  1797. var customDriverMethod = customDriverMethods[i];
  1798. if (!customDriverMethod || !driverObject[customDriverMethod] || typeof driverObject[customDriverMethod] !== 'function') {
  1799. reject(complianceError);
  1800. return;
  1801. }
  1802. }
  1803. var supportPromise = Promise$1.resolve(true);
  1804. if ('_support' in driverObject) {
  1805. if (driverObject._support && typeof driverObject._support === 'function') {
  1806. supportPromise = driverObject._support();
  1807. } else {
  1808. supportPromise = Promise$1.resolve(!!driverObject._support);
  1809. }
  1810. }
  1811. supportPromise.then(function (supportResult) {
  1812. driverSupport[driverName] = supportResult;
  1813. CustomDrivers[driverName] = driverObject;
  1814. resolve();
  1815. }, reject);
  1816. } catch (e) {
  1817. reject(e);
  1818. }
  1819. });
  1820. executeTwoCallbacks(promise, callback, errorCallback);
  1821. return promise;
  1822. };
  1823. LocalForage.prototype.driver = function driver() {
  1824. return this._driver || null;
  1825. };
  1826. LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) {
  1827. var self = this;
  1828. var getDriverPromise = Promise$1.resolve().then(function () {
  1829. if (isLibraryDriver(driverName)) {
  1830. switch (driverName) {
  1831. case self.INDEXEDDB:
  1832. return asyncStorage;
  1833. case self.LOCALSTORAGE:
  1834. return localStorageWrapper;
  1835. case self.WEBSQL:
  1836. return webSQLStorage;
  1837. }
  1838. } else if (CustomDrivers[driverName]) {
  1839. return CustomDrivers[driverName];
  1840. } else {
  1841. throw new Error('Driver not found.');
  1842. }
  1843. });
  1844. executeTwoCallbacks(getDriverPromise, callback, errorCallback);
  1845. return getDriverPromise;
  1846. };
  1847. LocalForage.prototype.getSerializer = function getSerializer(callback) {
  1848. var serializerPromise = Promise$1.resolve(localforageSerializer);
  1849. executeTwoCallbacks(serializerPromise, callback);
  1850. return serializerPromise;
  1851. };
  1852. LocalForage.prototype.ready = function ready(callback) {
  1853. var self = this;
  1854. var promise = self._driverSet.then(function () {
  1855. if (self._ready === null) {
  1856. self._ready = self._initDriver();
  1857. }
  1858. return self._ready;
  1859. });
  1860. executeTwoCallbacks(promise, callback, callback);
  1861. return promise;
  1862. };
  1863. LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) {
  1864. var self = this;
  1865. if (!isArray(drivers)) {
  1866. drivers = [drivers];
  1867. }
  1868. var supportedDrivers = this._getSupportedDrivers(drivers);
  1869. function setDriverToConfig() {
  1870. self._config.driver = self.driver();
  1871. }
  1872. function initDriver(supportedDrivers) {
  1873. return function () {
  1874. var currentDriverIndex = 0;
  1875. function driverPromiseLoop() {
  1876. while (currentDriverIndex < supportedDrivers.length) {
  1877. var driverName = supportedDrivers[currentDriverIndex];
  1878. currentDriverIndex++;
  1879. self._dbInfo = null;
  1880. self._ready = null;
  1881. return self.getDriver(driverName).then(function (driver) {
  1882. self._extend(driver);
  1883. setDriverToConfig();
  1884. self._ready = self._initStorage(self._config);
  1885. return self._ready;
  1886. })["catch"](driverPromiseLoop);
  1887. }
  1888. setDriverToConfig();
  1889. var error = new Error('No available storage method found.');
  1890. self._driverSet = Promise$1.reject(error);
  1891. return self._driverSet;
  1892. }
  1893. return driverPromiseLoop();
  1894. };
  1895. }
  1896. // There might be a driver initialization in progress
  1897. // so wait for it to finish in order to avoid a possible
  1898. // race condition to set _dbInfo
  1899. var oldDriverSetDone = this._driverSet !== null ? this._driverSet["catch"](function () {
  1900. return Promise$1.resolve();
  1901. }) : Promise$1.resolve();
  1902. this._driverSet = oldDriverSetDone.then(function () {
  1903. var driverName = supportedDrivers[0];
  1904. self._dbInfo = null;
  1905. self._ready = null;
  1906. return self.getDriver(driverName).then(function (driver) {
  1907. self._driver = driver._driver;
  1908. setDriverToConfig();
  1909. self._wrapLibraryMethodsWithReady();
  1910. self._initDriver = initDriver(supportedDrivers);
  1911. });
  1912. })["catch"](function () {
  1913. setDriverToConfig();
  1914. var error = new Error('No available storage method found.');
  1915. self._driverSet = Promise$1.reject(error);
  1916. return self._driverSet;
  1917. });
  1918. executeTwoCallbacks(this._driverSet, callback, errorCallback);
  1919. return this._driverSet;
  1920. };
  1921. LocalForage.prototype.supports = function supports(driverName) {
  1922. return !!driverSupport[driverName];
  1923. };
  1924. LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) {
  1925. extend(this, libraryMethodsAndProperties);
  1926. };
  1927. LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) {
  1928. var supportedDrivers = [];
  1929. for (var i = 0, len = drivers.length; i < len; i++) {
  1930. var driverName = drivers[i];
  1931. if (this.supports(driverName)) {
  1932. supportedDrivers.push(driverName);
  1933. }
  1934. }
  1935. return supportedDrivers;
  1936. };
  1937. LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() {
  1938. // Add a stub for each driver API method that delays the call to the
  1939. // corresponding driver method until localForage is ready. These stubs
  1940. // will be replaced by the driver methods as soon as the driver is
  1941. // loaded, so there is no performance impact.
  1942. for (var i = 0; i < LibraryMethods.length; i++) {
  1943. callWhenReady(this, LibraryMethods[i]);
  1944. }
  1945. };
  1946. LocalForage.prototype.createInstance = function createInstance(options) {
  1947. return new LocalForage(options);
  1948. };
  1949. return LocalForage;
  1950. }();
  1951. // The actual localForage object that we expose as a module or via a
  1952. // global. It's extended by pulling in one of our other libraries.
  1953. var localforage_js = new LocalForage();
  1954. module.exports = localforage_js;
  1955. },{"3":3}]},{},[4])(4)
  1956. });