├── .travis.yml
├── .gitignore
├── .jshintrc
├── src
├── .jshintrc
├── store.onlyreal.js
├── store.quota.js
├── store.dot.js
├── store.deep.js
├── store.measure.js
├── store.async.js
├── store.array.js
├── store.cache.js
├── store.dom.js
├── store.cookies.js
├── store.cookie.js
├── store.on.js
├── store.bind.js
├── store.overflow.js
├── store.old.js
└── store2.js
├── test
├── .jshintrc
├── store_dom.htm
├── store_amd.htm
├── store.html
└── store_test.js
├── store2.nuspec
├── LICENSE-MIT
├── package.json
├── CONTRIBUTING.md
├── index.d.ts
├── Gruntfile.js
├── dist
├── store2.min.js
├── store2.min.js.map
└── store2.js
├── libs
└── qunit
│ ├── qunit.css
│ └── qunit.js
└── README.md
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 | node_js:
3 | - '9'
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /node_modules/
2 | components
3 | build
4 | .DS_Store
5 |
--------------------------------------------------------------------------------
/.jshintrc:
--------------------------------------------------------------------------------
1 | {
2 | "curly": true,
3 | "eqeqeq": true,
4 | "immed": true,
5 | "latedef": true,
6 | "newcap": true,
7 | "noarg": true,
8 | "sub": true,
9 | "undef": true,
10 | "unused": true,
11 | "boss": true,
12 | "eqnull": true,
13 | "node": true,
14 | "esversion": 6
15 | }
16 |
--------------------------------------------------------------------------------
/src/.jshintrc:
--------------------------------------------------------------------------------
1 | {
2 | "curly": true,
3 | "eqeqeq": true,
4 | "immed": true,
5 | "latedef": true,
6 | "newcap": true,
7 | "noarg": true,
8 | "sub": true,
9 | "undef": true,
10 | "unused": true,
11 | "boss": true,
12 | "eqnull": true,
13 | "browser": true,
14 | "globals": {
15 | "module": true
16 | },
17 | "predef": ["jQuery","require","store","globalThis","Promise"]
18 | }
19 |
--------------------------------------------------------------------------------
/src/store.onlyreal.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2015 ESHA Research
3 | * Dual licensed under the MIT and GPL licenses:
4 | * http://www.opensource.org/licenses/mit-license.php
5 | * http://www.gnu.org/licenses/gpl.html
6 | *
7 | * Store nothing when storage is not supported.
8 | *
9 | * Status: ALPHA - due to being of doubtful propriety
10 | */
11 | ;(function(_) {
12 |
13 | var _set = _.set;
14 | _.set = function(area) {
15 | return area.name === 'fake' ? undefined : _set.apply(this, arguments);
16 | };
17 |
18 | })(window.store._);
19 |
--------------------------------------------------------------------------------
/test/.jshintrc:
--------------------------------------------------------------------------------
1 | {
2 | "curly": true,
3 | "eqeqeq": true,
4 | "immed": true,
5 | "latedef": true,
6 | "newcap": true,
7 | "noarg": true,
8 | "sub": true,
9 | "undef": true,
10 | "unused": true,
11 | "boss": true,
12 | "eqnull": true,
13 | "browser": true,
14 | "predef": [
15 | "jQuery",
16 | "QUnit",
17 | "module",
18 | "test",
19 | "asyncTest",
20 | "expect",
21 | "start",
22 | "stop",
23 | "ok",
24 | "equal",
25 | "notEqual",
26 | "deepEqual",
27 | "notDeepEqual",
28 | "strictEqual",
29 | "notStrictEqual",
30 | "throws",
31 | "require"
32 | ]
33 | }
--------------------------------------------------------------------------------
/store2.nuspec:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | store2
5 | store (Javascript)
6 | $version$
7 | Nathan Bubna
8 | nbubna
9 | false
10 | 2022
11 | https://github.com/nbubna/store
12 | https://mit-license.org/
13 | A feature-filled and friendly way to use localStorage and sessionStorage
14 | (JSON, namespacing, extensions, etc).
15 | localStorage sessionStorage json javascript namespace html5 store browser client persistence
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/test/store_dom.htm:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | store.dom.js Playground
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 | Foo bar
23 |
24 |
25 |
--------------------------------------------------------------------------------
/test/store_amd.htm:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | store.js Test Suite: using amd
6 |
7 |
8 |
9 |
10 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/LICENSE-MIT:
--------------------------------------------------------------------------------
1 | Copyright (c) 2017 Nathan Bubna
2 |
3 | Permission is hereby granted, free of charge, to any person
4 | obtaining a copy of this software and associated documentation
5 | files (the "Software"), to deal in the Software without
6 | restriction, including without limitation the rights to use,
7 | copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | copies of the Software, and to permit persons to whom the
9 | Software is furnished to do so, subject to the following
10 | conditions:
11 |
12 | The above copyright notice and this permission notice shall be
13 | included in all copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
17 | OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
19 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
20 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22 | OTHER DEALINGS IN THE SOFTWARE.
23 |
--------------------------------------------------------------------------------
/test/store.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | store.js Test Suite
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 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "store2",
3 | "version": "2.14.4",
4 | "description": "Better localStorage",
5 | "keywords": [
6 | "localStorage",
7 | "sessionStorage",
8 | "json",
9 | "namespace",
10 | "store"
11 | ],
12 | "author": {
13 | "name": "Nathan Bubna",
14 | "email": "nathan@esha.com",
15 | "url": "http://www.esha.com/"
16 | },
17 | "files": [
18 | "src",
19 | "dist",
20 | "index.d.ts"
21 | ],
22 | "main": "dist/store2.js",
23 | "types": "index.d.ts",
24 | "bugs": {
25 | "url": "http://github.com/nbubna/store/issues",
26 | "email": "nathan@esha.com"
27 | },
28 | "repository": {
29 | "type": "git",
30 | "url": "git+ssh://git@github.com/nbubna/store.git"
31 | },
32 | "license": "MIT",
33 | "scripts": {
34 | "prepublishOnly": "grunt && git commit -m \"$npm_package_version\" README.md *.json dist && git tag $npm_package_version && git push && git push --tags",
35 | "test": "grunt qunit"
36 | },
37 | "devDependencies": {
38 | "grunt": "^1.6.1",
39 | "grunt-cli": "^1.5.0",
40 | "grunt-contrib-clean": "^1.1.0",
41 | "grunt-contrib-concat": "^1.0.1",
42 | "grunt-contrib-jshint": "^3.2.0",
43 | "grunt-contrib-qunit": "^1.3.0",
44 | "grunt-contrib-uglify": "^2.3.0",
45 | "grunt-contrib-watch": "^1.1.0",
46 | "grunt-lib-phantomjs": "^1.1.0",
47 | "grunt-nuget": "^0.3.1",
48 | "load-grunt-tasks": "^3.5.2",
49 | "phantomjs": "^2.1.7",
50 | "time-grunt": "^1.4.0"
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/store.quota.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2013 ESHA Research
3 | * Dual licensed under the MIT and GPL licenses:
4 | * http://www.opensource.org/licenses/mit-license.php
5 | * http://www.gnu.org/licenses/gpl.html
6 | *
7 | * Bind handlers to quota errors:
8 | * store.quota(function(e, area, key, str) {
9 | * console.log(e, area, key, str);
10 | * });
11 | * If a handler returns true other handlers are not called and
12 | * the error is suppressed.
13 | *
14 | * Think quota errors will never happen to you? Think again:
15 | * http://spin.atomicobject.com/2013/01/23/ios-private-browsing-localstorage/
16 | * (this affects sessionStorage too)
17 | *
18 | * Status: ALPHA - API could use unbind feature
19 | */
20 | ;(function(store, _) {
21 |
22 | store.quota = function(fn) {
23 | store.quota.fns.push(fn);
24 | };
25 | store.quota.fns = [];
26 |
27 | var _set = _.set;
28 | _.set = function(area, key, str) {
29 | try {
30 | _set.apply(this, arguments);
31 | } catch (e) {
32 | if (e.name === 'QUOTA_EXCEEDED_ERR' ||
33 | e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
34 | var fns = store.quota.fns;
35 | for (var i=0,m=fns.length; i 0) {
50 | var kid = key.substring(dot + 1, key.length);
51 | key = key.substring(0, dot);
52 | return [key, kid];
53 | }
54 | };
55 |
56 | })(window.store._);
--------------------------------------------------------------------------------
/src/store.measure.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2013 ESHA Research
3 | * Dual licensed under the MIT and GPL licenses:
4 | * http://www.opensource.org/licenses/mit-license.php
5 | * http://www.gnu.org/licenses/gpl.html
6 | *
7 | * store.remainingSpace();// returns remainingSpace value (if browser supports it)
8 | * store.charsUsed();// returns length of all data when stringified
9 | * store.charsLeft([true]);// tests how many more chars we can fit (crash threat!)
10 | * store.charsTotal([true]);// charsUsed + charsLeft, duh.
11 | *
12 | * TODO: byte/string conversions
13 | *
14 | * Status: ALPHA - changing API *and* crash threats :)
15 | */
16 | ;(function(store, _) {
17 |
18 | function put(area, s) {
19 | try {
20 | area.setItem("__test__", s);
21 | return true;
22 | } catch (e) {}
23 | }
24 |
25 | _.fn('remainingSpace', function() {
26 | return this._area.remainingSpace;
27 | });
28 | _.fn('charsUsed', function() {
29 | return _.stringify(this.getAll()).length - 2;
30 | });
31 | _.fn('charsLeft', function(test) {
32 | if (this.isFake()){ return; }
33 | if (arguments.length === 0) {
34 | test = window.confirm('Calling store.charsLeft() may crash some browsers!');
35 | }
36 | if (test) {
37 | var s = 's ', add = s;
38 | // grow add for speed
39 | while (put(store._area, s)) {
40 | s += add;
41 | if (add.length < 50000) {
42 | add = s;
43 | }
44 | }
45 | // shrink add for accuracy
46 | while (add.length > 2) {
47 | s = s.substring(0, s.length - (add.length/2));
48 | while (put(store._area, s)) {
49 | s += add;
50 | }
51 | add = add.substring(add.length/2);
52 | }
53 | _.remove(store._area, "__test__");
54 | return s.length + 8;
55 | }
56 | });
57 | _.fn('charsTotal', function(test) {
58 | return store.charsUsed() + store.charsLeft(test);
59 | });
60 |
61 | })(window.store, window.store._);
--------------------------------------------------------------------------------
/src/store.async.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2019 ESHA Research
3 | * Dual licensed under the MIT and GPL licenses:
4 | * http://www.opensource.org/licenses/mit-license.php
5 | * http://www.gnu.org/licenses/gpl.html
6 | *
7 | * Adds an 'async' duplicate on all store APIs that
8 | * performs storage-related operations asynchronously and returns
9 | * a promise.
10 | *
11 | * Status: BETA - works great, but lacks justification for existence
12 | */
13 | ;(function(window, _) {
14 |
15 | var dontPromisify = ['async', 'area', 'namespace', 'isFake', 'toString'];
16 | _.promisify = function(api) {
17 | var async = api.async = _.Store(api._id, api._area, api._ns);
18 | async._async = true;
19 | Object.keys(api).forEach(function(name) {
20 | if (name.charAt(0) !== '_' && dontPromisify.indexOf(name) < 0) {
21 | var fn = api[name];
22 | if (typeof fn === "function") {
23 | async[name] = _.promiseFn(name, fn, api);
24 | }
25 | }
26 | });
27 | return async;
28 | };
29 | _.promiseFn = function(name, fn, self) {
30 | return function promised() {
31 | var args = arguments;
32 | return new Promise(function(resolve, reject) {
33 | setTimeout(function() {
34 | try {
35 | resolve(fn.apply(self, args));
36 | } catch (e) {
37 | reject(e);
38 | }
39 | }, 0);
40 | });
41 | };
42 | };
43 |
44 | // promisify existing apis
45 | for (var apiName in _.apis) {
46 | _.promisify(_.apis[apiName]);
47 | }
48 | // ensure future apis are promisified
49 | Object.defineProperty(_.storeAPI, 'async', {
50 | enumerable: true,
51 | configurable: true,
52 | get: function() {
53 | var async = _.promisify(this);
54 | // overwrite getter to avoid re-promisifying
55 | Object.defineProperty(this, 'async', {
56 | enumerable: true,
57 | value: async
58 | });
59 | return async;
60 | }
61 | });
62 |
63 | })(window, window.store._);
64 |
--------------------------------------------------------------------------------
/src/store.array.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2017 ESHA Research
3 | * Dual licensed under the MIT and GPL licenses:
4 | * http://www.opensource.org/licenses/mit-license.php
5 | * http://www.gnu.org/licenses/gpl.html
6 | *
7 | * Adds shortcut for safely applying all available Array functions to stored values. If there is no
8 | * value, the functions will act as if upon an empty one. If there is a non, array value, it is put
9 | * into an array before the function is applied. If the function results in an empty array, the
10 | * key/value is removed from the storage, otherwise the array is restored.
11 | *
12 | * store.push('array', 'a', 1, true);// == store.set('array', (store.get('array')||[]).push('a', 1, true]));
13 | * store.indexOf('array', true);// === store.get('array').indexOf(true)
14 | *
15 | * This will add all functions of Array.prototype that are specific to the Array interface and have no
16 | * conflict with existing store functions.
17 | *
18 | * Status: BETA - useful, but adds more functions than reasonable
19 | */
20 | ;(function(_, Array) {
21 |
22 | // expose internals on the underscore to allow extensibility
23 | _.array = function(fnName, key, args) {
24 | var value = this.get(key, []),
25 | array = Array.isArray(value) ? value : [value],
26 | ret = array[fnName].apply(array, args);
27 | if (array.length > 0) {
28 | this.set(key, array.length > 1 ? array : array[0]);
29 | } else {
30 | this.remove(key);
31 | }
32 | return ret;
33 | };
34 | _.arrayFn = function(fnName) {
35 | return function(key) {
36 | return this.array(fnName, key,
37 | arguments.length > 1 ? Array.prototype.slice.call(arguments, 1) : null);
38 | };
39 | };
40 |
41 | // add function(s) to the store interface
42 | _.fn('array', _.array);
43 | Object.getOwnPropertyNames(Array.prototype).forEach(function(name) {
44 | // add Array interface functions w/o existing conflicts
45 | if (typeof Array.prototype[name] === "function") {
46 | if (!(name in _.storeAPI)) {
47 | _.fn(name, _.array[name] = _.arrayFn(name));
48 | }
49 | }
50 | });
51 |
52 | })(window.store._, window.Array);
53 |
--------------------------------------------------------------------------------
/src/store.cache.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2013 ESHA Research
3 | * Dual licensed under the MIT and GPL licenses:
4 | * http://www.opensource.org/licenses/mit-license.php
5 | * http://www.gnu.org/licenses/gpl.html
6 | *
7 | * Allows use of a number as 'overwrite' param on set calls to give time in seconds after
8 | * which the value should not be retrievable again (an expiration time).
9 | *
10 | * Status: BETA - useful, needs testing
11 | */
12 | ;(function(_) {
13 | var prefix = 'exp@',
14 | suffix = ';',
15 | parse = _.parse,
16 | _get = _.get,
17 | _set = _.set;
18 | _.parse = function(s, fn) {
19 | if (s && s.indexOf(prefix) === 0) {
20 | s = s.substring(s.indexOf(suffix)+1);
21 | }
22 | return parse(s, fn);
23 | };
24 | _.expires = function(s) {
25 | if (s && s.indexOf(prefix) === 0) {
26 | return parseInt(s.substring(prefix.length, s.indexOf(suffix)), 10);
27 | }
28 | return false;
29 | };
30 | _.when = function(sec) {// if sec, return sec->date, else date->sec
31 | var now = Math.floor((new Date().getTime())/1000);
32 | return sec ? new Date((now+sec)*1000) : now;
33 | };
34 | _.cache = function(area, key) {
35 | var s = _get(area, key),
36 | sec = _.expires(s);
37 | if (sec && _.when() >= sec) {
38 | return area.removeItem(key);
39 | }
40 | return s;
41 | };
42 | _.get = function(area, key) {
43 | var s = _.cache(area, key);
44 | return s === undefined ? null : s;
45 | };
46 | _.set = function(area, key, string, sec) {
47 | try {
48 | if (sec) {
49 | string = prefix + (_.when()+sec) + suffix + string;
50 | }
51 | _set(area, key, string);
52 | } catch (e) {
53 | if (e.name === 'QUOTA_EXCEEDED_ERR' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
54 | var changed = false;
55 | for (var i=0,m=area.length; i
10 | * Some content
11 | *
12 | * Status: BETA - uses store, doesn't extend it, deserves standalone project
13 | */
14 | ;(function(document, store, _, Array) {
15 |
16 | // expose internal functions on store._.dom for extensibility
17 | var DOM = _.dom = function() {
18 | var nodes = document.querySelectorAll(DOM.selector),
19 | array = Array.prototype.slice.call(nodes);
20 | for (var i=0; i string | String[] | number[];
5 | export type Reviver = (key: string, value: any) => any;
6 | export type EachFn = (key: any, data: any) => false | any;
7 | export type TransactFn = (data: any) => any | undefined;
8 |
9 | type BaseSet = (key: any, data: any) => any;
10 | type BaseGet = (key: any) => any;
11 | type BaseSetAll = (obj: Object) => StoredData;
12 | type BaseGetAll = () => StoredData;
13 | type BaseTransact = (fn: EachFn, value?: any) => StoredData;
14 | type BaseClear = (clear: false) => StoreBase;
15 | export type Base = BaseSet & BaseGet & BaseSetAll & BaseGetAll & BaseTransact & BaseClear;
16 |
17 | export interface StoreAPI {
18 | clear(): StoreBase;
19 | clearAll(): StoreBase;
20 | each(callback: EachFn): StoreBase;
21 | get(key: any, alt?: any|Reviver): any;
22 | getAll(fillObj?: StoredData): StoredData;
23 | has(key: any): boolean;
24 | isFake(force?: boolean): boolean;
25 | keys(fillList?: string[]): string[];
26 | namespace(namespace: string, singleArea?: true, delim?: string): StoreType;
27 | remove(key: any, alt?: any|Reviver): any;
28 | set(key: any, data: any, overwrite?: boolean|Replacer): any;
29 | setAll(data: Object, overwrite?: boolean|Replacer): StoredData;
30 | add(key: any, data: any): any;
31 | size(): number;
32 | transact(key: any, fn: TransactFn, alt?: any|Reviver): StoreBase;
33 | area(id: string, area: Storage): StoreBase
34 | }
35 |
36 | export type StoreBase = StoreAPI & Base;
37 |
38 | // these are not guaranteed to be stable across minor versions
39 | // but historically, they have been pretty much so
40 | export interface DeveloperTools {
41 | readonly version: string;
42 | readonly areas: { [name: string]: Storage };
43 | readonly apis: { [name: string]: StoreAPI };
44 | nsdelim: string;
45 | revive: Reviver;
46 | replace: Replacer;
47 | readonly fn: (name: string, fn: Function) => void;
48 | storeAPI: StoreAPI;
49 | get: (area: Storage, key: string) => string;
50 | set: (area: Storage, key: string, string: string) => void;
51 | remove: (area: Storage, key: string) => void;
52 | key: (area: Storage, i: number) => string;
53 | length: (area: Storage) => number;
54 | clear: (area: Storage) => void;
55 | parse: (s: string, fn?: Reviver) => any;
56 | stringify: (d: any, fn?: Replacer) => string;
57 | inherit: (api: StoreAPI, o: object) => object;
58 | }
59 |
60 | export type StoreType = StoreBase & {
61 | local: StoreBase;
62 | session: StoreBase;
63 | page: StoreBase;
64 | readonly _: DeveloperTools,
65 | };
66 |
67 | declare const store: StoreType
68 | export default store
69 |
--------------------------------------------------------------------------------
/src/store.cookies.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2021 ESHA Research
3 | * Dual licensed under the MIT and GPL licenses:
4 | * http://www.opensource.org/licenses/mit-license.php
5 | * http://www.gnu.org/licenses/gpl.html
6 | *
7 | * Creates a store area that uses a separate cookies for each key/value as the backing
8 | * storage. This effectively gives you the store API for all cookies..
9 | * It could definitely use more testing. It also feels like it should better
10 | * integrated with the expire plugin before we call it BETA.
11 | *
12 | * Status: ALPHA - unsupported, useful, needs testing
13 | */
14 | ;(function(window, document, store, _) {
15 |
16 | var C = _.cookies = {// still good enough for me
17 | maxAge: 60*60*24*365*10,
18 | suffix: ';path=/;sameSite=strict'
19 | };
20 | C.all = function() {
21 | if (!document.cookie) {
22 | return {};
23 | }
24 | var cookies = document.cookie.split('; '),
25 | all = {};
26 | for (var i=0, cookie, eq; i - v<%= pkg.version %> - ' +
16 | '<%= grunt.template.today("yyyy-mm-dd") %>\n' +
17 | '<%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' +
18 | '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
19 | ' Licensed <%= pkg.license %> */\n',
20 | // Task configuration.
21 | clean: {
22 | files: ['dist']
23 | },
24 | concat: {
25 | options: {
26 | banner: '<%= banner %>',
27 | process: true,
28 | stripBanners: true
29 | },
30 | dist: {
31 | src: ['src/<%= pkg.name %>.js'],
32 | dest: 'dist/<%= pkg.name %>.js'
33 | }
34 | },
35 | uglify: {
36 | options: {
37 | banner: '<%= banner %>',
38 | sourceMap: true,
39 | },
40 | dist: {
41 | src: '<%= concat.dist.dest %>',
42 | dest: 'dist/<%= pkg.name %>.min.js'
43 | }
44 | },
45 | qunit: {
46 | files: ['test/**/*.html']
47 | },
48 | jshint: {
49 | gruntfile: {
50 | options: {
51 | globals: {
52 | localStorage: false,
53 | sessionStorage: false
54 | },
55 | jshintrc: '.jshintrc'
56 | },
57 | src: 'Gruntfile.js'
58 | },
59 | src: {
60 | options: {
61 | jshintrc: 'src/.jshintrc'
62 | },
63 | src: ['src/**/*.js']
64 | },
65 | test: {
66 | options: {
67 | jshintrc: 'test/.jshintrc'
68 | },
69 | src: ['test/**/*.js']
70 | }
71 | },
72 | watch: {
73 | gruntfile: {
74 | files: '<%= jshint.gruntfile.src %>',
75 | tasks: ['jshint:gruntfile']
76 | },
77 | src: {
78 | files: '<%= jshint.src.src %>',
79 | tasks: ['jshint:src', 'qunit']
80 | },
81 | test: {
82 | files: '<%= jshint.test.src %>',
83 | tasks: ['jshint:test', 'qunit']
84 | }
85 | },
86 | nugetpack: {
87 | dist: {
88 | src: 'store2.nuspec',
89 | dest: 'dist/',
90 | options: {
91 | version: '<%= pkg.version %>'
92 | }
93 | }
94 | },
95 | nugetpush: {
96 | dist: {
97 | src: 'dist/store2.<%= pkg.version %>.nupkg'
98 | }
99 | }
100 | });
101 |
102 | // load frame task
103 | grunt.loadTasks('tasks');
104 |
105 | // Default task.
106 | grunt.registerTask('default', ['jshint', 'clean', 'concat', 'qunit', 'uglify']);
107 | grunt.registerTask('nuget', ['nugetpack', 'nugetpush']);
108 |
109 | };
110 |
--------------------------------------------------------------------------------
/src/store.bind.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2013 ESHA Research
3 | * Dual licensed under the MIT and GPL licenses:
4 | * http://www.opensource.org/licenses/mit-license.php
5 | * http://www.gnu.org/licenses/gpl.html
6 | *
7 | * Makes it easy to watch for storage events by enhancing the events and
8 | * allowing binding to particular keys and/or namespaces.
9 | *
10 | * // listen to particular key storage events (yes, this is namespace sensitive)
11 | * store.on('foo', function listenToFoo(e){ console.log('foo was changed:', e); });
12 | * store.off('foo', listenToFoo);
13 | *
14 | * // listen to all storage events
15 | * store.on(function storageEvent(e){ console.log('web storage:', e); });
16 | * store.off(storageEvent);
17 | *
18 | * Status: ALPHA - useful, if you don't mind incomplete browser support for events
19 | */
20 | ;(function(window, document, _) {
21 | _.fn('on', function(key, fn) {
22 | if (!fn) { fn = key; key = ''; }// shift args when needed
23 | var s = this,
24 | bound,
25 | id = _.id(this._area);
26 | if (window.addEventListener) {
27 | window.addEventListener("storage", bound = function(e) {
28 | var k = s._out(e.key);
29 | if (k && (!key || k === key)) {// must match key if listener has one
30 | var eid = _.id(e.storageArea);
31 | if (!eid || id === eid) {// must match area, if event has a known one
32 | return fn.call(s, _.event(k, s, e));
33 | }
34 | }
35 | }, false);
36 | } else {
37 | document.attachEvent("onstorage", bound = function() {
38 | return fn.call(s, window.event);
39 | });
40 | }
41 | fn['_'+key+'listener'] = bound;
42 | return s;
43 | });
44 | _.fn('off', function(key, fn) {
45 | if (!fn) { fn = key; key = ''; }// shift args when needed
46 | var bound = fn['_'+key+'listener'];
47 | if (window.removeEventListener) {
48 | window.removeEventListener("storage", bound);
49 | } else {
50 | document.detachEvent("onstorage", bound);
51 | }
52 | return this;
53 | });
54 | _.event = function(k, s, e) {
55 | var event = {
56 | key: k,
57 | namespace: s.namespace(),
58 | newValue: _.parse(e.newValue),
59 | oldValue: _.parse(e.oldValue),
60 | url: e.url || e.uri,
61 | storageArea: e.storageArea,
62 | source: e.source,
63 | timeStamp: e.timeStamp,
64 | originalEvent: e
65 | };
66 | if (_.cache) {
67 | var min = _.expires(e.newValue || e.oldValue);
68 | if (min) {
69 | event.expires = _.when(min);
70 | }
71 | }
72 | return event;
73 | };
74 | _.id = function(area) {
75 | for (var id in _.areas) {
76 | if (area === _.areas[id]) {
77 | return id;
78 | }
79 | }
80 | };
81 | })(window, document, window.store._);
--------------------------------------------------------------------------------
/src/store.overflow.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2013 ESHA Research
3 | * Dual licensed under the MIT and GPL licenses:
4 | * http://www.opensource.org/licenses/mit-license.php
5 | * http://www.gnu.org/licenses/gpl.html
6 | *
7 | * When quota is reached on a storage area, this shifts incoming values to
8 | * fake storage, so they last only as long as the page does. This is useful
9 | * because it is more burdensome for localStorage to recover from quota errors
10 | * than incomplete caches. In other words, it is wiser to rely on store.js
11 | * never complaining than never missing data. You should already be checking
12 | * the integrity of cached data on every page load.
13 | *
14 | * Status: BETA
15 | */
16 | ;(function(store, _) {
17 | var _set = _.set,
18 | _get = _.get,
19 | _remove = _.remove,
20 | _key = _.key,
21 | _length = _.length,
22 | _clear = _.clear;
23 |
24 | _.overflow = function(area, create) {
25 | var name = area === _.areas.local ? '+local+' :
26 | area === _.areas.session ? '+session+' : false;
27 | if (name) {
28 | var overflow = _.areas[name];
29 | if (create && !overflow) {
30 | overflow = store.area(name)._area;// area() copies to _.areas
31 | } else if (create === false) {
32 | delete _.areas[name];
33 | delete store[name];
34 | }
35 | return overflow;
36 | }
37 | };
38 | _.set = function(area, key, string) {
39 | try {
40 | _set.apply(this, arguments);
41 | } catch (e) {
42 | if (e.name === 'QUOTA_EXCEEDED_ERR' ||
43 | e.name === 'NS_ERROR_DOM_QUOTA_REACHED' ||
44 | e.toString().indexOf("QUOTA_EXCEEDED_ERR") !== -1 ||
45 | e.toString().indexOf("QuotaExceededError") !== -1) {
46 | // the e.toString is needed for IE9 / IE10, cos name is empty there
47 | return _.set(_.overflow(area, true), key, string);
48 | }
49 | throw e;
50 | }
51 | };
52 | _.get = function(area, key) {
53 | var overflow = _.overflow(area);
54 | return (overflow && _get.call(this, overflow, key)) ||
55 | _get.apply(this, arguments);
56 | };
57 | _.remove = function(area, key) {
58 | var overflow = _.overflow(area);
59 | if (overflow){ _remove.call(this, overflow, key); }
60 | _remove.apply(this, arguments);
61 | };
62 | _.key = function(area, i) {
63 | var overflow = _.overflow(area);
64 | if (overflow) {
65 | var l = _length.call(this, area);
66 | if (i >= l) {
67 | i = i - l;// make i overflow-relative
68 | for (var j=0, m=_length.call(this, overflow); jc.length(this._area)&&(e--,d--)}return b||this},keys:function(a){return this.each(function(a,b,c){c.push(a)},a||[])},get:function(a,b){var d,e=c.get(this._area,this._in(a));return"function"==typeof b&&(d=b,b=null),null!==e?c.parse(e,d):null!=b?b:e},getAll:function(a){return this.each(function(a,b,c){c[a]=b},a||{})},transact:function(a,b,c){var d=this.get(a,c),e=b(d);return this.set(a,void 0===e?d:e),this},set:function(a,b,d){var e,f=this.get(a);return null!=f&&!1===d?b:("function"==typeof d&&(e=d,d=void 0),c.set(this._area,this._in(a),c.stringify(b,e),d)||f)},setAll:function(a,b){var c,d;for(var e in a)d=a[e],this.set(e,d,b)!==d&&(c=!0);return c},add:function(a,b,d){var e=this.get(a);if(e instanceof Array)b=e.concat(b);else if(null!==e){var f=typeof e;if(f===typeof b&&"object"===f){for(var g in b)e[g]=b[g];b=e}else b=e+b}return c.set(this._area,this._in(a),c.stringify(b,d)),b},remove:function(a,b){var d=this.get(a,b);return c.remove(this._area,this._in(a)),d},clear:function(){return this._ns?this.each(function(a){c.remove(this._area,this._in(a))},1):c.clear(this._area),this},clearAll:function(){var a=this._area;for(var b in c.areas)c.areas.hasOwnProperty(b)&&(this._area=c.areas[b],this.clear());return this._area=a,this},_in:function(a){return"string"!=typeof a&&(a=c.stringify(a)),this._ns?this._ns+a:a},_out:function(a){return this._ns?a&&0===a.indexOf(this._ns)?a.substring(this._ns.length):void 0:a}},storage:function(a){return c.inherit(c.storageAPI,{items:{},name:a})},storageAPI:{length:0,has:function(a){return this.items.hasOwnProperty(a)},key:function(a){var b=0;for(var c in this.items)if(this.has(c)&&a===b++)return c},setItem:function(a,b){this.has(a)||this.length++,this.items[a]=b},removeItem:function(a){this.has(a)&&(delete this.items[a],this.length--)},getItem:function(a){return this.has(a)?this.items[a]:null},clear:function(){for(var a in this.items)this.removeItem(a)}}},d=c.Store("local",function(){try{return localStorage}catch(a){}}());d.local=d,d._=c,d.area("session",function(){try{return sessionStorage}catch(a){}}()),d.area("page",c.storage("page")),"function"==typeof b&&void 0!==b.amd?b("store2",[],function(){return d}):"undefined"!=typeof module&&module.exports?module.exports=d:(a.store&&(c.conflict=a.store),a.store=d)}(this,this&&this.define);
5 | //# sourceMappingURL=store2.min.js.map
--------------------------------------------------------------------------------
/src/store.old.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2013 ESHA Research
3 | * Dual licensed under the MIT and GPL licenses:
4 | * http://www.opensource.org/licenses/mit-license.php
5 | * http://www.gnu.org/licenses/gpl.html
6 | *
7 | * If fake (non-persistent) storage for users stuck in the dark ages
8 | * does not satisfy you, this will replace it with the a reasonable imitator for their
9 | * pathetic, incompetent browser. Note that the session replacement here is potentially
10 | * insecure as it uses window.name without any fancy protections.
11 | *
12 | * Status: BETA - unsupported, useful, needs testing & refining
13 | */
14 | ;(function(window, document, store, _) {
15 |
16 | function addUpdateFn(area, name, update) {
17 | var old = area[name];
18 | area[name] = function() {
19 | var ret = old.apply(this, arguments);
20 | update.apply(this, arguments);
21 | return ret;
22 | };
23 | }
24 | function create(name, items, update) {
25 | var length = 0;
26 | for (var k in items) {
27 | if (items.hasOwnProperty(k)) {
28 | length++;
29 | }
30 | }
31 | var area = _.inherit(_.storageAPI, { items:items, length:length, name:name });
32 | if (update) {
33 | addUpdateFn(area, 'setItem', update);
34 | addUpdateFn(area, 'removeItem', update);
35 | }
36 | return area;
37 | }
38 |
39 | if (store.isFake()) {
40 | var area;
41 |
42 | if (document.documentElement.addBehavior) {// IE userData
43 | var el = document.createElement('div'),
44 | sn = 'localStorage',
45 | body = document.body,
46 | wrap = function wrap(fn) {
47 | return function() {
48 | body.appendChild(el);
49 | el.addBehavior('#default#userData');
50 | el.load(sn);
51 | var ret = fn.apply(store._area, arguments);
52 | el.save(sn);
53 | body.removeChild(el);
54 | return ret;
55 | };
56 | },
57 | has = function has(key){
58 | return el.getAttribute(key) !== null;
59 | },
60 | UserDataStorage = function UserDataStorage(){};
61 |
62 | UserDataStorage.prototype = {
63 | length: (wrap(function(){
64 | return el.XMLDocument.documentElement.attributes.length;
65 | }))(),
66 | has: wrap(has),
67 | key: wrap(function(i) {
68 | return el.XMLDocument.documentElement.attributes[i];
69 | }),
70 | setItem: wrap(function(k, v) {
71 | if (!has(k)) {
72 | this.length++;
73 | }
74 | el.setAttribute(k, v);
75 | }),
76 | removeItem: wrap(function(k) {
77 | if (has(k)) {
78 | el.removeAttribute(k);
79 | this.length--;
80 | }
81 | }),
82 | getItem: wrap(function(k){ return el.getAttribute(k); }),
83 | clear: wrap(function() {
84 | var all = el.XMLDocument.documentElement.attributes;
85 | for (var i=0, a; !!(a = all[i]); i++) {
86 | el.removeAttribute(a.name);
87 | }
88 | this.length = 0;
89 | })
90 | };
91 | area = new UserDataStorage();
92 |
93 | } else if ('globalStorage' in window && window.globalStorage) {// FF globalStorage
94 | area = create('global', window.globalStorage[window.location.hostname]);
95 |
96 | } else {// cookie
97 | var date = new Date(),
98 | key = 'store.local',
99 | items = {},
100 | cookies = document.cookie.split(';');
101 | date.setTime(date.getTime()+(5*365*24*60*60*1000));//5 years out
102 | date = date.toGMTString();
103 | for (var i=0,m=cookies.length; i li:last-child {
206 | border-radius: 0 0 5px 5px;
207 | -moz-border-radius: 0 0 5px 5px;
208 | -webkit-border-bottom-right-radius: 5px;
209 | -webkit-border-bottom-left-radius: 5px;
210 | }
211 |
212 | #qunit-tests .fail { color: #000000; background-color: #EE5757; }
213 | #qunit-tests .fail .test-name,
214 | #qunit-tests .fail .module-name { color: #000000; }
215 |
216 | #qunit-tests .fail .test-actual { color: #EE5757; }
217 | #qunit-tests .fail .test-expected { color: green; }
218 |
219 | #qunit-banner.qunit-fail { background-color: #EE5757; }
220 |
221 |
222 | /** Result */
223 |
224 | #qunit-testresult {
225 | padding: 0.5em 0.5em 0.5em 2.5em;
226 |
227 | color: #2b81af;
228 | background-color: #D2E0E6;
229 |
230 | border-bottom: 1px solid white;
231 | }
232 | #qunit-testresult .module-name {
233 | font-weight: bold;
234 | }
235 |
236 | /** Fixture */
237 |
238 | #qunit-fixture {
239 | position: absolute;
240 | top: -10000px;
241 | left: -10000px;
242 | width: 1000px;
243 | height: 1000px;
244 | }
245 |
--------------------------------------------------------------------------------
/dist/store2.min.js.map:
--------------------------------------------------------------------------------
1 | {"version":3,"sources":["store2.js"],"names":["window","define","_","version","areas","apis","nsdelim","inherit","api","o","p","hasOwnProperty","Object","defineProperty","getOwnPropertyDescriptor","stringify","d","fn","undefined","JSON","replace","parse","s","revive","e","name","storeAPI","get","area","key","getItem","set","string","setItem","remove","removeItem","i","length","clear","Store","id","namespace","store","data","overwrite","arguments","getAll","transact","each","setAll","_id","_area","storage","_ns","this","singleArea","delim","_delim","substring","ns","isFake","force","_real","toString","has","_in","size","keys","fill","m","_out","call","fillList","k","v","list","push","alt","fillObj","all","val","ret","replacer","changed","add","Array","concat","type","clearAll","indexOf","storageAPI","items","c","localStorage","local","sessionStorage","amd","module","exports","conflict"],"mappings":";;;CAEC,SAAUA,EAAQC,GACf,GAAIC,IACAC,QAAS,SACTC,SACAC,QACAC,QAAS,IAGTC,QAAS,SAASC,EAAKC,GACnB,IAAK,GAAIC,KAAKF,GACLC,EAAEE,eAAeD,IAClBE,OAAOC,eAAeJ,EAAGC,EAAGE,OAAOE,yBAAyBN,EAAKE,GAGzE,OAAOD,IAEXM,UAAW,SAASC,EAAGC,GACnB,WAAaC,KAANF,GAAgC,kBAANA,GAAmBA,EAAE,GAAKG,KAAKJ,UAAUC,EAAEC,GAAIf,EAAEkB,UAEtFC,MAAO,SAASC,EAAGL,GAEf,IAAK,MAAOE,MAAKE,MAAMC,EAAEL,GAAIf,EAAEqB,QAAU,MAAMC,GAAI,MAAOF,KAI9DL,GAAI,SAASQ,EAAMR,GACff,EAAEwB,SAASD,GAAQR,CACnB,KAAK,GAAIT,KAAON,GAAEG,KACdH,EAAEG,KAAKG,GAAKiB,GAAQR,GAG5BU,IAAK,SAASC,EAAMC,GAAM,MAAOD,GAAKE,QAAQD,IAC9CE,IAAK,SAASH,EAAMC,EAAKG,GAASJ,EAAKK,QAAQJ,EAAKG,IACpDE,OAAQ,SAASN,EAAMC,GAAMD,EAAKO,WAAWN,IAC7CA,IAAK,SAASD,EAAMQ,GAAI,MAAOR,GAAKC,IAAIO,IACxCC,OAAQ,SAAST,GAAO,MAAOA,GAAKS,QACpCC,MAAO,SAASV,GAAOA,EAAKU,SAG5BC,MAAO,SAASC,EAAIZ,EAAMa,GACtB,GAAIC,GAAQxC,EAAEK,QAAQL,EAAEwB,SAAU,SAASG,EAAKc,EAAMC,GAClD,MAAyB,KAArBC,UAAUR,OAAsBK,EAAMI,SACtB,kBAATH,GAA6BD,EAAMK,SAASlB,EAAKc,EAAMC,OACrD1B,KAATyB,EAA4BD,EAAMX,IAAIF,EAAKc,EAAMC,GAClC,gBAARf,IAAmC,gBAARA,GAA0Ba,EAAMf,IAAIE,GACvD,kBAARA,GAA4Ba,EAAMM,KAAKnB,GAC7CA,EACEa,EAAMO,OAAOpB,EAAKc,GADPD,EAAMJ,SAG5BI,GAAMQ,IAAMV,CACZ,KAEIZ,EAAKK,QADS,gBACQ,MACtBS,EAAMS,MAAQvB,EACdA,EAAKO,WAHS,iBAIhB,MAAOX,GACLkB,EAAMS,MAAQjD,EAAEkD,QAAQ,QAS5B,MAPAV,GAAMW,IAAMZ,GAAa,GACpBvC,EAAEE,MAAMoC,KACTtC,EAAEE,MAAMoC,GAAME,EAAMS,OAEnBjD,EAAEG,KAAKqC,EAAMW,IAAIX,EAAMQ,OACxBhD,EAAEG,KAAKqC,EAAMW,IAAIX,EAAMQ,KAAOR,GAE3BA,GAEXhB,UAEIE,KAAM,SAASY,EAAIZ,GACf,GAAIc,GAAQY,KAAKd,EAKjB,OAJKE,IAAUA,EAAMd,OACjBc,EAAQxC,EAAEqC,MAAMC,EAAIZ,EAAM0B,KAAKD,KAC1BC,KAAKd,KAAMc,KAAKd,GAAME,IAExBA,GAEXD,UAAW,SAASA,EAAWc,EAAYC,GAEvC,GADAA,EAAQA,GAASF,KAAKG,QAAUvD,EAAEI,SAC7BmC,EACD,MAAOa,MAAKD,IAAMC,KAAKD,IAAIK,UAAU,EAAEJ,KAAKD,IAAIhB,OAAOmB,EAAMnB,QAAU,EAE3E,IAAIsB,GAAKlB,EAAWC,EAAQY,KAAKK,EACjC,MAAKjB,GAAUA,EAAMD,YACjBC,EAAQxC,EAAEqC,MAAMe,KAAKJ,IAAKI,KAAKH,MAAOG,KAAKD,IAAIM,EAAGH,GAClDd,EAAMe,OAASD,EACVF,KAAKK,KAAML,KAAKK,GAAMjB,GACtBa,IACD,IAAK,GAAI9B,KAAQvB,GAAEE,MACfsC,EAAMd,KAAKH,EAAMvB,EAAEE,MAAMqB,GAIrC,OAAOiB,IAEXkB,OAAQ,SAASC,GAOb,MANIA,IACAP,KAAKQ,MAAQR,KAAKH,MAClBG,KAAKH,MAAQjD,EAAEkD,QAAQ,UACN,IAAVS,IACPP,KAAKH,MAAQG,KAAKQ,OAASR,KAAKH,OAET,SAApBG,KAAKH,MAAM1B,MAEtBsC,SAAU,WACN,MAAO,SAAST,KAAKD,IAAI,IAAIC,KAAKb,YAAY,IAAI,IAAIa,KAAKJ,IAAI,KAInEc,IAAK,SAASnC,GACV,MAAIyB,MAAKH,MAAMa,IACJV,KAAKH,MAAMa,IAAIV,KAAKW,IAAIpC,OAEzByB,KAAKW,IAAIpC,IAAQyB,MAAKH,QAEpCe,KAAM,WAAY,MAAOZ,MAAKa,OAAO9B,QACrCW,KAAM,SAAS/B,EAAImD,GACf,IAAK,GAAIhC,GAAE,EAAGiC,EAAEnE,EAAEmC,OAAOiB,KAAKH,OAAQf,EAAEiC,EAAGjC,IAAK,CAC5C,GAAIP,GAAMyB,KAAKgB,KAAKpE,EAAE2B,IAAIyB,KAAKH,MAAOf,GACtC,QAAYlB,KAARW,IACgD,IAA5CZ,EAAGsD,KAAKjB,KAAMzB,EAAKyB,KAAK3B,IAAIE,GAAMuC,GAClC,KAGJC,GAAInE,EAAEmC,OAAOiB,KAAKH,SAAUkB,IAAKjC,KAEzC,MAAOgC,IAAQd,MAEnBa,KAAM,SAASK,GACX,MAAOlB,MAAKN,KAAK,SAASyB,EAAGC,EAAGC,GAAOA,EAAKC,KAAKH,IAAOD,QAE5D7C,IAAK,SAASE,EAAKgD,GACf,GACI5D,GADAK,EAAIpB,EAAEyB,IAAI2B,KAAKH,MAAOG,KAAKW,IAAIpC,GAMnC,OAJmB,kBAARgD,KACP5D,EAAK4D,EACLA,EAAM,MAEG,OAANvD,EAAapB,EAAEmB,MAAMC,EAAGL,GACpB,MAAP4D,EAAcA,EAAMvD,GAE5BwB,OAAQ,SAASgC,GACb,MAAOxB,MAAKN,KAAK,SAASyB,EAAGC,EAAGK,GAAMA,EAAIN,GAAKC,GAAMI,QAEzD/B,SAAU,SAASlB,EAAKZ,EAAI4D,GACxB,GAAIG,GAAM1B,KAAK3B,IAAIE,EAAKgD,GACpBI,EAAMhE,EAAG+D,EAEb,OADA1B,MAAKvB,IAAIF,MAAaX,KAAR+D,EAAoBD,EAAMC,GACjC3B,MAEXvB,IAAK,SAASF,EAAKc,EAAMC,GACrB,GACIsC,GADAlE,EAAIsC,KAAK3B,IAAIE,EAEjB,OAAS,OAALb,IAA2B,IAAd4B,EACND,GAEc,kBAAdC,KACPsC,EAAWtC,EACXA,MAAY1B,IAEThB,EAAE6B,IAAIuB,KAAKH,MAAOG,KAAKW,IAAIpC,GAAM3B,EAAEa,UAAU4B,EAAMuC,GAAWtC,IAAc5B,IAEvFiC,OAAQ,SAASN,EAAMC,GACnB,GAAIuC,GAASH,CACb,KAAK,GAAInD,KAAOc,GACZqC,EAAMrC,EAAKd,GACPyB,KAAKvB,IAAIF,EAAKmD,EAAKpC,KAAeoC,IAClCG,GAAU,EAGlB,OAAOA,IAEXC,IAAK,SAASvD,EAAKc,EAAMuC,GACrB,GAAIlE,GAAIsC,KAAK3B,IAAIE,EACjB,IAAIb,YAAaqE,OACb1C,EAAO3B,EAAEsE,OAAO3C,OACb,IAAU,OAAN3B,EAAY,CACnB,GAAIuE,SAAcvE,EAClB,IAAIuE,UAAgB5C,IAAiB,WAAT4C,EAAmB,CAC3C,IAAK,GAAId,KAAK9B,GACV3B,EAAEyD,GAAK9B,EAAK8B,EAEhB9B,GAAO3B,MAEP2B,GAAO3B,EAAI2B,EAInB,MADAzC,GAAE6B,IAAIuB,KAAKH,MAAOG,KAAKW,IAAIpC,GAAM3B,EAAEa,UAAU4B,EAAMuC,IAC5CvC,GAEXT,OAAQ,SAASL,EAAKgD,GAClB,GAAI7D,GAAIsC,KAAK3B,IAAIE,EAAKgD,EAEtB,OADA3E,GAAEgC,OAAOoB,KAAKH,MAAOG,KAAKW,IAAIpC,IACvBb,GAEXsB,MAAO,WAMH,MALKgB,MAAKD,IAGNC,KAAKN,KAAK,SAASyB,GAAIvE,EAAEgC,OAAOoB,KAAKH,MAAOG,KAAKW,IAAIQ,KAAQ,GAF7DvE,EAAEoC,MAAMgB,KAAKH,OAIVG,MAEXkC,SAAU,WACN,GAAI5D,GAAO0B,KAAKH,KAChB,KAAK,GAAIX,KAAMtC,GAAEE,MACTF,EAAEE,MAAMO,eAAe6B,KACvBc,KAAKH,MAAQjD,EAAEE,MAAMoC,GACrBc,KAAKhB,QAIb,OADAgB,MAAKH,MAAQvB,EACN0B,MAIXW,IAAK,SAASQ,GAEV,MADiB,gBAANA,KAAiBA,EAAIvE,EAAEa,UAAU0D,IACrCnB,KAAKD,IAAMC,KAAKD,IAAMoB,EAAIA,GAErCH,KAAM,SAASG,GACX,MAAOnB,MAAKD,IACRoB,GAA6B,IAAxBA,EAAEgB,QAAQnC,KAAKD,KAChBoB,EAAEf,UAAUJ,KAAKD,IAAIhB,YACrBnB,GACJuD,IAGZrB,QAAS,SAAS3B,GACd,MAAOvB,GAAEK,QAAQL,EAAEwF,YAAcC,SAAWlE,KAAMA,KAEtDiE,YACIrD,OAAQ,EACR2B,IAAK,SAASS,GAAI,MAAOnB,MAAKqC,MAAMhF,eAAe8D,IACnD5C,IAAK,SAASO,GACV,GAAIwD,GAAI,CACR,KAAK,GAAInB,KAAKnB,MAAKqC,MACf,GAAIrC,KAAKU,IAAIS,IAAMrC,IAAMwD,IACrB,MAAOnB,IAInBxC,QAAS,SAASwC,EAAGC,GACZpB,KAAKU,IAAIS,IACVnB,KAAKjB,SAETiB,KAAKqC,MAAMlB,GAAKC,GAEpBvC,WAAY,SAASsC,GACbnB,KAAKU,IAAIS,WACFnB,MAAKqC,MAAMlB,GAClBnB,KAAKjB,WAGbP,QAAS,SAAS2C,GAAI,MAAOnB,MAAKU,IAAIS,GAAKnB,KAAKqC,MAAMlB,GAAK,MAC3DnC,MAAO,WAAY,IAAK,GAAImC,KAAKnB,MAAKqC,MAAQrC,KAAKnB,WAAWsC,MAIlE/B,EAEAxC,EAAEqC,MAAM,QAAS,WAAY,IAAK,MAAOsD,cAAe,MAAMrE,QAClEkB,GAAMoD,MAAQpD,EACdA,EAAMxC,EAAIA,EAEVwC,EAAMd,KAAK,UAAW,WAAY,IAAK,MAAOmE,gBAAiB,MAAMvE,SACrEkB,EAAMd,KAAK,OAAQ1B,EAAEkD,QAAQ,SAEP,kBAAXnD,QAAwCiB,KAAfjB,EAAO+F,IACvC/F,EAAO,YAAc,WACjB,MAAOyC,KAEc,mBAAXuD,SAA0BA,OAAOC,QAC/CD,OAAOC,QAAUxD,GAGb1C,EAAO0C,QAAQxC,EAAEiG,SAAWnG,EAAO0C,OACvC1C,EAAO0C,MAAQA,IAGpBY,KAAMA,MAAQA,KAAKrD","file":"store2.min.js"}
--------------------------------------------------------------------------------
/dist/store2.js:
--------------------------------------------------------------------------------
1 | /*! store2 - v2.14.4 - 2024-12-26
2 | * Copyright (c) 2024 Nathan Bubna; Licensed MIT */
3 | ;(function(window, define) {
4 | var _ = {
5 | version: "2.14.4",
6 | areas: {},
7 | apis: {},
8 | nsdelim: '.',
9 |
10 | // utilities
11 | inherit: function(api, o) {
12 | for (var p in api) {
13 | if (!o.hasOwnProperty(p)) {
14 | Object.defineProperty(o, p, Object.getOwnPropertyDescriptor(api, p));
15 | }
16 | }
17 | return o;
18 | },
19 | stringify: function(d, fn) {
20 | return d === undefined || typeof d === "function" ? d+'' : JSON.stringify(d,fn||_.replace);
21 | },
22 | parse: function(s, fn) {
23 | // if it doesn't parse, return as is
24 | try{ return JSON.parse(s,fn||_.revive); }catch(e){ return s; }
25 | },
26 |
27 | // extension hooks
28 | fn: function(name, fn) {
29 | _.storeAPI[name] = fn;
30 | for (var api in _.apis) {
31 | _.apis[api][name] = fn;
32 | }
33 | },
34 | get: function(area, key){ return area.getItem(key); },
35 | set: function(area, key, string){ area.setItem(key, string); },
36 | remove: function(area, key){ area.removeItem(key); },
37 | key: function(area, i){ return area.key(i); },
38 | length: function(area){ return area.length; },
39 | clear: function(area){ area.clear(); },
40 |
41 | // core functions
42 | Store: function(id, area, namespace) {
43 | var store = _.inherit(_.storeAPI, function(key, data, overwrite) {
44 | if (arguments.length === 0){ return store.getAll(); }
45 | if (typeof data === "function"){ return store.transact(key, data, overwrite); }// fn=data, alt=overwrite
46 | if (data !== undefined){ return store.set(key, data, overwrite); }
47 | if (typeof key === "string" || typeof key === "number"){ return store.get(key); }
48 | if (typeof key === "function"){ return store.each(key); }
49 | if (!key){ return store.clear(); }
50 | return store.setAll(key, data);// overwrite=data, data=key
51 | });
52 | store._id = id;
53 | try {
54 | var testKey = '__store2_test';
55 | area.setItem(testKey, 'ok');
56 | store._area = area;
57 | area.removeItem(testKey);
58 | } catch (e) {
59 | store._area = _.storage('fake');
60 | }
61 | store._ns = namespace || '';
62 | if (!_.areas[id]) {
63 | _.areas[id] = store._area;
64 | }
65 | if (!_.apis[store._ns+store._id]) {
66 | _.apis[store._ns+store._id] = store;
67 | }
68 | return store;
69 | },
70 | storeAPI: {
71 | // admin functions
72 | area: function(id, area) {
73 | var store = this[id];
74 | if (!store || !store.area) {
75 | store = _.Store(id, area, this._ns);//new area-specific api in this namespace
76 | if (!this[id]){ this[id] = store; }
77 | }
78 | return store;
79 | },
80 | namespace: function(namespace, singleArea, delim) {
81 | delim = delim || this._delim || _.nsdelim;
82 | if (!namespace){
83 | return this._ns ? this._ns.substring(0,this._ns.length-delim.length) : '';
84 | }
85 | var ns = namespace, store = this[ns];
86 | if (!store || !store.namespace) {
87 | store = _.Store(this._id, this._area, this._ns+ns+delim);//new namespaced api
88 | store._delim = delim;
89 | if (!this[ns]){ this[ns] = store; }
90 | if (!singleArea) {
91 | for (var name in _.areas) {
92 | store.area(name, _.areas[name]);
93 | }
94 | }
95 | }
96 | return store;
97 | },
98 | isFake: function(force) {
99 | if (force) {
100 | this._real = this._area;
101 | this._area = _.storage('fake');
102 | } else if (force === false) {
103 | this._area = this._real || this._area;
104 | }
105 | return this._area.name === 'fake';
106 | },
107 | toString: function() {
108 | return 'store'+(this._ns?'.'+this.namespace():'')+'['+this._id+']';
109 | },
110 |
111 | // storage functions
112 | has: function(key) {
113 | if (this._area.has) {
114 | return this._area.has(this._in(key));//extension hook
115 | }
116 | return !!(this._in(key) in this._area);
117 | },
118 | size: function(){ return this.keys().length; },
119 | each: function(fn, fill) {// fill is used by keys(fillList) and getAll(fillList))
120 | for (var i=0, m=_.length(this._area); i _.length(this._area)) { m--; i--; }// in case of removeItem
128 | }
129 | return fill || this;
130 | },
131 | keys: function(fillList) {
132 | return this.each(function(k, v, list){ list.push(k); }, fillList || []);
133 | },
134 | get: function(key, alt) {
135 | var s = _.get(this._area, this._in(key)),
136 | fn;
137 | if (typeof alt === "function") {
138 | fn = alt;
139 | alt = null;
140 | }
141 | return s !== null ? _.parse(s, fn) :
142 | alt != null ? alt : s;
143 | },
144 | getAll: function(fillObj) {
145 | return this.each(function(k, v, all){ all[k] = v; }, fillObj || {});
146 | },
147 | transact: function(key, fn, alt) {
148 | var val = this.get(key, alt),
149 | ret = fn(val);
150 | this.set(key, ret === undefined ? val : ret);
151 | return this;
152 | },
153 | set: function(key, data, overwrite) {
154 | var d = this.get(key),
155 | replacer;
156 | if (d != null && overwrite === false) {
157 | return data;
158 | }
159 | if (typeof overwrite === "function") {
160 | replacer = overwrite;
161 | overwrite = undefined;
162 | }
163 | return _.set(this._area, this._in(key), _.stringify(data, replacer), overwrite) || d;
164 | },
165 | setAll: function(data, overwrite) {
166 | var changed, val;
167 | for (var key in data) {
168 | val = data[key];
169 | if (this.set(key, val, overwrite) !== val) {
170 | changed = true;
171 | }
172 | }
173 | return changed;
174 | },
175 | add: function(key, data, replacer) {
176 | var d = this.get(key);
177 | if (d instanceof Array) {
178 | data = d.concat(data);
179 | } else if (d !== null) {
180 | var type = typeof d;
181 | if (type === typeof data && type === 'object') {
182 | for (var k in data) {
183 | d[k] = data[k];
184 | }
185 | data = d;
186 | } else {
187 | data = d + data;
188 | }
189 | }
190 | _.set(this._area, this._in(key), _.stringify(data, replacer));
191 | return data;
192 | },
193 | remove: function(key, alt) {
194 | var d = this.get(key, alt);
195 | _.remove(this._area, this._in(key));
196 | return d;
197 | },
198 | clear: function() {
199 | if (!this._ns) {
200 | _.clear(this._area);
201 | } else {
202 | this.each(function(k){ _.remove(this._area, this._in(k)); }, 1);
203 | }
204 | return this;
205 | },
206 | clearAll: function() {
207 | var area = this._area;
208 | for (var id in _.areas) {
209 | if (_.areas.hasOwnProperty(id)) {
210 | this._area = _.areas[id];
211 | this.clear();
212 | }
213 | }
214 | this._area = area;
215 | return this;
216 | },
217 |
218 | // internal use functions
219 | _in: function(k) {
220 | if (typeof k !== "string"){ k = _.stringify(k); }
221 | return this._ns ? this._ns + k : k;
222 | },
223 | _out: function(k) {
224 | return this._ns ?
225 | k && k.indexOf(this._ns) === 0 ?
226 | k.substring(this._ns.length) :
227 | undefined : // so each() knows to skip it
228 | k;
229 | }
230 | },// end _.storeAPI
231 | storage: function(name) {
232 | return _.inherit(_.storageAPI, { items: {}, name: name });
233 | },
234 | storageAPI: {
235 | length: 0,
236 | has: function(k){ return this.items.hasOwnProperty(k); },
237 | key: function(i) {
238 | var c = 0;
239 | for (var k in this.items){
240 | if (this.has(k) && i === c++) {
241 | return k;
242 | }
243 | }
244 | },
245 | setItem: function(k, v) {
246 | if (!this.has(k)) {
247 | this.length++;
248 | }
249 | this.items[k] = v;
250 | },
251 | removeItem: function(k) {
252 | if (this.has(k)) {
253 | delete this.items[k];
254 | this.length--;
255 | }
256 | },
257 | getItem: function(k){ return this.has(k) ? this.items[k] : null; },
258 | clear: function(){ for (var k in this.items){ this.removeItem(k); } }
259 | }// end _.storageAPI
260 | };
261 |
262 | var store =
263 | // safely set this up (throws error in IE10/32bit mode for local files)
264 | _.Store("local", (function(){try{ return localStorage; }catch(e){}})());
265 | store.local = store;// for completeness
266 | store._ = _;// for extenders and debuggers...
267 | // safely setup store.session (throws exception in FF for file:/// urls)
268 | store.area("session", (function(){try{ return sessionStorage; }catch(e){}})());
269 | store.area("page", _.storage("page"));
270 |
271 | if (typeof define === 'function' && define.amd !== undefined) {
272 | define('store2', [], function () {
273 | return store;
274 | });
275 | } else if (typeof module !== 'undefined' && module.exports) {
276 | module.exports = store;
277 | } else {
278 | // expose the primary store fn to the global object and save conflicts
279 | if (window.store){ _.conflict = window.store; }
280 | window.store = store;
281 | }
282 |
283 | })(this, this && this.define);
284 |
--------------------------------------------------------------------------------
/src/store2.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2022, ESHA Research
3 | * Dual licensed under the MIT and GPL licenses:
4 | * http://www.opensource.org/licenses/mit-license.php
5 | * http://www.gnu.org/licenses/gpl.html
6 | */
7 | ;(function(window, define) {
8 | var _ = {
9 | version: "<%= pkg.version %>",
10 | areas: {},
11 | apis: {},
12 | nsdelim: '.',
13 |
14 | // utilities
15 | inherit: function(api, o) {
16 | for (var p in api) {
17 | if (!o.hasOwnProperty(p)) {
18 | Object.defineProperty(o, p, Object.getOwnPropertyDescriptor(api, p));
19 | }
20 | }
21 | return o;
22 | },
23 | stringify: function(d, fn) {
24 | return d === undefined || typeof d === "function" ? d+'' : JSON.stringify(d,fn||_.replace);
25 | },
26 | parse: function(s, fn) {
27 | // if it doesn't parse, return as is
28 | try{ return JSON.parse(s,fn||_.revive); }catch(e){ return s; }
29 | },
30 |
31 | // extension hooks
32 | fn: function(name, fn) {
33 | _.storeAPI[name] = fn;
34 | for (var api in _.apis) {
35 | _.apis[api][name] = fn;
36 | }
37 | },
38 | get: function(area, key){ return area.getItem(key); },
39 | set: function(area, key, string){ area.setItem(key, string); },
40 | remove: function(area, key){ area.removeItem(key); },
41 | key: function(area, i){ return area.key(i); },
42 | length: function(area){ return area.length; },
43 | clear: function(area){ area.clear(); },
44 |
45 | // core functions
46 | Store: function(id, area, namespace) {
47 | var store = _.inherit(_.storeAPI, function(key, data, overwrite) {
48 | if (arguments.length === 0){ return store.getAll(); }
49 | if (typeof data === "function"){ return store.transact(key, data, overwrite); }// fn=data, alt=overwrite
50 | if (data !== undefined){ return store.set(key, data, overwrite); }
51 | if (typeof key === "string" || typeof key === "number"){ return store.get(key); }
52 | if (typeof key === "function"){ return store.each(key); }
53 | if (!key){ return store.clear(); }
54 | return store.setAll(key, data);// overwrite=data, data=key
55 | });
56 | store._id = id;
57 | try {
58 | var testKey = '__store2_test';
59 | area.setItem(testKey, 'ok');
60 | store._area = area;
61 | area.removeItem(testKey);
62 | } catch (e) {
63 | store._area = _.storage('fake');
64 | }
65 | store._ns = namespace || '';
66 | if (!_.areas[id]) {
67 | _.areas[id] = store._area;
68 | }
69 | if (!_.apis[store._ns+store._id]) {
70 | _.apis[store._ns+store._id] = store;
71 | }
72 | return store;
73 | },
74 | storeAPI: {
75 | // admin functions
76 | area: function(id, area) {
77 | var store = this[id];
78 | if (!store || !store.area) {
79 | store = _.Store(id, area, this._ns);//new area-specific api in this namespace
80 | if (!this[id]){ this[id] = store; }
81 | }
82 | return store;
83 | },
84 | namespace: function(namespace, singleArea, delim) {
85 | delim = delim || this._delim || _.nsdelim;
86 | if (!namespace){
87 | return this._ns ? this._ns.substring(0,this._ns.length-delim.length) : '';
88 | }
89 | var ns = namespace, store = this[ns];
90 | if (!store || !store.namespace) {
91 | store = _.Store(this._id, this._area, this._ns+ns+delim);//new namespaced api
92 | store._delim = delim;
93 | if (!this[ns]){ this[ns] = store; }
94 | if (!singleArea) {
95 | for (var name in _.areas) {
96 | store.area(name, _.areas[name]);
97 | }
98 | }
99 | }
100 | return store;
101 | },
102 | isFake: function(force) {
103 | if (force) {
104 | this._real = this._area;
105 | this._area = _.storage('fake');
106 | } else if (force === false) {
107 | this._area = this._real || this._area;
108 | }
109 | return this._area.name === 'fake';
110 | },
111 | toString: function() {
112 | return 'store'+(this._ns?'.'+this.namespace():'')+'['+this._id+']';
113 | },
114 |
115 | // storage functions
116 | has: function(key) {
117 | if (this._area.has) {
118 | return this._area.has(this._in(key));//extension hook
119 | }
120 | return !!(this._in(key) in this._area);
121 | },
122 | size: function(){ return this.keys().length; },
123 | each: function(fn, fill) {// fill is used by keys(fillList) and getAll(fillList))
124 | for (var i=0, m=_.length(this._area); i _.length(this._area)) { m--; i--; }// in case of removeItem
132 | }
133 | return fill || this;
134 | },
135 | keys: function(fillList) {
136 | return this.each(function(k, v, list){ list.push(k); }, fillList || []);
137 | },
138 | get: function(key, alt) {
139 | var s = _.get(this._area, this._in(key)),
140 | fn;
141 | if (typeof alt === "function") {
142 | fn = alt;
143 | alt = null;
144 | }
145 | return s !== null ? _.parse(s, fn) :
146 | alt != null ? alt : s;
147 | },
148 | getAll: function(fillObj) {
149 | return this.each(function(k, v, all){ all[k] = v; }, fillObj || {});
150 | },
151 | transact: function(key, fn, alt) {
152 | var val = this.get(key, alt),
153 | ret = fn(val);
154 | this.set(key, ret === undefined ? val : ret);
155 | return this;
156 | },
157 | set: function(key, data, overwrite) {
158 | var d = this.get(key),
159 | replacer;
160 | if (d != null && overwrite === false) {
161 | return data;
162 | }
163 | if (typeof overwrite === "function") {
164 | replacer = overwrite;
165 | overwrite = undefined;
166 | }
167 | return _.set(this._area, this._in(key), _.stringify(data, replacer), overwrite) || d;
168 | },
169 | setAll: function(data, overwrite) {
170 | var changed, val;
171 | for (var key in data) {
172 | val = data[key];
173 | if (this.set(key, val, overwrite) !== val) {
174 | changed = true;
175 | }
176 | }
177 | return changed;
178 | },
179 | add: function(key, data, replacer) {
180 | var d = this.get(key);
181 | if (d instanceof Array) {
182 | data = d.concat(data);
183 | } else if (d !== null) {
184 | var type = typeof d;
185 | if (type === typeof data && type === 'object') {
186 | for (var k in data) {
187 | d[k] = data[k];
188 | }
189 | data = d;
190 | } else {
191 | data = d + data;
192 | }
193 | }
194 | _.set(this._area, this._in(key), _.stringify(data, replacer));
195 | return data;
196 | },
197 | remove: function(key, alt) {
198 | var d = this.get(key, alt);
199 | _.remove(this._area, this._in(key));
200 | return d;
201 | },
202 | clear: function() {
203 | if (!this._ns) {
204 | _.clear(this._area);
205 | } else {
206 | this.each(function(k){ _.remove(this._area, this._in(k)); }, 1);
207 | }
208 | return this;
209 | },
210 | clearAll: function() {
211 | var area = this._area;
212 | for (var id in _.areas) {
213 | if (_.areas.hasOwnProperty(id)) {
214 | this._area = _.areas[id];
215 | this.clear();
216 | }
217 | }
218 | this._area = area;
219 | return this;
220 | },
221 |
222 | // internal use functions
223 | _in: function(k) {
224 | if (typeof k !== "string"){ k = _.stringify(k); }
225 | return this._ns ? this._ns + k : k;
226 | },
227 | _out: function(k) {
228 | return this._ns ?
229 | k && k.indexOf(this._ns) === 0 ?
230 | k.substring(this._ns.length) :
231 | undefined : // so each() knows to skip it
232 | k;
233 | }
234 | },// end _.storeAPI
235 | storage: function(name) {
236 | return _.inherit(_.storageAPI, { items: {}, name: name });
237 | },
238 | storageAPI: {
239 | length: 0,
240 | has: function(k){ return this.items.hasOwnProperty(k); },
241 | key: function(i) {
242 | var c = 0;
243 | for (var k in this.items){
244 | if (this.has(k) && i === c++) {
245 | return k;
246 | }
247 | }
248 | },
249 | setItem: function(k, v) {
250 | if (!this.has(k)) {
251 | this.length++;
252 | }
253 | this.items[k] = v;
254 | },
255 | removeItem: function(k) {
256 | if (this.has(k)) {
257 | delete this.items[k];
258 | this.length--;
259 | }
260 | },
261 | getItem: function(k){ return this.has(k) ? this.items[k] : null; },
262 | clear: function(){ for (var k in this.items){ this.removeItem(k); } }
263 | }// end _.storageAPI
264 | };
265 |
266 | var store =
267 | // safely set this up (throws error in IE10/32bit mode for local files)
268 | _.Store("local", (function(){try{ return localStorage; }catch(e){}})());
269 | store.local = store;// for completeness
270 | store._ = _;// for extenders and debuggers...
271 | // safely setup store.session (throws exception in FF for file:/// urls)
272 | store.area("session", (function(){try{ return sessionStorage; }catch(e){}})());
273 | store.area("page", _.storage("page"));
274 |
275 | if (typeof define === 'function' && define.amd !== undefined) {
276 | define('store2', [], function () {
277 | return store;
278 | });
279 | } else if (typeof module !== 'undefined' && module.exports) {
280 | module.exports = store;
281 | } else {
282 | // expose the primary store fn to the global object and save conflicts
283 | if (window.store){ _.conflict = window.store; }
284 | window.store = store;
285 | }
286 |
287 | })(this, this && this.define);
288 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | A feature-filled and friendly way to take advantage of localStorage and sessionStorage
2 | (JSON, namespacing, extensions, etc).
3 |
4 | Download: [store2.min.js][prod] or [store2.js][dev]
5 | [NPM][npm]: `npm install store2`
6 | [NuGet][]: `Install-Package store2`
7 |
8 | [NuGet]: http://nuget.org/packages/store2/
9 | [prod]: https://raw.github.com/nbubna/store/master/dist/store2.min.js
10 | [dev]: https://raw.github.com/nbubna/store/master/dist/store2.js
11 | [npm]: https://npmjs.org/package/store2
12 |
13 | [](https://travis-ci.org/nbubna/store)
14 | [](https://badge.fury.io/js/store2)
15 | [](https://www.npmjs.com/package/store2)
16 |
17 | ## Documentation
18 | The main store function can handle ```set```, ```get```, ```transact```, ```setAll```, ```getAll```, ```each```, and ```clear```
19 | actions directly. Respectively, these are called like so:
20 |
21 | ```javascript
22 | store(key, data); // sets stringified data under key
23 | store(key); // gets and parses data stored under key
24 | store(key, fn[, alt]); // run transaction function on/with data stored under key
25 | store({key: data, key2: data2}); // sets all key/data pairs in the object
26 | store(); // gets all stored key/data pairs as an object
27 | store((key, data)=>{ }); // calls function for each key/data in storage, return false to exit
28 | store(false); // clears all items from storage
29 | ```
30 |
31 | Parameters in [brackets] are optional. There are also more explicit and versatile functions available:
32 |
33 | ```javascript
34 | store.set(key, data[, overwrite]); // === store(key, data);
35 | store.setAll(data[, overwrite]); // === store({key: data, key2: data});
36 | store.get(key[, alt]); // === store(key);
37 | store.getAll([fillObj]); // === store();
38 | store.transact(key, fn[, alt]); // === store(key, fn[, alt]);
39 | store.clear(); // === store(false);
40 | store.has(key); // returns true or false
41 | store.remove(key[, alt]); // removes key and its data, then returns the data or alt, if none
42 | store.each(fn[, fill]); // === store(fn); optional call arg will be 3rd fn arg (e.g. for gathering values)
43 | store.add(key, data[, replacer]); // concats, merges, or adds new value into existing one
44 | store.keys([fillList]); // returns array of keys
45 | store.size(); // number of keys, not length of data
46 | store.clearAll(); // clears *ALL* areas (but still namespace sensitive)
47 | ```
48 |
49 | Passing in ```false``` for the optional overwrite parameters will cause ```set``` actions to be skipped
50 | if the storage already has a value for that key. All ```set``` action methods return the previous value
51 | for that key, by default. If overwrite is ```false``` and there is a previous value, the unused new
52 | value will be returned.
53 |
54 | Functions passed to ```transact``` will receive the current value for that key as an argument or
55 | a passed alternate if there is none. When the passed function is completed, transact will save the returned value
56 | under the specified key. If the function returns ```undefined```, the original value will be saved.
57 | This makes it easy for transact functions to change internal properties in a persistent way:
58 |
59 | ```javascript
60 | store.transact(key, function(obj) {
61 | obj.changed = 'newValue';// this change will be persisted
62 | });
63 | ```
64 |
65 | Functions passed to ```each``` will receive the key as first argument and current value as the second; if a `fill` parameter is specified, it's value will be the third argument for every call (few should ever
66 | need a `fill` parameter). If the function returns ```false``` at any point during the iteration, the
67 | loop will exit early and not continue on to the next key/value pair.
68 |
69 | ```javascript
70 | store.each(function(key, value) {
71 | console.log(key, '->', value);
72 | if (key === 'stopLoop') {
73 | return false;// this will cause each to stop calling this function
74 | }
75 | });
76 | ```
77 |
78 | All retrieval functions which take an optional ```alt``` parameter can also use that parameter to specify a "reviver" function. These receive each key and value (yes, nested ones too) as arguments and allow you to provide an alternate means of parsing that string. This is particularly useful for rich objects like ```Date``` types. See [MDN's JSON.parse docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) for more information and examples. Alternately, you can set a global reviver to the ```store._.revive``` property to handle all ```get```, ```getAll```, ```remove```, and ```transact``` calls.
79 |
80 | Likewise, setter functions which take an optional ```overwrite``` parameter can also use that parameter to accept a "replacer" function that receives each key and value (yes, nested ones too) as arguments and allow you to provide an alternate means of stringifying the values. This is particularly useful for rich objects like ```Map``` or ```Set```. See [MDN's JSON.stringify docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) for more information and examples. Alternately, you can set a global replacer to the ```store._.replace``` property to handle all ```set```, ```setAll```, ```add```, and ```transact``` calls.
81 |
82 | For ```getAll``` and ```keys```, there is the option to pass in the object or list, respectively,
83 | that you want the results to be added to. This is instead of an empty list.
84 | There are only a few special cases where you are likely to need or want this,
85 | in general, most users should ignore these optional parameters.
86 | These both use the second, optional argument ```each``` function,
87 | which is also a niche feature. The ```value``` argument is passed as
88 | the second arg to the callback function (in place of the data associated with the current key)
89 | and is returned at the end. Again, most users should not need this feature.
90 | All of these use the browser's localStorage (aka "local"). Using sessionStorage merely requires
91 | calling the same functions on ```store.session```:
92 |
93 | ```javascript
94 | store.session("addMeTo", "sessionStorage");
95 | store.local({lots: 'of', data: 'altogether'});// store.local === store :)
96 | ```
97 | There is also a store API automatically available for keeping non-persistent information,
98 | meant only to last until page reload.
99 | ```javascript
100 | store.page("until","reload");
101 | ```
102 |
103 | All the specific ```get```, ```set```, etc. functions are available on ```store.session```, ```store.local```, and ```store.page```, as well as any other storage facility registered via ```store.area(name, customStorageObject)``` by an extension, where customStorageObject must implement the [Storage interface][storage]. This is how [store.old.js][old] extends store.js to support older versions of IE and Firefox.
104 |
105 | [storage]: http://dev.w3.org/html5/webstorage/#the-storage-interface
106 |
107 | If you want to put stored data from different pages or areas f your site into separate namespaces,
108 | the ```store.namespace(ns)``` function is your friend:
109 |
110 | ```javascript
111 | var cart = store.namespace('cart');
112 | cart('total', 23.25);// stores in localStorage as 'cart.total'
113 | console.log(store('cart.total') == cart('total'));// logs true
114 | console.log(store.cart.getAll());// logs {total: 23.25}
115 | cart.session('group', 'toys');// stores in sessionStorage as 'cart.group'
116 | ```
117 |
118 | The namespace provides the same exact API as ```store``` but silently adds/removes the namespace prefix as needed.
119 | It also makes the namespaced API accessible directly via ```store[namespace]``` (e.g. ```store.cart```) as long as it
120 | does not conflict with an existing part of the store API.
121 |
122 | The 'namespace' function is one of three "extra" functions that are also part of the "store API":
123 |
124 | ```javascript
125 | store.namespace(prefix);// returns a new store API that prefixes all key-based functions
126 | store.isFake([force]);// test or set whether localStorage/sessionStorage or an in-memory, 'fake' storage is used
127 | ```
128 |
129 | ```store.namespace``` can also take extra params to only create the namespace in the called-on storage area, and
130 | to pass in an alternate namespace delimiter for advanced use-cases (e.g. ```store.page.namespace("subpage", true, ":")```).
131 |
132 | If localStorage or sessionStorage are unavailable, they will be faked to prevent errors,
133 | but data stored will NOT persist beyond the life of the current document/page. Use the
134 | [store.old.js][old] extension to add persistent backing for the store API in ancient browsers.
135 |
136 | ```isFake(true|false)``` is particularly useful to force use of a temporary, fake storage in testing situations,
137 | to prevent cluttering actual storage.
138 |
139 | ## Extensions
140 | These mostly could use further documentation and abuse...er...testing.
141 | Contributions are welcome!
142 | In particular, any ES6 user interested in making these [importable in ES6][es6importissue] would be appreciated.
143 |
144 | [es6importissue]: https://github.com/nbubna/store/issues/31
145 |
146 | #### Beta - Stable and definitely useful
147 | * [store.old.js][old] - Add working localStorage and sessionStorage polyfills for ancient browsers
148 | * [store.overflow.js][overflow] - Fall back to fake storage on quota errors
149 | * [store.cache.js][cache] - To make data expire, pass a number of seconds as the overwrite (third) param on ```set()``` calls
150 | * [store.on.js][on] - Superior storage event handling (per key, per namespace, etc in IE9+)
151 | * [store.array.js][array] - Easy, powerful array functions for any and all data (e.g. ```store.push(key, v1, v2)```).
152 | * [store.dom.js][dom] - Declarative, persistent DOM element content via store.
153 | * [store.cookie.js][cookie] - Support for a cookie as a storage area: ```store.cookie('num',1)``` to make sharing with backend easier.
154 |
155 | #### Alpha - Either incomplete or unstable or both
156 | * [store.quota.js][quota] - Register callbacks to handle (and even cancel) quota errors
157 | * [store.measure.js][measure] - Experimental extension for measuring space used and available (needs work)
158 | * [store.onlyreal.js][onlyreal] - When only fake storage is available, silently fail instead of faking it.
159 | * [store.dot.js][dot] - Creates accessors for keys (e.g. ```store.foo == store.get('foo')```)
160 | * [store.deep.js][deep] - Allow retrieval of properties from within stored objects (e.g. ```store.get('key.property')```)
161 | * [store.async.js][async] - Adds ```store.async``` duplicate to each store and namespace that performs functions asynchronously and returns a Promise that resolves when complete.
162 | * [store.cookies.js][cookies] - Support managing all cookies as a storage area with the store API (e.g. ```store.cookies.get('user')```)
163 |
164 | [old]: https://raw.github.com/nbubna/store/master/src/store.old.js
165 | [overflow]: https://raw.github.com/nbubna/store/master/src/store.overflow.js
166 | [cache]: https://raw.github.com/nbubna/store/master/src/store.cache.js
167 | [on]: https://raw.github.com/nbubna/store/master/src/store.on.js
168 | [quota]: https://raw.github.com/nbubna/store/master/src/store.quota.js
169 | [measure]: https://raw.github.com/nbubna/store/master/src/store.measure.js
170 | [onlyreal]: https://raw.github.com/nbubna/store/master/src/store.onlyreal.js
171 | [array]: https://raw.github.com/nbubna/store/master/src/store.array.js
172 | [dot]: https://raw.github.com/nbubna/store/master/src/store.dot.js
173 | [deep]: https://raw.github.com/nbubna/store/master/src/store.deep.js
174 | [dom]: https://raw.github.com/nbubna/store/master/src/store.dom.js
175 | [async]: https://raw.github.com/nbubna/store/master/src/store.async.js
176 | [cookie]: https://raw.github.com/nbubna/store/master/src/store.cookie.js
177 | [cookies]: https://raw.github.com/nbubna/store/master/src/store.cookies.js
178 |
179 | #### Write Your Own Extension
180 | To write your own extension, you can use or carefully override internal functions exposed as ```store._```.
181 | In particular, the ```store._.fn(fnName, fn)``` method is available to automatically add your new function
182 | to every instance of the ```store``` interface (e.g. ```store```, ```store.session```
183 | and all existing and future namespaces). Take care using this, as it will override existing methods.
184 | Here is a simple example:
185 |
186 | ```javascript
187 | (function(_) {
188 | _.fn('falsy', function(key) {
189 | return !this.get(key);
190 | });
191 | _.fn('truthy', function(key) {
192 | return !this.falsy(key);
193 | });
194 | })(store._);
195 | ```
196 | This extension would be used like so:
197 | ```javascript
198 | store('foo', 1);
199 | store.falsy('foo'); // returns false
200 |
201 | store.session('bar', 'one');
202 | store.session.truthy('bar'); // return true;
203 |
204 | const widgetStore = store.namespace('widget');
205 | widgetStore.falsy('state'); // returns true
206 | ```
207 |
208 | ## Release History
209 | * 2010-02-10 v0.1 (extraction from esha.js)
210 | * 2010-05-25 v1.0 (internal release)
211 | * 2013-04-09 [v2.0.3][] (public) - First GitHub release
212 | * 2013-04-20 [v2.1.0][] (public) - Drops flawed/confusing/unused key(i) method, fixes extension problems.
213 | * 2013-04-30 [v2.1.1][] (public) - Browserify (and friends) support (module.exports = store)
214 | * 2013-05-30 [v2.1.2][] (public) - Component support (old component.json is now bower.json)
215 | * 2014-03-10 [v2.1.6][] (public) - AMD support and Component improvements
216 | * 2015-02-02 [v2.2.0][] (public) - Change store.cache.js to use seconds, not minutes.
217 | * 2015-05-05 [v2.2.1][] (public) - node.js compatibility
218 | * 2015-05-08 [v2.2.2][] (public) - Always expose global to allow extensions to always work.
219 | * 2015-05-22 [v2.3.0][] (public) - Use fake storage for Safari private mode (instead of letting quota exceptions go)
220 | * 2015-10-27 [v2.3.2][] (public) - Add source map
221 | * 2017-01-04 [v2.4.0][] (public) - Add store.transact(key, fn[, alt])
222 | * 2017-01-09 [v2.5.0][] (public) - Update for issue #34; new extensions (array, dot, and deep); only expose global in non-AMD/CommonJS environments (PR #35)
223 | * 2017-08-09 [v2.5.2][] (public) - Fix `clear()` in fake storage (thx to Martin Kluska)
224 | * 2018-01-18 [v2.5.11][] (public) - Add ```index.d.ts``` in root to provide TypeScript support
225 | * 2018-01-23 [v2.6.0][] (public) - Support ```each(fn,value)```, ```getAll(fillObj)```, and ```keys(fillList)``` to support some advanced/corner cases
226 | * 2018-11-15 [v2.7.1][] (public) - Add ```add(key, data)``` for common case of saving a combination of existing and new data. Fix issue #60.
227 | * 2019-07-23 [v2.8.0][] (public) - Add ```store(fn)``` shortcut for ```store.each```, copy properties when inheriting, and make ```store.each(fn, fill)``` always send fill as 3rd arg instead of replacing values.
228 | * 2019-08-21 [v2.9.0][] (public) - Add store.remove(key, alt) to match behavior of store.get(key, alt) (Issue #68)
229 | * 2019-09-27 [v2.10.0][] (public) - Add ```store.page``` to provide page scope storage to complement local and session scope storage. (Issue #69)
230 | * 2020-03-23 [v2.11.0][] (public) - Add ```store.get(key, reviveFn)``` and ```store._.revive`` to support parsing for rich types (e.g. Date)
231 | * 2020-04-14 [v2.11.1][] (public) - Fix falsey alt value support in ```store.get(key, alt)```
232 | * 2020-05-11 [v2.11.2][] (public) - Fix missing TS declaration of new page scope storage.
233 | * 2020-08-12 [v2.12.0][] (public) - PRs for better Storage typing, better testKey, and dev dependency updates.
234 | * 2021-12-16 [v2.13.1][] (public) - Add ```store.set(key, value, replacerFn)```, ```store._replace```, and ```isFake([force])``` to support stringifying rich types and easier testing. And cookie-based extensions for using store backed by a single 'store' cookie or store API for all cookies.
235 | * 2022-03-14 [v2.13.2][] (public) - Restore missing TS declaration of store.area(id[, area])
236 | * 2022-05-11 [v2.14.0][] (public) - Allow namespace delimiter to be changed via store._.nsdelim
237 | * 2022-07-14 [v2.14.1][] (public) - Fix change to ```set``` that broke store.cache.js, and allow namespace delimiter to be passed to ```namespace(name, thisAreaOnly, delim)``` for a single namespace, to avoid conflicts.
238 | * 2022-07-18 [v2.14.2][] (public) - Fix typo in ```index.d.ts``` typings.
239 | * 2024-02-14 [v2.14.3][] (public) - Cut license options to just MIT, also removed Bower and Component support since those are long dead.
240 | * 2024-12-26 [v2.14.4][] (public) - Remove use of eval from store.deep.js
241 |
242 | [v2.0.3]: https://github.com/nbubna/store/tree/2.0.3
243 | [v2.1.0]: https://github.com/nbubna/store/tree/2.1.0
244 | [v2.1.1]: https://github.com/nbubna/store/tree/2.1.1
245 | [v2.1.2]: https://github.com/nbubna/store/tree/2.1.2
246 | [v2.1.6]: https://github.com/nbubna/store/tree/2.1.6
247 | [v2.2.0]: https://github.com/nbubna/store/tree/2.2.0
248 | [v2.2.1]: https://github.com/nbubna/store/tree/2.2.1
249 | [v2.2.2]: https://github.com/nbubna/store/tree/2.2.2
250 | [v2.3.0]: https://github.com/nbubna/store/tree/2.3.0
251 | [v2.3.2]: https://github.com/nbubna/store/tree/2.3.2
252 | [v2.4.0]: https://github.com/nbubna/store/tree/2.4.0
253 | [v2.5.0]: https://github.com/nbubna/store/tree/2.5.0
254 | [v2.5.2]: https://github.com/nbubna/store/tree/2.5.2
255 | [v2.5.11]: https://github.com/nbubna/store/tree/2.5.11
256 | [v2.6.0]: https://github.com/nbubna/store/tree/2.6.0
257 | [v2.7.1]: https://github.com/nbubna/store/tree/2.7.1
258 | [v2.8.0]: https://github.com/nbubna/store/tree/2.8.0
259 | [v2.9.0]: https://github.com/nbubna/store/tree/2.9.0
260 | [v2.10.0]: https://github.com/nbubna/store/tree/2.10.0
261 | [v2.11.1]: https://github.com/nbubna/store/tree/2.11.1
262 | [v2.11.2]: https://github.com/nbubna/store/tree/2.11.2
263 | [v2.12.0]: https://github.com/nbubna/store/tree/2.12.0
264 | [v2.13.1]: https://github.com/nbubna/store/tree/2.13.1
265 | [v2.13.2]: https://github.com/nbubna/store/tree/2.13.2
266 | [v2.14.0]: https://github.com/nbubna/store/tree/2.14.0
267 | [v2.14.1]: https://github.com/nbubna/store/tree/2.14.1
268 | [v2.14.2]: https://github.com/nbubna/store/tree/2.14.2
269 | [v2.14.3]: https://github.com/nbubna/store/tree/2.14.3
270 | [v2.14.4]: https://github.com/nbubna/store/tree/2.14.4
271 |
--------------------------------------------------------------------------------
/test/store_test.js:
--------------------------------------------------------------------------------
1 | /*
2 | ======== A Handy Little QUnit Reference ========
3 | http://api.qunitjs.com/
4 |
5 | Test methods:
6 | module(name, {[setup][ ,teardown]})
7 | test(name, callback)
8 | expect(numberOfAssertions)
9 | stop(increment)
10 | start(decrement)
11 | Test assertions:
12 | ok(value, [message])
13 | equal(actual, expected, [message])
14 | notEqual(actual, expected, [message])
15 | deepEqual(actual, expected, [message])
16 | notDeepEqual(actual, expected, [message])
17 | strictEqual(actual, expected, [message])
18 | notStrictEqual(actual, expected, [message])
19 | throws(block, [expected], [message])
20 | */
21 | (function(store) {
22 |
23 | var API = ['get', 'set', 'transact', 'has', 'remove', 'each', 'namespace', 'area',
24 | 'getAll', 'setAll', 'keys', 'isFake', 'clear', 'clearAll', 'size'];
25 |
26 | // expose some internals for REPL convenience
27 | window._ = store._;
28 | window.API = API;
29 |
30 | function has(key, s, sn) {
31 | if (!s) {
32 | s = store;
33 | }
34 | ok(key in s, "test store."+(sn?sn+'.':'')+key+" presence");
35 | }
36 | function is(key, expect, s, sn) {
37 | equal((s||store)[key], expect, "store."+(sn?sn+'.':'')+key);
38 | }
39 | /*function returns(fn, expect, s) {
40 | equal((s||store)[fn](), expect, fn+"()");
41 | }*/
42 | function noval(val, name) {
43 | ok(val === null || val === undefined, name);
44 | }
45 | /*function val(val, name) {
46 | ok(val !== null && val !== undefined, name);
47 | }*/
48 | function get(key, expect, s) {
49 | (expect && typeof expect === "object" ? deepEqual : equal)
50 | ((s || store).get(key), expect, "get '"+key+"'");
51 | }
52 | function save(key, val, s) {
53 | noval((s || store)(key, val), "save value for '"+key+"'");
54 | get(key, val, s);
55 | }
56 | function add(key, val, expect, s) {
57 | (s || store).add(key, val);
58 | get(key, expect, s);
59 | }
60 | function update(key, val, s) {
61 | if (typeof key === 'string' || val !== undefined) {
62 | ok((s || store)(key, val) != null, "update value for '"+key+"'");
63 | get(key, val, s);
64 | } else {
65 | equal((s || store)(key), true, 'update all values in '+key);
66 | for (var k in key) {
67 | get(k, key[k], s);
68 | }
69 | }
70 | }
71 | function transact(key, fn, alt, s) {
72 | var ret = (s || store)(key, fn, alt);
73 | strictEqual(ret, s || store, "transact should return this");
74 | }
75 | function getAll(expect, s, fillObj) {
76 | if (fillObj) {
77 | deepEqual((s || store).getAll(fillObj), expect, "getAll(fillObj)");
78 | } else {
79 | deepEqual((s || store)(), expect, "getAll");
80 | }
81 | }
82 | function keys(expect, s, fillList) {
83 | var _keys = (s || store).keys(fillList);
84 | for (var i=0,m=expect.length; i= 0, 'has '+expect[i]);
87 | }
88 | }
89 | if (fillList) {
90 | strictEqual(fillList, _keys, "should get fillList back");
91 | }
92 | equal(_keys.length, expect.length, 'deepEqual length');
93 | }
94 | function inArray(array, element) {
95 | for (var i=0,m=array.length; i -1);
148 | window.onload = function() {
149 | if (!is_events) {
150 |
151 | // ensure we start blank
152 | store.clearAll();
153 | test("interface", function() {
154 | ok(store, "store is present");
155 | for (var i=0; i -1);
517 | if (is_firefox) {
518 | test("tricky for browsers", function() {
519 | save('getItem', true);
520 | save('setItem', 12.2);
521 | save('clear', 'boo');
522 | save('removeItem', 'hi');
523 | save('key', {});
524 | save('length', 1);
525 | update('length', 2);
526 | clear();
527 | });
528 | }
529 | }
530 |
531 | if (store._.cache) {
532 | test("store.cache", function() {
533 | clear();
534 | store.set("time", "in", 100);
535 | ok(store.has("time"));
536 | equal(store("time"), "in");
537 | var val = localStorage.getItem("time");
538 | notEqual(val, null);
539 | ok(val.indexOf("exp@") === 0, "has prefix");
540 | ok(val.indexOf(";") > 4, "has suffix");
541 | if (String.prototype.startsWith) {// grunt qunity is too fast to test this reliably, it seems
542 | store.set("time", "out", 0.001);
543 | equal(store.get("time"), null);
544 | }
545 | });
546 | }
547 |
548 | // clean slate before event tests
549 | store.clearAll();
550 |
551 | var is_http = (window.location.href.indexOf('file') !== 0),
552 | is_modern = !!window.addEventListener;
553 | if (is_http && is_modern) {
554 | var events = store.namespace('events');
555 | if (is_events) {
556 | events('foo', {a:1,b:2});
557 | events('foo', true);
558 | events('bar', false);
559 | events(0);
560 | } else {
561 | var foos = 1;
562 | events.on('foo', function(e) {
563 | test("event "+e.key+foos, function() {
564 | equal('events', e.namespace, "e.namespace should be 'events'");
565 | equal('foo', e.key, "e.key should be 'foo'");
566 | ok(e.storageArea, "should have a storageArea");
567 | if (foos === 1) {
568 | ok(!e.oldValue, "shouldn't be any oldValue");
569 | } else if (foos === 2) {
570 | equal(2, e.oldValue.b, "oldValue should be object, not string");
571 | equal(true, e.newValue, "newValue should be true");
572 | } else if (foos === 3) {
573 | ok(!e.newValue, "shouldn't be any newValue");
574 | }
575 | foos++;
576 | });
577 | });
578 | var el = document.createElement('iframe');
579 | el.src = window.location.href+'?events=true';
580 | el.style.visibility = 'hidden';
581 | document.getElementsByTagName('body')[0].appendChild(el);
582 | }
583 | }
584 |
585 | };// end window.onload
586 |
587 | }(window.store));
588 |
--------------------------------------------------------------------------------
/libs/qunit/qunit.js:
--------------------------------------------------------------------------------
1 | /**
2 | * QUnit v1.11.0 - A JavaScript Unit Testing Framework
3 | *
4 | * http://qunitjs.com
5 | *
6 | * Copyright 2012 jQuery Foundation and other contributors
7 | * Released under the MIT license.
8 | * http://jquery.org/license
9 | */
10 |
11 | (function( window ) {
12 |
13 | var QUnit,
14 | assert,
15 | config,
16 | onErrorFnPrev,
17 | testId = 0,
18 | fileName = (sourceFromStacktrace( 0 ) || "" ).replace(/(:\d+)+\)?/, "").replace(/.+\//, ""),
19 | toString = Object.prototype.toString,
20 | hasOwn = Object.prototype.hasOwnProperty,
21 | // Keep a local reference to Date (GH-283)
22 | Date = window.Date,
23 | defined = {
24 | setTimeout: typeof window.setTimeout !== "undefined",
25 | sessionStorage: (function() {
26 | var x = "qunit-test-string";
27 | try {
28 | sessionStorage.setItem( x, x );
29 | sessionStorage.removeItem( x );
30 | return true;
31 | } catch( e ) {
32 | return false;
33 | }
34 | }())
35 | },
36 | /**
37 | * Provides a normalized error string, correcting an issue
38 | * with IE 7 (and prior) where Error.prototype.toString is
39 | * not properly implemented
40 | *
41 | * Based on http://es5.github.com/#x15.11.4.4
42 | *
43 | * @param {String|Error} error
44 | * @return {String} error message
45 | */
46 | errorString = function( error ) {
47 | var name, message,
48 | errorString = error.toString();
49 | if ( errorString.substring( 0, 7 ) === "[object" ) {
50 | name = error.name ? error.name.toString() : "Error";
51 | message = error.message ? error.message.toString() : "";
52 | if ( name && message ) {
53 | return name + ": " + message;
54 | } else if ( name ) {
55 | return name;
56 | } else if ( message ) {
57 | return message;
58 | } else {
59 | return "Error";
60 | }
61 | } else {
62 | return errorString;
63 | }
64 | },
65 | /**
66 | * Makes a clone of an object using only Array or Object as base,
67 | * and copies over the own enumerable properties.
68 | *
69 | * @param {Object} obj
70 | * @return {Object} New object with only the own properties (recursively).
71 | */
72 | objectValues = function( obj ) {
73 | // Grunt 0.3.x uses an older version of jshint that still has jshint/jshint#392.
74 | /*jshint newcap: false */
75 | var key, val,
76 | vals = QUnit.is( "array", obj ) ? [] : {};
77 | for ( key in obj ) {
78 | if ( hasOwn.call( obj, key ) ) {
79 | val = obj[key];
80 | vals[key] = val === Object(val) ? objectValues(val) : val;
81 | }
82 | }
83 | return vals;
84 | };
85 |
86 | function Test( settings ) {
87 | extend( this, settings );
88 | this.assertions = [];
89 | this.testNumber = ++Test.count;
90 | }
91 |
92 | Test.count = 0;
93 |
94 | Test.prototype = {
95 | init: function() {
96 | var a, b, li,
97 | tests = id( "qunit-tests" );
98 |
99 | if ( tests ) {
100 | b = document.createElement( "strong" );
101 | b.innerHTML = this.nameHtml;
102 |
103 | // `a` initialized at top of scope
104 | a = document.createElement( "a" );
105 | a.innerHTML = "Rerun";
106 | a.href = QUnit.url({ testNumber: this.testNumber });
107 |
108 | li = document.createElement( "li" );
109 | li.appendChild( b );
110 | li.appendChild( a );
111 | li.className = "running";
112 | li.id = this.id = "qunit-test-output" + testId++;
113 |
114 | tests.appendChild( li );
115 | }
116 | },
117 | setup: function() {
118 | if ( this.module !== config.previousModule ) {
119 | if ( config.previousModule ) {
120 | runLoggingCallbacks( "moduleDone", QUnit, {
121 | name: config.previousModule,
122 | failed: config.moduleStats.bad,
123 | passed: config.moduleStats.all - config.moduleStats.bad,
124 | total: config.moduleStats.all
125 | });
126 | }
127 | config.previousModule = this.module;
128 | config.moduleStats = { all: 0, bad: 0 };
129 | runLoggingCallbacks( "moduleStart", QUnit, {
130 | name: this.module
131 | });
132 | } else if ( config.autorun ) {
133 | runLoggingCallbacks( "moduleStart", QUnit, {
134 | name: this.module
135 | });
136 | }
137 |
138 | config.current = this;
139 |
140 | this.testEnvironment = extend({
141 | setup: function() {},
142 | teardown: function() {}
143 | }, this.moduleTestEnvironment );
144 |
145 | this.started = +new Date();
146 | runLoggingCallbacks( "testStart", QUnit, {
147 | name: this.testName,
148 | module: this.module
149 | });
150 |
151 | // allow utility functions to access the current test environment
152 | // TODO why??
153 | QUnit.current_testEnvironment = this.testEnvironment;
154 |
155 | if ( !config.pollution ) {
156 | saveGlobal();
157 | }
158 | if ( config.notrycatch ) {
159 | this.testEnvironment.setup.call( this.testEnvironment );
160 | return;
161 | }
162 | try {
163 | this.testEnvironment.setup.call( this.testEnvironment );
164 | } catch( e ) {
165 | QUnit.pushFailure( "Setup failed on " + this.testName + ": " + ( e.message || e ), extractStacktrace( e, 1 ) );
166 | }
167 | },
168 | run: function() {
169 | config.current = this;
170 |
171 | var running = id( "qunit-testresult" );
172 |
173 | if ( running ) {
174 | running.innerHTML = "Running:
" + this.nameHtml;
175 | }
176 |
177 | if ( this.async ) {
178 | QUnit.stop();
179 | }
180 |
181 | this.callbackStarted = +new Date();
182 |
183 | if ( config.notrycatch ) {
184 | this.callback.call( this.testEnvironment, QUnit.assert );
185 | this.callbackRuntime = +new Date() - this.callbackStarted;
186 | return;
187 | }
188 |
189 | try {
190 | this.callback.call( this.testEnvironment, QUnit.assert );
191 | this.callbackRuntime = +new Date() - this.callbackStarted;
192 | } catch( e ) {
193 | this.callbackRuntime = +new Date() - this.callbackStarted;
194 |
195 | QUnit.pushFailure( "Died on test #" + (this.assertions.length + 1) + " " + this.stack + ": " + ( e.message || e ), extractStacktrace( e, 0 ) );
196 | // else next test will carry the responsibility
197 | saveGlobal();
198 |
199 | // Restart the tests if they're blocking
200 | if ( config.blocking ) {
201 | QUnit.start();
202 | }
203 | }
204 | },
205 | teardown: function() {
206 | config.current = this;
207 | if ( config.notrycatch ) {
208 | if ( typeof this.callbackRuntime === "undefined" ) {
209 | this.callbackRuntime = +new Date() - this.callbackStarted;
210 | }
211 | this.testEnvironment.teardown.call( this.testEnvironment );
212 | return;
213 | } else {
214 | try {
215 | this.testEnvironment.teardown.call( this.testEnvironment );
216 | } catch( e ) {
217 | QUnit.pushFailure( "Teardown failed on " + this.testName + ": " + ( e.message || e ), extractStacktrace( e, 1 ) );
218 | }
219 | }
220 | checkPollution();
221 | },
222 | finish: function() {
223 | config.current = this;
224 | if ( config.requireExpects && this.expected === null ) {
225 | QUnit.pushFailure( "Expected number of assertions to be defined, but expect() was not called.", this.stack );
226 | } else if ( this.expected !== null && this.expected !== this.assertions.length ) {
227 | QUnit.pushFailure( "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run", this.stack );
228 | } else if ( this.expected === null && !this.assertions.length ) {
229 | QUnit.pushFailure( "Expected at least one assertion, but none were run - call expect(0) to accept zero assertions.", this.stack );
230 | }
231 |
232 | var i, assertion, a, b, time, li, ol,
233 | test = this,
234 | good = 0,
235 | bad = 0,
236 | tests = id( "qunit-tests" );
237 |
238 | this.runtime = +new Date() - this.started;
239 | config.stats.all += this.assertions.length;
240 | config.moduleStats.all += this.assertions.length;
241 |
242 | if ( tests ) {
243 | ol = document.createElement( "ol" );
244 | ol.className = "qunit-assert-list";
245 |
246 | for ( i = 0; i < this.assertions.length; i++ ) {
247 | assertion = this.assertions[i];
248 |
249 | li = document.createElement( "li" );
250 | li.className = assertion.result ? "pass" : "fail";
251 | li.innerHTML = assertion.message || ( assertion.result ? "okay" : "failed" );
252 | ol.appendChild( li );
253 |
254 | if ( assertion.result ) {
255 | good++;
256 | } else {
257 | bad++;
258 | config.stats.bad++;
259 | config.moduleStats.bad++;
260 | }
261 | }
262 |
263 | // store result when possible
264 | if ( QUnit.config.reorder && defined.sessionStorage ) {
265 | if ( bad ) {
266 | sessionStorage.setItem( "qunit-test-" + this.module + "-" + this.testName, bad );
267 | } else {
268 | sessionStorage.removeItem( "qunit-test-" + this.module + "-" + this.testName );
269 | }
270 | }
271 |
272 | if ( bad === 0 ) {
273 | addClass( ol, "qunit-collapsed" );
274 | }
275 |
276 | // `b` initialized at top of scope
277 | b = document.createElement( "strong" );
278 | b.innerHTML = this.nameHtml + " (" + bad + ", " + good + ", " + this.assertions.length + ")";
279 |
280 | addEvent(b, "click", function() {
281 | var next = b.parentNode.lastChild,
282 | collapsed = hasClass( next, "qunit-collapsed" );
283 | ( collapsed ? removeClass : addClass )( next, "qunit-collapsed" );
284 | });
285 |
286 | addEvent(b, "dblclick", function( e ) {
287 | var target = e && e.target ? e.target : window.event.srcElement;
288 | if ( target.nodeName.toLowerCase() === "span" || target.nodeName.toLowerCase() === "b" ) {
289 | target = target.parentNode;
290 | }
291 | if ( window.location && target.nodeName.toLowerCase() === "strong" ) {
292 | window.location = QUnit.url({ testNumber: test.testNumber });
293 | }
294 | });
295 |
296 | // `time` initialized at top of scope
297 | time = document.createElement( "span" );
298 | time.className = "runtime";
299 | time.innerHTML = this.runtime + " ms";
300 |
301 | // `li` initialized at top of scope
302 | li = id( this.id );
303 | li.className = bad ? "fail" : "pass";
304 | li.removeChild( li.firstChild );
305 | a = li.firstChild;
306 | li.appendChild( b );
307 | li.appendChild( a );
308 | li.appendChild( time );
309 | li.appendChild( ol );
310 |
311 | } else {
312 | for ( i = 0; i < this.assertions.length; i++ ) {
313 | if ( !this.assertions[i].result ) {
314 | bad++;
315 | config.stats.bad++;
316 | config.moduleStats.bad++;
317 | }
318 | }
319 | }
320 |
321 | runLoggingCallbacks( "testDone", QUnit, {
322 | name: this.testName,
323 | module: this.module,
324 | failed: bad,
325 | passed: this.assertions.length - bad,
326 | total: this.assertions.length,
327 | duration: this.runtime
328 | });
329 |
330 | QUnit.reset();
331 |
332 | config.current = undefined;
333 | },
334 |
335 | queue: function() {
336 | var bad,
337 | test = this;
338 |
339 | synchronize(function() {
340 | test.init();
341 | });
342 | function run() {
343 | // each of these can by async
344 | synchronize(function() {
345 | test.setup();
346 | });
347 | synchronize(function() {
348 | test.run();
349 | });
350 | synchronize(function() {
351 | test.teardown();
352 | });
353 | synchronize(function() {
354 | test.finish();
355 | });
356 | }
357 |
358 | // `bad` initialized at top of scope
359 | // defer when previous test run passed, if storage is available
360 | bad = QUnit.config.reorder && defined.sessionStorage &&
361 | +sessionStorage.getItem( "qunit-test-" + this.module + "-" + this.testName );
362 |
363 | if ( bad ) {
364 | run();
365 | } else {
366 | synchronize( run, true );
367 | }
368 | }
369 | };
370 |
371 | // Root QUnit object.
372 | // `QUnit` initialized at top of scope
373 | QUnit = {
374 |
375 | // call on start of module test to prepend name to all tests
376 | module: function( name, testEnvironment ) {
377 | config.currentModule = name;
378 | config.currentModuleTestEnvironment = testEnvironment;
379 | config.modules[name] = true;
380 | },
381 |
382 | asyncTest: function( testName, expected, callback ) {
383 | if ( arguments.length === 2 ) {
384 | callback = expected;
385 | expected = null;
386 | }
387 |
388 | QUnit.test( testName, expected, callback, true );
389 | },
390 |
391 | test: function( testName, expected, callback, async ) {
392 | var test,
393 | nameHtml = "" + escapeText( testName ) + "";
394 |
395 | if ( arguments.length === 2 ) {
396 | callback = expected;
397 | expected = null;
398 | }
399 |
400 | if ( config.currentModule ) {
401 | nameHtml = "" + escapeText( config.currentModule ) + ": " + nameHtml;
402 | }
403 |
404 | test = new Test({
405 | nameHtml: nameHtml,
406 | testName: testName,
407 | expected: expected,
408 | async: async,
409 | callback: callback,
410 | module: config.currentModule,
411 | moduleTestEnvironment: config.currentModuleTestEnvironment,
412 | stack: sourceFromStacktrace( 2 )
413 | });
414 |
415 | if ( !validTest( test ) ) {
416 | return;
417 | }
418 |
419 | test.queue();
420 | },
421 |
422 | // Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through.
423 | expect: function( asserts ) {
424 | if (arguments.length === 1) {
425 | config.current.expected = asserts;
426 | } else {
427 | return config.current.expected;
428 | }
429 | },
430 |
431 | start: function( count ) {
432 | // QUnit hasn't been initialized yet.
433 | // Note: RequireJS (et al) may delay onLoad
434 | if ( config.semaphore === undefined ) {
435 | QUnit.begin(function() {
436 | // This is triggered at the top of QUnit.load, push start() to the event loop, to allow QUnit.load to finish first
437 | setTimeout(function() {
438 | QUnit.start( count );
439 | });
440 | });
441 | return;
442 | }
443 |
444 | config.semaphore -= count || 1;
445 | // don't start until equal number of stop-calls
446 | if ( config.semaphore > 0 ) {
447 | return;
448 | }
449 | // ignore if start is called more often then stop
450 | if ( config.semaphore < 0 ) {
451 | config.semaphore = 0;
452 | QUnit.pushFailure( "Called start() while already started (QUnit.config.semaphore was 0 already)", null, sourceFromStacktrace(2) );
453 | return;
454 | }
455 | // A slight delay, to avoid any current callbacks
456 | if ( defined.setTimeout ) {
457 | window.setTimeout(function() {
458 | if ( config.semaphore > 0 ) {
459 | return;
460 | }
461 | if ( config.timeout ) {
462 | clearTimeout( config.timeout );
463 | }
464 |
465 | config.blocking = false;
466 | process( true );
467 | }, 13);
468 | } else {
469 | config.blocking = false;
470 | process( true );
471 | }
472 | },
473 |
474 | stop: function( count ) {
475 | config.semaphore += count || 1;
476 | config.blocking = true;
477 |
478 | if ( config.testTimeout && defined.setTimeout ) {
479 | clearTimeout( config.timeout );
480 | config.timeout = window.setTimeout(function() {
481 | QUnit.ok( false, "Test timed out" );
482 | config.semaphore = 1;
483 | QUnit.start();
484 | }, config.testTimeout );
485 | }
486 | }
487 | };
488 |
489 | // `assert` initialized at top of scope
490 | // Asssert helpers
491 | // All of these must either call QUnit.push() or manually do:
492 | // - runLoggingCallbacks( "log", .. );
493 | // - config.current.assertions.push({ .. });
494 | // We attach it to the QUnit object *after* we expose the public API,
495 | // otherwise `assert` will become a global variable in browsers (#341).
496 | assert = {
497 | /**
498 | * Asserts rough true-ish result.
499 | * @name ok
500 | * @function
501 | * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" );
502 | */
503 | ok: function( result, msg ) {
504 | if ( !config.current ) {
505 | throw new Error( "ok() assertion outside test context, was " + sourceFromStacktrace(2) );
506 | }
507 | result = !!result;
508 |
509 | var source,
510 | details = {
511 | module: config.current.module,
512 | name: config.current.testName,
513 | result: result,
514 | message: msg
515 | };
516 |
517 | msg = escapeText( msg || (result ? "okay" : "failed" ) );
518 | msg = "" + msg + "";
519 |
520 | if ( !result ) {
521 | source = sourceFromStacktrace( 2 );
522 | if ( source ) {
523 | details.source = source;
524 | msg += "| Source: | " + escapeText( source ) + " |
|---|
";
525 | }
526 | }
527 | runLoggingCallbacks( "log", QUnit, details );
528 | config.current.assertions.push({
529 | result: result,
530 | message: msg
531 | });
532 | },
533 |
534 | /**
535 | * Assert that the first two arguments are equal, with an optional message.
536 | * Prints out both actual and expected values.
537 | * @name equal
538 | * @function
539 | * @example equal( format( "Received {0} bytes.", 2), "Received 2 bytes.", "format() replaces {0} with next argument" );
540 | */
541 | equal: function( actual, expected, message ) {
542 | /*jshint eqeqeq:false */
543 | QUnit.push( expected == actual, actual, expected, message );
544 | },
545 |
546 | /**
547 | * @name notEqual
548 | * @function
549 | */
550 | notEqual: function( actual, expected, message ) {
551 | /*jshint eqeqeq:false */
552 | QUnit.push( expected != actual, actual, expected, message );
553 | },
554 |
555 | /**
556 | * @name propEqual
557 | * @function
558 | */
559 | propEqual: function( actual, expected, message ) {
560 | actual = objectValues(actual);
561 | expected = objectValues(expected);
562 | QUnit.push( QUnit.equiv(actual, expected), actual, expected, message );
563 | },
564 |
565 | /**
566 | * @name notPropEqual
567 | * @function
568 | */
569 | notPropEqual: function( actual, expected, message ) {
570 | actual = objectValues(actual);
571 | expected = objectValues(expected);
572 | QUnit.push( !QUnit.equiv(actual, expected), actual, expected, message );
573 | },
574 |
575 | /**
576 | * @name deepEqual
577 | * @function
578 | */
579 | deepEqual: function( actual, expected, message ) {
580 | QUnit.push( QUnit.equiv(actual, expected), actual, expected, message );
581 | },
582 |
583 | /**
584 | * @name notDeepEqual
585 | * @function
586 | */
587 | notDeepEqual: function( actual, expected, message ) {
588 | QUnit.push( !QUnit.equiv(actual, expected), actual, expected, message );
589 | },
590 |
591 | /**
592 | * @name strictEqual
593 | * @function
594 | */
595 | strictEqual: function( actual, expected, message ) {
596 | QUnit.push( expected === actual, actual, expected, message );
597 | },
598 |
599 | /**
600 | * @name notStrictEqual
601 | * @function
602 | */
603 | notStrictEqual: function( actual, expected, message ) {
604 | QUnit.push( expected !== actual, actual, expected, message );
605 | },
606 |
607 | "throws": function( block, expected, message ) {
608 | var actual,
609 | expectedOutput = expected,
610 | ok = false;
611 |
612 | // 'expected' is optional
613 | if ( typeof expected === "string" ) {
614 | message = expected;
615 | expected = null;
616 | }
617 |
618 | config.current.ignoreGlobalErrors = true;
619 | try {
620 | block.call( config.current.testEnvironment );
621 | } catch (e) {
622 | actual = e;
623 | }
624 | config.current.ignoreGlobalErrors = false;
625 |
626 | if ( actual ) {
627 | // we don't want to validate thrown error
628 | if ( !expected ) {
629 | ok = true;
630 | expectedOutput = null;
631 | // expected is a regexp
632 | } else if ( QUnit.objectType( expected ) === "regexp" ) {
633 | ok = expected.test( errorString( actual ) );
634 | // expected is a constructor
635 | } else if ( actual instanceof expected ) {
636 | ok = true;
637 | // expected is a validation function which returns true is validation passed
638 | } else if ( expected.call( {}, actual ) === true ) {
639 | expectedOutput = null;
640 | ok = true;
641 | }
642 |
643 | QUnit.push( ok, actual, expectedOutput, message );
644 | } else {
645 | QUnit.pushFailure( message, null, 'No exception was thrown.' );
646 | }
647 | }
648 | };
649 |
650 | /**
651 | * @deprecate since 1.8.0
652 | * Kept assertion helpers in root for backwards compatibility.
653 | */
654 | extend( QUnit, assert );
655 |
656 | /**
657 | * @deprecated since 1.9.0
658 | * Kept root "raises()" for backwards compatibility.
659 | * (Note that we don't introduce assert.raises).
660 | */
661 | QUnit.raises = assert[ "throws" ];
662 |
663 | /**
664 | * @deprecated since 1.0.0, replaced with error pushes since 1.3.0
665 | * Kept to avoid TypeErrors for undefined methods.
666 | */
667 | QUnit.equals = function() {
668 | QUnit.push( false, false, false, "QUnit.equals has been deprecated since 2009 (e88049a0), use QUnit.equal instead" );
669 | };
670 | QUnit.same = function() {
671 | QUnit.push( false, false, false, "QUnit.same has been deprecated since 2009 (e88049a0), use QUnit.deepEqual instead" );
672 | };
673 |
674 | // We want access to the constructor's prototype
675 | (function() {
676 | function F() {}
677 | F.prototype = QUnit;
678 | QUnit = new F();
679 | // Make F QUnit's constructor so that we can add to the prototype later
680 | QUnit.constructor = F;
681 | }());
682 |
683 | /**
684 | * Config object: Maintain internal state
685 | * Later exposed as QUnit.config
686 | * `config` initialized at top of scope
687 | */
688 | config = {
689 | // The queue of tests to run
690 | queue: [],
691 |
692 | // block until document ready
693 | blocking: true,
694 |
695 | // when enabled, show only failing tests
696 | // gets persisted through sessionStorage and can be changed in UI via checkbox
697 | hidepassed: false,
698 |
699 | // by default, run previously failed tests first
700 | // very useful in combination with "Hide passed tests" checked
701 | reorder: true,
702 |
703 | // by default, modify document.title when suite is done
704 | altertitle: true,
705 |
706 | // when enabled, all tests must call expect()
707 | requireExpects: false,
708 |
709 | // add checkboxes that are persisted in the query-string
710 | // when enabled, the id is set to `true` as a `QUnit.config` property
711 | urlConfig: [
712 | {
713 | id: "noglobals",
714 | label: "Check for Globals",
715 | tooltip: "Enabling this will test if any test introduces new properties on the `window` object. Stored as query-strings."
716 | },
717 | {
718 | id: "notrycatch",
719 | label: "No try-catch",
720 | tooltip: "Enabling this will run tests outside of a try-catch block. Makes debugging exceptions in IE reasonable. Stored as query-strings."
721 | }
722 | ],
723 |
724 | // Set of all modules.
725 | modules: {},
726 |
727 | // logging callback queues
728 | begin: [],
729 | done: [],
730 | log: [],
731 | testStart: [],
732 | testDone: [],
733 | moduleStart: [],
734 | moduleDone: []
735 | };
736 |
737 | // Export global variables, unless an 'exports' object exists,
738 | // in that case we assume we're in CommonJS (dealt with on the bottom of the script)
739 | if ( typeof exports === "undefined" ) {
740 | extend( window, QUnit );
741 |
742 | // Expose QUnit object
743 | window.QUnit = QUnit;
744 | }
745 |
746 | // Initialize more QUnit.config and QUnit.urlParams
747 | (function() {
748 | var i,
749 | location = window.location || { search: "", protocol: "file:" },
750 | params = location.search.slice( 1 ).split( "&" ),
751 | length = params.length,
752 | urlParams = {},
753 | current;
754 |
755 | if ( params[ 0 ] ) {
756 | for ( i = 0; i < length; i++ ) {
757 | current = params[ i ].split( "=" );
758 | current[ 0 ] = decodeURIComponent( current[ 0 ] );
759 | // allow just a key to turn on a flag, e.g., test.html?noglobals
760 | current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true;
761 | urlParams[ current[ 0 ] ] = current[ 1 ];
762 | }
763 | }
764 |
765 | QUnit.urlParams = urlParams;
766 |
767 | // String search anywhere in moduleName+testName
768 | config.filter = urlParams.filter;
769 |
770 | // Exact match of the module name
771 | config.module = urlParams.module;
772 |
773 | config.testNumber = parseInt( urlParams.testNumber, 10 ) || null;
774 |
775 | // Figure out if we're running the tests from a server or not
776 | QUnit.isLocal = location.protocol === "file:";
777 | }());
778 |
779 | // Extend QUnit object,
780 | // these after set here because they should not be exposed as global functions
781 | extend( QUnit, {
782 | assert: assert,
783 |
784 | config: config,
785 |
786 | // Initialize the configuration options
787 | init: function() {
788 | extend( config, {
789 | stats: { all: 0, bad: 0 },
790 | moduleStats: { all: 0, bad: 0 },
791 | started: +new Date(),
792 | updateRate: 1000,
793 | blocking: false,
794 | autostart: true,
795 | autorun: false,
796 | filter: "",
797 | queue: [],
798 | semaphore: 1
799 | });
800 |
801 | var tests, banner, result,
802 | qunit = id( "qunit" );
803 |
804 | if ( qunit ) {
805 | qunit.innerHTML =
806 | "" +
807 | "" +
808 | "" +
809 | "" +
810 | "
";
811 | }
812 |
813 | tests = id( "qunit-tests" );
814 | banner = id( "qunit-banner" );
815 | result = id( "qunit-testresult" );
816 |
817 | if ( tests ) {
818 | tests.innerHTML = "";
819 | }
820 |
821 | if ( banner ) {
822 | banner.className = "";
823 | }
824 |
825 | if ( result ) {
826 | result.parentNode.removeChild( result );
827 | }
828 |
829 | if ( tests ) {
830 | result = document.createElement( "p" );
831 | result.id = "qunit-testresult";
832 | result.className = "result";
833 | tests.parentNode.insertBefore( result, tests );
834 | result.innerHTML = "Running...
";
835 | }
836 | },
837 |
838 | // Resets the test setup. Useful for tests that modify the DOM.
839 | reset: function() {
840 | var fixture = id( "qunit-fixture" );
841 | if ( fixture ) {
842 | fixture.innerHTML = config.fixture;
843 | }
844 | },
845 |
846 | // Trigger an event on an element.
847 | // @example triggerEvent( document.body, "click" );
848 | triggerEvent: function( elem, type, event ) {
849 | if ( document.createEvent ) {
850 | event = document.createEvent( "MouseEvents" );
851 | event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
852 | 0, 0, 0, 0, 0, false, false, false, false, 0, null);
853 |
854 | elem.dispatchEvent( event );
855 | } else if ( elem.fireEvent ) {
856 | elem.fireEvent( "on" + type );
857 | }
858 | },
859 |
860 | // Safe object type checking
861 | is: function( type, obj ) {
862 | return QUnit.objectType( obj ) === type;
863 | },
864 |
865 | objectType: function( obj ) {
866 | if ( typeof obj === "undefined" ) {
867 | return "undefined";
868 | // consider: typeof null === object
869 | }
870 | if ( obj === null ) {
871 | return "null";
872 | }
873 |
874 | var match = toString.call( obj ).match(/^\[object\s(.*)\]$/),
875 | type = match && match[1] || "";
876 |
877 | switch ( type ) {
878 | case "Number":
879 | if ( isNaN(obj) ) {
880 | return "nan";
881 | }
882 | return "number";
883 | case "String":
884 | case "Boolean":
885 | case "Array":
886 | case "Date":
887 | case "RegExp":
888 | case "Function":
889 | return type.toLowerCase();
890 | }
891 | if ( typeof obj === "object" ) {
892 | return "object";
893 | }
894 | return undefined;
895 | },
896 |
897 | push: function( result, actual, expected, message ) {
898 | if ( !config.current ) {
899 | throw new Error( "assertion outside test context, was " + sourceFromStacktrace() );
900 | }
901 |
902 | var output, source,
903 | details = {
904 | module: config.current.module,
905 | name: config.current.testName,
906 | result: result,
907 | message: message,
908 | actual: actual,
909 | expected: expected
910 | };
911 |
912 | message = escapeText( message ) || ( result ? "okay" : "failed" );
913 | message = "" + message + "";
914 | output = message;
915 |
916 | if ( !result ) {
917 | expected = escapeText( QUnit.jsDump.parse(expected) );
918 | actual = escapeText( QUnit.jsDump.parse(actual) );
919 | output += "| Expected: | " + expected + " |
";
920 |
921 | if ( actual !== expected ) {
922 | output += "| Result: | " + actual + " |
";
923 | output += "| Diff: | " + QUnit.diff( expected, actual ) + " |
";
924 | }
925 |
926 | source = sourceFromStacktrace();
927 |
928 | if ( source ) {
929 | details.source = source;
930 | output += "| Source: | " + escapeText( source ) + " |
";
931 | }
932 |
933 | output += "
";
934 | }
935 |
936 | runLoggingCallbacks( "log", QUnit, details );
937 |
938 | config.current.assertions.push({
939 | result: !!result,
940 | message: output
941 | });
942 | },
943 |
944 | pushFailure: function( message, source, actual ) {
945 | if ( !config.current ) {
946 | throw new Error( "pushFailure() assertion outside test context, was " + sourceFromStacktrace(2) );
947 | }
948 |
949 | var output,
950 | details = {
951 | module: config.current.module,
952 | name: config.current.testName,
953 | result: false,
954 | message: message
955 | };
956 |
957 | message = escapeText( message ) || "error";
958 | message = "" + message + "";
959 | output = message;
960 |
961 | output += "";
962 |
963 | if ( actual ) {
964 | output += "| Result: | " + escapeText( actual ) + " |
";
965 | }
966 |
967 | if ( source ) {
968 | details.source = source;
969 | output += "| Source: | " + escapeText( source ) + " |
";
970 | }
971 |
972 | output += "
";
973 |
974 | runLoggingCallbacks( "log", QUnit, details );
975 |
976 | config.current.assertions.push({
977 | result: false,
978 | message: output
979 | });
980 | },
981 |
982 | url: function( params ) {
983 | params = extend( extend( {}, QUnit.urlParams ), params );
984 | var key,
985 | querystring = "?";
986 |
987 | for ( key in params ) {
988 | if ( !hasOwn.call( params, key ) ) {
989 | continue;
990 | }
991 | querystring += encodeURIComponent( key ) + "=" +
992 | encodeURIComponent( params[ key ] ) + "&";
993 | }
994 | return window.location.protocol + "//" + window.location.host +
995 | window.location.pathname + querystring.slice( 0, -1 );
996 | },
997 |
998 | extend: extend,
999 | id: id,
1000 | addEvent: addEvent
1001 | // load, equiv, jsDump, diff: Attached later
1002 | });
1003 |
1004 | /**
1005 | * @deprecated: Created for backwards compatibility with test runner that set the hook function
1006 | * into QUnit.{hook}, instead of invoking it and passing the hook function.
1007 | * QUnit.constructor is set to the empty F() above so that we can add to it's prototype here.
1008 | * Doing this allows us to tell if the following methods have been overwritten on the actual
1009 | * QUnit object.
1010 | */
1011 | extend( QUnit.constructor.prototype, {
1012 |
1013 | // Logging callbacks; all receive a single argument with the listed properties
1014 | // run test/logs.html for any related changes
1015 | begin: registerLoggingCallback( "begin" ),
1016 |
1017 | // done: { failed, passed, total, runtime }
1018 | done: registerLoggingCallback( "done" ),
1019 |
1020 | // log: { result, actual, expected, message }
1021 | log: registerLoggingCallback( "log" ),
1022 |
1023 | // testStart: { name }
1024 | testStart: registerLoggingCallback( "testStart" ),
1025 |
1026 | // testDone: { name, failed, passed, total, duration }
1027 | testDone: registerLoggingCallback( "testDone" ),
1028 |
1029 | // moduleStart: { name }
1030 | moduleStart: registerLoggingCallback( "moduleStart" ),
1031 |
1032 | // moduleDone: { name, failed, passed, total }
1033 | moduleDone: registerLoggingCallback( "moduleDone" )
1034 | });
1035 |
1036 | if ( typeof document === "undefined" || document.readyState === "complete" ) {
1037 | config.autorun = true;
1038 | }
1039 |
1040 | QUnit.load = function() {
1041 | runLoggingCallbacks( "begin", QUnit, {} );
1042 |
1043 | // Initialize the config, saving the execution queue
1044 | var banner, filter, i, label, len, main, ol, toolbar, userAgent, val,
1045 | urlConfigCheckboxesContainer, urlConfigCheckboxes, moduleFilter,
1046 | numModules = 0,
1047 | moduleFilterHtml = "",
1048 | urlConfigHtml = "",
1049 | oldconfig = extend( {}, config );
1050 |
1051 | QUnit.init();
1052 | extend(config, oldconfig);
1053 |
1054 | config.blocking = false;
1055 |
1056 | len = config.urlConfig.length;
1057 |
1058 | for ( i = 0; i < len; i++ ) {
1059 | val = config.urlConfig[i];
1060 | if ( typeof val === "string" ) {
1061 | val = {
1062 | id: val,
1063 | label: val,
1064 | tooltip: "[no tooltip available]"
1065 | };
1066 | }
1067 | config[ val.id ] = QUnit.urlParams[ val.id ];
1068 | urlConfigHtml += "";
1074 | }
1075 |
1076 | moduleFilterHtml += "";
1089 |
1090 | // `userAgent` initialized at top of scope
1091 | userAgent = id( "qunit-userAgent" );
1092 | if ( userAgent ) {
1093 | userAgent.innerHTML = navigator.userAgent;
1094 | }
1095 |
1096 | // `banner` initialized at top of scope
1097 | banner = id( "qunit-header" );
1098 | if ( banner ) {
1099 | banner.innerHTML = "" + banner.innerHTML + " ";
1100 | }
1101 |
1102 | // `toolbar` initialized at top of scope
1103 | toolbar = id( "qunit-testrunner-toolbar" );
1104 | if ( toolbar ) {
1105 | // `filter` initialized at top of scope
1106 | filter = document.createElement( "input" );
1107 | filter.type = "checkbox";
1108 | filter.id = "qunit-filter-pass";
1109 |
1110 | addEvent( filter, "click", function() {
1111 | var tmp,
1112 | ol = document.getElementById( "qunit-tests" );
1113 |
1114 | if ( filter.checked ) {
1115 | ol.className = ol.className + " hidepass";
1116 | } else {
1117 | tmp = " " + ol.className.replace( /[\n\t\r]/g, " " ) + " ";
1118 | ol.className = tmp.replace( / hidepass /, " " );
1119 | }
1120 | if ( defined.sessionStorage ) {
1121 | if (filter.checked) {
1122 | sessionStorage.setItem( "qunit-filter-passed-tests", "true" );
1123 | } else {
1124 | sessionStorage.removeItem( "qunit-filter-passed-tests" );
1125 | }
1126 | }
1127 | });
1128 |
1129 | if ( config.hidepassed || defined.sessionStorage && sessionStorage.getItem( "qunit-filter-passed-tests" ) ) {
1130 | filter.checked = true;
1131 | // `ol` initialized at top of scope
1132 | ol = document.getElementById( "qunit-tests" );
1133 | ol.className = ol.className + " hidepass";
1134 | }
1135 | toolbar.appendChild( filter );
1136 |
1137 | // `label` initialized at top of scope
1138 | label = document.createElement( "label" );
1139 | label.setAttribute( "for", "qunit-filter-pass" );
1140 | label.setAttribute( "title", "Only show tests and assertons that fail. Stored in sessionStorage." );
1141 | label.innerHTML = "Hide passed tests";
1142 | toolbar.appendChild( label );
1143 |
1144 | urlConfigCheckboxesContainer = document.createElement("span");
1145 | urlConfigCheckboxesContainer.innerHTML = urlConfigHtml;
1146 | urlConfigCheckboxes = urlConfigCheckboxesContainer.getElementsByTagName("input");
1147 | // For oldIE support:
1148 | // * Add handlers to the individual elements instead of the container
1149 | // * Use "click" instead of "change"
1150 | // * Fallback from event.target to event.srcElement
1151 | addEvents( urlConfigCheckboxes, "click", function( event ) {
1152 | var params = {},
1153 | target = event.target || event.srcElement;
1154 | params[ target.name ] = target.checked ? true : undefined;
1155 | window.location = QUnit.url( params );
1156 | });
1157 | toolbar.appendChild( urlConfigCheckboxesContainer );
1158 |
1159 | if (numModules > 1) {
1160 | moduleFilter = document.createElement( 'span' );
1161 | moduleFilter.setAttribute( 'id', 'qunit-modulefilter-container' );
1162 | moduleFilter.innerHTML = moduleFilterHtml;
1163 | addEvent( moduleFilter.lastChild, "change", function() {
1164 | var selectBox = moduleFilter.getElementsByTagName("select")[0],
1165 | selectedModule = decodeURIComponent(selectBox.options[selectBox.selectedIndex].value);
1166 |
1167 | window.location = QUnit.url( { module: ( selectedModule === "" ) ? undefined : selectedModule } );
1168 | });
1169 | toolbar.appendChild(moduleFilter);
1170 | }
1171 | }
1172 |
1173 | // `main` initialized at top of scope
1174 | main = id( "qunit-fixture" );
1175 | if ( main ) {
1176 | config.fixture = main.innerHTML;
1177 | }
1178 |
1179 | if ( config.autostart ) {
1180 | QUnit.start();
1181 | }
1182 | };
1183 |
1184 | addEvent( window, "load", QUnit.load );
1185 |
1186 | // `onErrorFnPrev` initialized at top of scope
1187 | // Preserve other handlers
1188 | onErrorFnPrev = window.onerror;
1189 |
1190 | // Cover uncaught exceptions
1191 | // Returning true will surpress the default browser handler,
1192 | // returning false will let it run.
1193 | window.onerror = function ( error, filePath, linerNr ) {
1194 | var ret = false;
1195 | if ( onErrorFnPrev ) {
1196 | ret = onErrorFnPrev( error, filePath, linerNr );
1197 | }
1198 |
1199 | // Treat return value as window.onerror itself does,
1200 | // Only do our handling if not surpressed.
1201 | if ( ret !== true ) {
1202 | if ( QUnit.config.current ) {
1203 | if ( QUnit.config.current.ignoreGlobalErrors ) {
1204 | return true;
1205 | }
1206 | QUnit.pushFailure( error, filePath + ":" + linerNr );
1207 | } else {
1208 | QUnit.test( "global failure", extend( function() {
1209 | QUnit.pushFailure( error, filePath + ":" + linerNr );
1210 | }, { validTest: validTest } ) );
1211 | }
1212 | return false;
1213 | }
1214 |
1215 | return ret;
1216 | };
1217 |
1218 | function done() {
1219 | config.autorun = true;
1220 |
1221 | // Log the last module results
1222 | if ( config.currentModule ) {
1223 | runLoggingCallbacks( "moduleDone", QUnit, {
1224 | name: config.currentModule,
1225 | failed: config.moduleStats.bad,
1226 | passed: config.moduleStats.all - config.moduleStats.bad,
1227 | total: config.moduleStats.all
1228 | });
1229 | }
1230 |
1231 | var i, key,
1232 | banner = id( "qunit-banner" ),
1233 | tests = id( "qunit-tests" ),
1234 | runtime = +new Date() - config.started,
1235 | passed = config.stats.all - config.stats.bad,
1236 | html = [
1237 | "Tests completed in ",
1238 | runtime,
1239 | " milliseconds.
",
1240 | "",
1241 | passed,
1242 | " assertions of ",
1243 | config.stats.all,
1244 | " passed, ",
1245 | config.stats.bad,
1246 | " failed."
1247 | ].join( "" );
1248 |
1249 | if ( banner ) {
1250 | banner.className = ( config.stats.bad ? "qunit-fail" : "qunit-pass" );
1251 | }
1252 |
1253 | if ( tests ) {
1254 | id( "qunit-testresult" ).innerHTML = html;
1255 | }
1256 |
1257 | if ( config.altertitle && typeof document !== "undefined" && document.title ) {
1258 | // show ✖ for good, ✔ for bad suite result in title
1259 | // use escape sequences in case file gets loaded with non-utf-8-charset
1260 | document.title = [
1261 | ( config.stats.bad ? "\u2716" : "\u2714" ),
1262 | document.title.replace( /^[\u2714\u2716] /i, "" )
1263 | ].join( " " );
1264 | }
1265 |
1266 | // clear own sessionStorage items if all tests passed
1267 | if ( config.reorder && defined.sessionStorage && config.stats.bad === 0 ) {
1268 | // `key` & `i` initialized at top of scope
1269 | for ( i = 0; i < sessionStorage.length; i++ ) {
1270 | key = sessionStorage.key( i++ );
1271 | if ( key.indexOf( "qunit-test-" ) === 0 ) {
1272 | sessionStorage.removeItem( key );
1273 | }
1274 | }
1275 | }
1276 |
1277 | // scroll back to top to show results
1278 | if ( window.scrollTo ) {
1279 | window.scrollTo(0, 0);
1280 | }
1281 |
1282 | runLoggingCallbacks( "done", QUnit, {
1283 | failed: config.stats.bad,
1284 | passed: passed,
1285 | total: config.stats.all,
1286 | runtime: runtime
1287 | });
1288 | }
1289 |
1290 | /** @return Boolean: true if this test should be ran */
1291 | function validTest( test ) {
1292 | var include,
1293 | filter = config.filter && config.filter.toLowerCase(),
1294 | module = config.module && config.module.toLowerCase(),
1295 | fullName = (test.module + ": " + test.testName).toLowerCase();
1296 |
1297 | // Internally-generated tests are always valid
1298 | if ( test.callback && test.callback.validTest === validTest ) {
1299 | delete test.callback.validTest;
1300 | return true;
1301 | }
1302 |
1303 | if ( config.testNumber ) {
1304 | return test.testNumber === config.testNumber;
1305 | }
1306 |
1307 | if ( module && ( !test.module || test.module.toLowerCase() !== module ) ) {
1308 | return false;
1309 | }
1310 |
1311 | if ( !filter ) {
1312 | return true;
1313 | }
1314 |
1315 | include = filter.charAt( 0 ) !== "!";
1316 | if ( !include ) {
1317 | filter = filter.slice( 1 );
1318 | }
1319 |
1320 | // If the filter matches, we need to honour include
1321 | if ( fullName.indexOf( filter ) !== -1 ) {
1322 | return include;
1323 | }
1324 |
1325 | // Otherwise, do the opposite
1326 | return !include;
1327 | }
1328 |
1329 | // so far supports only Firefox, Chrome and Opera (buggy), Safari (for real exceptions)
1330 | // Later Safari and IE10 are supposed to support error.stack as well
1331 | // See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack
1332 | function extractStacktrace( e, offset ) {
1333 | offset = offset === undefined ? 3 : offset;
1334 |
1335 | var stack, include, i;
1336 |
1337 | if ( e.stacktrace ) {
1338 | // Opera
1339 | return e.stacktrace.split( "\n" )[ offset + 3 ];
1340 | } else if ( e.stack ) {
1341 | // Firefox, Chrome
1342 | stack = e.stack.split( "\n" );
1343 | if (/^error$/i.test( stack[0] ) ) {
1344 | stack.shift();
1345 | }
1346 | if ( fileName ) {
1347 | include = [];
1348 | for ( i = offset; i < stack.length; i++ ) {
1349 | if ( stack[ i ].indexOf( fileName ) !== -1 ) {
1350 | break;
1351 | }
1352 | include.push( stack[ i ] );
1353 | }
1354 | if ( include.length ) {
1355 | return include.join( "\n" );
1356 | }
1357 | }
1358 | return stack[ offset ];
1359 | } else if ( e.sourceURL ) {
1360 | // Safari, PhantomJS
1361 | // hopefully one day Safari provides actual stacktraces
1362 | // exclude useless self-reference for generated Error objects
1363 | if ( /qunit.js$/.test( e.sourceURL ) ) {
1364 | return;
1365 | }
1366 | // for actual exceptions, this is useful
1367 | return e.sourceURL + ":" + e.line;
1368 | }
1369 | }
1370 | function sourceFromStacktrace( offset ) {
1371 | try {
1372 | throw new Error();
1373 | } catch ( e ) {
1374 | return extractStacktrace( e, offset );
1375 | }
1376 | }
1377 |
1378 | /**
1379 | * Escape text for attribute or text content.
1380 | */
1381 | function escapeText( s ) {
1382 | if ( !s ) {
1383 | return "";
1384 | }
1385 | s = s + "";
1386 | // Both single quotes and double quotes (for attributes)
1387 | return s.replace( /['"<>&]/g, function( s ) {
1388 | switch( s ) {
1389 | case '\'':
1390 | return ''';
1391 | case '"':
1392 | return '"';
1393 | case '<':
1394 | return '<';
1395 | case '>':
1396 | return '>';
1397 | case '&':
1398 | return '&';
1399 | }
1400 | });
1401 | }
1402 |
1403 | function synchronize( callback, last ) {
1404 | config.queue.push( callback );
1405 |
1406 | if ( config.autorun && !config.blocking ) {
1407 | process( last );
1408 | }
1409 | }
1410 |
1411 | function process( last ) {
1412 | function next() {
1413 | process( last );
1414 | }
1415 | var start = new Date().getTime();
1416 | config.depth = config.depth ? config.depth + 1 : 1;
1417 |
1418 | while ( config.queue.length && !config.blocking ) {
1419 | if ( !defined.setTimeout || config.updateRate <= 0 || ( ( new Date().getTime() - start ) < config.updateRate ) ) {
1420 | config.queue.shift()();
1421 | } else {
1422 | window.setTimeout( next, 13 );
1423 | break;
1424 | }
1425 | }
1426 | config.depth--;
1427 | if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) {
1428 | done();
1429 | }
1430 | }
1431 |
1432 | function saveGlobal() {
1433 | config.pollution = [];
1434 |
1435 | if ( config.noglobals ) {
1436 | for ( var key in window ) {
1437 | // in Opera sometimes DOM element ids show up here, ignore them
1438 | if ( !hasOwn.call( window, key ) || /^qunit-test-output/.test( key ) ) {
1439 | continue;
1440 | }
1441 | config.pollution.push( key );
1442 | }
1443 | }
1444 | }
1445 |
1446 | function checkPollution() {
1447 | var newGlobals,
1448 | deletedGlobals,
1449 | old = config.pollution;
1450 |
1451 | saveGlobal();
1452 |
1453 | newGlobals = diff( config.pollution, old );
1454 | if ( newGlobals.length > 0 ) {
1455 | QUnit.pushFailure( "Introduced global variable(s): " + newGlobals.join(", ") );
1456 | }
1457 |
1458 | deletedGlobals = diff( old, config.pollution );
1459 | if ( deletedGlobals.length > 0 ) {
1460 | QUnit.pushFailure( "Deleted global variable(s): " + deletedGlobals.join(", ") );
1461 | }
1462 | }
1463 |
1464 | // returns a new Array with the elements that are in a but not in b
1465 | function diff( a, b ) {
1466 | var i, j,
1467 | result = a.slice();
1468 |
1469 | for ( i = 0; i < result.length; i++ ) {
1470 | for ( j = 0; j < b.length; j++ ) {
1471 | if ( result[i] === b[j] ) {
1472 | result.splice( i, 1 );
1473 | i--;
1474 | break;
1475 | }
1476 | }
1477 | }
1478 | return result;
1479 | }
1480 |
1481 | function extend( a, b ) {
1482 | for ( var prop in b ) {
1483 | if ( b[ prop ] === undefined ) {
1484 | delete a[ prop ];
1485 |
1486 | // Avoid "Member not found" error in IE8 caused by setting window.constructor
1487 | } else if ( prop !== "constructor" || a !== window ) {
1488 | a[ prop ] = b[ prop ];
1489 | }
1490 | }
1491 |
1492 | return a;
1493 | }
1494 |
1495 | /**
1496 | * @param {HTMLElement} elem
1497 | * @param {string} type
1498 | * @param {Function} fn
1499 | */
1500 | function addEvent( elem, type, fn ) {
1501 | // Standards-based browsers
1502 | if ( elem.addEventListener ) {
1503 | elem.addEventListener( type, fn, false );
1504 | // IE
1505 | } else {
1506 | elem.attachEvent( "on" + type, fn );
1507 | }
1508 | }
1509 |
1510 | /**
1511 | * @param {Array|NodeList} elems
1512 | * @param {string} type
1513 | * @param {Function} fn
1514 | */
1515 | function addEvents( elems, type, fn ) {
1516 | var i = elems.length;
1517 | while ( i-- ) {
1518 | addEvent( elems[i], type, fn );
1519 | }
1520 | }
1521 |
1522 | function hasClass( elem, name ) {
1523 | return (" " + elem.className + " ").indexOf(" " + name + " ") > -1;
1524 | }
1525 |
1526 | function addClass( elem, name ) {
1527 | if ( !hasClass( elem, name ) ) {
1528 | elem.className += (elem.className ? " " : "") + name;
1529 | }
1530 | }
1531 |
1532 | function removeClass( elem, name ) {
1533 | var set = " " + elem.className + " ";
1534 | // Class name may appear multiple times
1535 | while ( set.indexOf(" " + name + " ") > -1 ) {
1536 | set = set.replace(" " + name + " " , " ");
1537 | }
1538 | // If possible, trim it for prettiness, but not neccecarily
1539 | elem.className = window.jQuery ? jQuery.trim( set ) : ( set.trim ? set.trim() : set );
1540 | }
1541 |
1542 | function id( name ) {
1543 | return !!( typeof document !== "undefined" && document && document.getElementById ) &&
1544 | document.getElementById( name );
1545 | }
1546 |
1547 | function registerLoggingCallback( key ) {
1548 | return function( callback ) {
1549 | config[key].push( callback );
1550 | };
1551 | }
1552 |
1553 | // Supports deprecated method of completely overwriting logging callbacks
1554 | function runLoggingCallbacks( key, scope, args ) {
1555 | var i, callbacks;
1556 | if ( QUnit.hasOwnProperty( key ) ) {
1557 | QUnit[ key ].call(scope, args );
1558 | } else {
1559 | callbacks = config[ key ];
1560 | for ( i = 0; i < callbacks.length; i++ ) {
1561 | callbacks[ i ].call( scope, args );
1562 | }
1563 | }
1564 | }
1565 |
1566 | // Test for equality any JavaScript type.
1567 | // Author: Philippe Rathé
1568 | QUnit.equiv = (function() {
1569 |
1570 | // Call the o related callback with the given arguments.
1571 | function bindCallbacks( o, callbacks, args ) {
1572 | var prop = QUnit.objectType( o );
1573 | if ( prop ) {
1574 | if ( QUnit.objectType( callbacks[ prop ] ) === "function" ) {
1575 | return callbacks[ prop ].apply( callbacks, args );
1576 | } else {
1577 | return callbacks[ prop ]; // or undefined
1578 | }
1579 | }
1580 | }
1581 |
1582 | // the real equiv function
1583 | var innerEquiv,
1584 | // stack to decide between skip/abort functions
1585 | callers = [],
1586 | // stack to avoiding loops from circular referencing
1587 | parents = [],
1588 |
1589 | getProto = Object.getPrototypeOf || function ( obj ) {
1590 | return obj.__proto__;
1591 | },
1592 | callbacks = (function () {
1593 |
1594 | // for string, boolean, number and null
1595 | function useStrictEquality( b, a ) {
1596 | /*jshint eqeqeq:false */
1597 | if ( b instanceof a.constructor || a instanceof b.constructor ) {
1598 | // to catch short annotaion VS 'new' annotation of a
1599 | // declaration
1600 | // e.g. var i = 1;
1601 | // var j = new Number(1);
1602 | return a == b;
1603 | } else {
1604 | return a === b;
1605 | }
1606 | }
1607 |
1608 | return {
1609 | "string": useStrictEquality,
1610 | "boolean": useStrictEquality,
1611 | "number": useStrictEquality,
1612 | "null": useStrictEquality,
1613 | "undefined": useStrictEquality,
1614 |
1615 | "nan": function( b ) {
1616 | return isNaN( b );
1617 | },
1618 |
1619 | "date": function( b, a ) {
1620 | return QUnit.objectType( b ) === "date" && a.valueOf() === b.valueOf();
1621 | },
1622 |
1623 | "regexp": function( b, a ) {
1624 | return QUnit.objectType( b ) === "regexp" &&
1625 | // the regex itself
1626 | a.source === b.source &&
1627 | // and its modifers
1628 | a.global === b.global &&
1629 | // (gmi) ...
1630 | a.ignoreCase === b.ignoreCase &&
1631 | a.multiline === b.multiline &&
1632 | a.sticky === b.sticky;
1633 | },
1634 |
1635 | // - skip when the property is a method of an instance (OOP)
1636 | // - abort otherwise,
1637 | // initial === would have catch identical references anyway
1638 | "function": function() {
1639 | var caller = callers[callers.length - 1];
1640 | return caller !== Object && typeof caller !== "undefined";
1641 | },
1642 |
1643 | "array": function( b, a ) {
1644 | var i, j, len, loop;
1645 |
1646 | // b could be an object literal here
1647 | if ( QUnit.objectType( b ) !== "array" ) {
1648 | return false;
1649 | }
1650 |
1651 | len = a.length;
1652 | if ( len !== b.length ) {
1653 | // safe and faster
1654 | return false;
1655 | }
1656 |
1657 | // track reference to avoid circular references
1658 | parents.push( a );
1659 | for ( i = 0; i < len; i++ ) {
1660 | loop = false;
1661 | for ( j = 0; j < parents.length; j++ ) {
1662 | if ( parents[j] === a[i] ) {
1663 | loop = true;// dont rewalk array
1664 | }
1665 | }
1666 | if ( !loop && !innerEquiv(a[i], b[i]) ) {
1667 | parents.pop();
1668 | return false;
1669 | }
1670 | }
1671 | parents.pop();
1672 | return true;
1673 | },
1674 |
1675 | "object": function( b, a ) {
1676 | var i, j, loop,
1677 | // Default to true
1678 | eq = true,
1679 | aProperties = [],
1680 | bProperties = [];
1681 |
1682 | // comparing constructors is more strict than using
1683 | // instanceof
1684 | if ( a.constructor !== b.constructor ) {
1685 | // Allow objects with no prototype to be equivalent to
1686 | // objects with Object as their constructor.
1687 | if ( !(( getProto(a) === null && getProto(b) === Object.prototype ) ||
1688 | ( getProto(b) === null && getProto(a) === Object.prototype ) ) ) {
1689 | return false;
1690 | }
1691 | }
1692 |
1693 | // stack constructor before traversing properties
1694 | callers.push( a.constructor );
1695 | // track reference to avoid circular references
1696 | parents.push( a );
1697 |
1698 | for ( i in a ) { // be strict: don't ensures hasOwnProperty
1699 | // and go deep
1700 | loop = false;
1701 | for ( j = 0; j < parents.length; j++ ) {
1702 | if ( parents[j] === a[i] ) {
1703 | // don't go down the same path twice
1704 | loop = true;
1705 | }
1706 | }
1707 | aProperties.push(i); // collect a's properties
1708 |
1709 | if (!loop && !innerEquiv( a[i], b[i] ) ) {
1710 | eq = false;
1711 | break;
1712 | }
1713 | }
1714 |
1715 | callers.pop(); // unstack, we are done
1716 | parents.pop();
1717 |
1718 | for ( i in b ) {
1719 | bProperties.push( i ); // collect b's properties
1720 | }
1721 |
1722 | // Ensures identical properties name
1723 | return eq && innerEquiv( aProperties.sort(), bProperties.sort() );
1724 | }
1725 | };
1726 | }());
1727 |
1728 | innerEquiv = function() { // can take multiple arguments
1729 | var args = [].slice.apply( arguments );
1730 | if ( args.length < 2 ) {
1731 | return true; // end transition
1732 | }
1733 |
1734 | return (function( a, b ) {
1735 | if ( a === b ) {
1736 | return true; // catch the most you can
1737 | } else if ( a === null || b === null || typeof a === "undefined" ||
1738 | typeof b === "undefined" ||
1739 | QUnit.objectType(a) !== QUnit.objectType(b) ) {
1740 | return false; // don't lose time with error prone cases
1741 | } else {
1742 | return bindCallbacks(a, callbacks, [ b, a ]);
1743 | }
1744 |
1745 | // apply transition with (1..n) arguments
1746 | }( args[0], args[1] ) && arguments.callee.apply( this, args.splice(1, args.length - 1 )) );
1747 | };
1748 |
1749 | return innerEquiv;
1750 | }());
1751 |
1752 | /**
1753 | * jsDump Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com |
1754 | * http://flesler.blogspot.com Licensed under BSD
1755 | * (http://www.opensource.org/licenses/bsd-license.php) Date: 5/15/2008
1756 | *
1757 | * @projectDescription Advanced and extensible data dumping for Javascript.
1758 | * @version 1.0.0
1759 | * @author Ariel Flesler
1760 | * @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html}
1761 | */
1762 | QUnit.jsDump = (function() {
1763 | function quote( str ) {
1764 | return '"' + str.toString().replace( /"/g, '\\"' ) + '"';
1765 | }
1766 | function literal( o ) {
1767 | return o + "";
1768 | }
1769 | function join( pre, arr, post ) {
1770 | var s = jsDump.separator(),
1771 | base = jsDump.indent(),
1772 | inner = jsDump.indent(1);
1773 | if ( arr.join ) {
1774 | arr = arr.join( "," + s + inner );
1775 | }
1776 | if ( !arr ) {
1777 | return pre + post;
1778 | }
1779 | return [ pre, inner + arr, base + post ].join(s);
1780 | }
1781 | function array( arr, stack ) {
1782 | var i = arr.length, ret = new Array(i);
1783 | this.up();
1784 | while ( i-- ) {
1785 | ret[i] = this.parse( arr[i] , undefined , stack);
1786 | }
1787 | this.down();
1788 | return join( "[", ret, "]" );
1789 | }
1790 |
1791 | var reName = /^function (\w+)/,
1792 | jsDump = {
1793 | // type is used mostly internally, you can fix a (custom)type in advance
1794 | parse: function( obj, type, stack ) {
1795 | stack = stack || [ ];
1796 | var inStack, res,
1797 | parser = this.parsers[ type || this.typeOf(obj) ];
1798 |
1799 | type = typeof parser;
1800 | inStack = inArray( obj, stack );
1801 |
1802 | if ( inStack !== -1 ) {
1803 | return "recursion(" + (inStack - stack.length) + ")";
1804 | }
1805 | if ( type === "function" ) {
1806 | stack.push( obj );
1807 | res = parser.call( this, obj, stack );
1808 | stack.pop();
1809 | return res;
1810 | }
1811 | return ( type === "string" ) ? parser : this.parsers.error;
1812 | },
1813 | typeOf: function( obj ) {
1814 | var type;
1815 | if ( obj === null ) {
1816 | type = "null";
1817 | } else if ( typeof obj === "undefined" ) {
1818 | type = "undefined";
1819 | } else if ( QUnit.is( "regexp", obj) ) {
1820 | type = "regexp";
1821 | } else if ( QUnit.is( "date", obj) ) {
1822 | type = "date";
1823 | } else if ( QUnit.is( "function", obj) ) {
1824 | type = "function";
1825 | } else if ( typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined" ) {
1826 | type = "window";
1827 | } else if ( obj.nodeType === 9 ) {
1828 | type = "document";
1829 | } else if ( obj.nodeType ) {
1830 | type = "node";
1831 | } else if (
1832 | // native arrays
1833 | toString.call( obj ) === "[object Array]" ||
1834 | // NodeList objects
1835 | ( typeof obj.length === "number" && typeof obj.item !== "undefined" && ( obj.length ? obj.item(0) === obj[0] : ( obj.item( 0 ) === null && typeof obj[0] === "undefined" ) ) )
1836 | ) {
1837 | type = "array";
1838 | } else if ( obj.constructor === Error.prototype.constructor ) {
1839 | type = "error";
1840 | } else {
1841 | type = typeof obj;
1842 | }
1843 | return type;
1844 | },
1845 | separator: function() {
1846 | return this.multiline ? this.HTML ? "
" : "\n" : this.HTML ? " " : " ";
1847 | },
1848 | // extra can be a number, shortcut for increasing-calling-decreasing
1849 | indent: function( extra ) {
1850 | if ( !this.multiline ) {
1851 | return "";
1852 | }
1853 | var chr = this.indentChar;
1854 | if ( this.HTML ) {
1855 | chr = chr.replace( /\t/g, " " ).replace( / /g, " " );
1856 | }
1857 | return new Array( this._depth_ + (extra||0) ).join(chr);
1858 | },
1859 | up: function( a ) {
1860 | this._depth_ += a || 1;
1861 | },
1862 | down: function( a ) {
1863 | this._depth_ -= a || 1;
1864 | },
1865 | setParser: function( name, parser ) {
1866 | this.parsers[name] = parser;
1867 | },
1868 | // The next 3 are exposed so you can use them
1869 | quote: quote,
1870 | literal: literal,
1871 | join: join,
1872 | //
1873 | _depth_: 1,
1874 | // This is the list of parsers, to modify them, use jsDump.setParser
1875 | parsers: {
1876 | window: "[Window]",
1877 | document: "[Document]",
1878 | error: function(error) {
1879 | return "Error(\"" + error.message + "\")";
1880 | },
1881 | unknown: "[Unknown]",
1882 | "null": "null",
1883 | "undefined": "undefined",
1884 | "function": function( fn ) {
1885 | var ret = "function",
1886 | // functions never have name in IE
1887 | name = "name" in fn ? fn.name : (reName.exec(fn) || [])[1];
1888 |
1889 | if ( name ) {
1890 | ret += " " + name;
1891 | }
1892 | ret += "( ";
1893 |
1894 | ret = [ ret, QUnit.jsDump.parse( fn, "functionArgs" ), "){" ].join( "" );
1895 | return join( ret, QUnit.jsDump.parse(fn,"functionCode" ), "}" );
1896 | },
1897 | array: array,
1898 | nodelist: array,
1899 | "arguments": array,
1900 | object: function( map, stack ) {
1901 | var ret = [ ], keys, key, val, i;
1902 | QUnit.jsDump.up();
1903 | keys = [];
1904 | for ( key in map ) {
1905 | keys.push( key );
1906 | }
1907 | keys.sort();
1908 | for ( i = 0; i < keys.length; i++ ) {
1909 | key = keys[ i ];
1910 | val = map[ key ];
1911 | ret.push( QUnit.jsDump.parse( key, "key" ) + ": " + QUnit.jsDump.parse( val, undefined, stack ) );
1912 | }
1913 | QUnit.jsDump.down();
1914 | return join( "{", ret, "}" );
1915 | },
1916 | node: function( node ) {
1917 | var len, i, val,
1918 | open = QUnit.jsDump.HTML ? "<" : "<",
1919 | close = QUnit.jsDump.HTML ? ">" : ">",
1920 | tag = node.nodeName.toLowerCase(),
1921 | ret = open + tag,
1922 | attrs = node.attributes;
1923 |
1924 | if ( attrs ) {
1925 | for ( i = 0, len = attrs.length; i < len; i++ ) {
1926 | val = attrs[i].nodeValue;
1927 | // IE6 includes all attributes in .attributes, even ones not explicitly set.
1928 | // Those have values like undefined, null, 0, false, "" or "inherit".
1929 | if ( val && val !== "inherit" ) {
1930 | ret += " " + attrs[i].nodeName + "=" + QUnit.jsDump.parse( val, "attribute" );
1931 | }
1932 | }
1933 | }
1934 | ret += close;
1935 |
1936 | // Show content of TextNode or CDATASection
1937 | if ( node.nodeType === 3 || node.nodeType === 4 ) {
1938 | ret += node.nodeValue;
1939 | }
1940 |
1941 | return ret + open + "/" + tag + close;
1942 | },
1943 | // function calls it internally, it's the arguments part of the function
1944 | functionArgs: function( fn ) {
1945 | var args,
1946 | l = fn.length;
1947 |
1948 | if ( !l ) {
1949 | return "";
1950 | }
1951 |
1952 | args = new Array(l);
1953 | while ( l-- ) {
1954 | // 97 is 'a'
1955 | args[l] = String.fromCharCode(97+l);
1956 | }
1957 | return " " + args.join( ", " ) + " ";
1958 | },
1959 | // object calls it internally, the key part of an item in a map
1960 | key: quote,
1961 | // function calls it internally, it's the content of the function
1962 | functionCode: "[code]",
1963 | // node calls it internally, it's an html attribute value
1964 | attribute: quote,
1965 | string: quote,
1966 | date: quote,
1967 | regexp: literal,
1968 | number: literal,
1969 | "boolean": literal
1970 | },
1971 | // if true, entities are escaped ( <, >, \t, space and \n )
1972 | HTML: false,
1973 | // indentation unit
1974 | indentChar: " ",
1975 | // if true, items in a collection, are separated by a \n, else just a space.
1976 | multiline: true
1977 | };
1978 |
1979 | return jsDump;
1980 | }());
1981 |
1982 | // from jquery.js
1983 | function inArray( elem, array ) {
1984 | if ( array.indexOf ) {
1985 | return array.indexOf( elem );
1986 | }
1987 |
1988 | for ( var i = 0, length = array.length; i < length; i++ ) {
1989 | if ( array[ i ] === elem ) {
1990 | return i;
1991 | }
1992 | }
1993 |
1994 | return -1;
1995 | }
1996 |
1997 | /*
1998 | * Javascript Diff Algorithm
1999 | * By John Resig (http://ejohn.org/)
2000 | * Modified by Chu Alan "sprite"
2001 | *
2002 | * Released under the MIT license.
2003 | *
2004 | * More Info:
2005 | * http://ejohn.org/projects/javascript-diff-algorithm/
2006 | *
2007 | * Usage: QUnit.diff(expected, actual)
2008 | *
2009 | * QUnit.diff( "the quick brown fox jumped over", "the quick fox jumps over" ) == "the quick brown fox jumped jumps over"
2010 | */
2011 | QUnit.diff = (function() {
2012 | /*jshint eqeqeq:false, eqnull:true */
2013 | function diff( o, n ) {
2014 | var i,
2015 | ns = {},
2016 | os = {};
2017 |
2018 | for ( i = 0; i < n.length; i++ ) {
2019 | if ( !hasOwn.call( ns, n[i] ) ) {
2020 | ns[ n[i] ] = {
2021 | rows: [],
2022 | o: null
2023 | };
2024 | }
2025 | ns[ n[i] ].rows.push( i );
2026 | }
2027 |
2028 | for ( i = 0; i < o.length; i++ ) {
2029 | if ( !hasOwn.call( os, o[i] ) ) {
2030 | os[ o[i] ] = {
2031 | rows: [],
2032 | n: null
2033 | };
2034 | }
2035 | os[ o[i] ].rows.push( i );
2036 | }
2037 |
2038 | for ( i in ns ) {
2039 | if ( !hasOwn.call( ns, i ) ) {
2040 | continue;
2041 | }
2042 | if ( ns[i].rows.length === 1 && hasOwn.call( os, i ) && os[i].rows.length === 1 ) {
2043 | n[ ns[i].rows[0] ] = {
2044 | text: n[ ns[i].rows[0] ],
2045 | row: os[i].rows[0]
2046 | };
2047 | o[ os[i].rows[0] ] = {
2048 | text: o[ os[i].rows[0] ],
2049 | row: ns[i].rows[0]
2050 | };
2051 | }
2052 | }
2053 |
2054 | for ( i = 0; i < n.length - 1; i++ ) {
2055 | if ( n[i].text != null && n[ i + 1 ].text == null && n[i].row + 1 < o.length && o[ n[i].row + 1 ].text == null &&
2056 | n[ i + 1 ] == o[ n[i].row + 1 ] ) {
2057 |
2058 | n[ i + 1 ] = {
2059 | text: n[ i + 1 ],
2060 | row: n[i].row + 1
2061 | };
2062 | o[ n[i].row + 1 ] = {
2063 | text: o[ n[i].row + 1 ],
2064 | row: i + 1
2065 | };
2066 | }
2067 | }
2068 |
2069 | for ( i = n.length - 1; i > 0; i-- ) {
2070 | if ( n[i].text != null && n[ i - 1 ].text == null && n[i].row > 0 && o[ n[i].row - 1 ].text == null &&
2071 | n[ i - 1 ] == o[ n[i].row - 1 ]) {
2072 |
2073 | n[ i - 1 ] = {
2074 | text: n[ i - 1 ],
2075 | row: n[i].row - 1
2076 | };
2077 | o[ n[i].row - 1 ] = {
2078 | text: o[ n[i].row - 1 ],
2079 | row: i - 1
2080 | };
2081 | }
2082 | }
2083 |
2084 | return {
2085 | o: o,
2086 | n: n
2087 | };
2088 | }
2089 |
2090 | return function( o, n ) {
2091 | o = o.replace( /\s+$/, "" );
2092 | n = n.replace( /\s+$/, "" );
2093 |
2094 | var i, pre,
2095 | str = "",
2096 | out = diff( o === "" ? [] : o.split(/\s+/), n === "" ? [] : n.split(/\s+/) ),
2097 | oSpace = o.match(/\s+/g),
2098 | nSpace = n.match(/\s+/g);
2099 |
2100 | if ( oSpace == null ) {
2101 | oSpace = [ " " ];
2102 | }
2103 | else {
2104 | oSpace.push( " " );
2105 | }
2106 |
2107 | if ( nSpace == null ) {
2108 | nSpace = [ " " ];
2109 | }
2110 | else {
2111 | nSpace.push( " " );
2112 | }
2113 |
2114 | if ( out.n.length === 0 ) {
2115 | for ( i = 0; i < out.o.length; i++ ) {
2116 | str += "" + out.o[i] + oSpace[i] + "";
2117 | }
2118 | }
2119 | else {
2120 | if ( out.n[0].text == null ) {
2121 | for ( n = 0; n < out.o.length && out.o[n].text == null; n++ ) {
2122 | str += "" + out.o[n] + oSpace[n] + "";
2123 | }
2124 | }
2125 |
2126 | for ( i = 0; i < out.n.length; i++ ) {
2127 | if (out.n[i].text == null) {
2128 | str += "" + out.n[i] + nSpace[i] + "";
2129 | }
2130 | else {
2131 | // `pre` initialized at top of scope
2132 | pre = "";
2133 |
2134 | for ( n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++ ) {
2135 | pre += "" + out.o[n] + oSpace[n] + "";
2136 | }
2137 | str += " " + out.n[i].text + nSpace[i] + pre;
2138 | }
2139 | }
2140 | }
2141 |
2142 | return str;
2143 | };
2144 | }());
2145 |
2146 | // for CommonJS enviroments, export everything
2147 | if ( typeof exports !== "undefined" ) {
2148 | extend( exports, QUnit );
2149 | }
2150 |
2151 | // get at whatever the global object is, like window in browsers
2152 | }( (function() {return this;}.call()) ));
2153 |
--------------------------------------------------------------------------------