Front end of the Slack clone application.

localforage.nopromises.js 65KB

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