storage.js 17.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
// See [Web Storage](http://dev.w3.org/html5/webstorage/)
'use strict';

var _get = require('babel-runtime/helpers/get')['default'];

var _inherits = require('babel-runtime/helpers/inherits')['default'];

var _createClass = require('babel-runtime/helpers/create-class')['default'];

var _classCallCheck = require('babel-runtime/helpers/class-call-check')['default'];

var _slicedToArray = require('babel-runtime/helpers/sliced-to-array')['default'];

var _toConsumableArray = require('babel-runtime/helpers/to-consumable-array')['default'];

var _Map = require('babel-runtime/core-js/map')['default'];

var _getIterator = require('babel-runtime/core-js/get-iterator')['default'];

var _Object$defineProperties = require('babel-runtime/core-js/object/define-properties')['default'];

var DOM = require('./dom');

// Implementation of the StorageEvent.

var StorageEvent = (function (_DOM$Event) {
  _inherits(StorageEvent, _DOM$Event);

  function StorageEvent(storage, url, key, oldValue, newValue) {
    _classCallCheck(this, StorageEvent);

    _get(Object.getPrototypeOf(StorageEvent.prototype), 'constructor', this).call(this, 'storage');
    this._storage = storage;
    this._url = url;
    this._key = key;
    this._oldValue = oldValue;
    this._newValue = newValue;
  }

  // Storage area. The storage area is shared by multiple documents of the same
  // origin. For session storage, they must also share the same browsing context.

  _createClass(StorageEvent, [{
    key: 'url',
    get: function get() {
      return this._url;
    }
  }, {
    key: 'storageArea',
    get: function get() {
      return this._storage;
    }
  }, {
    key: 'key',
    get: function get() {
      return this._key;
    }
  }, {
    key: 'oldValue',
    get: function get() {
      return this._oldValue;
    }
  }, {
    key: 'newValue',
    get: function get() {
      return this._newValue;
    }
  }]);

  return StorageEvent;
})(DOM.Event);

var StorageArea = (function () {
  function StorageArea() {
    _classCallCheck(this, StorageArea);

    this._items = new _Map();
    this._storages = [];
  }

  // Implementation of the Storage interface, used by local and session storage.

  // Fire a storage event. Fire in all documents that share this storage area,
  // except for the source document.

  _createClass(StorageArea, [{
    key: '_fire',
    value: function _fire(source, key, oldValue, newValue) {
      var _iteratorNormalCompletion = true;
      var _didIteratorError = false;
      var _iteratorError = undefined;

      try {
        for (var _iterator = _getIterator(this._storages), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
          var _step$value = _slicedToArray(_step.value, 2);

          var storage = _step$value[0];
          var _window = _step$value[1];

          if (storage === source) continue;
          var _event = new StorageEvent(storage, _window.location.href, key, oldValue, newValue);
          _window.dispatchEvent(_event);
        }
      } catch (err) {
        _didIteratorError = true;
        _iteratorError = err;
      } finally {
        try {
          if (!_iteratorNormalCompletion && _iterator['return']) {
            _iterator['return']();
          }
        } finally {
          if (_didIteratorError) {
            throw _iteratorError;
          }
        }
      }
    }

    // Return number of key/value pairs.
  }, {
    key: 'key',

    // Get key by ordinal position.
    value: function key(index) {
      var iterator = this._items.keys();
      var next = iterator.next();
      for (var i = 0; i < index; ++i) {
        next = iterator.next();
      }return next.value;
    }

    // Get value from key
  }, {
    key: 'get',
    value: function get(key) {
      return this._items.has(key) ? this._items.get(key) : null;
    }

    // Set the value of a key. We also need the source storage (so we don't send
    // it a storage event).
  }, {
    key: 'set',
    value: function set(source, key, value) {
      var oldValue = this._items.get(key);
      this._items.set(key, value);
      this._fire(source, key, oldValue, value);
    }

    // Remove the value at the key. We also need source storage (see set above).
  }, {
    key: 'remove',
    value: function remove(source, key) {
      var oldValue = this._items.get(key);
      this._items['delete'](key);
      this._fire(source, key, oldValue);
    }

    // Remove all values. We also need source storage (see set above).
  }, {
    key: 'clear',
    value: function clear(source) {
      this._items.clear();
      this._fire(source);
    }
  }, {
    key: 'toString',
    value: function toString() {
      return this._items.toString();
    }

    // Associate local/sessionStorage and window with this storage area. Used when firing events.
  }, {
    key: 'associate',
    value: function associate(storage, window) {
      this._storages.push([storage, window]);
    }
  }, {
    key: 'length',
    get: function get() {
      return this._items.size;
    }
  }, {
    key: 'pairs',
    get: function get() {
      return [].concat(_toConsumableArray(this._items));
    }
  }]);

  return StorageArea;
})();

var Storage = (function () {
  function Storage(area) {
    _classCallCheck(this, Storage);

    this._area = area;
  }

  // Combined local/session storage.

  // ### storage.length => Number
  //
  // Returns the number of key/value pairs in this storage.

  _createClass(Storage, [{
    key: 'key',

    // ### storage.key(index) => String
    //
    // Returns the key at this position.
    value: function key(index) {
      return this._area.key(index);
    }

    // ### storage.getItem(key) => Object
    //
    // Returns item by key.
  }, {
    key: 'getItem',
    value: function getItem(key) {
      return this._area.get(key.toString());
    }

    // ### storage.setItem(key, Object)
    //
    // Add item or change value of existing item.
  }, {
    key: 'setItem',
    value: function setItem(key, value) {
      this._area.set(this, key.toString(), value);
    }

    // ### storage.removeItem(key)
    //
    // Remove item.
  }, {
    key: 'removeItem',
    value: function removeItem(key) {
      this._area.remove(this, key.toString());
    }

    // ### storage.clear()
    //
    // Remove all items.
  }, {
    key: 'clear',
    value: function clear() {
      this._area.clear(this);
    }

    // Dump to a string, useful for debugging.
  }, {
    key: 'dump',
    value: function dump() {
      var output = arguments.length <= 0 || arguments[0] === undefined ? process.stdout : arguments[0];

      return this._area.dump(output);
    }
  }, {
    key: 'length',
    get: function get() {
      return this._area.length;
    }
  }]);

  return Storage;
})();

var Storages = (function () {
  function Storages() {
    _classCallCheck(this, Storages);

    this._locals = new _Map();
    this._sessions = new _Map();
  }

  // Return local Storage based on the document origin (hostname/port).

  _createClass(Storages, [{
    key: 'local',
    value: function local(host) {
      if (!this._locals.has(host)) this._locals.set(host, new StorageArea());
      return new Storage(this._locals.get(host));
    }

    // Return session Storage based on the document origin (hostname/port).
  }, {
    key: 'session',
    value: function session(host) {
      if (!this._sessions.has(host)) this._sessions.set(host, new StorageArea());
      return new Storage(this._sessions.get(host));
    }

    // Extend window with local/session storage support.
  }, {
    key: 'extend',
    value: function extend(window) {
      var storages = this;
      window.StorageEvent = StorageEvent;
      _Object$defineProperties(window, {
        localStorage: {
          get: function get() {
            var document = this.document;

            if (!document._localStorage) document._localStorage = storages.local(document.location.host);
            return document._localStorage;
          }
        },

        sessionStorage: {
          get: function get() {
            var document = this.document;

            if (!document._sessionStorage) document._sessionStorage = storages.session(document.location.host);
            return document._sessionStorage;
          }
        }
      });
    }

    // Used to dump state to console (debuggin)
  }, {
    key: 'dump',
    value: function dump() {
      var output = arguments.length <= 0 || arguments[0] === undefined ? process.stdout : arguments[0];
      var _iteratorNormalCompletion2 = true;
      var _didIteratorError2 = false;
      var _iteratorError2 = undefined;

      try {
        for (var _iterator2 = _getIterator(this._locals), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
          var _step2$value = _slicedToArray(_step2.value, 2);

          var domain = _step2$value[0];
          var area = _step2$value[1];

          output.write(domain + ' local:\n');
          var _iteratorNormalCompletion4 = true;
          var _didIteratorError4 = false;
          var _iteratorError4 = undefined;

          try {
            for (var _iterator4 = _getIterator(area.pairs), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
              var _step4$value = _slicedToArray(_step4.value, 2);

              var _name = _step4$value[0];
              var value = _step4$value[1];

              output.write('  ' + _name + ' = ' + value + '\n');
            }
          } catch (err) {
            _didIteratorError4 = true;
            _iteratorError4 = err;
          } finally {
            try {
              if (!_iteratorNormalCompletion4 && _iterator4['return']) {
                _iterator4['return']();
              }
            } finally {
              if (_didIteratorError4) {
                throw _iteratorError4;
              }
            }
          }
        }
      } catch (err) {
        _didIteratorError2 = true;
        _iteratorError2 = err;
      } finally {
        try {
          if (!_iteratorNormalCompletion2 && _iterator2['return']) {
            _iterator2['return']();
          }
        } finally {
          if (_didIteratorError2) {
            throw _iteratorError2;
          }
        }
      }

      var _iteratorNormalCompletion3 = true;
      var _didIteratorError3 = false;
      var _iteratorError3 = undefined;

      try {
        for (var _iterator3 = _getIterator(this._sessions), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
          var _step3$value = _slicedToArray(_step3.value, 2);

          var domain = _step3$value[0];
          var area = _step3$value[1];

          output.push(domain + ' session:\n');
          var _iteratorNormalCompletion5 = true;
          var _didIteratorError5 = false;
          var _iteratorError5 = undefined;

          try {
            for (var _iterator5 = _getIterator(area.pairs), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
              var _step5$value = _slicedToArray(_step5.value, 2);

              var _name2 = _step5$value[0];
              var value = _step5$value[1];

              output.write('  ' + _name2 + ' = ' + value + '\n');
            }
          } catch (err) {
            _didIteratorError5 = true;
            _iteratorError5 = err;
          } finally {
            try {
              if (!_iteratorNormalCompletion5 && _iterator5['return']) {
                _iterator5['return']();
              }
            } finally {
              if (_didIteratorError5) {
                throw _iteratorError5;
              }
            }
          }
        }
      } catch (err) {
        _didIteratorError3 = true;
        _iteratorError3 = err;
      } finally {
        try {
          if (!_iteratorNormalCompletion3 && _iterator3['return']) {
            _iterator3['return']();
          }
        } finally {
          if (_didIteratorError3) {
            throw _iteratorError3;
          }
        }
      }
    }

    // browser.saveStorage uses this
  }, {
    key: 'save',
    value: function save() {
      var serialized = ['# Saved on ' + new Date().toISOString()];
      var _iteratorNormalCompletion6 = true;
      var _didIteratorError6 = false;
      var _iteratorError6 = undefined;

      try {
        for (var _iterator6 = _getIterator(this._locals), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
          var _step6$value = _slicedToArray(_step6.value, 2);

          var domain = _step6$value[0];
          var area = _step6$value[1];

          var pairs = area.pairs;
          if (pairs.length) {
            serialized.push(domain + ' local:');
            var _iteratorNormalCompletion8 = true;
            var _didIteratorError8 = false;
            var _iteratorError8 = undefined;

            try {
              for (var _iterator8 = _getIterator(area.pairs), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) {
                var _step8$value = _slicedToArray(_step8.value, 2);

                var _name3 = _step8$value[0];
                var value = _step8$value[1];

                serialized.push('  ' + escape(_name3) + ' = ' + escape(value));
              }
            } catch (err) {
              _didIteratorError8 = true;
              _iteratorError8 = err;
            } finally {
              try {
                if (!_iteratorNormalCompletion8 && _iterator8['return']) {
                  _iterator8['return']();
                }
              } finally {
                if (_didIteratorError8) {
                  throw _iteratorError8;
                }
              }
            }
          }
        }
      } catch (err) {
        _didIteratorError6 = true;
        _iteratorError6 = err;
      } finally {
        try {
          if (!_iteratorNormalCompletion6 && _iterator6['return']) {
            _iterator6['return']();
          }
        } finally {
          if (_didIteratorError6) {
            throw _iteratorError6;
          }
        }
      }

      var _iteratorNormalCompletion7 = true;
      var _didIteratorError7 = false;
      var _iteratorError7 = undefined;

      try {
        for (var _iterator7 = _getIterator(this._sessions), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
          var _step7$value = _slicedToArray(_step7.value, 2);

          var domain = _step7$value[0];
          var area = _step7$value[1];

          var pairs = area.pairs;
          if (pairs.length) {
            serialized.push(domain + ' session:');
            var _iteratorNormalCompletion9 = true;
            var _didIteratorError9 = false;
            var _iteratorError9 = undefined;

            try {
              for (var _iterator9 = _getIterator(area.pairs), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) {
                var _step9$value = _slicedToArray(_step9.value, 2);

                var _name4 = _step9$value[0];
                var value = _step9$value[1];

                serialized.push('  ' + escape(_name4) + ' = ' + escape(value));
              }
            } catch (err) {
              _didIteratorError9 = true;
              _iteratorError9 = err;
            } finally {
              try {
                if (!_iteratorNormalCompletion9 && _iterator9['return']) {
                  _iterator9['return']();
                }
              } finally {
                if (_didIteratorError9) {
                  throw _iteratorError9;
                }
              }
            }
          }
        }
      } catch (err) {
        _didIteratorError7 = true;
        _iteratorError7 = err;
      } finally {
        try {
          if (!_iteratorNormalCompletion7 && _iterator7['return']) {
            _iterator7['return']();
          }
        } finally {
          if (_didIteratorError7) {
            throw _iteratorError7;
          }
        }
      }

      return serialized.join('\n') + '\n';
    }

    // browser.loadStorage uses this
  }, {
    key: 'load',
    value: function load(serialized) {
      var storage = null;
      var _iteratorNormalCompletion10 = true;
      var _didIteratorError10 = false;
      var _iteratorError10 = undefined;

      try {
        for (var _iterator10 = _getIterator(serialized.split(/\n+/)), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) {
          var item = _step10.value;

          if (item[0] === '#' || item === '') continue;
          if (item[0] === ' ') {
            var _item$split = item.split('=');

            var _item$split2 = _slicedToArray(_item$split, 2);

            var key = _item$split2[0];
            var value = _item$split2[1];

            if (storage) storage.setItem(unescape(key.trim()), unescape(value.trim()));else throw new Error('Must specify storage type using local: or session:');
          } else {
            var _item$split3 = item.split(' ');

            var _item$split32 = _slicedToArray(_item$split3, 2);

            var domain = _item$split32[0];
            var type = _item$split32[1];

            if (type === 'local:') storage = this.local(domain);else if (type === 'session:') storage = this.session(domain);else throw new Error('Unkown storage type ' + type);
          }
        }
      } catch (err) {
        _didIteratorError10 = true;
        _iteratorError10 = err;
      } finally {
        try {
          if (!_iteratorNormalCompletion10 && _iterator10['return']) {
            _iterator10['return']();
          }
        } finally {
          if (_didIteratorError10) {
            throw _iteratorError10;
          }
        }
      }
    }
  }]);

  return Storages;
})();

module.exports = Storages;
//# sourceMappingURL=storage.js.map