Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

indexeddb.js 36KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  1. (function (global, factory) {
  2. if (typeof define === "function" && define.amd) {
  3. define('asyncStorage', ['module', 'exports', '../utils/isIndexedDBValid', '../utils/createBlob', '../utils/idb', '../utils/promise', '../utils/executeCallback', '../utils/executeTwoCallbacks', '../utils/normalizeKey', '../utils/getCallback'], factory);
  4. } else if (typeof exports !== "undefined") {
  5. factory(module, exports, require('../utils/isIndexedDBValid'), require('../utils/createBlob'), require('../utils/idb'), require('../utils/promise'), require('../utils/executeCallback'), require('../utils/executeTwoCallbacks'), require('../utils/normalizeKey'), require('../utils/getCallback'));
  6. } else {
  7. var mod = {
  8. exports: {}
  9. };
  10. factory(mod, mod.exports, global.isIndexedDBValid, global.createBlob, global.idb, global.promise, global.executeCallback, global.executeTwoCallbacks, global.normalizeKey, global.getCallback);
  11. global.asyncStorage = mod.exports;
  12. }
  13. })(this, function (module, exports, _isIndexedDBValid, _createBlob, _idb, _promise, _executeCallback, _executeTwoCallbacks, _normalizeKey, _getCallback) {
  14. 'use strict';
  15. Object.defineProperty(exports, "__esModule", {
  16. value: true
  17. });
  18. var _isIndexedDBValid2 = _interopRequireDefault(_isIndexedDBValid);
  19. var _createBlob2 = _interopRequireDefault(_createBlob);
  20. var _idb2 = _interopRequireDefault(_idb);
  21. var _promise2 = _interopRequireDefault(_promise);
  22. var _executeCallback2 = _interopRequireDefault(_executeCallback);
  23. var _executeTwoCallbacks2 = _interopRequireDefault(_executeTwoCallbacks);
  24. var _normalizeKey2 = _interopRequireDefault(_normalizeKey);
  25. var _getCallback2 = _interopRequireDefault(_getCallback);
  26. function _interopRequireDefault(obj) {
  27. return obj && obj.__esModule ? obj : {
  28. default: obj
  29. };
  30. }
  31. // Some code originally from async_storage.js in
  32. // [Gaia](https://github.com/mozilla-b2g/gaia).
  33. var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';
  34. var supportsBlobs = void 0;
  35. var dbContexts = {};
  36. var toString = Object.prototype.toString;
  37. // Transaction Modes
  38. var READ_ONLY = 'readonly';
  39. var READ_WRITE = 'readwrite';
  40. // Transform a binary string to an array buffer, because otherwise
  41. // weird stuff happens when you try to work with the binary string directly.
  42. // It is known.
  43. // From http://stackoverflow.com/questions/14967647/ (continues on next line)
  44. // encode-decode-image-with-base64-breaks-image (2013-04-21)
  45. function _binStringToArrayBuffer(bin) {
  46. var length = bin.length;
  47. var buf = new ArrayBuffer(length);
  48. var arr = new Uint8Array(buf);
  49. for (var i = 0; i < length; i++) {
  50. arr[i] = bin.charCodeAt(i);
  51. }
  52. return buf;
  53. }
  54. //
  55. // Blobs are not supported in all versions of IndexedDB, notably
  56. // Chrome <37 and Android <5. In those versions, storing a blob will throw.
  57. //
  58. // Various other blob bugs exist in Chrome v37-42 (inclusive).
  59. // Detecting them is expensive and confusing to users, and Chrome 37-42
  60. // is at very low usage worldwide, so we do a hacky userAgent check instead.
  61. //
  62. // content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120
  63. // 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916
  64. // FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836
  65. //
  66. // Code borrowed from PouchDB. See:
  67. // https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-adapter-idb/src/blobSupport.js
  68. //
  69. function _checkBlobSupportWithoutCaching(idb) {
  70. return new _promise2.default(function (resolve) {
  71. var txn = idb.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE);
  72. var blob = (0, _createBlob2.default)(['']);
  73. txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');
  74. txn.onabort = function (e) {
  75. // If the transaction aborts now its due to not being able to
  76. // write to the database, likely due to the disk being full
  77. e.preventDefault();
  78. e.stopPropagation();
  79. resolve(false);
  80. };
  81. txn.oncomplete = function () {
  82. var matchedChrome = navigator.userAgent.match(/Chrome\/(\d+)/);
  83. var matchedEdge = navigator.userAgent.match(/Edge\//);
  84. // MS Edge pretends to be Chrome 42:
  85. // https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx
  86. resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43);
  87. };
  88. }).catch(function () {
  89. return false; // error, so assume unsupported
  90. });
  91. }
  92. function _checkBlobSupport(idb) {
  93. if (typeof supportsBlobs === 'boolean') {
  94. return _promise2.default.resolve(supportsBlobs);
  95. }
  96. return _checkBlobSupportWithoutCaching(idb).then(function (value) {
  97. supportsBlobs = value;
  98. return supportsBlobs;
  99. });
  100. }
  101. function _deferReadiness(dbInfo) {
  102. var dbContext = dbContexts[dbInfo.name];
  103. // Create a deferred object representing the current database operation.
  104. var deferredOperation = {};
  105. deferredOperation.promise = new _promise2.default(function (resolve, reject) {
  106. deferredOperation.resolve = resolve;
  107. deferredOperation.reject = reject;
  108. });
  109. // Enqueue the deferred operation.
  110. dbContext.deferredOperations.push(deferredOperation);
  111. // Chain its promise to the database readiness.
  112. if (!dbContext.dbReady) {
  113. dbContext.dbReady = deferredOperation.promise;
  114. } else {
  115. dbContext.dbReady = dbContext.dbReady.then(function () {
  116. return deferredOperation.promise;
  117. });
  118. }
  119. }
  120. function _advanceReadiness(dbInfo) {
  121. var dbContext = dbContexts[dbInfo.name];
  122. // Dequeue a deferred operation.
  123. var deferredOperation = dbContext.deferredOperations.pop();
  124. // Resolve its promise (which is part of the database readiness
  125. // chain of promises).
  126. if (deferredOperation) {
  127. deferredOperation.resolve();
  128. return deferredOperation.promise;
  129. }
  130. }
  131. function _rejectReadiness(dbInfo, err) {
  132. var dbContext = dbContexts[dbInfo.name];
  133. // Dequeue a deferred operation.
  134. var deferredOperation = dbContext.deferredOperations.pop();
  135. // Reject its promise (which is part of the database readiness
  136. // chain of promises).
  137. if (deferredOperation) {
  138. deferredOperation.reject(err);
  139. return deferredOperation.promise;
  140. }
  141. }
  142. function _getConnection(dbInfo, upgradeNeeded) {
  143. return new _promise2.default(function (resolve, reject) {
  144. dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext();
  145. if (dbInfo.db) {
  146. if (upgradeNeeded) {
  147. _deferReadiness(dbInfo);
  148. dbInfo.db.close();
  149. } else {
  150. return resolve(dbInfo.db);
  151. }
  152. }
  153. var dbArgs = [dbInfo.name];
  154. if (upgradeNeeded) {
  155. dbArgs.push(dbInfo.version);
  156. }
  157. var openreq = _idb2.default.open.apply(_idb2.default, dbArgs);
  158. if (upgradeNeeded) {
  159. openreq.onupgradeneeded = function (e) {
  160. var db = openreq.result;
  161. try {
  162. db.createObjectStore(dbInfo.storeName);
  163. if (e.oldVersion <= 1) {
  164. // Added when support for blob shims was added
  165. db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
  166. }
  167. } catch (ex) {
  168. if (ex.name === 'ConstraintError') {
  169. console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.');
  170. } else {
  171. throw ex;
  172. }
  173. }
  174. };
  175. }
  176. openreq.onerror = function (e) {
  177. e.preventDefault();
  178. reject(openreq.error);
  179. };
  180. openreq.onsuccess = function () {
  181. resolve(openreq.result);
  182. _advanceReadiness(dbInfo);
  183. };
  184. });
  185. }
  186. function _getOriginalConnection(dbInfo) {
  187. return _getConnection(dbInfo, false);
  188. }
  189. function _getUpgradedConnection(dbInfo) {
  190. return _getConnection(dbInfo, true);
  191. }
  192. function _isUpgradeNeeded(dbInfo, defaultVersion) {
  193. if (!dbInfo.db) {
  194. return true;
  195. }
  196. var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);
  197. var isDowngrade = dbInfo.version < dbInfo.db.version;
  198. var isUpgrade = dbInfo.version > dbInfo.db.version;
  199. if (isDowngrade) {
  200. // If the version is not the default one
  201. // then warn for impossible downgrade.
  202. if (dbInfo.version !== defaultVersion) {
  203. console.warn('The database "' + dbInfo.name + '"' + " can't be downgraded from version " + dbInfo.db.version + ' to version ' + dbInfo.version + '.');
  204. }
  205. // Align the versions to prevent errors.
  206. dbInfo.version = dbInfo.db.version;
  207. }
  208. if (isUpgrade || isNewStore) {
  209. // If the store is new then increment the version (if needed).
  210. // This will trigger an "upgradeneeded" event which is required
  211. // for creating a store.
  212. if (isNewStore) {
  213. var incVersion = dbInfo.db.version + 1;
  214. if (incVersion > dbInfo.version) {
  215. dbInfo.version = incVersion;
  216. }
  217. }
  218. return true;
  219. }
  220. return false;
  221. }
  222. // encode a blob for indexeddb engines that don't support blobs
  223. function _encodeBlob(blob) {
  224. return new _promise2.default(function (resolve, reject) {
  225. var reader = new FileReader();
  226. reader.onerror = reject;
  227. reader.onloadend = function (e) {
  228. var base64 = btoa(e.target.result || '');
  229. resolve({
  230. __local_forage_encoded_blob: true,
  231. data: base64,
  232. type: blob.type
  233. });
  234. };
  235. reader.readAsBinaryString(blob);
  236. });
  237. }
  238. // decode an encoded blob
  239. function _decodeBlob(encodedBlob) {
  240. var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));
  241. return (0, _createBlob2.default)([arrayBuff], { type: encodedBlob.type });
  242. }
  243. // is this one of our fancy encoded blobs?
  244. function _isEncodedBlob(value) {
  245. return value && value.__local_forage_encoded_blob;
  246. }
  247. // Specialize the default `ready()` function by making it dependent
  248. // on the current database operations. Thus, the driver will be actually
  249. // ready when it's been initialized (default) *and* there are no pending
  250. // operations on the database (initiated by some other instances).
  251. function _fullyReady(callback) {
  252. var self = this;
  253. var promise = self._initReady().then(function () {
  254. var dbContext = dbContexts[self._dbInfo.name];
  255. if (dbContext && dbContext.dbReady) {
  256. return dbContext.dbReady;
  257. }
  258. });
  259. (0, _executeTwoCallbacks2.default)(promise, callback, callback);
  260. return promise;
  261. }
  262. // Try to establish a new db connection to replace the
  263. // current one which is broken (i.e. experiencing
  264. // InvalidStateError while creating a transaction).
  265. function _tryReconnect(dbInfo) {
  266. _deferReadiness(dbInfo);
  267. var dbContext = dbContexts[dbInfo.name];
  268. var forages = dbContext.forages;
  269. for (var i = 0; i < forages.length; i++) {
  270. var forage = forages[i];
  271. if (forage._dbInfo.db) {
  272. forage._dbInfo.db.close();
  273. forage._dbInfo.db = null;
  274. }
  275. }
  276. dbInfo.db = null;
  277. return _getOriginalConnection(dbInfo).then(function (db) {
  278. dbInfo.db = db;
  279. if (_isUpgradeNeeded(dbInfo)) {
  280. // Reopen the database for upgrading.
  281. return _getUpgradedConnection(dbInfo);
  282. }
  283. return db;
  284. }).then(function (db) {
  285. // store the latest db reference
  286. // in case the db was upgraded
  287. dbInfo.db = dbContext.db = db;
  288. for (var i = 0; i < forages.length; i++) {
  289. forages[i]._dbInfo.db = db;
  290. }
  291. }).catch(function (err) {
  292. _rejectReadiness(dbInfo, err);
  293. throw err;
  294. });
  295. }
  296. // FF doesn't like Promises (micro-tasks) and IDDB store operations,
  297. // so we have to do it with callbacks
  298. function createTransaction(dbInfo, mode, callback, retries) {
  299. if (retries === undefined) {
  300. retries = 1;
  301. }
  302. try {
  303. var tx = dbInfo.db.transaction(dbInfo.storeName, mode);
  304. callback(null, tx);
  305. } catch (err) {
  306. if (retries > 0 && (!dbInfo.db || err.name === 'InvalidStateError' || err.name === 'NotFoundError')) {
  307. return _promise2.default.resolve().then(function () {
  308. if (!dbInfo.db || err.name === 'NotFoundError' && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) {
  309. // increase the db version, to create the new ObjectStore
  310. if (dbInfo.db) {
  311. dbInfo.version = dbInfo.db.version + 1;
  312. }
  313. // Reopen the database for upgrading.
  314. return _getUpgradedConnection(dbInfo);
  315. }
  316. }).then(function () {
  317. return _tryReconnect(dbInfo).then(function () {
  318. createTransaction(dbInfo, mode, callback, retries - 1);
  319. });
  320. }).catch(callback);
  321. }
  322. callback(err);
  323. }
  324. }
  325. function createDbContext() {
  326. return {
  327. // Running localForages sharing a database.
  328. forages: [],
  329. // Shared database.
  330. db: null,
  331. // Database readiness (promise).
  332. dbReady: null,
  333. // Deferred operations on the database.
  334. deferredOperations: []
  335. };
  336. }
  337. // Open the IndexedDB database (automatically creates one if one didn't
  338. // previously exist), using any options set in the config.
  339. function _initStorage(options) {
  340. var self = this;
  341. var dbInfo = {
  342. db: null
  343. };
  344. if (options) {
  345. for (var i in options) {
  346. dbInfo[i] = options[i];
  347. }
  348. }
  349. // Get the current context of the database;
  350. var dbContext = dbContexts[dbInfo.name];
  351. // ...or create a new context.
  352. if (!dbContext) {
  353. dbContext = createDbContext();
  354. // Register the new context in the global container.
  355. dbContexts[dbInfo.name] = dbContext;
  356. }
  357. // Register itself as a running localForage in the current context.
  358. dbContext.forages.push(self);
  359. // Replace the default `ready()` function with the specialized one.
  360. if (!self._initReady) {
  361. self._initReady = self.ready;
  362. self.ready = _fullyReady;
  363. }
  364. // Create an array of initialization states of the related localForages.
  365. var initPromises = [];
  366. function ignoreErrors() {
  367. // Don't handle errors here,
  368. // just makes sure related localForages aren't pending.
  369. return _promise2.default.resolve();
  370. }
  371. for (var j = 0; j < dbContext.forages.length; j++) {
  372. var forage = dbContext.forages[j];
  373. if (forage !== self) {
  374. // Don't wait for itself...
  375. initPromises.push(forage._initReady().catch(ignoreErrors));
  376. }
  377. }
  378. // Take a snapshot of the related localForages.
  379. var forages = dbContext.forages.slice(0);
  380. // Initialize the connection process only when
  381. // all the related localForages aren't pending.
  382. return _promise2.default.all(initPromises).then(function () {
  383. dbInfo.db = dbContext.db;
  384. // Get the connection or open a new one without upgrade.
  385. return _getOriginalConnection(dbInfo);
  386. }).then(function (db) {
  387. dbInfo.db = db;
  388. if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) {
  389. // Reopen the database for upgrading.
  390. return _getUpgradedConnection(dbInfo);
  391. }
  392. return db;
  393. }).then(function (db) {
  394. dbInfo.db = dbContext.db = db;
  395. self._dbInfo = dbInfo;
  396. // Share the final connection amongst related localForages.
  397. for (var k = 0; k < forages.length; k++) {
  398. var forage = forages[k];
  399. if (forage !== self) {
  400. // Self is already up-to-date.
  401. forage._dbInfo.db = dbInfo.db;
  402. forage._dbInfo.version = dbInfo.version;
  403. }
  404. }
  405. });
  406. }
  407. function getItem(key, callback) {
  408. var self = this;
  409. key = (0, _normalizeKey2.default)(key);
  410. var promise = new _promise2.default(function (resolve, reject) {
  411. self.ready().then(function () {
  412. createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
  413. if (err) {
  414. return reject(err);
  415. }
  416. try {
  417. var store = transaction.objectStore(self._dbInfo.storeName);
  418. var req = store.get(key);
  419. req.onsuccess = function () {
  420. var value = req.result;
  421. if (value === undefined) {
  422. value = null;
  423. }
  424. if (_isEncodedBlob(value)) {
  425. value = _decodeBlob(value);
  426. }
  427. resolve(value);
  428. };
  429. req.onerror = function () {
  430. reject(req.error);
  431. };
  432. } catch (e) {
  433. reject(e);
  434. }
  435. });
  436. }).catch(reject);
  437. });
  438. (0, _executeCallback2.default)(promise, callback);
  439. return promise;
  440. }
  441. // Iterate over all items stored in database.
  442. function iterate(iterator, callback) {
  443. var self = this;
  444. var promise = new _promise2.default(function (resolve, reject) {
  445. self.ready().then(function () {
  446. createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
  447. if (err) {
  448. return reject(err);
  449. }
  450. try {
  451. var store = transaction.objectStore(self._dbInfo.storeName);
  452. var req = store.openCursor();
  453. var iterationNumber = 1;
  454. req.onsuccess = function () {
  455. var cursor = req.result;
  456. if (cursor) {
  457. var value = cursor.value;
  458. if (_isEncodedBlob(value)) {
  459. value = _decodeBlob(value);
  460. }
  461. var result = iterator(value, cursor.key, iterationNumber++);
  462. // when the iterator callback returns any
  463. // (non-`undefined`) value, then we stop
  464. // the iteration immediately
  465. if (result !== void 0) {
  466. resolve(result);
  467. } else {
  468. cursor.continue();
  469. }
  470. } else {
  471. resolve();
  472. }
  473. };
  474. req.onerror = function () {
  475. reject(req.error);
  476. };
  477. } catch (e) {
  478. reject(e);
  479. }
  480. });
  481. }).catch(reject);
  482. });
  483. (0, _executeCallback2.default)(promise, callback);
  484. return promise;
  485. }
  486. function setItem(key, value, callback) {
  487. var self = this;
  488. key = (0, _normalizeKey2.default)(key);
  489. var promise = new _promise2.default(function (resolve, reject) {
  490. var dbInfo;
  491. self.ready().then(function () {
  492. dbInfo = self._dbInfo;
  493. if (toString.call(value) === '[object Blob]') {
  494. return _checkBlobSupport(dbInfo.db).then(function (blobSupport) {
  495. if (blobSupport) {
  496. return value;
  497. }
  498. return _encodeBlob(value);
  499. });
  500. }
  501. return value;
  502. }).then(function (value) {
  503. createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
  504. if (err) {
  505. return reject(err);
  506. }
  507. try {
  508. var store = transaction.objectStore(self._dbInfo.storeName);
  509. // The reason we don't _save_ null is because IE 10 does
  510. // not support saving the `null` type in IndexedDB. How
  511. // ironic, given the bug below!
  512. // See: https://github.com/mozilla/localForage/issues/161
  513. if (value === null) {
  514. value = undefined;
  515. }
  516. var req = store.put(value, key);
  517. transaction.oncomplete = function () {
  518. // Cast to undefined so the value passed to
  519. // callback/promise is the same as what one would get out
  520. // of `getItem()` later. This leads to some weirdness
  521. // (setItem('foo', undefined) will return `null`), but
  522. // it's not my fault localStorage is our baseline and that
  523. // it's weird.
  524. if (value === undefined) {
  525. value = null;
  526. }
  527. resolve(value);
  528. };
  529. transaction.onabort = transaction.onerror = function () {
  530. var err = req.error ? req.error : req.transaction.error;
  531. reject(err);
  532. };
  533. } catch (e) {
  534. reject(e);
  535. }
  536. });
  537. }).catch(reject);
  538. });
  539. (0, _executeCallback2.default)(promise, callback);
  540. return promise;
  541. }
  542. function removeItem(key, callback) {
  543. var self = this;
  544. key = (0, _normalizeKey2.default)(key);
  545. var promise = new _promise2.default(function (resolve, reject) {
  546. self.ready().then(function () {
  547. createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
  548. if (err) {
  549. return reject(err);
  550. }
  551. try {
  552. var store = transaction.objectStore(self._dbInfo.storeName);
  553. // We use a Grunt task to make this safe for IE and some
  554. // versions of Android (including those used by Cordova).
  555. // Normally IE won't like `.delete()` and will insist on
  556. // using `['delete']()`, but we have a build step that
  557. // fixes this for us now.
  558. var req = store.delete(key);
  559. transaction.oncomplete = function () {
  560. resolve();
  561. };
  562. transaction.onerror = function () {
  563. reject(req.error);
  564. };
  565. // The request will be also be aborted if we've exceeded our storage
  566. // space.
  567. transaction.onabort = function () {
  568. var err = req.error ? req.error : req.transaction.error;
  569. reject(err);
  570. };
  571. } catch (e) {
  572. reject(e);
  573. }
  574. });
  575. }).catch(reject);
  576. });
  577. (0, _executeCallback2.default)(promise, callback);
  578. return promise;
  579. }
  580. function clear(callback) {
  581. var self = this;
  582. var promise = new _promise2.default(function (resolve, reject) {
  583. self.ready().then(function () {
  584. createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {
  585. if (err) {
  586. return reject(err);
  587. }
  588. try {
  589. var store = transaction.objectStore(self._dbInfo.storeName);
  590. var req = store.clear();
  591. transaction.oncomplete = function () {
  592. resolve();
  593. };
  594. transaction.onabort = transaction.onerror = function () {
  595. var err = req.error ? req.error : req.transaction.error;
  596. reject(err);
  597. };
  598. } catch (e) {
  599. reject(e);
  600. }
  601. });
  602. }).catch(reject);
  603. });
  604. (0, _executeCallback2.default)(promise, callback);
  605. return promise;
  606. }
  607. function length(callback) {
  608. var self = this;
  609. var promise = new _promise2.default(function (resolve, reject) {
  610. self.ready().then(function () {
  611. createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
  612. if (err) {
  613. return reject(err);
  614. }
  615. try {
  616. var store = transaction.objectStore(self._dbInfo.storeName);
  617. var req = store.count();
  618. req.onsuccess = function () {
  619. resolve(req.result);
  620. };
  621. req.onerror = function () {
  622. reject(req.error);
  623. };
  624. } catch (e) {
  625. reject(e);
  626. }
  627. });
  628. }).catch(reject);
  629. });
  630. (0, _executeCallback2.default)(promise, callback);
  631. return promise;
  632. }
  633. function key(n, callback) {
  634. var self = this;
  635. var promise = new _promise2.default(function (resolve, reject) {
  636. if (n < 0) {
  637. resolve(null);
  638. return;
  639. }
  640. self.ready().then(function () {
  641. createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
  642. if (err) {
  643. return reject(err);
  644. }
  645. try {
  646. var store = transaction.objectStore(self._dbInfo.storeName);
  647. var advanced = false;
  648. var req = store.openKeyCursor();
  649. req.onsuccess = function () {
  650. var cursor = req.result;
  651. if (!cursor) {
  652. // this means there weren't enough keys
  653. resolve(null);
  654. return;
  655. }
  656. if (n === 0) {
  657. // We have the first key, return it if that's what they
  658. // wanted.
  659. resolve(cursor.key);
  660. } else {
  661. if (!advanced) {
  662. // Otherwise, ask the cursor to skip ahead n
  663. // records.
  664. advanced = true;
  665. cursor.advance(n);
  666. } else {
  667. // When we get here, we've got the nth key.
  668. resolve(cursor.key);
  669. }
  670. }
  671. };
  672. req.onerror = function () {
  673. reject(req.error);
  674. };
  675. } catch (e) {
  676. reject(e);
  677. }
  678. });
  679. }).catch(reject);
  680. });
  681. (0, _executeCallback2.default)(promise, callback);
  682. return promise;
  683. }
  684. function keys(callback) {
  685. var self = this;
  686. var promise = new _promise2.default(function (resolve, reject) {
  687. self.ready().then(function () {
  688. createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {
  689. if (err) {
  690. return reject(err);
  691. }
  692. try {
  693. var store = transaction.objectStore(self._dbInfo.storeName);
  694. var req = store.openKeyCursor();
  695. var keys = [];
  696. req.onsuccess = function () {
  697. var cursor = req.result;
  698. if (!cursor) {
  699. resolve(keys);
  700. return;
  701. }
  702. keys.push(cursor.key);
  703. cursor.continue();
  704. };
  705. req.onerror = function () {
  706. reject(req.error);
  707. };
  708. } catch (e) {
  709. reject(e);
  710. }
  711. });
  712. }).catch(reject);
  713. });
  714. (0, _executeCallback2.default)(promise, callback);
  715. return promise;
  716. }
  717. function dropInstance(options, callback) {
  718. callback = _getCallback2.default.apply(this, arguments);
  719. var currentConfig = this.config();
  720. options = typeof options !== 'function' && options || {};
  721. if (!options.name) {
  722. options.name = options.name || currentConfig.name;
  723. options.storeName = options.storeName || currentConfig.storeName;
  724. }
  725. var self = this;
  726. var promise;
  727. if (!options.name) {
  728. promise = _promise2.default.reject('Invalid arguments');
  729. } else {
  730. var isCurrentDb = options.name === currentConfig.name && self._dbInfo.db;
  731. var dbPromise = isCurrentDb ? _promise2.default.resolve(self._dbInfo.db) : _getOriginalConnection(options).then(function (db) {
  732. var dbContext = dbContexts[options.name];
  733. var forages = dbContext.forages;
  734. dbContext.db = db;
  735. for (var i = 0; i < forages.length; i++) {
  736. forages[i]._dbInfo.db = db;
  737. }
  738. return db;
  739. });
  740. if (!options.storeName) {
  741. promise = dbPromise.then(function (db) {
  742. _deferReadiness(options);
  743. var dbContext = dbContexts[options.name];
  744. var forages = dbContext.forages;
  745. db.close();
  746. for (var i = 0; i < forages.length; i++) {
  747. var forage = forages[i];
  748. forage._dbInfo.db = null;
  749. }
  750. var dropDBPromise = new _promise2.default(function (resolve, reject) {
  751. var req = _idb2.default.deleteDatabase(options.name);
  752. req.onerror = req.onblocked = function (err) {
  753. var db = req.result;
  754. if (db) {
  755. db.close();
  756. }
  757. reject(err);
  758. };
  759. req.onsuccess = function () {
  760. var db = req.result;
  761. if (db) {
  762. db.close();
  763. }
  764. resolve(db);
  765. };
  766. });
  767. return dropDBPromise.then(function (db) {
  768. dbContext.db = db;
  769. for (var i = 0; i < forages.length; i++) {
  770. var _forage = forages[i];
  771. _advanceReadiness(_forage._dbInfo);
  772. }
  773. }).catch(function (err) {
  774. (_rejectReadiness(options, err) || _promise2.default.resolve()).catch(function () {});
  775. throw err;
  776. });
  777. });
  778. } else {
  779. promise = dbPromise.then(function (db) {
  780. if (!db.objectStoreNames.contains(options.storeName)) {
  781. return;
  782. }
  783. var newVersion = db.version + 1;
  784. _deferReadiness(options);
  785. var dbContext = dbContexts[options.name];
  786. var forages = dbContext.forages;
  787. db.close();
  788. for (var i = 0; i < forages.length; i++) {
  789. var forage = forages[i];
  790. forage._dbInfo.db = null;
  791. forage._dbInfo.version = newVersion;
  792. }
  793. var dropObjectPromise = new _promise2.default(function (resolve, reject) {
  794. var req = _idb2.default.open(options.name, newVersion);
  795. req.onerror = function (err) {
  796. var db = req.result;
  797. db.close();
  798. reject(err);
  799. };
  800. req.onupgradeneeded = function () {
  801. var db = req.result;
  802. db.deleteObjectStore(options.storeName);
  803. };
  804. req.onsuccess = function () {
  805. var db = req.result;
  806. db.close();
  807. resolve(db);
  808. };
  809. });
  810. return dropObjectPromise.then(function (db) {
  811. dbContext.db = db;
  812. for (var j = 0; j < forages.length; j++) {
  813. var _forage2 = forages[j];
  814. _forage2._dbInfo.db = db;
  815. _advanceReadiness(_forage2._dbInfo);
  816. }
  817. }).catch(function (err) {
  818. (_rejectReadiness(options, err) || _promise2.default.resolve()).catch(function () {});
  819. throw err;
  820. });
  821. });
  822. }
  823. }
  824. (0, _executeCallback2.default)(promise, callback);
  825. return promise;
  826. }
  827. var asyncStorage = {
  828. _driver: 'asyncStorage',
  829. _initStorage: _initStorage,
  830. _support: (0, _isIndexedDBValid2.default)(),
  831. iterate: iterate,
  832. getItem: getItem,
  833. setItem: setItem,
  834. removeItem: removeItem,
  835. clear: clear,
  836. length: length,
  837. key: key,
  838. keys: keys,
  839. dropInstance: dropInstance
  840. };
  841. exports.default = asyncStorage;
  842. module.exports = exports['default'];
  843. });