Coverage

39.7%
4428
1757
2671

LineHitsSource

c:/noboxout/js-object-enhancements/index.js

100.0%
3
3
0
LineHitsSource
11(function () {
21 "use strict";
3
41 module.exports = require("c:/noboxout/js-object-enhancements/./lib/objects.js");
5
6}());

c:/noboxout/js-object-enhancements/lib/objects.js

82.7%
185
153
32
LineHitsSource
11(function () {
21 "use strict";
3
41 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
241 module.exports["typeof"] = __typeof = function (val) {
2581 if (val === null || val === undefined) {
263 return "null";
27 }
28 // dont deal with undefine...
2978 if (val === true || val === false) {
309 return "boolean";
31 }
32
3369 var type = typeof val;
34
3569 if (type === "object") {
36 // for performance, we check if it"s a plain object first
3741 if (type.constructor === ObjectConstructor) {
380 return type;
39 }
40
4141 if (val.push === ArrayPush && val.length != null) { // != null is ok!
429 return "array";
43 }
44 // for performance, I will keep this insecure
45 // if (hasOwnProperty.call(val, "callee")) {
4632 if (val.hasOwnProperty && val.hasOwnProperty("callee")) {
473 return "arguments";
48 }
4929 if (val instanceof Date) {
502 return "date";
51 }
5227 if (val instanceof RegExp) {
532 return "regexp";
54 }
55
56 // this is an instance of something?
5728 } else if (type === "number" && isNaN(val)) {
581 return "null";
59 }
60
6152 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
691 if (!Object.keys) {
700 Object.keys = function (obj) {
710 if (typeof obj !== "object" && (typeof obj !== "function" || obj === null)) {
720 throw new TypeError("Object.keys called on non-object");
73 }
74
750 var result = [], prop, i;
76
770 for (prop in obj) {
780 if (hasOwnProperty.call(obj, prop)) {
790 result.push(prop);
80 }
81 }
82
830 if (hasDontEnumBug) {
840 for (i = 0; i < dontEnumsLength; i++) {
850 if (hasOwnProperty.call(obj, dontEnums[i])) {
860 result.push(dontEnums[i]);
87 }
88 }
89 }
900 return result;
91 };
92 }
93
94 // define Object.defineProperty if not found, no functionality just a replacement so your code not throw!
951 if (!Object.defineProperty) {
960 Object.defineProperty = function (obj, name, prop) {
970 if (prop.get || prop.set) {
980 throw new Error("this is not supported in your js.engine");
99 }
1000 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!
1061 if (!Object.seal) {
1070 Object.seal = function (obj) {
1080 return obj;
109 };
110 }
111
1121 module.exports.values = function (obj) {
1130 if (__debug) {
1140 if (typeof obj !== "object" && (typeof obj !== "function" || obj === null)) {
1150 throw new TypeError("Object.values called on non-object");
116 }
117 }
118
1190 var result = [],
120 prop;
121
1220 for (prop in obj) {
1230 if (!__debug || hasOwnProperty.call(obj, prop)) {
1240 result.push(obj[prop]);
125 }
126 }
127
1280 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 */
1391 function __each(object, fn) {
1401 var key = null;
141
1421 for (key in object) {
1433 fn(object[key], key);
144 }
145
1461 return object;
147 }
148
1491 module.exports.each = __each;
150
1511 module.exports.forEach = __each;
152
1531 module.exports.clone = function (obj) {
1542 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 */
1661 module.exports.merge = __merge = function (to, from, clone, must_exists) {
167 //console.log("Object.merge", from);
16841 clone = clone || false;
16941 must_exists = must_exists || false;
170
17141 var ftype = __typeof(from),
172 key,
173 ret;
174
17541 switch (ftype) {
176 case "string":
1773 return clone ? "" + from : from;
178 case "number":
17916 return clone ? 0 + from : from;
180 case "array": // maybe need more deep clone ?
181
1825 if (clone) {
1834 ret = [];
1844 for (key = 0; key < from.length; ++key) {
18515 ret[key] = __merge(to[key] || {}, from[key], clone, must_exists);
186 }
187
1884 return ret;
189 }
190
1911 return from;
192 case "boolean":
1935 return clone ? (from ? true : false) : from;
194 case "null":
1950 return null;
196 case "function":
1970 return from;
198 case "object":
199 // to it not an object, overwrite!
20012 ret = __typeof(to) !== "object" ? {} : to || {};
201 // if has prototype just copy
20212 key = null;
203
20412 for (key in from) {
20519 if (key !== "prototype") {
20619 if (ret[key] === undefined) {
20717 if (must_exists) {
2081 continue;
209 }
21016 ret[key] = {};
211 }
21218 ret[key] = __merge(ret[key] || {}, from[key], clone, must_exists);
213 }
214 }
215
21612 return ret;
217 case "regexp":
2180 return new RegExp(from.source);
219 case "date":
2200 return clone ? new Date(from) : from;
221 }
222 // unknown type... just return
2230 return from;
224 };
225
2261 module.exports.combine = function (keys, values) {
2273 values = values || [];
2283 var i,
229 ret = {};
230
2313 for (i = 0; i < keys.length; ++i) {
2326 ret[keys[i]] = values[i] === undefined ? null : values[i];
233 }
2343 return ret;
235 };
236
2371 module.exports.ksort = function (from) {
2381 var keys = Object.keys(from),
239 i,
240 ret = {};
241
2421 for (i = 0; i < keys.length; ++i) {
2433 ret[keys[i]] = from[keys[i]];
244 }
245
2461 return ret;
247 };
248
2491 module.exports.extend = function () {
2501 var target = arguments[0] || {},
251 o,
252 p,
253 i,
254 len;
255
2561 for (i = 1, len = arguments.length; i < len; i++) {
2571 o = arguments[i];
258
2591 if ("object" === typeof o && o !== null) {
2601 for (p in o) {
2612 target[p] = o[p];
262 }
263 }
264 }
265
2661 return target;
267 };
268
2691 module.exports.extract = function (from, keys, default_value) {
2701 var i,
271 ret = {};
272
2731 default_value = default_value === undefined ? null : default_value;
274
2751 for (i = 0; i < keys.length; ++i) {
2762 ret[keys[i]] = from[keys[i]] === undefined ? default_value : from[keys[i]];
277 }
278
2791 return ret;
280 };
281
2821 module.exports.empty = function (obj) {
2832 var name;
2842 for (name in obj) {
2851 return false;
286 }
2871 return true;
288 };
289
2901 module.exports.depth = __depth = function (obj) {
29113 var i,
292 max,
293 props = false,
294 d = 0;
295
29613 if (obj === null || obj === undefined) {
2971 return 0;
298 }
299
30012 if (Array.isArray(obj)) {
301 // array
302
3031 for (i = 0, max = obj.length; i < max; ++i) {
3041 d = Math.max(d, __depth(obj[i]));
305 }
3061 props = max > 0;
30711 } else if ("object" === typeof obj) {
308 // object
309
31010 for (i in obj) {
3116 props = true;
3126 d = Math.max(d, __depth(obj[i]));
313 }
314 }
315
31612 return (props ? 1 : 0) + d;
317 };
318
3191 module.exports.rFilter = __rfilter = function (obj, callback, loop_arrays) {
32012 var i,
321 max;
32212 loop_arrays = loop_arrays === true;
323
32412 if (Array.isArray(obj)) {
325 // array
3263 if (!loop_arrays) {
3272 obj = callback(obj);
328 } else {
3291 for (i = 0, max = obj.length; i < max; ++i) {
3302 obj[i] = __rfilter(obj[i], callback, loop_arrays);
331 }
332 }
333
3343 return obj;
335 }
336
3379 if ("object" === typeof obj) {
338 // object
3394 if (!(obj instanceof Date || obj instanceof RegExp)) {
340
3412 for (i in obj) {
3427 obj[i] = __rfilter(obj[i], callback, loop_arrays);
343 }
3442 return obj;
345 }
346 }
347
3487 return callback(obj);
349 };
350
3511 module.exports.prefixKeys = function (obj, prefix, ignore_keys) {
3522 ignore_keys = ignore_keys || [];
3532 var i,
354 ret = {};
355
3562 if (ignore_keys.length) {
3571 for (i in obj) {
3583 if (ignore_keys.indexOf(i) === -1) {
3592 ret[prefix + i] = obj[i];
360 } else {
3611 ret[i] = obj[i];
362 }
363 }
364 } else {
3651 for (i in obj) {
3663 ret[prefix + i] = obj[i];
367 }
368 }
369
3702 return ret;
371 };
372
3731 module.exports.remPrefixKeys = function (obj, prefix, ignore_keys) {
3742 ignore_keys = ignore_keys || [];
3752 var i,
376 prefix_len = prefix.length,
377 ret = {};
378
3792 if (ignore_keys.length) {
3801 for (i in obj) {
3813 if (ignore_keys.indexOf(i) === -1) {
3822 if (i.indexOf(prefix) === 0) {
3831 ret[i.substring(prefix_len)] = obj[i];
384 } else {
3851 ret[i] = obj[i];
386 }
387 } else {
3881 ret[i] = obj[i];
389 }
390 }
391 } else {
3921 for (i in obj) {
3933 if (i.indexOf(prefix) === 0) {
3942 ret[i.substring(prefix_len)] = obj[i];
395 } else {
3961 ret[i] = obj[i];
397 }
398 }
399 }
400
4012 return ret;
402 };
403
404
4051 module.exports.diff = function (obj) {
4064 var ret = {},
407 argl = arguments.length,
408 k1,
409 i,
410 found;
411
4124 for (k1 in obj) {
41312 found = false;
41412 for (i = 1; i < argl && !found; ++i) {
41512 if (obj[k1] === arguments[i][k1]) {
4167 found = true;
417 }
418 }
419
42012 if (!found) {
4215 ret[k1] = obj[k1];
422 }
423
424 }
425
4264 return ret;
427
428 };
429
430}());

c:/noboxout/js-object-enhancements/node_modules/tap/lib/main.js

100.0%
9
9
0
LineHitsSource
1
21var 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.
81exports = module.exports = new GlobalHarness()
9
101exports.createProducer = exports.Producer = require("c:/noboxout/js-object-enhancements/node_modules/tap/lib/./tap-producer")
111exports.createConsumer = exports.Consumer = require("c:/noboxout/js-object-enhancements/node_modules/tap/lib/./tap-consumer")
121exports.yamlish = require("yamlish")
131exports.createTest = exports.Test = require("c:/noboxout/js-object-enhancements/node_modules/tap/lib/./tap-test")
141exports.createHarness = exports.Harness = require("c:/noboxout/js-object-enhancements/node_modules/tap/lib/./tap-harness")
151exports.createRunner = exports.Runner = require("c:/noboxout/js-object-enhancements/node_modules/tap/lib/./tap-runner")
161exports.assert = require("c:/noboxout/js-object-enhancements/node_modules/tap/lib/./tap-assert")
17

c:/noboxout/js-object-enhancements/node_modules/tap/lib/tap-global-harness.js

89.3%
28
25
3
LineHitsSource
1// this is just a harness that pipes to stdout.
2// It's the default one.
31module.exports = GlobalHarness
4
51var 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
111inherits(GlobalHarness, Harness)
121function GlobalHarness () {
13 //console.error("calling GlobalHarness")
141 if (globalHarness) return globalHarness
151 if (!(this instanceof GlobalHarness)) {
160 return globalHarness = new GlobalHarness
17 }
18
191 globalHarness = global.TAP_Global_Harness = this
201 GlobalHarness.super.call(this, Test)
21
221 this.output.pipe(process.stdout)
23 //this.output.on("data", function () {
24 // process.nextTick(process.stdout.flush.bind(process.stdout))
25 //})
26
271 this.test = this.test.bind(this)
28
291 this.plan = this.plan.bind(this)
30
311 var output = this.output
321 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)
375 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)
415 this.results.list.forEach(function (res) {
42 //delete res.error
43 //console.error("child resuilt", res)
4457 output.write(res)
45 })
46 //console.error("wrote child results")
475 this.results.list.length = 0
48 })
49
501 var streamEnded = false
511 this.on("end", function () {
52 //console.error("global ending the stream")
531 if (!streamEnded) {
541 this.results.list.forEach(function (res) {
550 output.write(res)
56 })
571 this.results.list.length = 0
581 output.end()
591 streamEnded = true
60 }
61 })
62
63 //this.on("end", this.output.end.bind(this.output))
64
651 process.on("unhandledException", function (e) {
660 this.bailout("unhandled exception: " + e.message)
67 })
68}
69

c:/noboxout/js-object-enhancements/node_modules/tap/node_modules/inherits/inherits.js

100.0%
9
9
0
LineHitsSource
11module.exports = inherits
2
31function inherits (c, p, proto) {
47 proto = proto || {}
57 var e = {}
67 ;[c.prototype, proto].forEach(function (s) {
714 Object.getOwnPropertyNames(s).forEach(function (k) {
87 e[k] = Object.getOwnPropertyDescriptor(s, k)
9 })
10 })
117 c.prototype = Object.create(p.prototype, e)
127 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

c:/noboxout/js-object-enhancements/node_modules/tap/lib/tap-results.js

84.8%
33
28
5
LineHitsSource
1// A class for counting up results in a test harness.
2
31module.exports = Results
4
51var inherits = require("inherits")
6 , EventEmitter = require("events").EventEmitter
7
81inherits(Results, EventEmitter)
9
101function Results (r) {
11 //console.error("result constructor", r)
1212 this.ok = true
1312 this.addSet(r)
14}
15
161Results.prototype.addSet = function (r) {
17 //console.error("add set of results", r)
1817 r = r || {ok: true}
1917 ; [ "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) {
31204 this[k] = (this[k] || 0) + (r[k] || 0)
32 //console.error([k, this[k]])
33 }, this)
34
3517 this.ok = this.ok && r.ok && true
3617 this.bailedOut = this.bailedOut || r.bailedOut || false
3717 this.list = (this.list || []).concat(r.list || [])
3817 this.emit("set", this.list)
39 //console.error("after addSet", this)
40}
41
421Results.prototype.add = function (r, addToList) {
43 //console.error("add result", r)
44114 var pf = r.ok ? "pass" : "fail"
45 , PF = r.ok ? "Pass" : "Fail"
46
47114 this.testsTotal ++
48114 this[pf + "Total"] ++
49
50114 if (r.skip) {
510 this["skip" + PF] ++
520 this.skip ++
53114 } else if (r.todo) {
540 this["todo" + PF] ++
550 this.todo ++
56 } else {
57114 this.tests ++
58114 this[pf] ++
59 }
60
61114 if (r.bailout || typeof r.bailout === "string") {
62 // console.error("Bailing out in result")
630 this.bailedOut = true
64 }
65114 this.ok = !!(this.ok && r.ok)
66
67171 if (addToList === false) return
6857 this.list = this.list || []
6957 this.list.push(r)
7057 this.emit("result", r)
71}
72

c:/noboxout/js-object-enhancements/node_modules/tap/lib/tap-harness.js

74.8%
103
77
26
LineHitsSource
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
111module.exports = Harness
121require("inherits")(Harness, require("events").EventEmitter)
13
141var 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
181function Harness (Test) {
196 if (!(this instanceof Harness)) return new Harness(Test)
20
21 //console.error("Test in "+this.constructor.name, Test)
22
236 this._Test = Test
246 this._plan = null
256 this._children = []
266 this._started = false
27
286 this._testCount = 0
296 this._planSum = 0
30
316 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))
376 var me = this
386 this.results.on("result", this.emit.bind(this, "result"))
39
406 var p = this.process.bind(this)
416 this.process = function () {
426 this._started = true
436 process.nextTick(p)
44 }
45
466 this.output = new TapProducer()
476 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.
541Harness.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"
596 if (this._current) {
605 if (!this._current._ended) return
61 // handle the current one before moving onto the next.
625 this.childEnd(this._current)
63 }
646 var skip = true
656 while (skip) {
66 //console.error("checking for skips")
676 var current = this._current = this._children.shift()
686 if (current) {
695 skip = current.conf.skip
705 if (skip) {
71 //console.error("add a failure for the skipping")
720 this.results.add(assert.fail(current.conf.name
73 ,{skip:true, diag:false}))
74 }
751 } else skip = false
76 }
77
78 // keep processing through skipped tests, instead of running them.
796 if (current && this._bailedOut) {
800 return this.process()
81 }
82
83 //console.error("got current?", !!current)
846 if (current) {
855 current.on("end", this.process)
865 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")
911 if (this._endNice) {
920 this._endNice()
93 } else {
941 this.end()
95 }
96 }
97}
98
991Harness.prototype.end = function () {
1006 if (this._children.length) {
1010 return this.process()
102 }
103 //console.error("harness end", this.constructor.name)
1046 if (this._bailedOut) return
105
106 // can't call .end() more than once.
1076 if (this._ended) {
108 //console.error("adding failure for end calling")
1090 this.results.add(assert.fail("end called more than once"))
110 }
111
112 // see if the plan is completed properly, if there was one.
1136 if (this._plan !== null) {
1140 var total = this._testCount
1150 if (total !== this._plan) {
1160 this.results.add(assert.equal(total, this._plan, "test count != plan"))
117 }
1180 this._plan = total
119 }
120
121 //console.error("setting ended true", this.constructor.name)
1226 this._ended = true
1236 this.emit("end")
124}
125
1261Harness.prototype.plan = function (p) {
127 //console.error("setting plan", new Error().stack)
1280 if (this._plan !== null) {
129 //console.error("about to add failure for calling plan")
1300 return this.results.add(assert.fail("plan set multiple times"))
131 }
1320 this._plan = p
1330 if (p === 0 || this.results.testsTotal) {
1340 this.end()
135 }
136}
137
1381Harness.prototype.childEnd = function (child) {
139 //console.error("childEnd")
1405 this._testCount ++
1415 this._planSum += child._plan
142 //console.error("adding set of child.results")
1435 this.results.addSet(child.results)
1445 this.emit("childEnd", child)
145 // was this planned?
1465 if (this._plan === this._testCount) {
147 //console.error("plan", [this._plan, this._testCount])
1480 return this.end()
149 }
150}
151
1521function copyObj(o) {
1530 var copied = {}
1540 Object.keys(o).forEach(function (k) { copied[k] = o[k] })
1550 return copied
156}
157
1581Harness.prototype.test = function test (name, conf, cb) {
1595 if (this._bailedOut) return
160
16110 if (typeof conf === "function") cb = conf, conf = null
1625 if (typeof name === "object") conf = name, name = null
1635 if (typeof name === "function") cb = name, name = null
164
1655 conf = (conf ? copyObj(conf) : {})
1665 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.
17210 if (isNaN(conf.timeout)) conf.timeout = 30000
1735 var t = new this._Test(this, name, conf)
1745 var self = this
1755 if (cb) {
176 //console.error("attaching cb to ready event")
1775 t.on("ready", function () {
1785 if (!isNaN(conf.timeout) && isFinite(conf.timeout)) {
1795 var timer = setTimeout(this.timeout.bind(this), conf.timeout)
1805 var clear = function () {
1815 clearTimeout(timer)
182 }
1835 t.on("end", clear)
1845 t.on("bailout", function (message) {
1850 self.bailout(message)
1860 clear()
187 })
188 }
189 })
1905 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 }
1975 return t
198}
199
2001Harness.prototype.bailout = function (message) {
201 // console.error("Harness bailout", this.constructor.name)
2020 message = message || ""
203 //console.error("adding bailout message result")
2040 this.results.add({bailout: message})
205 // console.error(">>> results after bailout" , this.results)
2060 this._bailedOut = true
2070 this.emit("bailout", message)
2080 this.output.end({bailout: message})
209}
210
2111Harness.prototype.add = function (child) {
212 //console.error("adding child")
2135 this._children.push(child)
2146 if (!this._started) this.process()
215}
216
217// the tearDown function is *always* guaranteed to happen.
218// Even if there's a bailout.
2191Harness.prototype.tearDown = function (fn) {
2200 this.on("end", fn)
221}
222

c:/noboxout/js-object-enhancements/node_modules/tap/lib/tap-producer.js

71.8%
78
56
22
LineHitsSource
11module.exports = TapProducer
2
31var Results = require("c:/noboxout/js-object-enhancements/node_modules/tap/lib/./tap-results")
4 , inherits = require("inherits")
5 , yamlish = require("yamlish")
6
71TapProducer.encode = function (result, diag) {
80 var tp = new TapProducer(diag)
9 , out = ""
100 tp.on("data", function (c) { out += c })
110 if (Array.isArray(result)) {
120 result.forEach(tp.write, tp)
130 } else tp.write(result)
140 tp.end()
150 return out
16}
17
181inherits(TapProducer, require("stream").Stream)
191function TapProducer (diag) {
206 TapProducer.super.call(this)
216 this.diag = diag
226 this.count = 0
236 this.readable = this.writable = true
246 this.results = new Results
25}
26
271TapProducer.prototype.trailer = true
28
291TapProducer.prototype.write = function (res) {
30 // console.error("TapProducer.write", res)
3163 if (typeof res === "function") throw new Error("wtf?")
3263 if (!this.writable) this.emit("error", new Error("not writable"))
33
3463 if (!this._didHead) {
351 this.emit("data", "TAP version 13\n")
361 this._didHead = true
37 }
38
3963 var diag = res.diag
40126 if (diag === undefined) diag = this.diag
41
4263 this.emit("data", encodeResult(res, this.count + 1, diag))
43
4469 if (typeof res === "string") return true
45
4657 if (res.bailout) {
470 var bo = "bail out!"
480 if (typeof res.bailout === "string") bo += " " + res.bailout
490 this.emit("data", bo)
500 return
51 }
5257 this.results.add(res, false)
53
5457 this.count ++
55}
56
571TapProducer.prototype.end = function (res) {
581 if (res) this.write(res)
59 // console.error("TapProducer end", res, this.results)
601 this.emit("data", "\n1.."+this.results.testsTotal+"\n")
611 if (this.trailer && typeof this.trailer !== "string") {
62 // summary trailer.
631 var trailer = "tests "+this.results.testsTotal + "\n"
641 if (this.results.pass) {
651 trailer += "pass " + this.results.pass + "\n"
66 }
671 if (this.results.fail) {
680 trailer += "fail " + this.results.fail + "\n"
69 }
701 if (this.results.skip) {
710 trailer += "skip "+this.results.skip + "\n"
72 }
731 if (this.results.todo) {
740 trailer += "todo "+this.results.todo + "\n"
75 }
761 if (this.results.bailedOut) {
770 trailer += "bailed out" + "\n"
78 }
79
801 if (this.results.testsTotal === this.results.pass) {
811 trailer += "\nok\n"
82 }
831 this.trailer = trailer
84 }
852 if (this.trailer) this.write(this.trailer)
861 this.writable = false
871 this.emit("end", null, this.count, this.ok)
88}
89
901function encodeResult (res, count, diag) {
91 // console.error(res, count, diag)
9263 if (typeof res === "string") {
936 res = res.split(/\r?\n/).map(function (l) {
9412 if (!l.trim()) return l.trim()
958 return "# " + l
96 }).join("\n")
9711 if (res.substr(-1) !== "\n") res += "\n"
986 return res
99 }
100
10157 if (res.bailout) return ""
102
103
10457 if (!!process.env.TAP_NODIAG) diag = false
10557 else if (!!process.env.TAP_DIAG) diag = true
106114 else if (diag === undefined) diag = !res.ok
107
10857 var output = ""
10957 res.name = res.name && ("" + res.name).trim()
11057 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
118114 if (!diag) return output
1190 var d = {}
120 , dc = 0
1210 Object.keys(res).filter(function (k) {
1220 return k !== "ok" && k !== "name" && k !== "id"
123 }).forEach(function (k) {
1240 dc ++
1250 d[k] = res[k]
126 })
127 //console.error(d, "about to encode")
1280 if (dc > 0) output += " ---"+yamlish.encode(d)+"\n ...\n"
1290 return output
130}
131

c:/noboxout/js-object-enhancements/node_modules/tap/node_modules/yamlish/yamlish.js

7.0%
128
9
119
LineHitsSource
11exports.encode = encode
21exports.decode = decode
3
41var seen = []
51function encode (obj, indent) {
60 var deep = arguments[2]
70 if (!indent) indent = " "
8
90 if (obj instanceof String ||
10 Object.prototype.toString.call(obj) === "[object String]") {
110 obj = obj.toString()
12 }
13
140 if (obj instanceof Number ||
15 Object.prototype.toString.call(obj) === "[object Number]") {
160 obj = obj.valueOf()
17 }
18
19 // take out the easy ones.
200 switch (typeof obj) {
21 case "string":
220 obj = obj.trim()
230 if (obj.indexOf("\n") !== -1) {
240 return "|\n" + indent + obj.split(/\r?\n/).join("\n"+indent)
25 } else {
260 return (obj)
27 }
28
29 case "number":
300 return obj.toString(10)
31
32 case "function":
330 return encode(obj.toString(), indent, true)
34
35 case "boolean":
360 return obj.toString()
37
38 case "undefined":
39 // fallthrough
40 case "object":
41 // at this point we know it types as an object
420 if (!obj) return "~"
43
440 if (obj instanceof Date ||
45 Object.prototype.toString.call(obj) === "[object Date]") {
460 return JSON.stringify("[Date " + obj.toISOString() + "]")
47 }
48
490 if (obj instanceof RegExp ||
50 Object.prototype.toString.call(obj) === "[object RegExp]") {
510 return JSON.stringify(obj.toString())
52 }
53
540 if (obj instanceof Boolean ||
55 Object.prototype.toString.call(obj) === "[object Boolean]") {
560 return obj.toString()
57 }
58
590 if (seen.indexOf(obj) !== -1) {
600 return "[Circular]"
61 }
620 seen.push(obj)
63
640 if (typeof Buffer === "function" &&
65 typeof Buffer.isBuffer === "function" &&
660 Buffer.isBuffer(obj)) return obj.inspect()
67
680 if (obj instanceof Error) {
690 var o = { name: obj.name
70 , message: obj.message
71 , type: obj.type }
72
730 if (obj.code) o.code = obj.code
740 if (obj.errno) o.errno = obj.errno
750 if (obj.type) o.type = obj.type
760 obj = o
77 }
78
790 var out = ""
80
810 if (Array.isArray(obj)) {
820 var out = "\n" + indent + "- " +obj.map(function (item) {
830 return encode(item, indent + " ", true)
84 }).join("\n"+indent + "- ")
850 break
86 }
87
88 // an actual object
890 var keys = Object.keys(obj)
90 , niceKeys = keys.map(function (k) {
910 return (k.match(/^[a-zA-Z0-9_]+$/) ? k : JSON.stringify(k)) + ": "
92 })
93 //console.error(keys, niceKeys, obj)
940 var maxLength = Math.max.apply(Math, niceKeys.map(function (k) {
950 return k.length
96 }).concat(0))
97 //console.error(niceKeys, maxLength)
98
990 var spaces = new Array(maxLength + 1).join(" ")
100
1010 if (!deep) indent += " "
1020 out = "\n" + indent + keys.map(function (k, i) {
1030 var niceKey = niceKeys[i]
1040 return niceKey + spaces.substr(niceKey.length)
105 + encode(obj[k], indent + " ", true)
106 }).join("\n" + indent)
1070 break
108
1090 default: return ""
110 }
1110 if (!deep) seen.length = 0
1120 return out
113}
114
1151function decode (str) {
1160 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
1200 if (v === "~") return null
121
1220 try {
1230 var jp = JSON.parse(str)
124 } catch (e) {
1250 var jp = ""
126 }
127
1280 if (jp &&
129 typeof jp === "string" &&
130 (d = jp.match(dateRe)) &&
131 (d = Date.parse(d[1]))) {
1320 return new Date(d)
133 }
134
1350 if (typeof jp === "boolean") return jp
1360 if (v && !isNaN(v)) return parseInt(v, 10)
137
138 // something interesting.
1390 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 ""
1450 var first = lines.shift().trim()
1460 if (lines.length) lines = undent(lines)
1470 switch (first) {
148 case "|":
1490 return lines.join("\n")
150 case ">":
1510 return lines.join("\n").split(/\n{2,}/).map(function (l) {
1520 return l.split(/\n/).join(" ")
153 }).join("\n")
154 default:
1550 if (!lines.length) return first
156 // array or object.
157 // the first line will be either "- value" or "key: value"
1580 return lines[0].charAt(0) === "-" ? decodeArr(lines) : decodeObj(lines)
159 }
160}
161
1621function decodeArr (lines) {
1630 var out = []
164 , key = 0
165 , val = []
1660 for (var i = 0, l = lines.length; i < l; i ++) {
167 // if it starts with a -, then it's a new thing
1680 var line = lines[i]
1690 if (line.charAt(0) === "-") {
1700 if (val.length) {
1710 out[key ++] = decode(val.join("\n"))
1720 val.length = 0
173 }
1740 val.push(line.substr(1).trim())
1750 } else if (line.charAt(0) === " ") {
1760 val.push(line)
1770 } else return []
178 }
1790 if (val.length) {
1800 out[key ++] = decode(val.join("\n"))
181 }
1820 return out
183}
184
1851function decodeObj (lines) {
1860 var out = {}
187 , val = []
188 , key = null
189
1900 for (var i = 0, l = lines.length; i < l; i ++) {
1910 var line = lines[i]
1920 if (line.charAt(0) === " ") {
1930 val.push(line)
1940 continue
195 }
196 // some key:val
1970 if (val.length) {
1980 out[key] = decode(val.join("\n"))
1990 val.length = 0
200 }
201 // parse out the quoted key
2020 var first
2030 if (line.charAt(0) === "\"") {
2040 for (var ii = 1, ll = line.length, esc = false; ii < ll; ii ++) {
2050 var c = line.charAt(ii)
2060 if (c === "\\") {
2070 esc = !esc
2080 } else if (c === "\"" && !esc) {
2090 break
210 }
211 }
2120 key = JSON.parse(line.substr(0, ii + 1))
2130 line = line.substr(ii + 1)
2140 first = line.substr(line.indexOf(":") + 1).trim()
215 } else {
2160 var kv = line.split(":")
2170 key = kv.shift()
2180 first = kv.join(":").trim()
219 }
220 // now we've set a key, and "first" has the first line of the value.
2210 val.push(first.trim())
222 }
2230 if (val.length) out[key] = decode(val.join("\n"))
2240 return out
225}
226
2271function undent (lines) {
2280 var i = lines[0].match(/^\s*/)[0].length
2290 return lines.map(function (line) {
2300 return line.substr(i)
231 })
232}
233
234
235// XXX Turn this into proper tests.
2361if (require.main === module) {
2370var obj = [{"bigstring":new Error().stack}
238 ,{ar:[{list:"of"},{some:"objects"}]}
239 ,{date:new Date()}
240 ,{"super huge string":new Error().stack}
241 ]
242
2430Date.prototype.toJSON = function (k, val) {
2440 console.error(k, val, this)
2450 return this.toISOString() + " (it's a date)"
246}
247
2480var enc = encode(obj)
249 , dec = decode(enc)
250 , encDec = encode(dec)
251
2520console.error(JSON.stringify({ obj : obj
253 , enc : enc.split(/\n/)
254 , dec : dec }, null, 2), encDec === enc)
255
2560var num = 100
257 , encNum = encode(num)
258 , decEncNum = decode(encNum)
2590console.error([num, encNum, decEncNum])
260}
261

c:/noboxout/js-object-enhancements/node_modules/tap/lib/tap-assert.js

41.1%
241
99
142
LineHitsSource
1// an assert module that returns tappable data for each assertion.
21var difflet = require('difflet')
3 , deepEqual = require('deep-equal')
4 , bufferEqual = require('buffer-equal')
5
61module.exports = assert
7
81var syns = {}
9 , id = 1
10
111function assert (ok, message, extra) {
1257 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])
1757 ok = !!ok
1857 var res = { id : id ++, ok: ok }
19
2057 var caller = getCaller(extra && extra.error)
2157 if (extra && extra.error) {
220 res.type = extra.error.name
230 res.message = extra.error.message
240 res.code = extra.error.code
25 || extra.error.type
260 res.errno = extra.error.errno
270 delete extra.error
28 }
2957 if (caller.file) {
3057 res.file = caller.file
3157 res.line = +caller.line
3257 res.column = +caller.column
33 }
3457 res.stack = caller.stack
35
3657 res.name = message || "(unnamed assert)"
37
38114 if (extra) Object.keys(extra).forEach(function (k) {
39228 if (!res.hasOwnProperty(k)) res[k] = extra[k]
40 })
41
42 // strings and objects are hard to diff by eye
4357 if (!ok &&
44 res.hasOwnProperty("found") &&
45 res.hasOwnProperty("wanted") &&
46 res.found !== res.wanted) {
470 if (typeof res.wanted !== typeof res.found ||
48 typeof res.wanted === "object" && (!res.found || !res.wanted)) {
490 res.type = { found: typeof found
50 , wanted: typeof wanted }
510 } else if (typeof res.wanted === "string") {
520 res.diff = diffString(res.found, res.wanted)
530 } else if (typeof res.wanted === "object") {
540 res.diff = diffObject(res.found, res.wanted)
55 }
56 }
57
58 //console.error("assert return", res)
59
6057 return res
61}
621assert.ok = assert
631syns.ok = [ "true", "assert" ]
64
65
661function notOk (ok, message, extra) {
670 return assert(!ok, message, extra)
68}
691assert.notOk = notOk
701syns.notOk = [ "false", "notok" ]
71
721function error (er, message, extra) {
730 if (!er) {
74 // just like notOk(er)
750 return assert(!er, message, extra)
76 }
770 message = message || er.message
780 extra = extra || {}
790 extra.error = er
800 return assert.fail(message, extra)
81}
821assert.error = error
831syns.error = [ "ifError", "ifErr", "iferror" ]
84
85
861function pass (message, extra) {
870 return assert(true, message, extra)
88}
891assert.pass = pass
90
911function fail (message, extra) {
92 //console.error("assert.fail", [message, extra])
93 //if (extra && extra.skip) return assert.skip(message, extra)
940 return assert(false, message, extra)
95}
961assert.fail = fail
97
981function skip (message, extra) {
99 //console.error("assert.skip", message, extra)
1000 if (!extra) extra = {}
1010 return { id: id ++, skip: true, name: message || "" }
102}
1031assert.skip = skip
104
1051function throws (fn, wanted, message, extra) {
1060 if (typeof wanted === "string") {
1070 extra = message
1080 message = wanted
1090 wanted = null
110 }
111
1120 if (extra && extra.skip) return assert.skip(message, extra)
113
1140 var found = null
1150 try {
1160 fn()
117 } catch (e) {
1180 found = { name: e.name, message: e.message }
119 }
120
1210 extra = extra || {}
122
1230 extra.found = found
1240 if (wanted) {
1250 wanted = { name: wanted.name, message: wanted.message }
1260 extra.wanted = wanted
127 }
128
1290 if (!message) {
1300 message = "Expected to throw"
1310 if (wanted) message += ": "+wanted.name + " " + wanted.message
132 }
133
1340 return (wanted) ? assert.similar(found, wanted, message, extra)
135 : assert.ok(found, message, extra)
136}
1371assert.throws = throws
138
139
1401function doesNotThrow (fn, message, extra) {
1410 if (extra && extra.skip) return assert.skip(message, extra)
1420 var found = null
1430 try {
1440 fn()
145 } catch (e) {
1460 found = {name: e.name, message: e.message}
147 }
1480 message = message || "Should not throw"
149
1500 return assert.equal(found, null, message, extra)
151}
1521assert.doesNotThrow = doesNotThrow
153
154
1551function equal (a, b, message, extra) {
15627 if (extra && extra.skip) return assert.skip(message, extra)
15727 extra = extra || {}
15827 message = message || "should be equal"
15927 extra.found = a
16027 extra.wanted = b
16127 return assert(a === b, message, extra)
162}
1631assert.equal = equal
1641syns.equal = ["equals"
165 ,"isEqual"
166 ,"is"
167 ,"strictEqual"
168 ,"strictEquals"]
169
170
1711function equivalent (a, b, message, extra) {
17230 if (extra && extra.skip) return assert.skip(message, extra)
17330 var extra = extra || {}
17430 message = message || "should be equivalent"
17530 extra.found = a
17630 extra.wanted = b
177
17830 if (Buffer.isBuffer(a) && Buffer.isBuffer(b)) {
1790 return assert(bufferEqual(a, b), message, extra)
180 } else {
18130 return assert(deepEqual(a, b), message, extra)
182 }
183}
1841assert.equivalent = equivalent
1851syns.equivalent = ["isEquivalent"
186 ,"looseEqual"
187 ,"looseEquals"
188 ,"isDeeply"
189 ,"same"
190 ,"deepEqual"
191 ,"deepEquals"]
192
193
1941function inequal (a, b, message, extra) {
1950 if (extra && extra.skip) return assert.skip(message, extra)
1960 extra = extra || {}
1970 message = message || "should not be equal"
1980 extra.found = a
1990 extra.doNotWant = b
2000 return assert(a !== b, message, extra)
201}
2021assert.inequal = inequal
2031syns.inequal = ["notEqual"
204 ,"notEquals"
205 ,"notStrictEqual"
206 ,"notStrictEquals"
207 ,"isNotEqual"
208 ,"isNot"
209 ,"not"
210 ,"doesNotEqual"
211 ,"isInequal"]
212
213
2141function inequivalent (a, b, message, extra) {
2150 if (extra && extra.skip) return assert.skip(message, extra)
2160 extra = extra || {}
2170 message = message || "should not be equivalent"
2180 extra.found = a
2190 extra.doNotWant = b
220
2210 if (Buffer.isBuffer(a) && Buffer.isBuffer(b)) {
2220 return assert(!bufferEqual(a, b), message, extra)
223 } else {
2240 return assert(!deepEqual(a, b), message, extra)
225 }
226}
2271assert.inequivalent = inequivalent
2281syns.inequivalent = ["notEquivalent"
229 ,"notDeepEqual"
230 ,"notDeeply"
231 ,"notSame"
232 ,"isNotDeepEqual"
233 ,"isNotDeeply"
234 ,"isNotEquivalent"
235 ,"isInequivalent"]
236
2371function similar (a, b, message, extra, flip) {
2380 if (extra && extra.skip) return assert.skip(message, extra)
239 // test that a has all the fields in b
2400 message = message || "should be similar"
241
2420 if (typeof a === "string" &&
243 (Object.prototype.toString.call(b) === "[object RegExp]")) {
2440 extra = extra || {}
2450 extra.pattern = b
2460 extra.string = a
2470 var ok = a.match(b)
2480 extra.match = ok
2490 if (flip) ok = !ok
2500 return assert.ok(ok, message, extra)
251 }
252
2530 var isObj = assert(a && typeof a === "object", message, extra)
2540 if (!isObj.ok) {
255 // not an object
2560 if (a == b) isObj.ok = true
2570 if (flip) isObj.ok = !isObj.ok
2580 return isObj
259 }
260
2610 var eq = flip ? inequivalent : equivalent
2620 return eq(selectFields(a, b), b, message, extra)
263}
2641assert.similar = similar
2651syns.similar = ["isSimilar"
266 ,"has"
267 ,"hasFields"
268 ,"like"
269 ,"isLike"]
270
2711function dissimilar (a, b, message, extra) {
2720 if (extra && extra.skip) return assert.skip(message, extra)
2730 message = message || "should be dissimilar"
2740 return similar(a, b, message, extra, true)
275}
2761assert.dissimilar = dissimilar
2771syns.dissimilar = ["unsimilar"
278 ,"notSimilar"
279 ,"unlike"
280 ,"isUnlike"
281 ,"notLike"
282 ,"isNotLike"
283 ,"doesNotHave"
284 ,"isNotSimilar"
285 ,"isDissimilar"]
286
2871function type (thing, t, message, extra) {
2880 if (extra && extra.skip) return assert.skip(message, extra)
2890 var name = t
2900 if (typeof name === "function") name = name.name || "(anonymous ctor)"
291 //console.error("name=%s", name)
2920 message = message || "type is "+name
2930 var type = typeof thing
294 //console.error("type=%s", type)
2950 if (!thing && type === "object") type = "null"
2960 if (type === "object" && t !== "object") {
2970 if (typeof t === "function") {
298 //console.error("it is a function!")
2990 extra = extra || {}
3000 extra.found = Object.getPrototypeOf(thing).constructor.name
3010 extra.wanted = name
302 //console.error(thing instanceof t, name)
3030 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)
3100 var p = thing
3110 while (p = Object.getPrototypeOf(p)) {
3120 if (p === t || p.constructor && p.constructor.name === t) {
3130 type = name
3140 break
315 }
316 }
317 }
318 //console.error(type, name, type === name)
3190 return assert.equal(type, name, message, extra)
320}
3211assert.type = type
3221syns.type = ["isa"]
323
324// synonyms are helpful.
3251Object.keys(syns).forEach(function (c) {
32610 syns[c].forEach(function (s) {
32751 Object.defineProperty(assert, s, { value: assert[c], enumerable: false })
328 })
329})
330
331// helpers below
332
3331function selectFields (a, b) {
334 // get the values in A of the fields in B
3350 var ret = Array.isArray(b) ? [] : {}
3360 Object.keys(b).forEach(function (k) {
3370 if (!a.hasOwnProperty(k)) return
3380 var v = b[k]
339 , av = a[k]
3400 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))) {
3470 ret[k] = selectFields(av, v)
3480 } else ret[k] = av
349 })
3500 return ret
351}
352
3531function sortObject (obj) {
3540 if (typeof obj !== 'object' || Array.isArray(obj) || obj === null) {
3550 return obj
356 }
357
3580 return Object.keys(obj).sort().reduce(function (acc, key) {
3590 acc[key] = sortObject(obj[key])
3600 return acc
361 }, {})
362}
363
3641function stringify (a) {
3650 return JSON.stringify(sortObject(a), (function () {
3660 var seen = []
367 , keys = []
3680 return function (key, val) {
3690 var s = seen.indexOf(val)
3700 if (s !== -1) {
3710 return "[Circular: "+keys[s]+"]"
372 }
3730 if (val && typeof val === "object" || typeof val === "function") {
3740 seen.push(val)
3750 keys.push(val["!"] || val.name || key || "<root>")
3760 if (typeof val === "function") {
3770 return val.toString().split(/\n/)[0]
3780 } else if (typeof val.toUTCString === "function") {
3790 return val.toUTCString()
380 }
381 }
3820 return val
383 }})())
384}
385
3861function diffString (f, w) {
3870 if (w === f) return null
3880 var p = 0
389 , l = w.length
3900 while (p < l && w.charAt(p) === f.charAt(p)) p ++
3910 w = stringify(w).substr(1).replace(/"$/, "")
3920 f = stringify(f).substr(1).replace(/"$/, "")
3930 return diff(f, w, p)
394}
395
3961function diffObject (f, w) {
3970 return difflet({ indent : 2, comment : true }).compare(w, f)
398}
399
4001function diff (f, w, p) {
4010 if (w === f) return null
4020 var i = p || 0 // it's going to be at least p. JSON can only be bigger.
403 , l = w.length
4040 while (i < l && w.charAt(i) === f.charAt(i)) i ++
4050 var pos = Math.max(0, i - 20)
4060 w = w.substr(pos, 40)
4070 f = f.substr(pos, 40)
4080 var pointer = i - pos
4090 return "FOUND: "+f+"\n"
410 + "WANTED: "+w+"\n"
411 + (new Array(pointer + 9).join(" "))
412 + "^ (at position = "+p+")"
413}
414
4151function getCaller (er) {
416 // get the first file/line that isn't this file.
417114 if (!er) er = new Error
41857 var stack = er.stack || ""
41957 stack = stack.split(/\n/)
42057 for (var i = 1, l = stack.length; i < l; i ++) {
421345 var s = stack[i].match(/\(([^):]+):([0-9]+):([0-9]+)\)$/)
422633 if (!s) continue
42357 var file = s[1]
424 , line = +s[2]
425 , col = +s[3]
42657 if (file.indexOf(__dirname) === 0) continue
42757 if (file.match(/tap-test\/test.js$/)) continue
42857 else break
429 }
43057 var res = {}
43157 if (file && file !== __filename && !file.match(/tap-test\/test.js$/)) {
43257 res.file = file
43357 res.line = line
43457 res.column = col
435 }
436
43757 res.stack = stack.slice(1).map(function (s) {
438570 return s.replace(/^\s*at\s*/, "")
439 })
440
44157 return res
442}
443
444
445

c:/noboxout/js-object-enhancements/node_modules/tap/node_modules/difflet/index.js

3.7%
219
8
211
LineHitsSource
11var traverse = require('traverse');
21var Stream = require('stream').Stream;
31var charm = require('charm');
41var deepEqual = require('deep-is');
5
61var exports = module.exports = function (opts_) {
70 var fn = difflet.bind(null, opts_);
80 fn.compare = function (prev, next) {
90 var opts = Object.keys(opts_ || {}).reduce(function (acc, key) {
100 acc[key] = opts_[key];
110 return acc;
12 }, {});
130 var s = opts.stream = new Stream;
140 var data = '';
150 s.write = function (buf) { data += buf };
160 s.end = function () {};
170 s.readable = true;
180 s.writable = true;
19
200 difflet(opts, prev, next);
210 return data;
22 };
230 return fn;
24};
25
261exports.compare = function (prev, next) {
270 return exports({}).compare(prev, next);
28};
29
301function difflet (opts, prev, next) {
310 var stream = opts.stream || new Stream;
320 if (!opts.stream) {
330 stream.readable = true;
340 stream.writable = true;
350 stream.write = function (buf) { this.emit('data', buf) };
360 stream.end = function () { this.emit('end') };
37 }
38
390 if (!opts) opts = {};
400 if (opts.start === undefined && opts.stop === undefined) {
410 var c = charm(stream);
420 opts.start = function (type) {
430 c.foreground({
44 inserted : 'green',
45 updated : 'blue',
46 deleted : 'red',
47 comment : 'cyan',
48 }[type]);
490 c.display('bright');
50 };
510 opts.stop = function (type) {
520 c.display('reset');
53 };
54 }
550 var write = function (buf) {
560 if (opts.write) opts.write(buf, stream)
570 else stream.write(buf)
58 };
59
600 var commaFirst = opts.comma === 'first';
61
620 var stringify = function (node, params) {
630 return stringifier.call(this, true, node, params || opts);
64 };
650 var plainStringify = function (node, params) {
660 return stringifier.call(this, false, node, params || opts);
67 };
68
690 var levels = 0;
700 function set (type) {
710 if (levels === 0) opts.start(type, stream);
720 levels ++;
73 }
74
750 function unset (type) {
760 if (--levels === 0) opts.stop(type, stream);
77 }
78
790 function stringifier (insertable, node, opts) {
800 var indent = opts.indent;
81
820 if (insertable) {
830 var prevNode = traverse.get(prev, this.path || []);
84 }
850 var inserted = insertable && prevNode === undefined;
86
870 var indentx;
880 try {
890 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
940 indentx = '';
95 }
960 if (commaFirst) indentx = indentx.slice(indent);
97
980 if (Array.isArray(node)) {
990 var updated = (prevNode || traverse.has(prev, this.path))
100 && !Array.isArray(prevNode);
1010 if (updated) {
1020 set('updated');
103 }
104
1050 if (opts.comment && !Array.isArray(prevNode)) {
1060 indent = 0;
107 }
108
1090 this.before(function () {
1100 if (inserted) set('inserted');
1110 if (indent && commaFirst) {
1120 if ((this.path || []).length === 0
113 || Array.isArray(this.parent.node)) {
1140 write('[ ');
115 }
1160 else write('\n' + indentx + '[ ');
117 }
1180 else if (indent) {
1190 write('[\n' + indentx);
120 }
121 else {
1220 write('[');
123 }
124 });
125
1260 this.post(function (child) {
1270 if (!child.isLast && !(indent && commaFirst)) {
1280 write(',');
129 }
130
1310 var prev = prevNode && prevNode[child.key];
1320 if (indent && opts.comment && child.node !== prev
133 && (typeof child.node !== 'object' || typeof prev !== 'object')
134 ) {
1350 set('comment');
1360 write(' // != ');
1370 traverse(prev).forEach(function (x) {
1380 plainStringify.call(this, x, { indent : 0 });
139 });
1400 unset('comment');
141 }
142
1430 if (!child.isLast) {
1440 if (indent && commaFirst) {
1450 write('\n' + indentx + ', ');
146 }
1470 else if (indent) {
1480 write('\n' + indentx);
149 }
150 }
151 });
152
1530 this.after(function () {
1540 if (indent && commaFirst) write('\n' + indentx);
1550 else if (indent) write('\n' + indentx.slice(indent));
156
1570 write(']');
1580 if (updated) unset('updated');
1590 if (inserted) unset('inserted');
160 });
161 }
1620 else if (isRegExp(node)) {
1630 this.block();
164
1650 if (inserted) {
1660 set('inserted');
1670 write(node.toString());
1680 unset('inserted');
169 }
1700 else if (insertable && prevNode !== node) {
1710 set('updated');
1720 write(node.toString());
1730 unset('updated');
174 }
1750 else write(node.toString());
176 }
1770 else if (typeof node === 'object'
178 && node && typeof node.inspect === 'function') {
1790 this.block();
1800 if (inserted) {
1810 set('inserted');
1820 write(node.inspect());
1830 unset('inserted');
184 }
1850 else if (!(prevNode && typeof prevNode.inspect === 'function'
186 && prevNode.inspect() === node.inspect())) {
1870 set('updated');
1880 write(node.inspect());
1890 unset('updated');
190 }
1910 else write(node.inspect());
192 }
1930 else if (typeof node == 'object' && node !== null) {
1940 var insertedKey = false;
1950 var deleted = insertable && typeof prevNode === 'object' && prevNode
196 ? Object.keys(prevNode).filter(function (key) {
1970 return !Object.hasOwnProperty.call(node, key);
198 })
199 : []
200 ;
201
2020 this.before(function () {
2030 if (inserted) set('inserted');
2040 write(indent && commaFirst && !this.isRoot
205 ? '\n' + indentx + '{ '
206 : '{'
207 );
208 });
209
2100 this.pre(function (x, key) {
2110 if (insertable) {
2120 var obj = traverse.get(prev, this.path.concat(key));
2130 if (obj === undefined) {
2140 insertedKey = true;
2150 set('inserted');
216 }
217 }
218
2190 if (indent && !commaFirst) write('\n' + indentx);
220
2210 plainStringify(key);
2220 write(indent ? ' : ' : ':');
223 });
224
2250 this.post(function (child) {
2260 if (!child.isLast && !(indent && commaFirst)) {
2270 write(',');
228 }
229
2300 if (child.isLast && deleted.length) {
2310 if (insertedKey) unset('inserted');
2320 insertedKey = false;
233 }
2340 else if (insertedKey) {
2350 unset('inserted');
2360 insertedKey = false;
237 }
238
2390 var prev = prevNode && prevNode[child.key];
2400 if (indent && opts.comment && child.node !== prev
241 && (typeof child.node !== 'object' || typeof prev !== 'object')
242 ) {
2430 set('comment');
2440 write(' // != ');
2450 traverse(prev).forEach(function (x) {
2460 plainStringify.call(this, x, { indent : 0 });
247 });
2480 unset('comment');
249 }
250
2510 if (child.isLast && deleted.length) {
2520 if (insertedKey) unset('inserted');
2530 insertedKey = false;
254
2550 if (indent && commaFirst) {
2560 write('\n' + indentx + ', ')
257 }
2580 else if (opts.comment && indent) {
2590 write('\n' + indentx);
260 }
2610 else if (indent) {
2620 write(',\n' + indentx);
263 }
2640 else write(',');
265 }
266 else {
2670 if (!child.isLast) {
2680 if (indent && commaFirst) {
2690 write('\n' + indentx + ', ');
270 }
271 }
272 }
273 });
274
2750 this.after(function () {
2760 if (inserted) unset('inserted');
277
2780 if (deleted.length) {
2790 if (indent && !commaFirst
280 && Object.keys(node).length === 0) {
2810 write('\n' + indentx);
282 }
283
2840 set('deleted');
2850 deleted.forEach(function (key, ix) {
2860 if (indent && opts.comment) {
2870 unset('deleted');
2880 set('comment');
2890 write('// ');
2900 unset('comment');
2910 set('deleted');
292 }
293
2940 plainStringify(key);
2950 write(indent ? ' : ' : ':');
2960 traverse(prevNode[key]).forEach(function (x) {
2970 plainStringify.call(this, x, { indent : 0 });
298 });
299
3000 var last = ix === deleted.length - 1;
3010 if (insertable && !last) {
3020 if (indent && commaFirst) {
3030 write('\n' + indentx + ', ');
304 }
3050 else if (indent) {
3060 write(',\n' + indentx);
307 }
3080 else write(',');
309 }
310 });
3110 unset('deleted');
312 }
313
3140 if (commaFirst && indent) {
3150 write(indentx.slice(indent) + ' }');
316 }
3170 else if (indent) {
3180 write('\n' + indentx.slice(indent) + '}');
319 }
3200 else write('}');
321 });
322 }
323 else {
3240 var changed = false;
325
3260 if (inserted) set('inserted');
3270 else if (insertable && !deepEqual(prevNode, node)) {
3280 changed = true;
3290 set('updated');
330 }
331
3320 if (typeof node === 'string') {
3330 write('"' + node.toString().replace(/"/g, '\\"') + '"');
334 }
3350 else if (isRegExp(node)) {
3360 write(node.toString());
337 }
3380 else if (typeof node === 'function') {
3390 write(node.name
340 ? '[Function: ' + node.name + ']'
341 : '[Function]'
342 );
343 }
3440 else if (node === undefined) {
3450 write('undefined');
346 }
3470 else if (node === null) {
3480 write('null');
349 }
350 else {
3510 write(node.toString());
352 }
353
3540 if (inserted) unset('inserted');
3550 else if (changed) unset('updated');
356 }
357 }
358
3590 if (opts.stream) {
3600 traverse(next).forEach(stringify);
361 }
3620 else process.nextTick(function () {
3630 traverse(next).forEach(stringify);
3640 stream.emit('end');
365 });
366
3670 return stream;
368}
369
3701function isRegExp (node) {
3710 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

c:/noboxout/js-object-enhancements/node_modules/tap/node_modules/difflet/node_modules/traverse/index.js

15.0%
180
27
153
LineHitsSource
11var traverse = module.exports = function (obj) {
20 return new Traverse(obj);
3};
4
51function Traverse (obj) {
60 this.value = obj;
7}
8
91Traverse.prototype.get = function (ps) {
100 var node = this.value;
110 for (var i = 0; i < ps.length; i ++) {
120 var key = ps[i];
130 if (!node || !hasOwnProperty.call(node, key)) {
140 node = undefined;
150 break;
16 }
170 node = node[key];
18 }
190 return node;
20};
21
221Traverse.prototype.has = function (ps) {
230 var node = this.value;
240 for (var i = 0; i < ps.length; i ++) {
250 var key = ps[i];
260 if (!node || !hasOwnProperty.call(node, key)) {
270 return false;
28 }
290 node = node[key];
30 }
310 return true;
32};
33
341Traverse.prototype.set = function (ps, value) {
350 var node = this.value;
360 for (var i = 0; i < ps.length - 1; i ++) {
370 var key = ps[i];
380 if (!hasOwnProperty.call(node, key)) node[key] = {};
390 node = node[key];
40 }
410 node[ps[i]] = value;
420 return value;
43};
44
451Traverse.prototype.map = function (cb) {
460 return walk(this.value, cb, true);
47};
48
491Traverse.prototype.forEach = function (cb) {
500 this.value = walk(this.value, cb, false);
510 return this.value;
52};
53
541Traverse.prototype.reduce = function (cb, init) {
550 var skip = arguments.length === 1;
560 var acc = skip ? this.value : init;
570 this.forEach(function (x) {
580 if (!this.isRoot || !skip) {
590 acc = cb.call(this, acc, x);
60 }
61 });
620 return acc;
63};
64
651Traverse.prototype.paths = function () {
660 var acc = [];
670 this.forEach(function (x) {
680 acc.push(this.path);
69 });
700 return acc;
71};
72
731Traverse.prototype.nodes = function () {
740 var acc = [];
750 this.forEach(function (x) {
760 acc.push(this.node);
77 });
780 return acc;
79};
80
811Traverse.prototype.clone = function () {
820 var parents = [], nodes = [];
83
840 return (function clone (src) {
850 for (var i = 0; i < parents.length; i++) {
860 if (parents[i] === src) {
870 return nodes[i];
88 }
89 }
90
910 if (typeof src === 'object' && src !== null) {
920 var dst = copy(src);
93
940 parents.push(src);
950 nodes.push(dst);
96
970 forEach(objectKeys(src), function (key) {
980 dst[key] = clone(src[key]);
99 });
100
1010 parents.pop();
1020 nodes.pop();
1030 return dst;
104 }
105 else {
1060 return src;
107 }
108 })(this.value);
109};
110
1111function walk (root, cb, immutable) {
1120 var path = [];
1130 var parents = [];
1140 var alive = true;
115
1160 return (function walker (node_) {
1170 var node = immutable ? copy(node_) : node_;
1180 var modifiers = {};
119
1200 var keepGoing = true;
121
1220 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) {
1330 if (!state.isRoot) {
1340 state.parent.node[state.key] = x;
135 }
1360 state.node = x;
1370 if (stopHere) keepGoing = false;
138 },
139 'delete' : function (stopHere) {
1400 delete state.parent.node[state.key];
1410 if (stopHere) keepGoing = false;
142 },
143 remove : function (stopHere) {
1440 if (isArray(state.parent.node)) {
1450 state.parent.node.splice(state.key, 1);
146 }
147 else {
1480 delete state.parent.node[state.key];
149 }
1500 if (stopHere) keepGoing = false;
151 },
152 keys : null,
1530 before : function (f) { modifiers.before = f },
1540 after : function (f) { modifiers.after = f },
1550 pre : function (f) { modifiers.pre = f },
1560 post : function (f) { modifiers.post = f },
1570 stop : function () { alive = false },
1580 block : function () { keepGoing = false }
159 };
160
1610 if (!alive) return state;
162
1630 function updateState() {
1640 if (typeof state.node === 'object' && state.node !== null) {
1650 if (!state.keys || state.node_ !== state.node) {
1660 state.keys = objectKeys(state.node)
167 }
168
1690 state.isLeaf = state.keys.length == 0;
170
1710 for (var i = 0; i < parents.length; i++) {
1720 if (parents[i].node_ === node_) {
1730 state.circular = parents[i];
1740 break;
175 }
176 }
177 }
178 else {
1790 state.isLeaf = true;
1800 state.keys = null;
181 }
182
1830 state.notLeaf = !state.isLeaf;
1840 state.notRoot = !state.isRoot;
185 }
186
1870 updateState();
188
189 // use return values to update if defined
1900 var ret = cb.call(state, state.node);
1910 if (ret !== undefined && state.update) state.update(ret);
192
1930 if (modifiers.before) modifiers.before.call(state, state.node);
194
1950 if (!keepGoing) return state;
196
1970 if (typeof state.node == 'object'
198 && state.node !== null && !state.circular) {
1990 parents.push(state);
200
2010 updateState();
202
2030 forEach(state.keys, function (key, i) {
2040 path.push(key);
205
2060 if (modifiers.pre) modifiers.pre.call(state, state.node[key], key);
207
2080 var child = walker(state.node[key]);
2090 if (immutable && hasOwnProperty.call(state.node, key)) {
2100 state.node[key] = child.node;
211 }
212
2130 child.isLast = i == state.keys.length - 1;
2140 child.isFirst = i == 0;
215
2160 if (modifiers.post) modifiers.post.call(state, child);
217
2180 path.pop();
219 });
2200 parents.pop();
221 }
222
2230 if (modifiers.after) modifiers.after.call(state, state.node);
224
2250 return state;
226 })(root).node;
227}
228
2291function copy (src) {
2300 if (typeof src === 'object' && src !== null) {
2310 var dst;
232
2330 if (isArray(src)) {
2340 dst = [];
235 }
2360 else if (isDate(src)) {
2370 dst = new Date(src.getTime ? src.getTime() : src);
238 }
2390 else if (isRegExp(src)) {
2400 dst = new RegExp(src);
241 }
2420 else if (isError(src)) {
2430 dst = { message: src.message };
244 }
2450 else if (isBoolean(src)) {
2460 dst = new Boolean(src);
247 }
2480 else if (isNumber(src)) {
2490 dst = new Number(src);
250 }
2510 else if (isString(src)) {
2520 dst = new String(src);
253 }
2540 else if (Object.create && Object.getPrototypeOf) {
2550 dst = Object.create(Object.getPrototypeOf(src));
256 }
2570 else if (src.constructor === Object) {
2580 dst = {};
259 }
260 else {
2610 var proto =
262 (src.constructor && src.constructor.prototype)
263 || src.__proto__
264 || {}
265 ;
2660 var T = function () {};
2670 T.prototype = proto;
2680 dst = new T;
269 }
270
2710 forEach(objectKeys(src), function (key) {
2720 dst[key] = src[key];
273 });
2740 return dst;
275 }
2760 else return src;
277}
278
2791var objectKeys = Object.keys || function keys (obj) {
2800 var res = [];
2810 for (var key in obj) res.push(key)
2820 return res;
283};
284
2851function toS (obj) { return Object.prototype.toString.call(obj) }
2861function isDate (obj) { return toS(obj) === '[object Date]' }
2871function isRegExp (obj) { return toS(obj) === '[object RegExp]' }
2881function isError (obj) { return toS(obj) === '[object Error]' }
2891function isBoolean (obj) { return toS(obj) === '[object Boolean]' }
2901function isNumber (obj) { return toS(obj) === '[object Number]' }
2911function isString (obj) { return toS(obj) === '[object String]' }
292
2931var isArray = Array.isArray || function isArray (xs) {
2940 return Object.prototype.toString.call(xs) === '[object Array]';
295};
296
2971var forEach = function (xs, fn) {
2982 if (xs.forEach) return xs.forEach(fn)
2990 else for (var i = 0; i < xs.length; i++) {
3000 fn(xs[i], i, xs);
301 }
302};
303
3041forEach(objectKeys(Traverse.prototype), function (key) {
3059 traverse[key] = function (obj) {
3060 var args = [].slice.call(arguments, 1);
3070 var t = new Traverse(obj);
3080 return t[key].apply(t, args);
309 };
310});
311
3121var hasOwnProperty = Object.hasOwnProperty || function (obj, key) {
3130 return key in obj;
314};
315

c:/noboxout/js-object-enhancements/node_modules/tap/node_modules/difflet/node_modules/charm/index.js

15.3%
163
25
138
LineHitsSource
11var tty = require('tty');
21var encode = require('./lib/encode');
31var Stream = require('stream').Stream;
4
51var exports = module.exports = function () {
60 var input = null;
70 function setInput (s) {
80 if (input) throw new Error('multiple inputs specified')
90 else input = s
10 }
11
120 var output = null;
130 function setOutput (s) {
140 if (output) throw new Error('multiple outputs specified')
150 else output = s
16 }
17
180 for (var i = 0; i < arguments.length; i++) {
190 var arg = arguments[i];
200 if (!arg) continue;
210 if (arg.readable) setInput(arg)
220 else if (arg.stdin || arg.input) setInput(arg.stdin || arg.input)
23
240 if (arg.writable) setOutput(arg)
250 else if (arg.stdout || arg.output) setOutput(arg.stdout || arg.output)
26
27 }
28
290 if (input && typeof input.fd === 'number' && tty.isatty(input.fd)) {
300 if (process.stdin.setRawMode) {
310 process.stdin.setRawMode(true);
32 }
330 else tty.setRawMode(true);
34 }
35
360 var charm = new Charm;
370 if (input) {
380 input.pipe(charm);
39 }
40
410 if (output) {
420 charm.pipe(output);
43 }
44
450 charm.once('^C', process.exit);
460 charm.once('end', function () {
470 if (input) {
480 if (typeof input.fd === 'number' && tty.isatty(input.fd)) {
490 if (process.stdin.setRawMode) {
500 process.stdin.setRawMode(false);
51 }
520 else tty.setRawMode(false);
53 }
540 input.destroy();
55 }
56 });
57
580 return charm;
59};
60
611var Charm = exports.Charm = function Charm () {
620 this.writable = true;
630 this.readable = true;
640 this.pending = [];
65}
66
671Charm.prototype = new Stream;
68
691Charm.prototype.write = function (buf) {
700 var self = this;
71
720 if (self.pending.length) {
730 var codes = extractCodes(buf);
740 var matched = false;
75
760 for (var i = 0; i < codes.length; i++) {
770 for (var j = 0; j < self.pending.length; j++) {
780 var cb = self.pending[j];
790 if (cb(codes[i])) {
800 matched = true;
810 self.pending.splice(j, 1);
820 break;
83 }
84 }
85 }
86
870 if (matched) return;
88 }
89
900 if (buf.length === 1) {
910 if (buf[0] === 3) self.emit('^C');
920 if (buf[0] === 4) self.emit('^D');
93 }
94
950 self.emit('data', buf);
96
970 return self;
98};
99
100
1011Charm.prototype.destroy = function () {
1020 this.end();
103};
104
1051Charm.prototype.end = function (buf) {
1060 if (buf) this.write(buf);
1070 this.emit('end');
108};
109
1101Charm.prototype.reset = function (cb) {
1110 this.write(encode('c'));
1120 return this;
113};
114
1151Charm.prototype.position = function (x, y) {
116 // get/set absolute coordinates
1170 if (typeof x === 'function') {
1180 var cb = x;
1190 this.pending.push(function (buf) {
1200 if (buf[0] === 27 && buf[1] === encode.ord('[')
121 && buf[buf.length-1] === encode.ord('R')) {
1220 var pos = buf.toString()
123 .slice(2,-1)
124 .split(';')
125 .map(Number)
126 ;
1270 cb(pos[1], pos[0]);
1280 return true;
129 }
130 });
1310 this.write(encode('[6n'));
132 }
133 else {
1340 this.write(encode(
135 '[' + Math.floor(y) + ';' + Math.floor(x) + 'f'
136 ));
137 }
1380 return this;
139};
140
1411Charm.prototype.move = function (x, y) {
142 // set relative coordinates
1430 var bufs = [];
144
1450 if (y < 0) this.up(-y)
1460 else if (y > 0) this.down(y)
147
1480 if (x > 0) this.right(x)
1490 else if (x < 0) this.left(-x)
150
1510 return this;
152};
153
1541Charm.prototype.up = function (y) {
1550 if (y === undefined) y = 1;
1560 this.write(encode('[' + Math.floor(y) + 'A'));
1570 return this;
158};
159
1601Charm.prototype.down = function (y) {
1610 if (y === undefined) y = 1;
1620 this.write(encode('[' + Math.floor(y) + 'B'));
1630 return this;
164};
165
1661Charm.prototype.right = function (x) {
1670 if (x === undefined) x = 1;
1680 this.write(encode('[' + Math.floor(x) + 'C'));
1690 return this;
170};
171
1721Charm.prototype.left = function (x) {
1730 if (x === undefined) x = 1;
1740 this.write(encode('[' + Math.floor(x) + 'D'));
1750 return this;
176};
177
1781Charm.prototype.column = function (x) {
1790 this.write(encode('[' + Math.floor(x) + 'G'));
1800 return this;
181};
182
1831Charm.prototype.push = function (withAttributes) {
1840 this.write(encode(withAttributes ? '7' : '[s'));
1850 return this;
186};
187
1881Charm.prototype.pop = function (withAttributes) {
1890 this.write(encode(withAttributes ? '8' : '[u'));
1900 return this;
191};
192
1931Charm.prototype.erase = function (s) {
1940 if (s === 'end' || s === '$') {
1950 this.write(encode('[K'));
196 }
1970 else if (s === 'start' || s === '^') {
1980 this.write(encode('[1K'));
199 }
2000 else if (s === 'line') {
2010 this.write(encode('[2K'));
202 }
2030 else if (s === 'down') {
2040 this.write(encode('[J'));
205 }
2060 else if (s === 'up') {
2070 this.write(encode('[1J'));
208 }
2090 else if (s === 'screen') {
2100 this.write(encode('[1J'));
211 }
212 else {
2130 this.emit('error', new Error('Unknown erase type: ' + s));
214 }
2150 return this;
216};
217
2181Charm.prototype.display = function (attr) {
2190 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];
2280 if (c === undefined) {
2290 this.emit('error', new Error('Unknown attribute: ' + attr));
230 }
2310 this.write(encode('[' + c + 'm'));
2320 return this;
233};
234
2351Charm.prototype.foreground = function (color) {
2360 if (typeof color === 'number') {
2370 if (color < 0 || color >= 256) {
2380 this.emit('error', new Error('Color out of range: ' + color));
239 }
2400 this.write(encode('[38;5;' + color + 'm'));
241 }
242 else {
2430 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
2540 if (!c) this.emit('error', new Error('Unknown color: ' + color));
2550 this.write(encode('[' + c + 'm'));
256 }
2570 return this;
258};
259
2601Charm.prototype.background = function (color) {
2610 if (typeof color === 'number') {
2620 if (color < 0 || color >= 256) {
2630 this.emit('error', new Error('Color out of range: ' + color));
264 }
2650 this.write(encode('[48;5;' + color + 'm'));
266 }
267 else {
2680 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
2790 if (!c) this.emit('error', new Error('Unknown color: ' + color));
2800 this.write(encode('[' + c + 'm'));
281 }
2820 return this;
283};
284
2851Charm.prototype.cursor = function (visible) {
2860 this.write(encode(visible ? '[?25h' : '[?25l'));
2870 return this;
288};
289
2901var extractCodes = exports.extractCodes = function (buf) {
2910 var codes = [];
2920 var start = -1;
293
2940 for (var i = 0; i < buf.length; i++) {
2950 if (buf[i] === 27) {
2960 if (start >= 0) codes.push(buf.slice(start, i));
2970 start = i;
298 }
2990 else if (start >= 0 && i === buf.length - 1) {
3000 codes.push(buf.slice(start));
301 }
302 }
303
3040 return codes;
305}
306

c:/noboxout/js-object-enhancements/node_modules/tap/node_modules/difflet/node_modules/charm/lib/encode.js

20.0%
10
2
8
LineHitsSource
11var encode = module.exports = function (xs) {
20 function bytes (s) {
30 if (typeof s === 'string') {
40 return s.split('').map(ord);
5 }
60 else if (Array.isArray(s)) {
70 return s.reduce(function (acc, c) {
80 return acc.concat(bytes(c));
9 }, []);
10 }
11 }
12
130 return new Buffer([ 0x1b ].concat(bytes(xs)));
14};
15
161var ord = encode.ord = function ord (c) {
170 return c.charCodeAt(0)
18};
19

c:/noboxout/js-object-enhancements/node_modules/tap/node_modules/difflet/node_modules/deep-is/index.js

16.3%
49
8
41
LineHitsSource
11var pSlice = Array.prototype.slice;
21var Object_keys = typeof Object.keys === 'function'
3 ? Object.keys
4 : function (obj) {
50 var keys = [];
60 for (var key in obj) keys.push(key);
70 return keys;
8 }
9;
10
111var deepEqual = module.exports = function (actual, expected) {
12 // enforce Object.is +0 !== -0
130 if (actual === 0 && expected === 0) {
140 return areZerosEqual(actual, expected);
15
16 // 7.1. All identical values are equivalent, as determined by ===.
170 } else if (actual === expected) {
180 return true;
19
200 } else if (actual instanceof Date && expected instanceof Date) {
210 return actual.getTime() === expected.getTime();
22
230 } else if (isNumberNaN(actual)) {
240 return isNumberNaN(expected);
25
26 // 7.3. Other pairs that do not both pass typeof value == 'object',
27 // equivalence is determined by ==.
280 } else if (typeof actual != 'object' && typeof expected != 'object') {
290 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 {
380 return objEquiv(actual, expected);
39 }
40};
41
421function isUndefinedOrNull(value) {
430 return value === null || value === undefined;
44}
45
461function isArguments(object) {
470 return Object.prototype.toString.call(object) == '[object Arguments]';
48}
49
501function isNumberNaN(value) {
51 // NaN === NaN -> false
520 return typeof value == 'number' && value !== value;
53}
54
551function areZerosEqual(zeroA, zeroB) {
56 // (1 / +0|0) -> Infinity, but (1 / -0) -> -Infinity and (Infinity !== -Infinity)
570 return (1 / zeroA) === (1 / zeroB);
58}
59
601function objEquiv(a, b) {
610 if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
620 return false;
63
64 // an identical 'prototype' property.
650 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.
680 if (isArguments(a)) {
690 if (!isArguments(b)) {
700 return false;
71 }
720 a = pSlice.call(a);
730 b = pSlice.call(b);
740 return deepEqual(a, b);
75 }
760 try {
770 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
810 return false;
82 }
83 // having the same number of owned properties (keys incorporates
84 // hasOwnProperty)
850 if (ka.length != kb.length)
860 return false;
87 //the same set of keys (although not necessarily the same order),
880 ka.sort();
890 kb.sort();
90 //~~~cheap key test
910 for (i = ka.length - 1; i >= 0; i--) {
920 if (ka[i] != kb[i])
930 return false;
94 }
95 //equivalent values for every corresponding key, and
96 //~~~possibly expensive deep test
970 for (i = ka.length - 1; i >= 0; i--) {
980 key = ka[i];
990 if (!deepEqual(a[key], b[key])) return false;
100 }
1010 return true;
102}
103

c:/noboxout/js-object-enhancements/node_modules/tap/node_modules/deep-equal/index.js

65.9%
41
27
14
LineHitsSource
11var pSlice = Array.prototype.slice;
21var Object_keys = typeof Object.keys === 'function'
3 ? Object.keys
4 : function (obj) {
50 var keys = [];
60 for (var key in obj) keys.push(key);
70 return keys;
8 }
9;
10
111var deepEqual = module.exports = function (actual, expected) {
12 // 7.1. All identical values are equivalent, as determined by ===.
13127 if (actual === expected) {
1484 return true;
15
1643 } else if (actual instanceof Date && expected instanceof Date) {
170 return actual.getTime() === expected.getTime();
18
19 // 7.3. Other pairs that do not both pass typeof value == 'object',
20 // equivalence is determined by ==.
2143 } else if (typeof actual != 'object' && typeof expected != 'object') {
220 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 {
3143 return objEquiv(actual, expected);
32 }
33}
34
351function isUndefinedOrNull(value) {
3686 return value === null || value === undefined;
37}
38
391function isArguments(object) {
4043 return Object.prototype.toString.call(object) == '[object Arguments]';
41}
42
431function objEquiv(a, b) {
4443 if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
450 return false;
46 // an identical 'prototype' property.
4743 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.
5043 if (isArguments(a)) {
510 if (!isArguments(b)) {
520 return false;
53 }
540 a = pSlice.call(a);
550 b = pSlice.call(b);
560 return deepEqual(a, b);
57 }
5843 try {
5943 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
630 return false;
64 }
65 // having the same number of owned properties (keys incorporates
66 // hasOwnProperty)
6743 if (ka.length != kb.length)
680 return false;
69 //the same set of keys (although not necessarily the same order),
7043 ka.sort();
7143 kb.sort();
72 //~~~cheap key test
7343 for (i = ka.length - 1; i >= 0; i--) {
7497 if (ka[i] != kb[i])
750 return false;
76 }
77 //equivalent values for every corresponding key, and
78 //~~~possibly expensive deep test
7943 for (i = ka.length - 1; i >= 0; i--) {
8097 key = ka[i];
8197 if (!deepEqual(a[key], b[key])) return false;
82 }
8343 return true;
84}
85

c:/noboxout/js-object-enhancements/node_modules/tap/node_modules/buffer-equal/index.js

25.0%
8
2
6
LineHitsSource
11var Buffer = require('buffer').Buffer; // for use with browserify
2
31module.exports = function (a, b) {
40 if (!Buffer.isBuffer(a)) return undefined;
50 if (!Buffer.isBuffer(b)) return undefined;
60 if (a.length !== b.length) return false;
7
80 for (var i = 0; i < a.length; i++) {
90 if (a[i] !== b[i]) return false;
10 }
11
120 return true;
13};
14

c:/noboxout/js-object-enhancements/node_modules/tap/lib/tap-test.js

66.7%
54
36
18
LineHitsSource
1// This is a very simple test framework that leverages the tap framework
2// to run tests and output tap-parseable results.
3
41module.exports = Test
5
61var 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
111inherits(Test, require("c:/noboxout/js-object-enhancements/node_modules/tap/lib/./tap-harness"))
12
131function Test (harness, name, conf) {
14 //console.error("test ctor")
155 if (!(this instanceof Test)) return new Test(harness, name, conf)
16
175 Test.super.call(this, Test)
18
195 conf.name = name || conf.name || "(anonymous)"
205 this.conf = conf
21
225 this.harness = harness
235 this.harness.add(this)
24}
25
26// it's taking too long!
271Test.prototype.timeout = function () {
28 // detect false alarms
290 if (this._ended) return
300 this.fail("Timeout!")
310 this.end()
32}
33
341Test.prototype.clear = function () {
350 this._started = false
360 this._ended = false
370 this._plan = null
380 this._bailedOut = false
390 this._testCount = 0
400 this.results = new Results()
41}
42
43// this gets called if a test throws ever
441Test.prototype.threw = function (ex) {
45 //console.error("threw!", ex.stack)
460 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")
490 if (!this._ended) this.end()
50}
51
521Test.prototype.comment = function (m) {
530 if (typeof m !== "string") {
540 return this.fail("Test.comment argument must be a string")
55 }
560 this.result("\n" + m.trim())
57}
58
591Test.prototype.result = function (res) {
6057 this.results.add(res)
6157 this._testCount ++
6257 this.emit("result", res)
6357 if (this._plan === this._testCount) {
640 process.nextTick(this._endNice.bind(this))
65 }
66}
67
681Test.prototype._endNice = function () {
690 if (!this._ended) this.end()
70}
71
72// parasitic
73// Who says you can't do multiple inheritance in js?
741Object.getOwnPropertyNames(assert).forEach(function (k) {
7573 if (k === "prototype" || k === "name") return
7669 var d = Object.getOwnPropertyDescriptor(assert, k)
77 , v = d.value
7871 if (!v) return
7967 d.value = assertParasite(v)
8067 Object.defineProperty(Test.prototype, k, d)
81})
82
8368function assertParasite (fn) { return function _testAssert () {
84 //console.error("_testAssert", fn.name, arguments)
8557 if (this._bailedOut) return
8657 var res = fn.apply(assert, arguments)
8757 this.result(res)
8857 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"
932Test.prototype.emit = (function (em) { return function (t) {
94 // bailouts bubble until handled
95124 if (t === "bailout" &&
96 this.listeners(t).length === 0 &&
97 this.harness) {
980 return this.harness.bailout(arguments[1])
99 }
100
101124 if (t === "error") return em.apply(this, arguments)
102124 try {
103124 em.apply(this, arguments)
104 } catch (ex) {
105 // any exceptions in a test are a failure
106 //console.error("caught!", ex.stack)
1070 this.threw(ex)
108 }
109}})(Test.super.prototype.emit)
110

c:/noboxout/js-object-enhancements/node_modules/tap/lib/tap-consumer.js

9.5%
126
12
114
LineHitsSource
11module.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
71var yamlish = require("yamlish")
8 , Results = require("c:/noboxout/js-object-enhancements/node_modules/tap/lib/./tap-results")
9 , inherits = require("inherits")
10
111TapConsumer.decode = TapConsumer.parse = function (str) {
120 var tc = new TapConsumer
13 , list = []
140 tc.on("data", function (res) {
150 list.push(res)
16 })
170 tc.end(str)
180 tc.results.list = list
190 return tc.results
20}
21
221inherits(TapConsumer, require("stream").Stream)
231function TapConsumer () {
240 if (!(this instanceof TapConsumer)) {
250 return new TapConsumer
26 }
27
280 TapConsumer.super.call(this)
290 this.results = new Results
300 this.readable = this.writable = true
31
320 this.on("data", function (res) {
330 if (typeof res === "object") this.results.add(res)
34 })
35
360 this._plan = null
370 this._buffer = ""
380 this._indent = []
390 this._current = null
400 this._actualCount = 0
410 this._passed = []
420 this._failed = []
43 //console.error("TapConsumer ctor done")
44}
45
461TapConsumer.prototype.bailedOut = false
47
481TapConsumer.prototype.write = function (chunk) {
490 if (!this.writable) this.emit("error", new Error("not writable"))
500 if (this.bailedOut) return true
51
520 this._buffer = this._buffer + chunk
53 // split it up into lines.
540 var lines = this._buffer.split(/\r?\n/)
55 // ignore the last line, since it might be incomplete.
560 this._buffer = lines.pop()
57
580 for (var i = 0, l = lines.length; i < l; i ++) {
59 //console.error([i, lines[i]])
60 // see if it's indented.
610 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.
650 if (spaces) {
660 var c = i
670 while (c < l && (!lines[c].trim() || lines[c].match(/^\s/))) {
680 this._indent.push(lines[c++])
69 }
70 //console.error(c-i, "indented", this._indent, this._current)
710 i = c - 1
720 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
760 this._parseLine(line)
77 }
780 return true
79}
80
811TapConsumer.prototype.end = function () {
82 // finish up any hanging indented sections or final buffer
830 if (this._buffer.match(/^\s/)) this._indent.push(this.buffer)
840 else this._parseLine(this._buffer)
85
860 if (!this.bailedOut &&
87 this._plan !== null &&
88 this.results.testsTotal !== this._plan) {
890 while (this._actualCount < this._plan) {
900 this.emit("data", {ok: false, name:"MISSING TEST",
91 id:this._actualCount ++ })
92 }
93 }
94
950 this._parseLine("")
960 this._buffer = ""
970 this.writable = false
980 this.emit("end", null, this._actualCount, this._passed)
99}
100
1011TapConsumer.prototype._parseLine = function (line) {
1020 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.
1070 if (this._current && this._indent.length) {
1080 this._parseIndented()
109 }
1100 this._indent.length = 0
1110 if (this._current) {
1120 if (this._current.ok) this._passed.push(this._current.id)
1130 else this._failed.push(this._current.id)
1140 this.emit("data", this._current)
115 }
1160 this._current = null
1170 line = line.trim()
1180 if (!line) return
119 // try to see what kind of line this is.
120
1210 var bo
1220 if (bo = line.match(/^bail out!\s*(.*)$/i)) {
1230 this.bailedOut = true
124 // this.emit("error", new Error(line))
1250 this.emit("bailout", bo[1])
1260 return
127 }
128
1290 if (line.match(/^#/)) { // just a comment
1300 line = line.replace(/^#+/, "").trim()
131 // console.error("outputting comment", [line])
1320 if (line) this.emit("data", line)
1330 return
134 }
135
1360 var plan = line.match(/^([0-9]+)\.\.([0-9]+)(?:\s+#(.*))?$/)
1370 if (plan) {
1380 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"
1440 this._plan = end
1450 this.emit("plan", end, comment)
146 // plan must come before or after all tests.
1470 if (this._actualCount !== 0) {
1480 this._sawPlan = true
149 }
1500 return
151 }
152
1530 if (line.match(/^(not )?ok(?:\s+([0-9]+))?/)) {
1540 this._parseResultLine(line)
1550 return
156 }
157
158 // garbage. emit as a comment.
159 //console.error("emitting", [line.trim()])
1600 if (line.trim()) this.emit("data", line.trim())
161}
162
1631TapConsumer.prototype._parseDirective = function (line) {
1640 line = line.trim()
1650 if (line.match(/^TODO\b/i)) {
1660 return { todo:true, explanation: line.replace(/^TODO\s*/i, "") }
1670 } else if (line.match(/^SKIP\b/i)) {
1680 return { skip:true, explanation: line.replace(/^SKIP\s*/i, "") }
169 }
170}
171
1721TapConsumer.prototype._parseResultLine = function (line) {
1730 this._actualCount ++
1740 if (this._sawPlan) {
1750 this.emit("data", {ok: false, name:"plan in the middle of tests"
176 ,id:this._actualCount ++})
177 }
1780 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]))
1880 rest = rest.replace(/([^\\])((?:\\\\)*)#/g, "$1\n$2").split("\n")
1890 name = rest.shift()
1900 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.
1940 var dir = this._parseDirective(rest.trim())
1950 if (!dir) name += rest ? "#" + rest : ""
196 else {
1970 res.ok = true
1980 if (dir.skip) res.skip = true
1990 else if (dir.todo) res.todo = true
2000 if (dir.explanation) res.explanation = dir.explanation
201 }
2020 res.name = name
203
204 //console.error(line, [ok, id, name])
2050 this._current = res
206}
207
2081TapConsumer.prototype._parseIndented = function () {
209 // pull yamlish block out
2100 var ind = this._indent
211 , ys
212 , ye
213 , yind
214 , diag
215 //console.error(ind, this._indent)
2160 for (var i = 0, l = ind.length; i < l; i ++) {
2170 var line = ind[i]
218 , lt = line.trim()
2190 if (!ys) {
2200 ys = line.match(/^(\s*)---(.*)$/)
2210 if (ys) {
2220 yind = ys[1]
2230 diag = [ys[2]]
224 //console.error([line,ys, diag])
2250 continue
2260 } else if (lt) this.emit("data", lt)
2270 } else if (ys && !ye) {
2280 if (line === yind + "...") ye = true
229 else {
2300 diag.push(line.substr(yind.length))
231 }
2320 } else if (ys && ye && lt) this.emit("data", lt)
233 }
2340 if (diag) {
235 //console.error('about to parse', diag)
2360 diag = yamlish.decode(diag.join("\n"))
237 //console.error('parsed', diag)
2380 Object.keys(diag).forEach(function (k) {
239 //console.error(this._current, k)
2400 if (!this._current.hasOwnProperty(k)) this._current[k] = diag[k]
241 }, this)
242 }
243}
244

c:/noboxout/js-object-enhancements/node_modules/tap/lib/tap-runner.js

6.4%
204
13
191
LineHitsSource
11var 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
181module.exports = Runner
19
201inherits(Runner, TapProducer)
21
221function Runner (options, cb) {
230 this.options = options
24
250 var diag = this.options.diag
260 var dir = this.options.argv.remain
270 Runner.super.call(this, diag)
28
290 this.doCoverage = doCoverage
30 // An array of full paths to files to obtain coverage
310 this.coverageFiles = []
32 // The source of these files
330 this.coverageFilesSource = {}
34 // Where to write coverage information
350 this.coverageOutDir = this.options["coverage-dir"]
36 // Temporary test files bunkerified we'll remove later
370 this.f2delete = []
38 // Raw coverage stats, as read from JSON files
390 this.rawCovStats = []
40 // Processed coverage information, per file to cover:
410 this.covStats = {}
42
430 if (dir) {
440 var filesToCover = this.options.cover
45
460 if (doCoverage) {
470 var mkdirp = require("mkdirp")
480 this.coverageOutDir = path.resolve(this.coverageOutDir)
490 this.getFilesToCover(filesToCover)
500 var self = this
510 return mkdirp(this.coverageOutDir, 0755, function (er) {
520 if (er) return self.emit("error", er)
530 self.run(dir, cb)
54 })
55 }
56
570 this.run(dir, cb)
58 }
59}
60
61
621Runner.prototype.run = function() {
630 var self = this
64 , args = Array.prototype.slice.call(arguments)
65 , cb = args.pop() || finish
66
670 function finish (er) {
680 if (er) {
690 self.emit("error", er)
70 }
71
720 if (!doCoverage) return self.end()
73
74 // Cleanup temporary test files with coverage:
750 self.f2delete.forEach(function(f) {
760 fs.unlinkSync(f)
77 })
780 self.getFilesToCoverSource(function(err, data) {
790 if (err) {
800 self.emit("error", err)
81 }
820 self.getPerFileCovInfo(function(err, data) {
830 if (err) {
840 self.emit("error", err)
85 }
860 self.mergeCovStats(function(err, data) {
870 if (err) {
880 self.emit("error", err)
89 }
900 CovHtml(self.covStats, self.coverageOutDir, function() {
910 self.end()
92 })
93 })
94 })
95 })
96 }
97
980 if (Array.isArray(args[0])) {
990 args = args[0]
100 }
1010 self.runFiles(args, "", cb)
102}
103
1041Runner.prototype.runDir = function (dir, cb) {
1050 var self = this
1060 fs.readdir(dir, function (er, files) {
1070 if (er) {
1080 self.write(assert.fail("failed to readdir " + dir, { error: er }))
1090 self.end()
1100 return
111 }
1120 files = files.sort(function(a, b) {
1130 return a > b ? 1 : -1
114 })
1150 files = files.filter(function(f) {
1160 return !f.match(/^\./)
117 })
1180 files = files.map(path.resolve.bind(path, dir))
119
1200 self.runFiles(files, path.resolve(dir), cb)
121 })
122}
123
124
1251Runner.prototype.runFiles = function (files, dir, cb) {
126
1270 var self = this
1280 chain(files.map(function(f) {
1290 return function (cb) {
1300 if (self._bailedOut) return
1310 var relDir = dir || path.dirname(f)
132 , fileName = relDir === "." ? f : f.substr(relDir.length + 1)
133
1340 self.write(fileName)
1350 fs.lstat(f, function(er, st) {
1360 if (er) {
1370 self.write(assert.fail("failed to stat " + f, {error: er}))
1380 return cb()
139 }
140
1410 var cmd = f, args = [], env = {}
142
1430 if (path.extname(f) === ".js") {
1440 cmd = "node"
1450 if (self.options.gc) {
1460 args.push("--expose-gc")
147 }
1480 args.push(fileName)
1490 } else if (path.extname(f) === ".coffee") {
1500 cmd = "coffee"
1510 args.push(fileName)
152 } else {
153 // Check if file is executable
1540 if ((st.mode & 0100) && process.getuid) {
1550 if (process.getuid() != st.uid) {
1560 return cb()
157 }
1580 } else if ((st.mode & 0010) && process.getgid) {
1590 if (process.getgid() != st.gid) {
1600 return cb()
161 }
1620 } else if ((st.mode & 0001) == 0) {
1630 return cb()
164 }
165 }
166
1670 if (st.isDirectory()) {
1680 return self.runDir(f, cb)
169 }
170
1710 if (doCoverage && path.extname(f) === ".js") {
1720 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
1780 fs.writeFileSync(tmpFname, fcontents, "utf8")
1790 args.splice(-1, 1, tmpFname)
180 }
181
1820 for (var i in process.env) {
1830 env[i] = process.env[i]
184 }
1850 env.TAP = 1
186
1870 var cp = child_process.spawn(cmd, args, { env: env, cwd: relDir })
188 , out = ""
189 , err = ""
190 , tc = new TapConsumer()
191 , childTests = [f]
192
1930 var timeout = setTimeout(function () {
1940 if (!cp._ended) {
1950 cp._timedOut = true
1960 cp.kill()
197 }
198 }, self.options.timeout * 1000)
199
2000 tc.on("data", function(c) {
2010 self.emit("result", c)
2020 self.write(c)
203 })
204
2050 tc.on("bailout", function (message) {
2060 clearTimeout(timeout)
2070 console.log("# " + f.substr(process.cwd().length + 1))
2080 process.stderr.write(err)
2090 process.stdout.write(out + "\n")
2100 self._bailedOut = true
2110 cp._ended = true
2120 cp.kill()
213 })
214
2150 cp.stdout.pipe(tc)
2160 cp.stdout.on("data", function (c) { out += c })
2170 cp.stderr.on("data", function (c) {
2180 if (self.options.stderr) process.stderr.write(c)
2190 err += c
220 })
221
2220 cp.on("exit", function (code, signal) {
2230 if (cp._ended) return
2240 cp._ended = true
2250 var ok = !cp._timedOut && code === 0
2260 clearTimeout(timeout)
227 //childTests.forEach(function (c) { self.write(c) })
2280 var res = { name: path.dirname(f).replace(process.cwd() + "/", "")
229 + "/" + fileName
230 , ok: ok
231 , exit: code }
232
2330 if (cp._timedOut)
2340 res.timedOut = cp._timedOut
2350 if (signal)
2360 res.signal = signal
237
2380 if (err) {
2390 res.stderr = err
2400 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.
2460 console.error(err)
247 }
248 }
249
250 // tc.results.ok = tc.results.ok && ok
2510 tc.results.add(res)
2520 res.command = [cmd].concat(args).map(JSON.stringify).join(" ")
2530 self.emit("result", res)
2540 self.emit("file", f, res, tc.results)
2550 self.write(res)
2560 self.write("\n")
2570 if (doCoverage) {
2580 self.f2delete.push(tmpFname)
259 }
2600 cb()
261 })
262 })
263 }
264 }), cb)
265
2660 return self
267}
268
269
270// Get an array of full paths to files we are interested into obtain
271// code coverage.
2721Runner.prototype.getFilesToCover = function(filesToCover) {
2730 var self = this
2740 filesToCover = filesToCover.split(",").map(function(f) {
2750 return path.resolve(f)
276 }).filter(function(f) {
2770 return path.existsSync(f)
278 })
279
2800 function recursive(f) {
2810 if (path.extname(f) === "") {
282 // Is a directory:
2830 fs.readdirSync(f).forEach(function(p) {
2840 recursive(f + "/" + p)
285 })
286 } else {
2870 self.coverageFiles.push(f)
288 }
289 }
2900 filesToCover.forEach(function(f) {
2910 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.
2971Runner.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.
3000 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.
3091Runner.prototype.coverFooter = function() {
3100 var self = this
311 // This needs to be a string with proper interpolations:
3120 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
3651Runner.prototype.getFilesToCoverSource = function(cb) {
3660 var self = this
3670 asyncMap(self.coverageFiles, function(f, cb) {
3680 fs.readFile(f, "utf8", function(err, data) {
3690 var lc = 0
3700 if (err) {
3710 cb(err)
372 }
3730 self.coverageFilesSource[f] = data.split("\n").map(function(l) {
3740 lc += 1
3750 return { number: lc, source: l }
376 })
3770 cb()
378 })
379 }, cb)
380}
381
3821Runner.prototype.getPerFileCovInfo = function(cb) {
3830 var self = this
384 , covPath = path.resolve(self.coverageOutDir)
385
3860 fs.readdir(covPath, function(err, files) {
3870 if (err) {
3880 self.emit("error", err)
389 }
3900 var covFiles = files.filter(function(f) {
3910 return path.extname(f) === ".json"
392 })
3930 asyncMap(covFiles, function(f, cb) {
3940 fs.readFile(path.resolve(covPath, f), "utf8", function(err, data) {
3950 if (err) {
3960 cb(err)
397 }
3980 self.rawCovStats.push(JSON.parse(data))
3990 cb()
400 })
401 }, function(f, cb) {
4020 fs.unlink(path.resolve(covPath, f), cb)
403 }, cb)
404 })
405}
406
4071Runner.prototype.mergeCovStats = function(cb) {
4080 var self = this
4090 self.rawCovStats.forEach(function(st) {
4100 Object.keys(st).forEach(function(i) {
411 // If this is the first time we reach this file, just add the info:
4120 if (!self.covStats[i]) {
4130 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)
4200 self.covStats[i].missing = self.covStats[i].missing.filter(
421 function(l) {
4220 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
4310 Object.keys(self.covStats).forEach(function(f) {
4320 self.covStats[f].missing = self.covStats[f].missing.map(function(line) {
4330 return { number: line.number, source: line.source }
434 })
435 })
436
4370 Object.keys(self.coverageFilesSource).forEach(function(f) {
4380 if (!self.covStats[f]) {
4390 self.covStats[f] = { missing: self.coverageFilesSource[f]
440 , percentage: 0
441 }
442 }
4430 self.covStats[f].lines = self.coverageFilesSource[f]
4440 self.covStats[f].loc = self.coverageFilesSource[f].length
445
4460 if (!self.covStats[f].percentage) {
4470 self.covStats[f].percentage =
448 1 - (self.covStats[f].missing.length / self.covStats[f].loc)
449 }
450
451 })
4520 cb()
453}
454

c:/noboxout/js-object-enhancements/node_modules/tap/node_modules/slide/lib/slide.js

100.0%
3
3
0
LineHitsSource
11exports.asyncMap = require("c:/noboxout/js-object-enhancements/node_modules/tap/node_modules/slide/lib/./async-map")
21exports.bindActor = require("c:/noboxout/js-object-enhancements/node_modules/tap/node_modules/slide/lib/./bind-actor")
31exports.chain = require("c:/noboxout/js-object-enhancements/node_modules/tap/node_modules/slide/lib/./chain")
4

c:/noboxout/js-object-enhancements/node_modules/tap/node_modules/slide/lib/async-map.js

8.0%
25
2
23
LineHitsSource
1
2/*
3usage:
4
5// do something to a list of things
6asyncMap(myListOfStuff, function (thing, cb) { doSomething(thing.foo, cb) }, cb)
7// do more than one thing to each item
8asyncMap(list, fooFn, barFn, cb)
9
10*/
11
121module.exports = asyncMap
13
141function asyncMap () {
150 var steps = Array.prototype.slice.call(arguments)
16 , list = steps.shift() || []
17 , cb_ = steps.pop()
180 if (typeof cb_ !== "function") throw new Error(
19 "No callback provided to asyncMap")
200 if (!list) return cb_(null, [])
210 if (!Array.isArray(list)) list = [list]
220 var n = steps.length
23 , data = [] // 2d array
24 , errState = null
25 , l = list.length
26 , a = l * n
270 if (!a) return cb_(null, [])
280 function cb (er) {
290 if (errState) return
300 var argLen = arguments.length
310 for (var i = 1; i < argLen; i ++) if (arguments[i] !== undefined) {
320 data[i - 1] = (data[i - 1] || []).concat(arguments[i])
33 }
34 // see if any new things have been added.
350 if (list.length > l) {
360 var newList = list.slice(l)
370 a += (list.length - l) * n
380 l = list.length
390 process.nextTick(function () {
400 newList.forEach(function (ar) {
410 steps.forEach(function (fn) { fn(ar, cb) })
42 })
43 })
44 }
45
460 if (er || --a === 0) {
470 errState = er
480 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.
530 list.forEach(function (ar) {
540 steps.forEach(function (fn) { fn(ar, cb) })
55 })
56}
57

c:/noboxout/js-object-enhancements/node_modules/tap/node_modules/slide/lib/bind-actor.js

18.2%
11
2
9
LineHitsSource
11module.exports = bindActor
21function bindActor () {
30 var args =
4 Array.prototype.slice.call
5 (arguments) // jswtf.
6 , obj = null
7 , fn
80 if (typeof args[0] === "object") {
90 obj = args.shift()
100 fn = args.shift()
110 if (typeof fn === "string")
120 fn = obj[ fn ]
130 } else fn = args.shift()
140 return function (cb) {
150 fn.apply(obj, args.concat(cb)) }
16}
17

c:/noboxout/js-object-enhancements/node_modules/tap/node_modules/slide/lib/chain.js

26.7%
15
4
11
LineHitsSource
11module.exports = chain
21var bindActor = require("c:/noboxout/js-object-enhancements/node_modules/tap/node_modules/slide/lib/./bind-actor.js")
32chain.first = {} ; chain.last = {}
41function chain (things, cb) {
50 var res = []
60 ;(function LOOP (i, len) {
70 if (i >= len) return cb(null,res)
80 if (Array.isArray(things[i]))
90 things[i] = bindActor.apply(null,
10 things[i].map(function(i){
110 return (i===chain.first) ? res[0]
12 : (i===chain.last)
13 ? res[res.length - 1] : i }))
140 if (!things[i]) return LOOP(i + 1, len)
150 things[i](function (er, data) {
160 if (er) return cb(er, res)
170 if (data !== undefined) res = res.concat(data)
180 LOOP(i + 1, len)
19 })
20 })(0, things.length) }
21

c:/noboxout/js-object-enhancements/node_modules/tap/lib/tap-cov-html.js

9.5%
21
2
19
LineHitsSource
11var fs = require('fs'),
2 path = require('path'),
3 asyncMap = require("slide").asyncMap,
4 util = require('util');
5
61var CovHtml = module.exports = function(cov_stats, cov_dir, cb) {
70 var index = [];
8
90 asyncMap(
10 Object.keys(cov_stats),
11 function(f, cb) {
120 var st = cov_stats[f],
13 missing_lines = st.missing.map(function(l) {
140 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) {
330 var number = line.number,
34 color = (missing_lines.indexOf(number) !== -1) ? '#fcc' : '#cfc';
350 return '<li id="L' + line.number + '" style="background-color: ' + color +
36 ';">' + line.source.replace(/</g, "&lt;") + '</li>';
37 }).join('\n') +
38 '</ol>\n' +
39 '<h2>Data</h2>\n'+
40 '<pre>' + util.inspect(st, true, Infinity, false).replace(/</g, "&lt;") + '</pre></body>\n</html>';
41
420 fs.writeFile(
43 cov_dir + '/' +
44 f.replace(process.cwd() + '/', '').replace(/\//g, '+') + '.html',
45 out,
46 'utf8',
47 function(err) {
480 if (err) {
490 throw err;
50 }
510 index.push(f);
520 cb();
53 });
54 },
55 function(err) {
560 if (err) {
570 throw err;
58 }
590 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) {
630 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
680 fs.writeFile(cov_dir + '/index.html', out, 'utf8', function(err) {
690 if (err) {
700 throw err;
71 }
720 cb();
73 });
74 }
75 );
76};
77
78
79

c:/noboxout/js-object-enhancements/node_modules/ass/lib/serialize.js

90.0%
10
9
1
LineHitsSource
1// extract coverage data from the _$jscoverage global, and serialize it into
2// a simple json format.
31module.exports = function() {
41 var jscoverage = global._$jscoverage;
51 var a = [];
6
71 if (jscoverage) {
81 Object.keys(jscoverage).forEach(function(file) {
926 var o = {
10 file: file,
11 source: jscoverage[file].source,
12 hits: [ ]
13 }
1426 for (var i = 0; i < o.source.length; i++) {
153905 o.hits.push(jscoverage[file][i]);
16 }
1725 a.push(o);
18 });
19 }
20
210 return JSON.stringify(a, null, " ");
22};
23

c:/noboxout/js-object-enhancements/node_modules/ass/lib/reporters/html.js

87.2%
39
34
5
LineHitsSource
11var cheerio = require('cheerio'),
2 fs = require('fs'),
3 path = require('path');
4
5// our html reporter
61module.exports = function(data) {
7 // let's write a looong function.
8
9 // parse html for our template
101 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
141 var gHits = 0, gMisses = 0;
15
161 Object.keys(data).forEach(function(fileName) {
1727 var f = $('#files .file.template').clone();
1827 f.removeClass('template');
1927 f.find('h2').attr('id', fileName).text(fileName);
20
2127 var hits = 0,
22 misses = 0;
23
2427 var srcTemplate = f.find('tr.template');
2527 for (var i = 1; i <= data[fileName].source.length; i++) {
26 // and add the source line
273939 var s = srcTemplate.clone().removeClass('template');
283940 s.find('.line').text(i);
293941 s.find('.hits').text(data[fileName][i]);
303941 s.find('.source').text(data[fileName].source[i - 1]);
31
323943 if (data[fileName][i]) {
33666 s.addClass('hit');
34667 hits++;
353278 } else if (data[fileName][i] !== undefined) {
361306 s.addClass('miss');
371306 misses++;
38 }
39
403951 f.find('#source tbody').append(s);
41 }
42
4326 var pct = (100.0 * hits / (hits + misses));
4426 f.find('.stats .percentage').text(pct.toFixed(1) + '%');
4526 f.find('.stats .sloc').text(hits + misses);
4626 f.find('.stats .hits').text(hits);
4726 f.find('.stats .misses').text(misses);
48
4926 $('#files').append(f);
50
51 // and an entry in the menu
5226 var m = $('#menu li.template').clone().removeClass('template');
5326 m.find('a').attr('href', '#' + fileName).text(fileName);
5426 m.find('.cov').text(pct.toFixed(0) + '%');
5526 $('#menu').append(m);
56
57 // update global stats
5826 gHits += hits;
5926 gMisses += misses;
60 });
61
62 // global stats
630 $('#stats .percentage').text((100.0 * gHits / (gHits + gMisses)).toFixed(1) + '%');
640 $('#stats .sloc').text(gHits + gMisses);
650 $('#stats .hits').text(gHits);
660 $('#stats .misses').text(gMisses);
67
680 return $.html();
69};
70

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/index.js

100.0%
2
2
0
LineHitsSource
1/**
2 * Export cheerio (with )
3 */
4
51exports = module.exports = process.env.CHEERIO_COV
6 ? require('./lib-cov/cheerio')
7 : require('./lib/cheerio');
8
9/*
10 Export the version
11*/
12
131exports.version = require('./package').version;
14

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/lib/cheerio.js

83.3%
42
35
7
LineHitsSource
1/*
2 Module dependencies
3*/
4
51var 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
161var api = ['attributes', 'traversing', 'manipulation', 'css'];
17
18/*
19 * A simple way to check for HTML strings or ID strings
20 */
21
221var quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/;
23
24/**
25 * Static Methods
26 */
27
281var $ = require('./static');
29
30/*
31 * Instance of cheerio
32 */
33
341var Cheerio = module.exports = function(selector, context, root) {
3563706 if (!(this instanceof Cheerio)) return new Cheerio(selector, context, root);
36
37 // $(), $(null), $(undefined), $(false)
38123298 if (!selector) return this;
39
404206 if (root) {
41113 if (typeof root === 'string') root = parse(root);
42113 this._root = this.make(root, this);
43 }
44
45 // $($)
464212 if (selector.cheerio) return selector;
47
48 // $(dom)
494215 if (selector.name || Array.isArray(selector))
500 return this.make(selector, this);
51
52 // $(<html>)
534219 if (typeof selector === 'string' && isHtml(selector)) {
544107 return this.make(parse(selector).children);
55 }
56
57 // If we don't have a context, maybe we have a root, from loading
58113 if (!context) {
59113 context = this._root;
600 } else if (typeof context === 'string') {
610 if (isHtml(context)) {
62 // $('li', '<ul>...</ul>')
630 context = parse(context);
640 context = this.make(context, this);
65 } else {
66 // $('li', 'ul')
670 selector = [context, selector].join(' ');
680 context = this._root;
69 }
70 }
71
72 // If we still don't have a context, return
73113 if (!context) return this;
74
75 // #id, .class, tag
76113 return context.find(selector);
77};
78
79/**
80 * Inherit from `static`
81 */
82
831Cheerio.__proto__ = require('./static');
84
85/*
86 * Set a signature of the object
87 */
88
891Cheerio.prototype.cheerio = '[cheerio object]';
90
91/*
92 * Cheerio default options
93 */
94
951Cheerio.prototype.options = {
96 ignoreWhitespace: false,
97 xmlMode: false,
98 lowerCaseTags: false
99};
100
101/*
102 * Make cheerio an array-like object
103 */
104
1051Cheerio.prototype.length = 0;
1061Cheerio.prototype.sort = [].splice;
107
108/*
109 * Check if string is HTML
110 */
1111var isHtml = function(str) {
112 // Faster than running regex, if str starts with `<` and ends with `>`, assume it's HTML
1138445 if (str.charAt(0) === '<' && str.charAt(str.length - 1) === '>' && str.length >= 3) return true;
114
115 // Run the regex
116113 var match = quickExpr.exec(str);
117113 return !!(match && match[1]);
118};
119
120/*
121 * Make a cheerio object
122 */
123
1241Cheerio.prototype.make = function(dom, context) {
12560878 if (dom.cheerio) return dom;
12660894 dom = (Array.isArray(dom)) ? dom : [dom];
12760910 return _.extend(context || new Cheerio(), dom, { length: dom.length });
128};
129
130/**
131 * Turn a cheerio object into an array
132 */
133
1341Cheerio.prototype.toArray = function() {
1354186 return [].slice.call(this, 0);
136};
137
138/**
139 * Plug in the API
140 */
1411api.forEach(function(mod) {
1424 _.extend(Cheerio.prototype, require('./api/' + mod));
143});
144

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/index.js

100.0%
4
4
0
LineHitsSource
11exports = module.exports = require('./lib/select');
2
3/*
4 Export the version
5*/
61exports.version = (function() {
71 var pkg = require('fs').readFileSync(__dirname + '/package.json', 'utf8');
81 return JSON.parse(pkg).version;
9})();
10

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/lib/select.js

92.9%
14
13
1
LineHitsSource
1/*
2 * Module dependencies
3 */
41var CSSselect = require('CSSselect'),
5 isArray = Array.isArray;
6
7/*
8 * Select function
9 */
101exports = module.exports = function(query, dom) {
1117005 dom = normalize(dom);
12
1317013 return CSSselect.iterate(query, dom);
14};
15
16/*
17 * Normalize the dom
18 */
191var normalize = exports.normalize = function(dom) {
2017041 dom = dom.cheerio ? dom.toArray() : dom;
2117045 dom = isArray(dom) ? dom : [dom];
22
2317053 var len = dom.length,
24 out = [],
25 elem;
26
2717069 for(var i = 0; i < len; i++) {
2850917 elem = dom[i];
2950929 if(elem.type === 'root') {
300 out = out.concat(elem.children || []);
31 } else {
3250965 out.push(elem);
33 }
34 }
35
3617105 return out;
37};

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/index.js

88.0%
25
22
3
LineHitsSource
11"use strict";
2
31module.exports = CSSselect;
4
51var 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
141function getSelectorFunc(searchFunc){
152 return function select(query, elems, options){
1634370 if(typeof query !== "function") query = compile(query, options);
1717189 if(!Array.isArray(elems)) elems = getChildren(elems);
1817193 else elems = removeSubsets(elems);
1917197 return searchFunc(query, elems);
20 };
21}
22
231var selectAll = getSelectorFunc(function selectAll(query, elems){
2417217 return (query === falseFunc || !elems || elems.length === 0) ? [] : findAll(query, elems);
25});
26
271var selectOne = getSelectorFunc(function selectOne(query, elems){
280 return (query === falseFunc || !elems || elems.length === 0) ? null : findOne(query, elems);
29});
30
311function is(elem, query, options){
320 return (typeof query === "function" ? query : compile(query, options))(elem);
33}
34
35/*
36 the exported interface
37*/
381function CSSselect(query, elems, options){
390 return selectAll(query, elems, options);
40}
41
421CSSselect.compile = compile;
431CSSselect.filters = Pseudos.filters;
441CSSselect.pseudos = Pseudos.pseudos;
45
461CSSselect.selectAll = selectAll;
471CSSselect.selectOne = selectOne;
48
491CSSselect.is = is;
50
51//legacy methods (might be removed)
521CSSselect.parse = compile;
531CSSselect.iterate = selectAll;
54

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/lib/pseudos.js

7.4%
136
10
126
LineHitsSource
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
141var 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
301function getFirstElement(elems){
310 for(var i = 0; elems && i < elems.length; i++){
320 if(isTag(elems[i])) return elems[i];
33 }
34}
35
361function getAttribFunc(name, value){
377 var data = {name: name, value: value};
387 return function attribFunc(next){
390 return checkAttrib(next, data);
40 };
41}
42
431function getChildFunc(next){
440 return function(elem){
450 return !!getParent(elem) && next(elem);
46 };
47}
48
491var filters = {
50 contains: function(next, text){
510 if(
52 (text.charAt(0) === "\"" || text.charAt(0) === "'") &&
53 text.charAt(0) === text.substr(-1)
54 ){
550 text = text.slice(1, -1);
56 }
570 return function contains(elem){
580 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){
650 return function firstChild(elem){
660 return getFirstElement(getSiblings(elem)) === elem && next(elem);
67 };
68 },
69 "last-child": function(next){
700 return function lastChild(elem){
710 var siblings = getSiblings(elem);
72
730 for(var i = siblings.length - 1; i >= 0; i--){
740 if(siblings[i] === elem) return next(elem);
750 if(isTag(siblings[i])) break;
76 }
77
780 return false;
79 };
80 },
81 "first-of-type": function(next){
820 return function firstOfType(elem){
830 var siblings = getSiblings(elem);
84
850 for(var i = 0; i < siblings.length; i++){
860 if(isTag(siblings[i])){
870 if(siblings[i] === elem) return next(elem);
880 if(getName(siblings[i]) === getName(elem)) break;
89 }
90 }
91
920 return false;
93 };
94 },
95 "last-of-type": function(next){
960 return function lastOfType(elem){
970 var siblings = getSiblings(elem);
98
990 for(var i = siblings.length-1; i >= 0; i--){
1000 if(isTag(siblings[i])){
1010 if(siblings[i] === elem) return next(elem);
1020 if(getName(siblings[i]) === getName(elem)) break;
103 }
104 }
105
1060 return false;
107 };
108 },
109 "only-of-type": function(next){
1100 return function onlyOfType(elem){
1110 var siblings = getSiblings(elem);
112
1130 for(var i = 0, j = siblings.length; i < j; i++){
1140 if(isTag(siblings[i])){
1150 if(siblings[i] === elem) continue;
1160 if(getName(siblings[i]) === getName(elem)) return false;
117 }
118 }
119
1200 return next(elem);
121 };
122 },
123 "only-child": function(next){
1240 return function onlyChild(elem){
1250 var siblings = getSiblings(elem);
126
1270 for(var i = 0; i < siblings.length; i++){
1280 if(isTag(siblings[i]) && siblings[i] !== elem) return false;
129 }
130
1310 return next(elem);
132 };
133 },
134 "nth-child": function(next, rule){
1350 var func = getNCheck(rule);
136
1370 if(func === falseFunc) return func;
1380 if(func === trueFunc) return getChildFunc(next);
139
1400 return function nthChild(elem){
1410 var siblings = getSiblings(elem);
142
1430 for(var i = 0, pos = 0; i < siblings.length; i++){
1440 if(isTag(siblings[i])){
1450 if(siblings[i] === elem) break;
1460 else pos++;
147 }
148 }
149
1500 return func(pos) && next(elem);
151 };
152 },
153 "nth-last-child": function(next, rule){
1540 var func = getNCheck(rule);
155
1560 if(func === falseFunc) return func;
1570 if(func === trueFunc) return getChildFunc(next);
158
1590 return function nthLastChild(elem){
1600 var siblings = getSiblings(elem);
161
1620 for(var pos = 0, i = siblings.length - 1; i >= 0; i--){
1630 if(isTag(siblings[i])){
1640 if(siblings[i] === elem) break;
1650 else pos++;
166 }
167 }
168
1690 return func(pos) && next(elem);
170 };
171 },
172 "nth-of-type": function(next, rule){
1730 var func = getNCheck(rule);
174
1750 if(func === falseFunc) return func;
1760 if(func === trueFunc) return getChildFunc(next);
177
1780 return function nthOfType(elem){
1790 var siblings = getSiblings(elem);
180
1810 for(var pos = 0, i = 0; i < siblings.length; i++){
1820 if(isTag(siblings[i])){
1830 if(siblings[i] === elem) break;
1840 if(getName(siblings[i]) === getName(elem)) pos++;
185 }
186 }
187
1880 return func(pos) && next(elem);
189 };
190 },
191 "nth-last-of-type": function(next, rule){
1920 var func = getNCheck(rule);
193
1940 if(func === falseFunc) return func;
1950 if(func === trueFunc) return getChildFunc(next);
196
1970 return function nthLastOfType(elem){
1980 var siblings = getSiblings(elem);
199
2000 for(var pos = 0, i = siblings.length - 1; i >= 0; i--){
2010 if(siblings[i] === elem) break;
2020 if(getName(siblings[i]) === getName(elem)) pos++;
203 }
204
2050 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
2201var pseudos = {
221 root: function(elem){
2220 return !getParent(elem);
223 },
224 empty: function(elem){
2250 return !getChildren(elem).some(function(elem){
2260 return isTag(elem) || elem.type === "text";
227 });
228 },
229
230 //forms
231 //to consider: :target, :enabled
232 selected: function(elem){
2330 if(hasAttrib(elem, "selected")) return true;
2340 else if(getName(elem) !== "option") return false;
235
236 //the first <option> in a <select> is also selected
2370 var parent = getParent(elem);
238
2390 if(!parent || getName(parent) !== "select") return false;
240
2410 var siblings = getChildren(parent),
242 sawElem = false;
243
2440 for(var i = 0; i < siblings.length; i++){
2450 if(isTag(siblings[i])){
2460 if(siblings[i] === elem){
2470 sawElem = true;
2480 } else if(!sawElem){
2490 return false;
2500 } else if(hasAttrib(siblings[i], "selected")){
2510 return false;
252 }
253 }
254 }
255
2560 return sawElem;
257 },
258 disabled: function(elem){
2590 return hasAttrib(elem, "disabled");
260 },
261 enabled: function(elem){
2620 return !hasAttrib(elem, "disabled");
263 },
264 checked: function(elem){
2650 return hasAttrib(elem, "checked") || pseudos.selected(elem);
266 },
267
268 //jQuery extensions
269
270 //:parent is the inverse of :empty
271 parent: function(elem){
2720 return !pseudos.empty(elem);
273 },
274 header: function(elem){
2750 var name = getName(elem);
2760 return name === "h1" ||
277 name === "h2" ||
278 name === "h3" ||
279 name === "h4" ||
280 name === "h5" ||
281 name === "h6";
282 },
283
284 button: function(elem){
2850 var name = getName(elem);
2860 return name === "button" ||
287 name === "input" &&
288 getAttribute(elem, "type") === "button";
289 },
290 input: function(elem){
2910 var name = getName(elem);
2920 return name === "input" ||
293 name === "textarea" ||
294 name === "select" ||
295 name === "button";
296 },
297 text: function(elem){
2980 var attr;
2990 return getName(elem) === "input" && (
300 !(attr = getAttribute(elem, "type")) ||
301 attr.toLowerCase() === "text"
302 );
303 }
304};
305
3061function verifyArgs(func, name, subselect){
3070 if(subselect === null){
3080 if(func.length > 1){
3090 throw new SyntaxError("pseudo-selector :" + name + " requires an argument");
310 }
311 } else {
3120 if(func.length === 1){
3130 throw new SyntaxError("pseudo-selector :" + name + " doesn't have any arguments");
314 }
315 }
316}
317
3181module.exports = {
319 compile: function(next, data){
3200 var name = data.name,
321 subselect = data.data;
322
3230 if(typeof filters[name] === "function"){
3240 verifyArgs(filters[name], name, subselect);
3250 return filters[name](next, subselect);
3260 } else if(typeof pseudos[name] === "function"){
3270 var func = pseudos[name];
3280 verifyArgs(func, name, subselect);
3290 return function pseudoArgs(elem){
3300 return func(elem, subselect) && next(elem);
331 };
332 } else {
3330 throw new SyntaxError("unmatched pseudo-class :" + name);
334 }
335 },
336 filters: filters,
337 pseudos: pseudos
338};
339

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/node_modules/domutils/index.js

100.0%
5
5
0
LineHitsSource
11var DomUtils = module.exports;
2
31[
4 "stringify", "traversal", "manipulation", "querying", "legacy", "helpers"
5].forEach(function(name){
66 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);
76 Object.keys(ext).forEach(function(key){
826 DomUtils[key] = ext[key].bind(DomUtils);
9 });
10});
11

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/node_modules/domutils/lib/stringify.js

23.3%
30
7
23
LineHitsSource
11var ElementType = require("domelementtype"),
2 isTag = ElementType.isTag;
3
41module.exports = {
5 getInnerHTML: getInnerHTML,
6 getOuterHTML: getOuterHTML,
7 getText: getText
8};
9
101function getInnerHTML(elem){
110 return elem.children ? elem.children.map(getOuterHTML).join("") : "";
12}
13
14//boolean attributes without a value (taken from MatthewMueller/cheerio)
151var 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
341var 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
521function getOuterHTML(elem){
530 switch(elem.type){
54 case ElementType.Text:
550 return elem.data;
56 case ElementType.Comment:
570 return "<!--" + elem.data + "-->";
58 case ElementType.Directive:
590 return "<" + elem.data + ">";
60 case ElementType.CDATA:
610 return "<!CDATA " + getInnerHTML(elem) + "]]>";
62 }
63
640 var ret = "<" + elem.name;
650 if("attribs" in elem){
660 for(var attr in elem.attribs){
670 if(elem.attribs.hasOwnProperty(attr)){
680 ret += " " + attr;
690 var value = elem.attribs[attr];
700 if(value == null){
710 if( !(attr in booleanAttribs) ){
720 ret += "=\"\"";
73 }
74 } else {
750 ret += "=\"" + value + "\"";
76 }
77 }
78 }
79 }
80
810 if (elem.name in emptyTags && elem.children.length === 0) {
820 return ret + " />";
83 } else {
840 return ret + ">" + getInnerHTML(elem) + "</" + elem.name + ">";
85 }
86}
87
881function getText(elem){
890 if(Array.isArray(elem)) return elem.map(getText).join("");
900 if(isTag(elem) || elem.type === ElementType.CDATA) return getText(elem.children);
910 if(elem.type === ElementType.Text) return elem.data;
920 return "";
93}

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/node_modules/domutils/node_modules/domelementtype/index.js

100.0%
2
2
0
LineHitsSource
1//Types of elements found in the DOM
21module.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){
127259060 return elem.type === "tag" || elem.type === "script" || elem.type === "style";
13 }
14};

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/node_modules/domutils/lib/traversal.js

76.9%
13
10
3
LineHitsSource
11var getChildren = exports.getChildren = function(elem){
27389197 return elem.children;
3};
4
51var getParent = exports.getParent = function(elem){
633324 return elem.parent;
7};
8
91exports.getSiblings = function(elem){
100 var parent = getParent(elem);
110 return parent ? getChildren(parent) : [elem];
12};
13
141exports.getAttributeValue = function(elem, name){
151399356 return elem.attribs && elem.attribs[name];
16};
17
181exports.hasAttrib = function(elem, name){
190 return hasOwnProperty.call(elem.attribs, name);
20};
21
221exports.getName = function(elem){
233146804 return elem.name;
24};
25

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/node_modules/domutils/lib/manipulation.js

10.9%
46
5
41
LineHitsSource
11exports.removeElement = function(elem){
20 if(elem.prev) elem.prev.next = elem.next;
30 if(elem.next) elem.next.prev = elem.prev;
4
50 if(elem.parent){
60 var childs = elem.parent.children;
70 childs.splice(childs.lastIndexOf(elem), 1);
8 }
9};
10
111exports.replaceElement = function(elem, replacement){
120 var prev = replacement.prev = elem.prev;
130 if(prev){
140 prev.next = replacement;
15 }
16
170 var next = replacement.next = elem.next;
180 if(next){
190 next.prev = replacement;
20 }
21
220 var parent = replacement.parent = elem.parent;
230 if(parent){
240 var childs = parent.children;
250 childs[childs.lastIndexOf(elem)] = replacement;
26 }
27};
28
291exports.appendChild = function(elem, child){
300 child.parent = elem;
31
320 if(elem.children.push(child) !== 1){
330 var sibling = elem.children[elem.children.length - 2];
340 sibling.next = child;
350 child.prev = sibling;
360 child.next = null;
37 }
38};
39
401exports.append = function(elem, next){
410 var parent = elem.parent,
42 currNext = elem.next;
43
440 next.next = currNext;
450 next.prev = elem;
460 elem.next = next;
47
480 if(currNext){
490 currNext.prev = next;
500 if(parent){
510 var childs = parent.children;
520 childs.splice(childs.lastIndexOf(currNext), 0, next);
53 }
540 } else if(parent){
550 parent.children.push(next);
56 }
57};
58
591exports.prepend = function(elem, prev){
600 var parent = elem.parent;
610 if(parent){
620 var childs = parent.children;
630 childs.splice(childs.lastIndexOf(elem), 0, prev);
64 }
65
660 if(elem.prev){
670 elem.prev.next = prev;
68 }
690 prev.prev = elem.prev;
700 prev.next = elem;
710 elem.prev = prev;
72};
73
74
75

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/node_modules/domutils/lib/querying.js

26.7%
45
12
33
LineHitsSource
11exports.find = function(test, arr, recurse, limit){
20 var result = [], childs;
3
40 for(var i = 0, j = arr.length; i < j; i++){
50 if(test(arr[i])){
60 result.push(arr[i]);
70 if(--limit <= 0) break;
8 }
9
100 childs = this.getChildren(arr[i]);
110 if(recurse && childs && childs.length > 0){
120 childs = this.find(test, childs, recurse, limit);
130 result = result.concat(childs);
140 limit -= childs.length;
150 if(limit <= 0) break;
16 }
17 }
18
190 return result;
20};
21
221exports.findOneChild = function(test, arr){
230 for(var i = 0, l = arr.length; i < l; i++){
240 if(test(arr[i])) return arr[i];
25 }
26
270 return null;
28};
29
301exports.findOne = function(test, arr){
310 var elem = null;
32
330 for(var i = 0, l = arr.length; i < l && !elem; i++){
340 if(test(arr[i])){
350 elem = arr[i];
360 } else if(arr[i].children && arr[i].children.length > 0){
370 elem = this.findOne(test, arr[i].children);
38 }
39 }
40
410 return elem;
42};
43
441exports.findAll = function(test, elems){
454070110 var result = [];
464070285 for(var i = 0, j = elems.length; i < j; i++){
477707592 if(test(elems[i])) result.push(elems[i]);
48
497688459 var childs = this.getChildren(elems[i]);
507688821 if(childs && childs.length){
514051364 result = result.concat(this.findAll(test, childs));
52 }
53 }
544071820 return result;
55};
56
571exports.filter = function(test, element, recurse, limit){
580 if(!Array.isArray(element)) element = [element];
59
600 if(typeof limit !== "number" || !isFinite(limit)){
610 if(recurse === false){
620 return element.filter(test);
63 } else {
640 return this.findAll(test, element);
65 }
660 } else if(limit === 1){
670 if(recurse === false){
680 element = this.findOneChild(test, element);
69 } else {
700 element = this.findOne(test, element);
71 }
720 return element ? [element] : [];
73 } else {
740 return this.find(test, element, recurse !== false, limit);
75 }
76};
77

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/node_modules/domutils/lib/legacy.js

21.3%
47
10
37
LineHitsSource
11var ElementType = require("domelementtype");
21var isTag = exports.isTag = ElementType.isTag;
3
41exports.testElement = function(options, element){
50 for(var key in options){
60 if(!options.hasOwnProperty(key));
70 else if(key === "tag_name"){
80 if(!isTag(element) || !options.tag_name(element.name)){
90 return false;
10 }
110 } else if(key === "tag_type"){
120 if(!options.tag_type(element.type)) return false;
130 } else if(key === "tag_contains"){
140 if(isTag(element) || !options.tag_contains(element.data)){
150 return false;
16 }
170 } else if(!element.attribs || !options[key](element.attribs[key])){
180 return false;
19 }
20 }
210 return true;
22};
23
241var Checks = {
25 tag_name: function(name){
260 if(typeof name === "function"){
270 return function(elem){ return isTag(elem) && name(elem.name); };
280 } else if(name === "*"){
290 return isTag;
30 } else {
310 return function(elem){ return isTag(elem) && elem.name === name; };
32 }
33 },
34 tag_type: function(type){
350 if(typeof type === "function"){
360 return function(elem){ return type(elem.type); };
37 } else {
380 return function(elem){ return elem.type === type; };
39 }
40 },
41 tag_contains: function(data){
420 if(typeof data === "function"){
430 return function(elem){ return !isTag(elem) && data(elem.data); };
44 } else {
450 return function(elem){ return !isTag(elem) && elem.data === data; };
46 }
47 }
48};
49
501function getAttribCheck(attrib, value){
510 if(typeof value === "function"){
520 return function(elem){ return elem.attribs && value(elem.attribs[attrib]); };
53 } else {
540 return function(elem){ return elem.attribs && elem.attribs[attrib] === value; };
55 }
56}
57
581function combineFuncs(a, b){
590 return function(elem){
600 return a(elem) || b(elem);
61 };
62}
63
641exports.getElements = function(options, element, recurse, limit){
650 var funcs = Object.keys(options).map(function(key){
660 var value = options[key];
670 return key in Checks ? Checks[key](value) : getAttribCheck(key, value);
68 });
69
700 return funcs.length === 0 ? [] : this.filter(
71 funcs.reduce(combineFuncs),
72 element, recurse, limit
73 );
74};
75
761exports.getElementById = function(id, element, recurse){
770 if(!Array.isArray(element)) element = [element];
780 return this.findOne(getAttribCheck("id", id), element, recurse !== false);
79};
80
811exports.getElementsByTagName = function(name, element, recurse, limit){
820 return this.filter(Checks.tag_name(name), element, recurse, limit);
83};
84
851exports.getElementsByTagType = function(type, element, recurse, limit){
860 return this.filter(Checks.tag_type(type), element, recurse, limit);
87};
88

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/node_modules/domutils/lib/helpers.js

80.0%
15
12
3
LineHitsSource
1// removeSubsets
2// Given an array of nodes, remove any member that is contained by another.
31exports.removeSubsets = function(nodes) {
420349 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.
820365 while (--idx > -1) {
960705 node = ancestor = nodes[idx];
10
11 // Temporarily remove the node under consideration
1260741 nodes[idx] = null;
1360753 replace = true;
14
1560777 while (ancestor) {
16182206 if (nodes.indexOf(ancestor) > -1) {
170 replace = false;
180 nodes.splice(idx, 1);
190 break;
20 }
21182386 ancestor = ancestor.parent;
22 }
23
24 // If the node has been found to be unique, re-insert it.
2560897 if (replace) {
2660909 nodes[idx] = node;
27 }
28 }
29
3020453 return nodes;
31};
32

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/lib/nth-check.js

18.9%
37
7
30
LineHitsSource
11var 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
51module.exports = function nthCheck(formula){
60 return compile(parse(formula));
7};
8
91module.exports.parse = parse;
101module.exports.compile = compile;
11
12//following http://www.w3.org/TR/css3-selectors/#nth-child-pseudo
13
14//[ ['-'|'+']? INTEGER? {N} [ S* ['-'|'+'] S* INTEGER ]?
151var re_nthElement = /^([+\-]?\d*n)?\s*(?:([+\-]?)\s*(\d+))?$/;
16
17/*
18 parses a nth-check formula, returns an array of two numbers
19*/
201function parse(formula){
210 formula = formula.trim().toLowerCase();
22
230 if(formula === "even"){
240 return [2, 0];
250 } else if(formula === "odd"){
260 return [2, 1];
27 } else {
280 var parsed = formula.match(re_nthElement);
29
300 if(!parsed){
310 throw new SyntaxError("n-th rule couldn't be parsed ('" + formula + "')");
32 }
33
340 var a;
35
360 if(parsed[1]){
370 a = parseInt(parsed[1], 10);
380 if(!a){
390 if(parsed[1].charAt(0) === "-") a = -1;
400 else a = 1;
41 }
420 } else a = 0;
43
440 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*/
551function compile(parsed){
560 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
610 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)
640 if(a ===-1) return function(pos){ return pos <= b; };
650 if(a === 0) return function(pos){ return pos === b; };
66 //when b <= 0 and a === 1, they match any element
670 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
700 var bMod = b % a;
710 if(bMod < 0) bMod += a;
72
730 if(a > 1){
740 return function(pos){
750 return pos >= b && pos % a === bMod;
76 };
77 }
78
790 a *= -1; //make `a` positive
80
810 return function(pos){
820 return pos <= b && pos % a === bMod;
83 };
84}

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/lib/basefunctions.js

66.7%
3
2
1
LineHitsSource
11module.exports = {
2 trueFunc: function trueFunc(){
320833 return true;
4 },
5 falseFunc: function falseFunc(){
60 return false;
7 }
8};

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/lib/attributes.js

20.8%
77
16
61
LineHitsSource
11var 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
71var reChars = /[-[\]{}()*+?.,\\^$|#\s]/g;
8
9/*
10 attribute selectors
11*/
12
131var attributeRules = {
14 __proto__: null,
15 equals: function(next, data){
165275 var name = data.name,
17 value = data.value;
18
195278 if(data.ignoreCase){
200 value = value.toLowerCase();
21
220 return function(elem){
230 var attr = getAttributeValue(elem, name);
240 return attr != null && attr.toLowerCase() === value && next(elem);
25 };
26 }
27
285287 return function(elem){
291118114 return getAttributeValue(elem, name) === value && next(elem);
30 };
31 },
32 hyphen: function(next, data){
330 var name = data.name,
34 value = data.value,
35 len = value.length;
36
370 if(data.ignoreCase){
380 value = value.toLowerCase();
39
400 return function(elem){
410 var attr = getAttributeValue(elem, name);
420 return attr != null &&
43 (attr.length === len || attr.charAt(len) === "-") &&
44 attr.substr(0, len).toLowerCase() === value &&
45 next(elem);
46 };
47 }
48
490 return function(elem){
500 var attr = getAttributeValue(elem, name);
510 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){
5815996 var name = data.name,
59 value = data.value;
60
6116005 if(/\s/.test(value)){
620 return falseFunc;
63 }
64
6516017 value = value.replace(reChars, "\\$&");
66
6716023 var pattern = "(?:^|\\s)" + value + "(?:$|\\s)",
68 flags = data.ignoreCase ? "i" : "",
69 regex = new RegExp(pattern, flags);
70
7116035 return function(elem){
72725993 var attr = getAttributeValue(elem, name);
73726002 return attr != null && regex.test(attr) && next(elem);
74 };
75 },
76 exists: function(next, data){
770 var name = data.name;
780 return function(elem){
790 return hasAttrib(elem, name) && next(elem);
80 };
81 },
82 start: function(next, data){
830 var name = data.name,
84 value = data.value,
85 len = value.length;
86
870 if(len === 0){
880 return falseFunc;
89 }
90
910 if(data.ignoreCase){
920 value = value.toLowerCase();
93
940 return function(elem){
950 var attr = getAttributeValue(elem, name);
960 return attr != null && attr.substr(0, len).toLowerCase() === value && next(elem);
97 };
98 }
99
1000 return function(elem){
1010 var attr = getAttributeValue(elem, name);
1020 return attr != null && attr.substr(0, len) === value && next(elem);
103 };
104 },
105 end: function(next, data){
1060 var name = data.name,
107 value = data.value,
108 len = -value.length;
109
1100 if(len === 0){
1110 return falseFunc;
112 }
113
1140 if(data.ignoreCase){
1150 value = value.toLowerCase();
116
1170 return function(elem){
1180 var attr = getAttributeValue(elem, name);
1190 return attr != null && attr.substr(len).toLowerCase() === value && next(elem);
120 };
121 }
122
1230 return function(elem){
1240 var attr = getAttributeValue(elem, name);
1250 return attr != null && attr.substr(len) === value && next(elem);
126 };
127 },
128 any: function(next, data){
1290 var name = data.name,
130 value = data.value;
131
1320 if(value === ""){
1330 return falseFunc;
134 }
135
1360 if(data.ignoreCase){
1370 var regex = new RegExp(value.replace(reChars, "\\$&"), "i");
138
1390 return function(elem){
1400 var attr = getAttributeValue(elem, name);
1410 return attr != null && regex.test(attr) && next(elem);
142 };
143 }
144
1450 return function(elem){
1460 var attr = getAttributeValue(elem, name);
1470 return attr != null && attr.indexOf(value) >= 0 && next(elem);
148 };
149 },
150 not: function(next, data){
1510 var name = data.name,
152 value = data.value;
153
1540 if(value === ""){
1550 return function(elem){
1560 return !!getAttributeValue(elem, name) && next(elem);
157 };
1580 } else if(data.ignoreCase){
1590 value = value.toLowerCase();
160
1610 return function(elem){
1620 var attr = getAttributeValue(elem, name);
1630 return attr != null && attr.toLowerCase() !== value && next(elem);
164 };
165 }
166
1670 return function(elem){
1680 return getAttributeValue(elem, name) !== value && next(elem);
169 };
170 }
171};
172
1731module.exports = {
174 compile: function(next, data){
17521781 return attributeRules[data.action](next, data);
176 },
177 rules: attributeRules
178};
179

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/lib/compile.js

56.3%
32
18
14
LineHitsSource
1/*
2 compiles a selector to an executable function
3*/
4
51module.exports = compile;
6
71var 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
161function compile(selector, options){
1721661 var next = parse(selector, options)
18 .map(compileRules)
19 .reduce(reduceRules, falseFunc);
20
2121677 return function(elem){
228721326 return isTag(elem) && next(elem);
23 };
24}
25
261function compileRules(arr){
2721701 if(arr.length === 0) return falseFunc;
2821705 return sortRules(arr).reduce(function(func, rule){
2932961 if(func === falseFunc) return func;
3032967 return Rules[rule.type](func, rule);
31 }, trueFunc);
32}
33
341function reduceRules(a, b){
3521733 if(b === falseFunc || a === trueFunc){
360 return a;
37 }
3821745 if(a === falseFunc || b === trueFunc){
3921749 return b;
40 }
41
420 return function combine(elem){
430 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
511var 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
571filters.not = function(next, select){
580 var func = compile(select);
59
600 if(func === falseFunc) return next;
610 if(func === trueFunc) return falseFunc;
62
630 return function(elem){
640 return !func(elem) && next(elem);
65 };
66};
67
681filters.has = function(next, selector){
690 var func = compile(selector);
70
710 if(func === falseFunc) return falseFunc;
720 if(func === trueFunc) return function(elem){
730 return isParent(elem) && next(elem);
74 };
75
760 return function has(elem){
770 return next(elem) && findOne(func, getChildren(elem)) !== null;
78 };
79};
80

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/node_modules/CSSwhat/index.js

52.9%
68
36
32
LineHitsSource
11"use strict";
2
31module.exports = parse;
4
51var 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
141var actionTypes = {
15 __proto__: null,
16 "undefined": "exists",
17 "": "equals",
18 "~": "element",
19 "^": "start",
20 "$": "end",
21 "*": "any",
22 "!": "not",
23 "|": "hyphen"
24};
25
261var simpleSelectors = {
27 __proto__: null,
28 ">": "child",
29 "<": "parent",
30 "~": "sibling",
31 "+": "adjacent",
32 "*": "universal"
33};
34
351var 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
421function funescape( _, escaped, escapedWhitespace ) {
430 var high = "0x" + escaped - 0x10000;
44 // NaN means non-codepoint
45 // Support: Firefox
46 // Workaround erroneous numeric interpretation of +"0x"
470 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
561function unescapeCSS(str){
5727963 return str.replace(re_escape, funescape);
58}
59
601function getClosingPos(selector){
610 var pos = 1, counter = 1, len = selector.length;
62
630 for(; counter > 0 && pos < len; pos++){
640 if(selector.charAt(pos) === "(") counter++;
650 else if(selector.charAt(pos) === ")") counter--;
66 }
67
680 return pos;
69}
70
711function parse(selector, options){
7222213 selector = (selector + "").trimLeft().replace(re_cleanSelector, "$1$2");
73
7422221 var subselects = [],
75 tokens = [],
76 data, firstChar, name;
77
7822237 function getName(){
7928073 var sub = selector.match(re_name)[0];
8028078 selector = selector.substr(sub.length);
8128083 return unescapeCSS(sub);
82 }
83
8422261 function getLCName(){
855612 var name = getName();
86
875614 if(!options || !options.xmlMode){
885615 name = name.toLowerCase();
89 }
90
915618 return name;
92 }
93
9422301 while(selector !== ""){
9533864 if(re_name.test(selector)){
965623 tokens.push({type: "tag", name: getLCName()});
9728252 } else if(re_ws.test(selector)){
985714 tokens.push({type: "descendant"});
995715 selector = selector.trimLeft();
100 } else {
10122555 firstChar = selector.charAt(0);
10222559 selector = selector.substr(1);
103
10422567 if(firstChar in simpleSelectors){
1050 tokens.push({type: simpleSelectors[firstChar]});
10622575 } else if(firstChar in attribSelectors){
10722579 tokens.push({
108 type: "attribute",
109 name: attribSelectors[firstChar][0],
110 action: attribSelectors[firstChar][1],
111 value: getName(),
112 ignoreCase: false
113 });
1140 } else if(firstChar === "["){
1150 data = selector.match(re_attr);
1160 if(!data){
1170 throw new SyntaxError("Malformed attribute selector: " + selector);
118 }
1190 selector = selector.substr(data[0].length);
1200 name = unescapeCSS(data[1]);
121
1220 if(!options || !options.xmlMode){
1230 name = name.toLowerCase();
124 }
125
1260 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
1340 } else if(firstChar === ":"){
135 //if(selector.charAt(0) === ":"){} //TODO pseudo-element
1360 name = getLCName();
1370 data = null;
138
1390 if(selector.charAt(0) === "("){
1400 var pos = getClosingPos(selector);
1410 data = selector.substr(1, pos - 2);
1420 selector = selector.substr(pos);
143 }
144
1450 tokens.push({type: "pseudo", name: name, data: data});
1460 } else if(firstChar === ","){
1470 if(tokens.length === 0){
1480 throw new SyntaxError("empty sub-selector");
149 }
1500 subselects.push(tokens);
1510 tokens = [];
152 } else {
153 //otherwise, the parser needs to throw or it would enter an infinite loop
1540 throw new SyntaxError("Unmatched selector: " + firstChar + selector);
155 }
156 }
157 }
158
15922561 if(subselects.length > 0 && tokens.length === 0){
1600 throw new SyntaxError("empty sub-selector");
161 }
16222573 subselects.push(tokens);
16322577 return subselects;
164}

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/lib/general.js

33.3%
30
10
20
LineHitsSource
11var 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*/
111module.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){
195714 var name = data.name;
205715 return function tag(elem){
213557627 return getName(elem) === name && next(elem);
22 };
23 },
24
25 //traversal
26 descendant: function(next){
275813 return function descendant(elem){
2811370 var found = false;
29
3011372 while(!found && (elem = getParent(elem))){
3133597 found = next(elem);
32 }
33
3411376 return found;
35 };
36 },
37 parent: function(next){
380 return function parent(elem){
390 return getChildren(elem).some(next);
40 };
41 },
42 child: function(next){
430 return function child(elem){
440 var parent = getParent(elem);
450 return !!parent && next(parent);
46 };
47 },
48 sibling: function(next){
490 return function sibling(elem){
500 var siblings = getSiblings(elem);
51
520 for(var i = 0; i < siblings.length; i++){
530 if(isTag(siblings[i])){
540 if(siblings[i] === elem) break;
550 if(next(siblings[i])) return true;
56 }
57 }
58
590 return false;
60 };
61 },
62 adjacent: function(next){
630 return function adjacent(elem){
640 var siblings = getSiblings(elem),
65 lastElement;
66
670 for(var i = 0; i < siblings.length; i++){
680 if(isTag(siblings[i])){
690 if(siblings[i] === elem) break;
700 lastElement = siblings[i];
71 }
72 }
73
740 return !!lastElement && next(lastElement);
75 };
76 },
77 universal: function(next){
780 return next;
79 }
80};

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/cheerio-select/node_modules/CSSselect/lib/sort.js

100.0%
11
11
0
LineHitsSource
11module.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
91var 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
231function sortByProcedure(arr){
24 //TODO sort individual attribute selectors
2523025 for(var i = 1; i < arr.length; i++){
2611939 var procNew = procedure[arr[i].type];
27
2811943 if(procNew !== -1){
296044 for(var j = i - 1; j >= 0 && procNew < procedure[arr[j].type]; j--){
3095 var tmp = arr[j + 1];
3195 arr[j + 1] = arr[j];
3295 arr[j] = tmp;
33 }
34 }
35 }
3623069 return arr;
37}

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/lib/parse.js

87.2%
47
41
6
LineHitsSource
1/*
2 Module Dependencies
3*/
41var htmlparser = require('htmlparser2'),
5 _ = require('underscore'),
6 isTag = require('./utils').isTag,
7 camelCase = require('./utils').camelCase;
8
9/*
10 Parser
11*/
121exports = module.exports = function(content, options) {
135738 var dom = evaluate(content, options);
14
15 // Generic root element
165741 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
265751 update(dom, root);
27
285753 return root;
29};
30
311var evaluate = exports.evaluate = function(content, options) {
32 // options = options || $.fn.options;
33
345759 var handler = new htmlparser.DomHandler(options),
35 parser = new htmlparser.Parser(handler, options);
36
375762 parser.write(content);
385763 parser.done();
39
405765 return connect(handler.dom);
41};
42
431var connect = exports.connect = function(dom, parent) {
4429615 parent = parent || null;
45
4629625 var prevElem = null;
47
4829635 _.each(dom, function(elem) {
49
5025001 if (isTag(elem.type)) {
51 // If tag and no attributes, add empty object
5223878 if (elem.attribs === undefined) {
530 elem.attribs = {};
54 } else {
55 // If there are already attributes, add them to the data list.
5623894 elem.data = parseData(elem);
57 }
58 }
59
60 // Set parent
6125045 elem.parent = parent;
62
63 // Previous Sibling
6425057 elem.prev = prevElem;
65
66 // Next sibling
6725069 elem.next = null;
6838047 if (prevElem) prevElem.next = elem;
69
70 // Run through the children
7125085 if (elem.children)
7223958 connect(elem.children, elem);
731131 else if (isTag(elem.type))
740 elem.children = [];
75
76 // Get ready for next element
7725109 prevElem = elem;
78 });
79
8029795 return dom;
81};
82
83/*
84 Update the dom structure, for one changed layer
85
86 * Much faster than reconnecting
87*/
881var update = exports.update = function(arr, parent) {
89 // normalize
9040585 if (!Array.isArray(arr)) arr = [arr];
91
92 // Update neighbors
9326119 for (var i = 0; i < arr.length; i++) {
94760689 arr[i].prev = arr[i - 1] || null;
95760790 arr[i].next = arr[i + 1] || null;
96760892 arr[i].parent = parent || null;
97 }
98
99 // Update parent
10026151 parent.children = arr;
101
10226160 return parent;
103};
104
105/**
106 * Extract data by using element attributes.
107 * @param {Object} elem Element
108 * @return {Object} `element.data` object
109 */
1101var parseData = exports.parseData = function(elem) {
11148228 if (elem.data === undefined) elem.data = {};
11224118 var value;
11324122 for (var key in elem.attribs) {
11423770 if (key.substr(0, 5) === 'data-') {
1150 value = elem.attribs[key];
1160 key = key.slice(5);
1170 key = camelCase(key);
1180 elem.data[key] = value;
119 }
120 }
12124154 return elem.data;
122};
123
124// module.exports = $.extend(exports);
125

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/htmlparser2/lib/index.js

25.9%
27
7
20
LineHitsSource
11function defineProp(name, value){
22 delete module.exports[name];
32 module.exports[name] = value;
42 return value;
5}
6
71module.exports = {
8 parseDOM: function (html) {
90 var handler = new module.exports.DomHandler();
100 var parser = new module.exports.Parser(handler);
110 parser.parseComplete(html);
120 return handler.dom;
13 },
14 parseFeed: function (feed) {
150 var handler = new module.exports.FeedHandler();
160 var parser = new module.exports.Parser(handler);
170 parser.parseComplete(feed);
180 return handler.dom;
19 },
20 get Parser(){
211 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(){
241 return defineProp("DomHandler", require("domhandler"));
25 },
26 get FeedHandler(){
270 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(){
300 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(){
330 return defineProp("ElementType", require("domelementtype"));
34 },
35 get Stream(){
360 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(){
390 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(){
420 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(){
450 return defineProp("DomUtils", require("domutils"));
46 },
47 get CollectingHandler(){
480 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(){
520 return defineProp("DefaultHandler", this.DomHandler);
53 },
54 get RssHandler(){
550 return defineProp("RssHandler", this.FeedHandler);
56 },
57 createDomStream: function(cb, options, elementCb){
580 var handler = new module.exports.DomHandler(cb, options, elementCb);
590 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

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/underscore/underscore.js

31.1%
578
180
398
LineHitsSource
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
61(function() {
7
8 // Baseline setup
9 // --------------
10
11 // Establish the root object, `window` in the browser, or `global` on the server.
121 var root = this;
13
14 // Save the previous value of the `_` variable.
151 var previousUnderscore = root._;
16
17 // Establish the object that gets returned to break out of a loop iteration.
181 var breaker = {};
19
20 // Save bytes in the minified (but not gzipped) version:
211 var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
22
23 // Create quick reference variables for speed access to core prototypes.
241 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.
321 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.
471 var _ = function(obj) {
480 if (obj instanceof _) return obj;
490 if (!(this instanceof _)) return new _(obj);
500 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.
571 if (typeof exports !== 'undefined') {
581 if (typeof module !== 'undefined' && module.exports) {
591 exports = module.exports = _;
60 }
611 exports._ = _;
62 } else {
630 root._ = _;
64 }
65
66 // Current version.
671 _.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.
751 var each = _.each = _.forEach = function(obj, iterator, context) {
76209322 if (obj == null) return;
77209358 if (nativeForEach && obj.forEach === nativeForEach) {
78179157 obj.forEach(iterator, context);
7930242 } else if (obj.length === +obj.length) {
8030247 for (var i = 0, l = obj.length; i < l; i++) {
8130252 if (iterator.call(context, obj[i], i, obj) === breaker) return;
82 }
83 } else {
840 for (var key in obj) {
850 if (_.has(obj, key)) {
860 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.
941 _.map = _.collect = function(obj, iterator, context) {
950 var results = [];
960 if (obj == null) return results;
970 if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
980 each(obj, function(value, index, list) {
990 results[results.length] = iterator.call(context, value, index, list);
100 });
1010 return results;
102 };
103
1041 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.
1081 _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
10924353 var initial = arguments.length > 2;
11024357 if (obj == null) obj = [];
11124361 if (nativeReduce && obj.reduce === nativeReduce) {
1120 if (context) iterator = _.bind(iterator, context);
1130 return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
114 }
11524377 each(obj, function(value, index, list) {
11624381 if (!initial) {
1170 memo = value;
1180 initial = true;
119 } else {
12024397 memo = iterator.call(context, memo, value, index, list);
121 }
122 });
12324409 if (!initial) throw new TypeError(reduceError);
12424413 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.
1291 _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
1300 var initial = arguments.length > 2;
1310 if (obj == null) obj = [];
1320 if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
1330 if (context) iterator = _.bind(iterator, context);
1340 return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
135 }
1360 var length = obj.length;
1370 if (length !== +length) {
1380 var keys = _.keys(obj);
1390 length = keys.length;
140 }
1410 each(obj, function(value, index, list) {
1420 index = keys ? keys[--length] : --length;
1430 if (!initial) {
1440 memo = obj[index];
1450 initial = true;
146 } else {
1470 memo = iterator.call(context, memo, obj[index], index, list);
148 }
149 });
1500 if (!initial) throw new TypeError(reduceError);
1510 return memo;
152 };
153
154 // Return the first value which passes a truth test. Aliased as `detect`.
1551 _.find = _.detect = function(obj, iterator, context) {
1560 var result;
1570 any(obj, function(value, index, list) {
1580 if (iterator.call(context, value, index, list)) {
1590 result = value;
1600 return true;
161 }
162 });
1630 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`.
1691 _.filter = _.select = function(obj, iterator, context) {
17030697 var results = [];
17130702 if (obj == null) return results;
17261414 if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
1730 each(obj, function(value, index, list) {
1740 if (iterator.call(context, value, index, list)) results[results.length] = value;
175 });
1760 return results;
177 };
178
179 // Return all the elements for which a truth test fails.
1801 _.reject = function(obj, iterator, context) {
1810 return _.filter(obj, function(value, index, list) {
1820 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`.
1891 _.every = _.all = function(obj, iterator, context) {
1900 iterator || (iterator = _.identity);
1910 var result = true;
1920 if (obj == null) return result;
1930 if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
1940 each(obj, function(value, index, list) {
1950 if (!(result = result && iterator.call(context, value, index, list))) return breaker;
196 });
1970 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`.
2031 var any = _.some = _.any = function(obj, iterator, context) {
2040 iterator || (iterator = _.identity);
2050 var result = false;
2060 if (obj == null) return result;
2070 if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
2080 each(obj, function(value, index, list) {
2090 if (result || (result = iterator.call(context, value, index, list))) return breaker;
210 });
2110 return !!result;
212 };
213
214 // Determine if the array or object contains a given value (using `===`).
215 // Aliased as `include`.
2161 _.contains = _.include = function(obj, target) {
21730983 if (obj == null) return false;
21861976 if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
2190 return any(obj, function(value) {
2200 return value === target;
221 });
222 };
223
224 // Invoke a method (with arguments) on every item in a collection.
2251 _.invoke = function(obj, method) {
2260 var args = slice.call(arguments, 2);
2270 var isFunc = _.isFunction(method);
2280 return _.map(obj, function(value) {
2290 return (isFunc ? method : value[method]).apply(value, args);
230 });
231 };
232
233 // Convenience version of a common use case of `map`: fetching a property.
2341 _.pluck = function(obj, key) {
2350 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.
2401 _.where = function(obj, attrs, first) {
2410 if (_.isEmpty(attrs)) return first ? null : [];
2420 return _[first ? 'find' : 'filter'](obj, function(value) {
2430 for (var key in attrs) {
2440 if (attrs[key] !== value[key]) return false;
245 }
2460 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.
2521 _.findWhere = function(obj, attrs) {
2530 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
2591 _.max = function(obj, iterator, context) {
2600 if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
2610 return Math.max.apply(Math, obj);
262 }
2630 if (!iterator && _.isEmpty(obj)) return -Infinity;
2640 var result = {computed : -Infinity, value: -Infinity};
2650 each(obj, function(value, index, list) {
2660 var computed = iterator ? iterator.call(context, value, index, list) : value;
2670 computed >= result.computed && (result = {value : value, computed : computed});
268 });
2690 return result.value;
270 };
271
272 // Return the minimum element (or element-based computation).
2731 _.min = function(obj, iterator, context) {
2740 if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
2750 return Math.min.apply(Math, obj);
276 }
2770 if (!iterator && _.isEmpty(obj)) return Infinity;
2780 var result = {computed : Infinity, value: Infinity};
2790 each(obj, function(value, index, list) {
2800 var computed = iterator ? iterator.call(context, value, index, list) : value;
2810 computed < result.computed && (result = {value : value, computed : computed});
282 });
2830 return result.value;
284 };
285
286 // Shuffle an array.
2871 _.shuffle = function(obj) {
2880 var rand;
2890 var index = 0;
2900 var shuffled = [];
2910 each(obj, function(value) {
2920 rand = _.random(index++);
2930 shuffled[index - 1] = shuffled[rand];
2940 shuffled[rand] = value;
295 });
2960 return shuffled;
297 };
298
299 // An internal function to generate lookup iterators.
3001 var lookupIterator = function(value) {
3010 return _.isFunction(value) ? value : function(obj){ return obj[value]; };
302 };
303
304 // Sort the object's values by a criterion produced by an iterator.
3051 _.sortBy = function(obj, value, context) {
3060 var iterator = lookupIterator(value);
3070 return _.pluck(_.map(obj, function(value, index, list) {
3080 return {
309 value : value,
310 index : index,
311 criteria : iterator.call(context, value, index, list)
312 };
313 }).sort(function(left, right) {
3140 var a = left.criteria;
3150 var b = right.criteria;
3160 if (a !== b) {
3170 if (a > b || a === void 0) return 1;
3180 if (a < b || b === void 0) return -1;
319 }
3200 return left.index < right.index ? -1 : 1;
321 }), 'value');
322 };
323
324 // An internal function used for aggregate "group by" operations.
3251 var group = function(obj, value, context, behavior) {
3260 var result = {};
3270 var iterator = lookupIterator(value || _.identity);
3280 each(obj, function(value, index) {
3290 var key = iterator.call(context, value, index, obj);
3300 behavior(result, key, value);
331 });
3320 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.
3371 _.groupBy = function(obj, value, context) {
3380 return group(obj, value, context, function(result, key, value) {
3390 (_.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.
3461 _.countBy = function(obj, value, context) {
3470 return group(obj, value, context, function(result, key) {
3480 if (!_.has(result, key)) result[key] = 0;
3490 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.
3551 _.sortedIndex = function(array, obj, iterator, context) {
3560 iterator = iterator == null ? _.identity : lookupIterator(iterator);
3570 var value = iterator.call(context, obj);
3580 var low = 0, high = array.length;
3590 while (low < high) {
3600 var mid = (low + high) >>> 1;
3610 iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
362 }
3630 return low;
364 };
365
366 // Safely convert anything iterable into a real, live array.
3671 _.toArray = function(obj) {
3680 if (!obj) return [];
3690 if (_.isArray(obj)) return slice.call(obj);
3700 if (obj.length === +obj.length) return _.map(obj, _.identity);
3710 return _.values(obj);
372 };
373
374 // Return the number of elements in an object.
3751 _.size = function(obj) {
37625988 if (obj == null) return 0;
37725992 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`.
3861 _.first = _.head = _.take = function(array, n, guard) {
3870 if (array == null) return void 0;
3880 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`.
3951 _.initial = function(array, n, guard) {
3960 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`.
4011 _.last = function(array, n, guard) {
4020 if (array == null) return void 0;
4030 if ((n != null) && !guard) {
4040 return slice.call(array, Math.max(array.length - n, 0));
405 } else {
4060 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`.
4141 _.rest = _.tail = _.drop = function(array, n, guard) {
4150 return slice.call(array, (n == null) || guard ? 1 : n);
416 };
417
418 // Trim out all falsy values from an array.
4191 _.compact = function(array) {
4200 return _.filter(array, _.identity);
421 };
422
423 // Internal implementation of a recursive `flatten` function.
4241 var flatten = function(input, shallow, output) {
42512706 each(input, function(value) {
42612708 if (_.isArray(value)) {
4276355 shallow ? push.apply(output, value) : flatten(value, shallow, output);
428 } else {
4296357 output.push(value);
430 }
431 });
43212720 return output;
433 };
434
435 // Return a completely flattened version of an array.
4361 _.flatten = function(array, shallow) {
4376365 return flatten(array, shallow, []);
438 };
439
440 // Return a version of the array that does not contain the specified value(s).
4411 _.without = function(array) {
4420 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`.
4481 _.uniq = _.unique = function(array, isSorted, iterator, context) {
44925713 if (_.isFunction(isSorted)) {
4500 context = iterator;
4510 iterator = isSorted;
4520 isSorted = false;
453 }
45425733 var initial = iterator ? _.map(array, iterator, context) : array;
45525737 var results = [];
45625741 var seen = [];
45725745 each(initial, function(value, index) {
45825749 if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) {
45925753 seen.push(value);
46025757 results.push(array[index]);
461 }
462 });
46325769 return results;
464 };
465
466 // Produce an array that contains the union: each distinct element from all of
467 // the passed-in arrays.
4681 _.union = function() {
4690 return _.uniq(concat.apply(ArrayProto, arguments));
470 };
471
472 // Produce an array that contains every item shared between all the
473 // passed-in arrays.
4741 _.intersection = function(array) {
4750 var rest = slice.call(arguments, 1);
4760 return _.filter(_.uniq(array), function(item) {
4770 return _.every(rest, function(other) {
4780 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.
4851 _.difference = function(array) {
4866416 var rest = concat.apply(ArrayProto, slice.call(arguments, 1));
48712885 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.
4921 _.zip = function() {
4930 var args = slice.call(arguments);
4940 var length = _.max(_.pluck(args, 'length'));
4950 var results = new Array(length);
4960 for (var i = 0; i < length; i++) {
4970 results[i] = _.pluck(args, "" + i);
498 }
4990 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.
5051 _.object = function(list, values) {
5060 if (list == null) return {};
5070 var result = {};
5080 for (var i = 0, l = list.length; i < l; i++) {
5090 if (values) {
5100 result[list[i]] = values[i];
511 } else {
5120 result[list[i][0]] = list[i][1];
513 }
514 }
5150 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.
5241 _.indexOf = function(array, item, isSorted) {
5250 if (array == null) return -1;
5260 var i = 0, l = array.length;
5270 if (isSorted) {
5280 if (typeof isSorted == 'number') {
5290 i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted);
530 } else {
5310 i = _.sortedIndex(array, item);
5320 return array[i] === item ? i : -1;
533 }
534 }
5350 if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
5360 for (; i < l; i++) if (array[i] === item) return i;
5370 return -1;
538 };
539
540 // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
5411 _.lastIndexOf = function(array, item, from) {
5420 if (array == null) return -1;
5430 var hasIndex = from != null;
5440 if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
5450 return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
546 }
5470 var i = (hasIndex ? from : array.length);
5480 while (i--) if (array[i] === item) return i;
5490 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).
5551 _.range = function(start, stop, step) {
5560 if (arguments.length <= 1) {
5570 stop = start || 0;
5580 start = 0;
559 }
5600 step = arguments[2] || 1;
561
5620 var len = Math.max(Math.ceil((stop - start) / step), 0);
5630 var idx = 0;
5640 var range = new Array(len);
565
5660 while(idx < len) {
5670 range[idx++] = start;
5680 start += step;
569 }
570
5710 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.
5801 _.bind = function(func, context) {
5810 if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
5820 var args = slice.call(arguments, 2);
5830 return function() {
5840 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.
5901 _.partial = function(func) {
5910 var args = slice.call(arguments, 1);
5920 return function() {
5930 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.
5991 _.bindAll = function(obj) {
6000 var funcs = slice.call(arguments, 1);
6010 if (funcs.length === 0) funcs = _.functions(obj);
6020 each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
6030 return obj;
604 };
605
606 // Memoize an expensive function by storing its results.
6071 _.memoize = function(func, hasher) {
6080 var memo = {};
6090 hasher || (hasher = _.identity);
6100 return function() {
6110 var key = hasher.apply(this, arguments);
6120 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.
6181 _.delay = function(func, wait) {
6190 var args = slice.call(arguments, 2);
6200 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.
6251 _.defer = function(func) {
6260 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.
6311 _.throttle = function(func, wait) {
6320 var context, args, timeout, result;
6330 var previous = 0;
6340 var later = function() {
6350 previous = new Date;
6360 timeout = null;
6370 result = func.apply(context, args);
638 };
6390 return function() {
6400 var now = new Date;
6410 var remaining = wait - (now - previous);
6420 context = this;
6430 args = arguments;
6440 if (remaining <= 0) {
6450 clearTimeout(timeout);
6460 timeout = null;
6470 previous = now;
6480 result = func.apply(context, args);
6490 } else if (!timeout) {
6500 timeout = setTimeout(later, remaining);
651 }
6520 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.
6601 _.debounce = function(func, wait, immediate) {
6610 var timeout, result;
6620 return function() {
6630 var context = this, args = arguments;
6640 var later = function() {
6650 timeout = null;
6660 if (!immediate) result = func.apply(context, args);
667 };
6680 var callNow = immediate && !timeout;
6690 clearTimeout(timeout);
6700 timeout = setTimeout(later, wait);
6710 if (callNow) result = func.apply(context, args);
6720 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.
6781 _.once = function(func) {
6790 var ran = false, memo;
6800 return function() {
6810 if (ran) return memo;
6820 ran = true;
6830 memo = func.apply(this, arguments);
6840 func = null;
6850 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.
6921 _.wrap = function(func, wrapper) {
6930 return function() {
6940 var args = [func];
6950 push.apply(args, arguments);
6960 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.
7021 _.compose = function() {
7030 var funcs = arguments;
7040 return function() {
7050 var args = arguments;
7060 for (var i = funcs.length - 1; i >= 0; i--) {
7070 args = [funcs[i].apply(this, args)];
708 }
7090 return args[0];
710 };
711 };
712
713 // Returns a function that will only be executed after being called N times.
7141 _.after = function(times, func) {
7150 if (times <= 0) return func();
7160 return function() {
7170 if (--times < 1) {
7180 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`
7281 _.keys = nativeKeys || function(obj) {
7290 if (obj !== Object(obj)) throw new TypeError('Invalid object');
7300 var keys = [];
7310 for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;
7320 return keys;
733 };
734
735 // Retrieve the values of an object's properties.
7361 _.values = function(obj) {
7370 var values = [];
7380 for (var key in obj) if (_.has(obj, key)) values.push(obj[key]);
7390 return values;
740 };
741
742 // Convert an object into a list of `[key, value]` pairs.
7431 _.pairs = function(obj) {
7440 var pairs = [];
7450 for (var key in obj) if (_.has(obj, key)) pairs.push([key, obj[key]]);
7460 return pairs;
747 };
748
749 // Invert the keys and values of an object. The values must be serializable.
7501 _.invert = function(obj) {
7511 var result = {};
75213 for (var key in obj) if (_.has(obj, key)) result[obj[key]] = key;
7531 return result;
754 };
755
756 // Return a sorted list of the function names available on the object.
757 // Aliased as `methods`
7581 _.functions = _.methods = function(obj) {
7591 var names = [];
7601 for (var key in obj) {
761216 if (_.isFunction(obj[key])) names.push(key);
762 }
7631 return names.sort();
764 };
765
766 // Extend a given object with all the properties in passed-in object(s).
7671 _.extend = function(obj) {
76897338 each(slice.call(arguments, 1), function(source) {
769194703 if (source) {
770194735 for (var prop in source) {
771248305 obj[prop] = source[prop];
772 }
773 }
774 });
77597441 return obj;
776 };
777
778 // Return a copy of the object only containing the whitelisted properties.
7791 _.pick = function(obj) {
7800 var copy = {};
7810 var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
7820 each(keys, function(key) {
7830 if (key in obj) copy[key] = obj[key];
784 });
7850 return copy;
786 };
787
788 // Return a copy of the object without the blacklisted properties.
7891 _.omit = function(obj) {
7900 var copy = {};
7910 var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
7920 for (var key in obj) {
7930 if (!_.contains(keys, key)) copy[key] = obj[key];
794 }
7950 return copy;
796 };
797
798 // Fill in a given object with default properties.
7991 _.defaults = function(obj) {
8000 each(slice.call(arguments, 1), function(source) {
8010 if (source) {
8020 for (var prop in source) {
8030 if (obj[prop] == null) obj[prop] = source[prop];
804 }
805 }
806 });
8070 return obj;
808 };
809
810 // Create a (shallow-cloned) duplicate of an object.
8111 _.clone = function(obj) {
8120 if (!_.isObject(obj)) return obj;
8130 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.
8191 _.tap = function(obj, interceptor) {
8200 interceptor(obj);
8210 return obj;
822 };
823
824 // Internal recursive comparison function for `isEqual`.
8251 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.
8280 if (a === b) return a !== 0 || 1 / a == 1 / b;
829 // A strict comparison is necessary because `null == undefined`.
8300 if (a == null || b == null) return a === b;
831 // Unwrap any wrapped objects.
8320 if (a instanceof _) a = a._wrapped;
8330 if (b instanceof _) b = b._wrapped;
834 // Compare `[[Class]]` names.
8350 var className = toString.call(a);
8360 if (className != toString.call(b)) return false;
8370 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")`.
8420 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.
8460 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.
8520 return +a == +b;
853 // RegExps are compared by their source patterns and flags.
854 case '[object RegExp]':
8550 return a.source == b.source &&
856 a.global == b.global &&
857 a.multiline == b.multiline &&
858 a.ignoreCase == b.ignoreCase;
859 }
8600 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`.
8630 var length = aStack.length;
8640 while (length--) {
865 // Linear search. Performance is inversely proportional to the number of
866 // unique nested structures.
8670 if (aStack[length] == a) return bStack[length] == b;
868 }
869 // Add the first object to the stack of traversed objects.
8700 aStack.push(a);
8710 bStack.push(b);
8720 var size = 0, result = true;
873 // Recursively compare objects and arrays.
8740 if (className == '[object Array]') {
875 // Compare array lengths to determine if a deep comparison is necessary.
8760 size = a.length;
8770 result = size == b.length;
8780 if (result) {
879 // Deep compare the contents, ignoring non-numeric properties.
8800 while (size--) {
8810 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.
8870 var aCtor = a.constructor, bCtor = b.constructor;
8880 if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) &&
889 _.isFunction(bCtor) && (bCtor instanceof bCtor))) {
8900 return false;
891 }
892 // Deep compare objects.
8930 for (var key in a) {
8940 if (_.has(a, key)) {
895 // Count the expected number of properties.
8960 size++;
897 // Deep compare each member.
8980 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.
9020 if (result) {
9030 for (key in b) {
9040 if (_.has(b, key) && !(size--)) break;
905 }
9060 result = !size;
907 }
908 }
909 // Remove the first object from the stack of traversed objects.
9100 aStack.pop();
9110 bStack.pop();
9120 return result;
913 };
914
915 // Perform a deep comparison to check if two objects are equal.
9161 _.isEqual = function(a, b) {
9170 return eq(a, b, [], []);
918 };
919
920 // Is a given array, string, or object empty?
921 // An "empty" object has no enumerable own-properties.
9221 _.isEmpty = function(obj) {
9230 if (obj == null) return true;
9240 if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
9250 for (var key in obj) if (_.has(obj, key)) return false;
9260 return true;
927 };
928
929 // Is a given value a DOM element?
9301 _.isElement = function(obj) {
9310 return !!(obj && obj.nodeType === 1);
932 };
933
934 // Is a given value an array?
935 // Delegates to ECMA5's native Array.isArray
9361 _.isArray = nativeIsArray || function(obj) {
9370 return toString.call(obj) == '[object Array]';
938 };
939
940 // Is a given variable an object?
9411 _.isObject = function(obj) {
9420 return obj === Object(obj);
943 };
944
945 // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
9461 each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
9476 _['is' + name] = function(obj) {
9483223 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.
9541 if (!_.isArguments(arguments)) {
9550 _.isArguments = function(obj) {
9560 return !!(obj && _.has(obj, 'callee'));
957 };
958 }
959
960 // Optimize `isFunction` if appropriate.
9611 if (typeof (/./) !== 'function') {
9621 _.isFunction = function(obj) {
96365381 return typeof obj === 'function';
964 };
965 }
966
967 // Is a given object a finite number?
9681 _.isFinite = function(obj) {
9690 return isFinite(obj) && !isNaN(parseFloat(obj));
970 };
971
972 // Is the given value `NaN`? (NaN is the only number which does not equal itself).
9731 _.isNaN = function(obj) {
9740 return _.isNumber(obj) && obj != +obj;
975 };
976
977 // Is a given value a boolean?
9781 _.isBoolean = function(obj) {
9790 return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
980 };
981
982 // Is a given value equal to null?
9831 _.isNull = function(obj) {
9840 return obj === null;
985 };
986
987 // Is a given variable undefined?
9881 _.isUndefined = function(obj) {
9890 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).
9941 _.has = function(obj, key) {
9956 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.
10031 _.noConflict = function() {
10040 root._ = previousUnderscore;
10050 return this;
1006 };
1007
1008 // Keep the identity function around for default iterators.
10091 _.identity = function(value) {
10100 return value;
1011 };
1012
1013 // Run a function **n** times.
10141 _.times = function(n, iterator, context) {
10150 var accum = Array(n);
10160 for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i);
10170 return accum;
1018 };
1019
1020 // Return a random integer between min and max (inclusive).
10211 _.random = function(min, max) {
10220 if (max == null) {
10230 max = min;
10240 min = 0;
1025 }
10260 return min + Math.floor(Math.random() * (max - min + 1));
1027 };
1028
1029 // List of HTML entities for escaping.
10301 var entityMap = {
1031 escape: {
1032 '&': '&amp;',
1033 '<': '&lt;',
1034 '>': '&gt;',
1035 '"': '&quot;',
1036 "'": '&#x27;',
1037 '/': '&#x2F;'
1038 }
1039 };
10401 entityMap.unescape = _.invert(entityMap.escape);
1041
1042 // Regexes containing the keys and values listed immediately above.
10431 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.
10491 _.each(['escape', 'unescape'], function(method) {
10502 _[method] = function(string) {
10510 if (string == null) return '';
10520 return ('' + string).replace(entityRegexes[method], function(match) {
10530 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.
10601 _.result = function(object, property) {
10610 if (object == null) return null;
10620 var value = object[property];
10630 return _.isFunction(value) ? value.call(object) : value;
1064 };
1065
1066 // Add your own custom functions to the Underscore object.
10671 _.mixin = function(obj) {
10681 each(_.functions(obj), function(name){
1069107 var func = _[name] = obj[name];
1070107 _.prototype[name] = function() {
10710 var args = [this._wrapped];
10720 push.apply(args, arguments);
10730 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.
10801 var idCounter = 0;
10811 _.uniqueId = function(prefix) {
10820 var id = ++idCounter + '';
10830 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.
10881 _.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.
10971 var noMatch = /(.)^/;
1098
1099 // Certain characters need to be escaped so that they can be put into a
1100 // string literal.
11011 var escapes = {
1102 "'": "'",
1103 '\\': '\\',
1104 '\r': 'r',
1105 '\n': 'n',
1106 '\t': 't',
1107 '\u2028': 'u2028',
1108 '\u2029': 'u2029'
1109 };
1110
11111 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.
11161 _.template = function(text, data, settings) {
11170 var render;
11180 settings = _.defaults({}, settings, _.templateSettings);
1119
1120 // Combine delimiters into one regular expression via alternation.
11210 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.
11280 var index = 0;
11290 var source = "__p+='";
11300 text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
11310 source += text.slice(index, offset)
11320 .replace(escaper, function(match) { return '\\' + escapes[match]; });
1133
11340 if (escape) {
11350 source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
1136 }
11370 if (interpolate) {
11380 source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
1139 }
11400 if (evaluate) {
11410 source += "';\n" + evaluate + "\n__p+='";
1142 }
11430 index = offset + match.length;
11440 return match;
1145 });
11460 source += "';\n";
1147
1148 // If a variable is not specified, place data values in local scope.
11490 if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
1150
11510 source = "var __t,__p='',__j=Array.prototype.join," +
1152 "print=function(){__p+=__j.call(arguments,'');};\n" +
1153 source + "return __p;\n";
1154
11550 try {
11560 render = new Function(settings.variable || 'obj', '_', source);
1157 } catch (e) {
11580 e.source = source;
11590 throw e;
1160 }
1161
11620 if (data) return render(data, _);
11630 var template = function(data) {
11640 return render.call(this, data, _);
1165 };
1166
1167 // Provide the compiled function source as a convenience for precompilation.
11680 template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
1169
11700 return template;
1171 };
1172
1173 // Add a "chain" function, which will delegate to the wrapper.
11741 _.chain = function(obj) {
11750 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.
11851 var result = function(obj) {
11860 return this._chain ? _(obj).chain() : obj;
1187 };
1188
1189 // Add all of the Underscore functions to the wrapper object.
11901 _.mixin(_);
1191
1192 // Add all mutator Array functions to the wrapper.
11931 each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
11947 var method = ArrayProto[name];
11957 _.prototype[name] = function() {
11960 var obj = this._wrapped;
11970 method.apply(obj, arguments);
11980 if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0];
11990 return result.call(this, obj);
1200 };
1201 });
1202
1203 // Add all accessor Array functions to the wrapper.
12041 each(['concat', 'join', 'slice'], function(name) {
12053 var method = ArrayProto[name];
12063 _.prototype[name] = function() {
12070 return result.call(this, method.apply(this._wrapped, arguments));
1208 };
1209 });
1210
12111 _.extend(_.prototype, {
1212
1213 // Start chaining a wrapped Underscore object.
1214 chain: function() {
12150 this._chain = true;
12160 return this;
1217 },
1218
1219 // Extracts the result from a wrapped and chained object.
1220 value: function() {
12210 return this._wrapped;
1222 }
1223
1224 });
1225
1226}).call(this);
1227

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/lib/utils.js

80.0%
10
8
2
LineHitsSource
1/**
2 * Module Dependencies
3 */
41var entities = require('entities');
5
6/**
7 * HTML Tags
8 */
9
101var 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
181exports.isTag = function(type) {
19293789 if (type.type) type = type.type;
20162880 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
291exports.camelCase = function(str) {
300 return str.replace(/[_.-](\w|$)/g, function(_, x) {
310 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
4150548exports.encode = function(str) { return entities.encode(String(str), 0); };
4232560exports.decode = function(str) { return entities.decode(str, 2); };
43

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/entities/index.js

75.9%
58
44
14
LineHitsSource
11var modes = ["XML", "HTML4", "HTML5"];
2
31module.exports = {
4 decode: function(data, level){
532602 if(!modes[level]) level = 0;
632607 return module.exports["decode" + modes[level]](data);
7 },
8 decodeStrict: function(data, level){
90 if(!modes[level]) level = 0;
100 return module.exports["decode" + modes[level] + "Strict"](data);
11 },
12 encode: function(data, level){
1350678 if(!modes[level]) level = 0;
1450686 return module.exports["encode" + modes[level]](data);
15 }
16};
17
181modes.reduce(function(prev, name){
193 var obj = require("c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/entities/./entities/" + name.toLowerCase() + ".json");
20
213 if(prev){
222 Object.keys(prev).forEach(function(name){
23359 obj[name] = prev[name];
24 });
25 }
26
273 module.exports["decode" + name + "Strict"] = getStrictReplacer(obj);
28
293 if(name === "XML"){
30 //there is no non-strict mode for XML
311 module.exports.decodeXML = module.exports.decodeXMLStrict;
32 } else {
332 module.exports["decode" + name] = getReplacer(obj);
34 }
35
363 module.exports["encode" + name] = getReverse(obj);
37
383 return obj;
39}, null);
40
411function getReplacer(obj){
422 var keys = Object.keys(obj).sort();
432 var re = keys.join("|").replace(/(\w+)\|\1;/g, "$1;?");
44
45 // also match hex and char codes
462 re += "|#[xX][\\da-fA-F]+;?|#\\d+;?";
47
482 return genReplaceFunc(
49 new RegExp("&(?:" + re + ")", "g"),
50 function func(name){
510 if(name.charAt(1) === "#"){
520 if(name.charAt(2).toLowerCase() === "x"){
530 return String.fromCharCode(parseInt(name.substr(3), 16));
54 }
550 return String.fromCharCode(parseInt(name.substr(2), 10));
56 }
570 return obj[name.substr(1)];
58 }
59 );
60}
61
621function getStrictReplacer(obj){
633 var keys = Object.keys(obj).sort().filter(RegExp.prototype.test, /;$/);
643 var re = keys.map(function(name){
652383 return name.slice(0, -1); //remove trailing semicolon
66 }).join("|");
67
68 // also match hex and char codes
693 re += "|#[xX][\\da-fA-F]+|#\\d+";
70
713 var expr = new RegExp("&(?:" + re + ");", "g");
72
733 return genReplaceFunc(expr, func);
74
750 function func(name){
760 if(name.charAt(1) === "#"){
770 if(name.charAt(2).toLowerCase() === "x"){
780 return String.fromCharCode(parseInt(name.substr(3), 16));
79 }
800 return String.fromCharCode(parseInt(name.substr(2), 10));
81 }
820 return obj[name.substr(1)];
83 }
84}
85
861var 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
881function nonUTF8Replacer(c){
890 return "&#" + c.charCodeAt(0) + ";";
90}
91
921function getReverse(obj){
933 var reverse = Object.keys(obj).filter(function(name){
94 //prefer identifiers with a semicolon
952591 return name.substr(-1) === ";" || obj[name + ";"] !== obj[name];
96 }).reduce(function(reverse, name){
972383 reverse[obj[name]] = name;
982383 return reverse;
99 }, {});
100
1013 var regex = new RegExp("\\" + Object.keys(reverse).sort().join("|\\"), "g");
1023 function func(name){
1033612 return "&" + reverse[name];
104 }
105
1063 return function(data){
10751338 return data
108 .replace(regex, func)
109 .replace(re_nonUTF8, nonUTF8Replacer);
110 };
111}
112
1131function genReplaceFunc(regex, func){
1145 return function(data){
11533097 return data.replace(regex, func);
116 };
117}
118

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/lib/static.js

49.0%
51
25
26
LineHitsSource
1/**
2 * Module dependencies
3 */
4
51var select = require('cheerio-select'),
6 parse = require('./parse'),
7 render = require('./render'),
8 decode = require('./utils').decode;
9
10/**
11 * $.load(str)
12 */
13
141var load = exports.load = function(str, options) {
151 var Cheerio = require('./cheerio'),
16 root = parse(str, options);
17
181 var initialize = function(selector, context, r) {
19213 return new Cheerio(selector, context, r || root);
20 };
21
22 // Add in the static methods
231 initialize.__proto__ = exports;
24
25 // Add in the root
261 initialize._root = root;
27
281 return initialize;
29};
30
31/**
32 * $.html([selector | dom])
33 */
34
351var html = exports.html = function(dom) {
367360 if (dom) {
377361 dom = (typeof dom === 'string') ? select(dom, this._root) : dom;
387362 return render(dom);
390 } else if (this._root && this._root.children) {
400 return render(this._root.children);
41 } else {
420 return '';
43 }
44};
45
46/**
47 * $.xml([selector | dom])
48 */
49
501var xml = exports.xml = function(dom) {
510 if (dom) {
520 dom = (typeof dom === 'string') ? select(dom, this._root) : dom;
530 return render(dom, { xmlMode: true });
540 } else if (this._root && this._root.children) {
550 return render(this._root.children, { xmlMode: true });
56 } else {
570 return '';
58 }
59};
60
61/**
62 * $.text(dom)
63 */
64
651var text = exports.text = function(elems) {
667720 if (!elems) return '';
67
687722 var ret = '',
69 len = elems.length,
70 elem;
71
727728 for (var i = 0; i < len; i ++) {
733864 elem = elems[i];
743864 if (elem.type === 'text') ret += decode(elem.data);
753864 else if (elem.children && elem.type !== 'comment') {
763864 ret += text(elem.children);
77 }
78 }
79
807734 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 */
881var parseHTML = exports.parseHTML = function(data, context, keepScripts) {
890 var parsed;
90
910 if (!data || typeof data !== 'string') {
920 return null;
93 }
94
950 if (typeof context === 'boolean') {
960 keepScripts = context;
97 }
98
990 parsed = this.load(data);
1000 if (!keepScripts) {
1010 parsed('script').remove();
102 }
103
1040 return parsed.root()[0].children;
105};
106
107/**
108 * $.root()
109 */
1101var root = exports.root = function() {
1110 return this(this._root);
112};
113
114/**
115 * $.contains()
116 */
1171var contains = exports.contains = function(container, contained) {
118
119 // According to the jQuery API, an element does not "contain" itself
1200 if (contained === container) {
1210 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)
1260 while (contained && contained !== contained.parent) {
1270 contained = contained.parent;
1280 if (contained === container) {
1290 return true;
130 }
131 }
132
1330 return false;
134};
135

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/lib/render.js

88.2%
51
45
6
LineHitsSource
1/*
2 Module dependencies
3*/
41var _ = require('underscore');
51var utils = require('./utils');
6
71var decode = utils.decode;
81var encode = utils.encode;
9
10/*
11 Boolean Attributes
12*/
131var rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i;
14
15/*
16 Format attributes
17*/
181var formatAttrs = function(attributes) {
1930359 if (!attributes) return '';
20
2130367 var output = [],
22 value;
23
24 // Loop through the attributes
2530383 for (var key in attributes) {
2630387 value = attributes[key];
2730391 if (!value && (rboolean.test(key) || key === '/')) {
280 output.push(key);
29 } else {
3030403 output.push(key + '="' + encode(decode(value)) + '"');
31 }
32 }
33
3430419 return output.join(' ');
35};
36
37/*
38 Self-enclosing tags (stolen from node-htmlparser)
39*/
401var 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*/
621var tagType = {
63 tag: 1,
64 script: 1,
65 link: 1,
66 style: 1,
67 template: 1
68};
69
701var render = module.exports = function(dom, opts) {
7138484 if (!Array.isArray(dom) && !dom.cheerio) dom = [dom];
7238489 opts = opts || {};
73
7438499 var output = [],
75 xmlMode = opts.xmlMode || false,
76 ignoreWhitespace = opts.ignoreWhitespace || false;
77
7838519 _.each(dom, function(elem) {
7932191 var pushVal;
80
8132199 if (tagType[elem.type])
8230996 pushVal = renderTag(elem, xmlMode);
831207 else if (elem.type === 'directive')
840 pushVal = renderDirective(elem);
851207 else if (elem.type === 'comment')
860 pushVal = renderComment(elem);
87 else
881207 pushVal = renderText(elem);
89
90 // Push rendered DOM node
9132239 output.push(pushVal);
92
9332247 if (elem.children)
9431044 output.push(render(elem.children, opts));
95
9632259 if ((!singleTag[elem.name] || xmlMode) && tagType[elem.type]) {
9731056 if (!isClosedTag(elem, xmlMode)) {
9831060 output.push('</' + elem.name + '>');
99 }
100 }
101 });
102
10338644 return output.join('');
104};
105
1061var isClosedTag = function(elem, xmlMode){
10762192 return (xmlMode && (!elem.children || elem.children.length === 0));
108};
109
1101var renderTag = function(elem, xmlMode) {
11131112 var tag = '<' + elem.name;
112
11331120 if (elem.attribs && _.size(elem.attribs)) {
11430739 tag += ' ' + formatAttrs(elem.attribs);
115 }
116
11731136 if (isClosedTag(elem, xmlMode)) {
1180 tag += '/';
119 }
120
12131152 return tag + '>';
122};
123
1241var renderDirective = function(elem) {
1250 return '<' + elem.data + '>';
126};
127
1281var renderText = function(elem) {
1291207 return elem.data;
130};
131
1321var renderComment = function(elem) {
1330 return '<!--' + elem.data + '-->';
134};
135
136// module.exports = $.extend(exports);
137

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/lib/api/attributes.js

27.8%
162
45
117
LineHitsSource
11var _ = 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
231var setAttr = function(el, name, value) {
243614 if (typeof name === 'object') return _.extend(el.attribs, name);
25
263615 if (value === null) {
270 removeAttribute(el, name);
28 } else {
293617 el.attribs[name] = encode(value);
30 }
31
323618 return el.attribs;
33};
34
351var attr = exports.attr = function(name, value) {
36 // Set the value (with attr map support)
377129 if (typeof name === 'object' || value !== undefined) {
383621 if (_.isFunction(value)) {
390 return this.each(function(i, el) {
400 setAttr(el, name, value.call(this, i, el.attribs[name]));
41 });
42 }
433624 return this.each(function(i, el) {
443625 el.attribs = setAttr(el, name, value);
45 });
46 }
47
483515 var elem = this[0];
49
503516 if (!elem || !isTag(elem)) return;
51
523517 if (!elem.attribs) {
530 elem.attribs = {};
54 }
55
56 // Return the entire attribs object if no attribute specified
573519 if (!name) {
580 for (var a in elem.attribs) {
590 elem.attribs[a] = decode(elem.attribs[a]);
60 }
610 return elem.attribs;
62 }
63
643523 if (hasOwn.call(elem.attribs, name)) {
65 // Get the (decoded) attribute
663524 return decode(elem.attribs[name]);
67 }
68};
69
701var setData = function(el, name, value) {
710 if (typeof name === 'object') return _.extend(el.data, name);
720 if (typeof name === 'string' && value !== undefined) {
730 el.data[name] = encode(value);
740 } else if (typeof name === 'object') {
75 // If its an object, loop through it
760 _.each(name, function(value, key) {
770 el.data[key] = encode(value);
78 });
79 }
80
810 return el.data;
82};
83
841var data = exports.data = function(name, value) {
850 var elem = this[0];
86
870 if (!elem || !isTag(elem)) return;
88
890 if (!elem.data) {
900 elem.data = {};
91 }
92
93 // Return the entire data object if no data specified
940 if (!name) {
95
960 _.each(elem.data, function(value, key) {
970 elem.data[key] = decode(value);
98 });
99
1000 return elem.data;
101 }
102
103 // Set the value (with attr map support)
1040 if (typeof name === 'object' || value !== undefined) {
1050 this.each(function(i, el) {
1060 el.data = setData(el, name, value);
107 });
1080 return this;
1090 } else if (hasOwn.call(elem.data, name)) {
110 // Get the (decoded) data
1110 var val = decode(elem.data[name]);
112
1130 if (hasOwn.call(primitives, val)) {
1140 val = primitives[val];
1150 } else if (val === String(Number(val))) {
1160 val = Number(val);
1170 } else if (rbrace.test(val)) {
1180 val = JSON.parse(val);
119 }
120
1210 return val;
1220 } else if (typeof name === 'string' && value === undefined) {
1230 return undefined;
124 }
125
1260 return this;
127};
128
129/**
130 * Get the value of an element
131 */
132
1331var val = exports.val = function(value) {
1340 var querying = arguments.length === 0,
135 element = this[0];
136
1370 if(!element) return;
138
1390 switch (element.name) {
140 case 'textarea':
1410 return querying ? this.text() : this.each(function() {
1420 this.text(value);
143 });
144 case 'input':
1450 switch (this.attr('type')) {
146 case 'radio':
1470 var queryString = 'input[type=radio][name=' + this.attr('name') + ']:checked';
1480 var parentEl, root;
149
150 // Go up until we hit a form or root
1510 parentEl = this.closest('form');
1520 if (parentEl.length === 0) {
1530 root = (this.parents().last()[0] || this[0]).parent;
1540 parentEl = this.make(root);
155 }
156
1570 if (querying) {
1580 return parentEl.find(queryString).attr('value');
159 } else {
1600 parentEl.find(':checked').removeAttr('checked');
1610 parentEl.find('input[type=radio][value="' + value + '"]').attr('checked', '');
1620 return this;
163 }
1640 break;
165 default:
1660 return querying ? this.attr('value') : this.each(function() {
1670 this.attr('value', value);
168 });
169 }
1700 return;
171 case 'select':
1720 var option = this.find('option:selected'),
173 returnValue;
1740 if (option === undefined) return undefined;
1750 if (!querying) {
1760 if (!this.attr().hasOwnProperty('multiple') && typeof value == 'object') {
1770 return this;
178 }
1790 if (typeof value != 'object') {
1800 value = [value];
181 }
1820 this.find('option').removeAttr('selected');
1830 for (var i = 0; i < value.length; i++) {
1840 this.find('option[value="' + value[i] + '"]').attr('selected', '');
185 }
1860 return this;
187 }
1880 returnValue = option.attr('value');
1890 if (this.attr().hasOwnProperty('multiple')) {
1900 returnValue = [];
1910 option.each(function() {
1920 returnValue.push(this.attr('value'));
193 });
194 }
1950 return returnValue;
196 case 'option':
1970 if (!querying) {
1980 this.attr('value', value);
1990 return this;
200 }
2010 return this.attr('value');
202 }
203};
204
205/**
206 * Remove an attribute
207 */
208
2091var removeAttribute = function(elem, name) {
2100 if (!isTag(elem.type) || !elem.attribs || !Object.hasOwnProperty.call(elem.attribs, name))
2110 return;
212
2130 if (rboolean.test(elem.attribs[name]))
2140 elem.attribs[name] = false;
215 else
2160 delete elem.attribs[name];
217};
218
219
2201var removeAttr = exports.removeAttr = function(name) {
2210 this.each(function(i, elem) {
2220 removeAttribute(elem, name);
223 });
224
2250 return this;
226};
227
2281var hasClass = exports.hasClass = function(className) {
2290 return _.any(this, function(elem) {
2300 var attrs = elem.attribs;
2310 return attrs && _.contains((attrs['class'] || '').split(rspace), className);
232 });
233};
234
2351var addClass = exports.addClass = function(value) {
236 // Support functions
2373616 if (_.isFunction(value)) {
2380 this.each(function(i) {
2390 var className = this.attr('class') || '';
2400 this.addClass(value.call(this[0], i, className));
241 });
242 }
243
244 // Return if no value or not a string or function
2453620 if (!value || !_.isString(value)) return this;
246
2473621 var classNames = value.split(rspace),
248 numElements = this.length,
249 numClasses,
250 setClass,
251 $elem;
252
253
2543622 for (var i = 0; i < numElements; i++) {
2553623 $elem = this.make(this[i]);
256 // If selected element isnt a tag, move on
2573624 if (!isTag(this[i])) continue;
258
259 // If we don't already have classes
2603625 if (!$elem.attr('class')) {
2613626 $elem.attr('class', classNames.join(' ').trim());
262 } else {
2630 setClass = ' ' + $elem.attr('class') + ' ';
2640 numClasses = classNames.length;
265
266 // Check if class already exists
2670 for (var j = 0; j < numClasses; j++) {
2680 if (!~setClass.indexOf(' ' + classNames[j] + ' '))
2690 setClass += classNames[j] + ' ';
270 }
271
2720 $elem.attr('class', setClass.trim());
273 }
274 }
275
2763633 return this;
277};
278
2791var removeClass = exports.removeClass = function(value) {
2807880 var split = function(className) {
28115762 return className ? className.trim().split(rspace) : [];
282 };
2837883 var classes, removeAll;
284
285 // Handle if value is a function
2867886 if (_.isFunction(value)) {
2870 return this.each(function(i, el) {
2880 this.removeClass(value.call(this[0], i, el.attribs['class'] || ''));
289 });
290 }
291
2927892 classes = split(value);
2937893 removeAll = arguments.length === 0;
294
2957895 return this.each(function(i, el) {
2967896 if (!isTag(el)) return;
2977897 el.attribs.class = removeAll ?
298 '' :
299 _.difference(split(el.attribs.class), classes).join(' ');
300 });
301};
302
3031var toggleClass = exports.toggleClass = function(value, stateVal) {
304 // Support functions
3050 if (_.isFunction(value)) {
3060 return this.each(function(i, el) {
3070 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
3120 if (!value || !_.isString(value)) return this;
313
3140 var classNames = value.split(rspace),
315 numClasses = classNames.length,
316 isBool = typeof stateVal === 'boolean',
317 numElements = this.length,
318 $elem,
319 state;
320
3210 for (var i = 0; i < numElements; i++) {
3220 $elem = this.make(this[i]);
323 // If selected element isnt a tag, move on
3240 if (!isTag(this[i])) continue;
325
326 // Check if class already exists
3270 for (var j = 0; j < numClasses; j++) {
328 // check each className given, space separated list
3290 state = isBool ? stateVal : !$elem.hasClass(classNames[j]);
3300 $elem[state ? 'addClass' : 'removeClass'](classNames[j]);
331 }
332 }
333
3340 return this;
335};
336
3371var is = exports.is = function (selector) {
3380 if (selector) {
3390 return this.filter(selector).length > 0;
340 }
3410 return false;
342};
343
344

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/lib/api/traversing.js

26.7%
101
27
74
LineHitsSource
11var _ = require('underscore'),
2 select = require('cheerio-select'),
3 utils = require('../utils'),
4 isTag = utils.isTag;
5
61var 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
1032045 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.
151var parent = exports.parent = function(selector) {
160 var set = [];
170 var $set;
18
190 this.each(function(idx, elem) {
200 var parentElem = elem.parent;
210 if (set.indexOf(parentElem) < 0 && parentElem.type !== 'root') {
220 set.push(parentElem);
23 }
24 });
25
260 $set = this.make(set);
27
280 if (arguments.length) {
290 $set = $set.filter(selector);
30 }
31
320 return $set;
33};
34
351var parents = exports.parents = function(selector) {
360 if (this[0] && this[0].parent) {
370 return traverseParents(this, this[0].parent, selector, Infinity);
38 }
390 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.
451var closest = exports.closest = function(selector) {
460 var set = [];
47
480 if (!selector) {
490 return this.make(set);
50 }
51
520 this.each(function(idx, elem) {
530 var closestElem = traverseParents(this, elem, selector, 1)[0];
54
55 // Do not add duplicate elements to the set
560 if (closestElem && set.indexOf(closestElem) < 0) {
570 set.push(closestElem);
58 }
59 }.bind(this));
60
610 return this.make(set);
62};
63
641var next = exports.next = function() {
650 if (!this[0]) { return this; }
660 var elem = this[0];
670 while ((elem = elem.next)) if (isTag(elem)) return this.make(elem);
680 return this.make([]);
69};
70
711var nextAll = exports.nextAll = function(selector) {
720 if (!this[0]) { return this; }
730 var elems = [], elem = this[0];
740 while ((elem = elem.next)) if (isTag(elem)) elems.push(elem);
750 return this.make(selector ? select(selector, elems) : elems);
76};
77
781var prev = exports.prev = function() {
790 if (!this[0]) { return this; }
800 var elem = this[0];
810 while ((elem = elem.prev)) if (isTag(elem)) return this.make(elem);
820 return this.make([]);
83};
84
851var prevAll = exports.prevAll = function(selector) {
860 if (!this[0]) { return this; }
870 var elems = [], elem = this[0];
880 while ((elem = elem.prev)) if (isTag(elem)) elems.push(elem);
890 return this.make(selector ? select(selector, elems) : elems);
90};
91
921var siblings = exports.siblings = function(selector) {
930 var elems = _.filter(
94 this.parent() ? this.parent().children() : this.siblingsAndMe(),
950 function(elem) { return isTag(elem) && !this.is(elem); },
96 this
97 );
980 if (selector !== undefined) {
990 elems = this.make(select(selector, elems));
100 }
1010 return this.make(elems);
102};
103
1041var children = exports.children = function(selector) {
105
10632429 var elems = _.reduce(this, function(memo, elem) {
10732433 return memo.concat(_.filter(elem.children, isTag));
108 }, []);
109
11064890 if (selector === undefined) return this.make(elems);
1110 else if (_.isNumber(selector)) return this.make(elems[selector]);
112
1130 return this.make(elems).filter(selector);
114};
115
1161var contents = exports.contents = function() {
1170 return this.make(_.reduce(this, function(all, elem) {
1180 all.push.apply(all, elem.children);
1190 return all;
120 }, []));
121};
122
1231var each = exports.each = function(fn) {
12440011 var i = 0, len = this.length;
12580034 while (i < len && fn.call(this.make(this[i]), i, this[i]) !== false) ++i;
12640023 return this;
127};
128
1291var map = exports.map = function(fn) {
1300 return _.map(this, function(el, i) {
1310 return fn.call(this.make(el), i, el);
132 }, this);
133};
134
1351var filter = exports.filter = function(match) {
1360 var make = _.bind(this.make, this);
1370 var filterFn;
138
1390 if (_.isString(match)) {
1400 filterFn = function(el) {
1410 return select(match, el)[0] === el;
142 };
1430 } else if (_.isFunction(match)) {
1440 filterFn = function(el, i) {
1450 return match.call(make(el), i, el);
146 };
1470 } else if (match.cheerio) {
1480 filterFn = match.is.bind(match);
149 } else {
1500 filterFn = function(el) {
1510 return match === el;
152 };
153 }
154
1550 return make(_.filter(this, filterFn));
156};
157
1581var first = exports.first = function() {
1590 return this[0] ? this.make(this[0]) : this;
160};
161
1621var last = exports.last = function() {
1630 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.
1671var eq = exports.eq = function(i) {
1680 i = +i;
1690 if (i < 0) i = this.length + i;
1700 return this[i] ? this.make(this[i]) : this.make([]);
171};
172
1731var slice = exports.slice = function() {
1740 return this.make([].slice.apply(this, arguments));
175};
176
1771function traverseParents(self, elem, selector, limit) {
1780 var elems = [];
1790 while (elems.length < limit && elem.type !== 'root') {
1800 if (!selector || self.make(elem).filter(selector).length) {
1810 elems.push(elem);
182 }
1830 elem = elem.parent;
184 }
1850 return self.make(elems);
186}
187

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/lib/api/manipulation.js

36.2%
94
34
60
LineHitsSource
11var _ = 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
111var makeDomArray = function(elem) {
1216290 if (elem == null) {
130 return [];
1416294 } else if (elem.cheerio) {
158148 return elem.toArray();
168149 } else if (_.isArray(elem)) {
178150 return _.flatten(elem.map(makeDomArray));
180 } else if (_.isString(elem)) {
190 return evaluate(elem);
20 } else {
210 return [elem];
22 }
23};
24
251var _insert = function(concatenator) {
262 return function() {
278160 var elems = slice.call(arguments),
28 dom = makeDomArray(elems);
29
308163 return this.each(function(i, el) {
318164 if (_.isFunction(elems[0])) {
320 dom = makeDomArray(elems[0].call(el, i, this.html()));
33 }
348167 updateDOM(concatenator(dom, el.children || (el.children = [])), el);
35 });
36 };
37};
38
391var append = exports.append = _insert(function(dom, children) {
408173 return children.concat(dom);
41});
42
431var prepend = exports.prepend = _insert(function(dom, children) {
440 return dom.concat(children);
45});
46
471var after = exports.after = function() {
480 var elems = slice.call(arguments),
49 dom = makeDomArray(elems);
50
510 this.each(function(i, el) {
520 var siblings = el.parent.children,
53 index = siblings.indexOf(el);
54
55 // If not found, move on
560 if (!~index) return;
57
580 if (_.isFunction(elems[0])) {
590 dom = makeDomArray(elems[0].call(el, i));
60 }
61
62 // Add element after `this` element
630 siblings.splice.apply(siblings, [++index, 0].concat(dom));
64
65 // Update next, prev, and parent pointers
660 updateDOM(siblings, el.parent);
670 el.parent.children = siblings;
68
69 });
70
710 return this;
72};
73
741var before = exports.before = function() {
750 var elems = slice.call(arguments),
76 dom = makeDomArray(elems);
77
780 this.each(function(i, el) {
790 var siblings = el.parent.children,
80 index = siblings.indexOf(el);
81
82 // If not found, move on
830 if (!~index) return;
84
850 if (_.isFunction(elems[0])) {
860 dom = makeDomArray(elems[0].call(el, i));
87 }
88
89 // Add element before `el` element
900 siblings.splice.apply(siblings, [index, 0].concat(dom));
91
92 // Update next, prev, and parent pointers
930 updateDOM(siblings, el.parent);
940 el.parent.children = siblings;
95
96 });
97
980 return this;
99};
100
101/*
102 remove([selector])
103*/
1041var remove = exports.remove = function(selector) {
1050 var elems = this;
106
107 // Filter if we have selector
1080 if (selector)
1090 elems = elems.filter(selector);
110
1110 elems.each(function(i, el) {
1120 var siblings = el.parent.children,
113 index = siblings.indexOf(el);
114
1150 if (!~index) return;
116
1170 siblings.splice(index, 1);
118
119 // Update next, prev, and parent pointers
1200 updateDOM(siblings, el.parent);
1210 el.parent.children = siblings;
122 });
123
1240 return this;
125};
126
1271var replaceWith = exports.replaceWith = function(content) {
1280 var dom = makeDomArray(content);
129
1300 this.each(function(i, el) {
1310 var siblings = el.parent.children,
132 index = siblings.indexOf(el);
133
1340 if (!~index) return;
135
1360 if (_.isFunction(content)) {
1370 dom = makeDomArray(content.call(el, i));
138 }
139
1400 siblings.splice.apply(siblings, [index, 1].concat(dom));
141
1420 updateDOM(siblings, el.parent);
1430 el.parent.children = siblings;
144 });
145
1460 return this;
147};
148
1491var empty = exports.empty = function() {
1500 this.each(function(i, el) {
1510 el.children = [];
152 });
1530 return this;
154};
155
156/**
157 * Set/Get the HTML
158 */
1591var html = exports.html = function(str) {
1600 if (str === undefined) {
1610 if (!this[0] || !this[0].children) return null;
1620 return $.html(this[0].children);
163 }
164
1650 str = str.cheerio ? str.toArray() : evaluate(str);
166
1670 this.each(function(i, el) {
1680 el.children = str;
1690 updateDOM(el.children, el);
170 });
171
1720 return this;
173};
174
1751var toString = exports.toString = function() {
1760 return $.html(this);
177};
178
1791var text = exports.text = function(str) {
180 // If `str` is undefined, act as a "getter"
18125001 if (str === undefined) {
1824354 return $.text(this);
18320653 } else if (_.isFunction(str)) {
184 // Function support
1850 return this.each(function(i, el) {
1860 return this.text(str.call(el, i, this.text()));
187 });
188 }
189
19020670 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
20020691 this.each(function(i, el) {
20120694 el.children = elem;
20220697 updateDOM(el.children, el);
203 });
204
20520704 return this;
206};
207
2081var clone = exports.clone = function() {
209 // Turn it into HTML, then recreate it,
210 // Seems to be the easiest way to reconnect everything correctly
2118346 return this.constructor($.html(this));
212};
213

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/lib/api/css.js

17.9%
39
7
32
LineHitsSource
11var _ = require('underscore');
21var 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
131exports.css = function(prop, val) {
140 if (arguments.length === 2 ||
15 // When `prop` is a "plain" object
16 (toString.call(prop) === '[object Object]')) {
170 return this.each(function(idx) {
180 this._setCss(prop, val, idx);
19 });
20 } else {
210 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
351exports._setCss = function(prop, val, idx) {
360 if ('string' == typeof prop) {
370 var styles = this._getCss();
380 if (_.isFunction(val)) {
390 val = val.call(this[0], idx, this[0]);
40 }
41
420 if (val === '') {
430 delete styles[prop];
440 } else if (val != null) {
450 styles[prop] = val;
46 }
47
480 return this.attr('style', stringify(styles));
490 } else if ('object' == typeof prop) {
500 Object.keys(prop).forEach(function(k){
510 this._setCss(k, prop[k]);
52 }, this);
530 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
651exports._getCss = function(prop) {
660 var styles = parse(this.attr('style'));
670 if (typeof prop === 'string') {
680 return styles[prop];
690 } else if (_.isArray(prop)) {
700 return _.pick(styles, prop);
71 } else {
720 return styles;
73 }
74};
75
76/**
77 * Stringify `obj` to styles.
78 *
79 * @param {Object} obj
80 * @return {Object}
81 * @api private
82 */
83
841function stringify(obj) {
850 return Object.keys(obj || {})
86 .reduce(function(str, prop){
870 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
1041function parse(styles) {
1050 styles = (styles || '').trim();
106
1070 if (!styles) return {};
108
1090 return styles
110 .split(/\s*;\s*/)
111 .reduce(function(obj, str){
1120 var parts = str.split(/\s*:\s*/);
1130 if (!parts[0]) return obj;
1140 obj[parts[0]] = parts[1];
1150 return obj;
116 }, {});
117}
118

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/htmlparser2/node_modules/domhandler/index.js

81.3%
75
61
14
LineHitsSource
11var ElementType = require("domelementtype");
2
31function DomHandler(callback, options, elementCB){
48475 if(typeof callback === "object"){
50 elementCB = options;
60 options = callback;
70 callback = null;
88479 } else if(typeof options === "function"){
90 elementCB = options;
100 options = defaultOpts;
11 }
128483 this._callback = callback;
138484 this._options = options || defaultOpts;
148485 this._elementCB = elementCB;
158486 this.dom = [];
168487 this._done = false;
178488 this._tagStack = [];
18}
19
20//default options
211var defaultOpts = {
22 ignoreWhitespace: false //Keep whitespace-only text nodes
23};
24
25//Resets the handler back to starting state
261DomHandler.prototype.onreset = function(){
270 DomHandler.call(this, this._callback, this._options, this._elementCB);
28};
29
30//Signals the handler that parsing is done
311DomHandler.prototype.onend = function(){
328503 if(this._done) return;
338504 this._done = true;
348505 this._handleCallback(null);
35};
36
371DomHandler.prototype._handleCallback =
38DomHandler.prototype.onerror = function(error){
398510 if(typeof this._callback === "function"){
400 this._callback(error, this.dom);
41 } else {
428513 if(error) throw error;
43 }
44};
45
461DomHandler.prototype.onclosetag = function(name){
47 //if(this._tagStack.pop().name !== name) this._handleCallback(Error("Tagname didn't match!"));
4835011 var elem = this._tagStack.pop();
4935015 if(this._elementCB) this._elementCB(elem);
50};
51
521DomHandler.prototype._addDomElement = function(element){
531373 var lastTag = this._tagStack[this._tagStack.length - 1];
54
551373 if(lastTag){
561368 lastTag.children.push(element);
57 } else { //There aren't parent elements
585 this.dom.push(element);
59 }
60};
61
621DomHandler.prototype.onopentag = function(name, attribs){
6335071 var lastTag = this._tagStack[this._tagStack.length - 1];
64
6535079 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
7535119 if(lastTag){
7626576 var idx = lastTag.children.length;
7726579 while(idx > 0){
7818406 if(ElementType.isTag(lastTag.children[--idx])){
7917600 element.prev = lastTag.children[idx];
8017602 lastTag.children[idx].next = element;
8117604 break;
82 }
83 }
8426600 lastTag.children.push(element);
85 } else {
868557 this.dom.push(element);
87 }
88
8935175 this._tagStack.push(element);
90};
91
921DomHandler.prototype.ontext = function(data){
931372 if(this._options.ignoreWhitespace && data.trim() === "") return;
94
951372 if(this._tagStack.length){
961369 var lastTag;
97
981369 if(
99 (lastTag = this._tagStack[this._tagStack.length - 1]) &&
100 (lastTag = lastTag.children[lastTag.children.length - 1]) &&
101 lastTag.type === ElementType.Text
102 ){
1031 lastTag.data += data;
1041 return;
105 }
106 } else {
1073 if(this.dom.length && this.dom[this.dom.length-1].type === ElementType.Text){
1080 this.dom[this.dom.length-1].data += data;
1090 return;
110 }
111 }
112
1131371 this._addDomElement({
114 data: data,
115 type: ElementType.Text
116 });
117};
118
1191DomHandler.prototype.oncomment = function(data){
1201 var lastTag = this._tagStack[this._tagStack.length - 1];
121
1221 if(lastTag && lastTag.type === ElementType.Comment){
1230 lastTag.data += data;
1240 return;
125 }
126
1271 var element = {
128 data: data,
129 type: ElementType.Comment
130 };
131
1321 this._addDomElement(element);
1331 this._tagStack.push(element);
134};
135
1361DomHandler.prototype.oncdatastart = function(){
1370 var element = {
138 children: [{
139 data: "",
140 type: ElementType.Text
141 }],
142 type: ElementType.CDATA
143 };
144
1450 this._addDomElement(element);
1460 this._tagStack.push(element);
147};
148
1491DomHandler.prototype.oncommentend = DomHandler.prototype.oncdataend = function(){
1501 this._tagStack.pop();
151};
152
1531DomHandler.prototype.onprocessinginstruction = function(name, data){
1541 this._addDomElement({
155 name: name,
156 data: data,
157 type: ElementType.Directive
158 });
159};
160
1611module.exports = DomHandler;

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/htmlparser2/node_modules/domelementtype/index.js

100.0%
2
2
0
LineHitsSource
1//Types of elements found in the DOM
21module.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){
1218621 return elem.type === "tag" || elem.type === "script" || elem.type === "style";
13 }
14};

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/htmlparser2/lib/Parser.js

70.2%
114
80
34
LineHitsSource
11var 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
261var formTags = {
27 input: true,
28 option: true,
29 optgroup: true,
30 select: true,
31 button: true,
32 datalist: true,
33 textarea: true
34};
351var 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
521var 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
751function Parser(cbs, options){
768726 this._options = options || {};
778727 this._cbs = cbs || {};
78
798729 this._tagname = "";
808730 this._attribname = "";
818731 this._attribs = null;
828732 this._stack = [];
838733 this._done = false;
84
858735 this._tokenizer = new Tokenizer(options, this);
86}
87
881require("util").inherits(Parser, require("events").EventEmitter);
89
90//Tokenizer event handlers
911Parser.prototype.ontext = function(data){
922832 if(this._cbs.ontext) this._cbs.ontext(data);
93};
94
951Parser.prototype.onopentagname = function(name){
9635949 if(!(this._options.xmlMode || "lowerCaseTags" in this._options) || this._options.lowerCaseTags){
9735953 name = name.toLowerCase();
98 }
99
10035965 this._tagname = name;
101
10235973 if (!this._options.xmlMode && name in openImpliesClose) {
10335084 for(
104 var el;
105 (el = this._stack[this._stack.length-1]) in openImpliesClose[name];
106 this.onclosetag(el)
107 );
108 }
109
11036005 if(this._options.xmlMode || !(name in voidElements)){
11136009 this._stack.push(name);
112 }
113
11436021 if(this._cbs.onopentagname) this._cbs.onopentagname(name);
11572050 if(this._cbs.onopentag) this._attribs = {};
116};
117
1181Parser.prototype.onopentagend = function(){
11936041 if(this._attribname !== "") this.onattribvalue("");
12036045 if(this._attribs){
12172098 if(this._cbs.onopentag) this._cbs.onopentag(this._tagname, this._attribs);
12236053 this._attribs = null;
123 }
12436061 if(!this._options.xmlMode && this._cbs.onclosetag && this._tagname in voidElements){
1250 this._cbs.onclosetag(this._tagname);
126 }
12736073 this._tagname = "";
128};
129
1301Parser.prototype.onclosetag = function(name){
13136089 if(!(this._options.xmlMode || "lowerCaseTags" in this._options) || this._options.lowerCaseTags){
13236093 name = name.toLowerCase();
133 }
13436101 if(this._stack.length && (!(name in voidElements) || this._options.xmlMode)){
13536105 var pos = this._stack.lastIndexOf(name);
13636109 if(pos !== -1){
13736113 if(this._cbs.onclosetag){
13836117 pos = this._stack.length - pos;
13972242 while(pos--) this._cbs.onclosetag(this._stack.pop());
140 }
1410 else this._stack.splice(pos);
1420 } else if(name === "p" && !this._options.xmlMode){
1430 this.onopentagname(name);
1440 this.onselfclosingtag();
145 }
1460 } else if(!this._options.xmlMode && (name === "br" || name === "p")){
1470 this.onopentagname(name);
1480 this.onselfclosingtag();
149 }
150};
151
1521Parser.prototype.onselfclosingtag = function(){
1530 var name = this._tagname;
154
1550 this.onopentagend();
156
157 //self-closing tags will be on the top of the stack
158 //(cheaper check than in onclosetag)
1590 if(this._stack[this._stack.length-1] === name){
1600 if(this._cbs.onclosetag){
1610 this._cbs.onclosetag(name);
162 }
1630 this._stack.pop();
164 }
165};
166
1671Parser.prototype.onattribname = function(name){
16835790 if(this._attribname !== "") this.onattribvalue("");
16935794 if(!(this._options.xmlMode || "lowerCaseAttributeNames" in this._options) || this._options.lowerCaseAttributeNames){
17035798 name = name.toLowerCase();
171 }
17235806 this._attribname = name;
173};
174
1751Parser.prototype.onattribvalue = function attribValue(value){
17635822 if(this._cbs.onattribute) this._cbs.onattribute(this._attribname, value);
17771652 if(this._attribs) this._attribs[this._attribname] = value;
17835830 this._attribname = "";
179};
180
1811Parser.prototype.ondeclaration = function(value){
1821 if(this._cbs.onprocessinginstruction){
1831 var name = value.split(/\s|\//, 1)[0];
1841 if(!(this._options.xmlMode || "lowerCaseTags" in this._options) || this._options.lowerCaseTags){
1851 name = name.toLowerCase();
186 }
1871 this._cbs.onprocessinginstruction("!" + name, "!" + value);
188 }
189};
190
1911Parser.prototype.onprocessinginstruction = function(value){
1920 if(this._cbs.onprocessinginstruction){
1930 var name = value.split(/\s|\//, 1)[0];
1940 if(!(this._options.xmlMode || "lowerCaseTags" in this._options) || this._options.lowerCaseTags){
1950 name = name.toLowerCase();
196 }
1970 this._cbs.onprocessinginstruction("?" + name, "?" + value);
198 }
199};
200
2011Parser.prototype.oncomment = function(value){
2022 if(this._cbs.oncomment) this._cbs.oncomment(value);
2032 if(this._cbs.oncommentend) this._cbs.oncommentend();
204};
205
2061Parser.prototype.oncdata = function(value){
2070 if(this._options.xmlMode){
2080 if(this._cbs.oncdatastart) this._cbs.oncdatastart();
2090 if(this._cbs.ontext) this._cbs.ontext(value);
2100 if(this._cbs.oncdataend) this._cbs.oncdataend();
211 } else {
2120 this.oncomment("[CDATA[" + value + "]]");
213 }
214};
215
2161Parser.prototype.onerror = function(err){
2170 if(this._cbs.onerror) this._cbs.onerror(err);
218};
219
2201Parser.prototype.onend = function(){
2218871 if(this._cbs.onclosetag){
2228872 for(
223 var i = this._stack.length;
224 i > 0;
225 this._cbs.onclosetag(this._stack[--i])
226 );
227 }
22817756 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
2331Parser.prototype.reset = function(){
2340 if(this._cbs.onreset) this._cbs.onreset();
2350 this._tokenizer.reset();
236
2370 this._tagname = "";
2380 this._attribname = "";
2390 this._attribs = null;
2400 this._stack = [];
2410 this._done = false;
242};
243
244//Parses a complete HTML document and pushes it to the handler
2451Parser.prototype.parseComplete = function(data){
2460 this.reset();
2470 this.end(data);
248};
249
2501Parser.prototype.write = function(chunk){
2518901 if(this._done) this.onerror(Error(".write() after done!"));
2528902 this._tokenizer.write(chunk);
253};
254
2551Parser.prototype.end = function(chunk){
2568906 if(this._done) this.onerror(Error(".end() after done!"));
2578907 this._tokenizer.end(chunk);
2588908 this._done = true;
259};
260
261//alias for backwards compat
2621Parser.prototype.parseChunk = Parser.prototype.write;
2631Parser.prototype.done = Parser.prototype.end;
264
2651module.exports = Parser;
266

c:/noboxout/js-object-enhancements/node_modules/ass/node_modules/cheerio/node_modules/htmlparser2/lib/Tokenizer.js

64.1%
340
218
122
LineHitsSource
11module.exports = Tokenizer;
2
31var 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
701function whitespace(c){
71368945 return c === " " || c === "\t" || c === "\r" || c === "\n";
72}
73
741function Tokenizer(options, cbs){
758993 this._state = TEXT;
768994 this._buffer = "";
778995 this._sectionStart = 0;
788996 this._index = 0;
798997 this._options = options;
808998 this._special = 0; // 1 for script, 2 for style
818999 this._cbs = cbs;
829000 this._running = true;
83}
84
85//TODO make events conditional
861Tokenizer.prototype.write = function(chunk){
879005 this._buffer += chunk;
88
899007 while(this._index < this._buffer.length && this._running){
90901553 var c = this._buffer.charAt(this._index);
91901647 if(this._state === TEXT){
92107350 if(c === "<"){
9374051 this._emitIfToken("ontext");
9474059 this._state = BEFORE_TAG_NAME;
9574067 this._sectionStart = this._index;
96 }
97794821 } else if(this._state === BEFORE_TAG_NAME){
9874091 if(c === "/"){
9937048 this._state = BEFORE_CLOSING_TAG_NAME;
10037055 } else if(c === ">" || this._special > 0) {
1011 this._state = TEXT;
102 } else {
10337066 if(whitespace(c));
10437070 else if(c === "!"){
1052 this._state = BEFORE_DECLARATION;
1062 this._sectionStart = this._index + 1;
10737080 } else if(c === "?"){
1080 this._state = IN_PROCESSING_INSTRUCTION;
1090 this._sectionStart = this._index + 1;
11037092 } else if(
111 !(this._options && this._options.xmlMode) &&
112 (c === "s" || c === "S")
113 ){
114191 this._state = BEFORE_SPECIAL;
115191 this._sectionStart = this._index;
116 } else {
11736929 this._state = IN_TAG_NAME;
11836933 this._sectionStart = this._index;
119 }
120 }
121722610 } else if(this._state === IN_TAG_NAME){
12275569 if(c === "/"){
1230 this._emitToken("onopentagname");
1240 this._cbs.onselfclosingtag();
1250 this._state = AFTER_CLOSING_TAG_NAME;
12675601 } else if(c === ">"){
127455 this._emitToken("onopentagname");
128455 this._cbs.onopentagend();
129455 this._state = TEXT;
130455 this._sectionStart = this._index + 1;
13175186 } else if(whitespace(c)){
13236725 this._emitToken("onopentagname");
13336729 this._state = BEFORE_ATTRIBUTE_NAME;
134 }
135648029 } else if(this._state === BEFORE_CLOSING_TAG_NAME){
13637196 if(whitespace(c));
13737200 else if(c === ">"){
1380 this._state = TEXT;
13937208 } else if(this._special > 0){
1402 if(c === "s" || c === "S"){
1412 this._state = BEFORE_SPECIAL_END;
142 } else {
1430 this._state = TEXT;
1440 continue;
145 }
146 } else {
14737238 this._state = IN_CLOSING_TAG_NAME;
14837242 this._sectionStart = this._index;
149 }
150611827 } else if(this._state === IN_CLOSING_TAG_NAME){
15175801 if(c === ">"){
15237260 this._emitToken("onclosetag");
15337264 this._state = TEXT;
15437268 this._sectionStart = this._index + 1;
15537272 this._special = 0;
15638565 } else if(whitespace(c)){
1570 this._emitToken("onclosetag");
1580 this._state = AFTER_CLOSING_TAG_NAME;
1590 this._special = 0;
160 }
161536672 } else if(this._state === AFTER_CLOSING_TAG_NAME){
162 //skip everything until ">"
1630 if(c === ">"){
1640 this._state = TEXT;
1650 this._sectionStart = this._index + 1;
166 }
167 }
168
169 /*
170 * attributes
171 */
172537310 else if(this._state === BEFORE_ATTRIBUTE_NAME){
17373780 if(c === ">"){
17436893 this._state = TEXT;
17536897 this._cbs.onopentagend();
17636901 this._sectionStart = this._index + 1;
17736907 } else if(c === "/"){
1780 this._cbs.onselfclosingtag();
1790 this._state = AFTER_CLOSING_TAG_NAME;
18036919 } else if(!whitespace(c)){
18136922 this._state = IN_ATTRIBUTE_NAME;
18236926 this._sectionStart = this._index;
183 }
184464138 } else if(this._state === IN_ATTRIBUTE_NAME){
185184419 if(c === "="){
18636942 this._emitIfToken("onattribname");
18736946 this._state = BEFORE_ATTRIBUTE_VALUE;
188147529 } else if(whitespace(c)){
1890 this._emitIfToken("onattribname");
1900 this._state = AFTER_ATTRIBUTE_NAME;
191147577 } else if(c === "/" || c === ">"){
1920 this._emitIfToken("onattribname");
1930 this._state = BEFORE_ATTRIBUTE_NAME;
1940 continue;
195 }
196280099 } else if(this._state === AFTER_ATTRIBUTE_NAME){
1970 if(c === "="){
1980 this._state = BEFORE_ATTRIBUTE_VALUE;
1990 } else if(c === "/" || c === ">"){
2000 this._state = BEFORE_ATTRIBUTE_NAME;
2010 continue;
2020 } else if(!whitespace(c)){
2030 this._state = IN_ATTRIBUTE_NAME;
2040 this._sectionStart = this._index;
205 }
206280399 } else if(this._state === BEFORE_ATTRIBUTE_VALUE){
20737026 if(c === "\""){
20837030 this._state = IN_ATTRIBUTE_VALUE_DOUBLE_QUOTES;
20937034 this._sectionStart = this._index + 1;
2100 } else if(c === "'"){
2110 this._state = IN_ATTRIBUTE_VALUE_SINGLE_QUOTES;
2120 this._sectionStart = this._index + 1;
2130 } else if(!whitespace(c)){
2140 this._state = IN_ATTRIBUTE_VALUE_NO_QUOTES;
2150 this._sectionStart = this._index;
216 }
217243663 } else if(this._state === IN_ATTRIBUTE_VALUE_DOUBLE_QUOTES){
218242116 if(c === "\""){
21937074 this._emitToken("onattribvalue");
22037078 this._state = BEFORE_ATTRIBUTE_NAME;
221 }
2221573 } else if(this._state === IN_ATTRIBUTE_VALUE_SINGLE_QUOTES){
2230 if(c === "'"){
2240 this._state = BEFORE_ATTRIBUTE_NAME;
2250 this._emitToken("onattribvalue");
226 }
2271573 } else if(this._state === IN_ATTRIBUTE_VALUE_NO_QUOTES){
2280 if(c === ">"){
2290 this._emitToken("onattribvalue");
2300 this._state = TEXT;
2310 this._cbs.onopentagend();
2320 this._sectionStart = this._index + 1;
2330 } else if(whitespace(c)){
2340 this._emitToken("onattribvalue");
2350 this._state = BEFORE_ATTRIBUTE_NAME;
236 }
237 }
238
239 /*
240 * declarations
241 */
2421573 else if(this._state === BEFORE_DECLARATION){
2432 if(c === "[") this._state = BEFORE_CDATA_1;
2443 else if(c === "-") this._state = BEFORE_COMMENT;
2451 else this._state = IN_DECLARATION;
2461571 } else if(this._state === IN_DECLARATION){
24712 if(c === ">"){
2481 this._emitToken("ondeclaration");
2491 this._state = TEXT;
2501 this._sectionStart = this._index + 1;
251 }
252 }
253
254 /*
255 * processing instructions
256 */
2571559 else if(this._state === IN_PROCESSING_INSTRUCTION){
2580 if(c === ">"){
2590 this._emitToken("onprocessinginstruction");
2600 this._state = TEXT;
2610 this._sectionStart = this._index + 1;
262 }
263 }
264
265 /*
266 * comments
267 */
2681559 else if(this._state === BEFORE_COMMENT){
2691 if(c === "-"){
2701 this._state = IN_COMMENT;
2711 this._sectionStart = this._index + 1;
272 } else {
2730 this._state = IN_DECLARATION;
274 }
2751558 } else if(this._state === IN_COMMENT){
2761346 if(c === "-") this._state = AFTER_COMMENT_1;
277215 } else if(this._state === AFTER_COMMENT_1){
2784 if(c === "-") this._state = AFTER_COMMENT_2;
2792 else this._state = IN_COMMENT;
280212 } else if(this._state === AFTER_COMMENT_2){
2811 if(c === ">"){
282 //remove 2 trailing chars
2831 this._cbs.oncomment(this._buffer.substring(this._sectionStart, this._index - 2));
2841 this._state = TEXT;
2851 this._sectionStart = this._index + 1;
2860 } else if (c !== "-") {
2870 this._state = IN_COMMENT;
288 }
289 // else: stay in AFTER_COMMENT_2 (`--->`)
290 }
291
292 /*
293 * cdata
294 */
295211 else if(this._state === BEFORE_CDATA_1){
2960 if(c === "C") this._state = BEFORE_CDATA_2;
2970 else this._state = IN_DECLARATION;
298211 } else if(this._state === BEFORE_CDATA_2){
2990 if(c === "D") this._state = BEFORE_CDATA_3;
3000 else this._state = IN_DECLARATION;
301211 } else if(this._state === BEFORE_CDATA_3){
3020 if(c === "A") this._state = BEFORE_CDATA_4;
3030 else this._state = IN_DECLARATION;
304211 } else if(this._state === BEFORE_CDATA_4){
3050 if(c === "T") this._state = BEFORE_CDATA_5;
3060 else this._state = IN_DECLARATION;
307211 } else if(this._state === BEFORE_CDATA_5){
3080 if(c === "A") this._state = BEFORE_CDATA_6;
3090 else this._state = IN_DECLARATION;
310211 } else if(this._state === BEFORE_CDATA_6){
3110 if(c === "["){
3120 this._state = IN_CDATA;
3130 this._sectionStart = this._index + 1;
314 } else {
3150 this._state = IN_DECLARATION;
316 }
317211 } else if(this._state === IN_CDATA){
3180 if(c === "]") this._state = AFTER_CDATA_1;
319211 } else if(this._state === AFTER_CDATA_1){
3200 if(c === "]") this._state = AFTER_CDATA_2;
3210 else this._state = IN_CDATA;
322211 } else if(this._state === AFTER_CDATA_2){
3230 if(c === ">"){
324 //remove 2 trailing chars
3250 this._cbs.oncdata(this._buffer.substring(this._sectionStart, this._index - 2));
3260 this._state = TEXT;
3270 this._sectionStart = this._index + 1;
3280 } else if (c !== "]") {
3290 this._state = IN_CDATA;
330 }
331 //else: stay in AFTER_CDATA_2 (`]]]>`)
332 }
333
334 /*
335 * special tags
336 */
337211 else if(this._state === BEFORE_SPECIAL){
338191 if(c === "c" || c === "C"){
3391 this._state = BEFORE_SCRIPT_1;
340190 } else if(c === "t" || c === "T"){
3411 this._state = BEFORE_STYLE_1;
342 } else {
343189 this._state = IN_TAG_NAME;
344189 continue; //consume the token again
345 }
34620 } else if(this._state === BEFORE_SPECIAL_END){
3472 if(this._special === 1 && (c === "c" || c === "C")){
3481 this._state = AFTER_SCRIPT_1;
3491 } else if(this._special === 2 && (c === "t" || c === "T")){
3501 this._state = AFTER_STYLE_1;
351 }
3520 else this._state = TEXT;
353 }
354
355 /*
356 * script
357 */
35818 else if(this._state === BEFORE_SCRIPT_1){
3591 if(c === "r" || c === "R"){
3601 this._state = BEFORE_SCRIPT_2;
361 } else {
3620 this._state = IN_TAG_NAME;
3630 continue; //consume the token again
364 }
36517 } else if(this._state === BEFORE_SCRIPT_2){
3661 if(c === "i" || c === "I"){
3671 this._state = BEFORE_SCRIPT_3;
368 } else {
3690 this._state = IN_TAG_NAME;
3700 continue; //consume the token again
371 }
37216 } else if(this._state === BEFORE_SCRIPT_3){
3731 if(c === "p" || c === "P"){
3741 this._state = BEFORE_SCRIPT_4;
375 } else {
3760 this._state = IN_TAG_NAME;
3770 continue; //consume the token again
378 }
37915 } else if(this._state === BEFORE_SCRIPT_4){
3801 if(c === "t" || c === "T"){
3811 this._state = BEFORE_SCRIPT_5;
382 } else {
3830 this._state = IN_TAG_NAME;
3840 continue; //consume the token again
385 }
38614 } else if(this._state === BEFORE_SCRIPT_5){
3871 if(c === "/" || c === ">" || whitespace(c)){
3881 this._special = 1;
389 }
3901 this._state = IN_TAG_NAME;
3911 continue; //consume the token again
392 }
393
39413 else if(this._state === AFTER_SCRIPT_1){
3951 if(c === "r" || c === "R"){
3961 this._state = AFTER_SCRIPT_2;
397 }
3980 else this._state = TEXT;
39912 } else if(this._state === AFTER_SCRIPT_2){
4001 if(c === "i" || c === "I"){
4011 this._state = AFTER_SCRIPT_3;
402 }
4030 else this._state = TEXT;
40411 } else if(this._state === AFTER_SCRIPT_3){
4051 if(c === "p" || c === "P"){
4061 this._state = AFTER_SCRIPT_4;
407 }
4080 else this._state = TEXT;
40910 } else if(this._state === AFTER_SCRIPT_4){
4101 if(c === "t" || c === "T"){
4111 this._state = AFTER_SCRIPT_5;
412 }
4130 else this._state = TEXT;
4149 } else if(this._state === AFTER_SCRIPT_5){
4151 if(c === ">" || whitespace(c)){
4161 this._state = IN_CLOSING_TAG_NAME;
4171 this._sectionStart = this._index - 6;
4181 continue; //reconsume the token
419 }
4200 else this._state = TEXT;
421 }
422
423 /*
424 * style
425 */
4268 else if(this._state === BEFORE_STYLE_1){
4271 if(c === "y" || c === "Y"){
4281 this._state = BEFORE_STYLE_2;
429 } else {
4300 this._state = IN_TAG_NAME;
4310 continue; //consume the token again
432 }
4337 } else if(this._state === BEFORE_STYLE_2){
4341 if(c === "l" || c === "L"){
4351 this._state = BEFORE_STYLE_3;
436 } else {
4370 this._state = IN_TAG_NAME;
4380 continue; //consume the token again
439 }
4406 } else if(this._state === BEFORE_STYLE_3){
4411 if(c === "e" || c === "E"){
4421 this._state = BEFORE_STYLE_4;
443 } else {
4440 this._state = IN_TAG_NAME;
4450 continue; //consume the token again
446 }
4475 } else if(this._state === BEFORE_STYLE_4){
4481 if(c === "/" || c === ">" || whitespace(c)){
4491 this._special = 2;
450 }
4511 this._state = IN_TAG_NAME;
4521 continue; //consume the token again
453 }
454
4554 else if(this._state === AFTER_STYLE_1){
4561 if(c === "y" || c === "Y"){
4571 this._state = AFTER_STYLE_2;
458 }
4590 else this._state = TEXT;
4603 } else if(this._state === AFTER_STYLE_2){
4611 if(c === "l" || c === "L"){
4621 this._state = AFTER_STYLE_3;
463 }
4640 else this._state = TEXT;
4652 } else if(this._state === AFTER_STYLE_3){
4661 if(c === "e" || c === "E"){
4671 this._state = AFTER_STYLE_4;
468 }
4690 else this._state = TEXT;
4701 } else if(this._state === AFTER_STYLE_4){
4711 if(c === ">" || whitespace(c)){
4721 this._state = IN_CLOSING_TAG_NAME;
4731 this._sectionStart = this._index - 5;
4741 continue; //reconsume the token
475 }
4760 else this._state = TEXT;
477 }
478
479
480 else {
4810 this._cbs.onerror(Error("unknown state"), this._state);
482 }
483
484938396 this._index++;
485 }
486
487 //cleanup
4889406 if(this._sectionStart === -1){
4890 this._buffer = "";
4900 this._index = 0;
491 } else {
4929410 if(this._state === TEXT){
4939411 if(this._sectionStart !== this._index){
4941 this._cbs.ontext(this._buffer.substr(this._sectionStart));
495 }
4969414 this._buffer = "";
4979415 this._index = 0;
4980 } else if(this._sectionStart === this._index){
499 //the section just started
5000 this._buffer = "";
5010 this._index = 0;
5020 } else if(this._sectionStart > 0){
503 //remove everything unnecessary
5040 this._buffer = this._buffer.substr(this._sectionStart);
5050 this._index -= this._sectionStart;
506 }
507
5089426 this._sectionStart = 0;
509 }
510};
511
5121Tokenizer.prototype.pause = function(){
5130 this._running = false;
514};
5151Tokenizer.prototype.resume = function(){
5160 this._running = true;
517};
518
5191Tokenizer.prototype.end = function(chunk){
5209438 if(chunk) this.write(chunk);
521
522 //if there is remaining data, emit it in a reasonable way
5239441 if(this._sectionStart > this._index){
5240 var data = this._buffer.substr(this._sectionStart);
525
5260 if(this._state === IN_CDATA || this._state === AFTER_CDATA_1 || this._state === AFTER_CDATA_2){
5270 this._cbs.oncdata(data);
5280 } else if(this._state === IN_COMMENT || this._state === AFTER_COMMENT_1 || this._state === AFTER_COMMENT_2){
5290 this._cbs.oncomment(data);
5300 } else if(this._state === IN_TAG_NAME){
5310 this._cbs.onopentagname(data);
5320 } else if(this._state === IN_CLOSING_TAG_NAME){
5330 this._cbs.onclosetag(data);
534 } else {
5350 this._cbs.ontext(data);
536 }
537 }
538
5399457 this._cbs.onend();
540};
541
5421Tokenizer.prototype.reset = function(){
5430 Tokenizer.call(this, this._options, this._cbs);
544};
545
5461Tokenizer.prototype._emitToken = function(name){
547116067 this._cbs[name](this._buffer.substring(this._sectionStart, this._index));
548116079 this._sectionStart = -1;
549};
550
5511Tokenizer.prototype._emitIfToken = function(name){
552116129 if(this._index > this._sectionStart){
55339847 this._cbs[name](this._buffer.substring(this._sectionStart, this._index));
554 }
555116165 this._sectionStart = -1;
556};
557