Permalink
Browse files

IndexedDB Polyfill. Intial diff

Summary: Most of implemented API are covered by tests.

Test Plan: QUnit tests. Open index.html in target browser.

Reviewers: sidd

CC: davidrecordon, achao, security-diffs@lists

Differential Revision: https://phabricator.fb.com/D504102
  • Loading branch information...
1 parent ac884e5 commit 09a10c4c5e7e18fdb4dbe3aa17081d66b302c2a0 Khamza Davletov committed Jun 26, 2012
Showing with 13,922 additions and 0 deletions.
  1. +150 −0 IDBCursor.js
  2. +152 −0 IDBDatabase.js
  3. +182 −0 IDBFactory.js
  4. +38 −0 IDBIndex.js
  5. +32 −0 IDBKeyRange.js
  6. +297 −0 IDBObjectStore.js
  7. +26 −0 IDBRequest.js
  8. +87 −0 IDBTransaction.js
  9. +14 −0 README
  10. +69 −0 index.html
  11. +96 −0 indexedDB.polyfill.js
  12. +9,404 −0 lib/jquery-1.7.2.js
  13. +236 −0 lib/qunit.css
  14. +1,863 −0 lib/qunit.js
  15. +128 −0 test/IDBCursorTests.js
  16. +174 −0 test/IDBDatabaseTests.js
  17. +189 −0 test/IDBFactoryTests.js
  18. +48 −0 test/IDBIndexTests.js
  19. +372 −0 test/IDBObjectStoreTests.js
  20. +131 −0 test/PerformanceTests.js
  21. +133 −0 test/TestUtils.js
  22. +101 −0 test/webkitIndexedDB.js
View
150 IDBCursor.js
@@ -0,0 +1,150 @@
+if (window.indexedDB.polyfill)
+(function(window, indexedDB, util, undefined)
+{
+ var IDBCursor = util.IDBCursor = window.IDBCursor = function (source, direction, request)
+ {
+ this.source = source;
+ this.direction = direction || IDBCursor.NEXT;
+ this.key = null;
+ this.primaryKey = null; // position, effective key
+
+ this._request = request;
+ this._range = null;
+ this._gotValue = true;
+ this._objectStorePosition = null; // used for indexes
+ };
+
+ IDBCursor.prototype.update = function (value)
+ {
+
+ };
+
+ IDBCursor.prototype.advance = function (count)
+ {
+
+ };
+
+ IDBCursor.prototype.continue = function (key)
+ {
+ if (!this._gotValue) throw util.exception("InvalidStateError");
+
+ var range = this._range;
+ var filter = util.IDBKeyRange.bound(range.lower, range.upper, range.lowerOpen, range.upperOpen);
+ if (key)
+ {
+ if (isAsc(this))
+ {
+ if (key <= this.primaryKey) throw util.exception("DataError");
+ filter.lower = key;
+ filter.lowerOpen = false;
+ }
+ else
+ {
+ if (key >= this.primaryKey) throw util.exception("DataError");
+ filter.upper = key;
+ filter.upperOpen = false;
+ }
+ }
+ else if (this.primaryKey)
+ {
+ if (isAsc(this))
+ {
+ filter.lower = this.primaryKey;
+ filter.lowerOpen = true;
+ }
+ else
+ {
+ filter.upper = this.primaryKey;
+ filter.upperOpen = true;
+ }
+ }
+ iterateCursor(this, filter);
+ this._gotValue = false;
+ };
+
+ IDBCursor.prototype.delete = function ()
+ {
+
+ };
+
+
+ // Internal methods
+ function iterateCursor(me, filter)
+ {
+ var tx = me.source.transaction;
+ me._request.readyState = util.IDBRequest.LOADING;
+ tx._enqueueRequest(function (sqlTx, nextRequestCallback)
+ {
+ var sql = ["SELECT key, value FROM \"" + me.source.name + "\" WHERE (0 = 0)"];
+ var args = [];
+ if (filter.lower)
+ {
+ sql.push("AND (key >" + (filter.lowerOpen ? "" : "="), "?)");
+ args.push(w_JSON.stringify(filter.lower));
+ }
+ if (filter.upper)
+ {
+ sql.push("AND (key <" + (filter.upperOpen ? "" : "="), "?)");
+ args.push(w_JSON.stringify(filter.upper));
+ }
+
+ sql.push("ORDER BY key");
+ if (!isAsc(me)) sql.push("DESC");
+ sql.push("LIMIT 1");
+
+ sqlTx.executeSql(sql.join(" "), args,
+ function (tx, results)
+ {
+ var request = me._request;
+ request.readyState = util.IDBRequest.DONE;
+ if (results.rows.length == 0)
+ {
+ me.key = me.primaryKey = undefined;
+ if (typeof me.value !== "undefined") me.value = undefined;
+ request.result = null;
+ }
+ else
+ {
+ var found = found = results.rows.item(0);
+ me.key = me.primaryKey = w_JSON.parse(found.key);
+ if (typeof me.value !== "undefined") me.value = w_JSON.parse(found.value);
+ me._gotValue = true;
+ request.result = me;
+ }
+ if (request.onsuccess) request.onsuccess(util.event("success", request));
+ nextRequestCallback();
+ },
+ function (tx, sqlError)
+ {
+ var request = m._request;
+ request.error = sqlError;
+ if (request.onerror) request.onerror(util.event("error", request));
+ nextRequestCallback();
+ });
+ });
+ }
+
+ // Utils
+ var w_JSON = window.JSON;
+
+ function isAsc(cursor)
+ {
+ return [IDBCursor.NEXT, IDBCursor.NEXT_NO_DUPLICATE].indexOf(cursor.direction) >= 0;
+ }
+
+
+ IDBCursor.NEXT = "next";
+ IDBCursor.NEXT_NO_DUPLICATE = "nextunique";
+ IDBCursor.PREV = "prev";
+ IDBCursor.PREV_NO_DUPLICATE = "prevunique";
+
+ var IDBCursorWithValue = function (source, direction, request)
+ {
+ IDBCursor.apply(this, arguments);
+ this.value = null;
+ };
+ IDBCursorWithValue.prototype = new IDBCursor();
+ IDBCursorWithValue.prototype.constructor = IDBCursorWithValue;
+ util.IDBCursorWithValue = window.IDBCursorWithValue = IDBCursorWithValue;
+
+}(window, window.indexedDB, window.indexedDB.util));
View
152 IDBDatabase.js
@@ -0,0 +1,152 @@
+if (window.indexedDB.polyfill)
+(function(window, indexedDB, util, undefined)
+{
+ var IDBDatabase = util.IDBDatabase = window.IDBDatabase = function (name, webdb)
+ {
+ this.name = name;
+ this.version = null;
+ this.objectStoreNames = new indexedDB.DOMStringList();
+ this.onabort = null;
+ this.onerror = null;
+ this.onversionchange = null
+
+ this._webdb = webdb;
+ this._objectStores = null;
+ };
+
+ IDBDatabase.prototype.createObjectStore = function (name, optionalParameters)
+ {
+ validateVersionChangeTx(this._versionChangeTx);
+
+ // Validate existence of ObjectStore
+ if (this.objectStoreNames.indexOf(name) >= 0)
+ {
+ throw util.error("ConstraintError");
+ }
+
+ var op = optionalParameters || { };
+ var keyPath = op.keyPath || null;
+ var autoIncrement = op.autoIncrement && op.autoIncrement != false || false;
+ if (autoIncrement && (keyPath == "" || (keyPath instanceof Array)))
+ {
+ throw util.error("InvalidAccessError");
+ }
+ if (keyPath != null) keyPath = validateKeyPath(keyPath);
+
+ return createObjectStore(this, name, keyPath, autoIncrement);
+ };
+
+ IDBDatabase.prototype.deleteObjectStore = function (name)
+ {
+ validateVersionChangeTx(this._versionChangeTx);
+ if (this.objectStoreNames.indexOf(name) == -1)
+ {
+ throw util.error("NotFoundError");
+ }
+ var i = this.objectStoreNames.indexOf(name);
+ if (i > -1) this.objectStoreNames.splice(i, 1);
+ var me = this;
+ this._versionChangeTx._enqueueRequest(function (sqlTx, nextRequestCallback)
+ {
+ sqlTx.executeSql("DROP TABLE \"" + name + "\"", [], null,
+ function (tx, sqlError) { me.objectStoreNames.push(name); }
+ );
+ sqlTx.executeSql("DELETE FROM " + indexedDB.SCHEMA_TABLE + " WHERE type = 'table' AND name = ?", [name]);
+ nextRequestCallback();
+ });
+ };
+
+ IDBDatabase.prototype.transaction = function (storeNames, mode)
+ {
+ return new util.IDBTransaction(this, storeNames, mode || util.IDBTransaction.READ_ONLY);
+ };
+
+ IDBDatabase.prototype.close = function ()
+ {
+ return null;
+ };
+
+ IDBDatabase.prototype._loadObjectStores = function (sqlTx, successCallback, errorCallback)
+ {
+ var me = this;
+ sqlTx.executeSql("SELECT name, keyPath, autoInc FROM " + indexedDB.SCHEMA_TABLE +
+ " WHERE type='table'", null,
+ function (sqlTx, resultSet)
+ {
+ me._objectStores = { };
+ var item = null;
+ for (var i = 0; i < resultSet.rows.length; i++)
+ {
+ var item = resultSet.rows.item(i);
+
+ me.objectStoreNames.push(item.name);
+ me._objectStores[item.name] = new util.IDBObjectStore(
+ item.name, w_JSON.parse(item.keyPath), item.autoInc);
+ }
+ if (successCallback) successCallback();
+ },
+ function (sqlTx, sqlError)
+ {
+ if (errorCallback) errorCallback(sqlError);
+ });
+ }
+
+ // Utils
+ var w_JSON = window.JSON;
+
+ function validateVersionChangeTx(tx)
+ {
+ if (!tx || tx.mode !== util.IDBTransaction.VERSION_CHANGE)
+ {
+ throw util.error("InvalidStateError");
+ }
+ }
+
+ function validateKeyPath(keyPath)
+ {
+ if (keyPath === "") return "";
+
+ var r = /^([^\d\W]\w*\.)+$/i;
+ if (keyPath instanceof Array)
+ {
+ var i = keyPath.length;
+ if (i == 0) throw util.error("SyntaxError");
+
+ while (i--)
+ {
+ if (!r.test(keyPath[i] + ".")) throw util.error("SyntaxError");
+ }
+ return keyPath;
+ }
+ if (!r.test(keyPath + ".")) throw util.error("SyntaxError");
+ return keyPath;
+ }
+
+ function createObjectStore(me, name, keyPath, autoIncrement)
+ {
+ var objectStore = new util.IDBObjectStore(name, keyPath, autoIncrement, me._versionChangeTx);
+ me._objectStores[name] = objectStore;
+ me.objectStoreNames.push(name);
+ me._versionChangeTx._enqueueRequest(function (sqlTx, nextRequestCallback)
+ {
+ sqlTx.executeSql("CREATE TABLE \"" + name + "\" (id INTEGER PRIMARY KEY AUTOINCREMENT, " +
+ "key TEXT, value BLOB)", [], null,
+ function (tx, sqlError)
+ {
+ var i = me.objectStoreNames.indexOf(name);
+ if (i > -1) me.objectStoreNames.splice(i, 1);
+
+ delete me._objectStores[name];
+ }
+ );
+ sqlTx.executeSql("CREATE INDEX Index_" + name + "_key ON \"" + name + "\" (key)");
+
+ sqlTx.executeSql("INSERT INTO " + indexedDB.SCHEMA_TABLE +
+ " (type, name, keyPath, autoInc) VALUES ('table', ?, ?, ?)",
+ [name, w_JSON.stringify(keyPath), autoIncrement ? 1 : 0]);
+ nextRequestCallback();
+ });
+ return objectStore;
+ }
+
+}(window, window.indexedDB, window.indexedDB.util));
View
182 IDBFactory.js
@@ -0,0 +1,182 @@
+if (window.indexedDB.polyfill)
+(function(window, indexedDB, util, undefined)
+{
+ indexedDB.open = function (name, version)
+ {
+ if (version !== undefined)
+ {
+ version = parseInt(version);
+ if (isNaN(version) || version <= 0) throw util.exception("Invalid version");
+ }
+ var request = new util.IDBOpenDBRequest();
+ request.source = null;
+ request.readyState = util.IDBRequest.LOADING;
+ util.async(function ()
+ {
+ request.readyState = util.IDBRequest.DONE;
+ runStepsForOpeningDB(name, version, request);
+ });
+ return request;
+ };
+
+ function runStepsForOpeningDB(name, version, request)
+ {
+ var sqldb = openSqlDB(name);
+ if (sqldb.version !== "" && isNaN(parseInt(sqldb.version))) // sqldb.version is corrupt
+ {
+ request.errorCode = util.IDBDatabaseException.VERSION_ERR;
+ if (request.onerror) request.onerror(util.event("error", request));
+ return;
+ }
+ var db = new util.IDBDatabase(name, sqldb);
+ var sqldbVersion = sqldb.version == "" ? 0 : parseInt(sqldb.version);
+ db.version = (version === undefined) ?
+ (sqldbVersion === 0 ? 1 : sqldbVersion) :
+ version;
+
+ if (sqldbVersion < db.version)
+ {
+ openLowerVersion(request, db, sqldbVersion);
+ }
+ else if (sqldbVersion == db.version)
+ {
+ openVersionMatch(request, db, sqldb);
+ }
+ else
+ {
+ request.error = util.error("VersionError");
+ if (request.onerror) request.onerror(util.event("error", request));
+ }
+ }
+
+ function openLowerVersion(request, db, sqldbVersion)
+ {
+ var tx = new util.IDBTransaction(db, [], util.IDBTransaction.VERSION_CHANGE);
+ tx._enqueueRequest(function (sqlTx, nextRequestCallback)
+ {
+ request.transaction = db._versionChangeTx = tx;
+ if (sqldbVersion == 0)
+ {
+ sqlTx.executeSql("CREATE TABLE '" + indexedDB.SCHEMA_TABLE + "' (" +
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
+ "type TEXT NOT NULL, " +
+ "name TEXT NOT NULL, " +
+ "keyPath TEXT, " +
+ "autoInc BOOLEAN, " +
+ "currentNo INTEGER NOT NULL DEFAULT 1, " +
+ "UNIQUE (type, name) ON CONFLICT ROLLBACK)");
+ }
+ db._loadObjectStores(sqlTx,
+ function ()
+ {
+ request.result = db;
+ if (request.onupgradeneeded)
+ {
+ var e = util.event("onupgradeneeded", request);
+ e.oldVersion = sqldbVersion;
+ e.newVersion = db.version;
+ request.onupgradeneeded(e);
+ }
+ nextRequestCallback();
+ },
+ function (sqlError)
+ {
+ console.log(sqlError);
+ nextRequestCallback();
+ });
+ });
+ tx.onerror = function (e)
+ {
+ // NOTE: All create/deleteObjectStore errors handled here, hence no need for
+ // unnecessary generic handlers for each.
+ request.transaction = db._versionChangeTx = null;
+ request.error = tx.error;
+ if (request.onerror) request.onerror(util.event("error", request));
+ };
+ tx.oncomplete = function (e)
+ {
+ request.transaction = db._versionChangeTx = null;
+ if (request.onsuccess) request.onsuccess(util.event("success", request));
+ };
+ }
+
+ function openVersionMatch(request, db, sqldb)
+ {
+ sqldb.transaction(
+ function (sqlTx)
+ {
+ db._loadObjectStores(sqlTx);
+ },
+ function (sqlError)
+ {
+ request.error = sqlError;
+ if (request.onerror) request.onerror(util.event("error", request));
+ },
+ function ()
+ {
+ request.result = db;
+ if (request.onsuccess) request.onsuccess(util.event("success", request));
+ }
+ );
+ }
+
+ // IDBFactory.deleteDatabase
+ indexedDB.deleteDatabase = function (name)
+ {
+ // INFO: There is no way to delete database in Web SQL Database API.
+ var request = new util.IDBOpenDBRequest();
+ request.readyState = util.IDBRequest.LOADING;
+ indexedDB.util.async(function()
+ {
+ request.readyState = util.IDBRequest.DONE;
+ var sqldb = openSqlDB(name);
+ if (sqldb.version == "")
+ {
+ if (request.onsuccess) request.onsuccess(null);
+ }
+ else
+ {
+ sqldb.changeVersion(sqldb.version, "",
+ function (tx)
+ {
+ tx.executeSql("SELECT name FROM '" + indexedDB.SCHEMA_TABLE +"'", null,
+ function (tx, results)
+ {
+ var i;
+ for (i = 0; i < results.rows.length; i++)
+ {
+ tx.executeSql("DROP TABLE \"" + results.rows.item(i).name + "\"");
+ }
+ tx.executeSql("DROP TABLE '" + indexedDB.SCHEMA_TABLE + "'");
+ });
+ },
+ function (e)
+ {
+ if (request.onerror) request.onerror(e);
+ },
+ function ()
+ {
+ if (request.onsuccess) request.onsuccess(null);
+ });
+ };
+ });
+ return request;
+ };
+
+ // IDBFactory.cmp
+ indexedDB.cmp = function (first, second)
+ {
+ // TODO: Compare according to doc
+ return first > second ? 1 : (first == second ? 0 : -1);
+ }
+
+ // Utils
+ function openSqlDB(name)
+ {
+ return window.openDatabase(
+ indexedDB.DB_PREFIX + name, "",
+ indexedDB.DB_DESCRIPTION + name,
+ indexedDB.DEFAULT_DB_SIZE);
+ }
+
+}(window, window.indexedDB, window.indexedDB.util));
View
38 IDBIndex.js
@@ -0,0 +1,38 @@
+if (window.indexedDB.polyfill)
+(function(window, indexedDB, util, undefined)
+{
+ var IDBIndex = util.IDBIndex = window.IDBIndex = function(source)
+ {
+ this.name = null;
+ this.objectStore = null;
+ this.keyPath = null;
+ this.multiEntry = null;
+ this.unique = null;
+ };
+
+ IDBIndex.prototype.openCursor = function (range, direction)
+ {
+
+ }
+
+ IDBIndex.prototype.openKeyCursor = function (range, direction)
+ {
+
+ }
+
+ IDBIndex.prototype.get = function (key)
+ {
+
+ }
+
+ IDBIndex.prototype.getKey = function (key)
+ {
+
+ }
+
+ IDBIndex.prototype.count = function (key)
+ {
+
+ }
+
+}(window, window.indexedDB, window.indexedDB.util));
View
32 IDBKeyRange.js
@@ -0,0 +1,32 @@
+if (window.indexedDB.polyfill)
+(function(window, util, undefined)
+{
+ var IDBKeyRange = util.IDBKeyRange = window.IDBKeyRange = function (lower, upper, lowerOpen, upperOpen)
+ {
+ this.lower = lower;
+ this.upper = upper;
+ this.lowerOpen = lowerOpen || false;
+ this.upperOpen = upperOpen || false;
+ };
+
+ IDBKeyRange.only = function (value)
+ {
+ return new IDBKeyRange(value, value, false, false)
+ };
+
+ IDBKeyRange.lowerBound = function (lower, open)
+ {
+ return new IDBKeyRange(lower, undefined, open || false, true);
+ };
+
+ IDBKeyRange.upperBound = function (upper, open)
+ {
+ return new IDBKeyRange(undefined, upper, true, open || false);
+ };
+
+ IDBKeyRange.bound = function (lower, upper, lowerOpen, upperOpen)
+ {
+ return new IDBKeyRange(lower, upper, lowerOpen || false, upperOpen || false);
+ };
+
+}(window, window.indexedDB.util));
View
297 IDBObjectStore.js
@@ -0,0 +1,297 @@
+if (window.indexedDB.polyfill)
+(function (window, indexedDB, util, undefined)
+{
+ var IDBObjectStore = util.IDBObjectStore = window.IDBObjectStore = function (name, keyPath, autoIncrement, tx)
+ {
+ this.name = name;
+ this.keyPath = keyPath;
+ this.indexNames = new indexedDB.DOMStringList();
+ this.transaction = tx;
+ this.autoIncrement = autoIncrement == true;
+ };
+
+ IDBObjectStore.prototype.put = function (value, key)
+ {
+ return storeRecord(this, value, key, false);
+ };
+
+ IDBObjectStore.prototype.add = function (value, key)
+ {
+ return storeRecord(this, value, key, true);
+ };
+
+ //region add & put helper functions
+ function storeRecord(me, value, key, noOverwrite)
+ {
+ assertReadOnly(me.transaction);
+
+ var validation = validateKey(me, value, key);
+ var key = validation.key, strKey = validation.str;
+
+ var request = new util.IDBRequest();
+ request.readyState = util.IDBRequest.LOADING;
+ request.source = me;
+ me.transaction._enqueueRequest(function (sqlTx, nextRequestCallback)
+ {
+ runStepsForStoringRecord(request, sqlTx, nextRequestCallback, noOverwrite, value, key, strKey);
+ });
+ return request;
+ }
+
+ function validateKey(me, value, key)
+ {
+ var key = key, str;
+ if (me.keyPath != null)
+ {
+ if (key != null) throw util.error("DataError");
+
+ key = extractKeyFromValue(value, me.keyPath);
+ }
+ if (key == null)
+ {
+ if (!me.autoIncrement) throw util.error("DataError");
+ }
+ else
+ {
+ // NOTE: key validation
+ str = w_JSON.stringify(key);
+ if (typeof key == "boolean") throw util.error("DataError");
+
+ if ((/[,[]{.*?}[,\]]/).test(str) ||
+ (/^{.*?}$/).test(str) ||
+ (/[,[](true|false)[,\]]/).test(str)) throw util.error("DataError");
+ }
+ return { key : key, str : str };
+ }
+
+ function extractKeyFromValue(value, keyPath)
+ {
+ var key;
+ if (keyPath instanceof Array)
+ {
+ key = [];
+ for (var i = 0; i < keyPath.length; i++)
+ {
+ key.push(extractKeyFromValue(value, keyPath[i]));
+ }
+ }
+ else
+ {
+ if (keyPath === "") return value;
+
+ key = value;
+ var paths = keyPath.split(".");
+ for (var i = 0; i < paths.length; i++)
+ {
+ if (key == null) return null;
+ key = key[paths[i]];
+ }
+ }
+ return key;
+ }
+
+
+ function runStepsForStoringRecord(request, sqlTx, nextRequestCallback, noOverwrite, value, key, strKey)
+ {
+ var me = request.source;
+ request.readyState = util.IDBRequest.DONE;
+ if (me.autoIncrement && (key == null || isPositiveFloat(key)))
+ {
+ sqlTx.executeSql("SELECT currentNo FROM " + indexedDB.SCHEMA_TABLE +
+ " WHERE type='table' AND name = ?", [me.name],
+ function (sqlTx, resultSet)
+ {
+ if (resultSet.rows.length != 1)
+ {
+ // error
+ }
+ var currentNo = resultSet.rows.item(0).currentNo;
+ if (key == null)
+ {
+ key = currentNo;
+ strKey = key.toString();
+ if (me.keyPath != null)
+ {
+ assignKeyToValue(value, me.keyPath, key);
+ }
+ }
+ if (key >= currentNo)
+ {
+ incrementCurrentNumber(sqlTx, me.name, Math.floor(key + 1));
+ }
+ sqlInsertKeyValue(request, sqlTx, nextRequestCallback, noOverwrite, strKey, value);
+ },
+ function (tx, sqlError)
+ {
+ // error
+ });
+ }
+ else
+ {
+ sqlInsertKeyValue(request, sqlTx, nextRequestCallback, noOverwrite, strKey, value);
+ }
+ }
+
+ function incrementCurrentNumber(sqlTx, tableName, currentNo)
+ {
+ sqlTx.executeSql("UPDATE " + indexedDB.SCHEMA_TABLE + " SET currentNo = ? " +
+ "WHERE type='table' AND name = ?", [currentNo, tableName],
+ function (sqlTx, resultSet)
+ {
+ if (resultSet.rowsAffected != 1)
+ {
+ // TODO: error
+ }
+ },
+ function (tx, sqlError)
+ {
+ // TODO: error
+ });
+ }
+
+ function sqlInsertKeyValue(request, sqlTx, nextRequestCallback, noOverwrite, strKey, value)
+ {
+ var tableName = request.source.name;
+ var sql = (noOverwrite ? "INSERT" : "REPLACE") + " INTO \"" + tableName + "\" (key, value) VALUES (?, ?)";
+ var strValue = w_JSON.stringify(value);
+ sqlTx.executeSql(sql, [strKey, strValue],
+ function (tx, resultSet)
+ {
+ if (request.onsuccess) request.onsuccess(util.event("success", request));
+ nextRequestCallback();
+ },
+ function (tx, sqlError)
+ {
+ request.error = sqlError;
+ if (request.onerror) request.onerror(util.event("error", request));
+ nextRequestCallback();
+ });
+ }
+
+ function assignKeyToValue(value, keyPath, key)
+ {
+ if (!(value instanceof Object) && !(value instanceof Array)) throw util.error("DataError");
+
+ var path = keyPath.split(".");
+ var attr = null;
+ for (var i = 0; i < path.length - 1; i++)
+ {
+ attr = path[i];
+ if (value[attr] == null) value[attr] = { };
+ value = value[attr];
+ }
+ value[path[path.length - 1]] = key;
+
+ }
+ //endregion
+
+ IDBObjectStore.prototype.delete = function (key)
+ {
+ assertReadOnly(this.transaction);
+
+ var request = new util.IDBRequest();
+ request.source = this;
+ var me = this;
+ this.transaction._enqueueRequest(function (sqlTx, nextRequestCallback)
+ {
+ var strKey = w_JSON.stringify(key);
+ sqlTx.executeSql("DELETE FROM \"" + me.name + "\" WHERE key = ?", [strKey],
+ function (tx, resultSet)
+ {
+ if (request.onsuccess) request.onsuccess(util.event("success", request));
+ nextRequestCallback();
+ },
+ function (tx, sqlError)
+ {
+ if (request.onerror) request.onerror(sqlError);
+ nextRequestCallback();
+ });
+ });
+ return request;
+ };
+
+ IDBObjectStore.prototype.get = function (key)
+ {
+ var request = new util.IDBRequest();
+ var me = this;
+ request.source = me;
+ me.transaction._enqueueRequest(function (sqlTx, nextRequestCallback)
+ {
+ var strKey = w_JSON.stringify(key);
+ sqlTx.executeSql("SELECT value FROM \"" + me.name + "\" WHERE key = ?", [strKey],
+ function (tx, resultSet)
+ {
+ if (resultSet.rows.length > 0)
+ {
+ var strValue = resultSet.rows.item(0).value;
+ request.result = w_JSON.parse(strValue);
+ }
+ if (request.onsuccess) request.onsuccess(util.event("success", request));
+ nextRequestCallback();
+ },
+ function (tx, sqlError)
+ {
+ request.error = sqlError;
+ if (request.onerror) request.onerror(util.event("error", request));
+ nextRequestCallback();
+ });
+ });
+ return request;
+ };
+
+ IDBObjectStore.prototype.clear = function ()
+ {
+ };
+
+ IDBObjectStore.prototype.openCursor = function (range, direction)
+ {
+ var request = new util.IDBRequest(this);
+ request.readyState = util.IDBRequest.LOADING;
+ var cursor = new util.IDBCursorWithValue(this, direction, request);
+
+ if (range == null)
+ {
+ range = util.IDBKeyRange.bound();
+ }
+ else if (!(range instanceof util.IDBKeyRange))
+ {
+ range = util.IDBKeyRange.only(range);
+ }
+ cursor._range = range;
+ cursor.continue();
+ return request;
+ };
+
+ IDBObjectStore.prototype.createIndex = function (name, keyPath, optionalParameters)
+ {
+ };
+
+ IDBObjectStore.prototype.index = function (name)
+ {
+ };
+
+ IDBObjectStore.prototype.deleteIndex = function (indexName)
+ {
+ };
+
+ IDBObjectStore.prototype.count = function (key)
+ {
+ };
+
+ // Utils
+ var w_JSON = window.JSON;
+
+ function assertReadOnly(tx)
+ {
+ if (tx.mode === util.IDBTransaction.READ_ONLY)
+ {
+ throw util.error("ReadOnlyError", "A mutation operation was attempted in a READ_ONLY transaction.");
+ }
+ }
+
+ function isPositiveFloat(value)
+ {
+ return typeof value == "number" && value > 0;
+ }
+
+}(window, window.indexedDB, window.indexedDB.util));
View
26 IDBRequest.js
@@ -0,0 +1,26 @@
+if (window.indexedDB.polyfill)
+(function(window, indexedDB, util, undefined)
+{
+ var IDBRequest = util.IDBRequest = window.IDBRequest = function(source)
+ {
+ this.result = null;
+ this.error = null;
+ this.source = source;
+ this.transaction = null;
+ this.readyState = null;
+ this.onsuccess = null;
+ this.onerror = null;
+ };
+ IDBRequest.LOADING = "pending";
+ IDBRequest.DONE = "done";
+
+ var IDBOpenDBRequest = util.IDBOpenDBRequest = window.IDBOpenDBRequest = function(source)
+ {
+ IDBRequest.call(this, arguments);
+ this.onblocked = null;
+ this.onupgradeneeded = null;
+ };
+ IDBOpenDBRequest.prototype = new IDBRequest();
+ IDBOpenDBRequest.prototype.constructor = IDBOpenDBRequest;
+
+}(window, window.indexedDB, window.indexedDB.util));
View
87 IDBTransaction.js
@@ -0,0 +1,87 @@
+if (window.indexedDB.polyfill)
+(function(window, util, undefined)
+{
+ var IDBTransaction = util.IDBTransaction = window.IDBTransaction = function(db, storeNames, mode)
+ {
+ this.db = db;
+ this.mode = mode;
+ this.onabort = null;
+ this.oncomplete = null;
+ this.onerror = null;
+
+ this._active = true;
+ this._requests = [];
+ var sqldb = this.db._webdb;
+
+ // Main
+ var txFn;
+ if (mode === IDBTransaction.READ_ONLY) txFn = sqldb.readTransaction;
+ else if (mode === IDBTransaction.READ_WRITE) txFn = sqldb.transaction;
+ else if (mode === IDBTransaction.VERSION_CHANGE)
+ {
+ txFn = function (x, y, z) { sqldb.changeVersion(sqldb.version, db.version, x, y, z); };
+ }
+
+ var me = this;
+ txFn && txFn.call(sqldb,
+ function (sqlTx) {
+ performOperation(me, sqlTx, 0); },
+ function (sqlError) {
+ me.error = sqlError;
+ if (me.onerror) me.onerror(util.event("error", me)); },
+ function () {
+ if (me.oncomplete) me.oncomplete(util.event("success", me)); });
+ };
+
+ function performOperation(me, sqlTx, operationIndex)
+ {
+ if (operationIndex >= me._requests.length)
+ {
+ me._active = false;
+ me._requests = [];
+ for (prop in me.db._objectStores)
+ {
+ me.db._objectStores[prop].transaction = null;
+ }
+ return;
+ }
+
+ operation = me._requests[operationIndex];
+ operation(sqlTx, function ()
+ {
+ performOperation(me, sqlTx, operationIndex + 1);
+ });
+ }
+
+ IDBTransaction.prototype.objectStore = function (name)
+ {
+ validateActive(this);
+ var objectStore = this.db._objectStores[name];
+ if (objectStore)
+ {
+ objectStore.transaction = this;
+ return objectStore;
+ }
+ else
+ {
+ throw util.error("NotFoundError");
+ }
+ };
+
+ IDBTransaction.prototype._enqueueRequest = function (sqlTxCallback)
+ {
+ validateActive(this);
+ this._requests.push(sqlTxCallback);
+ };
+
+ IDBTransaction.READ_ONLY = "readonly";
+ IDBTransaction.READ_WRITE = "readwrite";
+ IDBTransaction.VERSION_CHANGE = "versionchange";
+
+ // Utils
+ function validateActive(me)
+ {
+ if (!me._active) throw new util.error("TransactionInactiveError");
+ }
+
+}(window, window.indexedDB.util));
View
14 README
@@ -0,0 +1,14 @@
+README
+
+A. Unit Test.
+
+To run unit tests open index.html in target browser. To verify unit tests against Firefox's native implementation of
+IndexedDB API, open the same page through web (http) server. Because, otherwise Firefox does not let to create
+IndexedDB databases under localhost origin.
+
+Tests sometimes may fail due to their incompleteness in development. Particularly, QUnit's execution of asynchronous
+code needs to be wrapped by stop-start sign posts correctly and there must be one-to-one correspondence between all
+'stops' and 'starts' in the code. However, sometimes it is not easy to foresee which async code get executed at the
+very end, 'start' command may be executed too early leaving other async code with unit tests to be left out of a
+test scope. This results test failures also affects to subsequent tests with outcomes like databases left unclosed
+or current test's 'stop' stops the 'start' from previous unsuccessful test, thus leaving current closing 'start' without a match.
View
69 index.html
@@ -0,0 +1,69 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="utf-8" />
+
+ <!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame
+ Remove this if you use the .htaccess -->
+ <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
+
+ <title>page</title>
+ <meta name="description" content="" />
+ <meta name="author" content="khamza" />
+
+ <!-- Replace favicon.ico & apple-touch-icon.png in the root of your domain and delete these references -->
+ <link rel="shortcut icon" href="/favicon.ico" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="stylesheet" href="lib/qunit.css" />
+ <script src="lib/jquery-1.7.2.js"></script>
+ <script type="text/javascript" src="lib/qunit.js"></script>
+
+ <script type="text/javascript">
+ if (!$.browser.mozilla)
+ {
+ window.indexedDB = { polyfill : true };
+ }
+ </script>
+
+ <script type="text/javascript" src="indexedDB.polyfill.js"></script>
+ <script type="text/javascript" src="test/webkitIndexedDB.js"></script>
+ <script type="text/javascript" src="IDBRequest.js"></script>
+ <script type="text/javascript" src="IDBFactory.js"></script>
+ <script type="text/javascript" src="IDBDatabase.js"></script>
+ <script type="text/javascript" src="IDBTransaction.js"></script>
+ <script type="text/javascript" src="IDBObjectStore.js"></script>
+ <script type="text/javascript" src="IDBCursor.js"></script>
+ <script type="text/javascript" src="IDBKeyRange.js"></script>
+ <script type="text/javascript" src="IDBIndex.js"></script>
+
+ <script type="text/javascript" src="test/TestUtils.js"></script>
+ <script type="text/javascript" src="test/IDBFactoryTests.js"></script>
+ <script type="text/javascript" src="test/IDBDatabaseTests.js"></script>
+ <script type="text/javascript" src="test/IDBObjectStoreTests.js"></script>
+ <script type="text/javascript" src="test/IDBCursorTests.js"></script>
+ <script type="text/javascript" src="test/IDBIndexTests.js"></script>
+ <script type="text/javascript" src="test/PerformanceTests.js"></script>
+
+</head>
+
+<body>
+
+<h1 id="qunit-header">QUnit example</h1>
+<h2 id="qunit-banner"></h2>
+<div id="qunit-testrunner-toolbar"></div>
+<h2 id="qunit-userAgent"></h2>
+<ol id="qunit-tests"></ol>
+<div id="qunit-fixture">test markup, will be hidden</div>
+
+<script type="text/javascript">
+
+ //PerformanceTests.run();
+
+ IDBFactoryTests.run();
+ IDBDatabaseTests.run();
+ IDBObjectStoreTests.run();
+ IDBCursorTests.run();
+
+</script>
+</body>
+</html>
View
96 indexedDB.polyfill.js
@@ -0,0 +1,96 @@
+(function(window, undefined)
+{
+ var indexedDB = window.indexedDB = window.indexedDB || window.mozIndexedDB ||
+ window.webkitIndexedDB || window.msIndexedDB || { polyfill : true };
+
+ window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction;
+ window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange;
+ window.IDBCursor = window.IDBCursor || window.webkitIDBCursor;
+
+ if (!indexedDB.polyfill) return;
+
+ console.warn('This browser most likely does not support IndexedDB technology. Initialing custom IndexedDB' +
+ ' implementation using Web SQL Database technology.');
+
+
+ // Configuration
+ indexedDB.SCHEMA_TABLE = "__IndexedDBSchemaInfo__";
+ indexedDB.INDEXEDDB_METADATA_CURRENT_VERSION = "v1.0";
+ indexedDB.DB_PREFIX = "__INDEXEDDB__";
+ indexedDB.DB_DESCRIPTION = "IndexedDB ";
+ indexedDB.DEFAULT_DB_SIZE = 5 * 1024 * 1024;
+ indexedDB.CURSOR_CHUNK_SIZE = 10;
+
+ // Data types
+ indexedDB.DOMStringList = function () { };
+ indexedDB.DOMStringList.prototype = [];
+ indexedDB.DOMStringList.constructor = indexedDB.DOMStringList;
+ indexedDB.DOMStringList.prototype.contains = function (str)
+ {
+ return this.indexOf(str) >= 0;
+ };
+
+
+ indexedDB.util =
+ {
+ async : function (fn) { w_setTimeout(fn, 0); },
+
+ exception : function (type, message, innerException)
+ {
+ var result = new w_Error(message);
+ result.type = type;
+ result.inner = innerException;
+ return result;
+ },
+
+ error : function (name, message, inner)
+ {
+ return {
+ name : name,
+ message : message,
+ inner : inner
+ }
+ },
+
+ event : function (type, target)
+ {
+ return {
+ type : type,
+ target : target,
+ currentTarget : target,
+ preventDefault : function () { }
+ };
+ }
+ };
+
+ /*
+ IDBVersionChangeEvent.prototype = new Event(null);
+ IDBVersionChangeEvent.prototype.constructor = IDBVersionChangeEvent;
+ function IDBVersionChangeEvent ()
+ {
+ this.oldVersoin = null;
+ this.newVersion = null;
+ }
+ */
+
+ var IDBDatabaseException = window.IDBDatabaseException =
+ {
+ ABORT_ERR : 8,
+ CONSTRAINT_ERR : 4,
+ DATA_ERR : 5,
+ NON_TRANSIENT_ERR : 2,
+ NOT_ALLOWED_ERR : 6,
+ NOT_FOUND_ERR : 3,
+ QUOTA_ERR : 11,
+ READ_ONLY_ERR : 9,
+ TIMEOUT_ERR : 10,
+ TRANSACTION_INACTIVE_ERR : 7,
+ UNKNOWN_ERR : 1,
+ VERSION_ERR : 12
+ };
+
+ // Cached
+ var w_Error = window.Error;
+ var w_setTimeout = window.setTimeout;
+
+}(window));
View
9,404 lib/jquery-1.7.2.js
9,404 additions, 0 deletions not shown because the diff is too large. Please use a local Git client to view these changes.
View
236 lib/qunit.css
@@ -0,0 +1,236 @@
+/**
+ * QUnit v1.9.0pre - A JavaScript Unit Testing Framework
+ *
+ * http://docs.jquery.com/QUnit
+ *
+ * Copyright (c) 2012 John Resig, Jörn Zaefferer
+ * Dual licensed under the MIT (MIT-LICENSE.txt)
+ * or GPL (GPL-LICENSE.txt) licenses.
+ */
+
+/** Font Family and Sizes */
+
+#qunit-tests, #qunit-header, #qunit-banner, #qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult {
+ font-family: "Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial, sans-serif;
+}
+
+#qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult, #qunit-tests li { font-size: small; }
+#qunit-tests { font-size: smaller; }
+
+
+/** Resets */
+
+#qunit-tests, #qunit-tests ol, #qunit-header, #qunit-banner, #qunit-userAgent, #qunit-testresult {
+ margin: 0;
+ padding: 0;
+}
+
+
+/** Header */
+
+#qunit-header {
+ padding: 0.5em 0 0.5em 1em;
+
+ color: #8699a4;
+ background-color: #0d3349;
+
+ font-size: 1.5em;
+ line-height: 1em;
+ font-weight: normal;
+
+ border-radius: 15px 15px 0 0;
+ -moz-border-radius: 15px 15px 0 0;
+ -webkit-border-top-right-radius: 15px;
+ -webkit-border-top-left-radius: 15px;
+}
+
+#qunit-header a {
+ text-decoration: none;
+ color: #c2ccd1;
+}
+
+#qunit-header a:hover,
+#qunit-header a:focus {
+ color: #fff;
+}
+
+#qunit-header label {
+ display: inline-block;
+ padding-left: 0.5em;
+}
+
+#qunit-banner {
+ height: 5px;
+}
+
+#qunit-testrunner-toolbar {
+ padding: 0.5em 0 0.5em 2em;
+ color: #5E740B;
+ background-color: #eee;
+}
+
+#qunit-userAgent {
+ padding: 0.5em 0 0.5em 2.5em;
+ background-color: #2b81af;
+ color: #fff;
+ text-shadow: rgba(0, 0, 0, 0.5) 2px 2px 1px;
+}
+
+
+/** Tests: Pass/Fail */
+
+#qunit-tests {
+ list-style-position: inside;
+}
+
+#qunit-tests li {
+ padding: 0.4em 0.5em 0.4em 2.5em;
+ border-bottom: 1px solid #fff;
+ list-style-position: inside;
+}
+
+#qunit-tests.hidepass li.pass, #qunit-tests.hidepass li.running {
+ display: none;
+}
+
+#qunit-tests li strong {
+ cursor: pointer;
+}
+
+#qunit-tests li a {
+ padding: 0.5em;
+ color: #c2ccd1;
+ text-decoration: none;
+}
+#qunit-tests li a:hover,
+#qunit-tests li a:focus {
+ color: #000;
+}
+
+#qunit-tests ol {
+ margin-top: 0.5em;
+ padding: 0.5em;
+
+ background-color: #fff;
+
+ border-radius: 15px;
+ -moz-border-radius: 15px;
+ -webkit-border-radius: 15px;
+
+ box-shadow: inset 0px 2px 13px #999;
+ -moz-box-shadow: inset 0px 2px 13px #999;
+ -webkit-box-shadow: inset 0px 2px 13px #999;
+}
+
+#qunit-tests table {
+ border-collapse: collapse;
+ margin-top: .2em;
+}
+
+#qunit-tests th {
+ text-align: right;
+ vertical-align: top;
+ padding: 0 .5em 0 0;
+}
+
+#qunit-tests td {
+ vertical-align: top;
+}
+
+#qunit-tests pre {
+ margin: 0;
+ white-space: pre-wrap;
+ word-wrap: break-word;
+}
+
+#qunit-tests del {
+ background-color: #e0f2be;
+ color: #374e0c;
+ text-decoration: none;
+}
+
+#qunit-tests ins {
+ background-color: #ffcaca;
+ color: #500;
+ text-decoration: none;
+}
+
+/*** Test Counts */
+
+#qunit-tests b.counts { color: black; }
+#qunit-tests b.passed { color: #5E740B; }
+#qunit-tests b.failed { color: #710909; }
+
+#qunit-tests li li {
+ margin: 0.5em;
+ padding: 0.4em 0.5em 0.4em 0.5em;
+ background-color: #fff;
+ border-bottom: none;
+ list-style-position: inside;
+}
+
+/*** Passing Styles */
+
+#qunit-tests li li.pass {
+ color: #5E740B;
+ background-color: #fff;
+ border-left: 26px solid #C6E746;
+}
+
+#qunit-tests .pass { color: #528CE0; background-color: #D2E0E6; }
+#qunit-tests .pass .test-name { color: #366097; }
+
+#qunit-tests .pass .test-actual,
+#qunit-tests .pass .test-expected { color: #999999; }
+
+#qunit-banner.qunit-pass { background-color: #C6E746; }
+
+/*** Failing Styles */
+
+#qunit-tests li li.fail {
+ color: #710909;
+ background-color: #fff;
+ border-left: 26px solid #EE5757;
+ white-space: pre;
+}
+
+#qunit-tests > li:last-child {
+ border-radius: 0 0 15px 15px;
+ -moz-border-radius: 0 0 15px 15px;
+ -webkit-border-bottom-right-radius: 15px;
+ -webkit-border-bottom-left-radius: 15px;
+}
+
+#qunit-tests .fail { color: #000000; background-color: #EE5757; }
+#qunit-tests .fail .test-name,
+#qunit-tests .fail .module-name { color: #000000; }
+
+#qunit-tests .fail .test-actual { color: #EE5757; }
+#qunit-tests .fail .test-expected { color: green; }
+
+#qunit-banner.qunit-fail { background-color: #EE5757; }
+
+
+/** Result */
+
+#qunit-testresult {
+ padding: 0.5em 0.5em 0.5em 2.5em;
+
+ color: #2b81af;
+ background-color: #D2E0E6;
+
+ border-bottom: 1px solid white;
+}
+#qunit-testresult .module-name {
+ font-weight: bold;
+}
+
+/** Fixture */
+
+#qunit-fixture {
+ position: absolute;
+ top: -10000px;
+ left: -10000px;
+ width: 1000px;
+ height: 1000px;
+}
View
1,863 lib/qunit.js
@@ -0,0 +1,1863 @@
+/**
+ * QUnit v1.9.0pre - A JavaScript Unit Testing Framework
+ *
+ * http://docs.jquery.com/QUnit
+ *
+ * Copyright (c) 2012 John Resig, Jörn Zaefferer
+ * Dual licensed under the MIT (MIT-LICENSE.txt)
+ * or GPL (GPL-LICENSE.txt) licenses.
+ */
+
+(function( window ) {
+
+var QUnit,
+ config,
+ onErrorFnPrev,
+ testId = 0,
+ fileName = (sourceFromStacktrace( 0 ) || "" ).replace(/(:\d+)+\)?/, "").replace(/.+\//, ""),
+ toString = Object.prototype.toString,
+ hasOwn = Object.prototype.hasOwnProperty,
+ defined = {
+ setTimeout: typeof window.setTimeout !== "undefined",
+ sessionStorage: (function() {
+ var x = "qunit-test-string";
+ try {
+ sessionStorage.setItem( x, x );
+ sessionStorage.removeItem( x );
+ return true;
+ } catch( e ) {
+ return false;
+ }
+ }())
+};
+
+function Test( settings ) {
+ extend( this, settings );
+ this.assertions = [];
+ this.testNumber = ++Test.count;
+}
+
+Test.count = 0;
+
+Test.prototype = {
+ init: function() {
+ var a, b, li,
+ tests = id( "qunit-tests" );
+
+ if ( tests ) {
+ b = document.createElement( "strong" );
+ b.innerHTML = this.name;
+
+ // `a` initialized at top of scope
+ a = document.createElement( "a" );
+ a.innerHTML = "Rerun";
+ a.href = QUnit.url({ testNumber: this.testNumber });
+
+ li = document.createElement( "li" );
+ li.appendChild( b );
+ li.appendChild( a );
+ li.className = "running";
+ li.id = this.id = "qunit-test-output" + testId++;
+
+ tests.appendChild( li );
+ }
+ },
+ setup: function() {
+ if ( this.module !== config.previousModule ) {
+ if ( config.previousModule ) {
+ runLoggingCallbacks( "moduleDone", QUnit, {
+ name: config.previousModule,
+ failed: config.moduleStats.bad,
+ passed: config.moduleStats.all - config.moduleStats.bad,
+ total: config.moduleStats.all
+ });
+ }
+ config.previousModule = this.module;
+ config.moduleStats = { all: 0, bad: 0 };
+ runLoggingCallbacks( "moduleStart", QUnit, {
+ name: this.module
+ });
+ } else if ( config.autorun ) {
+ runLoggingCallbacks( "moduleStart", QUnit, {
+ name: this.module
+ });
+ }
+
+ config.current = this;
+
+ this.testEnvironment = extend({
+ setup: function() {},
+ teardown: function() {}
+ }, this.moduleTestEnvironment );
+
+ runLoggingCallbacks( "testStart", QUnit, {
+ name: this.testName,
+ module: this.module
+ });
+
+ // allow utility functions to access the current test environment
+ // TODO why??
+ QUnit.current_testEnvironment = this.testEnvironment;
+
+ if ( !config.pollution ) {
+ saveGlobal();
+ }
+ if ( config.notrycatch ) {
+ this.testEnvironment.setup.call( this.testEnvironment );
+ return;
+ }
+ try {
+ this.testEnvironment.setup.call( this.testEnvironment );
+ } catch( e ) {
+ QUnit.pushFailure( "Setup failed on " + this.testName + ": " + e.message, extractStacktrace( e, 1 ) );
+ }
+ },
+ run: function() {
+ config.current = this;
+
+ var running = id( "qunit-testresult" );
+
+ if ( running ) {
+ running.innerHTML = "Running: <br/>" + this.name;
+ }
+
+ if ( this.async ) {
+ QUnit.stop();
+ }
+
+ if ( config.notrycatch ) {
+ this.callback.call( this.testEnvironment, QUnit.assert );
+ return;
+ }
+
+ try {
+ this.callback.call( this.testEnvironment, QUnit.assert );
+ } catch( e ) {
+ QUnit.pushFailure( "Died on test #" + (this.assertions.length + 1) + " " + this.stack + ": " + e.message, extractStacktrace( e, 0 ) );
+ // else next test will carry the responsibility
+ saveGlobal();
+
+ // Restart the tests if they're blocking
+ if ( config.blocking ) {
+ QUnit.start();
+ }
+ }
+ },
+ teardown: function() {
+ config.current = this;
+ if ( config.notrycatch ) {
+ this.testEnvironment.teardown.call( this.testEnvironment );
+ return;
+ } else {
+ try {
+ this.testEnvironment.teardown.call( this.testEnvironment );
+ } catch( e ) {
+ QUnit.pushFailure( "Teardown failed on " + this.testName + ": " + e.message, extractStacktrace( e, 1 ) );
+ }
+ }
+ checkPollution();
+ },
+ finish: function() {
+ config.current = this;
+ if ( config.requireExpects && this.expected == null ) {
+ QUnit.pushFailure( "Expected number of assertions to be defined, but expect() was not called.", this.stack );
+ } else if ( this.expected != null && this.expected != this.assertions.length ) {
+ QUnit.pushFailure( "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run", this.stack );
+ } else if ( this.expected == null && !this.assertions.length ) {
+ QUnit.pushFailure( "Expected at least one assertion, but none were run - call expect(0) to accept zero assertions.", this.stack );
+ }
+
+ var assertion, a, b, i, li, ol,
+ test = this,
+ good = 0,
+ bad = 0,
+ tests = id( "qunit-tests" );
+
+ config.stats.all += this.assertions.length;
+ config.moduleStats.all += this.assertions.length;
+
+ if ( tests ) {
+ ol = document.createElement( "ol" );
+
+ for ( i = 0; i < this.assertions.length; i++ ) {
+ assertion = this.assertions[i];
+
+ li = document.createElement( "li" );
+ li.className = assertion.result ? "pass" : "fail";
+ li.innerHTML = assertion.message || ( assertion.result ? "okay" : "failed" );
+ ol.appendChild( li );
+
+ if ( assertion.result ) {
+ good++;
+ } else {
+ bad++;
+ config.stats.bad++;
+ config.moduleStats.bad++;
+ }
+ }
+
+ // store result when possible
+ if ( QUnit.config.reorder && defined.sessionStorage ) {
+ if ( bad ) {
+ sessionStorage.setItem( "qunit-test-" + this.module + "-" + this.testName, bad );
+ } else {
+ sessionStorage.removeItem( "qunit-test-" + this.module + "-" + this.testName );
+ }
+ }
+
+ if ( bad === 0 ) {
+ ol.style.display = "none";
+ }
+
+ // `b` initialized at top of scope
+ b = document.createElement( "strong" );
+ b.innerHTML = this.name + " <b class='counts'>(<b class='failed'>" + bad + "</b>, <b class='passed'>" + good + "</b>, " + this.assertions.length + ")</b>";
+
+ addEvent(b, "click", function() {
+ var next = b.nextSibling.nextSibling,
+ display = next.style.display;
+ next.style.display = display === "none" ? "block" : "none";
+ });
+
+ addEvent(b, "dblclick", function( e ) {
+ var target = e && e.target ? e.target : window.event.srcElement;
+ if ( target.nodeName.toLowerCase() == "span" || target.nodeName.toLowerCase() == "b" ) {
+ target = target.parentNode;
+ }
+ if ( window.location && target.nodeName.toLowerCase() === "strong" ) {
+ window.location = QUnit.url({ testNumber: test.testNumber });
+ }
+ });
+
+ // `li` initialized at top of scope
+ li = id( this.id );
+ li.className = bad ? "fail" : "pass";
+ li.removeChild( li.firstChild );
+ a = li.firstChild;
+ li.appendChild( b );
+ li.appendChild ( a );
+ li.appendChild( ol );
+
+ } else {
+ for ( i = 0; i < this.assertions.length; i++ ) {
+ if ( !this.assertions[i].result ) {
+ bad++;
+ config.stats.bad++;
+ config.moduleStats.bad++;
+ }
+ }
+ }
+
+ runLoggingCallbacks( "testDone", QUnit, {
+ name: this.testName,
+ module: this.module,
+ failed: bad,
+ passed: this.assertions.length - bad,
+ total: this.assertions.length
+ });
+
+ QUnit.reset();
+
+ config.current = undefined;
+ },
+
+ queue: function() {
+ var bad,
+ test = this;
+
+ synchronize(function() {
+ test.init();
+ });
+ function run() {
+ // each of these can by async
+ synchronize(function() {
+ test.setup();
+ });
+ synchronize(function() {
+ test.run();
+ });
+ synchronize(function() {
+ test.teardown();
+ });
+ synchronize(function() {
+ test.finish();
+ });
+ }
+
+ // `bad` initialized at top of scope
+ // defer when previous test run passed, if storage is available
+ bad = QUnit.config.reorder && defined.sessionStorage &&
+ +sessionStorage.getItem( "qunit-test-" + this.module + "-" + this.testName );
+
+ if ( bad ) {
+ run();
+ } else {
+ synchronize( run, true );
+ }
+ }
+};
+
+// Root QUnit object.
+// `QUnit` initialized at top of scope
+QUnit = {
+
+ // call on start of module test to prepend name to all tests
+ module: function( name, testEnvironment ) {
+ config.currentModule = name;
+ config.currentModuleTestEnviroment = testEnvironment;
+ },
+
+ asyncTest: function( testName, expected, callback ) {
+ if ( arguments.length === 2 ) {
+ callback = expected;
+ expected = null;
+ }
+
+ QUnit.test( testName, expected, callback, true );
+ },
+
+ test: function( testName, expected, callback, async ) {
+ var test,
+ name = "<span class='test-name'>" + escapeInnerText( testName ) + "</span>";
+
+ if ( arguments.length === 2 ) {
+ callback = expected;
+ expected = null;
+ }
+
+ if ( config.currentModule ) {
+ name = "<span class='module-name'>" + config.currentModule + "</span>: " + name;
+ }
+
+ test = new Test({
+ name: name,
+ testName: testName,
+ expected: expected,
+ async: async,
+ callback: callback,
+ module: config.currentModule,
+ moduleTestEnvironment: config.currentModuleTestEnviroment,
+ stack: sourceFromStacktrace( 2 )
+ });
+
+ if ( !validTest( test ) ) {
+ return;
+ }
+
+ test.queue();
+ },
+
+ // Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through.
+ expect: function( asserts ) {
+ config.current.expected = asserts;
+ },
+
+ start: function( count ) {
+ config.semaphore -= count || 1;
+ // don't start until equal number of stop-calls
+ if ( config.semaphore > 0 ) {
+ return;
+ }
+ // ignore if start is called more often then stop
+ if ( config.semaphore < 0 ) {
+ config.semaphore = 0;
+ }
+ // A slight delay, to avoid any current callbacks
+ if ( defined.setTimeout ) {
+ window.setTimeout(function() {
+ if ( config.semaphore > 0 ) {
+ return;
+ }
+ if ( config.timeout ) {
+ clearTimeout( config.timeout );
+ }
+
+ config.blocking = false;
+ process( true );
+ }, 13);
+ } else {
+ config.blocking = false;
+ process( true );
+ }
+ },
+
+ stop: function( count ) {
+ config.semaphore += count || 1;
+ config.blocking = true;
+
+ if ( config.testTimeout && defined.setTimeout ) {
+ clearTimeout( config.timeout );
+ config.timeout = window.setTimeout(function() {
+ QUnit.ok( false, "Test timed out" );
+ config.semaphore = 1;
+ QUnit.start();
+ }, config.testTimeout );
+ }
+ }
+};
+
+// Asssert helpers
+// All of these must call either QUnit.push() or manually do:
+// - runLoggingCallbacks( "log", .. );
+// - config.current.assertions.push({ .. });
+QUnit.assert = {
+ /**
+ * Asserts rough true-ish result.
+ * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" );
+ */
+ ok: function( result, msg ) {
+ if ( !config.current ) {
+ throw new Error( "ok() assertion outside test context, was " + sourceFromStacktrace(2) );
+ }
+ result = !!result;
+
+ var source,
+ details = {
+ result: result,
+ message: msg
+ };
+
+ msg = escapeInnerText( msg || (result ? "okay" : "failed" ) );
+ msg = "<span class='test-message'>" + msg + "</span>";
+
+ if ( !result ) {
+ source = sourceFromStacktrace( 2 );
+ if ( source ) {
+ details.source = source;
+ msg += "<table><tr class='test-source'><th>Source: </th><td><pre>" + escapeInnerText( source ) + "</pre></td></tr></table>";
+ }
+ }
+ runLoggingCallbacks( "log", QUnit, details );
+ config.current.assertions.push({
+ result: result,
+ message: msg
+ });
+ },
+
+ /**
+ * Assert that the first two arguments are equal, with an optional message.
+ * Prints out both actual and expected values.
+ * @example equal( format( "Received {0} bytes.", 2), "Received 2 bytes.", "format() replaces {0} with next argument" );
+ */
+ equal: function( actual, expected, message ) {
+ QUnit.push( expected == actual, actual, expected, message );
+ },
+
+ notEqual: function( actual, expected, message ) {
+ QUnit.push( expected != actual, actual, expected, message );
+ },
+
+ deepEqual: function( actual, expected, message ) {
+ QUnit.push( QUnit.equiv(actual, expected), actual, expected, message );
+ },
+
+ notDeepEqual: function( actual, expected, message ) {
+ QUnit.push( !QUnit.equiv(actual, expected), actual, expected, message );
+ },
+
+ strictEqual: function( actual, expected, message ) {
+ QUnit.push( expected === actual, actual, expected, message );
+ },
+
+ notStrictEqual: function( actual, expected, message ) {
+ QUnit.push( expected !== actual, actual, expected, message );
+ },
+
+ raises: function( block, expected, message ) {
+ var actual,
+ ok = false;
+
+ if ( typeof expected === "string" ) {
+ message = expected;
+ expected = null;
+ }
+
+ config.current.ignoreGlobalErrors = true;
+ try {
+ block.call( config.current.testEnvironment );
+ } catch (e) {
+ actual = e;
+ }
+ config.current.ignoreGlobalErrors = false;
+
+ if ( actual ) {
+ // we don't want to validate thrown error
+ if ( !expected ) {
+ ok = true;
+ // expected is a regexp
+ } else if ( QUnit.objectType( expected ) === "regexp" ) {
+ ok = expected.test( actual );
+ // expected is a constructor
+ } else if ( actual instanceof expected ) {
+ ok = true;
+ // expected is a validation function which returns true is validation passed
+ } else if ( expected.call( {}, actual ) === true ) {
+ ok = true;
+ }
+ }
+
+ QUnit.push( ok, actual, null, message );
+ }
+};
+
+// @deprecated: Kept assertion helpers in root for backwards compatibility
+extend( QUnit, QUnit.assert );
+
+/**
+ * @deprecated: Kept for backwards compatibility
+ * next step: remove entirely
+ */
+QUnit.equals = function() {
+ QUnit.push( false, false, false, "QUnit.equals has been deprecated since 2009 (e88049a0), use QUnit.equal instead" );
+};
+QUnit.same = function() {
+ QUnit.push( false, false, false, "QUnit.same has been deprecated since 2009 (e88049a0), use QUnit.deepEqual instead" );
+};
+
+// We want access to the constructor's prototype
+(function() {
+ function F() {}
+ F.prototype = QUnit;
+ QUnit = new F();
+ // Make F QUnit's constructor so that we can add to the prototype later
+ QUnit.constructor = F;
+}());
+
+/**
+ * Config object: Maintain internal state
+ * Later exposed as QUnit.config
+ * `config` initialized at top of scope
+ */
+config = {
+ // The queue of tests to run
+ queue: [],
+
+ // block until document ready
+ blocking: true,
+
+ // when enabled, show only failing tests
+ // gets persisted through sessionStorage and can be changed in UI via checkbox
+ hidepassed: false,
+
+ // by default, run previously failed tests first
+ // very useful in combination with "Hide passed tests" checked
+ reorder: true,
+
+ // by default, modify document.title when suite is done
+ altertitle: true,
+
+ // when enabled, all tests must call expect()
+ requireExpects: false,
+
+ urlConfig: [ "noglobals", "notrycatch" ],
+
+ // logging callback queues
+ begin: [],
+ done: [],
+ log: [],
+ testStart: [],
+ testDone: [],
+ moduleStart: [],
+ moduleDone: []
+};
+
+// Initialize more QUnit.config and QUnit.urlParams
+(function() {
+ var i,
+ location = window.location || { search: "", protocol: "file:" },
+ params = location.search.slice( 1 ).split( "&" ),
+ length = params.length,
+ urlParams = {},
+ current;
+
+ if ( params[ 0 ] ) {
+ for ( i = 0; i < length; i++ ) {
+ current = params[ i ].split( "=" );
+ current[ 0 ] = decodeURIComponent( current[ 0 ] );
+ // allow just a key to turn on a flag, e.g., test.html?noglobals
+ current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true;
+ urlParams[ current[ 0 ] ] = current[ 1 ];
+ }
+ }
+
+ QUnit.urlParams = urlParams;
+
+ // String search anywhere in moduleName+testName
+ config.filter = urlParams.filter;
+
+ // Exact match of the module name
+ config.module = urlParams.module;
+
+ config.testNumber = parseInt( urlParams.testNumber, 10 ) || null;
+
+ // Figure out if we're running the tests from a server or not
+ QUnit.isLocal = location.protocol === "file:";
+}());
+
+// Export global variables, unless an 'exports' object exists,
+// in that case we assume we're in CommonJS (dealt with on the bottom of the script)
+if ( typeof exports === "undefined" ) {
+ extend( window, QUnit );
+
+ // Expose QUnit object
+ window.QUnit = QUnit;
+}
+
+// Extend QUnit object,
+// these after set here because they should not be exposed as global functions
+extend( QUnit, {
+ config: config,
+
+ // Initialize the configuration options
+ init: function() {
+ extend( config, {
+ stats: { all: 0, bad: 0 },
+ moduleStats: { all: 0, bad: 0 },
+ started: +new Date(),
+ updateRate: 1000,
+ blocking: false,
+ autostart: true,
+ autorun: false,
+ filter: "",
+ queue: [],
+ semaphore: 0
+ });
+
+ var tests, banner, result,
+ qunit = id( "qunit" );
+
+ if ( qunit ) {
+ qunit.innerHTML =
+ "<h1 id='qunit-header'>" + escapeInnerText( document.title ) + "</h1>" +
+ "<h2 id='qunit-banner'></h2>" +
+ "<div id='qunit-testrunner-toolbar'></div>" +
+ "<h2 id='qunit-userAgent'></h2>" +
+ "<ol id='qunit-tests'></ol>";
+ }
+
+ tests = id( "qunit-tests" );
+ banner = id( "qunit-banner" );
+ result = id( "qunit-testresult" );
+
+ if ( tests ) {
+ tests.innerHTML = "";
+ }
+
+ if ( banner ) {
+ banner.className = "";
+ }
+
+ if ( result ) {
+ result.parentNode.removeChild( result );
+ }
+
+ if ( tests ) {
+ result = document.createElement( "p" );
+ result.id = "qunit-testresult";
+ result.className = "result";
+ tests.parentNode.insertBefore( result, tests );
+ result.innerHTML = "Running...<br/>&nbsp;";
+ }
+ },
+
+ // Resets the test setup. Useful for tests that modify the DOM.
+ // If jQuery is available, uses jQuery's html(), otherwise just innerHTML.
+ reset: function() {
+ var fixture;
+
+ if ( window.jQuery ) {
+ jQuery( "#qunit-fixture" ).html( config.fixture );
+ } else {
+ fixture = id( "qunit-fixture" );
+ if ( fixture ) {
+ fixture.innerHTML = config.fixture;
+ }
+ }
+ },
+
+ // Trigger an event on an element.
+ // @example triggerEvent( document.body, "click" );
+ triggerEvent: function( elem, type, event ) {
+ if ( document.createEvent ) {
+ event = document.createEvent( "MouseEvents" );
+ event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
+ 0, 0, 0, 0, 0, false, false, false, false, 0, null);
+
+ elem.dispatchEvent( event );
+ } else if ( elem.fireEvent ) {
+ elem.fireEvent( "on" + type );
+ }
+ },
+
+ // Safe object type checking
+ is: function( type, obj ) {
+ return QUnit.objectType( obj ) == type;
+ },
+
+ objectType: function( obj ) {
+ if ( typeof obj === "undefined" ) {
+ return "undefined";
+ // consider: typeof null === object
+ }
+ if ( obj === null ) {
+ return "null";
+ }
+
+ var type = toString.call( obj ).match(/^\[object\s(.*)\]$/)[1] || "";
+
+ switch ( type ) {
+ case "Number":
+ if ( isNaN(obj) ) {
+ return "nan";
+ }
+ return "number";
+ case "String":
+ case "Boolean":
+ case "Array":
+ case "Date":
+ case "RegExp":
+ case "Function":
+ return type.toLowerCase();
+ }
+ if ( typeof obj === "object" ) {
+ return "object";
+ }
+ return undefined;
+ },
+
+ push: function( result, actual, expected, message ) {
+ if ( !config.current ) {
+ throw new Error( "assertion outside test context, was " + sourceFromStacktrace() );
+ }
+
+ var output, source,
+ details = {
+ result: result,
+ message: message,
+ actual: actual,
+ expected: expected
+ };
+
+ message = escapeInnerText( message ) || ( result ? "okay" : "failed" );
+ message = "<span class='test-message'>" + message + "</span>";
+ output = message;
+
+ if ( !result ) {
+ expected = escapeInnerText( QUnit.jsDump.parse(expected) );
+ actual = escapeInnerText( QUnit.jsDump.parse(actual) );
+ output += "<table><tr class='test-expected'><th>Expected: </th><td><pre>" + expected + "</pre></td></tr>";
+
+ if ( actual != expected ) {
+ output += "<tr class='test-actual'><th>Result: </th><td><pre>" + actual + "</pre></td></tr>";
+ output += "<tr class='test-diff'><th>Diff: </th><td><pre>" + QUnit.diff( expected, actual ) + "</pre></td></tr>";
+ }
+
+ source = sourceFromStacktrace();
+
+ if ( source ) {
+ details.source = source;
+ output += "<tr class='test-source'><th>Source: </th><td><pre>" + escapeInnerText( source ) + "</pre></td></tr>";
+ }
+
+ output += "</table>";
+ }
+
+ runLoggingCallbacks( "log", QUnit, details );
+
+ config.current.assertions.push({
+ result: !!result,
+ message: output
+ });
+ },
+
+ pushFailure: function( message, source ) {
+ if ( !config.current ) {
+ throw new Error( "pushFailure() assertion outside test context, was " + sourceFromStacktrace(2) );
+ }
+
+ var output,
+ details = {
+ result: false,
+ message: message
+ };
+
+ message = escapeInnerText(message ) || "error";
+ message = "<span class='test-message'>" + message + "</span>";
+ output = message;
+
+ if ( source ) {
+ details.source = source;
+ output += "<table><tr class='test-source'><th>Source: </th><td><pre>" + escapeInnerText( source ) + "</pre></td></tr></table>";
+ }
+
+ runLoggingCallbacks( "log", QUnit, details );
+
+ config.current.assertions.push({
+ result: false,
+ message: output
+ });
+ },
+
+ url: function( params ) {
+ params = extend( extend( {}, QUnit.urlParams ), params );
+ var key,
+ querystring = "?";
+
+ for ( key in params ) {
+ if ( !hasOwn.call( params, key ) ) {
+ continue;
+ }
+ querystring += encodeURIComponent( key ) + "=" +
+ encodeURIComponent( params[ key ] ) + "&";
+ }
+ return window.location.pathname + querystring.slice( 0, -1 );
+ },
+
+ extend: extend,
+ id: id,
+ addEvent: addEvent
+ // load, equiv, jsDump, diff: Attached later
+});
+
+/**
+ * @deprecated: Created for backwards compatibility with test runner that set the hook function
+ * into QUnit.{hook}, instead of invoking it and passing the hook function.
+ * QUnit.constructor is set to the empty F() above so that we can add to it's prototype here.
+ * Doing this allows us to tell if the following methods have been overwritten on the actual
+ * QUnit object.
+ */
+extend( QUnit.constructor.prototype, {
+
+ // Logging callbacks; all receive a single argument with the listed properties
+ // run test/logs.html for any related changes
+ begin: registerLoggingCallback( "begin" ),
+
+ // done: { failed, passed, total, runtime }
+ done: registerLoggingCallback( "done" ),
+
+ // log: { result, actual, expected, message }
+ log: registerLoggingCallback( "log" ),
+
+ // testStart: { name }
+ testStart: registerLoggingCallback( "testStart" ),
+
+ // testDone: { name, failed, passed, total }
+ testDone: registerLoggingCallback( "testDone" ),
+
+ // moduleStart: { name }
+ moduleStart: registerLoggingCallback( "moduleStart" ),
+
+ // moduleDone: { name, failed, passed, total }
+ moduleDone: registerLoggingCallback( "moduleDone" )
+});
+
+if ( typeof document === "undefined" || document.readyState === "complete" ) {
+ config.autorun = true;
+}
+
+QUnit.load = function() {
+ runLoggingCallbacks( "begin", QUnit, {} );
+
+ // Initialize the config, saving the execution queue
+ var banner, filter, i, label, len, main, ol, toolbar, userAgent, val,
+ urlConfigHtml = "",
+ oldconfig = extend( {}, config );
+
+ QUnit.init();
+ extend(config, oldconfig);
+
+ config.blocking = false;
+
+ len = config.urlConfig.length;
+
+ for ( i = 0; i < len; i++ ) {
+ val = config.urlConfig[i];
+ config[val] = QUnit.urlParams[val];
+ urlConfigHtml += "<label><input name='" + val + "' type='checkbox'" + ( config[val] ? " checked='checked'" : "" ) + ">" + val + "</label>";
+ }
+
+ // `userAgent` initialized at top of scope
+ userAgent = id( "qunit-userAgent" );
+ if ( userAgent ) {
+ userAgent.innerHTML = navigator.userAgent;
+ }
+
+ // `banner` initialized at top of scope
+ banner = id( "qunit-header" );
+ if ( banner ) {
+ banner.innerHTML = "<a href='" + QUnit.url({ filter: undefined }) + "'>" + banner.innerHTML + "</a> " + urlConfigHtml;
+ addEvent( banner, "change", function( event ) {
+ var params = {};
+ params[ event.target.name ] = event.target.checked ? true : undefined;
+ window.location = QUnit.url( params );
+ });
+ }
+
+ // `toolbar` initialized at top of scope
+ toolbar = id( "qunit-testrunner-toolbar" );
+ if ( toolbar ) {
+ // `filter` initialized at top of scope
+ filter = document.createElement( "input" );
+ filter.type = "checkbox";
+ filter.id = "qunit-filter-pass";
+
+ addEvent( filter, "click", function() {
+ var tmp,
+ ol = document.getElementById( "qunit-tests" );
+
+ if ( filter.checked ) {
+ ol.className = ol.className + " hidepass";
+ } else {
+ tmp = " " + ol.className.replace( /[\n\t\r]/g, " " ) + " ";
+ ol.className = tmp.replace( / hidepass /, " " );
+ }
+ if ( defined.