| Line | Hits | Source |
|---|---|---|
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | (function () { |
| 2 | 1 | "use strict"; |
| 3 | ||
| 4 | 1 | module.exports = require("c:/noboxout/js-object-enhancements/./lib/objects.js"); |
| 5 | ||
| 6 | }()); |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | (function () { |
| 2 | 1 | "use strict"; |
| 3 | ||
| 4 | 1 | var hasOwnProperty = Object.prototype.hasOwnProperty, |
| 5 | hasDontEnumBug = !({toString: null}).propertyIsEnumerable("toString"), | |
| 6 | dontEnums = [ | |
| 7 | "toString", | |
| 8 | "toLocaleString", | |
| 9 | "valueOf", | |
| 10 | "hasOwnProperty", | |
| 11 | "isPrototypeOf", | |
| 12 | "propertyIsEnumerable", | |
| 13 | "constructor" | |
| 14 | ], | |
| 15 | dontEnumsLength = dontEnums.length, | |
| 16 | ArrayPush = Array.prototype.push, | |
| 17 | ObjectConstructor = Object.prototype.constructor, | |
| 18 | __typeof, | |
| 19 | __merge, | |
| 20 | __depth, | |
| 21 | __rfilter, | |
| 22 | __debug = true; | |
| 23 | ||
| 24 | 1 | module.exports["typeof"] = __typeof = function (val) { |
| 25 | 81 | if (val === null || val === undefined) { |
| 26 | 3 | return "null"; |
| 27 | } | |
| 28 | // dont deal with undefine... | |
| 29 | 78 | if (val === true || val === false) { |
| 30 | 9 | return "boolean"; |
| 31 | } | |
| 32 | ||
| 33 | 69 | var type = typeof val; |
| 34 | ||
| 35 | 69 | if (type === "object") { |
| 36 | // for performance, we check if it"s a plain object first | |
| 37 | 41 | if (type.constructor === ObjectConstructor) { |
| 38 | 0 | return type; |
| 39 | } | |
| 40 | ||
| 41 | 41 | if (val.push === ArrayPush && val.length != null) { // != null is ok! |
| 42 | 9 | return "array"; |
| 43 | } | |
| 44 | // for performance, I will keep this insecure | |
| 45 | // if (hasOwnProperty.call(val, "callee")) { | |
| 46 | 32 | if (val.hasOwnProperty && val.hasOwnProperty("callee")) { |
| 47 | 3 | return "arguments"; |
| 48 | } | |
| 49 | 29 | if (val instanceof Date) { |
| 50 | 2 | return "date"; |
| 51 | } | |
| 52 | 27 | if (val instanceof RegExp) { |
| 53 | 2 | return "regexp"; |
| 54 | } | |
| 55 | ||
| 56 | // this is an instance of something? | |
| 57 | 28 | } else if (type === "number" && isNaN(val)) { |
| 58 | 1 | return "null"; |
| 59 | } | |
| 60 | ||
| 61 | 52 | return type; |
| 62 | }; | |
| 63 | ||
| 64 | // | |
| 65 | // Object | |
| 66 | // | |
| 67 | ||
| 68 | // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys | |
| 69 | 1 | if (!Object.keys) { |
| 70 | 0 | Object.keys = function (obj) { |
| 71 | 0 | if (typeof obj !== "object" && (typeof obj !== "function" || obj === null)) { |
| 72 | 0 | throw new TypeError("Object.keys called on non-object"); |
| 73 | } | |
| 74 | ||
| 75 | 0 | var result = [], prop, i; |
| 76 | ||
| 77 | 0 | for (prop in obj) { |
| 78 | 0 | if (hasOwnProperty.call(obj, prop)) { |
| 79 | 0 | result.push(prop); |
| 80 | } | |
| 81 | } | |
| 82 | ||
| 83 | 0 | if (hasDontEnumBug) { |
| 84 | 0 | for (i = 0; i < dontEnumsLength; i++) { |
| 85 | 0 | if (hasOwnProperty.call(obj, dontEnums[i])) { |
| 86 | 0 | result.push(dontEnums[i]); |
| 87 | } | |
| 88 | } | |
| 89 | } | |
| 90 | 0 | return result; |
| 91 | }; | |
| 92 | } | |
| 93 | ||
| 94 | // define Object.defineProperty if not found, no functionality just a replacement so your code not throw! | |
| 95 | 1 | if (!Object.defineProperty) { |
| 96 | 0 | Object.defineProperty = function (obj, name, prop) { |
| 97 | 0 | if (prop.get || prop.set) { |
| 98 | 0 | throw new Error("this is not supported in your js.engine"); |
| 99 | } | |
| 100 | 0 | obj[name] = prop.value; |
| 101 | }; | |
| 102 | } | |
| 103 | ||
| 104 | ||
| 105 | // define Object.seal if not found, no functionality just a replacement so your code not throw! | |
| 106 | 1 | if (!Object.seal) { |
| 107 | 0 | Object.seal = function (obj) { |
| 108 | 0 | return obj; |
| 109 | }; | |
| 110 | } | |
| 111 | ||
| 112 | 1 | module.exports.values = function (obj) { |
| 113 | 0 | if (__debug) { |
| 114 | 0 | if (typeof obj !== "object" && (typeof obj !== "function" || obj === null)) { |
| 115 | 0 | throw new TypeError("Object.values called on non-object"); |
| 116 | } | |
| 117 | } | |
| 118 | ||
| 119 | 0 | var result = [], |
| 120 | prop; | |
| 121 | ||
| 122 | 0 | for (prop in obj) { |
| 123 | 0 | if (!__debug || hasOwnProperty.call(obj, prop)) { |
| 124 | 0 | result.push(obj[prop]); |
| 125 | } | |
| 126 | } | |
| 127 | ||
| 128 | 0 | return result; |
| 129 | }; | |
| 130 | ||
| 131 | ||
| 132 | /** | |
| 133 | * get the keys of an object (or anything iterable for...in) note: remove prototype key | |
| 134 | * | |
| 135 | * @param {Object} object | |
| 136 | * @param {Function} fn | |
| 137 | * @returns {Object} object | |
| 138 | */ | |
| 139 | 1 | function __each(object, fn) { |
| 140 | 1 | var key = null; |
| 141 | ||
| 142 | 1 | for (key in object) { |
| 143 | 3 | fn(object[key], key); |
| 144 | } | |
| 145 | ||
| 146 | 1 | return object; |
| 147 | } | |
| 148 | ||
| 149 | 1 | module.exports.each = __each; |
| 150 | ||
| 151 | 1 | module.exports.forEach = __each; |
| 152 | ||
| 153 | 1 | module.exports.clone = function (obj) { |
| 154 | 2 | return __merge({}, obj, true, false); |
| 155 | }; | |
| 156 | ||
| 157 | /** | |
| 158 | * merge two object | |
| 159 | * | |
| 160 | * | |
| 161 | * @params {Object} to, this parameter is modified | |
| 162 | * @params {Object} from | |
| 163 | * @params {Boolean} clone | |
| 164 | * @params {Boolean} must_exists do not allow undefined in the objects | |
| 165 | */ | |
| 166 | 1 | module.exports.merge = __merge = function (to, from, clone, must_exists) { |
| 167 | //console.log("Object.merge", from); | |
| 168 | 41 | clone = clone || false; |
| 169 | 41 | must_exists = must_exists || false; |
| 170 | ||
| 171 | 41 | var ftype = __typeof(from), |
| 172 | key, | |
| 173 | ret; | |
| 174 | ||
| 175 | 41 | switch (ftype) { |
| 176 | case "string": | |
| 177 | 3 | return clone ? "" + from : from; |
| 178 | case "number": | |
| 179 | 16 | return clone ? 0 + from : from; |
| 180 | case "array": // maybe need more deep clone ? | |
| 181 | ||
| 182 | 5 | if (clone) { |
| 183 | 4 | ret = []; |
| 184 | 4 | for (key = 0; key < from.length; ++key) { |
| 185 | 15 | ret[key] = __merge(to[key] || {}, from[key], clone, must_exists); |
| 186 | } | |
| 187 | ||
| 188 | 4 | return ret; |
| 189 | } | |
| 190 | ||
| 191 | 1 | return from; |
| 192 | case "boolean": | |
| 193 | 5 | return clone ? (from ? true : false) : from; |
| 194 | case "null": | |
| 195 | 0 | return null; |
| 196 | case "function": | |
| 197 | 0 | return from; |
| 198 | case "object": | |
| 199 | // to it not an object, overwrite! | |
| 200 | 12 | ret = __typeof(to) !== "object" ? {} : to || {}; |
| 201 | // if has prototype just copy | |
| 202 | 12 | key = null; |
| 203 | ||
| 204 | 12 | for (key in from) { |
| 205 | 19 | if (key !== "prototype") { |
| 206 | 19 | if (ret[key] === undefined) { |
| 207 | 17 | if (must_exists) { |
| 208 | 1 | continue; |
| 209 | } | |
| 210 | 16 | ret[key] = {}; |
| 211 | } | |
| 212 | 18 | ret[key] = __merge(ret[key] || {}, from[key], clone, must_exists); |
| 213 | } | |
| 214 | } | |
| 215 | ||
| 216 | 12 | return ret; |
| 217 | case "regexp": | |
| 218 | 0 | return new RegExp(from.source); |
| 219 | case "date": | |
| 220 | 0 | return clone ? new Date(from) : from; |
| 221 | } | |
| 222 | // unknown type... just return | |
| 223 | 0 | return from; |
| 224 | }; | |
| 225 | ||
| 226 | 1 | module.exports.combine = function (keys, values) { |
| 227 | 3 | values = values || []; |
| 228 | 3 | var i, |
| 229 | ret = {}; | |
| 230 | ||
| 231 | 3 | for (i = 0; i < keys.length; ++i) { |
| 232 | 6 | ret[keys[i]] = values[i] === undefined ? null : values[i]; |
| 233 | } | |
| 234 | 3 | return ret; |
| 235 | }; | |
| 236 | ||
| 237 | 1 | module.exports.ksort = function (from) { |
| 238 | 1 | var keys = Object.keys(from), |
| 239 | i, | |
| 240 | ret = {}; | |
| 241 | ||
| 242 | 1 | for (i = 0; i < keys.length; ++i) { |
| 243 | 3 | ret[keys[i]] = from[keys[i]]; |
| 244 | } | |
| 245 | ||
| 246 | 1 | return ret; |
| 247 | }; | |
| 248 | ||
| 249 | 1 | module.exports.extend = function () { |
| 250 | 1 | var target = arguments[0] || {}, |
| 251 | o, | |
| 252 | p, | |
| 253 | i, | |
| 254 | len; | |
| 255 | ||
| 256 | 1 | for (i = 1, len = arguments.length; i < len; i++) { |
| 257 | 1 | o = arguments[i]; |
| 258 | ||
| 259 | 1 | if ("object" === typeof o && o !== null) { |
| 260 | 1 | for (p in o) { |
| 261 | 2 | target[p] = o[p]; |
| 262 | } | |
| 263 | } | |
| 264 | } | |
| 265 | ||
| 266 | 1 | return target; |
| 267 | }; | |
| 268 | ||
| 269 | 1 | module.exports.extract = function (from, keys, default_value) { |
| 270 | 1 | var i, |
| 271 | ret = {}; | |
| 272 | ||
| 273 | 1 | default_value = default_value === undefined ? null : default_value; |
| 274 | ||
| 275 | 1 | for (i = 0; i < keys.length; ++i) { |
| 276 | 2 | ret[keys[i]] = from[keys[i]] === undefined ? default_value : from[keys[i]]; |
| 277 | } | |
| 278 | ||
| 279 | 1 | return ret; |
| 280 | }; | |
| 281 | ||
| 282 | 1 | module.exports.empty = function (obj) { |
| 283 | 2 | var name; |
| 284 | 2 | for (name in obj) { |
| 285 | 1 | return false; |
| 286 | } | |
| 287 | 1 | return true; |
| 288 | }; | |
| 289 | ||
| 290 | 1 | module.exports.depth = __depth = function (obj) { |
| 291 | 13 | var i, |
| 292 | max, | |
| 293 | props = false, | |
| 294 | d = 0; | |
| 295 | ||
| 296 | 13 | if (obj === null || obj === undefined) { |
| 297 | 1 | return 0; |
| 298 | } | |
| 299 | ||
| 300 | 12 | if (Array.isArray(obj)) { |
| 301 | // array | |
| 302 | ||
| 303 | 1 | for (i = 0, max = obj.length; i < max; ++i) { |
| 304 | 1 | d = Math.max(d, __depth(obj[i])); |
| 305 | } | |
| 306 | 1 | props = max > 0; |
| 307 | 11 | } else if ("object" === typeof obj) { |
| 308 | // object | |
| 309 | ||
| 310 | 10 | for (i in obj) { |
| 311 | 6 | props = true; |
| 312 | 6 | d = Math.max(d, __depth(obj[i])); |
| 313 | } | |
| 314 | } | |
| 315 | ||
| 316 | 12 | return (props ? 1 : 0) + d; |
| 317 | }; | |
| 318 | ||
| 319 | 1 | module.exports.rFilter = __rfilter = function (obj, callback, loop_arrays) { |
| 320 | 12 | var i, |
| 321 | max; | |
| 322 | 12 | loop_arrays = loop_arrays === true; |
| 323 | ||
| 324 | 12 | if (Array.isArray(obj)) { |
| 325 | // array | |
| 326 | 3 | if (!loop_arrays) { |
| 327 | 2 | obj = callback(obj); |
| 328 | } else { | |
| 329 | 1 | for (i = 0, max = obj.length; i < max; ++i) { |
| 330 | 2 | obj[i] = __rfilter(obj[i], callback, loop_arrays); |
| 331 | } | |
| 332 | } | |
| 333 | ||
| 334 | 3 | return obj; |
| 335 | } | |
| 336 | ||
| 337 | 9 | if ("object" === typeof obj) { |
| 338 | // object | |
| 339 | 4 | if (!(obj instanceof Date || obj instanceof RegExp)) { |
| 340 | ||
| 341 | 2 | for (i in obj) { |
| 342 | 7 | obj[i] = __rfilter(obj[i], callback, loop_arrays); |
| 343 | } | |
| 344 | 2 | return obj; |
| 345 | } | |
| 346 | } | |
| 347 | ||
| 348 | 7 | return callback(obj); |
| 349 | }; | |
| 350 | ||
| 351 | 1 | module.exports.prefixKeys = function (obj, prefix, ignore_keys) { |
| 352 | 2 | ignore_keys = ignore_keys || []; |
| 353 | 2 | var i, |
| 354 | ret = {}; | |
| 355 | ||
| 356 | 2 | if (ignore_keys.length) { |
| 357 | 1 | for (i in obj) { |
| 358 | 3 | if (ignore_keys.indexOf(i) === -1) { |
| 359 | 2 | ret[prefix + i] = obj[i]; |
| 360 | } else { | |
| 361 | 1 | ret[i] = obj[i]; |
| 362 | } | |
| 363 | } | |
| 364 | } else { | |
| 365 | 1 | for (i in obj) { |
| 366 | 3 | ret[prefix + i] = obj[i]; |
| 367 | } | |
| 368 | } | |
| 369 | ||
| 370 | 2 | return ret; |
| 371 | }; | |
| 372 | ||
| 373 | 1 | module.exports.remPrefixKeys = function (obj, prefix, ignore_keys) { |
| 374 | 2 | ignore_keys = ignore_keys || []; |
| 375 | 2 | var i, |
| 376 | prefix_len = prefix.length, | |
| 377 | ret = {}; | |
| 378 | ||
| 379 | 2 | if (ignore_keys.length) { |
| 380 | 1 | for (i in obj) { |
| 381 | 3 | if (ignore_keys.indexOf(i) === -1) { |
| 382 | 2 | if (i.indexOf(prefix) === 0) { |
| 383 | 1 | ret[i.substring(prefix_len)] = obj[i]; |
| 384 | } else { | |
| 385 | 1 | ret[i] = obj[i]; |
| 386 | } | |
| 387 | } else { | |
| 388 | 1 | ret[i] = obj[i]; |
| 389 | } | |
| 390 | } | |
| 391 | } else { | |
| 392 | 1 | for (i in obj) { |
| 393 | 3 | if (i.indexOf(prefix) === 0) { |
| 394 | 2 | ret[i.substring(prefix_len)] = obj[i]; |
| 395 | } else { | |
| 396 | 1 | ret[i] = obj[i]; |
| 397 | } | |
| 398 | } | |
| 399 | } | |
| 400 | ||
| 401 | 2 | return ret; |
| 402 | }; | |
| 403 | ||
| 404 | ||
| 405 | 1 | module.exports.diff = function (obj) { |
| 406 | 4 | var ret = {}, |
| 407 | argl = arguments.length, | |
| 408 | k1, | |
| 409 | i, | |
| 410 | found; | |
| 411 | ||
| 412 | 4 | for (k1 in obj) { |
| 413 | 12 | found = false; |
| 414 | 12 | for (i = 1; i < argl && !found; ++i) { |
| 415 | 12 | if (obj[k1] === arguments[i][k1]) { |
| 416 | 7 | found = true; |
| 417 | } | |
| 418 | } | |
| 419 | ||
| 420 | 12 | if (!found) { |
| 421 | 5 | ret[k1] = obj[k1]; |
| 422 | } | |
| 423 | ||
| 424 | } | |
| 425 | ||
| 426 | 4 | return ret; |
| 427 | ||
| 428 | }; | |
| 429 | ||
| 430 | }()); |
| Line | Hits | Source |
|---|---|---|
| 1 | ||
| 2 | 1 | var GlobalHarness = require("c:/noboxout/js-object-enhancements/node_modules/tap/lib/./tap-global-harness") |
| 3 | ||
| 4 | // this lets you do stuff like: | |
| 5 | // var test = require("tap").test | |
| 6 | // test(...) | |
| 7 | // to run stuff in the global harness. | |
| 8 | 1 | exports = module.exports = new GlobalHarness() |
| 9 | ||
| 10 | 1 | exports.createProducer = exports.Producer = require("c:/noboxout/js-object-enhancements/node_modules/tap/lib/./tap-producer") |
| 11 | 1 | exports.createConsumer = exports.Consumer = require("c:/noboxout/js-object-enhancements/node_modules/tap/lib/./tap-consumer") |
| 12 | 1 | exports.yamlish = require("yamlish") |
| 13 | 1 | exports.createTest = exports.Test = require("c:/noboxout/js-object-enhancements/node_modules/tap/lib/./tap-test") |
| 14 | 1 | exports.createHarness = exports.Harness = require("c:/noboxout/js-object-enhancements/node_modules/tap/lib/./tap-harness") |
| 15 | 1 | exports.createRunner = exports.Runner = require("c:/noboxout/js-object-enhancements/node_modules/tap/lib/./tap-runner") |
| 16 | 1 | exports.assert = require("c:/noboxout/js-object-enhancements/node_modules/tap/lib/./tap-assert") |
| 17 |
| Line | Hits | Source |
|---|---|---|
| 1 | // this is just a harness that pipes to stdout. | |
| 2 | // It's the default one. | |
| 3 | 1 | module.exports = GlobalHarness |
| 4 | ||
| 5 | 1 | var globalHarness = global.TAP_Global_Harness |
| 6 | , inherits = require("inherits") | |
| 7 | , Results = require("c:/noboxout/js-object-enhancements/node_modules/tap/lib/./tap-results") | |
| 8 | , Harness = require("c:/noboxout/js-object-enhancements/node_modules/tap/lib/./tap-harness") | |
| 9 | , Test = require("c:/noboxout/js-object-enhancements/node_modules/tap/lib/./tap-test") | |
| 10 | ||
| 11 | 1 | inherits(GlobalHarness, Harness) |
| 12 | 1 | function GlobalHarness () { |
| 13 | //console.error("calling GlobalHarness") | |
| 14 | 1 | if (globalHarness) return globalHarness |
| 15 | 1 | if (!(this instanceof GlobalHarness)) { |
| 16 | 0 | return globalHarness = new GlobalHarness |
| 17 | } | |
| 18 | ||
| 19 | 1 | globalHarness = global.TAP_Global_Harness = this |
| 20 | 1 | GlobalHarness.super.call(this, Test) |
| 21 | ||
| 22 | 1 | this.output.pipe(process.stdout) |
| 23 | //this.output.on("data", function () { | |
| 24 | // process.nextTick(process.stdout.flush.bind(process.stdout)) | |
| 25 | //}) | |
| 26 | ||
| 27 | 1 | this.test = this.test.bind(this) |
| 28 | ||
| 29 | 1 | this.plan = this.plan.bind(this) |
| 30 | ||
| 31 | 1 | var output = this.output |
| 32 | 1 | this.on("childEnd", function (child) { |
| 33 | //console.error("childEnd in global harness") | |
| 34 | //console.error(child.results) | |
| 35 | // write out the stuff for this child. | |
| 36 | //console.error("child.conf", child.conf) | |
| 37 | 5 | output.write(child.conf.name || "(unnamed test)") |
| 38 | // maybe write some other stuff about the number of tests in this | |
| 39 | // thing, etc. I dunno. | |
| 40 | //console.error("child results", child.results) | |
| 41 | 5 | this.results.list.forEach(function (res) { |
| 42 | //delete res.error | |
| 43 | //console.error("child resuilt", res) | |
| 44 | 57 | output.write(res) |
| 45 | }) | |
| 46 | //console.error("wrote child results") | |
| 47 | 5 | this.results.list.length = 0 |
| 48 | }) | |
| 49 | ||
| 50 | 1 | var streamEnded = false |
| 51 | 1 | this.on("end", function () { |
| 52 | //console.error("global ending the stream") | |
| 53 | 1 | if (!streamEnded) { |
| 54 | 1 | this.results.list.forEach(function (res) { |
| 55 | 0 | output.write(res) |
| 56 | }) | |
| 57 | 1 | this.results.list.length = 0 |
| 58 | 1 | output.end() |
| 59 | 1 | streamEnded = true |
| 60 | } | |
| 61 | }) | |
| 62 | ||
| 63 | //this.on("end", this.output.end.bind(this.output)) | |
| 64 | ||
| 65 | 1 | process.on("unhandledException", function (e) { |
| 66 | 0 | this.bailout("unhandled exception: " + e.message) |
| 67 | }) | |
| 68 | } | |
| 69 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | module.exports = inherits |
| 2 | ||
| 3 | 1 | function inherits (c, p, proto) { |
| 4 | 7 | proto = proto || {} |
| 5 | 7 | var e = {} |
| 6 | 7 | ;[c.prototype, proto].forEach(function (s) { |
| 7 | 14 | Object.getOwnPropertyNames(s).forEach(function (k) { |
| 8 | 7 | e[k] = Object.getOwnPropertyDescriptor(s, k) |
| 9 | }) | |
| 10 | }) | |
| 11 | 7 | c.prototype = Object.create(p.prototype, e) |
| 12 | 7 | c.super = p |
| 13 | } | |
| 14 | ||
| 15 | //function Child () { | |
| 16 | // Child.super.call(this) | |
| 17 | // console.error([this | |
| 18 | // ,this.constructor | |
| 19 | // ,this.constructor === Child | |
| 20 | // ,this.constructor.super === Parent | |
| 21 | // ,Object.getPrototypeOf(this) === Child.prototype | |
| 22 | // ,Object.getPrototypeOf(Object.getPrototypeOf(this)) | |
| 23 | // === Parent.prototype | |
| 24 | // ,this instanceof Child | |
| 25 | // ,this instanceof Parent]) | |
| 26 | //} | |
| 27 | //function Parent () {} | |
| 28 | //inherits(Child, Parent) | |
| 29 | //new Child | |
| 30 |
| Line | Hits | Source |
|---|---|---|
| 1 | // A class for counting up results in a test harness. | |
| 2 | ||
| 3 | 1 | module.exports = Results |
| 4 | ||
| 5 | 1 | var inherits = require("inherits") |
| 6 | , EventEmitter = require("events").EventEmitter | |
| 7 | ||
| 8 | 1 | inherits(Results, EventEmitter) |
| 9 | ||
| 10 | 1 | function Results (r) { |
| 11 | //console.error("result constructor", r) | |
| 12 | 12 | this.ok = true |
| 13 | 12 | this.addSet(r) |
| 14 | } | |
| 15 | ||
| 16 | 1 | Results.prototype.addSet = function (r) { |
| 17 | //console.error("add set of results", r) | |
| 18 | 17 | r = r || {ok: true} |
| 19 | 17 | ; [ "todo" |
| 20 | , "todoPass" | |
| 21 | , "todoFail" | |
| 22 | , "skip" | |
| 23 | , "skipPass" | |
| 24 | , "skipFail" | |
| 25 | , "pass" | |
| 26 | , "passTotal" | |
| 27 | , "fail" | |
| 28 | , "failTotal" | |
| 29 | , "tests" | |
| 30 | , "testsTotal" ].forEach(function (k) { | |
| 31 | 204 | this[k] = (this[k] || 0) + (r[k] || 0) |
| 32 | //console.error([k, this[k]]) | |
| 33 | }, this) | |
| 34 | ||
| 35 | 17 | this.ok = this.ok && r.ok && true |
| 36 | 17 | this.bailedOut = this.bailedOut || r.bailedOut || false |
| 37 | 17 | this.list = (this.list || []).concat(r.list || []) |
| 38 | 17 | this.emit("set", this.list) |
| 39 | //console.error("after addSet", this) | |
| 40 | } | |
| 41 | ||
| 42 | 1 | Results.prototype.add = function (r, addToList) { |
| 43 | //console.error("add result", r) | |
| 44 | 114 | var pf = r.ok ? "pass" : "fail" |
| 45 | , PF = r.ok ? "Pass" : "Fail" | |
| 46 | ||
| 47 | 114 | this.testsTotal ++ |
| 48 | 114 | this[pf + "Total"] ++ |
| 49 | ||
| 50 | 114 | if (r.skip) { |
| 51 | 0 | this["skip" + PF] ++ |
| 52 | 0 | this.skip ++ |
| 53 | 114 | } else if (r.todo) { |
| 54 | 0 | this["todo" + PF] ++ |
| 55 | 0 | this.todo ++ |
| 56 | } else { | |
| 57 | 114 | this.tests ++ |
| 58 | 114 | this[pf] ++ |
| 59 | } | |
| 60 | ||
| 61 | 114 | if (r.bailout || typeof r.bailout === "string") { |
| 62 | // console.error("Bailing out in result") | |
| 63 | 0 | this.bailedOut = true |
| 64 | } | |
| 65 | 114 | this.ok = !!(this.ok && r.ok) |
| 66 | ||
| 67 | 171 | if (addToList === false) return |
| 68 | 57 | this.list = this.list || [] |
| 69 | 57 | this.list.push(r) |
| 70 | 57 | this.emit("result", r) |
| 71 | } | |
| 72 |
| Line | Hits | Source |
|---|---|---|
| 1 | // a thing that runs tests. | |
| 2 | // Every "test" is also a harness. If they do not have a harness, | |
| 3 | // then they are attached to the defaut "global harness", | |
| 4 | // which writes its results to stdout. | |
| 5 | ||
| 6 | ||
| 7 | // TODO: | |
| 8 | // - Bailout should stop running any tests. | |
| 9 | // - "skip" in the test config obj should skip it. | |
| 10 | ||
| 11 | 1 | module.exports = Harness |
| 12 | 1 | require("inherits")(Harness, require("events").EventEmitter) |
| 13 | ||
| 14 | 1 | var Results = require("c:/noboxout/js-object-enhancements/node_modules/tap/lib/./tap-results") |
| 15 | , TapProducer = require("c:/noboxout/js-object-enhancements/node_modules/tap/lib/./tap-producer") | |
| 16 | , assert = require("c:/noboxout/js-object-enhancements/node_modules/tap/lib/./tap-assert") | |
| 17 | ||
| 18 | 1 | function Harness (Test) { |
| 19 | 6 | if (!(this instanceof Harness)) return new Harness(Test) |
| 20 | ||
| 21 | //console.error("Test in "+this.constructor.name, Test) | |
| 22 | ||
| 23 | 6 | this._Test = Test |
| 24 | 6 | this._plan = null |
| 25 | 6 | this._children = [] |
| 26 | 6 | this._started = false |
| 27 | ||
| 28 | 6 | this._testCount = 0 |
| 29 | 6 | this._planSum = 0 |
| 30 | ||
| 31 | 6 | this.results = new Results() |
| 32 | // emit result events on the harness. | |
| 33 | //this.results.on("result", function (res) { | |
| 34 | // console.error("proxying result ev from res to harness") | |
| 35 | // this.emit("result", res) | |
| 36 | //}.bind(this)) | |
| 37 | 6 | var me = this |
| 38 | 6 | this.results.on("result", this.emit.bind(this, "result")) |
| 39 | ||
| 40 | 6 | var p = this.process.bind(this) |
| 41 | 6 | this.process = function () { |
| 42 | 6 | this._started = true |
| 43 | 6 | process.nextTick(p) |
| 44 | } | |
| 45 | ||
| 46 | 6 | this.output = new TapProducer() |
| 47 | 6 | Harness.super.call(this) |
| 48 | } | |
| 49 | ||
| 50 | // this function actually only gets called bound to | |
| 51 | // the Harness object, and on process.nextTick. Even if | |
| 52 | // passed as an event handler, everything *else* will | |
| 53 | // happen before it gets called. | |
| 54 | 1 | Harness.prototype.process = function () { |
| 55 | //console.error("harness process") | |
| 56 | // "end" can emit multiple times, so only actually move on | |
| 57 | // to the next test if the current one is actually over. | |
| 58 | // TODO: multiple in-process tests, if all are marked "async" | |
| 59 | 6 | if (this._current) { |
| 60 | 5 | if (!this._current._ended) return |
| 61 | // handle the current one before moving onto the next. | |
| 62 | 5 | this.childEnd(this._current) |
| 63 | } | |
| 64 | 6 | var skip = true |
| 65 | 6 | while (skip) { |
| 66 | //console.error("checking for skips") | |
| 67 | 6 | var current = this._current = this._children.shift() |
| 68 | 6 | if (current) { |
| 69 | 5 | skip = current.conf.skip |
| 70 | 5 | if (skip) { |
| 71 | //console.error("add a failure for the skipping") | |
| 72 | 0 | this.results.add(assert.fail(current.conf.name |
| 73 | ,{skip:true, diag:false})) | |
| 74 | } | |
| 75 | 1 | } else skip = false |
| 76 | } | |
| 77 | ||
| 78 | // keep processing through skipped tests, instead of running them. | |
| 79 | 6 | if (current && this._bailedOut) { |
| 80 | 0 | return this.process() |
| 81 | } | |
| 82 | ||
| 83 | //console.error("got current?", !!current) | |
| 84 | 6 | if (current) { |
| 85 | 5 | current.on("end", this.process) |
| 86 | 5 | current.emit("ready") |
| 87 | //console.error("emitted ready") | |
| 88 | //console.error("_plan", this._plan, this.constructor.name) | |
| 89 | } else { | |
| 90 | //console.error("Harness process: no more left. ending") | |
| 91 | 1 | if (this._endNice) { |
| 92 | 0 | this._endNice() |
| 93 | } else { | |
| 94 | 1 | this.end() |
| 95 | } | |
| 96 | } | |
| 97 | } | |
| 98 | ||
| 99 | 1 | Harness.prototype.end = function () { |
| 100 | 6 | if (this._children.length) { |
| 101 | 0 | return this.process() |
| 102 | } | |
| 103 | //console.error("harness end", this.constructor.name) | |
| 104 | 6 | if (this._bailedOut) return |
| 105 | ||
| 106 | // can't call .end() more than once. | |
| 107 | 6 | if (this._ended) { |
| 108 | //console.error("adding failure for end calling") | |
| 109 | 0 | this.results.add(assert.fail("end called more than once")) |
| 110 | } | |
| 111 | ||
| 112 | // see if the plan is completed properly, if there was one. | |
| 113 | 6 | if (this._plan !== null) { |
| 114 | 0 | var total = this._testCount |
| 115 | 0 | if (total !== this._plan) { |
| 116 | 0 | this.results.add(assert.equal(total, this._plan, "test count != plan")) |
| 117 | } | |
| 118 | 0 | this._plan = total |
| 119 | } | |
| 120 | ||
| 121 | //console.error("setting ended true", this.constructor.name) | |
| 122 | 6 | this._ended = true |
| 123 | 6 | this.emit("end") |
| 124 | } | |
| 125 | ||
| 126 | 1 | Harness.prototype.plan = function (p) { |
| 127 | //console.error("setting plan", new Error().stack) | |
| 128 | 0 | if (this._plan !== null) { |
| 129 | //console.error("about to add failure for calling plan") | |
| 130 | 0 | return this.results.add(assert.fail("plan set multiple times")) |
| 131 | } | |
| 132 | 0 | this._plan = p |
| 133 | 0 | if (p === 0 || this.results.testsTotal) { |
| 134 | 0 | this.end() |
| 135 | } | |
| 136 | } | |
| 137 | ||
| 138 | 1 | Harness.prototype.childEnd = function (child) { |
| 139 | //console.error("childEnd") | |
| 140 | 5 | this._testCount ++ |
| 141 | 5 | this._planSum += child._plan |
| 142 | //console.error("adding set of child.results") | |
| 143 | 5 | this.results.addSet(child.results) |
| 144 | 5 | this.emit("childEnd", child) |
| 145 | // was this planned? | |
| 146 | 5 | if (this._plan === this._testCount) { |
| 147 | //console.error("plan", [this._plan, this._testCount]) | |
| 148 | 0 | return this.end() |
| 149 | } | |
| 150 | } | |
| 151 | ||
| 152 | 1 | function copyObj(o) { |
| 153 | 0 | var copied = {} |
| 154 | 0 | Object.keys(o).forEach(function (k) { copied[k] = o[k] }) |
| 155 | 0 | return copied |
| 156 | } | |
| 157 | ||
| 158 | 1 | Harness.prototype.test = function test (name, conf, cb) { |
| 159 | 5 | if (this._bailedOut) return |
| 160 | ||
| 161 | 10 | if (typeof conf === "function") cb = conf, conf = null |
| 162 | 5 | if (typeof name === "object") conf = name, name = null |
| 163 | 5 | if (typeof name === "function") cb = name, name = null |
| 164 | ||
| 165 | 5 | conf = (conf ? copyObj(conf) : {}) |
| 166 | 5 | name = name || "" |
| 167 | ||
| 168 | //console.error("making test", [name, conf, cb]) | |
| 169 | ||
| 170 | // timeout: value in milliseconds. Defaults to 30s | |
| 171 | // Set to Infinity to have no timeout. | |
| 172 | 10 | if (isNaN(conf.timeout)) conf.timeout = 30000 |
| 173 | 5 | var t = new this._Test(this, name, conf) |
| 174 | 5 | var self = this |
| 175 | 5 | if (cb) { |
| 176 | //console.error("attaching cb to ready event") | |
| 177 | 5 | t.on("ready", function () { |
| 178 | 5 | if (!isNaN(conf.timeout) && isFinite(conf.timeout)) { |
| 179 | 5 | var timer = setTimeout(this.timeout.bind(this), conf.timeout) |
| 180 | 5 | var clear = function () { |
| 181 | 5 | clearTimeout(timer) |
| 182 | } | |
| 183 | 5 | t.on("end", clear) |
| 184 | 5 | t.on("bailout", function (message) { |
| 185 | 0 | self.bailout(message) |
| 186 | 0 | clear() |
| 187 | }) | |
| 188 | } | |
| 189 | }) | |
| 190 | 5 | t.on("ready", cb.bind(t, t)) |
| 191 | // proxy the child results to this object. | |
| 192 | //t.on("result", function (res) { | |
| 193 | // console.error("in harness, proxying result up") | |
| 194 | // t.results.add(res) | |
| 195 | //}) | |
| 196 | } | |
| 197 | 5 | return t |
| 198 | } | |
| 199 | ||
| 200 | 1 | Harness.prototype.bailout = function (message) { |
| 201 | // console.error("Harness bailout", this.constructor.name) | |
| 202 | 0 | message = message || "" |
| 203 | //console.error("adding bailout message result") | |
| 204 | 0 | this.results.add({bailout: message}) |
| 205 | // console.error(">>> results after bailout" , this.results) | |
| 206 | 0 | this._bailedOut = true |
| 207 | 0 | this.emit("bailout", message) |
| 208 | 0 | this.output.end({bailout: message}) |
| 209 | } | |
| 210 | ||
| 211 | 1 | Harness.prototype.add = function (child) { |
| 212 | //console.error("adding child") | |
| 213 | 5 | this._children.push(child) |
| 214 | 6 | if (!this._started) this.process() |
| 215 | } | |
| 216 | ||
| 217 | // the tearDown function is *always* guaranteed to happen. | |
| 218 | // Even if there's a bailout. | |
| 219 | 1 | Harness.prototype.tearDown = function (fn) { |
| 220 | 0 | this.on("end", fn) |
| 221 | } | |
| 222 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | module.exports = TapProducer |
| 2 | ||
| 3 | 1 | var Results = require("c:/noboxout/js-object-enhancements/node_modules/tap/lib/./tap-results") |
| 4 | , inherits = require("inherits") | |
| 5 | , yamlish = require("yamlish") | |
| 6 | ||
| 7 | 1 | TapProducer.encode = function (result, diag) { |
| 8 | 0 | var tp = new TapProducer(diag) |
| 9 | , out = "" | |
| 10 | 0 | tp.on("data", function (c) { out += c }) |
| 11 | 0 | if (Array.isArray(result)) { |
| 12 | 0 | result.forEach(tp.write, tp) |
| 13 | 0 | } else tp.write(result) |
| 14 | 0 | tp.end() |
| 15 | 0 | return out |
| 16 | } | |
| 17 | ||
| 18 | 1 | inherits(TapProducer, require("stream").Stream) |
| 19 | 1 | function TapProducer (diag) { |
| 20 | 6 | TapProducer.super.call(this) |
| 21 | 6 | this.diag = diag |
| 22 | 6 | this.count = 0 |
| 23 | 6 | this.readable = this.writable = true |
| 24 | 6 | this.results = new Results |
| 25 | } | |
| 26 | ||
| 27 | 1 | TapProducer.prototype.trailer = true |
| 28 | ||
| 29 | 1 | TapProducer.prototype.write = function (res) { |
| 30 | // console.error("TapProducer.write", res) | |
| 31 | 63 | if (typeof res === "function") throw new Error("wtf?") |
| 32 | 63 | if (!this.writable) this.emit("error", new Error("not writable")) |
| 33 | ||
| 34 | 63 | if (!this._didHead) { |
| 35 | 1 | this.emit("data", "TAP version 13\n") |
| 36 | 1 | this._didHead = true |
| 37 | } | |
| 38 | ||
| 39 | 63 | var diag = res.diag |
| 40 | 126 | if (diag === undefined) diag = this.diag |
| 41 | ||
| 42 | 63 | this.emit("data", encodeResult(res, this.count + 1, diag)) |
| 43 | ||
| 44 | 69 | if (typeof res === "string") return true |
| 45 | ||
| 46 | 57 | if (res.bailout) { |
| 47 | 0 | var bo = "bail out!" |
| 48 | 0 | if (typeof res.bailout === "string") bo += " " + res.bailout |
| 49 | 0 | this.emit("data", bo) |
| 50 | 0 | return |
| 51 | } | |
| 52 | 57 | this.results.add(res, false) |
| 53 | ||
| 54 | 57 | this.count ++ |
| 55 | } | |
| 56 | ||
| 57 | 1 | TapProducer.prototype.end = function (res) { |
| 58 | 1 | if (res) this.write(res) |
| 59 | // console.error("TapProducer end", res, this.results) | |
| 60 | 1 | this.emit("data", "\n1.."+this.results.testsTotal+"\n") |
| 61 | 1 | if (this.trailer && typeof this.trailer !== "string") { |
| 62 | // summary trailer. | |
| 63 | 1 | var trailer = "tests "+this.results.testsTotal + "\n" |
| 64 | 1 | if (this.results.pass) { |
| 65 | 1 | trailer += "pass " + this.results.pass + "\n" |
| 66 | } | |
| 67 | 1 | if (this.results.fail) { |
| 68 | 0 | trailer += "fail " + this.results.fail + "\n" |
| 69 | } | |
| 70 | 1 | if (this.results.skip) { |
| 71 | 0 | trailer += "skip "+this.results.skip + "\n" |
| 72 | } | |
| 73 | 1 | if (this.results.todo) { |
| 74 | 0 | trailer += "todo "+this.results.todo + "\n" |
| 75 | } | |
| 76 | 1 | if (this.results.bailedOut) { |
| 77 | 0 | trailer += "bailed out" + "\n" |
| 78 | } | |
| 79 | ||
| 80 | 1 | if (this.results.testsTotal === this.results.pass) { |
| 81 | 1 | trailer += "\nok\n" |
| 82 | } | |
| 83 | 1 | this.trailer = trailer |
| 84 | } | |
| 85 | 2 | if (this.trailer) this.write(this.trailer) |
| 86 | 1 | this.writable = false |
| 87 | 1 | this.emit("end", null, this.count, this.ok) |
| 88 | } | |
| 89 | ||
| 90 | 1 | function encodeResult (res, count, diag) { |
| 91 | // console.error(res, count, diag) | |
| 92 | 63 | if (typeof res === "string") { |
| 93 | 6 | res = res.split(/\r?\n/).map(function (l) { |
| 94 | 12 | if (!l.trim()) return l.trim() |
| 95 | 8 | return "# " + l |
| 96 | }).join("\n") | |
| 97 | 11 | if (res.substr(-1) !== "\n") res += "\n" |
| 98 | 6 | return res |
| 99 | } | |
| 100 | ||
| 101 | 57 | if (res.bailout) return "" |
| 102 | ||
| 103 | ||
| 104 | 57 | if (!!process.env.TAP_NODIAG) diag = false |
| 105 | 57 | else if (!!process.env.TAP_DIAG) diag = true |
| 106 | 114 | else if (diag === undefined) diag = !res.ok |
| 107 | ||
| 108 | 57 | var output = "" |
| 109 | 57 | res.name = res.name && ("" + res.name).trim() |
| 110 | 57 | output += ( !res.ok ? "not " : "") + "ok " + count |
| 111 | + ( !res.name ? "" | |
| 112 | : " " + res.name.replace(/[\r\n]/g, " ") ) | |
| 113 | + ( res.skip ? " # SKIP" | |
| 114 | : res.todo ? " # TODO" | |
| 115 | : "" ) | |
| 116 | + "\n" | |
| 117 | ||
| 118 | 114 | if (!diag) return output |
| 119 | 0 | var d = {} |
| 120 | , dc = 0 | |
| 121 | 0 | Object.keys(res).filter(function (k) { |
| 122 | 0 | return k !== "ok" && k !== "name" && k !== "id" |
| 123 | }).forEach(function (k) { | |
| 124 | 0 | dc ++ |
| 125 | 0 | d[k] = res[k] |
| 126 | }) | |
| 127 | //console.error(d, "about to encode") | |
| 128 | 0 | if (dc > 0) output += " ---"+yamlish.encode(d)+"\n ...\n" |
| 129 | 0 | return output |
| 130 | } | |
| 131 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | exports.encode = encode |
| 2 | 1 | exports.decode = decode |
| 3 | ||
| 4 | 1 | var seen = [] |
| 5 | 1 | function encode (obj, indent) { |
| 6 | 0 | var deep = arguments[2] |
| 7 | 0 | if (!indent) indent = " " |
| 8 | ||
| 9 | 0 | if (obj instanceof String || |
| 10 | Object.prototype.toString.call(obj) === "[object String]") { | |
| 11 | 0 | obj = obj.toString() |
| 12 | } | |
| 13 | ||
| 14 | 0 | if (obj instanceof Number || |
| 15 | Object.prototype.toString.call(obj) === "[object Number]") { | |
| 16 | 0 | obj = obj.valueOf() |
| 17 | } | |
| 18 | ||
| 19 | // take out the easy ones. | |
| 20 | 0 | switch (typeof obj) { |
| 21 | case "string": | |
| 22 | 0 | obj = obj.trim() |
| 23 | 0 | if (obj.indexOf("\n") !== -1) { |
| 24 | 0 | return "|\n" + indent + obj.split(/\r?\n/).join("\n"+indent) |
| 25 | } else { | |
| 26 | 0 | return (obj) |
| 27 | } | |
| 28 | ||
| 29 | case "number": | |
| 30 | 0 | return obj.toString(10) |
| 31 | ||
| 32 | case "function": | |
| 33 | 0 | return encode(obj.toString(), indent, true) |
| 34 | ||
| 35 | case "boolean": | |
| 36 | 0 | return obj.toString() |
| 37 | ||
| 38 | case "undefined": | |
| 39 | // fallthrough | |
| 40 | case "object": | |
| 41 | // at this point we know it types as an object | |
| 42 | 0 | if (!obj) return "~" |
| 43 | ||
| 44 | 0 | if (obj instanceof Date || |
| 45 | Object.prototype.toString.call(obj) === "[object Date]") { | |
| 46 | 0 | return JSON.stringify("[Date " + obj.toISOString() + "]") |
| 47 | } | |
| 48 | ||
| 49 | 0 | if (obj instanceof RegExp || |
| 50 | Object.prototype.toString.call(obj) === "[object RegExp]") { | |
| 51 | 0 | return JSON.stringify(obj.toString()) |
| 52 | } | |
| 53 | ||
| 54 | 0 | if (obj instanceof Boolean || |
| 55 | Object.prototype.toString.call(obj) === "[object Boolean]") { | |
| 56 | 0 | return obj.toString() |
| 57 | } | |
| 58 | ||
| 59 | 0 | if (seen.indexOf(obj) !== -1) { |
| 60 | 0 | return "[Circular]" |
| 61 | } | |
| 62 | 0 | seen.push(obj) |
| 63 | ||
| 64 | 0 | if (typeof Buffer === "function" && |
| 65 | typeof Buffer.isBuffer === "function" && | |
| 66 | 0 | Buffer.isBuffer(obj)) return obj.inspect() |
| 67 | ||
| 68 | 0 | if (obj instanceof Error) { |
| 69 | 0 | var o = { name: obj.name |
| 70 | , message: obj.message | |
| 71 | , type: obj.type } | |
| 72 | ||
| 73 | 0 | if (obj.code) o.code = obj.code |
| 74 | 0 | if (obj.errno) o.errno = obj.errno |
| 75 | 0 | if (obj.type) o.type = obj.type |
| 76 | 0 | obj = o |
| 77 | } | |
| 78 | ||
| 79 | 0 | var out = "" |
| 80 | ||
| 81 | 0 | if (Array.isArray(obj)) { |
| 82 | 0 | var out = "\n" + indent + "- " +obj.map(function (item) { |
| 83 | 0 | return encode(item, indent + " ", true) |
| 84 | }).join("\n"+indent + "- ") | |
| 85 | 0 | break |
| 86 | } | |
| 87 | ||
| 88 | // an actual object | |
| 89 | 0 | var keys = Object.keys(obj) |
| 90 | , niceKeys = keys.map(function (k) { | |
| 91 | 0 | return (k.match(/^[a-zA-Z0-9_]+$/) ? k : JSON.stringify(k)) + ": " |
| 92 | }) | |
| 93 | //console.error(keys, niceKeys, obj) | |
| 94 | 0 | var maxLength = Math.max.apply(Math, niceKeys.map(function (k) { |
| 95 | 0 | return k.length |
| 96 | }).concat(0)) | |
| 97 | //console.error(niceKeys, maxLength) | |
| 98 | ||
| 99 | 0 | var spaces = new Array(maxLength + 1).join(" ") |
| 100 | ||
| 101 | 0 | if (!deep) indent += " " |
| 102 | 0 | out = "\n" + indent + keys.map(function (k, i) { |
| 103 | 0 | var niceKey = niceKeys[i] |
| 104 | 0 | return niceKey + spaces.substr(niceKey.length) |
| 105 | + encode(obj[k], indent + " ", true) | |
| 106 | }).join("\n" + indent) | |
| 107 | 0 | break |
| 108 | ||
| 109 | 0 | default: return "" |
| 110 | } | |
| 111 | 0 | if (!deep) seen.length = 0 |
| 112 | 0 | return out |
| 113 | } | |
| 114 | ||
| 115 | 1 | function decode (str) { |
| 116 | 0 | var v = str.trim() |
| 117 | , d | |
| 118 | , dateRe = /^\[Date ([0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}(?::[0-9]{2})?(?:\.[0-9]{3})?(?:[A-Z]+)?)\]$/ | |
| 119 | ||
| 120 | 0 | if (v === "~") return null |
| 121 | ||
| 122 | 0 | try { |
| 123 | 0 | var jp = JSON.parse(str) |
| 124 | } catch (e) { | |
| 125 | 0 | var jp = "" |
| 126 | } | |
| 127 | ||
| 128 | 0 | if (jp && |
| 129 | typeof jp === "string" && | |
| 130 | (d = jp.match(dateRe)) && | |
| 131 | (d = Date.parse(d[1]))) { | |
| 132 | 0 | return new Date(d) |
| 133 | } | |
| 134 | ||
| 135 | 0 | if (typeof jp === "boolean") return jp |
| 136 | 0 | if (v && !isNaN(v)) return parseInt(v, 10) |
| 137 | ||
| 138 | // something interesting. | |
| 139 | 0 | var lines = str.split(/\r?\n/) |
| 140 | // check if it's some kind of string or something. | |
| 141 | // if the first line is > or | then it's a wrapping indented string. | |
| 142 | // if the first line is blank, and there are many lines, | |
| 143 | // then it's an array or object. | |
| 144 | // otherwise, it's just "" | |
| 145 | 0 | var first = lines.shift().trim() |
| 146 | 0 | if (lines.length) lines = undent(lines) |
| 147 | 0 | switch (first) { |
| 148 | case "|": | |
| 149 | 0 | return lines.join("\n") |
| 150 | case ">": | |
| 151 | 0 | return lines.join("\n").split(/\n{2,}/).map(function (l) { |
| 152 | 0 | return l.split(/\n/).join(" ") |
| 153 | }).join("\n") | |
| 154 | default: | |
| 155 | 0 | if (!lines.length) return first |
| 156 | // array or object. | |
| 157 | // the first line will be either "- value" or "key: value" | |
| 158 | 0 | return lines[0].charAt(0) === "-" ? decodeArr(lines) : decodeObj(lines) |
| 159 | } | |
| 160 | } | |
| 161 | ||
| 162 | 1 | function decodeArr (lines) { |
| 163 | 0 | var out = [] |
| 164 | , key = 0 | |
| 165 | , val = [] | |
| 166 | 0 | for (var i = 0, l = lines.length; i < l; i ++) { |
| 167 | // if it starts with a -, then it's a new thing | |
| 168 | 0 | var line = lines[i] |
| 169 | 0 | if (line.charAt(0) === "-") { |
| 170 | 0 | if (val.length) { |
| 171 | 0 | out[key ++] = decode(val.join("\n")) |
| 172 | 0 | val.length = 0 |
| 173 | } | |
| 174 | 0 | val.push(line.substr(1).trim()) |
| 175 | 0 | } else if (line.charAt(0) === " ") { |
| 176 | 0 | val.push(line) |
| 177 | 0 | } else return [] |
| 178 | } | |
| 179 | 0 | if (val.length) { |
| 180 | 0 | out[key ++] = decode(val.join("\n")) |
| 181 | } | |
| 182 | 0 | return out |
| 183 | } | |
| 184 | ||
| 185 | 1 | function decodeObj (lines) { |
| 186 | 0 | var out = {} |
| 187 | , val = [] | |
| 188 | , key = null | |
| 189 | ||
| 190 | 0 | for (var i = 0, l = lines.length; i < l; i ++) { |
| 191 | 0 | var line = lines[i] |
| 192 | 0 | if (line.charAt(0) === " ") { |
| 193 | 0 | val.push(line) |
| 194 | 0 | continue |
| 195 | } | |
| 196 | // some key:val | |
| 197 | 0 | if (val.length) { |
| 198 | 0 | out[key] = decode(val.join("\n")) |
| 199 | 0 | val.length = 0 |
| 200 | } | |
| 201 | // parse out the quoted key | |
| 202 | 0 | var first |
| 203 | 0 | if (line.charAt(0) === "\"") { |
| 204 | 0 | for (var ii = 1, ll = line.length, esc = false; ii < ll; ii ++) { |
| 205 | 0 | var c = line.charAt(ii) |
| 206 | 0 | if (c === "\\") { |
| 207 | 0 | esc = !esc |
| 208 | 0 | } else if (c === "\"" && !esc) { |
| 209 | 0 | break |
| 210 | } | |
| 211 | } | |
| 212 | 0 | key = JSON.parse(line.substr(0, ii + 1)) |
| 213 | 0 | line = line.substr(ii + 1) |
| 214 | 0 | first = line.substr(line.indexOf(":") + 1).trim() |
| 215 | } else { | |
| 216 | 0 | var kv = line.split(":") |
| 217 | 0 | key = kv.shift() |
| 218 | 0 | first = kv.join(":").trim() |
| 219 | } | |
| 220 | // now we've set a key, and "first" has the first line of the value. | |
| 221 | 0 | val.push(first.trim()) |
| 222 | } | |
| 223 | 0 | if (val.length) out[key] = decode(val.join("\n")) |
| 224 | 0 | return out |
| 225 | } | |
| 226 | ||
| 227 | 1 | function undent (lines) { |
| 228 | 0 | var i = lines[0].match(/^\s*/)[0].length |
| 229 | 0 | return lines.map(function (line) { |
| 230 | 0 | return line.substr(i) |
| 231 | }) | |
| 232 | } | |
| 233 | ||
| 234 | ||
| 235 | // XXX Turn this into proper tests. | |
| 236 | 1 | if (require.main === module) { |
| 237 | 0 | var obj = [{"bigstring":new Error().stack} |
| 238 | ,{ar:[{list:"of"},{some:"objects"}]} | |
| 239 | ,{date:new Date()} | |
| 240 | ,{"super huge string":new Error().stack} | |
| 241 | ] | |
| 242 | ||
| 243 | 0 | Date.prototype.toJSON = function (k, val) { |
| 244 | 0 | console.error(k, val, this) |
| 245 | 0 | return this.toISOString() + " (it's a date)" |
| 246 | } | |
| 247 | ||
| 248 | 0 | var enc = encode(obj) |
| 249 | , dec = decode(enc) | |
| 250 | , encDec = encode(dec) | |
| 251 | ||
| 252 | 0 | console.error(JSON.stringify({ obj : obj |
| 253 | , enc : enc.split(/\n/) | |
| 254 | , dec : dec }, null, 2), encDec === enc) | |
| 255 | ||
| 256 | 0 | var num = 100 |
| 257 | , encNum = encode(num) | |
| 258 | , decEncNum = decode(encNum) | |
| 259 | 0 | console.error([num, encNum, decEncNum]) |
| 260 | } | |
| 261 |
| Line | Hits | Source |
|---|---|---|
| 1 | // an assert module that returns tappable data for each assertion. | |
| 2 | 1 | var difflet = require('difflet') |
| 3 | , deepEqual = require('deep-equal') | |
| 4 | , bufferEqual = require('buffer-equal') | |
| 5 | ||
| 6 | 1 | module.exports = assert |
| 7 | ||
| 8 | 1 | var syns = {} |
| 9 | , id = 1 | |
| 10 | ||
| 11 | 1 | function assert (ok, message, extra) { |
| 12 | 57 | if (extra && extra.skip) return assert.skip(message, extra) |
| 13 | ||
| 14 | //console.error("assert %j", [ok, message, extra]) | |
| 15 | //if (extra && extra.skip) return assert.skip(message, extra) | |
| 16 | //console.error("assert", [ok, message, extra]) | |
| 17 | 57 | ok = !!ok |
| 18 | 57 | var res = { id : id ++, ok: ok } |
| 19 | ||
| 20 | 57 | var caller = getCaller(extra && extra.error) |
| 21 | 57 | if (extra && extra.error) { |
| 22 | 0 | res.type = extra.error.name |
| 23 | 0 | res.message = extra.error.message |
| 24 | 0 | res.code = extra.error.code |
| 25 | || extra.error.type | |
| 26 | 0 | res.errno = extra.error.errno |
| 27 | 0 | delete extra.error |
| 28 | } | |
| 29 | 57 | if (caller.file) { |
| 30 | 57 | res.file = caller.file |
| 31 | 57 | res.line = +caller.line |
| 32 | 57 | res.column = +caller.column |
| 33 | } | |
| 34 | 57 | res.stack = caller.stack |
| 35 | ||
| 36 | 57 | res.name = message || "(unnamed assert)" |
| 37 | ||
| 38 | 114 | if (extra) Object.keys(extra).forEach(function (k) { |
| 39 | 228 | if (!res.hasOwnProperty(k)) res[k] = extra[k] |
| 40 | }) | |
| 41 | ||
| 42 | // strings and objects are hard to diff by eye | |
| 43 | 57 | if (!ok && |
| 44 | res.hasOwnProperty("found") && | |
| 45 | res.hasOwnProperty("wanted") && | |
| 46 | res.found !== res.wanted) { | |
| 47 | 0 | if (typeof res.wanted !== typeof res.found || |
| 48 | typeof res.wanted === "object" && (!res.found || !res.wanted)) { | |
| 49 | 0 | res.type = { found: typeof found |
| 50 | , wanted: typeof wanted } | |
| 51 | 0 | } else if (typeof res.wanted === "string") { |
| 52 | 0 | res.diff = diffString(res.found, res.wanted) |
| 53 | 0 | } else if (typeof res.wanted === "object") { |
| 54 | 0 | res.diff = diffObject(res.found, res.wanted) |
| 55 | } | |
| 56 | } | |
| 57 | ||
| 58 | //console.error("assert return", res) | |
| 59 | ||
| 60 | 57 | return res |
| 61 | } | |
| 62 | 1 | assert.ok = assert |
| 63 | 1 | syns.ok = [ "true", "assert" ] |
| 64 | ||
| 65 | ||
| 66 | 1 | function notOk (ok, message, extra) { |
| 67 | 0 | return assert(!ok, message, extra) |
| 68 | } | |
| 69 | 1 | assert.notOk = notOk |
| 70 | 1 | syns.notOk = [ "false", "notok" ] |
| 71 | ||
| 72 | 1 | function error (er, message, extra) { |
| 73 | 0 | if (!er) { |
| 74 | // just like notOk(er) | |
| 75 | 0 | return assert(!er, message, extra) |
| 76 | } | |
| 77 | 0 | message = message || er.message |
| 78 | 0 | extra = extra || {} |
| 79 | 0 | extra.error = er |
| 80 | 0 | return assert.fail(message, extra) |
| 81 | } | |
| 82 | 1 | assert.error = error |
| 83 | 1 | syns.error = [ "ifError", "ifErr", "iferror" ] |
| 84 | ||
| 85 | ||
| 86 | 1 | function pass (message, extra) { |
| 87 | 0 | return assert(true, message, extra) |
| 88 | } | |
| 89 | 1 | assert.pass = pass |
| 90 | ||
| 91 | 1 | function fail (message, extra) { |
| 92 | //console.error("assert.fail", [message, extra]) | |
| 93 | //if (extra && extra.skip) return assert.skip(message, extra) | |
| 94 | 0 | return assert(false, message, extra) |
| 95 | } | |
| 96 | 1 | assert.fail = fail |
| 97 | ||
| 98 | 1 | function skip (message, extra) { |
| 99 | //console.error("assert.skip", message, extra) | |
| 100 | 0 | if (!extra) extra = {} |
| 101 | 0 | return { id: id ++, skip: true, name: message || "" } |
| 102 | } | |
| 103 | 1 | assert.skip = skip |
| 104 | ||
| 105 | 1 | function throws (fn, wanted, message, extra) { |
| 106 | 0 | if (typeof wanted === "string") { |
| 107 | 0 | extra = message |
| 108 | 0 | message = wanted |
| 109 | 0 | wanted = null |
| 110 | } | |
| 111 | ||
| 112 | 0 | if (extra && extra.skip) return assert.skip(message, extra) |
| 113 | ||
| 114 | 0 | var found = null |
| 115 | 0 | try { |
| 116 | 0 | fn() |
| 117 | } catch (e) { | |
| 118 | 0 | found = { name: e.name, message: e.message } |
| 119 | } | |
| 120 | ||
| 121 | 0 | extra = extra || {} |
| 122 | ||
| 123 | 0 | extra.found = found |
| 124 | 0 | if (wanted) { |
| 125 | 0 | wanted = { name: wanted.name, message: wanted.message } |
| 126 | 0 | extra.wanted = wanted |
| 127 | } | |
| 128 | ||
| 129 | 0 | if (!message) { |
| 130 | 0 | message = "Expected to throw" |
| 131 | 0 | if (wanted) message += ": "+wanted.name + " " + wanted.message |
| 132 | } | |
| 133 | ||
| 134 | 0 | return (wanted) ? assert.similar(found, wanted, message, extra) |
| 135 | : assert.ok(found, message, extra) | |
| 136 | } | |
| 137 | 1 | assert.throws = throws |
| 138 | ||
| 139 | ||
| 140 | 1 | function doesNotThrow (fn, message, extra) { |
| 141 | 0 | if (extra && extra.skip) return assert.skip(message, extra) |
| 142 | 0 | var found = null |
| 143 | 0 | try { |
| 144 | 0 | fn() |
| 145 | } catch (e) { | |
| 146 | 0 | found = {name: e.name, message: e.message} |
| 147 | } | |
| 148 | 0 | message = message || "Should not throw" |
| 149 | ||
| 150 | 0 | return assert.equal(found, null, message, extra) |
| 151 | } | |
| 152 | 1 | assert.doesNotThrow = doesNotThrow |
| 153 | ||
| 154 | ||
| 155 | 1 | function equal (a, b, message, extra) { |
| 156 | 27 | if (extra && extra.skip) return assert.skip(message, extra) |
| 157 | 27 | extra = extra || {} |
| 158 | 27 | message = message || "should be equal" |
| 159 | 27 | extra.found = a |
| 160 | 27 | extra.wanted = b |
| 161 | 27 | return assert(a === b, message, extra) |
| 162 | } | |
| 163 | 1 | assert.equal = equal |
| 164 | 1 | syns.equal = ["equals" |
| 165 | ,"isEqual" | |
| 166 | ,"is" | |
| 167 | ,"strictEqual" | |
| 168 | ,"strictEquals"] | |
| 169 | ||
| 170 | ||
| 171 | 1 | function equivalent (a, b, message, extra) { |
| 172 | 30 | if (extra && extra.skip) return assert.skip(message, extra) |
| 173 | 30 | var extra = extra || {} |
| 174 | 30 | message = message || "should be equivalent" |
| 175 | 30 | extra.found = a |
| 176 | 30 | extra.wanted = b |
| 177 | ||
| 178 | 30 | if (Buffer.isBuffer(a) && Buffer.isBuffer(b)) { |
| 179 | 0 | return assert(bufferEqual(a, b), message, extra) |
| 180 | } else { | |
| 181 | 30 | return assert(deepEqual(a, b), message, extra) |
| 182 | } | |
| 183 | } | |
| 184 | 1 | assert.equivalent = equivalent |
| 185 | 1 | syns.equivalent = ["isEquivalent" |
| 186 | ,"looseEqual" | |
| 187 | ,"looseEquals" | |
| 188 | ,"isDeeply" | |
| 189 | ,"same" | |
| 190 | ,"deepEqual" | |
| 191 | ,"deepEquals"] | |
| 192 | ||
| 193 | ||
| 194 | 1 | function inequal (a, b, message, extra) { |
| 195 | 0 | if (extra && extra.skip) return assert.skip(message, extra) |
| 196 | 0 | extra = extra || {} |
| 197 | 0 | message = message || "should not be equal" |
| 198 | 0 | extra.found = a |
| 199 | 0 | extra.doNotWant = b |
| 200 | 0 | return assert(a !== b, message, extra) |
| 201 | } | |
| 202 | 1 | assert.inequal = inequal |
| 203 | 1 | syns.inequal = ["notEqual" |
| 204 | ,"notEquals" | |
| 205 | ,"notStrictEqual" | |
| 206 | ,"notStrictEquals" | |
| 207 | ,"isNotEqual" | |
| 208 | ,"isNot" | |
| 209 | ,"not" | |
| 210 | ,"doesNotEqual" | |
| 211 | ,"isInequal"] | |
| 212 | ||
| 213 | ||
| 214 | 1 | function inequivalent (a, b, message, extra) { |
| 215 | 0 | if (extra && extra.skip) return assert.skip(message, extra) |
| 216 | 0 | extra = extra || {} |
| 217 | 0 | message = message || "should not be equivalent" |
| 218 | 0 | extra.found = a |
| 219 | 0 | extra.doNotWant = b |
| 220 | ||
| 221 | 0 | if (Buffer.isBuffer(a) && Buffer.isBuffer(b)) { |
| 222 | 0 | return assert(!bufferEqual(a, b), message, extra) |
| 223 | } else { | |
| 224 | 0 | return assert(!deepEqual(a, b), message, extra) |
| 225 | } | |
| 226 | } | |
| 227 | 1 | assert.inequivalent = inequivalent |
| 228 | 1 | syns.inequivalent = ["notEquivalent" |
| 229 | ,"notDeepEqual" | |
| 230 | ,"notDeeply" | |
| 231 | ,"notSame" | |
| 232 | ,"isNotDeepEqual" | |
| 233 | ,"isNotDeeply" | |
| 234 | ,"isNotEquivalent" | |
| 235 | ,"isInequivalent"] | |
| 236 | ||
| 237 | 1 | function similar (a, b, message, extra, flip) { |
| 238 | 0 | if (extra && extra.skip) return assert.skip(message, extra) |
| 239 | // test that a has all the fields in b | |
| 240 | 0 | message = message || "should be similar" |
| 241 | ||
| 242 | 0 | if (typeof a === "string" && |
| 243 | (Object.prototype.toString.call(b) === "[object RegExp]")) { | |
| 244 | 0 | extra = extra || {} |
| 245 | 0 | extra.pattern = b |
| 246 | 0 | extra.string = a |
| 247 | 0 | var ok = a.match(b) |
| 248 | 0 | extra.match = ok |
| 249 | 0 | if (flip) ok = !ok |
| 250 | 0 | return assert.ok(ok, message, extra) |
| 251 | } | |
| 252 | ||
| 253 | 0 | var isObj = assert(a && typeof a === "object", message, extra) |
| 254 | 0 | if (!isObj.ok) { |
| 255 | // not an object | |
| 256 | 0 | if (a == b) isObj.ok = true |
| 257 | 0 | if (flip) isObj.ok = !isObj.ok |
| 258 | 0 | return isObj |
| 259 | } | |
| 260 | ||
| 261 | 0 | var eq = flip ? inequivalent : equivalent |
| 262 | 0 | return eq(selectFields(a, b), b, message, extra) |
| 263 | } | |
| 264 | 1 | assert.similar = similar |
| 265 | 1 | syns.similar = ["isSimilar" |
| 266 | ,"has" | |
| 267 | ,"hasFields" | |
| 268 | ,"like" | |
| 269 | ,"isLike"] | |
| 270 | ||
| 271 | 1 | function dissimilar (a, b, message, extra) { |
| 272 | 0 | if (extra && extra.skip) return assert.skip(message, extra) |
| 273 | 0 | message = message || "should be dissimilar" |
| 274 | 0 | return similar(a, b, message, extra, true) |
| 275 | } | |
| 276 | 1 | assert.dissimilar = dissimilar |
| 277 | 1 | syns.dissimilar = ["unsimilar" |
| 278 | ,"notSimilar" | |
| 279 | ,"unlike" | |
| 280 | ,"isUnlike" | |
| 281 | ,"notLike" | |
| 282 | ,"isNotLike" | |
| 283 | ,"doesNotHave" | |
| 284 | ,"isNotSimilar" | |
| 285 | ,"isDissimilar"] | |
| 286 | ||
| 287 | 1 | function type (thing, t, message, extra) { |
| 288 | 0 | if (extra && extra.skip) return assert.skip(message, extra) |
| 289 | 0 | var name = t |
| 290 | 0 | if (typeof name === "function") name = name.name || "(anonymous ctor)" |
| 291 | //console.error("name=%s", name) | |
| 292 | 0 | message = message || "type is "+name |
| 293 | 0 | var type = typeof thing |
| 294 | //console.error("type=%s", type) | |
| 295 | 0 | if (!thing && type === "object") type = "null" |
| 296 | 0 | if (type === "object" && t !== "object") { |
| 297 | 0 | if (typeof t === "function") { |
| 298 | //console.error("it is a function!") | |
| 299 | 0 | extra = extra || {} |
| 300 | 0 | extra.found = Object.getPrototypeOf(thing).constructor.name |
| 301 | 0 | extra.wanted = name |
| 302 | //console.error(thing instanceof t, name) | |
| 303 | 0 | return assert.ok(thing instanceof t, message, extra) |
| 304 | } | |
| 305 | ||
| 306 | //console.error("check prototype chain") | |
| 307 | // check against classnames or objects in prototype chain, as well. | |
| 308 | // type(new Error("asdf"), "Error") | |
| 309 | // type(Object.create(foo), foo) | |
| 310 | 0 | var p = thing |
| 311 | 0 | while (p = Object.getPrototypeOf(p)) { |
| 312 | 0 | if (p === t || p.constructor && p.constructor.name === t) { |
| 313 | 0 | type = name |
| 314 | 0 | break |
| 315 | } | |
| 316 | } | |
| 317 | } | |
| 318 | //console.error(type, name, type === name) | |
| 319 | 0 | return assert.equal(type, name, message, extra) |
| 320 | } | |
| 321 | 1 | assert.type = type |
| 322 | 1 | syns.type = ["isa"] |
| 323 | ||
| 324 | // synonyms are helpful. | |
| 325 | 1 | Object.keys(syns).forEach(function (c) { |
| 326 | 10 | syns[c].forEach(function (s) { |
| 327 | 51 | Object.defineProperty(assert, s, { value: assert[c], enumerable: false }) |
| 328 | }) | |
| 329 | }) | |
| 330 | ||
| 331 | // helpers below | |
| 332 | ||
| 333 | 1 | function selectFields (a, b) { |
| 334 | // get the values in A of the fields in B | |
| 335 | 0 | var ret = Array.isArray(b) ? [] : {} |
| 336 | 0 | Object.keys(b).forEach(function (k) { |
| 337 | 0 | if (!a.hasOwnProperty(k)) return |
| 338 | 0 | var v = b[k] |
| 339 | , av = a[k] | |
| 340 | 0 | if (v && av && typeof v === "object" && typeof av === "object" |
| 341 | && !(v instanceof Date) | |
| 342 | && !(v instanceof RegExp) | |
| 343 | && !(v instanceof String) | |
| 344 | && !(v instanceof Boolean) | |
| 345 | && !(v instanceof Number) | |
| 346 | && !(Array.isArray(v))) { | |
| 347 | 0 | ret[k] = selectFields(av, v) |
| 348 | 0 | } else ret[k] = av |
| 349 | }) | |
| 350 | 0 | return ret |
| 351 | } | |
| 352 | ||
| 353 | 1 | function sortObject (obj) { |
| 354 | 0 | if (typeof obj !== 'object' || Array.isArray(obj) || obj === null) { |
| 355 | 0 | return obj |
| 356 | } | |
| 357 | ||
| 358 | 0 | return Object.keys(obj).sort().reduce(function (acc, key) { |
| 359 | 0 | acc[key] = sortObject(obj[key]) |
| 360 | 0 | return acc |
| 361 | }, {}) | |
| 362 | } | |
| 363 | ||
| 364 | 1 | function stringify (a) { |
| 365 | 0 | return JSON.stringify(sortObject(a), (function () { |
| 366 | 0 | var seen = [] |
| 367 | , keys = [] | |
| 368 | 0 | return function (key, val) { |
| 369 | 0 | var s = seen.indexOf(val) |
| 370 | 0 | if (s !== -1) { |
| 371 | 0 | return "[Circular: "+keys[s]+"]" |
| 372 | } | |
| 373 | 0 | if (val && typeof val === "object" || typeof val === "function") { |
| 374 | 0 | seen.push(val) |
| 375 | 0 | keys.push(val["!"] || val.name || key || "<root>") |
| 376 | 0 | if (typeof val === "function") { |
| 377 | 0 | return val.toString().split(/\n/)[0] |
| 378 | 0 | } else if (typeof val.toUTCString === "function") { |
| 379 | 0 | return val.toUTCString() |
| 380 | } | |
| 381 | } | |
| 382 | 0 | return val |
| 383 | }})()) | |
| 384 | } | |
| 385 | ||
| 386 | 1 | function diffString (f, w) { |
| 387 | 0 | if (w === f) return null |
| 388 | 0 | var p = 0 |
| 389 | , l = w.length | |
| 390 | 0 | while (p < l && w.charAt(p) === f.charAt(p)) p ++ |
| 391 | 0 | w = stringify(w).substr(1).replace(/"$/, "") |
| 392 | 0 | f = stringify(f).substr(1).replace(/"$/, "") |
| 393 | 0 | return diff(f, w, p) |
| 394 | } | |
| 395 | ||
| 396 | 1 | function diffObject (f, w) { |
| 397 | 0 | return difflet({ indent : 2, comment : true }).compare(w, f) |
| 398 | } | |
| 399 | ||
| 400 | 1 | function diff (f, w, p) { |
| 401 | 0 | if (w === f) return null |
| 402 | 0 | var i = p || 0 // it's going to be at least p. JSON can only be bigger. |
| 403 | , l = w.length | |
| 404 | 0 | while (i < l && w.charAt(i) === f.charAt(i)) i ++ |
| 405 | 0 | var pos = Math.max(0, i - 20) |
| 406 | 0 | w = w.substr(pos, 40) |
| 407 | 0 | f = f.substr(pos, 40) |
| 408 | 0 | var pointer = i - pos |
| 409 | 0 | return "FOUND: "+f+"\n" |
| 410 | + "WANTED: "+w+"\n" | |
| 411 | + (new Array(pointer + 9).join(" ")) | |
| 412 | + "^ (at position = "+p+")" | |
| 413 | } | |
| 414 | ||
| 415 | 1 | function getCaller (er) { |
| 416 | // get the first file/line that isn't this file. | |
| 417 | 114 | if (!er) er = new Error |
| 418 | 57 | var stack = er.stack || "" |
| 419 | 57 | stack = stack.split(/\n/) |
| 420 | 57 | for (var i = 1, l = stack.length; i < l; i ++) { |
| 421 | 345 | var s = stack[i].match(/\(([^):]+):([0-9]+):([0-9]+)\)$/) |
| 422 | 633 | if (!s) continue |
| 423 | 57 | var file = s[1] |
| 424 | , line = +s[2] | |
| 425 | , col = +s[3] | |
| 426 | 57 | if (file.indexOf(__dirname) === 0) continue |
| 427 | 57 | if (file.match(/tap-test\/test.js$/)) continue |
| 428 | 57 | else break |
| 429 | } | |
| 430 | 57 | var res = {} |
| 431 | 57 | if (file && file !== __filename && !file.match(/tap-test\/test.js$/)) { |
| 432 | 57 | res.file = file |
| 433 | 57 | res.line = line |
| 434 | 57 | res.column = col |
| 435 | } | |
| 436 | ||
| 437 | 57 | res.stack = stack.slice(1).map(function (s) { |
| 438 | 570 | return s.replace(/^\s*at\s*/, "") |
| 439 | }) | |
| 440 | ||
| 441 | 57 | return res |
| 442 | } | |
| 443 | ||
| 444 | ||
| 445 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | var traverse = require('traverse'); |
| 2 | 1 | var Stream = require('stream').Stream; |
| 3 | 1 | var charm = require('charm'); |
| 4 | 1 | var deepEqual = require('deep-is'); |
| 5 | ||
| 6 | 1 | var exports = module.exports = function (opts_) { |
| 7 | 0 | var fn = difflet.bind(null, opts_); |
| 8 | 0 | fn.compare = function (prev, next) { |
| 9 | 0 | var opts = Object.keys(opts_ || {}).reduce(function (acc, key) { |
| 10 | 0 | acc[key] = opts_[key]; |
| 11 | 0 | return acc; |
| 12 | }, {}); | |
| 13 | 0 | var s = opts.stream = new Stream; |
| 14 | 0 | var data = ''; |
| 15 | 0 | s.write = function (buf) { data += buf }; |
| 16 | 0 | s.end = function () {}; |
| 17 | 0 | s.readable = true; |
| 18 | 0 | s.writable = true; |
| 19 | ||
| 20 | 0 | difflet(opts, prev, next); |
| 21 | 0 | return data; |
| 22 | }; | |
| 23 | 0 | return fn; |
| 24 | }; | |
| 25 | ||
| 26 | 1 | exports.compare = function (prev, next) { |
| 27 | 0 | return exports({}).compare(prev, next); |
| 28 | }; | |
| 29 | ||
| 30 | 1 | function difflet (opts, prev, next) { |
| 31 | 0 | var stream = opts.stream || new Stream; |
| 32 | 0 | if (!opts.stream) { |
| 33 | 0 | stream.readable = true; |
| 34 | 0 | stream.writable = true; |
| 35 | 0 | stream.write = function (buf) { this.emit('data', buf) }; |
| 36 | 0 | stream.end = function () { this.emit('end') }; |
| 37 | } | |
| 38 | ||
| 39 | 0 | if (!opts) opts = {}; |
| 40 | 0 | if (opts.start === undefined && opts.stop === undefined) { |
| 41 | 0 | var c = charm(stream); |
| 42 | 0 | opts.start = function (type) { |
| 43 | 0 | c.foreground({ |
| 44 | inserted : 'green', | |
| 45 | updated : 'blue', | |
| 46 | deleted : 'red', | |
| 47 | comment : 'cyan', | |
| 48 | }[type]); | |
| 49 | 0 | c.display('bright'); |
| 50 | }; | |
| 51 | 0 | opts.stop = function (type) { |
| 52 | 0 | c.display('reset'); |
| 53 | }; | |
| 54 | } | |
| 55 | 0 | var write = function (buf) { |
| 56 | 0 | if (opts.write) opts.write(buf, stream) |
| 57 | 0 | else stream.write(buf) |
| 58 | }; | |
| 59 | ||
| 60 | 0 | var commaFirst = opts.comma === 'first'; |
| 61 | ||
| 62 | 0 | var stringify = function (node, params) { |
| 63 | 0 | return stringifier.call(this, true, node, params || opts); |
| 64 | }; | |
| 65 | 0 | var plainStringify = function (node, params) { |
| 66 | 0 | return stringifier.call(this, false, node, params || opts); |
| 67 | }; | |
| 68 | ||
| 69 | 0 | var levels = 0; |
| 70 | 0 | function set (type) { |
| 71 | 0 | if (levels === 0) opts.start(type, stream); |
| 72 | 0 | levels ++; |
| 73 | } | |
| 74 | ||
| 75 | 0 | function unset (type) { |
| 76 | 0 | if (--levels === 0) opts.stop(type, stream); |
| 77 | } | |
| 78 | ||
| 79 | 0 | function stringifier (insertable, node, opts) { |
| 80 | 0 | var indent = opts.indent; |
| 81 | ||
| 82 | 0 | if (insertable) { |
| 83 | 0 | var prevNode = traverse.get(prev, this.path || []); |
| 84 | } | |
| 85 | 0 | var inserted = insertable && prevNode === undefined; |
| 86 | ||
| 87 | 0 | var indentx; |
| 88 | 0 | try { |
| 89 | 0 | indentx = indent ? Array( |
| 90 | ((this.path || []).length + 1) * indent + 1 | |
| 91 | ).join(' ') : ''; | |
| 92 | } catch (e) { | |
| 93 | // at times we get an invalid Array size here and need to prevent crashing | |
| 94 | 0 | indentx = ''; |
| 95 | } | |
| 96 | 0 | if (commaFirst) indentx = indentx.slice(indent); |
| 97 | ||
| 98 | 0 | if (Array.isArray(node)) { |
| 99 | 0 | var updated = (prevNode || traverse.has(prev, this.path)) |
| 100 | && !Array.isArray(prevNode); | |
| 101 | 0 | if (updated) { |
| 102 | 0 | set('updated'); |
| 103 | } | |
| 104 | ||
| 105 | 0 | if (opts.comment && !Array.isArray(prevNode)) { |
| 106 | 0 | indent = 0; |
| 107 | } | |
| 108 | ||
| 109 | 0 | this.before(function () { |
| 110 | 0 | if (inserted) set('inserted'); |
| 111 | 0 | if (indent && commaFirst) { |
| 112 | 0 | if ((this.path || []).length === 0 |
| 113 | || Array.isArray(this.parent.node)) { | |
| 114 | 0 | write('[ '); |
| 115 | } | |
| 116 | 0 | else write('\n' + indentx + '[ '); |
| 117 | } | |
| 118 | 0 | else if (indent) { |
| 119 | 0 | write('[\n' + indentx); |
| 120 | } | |
| 121 | else { | |
| 122 | 0 | write('['); |
| 123 | } | |
| 124 | }); | |
| 125 | ||
| 126 | 0 | this.post(function (child) { |
| 127 | 0 | if (!child.isLast && !(indent && commaFirst)) { |
| 128 | 0 | write(','); |
| 129 | } | |
| 130 | ||
| 131 | 0 | var prev = prevNode && prevNode[child.key]; |
| 132 | 0 | if (indent && opts.comment && child.node !== prev |
| 133 | && (typeof child.node !== 'object' || typeof prev !== 'object') | |
| 134 | ) { | |
| 135 | 0 | set('comment'); |
| 136 | 0 | write(' // != '); |
| 137 | 0 | traverse(prev).forEach(function (x) { |
| 138 | 0 | plainStringify.call(this, x, { indent : 0 }); |
| 139 | }); | |
| 140 | 0 | unset('comment'); |
| 141 | } | |
| 142 | ||
| 143 | 0 | if (!child.isLast) { |
| 144 | 0 | if (indent && commaFirst) { |
| 145 | 0 | write('\n' + indentx + ', '); |
| 146 | } | |
| 147 | 0 | else if (indent) { |
| 148 | 0 | write('\n' + indentx); |
| 149 | } | |
| 150 | } | |
| 151 | }); | |
| 152 | ||
| 153 | 0 | this.after(function () { |
| 154 | 0 | if (indent && commaFirst) write('\n' + indentx); |
| 155 | 0 | else if (indent) write('\n' + indentx.slice(indent)); |
| 156 | ||
| 157 | 0 | write(']'); |
| 158 | 0 | if (updated) unset('updated'); |
| 159 | 0 | if (inserted) unset('inserted'); |
| 160 | }); | |
| 161 | } | |
| 162 | 0 | else if (isRegExp(node)) { |
| 163 | 0 | this.block(); |
| 164 | ||
| 165 | 0 | if (inserted) { |
| 166 | 0 | set('inserted'); |
| 167 | 0 | write(node.toString()); |
| 168 | 0 | unset('inserted'); |
| 169 | } | |
| 170 | 0 | else if (insertable && prevNode !== node) { |
| 171 | 0 | set('updated'); |
| 172 | 0 | write(node.toString()); |
| 173 | 0 | unset('updated'); |
| 174 | } | |
| 175 | 0 | else write(node.toString()); |
| 176 | } | |
| 177 | 0 | else if (typeof node === 'object' |
| 178 | && node && typeof node.inspect === 'function') { | |
| 179 | 0 | this.block(); |
| 180 | 0 | if (inserted) { |
| 181 | 0 | set('inserted'); |
| 182 | 0 | write(node.inspect()); |
| 183 | 0 | unset('inserted'); |
| 184 | } | |
| 185 | 0 | else if (!(prevNode && typeof prevNode.inspect === 'function' |
| 186 | && prevNode.inspect() === node.inspect())) { | |
| 187 | 0 | set('updated'); |
| 188 | 0 | write(node.inspect()); |
| 189 | 0 | unset('updated'); |
| 190 | } | |
| 191 | 0 | else write(node.inspect()); |
| 192 | } | |
| 193 | 0 | else if (typeof node == 'object' && node !== null) { |
| 194 | 0 | var insertedKey = false; |
| 195 | 0 | var deleted = insertable && typeof prevNode === 'object' && prevNode |
| 196 | ? Object.keys(prevNode).filter(function (key) { | |
| 197 | 0 | return !Object.hasOwnProperty.call(node, key); |
| 198 | }) | |
| 199 | : [] | |
| 200 | ; | |
| 201 | ||
| 202 | 0 | this.before(function () { |
| 203 | 0 | if (inserted) set('inserted'); |
| 204 | 0 | write(indent && commaFirst && !this.isRoot |
| 205 | ? '\n' + indentx + '{ ' | |
| 206 | : '{' | |
| 207 | ); | |
| 208 | }); | |
| 209 | ||
| 210 | 0 | this.pre(function (x, key) { |
| 211 | 0 | if (insertable) { |
| 212 | 0 | var obj = traverse.get(prev, this.path.concat(key)); |
| 213 | 0 | if (obj === undefined) { |
| 214 | 0 | insertedKey = true; |
| 215 | 0 | set('inserted'); |
| 216 | } | |
| 217 | } | |
| 218 | ||
| 219 | 0 | if (indent && !commaFirst) write('\n' + indentx); |
| 220 | ||
| 221 | 0 | plainStringify(key); |
| 222 | 0 | write(indent ? ' : ' : ':'); |
| 223 | }); | |
| 224 | ||
| 225 | 0 | this.post(function (child) { |
| 226 | 0 | if (!child.isLast && !(indent && commaFirst)) { |
| 227 | 0 | write(','); |
| 228 | } | |
| 229 | ||
| 230 | 0 | if (child.isLast && deleted.length) { |
| 231 | 0 | if (insertedKey) unset('inserted'); |
| 232 | 0 | insertedKey = false; |
| 233 | } | |
| 234 | 0 | else if (insertedKey) { |
| 235 | 0 | unset('inserted'); |
| 236 | 0 | insertedKey = false; |
| 237 | } | |
| 238 | ||
| 239 | 0 | var prev = prevNode && prevNode[child.key]; |
| 240 | 0 | if (indent && opts.comment && child.node !== prev |
| 241 | && (typeof child.node !== 'object' || typeof prev !== 'object') | |
| 242 | ) { | |
| 243 | 0 | set('comment'); |
| 244 | 0 | write(' // != '); |
| 245 | 0 | traverse(prev).forEach(function (x) { |
| 246 | 0 | plainStringify.call(this, x, { indent : 0 }); |
| 247 | }); | |
| 248 | 0 | unset('comment'); |
| 249 | } | |
| 250 | ||
| 251 | 0 | if (child.isLast && deleted.length) { |
| 252 | 0 | if (insertedKey) unset('inserted'); |
| 253 | 0 | insertedKey = false; |
| 254 | ||
| 255 | 0 | if (indent && commaFirst) { |
| 256 | 0 | write('\n' + indentx + ', ') |
| 257 | } | |
| 258 | 0 | else if (opts.comment && indent) { |
| 259 | 0 | write('\n' + indentx); |
| 260 | } | |
| 261 | 0 | else if (indent) { |
| 262 | 0 | write(',\n' + indentx); |
| 263 | } | |
| 264 | 0 | else write(','); |
| 265 | } | |
| 266 | else { | |
| 267 | 0 | if (!child.isLast) { |
| 268 | 0 | if (indent && commaFirst) { |
| 269 | 0 | write('\n' + indentx + ', '); |
| 270 | } | |
| 271 | } | |
| 272 | } | |
| 273 | }); | |
| 274 | ||
| 275 | 0 | this.after(function () { |
| 276 | 0 | if (inserted) unset('inserted'); |
| 277 | ||
| 278 | 0 | if (deleted.length) { |
| 279 | 0 | if (indent && !commaFirst |
| 280 | && Object.keys(node).length === 0) { | |
| 281 | 0 | write('\n' + indentx); |
| 282 | } | |
| 283 | ||
| 284 | 0 | set('deleted'); |
| 285 | 0 | deleted.forEach(function (key, ix) { |
| 286 | 0 | if (indent && opts.comment) { |
| 287 | 0 | unset('deleted'); |
| 288 | 0 | set('comment'); |
| 289 | 0 | write('// '); |
| 290 | 0 | unset('comment'); |
| 291 | 0 | set('deleted'); |
| 292 | } | |
| 293 | ||
| 294 | 0 | plainStringify(key); |
| 295 | 0 | write(indent ? ' : ' : ':'); |
| 296 | 0 | traverse(prevNode[key]).forEach(function (x) { |
| 297 | 0 | plainStringify.call(this, x, { indent : 0 }); |
| 298 | }); | |
| 299 | ||
| 300 | 0 | var last = ix === deleted.length - 1; |
| 301 | 0 | if (insertable && !last) { |
| 302 | 0 | if (indent && commaFirst) { |
| 303 | 0 | write('\n' + indentx + ', '); |
| 304 | } | |
| 305 | 0 | else if (indent) { |
| 306 | 0 | write(',\n' + indentx); |
| 307 | } | |
| 308 | 0 | else write(','); |
| 309 | } | |
| 310 | }); | |
| 311 | 0 | unset('deleted'); |
| 312 | } | |
| 313 | ||
| 314 | 0 | if (commaFirst && indent) { |
| 315 | 0 | write(indentx.slice(indent) + ' }'); |
| 316 | } | |
| 317 | 0 | else if (indent) { |
| 318 | 0 | write('\n' + indentx.slice(indent) + '}'); |
| 319 | } | |
| 320 | 0 | else write('}'); |
| 321 | }); | |
| 322 | } | |
| 323 | else { | |
| 324 | 0 | var changed = false; |
| 325 | ||
| 326 | 0 | if (inserted) set('inserted'); |
| 327 | 0 | else if (insertable && !deepEqual(prevNode, node)) { |
| 328 | 0 | changed = true; |
| 329 | 0 | set('updated'); |
| 330 | } | |
| 331 | ||
| 332 | 0 | if (typeof node === 'string') { |
| 333 | 0 | write('"' + node.toString().replace(/"/g, '\\"') + '"'); |
| 334 | } | |
| 335 | 0 | else if (isRegExp(node)) { |
| 336 | 0 | write(node.toString()); |
| 337 | } | |
| 338 | 0 | else if (typeof node === 'function') { |
| 339 | 0 | write(node.name |
| 340 | ? '[Function: ' + node.name + ']' | |
| 341 | : '[Function]' | |
| 342 | ); | |
| 343 | } | |
| 344 | 0 | else if (node === undefined) { |
| 345 | 0 | write('undefined'); |
| 346 | } | |
| 347 | 0 | else if (node === null) { |
| 348 | 0 | write('null'); |
| 349 | } | |
| 350 | else { | |
| 351 | 0 | write(node.toString()); |
| 352 | } | |
| 353 | ||
| 354 | 0 | if (inserted) unset('inserted'); |
| 355 | 0 | else if (changed) unset('updated'); |
| 356 | } | |
| 357 | } | |
| 358 | ||
| 359 | 0 | if (opts.stream) { |
| 360 | 0 | traverse(next).forEach(stringify); |
| 361 | } | |
| 362 | 0 | else process.nextTick(function () { |
| 363 | 0 | traverse(next).forEach(stringify); |
| 364 | 0 | stream.emit('end'); |
| 365 | }); | |
| 366 | ||
| 367 | 0 | return stream; |
| 368 | } | |
| 369 | ||
| 370 | 1 | function isRegExp (node) { |
| 371 | 0 | return node instanceof RegExp || (node |
| 372 | && typeof node.test === 'function' | |
| 373 | && typeof node.exec === 'function' | |
| 374 | && typeof node.compile === 'function' | |
| 375 | && node.constructor && node.constructor.name === 'RegExp' | |
| 376 | ); | |
| 377 | } | |
| 378 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | var traverse = module.exports = function (obj) { |
| 2 | 0 | return new Traverse(obj); |
| 3 | }; | |
| 4 | ||
| 5 | 1 | function Traverse (obj) { |
| 6 | 0 | this.value = obj; |
| 7 | } | |
| 8 | ||
| 9 | 1 | Traverse.prototype.get = function (ps) { |
| 10 | 0 | var node = this.value; |
| 11 | 0 | for (var i = 0; i < ps.length; i ++) { |
| 12 | 0 | var key = ps[i]; |
| 13 | 0 | if (!node || !hasOwnProperty.call(node, key)) { |
| 14 | 0 | node = undefined; |
| 15 | 0 | break; |
| 16 | } | |
| 17 | 0 | node = node[key]; |
| 18 | } | |
| 19 | 0 | return node; |
| 20 | }; | |
| 21 | ||
| 22 | 1 | Traverse.prototype.has = function (ps) { |
| 23 | 0 | var node = this.value; |
| 24 | 0 | for (var i = 0; i < ps.length; i ++) { |
| 25 | 0 | var key = ps[i]; |
| 26 | 0 | if (!node || !hasOwnProperty.call(node, key)) { |
| 27 | 0 | return false; |
| 28 | } | |
| 29 | 0 | node = node[key]; |
| 30 | } | |
| 31 | 0 | return true; |
| 32 | }; | |
| 33 | ||
| 34 | 1 | Traverse.prototype.set = function (ps, value) { |
| 35 | 0 | var node = this.value; |
| 36 | 0 | for (var i = 0; i < ps.length - 1; i ++) { |
| 37 | 0 | var key = ps[i]; |
| 38 | 0 | if (!hasOwnProperty.call(node, key)) node[key] = {}; |
| 39 | 0 | node = node[key]; |
| 40 | } | |
| 41 | 0 | node[ps[i]] = value; |
| 42 | 0 | return value; |
| 43 | }; | |
| 44 | ||
| 45 | 1 | Traverse.prototype.map = function (cb) { |
| 46 | 0 | return walk(this.value, cb, true); |
| 47 | }; | |
| 48 | ||
| 49 | 1 | Traverse.prototype.forEach = function (cb) { |
| 50 | 0 | this.value = walk(this.value, cb, false); |
| 51 | 0 | return this.value; |
| 52 | }; | |
| 53 | ||
| 54 | 1 | Traverse.prototype.reduce = function (cb, init) { |
| 55 | 0 | var skip = arguments.length === 1; |
| 56 | 0 | var acc = skip ? this.value : init; |
| 57 | 0 | this.forEach(function (x) { |
| 58 | 0 | if (!this.isRoot || !skip) { |
| 59 | 0 | acc = cb.call(this, acc, x); |
| 60 | } | |
| 61 | }); | |
| 62 | 0 | return acc; |
| 63 | }; | |
| 64 | ||
| 65 | 1 | Traverse.prototype.paths = function () { |
| 66 | 0 | var acc = []; |
| 67 | 0 | this.forEach(function (x) { |
| 68 | 0 | acc.push(this.path); |
| 69 | }); | |
| 70 | 0 | return acc; |
| 71 | }; | |
| 72 | ||
| 73 | 1 | Traverse.prototype.nodes = function () { |
| 74 | 0 | var acc = []; |
| 75 | 0 | this.forEach(function (x) { |
| 76 | 0 | acc.push(this.node); |
| 77 | }); | |
| 78 | 0 | return acc; |
| 79 | }; | |
| 80 | ||
| 81 | 1 | Traverse.prototype.clone = function () { |
| 82 | 0 | var parents = [], nodes = []; |
| 83 | ||
| 84 | 0 | return (function clone (src) { |
| 85 | 0 | for (var i = 0; i < parents.length; i++) { |
| 86 | 0 | if (parents[i] === src) { |
| 87 | 0 | return nodes[i]; |
| 88 | } | |
| 89 | } | |
| 90 | ||
| 91 | 0 | if (typeof src === 'object' && src !== null) { |
| 92 | 0 | var dst = copy(src); |
| 93 | ||
| 94 | 0 | parents.push(src); |
| 95 | 0 | nodes.push(dst); |
| 96 | ||
| 97 | 0 | forEach(objectKeys(src), function (key) { |
| 98 | 0 | dst[key] = clone(src[key]); |
| 99 | }); | |
| 100 | ||
| 101 | 0 | parents.pop(); |
| 102 | 0 | nodes.pop(); |
| 103 | 0 | return dst; |
| 104 | } | |
| 105 | else { | |
| 106 | 0 | return src; |
| 107 | } | |
| 108 | })(this.value); | |
| 109 | }; | |
| 110 | ||
| 111 | 1 | function walk (root, cb, immutable) { |
| 112 | 0 | var path = []; |
| 113 | 0 | var parents = []; |
| 114 | 0 | var alive = true; |
| 115 | ||
| 116 | 0 | return (function walker (node_) { |
| 117 | 0 | var node = immutable ? copy(node_) : node_; |
| 118 | 0 | var modifiers = {}; |
| 119 | ||
| 120 | 0 | var keepGoing = true; |
| 121 | ||
| 122 | 0 | var state = { |
| 123 | node : node, | |
| 124 | node_ : node_, | |
| 125 | path : [].concat(path), | |
| 126 | parent : parents[parents.length - 1], | |
| 127 | parents : parents, | |
| 128 | key : path.slice(-1)[0], | |
| 129 | isRoot : path.length === 0, | |
| 130 | level : path.length, | |
| 131 | circular : null, | |
| 132 | update : function (x, stopHere) { | |
| 133 | 0 | if (!state.isRoot) { |
| 134 | 0 | state.parent.node[state.key] = x; |
| 135 | } | |
| 136 | 0 | state.node = x; |
| 137 | 0 | if (stopHere) keepGoing = false; |
| 138 | }, | |
| 139 | 'delete' : function (stopHere) { | |
| 140 | 0 | delete state.parent.node[state.key]; |
| 141 | 0 | if (stopHere) keepGoing = false; |
| 142 | }, | |
| 143 | remove : function (stopHere) { | |
| 144 | 0 | if (isArray(state.parent.node)) { |
| 145 | 0 | state.parent.node.splice(state.key, 1); |
| 146 | } | |
| 147 | else { | |
| 148 | 0 | delete state.parent.node[state.key]; |
| 149 | } | |
| 150 | 0 | if (stopHere) keepGoing = false; |
| 151 | }, | |
| 152 | keys : null, | |
| 153 | 0 | before : function (f) { modifiers.before = f }, |
| 154 | 0 | after : function (f) { modifiers.after = f }, |
| 155 | 0 | pre : function (f) { modifiers.pre = f }, |
| 156 | 0 | post : function (f) { modifiers.post = f }, |
| 157 | 0 | stop : function () { alive = false }, |
| 158 | 0 | block : function () { keepGoing = false } |
| 159 | }; | |
| 160 | ||
| 161 | 0 | if (!alive) return state; |
| 162 | ||
| 163 | 0 | function updateState() { |
| 164 | 0 | if (typeof state.node === 'object' && state.node !== null) { |
| 165 | 0 | if (!state.keys || state.node_ !== state.node) { |
| 166 | 0 | state.keys = objectKeys(state.node) |
| 167 | } | |
| 168 | ||
| 169 | 0 | state.isLeaf = state.keys.length == 0; |
| 170 | ||
| 171 | 0 | for (var i = 0; i < parents.length; i++) { |
| 172 | 0 | if (parents[i].node_ === node_) { |
| 173 | 0 | state.circular = parents[i]; |
| 174 | 0 | break; |
| 175 | } | |
| 176 | } | |
| 177 | } | |
| 178 | else { | |
| 179 | 0 | state.isLeaf = true; |
| 180 | 0 | state.keys = null; |
| 181 | } | |
| 182 | ||
| 183 | 0 | state.notLeaf = !state.isLeaf; |
| 184 | 0 | state.notRoot = !state.isRoot; |
| 185 | } | |
| 186 | ||
| 187 | 0 | updateState(); |
| 188 | ||
| 189 | // use return values to update if defined | |
| 190 | 0 | var ret = cb.call(state, state.node); |
| 191 | 0 | if (ret !== undefined && state.update) state.update(ret); |
| 192 | ||
| 193 | 0 | if (modifiers.before) modifiers.before.call(state, state.node); |
| 194 | ||
| 195 | 0 | if (!keepGoing) return state; |
| 196 | ||
| 197 | 0 | if (typeof state.node == 'object' |
| 198 | && state.node !== null && !state.circular) { | |
| 199 | 0 | parents.push(state); |
| 200 | ||
| 201 | 0 | updateState(); |
| 202 | ||
| 203 | 0 | forEach(state.keys, function (key, i) { |
| 204 | 0 | path.push(key); |
| 205 | ||
| 206 | 0 | if (modifiers.pre) modifiers.pre.call(state, state.node[key], key); |
| 207 | ||
| 208 | 0 | var child = walker(state.node[key]); |
| 209 | 0 | if (immutable && hasOwnProperty.call(state.node, key)) { |
| 210 | 0 | state.node[key] = child.node; |
| 211 | } | |
| 212 | ||
| 213 | 0 | child.isLast = i == state.keys.length - 1; |
| 214 | 0 | child.isFirst = i == 0; |
| 215 | ||
| 216 | 0 | if (modifiers.post) modifiers.post.call(state, child); |
| 217 | ||
| 218 | 0 | path.pop(); |
| 219 | }); | |
| 220 | 0 | parents.pop(); |
| 221 | } | |
| 222 | ||
| 223 | 0 | if (modifiers.after) modifiers.after.call(state, state.node); |
| 224 | ||
| 225 | 0 | return state; |
| 226 | })(root).node; | |
| 227 | } | |
| 228 | ||
| 229 | 1 | function copy (src) { |
| 230 | 0 | if (typeof src === 'object' && src !== null) { |
| 231 | 0 | var dst; |
| 232 | ||
| 233 | 0 | if (isArray(src)) { |
| 234 | 0 | dst = []; |
| 235 | } | |
| 236 | 0 | else if (isDate(src)) { |
| 237 | 0 | dst = new Date(src.getTime ? src.getTime() : src); |
| 238 | } | |
| 239 | 0 | else if (isRegExp(src)) { |
| 240 | 0 | dst = new RegExp(src); |
| 241 | } | |
| 242 | 0 | else if (isError(src)) { |
| 243 | 0 | dst = { message: src.message }; |
| 244 | } | |
| 245 | 0 | else if (isBoolean(src)) { |
| 246 | 0 | dst = new Boolean(src); |
| 247 | } | |
| 248 | 0 | else if (isNumber(src)) { |
| 249 | 0 | dst = new Number(src); |
| 250 | } | |
| 251 | 0 | else if (isString(src)) { |
| 252 | 0 | dst = new String(src); |
| 253 | } | |
| 254 | 0 | else if (Object.create && Object.getPrototypeOf) { |
| 255 | 0 | dst = Object.create(Object.getPrototypeOf(src)); |
| 256 | } | |
| 257 | 0 | else if (src.constructor === Object) { |
| 258 | 0 | dst = {}; |
| 259 | } | |
| 260 | else { | |
| 261 | 0 | var proto = |
| 262 | (src.constructor && src.constructor.prototype) | |
| 263 | || src.__proto__ | |
| 264 | || {} | |
| 265 | ; | |
| 266 | 0 | var T = function () {}; |
| 267 | 0 | T.prototype = proto; |
| 268 | 0 | dst = new T; |
| 269 | } | |
| 270 | ||
| 271 | 0 | forEach(objectKeys(src), function (key) { |
| 272 | 0 | dst[key] = src[key]; |
| 273 | }); | |
| 274 | 0 | return dst; |
| 275 | } | |
| 276 | 0 | else return src; |
| 277 | } | |
| 278 | ||
| 279 | 1 | var objectKeys = Object.keys || function keys (obj) { |
| 280 | 0 | var res = []; |
| 281 | 0 | for (var key in obj) res.push(key) |
| 282 | 0 | return res; |
| 283 | }; | |
| 284 | ||
| 285 | 1 | function toS (obj) { return Object.prototype.toString.call(obj) } |
| 286 | 1 | function isDate (obj) { return toS(obj) === '[object Date]' } |
| 287 | 1 | function isRegExp (obj) { return toS(obj) === '[object RegExp]' } |
| 288 | 1 | function isError (obj) { return toS(obj) === '[object Error]' } |
| 289 | 1 | function isBoolean (obj) { return toS(obj) === '[object Boolean]' } |
| 290 | 1 | function isNumber (obj) { return toS(obj) === '[object Number]' } |
| 291 | 1 | function isString (obj) { return toS(obj) === '[object String]' } |
| 292 | ||
| 293 | 1 | var isArray = Array.isArray || function isArray (xs) { |
| 294 | 0 | return Object.prototype.toString.call(xs) === '[object Array]'; |
| 295 | }; | |
| 296 | ||
| 297 | 1 | var forEach = function (xs, fn) { |
| 298 | 2 | if (xs.forEach) return xs.forEach(fn) |
| 299 | 0 | else for (var i = 0; i < xs.length; i++) { |
| 300 | 0 | fn(xs[i], i, xs); |
| 301 | } | |
| 302 | }; | |
| 303 | ||
| 304 | 1 | forEach(objectKeys(Traverse.prototype), function (key) { |
| 305 | 9 | traverse[key] = function (obj) { |
| 306 | 0 | var args = [].slice.call(arguments, 1); |
| 307 | 0 | var t = new Traverse(obj); |
| 308 | 0 | return t[key].apply(t, args); |
| 309 | }; | |
| 310 | }); | |
| 311 | ||
| 312 | 1 | var hasOwnProperty = Object.hasOwnProperty || function (obj, key) { |
| 313 | 0 | return key in obj; |
| 314 | }; | |
| 315 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | var tty = require('tty'); |
| 2 | 1 | var encode = require('./lib/encode'); |
| 3 | 1 | var Stream = require('stream').Stream; |
| 4 | ||
| 5 | 1 | var exports = module.exports = function () { |
| 6 | 0 | var input = null; |
| 7 | 0 | function setInput (s) { |
| 8 | 0 | if (input) throw new Error('multiple inputs specified') |
| 9 | 0 | else input = s |
| 10 | } | |
| 11 | ||
| 12 | 0 | var output = null; |
| 13 | 0 | function setOutput (s) { |
| 14 | 0 | if (output) throw new Error('multiple outputs specified') |
| 15 | 0 | else output = s |
| 16 | } | |
| 17 | ||
| 18 | 0 | for (var i = 0; i < arguments.length; i++) { |
| 19 | 0 | var arg = arguments[i]; |
| 20 | 0 | if (!arg) continue; |
| 21 | 0 | if (arg.readable) setInput(arg) |
| 22 | 0 | else if (arg.stdin || arg.input) setInput(arg.stdin || arg.input) |
| 23 | ||
| 24 | 0 | if (arg.writable) setOutput(arg) |
| 25 | 0 | else if (arg.stdout || arg.output) setOutput(arg.stdout || arg.output) |
| 26 | ||
| 27 | } | |
| 28 | ||
| 29 | 0 | if (input && typeof input.fd === 'number' && tty.isatty(input.fd)) { |
| 30 | 0 | if (process.stdin.setRawMode) { |
| 31 | 0 | process.stdin.setRawMode(true); |
| 32 | } | |
| 33 | 0 | else tty.setRawMode(true); |
| 34 | } | |
| 35 | ||
| 36 | 0 | var charm = new Charm; |
| 37 | 0 | if (input) { |
| 38 | 0 | input.pipe(charm); |
| 39 | } | |
| 40 | ||
| 41 | 0 | if (output) { |
| 42 | 0 | charm.pipe(output); |
| 43 | } | |
| 44 | ||
| 45 | 0 | charm.once('^C', process.exit); |
| 46 | 0 | charm.once('end', function () { |
| 47 | 0 | if (input) { |
| 48 | 0 | if (typeof input.fd === 'number' && tty.isatty(input.fd)) { |
| 49 | 0 | if (process.stdin.setRawMode) { |
| 50 | 0 | process.stdin.setRawMode(false); |
| 51 | } | |
| 52 | 0 | else tty.setRawMode(false); |
| 53 | } | |
| 54 | 0 | input.destroy(); |
| 55 | } | |
| 56 | }); | |
| 57 | ||
| 58 | 0 | return charm; |
| 59 | }; | |
| 60 | ||
| 61 | 1 | var Charm = exports.Charm = function Charm () { |
| 62 | 0 | this.writable = true; |
| 63 | 0 | this.readable = true; |
| 64 | 0 | this.pending = []; |
| 65 | } | |
| 66 | ||
| 67 | 1 | Charm.prototype = new Stream; |
| 68 | ||
| 69 | 1 | Charm.prototype.write = function (buf) { |
| 70 | 0 | var self = this; |
| 71 | ||
| 72 | 0 | if (self.pending.length) { |
| 73 | 0 | var codes = extractCodes(buf); |
| 74 | 0 | var matched = false; |
| 75 | ||
| 76 | 0 | for (var i = 0; i < codes.length; i++) { |
| 77 | 0 | for (var j = 0; j < self.pending.length; j++) { |
| 78 | 0 | var cb = self.pending[j]; |
| 79 | 0 | if (cb(codes[i])) { |
| 80 | 0 | matched = true; |
| 81 | 0 | self.pending.splice(j, 1); |
| 82 | 0 | break; |
| 83 | } | |
| 84 | } | |
| 85 | } | |
| 86 | ||
| 87 | 0 | if (matched) return; |
| 88 | } | |
| 89 | ||
| 90 | 0 | if (buf.length === 1) { |
| 91 | 0 | if (buf[0] === 3) self.emit('^C'); |
| 92 | 0 | if (buf[0] === 4) self.emit('^D'); |
| 93 | } | |
| 94 | ||
| 95 | 0 | self.emit('data', buf); |
| 96 | ||
| 97 | 0 | return self; |
| 98 | }; | |
| 99 | ||
| 100 | ||
| 101 | 1 | Charm.prototype.destroy = function () { |
| 102 | 0 | this.end(); |
| 103 | }; | |
| 104 | ||
| 105 | 1 | Charm.prototype.end = function (buf) { |
| 106 | 0 | if (buf) this.write(buf); |
| 107 | 0 | this.emit('end'); |
| 108 | }; | |
| 109 | ||
| 110 | 1 | Charm.prototype.reset = function (cb) { |
| 111 | 0 | this.write(encode('c')); |
| 112 | 0 | return this; |
| 113 | }; | |
| 114 | ||
| 115 | 1 | Charm.prototype.position = function (x, y) { |
| 116 | // get/set absolute coordinates | |
| 117 | 0 | if (typeof x === 'function') { |
| 118 | 0 | var cb = x; |
| 119 | 0 | this.pending.push(function (buf) { |
| 120 | 0 | if (buf[0] === 27 && buf[1] === encode.ord('[') |
| 121 | && buf[buf.length-1] === encode.ord('R')) { | |
| 122 | 0 | var pos = buf.toString() |
| 123 | .slice(2,-1) | |
| 124 | .split(';') | |
| 125 | .map(Number) | |
| 126 | ; | |
| 127 | 0 | cb(pos[1], pos[0]); |
| 128 | 0 | return true; |
| 129 | } | |
| 130 | }); | |
| 131 | 0 | this.write(encode('[6n')); |
| 132 | } | |
| 133 | else { | |
| 134 | 0 | this.write(encode( |
| 135 | '[' + Math.floor(y) + ';' + Math.floor(x) + 'f' | |
| 136 | )); | |
| 137 | } | |
| 138 | 0 | return this; |
| 139 | }; | |
| 140 | ||
| 141 | 1 | Charm.prototype.move = function (x, y) { |
| 142 | // set relative coordinates | |
| 143 | 0 | var bufs = []; |
| 144 | ||
| 145 | 0 | if (y < 0) this.up(-y) |
| 146 | 0 | else if (y > 0) this.down(y) |
| 147 | ||
| 148 | 0 | if (x > 0) this.right(x) |
| 149 | 0 | else if (x < 0) this.left(-x) |
| 150 | ||
| 151 | 0 | return this; |
| 152 | }; | |
| 153 | ||
| 154 | 1 | Charm.prototype.up = function (y) { |
| 155 | 0 | if (y === undefined) y = 1; |
| 156 | 0 | this.write(encode('[' + Math.floor(y) + 'A')); |
| 157 | 0 | return this; |
| 158 | }; | |
| 159 | ||
| 160 | 1 | Charm.prototype.down = function (y) { |
| 161 | 0 | if (y === undefined) y = 1; |
| 162 | 0 | this.write(encode('[' + Math.floor(y) + 'B')); |
| 163 | 0 | return this; |
| 164 | }; | |
| 165 | ||
| 166 | 1 | Charm.prototype.right = function (x) { |
| 167 | 0 | if (x === undefined) x = 1; |
| 168 | 0 | this.write(encode('[' + Math.floor(x) + 'C')); |
| 169 | 0 | return this; |
| 170 | }; | |
| 171 | ||
| 172 | 1 | Charm.prototype.left = function (x) { |
| 173 | 0 | if (x === undefined) x = 1; |
| 174 | 0 | this.write(encode('[' + Math.floor(x) + 'D')); |
| 175 | 0 | return this; |
| 176 | }; | |
| 177 | ||
| 178 | 1 | Charm.prototype.column = function (x) { |
| 179 | 0 | this.write(encode('[' + Math.floor(x) + 'G')); |
| 180 | 0 | return this; |
| 181 | }; | |
| 182 | ||
| 183 | 1 | Charm.prototype.push = function (withAttributes) { |
| 184 | 0 | this.write(encode(withAttributes ? '7' : '[s')); |
| 185 | 0 | return this; |
| 186 | }; | |
| 187 | ||
| 188 | 1 | Charm.prototype.pop = function (withAttributes) { |
| 189 | 0 | this.write(encode(withAttributes ? '8' : '[u')); |
| 190 | 0 | return this; |
| 191 | }; | |
| 192 | ||
| 193 | 1 | Charm.prototype.erase = function (s) { |
| 194 | 0 | if (s === 'end' || s === '$') { |
| 195 | 0 | this.write(encode('[K')); |
| 196 | } | |
| 197 | 0 | else if (s === 'start' || s === '^') { |
| 198 | 0 | this.write(encode('[1K')); |
| 199 | } | |
| 200 | 0 | else if (s === 'line') { |
| 201 | 0 | this.write(encode('[2K')); |
| 202 | } | |
| 203 | 0 | else if (s === 'down') { |
| 204 | 0 | this.write(encode('[J')); |
| 205 | } | |
| 206 | 0 | else if (s === 'up') { |
| 207 | 0 | this.write(encode('[1J')); |
| 208 | } | |
| 209 | 0 | else if (s === 'screen') { |
| 210 | 0 | this.write(encode('[1J')); |
| 211 | } | |
| 212 | else { | |
| 213 | 0 | this.emit('error', new Error('Unknown erase type: ' + s)); |
| 214 | } | |
| 215 | 0 | return this; |
| 216 | }; | |
| 217 | ||
| 218 | 1 | Charm.prototype.display = function (attr) { |
| 219 | 0 | var c = { |
| 220 | reset : 0, | |
| 221 | bright : 1, | |
| 222 | dim : 2, | |
| 223 | underscore : 4, | |
| 224 | blink : 5, | |
| 225 | reverse : 7, | |
| 226 | hidden : 8 | |
| 227 | }[attr]; | |
| 228 | 0 | if (c === undefined) { |
| 229 | 0 | this.emit('error', new Error('Unknown attribute: ' + attr)); |
| 230 | } | |
| 231 | 0 | this.write(encode('[' + c + 'm')); |
| 232 | 0 | return this; |
| 233 | }; | |
| 234 | ||
| 235 | 1 | Charm.prototype.foreground = function (color) { |
| 236 | 0 | if (typeof color === 'number') { |
| 237 | 0 | if (color < 0 || color >= 256) { |
| 238 | 0 | this.emit('error', new Error('Color out of range: ' + color)); |
| 239 | } | |
| 240 | 0 | this.write(encode('[38;5;' + color + 'm')); |
| 241 | } | |
| 242 | else { | |
| 243 | 0 | var c = { |
| 244 | black : 30, | |
| 245 | red : 31, | |
| 246 | green : 32, | |
| 247 | yellow : 33, | |
| 248 | blue : 34, | |
| 249 | magenta : 35, | |
| 250 | cyan : 36, | |
| 251 | white : 37 | |
| 252 | }[color.toLowerCase()]; | |
| 253 | ||
| 254 | 0 | if (!c) this.emit('error', new Error('Unknown color: ' + color)); |
| 255 | 0 | this.write(encode('[' + c + 'm')); |
| 256 | } | |
| 257 | 0 | return this; |
| 258 | }; | |
| 259 | ||
| 260 | 1 | Charm.prototype.background = function (color) { |
| 261 | 0 | if (typeof color === 'number') { |
| 262 | 0 | if (color < 0 || color >= 256) { |
| 263 | 0 | this.emit('error', new Error('Color out of range: ' + color)); |
| 264 | } | |
| 265 | 0 | this.write(encode('[48;5;' + color + 'm')); |
| 266 | } | |
| 267 | else { | |
| 268 | 0 | var c = { |
| 269 | black : 40, | |
| 270 | red : 41, | |
| 271 | green : 42, | |
| 272 | yellow : 43, | |
| 273 | blue : 44, | |
| 274 | magenta : 45, | |
| 275 | cyan : 46, | |
| 276 | white : 47 | |
| 277 | }[color.toLowerCase()]; | |
| 278 | ||
| 279 | 0 | if (!c) this.emit('error', new Error('Unknown color: ' + color)); |
| 280 | 0 | this.write(encode('[' + c + 'm')); |
| 281 | } | |
| 282 | 0 | return this; |
| 283 | }; | |
| 284 | ||
| 285 | 1 | Charm.prototype.cursor = function (visible) { |
| 286 | 0 | this.write(encode(visible ? '[?25h' : '[?25l')); |
| 287 | 0 | return this; |
| 288 | }; | |
| 289 | ||
| 290 | 1 | var extractCodes = exports.extractCodes = function (buf) { |
| 291 | 0 | var codes = []; |
| 292 | 0 | var start = -1; |
| 293 | ||
| 294 | 0 | for (var i = 0; i < buf.length; i++) { |
| 295 | 0 | if (buf[i] === 27) { |
| 296 | 0 | if (start >= 0) codes.push(buf.slice(start, i)); |
| 297 | 0 | start = i; |
| 298 | } | |
| 299 | 0 | else if (start >= 0 && i === buf.length - 1) { |
| 300 | 0 | codes.push(buf.slice(start)); |
| 301 | } | |
| 302 | } | |
| 303 | ||
| 304 | 0 | return codes; |
| 305 | } | |
| 306 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | var encode = module.exports = function (xs) { |
| 2 | 0 | function bytes (s) { |
| 3 | 0 | if (typeof s === 'string') { |
| 4 | 0 | return s.split('').map(ord); |
| 5 | } | |
| 6 | 0 | else if (Array.isArray(s)) { |
| 7 | 0 | return s.reduce(function (acc, c) { |
| 8 | 0 | return acc.concat(bytes(c)); |
| 9 | }, []); | |
| 10 | } | |
| 11 | } | |
| 12 | ||
| 13 | 0 | return new Buffer([ 0x1b ].concat(bytes(xs))); |
| 14 | }; | |
| 15 | ||
| 16 | 1 | var ord = encode.ord = function ord (c) { |
| 17 | 0 | return c.charCodeAt(0) |
| 18 | }; | |
| 19 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | var pSlice = Array.prototype.slice; |
| 2 | 1 | var Object_keys = typeof Object.keys === 'function' |
| 3 | ? Object.keys | |
| 4 | : function (obj) { | |
| 5 | 0 | var keys = []; |
| 6 | 0 | for (var key in obj) keys.push(key); |
| 7 | 0 | return keys; |
| 8 | } | |
| 9 | ; | |
| 10 | ||
| 11 | 1 | var deepEqual = module.exports = function (actual, expected) { |
| 12 | // enforce Object.is +0 !== -0 | |
| 13 | 0 | if (actual === 0 && expected === 0) { |
| 14 | 0 | return areZerosEqual(actual, expected); |
| 15 | ||
| 16 | // 7.1. All identical values are equivalent, as determined by ===. | |
| 17 | 0 | } else if (actual === expected) { |
| 18 | 0 | return true; |
| 19 | ||
| 20 | 0 | } else if (actual instanceof Date && expected instanceof Date) { |
| 21 | 0 | return actual.getTime() === expected.getTime(); |
| 22 | ||
| 23 | 0 | } else if (isNumberNaN(actual)) { |
| 24 | 0 | return isNumberNaN(expected); |
| 25 | ||
| 26 | // 7.3. Other pairs that do not both pass typeof value == 'object', | |
| 27 | // equivalence is determined by ==. | |
| 28 | 0 | } else if (typeof actual != 'object' && typeof expected != 'object') { |
| 29 | 0 | return actual == expected; |
| 30 | ||
| 31 | // 7.4. For all other Object pairs, including Array objects, equivalence is | |
| 32 | // determined by having the same number of owned properties (as verified | |
| 33 | // with Object.prototype.hasOwnProperty.call), the same set of keys | |
| 34 | // (although not necessarily the same order), equivalent values for every | |
| 35 | // corresponding key, and an identical 'prototype' property. Note: this | |
| 36 | // accounts for both named and indexed properties on Arrays. | |
| 37 | } else { | |
| 38 | 0 | return objEquiv(actual, expected); |
| 39 | } | |
| 40 | }; | |
| 41 | ||
| 42 | 1 | function isUndefinedOrNull(value) { |
| 43 | 0 | return value === null || value === undefined; |
| 44 | } | |
| 45 | ||
| 46 | 1 | function isArguments(object) { |
| 47 | 0 | return Object.prototype.toString.call(object) == '[object Arguments]'; |
| 48 | } | |
| 49 | ||
| 50 | 1 | function isNumberNaN(value) { |
| 51 | // NaN === NaN -> false | |
| 52 | 0 | return typeof value == 'number' && value !== value; |
| 53 | } | |
| 54 | ||
| 55 | 1 | function areZerosEqual(zeroA, zeroB) { |
| 56 | // (1 / +0|0) -> Infinity, but (1 / -0) -> -Infinity and (Infinity !== -Infinity) | |
| 57 | 0 | return (1 / zeroA) === (1 / zeroB); |
| 58 | } | |
| 59 | ||
| 60 | 1 | function objEquiv(a, b) { |
| 61 | 0 | if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) |
| 62 | 0 | return false; |
| 63 | ||
| 64 | // an identical 'prototype' property. | |
| 65 | 0 | if (a.prototype !== b.prototype) return false; |
| 66 | //~~~I've managed to break Object.keys through screwy arguments passing. | |
| 67 | // Converting to array solves the problem. | |
| 68 | 0 | if (isArguments(a)) { |
| 69 | 0 | if (!isArguments(b)) { |
| 70 | 0 | return false; |
| 71 | } | |
| 72 | 0 | a = pSlice.call(a); |
| 73 | 0 | b = pSlice.call(b); |
| 74 | 0 | return deepEqual(a, b); |
| 75 | } | |
| 76 | 0 | try { |
| 77 | 0 | var ka = Object_keys(a), |
| 78 | kb = Object_keys(b), | |
| 79 | key, i; | |
| 80 | } catch (e) {//happens when one is a string literal and the other isn't | |
| 81 | 0 | return false; |
| 82 | } | |
| 83 | // having the same number of owned properties (keys incorporates | |
| 84 | // hasOwnProperty) | |
| 85 | 0 | if (ka.length != kb.length) |
| 86 | 0 | return false; |
| 87 | //the same set of keys (although not necessarily the same order), | |
| 88 | 0 | ka.sort(); |
| 89 | 0 | kb.sort(); |
| 90 | //~~~cheap key test | |
| 91 | 0 | for (i = ka.length - 1; i >= 0; i--) { |
| 92 | 0 | if (ka[i] != kb[i]) |
| 93 | 0 | return false; |
| 94 | } | |
| 95 | //equivalent values for every corresponding key, and | |
| 96 | //~~~possibly expensive deep test | |
| 97 | 0 | for (i = ka.length - 1; i >= 0; i--) { |
| 98 | 0 | key = ka[i]; |
| 99 | 0 | if (!deepEqual(a[key], b[key])) return false; |
| 100 | } | |
| 101 | 0 | return true; |
| 102 | } | |
| 103 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | var pSlice = Array.prototype.slice; |
| 2 | 1 | var Object_keys = typeof Object.keys === 'function' |
| 3 | ? Object.keys | |
| 4 | : function (obj) { | |
| 5 | 0 | var keys = []; |
| 6 | 0 | for (var key in obj) keys.push(key); |
| 7 | 0 | return keys; |
| 8 | } | |
| 9 | ; | |
| 10 | ||
| 11 | 1 | var deepEqual = module.exports = function (actual, expected) { |
| 12 | // 7.1. All identical values are equivalent, as determined by ===. | |
| 13 | 127 | if (actual === expected) { |
| 14 | 84 | return true; |
| 15 | ||
| 16 | 43 | } else if (actual instanceof Date && expected instanceof Date) { |
| 17 | 0 | return actual.getTime() === expected.getTime(); |
| 18 | ||
| 19 | // 7.3. Other pairs that do not both pass typeof value == 'object', | |
| 20 | // equivalence is determined by ==. | |
| 21 | 43 | } else if (typeof actual != 'object' && typeof expected != 'object') { |
| 22 | 0 | return actual == expected; |
| 23 | ||
| 24 | // 7.4. For all other Object pairs, including Array objects, equivalence is | |
| 25 | // determined by having the same number of owned properties (as verified | |
| 26 | // with Object.prototype.hasOwnProperty.call), the same set of keys | |
| 27 | // (although not necessarily the same order), equivalent values for every | |
| 28 | // corresponding key, and an identical 'prototype' property. Note: this | |
| 29 | // accounts for both named and indexed properties on Arrays. | |
| 30 | } else { | |
| 31 | 43 | return objEquiv(actual, expected); |
| 32 | } | |
| 33 | } | |
| 34 | ||
| 35 | 1 | function isUndefinedOrNull(value) { |
| 36 | 86 | return value === null || value === undefined; |
| 37 | } | |
| 38 | ||
| 39 | 1 | function isArguments(object) { |
| 40 | 43 | return Object.prototype.toString.call(object) == '[object Arguments]'; |
| 41 | } | |
| 42 | ||
| 43 | 1 | function objEquiv(a, b) { |
| 44 | 43 | if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) |
| 45 | 0 | return false; |
| 46 | // an identical 'prototype' property. | |
| 47 | 43 | if (a.prototype !== b.prototype) return false; |
| 48 | //~~~I've managed to break Object.keys through screwy arguments passing. | |
| 49 | // Converting to array solves the problem. | |
| 50 | 43 | if (isArguments(a)) { |
| 51 | 0 | if (!isArguments(b)) { |
| 52 | 0 | return false; |
| 53 | } | |
| 54 | 0 | a = pSlice.call(a); |
| 55 | 0 | b = pSlice.call(b); |
| 56 | 0 | return deepEqual(a, b); |
| 57 | } | |
| 58 | 43 | try { |
| 59 | 43 | var ka = Object_keys(a), |
| 60 | kb = Object_keys(b), | |
| 61 | key, i; | |
| 62 | } catch (e) {//happens when one is a string literal and the other isn't | |
| 63 | 0 | return false; |
| 64 | } | |
| 65 | // having the same number of owned properties (keys incorporates | |
| 66 | // hasOwnProperty) | |
| 67 | 43 | if (ka.length != kb.length) |
| 68 | 0 | return false; |
| 69 | //the same set of keys (although not necessarily the same order), | |
| 70 | 43 | ka.sort(); |
| 71 | 43 | kb.sort(); |
| 72 | //~~~cheap key test | |
| 73 | 43 | for (i = ka.length - 1; i >= 0; i--) { |
| 74 | 97 | if (ka[i] != kb[i]) |
| 75 | 0 | return false; |
| 76 | } | |
| 77 | //equivalent values for every corresponding key, and | |
| 78 | //~~~possibly expensive deep test | |
| 79 | 43 | for (i = ka.length - 1; i >= 0; i--) { |
| 80 | 97 | key = ka[i]; |
| 81 | 97 | if (!deepEqual(a[key], b[key])) return false; |
| 82 | } | |
| 83 | 43 | return true; |
| 84 | } | |
| 85 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | var Buffer = require('buffer').Buffer; // for use with browserify |
| 2 | ||
| 3 | 1 | module.exports = function (a, b) { |
| 4 | 0 | if (!Buffer.isBuffer(a)) return undefined; |
| 5 | 0 | if (!Buffer.isBuffer(b)) return undefined; |
| 6 | 0 | if (a.length !== b.length) return false; |
| 7 | ||
| 8 | 0 | for (var i = 0; i < a.length; i++) { |
| 9 | 0 | if (a[i] !== b[i]) return false; |
| 10 | } | |
| 11 | ||
| 12 | 0 | return true; |
| 13 | }; | |
| 14 |
| Line | Hits | Source |
|---|---|---|
| 1 | // This is a very simple test framework that leverages the tap framework | |
| 2 | // to run tests and output tap-parseable results. | |
| 3 | ||
| 4 | 1 | module.exports = Test |
| 5 | ||
| 6 | 1 | var assert = require("c:/noboxout/js-object-enhancements/node_modules/tap/lib/./tap-assert") |
| 7 | , inherits = require("inherits") | |
| 8 | , Results = require("c:/noboxout/js-object-enhancements/node_modules/tap/lib/./tap-results") | |
| 9 | ||
| 10 | // tests are also test harnesses | |
| 11 | 1 | inherits(Test, require("c:/noboxout/js-object-enhancements/node_modules/tap/lib/./tap-harness")) |
| 12 | ||
| 13 | 1 | function Test (harness, name, conf) { |
| 14 | //console.error("test ctor") | |
| 15 | 5 | if (!(this instanceof Test)) return new Test(harness, name, conf) |
| 16 | ||
| 17 | 5 | Test.super.call(this, Test) |
| 18 | ||
| 19 | 5 | conf.name = name || conf.name || "(anonymous)" |
| 20 | 5 | this.conf = conf |
| 21 | ||
| 22 | 5 | this.harness = harness |
| 23 | 5 | this.harness.add(this) |
| 24 | } | |
| 25 | ||
| 26 | // it's taking too long! | |
| 27 | 1 | Test.prototype.timeout = function () { |
| 28 | // detect false alarms | |
| 29 | 0 | if (this._ended) return |
| 30 | 0 | this.fail("Timeout!") |
| 31 | 0 | this.end() |
| 32 | } | |
| 33 | ||
| 34 | 1 | Test.prototype.clear = function () { |
| 35 | 0 | this._started = false |
| 36 | 0 | this._ended = false |
| 37 | 0 | this._plan = null |
| 38 | 0 | this._bailedOut = false |
| 39 | 0 | this._testCount = 0 |
| 40 | 0 | this.results = new Results() |
| 41 | } | |
| 42 | ||
| 43 | // this gets called if a test throws ever | |
| 44 | 1 | Test.prototype.threw = function (ex) { |
| 45 | //console.error("threw!", ex.stack) | |
| 46 | 0 | this.fail(ex.name + ": " + ex.message, { error: ex, thrown: true }) |
| 47 | // may emit further failing tests if the plan is not completed | |
| 48 | //console.error("end, because it threw") | |
| 49 | 0 | if (!this._ended) this.end() |
| 50 | } | |
| 51 | ||
| 52 | 1 | Test.prototype.comment = function (m) { |
| 53 | 0 | if (typeof m !== "string") { |
| 54 | 0 | return this.fail("Test.comment argument must be a string") |
| 55 | } | |
| 56 | 0 | this.result("\n" + m.trim()) |
| 57 | } | |
| 58 | ||
| 59 | 1 | Test.prototype.result = function (res) { |
| 60 | 57 | this.results.add(res) |
| 61 | 57 | this._testCount ++ |
| 62 | 57 | this.emit("result", res) |
| 63 | 57 | if (this._plan === this._testCount) { |
| 64 | 0 | process.nextTick(this._endNice.bind(this)) |
| 65 | } | |
| 66 | } | |
| 67 | ||
| 68 | 1 | Test.prototype._endNice = function () { |
| 69 | 0 | if (!this._ended) this.end() |
| 70 | } | |
| 71 | ||
| 72 | // parasitic | |
| 73 | // Who says you can't do multiple inheritance in js? | |
| 74 | 1 | Object.getOwnPropertyNames(assert).forEach(function (k) { |
| 75 | 73 | if (k === "prototype" || k === "name") return |
| 76 | 69 | var d = Object.getOwnPropertyDescriptor(assert, k) |
| 77 | , v = d.value | |
| 78 | 71 | if (!v) return |
| 79 | 67 | d.value = assertParasite(v) |
| 80 | 67 | Object.defineProperty(Test.prototype, k, d) |
| 81 | }) | |
| 82 | ||
| 83 | 68 | function assertParasite (fn) { return function _testAssert () { |
| 84 | //console.error("_testAssert", fn.name, arguments) | |
| 85 | 57 | if (this._bailedOut) return |
| 86 | 57 | var res = fn.apply(assert, arguments) |
| 87 | 57 | this.result(res) |
| 88 | 57 | return res |
| 89 | }} | |
| 90 | ||
| 91 | // a few tweaks on the EE emit function, because | |
| 92 | // we want to catch all thrown errors and bubble up "bailout" | |
| 93 | 2 | Test.prototype.emit = (function (em) { return function (t) { |
| 94 | // bailouts bubble until handled | |
| 95 | 124 | if (t === "bailout" && |
| 96 | this.listeners(t).length === 0 && | |
| 97 | this.harness) { | |
| 98 | 0 | return this.harness.bailout(arguments[1]) |
| 99 | } | |
| 100 | ||
| 101 | 124 | if (t === "error") return em.apply(this, arguments) |
| 102 | 124 | try { |
| 103 | 124 | em.apply(this, arguments) |
| 104 | } catch (ex) { | |
| 105 | // any exceptions in a test are a failure | |
| 106 | //console.error("caught!", ex.stack) | |
| 107 | 0 | this.threw(ex) |
| 108 | } | |
| 109 | }})(Test.super.prototype.emit) | |
| 110 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | module.exports = TapConsumer |
| 2 | ||
| 3 | // pipe a stream into this that's emitting tap-formatted data, | |
| 4 | // and it'll emit "data" events with test objects or comment strings | |
| 5 | // and an "end" event with the final results. | |
| 6 | ||
| 7 | 1 | var yamlish = require("yamlish") |
| 8 | , Results = require("c:/noboxout/js-object-enhancements/node_modules/tap/lib/./tap-results") | |
| 9 | , inherits = require("inherits") | |
| 10 | ||
| 11 | 1 | TapConsumer.decode = TapConsumer.parse = function (str) { |
| 12 | 0 | var tc = new TapConsumer |
| 13 | , list = [] | |
| 14 | 0 | tc.on("data", function (res) { |
| 15 | 0 | list.push(res) |
| 16 | }) | |
| 17 | 0 | tc.end(str) |
| 18 | 0 | tc.results.list = list |
| 19 | 0 | return tc.results |
| 20 | } | |
| 21 | ||
| 22 | 1 | inherits(TapConsumer, require("stream").Stream) |
| 23 | 1 | function TapConsumer () { |
| 24 | 0 | if (!(this instanceof TapConsumer)) { |
| 25 | 0 | return new TapConsumer |
| 26 | } | |
| 27 | ||
| 28 | 0 | TapConsumer.super.call(this) |
| 29 | 0 | this.results = new Results |
| 30 | 0 | this.readable = this.writable = true |
| 31 | ||
| 32 | 0 | this.on("data", function (res) { |
| 33 | 0 | if (typeof res === "object") this.results.add(res) |
| 34 | }) | |
| 35 | ||
| 36 | 0 | this._plan = null |
| 37 | 0 | this._buffer = "" |
| 38 | 0 | this._indent = [] |
| 39 | 0 | this._current = null |
| 40 | 0 | this._actualCount = 0 |
| 41 | 0 | this._passed = [] |
| 42 | 0 | this._failed = [] |
| 43 | //console.error("TapConsumer ctor done") | |
| 44 | } | |
| 45 | ||
| 46 | 1 | TapConsumer.prototype.bailedOut = false |
| 47 | ||
| 48 | 1 | TapConsumer.prototype.write = function (chunk) { |
| 49 | 0 | if (!this.writable) this.emit("error", new Error("not writable")) |
| 50 | 0 | if (this.bailedOut) return true |
| 51 | ||
| 52 | 0 | this._buffer = this._buffer + chunk |
| 53 | // split it up into lines. | |
| 54 | 0 | var lines = this._buffer.split(/\r?\n/) |
| 55 | // ignore the last line, since it might be incomplete. | |
| 56 | 0 | this._buffer = lines.pop() |
| 57 | ||
| 58 | 0 | for (var i = 0, l = lines.length; i < l; i ++) { |
| 59 | //console.error([i, lines[i]]) | |
| 60 | // see if it's indented. | |
| 61 | 0 | var line = lines[i] |
| 62 | , spaces = (this._indent.length && !line.trim()) | |
| 63 | || line.match(/^\s/) | |
| 64 | // at this level, only interested in fully undented stuff. | |
| 65 | 0 | if (spaces) { |
| 66 | 0 | var c = i |
| 67 | 0 | while (c < l && (!lines[c].trim() || lines[c].match(/^\s/))) { |
| 68 | 0 | this._indent.push(lines[c++]) |
| 69 | } | |
| 70 | //console.error(c-i, "indented", this._indent, this._current) | |
| 71 | 0 | i = c - 1 |
| 72 | 0 | continue |
| 73 | } | |
| 74 | // some kind of line. summary, ok, notok, comment, or garbage. | |
| 75 | // this also finishes parsing any of the indented lines from before | |
| 76 | 0 | this._parseLine(line) |
| 77 | } | |
| 78 | 0 | return true |
| 79 | } | |
| 80 | ||
| 81 | 1 | TapConsumer.prototype.end = function () { |
| 82 | // finish up any hanging indented sections or final buffer | |
| 83 | 0 | if (this._buffer.match(/^\s/)) this._indent.push(this.buffer) |
| 84 | 0 | else this._parseLine(this._buffer) |
| 85 | ||
| 86 | 0 | if (!this.bailedOut && |
| 87 | this._plan !== null && | |
| 88 | this.results.testsTotal !== this._plan) { | |
| 89 | 0 | while (this._actualCount < this._plan) { |
| 90 | 0 | this.emit("data", {ok: false, name:"MISSING TEST", |
| 91 | id:this._actualCount ++ }) | |
| 92 | } | |
| 93 | } | |
| 94 | ||
| 95 | 0 | this._parseLine("") |
| 96 | 0 | this._buffer = "" |
| 97 | 0 | this.writable = false |
| 98 | 0 | this.emit("end", null, this._actualCount, this._passed) |
| 99 | } | |
| 100 | ||
| 101 | 1 | TapConsumer.prototype._parseLine = function (line) { |
| 102 | 0 | if (this.bailedOut) return |
| 103 | //console.error("_parseLine", [line]) | |
| 104 | // if there are any indented lines, and there is a | |
| 105 | // current object already, then they belong to it. | |
| 106 | // if there is not a current object, then they're garbage. | |
| 107 | 0 | if (this._current && this._indent.length) { |
| 108 | 0 | this._parseIndented() |
| 109 | } | |
| 110 | 0 | this._indent.length = 0 |
| 111 | 0 | if (this._current) { |
| 112 | 0 | if (this._current.ok) this._passed.push(this._current.id) |
| 113 | 0 | else this._failed.push(this._current.id) |
| 114 | 0 | this.emit("data", this._current) |
| 115 | } | |
| 116 | 0 | this._current = null |
| 117 | 0 | line = line.trim() |
| 118 | 0 | if (!line) return |
| 119 | // try to see what kind of line this is. | |
| 120 | ||
| 121 | 0 | var bo |
| 122 | 0 | if (bo = line.match(/^bail out!\s*(.*)$/i)) { |
| 123 | 0 | this.bailedOut = true |
| 124 | // this.emit("error", new Error(line)) | |
| 125 | 0 | this.emit("bailout", bo[1]) |
| 126 | 0 | return |
| 127 | } | |
| 128 | ||
| 129 | 0 | if (line.match(/^#/)) { // just a comment |
| 130 | 0 | line = line.replace(/^#+/, "").trim() |
| 131 | // console.error("outputting comment", [line]) | |
| 132 | 0 | if (line) this.emit("data", line) |
| 133 | 0 | return |
| 134 | } | |
| 135 | ||
| 136 | 0 | var plan = line.match(/^([0-9]+)\.\.([0-9]+)(?:\s+#(.*))?$/) |
| 137 | 0 | if (plan) { |
| 138 | 0 | var start = +(plan[1]) |
| 139 | , end = +(plan[2]) | |
| 140 | , comment = plan[3] | |
| 141 | ||
| 142 | // TODO: maybe do something else with this? | |
| 143 | // it might be something like: "1..0 #Skip because of reasons" | |
| 144 | 0 | this._plan = end |
| 145 | 0 | this.emit("plan", end, comment) |
| 146 | // plan must come before or after all tests. | |
| 147 | 0 | if (this._actualCount !== 0) { |
| 148 | 0 | this._sawPlan = true |
| 149 | } | |
| 150 | 0 | return |
| 151 | } | |
| 152 | ||
| 153 | 0 | if (line.match(/^(not )?ok(?:\s+([0-9]+))?/)) { |
| 154 | 0 | this._parseResultLine(line) |
| 155 | 0 | return |
| 156 | } | |
| 157 | ||
| 158 | // garbage. emit as a comment. | |
| 159 | //console.error("emitting", [line.trim()]) | |
| 160 | 0 | if (line.trim()) this.emit("data", line.trim()) |
| 161 | } | |
| 162 | ||
| 163 | 1 | TapConsumer.prototype._parseDirective = function (line) { |
| 164 | 0 | line = line.trim() |
| 165 | 0 | if (line.match(/^TODO\b/i)) { |
| 166 | 0 | return { todo:true, explanation: line.replace(/^TODO\s*/i, "") } |
| 167 | 0 | } else if (line.match(/^SKIP\b/i)) { |
| 168 | 0 | return { skip:true, explanation: line.replace(/^SKIP\s*/i, "") } |
| 169 | } | |
| 170 | } | |
| 171 | ||
| 172 | 1 | TapConsumer.prototype._parseResultLine = function (line) { |
| 173 | 0 | this._actualCount ++ |
| 174 | 0 | if (this._sawPlan) { |
| 175 | 0 | this.emit("data", {ok: false, name:"plan in the middle of tests" |
| 176 | ,id:this._actualCount ++}) | |
| 177 | } | |
| 178 | 0 | var parsed = line.match(/^(not )?ok(?: ([0-9]+))?(?:(?: - )?(.*))?$/) |
| 179 | , ok = !parsed[1] | |
| 180 | , id = +(parsed[2] || this._actualCount) | |
| 181 | , rest = parsed[3] || "" | |
| 182 | , name | |
| 183 | , res = { id:id, ok:ok } | |
| 184 | ||
| 185 | // split on un-escaped # characters | |
| 186 | ||
| 187 | //console.log("# "+JSON.stringify([name, rest])) | |
| 188 | 0 | rest = rest.replace(/([^\\])((?:\\\\)*)#/g, "$1\n$2").split("\n") |
| 189 | 0 | name = rest.shift() |
| 190 | 0 | rest = rest.filter(function (r) { return r.trim() }).join("#") |
| 191 | //console.log("# "+JSON.stringify([name, rest])) | |
| 192 | ||
| 193 | // now, let's see if there's a directive in there. | |
| 194 | 0 | var dir = this._parseDirective(rest.trim()) |
| 195 | 0 | if (!dir) name += rest ? "#" + rest : "" |
| 196 | else { | |
| 197 | 0 | res.ok = true |
| 198 | 0 | if (dir.skip) res.skip = true |
| 199 | 0 | else if (dir.todo) res.todo = true |
| 200 | 0 | if (dir.explanation) res.explanation = dir.explanation |
| 201 | } | |
| 202 | 0 | res.name = name |
| 203 | ||
| 204 | //console.error(line, [ok, id, name]) | |
| 205 | 0 | this._current = res |
| 206 | } | |
| 207 | ||
| 208 | 1 | TapConsumer.prototype._parseIndented = function () { |
| 209 | // pull yamlish block out | |
| 210 | 0 | var ind = this._indent |
| 211 | , ys | |
| 212 | , ye | |
| 213 | , yind | |
| 214 | , diag | |
| 215 | //console.error(ind, this._indent) | |
| 216 | 0 | for (var i = 0, l = ind.length; i < l; i ++) { |
| 217 | 0 | var line = ind[i] |
| 218 | , lt = line.trim() | |
| 219 | 0 | if (!ys) { |
| 220 | 0 | ys = line.match(/^(\s*)---(.*)$/) |
| 221 | 0 | if (ys) { |
| 222 | 0 | yind = ys[1] |
| 223 | 0 | diag = [ys[2]] |
| 224 | //console.error([line,ys, diag]) | |
| 225 | 0 | continue |
| 226 | 0 | } else if (lt) this.emit("data", lt) |
| 227 | 0 | } else if (ys && !ye) { |
| 228 | 0 | if (line === yind + "...") ye = true |
| 229 | else { | |
| 230 | 0 | diag.push(line.substr(yind.length)) |
| 231 | } | |
| 232 | 0 | } else if (ys && ye && lt) this.emit("data", lt) |
| 233 | } | |
| 234 | 0 | if (diag) { |
| 235 | //console.error('about to parse', diag) | |
| 236 | 0 | diag = yamlish.decode(diag.join("\n")) |
| 237 | //console.error('parsed', diag) | |
| 238 | 0 | Object.keys(diag).forEach(function (k) { |
| 239 | //console.error(this._current, k) | |
| 240 | 0 | if (!this._current.hasOwnProperty(k)) this._current[k] = diag[k] |
| 241 | }, this) | |
| 242 | } | |
| 243 | } | |
| 244 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | var fs = require("fs") |
| 2 | , child_process = require("child_process") | |
| 3 | , path = require("path") | |
| 4 | , chain = require("slide").chain | |
| 5 | , asyncMap = require("slide").asyncMap | |
| 6 | , TapProducer = require("c:/noboxout/js-object-enhancements/node_modules/tap/lib/./tap-producer.js") | |
| 7 | , TapConsumer = require("c:/noboxout/js-object-enhancements/node_modules/tap/lib/./tap-consumer.js") | |
| 8 | , assert = require("c:/noboxout/js-object-enhancements/node_modules/tap/lib/./tap-assert.js") | |
| 9 | , inherits = require("inherits") | |
| 10 | , util = require("util") | |
| 11 | , CovHtml = require("c:/noboxout/js-object-enhancements/node_modules/tap/lib/./tap-cov-html.js") | |
| 12 | ||
| 13 | // XXX Clean up the coverage options | |
| 14 | , doCoverage = process.env.TAP_COV | |
| 15 | || process.env.npm_package_config_coverage | |
| 16 | || process.env.npm_config_coverage | |
| 17 | ||
| 18 | 1 | module.exports = Runner |
| 19 | ||
| 20 | 1 | inherits(Runner, TapProducer) |
| 21 | ||
| 22 | 1 | function Runner (options, cb) { |
| 23 | 0 | this.options = options |
| 24 | ||
| 25 | 0 | var diag = this.options.diag |
| 26 | 0 | var dir = this.options.argv.remain |
| 27 | 0 | Runner.super.call(this, diag) |
| 28 | ||
| 29 | 0 | this.doCoverage = doCoverage |
| 30 | // An array of full paths to files to obtain coverage | |
| 31 | 0 | this.coverageFiles = [] |
| 32 | // The source of these files | |
| 33 | 0 | this.coverageFilesSource = {} |
| 34 | // Where to write coverage information | |
| 35 | 0 | this.coverageOutDir = this.options["coverage-dir"] |
| 36 | // Temporary test files bunkerified we'll remove later | |
| 37 | 0 | this.f2delete = [] |
| 38 | // Raw coverage stats, as read from JSON files | |
| 39 | 0 | this.rawCovStats = [] |
| 40 | // Processed coverage information, per file to cover: | |
| 41 | 0 | this.covStats = {} |
| 42 | ||
| 43 | 0 | if (dir) { |
| 44 | 0 | var filesToCover = this.options.cover |
| 45 | ||
| 46 | 0 | if (doCoverage) { |
| 47 | 0 | var mkdirp = require("mkdirp") |
| 48 | 0 | this.coverageOutDir = path.resolve(this.coverageOutDir) |
| 49 | 0 | this.getFilesToCover(filesToCover) |
| 50 | 0 | var self = this |
| 51 | 0 | return mkdirp(this.coverageOutDir, 0755, function (er) { |
| 52 | 0 | if (er) return self.emit("error", er) |
| 53 | 0 | self.run(dir, cb) |
| 54 | }) | |
| 55 | } | |
| 56 | ||
| 57 | 0 | this.run(dir, cb) |
| 58 | } | |
| 59 | } | |
| 60 | ||
| 61 | ||
| 62 | 1 | Runner.prototype.run = function() { |
| 63 | 0 | var self = this |
| 64 | , args = Array.prototype.slice.call(arguments) | |
| 65 | , cb = args.pop() || finish | |
| 66 | ||
| 67 | 0 | function finish (er) { |
| 68 | 0 | if (er) { |
| 69 | 0 | self.emit("error", er) |
| 70 | } | |
| 71 | ||
| 72 | 0 | if (!doCoverage) return self.end() |
| 73 | ||
| 74 | // Cleanup temporary test files with coverage: | |
| 75 | 0 | self.f2delete.forEach(function(f) { |
| 76 | 0 | fs.unlinkSync(f) |
| 77 | }) | |
| 78 | 0 | self.getFilesToCoverSource(function(err, data) { |
| 79 | 0 | if (err) { |
| 80 | 0 | self.emit("error", err) |
| 81 | } | |
| 82 | 0 | self.getPerFileCovInfo(function(err, data) { |
| 83 | 0 | if (err) { |
| 84 | 0 | self.emit("error", err) |
| 85 | } | |
| 86 | 0 | self.mergeCovStats(function(err, data) { |
| 87 | 0 | if (err) { |
| 88 | 0 | self.emit("error", err) |
| 89 | } | |
| 90 | 0 | CovHtml(self.covStats, self.coverageOutDir, function() { |
| 91 | 0 | self.end() |
| 92 | }) | |
| 93 | }) | |
| 94 | }) | |
| 95 | }) | |
| 96 | } | |
| 97 | ||
| 98 | 0 | if (Array.isArray(args[0])) { |
| 99 | 0 | args = args[0] |
| 100 | } | |
| 101 | 0 | self.runFiles(args, "", cb) |
| 102 | } | |
| 103 | ||
| 104 | 1 | Runner.prototype.runDir = function (dir, cb) { |
| 105 | 0 | var self = this |
| 106 | 0 | fs.readdir(dir, function (er, files) { |
| 107 | 0 | if (er) { |
| 108 | 0 | self.write(assert.fail("failed to readdir " + dir, { error: er })) |
| 109 | 0 | self.end() |
| 110 | 0 | return |
| 111 | } | |
| 112 | 0 | files = files.sort(function(a, b) { |
| 113 | 0 | return a > b ? 1 : -1 |
| 114 | }) | |
| 115 | 0 | files = files.filter(function(f) { |
| 116 | 0 | return !f.match(/^\./) |
| 117 | }) | |
| 118 | 0 | files = files.map(path.resolve.bind(path, dir)) |
| 119 | ||
| 120 | 0 | self.runFiles(files, path.resolve(dir), cb) |
| 121 | }) | |
| 122 | } | |
| 123 | ||
| 124 | ||
| 125 | 1 | Runner.prototype.runFiles = function (files, dir, cb) { |
| 126 | ||
| 127 | 0 | var self = this |
| 128 | 0 | chain(files.map(function(f) { |
| 129 | 0 | return function (cb) { |
| 130 | 0 | if (self._bailedOut) return |
| 131 | 0 | var relDir = dir || path.dirname(f) |
| 132 | , fileName = relDir === "." ? f : f.substr(relDir.length + 1) | |
| 133 | ||
| 134 | 0 | self.write(fileName) |
| 135 | 0 | fs.lstat(f, function(er, st) { |
| 136 | 0 | if (er) { |
| 137 | 0 | self.write(assert.fail("failed to stat " + f, {error: er})) |
| 138 | 0 | return cb() |
| 139 | } | |
| 140 | ||
| 141 | 0 | var cmd = f, args = [], env = {} |
| 142 | ||
| 143 | 0 | if (path.extname(f) === ".js") { |
| 144 | 0 | cmd = "node" |
| 145 | 0 | if (self.options.gc) { |
| 146 | 0 | args.push("--expose-gc") |
| 147 | } | |
| 148 | 0 | args.push(fileName) |
| 149 | 0 | } else if (path.extname(f) === ".coffee") { |
| 150 | 0 | cmd = "coffee" |
| 151 | 0 | args.push(fileName) |
| 152 | } else { | |
| 153 | // Check if file is executable | |
| 154 | 0 | if ((st.mode & 0100) && process.getuid) { |
| 155 | 0 | if (process.getuid() != st.uid) { |
| 156 | 0 | return cb() |
| 157 | } | |
| 158 | 0 | } else if ((st.mode & 0010) && process.getgid) { |
| 159 | 0 | if (process.getgid() != st.gid) { |
| 160 | 0 | return cb() |
| 161 | } | |
| 162 | 0 | } else if ((st.mode & 0001) == 0) { |
| 163 | 0 | return cb() |
| 164 | } | |
| 165 | } | |
| 166 | ||
| 167 | 0 | if (st.isDirectory()) { |
| 168 | 0 | return self.runDir(f, cb) |
| 169 | } | |
| 170 | ||
| 171 | 0 | if (doCoverage && path.extname(f) === ".js") { |
| 172 | 0 | var foriginal = fs.readFileSync(f, "utf8") |
| 173 | , fcontents = self.coverHeader() + foriginal + self.coverFooter() | |
| 174 | , tmpBaseName = path.basename(f, path.extname(f)) | |
| 175 | + ".with-coverage." + process.pid + path.extname(f) | |
| 176 | , tmpFname = path.resolve(path.dirname(f), tmpBaseName) | |
| 177 | ||
| 178 | 0 | fs.writeFileSync(tmpFname, fcontents, "utf8") |
| 179 | 0 | args.splice(-1, 1, tmpFname) |
| 180 | } | |
| 181 | ||
| 182 | 0 | for (var i in process.env) { |
| 183 | 0 | env[i] = process.env[i] |
| 184 | } | |
| 185 | 0 | env.TAP = 1 |
| 186 | ||
| 187 | 0 | var cp = child_process.spawn(cmd, args, { env: env, cwd: relDir }) |
| 188 | , out = "" | |
| 189 | , err = "" | |
| 190 | , tc = new TapConsumer() | |
| 191 | , childTests = [f] | |
| 192 | ||
| 193 | 0 | var timeout = setTimeout(function () { |
| 194 | 0 | if (!cp._ended) { |
| 195 | 0 | cp._timedOut = true |
| 196 | 0 | cp.kill() |
| 197 | } | |
| 198 | }, self.options.timeout * 1000) | |
| 199 | ||
| 200 | 0 | tc.on("data", function(c) { |
| 201 | 0 | self.emit("result", c) |
| 202 | 0 | self.write(c) |
| 203 | }) | |
| 204 | ||
| 205 | 0 | tc.on("bailout", function (message) { |
| 206 | 0 | clearTimeout(timeout) |
| 207 | 0 | console.log("# " + f.substr(process.cwd().length + 1)) |
| 208 | 0 | process.stderr.write(err) |
| 209 | 0 | process.stdout.write(out + "\n") |
| 210 | 0 | self._bailedOut = true |
| 211 | 0 | cp._ended = true |
| 212 | 0 | cp.kill() |
| 213 | }) | |
| 214 | ||
| 215 | 0 | cp.stdout.pipe(tc) |
| 216 | 0 | cp.stdout.on("data", function (c) { out += c }) |
| 217 | 0 | cp.stderr.on("data", function (c) { |
| 218 | 0 | if (self.options.stderr) process.stderr.write(c) |
| 219 | 0 | err += c |
| 220 | }) | |
| 221 | ||
| 222 | 0 | cp.on("exit", function (code, signal) { |
| 223 | 0 | if (cp._ended) return |
| 224 | 0 | cp._ended = true |
| 225 | 0 | var ok = !cp._timedOut && code === 0 |
| 226 | 0 | clearTimeout(timeout) |
| 227 | //childTests.forEach(function (c) { self.write(c) }) | |
| 228 | 0 | var res = { name: path.dirname(f).replace(process.cwd() + "/", "") |
| 229 | + "/" + fileName | |
| 230 | , ok: ok | |
| 231 | , exit: code } | |
| 232 | ||
| 233 | 0 | if (cp._timedOut) |
| 234 | 0 | res.timedOut = cp._timedOut |
| 235 | 0 | if (signal) |
| 236 | 0 | res.signal = signal |
| 237 | ||
| 238 | 0 | if (err) { |
| 239 | 0 | res.stderr = err |
| 240 | 0 | if (tc.results.ok && |
| 241 | tc.results.tests === 0 && | |
| 242 | !self.options.stderr) { | |
| 243 | // perhaps a compilation error or something else failed. | |
| 244 | // no need if stderr is set, since it will have been | |
| 245 | // output already anyway. | |
| 246 | 0 | console.error(err) |
| 247 | } | |
| 248 | } | |
| 249 | ||
| 250 | // tc.results.ok = tc.results.ok && ok | |
| 251 | 0 | tc.results.add(res) |
| 252 | 0 | res.command = [cmd].concat(args).map(JSON.stringify).join(" ") |
| 253 | 0 | self.emit("result", res) |
| 254 | 0 | self.emit("file", f, res, tc.results) |
| 255 | 0 | self.write(res) |
| 256 | 0 | self.write("\n") |
| 257 | 0 | if (doCoverage) { |
| 258 | 0 | self.f2delete.push(tmpFname) |
| 259 | } | |
| 260 | 0 | cb() |
| 261 | }) | |
| 262 | }) | |
| 263 | } | |
| 264 | }), cb) | |
| 265 | ||
| 266 | 0 | return self |
| 267 | } | |
| 268 | ||
| 269 | ||
| 270 | // Get an array of full paths to files we are interested into obtain | |
| 271 | // code coverage. | |
| 272 | 1 | Runner.prototype.getFilesToCover = function(filesToCover) { |
| 273 | 0 | var self = this |
| 274 | 0 | filesToCover = filesToCover.split(",").map(function(f) { |
| 275 | 0 | return path.resolve(f) |
| 276 | }).filter(function(f) { | |
| 277 | 0 | return path.existsSync(f) |
| 278 | }) | |
| 279 | ||
| 280 | 0 | function recursive(f) { |
| 281 | 0 | if (path.extname(f) === "") { |
| 282 | // Is a directory: | |
| 283 | 0 | fs.readdirSync(f).forEach(function(p) { |
| 284 | 0 | recursive(f + "/" + p) |
| 285 | }) | |
| 286 | } else { | |
| 287 | 0 | self.coverageFiles.push(f) |
| 288 | } | |
| 289 | } | |
| 290 | 0 | filesToCover.forEach(function(f) { |
| 291 | 0 | recursive(f) |
| 292 | }) | |
| 293 | } | |
| 294 | ||
| 295 | // Prepend to every test file to run. Note tap.test at the very top due it | |
| 296 | // "plays" with include paths. | |
| 297 | 1 | Runner.prototype.coverHeader = function() { |
| 298 | // semi here since we're injecting it before the first line, | |
| 299 | // and don't want to mess up line numbers in the test files. | |
| 300 | 0 | return "var ___TAP_COVERAGE = require(" |
| 301 | + JSON.stringify(require.resolve("runforcover")) | |
| 302 | + ").cover(/.*/g);" | |
| 303 | } | |
| 304 | ||
| 305 | // Append at the end of every test file to run. Actually, the stuff which gets | |
| 306 | // the coverage information. | |
| 307 | // Maybe it would be better to move into a separate file template so editing | |
| 308 | // could be easier. | |
| 309 | 1 | Runner.prototype.coverFooter = function() { |
| 310 | 0 | var self = this |
| 311 | // This needs to be a string with proper interpolations: | |
| 312 | 0 | return [ "" |
| 313 | , "var ___TAP = require(" + JSON.stringify(require.resolve("./main.js")) + ")" | |
| 314 | , "if (typeof ___TAP._plan === 'number') ___TAP._plan ++" | |
| 315 | , "___TAP.test(" + JSON.stringify("___coverage") + ", function(t) {" | |
| 316 | , " var covFiles = " + JSON.stringify(self.coverageFiles) | |
| 317 | , " , covDir = " + JSON.stringify(self.coverageOutDir) | |
| 318 | , " , path = require('path')" | |
| 319 | , " , fs = require('fs')" | |
| 320 | , " , testFnBase = path.basename(__filename, '.js') + '.json'" | |
| 321 | , " , testFn = path.resolve(covDir, testFnBase)" | |
| 322 | , "" | |
| 323 | , " function asyncForEach(arr, fn, callback) {" | |
| 324 | , " if (!arr.length) {" | |
| 325 | , " return callback()" | |
| 326 | , " }" | |
| 327 | , " var completed = 0" | |
| 328 | , " arr.forEach(function(i) {" | |
| 329 | , " fn(i, function (err) {" | |
| 330 | , " if (err) {" | |
| 331 | , " callback(err)" | |
| 332 | , " callback = function () {}" | |
| 333 | , " } else {" | |
| 334 | , " completed += 1" | |
| 335 | , " if (completed === arr.length) {" | |
| 336 | , " callback()" | |
| 337 | , " }" | |
| 338 | , " }" | |
| 339 | , " })" | |
| 340 | , " })" | |
| 341 | , " }" | |
| 342 | , "" | |
| 343 | , " ___TAP_COVERAGE(function(coverageData) {" | |
| 344 | , " var outObj = {}" | |
| 345 | , " asyncForEach(covFiles, function(f, cb) {" | |
| 346 | , " if (coverageData[f]) {" | |
| 347 | , " var stats = coverageData[f].stats()" | |
| 348 | , " , stObj = stats" | |
| 349 | , " stObj.lines = stats.lines.map(function (l) {" | |
| 350 | , " return { number: l.lineno, source: l.source() }" | |
| 351 | , " })" | |
| 352 | , " outObj[f] = stObj" | |
| 353 | , " }" | |
| 354 | , " cb()" | |
| 355 | , " }, function(err) {" | |
| 356 | , " ___TAP_COVERAGE.release()" | |
| 357 | , " fs.writeFileSync(testFn, JSON.stringify(outObj))" | |
| 358 | , " t.end()" | |
| 359 | , " })" | |
| 360 | , " })" | |
| 361 | , "})" ].join("\n") | |
| 362 | } | |
| 363 | ||
| 364 | ||
| 365 | 1 | Runner.prototype.getFilesToCoverSource = function(cb) { |
| 366 | 0 | var self = this |
| 367 | 0 | asyncMap(self.coverageFiles, function(f, cb) { |
| 368 | 0 | fs.readFile(f, "utf8", function(err, data) { |
| 369 | 0 | var lc = 0 |
| 370 | 0 | if (err) { |
| 371 | 0 | cb(err) |
| 372 | } | |
| 373 | 0 | self.coverageFilesSource[f] = data.split("\n").map(function(l) { |
| 374 | 0 | lc += 1 |
| 375 | 0 | return { number: lc, source: l } |
| 376 | }) | |
| 377 | 0 | cb() |
| 378 | }) | |
| 379 | }, cb) | |
| 380 | } | |
| 381 | ||
| 382 | 1 | Runner.prototype.getPerFileCovInfo = function(cb) { |
| 383 | 0 | var self = this |
| 384 | , covPath = path.resolve(self.coverageOutDir) | |
| 385 | ||
| 386 | 0 | fs.readdir(covPath, function(err, files) { |
| 387 | 0 | if (err) { |
| 388 | 0 | self.emit("error", err) |
| 389 | } | |
| 390 | 0 | var covFiles = files.filter(function(f) { |
| 391 | 0 | return path.extname(f) === ".json" |
| 392 | }) | |
| 393 | 0 | asyncMap(covFiles, function(f, cb) { |
| 394 | 0 | fs.readFile(path.resolve(covPath, f), "utf8", function(err, data) { |
| 395 | 0 | if (err) { |
| 396 | 0 | cb(err) |
| 397 | } | |
| 398 | 0 | self.rawCovStats.push(JSON.parse(data)) |
| 399 | 0 | cb() |
| 400 | }) | |
| 401 | }, function(f, cb) { | |
| 402 | 0 | fs.unlink(path.resolve(covPath, f), cb) |
| 403 | }, cb) | |
| 404 | }) | |
| 405 | } | |
| 406 | ||
| 407 | 1 | Runner.prototype.mergeCovStats = function(cb) { |
| 408 | 0 | var self = this |
| 409 | 0 | self.rawCovStats.forEach(function(st) { |
| 410 | 0 | Object.keys(st).forEach(function(i) { |
| 411 | // If this is the first time we reach this file, just add the info: | |
| 412 | 0 | if (!self.covStats[i]) { |
| 413 | 0 | self.covStats[i] = { |
| 414 | missing: st[i].lines | |
| 415 | } | |
| 416 | } else { | |
| 417 | // If we already added info for this file before, we need to remove | |
| 418 | // from self.covStats any line not duplicated again (since it has | |
| 419 | // run on such case) | |
| 420 | 0 | self.covStats[i].missing = self.covStats[i].missing.filter( |
| 421 | function(l) { | |
| 422 | 0 | return (st[i].lines.indexOf(l)) |
| 423 | }) | |
| 424 | } | |
| 425 | }) | |
| 426 | }) | |
| 427 | ||
| 428 | // This is due to a bug into | |
| 429 | // chrisdickinson/node-bunker/blob/feature/add-coverage-interface | |
| 430 | // which is using array indexes for line numbers instead of the right number | |
| 431 | 0 | Object.keys(self.covStats).forEach(function(f) { |
| 432 | 0 | self.covStats[f].missing = self.covStats[f].missing.map(function(line) { |
| 433 | 0 | return { number: line.number, source: line.source } |
| 434 | }) | |
| 435 | }) | |
| 436 | ||
| 437 | 0 | Object.keys(self.coverageFilesSource).forEach(function(f) { |
| 438 | 0 | if (!self.covStats[f]) { |
| 439 | 0 | self.covStats[f] = { missing: self.coverageFilesSource[f] |
| 440 | , percentage: 0 | |
| 441 | } | |
| 442 | } | |
| 443 | 0 | self.covStats[f].lines = self.coverageFilesSource[f] |
| 444 | 0 | self.covStats[f].loc = self.coverageFilesSource[f].length |
| 445 | ||
| 446 | 0 | if (!self.covStats[f].percentage) { |
| 447 | 0 | self.covStats[f].percentage = |
| 448 | 1 - (self.covStats[f].missing.length / self.covStats[f].loc) | |
| 449 | } | |
| 450 | ||
| 451 | }) | |
| 452 | 0 | cb() |
| 453 | } | |
| 454 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | exports.asyncMap = require("c:/noboxout/js-object-enhancements/node_modules/tap/node_modules/slide/lib/./async-map") |
| 2 | 1 | exports.bindActor = require("c:/noboxout/js-object-enhancements/node_modules/tap/node_modules/slide/lib/./bind-actor") |
| 3 | 1 | exports.chain = require("c:/noboxout/js-object-enhancements/node_modules/tap/node_modules/slide/lib/./chain") |
| 4 |
| Line | Hits | Source |
|---|---|---|
| 1 | ||
| 2 | /* | |
| 3 | usage: | |
| 4 | ||
| 5 | // do something to a list of things | |
| 6 | asyncMap(myListOfStuff, function (thing, cb) { doSomething(thing.foo, cb) }, cb) | |
| 7 | // do more than one thing to each item | |
| 8 | asyncMap(list, fooFn, barFn, cb) | |
| 9 | ||
| 10 | */ | |
| 11 | ||
| 12 | 1 | module.exports = asyncMap |
| 13 | ||
| 14 | 1 | function asyncMap () { |
| 15 | 0 | var steps = Array.prototype.slice.call(arguments) |
| 16 | , list = steps.shift() || [] | |
| 17 | , cb_ = steps.pop() | |
| 18 | 0 | if (typeof cb_ !== "function") throw new Error( |
| 19 | "No callback provided to asyncMap") | |
| 20 | 0 | if (!list) return cb_(null, []) |
| 21 | 0 | if (!Array.isArray(list)) list = [list] |
| 22 | 0 | var n = steps.length |
| 23 | , data = [] // 2d array | |
| 24 | , errState = null | |
| 25 | , l = list.length | |
| 26 | , a = l * n | |
| 27 | 0 | if (!a) return cb_(null, []) |
| 28 | 0 | function cb (er) { |
| 29 | 0 | if (errState) return |
| 30 | 0 | var argLen = arguments.length |
| 31 | 0 | for (var i = 1; i < argLen; i ++) if (arguments[i] !== undefined) { |
| 32 | 0 | data[i - 1] = (data[i - 1] || []).concat(arguments[i]) |
| 33 | } | |
| 34 | // see if any new things have been added. | |
| 35 | 0 | if (list.length > l) { |
| 36 | 0 | var newList = list.slice(l) |
| 37 | 0 | a += (list.length - l) * n |
| 38 | 0 | l = list.length |
| 39 | 0 | process.nextTick(function () { |
| 40 | 0 | newList.forEach(function (ar) { |
| 41 | 0 | steps.forEach(function (fn) { fn(ar, cb) }) |
| 42 | }) | |
| 43 | }) | |
| 44 | } | |
| 45 | ||
| 46 | 0 | if (er || --a === 0) { |
| 47 | 0 | errState = er |
| 48 | 0 | cb_.apply(null, [errState].concat(data)) |
| 49 | } | |
| 50 | } | |
| 51 | // expect the supplied cb function to be called | |
| 52 | // "n" times for each thing in the array. | |
| 53 | 0 | list.forEach(function (ar) { |
| 54 | 0 | steps.forEach(function (fn) { fn(ar, cb) }) |
| 55 | }) | |
| 56 | } | |
| 57 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | module.exports = bindActor |
| 2 | 1 | function bindActor () { |
| 3 | 0 | var args = |
| 4 | Array.prototype.slice.call | |
| 5 | (arguments) // jswtf. | |
| 6 | , obj = null | |
| 7 | , fn | |
| 8 | 0 | if (typeof args[0] === "object") { |
| 9 | 0 | obj = args.shift() |
| 10 | 0 | fn = args.shift() |
| 11 | 0 | if (typeof fn === "string") |
| 12 | 0 | fn = obj[ fn ] |
| 13 | 0 | } else fn = args.shift() |
| 14 | 0 | return function (cb) { |
| 15 | 0 | fn.apply(obj, args.concat(cb)) } |
| 16 | } | |
| 17 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | module.exports = chain |
| 2 | 1 | var bindActor = require("c:/noboxout/js-object-enhancements/node_modules/tap/node_modules/slide/lib/./bind-actor.js") |
| 3 | 2 | chain.first = {} ; chain.last = {} |
| 4 | 1 | function chain (things, cb) { |
| 5 | 0 | var res = [] |
| 6 | 0 | ;(function LOOP (i, len) { |
| 7 | 0 | if (i >= len) return cb(null,res) |
| 8 | 0 | if (Array.isArray(things[i])) |
| 9 | 0 | things[i] = bindActor.apply(null, |
| 10 | things[i].map(function(i){ | |
| 11 | 0 | return (i===chain.first) ? res[0] |
| 12 | : (i===chain.last) | |
| 13 | ? res[res.length - 1] : i })) | |
| 14 | 0 | if (!things[i]) return LOOP(i + 1, len) |
| 15 | 0 | things[i](function (er, data) { |
| 16 | 0 | if (er) return cb(er, res) |
| 17 | 0 | if (data !== undefined) res = res.concat(data) |
| 18 | 0 | LOOP(i + 1, len) |
| 19 | }) | |
| 20 | })(0, things.length) } | |
| 21 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | var fs = require('fs'), |
| 2 | path = require('path'), | |
| 3 | asyncMap = require("slide").asyncMap, | |
| 4 | util = require('util'); | |
| 5 | ||
| 6 | 1 | var CovHtml = module.exports = function(cov_stats, cov_dir, cb) { |
| 7 | 0 | var index = []; |
| 8 | ||
| 9 | 0 | asyncMap( |
| 10 | Object.keys(cov_stats), | |
| 11 | function(f, cb) { | |
| 12 | 0 | var st = cov_stats[f], |
| 13 | missing_lines = st.missing.map(function(l) { | |
| 14 | 0 | return l.number; |
| 15 | }), | |
| 16 | out = '<!doctype html>\n<html lang="en">\n<head>\n ' + | |
| 17 | '<meta charset="utf-8">\n <title>' + | |
| 18 | ||
| 19 | f + ' (' + st.loc + ')</title>\n' + | |
| 20 | '<style type="text/css">\n' + | |
| 21 | 'li {\n' + | |
| 22 | ' font-family: monospace;\n' + | |
| 23 | ' white-space: pre;\n' + | |
| 24 | '}\n' + | |
| 25 | '</style>\n' + | |
| 26 | '</head>\n<body>\n' + | |
| 27 | '<h1>' + f + ' (' + st.loc + ')' + '</h1>' + | |
| 28 | '<h2>Run: ' + (st.missing.length ? st.loc - st.missing.length : st.loc) + ', Missing: ' + | |
| 29 | st.missing.length + ', Percentage: ' + st.percentage + '</h2>' + | |
| 30 | '<h2>Source:</h2>\n' + | |
| 31 | '<ol>\n' + | |
| 32 | st.lines.map(function(line) { | |
| 33 | 0 | var number = line.number, |
| 34 | color = (missing_lines.indexOf(number) !== -1) ? '#fcc' : '#cfc'; | |
| 35 | 0 | return '<li id="L' + line.number + '" style="background-color: ' + color + |
| 36 | ';">' + line.source.replace(/</g, "<") + '</li>'; | |
| 37 | }).join('\n') + | |
| 38 | '</ol>\n' + | |
| 39 | '<h2>Data</h2>\n'+ | |
| 40 | '<pre>' + util.inspect(st, true, Infinity, false).replace(/</g, "<") + '</pre></body>\n</html>'; | |
| 41 | ||
| 42 | 0 | fs.writeFile( |
| 43 | cov_dir + '/' + | |
| 44 | f.replace(process.cwd() + '/', '').replace(/\//g, '+') + '.html', | |
| 45 | out, | |
| 46 | 'utf8', | |
| 47 | function(err) { | |
| 48 | 0 | if (err) { |
| 49 | 0 | throw err; |
| 50 | } | |
| 51 | 0 | index.push(f); |
| 52 | 0 | cb(); |
| 53 | }); | |
| 54 | }, | |
| 55 | function(err) { | |
| 56 | 0 | if (err) { |
| 57 | 0 | throw err; |
| 58 | } | |
| 59 | 0 | var out = '<!doctype html>\n<html lang="en">\n<head>\n ' + |
| 60 | '<meta charset="utf-8">\n <title>Coverage Index</title>\n</head>\n' + | |
| 61 | '<body>\n<h1>Code Coverage Information</h1>\n<ul>' + | |
| 62 | index.map(function(fname) { | |
| 63 | 0 | return '<li><a href="' + |
| 64 | fname.replace(process.cwd() + '/', '').replace(/\//g, '+') + '.html' + | |
| 65 | '">' + fname + '</a></li>'; | |
| 66 | }).join('\n') + '</ul>\n</body>\n</html>'; | |
| 67 | ||
| 68 | 0 | fs.writeFile(cov_dir + '/index.html', out, 'utf8', function(err) { |
| 69 | 0 | if (err) { |
| 70 | 0 | throw err; |
| 71 | } | |
| 72 | 0 | cb(); |
| 73 | }); | |
| 74 | } | |
| 75 | ); | |
| 76 | }; | |
| 77 | ||
| 78 | ||
| 79 |
| Line | Hits | Source |
|---|---|---|
| 1 | // extract coverage data from the _$jscoverage global, and serialize it into | |
| 2 | // a simple json format. | |
| 3 | 1 | module.exports = function() { |
| 4 | 1 | var jscoverage = global._$jscoverage; |
| 5 | 1 | var a = []; |
| 6 | ||
| 7 | 1 | if (jscoverage) { |
| 8 | 1 | Object.keys(jscoverage).forEach(function(file) { |
| 9 | 26 | var o = { |
| 10 | file: file, | |
| 11 | source: jscoverage[file].source, | |
| 12 | hits: [ ] | |
| 13 | } | |
| 14 | 26 | for (var i = 0; i < o.source.length; i++) { |
| 15 | 3905 | o.hits.push(jscoverage[file][i]); |
| 16 | } | |
| 17 | 25 | a.push(o); |
| 18 | }); | |
| 19 | } | |
| 20 | ||
| 21 | 0 | return JSON.stringify(a, null, " "); |
| 22 | }; | |
| 23 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | var cheerio = require('cheerio'), |
| 2 | fs = require('fs'), | |
| 3 | path = require('path'); | |
| 4 | ||
| 5 | // our html reporter | |
| 6 | 1 | module.exports = function(data) { |
| 7 | // let's write a looong function. | |
| 8 | ||
| 9 | // parse html for our template | |
| 10 | 1 | var $ = cheerio.load(fs.readFileSync(path.join(__dirname, '..', '..', 'resources', 'coverage-template.html'))); |
| 11 | ||
| 12 | // for each file, we'll make a files entry, and we'll collect cumulative | |
| 13 | // stats as we go | |
| 14 | 1 | var gHits = 0, gMisses = 0; |
| 15 | ||
| 16 | 1 | Object.keys(data).forEach(function(fileName) { |
| 17 | 27 | var f = $('#files .file.template').clone(); |
| 18 | 27 | f.removeClass('template'); |
| 19 | 27 | f.find('h2').attr('id', fileName).text(fileName); |
| 20 | ||
| 21 | 27 | var hits = 0, |
| 22 | misses = 0; | |
| 23 | ||
| 24 | 27 | var srcTemplate = f.find('tr.template'); |
| 25 | 27 | for (var i = 1; i <= data[fileName].source.length; i++) { |
| 26 | // and add the source line | |
| 27 | 3939 | var s = srcTemplate.clone().removeClass('template'); |
| 28 | 3940 | s.find('.line').text(i); |
| 29 | 3941 | s.find('.hits').text(data[fileName][i]); |
| 30 | 3941 | s.find('.source').text(data[fileName].source[i - 1]); |
| 31 | ||
| 32 | 3943 | if (data[fileName][i]) { |
| 33 | 666 | s.addClass('hit'); |
| 34 | 667 | hits++; |
| 35 | 3278 | } else if (data[fileName][i] !== undefined) { |
| 36 | 1306 | s.addClass('miss'); |
| 37 | 1306 | misses++; |
| 38 | } | |
| 39 | ||
| 40 | 3951 | f.find('#source tbody').append(s); |
| 41 | } | |
| 42 | ||
| 43 | 26 | var pct = (100.0 * hits / (hits + misses)); |
| 44 | 26 | f.find('.stats .percentage').text(pct.toFixed(1) + '%'); |
| 45 | 26 | f.find('.stats .sloc').text(hits + misses); |
| 46 | 26 | f.find('.stats .hits').text(hits); |
| 47 | 26 | f.find('.stats .misses').text(misses); |
| 48 | ||
| 49 | 26 | $('#files').append(f); |
| 50 | ||
| 51 | // and an entry in the menu | |
| 52 | 26 | var m = $('#menu li.template').clone().removeClass('template'); |
| 53 | 26 | m.find('a').attr('href', '#' + fileName).text(fileName); |
| 54 | 26 | m.find('.cov').text(pct.toFixed(0) + '%'); |
| 55 | 26 | $('#menu').append(m); |
| 56 | ||
| 57 | // update global stats | |
| 58 | 26 | gHits += hits; |
| 59 | 26 | gMisses += misses; |
| 60 | }); | |
| 61 | ||
| 62 | // global stats | |
| 63 | 0 | $('#stats .percentage').text((100.0 * gHits / (gHits + gMisses)).toFixed(1) + '%'); |
| 64 | 0 | $('#stats .sloc').text(gHits + gMisses); |
| 65 | 0 | $('#stats .hits').text(gHits); |
| 66 | 0 | $('#stats .misses').text(gMisses); |
| 67 | ||
| 68 | 0 | return $.html(); |
| 69 | }; | |
| 70 |
| Line | Hits | Source |
|---|---|---|
| 1 | /** | |
| 2 | * Export cheerio (with ) | |
| 3 | */ | |
| 4 | ||
| 5 | 1 | exports = module.exports = process.env.CHEERIO_COV |
| 6 | ? require('./lib-cov/cheerio') | |
| 7 | : require('./lib/cheerio'); | |
| 8 | ||
| 9 | /* | |
| 10 | Export the version | |
| 11 | */ | |
| 12 | ||
| 13 | 1 | exports.version = require('./package').version; |
| 14 |
| Line | Hits | Source |
|---|---|---|
| 1 | /* | |
| 2 | Module dependencies | |
| 3 | */ | |
| 4 | ||
| 5 | 1 | var path = require('path'), |
| 6 | select = require('cheerio-select'), | |
| 7 | parse = require('./parse'), | |
| 8 | evaluate = parse.evaluate, | |
| 9 | updateDOM = parse.update, | |
| 10 | _ = require('underscore'); | |
| 11 | ||
| 12 | /* | |
| 13 | * The API | |
| 14 | */ | |
| 15 | ||
| 16 | 1 | var api = ['attributes', 'traversing', 'manipulation', 'css']; |
| 17 | ||
| 18 | /* | |
| 19 | * A simple way to check for HTML strings or ID strings | |
| 20 | */ | |
| 21 | ||
| 22 | 1 | var quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/; |
| 23 | ||
| 24 | /** | |
| 25 | * Static Methods | |
| 26 | */ | |
| 27 | ||
| 28 | 1 | var $ = require('./static'); |
| 29 | ||
| 30 | /* | |
| 31 | * Instance of cheerio | |
| 32 | */ | |
| 33 | ||
| 34 | 1 | var Cheerio = module.exports = function(selector, context, root) { |
| 35 | 63706 | if (!(this instanceof Cheerio)) return new Cheerio(selector, context, root); |
| 36 | ||
| 37 | // $(), $(null), $(undefined), $(false) | |
| 38 | 123298 | if (!selector) return this; |
| 39 | ||
| 40 | 4206 | if (root) { |
| 41 | 113 | if (typeof root === 'string') root = parse(root); |
| 42 | 113 | this._root = this.make(root, this); |
| 43 | } | |
| 44 | ||
| 45 | // $($) | |
| 46 | 4212 | if (selector.cheerio) return selector; |
| 47 | ||
| 48 | // $(dom) | |
| 49 | 4215 | if (selector.name || Array.isArray(selector)) |
| 50 | 0 | return this.make(selector, this); |
| 51 | ||
| 52 | // $(<html>) | |
| 53 | 4219 | if (typeof selector === 'string' && isHtml(selector)) { |
| 54 | 4107 | return this.make(parse(selector).children); |
| 55 | } | |
| 56 | ||
| 57 | // If we don't have a context, maybe we have a root, from loading | |
| 58 | 113 | if (!context) { |
| 59 | 113 | context = this._root; |
| 60 | 0 | } else if (typeof context === 'string') { |
| 61 | 0 | if (isHtml(context)) { |
| 62 | // $('li', '<ul>...</ul>') | |
| 63 | 0 | context = parse(context); |
| 64 | 0 | context = this.make(context, this); |
| 65 | } else { | |
| 66 | // $('li', 'ul') | |
| 67 | 0 | selector = [context, selector].join(' '); |
| 68 | 0 | context = this._root; |
| 69 | } | |
| 70 | } | |
| 71 | ||
| 72 | // If we still don't have a context, return | |
| 73 | 113 | if (!context) return this; |
| 74 | ||
| 75 | // #id, .class, tag | |
| 76 | 113 | return context.find(selector); |
| 77 | }; | |
| 78 | ||
| 79 | /** | |
| 80 | * Inherit from `static` | |
| 81 | */ | |
| 82 | ||
| 83 | 1 | Cheerio.__proto__ = require('./static'); |
| 84 | ||
| 85 | /* | |
| 86 | * Set a signature of the object | |
| 87 | */ | |
| 88 | ||
| 89 | 1 | Cheerio.prototype.cheerio = '[cheerio object]'; |
| 90 | ||
| 91 | /* | |
| 92 | * Cheerio default options | |
| 93 | */ | |
| 94 | ||
| 95 | 1 | Cheerio.prototype.options = { |
| 96 | ignoreWhitespace: false, | |
| 97 | xmlMode: false, | |
| 98 | lowerCaseTags: false | |
| 99 | }; | |
| 100 | ||
| 101 | /* | |
| 102 | * Make cheerio an array-like object | |
| 103 | */ | |
| 104 | ||
| 105 | 1 | Cheerio.prototype.length = 0; |
| 106 | 1 | Cheerio.prototype.sort = [].splice; |
| 107 | ||
| 108 | /* | |
| 109 | * Check if string is HTML | |
| 110 | */ | |
| 111 | 1 | var isHtml = function(str) { |
| 112 | // Faster than running regex, if str starts with `<` and ends with `>`, assume it's HTML | |
| 113 | 8445 | if (str.charAt(0) === '<' && str.charAt(str.length - 1) === '>' && str.length >= 3) return true; |
| 114 | ||
| 115 | // Run the regex | |
| 116 | 113 | var match = quickExpr.exec(str); |
| 117 | 113 | return !!(match && match[1]); |
| 118 | }; | |
| 119 | ||
| 120 | /* | |
| 121 | * Make a cheerio object | |
| 122 | */ | |
| 123 | ||
| 124 | 1 | Cheerio.prototype.make = function(dom, context) { |
| 125 | 60878 | if (dom.cheerio) return dom; |
| 126 | 60894 | dom = (Array.isArray(dom)) ? dom : [dom]; |
| 127 | 60910 | return _.extend(context || new Cheerio(), dom, { length: dom.length }); |
| 128 | }; | |
| 129 | ||
| 130 | /** | |
| 131 | * Turn a cheerio object into an array | |
| 132 | */ | |
| 133 | ||
| 134 | 1 | Cheerio.prototype.toArray = function() { |
| 135 | 4186 | return [].slice.call(this, 0); |
| 136 | }; | |
| 137 | ||
| 138 | /** | |
| 139 | * Plug in the API | |
| 140 | */ | |
| 141 | 1 | api.forEach(function(mod) { |
| 142 | 4 | _.extend(Cheerio.prototype, require('./api/' + mod)); |
| 143 | }); | |
| 144 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | exports = module.exports = require('./lib/select'); |
| 2 | ||
| 3 | /* | |
| 4 | Export the version | |
| 5 | */ | |
| 6 | 1 | exports.version = (function() { |
| 7 | 1 | var pkg = require('fs').readFileSync(__dirname + '/package.json', 'utf8'); |
| 8 | 1 | return JSON.parse(pkg).version; |
| 9 | })(); | |
| 10 |
| Line | Hits | Source |
|---|---|---|
| 1 | /* | |
| 2 | * Module dependencies | |
| 3 | */ | |
| 4 | 1 | var CSSselect = require('CSSselect'), |
| 5 | isArray = Array.isArray; | |
| 6 | ||
| 7 | /* | |
| 8 | * Select function | |
| 9 | */ | |
| 10 | 1 | exports = module.exports = function(query, dom) { |
| 11 | 17005 | dom = normalize(dom); |
| 12 | ||
| 13 | 17013 | return CSSselect.iterate(query, dom); |
| 14 | }; | |
| 15 | ||
| 16 | /* | |
| 17 | * Normalize the dom | |
| 18 | */ | |
| 19 | 1 | var normalize = exports.normalize = function(dom) { |
| 20 | 17041 | dom = dom.cheerio ? dom.toArray() : dom; |
| 21 | 17045 | dom = isArray(dom) ? dom : [dom]; |
| 22 | ||
| 23 | 17053 | var len = dom.length, |
| 24 | out = [], | |
| 25 | elem; | |
| 26 | ||
| 27 | 17069 | for(var i = 0; i < len; i++) { |
| 28 | 50917 | elem = dom[i]; |
| 29 | 50929 | if(elem.type === 'root') { |
| 30 | 0 | out = out.concat(elem.children || []); |
| 31 | } else { | |
| 32 | 50965 | out.push(elem); |
| 33 | } | |
| 34 | } | |
| 35 | ||
| 36 | 17105 | return out; |
| 37 | }; |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | "use strict"; |
| 2 | ||
| 3 | 1 | module.exports = CSSselect; |
| 4 | ||
| 5 | 1 | var Pseudos = require("c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/./lib/pseudos.js"), |
| 6 | DomUtils = require("domutils"), | |
| 7 | findOne = DomUtils.findOne, | |
| 8 | findAll = DomUtils.findAll, | |
| 9 | getChildren = DomUtils.getChildren, | |
| 10 | removeSubsets = DomUtils.removeSubsets, | |
| 11 | falseFunc = require("c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/./lib/basefunctions.js").falseFunc, | |
| 12 | compile = require("c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/./lib/compile.js"); | |
| 13 | ||
| 14 | 1 | function getSelectorFunc(searchFunc){ |
| 15 | 2 | return function select(query, elems, options){ |
| 16 | 34370 | if(typeof query !== "function") query = compile(query, options); |
| 17 | 17189 | if(!Array.isArray(elems)) elems = getChildren(elems); |
| 18 | 17193 | else elems = removeSubsets(elems); |
| 19 | 17197 | return searchFunc(query, elems); |
| 20 | }; | |
| 21 | } | |
| 22 | ||
| 23 | 1 | var selectAll = getSelectorFunc(function selectAll(query, elems){ |
| 24 | 17217 | return (query === falseFunc || !elems || elems.length === 0) ? [] : findAll(query, elems); |
| 25 | }); | |
| 26 | ||
| 27 | 1 | var selectOne = getSelectorFunc(function selectOne(query, elems){ |
| 28 | 0 | return (query === falseFunc || !elems || elems.length === 0) ? null : findOne(query, elems); |
| 29 | }); | |
| 30 | ||
| 31 | 1 | function is(elem, query, options){ |
| 32 | 0 | return (typeof query === "function" ? query : compile(query, options))(elem); |
| 33 | } | |
| 34 | ||
| 35 | /* | |
| 36 | the exported interface | |
| 37 | */ | |
| 38 | 1 | function CSSselect(query, elems, options){ |
| 39 | 0 | return selectAll(query, elems, options); |
| 40 | } | |
| 41 | ||
| 42 | 1 | CSSselect.compile = compile; |
| 43 | 1 | CSSselect.filters = Pseudos.filters; |
| 44 | 1 | CSSselect.pseudos = Pseudos.pseudos; |
| 45 | ||
| 46 | 1 | CSSselect.selectAll = selectAll; |
| 47 | 1 | CSSselect.selectOne = selectOne; |
| 48 | ||
| 49 | 1 | CSSselect.is = is; |
| 50 | ||
| 51 | //legacy methods (might be removed) | |
| 52 | 1 | CSSselect.parse = compile; |
| 53 | 1 | CSSselect.iterate = selectAll; |
| 54 |
| Line | Hits | Source |
|---|---|---|
| 1 | /* | |
| 2 | pseudo selectors | |
| 3 | ||
| 4 | --- | |
| 5 | ||
| 6 | they are available in two forms: | |
| 7 | * filters called when the selector | |
| 8 | is compiled and return a function | |
| 9 | that needs to return next() | |
| 10 | * pseudos get called on execution | |
| 11 | they need to return a boolean | |
| 12 | */ | |
| 13 | ||
| 14 | 1 | var DomUtils = require("domutils"), |
| 15 | isTag = DomUtils.isTag, | |
| 16 | getText = DomUtils.getText, | |
| 17 | getParent = DomUtils.getParent, | |
| 18 | getChildren = DomUtils.getChildren, | |
| 19 | getSiblings = DomUtils.getSiblings, | |
| 20 | hasAttrib = DomUtils.hasAttrib, | |
| 21 | getName = DomUtils.getName, | |
| 22 | getAttribute= DomUtils.getAttributeValue, | |
| 23 | getNCheck = require("c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/lib/./nth-check.js"), | |
| 24 | checkAttrib = require("c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/lib/./attributes.js").rules.equals, | |
| 25 | BaseFuncs = require("c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/lib/./basefunctions.js"), | |
| 26 | trueFunc = BaseFuncs.trueFunc, | |
| 27 | falseFunc = BaseFuncs.falseFunc; | |
| 28 | ||
| 29 | //helper methods | |
| 30 | 1 | function getFirstElement(elems){ |
| 31 | 0 | for(var i = 0; elems && i < elems.length; i++){ |
| 32 | 0 | if(isTag(elems[i])) return elems[i]; |
| 33 | } | |
| 34 | } | |
| 35 | ||
| 36 | 1 | function getAttribFunc(name, value){ |
| 37 | 7 | var data = {name: name, value: value}; |
| 38 | 7 | return function attribFunc(next){ |
| 39 | 0 | return checkAttrib(next, data); |
| 40 | }; | |
| 41 | } | |
| 42 | ||
| 43 | 1 | function getChildFunc(next){ |
| 44 | 0 | return function(elem){ |
| 45 | 0 | return !!getParent(elem) && next(elem); |
| 46 | }; | |
| 47 | } | |
| 48 | ||
| 49 | 1 | var filters = { |
| 50 | contains: function(next, text){ | |
| 51 | 0 | if( |
| 52 | (text.charAt(0) === "\"" || text.charAt(0) === "'") && | |
| 53 | text.charAt(0) === text.substr(-1) | |
| 54 | ){ | |
| 55 | 0 | text = text.slice(1, -1); |
| 56 | } | |
| 57 | 0 | return function contains(elem){ |
| 58 | 0 | return getText(elem).indexOf(text) >= 0 && next(elem); |
| 59 | }; | |
| 60 | }, | |
| 61 | ||
| 62 | //location specific methods | |
| 63 | //first- and last-child methods return as soon as they find another element | |
| 64 | "first-child": function(next){ | |
| 65 | 0 | return function firstChild(elem){ |
| 66 | 0 | return getFirstElement(getSiblings(elem)) === elem && next(elem); |
| 67 | }; | |
| 68 | }, | |
| 69 | "last-child": function(next){ | |
| 70 | 0 | return function lastChild(elem){ |
| 71 | 0 | var siblings = getSiblings(elem); |
| 72 | ||
| 73 | 0 | for(var i = siblings.length - 1; i >= 0; i--){ |
| 74 | 0 | if(siblings[i] === elem) return next(elem); |
| 75 | 0 | if(isTag(siblings[i])) break; |
| 76 | } | |
| 77 | ||
| 78 | 0 | return false; |
| 79 | }; | |
| 80 | }, | |
| 81 | "first-of-type": function(next){ | |
| 82 | 0 | return function firstOfType(elem){ |
| 83 | 0 | var siblings = getSiblings(elem); |
| 84 | ||
| 85 | 0 | for(var i = 0; i < siblings.length; i++){ |
| 86 | 0 | if(isTag(siblings[i])){ |
| 87 | 0 | if(siblings[i] === elem) return next(elem); |
| 88 | 0 | if(getName(siblings[i]) === getName(elem)) break; |
| 89 | } | |
| 90 | } | |
| 91 | ||
| 92 | 0 | return false; |
| 93 | }; | |
| 94 | }, | |
| 95 | "last-of-type": function(next){ | |
| 96 | 0 | return function lastOfType(elem){ |
| 97 | 0 | var siblings = getSiblings(elem); |
| 98 | ||
| 99 | 0 | for(var i = siblings.length-1; i >= 0; i--){ |
| 100 | 0 | if(isTag(siblings[i])){ |
| 101 | 0 | if(siblings[i] === elem) return next(elem); |
| 102 | 0 | if(getName(siblings[i]) === getName(elem)) break; |
| 103 | } | |
| 104 | } | |
| 105 | ||
| 106 | 0 | return false; |
| 107 | }; | |
| 108 | }, | |
| 109 | "only-of-type": function(next){ | |
| 110 | 0 | return function onlyOfType(elem){ |
| 111 | 0 | var siblings = getSiblings(elem); |
| 112 | ||
| 113 | 0 | for(var i = 0, j = siblings.length; i < j; i++){ |
| 114 | 0 | if(isTag(siblings[i])){ |
| 115 | 0 | if(siblings[i] === elem) continue; |
| 116 | 0 | if(getName(siblings[i]) === getName(elem)) return false; |
| 117 | } | |
| 118 | } | |
| 119 | ||
| 120 | 0 | return next(elem); |
| 121 | }; | |
| 122 | }, | |
| 123 | "only-child": function(next){ | |
| 124 | 0 | return function onlyChild(elem){ |
| 125 | 0 | var siblings = getSiblings(elem); |
| 126 | ||
| 127 | 0 | for(var i = 0; i < siblings.length; i++){ |
| 128 | 0 | if(isTag(siblings[i]) && siblings[i] !== elem) return false; |
| 129 | } | |
| 130 | ||
| 131 | 0 | return next(elem); |
| 132 | }; | |
| 133 | }, | |
| 134 | "nth-child": function(next, rule){ | |
| 135 | 0 | var func = getNCheck(rule); |
| 136 | ||
| 137 | 0 | if(func === falseFunc) return func; |
| 138 | 0 | if(func === trueFunc) return getChildFunc(next); |
| 139 | ||
| 140 | 0 | return function nthChild(elem){ |
| 141 | 0 | var siblings = getSiblings(elem); |
| 142 | ||
| 143 | 0 | for(var i = 0, pos = 0; i < siblings.length; i++){ |
| 144 | 0 | if(isTag(siblings[i])){ |
| 145 | 0 | if(siblings[i] === elem) break; |
| 146 | 0 | else pos++; |
| 147 | } | |
| 148 | } | |
| 149 | ||
| 150 | 0 | return func(pos) && next(elem); |
| 151 | }; | |
| 152 | }, | |
| 153 | "nth-last-child": function(next, rule){ | |
| 154 | 0 | var func = getNCheck(rule); |
| 155 | ||
| 156 | 0 | if(func === falseFunc) return func; |
| 157 | 0 | if(func === trueFunc) return getChildFunc(next); |
| 158 | ||
| 159 | 0 | return function nthLastChild(elem){ |
| 160 | 0 | var siblings = getSiblings(elem); |
| 161 | ||
| 162 | 0 | for(var pos = 0, i = siblings.length - 1; i >= 0; i--){ |
| 163 | 0 | if(isTag(siblings[i])){ |
| 164 | 0 | if(siblings[i] === elem) break; |
| 165 | 0 | else pos++; |
| 166 | } | |
| 167 | } | |
| 168 | ||
| 169 | 0 | return func(pos) && next(elem); |
| 170 | }; | |
| 171 | }, | |
| 172 | "nth-of-type": function(next, rule){ | |
| 173 | 0 | var func = getNCheck(rule); |
| 174 | ||
| 175 | 0 | if(func === falseFunc) return func; |
| 176 | 0 | if(func === trueFunc) return getChildFunc(next); |
| 177 | ||
| 178 | 0 | return function nthOfType(elem){ |
| 179 | 0 | var siblings = getSiblings(elem); |
| 180 | ||
| 181 | 0 | for(var pos = 0, i = 0; i < siblings.length; i++){ |
| 182 | 0 | if(isTag(siblings[i])){ |
| 183 | 0 | if(siblings[i] === elem) break; |
| 184 | 0 | if(getName(siblings[i]) === getName(elem)) pos++; |
| 185 | } | |
| 186 | } | |
| 187 | ||
| 188 | 0 | return func(pos) && next(elem); |
| 189 | }; | |
| 190 | }, | |
| 191 | "nth-last-of-type": function(next, rule){ | |
| 192 | 0 | var func = getNCheck(rule); |
| 193 | ||
| 194 | 0 | if(func === falseFunc) return func; |
| 195 | 0 | if(func === trueFunc) return getChildFunc(next); |
| 196 | ||
| 197 | 0 | return function nthLastOfType(elem){ |
| 198 | 0 | var siblings = getSiblings(elem); |
| 199 | ||
| 200 | 0 | for(var pos = 0, i = siblings.length - 1; i >= 0; i--){ |
| 201 | 0 | if(siblings[i] === elem) break; |
| 202 | 0 | if(getName(siblings[i]) === getName(elem)) pos++; |
| 203 | } | |
| 204 | ||
| 205 | 0 | return func(pos) && next(elem); |
| 206 | }; | |
| 207 | }, | |
| 208 | ||
| 209 | //jQuery extensions (others follow as pseudos) | |
| 210 | checkbox: getAttribFunc("type", "checkbox"), | |
| 211 | file: getAttribFunc("type", "file"), | |
| 212 | password: getAttribFunc("type", "password"), | |
| 213 | radio: getAttribFunc("type", "radio"), | |
| 214 | reset: getAttribFunc("type", "reset"), | |
| 215 | image: getAttribFunc("type", "image"), | |
| 216 | submit: getAttribFunc("type", "submit") | |
| 217 | }; | |
| 218 | ||
| 219 | //while filters are precompiled, pseudos get called when they are needed | |
| 220 | 1 | var pseudos = { |
| 221 | root: function(elem){ | |
| 222 | 0 | return !getParent(elem); |
| 223 | }, | |
| 224 | empty: function(elem){ | |
| 225 | 0 | return !getChildren(elem).some(function(elem){ |
| 226 | 0 | return isTag(elem) || elem.type === "text"; |
| 227 | }); | |
| 228 | }, | |
| 229 | ||
| 230 | //forms | |
| 231 | //to consider: :target, :enabled | |
| 232 | selected: function(elem){ | |
| 233 | 0 | if(hasAttrib(elem, "selected")) return true; |
| 234 | 0 | else if(getName(elem) !== "option") return false; |
| 235 | ||
| 236 | //the first <option> in a <select> is also selected | |
| 237 | 0 | var parent = getParent(elem); |
| 238 | ||
| 239 | 0 | if(!parent || getName(parent) !== "select") return false; |
| 240 | ||
| 241 | 0 | var siblings = getChildren(parent), |
| 242 | sawElem = false; | |
| 243 | ||
| 244 | 0 | for(var i = 0; i < siblings.length; i++){ |
| 245 | 0 | if(isTag(siblings[i])){ |
| 246 | 0 | if(siblings[i] === elem){ |
| 247 | 0 | sawElem = true; |
| 248 | 0 | } else if(!sawElem){ |
| 249 | 0 | return false; |
| 250 | 0 | } else if(hasAttrib(siblings[i], "selected")){ |
| 251 | 0 | return false; |
| 252 | } | |
| 253 | } | |
| 254 | } | |
| 255 | ||
| 256 | 0 | return sawElem; |
| 257 | }, | |
| 258 | disabled: function(elem){ | |
| 259 | 0 | return hasAttrib(elem, "disabled"); |
| 260 | }, | |
| 261 | enabled: function(elem){ | |
| 262 | 0 | return !hasAttrib(elem, "disabled"); |
| 263 | }, | |
| 264 | checked: function(elem){ | |
| 265 | 0 | return hasAttrib(elem, "checked") || pseudos.selected(elem); |
| 266 | }, | |
| 267 | ||
| 268 | //jQuery extensions | |
| 269 | ||
| 270 | //:parent is the inverse of :empty | |
| 271 | parent: function(elem){ | |
| 272 | 0 | return !pseudos.empty(elem); |
| 273 | }, | |
| 274 | header: function(elem){ | |
| 275 | 0 | var name = getName(elem); |
| 276 | 0 | return name === "h1" || |
| 277 | name === "h2" || | |
| 278 | name === "h3" || | |
| 279 | name === "h4" || | |
| 280 | name === "h5" || | |
| 281 | name === "h6"; | |
| 282 | }, | |
| 283 | ||
| 284 | button: function(elem){ | |
| 285 | 0 | var name = getName(elem); |
| 286 | 0 | return name === "button" || |
| 287 | name === "input" && | |
| 288 | getAttribute(elem, "type") === "button"; | |
| 289 | }, | |
| 290 | input: function(elem){ | |
| 291 | 0 | var name = getName(elem); |
| 292 | 0 | return name === "input" || |
| 293 | name === "textarea" || | |
| 294 | name === "select" || | |
| 295 | name === "button"; | |
| 296 | }, | |
| 297 | text: function(elem){ | |
| 298 | 0 | var attr; |
| 299 | 0 | return getName(elem) === "input" && ( |
| 300 | !(attr = getAttribute(elem, "type")) || | |
| 301 | attr.toLowerCase() === "text" | |
| 302 | ); | |
| 303 | } | |
| 304 | }; | |
| 305 | ||
| 306 | 1 | function verifyArgs(func, name, subselect){ |
| 307 | 0 | if(subselect === null){ |
| 308 | 0 | if(func.length > 1){ |
| 309 | 0 | throw new SyntaxError("pseudo-selector :" + name + " requires an argument"); |
| 310 | } | |
| 311 | } else { | |
| 312 | 0 | if(func.length === 1){ |
| 313 | 0 | throw new SyntaxError("pseudo-selector :" + name + " doesn't have any arguments"); |
| 314 | } | |
| 315 | } | |
| 316 | } | |
| 317 | ||
| 318 | 1 | module.exports = { |
| 319 | compile: function(next, data){ | |
| 320 | 0 | var name = data.name, |
| 321 | subselect = data.data; | |
| 322 | ||
| 323 | 0 | if(typeof filters[name] === "function"){ |
| 324 | 0 | verifyArgs(filters[name], name, subselect); |
| 325 | 0 | return filters[name](next, subselect); |
| 326 | 0 | } else if(typeof pseudos[name] === "function"){ |
| 327 | 0 | var func = pseudos[name]; |
| 328 | 0 | verifyArgs(func, name, subselect); |
| 329 | 0 | return function pseudoArgs(elem){ |
| 330 | 0 | return func(elem, subselect) && next(elem); |
| 331 | }; | |
| 332 | } else { | |
| 333 | 0 | throw new SyntaxError("unmatched pseudo-class :" + name); |
| 334 | } | |
| 335 | }, | |
| 336 | filters: filters, | |
| 337 | pseudos: pseudos | |
| 338 | }; | |
| 339 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | var DomUtils = module.exports; |
| 2 | ||
| 3 | 1 | [ |
| 4 | "stringify", "traversal", "manipulation", "querying", "legacy", "helpers" | |
| 5 | ].forEach(function(name){ | |
| 6 | 6 | var ext = require("c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/node_modules/domutils/./lib/" + name); |
| 7 | 6 | Object.keys(ext).forEach(function(key){ |
| 8 | 26 | DomUtils[key] = ext[key].bind(DomUtils); |
| 9 | }); | |
| 10 | }); | |
| 11 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | var ElementType = require("domelementtype"), |
| 2 | isTag = ElementType.isTag; | |
| 3 | ||
| 4 | 1 | module.exports = { |
| 5 | getInnerHTML: getInnerHTML, | |
| 6 | getOuterHTML: getOuterHTML, | |
| 7 | getText: getText | |
| 8 | }; | |
| 9 | ||
| 10 | 1 | function getInnerHTML(elem){ |
| 11 | 0 | return elem.children ? elem.children.map(getOuterHTML).join("") : ""; |
| 12 | } | |
| 13 | ||
| 14 | //boolean attributes without a value (taken from MatthewMueller/cheerio) | |
| 15 | 1 | var booleanAttribs = { |
| 16 | __proto__: null, | |
| 17 | async: true, | |
| 18 | autofocus: true, | |
| 19 | autoplay: true, | |
| 20 | checked: true, | |
| 21 | controls: true, | |
| 22 | defer: true, | |
| 23 | disabled: true, | |
| 24 | hidden: true, | |
| 25 | loop: true, | |
| 26 | multiple: true, | |
| 27 | open: true, | |
| 28 | readonly: true, | |
| 29 | required: true, | |
| 30 | scoped: true, | |
| 31 | selected: true | |
| 32 | }; | |
| 33 | ||
| 34 | 1 | var emptyTags = { |
| 35 | __proto__: null, | |
| 36 | area: true, | |
| 37 | base: true, | |
| 38 | basefont: true, | |
| 39 | br: true, | |
| 40 | col: true, | |
| 41 | frame: true, | |
| 42 | hr: true, | |
| 43 | img: true, | |
| 44 | input: true, | |
| 45 | isindex: true, | |
| 46 | link: true, | |
| 47 | meta: true, | |
| 48 | param: true, | |
| 49 | embed: true | |
| 50 | }; | |
| 51 | ||
| 52 | 1 | function getOuterHTML(elem){ |
| 53 | 0 | switch(elem.type){ |
| 54 | case ElementType.Text: | |
| 55 | 0 | return elem.data; |
| 56 | case ElementType.Comment: | |
| 57 | 0 | return "<!--" + elem.data + "-->"; |
| 58 | case ElementType.Directive: | |
| 59 | 0 | return "<" + elem.data + ">"; |
| 60 | case ElementType.CDATA: | |
| 61 | 0 | return "<!CDATA " + getInnerHTML(elem) + "]]>"; |
| 62 | } | |
| 63 | ||
| 64 | 0 | var ret = "<" + elem.name; |
| 65 | 0 | if("attribs" in elem){ |
| 66 | 0 | for(var attr in elem.attribs){ |
| 67 | 0 | if(elem.attribs.hasOwnProperty(attr)){ |
| 68 | 0 | ret += " " + attr; |
| 69 | 0 | var value = elem.attribs[attr]; |
| 70 | 0 | if(value == null){ |
| 71 | 0 | if( !(attr in booleanAttribs) ){ |
| 72 | 0 | ret += "=\"\""; |
| 73 | } | |
| 74 | } else { | |
| 75 | 0 | ret += "=\"" + value + "\""; |
| 76 | } | |
| 77 | } | |
| 78 | } | |
| 79 | } | |
| 80 | ||
| 81 | 0 | if (elem.name in emptyTags && elem.children.length === 0) { |
| 82 | 0 | return ret + " />"; |
| 83 | } else { | |
| 84 | 0 | return ret + ">" + getInnerHTML(elem) + "</" + elem.name + ">"; |
| 85 | } | |
| 86 | } | |
| 87 | ||
| 88 | 1 | function getText(elem){ |
| 89 | 0 | if(Array.isArray(elem)) return elem.map(getText).join(""); |
| 90 | 0 | if(isTag(elem) || elem.type === ElementType.CDATA) return getText(elem.children); |
| 91 | 0 | if(elem.type === ElementType.Text) return elem.data; |
| 92 | 0 | return ""; |
| 93 | } |
| Line | Hits | Source |
|---|---|---|
| 1 | //Types of elements found in the DOM | |
| 2 | 1 | module.exports = { |
| 3 | Text: "text", //Text | |
| 4 | Directive: "directive", //<? ... ?> | |
| 5 | Comment: "comment", //<!-- ... --> | |
| 6 | Script: "script", //<script> tags | |
| 7 | Style: "style", //<style> tags | |
| 8 | Tag: "tag", //Any tag | |
| 9 | CDATA: "cdata", //<![CDATA[ ... ]]> | |
| 10 | ||
| 11 | isTag: function(elem){ | |
| 12 | 7259060 | return elem.type === "tag" || elem.type === "script" || elem.type === "style"; |
| 13 | } | |
| 14 | }; |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | var getChildren = exports.getChildren = function(elem){ |
| 2 | 7389197 | return elem.children; |
| 3 | }; | |
| 4 | ||
| 5 | 1 | var getParent = exports.getParent = function(elem){ |
| 6 | 33324 | return elem.parent; |
| 7 | }; | |
| 8 | ||
| 9 | 1 | exports.getSiblings = function(elem){ |
| 10 | 0 | var parent = getParent(elem); |
| 11 | 0 | return parent ? getChildren(parent) : [elem]; |
| 12 | }; | |
| 13 | ||
| 14 | 1 | exports.getAttributeValue = function(elem, name){ |
| 15 | 1399356 | return elem.attribs && elem.attribs[name]; |
| 16 | }; | |
| 17 | ||
| 18 | 1 | exports.hasAttrib = function(elem, name){ |
| 19 | 0 | return hasOwnProperty.call(elem.attribs, name); |
| 20 | }; | |
| 21 | ||
| 22 | 1 | exports.getName = function(elem){ |
| 23 | 3146804 | return elem.name; |
| 24 | }; | |
| 25 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | exports.removeElement = function(elem){ |
| 2 | 0 | if(elem.prev) elem.prev.next = elem.next; |
| 3 | 0 | if(elem.next) elem.next.prev = elem.prev; |
| 4 | ||
| 5 | 0 | if(elem.parent){ |
| 6 | 0 | var childs = elem.parent.children; |
| 7 | 0 | childs.splice(childs.lastIndexOf(elem), 1); |
| 8 | } | |
| 9 | }; | |
| 10 | ||
| 11 | 1 | exports.replaceElement = function(elem, replacement){ |
| 12 | 0 | var prev = replacement.prev = elem.prev; |
| 13 | 0 | if(prev){ |
| 14 | 0 | prev.next = replacement; |
| 15 | } | |
| 16 | ||
| 17 | 0 | var next = replacement.next = elem.next; |
| 18 | 0 | if(next){ |
| 19 | 0 | next.prev = replacement; |
| 20 | } | |
| 21 | ||
| 22 | 0 | var parent = replacement.parent = elem.parent; |
| 23 | 0 | if(parent){ |
| 24 | 0 | var childs = parent.children; |
| 25 | 0 | childs[childs.lastIndexOf(elem)] = replacement; |
| 26 | } | |
| 27 | }; | |
| 28 | ||
| 29 | 1 | exports.appendChild = function(elem, child){ |
| 30 | 0 | child.parent = elem; |
| 31 | ||
| 32 | 0 | if(elem.children.push(child) !== 1){ |
| 33 | 0 | var sibling = elem.children[elem.children.length - 2]; |
| 34 | 0 | sibling.next = child; |
| 35 | 0 | child.prev = sibling; |
| 36 | 0 | child.next = null; |
| 37 | } | |
| 38 | }; | |
| 39 | ||
| 40 | 1 | exports.append = function(elem, next){ |
| 41 | 0 | var parent = elem.parent, |
| 42 | currNext = elem.next; | |
| 43 | ||
| 44 | 0 | next.next = currNext; |
| 45 | 0 | next.prev = elem; |
| 46 | 0 | elem.next = next; |
| 47 | ||
| 48 | 0 | if(currNext){ |
| 49 | 0 | currNext.prev = next; |
| 50 | 0 | if(parent){ |
| 51 | 0 | var childs = parent.children; |
| 52 | 0 | childs.splice(childs.lastIndexOf(currNext), 0, next); |
| 53 | } | |
| 54 | 0 | } else if(parent){ |
| 55 | 0 | parent.children.push(next); |
| 56 | } | |
| 57 | }; | |
| 58 | ||
| 59 | 1 | exports.prepend = function(elem, prev){ |
| 60 | 0 | var parent = elem.parent; |
| 61 | 0 | if(parent){ |
| 62 | 0 | var childs = parent.children; |
| 63 | 0 | childs.splice(childs.lastIndexOf(elem), 0, prev); |
| 64 | } | |
| 65 | ||
| 66 | 0 | if(elem.prev){ |
| 67 | 0 | elem.prev.next = prev; |
| 68 | } | |
| 69 | 0 | prev.prev = elem.prev; |
| 70 | 0 | prev.next = elem; |
| 71 | 0 | elem.prev = prev; |
| 72 | }; | |
| 73 | ||
| 74 | ||
| 75 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | exports.find = function(test, arr, recurse, limit){ |
| 2 | 0 | var result = [], childs; |
| 3 | ||
| 4 | 0 | for(var i = 0, j = arr.length; i < j; i++){ |
| 5 | 0 | if(test(arr[i])){ |
| 6 | 0 | result.push(arr[i]); |
| 7 | 0 | if(--limit <= 0) break; |
| 8 | } | |
| 9 | ||
| 10 | 0 | childs = this.getChildren(arr[i]); |
| 11 | 0 | if(recurse && childs && childs.length > 0){ |
| 12 | 0 | childs = this.find(test, childs, recurse, limit); |
| 13 | 0 | result = result.concat(childs); |
| 14 | 0 | limit -= childs.length; |
| 15 | 0 | if(limit <= 0) break; |
| 16 | } | |
| 17 | } | |
| 18 | ||
| 19 | 0 | return result; |
| 20 | }; | |
| 21 | ||
| 22 | 1 | exports.findOneChild = function(test, arr){ |
| 23 | 0 | for(var i = 0, l = arr.length; i < l; i++){ |
| 24 | 0 | if(test(arr[i])) return arr[i]; |
| 25 | } | |
| 26 | ||
| 27 | 0 | return null; |
| 28 | }; | |
| 29 | ||
| 30 | 1 | exports.findOne = function(test, arr){ |
| 31 | 0 | var elem = null; |
| 32 | ||
| 33 | 0 | for(var i = 0, l = arr.length; i < l && !elem; i++){ |
| 34 | 0 | if(test(arr[i])){ |
| 35 | 0 | elem = arr[i]; |
| 36 | 0 | } else if(arr[i].children && arr[i].children.length > 0){ |
| 37 | 0 | elem = this.findOne(test, arr[i].children); |
| 38 | } | |
| 39 | } | |
| 40 | ||
| 41 | 0 | return elem; |
| 42 | }; | |
| 43 | ||
| 44 | 1 | exports.findAll = function(test, elems){ |
| 45 | 4070110 | var result = []; |
| 46 | 4070285 | for(var i = 0, j = elems.length; i < j; i++){ |
| 47 | 7707592 | if(test(elems[i])) result.push(elems[i]); |
| 48 | ||
| 49 | 7688459 | var childs = this.getChildren(elems[i]); |
| 50 | 7688821 | if(childs && childs.length){ |
| 51 | 4051364 | result = result.concat(this.findAll(test, childs)); |
| 52 | } | |
| 53 | } | |
| 54 | 4071820 | return result; |
| 55 | }; | |
| 56 | ||
| 57 | 1 | exports.filter = function(test, element, recurse, limit){ |
| 58 | 0 | if(!Array.isArray(element)) element = [element]; |
| 59 | ||
| 60 | 0 | if(typeof limit !== "number" || !isFinite(limit)){ |
| 61 | 0 | if(recurse === false){ |
| 62 | 0 | return element.filter(test); |
| 63 | } else { | |
| 64 | 0 | return this.findAll(test, element); |
| 65 | } | |
| 66 | 0 | } else if(limit === 1){ |
| 67 | 0 | if(recurse === false){ |
| 68 | 0 | element = this.findOneChild(test, element); |
| 69 | } else { | |
| 70 | 0 | element = this.findOne(test, element); |
| 71 | } | |
| 72 | 0 | return element ? [element] : []; |
| 73 | } else { | |
| 74 | 0 | return this.find(test, element, recurse !== false, limit); |
| 75 | } | |
| 76 | }; | |
| 77 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | var ElementType = require("domelementtype"); |
| 2 | 1 | var isTag = exports.isTag = ElementType.isTag; |
| 3 | ||
| 4 | 1 | exports.testElement = function(options, element){ |
| 5 | 0 | for(var key in options){ |
| 6 | 0 | if(!options.hasOwnProperty(key)); |
| 7 | 0 | else if(key === "tag_name"){ |
| 8 | 0 | if(!isTag(element) || !options.tag_name(element.name)){ |
| 9 | 0 | return false; |
| 10 | } | |
| 11 | 0 | } else if(key === "tag_type"){ |
| 12 | 0 | if(!options.tag_type(element.type)) return false; |
| 13 | 0 | } else if(key === "tag_contains"){ |
| 14 | 0 | if(isTag(element) || !options.tag_contains(element.data)){ |
| 15 | 0 | return false; |
| 16 | } | |
| 17 | 0 | } else if(!element.attribs || !options[key](element.attribs[key])){ |
| 18 | 0 | return false; |
| 19 | } | |
| 20 | } | |
| 21 | 0 | return true; |
| 22 | }; | |
| 23 | ||
| 24 | 1 | var Checks = { |
| 25 | tag_name: function(name){ | |
| 26 | 0 | if(typeof name === "function"){ |
| 27 | 0 | return function(elem){ return isTag(elem) && name(elem.name); }; |
| 28 | 0 | } else if(name === "*"){ |
| 29 | 0 | return isTag; |
| 30 | } else { | |
| 31 | 0 | return function(elem){ return isTag(elem) && elem.name === name; }; |
| 32 | } | |
| 33 | }, | |
| 34 | tag_type: function(type){ | |
| 35 | 0 | if(typeof type === "function"){ |
| 36 | 0 | return function(elem){ return type(elem.type); }; |
| 37 | } else { | |
| 38 | 0 | return function(elem){ return elem.type === type; }; |
| 39 | } | |
| 40 | }, | |
| 41 | tag_contains: function(data){ | |
| 42 | 0 | if(typeof data === "function"){ |
| 43 | 0 | return function(elem){ return !isTag(elem) && data(elem.data); }; |
| 44 | } else { | |
| 45 | 0 | return function(elem){ return !isTag(elem) && elem.data === data; }; |
| 46 | } | |
| 47 | } | |
| 48 | }; | |
| 49 | ||
| 50 | 1 | function getAttribCheck(attrib, value){ |
| 51 | 0 | if(typeof value === "function"){ |
| 52 | 0 | return function(elem){ return elem.attribs && value(elem.attribs[attrib]); }; |
| 53 | } else { | |
| 54 | 0 | return function(elem){ return elem.attribs && elem.attribs[attrib] === value; }; |
| 55 | } | |
| 56 | } | |
| 57 | ||
| 58 | 1 | function combineFuncs(a, b){ |
| 59 | 0 | return function(elem){ |
| 60 | 0 | return a(elem) || b(elem); |
| 61 | }; | |
| 62 | } | |
| 63 | ||
| 64 | 1 | exports.getElements = function(options, element, recurse, limit){ |
| 65 | 0 | var funcs = Object.keys(options).map(function(key){ |
| 66 | 0 | var value = options[key]; |
| 67 | 0 | return key in Checks ? Checks[key](value) : getAttribCheck(key, value); |
| 68 | }); | |
| 69 | ||
| 70 | 0 | return funcs.length === 0 ? [] : this.filter( |
| 71 | funcs.reduce(combineFuncs), | |
| 72 | element, recurse, limit | |
| 73 | ); | |
| 74 | }; | |
| 75 | ||
| 76 | 1 | exports.getElementById = function(id, element, recurse){ |
| 77 | 0 | if(!Array.isArray(element)) element = [element]; |
| 78 | 0 | return this.findOne(getAttribCheck("id", id), element, recurse !== false); |
| 79 | }; | |
| 80 | ||
| 81 | 1 | exports.getElementsByTagName = function(name, element, recurse, limit){ |
| 82 | 0 | return this.filter(Checks.tag_name(name), element, recurse, limit); |
| 83 | }; | |
| 84 | ||
| 85 | 1 | exports.getElementsByTagType = function(type, element, recurse, limit){ |
| 86 | 0 | return this.filter(Checks.tag_type(type), element, recurse, limit); |
| 87 | }; | |
| 88 |
| Line | Hits | Source |
|---|---|---|
| 1 | // removeSubsets | |
| 2 | // Given an array of nodes, remove any member that is contained by another. | |
| 3 | 1 | exports.removeSubsets = function(nodes) { |
| 4 | 20349 | var idx = nodes.length, node, ancestor, replace; |
| 5 | ||
| 6 | // Check if each node (or one of its ancestors) is already contained in the | |
| 7 | // array. | |
| 8 | 20365 | while (--idx > -1) { |
| 9 | 60705 | node = ancestor = nodes[idx]; |
| 10 | ||
| 11 | // Temporarily remove the node under consideration | |
| 12 | 60741 | nodes[idx] = null; |
| 13 | 60753 | replace = true; |
| 14 | ||
| 15 | 60777 | while (ancestor) { |
| 16 | 182206 | if (nodes.indexOf(ancestor) > -1) { |
| 17 | 0 | replace = false; |
| 18 | 0 | nodes.splice(idx, 1); |
| 19 | 0 | break; |
| 20 | } | |
| 21 | 182386 | ancestor = ancestor.parent; |
| 22 | } | |
| 23 | ||
| 24 | // If the node has been found to be unique, re-insert it. | |
| 25 | 60897 | if (replace) { |
| 26 | 60909 | nodes[idx] = node; |
| 27 | } | |
| 28 | } | |
| 29 | ||
| 30 | 20453 | return nodes; |
| 31 | }; | |
| 32 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | var BaseFuncs = require("c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/lib/./basefunctions.js"), |
| 2 | trueFunc = BaseFuncs.trueFunc, | |
| 3 | falseFunc = BaseFuncs.falseFunc; | |
| 4 | ||
| 5 | 1 | module.exports = function nthCheck(formula){ |
| 6 | 0 | return compile(parse(formula)); |
| 7 | }; | |
| 8 | ||
| 9 | 1 | module.exports.parse = parse; |
| 10 | 1 | module.exports.compile = compile; |
| 11 | ||
| 12 | //following http://www.w3.org/TR/css3-selectors/#nth-child-pseudo | |
| 13 | ||
| 14 | //[ ['-'|'+']? INTEGER? {N} [ S* ['-'|'+'] S* INTEGER ]? | |
| 15 | 1 | var re_nthElement = /^([+\-]?\d*n)?\s*(?:([+\-]?)\s*(\d+))?$/; |
| 16 | ||
| 17 | /* | |
| 18 | parses a nth-check formula, returns an array of two numbers | |
| 19 | */ | |
| 20 | 1 | function parse(formula){ |
| 21 | 0 | formula = formula.trim().toLowerCase(); |
| 22 | ||
| 23 | 0 | if(formula === "even"){ |
| 24 | 0 | return [2, 0]; |
| 25 | 0 | } else if(formula === "odd"){ |
| 26 | 0 | return [2, 1]; |
| 27 | } else { | |
| 28 | 0 | var parsed = formula.match(re_nthElement); |
| 29 | ||
| 30 | 0 | if(!parsed){ |
| 31 | 0 | throw new SyntaxError("n-th rule couldn't be parsed ('" + formula + "')"); |
| 32 | } | |
| 33 | ||
| 34 | 0 | var a; |
| 35 | ||
| 36 | 0 | if(parsed[1]){ |
| 37 | 0 | a = parseInt(parsed[1], 10); |
| 38 | 0 | if(!a){ |
| 39 | 0 | if(parsed[1].charAt(0) === "-") a = -1; |
| 40 | 0 | else a = 1; |
| 41 | } | |
| 42 | 0 | } else a = 0; |
| 43 | ||
| 44 | 0 | return [ |
| 45 | a, | |
| 46 | parsed[3] ? parseInt((parsed[2] || "") + parsed[3], 10) : 0 | |
| 47 | ]; | |
| 48 | } | |
| 49 | } | |
| 50 | ||
| 51 | /* | |
| 52 | returns a function that checks if an elements index matches the given rule | |
| 53 | highly optimized to return the fastest solution | |
| 54 | */ | |
| 55 | 1 | function compile(parsed){ |
| 56 | 0 | var a = parsed[0], |
| 57 | b = parsed[1] - 1; | |
| 58 | ||
| 59 | //when b <= 0, a*n won't be possible for any matches when a < 0 | |
| 60 | //besides, the specification says that no element is matched when a and b are 0 | |
| 61 | 0 | if(b < 0 && a <= 0) return falseFunc; |
| 62 | ||
| 63 | //when a is in the range -1..1, it matches any element (so only b is checked) | |
| 64 | 0 | if(a ===-1) return function(pos){ return pos <= b; }; |
| 65 | 0 | if(a === 0) return function(pos){ return pos === b; }; |
| 66 | //when b <= 0 and a === 1, they match any element | |
| 67 | 0 | if(a === 1) return b < 0 ? trueFunc : function(pos){ return pos >= b; }; |
| 68 | ||
| 69 | //when a > 0, modulo can be used to check if there is a match | |
| 70 | 0 | var bMod = b % a; |
| 71 | 0 | if(bMod < 0) bMod += a; |
| 72 | ||
| 73 | 0 | if(a > 1){ |
| 74 | 0 | return function(pos){ |
| 75 | 0 | return pos >= b && pos % a === bMod; |
| 76 | }; | |
| 77 | } | |
| 78 | ||
| 79 | 0 | a *= -1; //make `a` positive |
| 80 | ||
| 81 | 0 | return function(pos){ |
| 82 | 0 | return pos <= b && pos % a === bMod; |
| 83 | }; | |
| 84 | } |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | module.exports = { |
| 2 | trueFunc: function trueFunc(){ | |
| 3 | 20833 | return true; |
| 4 | }, | |
| 5 | falseFunc: function falseFunc(){ | |
| 6 | 0 | return false; |
| 7 | } | |
| 8 | }; |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | var DomUtils = require("domutils"), |
| 2 | hasAttrib = DomUtils.hasAttrib, | |
| 3 | getAttributeValue = DomUtils.getAttributeValue, | |
| 4 | falseFunc = require("c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/lib/./basefunctions.js").falseFunc; | |
| 5 | ||
| 6 | //https://github.com/slevithan/XRegExp/blob/master/src/xregexp.js#L469 | |
| 7 | 1 | var reChars = /[-[\]{}()*+?.,\\^$|#\s]/g; |
| 8 | ||
| 9 | /* | |
| 10 | attribute selectors | |
| 11 | */ | |
| 12 | ||
| 13 | 1 | var attributeRules = { |
| 14 | __proto__: null, | |
| 15 | equals: function(next, data){ | |
| 16 | 5275 | var name = data.name, |
| 17 | value = data.value; | |
| 18 | ||
| 19 | 5278 | if(data.ignoreCase){ |
| 20 | 0 | value = value.toLowerCase(); |
| 21 | ||
| 22 | 0 | return function(elem){ |
| 23 | 0 | var attr = getAttributeValue(elem, name); |
| 24 | 0 | return attr != null && attr.toLowerCase() === value && next(elem); |
| 25 | }; | |
| 26 | } | |
| 27 | ||
| 28 | 5287 | return function(elem){ |
| 29 | 1118114 | return getAttributeValue(elem, name) === value && next(elem); |
| 30 | }; | |
| 31 | }, | |
| 32 | hyphen: function(next, data){ | |
| 33 | 0 | var name = data.name, |
| 34 | value = data.value, | |
| 35 | len = value.length; | |
| 36 | ||
| 37 | 0 | if(data.ignoreCase){ |
| 38 | 0 | value = value.toLowerCase(); |
| 39 | ||
| 40 | 0 | return function(elem){ |
| 41 | 0 | var attr = getAttributeValue(elem, name); |
| 42 | 0 | return attr != null && |
| 43 | (attr.length === len || attr.charAt(len) === "-") && | |
| 44 | attr.substr(0, len).toLowerCase() === value && | |
| 45 | next(elem); | |
| 46 | }; | |
| 47 | } | |
| 48 | ||
| 49 | 0 | return function(elem){ |
| 50 | 0 | var attr = getAttributeValue(elem, name); |
| 51 | 0 | return attr != null && |
| 52 | attr.substr(0, len) === value && | |
| 53 | (attr.length === len || attr.charAt(len) === "-") && | |
| 54 | next(elem); | |
| 55 | }; | |
| 56 | }, | |
| 57 | element: function(next, data){ | |
| 58 | 15996 | var name = data.name, |
| 59 | value = data.value; | |
| 60 | ||
| 61 | 16005 | if(/\s/.test(value)){ |
| 62 | 0 | return falseFunc; |
| 63 | } | |
| 64 | ||
| 65 | 16017 | value = value.replace(reChars, "\\$&"); |
| 66 | ||
| 67 | 16023 | var pattern = "(?:^|\\s)" + value + "(?:$|\\s)", |
| 68 | flags = data.ignoreCase ? "i" : "", | |
| 69 | regex = new RegExp(pattern, flags); | |
| 70 | ||
| 71 | 16035 | return function(elem){ |
| 72 | 725993 | var attr = getAttributeValue(elem, name); |
| 73 | 726002 | return attr != null && regex.test(attr) && next(elem); |
| 74 | }; | |
| 75 | }, | |
| 76 | exists: function(next, data){ | |
| 77 | 0 | var name = data.name; |
| 78 | 0 | return function(elem){ |
| 79 | 0 | return hasAttrib(elem, name) && next(elem); |
| 80 | }; | |
| 81 | }, | |
| 82 | start: function(next, data){ | |
| 83 | 0 | var name = data.name, |
| 84 | value = data.value, | |
| 85 | len = value.length; | |
| 86 | ||
| 87 | 0 | if(len === 0){ |
| 88 | 0 | return falseFunc; |
| 89 | } | |
| 90 | ||
| 91 | 0 | if(data.ignoreCase){ |
| 92 | 0 | value = value.toLowerCase(); |
| 93 | ||
| 94 | 0 | return function(elem){ |
| 95 | 0 | var attr = getAttributeValue(elem, name); |
| 96 | 0 | return attr != null && attr.substr(0, len).toLowerCase() === value && next(elem); |
| 97 | }; | |
| 98 | } | |
| 99 | ||
| 100 | 0 | return function(elem){ |
| 101 | 0 | var attr = getAttributeValue(elem, name); |
| 102 | 0 | return attr != null && attr.substr(0, len) === value && next(elem); |
| 103 | }; | |
| 104 | }, | |
| 105 | end: function(next, data){ | |
| 106 | 0 | var name = data.name, |
| 107 | value = data.value, | |
| 108 | len = -value.length; | |
| 109 | ||
| 110 | 0 | if(len === 0){ |
| 111 | 0 | return falseFunc; |
| 112 | } | |
| 113 | ||
| 114 | 0 | if(data.ignoreCase){ |
| 115 | 0 | value = value.toLowerCase(); |
| 116 | ||
| 117 | 0 | return function(elem){ |
| 118 | 0 | var attr = getAttributeValue(elem, name); |
| 119 | 0 | return attr != null && attr.substr(len).toLowerCase() === value && next(elem); |
| 120 | }; | |
| 121 | } | |
| 122 | ||
| 123 | 0 | return function(elem){ |
| 124 | 0 | var attr = getAttributeValue(elem, name); |
| 125 | 0 | return attr != null && attr.substr(len) === value && next(elem); |
| 126 | }; | |
| 127 | }, | |
| 128 | any: function(next, data){ | |
| 129 | 0 | var name = data.name, |
| 130 | value = data.value; | |
| 131 | ||
| 132 | 0 | if(value === ""){ |
| 133 | 0 | return falseFunc; |
| 134 | } | |
| 135 | ||
| 136 | 0 | if(data.ignoreCase){ |
| 137 | 0 | var regex = new RegExp(value.replace(reChars, "\\$&"), "i"); |
| 138 | ||
| 139 | 0 | return function(elem){ |
| 140 | 0 | var attr = getAttributeValue(elem, name); |
| 141 | 0 | return attr != null && regex.test(attr) && next(elem); |
| 142 | }; | |
| 143 | } | |
| 144 | ||
| 145 | 0 | return function(elem){ |
| 146 | 0 | var attr = getAttributeValue(elem, name); |
| 147 | 0 | return attr != null && attr.indexOf(value) >= 0 && next(elem); |
| 148 | }; | |
| 149 | }, | |
| 150 | not: function(next, data){ | |
| 151 | 0 | var name = data.name, |
| 152 | value = data.value; | |
| 153 | ||
| 154 | 0 | if(value === ""){ |
| 155 | 0 | return function(elem){ |
| 156 | 0 | return !!getAttributeValue(elem, name) && next(elem); |
| 157 | }; | |
| 158 | 0 | } else if(data.ignoreCase){ |
| 159 | 0 | value = value.toLowerCase(); |
| 160 | ||
| 161 | 0 | return function(elem){ |
| 162 | 0 | var attr = getAttributeValue(elem, name); |
| 163 | 0 | return attr != null && attr.toLowerCase() !== value && next(elem); |
| 164 | }; | |
| 165 | } | |
| 166 | ||
| 167 | 0 | return function(elem){ |
| 168 | 0 | return getAttributeValue(elem, name) !== value && next(elem); |
| 169 | }; | |
| 170 | } | |
| 171 | }; | |
| 172 | ||
| 173 | 1 | module.exports = { |
| 174 | compile: function(next, data){ | |
| 175 | 21781 | return attributeRules[data.action](next, data); |
| 176 | }, | |
| 177 | rules: attributeRules | |
| 178 | }; | |
| 179 |
| Line | Hits | Source |
|---|---|---|
| 1 | /* | |
| 2 | compiles a selector to an executable function | |
| 3 | */ | |
| 4 | ||
| 5 | 1 | module.exports = compile; |
| 6 | ||
| 7 | 1 | var parse = require("CSSwhat"), |
| 8 | DomUtils = require("domutils"), | |
| 9 | isTag = DomUtils.isTag, | |
| 10 | Rules = require("c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/lib/./general.js"), | |
| 11 | sortRules = require("c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/lib/./sort.js"), | |
| 12 | BaseFuncs = require("c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/lib/./basefunctions.js"), | |
| 13 | trueFunc = BaseFuncs.trueFunc, | |
| 14 | falseFunc = BaseFuncs.falseFunc; | |
| 15 | ||
| 16 | 1 | function compile(selector, options){ |
| 17 | 21661 | var next = parse(selector, options) |
| 18 | .map(compileRules) | |
| 19 | .reduce(reduceRules, falseFunc); | |
| 20 | ||
| 21 | 21677 | return function(elem){ |
| 22 | 8721326 | return isTag(elem) && next(elem); |
| 23 | }; | |
| 24 | } | |
| 25 | ||
| 26 | 1 | function compileRules(arr){ |
| 27 | 21701 | if(arr.length === 0) return falseFunc; |
| 28 | 21705 | return sortRules(arr).reduce(function(func, rule){ |
| 29 | 32961 | if(func === falseFunc) return func; |
| 30 | 32967 | return Rules[rule.type](func, rule); |
| 31 | }, trueFunc); | |
| 32 | } | |
| 33 | ||
| 34 | 1 | function reduceRules(a, b){ |
| 35 | 21733 | if(b === falseFunc || a === trueFunc){ |
| 36 | 0 | return a; |
| 37 | } | |
| 38 | 21745 | if(a === falseFunc || b === trueFunc){ |
| 39 | 21749 | return b; |
| 40 | } | |
| 41 | ||
| 42 | 0 | return function combine(elem){ |
| 43 | 0 | return a(elem) || b(elem); |
| 44 | }; | |
| 45 | } | |
| 46 | ||
| 47 | //:not and :has have to compile selectors | |
| 48 | //doing this in lib/pseudos.js would lead to circular dependencies, | |
| 49 | //so we add them here | |
| 50 | ||
| 51 | 1 | var Pseudos = require("c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/lib/./pseudos.js"), |
| 52 | filters = Pseudos.filters, | |
| 53 | isParent = Pseudos.pseudos.parent, | |
| 54 | findOne = DomUtils.findOne, | |
| 55 | getChildren = DomUtils.getChildren; | |
| 56 | ||
| 57 | 1 | filters.not = function(next, select){ |
| 58 | 0 | var func = compile(select); |
| 59 | ||
| 60 | 0 | if(func === falseFunc) return next; |
| 61 | 0 | if(func === trueFunc) return falseFunc; |
| 62 | ||
| 63 | 0 | return function(elem){ |
| 64 | 0 | return !func(elem) && next(elem); |
| 65 | }; | |
| 66 | }; | |
| 67 | ||
| 68 | 1 | filters.has = function(next, selector){ |
| 69 | 0 | var func = compile(selector); |
| 70 | ||
| 71 | 0 | if(func === falseFunc) return falseFunc; |
| 72 | 0 | if(func === trueFunc) return function(elem){ |
| 73 | 0 | return isParent(elem) && next(elem); |
| 74 | }; | |
| 75 | ||
| 76 | 0 | return function has(elem){ |
| 77 | 0 | return next(elem) && findOne(func, getChildren(elem)) !== null; |
| 78 | }; | |
| 79 | }; | |
| 80 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | "use strict"; |
| 2 | ||
| 3 | 1 | module.exports = parse; |
| 4 | ||
| 5 | 1 | var re_ws = /^\s/, |
| 6 | re_name = /^(?:\\.|[\w\-\u00c0-\uFFFF])+/, | |
| 7 | re_cleanSelector = /([^\\])\s*([>~+,]|$)\s*/g, | |
| 8 | re_combinators = /^\s*[^\\]\s*[>~+,]|$\s*/g, | |
| 9 | re_escape = /\\([\da-f]{1,6}\s?|(\s)|.)/ig, | |
| 10 | re_comma = /^\s*,\s*/, | |
| 11 | //modified version of https://github.com/jquery/sizzle/blob/master/src/sizzle.js#L87 | |
| 12 | re_attr = /^\s*((?:\\.|[\w\u00c0-\uFFFF\-])+)\s*(?:(\S?)=\s*(?:(['"])(.*?)\3|(#?(?:\\.|[\w\u00c0-\uFFFF\-])*)|)|)\s*(i)?\]/; | |
| 13 | ||
| 14 | 1 | var actionTypes = { |
| 15 | __proto__: null, | |
| 16 | "undefined": "exists", | |
| 17 | "": "equals", | |
| 18 | "~": "element", | |
| 19 | "^": "start", | |
| 20 | "$": "end", | |
| 21 | "*": "any", | |
| 22 | "!": "not", | |
| 23 | "|": "hyphen" | |
| 24 | }; | |
| 25 | ||
| 26 | 1 | var simpleSelectors = { |
| 27 | __proto__: null, | |
| 28 | ">": "child", | |
| 29 | "<": "parent", | |
| 30 | "~": "sibling", | |
| 31 | "+": "adjacent", | |
| 32 | "*": "universal" | |
| 33 | }; | |
| 34 | ||
| 35 | 1 | var attribSelectors = { |
| 36 | __proto__: null, | |
| 37 | "#": ["id", "equals"], | |
| 38 | ".": ["class", "element"] | |
| 39 | }; | |
| 40 | ||
| 41 | //unescape function taken from https://github.com/jquery/sizzle/blob/master/src/sizzle.js#L139 | |
| 42 | 1 | function funescape( _, escaped, escapedWhitespace ) { |
| 43 | 0 | var high = "0x" + escaped - 0x10000; |
| 44 | // NaN means non-codepoint | |
| 45 | // Support: Firefox | |
| 46 | // Workaround erroneous numeric interpretation of +"0x" | |
| 47 | 0 | return high !== high || escapedWhitespace ? |
| 48 | escaped : | |
| 49 | // BMP codepoint | |
| 50 | high < 0 ? | |
| 51 | String.fromCharCode( high + 0x10000 ) : | |
| 52 | // Supplemental Plane codepoint (surrogate pair) | |
| 53 | String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); | |
| 54 | } | |
| 55 | ||
| 56 | 1 | function unescapeCSS(str){ |
| 57 | 27963 | return str.replace(re_escape, funescape); |
| 58 | } | |
| 59 | ||
| 60 | 1 | function getClosingPos(selector){ |
| 61 | 0 | var pos = 1, counter = 1, len = selector.length; |
| 62 | ||
| 63 | 0 | for(; counter > 0 && pos < len; pos++){ |
| 64 | 0 | if(selector.charAt(pos) === "(") counter++; |
| 65 | 0 | else if(selector.charAt(pos) === ")") counter--; |
| 66 | } | |
| 67 | ||
| 68 | 0 | return pos; |
| 69 | } | |
| 70 | ||
| 71 | 1 | function parse(selector, options){ |
| 72 | 22213 | selector = (selector + "").trimLeft().replace(re_cleanSelector, "$1$2"); |
| 73 | ||
| 74 | 22221 | var subselects = [], |
| 75 | tokens = [], | |
| 76 | data, firstChar, name; | |
| 77 | ||
| 78 | 22237 | function getName(){ |
| 79 | 28073 | var sub = selector.match(re_name)[0]; |
| 80 | 28078 | selector = selector.substr(sub.length); |
| 81 | 28083 | return unescapeCSS(sub); |
| 82 | } | |
| 83 | ||
| 84 | 22261 | function getLCName(){ |
| 85 | 5612 | var name = getName(); |
| 86 | ||
| 87 | 5614 | if(!options || !options.xmlMode){ |
| 88 | 5615 | name = name.toLowerCase(); |
| 89 | } | |
| 90 | ||
| 91 | 5618 | return name; |
| 92 | } | |
| 93 | ||
| 94 | 22301 | while(selector !== ""){ |
| 95 | 33864 | if(re_name.test(selector)){ |
| 96 | 5623 | tokens.push({type: "tag", name: getLCName()}); |
| 97 | 28252 | } else if(re_ws.test(selector)){ |
| 98 | 5714 | tokens.push({type: "descendant"}); |
| 99 | 5715 | selector = selector.trimLeft(); |
| 100 | } else { | |
| 101 | 22555 | firstChar = selector.charAt(0); |
| 102 | 22559 | selector = selector.substr(1); |
| 103 | ||
| 104 | 22567 | if(firstChar in simpleSelectors){ |
| 105 | 0 | tokens.push({type: simpleSelectors[firstChar]}); |
| 106 | 22575 | } else if(firstChar in attribSelectors){ |
| 107 | 22579 | tokens.push({ |
| 108 | type: "attribute", | |
| 109 | name: attribSelectors[firstChar][0], | |
| 110 | action: attribSelectors[firstChar][1], | |
| 111 | value: getName(), | |
| 112 | ignoreCase: false | |
| 113 | }); | |
| 114 | 0 | } else if(firstChar === "["){ |
| 115 | 0 | data = selector.match(re_attr); |
| 116 | 0 | if(!data){ |
| 117 | 0 | throw new SyntaxError("Malformed attribute selector: " + selector); |
| 118 | } | |
| 119 | 0 | selector = selector.substr(data[0].length); |
| 120 | 0 | name = unescapeCSS(data[1]); |
| 121 | ||
| 122 | 0 | if(!options || !options.xmlMode){ |
| 123 | 0 | name = name.toLowerCase(); |
| 124 | } | |
| 125 | ||
| 126 | 0 | tokens.push({ |
| 127 | type: "attribute", | |
| 128 | name: name, | |
| 129 | action: actionTypes[data[2]], | |
| 130 | value: unescapeCSS(data[4] || data[5] || ""), | |
| 131 | ignoreCase: !!data[6] | |
| 132 | }); | |
| 133 | ||
| 134 | 0 | } else if(firstChar === ":"){ |
| 135 | //if(selector.charAt(0) === ":"){} //TODO pseudo-element | |
| 136 | 0 | name = getLCName(); |
| 137 | 0 | data = null; |
| 138 | ||
| 139 | 0 | if(selector.charAt(0) === "("){ |
| 140 | 0 | var pos = getClosingPos(selector); |
| 141 | 0 | data = selector.substr(1, pos - 2); |
| 142 | 0 | selector = selector.substr(pos); |
| 143 | } | |
| 144 | ||
| 145 | 0 | tokens.push({type: "pseudo", name: name, data: data}); |
| 146 | 0 | } else if(firstChar === ","){ |
| 147 | 0 | if(tokens.length === 0){ |
| 148 | 0 | throw new SyntaxError("empty sub-selector"); |
| 149 | } | |
| 150 | 0 | subselects.push(tokens); |
| 151 | 0 | tokens = []; |
| 152 | } else { | |
| 153 | //otherwise, the parser needs to throw or it would enter an infinite loop | |
| 154 | 0 | throw new SyntaxError("Unmatched selector: " + firstChar + selector); |
| 155 | } | |
| 156 | } | |
| 157 | } | |
| 158 | ||
| 159 | 22561 | if(subselects.length > 0 && tokens.length === 0){ |
| 160 | 0 | throw new SyntaxError("empty sub-selector"); |
| 161 | } | |
| 162 | 22573 | subselects.push(tokens); |
| 163 | 22577 | return subselects; |
| 164 | } |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | var DomUtils = require("domutils"), |
| 2 | isTag = DomUtils.isTag, | |
| 3 | getParent = DomUtils.getParent, | |
| 4 | getChildren = DomUtils.getChildren, | |
| 5 | getSiblings = DomUtils.getSiblings, | |
| 6 | getName = DomUtils.getName; | |
| 7 | ||
| 8 | /* | |
| 9 | all available rules | |
| 10 | */ | |
| 11 | 1 | module.exports = { |
| 12 | __proto__: null, | |
| 13 | ||
| 14 | attribute: require("c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/lib/./attributes.js").compile, | |
| 15 | pseudo: require("c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/lib/./pseudos.js").compile, | |
| 16 | ||
| 17 | //tags | |
| 18 | tag: function(next, data){ | |
| 19 | 5714 | var name = data.name; |
| 20 | 5715 | return function tag(elem){ |
| 21 | 3557627 | return getName(elem) === name && next(elem); |
| 22 | }; | |
| 23 | }, | |
| 24 | ||
| 25 | //traversal | |
| 26 | descendant: function(next){ | |
| 27 | 5813 | return function descendant(elem){ |
| 28 | 11370 | var found = false; |
| 29 | ||
| 30 | 11372 | while(!found && (elem = getParent(elem))){ |
| 31 | 33597 | found = next(elem); |
| 32 | } | |
| 33 | ||
| 34 | 11376 | return found; |
| 35 | }; | |
| 36 | }, | |
| 37 | parent: function(next){ | |
| 38 | 0 | return function parent(elem){ |
| 39 | 0 | return getChildren(elem).some(next); |
| 40 | }; | |
| 41 | }, | |
| 42 | child: function(next){ | |
| 43 | 0 | return function child(elem){ |
| 44 | 0 | var parent = getParent(elem); |
| 45 | 0 | return !!parent && next(parent); |
| 46 | }; | |
| 47 | }, | |
| 48 | sibling: function(next){ | |
| 49 | 0 | return function sibling(elem){ |
| 50 | 0 | var siblings = getSiblings(elem); |
| 51 | ||
| 52 | 0 | for(var i = 0; i < siblings.length; i++){ |
| 53 | 0 | if(isTag(siblings[i])){ |
| 54 | 0 | if(siblings[i] === elem) break; |
| 55 | 0 | if(next(siblings[i])) return true; |
| 56 | } | |
| 57 | } | |
| 58 | ||
| 59 | 0 | return false; |
| 60 | }; | |
| 61 | }, | |
| 62 | adjacent: function(next){ | |
| 63 | 0 | return function adjacent(elem){ |
| 64 | 0 | var siblings = getSiblings(elem), |
| 65 | lastElement; | |
| 66 | ||
| 67 | 0 | for(var i = 0; i < siblings.length; i++){ |
| 68 | 0 | if(isTag(siblings[i])){ |
| 69 | 0 | if(siblings[i] === elem) break; |
| 70 | 0 | lastElement = siblings[i]; |
| 71 | } | |
| 72 | } | |
| 73 | ||
| 74 | 0 | return !!lastElement && next(lastElement); |
| 75 | }; | |
| 76 | }, | |
| 77 | universal: function(next){ | |
| 78 | 0 | return next; |
| 79 | } | |
| 80 | }; |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | module.exports = sortByProcedure; |
| 2 | ||
| 3 | /* | |
| 4 | sort the parts of the passed selector, | |
| 5 | as there is potential for optimization | |
| 6 | (some types of selectors are faster than others) | |
| 7 | */ | |
| 8 | ||
| 9 | 1 | var procedure = { |
| 10 | __proto__: null, | |
| 11 | universal: 5, //should be last so that it can be ignored | |
| 12 | tag: 3, //very quick test | |
| 13 | attribute: 1, //can be faster than class | |
| 14 | pseudo: 0, //can be pretty expensive (especially :has) | |
| 15 | ||
| 16 | //everything else shouldn't be moved | |
| 17 | descendant: -1, | |
| 18 | child: -1, | |
| 19 | sibling: -1, | |
| 20 | adjacent: -1 | |
| 21 | }; | |
| 22 | ||
| 23 | 1 | function sortByProcedure(arr){ |
| 24 | //TODO sort individual attribute selectors | |
| 25 | 23025 | for(var i = 1; i < arr.length; i++){ |
| 26 | 11939 | var procNew = procedure[arr[i].type]; |
| 27 | ||
| 28 | 11943 | if(procNew !== -1){ |
| 29 | 6044 | for(var j = i - 1; j >= 0 && procNew < procedure[arr[j].type]; j--){ |
| 30 | 95 | var tmp = arr[j + 1]; |
| 31 | 95 | arr[j + 1] = arr[j]; |
| 32 | 95 | arr[j] = tmp; |
| 33 | } | |
| 34 | } | |
| 35 | } | |
| 36 | 23069 | return arr; |
| 37 | } |
| Line | Hits | Source |
|---|---|---|
| 1 | /* | |
| 2 | Module Dependencies | |
| 3 | */ | |
| 4 | 1 | var htmlparser = require('htmlparser2'), |
| 5 | _ = require('underscore'), | |
| 6 | isTag = require('./utils').isTag, | |
| 7 | camelCase = require('./utils').camelCase; | |
| 8 | ||
| 9 | /* | |
| 10 | Parser | |
| 11 | */ | |
| 12 | 1 | exports = module.exports = function(content, options) { |
| 13 | 5738 | var dom = evaluate(content, options); |
| 14 | ||
| 15 | // Generic root element | |
| 16 | 5741 | var root = { |
| 17 | type: 'root', | |
| 18 | name: 'root', | |
| 19 | parent: null, | |
| 20 | prev: null, | |
| 21 | next: null, | |
| 22 | children: [] | |
| 23 | }; | |
| 24 | ||
| 25 | // Update the dom using the root | |
| 26 | 5751 | update(dom, root); |
| 27 | ||
| 28 | 5753 | return root; |
| 29 | }; | |
| 30 | ||
| 31 | 1 | var evaluate = exports.evaluate = function(content, options) { |
| 32 | // options = options || $.fn.options; | |
| 33 | ||
| 34 | 5759 | var handler = new htmlparser.DomHandler(options), |
| 35 | parser = new htmlparser.Parser(handler, options); | |
| 36 | ||
| 37 | 5762 | parser.write(content); |
| 38 | 5763 | parser.done(); |
| 39 | ||
| 40 | 5765 | return connect(handler.dom); |
| 41 | }; | |
| 42 | ||
| 43 | 1 | var connect = exports.connect = function(dom, parent) { |
| 44 | 29615 | parent = parent || null; |
| 45 | ||
| 46 | 29625 | var prevElem = null; |
| 47 | ||
| 48 | 29635 | _.each(dom, function(elem) { |
| 49 | ||
| 50 | 25001 | if (isTag(elem.type)) { |
| 51 | // If tag and no attributes, add empty object | |
| 52 | 23878 | if (elem.attribs === undefined) { |
| 53 | 0 | elem.attribs = {}; |
| 54 | } else { | |
| 55 | // If there are already attributes, add them to the data list. | |
| 56 | 23894 | elem.data = parseData(elem); |
| 57 | } | |
| 58 | } | |
| 59 | ||
| 60 | // Set parent | |
| 61 | 25045 | elem.parent = parent; |
| 62 | ||
| 63 | // Previous Sibling | |
| 64 | 25057 | elem.prev = prevElem; |
| 65 | ||
| 66 | // Next sibling | |
| 67 | 25069 | elem.next = null; |
| 68 | 38047 | if (prevElem) prevElem.next = elem; |
| 69 | ||
| 70 | // Run through the children | |
| 71 | 25085 | if (elem.children) |
| 72 | 23958 | connect(elem.children, elem); |
| 73 | 1131 | else if (isTag(elem.type)) |
| 74 | 0 | elem.children = []; |
| 75 | ||
| 76 | // Get ready for next element | |
| 77 | 25109 | prevElem = elem; |
| 78 | }); | |
| 79 | ||
| 80 | 29795 | return dom; |
| 81 | }; | |
| 82 | ||
| 83 | /* | |
| 84 | Update the dom structure, for one changed layer | |
| 85 | ||
| 86 | * Much faster than reconnecting | |
| 87 | */ | |
| 88 | 1 | var update = exports.update = function(arr, parent) { |
| 89 | // normalize | |
| 90 | 40585 | if (!Array.isArray(arr)) arr = [arr]; |
| 91 | ||
| 92 | // Update neighbors | |
| 93 | 26119 | for (var i = 0; i < arr.length; i++) { |
| 94 | 760689 | arr[i].prev = arr[i - 1] || null; |
| 95 | 760790 | arr[i].next = arr[i + 1] || null; |
| 96 | 760892 | arr[i].parent = parent || null; |
| 97 | } | |
| 98 | ||
| 99 | // Update parent | |
| 100 | 26151 | parent.children = arr; |
| 101 | ||
| 102 | 26160 | return parent; |
| 103 | }; | |
| 104 | ||
| 105 | /** | |
| 106 | * Extract data by using element attributes. | |
| 107 | * @param {Object} elem Element | |
| 108 | * @return {Object} `element.data` object | |
| 109 | */ | |
| 110 | 1 | var parseData = exports.parseData = function(elem) { |
| 111 | 48228 | if (elem.data === undefined) elem.data = {}; |
| 112 | 24118 | var value; |
| 113 | 24122 | for (var key in elem.attribs) { |
| 114 | 23770 | if (key.substr(0, 5) === 'data-') { |
| 115 | 0 | value = elem.attribs[key]; |
| 116 | 0 | key = key.slice(5); |
| 117 | 0 | key = camelCase(key); |
| 118 | 0 | elem.data[key] = value; |
| 119 | } | |
| 120 | } | |
| 121 | 24154 | return elem.data; |
| 122 | }; | |
| 123 | ||
| 124 | // module.exports = $.extend(exports); | |
| 125 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | function defineProp(name, value){ |
| 2 | 2 | delete module.exports[name]; |
| 3 | 2 | module.exports[name] = value; |
| 4 | 2 | return value; |
| 5 | } | |
| 6 | ||
| 7 | 1 | module.exports = { |
| 8 | parseDOM: function (html) { | |
| 9 | 0 | var handler = new module.exports.DomHandler(); |
| 10 | 0 | var parser = new module.exports.Parser(handler); |
| 11 | 0 | parser.parseComplete(html); |
| 12 | 0 | return handler.dom; |
| 13 | }, | |
| 14 | parseFeed: function (feed) { | |
| 15 | 0 | var handler = new module.exports.FeedHandler(); |
| 16 | 0 | var parser = new module.exports.Parser(handler); |
| 17 | 0 | parser.parseComplete(feed); |
| 18 | 0 | return handler.dom; |
| 19 | }, | |
| 20 | get Parser(){ | |
| 21 | 1 | return defineProp("Parser", require("c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/htmlparser2/lib/./Parser.js")); |
| 22 | }, | |
| 23 | get DomHandler(){ | |
| 24 | 1 | return defineProp("DomHandler", require("domhandler")); |
| 25 | }, | |
| 26 | get FeedHandler(){ | |
| 27 | 0 | return defineProp("FeedHandler", require("c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/htmlparser2/lib/./FeedHandler.js")); |
| 28 | }, | |
| 29 | get Tokenizer(){ | |
| 30 | 0 | return defineProp("Tokenizer", require("c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/htmlparser2/lib/./Tokenizer.js")); |
| 31 | }, | |
| 32 | get ElementType(){ | |
| 33 | 0 | return defineProp("ElementType", require("domelementtype")); |
| 34 | }, | |
| 35 | get Stream(){ | |
| 36 | 0 | return defineProp("Stream", require("c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/htmlparser2/lib/./Stream.js")); |
| 37 | }, | |
| 38 | get WritableStream(){ | |
| 39 | 0 | return defineProp("WritableStream", require("c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/htmlparser2/lib/./WritableStream.js")); |
| 40 | }, | |
| 41 | get ProxyHandler(){ | |
| 42 | 0 | return defineProp("ProxyHandler", require("c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/htmlparser2/lib/./ProxyHandler.js")); |
| 43 | }, | |
| 44 | get DomUtils(){ | |
| 45 | 0 | return defineProp("DomUtils", require("domutils")); |
| 46 | }, | |
| 47 | get CollectingHandler(){ | |
| 48 | 0 | return defineProp("CollectingHandler", require("c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/htmlparser2/lib/./CollectingHandler.js")); |
| 49 | }, | |
| 50 | // For legacy support | |
| 51 | get DefaultHandler(){ | |
| 52 | 0 | return defineProp("DefaultHandler", this.DomHandler); |
| 53 | }, | |
| 54 | get RssHandler(){ | |
| 55 | 0 | return defineProp("RssHandler", this.FeedHandler); |
| 56 | }, | |
| 57 | createDomStream: function(cb, options, elementCb){ | |
| 58 | 0 | var handler = new module.exports.DomHandler(cb, options, elementCb); |
| 59 | 0 | return new module.exports.Parser(handler, options); |
| 60 | }, | |
| 61 | // List of all events that the parser emits | |
| 62 | EVENTS: { /* Format: eventname: number of arguments */ | |
| 63 | attribute: 2, | |
| 64 | cdatastart: 0, | |
| 65 | cdataend: 0, | |
| 66 | text: 1, | |
| 67 | processinginstruction: 2, | |
| 68 | comment: 1, | |
| 69 | commentend: 0, | |
| 70 | closetag: 1, | |
| 71 | opentag: 2, | |
| 72 | opentagname: 1, | |
| 73 | error: 1, | |
| 74 | end: 0 | |
| 75 | } | |
| 76 | }; | |
| 77 |
| Line | Hits | Source |
|---|---|---|
| 1 | // Underscore.js 1.4.4 | |
| 2 | // http://underscorejs.org | |
| 3 | // (c) 2009-2013 Jeremy Ashkenas, DocumentCloud Inc. | |
| 4 | // Underscore may be freely distributed under the MIT license. | |
| 5 | ||
| 6 | 1 | (function() { |
| 7 | ||
| 8 | // Baseline setup | |
| 9 | // -------------- | |
| 10 | ||
| 11 | // Establish the root object, `window` in the browser, or `global` on the server. | |
| 12 | 1 | var root = this; |
| 13 | ||
| 14 | // Save the previous value of the `_` variable. | |
| 15 | 1 | var previousUnderscore = root._; |
| 16 | ||
| 17 | // Establish the object that gets returned to break out of a loop iteration. | |
| 18 | 1 | var breaker = {}; |
| 19 | ||
| 20 | // Save bytes in the minified (but not gzipped) version: | |
| 21 | 1 | var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; |
| 22 | ||
| 23 | // Create quick reference variables for speed access to core prototypes. | |
| 24 | 1 | var push = ArrayProto.push, |
| 25 | slice = ArrayProto.slice, | |
| 26 | concat = ArrayProto.concat, | |
| 27 | toString = ObjProto.toString, | |
| 28 | hasOwnProperty = ObjProto.hasOwnProperty; | |
| 29 | ||
| 30 | // All **ECMAScript 5** native function implementations that we hope to use | |
| 31 | // are declared here. | |
| 32 | 1 | var |
| 33 | nativeForEach = ArrayProto.forEach, | |
| 34 | nativeMap = ArrayProto.map, | |
| 35 | nativeReduce = ArrayProto.reduce, | |
| 36 | nativeReduceRight = ArrayProto.reduceRight, | |
| 37 | nativeFilter = ArrayProto.filter, | |
| 38 | nativeEvery = ArrayProto.every, | |
| 39 | nativeSome = ArrayProto.some, | |
| 40 | nativeIndexOf = ArrayProto.indexOf, | |
| 41 | nativeLastIndexOf = ArrayProto.lastIndexOf, | |
| 42 | nativeIsArray = Array.isArray, | |
| 43 | nativeKeys = Object.keys, | |
| 44 | nativeBind = FuncProto.bind; | |
| 45 | ||
| 46 | // Create a safe reference to the Underscore object for use below. | |
| 47 | 1 | var _ = function(obj) { |
| 48 | 0 | if (obj instanceof _) return obj; |
| 49 | 0 | if (!(this instanceof _)) return new _(obj); |
| 50 | 0 | this._wrapped = obj; |
| 51 | }; | |
| 52 | ||
| 53 | // Export the Underscore object for **Node.js**, with | |
| 54 | // backwards-compatibility for the old `require()` API. If we're in | |
| 55 | // the browser, add `_` as a global object via a string identifier, | |
| 56 | // for Closure Compiler "advanced" mode. | |
| 57 | 1 | if (typeof exports !== 'undefined') { |
| 58 | 1 | if (typeof module !== 'undefined' && module.exports) { |
| 59 | 1 | exports = module.exports = _; |
| 60 | } | |
| 61 | 1 | exports._ = _; |
| 62 | } else { | |
| 63 | 0 | root._ = _; |
| 64 | } | |
| 65 | ||
| 66 | // Current version. | |
| 67 | 1 | _.VERSION = '1.4.4'; |
| 68 | ||
| 69 | // Collection Functions | |
| 70 | // -------------------- | |
| 71 | ||
| 72 | // The cornerstone, an `each` implementation, aka `forEach`. | |
| 73 | // Handles objects with the built-in `forEach`, arrays, and raw objects. | |
| 74 | // Delegates to **ECMAScript 5**'s native `forEach` if available. | |
| 75 | 1 | var each = _.each = _.forEach = function(obj, iterator, context) { |
| 76 | 209322 | if (obj == null) return; |
| 77 | 209358 | if (nativeForEach && obj.forEach === nativeForEach) { |
| 78 | 179157 | obj.forEach(iterator, context); |
| 79 | 30242 | } else if (obj.length === +obj.length) { |
| 80 | 30247 | for (var i = 0, l = obj.length; i < l; i++) { |
| 81 | 30252 | if (iterator.call(context, obj[i], i, obj) === breaker) return; |
| 82 | } | |
| 83 | } else { | |
| 84 | 0 | for (var key in obj) { |
| 85 | 0 | if (_.has(obj, key)) { |
| 86 | 0 | if (iterator.call(context, obj[key], key, obj) === breaker) return; |
| 87 | } | |
| 88 | } | |
| 89 | } | |
| 90 | }; | |
| 91 | ||
| 92 | // Return the results of applying the iterator to each element. | |
| 93 | // Delegates to **ECMAScript 5**'s native `map` if available. | |
| 94 | 1 | _.map = _.collect = function(obj, iterator, context) { |
| 95 | 0 | var results = []; |
| 96 | 0 | if (obj == null) return results; |
| 97 | 0 | if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context); |
| 98 | 0 | each(obj, function(value, index, list) { |
| 99 | 0 | results[results.length] = iterator.call(context, value, index, list); |
| 100 | }); | |
| 101 | 0 | return results; |
| 102 | }; | |
| 103 | ||
| 104 | 1 | var reduceError = 'Reduce of empty array with no initial value'; |
| 105 | ||
| 106 | // **Reduce** builds up a single result from a list of values, aka `inject`, | |
| 107 | // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available. | |
| 108 | 1 | _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) { |
| 109 | 24353 | var initial = arguments.length > 2; |
| 110 | 24357 | if (obj == null) obj = []; |
| 111 | 24361 | if (nativeReduce && obj.reduce === nativeReduce) { |
| 112 | 0 | if (context) iterator = _.bind(iterator, context); |
| 113 | 0 | return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator); |
| 114 | } | |
| 115 | 24377 | each(obj, function(value, index, list) { |
| 116 | 24381 | if (!initial) { |
| 117 | 0 | memo = value; |
| 118 | 0 | initial = true; |
| 119 | } else { | |
| 120 | 24397 | memo = iterator.call(context, memo, value, index, list); |
| 121 | } | |
| 122 | }); | |
| 123 | 24409 | if (!initial) throw new TypeError(reduceError); |
| 124 | 24413 | return memo; |
| 125 | }; | |
| 126 | ||
| 127 | // The right-associative version of reduce, also known as `foldr`. | |
| 128 | // Delegates to **ECMAScript 5**'s native `reduceRight` if available. | |
| 129 | 1 | _.reduceRight = _.foldr = function(obj, iterator, memo, context) { |
| 130 | 0 | var initial = arguments.length > 2; |
| 131 | 0 | if (obj == null) obj = []; |
| 132 | 0 | if (nativeReduceRight && obj.reduceRight === nativeReduceRight) { |
| 133 | 0 | if (context) iterator = _.bind(iterator, context); |
| 134 | 0 | return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator); |
| 135 | } | |
| 136 | 0 | var length = obj.length; |
| 137 | 0 | if (length !== +length) { |
| 138 | 0 | var keys = _.keys(obj); |
| 139 | 0 | length = keys.length; |
| 140 | } | |
| 141 | 0 | each(obj, function(value, index, list) { |
| 142 | 0 | index = keys ? keys[--length] : --length; |
| 143 | 0 | if (!initial) { |
| 144 | 0 | memo = obj[index]; |
| 145 | 0 | initial = true; |
| 146 | } else { | |
| 147 | 0 | memo = iterator.call(context, memo, obj[index], index, list); |
| 148 | } | |
| 149 | }); | |
| 150 | 0 | if (!initial) throw new TypeError(reduceError); |
| 151 | 0 | return memo; |
| 152 | }; | |
| 153 | ||
| 154 | // Return the first value which passes a truth test. Aliased as `detect`. | |
| 155 | 1 | _.find = _.detect = function(obj, iterator, context) { |
| 156 | 0 | var result; |
| 157 | 0 | any(obj, function(value, index, list) { |
| 158 | 0 | if (iterator.call(context, value, index, list)) { |
| 159 | 0 | result = value; |
| 160 | 0 | return true; |
| 161 | } | |
| 162 | }); | |
| 163 | 0 | return result; |
| 164 | }; | |
| 165 | ||
| 166 | // Return all the elements that pass a truth test. | |
| 167 | // Delegates to **ECMAScript 5**'s native `filter` if available. | |
| 168 | // Aliased as `select`. | |
| 169 | 1 | _.filter = _.select = function(obj, iterator, context) { |
| 170 | 30697 | var results = []; |
| 171 | 30702 | if (obj == null) return results; |
| 172 | 61414 | if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context); |
| 173 | 0 | each(obj, function(value, index, list) { |
| 174 | 0 | if (iterator.call(context, value, index, list)) results[results.length] = value; |
| 175 | }); | |
| 176 | 0 | return results; |
| 177 | }; | |
| 178 | ||
| 179 | // Return all the elements for which a truth test fails. | |
| 180 | 1 | _.reject = function(obj, iterator, context) { |
| 181 | 0 | return _.filter(obj, function(value, index, list) { |
| 182 | 0 | return !iterator.call(context, value, index, list); |
| 183 | }, context); | |
| 184 | }; | |
| 185 | ||
| 186 | // Determine whether all of the elements match a truth test. | |
| 187 | // Delegates to **ECMAScript 5**'s native `every` if available. | |
| 188 | // Aliased as `all`. | |
| 189 | 1 | _.every = _.all = function(obj, iterator, context) { |
| 190 | 0 | iterator || (iterator = _.identity); |
| 191 | 0 | var result = true; |
| 192 | 0 | if (obj == null) return result; |
| 193 | 0 | if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context); |
| 194 | 0 | each(obj, function(value, index, list) { |
| 195 | 0 | if (!(result = result && iterator.call(context, value, index, list))) return breaker; |
| 196 | }); | |
| 197 | 0 | return !!result; |
| 198 | }; | |
| 199 | ||
| 200 | // Determine if at least one element in the object matches a truth test. | |
| 201 | // Delegates to **ECMAScript 5**'s native `some` if available. | |
| 202 | // Aliased as `any`. | |
| 203 | 1 | var any = _.some = _.any = function(obj, iterator, context) { |
| 204 | 0 | iterator || (iterator = _.identity); |
| 205 | 0 | var result = false; |
| 206 | 0 | if (obj == null) return result; |
| 207 | 0 | if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context); |
| 208 | 0 | each(obj, function(value, index, list) { |
| 209 | 0 | if (result || (result = iterator.call(context, value, index, list))) return breaker; |
| 210 | }); | |
| 211 | 0 | return !!result; |
| 212 | }; | |
| 213 | ||
| 214 | // Determine if the array or object contains a given value (using `===`). | |
| 215 | // Aliased as `include`. | |
| 216 | 1 | _.contains = _.include = function(obj, target) { |
| 217 | 30983 | if (obj == null) return false; |
| 218 | 61976 | if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; |
| 219 | 0 | return any(obj, function(value) { |
| 220 | 0 | return value === target; |
| 221 | }); | |
| 222 | }; | |
| 223 | ||
| 224 | // Invoke a method (with arguments) on every item in a collection. | |
| 225 | 1 | _.invoke = function(obj, method) { |
| 226 | 0 | var args = slice.call(arguments, 2); |
| 227 | 0 | var isFunc = _.isFunction(method); |
| 228 | 0 | return _.map(obj, function(value) { |
| 229 | 0 | return (isFunc ? method : value[method]).apply(value, args); |
| 230 | }); | |
| 231 | }; | |
| 232 | ||
| 233 | // Convenience version of a common use case of `map`: fetching a property. | |
| 234 | 1 | _.pluck = function(obj, key) { |
| 235 | 0 | return _.map(obj, function(value){ return value[key]; }); |
| 236 | }; | |
| 237 | ||
| 238 | // Convenience version of a common use case of `filter`: selecting only objects | |
| 239 | // containing specific `key:value` pairs. | |
| 240 | 1 | _.where = function(obj, attrs, first) { |
| 241 | 0 | if (_.isEmpty(attrs)) return first ? null : []; |
| 242 | 0 | return _[first ? 'find' : 'filter'](obj, function(value) { |
| 243 | 0 | for (var key in attrs) { |
| 244 | 0 | if (attrs[key] !== value[key]) return false; |
| 245 | } | |
| 246 | 0 | return true; |
| 247 | }); | |
| 248 | }; | |
| 249 | ||
| 250 | // Convenience version of a common use case of `find`: getting the first object | |
| 251 | // containing specific `key:value` pairs. | |
| 252 | 1 | _.findWhere = function(obj, attrs) { |
| 253 | 0 | return _.where(obj, attrs, true); |
| 254 | }; | |
| 255 | ||
| 256 | // Return the maximum element or (element-based computation). | |
| 257 | // Can't optimize arrays of integers longer than 65,535 elements. | |
| 258 | // See: https://bugs.webkit.org/show_bug.cgi?id=80797 | |
| 259 | 1 | _.max = function(obj, iterator, context) { |
| 260 | 0 | if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { |
| 261 | 0 | return Math.max.apply(Math, obj); |
| 262 | } | |
| 263 | 0 | if (!iterator && _.isEmpty(obj)) return -Infinity; |
| 264 | 0 | var result = {computed : -Infinity, value: -Infinity}; |
| 265 | 0 | each(obj, function(value, index, list) { |
| 266 | 0 | var computed = iterator ? iterator.call(context, value, index, list) : value; |
| 267 | 0 | computed >= result.computed && (result = {value : value, computed : computed}); |
| 268 | }); | |
| 269 | 0 | return result.value; |
| 270 | }; | |
| 271 | ||
| 272 | // Return the minimum element (or element-based computation). | |
| 273 | 1 | _.min = function(obj, iterator, context) { |
| 274 | 0 | if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { |
| 275 | 0 | return Math.min.apply(Math, obj); |
| 276 | } | |
| 277 | 0 | if (!iterator && _.isEmpty(obj)) return Infinity; |
| 278 | 0 | var result = {computed : Infinity, value: Infinity}; |
| 279 | 0 | each(obj, function(value, index, list) { |
| 280 | 0 | var computed = iterator ? iterator.call(context, value, index, list) : value; |
| 281 | 0 | computed < result.computed && (result = {value : value, computed : computed}); |
| 282 | }); | |
| 283 | 0 | return result.value; |
| 284 | }; | |
| 285 | ||
| 286 | // Shuffle an array. | |
| 287 | 1 | _.shuffle = function(obj) { |
| 288 | 0 | var rand; |
| 289 | 0 | var index = 0; |
| 290 | 0 | var shuffled = []; |
| 291 | 0 | each(obj, function(value) { |
| 292 | 0 | rand = _.random(index++); |
| 293 | 0 | shuffled[index - 1] = shuffled[rand]; |
| 294 | 0 | shuffled[rand] = value; |
| 295 | }); | |
| 296 | 0 | return shuffled; |
| 297 | }; | |
| 298 | ||
| 299 | // An internal function to generate lookup iterators. | |
| 300 | 1 | var lookupIterator = function(value) { |
| 301 | 0 | return _.isFunction(value) ? value : function(obj){ return obj[value]; }; |
| 302 | }; | |
| 303 | ||
| 304 | // Sort the object's values by a criterion produced by an iterator. | |
| 305 | 1 | _.sortBy = function(obj, value, context) { |
| 306 | 0 | var iterator = lookupIterator(value); |
| 307 | 0 | return _.pluck(_.map(obj, function(value, index, list) { |
| 308 | 0 | return { |
| 309 | value : value, | |
| 310 | index : index, | |
| 311 | criteria : iterator.call(context, value, index, list) | |
| 312 | }; | |
| 313 | }).sort(function(left, right) { | |
| 314 | 0 | var a = left.criteria; |
| 315 | 0 | var b = right.criteria; |
| 316 | 0 | if (a !== b) { |
| 317 | 0 | if (a > b || a === void 0) return 1; |
| 318 | 0 | if (a < b || b === void 0) return -1; |
| 319 | } | |
| 320 | 0 | return left.index < right.index ? -1 : 1; |
| 321 | }), 'value'); | |
| 322 | }; | |
| 323 | ||
| 324 | // An internal function used for aggregate "group by" operations. | |
| 325 | 1 | var group = function(obj, value, context, behavior) { |
| 326 | 0 | var result = {}; |
| 327 | 0 | var iterator = lookupIterator(value || _.identity); |
| 328 | 0 | each(obj, function(value, index) { |
| 329 | 0 | var key = iterator.call(context, value, index, obj); |
| 330 | 0 | behavior(result, key, value); |
| 331 | }); | |
| 332 | 0 | return result; |
| 333 | }; | |
| 334 | ||
| 335 | // Groups the object's values by a criterion. Pass either a string attribute | |
| 336 | // to group by, or a function that returns the criterion. | |
| 337 | 1 | _.groupBy = function(obj, value, context) { |
| 338 | 0 | return group(obj, value, context, function(result, key, value) { |
| 339 | 0 | (_.has(result, key) ? result[key] : (result[key] = [])).push(value); |
| 340 | }); | |
| 341 | }; | |
| 342 | ||
| 343 | // Counts instances of an object that group by a certain criterion. Pass | |
| 344 | // either a string attribute to count by, or a function that returns the | |
| 345 | // criterion. | |
| 346 | 1 | _.countBy = function(obj, value, context) { |
| 347 | 0 | return group(obj, value, context, function(result, key) { |
| 348 | 0 | if (!_.has(result, key)) result[key] = 0; |
| 349 | 0 | result[key]++; |
| 350 | }); | |
| 351 | }; | |
| 352 | ||
| 353 | // Use a comparator function to figure out the smallest index at which | |
| 354 | // an object should be inserted so as to maintain order. Uses binary search. | |
| 355 | 1 | _.sortedIndex = function(array, obj, iterator, context) { |
| 356 | 0 | iterator = iterator == null ? _.identity : lookupIterator(iterator); |
| 357 | 0 | var value = iterator.call(context, obj); |
| 358 | 0 | var low = 0, high = array.length; |
| 359 | 0 | while (low < high) { |
| 360 | 0 | var mid = (low + high) >>> 1; |
| 361 | 0 | iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid; |
| 362 | } | |
| 363 | 0 | return low; |
| 364 | }; | |
| 365 | ||
| 366 | // Safely convert anything iterable into a real, live array. | |
| 367 | 1 | _.toArray = function(obj) { |
| 368 | 0 | if (!obj) return []; |
| 369 | 0 | if (_.isArray(obj)) return slice.call(obj); |
| 370 | 0 | if (obj.length === +obj.length) return _.map(obj, _.identity); |
| 371 | 0 | return _.values(obj); |
| 372 | }; | |
| 373 | ||
| 374 | // Return the number of elements in an object. | |
| 375 | 1 | _.size = function(obj) { |
| 376 | 25988 | if (obj == null) return 0; |
| 377 | 25992 | return (obj.length === +obj.length) ? obj.length : _.keys(obj).length; |
| 378 | }; | |
| 379 | ||
| 380 | // Array Functions | |
| 381 | // --------------- | |
| 382 | ||
| 383 | // Get the first element of an array. Passing **n** will return the first N | |
| 384 | // values in the array. Aliased as `head` and `take`. The **guard** check | |
| 385 | // allows it to work with `_.map`. | |
| 386 | 1 | _.first = _.head = _.take = function(array, n, guard) { |
| 387 | 0 | if (array == null) return void 0; |
| 388 | 0 | return (n != null) && !guard ? slice.call(array, 0, n) : array[0]; |
| 389 | }; | |
| 390 | ||
| 391 | // Returns everything but the last entry of the array. Especially useful on | |
| 392 | // the arguments object. Passing **n** will return all the values in | |
| 393 | // the array, excluding the last N. The **guard** check allows it to work with | |
| 394 | // `_.map`. | |
| 395 | 1 | _.initial = function(array, n, guard) { |
| 396 | 0 | return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n)); |
| 397 | }; | |
| 398 | ||
| 399 | // Get the last element of an array. Passing **n** will return the last N | |
| 400 | // values in the array. The **guard** check allows it to work with `_.map`. | |
| 401 | 1 | _.last = function(array, n, guard) { |
| 402 | 0 | if (array == null) return void 0; |
| 403 | 0 | if ((n != null) && !guard) { |
| 404 | 0 | return slice.call(array, Math.max(array.length - n, 0)); |
| 405 | } else { | |
| 406 | 0 | return array[array.length - 1]; |
| 407 | } | |
| 408 | }; | |
| 409 | ||
| 410 | // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. | |
| 411 | // Especially useful on the arguments object. Passing an **n** will return | |
| 412 | // the rest N values in the array. The **guard** | |
| 413 | // check allows it to work with `_.map`. | |
| 414 | 1 | _.rest = _.tail = _.drop = function(array, n, guard) { |
| 415 | 0 | return slice.call(array, (n == null) || guard ? 1 : n); |
| 416 | }; | |
| 417 | ||
| 418 | // Trim out all falsy values from an array. | |
| 419 | 1 | _.compact = function(array) { |
| 420 | 0 | return _.filter(array, _.identity); |
| 421 | }; | |
| 422 | ||
| 423 | // Internal implementation of a recursive `flatten` function. | |
| 424 | 1 | var flatten = function(input, shallow, output) { |
| 425 | 12706 | each(input, function(value) { |
| 426 | 12708 | if (_.isArray(value)) { |
| 427 | 6355 | shallow ? push.apply(output, value) : flatten(value, shallow, output); |
| 428 | } else { | |
| 429 | 6357 | output.push(value); |
| 430 | } | |
| 431 | }); | |
| 432 | 12720 | return output; |
| 433 | }; | |
| 434 | ||
| 435 | // Return a completely flattened version of an array. | |
| 436 | 1 | _.flatten = function(array, shallow) { |
| 437 | 6365 | return flatten(array, shallow, []); |
| 438 | }; | |
| 439 | ||
| 440 | // Return a version of the array that does not contain the specified value(s). | |
| 441 | 1 | _.without = function(array) { |
| 442 | 0 | return _.difference(array, slice.call(arguments, 1)); |
| 443 | }; | |
| 444 | ||
| 445 | // Produce a duplicate-free version of the array. If the array has already | |
| 446 | // been sorted, you have the option of using a faster algorithm. | |
| 447 | // Aliased as `unique`. | |
| 448 | 1 | _.uniq = _.unique = function(array, isSorted, iterator, context) { |
| 449 | 25713 | if (_.isFunction(isSorted)) { |
| 450 | 0 | context = iterator; |
| 451 | 0 | iterator = isSorted; |
| 452 | 0 | isSorted = false; |
| 453 | } | |
| 454 | 25733 | var initial = iterator ? _.map(array, iterator, context) : array; |
| 455 | 25737 | var results = []; |
| 456 | 25741 | var seen = []; |
| 457 | 25745 | each(initial, function(value, index) { |
| 458 | 25749 | if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) { |
| 459 | 25753 | seen.push(value); |
| 460 | 25757 | results.push(array[index]); |
| 461 | } | |
| 462 | }); | |
| 463 | 25769 | return results; |
| 464 | }; | |
| 465 | ||
| 466 | // Produce an array that contains the union: each distinct element from all of | |
| 467 | // the passed-in arrays. | |
| 468 | 1 | _.union = function() { |
| 469 | 0 | return _.uniq(concat.apply(ArrayProto, arguments)); |
| 470 | }; | |
| 471 | ||
| 472 | // Produce an array that contains every item shared between all the | |
| 473 | // passed-in arrays. | |
| 474 | 1 | _.intersection = function(array) { |
| 475 | 0 | var rest = slice.call(arguments, 1); |
| 476 | 0 | return _.filter(_.uniq(array), function(item) { |
| 477 | 0 | return _.every(rest, function(other) { |
| 478 | 0 | return _.indexOf(other, item) >= 0; |
| 479 | }); | |
| 480 | }); | |
| 481 | }; | |
| 482 | ||
| 483 | // Take the difference between one array and a number of other arrays. | |
| 484 | // Only the elements present in just the first array will remain. | |
| 485 | 1 | _.difference = function(array) { |
| 486 | 6416 | var rest = concat.apply(ArrayProto, slice.call(arguments, 1)); |
| 487 | 12885 | return _.filter(array, function(value){ return !_.contains(rest, value); }); |
| 488 | }; | |
| 489 | ||
| 490 | // Zip together multiple lists into a single array -- elements that share | |
| 491 | // an index go together. | |
| 492 | 1 | _.zip = function() { |
| 493 | 0 | var args = slice.call(arguments); |
| 494 | 0 | var length = _.max(_.pluck(args, 'length')); |
| 495 | 0 | var results = new Array(length); |
| 496 | 0 | for (var i = 0; i < length; i++) { |
| 497 | 0 | results[i] = _.pluck(args, "" + i); |
| 498 | } | |
| 499 | 0 | return results; |
| 500 | }; | |
| 501 | ||
| 502 | // Converts lists into objects. Pass either a single array of `[key, value]` | |
| 503 | // pairs, or two parallel arrays of the same length -- one of keys, and one of | |
| 504 | // the corresponding values. | |
| 505 | 1 | _.object = function(list, values) { |
| 506 | 0 | if (list == null) return {}; |
| 507 | 0 | var result = {}; |
| 508 | 0 | for (var i = 0, l = list.length; i < l; i++) { |
| 509 | 0 | if (values) { |
| 510 | 0 | result[list[i]] = values[i]; |
| 511 | } else { | |
| 512 | 0 | result[list[i][0]] = list[i][1]; |
| 513 | } | |
| 514 | } | |
| 515 | 0 | return result; |
| 516 | }; | |
| 517 | ||
| 518 | // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**), | |
| 519 | // we need this function. Return the position of the first occurrence of an | |
| 520 | // item in an array, or -1 if the item is not included in the array. | |
| 521 | // Delegates to **ECMAScript 5**'s native `indexOf` if available. | |
| 522 | // If the array is large and already in sort order, pass `true` | |
| 523 | // for **isSorted** to use binary search. | |
| 524 | 1 | _.indexOf = function(array, item, isSorted) { |
| 525 | 0 | if (array == null) return -1; |
| 526 | 0 | var i = 0, l = array.length; |
| 527 | 0 | if (isSorted) { |
| 528 | 0 | if (typeof isSorted == 'number') { |
| 529 | 0 | i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted); |
| 530 | } else { | |
| 531 | 0 | i = _.sortedIndex(array, item); |
| 532 | 0 | return array[i] === item ? i : -1; |
| 533 | } | |
| 534 | } | |
| 535 | 0 | if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted); |
| 536 | 0 | for (; i < l; i++) if (array[i] === item) return i; |
| 537 | 0 | return -1; |
| 538 | }; | |
| 539 | ||
| 540 | // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available. | |
| 541 | 1 | _.lastIndexOf = function(array, item, from) { |
| 542 | 0 | if (array == null) return -1; |
| 543 | 0 | var hasIndex = from != null; |
| 544 | 0 | if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) { |
| 545 | 0 | return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item); |
| 546 | } | |
| 547 | 0 | var i = (hasIndex ? from : array.length); |
| 548 | 0 | while (i--) if (array[i] === item) return i; |
| 549 | 0 | return -1; |
| 550 | }; | |
| 551 | ||
| 552 | // Generate an integer Array containing an arithmetic progression. A port of | |
| 553 | // the native Python `range()` function. See | |
| 554 | // [the Python documentation](http://docs.python.org/library/functions.html#range). | |
| 555 | 1 | _.range = function(start, stop, step) { |
| 556 | 0 | if (arguments.length <= 1) { |
| 557 | 0 | stop = start || 0; |
| 558 | 0 | start = 0; |
| 559 | } | |
| 560 | 0 | step = arguments[2] || 1; |
| 561 | ||
| 562 | 0 | var len = Math.max(Math.ceil((stop - start) / step), 0); |
| 563 | 0 | var idx = 0; |
| 564 | 0 | var range = new Array(len); |
| 565 | ||
| 566 | 0 | while(idx < len) { |
| 567 | 0 | range[idx++] = start; |
| 568 | 0 | start += step; |
| 569 | } | |
| 570 | ||
| 571 | 0 | return range; |
| 572 | }; | |
| 573 | ||
| 574 | // Function (ahem) Functions | |
| 575 | // ------------------ | |
| 576 | ||
| 577 | // Create a function bound to a given object (assigning `this`, and arguments, | |
| 578 | // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if | |
| 579 | // available. | |
| 580 | 1 | _.bind = function(func, context) { |
| 581 | 0 | if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); |
| 582 | 0 | var args = slice.call(arguments, 2); |
| 583 | 0 | return function() { |
| 584 | 0 | return func.apply(context, args.concat(slice.call(arguments))); |
| 585 | }; | |
| 586 | }; | |
| 587 | ||
| 588 | // Partially apply a function by creating a version that has had some of its | |
| 589 | // arguments pre-filled, without changing its dynamic `this` context. | |
| 590 | 1 | _.partial = function(func) { |
| 591 | 0 | var args = slice.call(arguments, 1); |
| 592 | 0 | return function() { |
| 593 | 0 | return func.apply(this, args.concat(slice.call(arguments))); |
| 594 | }; | |
| 595 | }; | |
| 596 | ||
| 597 | // Bind all of an object's methods to that object. Useful for ensuring that | |
| 598 | // all callbacks defined on an object belong to it. | |
| 599 | 1 | _.bindAll = function(obj) { |
| 600 | 0 | var funcs = slice.call(arguments, 1); |
| 601 | 0 | if (funcs.length === 0) funcs = _.functions(obj); |
| 602 | 0 | each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); }); |
| 603 | 0 | return obj; |
| 604 | }; | |
| 605 | ||
| 606 | // Memoize an expensive function by storing its results. | |
| 607 | 1 | _.memoize = function(func, hasher) { |
| 608 | 0 | var memo = {}; |
| 609 | 0 | hasher || (hasher = _.identity); |
| 610 | 0 | return function() { |
| 611 | 0 | var key = hasher.apply(this, arguments); |
| 612 | 0 | return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments)); |
| 613 | }; | |
| 614 | }; | |
| 615 | ||
| 616 | // Delays a function for the given number of milliseconds, and then calls | |
| 617 | // it with the arguments supplied. | |
| 618 | 1 | _.delay = function(func, wait) { |
| 619 | 0 | var args = slice.call(arguments, 2); |
| 620 | 0 | return setTimeout(function(){ return func.apply(null, args); }, wait); |
| 621 | }; | |
| 622 | ||
| 623 | // Defers a function, scheduling it to run after the current call stack has | |
| 624 | // cleared. | |
| 625 | 1 | _.defer = function(func) { |
| 626 | 0 | return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); |
| 627 | }; | |
| 628 | ||
| 629 | // Returns a function, that, when invoked, will only be triggered at most once | |
| 630 | // during a given window of time. | |
| 631 | 1 | _.throttle = function(func, wait) { |
| 632 | 0 | var context, args, timeout, result; |
| 633 | 0 | var previous = 0; |
| 634 | 0 | var later = function() { |
| 635 | 0 | previous = new Date; |
| 636 | 0 | timeout = null; |
| 637 | 0 | result = func.apply(context, args); |
| 638 | }; | |
| 639 | 0 | return function() { |
| 640 | 0 | var now = new Date; |
| 641 | 0 | var remaining = wait - (now - previous); |
| 642 | 0 | context = this; |
| 643 | 0 | args = arguments; |
| 644 | 0 | if (remaining <= 0) { |
| 645 | 0 | clearTimeout(timeout); |
| 646 | 0 | timeout = null; |
| 647 | 0 | previous = now; |
| 648 | 0 | result = func.apply(context, args); |
| 649 | 0 | } else if (!timeout) { |
| 650 | 0 | timeout = setTimeout(later, remaining); |
| 651 | } | |
| 652 | 0 | return result; |
| 653 | }; | |
| 654 | }; | |
| 655 | ||
| 656 | // Returns a function, that, as long as it continues to be invoked, will not | |
| 657 | // be triggered. The function will be called after it stops being called for | |
| 658 | // N milliseconds. If `immediate` is passed, trigger the function on the | |
| 659 | // leading edge, instead of the trailing. | |
| 660 | 1 | _.debounce = function(func, wait, immediate) { |
| 661 | 0 | var timeout, result; |
| 662 | 0 | return function() { |
| 663 | 0 | var context = this, args = arguments; |
| 664 | 0 | var later = function() { |
| 665 | 0 | timeout = null; |
| 666 | 0 | if (!immediate) result = func.apply(context, args); |
| 667 | }; | |
| 668 | 0 | var callNow = immediate && !timeout; |
| 669 | 0 | clearTimeout(timeout); |
| 670 | 0 | timeout = setTimeout(later, wait); |
| 671 | 0 | if (callNow) result = func.apply(context, args); |
| 672 | 0 | return result; |
| 673 | }; | |
| 674 | }; | |
| 675 | ||
| 676 | // Returns a function that will be executed at most one time, no matter how | |
| 677 | // often you call it. Useful for lazy initialization. | |
| 678 | 1 | _.once = function(func) { |
| 679 | 0 | var ran = false, memo; |
| 680 | 0 | return function() { |
| 681 | 0 | if (ran) return memo; |
| 682 | 0 | ran = true; |
| 683 | 0 | memo = func.apply(this, arguments); |
| 684 | 0 | func = null; |
| 685 | 0 | return memo; |
| 686 | }; | |
| 687 | }; | |
| 688 | ||
| 689 | // Returns the first function passed as an argument to the second, | |
| 690 | // allowing you to adjust arguments, run code before and after, and | |
| 691 | // conditionally execute the original function. | |
| 692 | 1 | _.wrap = function(func, wrapper) { |
| 693 | 0 | return function() { |
| 694 | 0 | var args = [func]; |
| 695 | 0 | push.apply(args, arguments); |
| 696 | 0 | return wrapper.apply(this, args); |
| 697 | }; | |
| 698 | }; | |
| 699 | ||
| 700 | // Returns a function that is the composition of a list of functions, each | |
| 701 | // consuming the return value of the function that follows. | |
| 702 | 1 | _.compose = function() { |
| 703 | 0 | var funcs = arguments; |
| 704 | 0 | return function() { |
| 705 | 0 | var args = arguments; |
| 706 | 0 | for (var i = funcs.length - 1; i >= 0; i--) { |
| 707 | 0 | args = [funcs[i].apply(this, args)]; |
| 708 | } | |
| 709 | 0 | return args[0]; |
| 710 | }; | |
| 711 | }; | |
| 712 | ||
| 713 | // Returns a function that will only be executed after being called N times. | |
| 714 | 1 | _.after = function(times, func) { |
| 715 | 0 | if (times <= 0) return func(); |
| 716 | 0 | return function() { |
| 717 | 0 | if (--times < 1) { |
| 718 | 0 | return func.apply(this, arguments); |
| 719 | } | |
| 720 | }; | |
| 721 | }; | |
| 722 | ||
| 723 | // Object Functions | |
| 724 | // ---------------- | |
| 725 | ||
| 726 | // Retrieve the names of an object's properties. | |
| 727 | // Delegates to **ECMAScript 5**'s native `Object.keys` | |
| 728 | 1 | _.keys = nativeKeys || function(obj) { |
| 729 | 0 | if (obj !== Object(obj)) throw new TypeError('Invalid object'); |
| 730 | 0 | var keys = []; |
| 731 | 0 | for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key; |
| 732 | 0 | return keys; |
| 733 | }; | |
| 734 | ||
| 735 | // Retrieve the values of an object's properties. | |
| 736 | 1 | _.values = function(obj) { |
| 737 | 0 | var values = []; |
| 738 | 0 | for (var key in obj) if (_.has(obj, key)) values.push(obj[key]); |
| 739 | 0 | return values; |
| 740 | }; | |
| 741 | ||
| 742 | // Convert an object into a list of `[key, value]` pairs. | |
| 743 | 1 | _.pairs = function(obj) { |
| 744 | 0 | var pairs = []; |
| 745 | 0 | for (var key in obj) if (_.has(obj, key)) pairs.push([key, obj[key]]); |
| 746 | 0 | return pairs; |
| 747 | }; | |
| 748 | ||
| 749 | // Invert the keys and values of an object. The values must be serializable. | |
| 750 | 1 | _.invert = function(obj) { |
| 751 | 1 | var result = {}; |
| 752 | 13 | for (var key in obj) if (_.has(obj, key)) result[obj[key]] = key; |
| 753 | 1 | return result; |
| 754 | }; | |
| 755 | ||
| 756 | // Return a sorted list of the function names available on the object. | |
| 757 | // Aliased as `methods` | |
| 758 | 1 | _.functions = _.methods = function(obj) { |
| 759 | 1 | var names = []; |
| 760 | 1 | for (var key in obj) { |
| 761 | 216 | if (_.isFunction(obj[key])) names.push(key); |
| 762 | } | |
| 763 | 1 | return names.sort(); |
| 764 | }; | |
| 765 | ||
| 766 | // Extend a given object with all the properties in passed-in object(s). | |
| 767 | 1 | _.extend = function(obj) { |
| 768 | 97338 | each(slice.call(arguments, 1), function(source) { |
| 769 | 194703 | if (source) { |
| 770 | 194735 | for (var prop in source) { |
| 771 | 248305 | obj[prop] = source[prop]; |
| 772 | } | |
| 773 | } | |
| 774 | }); | |
| 775 | 97441 | return obj; |
| 776 | }; | |
| 777 | ||
| 778 | // Return a copy of the object only containing the whitelisted properties. | |
| 779 | 1 | _.pick = function(obj) { |
| 780 | 0 | var copy = {}; |
| 781 | 0 | var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); |
| 782 | 0 | each(keys, function(key) { |
| 783 | 0 | if (key in obj) copy[key] = obj[key]; |
| 784 | }); | |
| 785 | 0 | return copy; |
| 786 | }; | |
| 787 | ||
| 788 | // Return a copy of the object without the blacklisted properties. | |
| 789 | 1 | _.omit = function(obj) { |
| 790 | 0 | var copy = {}; |
| 791 | 0 | var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); |
| 792 | 0 | for (var key in obj) { |
| 793 | 0 | if (!_.contains(keys, key)) copy[key] = obj[key]; |
| 794 | } | |
| 795 | 0 | return copy; |
| 796 | }; | |
| 797 | ||
| 798 | // Fill in a given object with default properties. | |
| 799 | 1 | _.defaults = function(obj) { |
| 800 | 0 | each(slice.call(arguments, 1), function(source) { |
| 801 | 0 | if (source) { |
| 802 | 0 | for (var prop in source) { |
| 803 | 0 | if (obj[prop] == null) obj[prop] = source[prop]; |
| 804 | } | |
| 805 | } | |
| 806 | }); | |
| 807 | 0 | return obj; |
| 808 | }; | |
| 809 | ||
| 810 | // Create a (shallow-cloned) duplicate of an object. | |
| 811 | 1 | _.clone = function(obj) { |
| 812 | 0 | if (!_.isObject(obj)) return obj; |
| 813 | 0 | return _.isArray(obj) ? obj.slice() : _.extend({}, obj); |
| 814 | }; | |
| 815 | ||
| 816 | // Invokes interceptor with the obj, and then returns obj. | |
| 817 | // The primary purpose of this method is to "tap into" a method chain, in | |
| 818 | // order to perform operations on intermediate results within the chain. | |
| 819 | 1 | _.tap = function(obj, interceptor) { |
| 820 | 0 | interceptor(obj); |
| 821 | 0 | return obj; |
| 822 | }; | |
| 823 | ||
| 824 | // Internal recursive comparison function for `isEqual`. | |
| 825 | 1 | var eq = function(a, b, aStack, bStack) { |
| 826 | // Identical objects are equal. `0 === -0`, but they aren't identical. | |
| 827 | // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal. | |
| 828 | 0 | if (a === b) return a !== 0 || 1 / a == 1 / b; |
| 829 | // A strict comparison is necessary because `null == undefined`. | |
| 830 | 0 | if (a == null || b == null) return a === b; |
| 831 | // Unwrap any wrapped objects. | |
| 832 | 0 | if (a instanceof _) a = a._wrapped; |
| 833 | 0 | if (b instanceof _) b = b._wrapped; |
| 834 | // Compare `[[Class]]` names. | |
| 835 | 0 | var className = toString.call(a); |
| 836 | 0 | if (className != toString.call(b)) return false; |
| 837 | 0 | switch (className) { |
| 838 | // Strings, numbers, dates, and booleans are compared by value. | |
| 839 | case '[object String]': | |
| 840 | // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is | |
| 841 | // equivalent to `new String("5")`. | |
| 842 | 0 | return a == String(b); |
| 843 | case '[object Number]': | |
| 844 | // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for | |
| 845 | // other numeric values. | |
| 846 | 0 | return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b); |
| 847 | case '[object Date]': | |
| 848 | case '[object Boolean]': | |
| 849 | // Coerce dates and booleans to numeric primitive values. Dates are compared by their | |
| 850 | // millisecond representations. Note that invalid dates with millisecond representations | |
| 851 | // of `NaN` are not equivalent. | |
| 852 | 0 | return +a == +b; |
| 853 | // RegExps are compared by their source patterns and flags. | |
| 854 | case '[object RegExp]': | |
| 855 | 0 | return a.source == b.source && |
| 856 | a.global == b.global && | |
| 857 | a.multiline == b.multiline && | |
| 858 | a.ignoreCase == b.ignoreCase; | |
| 859 | } | |
| 860 | 0 | if (typeof a != 'object' || typeof b != 'object') return false; |
| 861 | // Assume equality for cyclic structures. The algorithm for detecting cyclic | |
| 862 | // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. | |
| 863 | 0 | var length = aStack.length; |
| 864 | 0 | while (length--) { |
| 865 | // Linear search. Performance is inversely proportional to the number of | |
| 866 | // unique nested structures. | |
| 867 | 0 | if (aStack[length] == a) return bStack[length] == b; |
| 868 | } | |
| 869 | // Add the first object to the stack of traversed objects. | |
| 870 | 0 | aStack.push(a); |
| 871 | 0 | bStack.push(b); |
| 872 | 0 | var size = 0, result = true; |
| 873 | // Recursively compare objects and arrays. | |
| 874 | 0 | if (className == '[object Array]') { |
| 875 | // Compare array lengths to determine if a deep comparison is necessary. | |
| 876 | 0 | size = a.length; |
| 877 | 0 | result = size == b.length; |
| 878 | 0 | if (result) { |
| 879 | // Deep compare the contents, ignoring non-numeric properties. | |
| 880 | 0 | while (size--) { |
| 881 | 0 | if (!(result = eq(a[size], b[size], aStack, bStack))) break; |
| 882 | } | |
| 883 | } | |
| 884 | } else { | |
| 885 | // Objects with different constructors are not equivalent, but `Object`s | |
| 886 | // from different frames are. | |
| 887 | 0 | var aCtor = a.constructor, bCtor = b.constructor; |
| 888 | 0 | if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) && |
| 889 | _.isFunction(bCtor) && (bCtor instanceof bCtor))) { | |
| 890 | 0 | return false; |
| 891 | } | |
| 892 | // Deep compare objects. | |
| 893 | 0 | for (var key in a) { |
| 894 | 0 | if (_.has(a, key)) { |
| 895 | // Count the expected number of properties. | |
| 896 | 0 | size++; |
| 897 | // Deep compare each member. | |
| 898 | 0 | if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break; |
| 899 | } | |
| 900 | } | |
| 901 | // Ensure that both objects contain the same number of properties. | |
| 902 | 0 | if (result) { |
| 903 | 0 | for (key in b) { |
| 904 | 0 | if (_.has(b, key) && !(size--)) break; |
| 905 | } | |
| 906 | 0 | result = !size; |
| 907 | } | |
| 908 | } | |
| 909 | // Remove the first object from the stack of traversed objects. | |
| 910 | 0 | aStack.pop(); |
| 911 | 0 | bStack.pop(); |
| 912 | 0 | return result; |
| 913 | }; | |
| 914 | ||
| 915 | // Perform a deep comparison to check if two objects are equal. | |
| 916 | 1 | _.isEqual = function(a, b) { |
| 917 | 0 | return eq(a, b, [], []); |
| 918 | }; | |
| 919 | ||
| 920 | // Is a given array, string, or object empty? | |
| 921 | // An "empty" object has no enumerable own-properties. | |
| 922 | 1 | _.isEmpty = function(obj) { |
| 923 | 0 | if (obj == null) return true; |
| 924 | 0 | if (_.isArray(obj) || _.isString(obj)) return obj.length === 0; |
| 925 | 0 | for (var key in obj) if (_.has(obj, key)) return false; |
| 926 | 0 | return true; |
| 927 | }; | |
| 928 | ||
| 929 | // Is a given value a DOM element? | |
| 930 | 1 | _.isElement = function(obj) { |
| 931 | 0 | return !!(obj && obj.nodeType === 1); |
| 932 | }; | |
| 933 | ||
| 934 | // Is a given value an array? | |
| 935 | // Delegates to ECMA5's native Array.isArray | |
| 936 | 1 | _.isArray = nativeIsArray || function(obj) { |
| 937 | 0 | return toString.call(obj) == '[object Array]'; |
| 938 | }; | |
| 939 | ||
| 940 | // Is a given variable an object? | |
| 941 | 1 | _.isObject = function(obj) { |
| 942 | 0 | return obj === Object(obj); |
| 943 | }; | |
| 944 | ||
| 945 | // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp. | |
| 946 | 1 | each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) { |
| 947 | 6 | _['is' + name] = function(obj) { |
| 948 | 3223 | return toString.call(obj) == '[object ' + name + ']'; |
| 949 | }; | |
| 950 | }); | |
| 951 | ||
| 952 | // Define a fallback version of the method in browsers (ahem, IE), where | |
| 953 | // there isn't any inspectable "Arguments" type. | |
| 954 | 1 | if (!_.isArguments(arguments)) { |
| 955 | 0 | _.isArguments = function(obj) { |
| 956 | 0 | return !!(obj && _.has(obj, 'callee')); |
| 957 | }; | |
| 958 | } | |
| 959 | ||
| 960 | // Optimize `isFunction` if appropriate. | |
| 961 | 1 | if (typeof (/./) !== 'function') { |
| 962 | 1 | _.isFunction = function(obj) { |
| 963 | 65381 | return typeof obj === 'function'; |
| 964 | }; | |
| 965 | } | |
| 966 | ||
| 967 | // Is a given object a finite number? | |
| 968 | 1 | _.isFinite = function(obj) { |
| 969 | 0 | return isFinite(obj) && !isNaN(parseFloat(obj)); |
| 970 | }; | |
| 971 | ||
| 972 | // Is the given value `NaN`? (NaN is the only number which does not equal itself). | |
| 973 | 1 | _.isNaN = function(obj) { |
| 974 | 0 | return _.isNumber(obj) && obj != +obj; |
| 975 | }; | |
| 976 | ||
| 977 | // Is a given value a boolean? | |
| 978 | 1 | _.isBoolean = function(obj) { |
| 979 | 0 | return obj === true || obj === false || toString.call(obj) == '[object Boolean]'; |
| 980 | }; | |
| 981 | ||
| 982 | // Is a given value equal to null? | |
| 983 | 1 | _.isNull = function(obj) { |
| 984 | 0 | return obj === null; |
| 985 | }; | |
| 986 | ||
| 987 | // Is a given variable undefined? | |
| 988 | 1 | _.isUndefined = function(obj) { |
| 989 | 0 | return obj === void 0; |
| 990 | }; | |
| 991 | ||
| 992 | // Shortcut function for checking if an object has a given property directly | |
| 993 | // on itself (in other words, not on a prototype). | |
| 994 | 1 | _.has = function(obj, key) { |
| 995 | 6 | return hasOwnProperty.call(obj, key); |
| 996 | }; | |
| 997 | ||
| 998 | // Utility Functions | |
| 999 | // ----------------- | |
| 1000 | ||
| 1001 | // Run Underscore.js in *noConflict* mode, returning the `_` variable to its | |
| 1002 | // previous owner. Returns a reference to the Underscore object. | |
| 1003 | 1 | _.noConflict = function() { |
| 1004 | 0 | root._ = previousUnderscore; |
| 1005 | 0 | return this; |
| 1006 | }; | |
| 1007 | ||
| 1008 | // Keep the identity function around for default iterators. | |
| 1009 | 1 | _.identity = function(value) { |
| 1010 | 0 | return value; |
| 1011 | }; | |
| 1012 | ||
| 1013 | // Run a function **n** times. | |
| 1014 | 1 | _.times = function(n, iterator, context) { |
| 1015 | 0 | var accum = Array(n); |
| 1016 | 0 | for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i); |
| 1017 | 0 | return accum; |
| 1018 | }; | |
| 1019 | ||
| 1020 | // Return a random integer between min and max (inclusive). | |
| 1021 | 1 | _.random = function(min, max) { |
| 1022 | 0 | if (max == null) { |
| 1023 | 0 | max = min; |
| 1024 | 0 | min = 0; |
| 1025 | } | |
| 1026 | 0 | return min + Math.floor(Math.random() * (max - min + 1)); |
| 1027 | }; | |
| 1028 | ||
| 1029 | // List of HTML entities for escaping. | |
| 1030 | 1 | var entityMap = { |
| 1031 | escape: { | |
| 1032 | '&': '&', | |
| 1033 | '<': '<', | |
| 1034 | '>': '>', | |
| 1035 | '"': '"', | |
| 1036 | "'": ''', | |
| 1037 | '/': '/' | |
| 1038 | } | |
| 1039 | }; | |
| 1040 | 1 | entityMap.unescape = _.invert(entityMap.escape); |
| 1041 | ||
| 1042 | // Regexes containing the keys and values listed immediately above. | |
| 1043 | 1 | var entityRegexes = { |
| 1044 | escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'), | |
| 1045 | unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g') | |
| 1046 | }; | |
| 1047 | ||
| 1048 | // Functions for escaping and unescaping strings to/from HTML interpolation. | |
| 1049 | 1 | _.each(['escape', 'unescape'], function(method) { |
| 1050 | 2 | _[method] = function(string) { |
| 1051 | 0 | if (string == null) return ''; |
| 1052 | 0 | return ('' + string).replace(entityRegexes[method], function(match) { |
| 1053 | 0 | return entityMap[method][match]; |
| 1054 | }); | |
| 1055 | }; | |
| 1056 | }); | |
| 1057 | ||
| 1058 | // If the value of the named property is a function then invoke it; | |
| 1059 | // otherwise, return it. | |
| 1060 | 1 | _.result = function(object, property) { |
| 1061 | 0 | if (object == null) return null; |
| 1062 | 0 | var value = object[property]; |
| 1063 | 0 | return _.isFunction(value) ? value.call(object) : value; |
| 1064 | }; | |
| 1065 | ||
| 1066 | // Add your own custom functions to the Underscore object. | |
| 1067 | 1 | _.mixin = function(obj) { |
| 1068 | 1 | each(_.functions(obj), function(name){ |
| 1069 | 107 | var func = _[name] = obj[name]; |
| 1070 | 107 | _.prototype[name] = function() { |
| 1071 | 0 | var args = [this._wrapped]; |
| 1072 | 0 | push.apply(args, arguments); |
| 1073 | 0 | return result.call(this, func.apply(_, args)); |
| 1074 | }; | |
| 1075 | }); | |
| 1076 | }; | |
| 1077 | ||
| 1078 | // Generate a unique integer id (unique within the entire client session). | |
| 1079 | // Useful for temporary DOM ids. | |
| 1080 | 1 | var idCounter = 0; |
| 1081 | 1 | _.uniqueId = function(prefix) { |
| 1082 | 0 | var id = ++idCounter + ''; |
| 1083 | 0 | return prefix ? prefix + id : id; |
| 1084 | }; | |
| 1085 | ||
| 1086 | // By default, Underscore uses ERB-style template delimiters, change the | |
| 1087 | // following template settings to use alternative delimiters. | |
| 1088 | 1 | _.templateSettings = { |
| 1089 | evaluate : /<%([\s\S]+?)%>/g, | |
| 1090 | interpolate : /<%=([\s\S]+?)%>/g, | |
| 1091 | escape : /<%-([\s\S]+?)%>/g | |
| 1092 | }; | |
| 1093 | ||
| 1094 | // When customizing `templateSettings`, if you don't want to define an | |
| 1095 | // interpolation, evaluation or escaping regex, we need one that is | |
| 1096 | // guaranteed not to match. | |
| 1097 | 1 | var noMatch = /(.)^/; |
| 1098 | ||
| 1099 | // Certain characters need to be escaped so that they can be put into a | |
| 1100 | // string literal. | |
| 1101 | 1 | var escapes = { |
| 1102 | "'": "'", | |
| 1103 | '\\': '\\', | |
| 1104 | '\r': 'r', | |
| 1105 | '\n': 'n', | |
| 1106 | '\t': 't', | |
| 1107 | '\u2028': 'u2028', | |
| 1108 | '\u2029': 'u2029' | |
| 1109 | }; | |
| 1110 | ||
| 1111 | 1 | var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g; |
| 1112 | ||
| 1113 | // JavaScript micro-templating, similar to John Resig's implementation. | |
| 1114 | // Underscore templating handles arbitrary delimiters, preserves whitespace, | |
| 1115 | // and correctly escapes quotes within interpolated code. | |
| 1116 | 1 | _.template = function(text, data, settings) { |
| 1117 | 0 | var render; |
| 1118 | 0 | settings = _.defaults({}, settings, _.templateSettings); |
| 1119 | ||
| 1120 | // Combine delimiters into one regular expression via alternation. | |
| 1121 | 0 | var matcher = new RegExp([ |
| 1122 | (settings.escape || noMatch).source, | |
| 1123 | (settings.interpolate || noMatch).source, | |
| 1124 | (settings.evaluate || noMatch).source | |
| 1125 | ].join('|') + '|$', 'g'); | |
| 1126 | ||
| 1127 | // Compile the template source, escaping string literals appropriately. | |
| 1128 | 0 | var index = 0; |
| 1129 | 0 | var source = "__p+='"; |
| 1130 | 0 | text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { |
| 1131 | 0 | source += text.slice(index, offset) |
| 1132 | 0 | .replace(escaper, function(match) { return '\\' + escapes[match]; }); |
| 1133 | ||
| 1134 | 0 | if (escape) { |
| 1135 | 0 | source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; |
| 1136 | } | |
| 1137 | 0 | if (interpolate) { |
| 1138 | 0 | source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; |
| 1139 | } | |
| 1140 | 0 | if (evaluate) { |
| 1141 | 0 | source += "';\n" + evaluate + "\n__p+='"; |
| 1142 | } | |
| 1143 | 0 | index = offset + match.length; |
| 1144 | 0 | return match; |
| 1145 | }); | |
| 1146 | 0 | source += "';\n"; |
| 1147 | ||
| 1148 | // If a variable is not specified, place data values in local scope. | |
| 1149 | 0 | if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; |
| 1150 | ||
| 1151 | 0 | source = "var __t,__p='',__j=Array.prototype.join," + |
| 1152 | "print=function(){__p+=__j.call(arguments,'');};\n" + | |
| 1153 | source + "return __p;\n"; | |
| 1154 | ||
| 1155 | 0 | try { |
| 1156 | 0 | render = new Function(settings.variable || 'obj', '_', source); |
| 1157 | } catch (e) { | |
| 1158 | 0 | e.source = source; |
| 1159 | 0 | throw e; |
| 1160 | } | |
| 1161 | ||
| 1162 | 0 | if (data) return render(data, _); |
| 1163 | 0 | var template = function(data) { |
| 1164 | 0 | return render.call(this, data, _); |
| 1165 | }; | |
| 1166 | ||
| 1167 | // Provide the compiled function source as a convenience for precompilation. | |
| 1168 | 0 | template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}'; |
| 1169 | ||
| 1170 | 0 | return template; |
| 1171 | }; | |
| 1172 | ||
| 1173 | // Add a "chain" function, which will delegate to the wrapper. | |
| 1174 | 1 | _.chain = function(obj) { |
| 1175 | 0 | return _(obj).chain(); |
| 1176 | }; | |
| 1177 | ||
| 1178 | // OOP | |
| 1179 | // --------------- | |
| 1180 | // If Underscore is called as a function, it returns a wrapped object that | |
| 1181 | // can be used OO-style. This wrapper holds altered versions of all the | |
| 1182 | // underscore functions. Wrapped objects may be chained. | |
| 1183 | ||
| 1184 | // Helper function to continue chaining intermediate results. | |
| 1185 | 1 | var result = function(obj) { |
| 1186 | 0 | return this._chain ? _(obj).chain() : obj; |
| 1187 | }; | |
| 1188 | ||
| 1189 | // Add all of the Underscore functions to the wrapper object. | |
| 1190 | 1 | _.mixin(_); |
| 1191 | ||
| 1192 | // Add all mutator Array functions to the wrapper. | |
| 1193 | 1 | each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { |
| 1194 | 7 | var method = ArrayProto[name]; |
| 1195 | 7 | _.prototype[name] = function() { |
| 1196 | 0 | var obj = this._wrapped; |
| 1197 | 0 | method.apply(obj, arguments); |
| 1198 | 0 | if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0]; |
| 1199 | 0 | return result.call(this, obj); |
| 1200 | }; | |
| 1201 | }); | |
| 1202 | ||
| 1203 | // Add all accessor Array functions to the wrapper. | |
| 1204 | 1 | each(['concat', 'join', 'slice'], function(name) { |
| 1205 | 3 | var method = ArrayProto[name]; |
| 1206 | 3 | _.prototype[name] = function() { |
| 1207 | 0 | return result.call(this, method.apply(this._wrapped, arguments)); |
| 1208 | }; | |
| 1209 | }); | |
| 1210 | ||
| 1211 | 1 | _.extend(_.prototype, { |
| 1212 | ||
| 1213 | // Start chaining a wrapped Underscore object. | |
| 1214 | chain: function() { | |
| 1215 | 0 | this._chain = true; |
| 1216 | 0 | return this; |
| 1217 | }, | |
| 1218 | ||
| 1219 | // Extracts the result from a wrapped and chained object. | |
| 1220 | value: function() { | |
| 1221 | 0 | return this._wrapped; |
| 1222 | } | |
| 1223 | ||
| 1224 | }); | |
| 1225 | ||
| 1226 | }).call(this); | |
| 1227 |
| Line | Hits | Source |
|---|---|---|
| 1 | /** | |
| 2 | * Module Dependencies | |
| 3 | */ | |
| 4 | 1 | var entities = require('entities'); |
| 5 | ||
| 6 | /** | |
| 7 | * HTML Tags | |
| 8 | */ | |
| 9 | ||
| 10 | 1 | var tags = { tag: true, script: true, style: true }; |
| 11 | ||
| 12 | /** | |
| 13 | * Check if the DOM element is a tag | |
| 14 | * | |
| 15 | * isTag(type) includes <script> and <style> tags | |
| 16 | */ | |
| 17 | ||
| 18 | 1 | exports.isTag = function(type) { |
| 19 | 293789 | if (type.type) type = type.type; |
| 20 | 162880 | return tags[type] || false; |
| 21 | }; | |
| 22 | ||
| 23 | /** | |
| 24 | * Convert a string to camel case notation. | |
| 25 | * @param {String} str String to be converted. | |
| 26 | * @return {String} String in camel case notation. | |
| 27 | */ | |
| 28 | ||
| 29 | 1 | exports.camelCase = function(str) { |
| 30 | 0 | return str.replace(/[_.-](\w|$)/g, function(_, x) { |
| 31 | 0 | return x.toUpperCase(); |
| 32 | }); | |
| 33 | }; | |
| 34 | ||
| 35 | /** | |
| 36 | * Expose encode and decode methods from FB55's node-entities library | |
| 37 | * | |
| 38 | * 0 = XML, 1 = HTML4 and 2 = HTML5 | |
| 39 | */ | |
| 40 | ||
| 41 | 50548 | exports.encode = function(str) { return entities.encode(String(str), 0); }; |
| 42 | 32560 | exports.decode = function(str) { return entities.decode(str, 2); }; |
| 43 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | var modes = ["XML", "HTML4", "HTML5"]; |
| 2 | ||
| 3 | 1 | module.exports = { |
| 4 | decode: function(data, level){ | |
| 5 | 32602 | if(!modes[level]) level = 0; |
| 6 | 32607 | return module.exports["decode" + modes[level]](data); |
| 7 | }, | |
| 8 | decodeStrict: function(data, level){ | |
| 9 | 0 | if(!modes[level]) level = 0; |
| 10 | 0 | return module.exports["decode" + modes[level] + "Strict"](data); |
| 11 | }, | |
| 12 | encode: function(data, level){ | |
| 13 | 50678 | if(!modes[level]) level = 0; |
| 14 | 50686 | return module.exports["encode" + modes[level]](data); |
| 15 | } | |
| 16 | }; | |
| 17 | ||
| 18 | 1 | modes.reduce(function(prev, name){ |
| 19 | 3 | var obj = require("c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/entities/./entities/" + name.toLowerCase() + ".json"); |
| 20 | ||
| 21 | 3 | if(prev){ |
| 22 | 2 | Object.keys(prev).forEach(function(name){ |
| 23 | 359 | obj[name] = prev[name]; |
| 24 | }); | |
| 25 | } | |
| 26 | ||
| 27 | 3 | module.exports["decode" + name + "Strict"] = getStrictReplacer(obj); |
| 28 | ||
| 29 | 3 | if(name === "XML"){ |
| 30 | //there is no non-strict mode for XML | |
| 31 | 1 | module.exports.decodeXML = module.exports.decodeXMLStrict; |
| 32 | } else { | |
| 33 | 2 | module.exports["decode" + name] = getReplacer(obj); |
| 34 | } | |
| 35 | ||
| 36 | 3 | module.exports["encode" + name] = getReverse(obj); |
| 37 | ||
| 38 | 3 | return obj; |
| 39 | }, null); | |
| 40 | ||
| 41 | 1 | function getReplacer(obj){ |
| 42 | 2 | var keys = Object.keys(obj).sort(); |
| 43 | 2 | var re = keys.join("|").replace(/(\w+)\|\1;/g, "$1;?"); |
| 44 | ||
| 45 | // also match hex and char codes | |
| 46 | 2 | re += "|#[xX][\\da-fA-F]+;?|#\\d+;?"; |
| 47 | ||
| 48 | 2 | return genReplaceFunc( |
| 49 | new RegExp("&(?:" + re + ")", "g"), | |
| 50 | function func(name){ | |
| 51 | 0 | if(name.charAt(1) === "#"){ |
| 52 | 0 | if(name.charAt(2).toLowerCase() === "x"){ |
| 53 | 0 | return String.fromCharCode(parseInt(name.substr(3), 16)); |
| 54 | } | |
| 55 | 0 | return String.fromCharCode(parseInt(name.substr(2), 10)); |
| 56 | } | |
| 57 | 0 | return obj[name.substr(1)]; |
| 58 | } | |
| 59 | ); | |
| 60 | } | |
| 61 | ||
| 62 | 1 | function getStrictReplacer(obj){ |
| 63 | 3 | var keys = Object.keys(obj).sort().filter(RegExp.prototype.test, /;$/); |
| 64 | 3 | var re = keys.map(function(name){ |
| 65 | 2383 | return name.slice(0, -1); //remove trailing semicolon |
| 66 | }).join("|"); | |
| 67 | ||
| 68 | // also match hex and char codes | |
| 69 | 3 | re += "|#[xX][\\da-fA-F]+|#\\d+"; |
| 70 | ||
| 71 | 3 | var expr = new RegExp("&(?:" + re + ");", "g"); |
| 72 | ||
| 73 | 3 | return genReplaceFunc(expr, func); |
| 74 | ||
| 75 | 0 | function func(name){ |
| 76 | 0 | if(name.charAt(1) === "#"){ |
| 77 | 0 | if(name.charAt(2).toLowerCase() === "x"){ |
| 78 | 0 | return String.fromCharCode(parseInt(name.substr(3), 16)); |
| 79 | } | |
| 80 | 0 | return String.fromCharCode(parseInt(name.substr(2), 10)); |
| 81 | } | |
| 82 | 0 | return obj[name.substr(1)]; |
| 83 | } | |
| 84 | } | |
| 85 | ||
| 86 | 1 | var re_nonUTF8 = /[\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]/g; |
| 87 | ||
| 88 | 1 | function nonUTF8Replacer(c){ |
| 89 | 0 | return "&#" + c.charCodeAt(0) + ";"; |
| 90 | } | |
| 91 | ||
| 92 | 1 | function getReverse(obj){ |
| 93 | 3 | var reverse = Object.keys(obj).filter(function(name){ |
| 94 | //prefer identifiers with a semicolon | |
| 95 | 2591 | return name.substr(-1) === ";" || obj[name + ";"] !== obj[name]; |
| 96 | }).reduce(function(reverse, name){ | |
| 97 | 2383 | reverse[obj[name]] = name; |
| 98 | 2383 | return reverse; |
| 99 | }, {}); | |
| 100 | ||
| 101 | 3 | var regex = new RegExp("\\" + Object.keys(reverse).sort().join("|\\"), "g"); |
| 102 | 3 | function func(name){ |
| 103 | 3612 | return "&" + reverse[name]; |
| 104 | } | |
| 105 | ||
| 106 | 3 | return function(data){ |
| 107 | 51338 | return data |
| 108 | .replace(regex, func) | |
| 109 | .replace(re_nonUTF8, nonUTF8Replacer); | |
| 110 | }; | |
| 111 | } | |
| 112 | ||
| 113 | 1 | function genReplaceFunc(regex, func){ |
| 114 | 5 | return function(data){ |
| 115 | 33097 | return data.replace(regex, func); |
| 116 | }; | |
| 117 | } | |
| 118 |
| Line | Hits | Source |
|---|---|---|
| 1 | /** | |
| 2 | * Module dependencies | |
| 3 | */ | |
| 4 | ||
| 5 | 1 | var select = require('cheerio-select'), |
| 6 | parse = require('./parse'), | |
| 7 | render = require('./render'), | |
| 8 | decode = require('./utils').decode; | |
| 9 | ||
| 10 | /** | |
| 11 | * $.load(str) | |
| 12 | */ | |
| 13 | ||
| 14 | 1 | var load = exports.load = function(str, options) { |
| 15 | 1 | var Cheerio = require('./cheerio'), |
| 16 | root = parse(str, options); | |
| 17 | ||
| 18 | 1 | var initialize = function(selector, context, r) { |
| 19 | 213 | return new Cheerio(selector, context, r || root); |
| 20 | }; | |
| 21 | ||
| 22 | // Add in the static methods | |
| 23 | 1 | initialize.__proto__ = exports; |
| 24 | ||
| 25 | // Add in the root | |
| 26 | 1 | initialize._root = root; |
| 27 | ||
| 28 | 1 | return initialize; |
| 29 | }; | |
| 30 | ||
| 31 | /** | |
| 32 | * $.html([selector | dom]) | |
| 33 | */ | |
| 34 | ||
| 35 | 1 | var html = exports.html = function(dom) { |
| 36 | 7360 | if (dom) { |
| 37 | 7361 | dom = (typeof dom === 'string') ? select(dom, this._root) : dom; |
| 38 | 7362 | return render(dom); |
| 39 | 0 | } else if (this._root && this._root.children) { |
| 40 | 0 | return render(this._root.children); |
| 41 | } else { | |
| 42 | 0 | return ''; |
| 43 | } | |
| 44 | }; | |
| 45 | ||
| 46 | /** | |
| 47 | * $.xml([selector | dom]) | |
| 48 | */ | |
| 49 | ||
| 50 | 1 | var xml = exports.xml = function(dom) { |
| 51 | 0 | if (dom) { |
| 52 | 0 | dom = (typeof dom === 'string') ? select(dom, this._root) : dom; |
| 53 | 0 | return render(dom, { xmlMode: true }); |
| 54 | 0 | } else if (this._root && this._root.children) { |
| 55 | 0 | return render(this._root.children, { xmlMode: true }); |
| 56 | } else { | |
| 57 | 0 | return ''; |
| 58 | } | |
| 59 | }; | |
| 60 | ||
| 61 | /** | |
| 62 | * $.text(dom) | |
| 63 | */ | |
| 64 | ||
| 65 | 1 | var text = exports.text = function(elems) { |
| 66 | 7720 | if (!elems) return ''; |
| 67 | ||
| 68 | 7722 | var ret = '', |
| 69 | len = elems.length, | |
| 70 | elem; | |
| 71 | ||
| 72 | 7728 | for (var i = 0; i < len; i ++) { |
| 73 | 3864 | elem = elems[i]; |
| 74 | 3864 | if (elem.type === 'text') ret += decode(elem.data); |
| 75 | 3864 | else if (elem.children && elem.type !== 'comment') { |
| 76 | 3864 | ret += text(elem.children); |
| 77 | } | |
| 78 | } | |
| 79 | ||
| 80 | 7734 | return ret; |
| 81 | }; | |
| 82 | ||
| 83 | /** | |
| 84 | * $.parseHTML(data [, context ] [, keepScripts ]) | |
| 85 | * Parses a string into an array of DOM nodes. The `context` argument has no | |
| 86 | * meaning for Cheerio, but it is maintained for API compatability with jQuery. | |
| 87 | */ | |
| 88 | 1 | var parseHTML = exports.parseHTML = function(data, context, keepScripts) { |
| 89 | 0 | var parsed; |
| 90 | ||
| 91 | 0 | if (!data || typeof data !== 'string') { |
| 92 | 0 | return null; |
| 93 | } | |
| 94 | ||
| 95 | 0 | if (typeof context === 'boolean') { |
| 96 | 0 | keepScripts = context; |
| 97 | } | |
| 98 | ||
| 99 | 0 | parsed = this.load(data); |
| 100 | 0 | if (!keepScripts) { |
| 101 | 0 | parsed('script').remove(); |
| 102 | } | |
| 103 | ||
| 104 | 0 | return parsed.root()[0].children; |
| 105 | }; | |
| 106 | ||
| 107 | /** | |
| 108 | * $.root() | |
| 109 | */ | |
| 110 | 1 | var root = exports.root = function() { |
| 111 | 0 | return this(this._root); |
| 112 | }; | |
| 113 | ||
| 114 | /** | |
| 115 | * $.contains() | |
| 116 | */ | |
| 117 | 1 | var contains = exports.contains = function(container, contained) { |
| 118 | ||
| 119 | // According to the jQuery API, an element does not "contain" itself | |
| 120 | 0 | if (contained === container) { |
| 121 | 0 | return false; |
| 122 | } | |
| 123 | ||
| 124 | // Step up the descendents, stopping when the root element is reached | |
| 125 | // (signaled by `.parent` returning a reference to the same object) | |
| 126 | 0 | while (contained && contained !== contained.parent) { |
| 127 | 0 | contained = contained.parent; |
| 128 | 0 | if (contained === container) { |
| 129 | 0 | return true; |
| 130 | } | |
| 131 | } | |
| 132 | ||
| 133 | 0 | return false; |
| 134 | }; | |
| 135 |
| Line | Hits | Source |
|---|---|---|
| 1 | /* | |
| 2 | Module dependencies | |
| 3 | */ | |
| 4 | 1 | var _ = require('underscore'); |
| 5 | 1 | var utils = require('./utils'); |
| 6 | ||
| 7 | 1 | var decode = utils.decode; |
| 8 | 1 | var encode = utils.encode; |
| 9 | ||
| 10 | /* | |
| 11 | Boolean Attributes | |
| 12 | */ | |
| 13 | 1 | var rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i; |
| 14 | ||
| 15 | /* | |
| 16 | Format attributes | |
| 17 | */ | |
| 18 | 1 | var formatAttrs = function(attributes) { |
| 19 | 30359 | if (!attributes) return ''; |
| 20 | ||
| 21 | 30367 | var output = [], |
| 22 | value; | |
| 23 | ||
| 24 | // Loop through the attributes | |
| 25 | 30383 | for (var key in attributes) { |
| 26 | 30387 | value = attributes[key]; |
| 27 | 30391 | if (!value && (rboolean.test(key) || key === '/')) { |
| 28 | 0 | output.push(key); |
| 29 | } else { | |
| 30 | 30403 | output.push(key + '="' + encode(decode(value)) + '"'); |
| 31 | } | |
| 32 | } | |
| 33 | ||
| 34 | 30419 | return output.join(' '); |
| 35 | }; | |
| 36 | ||
| 37 | /* | |
| 38 | Self-enclosing tags (stolen from node-htmlparser) | |
| 39 | */ | |
| 40 | 1 | var singleTag = { |
| 41 | area: 1, | |
| 42 | base: 1, | |
| 43 | basefont: 1, | |
| 44 | br: 1, | |
| 45 | col: 1, | |
| 46 | frame: 1, | |
| 47 | hr: 1, | |
| 48 | img: 1, | |
| 49 | input: 1, | |
| 50 | isindex: 1, | |
| 51 | link: 1, | |
| 52 | meta: 1, | |
| 53 | param: 1, | |
| 54 | embed: 1, | |
| 55 | include: 1, | |
| 56 | 'yield': 1 | |
| 57 | }; | |
| 58 | ||
| 59 | /* | |
| 60 | Tag types from htmlparser | |
| 61 | */ | |
| 62 | 1 | var tagType = { |
| 63 | tag: 1, | |
| 64 | script: 1, | |
| 65 | link: 1, | |
| 66 | style: 1, | |
| 67 | template: 1 | |
| 68 | }; | |
| 69 | ||
| 70 | 1 | var render = module.exports = function(dom, opts) { |
| 71 | 38484 | if (!Array.isArray(dom) && !dom.cheerio) dom = [dom]; |
| 72 | 38489 | opts = opts || {}; |
| 73 | ||
| 74 | 38499 | var output = [], |
| 75 | xmlMode = opts.xmlMode || false, | |
| 76 | ignoreWhitespace = opts.ignoreWhitespace || false; | |
| 77 | ||
| 78 | 38519 | _.each(dom, function(elem) { |
| 79 | 32191 | var pushVal; |
| 80 | ||
| 81 | 32199 | if (tagType[elem.type]) |
| 82 | 30996 | pushVal = renderTag(elem, xmlMode); |
| 83 | 1207 | else if (elem.type === 'directive') |
| 84 | 0 | pushVal = renderDirective(elem); |
| 85 | 1207 | else if (elem.type === 'comment') |
| 86 | 0 | pushVal = renderComment(elem); |
| 87 | else | |
| 88 | 1207 | pushVal = renderText(elem); |
| 89 | ||
| 90 | // Push rendered DOM node | |
| 91 | 32239 | output.push(pushVal); |
| 92 | ||
| 93 | 32247 | if (elem.children) |
| 94 | 31044 | output.push(render(elem.children, opts)); |
| 95 | ||
| 96 | 32259 | if ((!singleTag[elem.name] || xmlMode) && tagType[elem.type]) { |
| 97 | 31056 | if (!isClosedTag(elem, xmlMode)) { |
| 98 | 31060 | output.push('</' + elem.name + '>'); |
| 99 | } | |
| 100 | } | |
| 101 | }); | |
| 102 | ||
| 103 | 38644 | return output.join(''); |
| 104 | }; | |
| 105 | ||
| 106 | 1 | var isClosedTag = function(elem, xmlMode){ |
| 107 | 62192 | return (xmlMode && (!elem.children || elem.children.length === 0)); |
| 108 | }; | |
| 109 | ||
| 110 | 1 | var renderTag = function(elem, xmlMode) { |
| 111 | 31112 | var tag = '<' + elem.name; |
| 112 | ||
| 113 | 31120 | if (elem.attribs && _.size(elem.attribs)) { |
| 114 | 30739 | tag += ' ' + formatAttrs(elem.attribs); |
| 115 | } | |
| 116 | ||
| 117 | 31136 | if (isClosedTag(elem, xmlMode)) { |
| 118 | 0 | tag += '/'; |
| 119 | } | |
| 120 | ||
| 121 | 31152 | return tag + '>'; |
| 122 | }; | |
| 123 | ||
| 124 | 1 | var renderDirective = function(elem) { |
| 125 | 0 | return '<' + elem.data + '>'; |
| 126 | }; | |
| 127 | ||
| 128 | 1 | var renderText = function(elem) { |
| 129 | 1207 | return elem.data; |
| 130 | }; | |
| 131 | ||
| 132 | 1 | var renderComment = function(elem) { |
| 133 | 0 | return '<!--' + elem.data + '-->'; |
| 134 | }; | |
| 135 | ||
| 136 | // module.exports = $.extend(exports); | |
| 137 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | var _ = require('underscore'), |
| 2 | utils = require('../utils'), | |
| 3 | isTag = utils.isTag, | |
| 4 | decode = utils.decode, | |
| 5 | encode = utils.encode, | |
| 6 | hasOwn = Object.prototype.hasOwnProperty, | |
| 7 | rspace = /\s+/, | |
| 8 | ||
| 9 | // Lookup table for coercing string data-* attributes to their corresponding | |
| 10 | // JavaScript primitives | |
| 11 | primitives = { | |
| 12 | null: null, | |
| 13 | true: true, | |
| 14 | false: false | |
| 15 | }, | |
| 16 | ||
| 17 | // Attributes that are booleans | |
| 18 | rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, | |
| 19 | // Matches strings that look like JSON objects or arrays | |
| 20 | rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/; | |
| 21 | ||
| 22 | ||
| 23 | 1 | var setAttr = function(el, name, value) { |
| 24 | 3614 | if (typeof name === 'object') return _.extend(el.attribs, name); |
| 25 | ||
| 26 | 3615 | if (value === null) { |
| 27 | 0 | removeAttribute(el, name); |
| 28 | } else { | |
| 29 | 3617 | el.attribs[name] = encode(value); |
| 30 | } | |
| 31 | ||
| 32 | 3618 | return el.attribs; |
| 33 | }; | |
| 34 | ||
| 35 | 1 | var attr = exports.attr = function(name, value) { |
| 36 | // Set the value (with attr map support) | |
| 37 | 7129 | if (typeof name === 'object' || value !== undefined) { |
| 38 | 3621 | if (_.isFunction(value)) { |
| 39 | 0 | return this.each(function(i, el) { |
| 40 | 0 | setAttr(el, name, value.call(this, i, el.attribs[name])); |
| 41 | }); | |
| 42 | } | |
| 43 | 3624 | return this.each(function(i, el) { |
| 44 | 3625 | el.attribs = setAttr(el, name, value); |
| 45 | }); | |
| 46 | } | |
| 47 | ||
| 48 | 3515 | var elem = this[0]; |
| 49 | ||
| 50 | 3516 | if (!elem || !isTag(elem)) return; |
| 51 | ||
| 52 | 3517 | if (!elem.attribs) { |
| 53 | 0 | elem.attribs = {}; |
| 54 | } | |
| 55 | ||
| 56 | // Return the entire attribs object if no attribute specified | |
| 57 | 3519 | if (!name) { |
| 58 | 0 | for (var a in elem.attribs) { |
| 59 | 0 | elem.attribs[a] = decode(elem.attribs[a]); |
| 60 | } | |
| 61 | 0 | return elem.attribs; |
| 62 | } | |
| 63 | ||
| 64 | 3523 | if (hasOwn.call(elem.attribs, name)) { |
| 65 | // Get the (decoded) attribute | |
| 66 | 3524 | return decode(elem.attribs[name]); |
| 67 | } | |
| 68 | }; | |
| 69 | ||
| 70 | 1 | var setData = function(el, name, value) { |
| 71 | 0 | if (typeof name === 'object') return _.extend(el.data, name); |
| 72 | 0 | if (typeof name === 'string' && value !== undefined) { |
| 73 | 0 | el.data[name] = encode(value); |
| 74 | 0 | } else if (typeof name === 'object') { |
| 75 | // If its an object, loop through it | |
| 76 | 0 | _.each(name, function(value, key) { |
| 77 | 0 | el.data[key] = encode(value); |
| 78 | }); | |
| 79 | } | |
| 80 | ||
| 81 | 0 | return el.data; |
| 82 | }; | |
| 83 | ||
| 84 | 1 | var data = exports.data = function(name, value) { |
| 85 | 0 | var elem = this[0]; |
| 86 | ||
| 87 | 0 | if (!elem || !isTag(elem)) return; |
| 88 | ||
| 89 | 0 | if (!elem.data) { |
| 90 | 0 | elem.data = {}; |
| 91 | } | |
| 92 | ||
| 93 | // Return the entire data object if no data specified | |
| 94 | 0 | if (!name) { |
| 95 | ||
| 96 | 0 | _.each(elem.data, function(value, key) { |
| 97 | 0 | elem.data[key] = decode(value); |
| 98 | }); | |
| 99 | ||
| 100 | 0 | return elem.data; |
| 101 | } | |
| 102 | ||
| 103 | // Set the value (with attr map support) | |
| 104 | 0 | if (typeof name === 'object' || value !== undefined) { |
| 105 | 0 | this.each(function(i, el) { |
| 106 | 0 | el.data = setData(el, name, value); |
| 107 | }); | |
| 108 | 0 | return this; |
| 109 | 0 | } else if (hasOwn.call(elem.data, name)) { |
| 110 | // Get the (decoded) data | |
| 111 | 0 | var val = decode(elem.data[name]); |
| 112 | ||
| 113 | 0 | if (hasOwn.call(primitives, val)) { |
| 114 | 0 | val = primitives[val]; |
| 115 | 0 | } else if (val === String(Number(val))) { |
| 116 | 0 | val = Number(val); |
| 117 | 0 | } else if (rbrace.test(val)) { |
| 118 | 0 | val = JSON.parse(val); |
| 119 | } | |
| 120 | ||
| 121 | 0 | return val; |
| 122 | 0 | } else if (typeof name === 'string' && value === undefined) { |
| 123 | 0 | return undefined; |
| 124 | } | |
| 125 | ||
| 126 | 0 | return this; |
| 127 | }; | |
| 128 | ||
| 129 | /** | |
| 130 | * Get the value of an element | |
| 131 | */ | |
| 132 | ||
| 133 | 1 | var val = exports.val = function(value) { |
| 134 | 0 | var querying = arguments.length === 0, |
| 135 | element = this[0]; | |
| 136 | ||
| 137 | 0 | if(!element) return; |
| 138 | ||
| 139 | 0 | switch (element.name) { |
| 140 | case 'textarea': | |
| 141 | 0 | return querying ? this.text() : this.each(function() { |
| 142 | 0 | this.text(value); |
| 143 | }); | |
| 144 | case 'input': | |
| 145 | 0 | switch (this.attr('type')) { |
| 146 | case 'radio': | |
| 147 | 0 | var queryString = 'input[type=radio][name=' + this.attr('name') + ']:checked'; |
| 148 | 0 | var parentEl, root; |
| 149 | ||
| 150 | // Go up until we hit a form or root | |
| 151 | 0 | parentEl = this.closest('form'); |
| 152 | 0 | if (parentEl.length === 0) { |
| 153 | 0 | root = (this.parents().last()[0] || this[0]).parent; |
| 154 | 0 | parentEl = this.make(root); |
| 155 | } | |
| 156 | ||
| 157 | 0 | if (querying) { |
| 158 | 0 | return parentEl.find(queryString).attr('value'); |
| 159 | } else { | |
| 160 | 0 | parentEl.find(':checked').removeAttr('checked'); |
| 161 | 0 | parentEl.find('input[type=radio][value="' + value + '"]').attr('checked', ''); |
| 162 | 0 | return this; |
| 163 | } | |
| 164 | 0 | break; |
| 165 | default: | |
| 166 | 0 | return querying ? this.attr('value') : this.each(function() { |
| 167 | 0 | this.attr('value', value); |
| 168 | }); | |
| 169 | } | |
| 170 | 0 | return; |
| 171 | case 'select': | |
| 172 | 0 | var option = this.find('option:selected'), |
| 173 | returnValue; | |
| 174 | 0 | if (option === undefined) return undefined; |
| 175 | 0 | if (!querying) { |
| 176 | 0 | if (!this.attr().hasOwnProperty('multiple') && typeof value == 'object') { |
| 177 | 0 | return this; |
| 178 | } | |
| 179 | 0 | if (typeof value != 'object') { |
| 180 | 0 | value = [value]; |
| 181 | } | |
| 182 | 0 | this.find('option').removeAttr('selected'); |
| 183 | 0 | for (var i = 0; i < value.length; i++) { |
| 184 | 0 | this.find('option[value="' + value[i] + '"]').attr('selected', ''); |
| 185 | } | |
| 186 | 0 | return this; |
| 187 | } | |
| 188 | 0 | returnValue = option.attr('value'); |
| 189 | 0 | if (this.attr().hasOwnProperty('multiple')) { |
| 190 | 0 | returnValue = []; |
| 191 | 0 | option.each(function() { |
| 192 | 0 | returnValue.push(this.attr('value')); |
| 193 | }); | |
| 194 | } | |
| 195 | 0 | return returnValue; |
| 196 | case 'option': | |
| 197 | 0 | if (!querying) { |
| 198 | 0 | this.attr('value', value); |
| 199 | 0 | return this; |
| 200 | } | |
| 201 | 0 | return this.attr('value'); |
| 202 | } | |
| 203 | }; | |
| 204 | ||
| 205 | /** | |
| 206 | * Remove an attribute | |
| 207 | */ | |
| 208 | ||
| 209 | 1 | var removeAttribute = function(elem, name) { |
| 210 | 0 | if (!isTag(elem.type) || !elem.attribs || !Object.hasOwnProperty.call(elem.attribs, name)) |
| 211 | 0 | return; |
| 212 | ||
| 213 | 0 | if (rboolean.test(elem.attribs[name])) |
| 214 | 0 | elem.attribs[name] = false; |
| 215 | else | |
| 216 | 0 | delete elem.attribs[name]; |
| 217 | }; | |
| 218 | ||
| 219 | ||
| 220 | 1 | var removeAttr = exports.removeAttr = function(name) { |
| 221 | 0 | this.each(function(i, elem) { |
| 222 | 0 | removeAttribute(elem, name); |
| 223 | }); | |
| 224 | ||
| 225 | 0 | return this; |
| 226 | }; | |
| 227 | ||
| 228 | 1 | var hasClass = exports.hasClass = function(className) { |
| 229 | 0 | return _.any(this, function(elem) { |
| 230 | 0 | var attrs = elem.attribs; |
| 231 | 0 | return attrs && _.contains((attrs['class'] || '').split(rspace), className); |
| 232 | }); | |
| 233 | }; | |
| 234 | ||
| 235 | 1 | var addClass = exports.addClass = function(value) { |
| 236 | // Support functions | |
| 237 | 3616 | if (_.isFunction(value)) { |
| 238 | 0 | this.each(function(i) { |
| 239 | 0 | var className = this.attr('class') || ''; |
| 240 | 0 | this.addClass(value.call(this[0], i, className)); |
| 241 | }); | |
| 242 | } | |
| 243 | ||
| 244 | // Return if no value or not a string or function | |
| 245 | 3620 | if (!value || !_.isString(value)) return this; |
| 246 | ||
| 247 | 3621 | var classNames = value.split(rspace), |
| 248 | numElements = this.length, | |
| 249 | numClasses, | |
| 250 | setClass, | |
| 251 | $elem; | |
| 252 | ||
| 253 | ||
| 254 | 3622 | for (var i = 0; i < numElements; i++) { |
| 255 | 3623 | $elem = this.make(this[i]); |
| 256 | // If selected element isnt a tag, move on | |
| 257 | 3624 | if (!isTag(this[i])) continue; |
| 258 | ||
| 259 | // If we don't already have classes | |
| 260 | 3625 | if (!$elem.attr('class')) { |
| 261 | 3626 | $elem.attr('class', classNames.join(' ').trim()); |
| 262 | } else { | |
| 263 | 0 | setClass = ' ' + $elem.attr('class') + ' '; |
| 264 | 0 | numClasses = classNames.length; |
| 265 | ||
| 266 | // Check if class already exists | |
| 267 | 0 | for (var j = 0; j < numClasses; j++) { |
| 268 | 0 | if (!~setClass.indexOf(' ' + classNames[j] + ' ')) |
| 269 | 0 | setClass += classNames[j] + ' '; |
| 270 | } | |
| 271 | ||
| 272 | 0 | $elem.attr('class', setClass.trim()); |
| 273 | } | |
| 274 | } | |
| 275 | ||
| 276 | 3633 | return this; |
| 277 | }; | |
| 278 | ||
| 279 | 1 | var removeClass = exports.removeClass = function(value) { |
| 280 | 7880 | var split = function(className) { |
| 281 | 15762 | return className ? className.trim().split(rspace) : []; |
| 282 | }; | |
| 283 | 7883 | var classes, removeAll; |
| 284 | ||
| 285 | // Handle if value is a function | |
| 286 | 7886 | if (_.isFunction(value)) { |
| 287 | 0 | return this.each(function(i, el) { |
| 288 | 0 | this.removeClass(value.call(this[0], i, el.attribs['class'] || '')); |
| 289 | }); | |
| 290 | } | |
| 291 | ||
| 292 | 7892 | classes = split(value); |
| 293 | 7893 | removeAll = arguments.length === 0; |
| 294 | ||
| 295 | 7895 | return this.each(function(i, el) { |
| 296 | 7896 | if (!isTag(el)) return; |
| 297 | 7897 | el.attribs.class = removeAll ? |
| 298 | '' : | |
| 299 | _.difference(split(el.attribs.class), classes).join(' '); | |
| 300 | }); | |
| 301 | }; | |
| 302 | ||
| 303 | 1 | var toggleClass = exports.toggleClass = function(value, stateVal) { |
| 304 | // Support functions | |
| 305 | 0 | if (_.isFunction(value)) { |
| 306 | 0 | return this.each(function(i, el) { |
| 307 | 0 | this.toggleClass(value.call(this, i, el.attribs['class'] || '', stateVal), stateVal); |
| 308 | }); | |
| 309 | } | |
| 310 | ||
| 311 | // Return if no value or not a string or function | |
| 312 | 0 | if (!value || !_.isString(value)) return this; |
| 313 | ||
| 314 | 0 | var classNames = value.split(rspace), |
| 315 | numClasses = classNames.length, | |
| 316 | isBool = typeof stateVal === 'boolean', | |
| 317 | numElements = this.length, | |
| 318 | $elem, | |
| 319 | state; | |
| 320 | ||
| 321 | 0 | for (var i = 0; i < numElements; i++) { |
| 322 | 0 | $elem = this.make(this[i]); |
| 323 | // If selected element isnt a tag, move on | |
| 324 | 0 | if (!isTag(this[i])) continue; |
| 325 | ||
| 326 | // Check if class already exists | |
| 327 | 0 | for (var j = 0; j < numClasses; j++) { |
| 328 | // check each className given, space separated list | |
| 329 | 0 | state = isBool ? stateVal : !$elem.hasClass(classNames[j]); |
| 330 | 0 | $elem[state ? 'addClass' : 'removeClass'](classNames[j]); |
| 331 | } | |
| 332 | } | |
| 333 | ||
| 334 | 0 | return this; |
| 335 | }; | |
| 336 | ||
| 337 | 1 | var is = exports.is = function (selector) { |
| 338 | 0 | if (selector) { |
| 339 | 0 | return this.filter(selector).length > 0; |
| 340 | } | |
| 341 | 0 | return false; |
| 342 | }; | |
| 343 | ||
| 344 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | var _ = require('underscore'), |
| 2 | select = require('cheerio-select'), | |
| 3 | utils = require('../utils'), | |
| 4 | isTag = utils.isTag; | |
| 5 | ||
| 6 | 1 | var find = exports.find = function(selector) { |
| 7 | // TODO: Remove the call to _.uniq when the underlying bug in CSSselect has | |
| 8 | // been resolved: | |
| 9 | // https://github.com/fb55/CSSselect/issues/12 | |
| 10 | 32045 | return this.make(_.uniq(select(selector, [].slice.call(this.children())))); |
| 11 | }; | |
| 12 | ||
| 13 | // Get the parent of each element in the current set of matched elements, | |
| 14 | // optionally filtered by a selector. | |
| 15 | 1 | var parent = exports.parent = function(selector) { |
| 16 | 0 | var set = []; |
| 17 | 0 | var $set; |
| 18 | ||
| 19 | 0 | this.each(function(idx, elem) { |
| 20 | 0 | var parentElem = elem.parent; |
| 21 | 0 | if (set.indexOf(parentElem) < 0 && parentElem.type !== 'root') { |
| 22 | 0 | set.push(parentElem); |
| 23 | } | |
| 24 | }); | |
| 25 | ||
| 26 | 0 | $set = this.make(set); |
| 27 | ||
| 28 | 0 | if (arguments.length) { |
| 29 | 0 | $set = $set.filter(selector); |
| 30 | } | |
| 31 | ||
| 32 | 0 | return $set; |
| 33 | }; | |
| 34 | ||
| 35 | 1 | var parents = exports.parents = function(selector) { |
| 36 | 0 | if (this[0] && this[0].parent) { |
| 37 | 0 | return traverseParents(this, this[0].parent, selector, Infinity); |
| 38 | } | |
| 39 | 0 | return this; |
| 40 | }; | |
| 41 | ||
| 42 | // For each element in the set, get the first element that matches the selector | |
| 43 | // by testing the element itself and traversing up through its ancestors in the | |
| 44 | // DOM tree. | |
| 45 | 1 | var closest = exports.closest = function(selector) { |
| 46 | 0 | var set = []; |
| 47 | ||
| 48 | 0 | if (!selector) { |
| 49 | 0 | return this.make(set); |
| 50 | } | |
| 51 | ||
| 52 | 0 | this.each(function(idx, elem) { |
| 53 | 0 | var closestElem = traverseParents(this, elem, selector, 1)[0]; |
| 54 | ||
| 55 | // Do not add duplicate elements to the set | |
| 56 | 0 | if (closestElem && set.indexOf(closestElem) < 0) { |
| 57 | 0 | set.push(closestElem); |
| 58 | } | |
| 59 | }.bind(this)); | |
| 60 | ||
| 61 | 0 | return this.make(set); |
| 62 | }; | |
| 63 | ||
| 64 | 1 | var next = exports.next = function() { |
| 65 | 0 | if (!this[0]) { return this; } |
| 66 | 0 | var elem = this[0]; |
| 67 | 0 | while ((elem = elem.next)) if (isTag(elem)) return this.make(elem); |
| 68 | 0 | return this.make([]); |
| 69 | }; | |
| 70 | ||
| 71 | 1 | var nextAll = exports.nextAll = function(selector) { |
| 72 | 0 | if (!this[0]) { return this; } |
| 73 | 0 | var elems = [], elem = this[0]; |
| 74 | 0 | while ((elem = elem.next)) if (isTag(elem)) elems.push(elem); |
| 75 | 0 | return this.make(selector ? select(selector, elems) : elems); |
| 76 | }; | |
| 77 | ||
| 78 | 1 | var prev = exports.prev = function() { |
| 79 | 0 | if (!this[0]) { return this; } |
| 80 | 0 | var elem = this[0]; |
| 81 | 0 | while ((elem = elem.prev)) if (isTag(elem)) return this.make(elem); |
| 82 | 0 | return this.make([]); |
| 83 | }; | |
| 84 | ||
| 85 | 1 | var prevAll = exports.prevAll = function(selector) { |
| 86 | 0 | if (!this[0]) { return this; } |
| 87 | 0 | var elems = [], elem = this[0]; |
| 88 | 0 | while ((elem = elem.prev)) if (isTag(elem)) elems.push(elem); |
| 89 | 0 | return this.make(selector ? select(selector, elems) : elems); |
| 90 | }; | |
| 91 | ||
| 92 | 1 | var siblings = exports.siblings = function(selector) { |
| 93 | 0 | var elems = _.filter( |
| 94 | this.parent() ? this.parent().children() : this.siblingsAndMe(), | |
| 95 | 0 | function(elem) { return isTag(elem) && !this.is(elem); }, |
| 96 | this | |
| 97 | ); | |
| 98 | 0 | if (selector !== undefined) { |
| 99 | 0 | elems = this.make(select(selector, elems)); |
| 100 | } | |
| 101 | 0 | return this.make(elems); |
| 102 | }; | |
| 103 | ||
| 104 | 1 | var children = exports.children = function(selector) { |
| 105 | ||
| 106 | 32429 | var elems = _.reduce(this, function(memo, elem) { |
| 107 | 32433 | return memo.concat(_.filter(elem.children, isTag)); |
| 108 | }, []); | |
| 109 | ||
| 110 | 64890 | if (selector === undefined) return this.make(elems); |
| 111 | 0 | else if (_.isNumber(selector)) return this.make(elems[selector]); |
| 112 | ||
| 113 | 0 | return this.make(elems).filter(selector); |
| 114 | }; | |
| 115 | ||
| 116 | 1 | var contents = exports.contents = function() { |
| 117 | 0 | return this.make(_.reduce(this, function(all, elem) { |
| 118 | 0 | all.push.apply(all, elem.children); |
| 119 | 0 | return all; |
| 120 | }, [])); | |
| 121 | }; | |
| 122 | ||
| 123 | 1 | var each = exports.each = function(fn) { |
| 124 | 40011 | var i = 0, len = this.length; |
| 125 | 80034 | while (i < len && fn.call(this.make(this[i]), i, this[i]) !== false) ++i; |
| 126 | 40023 | return this; |
| 127 | }; | |
| 128 | ||
| 129 | 1 | var map = exports.map = function(fn) { |
| 130 | 0 | return _.map(this, function(el, i) { |
| 131 | 0 | return fn.call(this.make(el), i, el); |
| 132 | }, this); | |
| 133 | }; | |
| 134 | ||
| 135 | 1 | var filter = exports.filter = function(match) { |
| 136 | 0 | var make = _.bind(this.make, this); |
| 137 | 0 | var filterFn; |
| 138 | ||
| 139 | 0 | if (_.isString(match)) { |
| 140 | 0 | filterFn = function(el) { |
| 141 | 0 | return select(match, el)[0] === el; |
| 142 | }; | |
| 143 | 0 | } else if (_.isFunction(match)) { |
| 144 | 0 | filterFn = function(el, i) { |
| 145 | 0 | return match.call(make(el), i, el); |
| 146 | }; | |
| 147 | 0 | } else if (match.cheerio) { |
| 148 | 0 | filterFn = match.is.bind(match); |
| 149 | } else { | |
| 150 | 0 | filterFn = function(el) { |
| 151 | 0 | return match === el; |
| 152 | }; | |
| 153 | } | |
| 154 | ||
| 155 | 0 | return make(_.filter(this, filterFn)); |
| 156 | }; | |
| 157 | ||
| 158 | 1 | var first = exports.first = function() { |
| 159 | 0 | return this[0] ? this.make(this[0]) : this; |
| 160 | }; | |
| 161 | ||
| 162 | 1 | var last = exports.last = function() { |
| 163 | 0 | return this[0] ? this.make(this[this.length - 1]) : this; |
| 164 | }; | |
| 165 | ||
| 166 | // Reduce the set of matched elements to the one at the specified index. | |
| 167 | 1 | var eq = exports.eq = function(i) { |
| 168 | 0 | i = +i; |
| 169 | 0 | if (i < 0) i = this.length + i; |
| 170 | 0 | return this[i] ? this.make(this[i]) : this.make([]); |
| 171 | }; | |
| 172 | ||
| 173 | 1 | var slice = exports.slice = function() { |
| 174 | 0 | return this.make([].slice.apply(this, arguments)); |
| 175 | }; | |
| 176 | ||
| 177 | 1 | function traverseParents(self, elem, selector, limit) { |
| 178 | 0 | var elems = []; |
| 179 | 0 | while (elems.length < limit && elem.type !== 'root') { |
| 180 | 0 | if (!selector || self.make(elem).filter(selector).length) { |
| 181 | 0 | elems.push(elem); |
| 182 | } | |
| 183 | 0 | elem = elem.parent; |
| 184 | } | |
| 185 | 0 | return self.make(elems); |
| 186 | } | |
| 187 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | var _ = require('underscore'), |
| 2 | parse = require('../parse'), | |
| 3 | $ = require('../static'), | |
| 4 | updateDOM = parse.update, | |
| 5 | evaluate = parse.evaluate, | |
| 6 | encode = require('../utils').encode, | |
| 7 | slice = Array.prototype.slice; | |
| 8 | ||
| 9 | // Create an array of nodes, recursing into arrays and parsing strings if | |
| 10 | // necessary | |
| 11 | 1 | var makeDomArray = function(elem) { |
| 12 | 16290 | if (elem == null) { |
| 13 | 0 | return []; |
| 14 | 16294 | } else if (elem.cheerio) { |
| 15 | 8148 | return elem.toArray(); |
| 16 | 8149 | } else if (_.isArray(elem)) { |
| 17 | 8150 | return _.flatten(elem.map(makeDomArray)); |
| 18 | 0 | } else if (_.isString(elem)) { |
| 19 | 0 | return evaluate(elem); |
| 20 | } else { | |
| 21 | 0 | return [elem]; |
| 22 | } | |
| 23 | }; | |
| 24 | ||
| 25 | 1 | var _insert = function(concatenator) { |
| 26 | 2 | return function() { |
| 27 | 8160 | var elems = slice.call(arguments), |
| 28 | dom = makeDomArray(elems); | |
| 29 | ||
| 30 | 8163 | return this.each(function(i, el) { |
| 31 | 8164 | if (_.isFunction(elems[0])) { |
| 32 | 0 | dom = makeDomArray(elems[0].call(el, i, this.html())); |
| 33 | } | |
| 34 | 8167 | updateDOM(concatenator(dom, el.children || (el.children = [])), el); |
| 35 | }); | |
| 36 | }; | |
| 37 | }; | |
| 38 | ||
| 39 | 1 | var append = exports.append = _insert(function(dom, children) { |
| 40 | 8173 | return children.concat(dom); |
| 41 | }); | |
| 42 | ||
| 43 | 1 | var prepend = exports.prepend = _insert(function(dom, children) { |
| 44 | 0 | return dom.concat(children); |
| 45 | }); | |
| 46 | ||
| 47 | 1 | var after = exports.after = function() { |
| 48 | 0 | var elems = slice.call(arguments), |
| 49 | dom = makeDomArray(elems); | |
| 50 | ||
| 51 | 0 | this.each(function(i, el) { |
| 52 | 0 | var siblings = el.parent.children, |
| 53 | index = siblings.indexOf(el); | |
| 54 | ||
| 55 | // If not found, move on | |
| 56 | 0 | if (!~index) return; |
| 57 | ||
| 58 | 0 | if (_.isFunction(elems[0])) { |
| 59 | 0 | dom = makeDomArray(elems[0].call(el, i)); |
| 60 | } | |
| 61 | ||
| 62 | // Add element after `this` element | |
| 63 | 0 | siblings.splice.apply(siblings, [++index, 0].concat(dom)); |
| 64 | ||
| 65 | // Update next, prev, and parent pointers | |
| 66 | 0 | updateDOM(siblings, el.parent); |
| 67 | 0 | el.parent.children = siblings; |
| 68 | ||
| 69 | }); | |
| 70 | ||
| 71 | 0 | return this; |
| 72 | }; | |
| 73 | ||
| 74 | 1 | var before = exports.before = function() { |
| 75 | 0 | var elems = slice.call(arguments), |
| 76 | dom = makeDomArray(elems); | |
| 77 | ||
| 78 | 0 | this.each(function(i, el) { |
| 79 | 0 | var siblings = el.parent.children, |
| 80 | index = siblings.indexOf(el); | |
| 81 | ||
| 82 | // If not found, move on | |
| 83 | 0 | if (!~index) return; |
| 84 | ||
| 85 | 0 | if (_.isFunction(elems[0])) { |
| 86 | 0 | dom = makeDomArray(elems[0].call(el, i)); |
| 87 | } | |
| 88 | ||
| 89 | // Add element before `el` element | |
| 90 | 0 | siblings.splice.apply(siblings, [index, 0].concat(dom)); |
| 91 | ||
| 92 | // Update next, prev, and parent pointers | |
| 93 | 0 | updateDOM(siblings, el.parent); |
| 94 | 0 | el.parent.children = siblings; |
| 95 | ||
| 96 | }); | |
| 97 | ||
| 98 | 0 | return this; |
| 99 | }; | |
| 100 | ||
| 101 | /* | |
| 102 | remove([selector]) | |
| 103 | */ | |
| 104 | 1 | var remove = exports.remove = function(selector) { |
| 105 | 0 | var elems = this; |
| 106 | ||
| 107 | // Filter if we have selector | |
| 108 | 0 | if (selector) |
| 109 | 0 | elems = elems.filter(selector); |
| 110 | ||
| 111 | 0 | elems.each(function(i, el) { |
| 112 | 0 | var siblings = el.parent.children, |
| 113 | index = siblings.indexOf(el); | |
| 114 | ||
| 115 | 0 | if (!~index) return; |
| 116 | ||
| 117 | 0 | siblings.splice(index, 1); |
| 118 | ||
| 119 | // Update next, prev, and parent pointers | |
| 120 | 0 | updateDOM(siblings, el.parent); |
| 121 | 0 | el.parent.children = siblings; |
| 122 | }); | |
| 123 | ||
| 124 | 0 | return this; |
| 125 | }; | |
| 126 | ||
| 127 | 1 | var replaceWith = exports.replaceWith = function(content) { |
| 128 | 0 | var dom = makeDomArray(content); |
| 129 | ||
| 130 | 0 | this.each(function(i, el) { |
| 131 | 0 | var siblings = el.parent.children, |
| 132 | index = siblings.indexOf(el); | |
| 133 | ||
| 134 | 0 | if (!~index) return; |
| 135 | ||
| 136 | 0 | if (_.isFunction(content)) { |
| 137 | 0 | dom = makeDomArray(content.call(el, i)); |
| 138 | } | |
| 139 | ||
| 140 | 0 | siblings.splice.apply(siblings, [index, 1].concat(dom)); |
| 141 | ||
| 142 | 0 | updateDOM(siblings, el.parent); |
| 143 | 0 | el.parent.children = siblings; |
| 144 | }); | |
| 145 | ||
| 146 | 0 | return this; |
| 147 | }; | |
| 148 | ||
| 149 | 1 | var empty = exports.empty = function() { |
| 150 | 0 | this.each(function(i, el) { |
| 151 | 0 | el.children = []; |
| 152 | }); | |
| 153 | 0 | return this; |
| 154 | }; | |
| 155 | ||
| 156 | /** | |
| 157 | * Set/Get the HTML | |
| 158 | */ | |
| 159 | 1 | var html = exports.html = function(str) { |
| 160 | 0 | if (str === undefined) { |
| 161 | 0 | if (!this[0] || !this[0].children) return null; |
| 162 | 0 | return $.html(this[0].children); |
| 163 | } | |
| 164 | ||
| 165 | 0 | str = str.cheerio ? str.toArray() : evaluate(str); |
| 166 | ||
| 167 | 0 | this.each(function(i, el) { |
| 168 | 0 | el.children = str; |
| 169 | 0 | updateDOM(el.children, el); |
| 170 | }); | |
| 171 | ||
| 172 | 0 | return this; |
| 173 | }; | |
| 174 | ||
| 175 | 1 | var toString = exports.toString = function() { |
| 176 | 0 | return $.html(this); |
| 177 | }; | |
| 178 | ||
| 179 | 1 | var text = exports.text = function(str) { |
| 180 | // If `str` is undefined, act as a "getter" | |
| 181 | 25001 | if (str === undefined) { |
| 182 | 4354 | return $.text(this); |
| 183 | 20653 | } else if (_.isFunction(str)) { |
| 184 | // Function support | |
| 185 | 0 | return this.each(function(i, el) { |
| 186 | 0 | return this.text(str.call(el, i, this.text())); |
| 187 | }); | |
| 188 | } | |
| 189 | ||
| 190 | 20670 | var elem = { |
| 191 | data: encode(str), | |
| 192 | type: 'text', | |
| 193 | parent: null, | |
| 194 | prev: null, | |
| 195 | next: null, | |
| 196 | children: [] | |
| 197 | }; | |
| 198 | ||
| 199 | // Append text node to each selected elements | |
| 200 | 20691 | this.each(function(i, el) { |
| 201 | 20694 | el.children = elem; |
| 202 | 20697 | updateDOM(el.children, el); |
| 203 | }); | |
| 204 | ||
| 205 | 20704 | return this; |
| 206 | }; | |
| 207 | ||
| 208 | 1 | var clone = exports.clone = function() { |
| 209 | // Turn it into HTML, then recreate it, | |
| 210 | // Seems to be the easiest way to reconnect everything correctly | |
| 211 | 8346 | return this.constructor($.html(this)); |
| 212 | }; | |
| 213 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | var _ = require('underscore'); |
| 2 | 1 | var toString = Object.prototype.toString; |
| 3 | ||
| 4 | /** | |
| 5 | * Set / Get css. | |
| 6 | * | |
| 7 | * @param {String|Object} prop | |
| 8 | * @param {String} val | |
| 9 | * @return {self} | |
| 10 | * @api public | |
| 11 | */ | |
| 12 | ||
| 13 | 1 | exports.css = function(prop, val) { |
| 14 | 0 | if (arguments.length === 2 || |
| 15 | // When `prop` is a "plain" object | |
| 16 | (toString.call(prop) === '[object Object]')) { | |
| 17 | 0 | return this.each(function(idx) { |
| 18 | 0 | this._setCss(prop, val, idx); |
| 19 | }); | |
| 20 | } else { | |
| 21 | 0 | return this._getCss(prop); |
| 22 | } | |
| 23 | }; | |
| 24 | ||
| 25 | /** | |
| 26 | * Set styles of all elements. | |
| 27 | * | |
| 28 | * @param {String|Object} prop | |
| 29 | * @param {String} val | |
| 30 | * @param {Number} idx - optional index within the selection | |
| 31 | * @return {self} | |
| 32 | * @api private | |
| 33 | */ | |
| 34 | ||
| 35 | 1 | exports._setCss = function(prop, val, idx) { |
| 36 | 0 | if ('string' == typeof prop) { |
| 37 | 0 | var styles = this._getCss(); |
| 38 | 0 | if (_.isFunction(val)) { |
| 39 | 0 | val = val.call(this[0], idx, this[0]); |
| 40 | } | |
| 41 | ||
| 42 | 0 | if (val === '') { |
| 43 | 0 | delete styles[prop]; |
| 44 | 0 | } else if (val != null) { |
| 45 | 0 | styles[prop] = val; |
| 46 | } | |
| 47 | ||
| 48 | 0 | return this.attr('style', stringify(styles)); |
| 49 | 0 | } else if ('object' == typeof prop) { |
| 50 | 0 | Object.keys(prop).forEach(function(k){ |
| 51 | 0 | this._setCss(k, prop[k]); |
| 52 | }, this); | |
| 53 | 0 | return this; |
| 54 | } | |
| 55 | }; | |
| 56 | ||
| 57 | /** | |
| 58 | * Get parsed styles of the first element. | |
| 59 | * | |
| 60 | * @param {String} prop | |
| 61 | * @return {Object} | |
| 62 | * @api private | |
| 63 | */ | |
| 64 | ||
| 65 | 1 | exports._getCss = function(prop) { |
| 66 | 0 | var styles = parse(this.attr('style')); |
| 67 | 0 | if (typeof prop === 'string') { |
| 68 | 0 | return styles[prop]; |
| 69 | 0 | } else if (_.isArray(prop)) { |
| 70 | 0 | return _.pick(styles, prop); |
| 71 | } else { | |
| 72 | 0 | return styles; |
| 73 | } | |
| 74 | }; | |
| 75 | ||
| 76 | /** | |
| 77 | * Stringify `obj` to styles. | |
| 78 | * | |
| 79 | * @param {Object} obj | |
| 80 | * @return {Object} | |
| 81 | * @api private | |
| 82 | */ | |
| 83 | ||
| 84 | 1 | function stringify(obj) { |
| 85 | 0 | return Object.keys(obj || {}) |
| 86 | .reduce(function(str, prop){ | |
| 87 | 0 | return str += '' |
| 88 | + (str ? ' ' : '') | |
| 89 | + prop | |
| 90 | + ': ' | |
| 91 | + obj[prop] | |
| 92 | + ';'; | |
| 93 | }, ''); | |
| 94 | } | |
| 95 | ||
| 96 | /** | |
| 97 | * Parse `styles`. | |
| 98 | * | |
| 99 | * @param {String} styles | |
| 100 | * @return {Object} | |
| 101 | * @api private | |
| 102 | */ | |
| 103 | ||
| 104 | 1 | function parse(styles) { |
| 105 | 0 | styles = (styles || '').trim(); |
| 106 | ||
| 107 | 0 | if (!styles) return {}; |
| 108 | ||
| 109 | 0 | return styles |
| 110 | .split(/\s*;\s*/) | |
| 111 | .reduce(function(obj, str){ | |
| 112 | 0 | var parts = str.split(/\s*:\s*/); |
| 113 | 0 | if (!parts[0]) return obj; |
| 114 | 0 | obj[parts[0]] = parts[1]; |
| 115 | 0 | return obj; |
| 116 | }, {}); | |
| 117 | } | |
| 118 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | var ElementType = require("domelementtype"); |
| 2 | ||
| 3 | 1 | function DomHandler(callback, options, elementCB){ |
| 4 | 8475 | if(typeof callback === "object"){ |
| 5 | 0 | elementCB = options; |
| 6 | 0 | options = callback; |
| 7 | 0 | callback = null; |
| 8 | 8479 | } else if(typeof options === "function"){ |
| 9 | 0 | elementCB = options; |
| 10 | 0 | options = defaultOpts; |
| 11 | } | |
| 12 | 8483 | this._callback = callback; |
| 13 | 8484 | this._options = options || defaultOpts; |
| 14 | 8485 | this._elementCB = elementCB; |
| 15 | 8486 | this.dom = []; |
| 16 | 8487 | this._done = false; |
| 17 | 8488 | this._tagStack = []; |
| 18 | } | |
| 19 | ||
| 20 | //default options | |
| 21 | 1 | var defaultOpts = { |
| 22 | ignoreWhitespace: false //Keep whitespace-only text nodes | |
| 23 | }; | |
| 24 | ||
| 25 | //Resets the handler back to starting state | |
| 26 | 1 | DomHandler.prototype.onreset = function(){ |
| 27 | 0 | DomHandler.call(this, this._callback, this._options, this._elementCB); |
| 28 | }; | |
| 29 | ||
| 30 | //Signals the handler that parsing is done | |
| 31 | 1 | DomHandler.prototype.onend = function(){ |
| 32 | 8503 | if(this._done) return; |
| 33 | 8504 | this._done = true; |
| 34 | 8505 | this._handleCallback(null); |
| 35 | }; | |
| 36 | ||
| 37 | 1 | DomHandler.prototype._handleCallback = |
| 38 | DomHandler.prototype.onerror = function(error){ | |
| 39 | 8510 | if(typeof this._callback === "function"){ |
| 40 | 0 | this._callback(error, this.dom); |
| 41 | } else { | |
| 42 | 8513 | if(error) throw error; |
| 43 | } | |
| 44 | }; | |
| 45 | ||
| 46 | 1 | DomHandler.prototype.onclosetag = function(name){ |
| 47 | //if(this._tagStack.pop().name !== name) this._handleCallback(Error("Tagname didn't match!")); | |
| 48 | 35011 | var elem = this._tagStack.pop(); |
| 49 | 35015 | if(this._elementCB) this._elementCB(elem); |
| 50 | }; | |
| 51 | ||
| 52 | 1 | DomHandler.prototype._addDomElement = function(element){ |
| 53 | 1373 | var lastTag = this._tagStack[this._tagStack.length - 1]; |
| 54 | ||
| 55 | 1373 | if(lastTag){ |
| 56 | 1368 | lastTag.children.push(element); |
| 57 | } else { //There aren't parent elements | |
| 58 | 5 | this.dom.push(element); |
| 59 | } | |
| 60 | }; | |
| 61 | ||
| 62 | 1 | DomHandler.prototype.onopentag = function(name, attribs){ |
| 63 | 35071 | var lastTag = this._tagStack[this._tagStack.length - 1]; |
| 64 | ||
| 65 | 35079 | var element = { |
| 66 | type: name === "script" ? ElementType.Script : name === "style" ? ElementType.Style : ElementType.Tag, | |
| 67 | name: name, | |
| 68 | attribs: attribs, | |
| 69 | children: [], | |
| 70 | prev: null, | |
| 71 | next: null, | |
| 72 | parent: lastTag || null | |
| 73 | }; | |
| 74 | ||
| 75 | 35119 | if(lastTag){ |
| 76 | 26576 | var idx = lastTag.children.length; |
| 77 | 26579 | while(idx > 0){ |
| 78 | 18406 | if(ElementType.isTag(lastTag.children[--idx])){ |
| 79 | 17600 | element.prev = lastTag.children[idx]; |
| 80 | 17602 | lastTag.children[idx].next = element; |
| 81 | 17604 | break; |
| 82 | } | |
| 83 | } | |
| 84 | 26600 | lastTag.children.push(element); |
| 85 | } else { | |
| 86 | 8557 | this.dom.push(element); |
| 87 | } | |
| 88 | ||
| 89 | 35175 | this._tagStack.push(element); |
| 90 | }; | |
| 91 | ||
| 92 | 1 | DomHandler.prototype.ontext = function(data){ |
| 93 | 1372 | if(this._options.ignoreWhitespace && data.trim() === "") return; |
| 94 | ||
| 95 | 1372 | if(this._tagStack.length){ |
| 96 | 1369 | var lastTag; |
| 97 | ||
| 98 | 1369 | if( |
| 99 | (lastTag = this._tagStack[this._tagStack.length - 1]) && | |
| 100 | (lastTag = lastTag.children[lastTag.children.length - 1]) && | |
| 101 | lastTag.type === ElementType.Text | |
| 102 | ){ | |
| 103 | 1 | lastTag.data += data; |
| 104 | 1 | return; |
| 105 | } | |
| 106 | } else { | |
| 107 | 3 | if(this.dom.length && this.dom[this.dom.length-1].type === ElementType.Text){ |
| 108 | 0 | this.dom[this.dom.length-1].data += data; |
| 109 | 0 | return; |
| 110 | } | |
| 111 | } | |
| 112 | ||
| 113 | 1371 | this._addDomElement({ |
| 114 | data: data, | |
| 115 | type: ElementType.Text | |
| 116 | }); | |
| 117 | }; | |
| 118 | ||
| 119 | 1 | DomHandler.prototype.oncomment = function(data){ |
| 120 | 1 | var lastTag = this._tagStack[this._tagStack.length - 1]; |
| 121 | ||
| 122 | 1 | if(lastTag && lastTag.type === ElementType.Comment){ |
| 123 | 0 | lastTag.data += data; |
| 124 | 0 | return; |
| 125 | } | |
| 126 | ||
| 127 | 1 | var element = { |
| 128 | data: data, | |
| 129 | type: ElementType.Comment | |
| 130 | }; | |
| 131 | ||
| 132 | 1 | this._addDomElement(element); |
| 133 | 1 | this._tagStack.push(element); |
| 134 | }; | |
| 135 | ||
| 136 | 1 | DomHandler.prototype.oncdatastart = function(){ |
| 137 | 0 | var element = { |
| 138 | children: [{ | |
| 139 | data: "", | |
| 140 | type: ElementType.Text | |
| 141 | }], | |
| 142 | type: ElementType.CDATA | |
| 143 | }; | |
| 144 | ||
| 145 | 0 | this._addDomElement(element); |
| 146 | 0 | this._tagStack.push(element); |
| 147 | }; | |
| 148 | ||
| 149 | 1 | DomHandler.prototype.oncommentend = DomHandler.prototype.oncdataend = function(){ |
| 150 | 1 | this._tagStack.pop(); |
| 151 | }; | |
| 152 | ||
| 153 | 1 | DomHandler.prototype.onprocessinginstruction = function(name, data){ |
| 154 | 1 | this._addDomElement({ |
| 155 | name: name, | |
| 156 | data: data, | |
| 157 | type: ElementType.Directive | |
| 158 | }); | |
| 159 | }; | |
| 160 | ||
| 161 | 1 | module.exports = DomHandler; |
| Line | Hits | Source |
|---|---|---|
| 1 | //Types of elements found in the DOM | |
| 2 | 1 | module.exports = { |
| 3 | Text: "text", //Text | |
| 4 | Directive: "directive", //<? ... ?> | |
| 5 | Comment: "comment", //<!-- ... --> | |
| 6 | Script: "script", //<script> tags | |
| 7 | Style: "style", //<style> tags | |
| 8 | Tag: "tag", //Any tag | |
| 9 | CDATA: "cdata", //<![CDATA[ ... ]]> | |
| 10 | ||
| 11 | isTag: function(elem){ | |
| 12 | 18621 | return elem.type === "tag" || elem.type === "script" || elem.type === "style"; |
| 13 | } | |
| 14 | }; |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | var Tokenizer = require("c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/htmlparser2/lib/./Tokenizer.js"); |
| 2 | ||
| 3 | /* | |
| 4 | Options: | |
| 5 | ||
| 6 | xmlMode: Special behavior for script/style tags (true by default) | |
| 7 | lowerCaseAttributeNames: call .toLowerCase for each attribute name (true if xmlMode is `false`) | |
| 8 | lowerCaseTags: call .toLowerCase for each tag name (true if xmlMode is `false`) | |
| 9 | */ | |
| 10 | ||
| 11 | /* | |
| 12 | Callbacks: | |
| 13 | ||
| 14 | oncdataend, | |
| 15 | oncdatastart, | |
| 16 | onclosetag, | |
| 17 | oncomment, | |
| 18 | oncommentend, | |
| 19 | onerror, | |
| 20 | onopentag, | |
| 21 | onprocessinginstruction, | |
| 22 | onreset, | |
| 23 | ontext | |
| 24 | */ | |
| 25 | ||
| 26 | 1 | var formTags = { |
| 27 | input: true, | |
| 28 | option: true, | |
| 29 | optgroup: true, | |
| 30 | select: true, | |
| 31 | button: true, | |
| 32 | datalist: true, | |
| 33 | textarea: true | |
| 34 | }; | |
| 35 | 1 | var openImpliesClose = { |
| 36 | tr : { tr:true, th:true, td:true }, | |
| 37 | th : { th:true }, | |
| 38 | td : { thead:true, td:true }, | |
| 39 | body : { head:true, link:true, script:true }, | |
| 40 | li : { li:true }, | |
| 41 | p : { p:true }, | |
| 42 | select : formTags, | |
| 43 | input : formTags, | |
| 44 | output : formTags, | |
| 45 | button : formTags, | |
| 46 | datalist: formTags, | |
| 47 | textarea: formTags, | |
| 48 | option : { option:true }, | |
| 49 | optgroup: { optgroup:true } | |
| 50 | }; | |
| 51 | ||
| 52 | 1 | var voidElements = { |
| 53 | __proto__: null, | |
| 54 | area: true, | |
| 55 | base: true, | |
| 56 | basefont: true, | |
| 57 | br: true, | |
| 58 | col: true, | |
| 59 | command: true, | |
| 60 | embed: true, | |
| 61 | frame: true, | |
| 62 | hr: true, | |
| 63 | img: true, | |
| 64 | input: true, | |
| 65 | isindex: true, | |
| 66 | keygen: true, | |
| 67 | link: true, | |
| 68 | meta: true, | |
| 69 | param: true, | |
| 70 | source: true, | |
| 71 | track: true, | |
| 72 | wbr: true | |
| 73 | }; | |
| 74 | ||
| 75 | 1 | function Parser(cbs, options){ |
| 76 | 8726 | this._options = options || {}; |
| 77 | 8727 | this._cbs = cbs || {}; |
| 78 | ||
| 79 | 8729 | this._tagname = ""; |
| 80 | 8730 | this._attribname = ""; |
| 81 | 8731 | this._attribs = null; |
| 82 | 8732 | this._stack = []; |
| 83 | 8733 | this._done = false; |
| 84 | ||
| 85 | 8735 | this._tokenizer = new Tokenizer(options, this); |
| 86 | } | |
| 87 | ||
| 88 | 1 | require("util").inherits(Parser, require("events").EventEmitter); |
| 89 | ||
| 90 | //Tokenizer event handlers | |
| 91 | 1 | Parser.prototype.ontext = function(data){ |
| 92 | 2832 | if(this._cbs.ontext) this._cbs.ontext(data); |
| 93 | }; | |
| 94 | ||
| 95 | 1 | Parser.prototype.onopentagname = function(name){ |
| 96 | 35949 | if(!(this._options.xmlMode || "lowerCaseTags" in this._options) || this._options.lowerCaseTags){ |
| 97 | 35953 | name = name.toLowerCase(); |
| 98 | } | |
| 99 | ||
| 100 | 35965 | this._tagname = name; |
| 101 | ||
| 102 | 35973 | if (!this._options.xmlMode && name in openImpliesClose) { |
| 103 | 35084 | for( |
| 104 | var el; | |
| 105 | (el = this._stack[this._stack.length-1]) in openImpliesClose[name]; | |
| 106 | this.onclosetag(el) | |
| 107 | ); | |
| 108 | } | |
| 109 | ||
| 110 | 36005 | if(this._options.xmlMode || !(name in voidElements)){ |
| 111 | 36009 | this._stack.push(name); |
| 112 | } | |
| 113 | ||
| 114 | 36021 | if(this._cbs.onopentagname) this._cbs.onopentagname(name); |
| 115 | 72050 | if(this._cbs.onopentag) this._attribs = {}; |
| 116 | }; | |
| 117 | ||
| 118 | 1 | Parser.prototype.onopentagend = function(){ |
| 119 | 36041 | if(this._attribname !== "") this.onattribvalue(""); |
| 120 | 36045 | if(this._attribs){ |
| 121 | 72098 | if(this._cbs.onopentag) this._cbs.onopentag(this._tagname, this._attribs); |
| 122 | 36053 | this._attribs = null; |
| 123 | } | |
| 124 | 36061 | if(!this._options.xmlMode && this._cbs.onclosetag && this._tagname in voidElements){ |
| 125 | 0 | this._cbs.onclosetag(this._tagname); |
| 126 | } | |
| 127 | 36073 | this._tagname = ""; |
| 128 | }; | |
| 129 | ||
| 130 | 1 | Parser.prototype.onclosetag = function(name){ |
| 131 | 36089 | if(!(this._options.xmlMode || "lowerCaseTags" in this._options) || this._options.lowerCaseTags){ |
| 132 | 36093 | name = name.toLowerCase(); |
| 133 | } | |
| 134 | 36101 | if(this._stack.length && (!(name in voidElements) || this._options.xmlMode)){ |
| 135 | 36105 | var pos = this._stack.lastIndexOf(name); |
| 136 | 36109 | if(pos !== -1){ |
| 137 | 36113 | if(this._cbs.onclosetag){ |
| 138 | 36117 | pos = this._stack.length - pos; |
| 139 | 72242 | while(pos--) this._cbs.onclosetag(this._stack.pop()); |
| 140 | } | |
| 141 | 0 | else this._stack.splice(pos); |
| 142 | 0 | } else if(name === "p" && !this._options.xmlMode){ |
| 143 | 0 | this.onopentagname(name); |
| 144 | 0 | this.onselfclosingtag(); |
| 145 | } | |
| 146 | 0 | } else if(!this._options.xmlMode && (name === "br" || name === "p")){ |
| 147 | 0 | this.onopentagname(name); |
| 148 | 0 | this.onselfclosingtag(); |
| 149 | } | |
| 150 | }; | |
| 151 | ||
| 152 | 1 | Parser.prototype.onselfclosingtag = function(){ |
| 153 | 0 | var name = this._tagname; |
| 154 | ||
| 155 | 0 | this.onopentagend(); |
| 156 | ||
| 157 | //self-closing tags will be on the top of the stack | |
| 158 | //(cheaper check than in onclosetag) | |
| 159 | 0 | if(this._stack[this._stack.length-1] === name){ |
| 160 | 0 | if(this._cbs.onclosetag){ |
| 161 | 0 | this._cbs.onclosetag(name); |
| 162 | } | |
| 163 | 0 | this._stack.pop(); |
| 164 | } | |
| 165 | }; | |
| 166 | ||
| 167 | 1 | Parser.prototype.onattribname = function(name){ |
| 168 | 35790 | if(this._attribname !== "") this.onattribvalue(""); |
| 169 | 35794 | if(!(this._options.xmlMode || "lowerCaseAttributeNames" in this._options) || this._options.lowerCaseAttributeNames){ |
| 170 | 35798 | name = name.toLowerCase(); |
| 171 | } | |
| 172 | 35806 | this._attribname = name; |
| 173 | }; | |
| 174 | ||
| 175 | 1 | Parser.prototype.onattribvalue = function attribValue(value){ |
| 176 | 35822 | if(this._cbs.onattribute) this._cbs.onattribute(this._attribname, value); |
| 177 | 71652 | if(this._attribs) this._attribs[this._attribname] = value; |
| 178 | 35830 | this._attribname = ""; |
| 179 | }; | |
| 180 | ||
| 181 | 1 | Parser.prototype.ondeclaration = function(value){ |
| 182 | 1 | if(this._cbs.onprocessinginstruction){ |
| 183 | 1 | var name = value.split(/\s|\//, 1)[0]; |
| 184 | 1 | if(!(this._options.xmlMode || "lowerCaseTags" in this._options) || this._options.lowerCaseTags){ |
| 185 | 1 | name = name.toLowerCase(); |
| 186 | } | |
| 187 | 1 | this._cbs.onprocessinginstruction("!" + name, "!" + value); |
| 188 | } | |
| 189 | }; | |
| 190 | ||
| 191 | 1 | Parser.prototype.onprocessinginstruction = function(value){ |
| 192 | 0 | if(this._cbs.onprocessinginstruction){ |
| 193 | 0 | var name = value.split(/\s|\//, 1)[0]; |
| 194 | 0 | if(!(this._options.xmlMode || "lowerCaseTags" in this._options) || this._options.lowerCaseTags){ |
| 195 | 0 | name = name.toLowerCase(); |
| 196 | } | |
| 197 | 0 | this._cbs.onprocessinginstruction("?" + name, "?" + value); |
| 198 | } | |
| 199 | }; | |
| 200 | ||
| 201 | 1 | Parser.prototype.oncomment = function(value){ |
| 202 | 2 | if(this._cbs.oncomment) this._cbs.oncomment(value); |
| 203 | 2 | if(this._cbs.oncommentend) this._cbs.oncommentend(); |
| 204 | }; | |
| 205 | ||
| 206 | 1 | Parser.prototype.oncdata = function(value){ |
| 207 | 0 | if(this._options.xmlMode){ |
| 208 | 0 | if(this._cbs.oncdatastart) this._cbs.oncdatastart(); |
| 209 | 0 | if(this._cbs.ontext) this._cbs.ontext(value); |
| 210 | 0 | if(this._cbs.oncdataend) this._cbs.oncdataend(); |
| 211 | } else { | |
| 212 | 0 | this.oncomment("[CDATA[" + value + "]]"); |
| 213 | } | |
| 214 | }; | |
| 215 | ||
| 216 | 1 | Parser.prototype.onerror = function(err){ |
| 217 | 0 | if(this._cbs.onerror) this._cbs.onerror(err); |
| 218 | }; | |
| 219 | ||
| 220 | 1 | Parser.prototype.onend = function(){ |
| 221 | 8871 | if(this._cbs.onclosetag){ |
| 222 | 8872 | for( |
| 223 | var i = this._stack.length; | |
| 224 | i > 0; | |
| 225 | this._cbs.onclosetag(this._stack[--i]) | |
| 226 | ); | |
| 227 | } | |
| 228 | 17756 | if(this._cbs.onend) this._cbs.onend(); |
| 229 | }; | |
| 230 | ||
| 231 | ||
| 232 | //Resets the parser to a blank state, ready to parse a new HTML document | |
| 233 | 1 | Parser.prototype.reset = function(){ |
| 234 | 0 | if(this._cbs.onreset) this._cbs.onreset(); |
| 235 | 0 | this._tokenizer.reset(); |
| 236 | ||
| 237 | 0 | this._tagname = ""; |
| 238 | 0 | this._attribname = ""; |
| 239 | 0 | this._attribs = null; |
| 240 | 0 | this._stack = []; |
| 241 | 0 | this._done = false; |
| 242 | }; | |
| 243 | ||
| 244 | //Parses a complete HTML document and pushes it to the handler | |
| 245 | 1 | Parser.prototype.parseComplete = function(data){ |
| 246 | 0 | this.reset(); |
| 247 | 0 | this.end(data); |
| 248 | }; | |
| 249 | ||
| 250 | 1 | Parser.prototype.write = function(chunk){ |
| 251 | 8901 | if(this._done) this.onerror(Error(".write() after done!")); |
| 252 | 8902 | this._tokenizer.write(chunk); |
| 253 | }; | |
| 254 | ||
| 255 | 1 | Parser.prototype.end = function(chunk){ |
| 256 | 8906 | if(this._done) this.onerror(Error(".end() after done!")); |
| 257 | 8907 | this._tokenizer.end(chunk); |
| 258 | 8908 | this._done = true; |
| 259 | }; | |
| 260 | ||
| 261 | //alias for backwards compat | |
| 262 | 1 | Parser.prototype.parseChunk = Parser.prototype.write; |
| 263 | 1 | Parser.prototype.done = Parser.prototype.end; |
| 264 | ||
| 265 | 1 | module.exports = Parser; |
| 266 |
| Line | Hits | Source |
|---|---|---|
| 1 | 1 | module.exports = Tokenizer; |
| 2 | ||
| 3 | 1 | var i = 0, |
| 4 | ||
| 5 | TEXT = i++, | |
| 6 | BEFORE_TAG_NAME = i++, //after < | |
| 7 | IN_TAG_NAME = i++, | |
| 8 | BEFORE_CLOSING_TAG_NAME = i++, | |
| 9 | IN_CLOSING_TAG_NAME = i++, | |
| 10 | AFTER_CLOSING_TAG_NAME = i++, | |
| 11 | ||
| 12 | //attributes | |
| 13 | BEFORE_ATTRIBUTE_NAME = i++, | |
| 14 | IN_ATTRIBUTE_NAME = i++, | |
| 15 | AFTER_ATTRIBUTE_NAME = i++, | |
| 16 | BEFORE_ATTRIBUTE_VALUE = i++, | |
| 17 | IN_ATTRIBUTE_VALUE_DOUBLE_QUOTES = i++, // " | |
| 18 | IN_ATTRIBUTE_VALUE_SINGLE_QUOTES = i++, // ' | |
| 19 | IN_ATTRIBUTE_VALUE_NO_QUOTES = i++, | |
| 20 | ||
| 21 | //declarations | |
| 22 | BEFORE_DECLARATION = i++, // ! | |
| 23 | IN_DECLARATION = i++, | |
| 24 | ||
| 25 | //processing instructions | |
| 26 | IN_PROCESSING_INSTRUCTION = i++, // ? | |
| 27 | ||
| 28 | //comments | |
| 29 | BEFORE_COMMENT = i++, | |
| 30 | IN_COMMENT = i++, | |
| 31 | AFTER_COMMENT_1 = i++, | |
| 32 | AFTER_COMMENT_2 = i++, | |
| 33 | ||
| 34 | //cdata | |
| 35 | BEFORE_CDATA_1 = i++, // [ | |
| 36 | BEFORE_CDATA_2 = i++, // C | |
| 37 | BEFORE_CDATA_3 = i++, // D | |
| 38 | BEFORE_CDATA_4 = i++, // A | |
| 39 | BEFORE_CDATA_5 = i++, // T | |
| 40 | BEFORE_CDATA_6 = i++, // A | |
| 41 | IN_CDATA = i++,// [ | |
| 42 | AFTER_CDATA_1 = i++, // ] | |
| 43 | AFTER_CDATA_2 = i++, // ] | |
| 44 | ||
| 45 | //special tags | |
| 46 | BEFORE_SPECIAL = i++, //S | |
| 47 | BEFORE_SPECIAL_END = i++, //S | |
| 48 | ||
| 49 | BEFORE_SCRIPT_1 = i++, //C | |
| 50 | BEFORE_SCRIPT_2 = i++, //R | |
| 51 | BEFORE_SCRIPT_3 = i++, //I | |
| 52 | BEFORE_SCRIPT_4 = i++, //P | |
| 53 | BEFORE_SCRIPT_5 = i++, //T | |
| 54 | AFTER_SCRIPT_1 = i++, //C | |
| 55 | AFTER_SCRIPT_2 = i++, //R | |
| 56 | AFTER_SCRIPT_3 = i++, //I | |
| 57 | AFTER_SCRIPT_4 = i++, //P | |
| 58 | AFTER_SCRIPT_5 = i++, //T | |
| 59 | ||
| 60 | BEFORE_STYLE_1 = i++, //T | |
| 61 | BEFORE_STYLE_2 = i++, //Y | |
| 62 | BEFORE_STYLE_3 = i++, //L | |
| 63 | BEFORE_STYLE_4 = i++, //E | |
| 64 | AFTER_STYLE_1 = i++, //T | |
| 65 | AFTER_STYLE_2 = i++, //Y | |
| 66 | AFTER_STYLE_3 = i++, //L | |
| 67 | AFTER_STYLE_4 = i++; //E | |
| 68 | ||
| 69 | ||
| 70 | 1 | function whitespace(c){ |
| 71 | 368945 | return c === " " || c === "\t" || c === "\r" || c === "\n"; |
| 72 | } | |
| 73 | ||
| 74 | 1 | function Tokenizer(options, cbs){ |
| 75 | 8993 | this._state = TEXT; |
| 76 | 8994 | this._buffer = ""; |
| 77 | 8995 | this._sectionStart = 0; |
| 78 | 8996 | this._index = 0; |
| 79 | 8997 | this._options = options; |
| 80 | 8998 | this._special = 0; // 1 for script, 2 for style |
| 81 | 8999 | this._cbs = cbs; |
| 82 | 9000 | this._running = true; |
| 83 | } | |
| 84 | ||
| 85 | //TODO make events conditional | |
| 86 | 1 | Tokenizer.prototype.write = function(chunk){ |
| 87 | 9005 | this._buffer += chunk; |
| 88 | ||
| 89 | 9007 | while(this._index < this._buffer.length && this._running){ |
| 90 | 901553 | var c = this._buffer.charAt(this._index); |
| 91 | 901647 | if(this._state === TEXT){ |
| 92 | 107350 | if(c === "<"){ |
| 93 | 74051 | this._emitIfToken("ontext"); |
| 94 | 74059 | this._state = BEFORE_TAG_NAME; |
| 95 | 74067 | this._sectionStart = this._index; |
| 96 | } | |
| 97 | 794821 | } else if(this._state === BEFORE_TAG_NAME){ |
| 98 | 74091 | if(c === "/"){ |
| 99 | 37048 | this._state = BEFORE_CLOSING_TAG_NAME; |
| 100 | 37055 | } else if(c === ">" || this._special > 0) { |
| 101 | 1 | this._state = TEXT; |
| 102 | } else { | |
| 103 | 37066 | if(whitespace(c)); |
| 104 | 37070 | else if(c === "!"){ |
| 105 | 2 | this._state = BEFORE_DECLARATION; |
| 106 | 2 | this._sectionStart = this._index + 1; |
| 107 | 37080 | } else if(c === "?"){ |
| 108 | 0 | this._state = IN_PROCESSING_INSTRUCTION; |
| 109 | 0 | this._sectionStart = this._index + 1; |
| 110 | 37092 | } else if( |
| 111 | !(this._options && this._options.xmlMode) && | |
| 112 | (c === "s" || c === "S") | |
| 113 | ){ | |
| 114 | 191 | this._state = BEFORE_SPECIAL; |
| 115 | 191 | this._sectionStart = this._index; |
| 116 | } else { | |
| 117 | 36929 | this._state = IN_TAG_NAME; |
| 118 | 36933 | this._sectionStart = this._index; |
| 119 | } | |
| 120 | } | |
| 121 | 722610 | } else if(this._state === IN_TAG_NAME){ |
| 122 | 75569 | if(c === "/"){ |
| 123 | 0 | this._emitToken("onopentagname"); |
| 124 | 0 | this._cbs.onselfclosingtag(); |
| 125 | 0 | this._state = AFTER_CLOSING_TAG_NAME; |
| 126 | 75601 | } else if(c === ">"){ |
| 127 | 455 | this._emitToken("onopentagname"); |
| 128 | 455 | this._cbs.onopentagend(); |
| 129 | 455 | this._state = TEXT; |
| 130 | 455 | this._sectionStart = this._index + 1; |
| 131 | 75186 | } else if(whitespace(c)){ |
| 132 | 36725 | this._emitToken("onopentagname"); |
| 133 | 36729 | this._state = BEFORE_ATTRIBUTE_NAME; |
| 134 | } | |
| 135 | 648029 | } else if(this._state === BEFORE_CLOSING_TAG_NAME){ |
| 136 | 37196 | if(whitespace(c)); |
| 137 | 37200 | else if(c === ">"){ |
| 138 | 0 | this._state = TEXT; |
| 139 | 37208 | } else if(this._special > 0){ |
| 140 | 2 | if(c === "s" || c === "S"){ |
| 141 | 2 | this._state = BEFORE_SPECIAL_END; |
| 142 | } else { | |
| 143 | 0 | this._state = TEXT; |
| 144 | 0 | continue; |
| 145 | } | |
| 146 | } else { | |
| 147 | 37238 | this._state = IN_CLOSING_TAG_NAME; |
| 148 | 37242 | this._sectionStart = this._index; |
| 149 | } | |
| 150 | 611827 | } else if(this._state === IN_CLOSING_TAG_NAME){ |
| 151 | 75801 | if(c === ">"){ |
| 152 | 37260 | this._emitToken("onclosetag"); |
| 153 | 37264 | this._state = TEXT; |
| 154 | 37268 | this._sectionStart = this._index + 1; |
| 155 | 37272 | this._special = 0; |
| 156 | 38565 | } else if(whitespace(c)){ |
| 157 | 0 | this._emitToken("onclosetag"); |
| 158 | 0 | this._state = AFTER_CLOSING_TAG_NAME; |
| 159 | 0 | this._special = 0; |
| 160 | } | |
| 161 | 536672 | } else if(this._state === AFTER_CLOSING_TAG_NAME){ |
| 162 | //skip everything until ">" | |
| 163 | 0 | if(c === ">"){ |
| 164 | 0 | this._state = TEXT; |
| 165 | 0 | this._sectionStart = this._index + 1; |
| 166 | } | |
| 167 | } | |
| 168 | ||
| 169 | /* | |
| 170 | * attributes | |
| 171 | */ | |
| 172 | 537310 | else if(this._state === BEFORE_ATTRIBUTE_NAME){ |
| 173 | 73780 | if(c === ">"){ |
| 174 | 36893 | this._state = TEXT; |
| 175 | 36897 | this._cbs.onopentagend(); |
| 176 | 36901 | this._sectionStart = this._index + 1; |
| 177 | 36907 | } else if(c === "/"){ |
| 178 | 0 | this._cbs.onselfclosingtag(); |
| 179 | 0 | this._state = AFTER_CLOSING_TAG_NAME; |
| 180 | 36919 | } else if(!whitespace(c)){ |
| 181 | 36922 | this._state = IN_ATTRIBUTE_NAME; |
| 182 | 36926 | this._sectionStart = this._index; |
| 183 | } | |
| 184 | 464138 | } else if(this._state === IN_ATTRIBUTE_NAME){ |
| 185 | 184419 | if(c === "="){ |
| 186 | 36942 | this._emitIfToken("onattribname"); |
| 187 | 36946 | this._state = BEFORE_ATTRIBUTE_VALUE; |
| 188 | 147529 | } else if(whitespace(c)){ |
| 189 | 0 | this._emitIfToken("onattribname"); |
| 190 | 0 | this._state = AFTER_ATTRIBUTE_NAME; |
| 191 | 147577 | } else if(c === "/" || c === ">"){ |
| 192 | 0 | this._emitIfToken("onattribname"); |
| 193 | 0 | this._state = BEFORE_ATTRIBUTE_NAME; |
| 194 | 0 | continue; |
| 195 | } | |
| 196 | 280099 | } else if(this._state === AFTER_ATTRIBUTE_NAME){ |
| 197 | 0 | if(c === "="){ |
| 198 | 0 | this._state = BEFORE_ATTRIBUTE_VALUE; |
| 199 | 0 | } else if(c === "/" || c === ">"){ |
| 200 | 0 | this._state = BEFORE_ATTRIBUTE_NAME; |
| 201 | 0 | continue; |
| 202 | 0 | } else if(!whitespace(c)){ |
| 203 | 0 | this._state = IN_ATTRIBUTE_NAME; |
| 204 | 0 | this._sectionStart = this._index; |
| 205 | } | |
| 206 | 280399 | } else if(this._state === BEFORE_ATTRIBUTE_VALUE){ |
| 207 | 37026 | if(c === "\""){ |
| 208 | 37030 | this._state = IN_ATTRIBUTE_VALUE_DOUBLE_QUOTES; |
| 209 | 37034 | this._sectionStart = this._index + 1; |
| 210 | 0 | } else if(c === "'"){ |
| 211 | 0 | this._state = IN_ATTRIBUTE_VALUE_SINGLE_QUOTES; |
| 212 | 0 | this._sectionStart = this._index + 1; |
| 213 | 0 | } else if(!whitespace(c)){ |
| 214 | 0 | this._state = IN_ATTRIBUTE_VALUE_NO_QUOTES; |
| 215 | 0 | this._sectionStart = this._index; |
| 216 | } | |
| 217 | 243663 | } else if(this._state === IN_ATTRIBUTE_VALUE_DOUBLE_QUOTES){ |
| 218 | 242116 | if(c === "\""){ |
| 219 | 37074 | this._emitToken("onattribvalue"); |
| 220 | 37078 | this._state = BEFORE_ATTRIBUTE_NAME; |
| 221 | } | |
| 222 | 1573 | } else if(this._state === IN_ATTRIBUTE_VALUE_SINGLE_QUOTES){ |
| 223 | 0 | if(c === "'"){ |
| 224 | 0 | this._state = BEFORE_ATTRIBUTE_NAME; |
| 225 | 0 | this._emitToken("onattribvalue"); |
| 226 | } | |
| 227 | 1573 | } else if(this._state === IN_ATTRIBUTE_VALUE_NO_QUOTES){ |
| 228 | 0 | if(c === ">"){ |
| 229 | 0 | this._emitToken("onattribvalue"); |
| 230 | 0 | this._state = TEXT; |
| 231 | 0 | this._cbs.onopentagend(); |
| 232 | 0 | this._sectionStart = this._index + 1; |
| 233 | 0 | } else if(whitespace(c)){ |
| 234 | 0 | this._emitToken("onattribvalue"); |
| 235 | 0 | this._state = BEFORE_ATTRIBUTE_NAME; |
| 236 | } | |
| 237 | } | |
| 238 | ||
| 239 | /* | |
| 240 | * declarations | |
| 241 | */ | |
| 242 | 1573 | else if(this._state === BEFORE_DECLARATION){ |
| 243 | 2 | if(c === "[") this._state = BEFORE_CDATA_1; |
| 244 | 3 | else if(c === "-") this._state = BEFORE_COMMENT; |
| 245 | 1 | else this._state = IN_DECLARATION; |
| 246 | 1571 | } else if(this._state === IN_DECLARATION){ |
| 247 | 12 | if(c === ">"){ |
| 248 | 1 | this._emitToken("ondeclaration"); |
| 249 | 1 | this._state = TEXT; |
| 250 | 1 | this._sectionStart = this._index + 1; |
| 251 | } | |
| 252 | } | |
| 253 | ||
| 254 | /* | |
| 255 | * processing instructions | |
| 256 | */ | |
| 257 | 1559 | else if(this._state === IN_PROCESSING_INSTRUCTION){ |
| 258 | 0 | if(c === ">"){ |
| 259 | 0 | this._emitToken("onprocessinginstruction"); |
| 260 | 0 | this._state = TEXT; |
| 261 | 0 | this._sectionStart = this._index + 1; |
| 262 | } | |
| 263 | } | |
| 264 | ||
| 265 | /* | |
| 266 | * comments | |
| 267 | */ | |
| 268 | 1559 | else if(this._state === BEFORE_COMMENT){ |
| 269 | 1 | if(c === "-"){ |
| 270 | 1 | this._state = IN_COMMENT; |
| 271 | 1 | this._sectionStart = this._index + 1; |
| 272 | } else { | |
| 273 | 0 | this._state = IN_DECLARATION; |
| 274 | } | |
| 275 | 1558 | } else if(this._state === IN_COMMENT){ |
| 276 | 1346 | if(c === "-") this._state = AFTER_COMMENT_1; |
| 277 | 215 | } else if(this._state === AFTER_COMMENT_1){ |
| 278 | 4 | if(c === "-") this._state = AFTER_COMMENT_2; |
| 279 | 2 | else this._state = IN_COMMENT; |
| 280 | 212 | } else if(this._state === AFTER_COMMENT_2){ |
| 281 | 1 | if(c === ">"){ |
| 282 | //remove 2 trailing chars | |
| 283 | 1 | this._cbs.oncomment(this._buffer.substring(this._sectionStart, this._index - 2)); |
| 284 | 1 | this._state = TEXT; |
| 285 | 1 | this._sectionStart = this._index + 1; |
| 286 | 0 | } else if (c !== "-") { |
| 287 | 0 | this._state = IN_COMMENT; |
| 288 | } | |
| 289 | // else: stay in AFTER_COMMENT_2 (`--->`) | |
| 290 | } | |
| 291 | ||
| 292 | /* | |
| 293 | * cdata | |
| 294 | */ | |
| 295 | 211 | else if(this._state === BEFORE_CDATA_1){ |
| 296 | 0 | if(c === "C") this._state = BEFORE_CDATA_2; |
| 297 | 0 | else this._state = IN_DECLARATION; |
| 298 | 211 | } else if(this._state === BEFORE_CDATA_2){ |
| 299 | 0 | if(c === "D") this._state = BEFORE_CDATA_3; |
| 300 | 0 | else this._state = IN_DECLARATION; |
| 301 | 211 | } else if(this._state === BEFORE_CDATA_3){ |
| 302 | 0 | if(c === "A") this._state = BEFORE_CDATA_4; |
| 303 | 0 | else this._state = IN_DECLARATION; |
| 304 | 211 | } else if(this._state === BEFORE_CDATA_4){ |
| 305 | 0 | if(c === "T") this._state = BEFORE_CDATA_5; |
| 306 | 0 | else this._state = IN_DECLARATION; |
| 307 | 211 | } else if(this._state === BEFORE_CDATA_5){ |
| 308 | 0 | if(c === "A") this._state = BEFORE_CDATA_6; |
| 309 | 0 | else this._state = IN_DECLARATION; |
| 310 | 211 | } else if(this._state === BEFORE_CDATA_6){ |
| 311 | 0 | if(c === "["){ |
| 312 | 0 | this._state = IN_CDATA; |
| 313 | 0 | this._sectionStart = this._index + 1; |
| 314 | } else { | |
| 315 | 0 | this._state = IN_DECLARATION; |
| 316 | } | |
| 317 | 211 | } else if(this._state === IN_CDATA){ |
| 318 | 0 | if(c === "]") this._state = AFTER_CDATA_1; |
| 319 | 211 | } else if(this._state === AFTER_CDATA_1){ |
| 320 | 0 | if(c === "]") this._state = AFTER_CDATA_2; |
| 321 | 0 | else this._state = IN_CDATA; |
| 322 | 211 | } else if(this._state === AFTER_CDATA_2){ |
| 323 | 0 | if(c === ">"){ |
| 324 | //remove 2 trailing chars | |
| 325 | 0 | this._cbs.oncdata(this._buffer.substring(this._sectionStart, this._index - 2)); |
| 326 | 0 | this._state = TEXT; |
| 327 | 0 | this._sectionStart = this._index + 1; |
| 328 | 0 | } else if (c !== "]") { |
| 329 | 0 | this._state = IN_CDATA; |
| 330 | } | |
| 331 | //else: stay in AFTER_CDATA_2 (`]]]>`) | |
| 332 | } | |
| 333 | ||
| 334 | /* | |
| 335 | * special tags | |
| 336 | */ | |
| 337 | 211 | else if(this._state === BEFORE_SPECIAL){ |
| 338 | 191 | if(c === "c" || c === "C"){ |
| 339 | 1 | this._state = BEFORE_SCRIPT_1; |
| 340 | 190 | } else if(c === "t" || c === "T"){ |
| 341 | 1 | this._state = BEFORE_STYLE_1; |
| 342 | } else { | |
| 343 | 189 | this._state = IN_TAG_NAME; |
| 344 | 189 | continue; //consume the token again |
| 345 | } | |
| 346 | 20 | } else if(this._state === BEFORE_SPECIAL_END){ |
| 347 | 2 | if(this._special === 1 && (c === "c" || c === "C")){ |
| 348 | 1 | this._state = AFTER_SCRIPT_1; |
| 349 | 1 | } else if(this._special === 2 && (c === "t" || c === "T")){ |
| 350 | 1 | this._state = AFTER_STYLE_1; |
| 351 | } | |
| 352 | 0 | else this._state = TEXT; |
| 353 | } | |
| 354 | ||
| 355 | /* | |
| 356 | * script | |
| 357 | */ | |
| 358 | 18 | else if(this._state === BEFORE_SCRIPT_1){ |
| 359 | 1 | if(c === "r" || c === "R"){ |
| 360 | 1 | this._state = BEFORE_SCRIPT_2; |
| 361 | } else { | |
| 362 | 0 | this._state = IN_TAG_NAME; |
| 363 | 0 | continue; //consume the token again |
| 364 | } | |
| 365 | 17 | } else if(this._state === BEFORE_SCRIPT_2){ |
| 366 | 1 | if(c === "i" || c === "I"){ |
| 367 | 1 | this._state = BEFORE_SCRIPT_3; |
| 368 | } else { | |
| 369 | 0 | this._state = IN_TAG_NAME; |
| 370 | 0 | continue; //consume the token again |
| 371 | } | |
| 372 | 16 | } else if(this._state === BEFORE_SCRIPT_3){ |
| 373 | 1 | if(c === "p" || c === "P"){ |
| 374 | 1 | this._state = BEFORE_SCRIPT_4; |
| 375 | } else { | |
| 376 | 0 | this._state = IN_TAG_NAME; |
| 377 | 0 | continue; //consume the token again |
| 378 | } | |
| 379 | 15 | } else if(this._state === BEFORE_SCRIPT_4){ |
| 380 | 1 | if(c === "t" || c === "T"){ |
| 381 | 1 | this._state = BEFORE_SCRIPT_5; |
| 382 | } else { | |
| 383 | 0 | this._state = IN_TAG_NAME; |
| 384 | 0 | continue; //consume the token again |
| 385 | } | |
| 386 | 14 | } else if(this._state === BEFORE_SCRIPT_5){ |
| 387 | 1 | if(c === "/" || c === ">" || whitespace(c)){ |
| 388 | 1 | this._special = 1; |
| 389 | } | |
| 390 | 1 | this._state = IN_TAG_NAME; |
| 391 | 1 | continue; //consume the token again |
| 392 | } | |
| 393 | ||
| 394 | 13 | else if(this._state === AFTER_SCRIPT_1){ |
| 395 | 1 | if(c === "r" || c === "R"){ |
| 396 | 1 | this._state = AFTER_SCRIPT_2; |
| 397 | } | |
| 398 | 0 | else this._state = TEXT; |
| 399 | 12 | } else if(this._state === AFTER_SCRIPT_2){ |
| 400 | 1 | if(c === "i" || c === "I"){ |
| 401 | 1 | this._state = AFTER_SCRIPT_3; |
| 402 | } | |
| 403 | 0 | else this._state = TEXT; |
| 404 | 11 | } else if(this._state === AFTER_SCRIPT_3){ |
| 405 | 1 | if(c === "p" || c === "P"){ |
| 406 | 1 | this._state = AFTER_SCRIPT_4; |
| 407 | } | |
| 408 | 0 | else this._state = TEXT; |
| 409 | 10 | } else if(this._state === AFTER_SCRIPT_4){ |
| 410 | 1 | if(c === "t" || c === "T"){ |
| 411 | 1 | this._state = AFTER_SCRIPT_5; |
| 412 | } | |
| 413 | 0 | else this._state = TEXT; |
| 414 | 9 | } else if(this._state === AFTER_SCRIPT_5){ |
| 415 | 1 | if(c === ">" || whitespace(c)){ |
| 416 | 1 | this._state = IN_CLOSING_TAG_NAME; |
| 417 | 1 | this._sectionStart = this._index - 6; |
| 418 | 1 | continue; //reconsume the token |
| 419 | } | |
| 420 | 0 | else this._state = TEXT; |
| 421 | } | |
| 422 | ||
| 423 | /* | |
| 424 | * style | |
| 425 | */ | |
| 426 | 8 | else if(this._state === BEFORE_STYLE_1){ |
| 427 | 1 | if(c === "y" || c === "Y"){ |
| 428 | 1 | this._state = BEFORE_STYLE_2; |
| 429 | } else { | |
| 430 | 0 | this._state = IN_TAG_NAME; |
| 431 | 0 | continue; //consume the token again |
| 432 | } | |
| 433 | 7 | } else if(this._state === BEFORE_STYLE_2){ |
| 434 | 1 | if(c === "l" || c === "L"){ |
| 435 | 1 | this._state = BEFORE_STYLE_3; |
| 436 | } else { | |
| 437 | 0 | this._state = IN_TAG_NAME; |
| 438 | 0 | continue; //consume the token again |
| 439 | } | |
| 440 | 6 | } else if(this._state === BEFORE_STYLE_3){ |
| 441 | 1 | if(c === "e" || c === "E"){ |
| 442 | 1 | this._state = BEFORE_STYLE_4; |
| 443 | } else { | |
| 444 | 0 | this._state = IN_TAG_NAME; |
| 445 | 0 | continue; //consume the token again |
| 446 | } | |
| 447 | 5 | } else if(this._state === BEFORE_STYLE_4){ |
| 448 | 1 | if(c === "/" || c === ">" || whitespace(c)){ |
| 449 | 1 | this._special = 2; |
| 450 | } | |
| 451 | 1 | this._state = IN_TAG_NAME; |
| 452 | 1 | continue; //consume the token again |
| 453 | } | |
| 454 | ||
| 455 | 4 | else if(this._state === AFTER_STYLE_1){ |
| 456 | 1 | if(c === "y" || c === "Y"){ |
| 457 | 1 | this._state = AFTER_STYLE_2; |
| 458 | } | |
| 459 | 0 | else this._state = TEXT; |
| 460 | 3 | } else if(this._state === AFTER_STYLE_2){ |
| 461 | 1 | if(c === "l" || c === "L"){ |
| 462 | 1 | this._state = AFTER_STYLE_3; |
| 463 | } | |
| 464 | 0 | else this._state = TEXT; |
| 465 | 2 | } else if(this._state === AFTER_STYLE_3){ |
| 466 | 1 | if(c === "e" || c === "E"){ |
| 467 | 1 | this._state = AFTER_STYLE_4; |
| 468 | } | |
| 469 | 0 | else this._state = TEXT; |
| 470 | 1 | } else if(this._state === AFTER_STYLE_4){ |
| 471 | 1 | if(c === ">" || whitespace(c)){ |
| 472 | 1 | this._state = IN_CLOSING_TAG_NAME; |
| 473 | 1 | this._sectionStart = this._index - 5; |
| 474 | 1 | continue; //reconsume the token |
| 475 | } | |
| 476 | 0 | else this._state = TEXT; |
| 477 | } | |
| 478 | ||
| 479 | ||
| 480 | else { | |
| 481 | 0 | this._cbs.onerror(Error("unknown state"), this._state); |
| 482 | } | |
| 483 | ||
| 484 | 938396 | this._index++; |
| 485 | } | |
| 486 | ||
| 487 | //cleanup | |
| 488 | 9406 | if(this._sectionStart === -1){ |
| 489 | 0 | this._buffer = ""; |
| 490 | 0 | this._index = 0; |
| 491 | } else { | |
| 492 | 9410 | if(this._state === TEXT){ |
| 493 | 9411 | if(this._sectionStart !== this._index){ |
| 494 | 1 | this._cbs.ontext(this._buffer.substr(this._sectionStart)); |
| 495 | } | |
| 496 | 9414 | this._buffer = ""; |
| 497 | 9415 | this._index = 0; |
| 498 | 0 | } else if(this._sectionStart === this._index){ |
| 499 | //the section just started | |
| 500 | 0 | this._buffer = ""; |
| 501 | 0 | this._index = 0; |
| 502 | 0 | } else if(this._sectionStart > 0){ |
| 503 | //remove everything unnecessary | |
| 504 | 0 | this._buffer = this._buffer.substr(this._sectionStart); |
| 505 | 0 | this._index -= this._sectionStart; |
| 506 | } | |
| 507 | ||
| 508 | 9426 | this._sectionStart = 0; |
| 509 | } | |
| 510 | }; | |
| 511 | ||
| 512 | 1 | Tokenizer.prototype.pause = function(){ |
| 513 | 0 | this._running = false; |
| 514 | }; | |
| 515 | 1 | Tokenizer.prototype.resume = function(){ |
| 516 | 0 | this._running = true; |
| 517 | }; | |
| 518 | ||
| 519 | 1 | Tokenizer.prototype.end = function(chunk){ |
| 520 | 9438 | if(chunk) this.write(chunk); |
| 521 | ||
| 522 | //if there is remaining data, emit it in a reasonable way | |
| 523 | 9441 | if(this._sectionStart > this._index){ |
| 524 | 0 | var data = this._buffer.substr(this._sectionStart); |
| 525 | ||
| 526 | 0 | if(this._state === IN_CDATA || this._state === AFTER_CDATA_1 || this._state === AFTER_CDATA_2){ |
| 527 | 0 | this._cbs.oncdata(data); |
| 528 | 0 | } else if(this._state === IN_COMMENT || this._state === AFTER_COMMENT_1 || this._state === AFTER_COMMENT_2){ |
| 529 | 0 | this._cbs.oncomment(data); |
| 530 | 0 | } else if(this._state === IN_TAG_NAME){ |
| 531 | 0 | this._cbs.onopentagname(data); |
| 532 | 0 | } else if(this._state === IN_CLOSING_TAG_NAME){ |
| 533 | 0 | this._cbs.onclosetag(data); |
| 534 | } else { | |
| 535 | 0 | this._cbs.ontext(data); |
| 536 | } | |
| 537 | } | |
| 538 | ||
| 539 | 9457 | this._cbs.onend(); |
| 540 | }; | |
| 541 | ||
| 542 | 1 | Tokenizer.prototype.reset = function(){ |
| 543 | 0 | Tokenizer.call(this, this._options, this._cbs); |
| 544 | }; | |
| 545 | ||
| 546 | 1 | Tokenizer.prototype._emitToken = function(name){ |
| 547 | 116067 | this._cbs[name](this._buffer.substring(this._sectionStart, this._index)); |
| 548 | 116079 | this._sectionStart = -1; |
| 549 | }; | |
| 550 | ||
| 551 | 1 | Tokenizer.prototype._emitIfToken = function(name){ |
| 552 | 116129 | if(this._index > this._sectionStart){ |
| 553 | 39847 | this._cbs[name](this._buffer.substring(this._sectionStart, this._index)); |
| 554 | } | |
| 555 | 116165 | this._sectionStart = -1; |
| 556 | }; | |
| 557 |