dot.dot.dot.exampol

This commit is contained in:
Captain Nick Lucifer* 2023-03-10 23:21:16 +05:45
commit a0bc2d79de
406 changed files with 34577 additions and 0 deletions

1
node_modules/burrito/.npmignore generated vendored Normal file
View file

@ -0,0 +1 @@
node_modules

4
node_modules/burrito/.travis.yml generated vendored Normal file
View file

@ -0,0 +1,4 @@
language: node_js
node_js:
- 0.4
- 0.6

187
node_modules/burrito/README.markdown generated vendored Normal file
View file

@ -0,0 +1,187 @@
burrito
=======
Burrito makes it easy to do crazy stuff with the javascript AST.
This is super useful if you want to roll your own stack traces or build a code
coverage tool.
[![build status](https://secure.travis-ci.org/substack/node-burrito.png)](http://travis-ci.org/substack/node-burrito)
![node.wrap("burrito")](http://substack.net/images/burrito.png)
examples
========
microwave
---------
examples/microwave.js
````javascript
var burrito = require('burrito');
var res = burrito.microwave('Math.sin(2)', function (node) {
if (node.name === 'num') node.wrap('Math.PI / %s');
});
console.log(res); // sin(pi / 2) == 1
````
output:
1
wrap
----
examples/wrap.js
````javascript
var burrito = require('burrito');
var src = burrito('f() && g(h())\nfoo()', function (node) {
if (node.name === 'call') node.wrap('qqq(%s)');
});
console.log(src);
````
output:
qqq(f()) && qqq(g(qqq(h())));
qqq(foo());
methods
=======
var burrito = require('burrito');
burrito(code, cb)
-----------------
Given some source `code` and a function `trace`, walk the ast by expression.
The `cb` gets called with a node object described below.
If `code` is an Array then it is assumbed to be an AST which you can generate
yourself with `burrito.parse()`. The AST must be annotated, so make sure to
`burrito.parse(src, false, true)`.
burrito.microwave(code, context={}, cb)
---------------------------------------
Like `burrito()` except the result is run using
`vm.runInNewContext(res, context)`.
node object
===========
node.name
---------
Name is a string that contains the type of the expression as named by uglify.
node.wrap(s)
------------
Wrap the current expression in `s`.
If `s` is a string, `"%s"` will be replaced with the stringified current
expression.
If `s` is a function, it is called with the stringified current expression and
should return a new stringified expression.
If the `node.name === "binary"`, you get the subterms "%a" and "%b" to play with
too. These subterms are applied if `s` is a function too: `s(expr, a, b)`.
Protip: to insert multiple statements you can use javascript's lesser-known block
syntax that it gets from C:
````javascript
if (node.name === 'stat') node.wrap('{ foo(); %s }')
````
node.node
---------
raw ast data generated by uglify
node.value
----------
`node.node.slice(1)` to skip the annotations
node.start
----------
The start location of the expression, like this:
````javascript
{ type: 'name',
value: 'b',
line: 0,
col: 3,
pos: 3,
nlb: false,
comments_before: [] }
````
node.end
--------
The end location of the expression, formatted the same as `node.start`.
node.state
----------
The state of the traversal using traverse.
node.source()
-------------
Returns a stringified version of the expression.
node.parent()
-------------
Returns the parent `node` or `null` if the node is the root element.
node.label()
------------
Return the label of the present node or `null` if there is no label.
Labels are returned for "call", "var", "defun", and "function" nodes.
Returns an array for "var" nodes since `var` statements can
contain multiple labels in assignment.
install
=======
With [npm](http://npmjs.org) you can just:
npm install burrito
in the browser
==============
Burrito works in browser with
[browserify](https://github.com/substack/node-browserify).
It has been tested against:
* Internet Explorer 5.5, 6.0, 7.0, 8.0, 9.0
* Firefox 3.5
* Chrome 6.0
* Opera 10.6
* Safari 5.0
kudos
=====
Heavily inspired by (and previously mostly lifted outright from) isaacs's nifty
tmp/instrument.js thingy from uglify-js.

8
node_modules/burrito/example/microwave.js generated vendored Normal file
View file

@ -0,0 +1,8 @@
var burrito = require('burrito');
var res = burrito.microwave('Math.sin(2)', function (node) {
console.dir(node);
if (node.name === 'num') node.wrap('Math.PI / %s');
});
console.log(res); // sin(pi / 2) == 1

4832
node_modules/burrito/example/web/bs.js generated vendored Normal file

File diff suppressed because it is too large Load diff

14
node_modules/burrito/example/web/index.html generated vendored Normal file
View file

@ -0,0 +1,14 @@
<html>
<head>
<script type="text/javascript" src="/browserify.js"></script>
<style type="text/css">
pre {
white-space: pre;
word-wrap: break-word;
}
</style>
</head>
<body>
<pre id="output"></pre>
</body>
</html>

17
node_modules/burrito/example/web/main.js generated vendored Normal file
View file

@ -0,0 +1,17 @@
var burrito = require('burrito');
var json = require('jsonify');
var src = [
'function f () { g() }',
'function g () { h() }',
'function h () { throw "moo" + Array(x).join("!") }',
'var x = 4',
'f()'
].join('\r\n');
window.onload = function () {
burrito(src, function (node) {
document.body.innerHTML += node.name + '<br>\n';
});
};
if (document.readyState === 'complete') window.onload();

12
node_modules/burrito/example/web/server.js generated vendored Normal file
View file

@ -0,0 +1,12 @@
var express = require('express');
var browserify = require('browserify');
var app = express.createServer();
app.use(express.static(__dirname));
app.use(browserify({
entry : __dirname + '/main.js',
watch : true,
}));
app.listen(8081);
console.log('Listening on :8081');

7
node_modules/burrito/example/wrap.js generated vendored Normal file
View file

@ -0,0 +1,7 @@
var burrito = require('burrito');
var src = burrito('f() && g(h())\nfoo()', function (node) {
if (node.name === 'call') node.wrap('qqq(%s)');
});
console.log(src);

208
node_modules/burrito/index.js generated vendored Normal file
View file

@ -0,0 +1,208 @@
var uglify = require('uglify-js');
var parser = uglify.parser;
var parse = function (expr) {
if (typeof expr !== 'string') throw 'expression should be a string';
try {
var ast = parser.parse.apply(null, arguments);
}
catch (err) {
if (err.message === undefined
|| err.line === undefined
|| err.col === undefined
|| err.pos === undefined
) { throw err }
var e = new SyntaxError(
err.message
+ '\n at line ' + err.line + ':' + err.col + ' in expression:\n\n'
+ ' ' + expr.split(/\r?\n/)[err.line]
);
e.original = err;
e.line = err.line;
e.col = err.col;
e.pos = err.pos;
throw e;
}
return ast;
};
var deparse = function (ast, b) {
return uglify.uglify.gen_code(ast, { beautify : b });
};
var traverse = require('traverse');
var vm = require('vm');
var burrito = module.exports = function (code, cb) {
var ast = Array_isArray(code)
? code // already an ast
: parse(code.toString(), false, true)
;
var ast_ = traverse(ast).map(function mapper () {
wrapNode(this, cb);
});
return deparse(parse(deparse(ast_)), true);
};
var wrapNode = burrito.wrapNode = function (state, cb) {
var node = state.node;
var ann = Array_isArray(node) && node[0]
&& typeof node[0] === 'object' && node[0].name
? node[0]
: null
;
if (!ann) return undefined;
var self = {
name : ann.name,
node : node,
start : node[0].start,
end : node[0].end,
value : node.slice(1),
state : state
};
self.wrap = function (s) {
var subsrc = deparse(
traverse(node).map(function (x) {
if (!this.isRoot) wrapNode(this, cb)
})
);
if (self.name === 'binary') {
var a = deparse(traverse(node[2]).map(function (x) {
if (!this.isRoot) wrapNode(this, cb)
}));
var b = deparse(traverse(node[3]).map(function (x) {
if (!this.isRoot) wrapNode(this, cb)
}));
}
var src = '';
if (typeof s === 'function') {
if (self.name === 'binary') {
src = s(subsrc, a, b);
}
else {
src = s(subsrc);
}
}
else {
src = s.toString()
.replace(/%s/g, function () {
return subsrc
})
;
if (self.name === 'binary') {
src = src
.replace(/%a/g, function () { return a })
.replace(/%b/g, function () { return b })
;
}
}
var expr = parse(src);
state.update(expr, true);
};
var cache = {};
self.parent = state.isRoot ? null : function () {
if (!cache.parent) {
var s = state;
var x;
do {
s = s.parent;
if (s) x = wrapNode(s);
} while (s && !x);
cache.parent = x;
}
return cache.parent;
};
self.source = function () {
if (!cache.source) cache.source = deparse(node);
return cache.source;
};
self.label = function () {
return burrito.label(self);
};
if (cb) cb.call(state, self);
if (self.node[0].name === 'conditional') {
self.wrap('[%s][0]');
}
return self;
}
burrito.microwave = function (code, context, cb) {
if (!cb) { cb = context; context = {} };
if (!context) context = {};
var src = burrito(code, cb);
return vm.runInNewContext(src, context);
};
burrito.generateName = function (len) {
var name = '';
var lower = '$'.charCodeAt(0);
var upper = 'z'.charCodeAt(0);
while (name.length < len) {
var c = String.fromCharCode(Math.floor(
Math.random() * (upper - lower + 1) + lower
));
if ((name + c).match(/^[A-Za-z_$][A-Za-z0-9_$]*$/)) name += c;
}
return name;
};
burrito.parse = parse;
burrito.deparse = deparse;
burrito.label = function (node) {
if (node.name === 'call') {
if (typeof node.value[0] === 'string') {
return node.value[0];
}
else if (node.value[0] && typeof node.value[0][1] === 'string') {
return node.value[0][1];
}
else if (node.value[0][0] === 'dot') {
return node.value[0][node.value[0].length - 1];
}
else {
return null;
}
}
else if (node.name === 'var') {
return node.value[0].map(function (x) { return x[0] });
}
else if (node.name === 'defun') {
return node.value[0];
}
else if (node.name === 'function') {
return node.value[0];
}
else {
return null;
}
};
var Array_isArray = Array.isArray || function isArray (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};

View file

@ -0,0 +1 @@
node_modules

24
node_modules/burrito/node_modules/traverse/LICENSE generated vendored Normal file
View file

@ -0,0 +1,24 @@
Copyright 2010 James Halliday (mail@substack.net)
This project is free software released under the MIT/X11 license:
http://www.opensource.org/licenses/mit-license.php
Copyright 2010 James Halliday (mail@substack.net)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -0,0 +1,237 @@
traverse
========
Traverse and transform objects by visiting every node on a recursive walk.
examples
========
transform negative numbers in-place
-----------------------------------
negative.js
````javascript
var traverse = require('traverse');
var obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ];
traverse(obj).forEach(function (x) {
if (x < 0) this.update(x + 128);
});
console.dir(obj);
````
Output:
[ 5, 6, 125, [ 7, 8, 126, 1 ], { f: 10, g: 115 } ]
collect leaf nodes
------------------
leaves.js
````javascript
var traverse = require('traverse');
var obj = {
a : [1,2,3],
b : 4,
c : [5,6],
d : { e : [7,8], f : 9 },
};
var leaves = traverse(obj).reduce(function (acc, x) {
if (this.isLeaf) acc.push(x);
return acc;
}, []);
console.dir(leaves);
````
Output:
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
scrub circular references
-------------------------
scrub.js:
````javascript
var traverse = require('traverse');
var obj = { a : 1, b : 2, c : [ 3, 4 ] };
obj.c.push(obj);
var scrubbed = traverse(obj).map(function (x) {
if (this.circular) this.remove()
});
console.dir(scrubbed);
````
output:
{ a: 1, b: 2, c: [ 3, 4 ] }
context
=======
Each method that takes a callback has a context (its `this` object) with these
attributes:
this.node
---------
The present node on the recursive walk
this.path
---------
An array of string keys from the root to the present node
this.parent
-----------
The context of the node's parent.
This is `undefined` for the root node.
this.key
--------
The name of the key of the present node in its parent.
This is `undefined` for the root node.
this.isRoot, this.notRoot
-------------------------
Whether the present node is the root node
this.isLeaf, this.notLeaf
-------------------------
Whether or not the present node is a leaf node (has no children)
this.level
----------
Depth of the node within the traversal
this.circular
-------------
If the node equals one of its parents, the `circular` attribute is set to the
context of that parent and the traversal progresses no deeper.
this.update(value, stopHere=false)
----------------------------------
Set a new value for the present node.
All the elements in `value` will be recursively traversed unless `stopHere` is
true.
this.remove(stopHere=false)
-------------
Remove the current element from the output. If the node is in an Array it will
be spliced off. Otherwise it will be deleted from its parent.
this.delete(stopHere=false)
-------------
Delete the current element from its parent in the output. Calls `delete` even on
Arrays.
this.before(fn)
---------------
Call this function before any of the children are traversed.
You can assign into `this.keys` here to traverse in a custom order.
this.after(fn)
--------------
Call this function after any of the children are traversed.
this.pre(fn)
------------
Call this function before each of the children are traversed.
this.post(fn)
-------------
Call this function after each of the children are traversed.
methods
=======
.map(fn)
--------
Execute `fn` for each node in the object and return a new object with the
results of the walk. To update nodes in the result use `this.update(value)`.
.forEach(fn)
------------
Execute `fn` for each node in the object but unlike `.map()`, when
`this.update()` is called it updates the object in-place.
.reduce(fn, acc)
----------------
For each node in the object, perform a
[left-fold](http://en.wikipedia.org/wiki/Fold_(higher-order_function))
with the return value of `fn(acc, node)`.
If `acc` isn't specified, `acc` is set to the root object for the first step
and the root element is skipped.
.paths()
--------
Return an `Array` of every possible non-cyclic path in the object.
Paths are `Array`s of string keys.
.nodes()
--------
Return an `Array` of every node in the object.
.clone()
--------
Create a deep clone of the object.
install
=======
Using [npm](http://npmjs.org) do:
$ npm install traverse
test
====
Using [expresso](http://github.com/visionmedia/expresso) do:
$ expresso
100% wahoo, your stuff is not broken!
in the browser
==============
Use [browserify](https://github.com/substack/node-browserify) to run traverse in
the browser.
traverse has been tested and works with:
* Internet Explorer 5.5, 6.0, 7.0, 8.0, 9.0
* Firefox 3.5
* Chrome 6.0
* Opera 10.6
* Safari 5.0

16
node_modules/burrito/node_modules/traverse/examples/json.js generated vendored Executable file
View file

@ -0,0 +1,16 @@
var traverse = require('traverse');
var id = 54;
var callbacks = {};
var obj = { moo : function () {}, foo : [2,3,4, function () {}] };
var scrubbed = traverse(obj).map(function (x) {
if (typeof x === 'function') {
callbacks[id] = { id : id, f : x, path : this.path };
this.update('[Function]');
id++;
}
});
console.dir(scrubbed);
console.dir(callbacks);

View file

@ -0,0 +1,15 @@
var traverse = require('traverse');
var obj = {
a : [1,2,3],
b : 4,
c : [5,6],
d : { e : [7,8], f : 9 },
};
var leaves = traverse(obj).reduce(function (acc, x) {
if (this.isLeaf) acc.push(x);
return acc;
}, []);
console.dir(leaves);

View file

@ -0,0 +1,8 @@
var traverse = require('traverse');
var obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ];
traverse(obj).forEach(function (x) {
if (x < 0) this.update(x + 128);
});
console.dir(obj);

10
node_modules/burrito/node_modules/traverse/examples/scrub.js generated vendored Executable file
View file

@ -0,0 +1,10 @@
// scrub out circular references
var traverse = require('traverse');
var obj = { a : 1, b : 2, c : [ 3, 4 ] };
obj.c.push(obj);
var scrubbed = traverse(obj).map(function (x) {
if (this.circular) this.remove()
});
console.dir(scrubbed);

View file

@ -0,0 +1,38 @@
#!/usr/bin/env node
var traverse = require('traverse');
var obj = [ 'five', 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ];
var s = '';
traverse(obj).forEach(function to_s (node) {
if (Array.isArray(node)) {
this.before(function () { s += '[' });
this.post(function (child) {
if (!child.isLast) s += ',';
});
this.after(function () { s += ']' });
}
else if (typeof node == 'object') {
this.before(function () { s += '{' });
this.pre(function (x, key) {
to_s(key);
s += ':';
});
this.post(function (child) {
if (!child.isLast) s += ',';
});
this.after(function () { s += '}' });
}
else if (typeof node == 'string') {
s += '"' + node.toString().replace(/"/g, '\\"') + '"';
}
else if (typeof node == 'function') {
s += 'null';
}
else {
s += node.toString();
}
});
console.log('JSON.stringify: ' + JSON.stringify(obj));
console.log('this stringify: ' + s);

267
node_modules/burrito/node_modules/traverse/index.js generated vendored Normal file
View file

@ -0,0 +1,267 @@
module.exports = Traverse;
function Traverse (obj) {
if (!(this instanceof Traverse)) return new Traverse(obj);
this.value = obj;
}
Traverse.prototype.get = function (ps) {
var node = this.value;
for (var i = 0; i < ps.length; i ++) {
var key = ps[i];
if (!Object.hasOwnProperty.call(node, key)) {
node = undefined;
break;
}
node = node[key];
}
return node;
};
Traverse.prototype.set = function (ps, value) {
var node = this.value;
for (var i = 0; i < ps.length - 1; i ++) {
var key = ps[i];
if (!Object.hasOwnProperty.call(node, key)) node[key] = {};
node = node[key];
}
node[ps[i]] = value;
return value;
};
Traverse.prototype.map = function (cb) {
return walk(this.value, cb, true);
};
Traverse.prototype.forEach = function (cb) {
this.value = walk(this.value, cb, false);
return this.value;
};
Traverse.prototype.reduce = function (cb, init) {
var skip = arguments.length === 1;
var acc = skip ? this.value : init;
this.forEach(function (x) {
if (!this.isRoot || !skip) {
acc = cb.call(this, acc, x);
}
});
return acc;
};
Traverse.prototype.paths = function () {
var acc = [];
this.forEach(function (x) {
acc.push(this.path);
});
return acc;
};
Traverse.prototype.nodes = function () {
var acc = [];
this.forEach(function (x) {
acc.push(this.node);
});
return acc;
};
Traverse.prototype.clone = function () {
var parents = [], nodes = [];
return (function clone (src) {
for (var i = 0; i < parents.length; i++) {
if (parents[i] === src) {
return nodes[i];
}
}
if (typeof src === 'object' && src !== null) {
var dst = copy(src);
parents.push(src);
nodes.push(dst);
forEach(Object_keys(src), function (key) {
dst[key] = clone(src[key]);
});
parents.pop();
nodes.pop();
return dst;
}
else {
return src;
}
})(this.value);
};
function walk (root, cb, immutable) {
var path = [];
var parents = [];
var alive = true;
return (function walker (node_) {
var node = immutable ? copy(node_) : node_;
var modifiers = {};
var keepGoing = true;
var state = {
node : node,
node_ : node_,
path : [].concat(path),
parent : parents[parents.length - 1],
parents : parents,
key : path.slice(-1)[0],
isRoot : path.length === 0,
level : path.length,
circular : null,
update : function (x, stopHere) {
if (!state.isRoot) {
state.parent.node[state.key] = x;
}
state.node = x;
if (stopHere) keepGoing = false;
},
'delete' : function (stopHere) {
delete state.parent.node[state.key];
if (stopHere) keepGoing = false;
},
remove : function (stopHere) {
if (Array_isArray(state.parent.node)) {
state.parent.node.splice(state.key, 1);
}
else {
delete state.parent.node[state.key];
}
if (stopHere) keepGoing = false;
},
keys : null,
before : function (f) { modifiers.before = f },
after : function (f) { modifiers.after = f },
pre : function (f) { modifiers.pre = f },
post : function (f) { modifiers.post = f },
stop : function () { alive = false },
block : function () { keepGoing = false }
};
if (!alive) return state;
if (typeof node === 'object' && node !== null) {
state.keys = Object_keys(node);
state.isLeaf = state.keys.length == 0;
for (var i = 0; i < parents.length; i++) {
if (parents[i].node_ === node_) {
state.circular = parents[i];
break;
}
}
}
else {
state.isLeaf = true;
}
state.notLeaf = !state.isLeaf;
state.notRoot = !state.isRoot;
// use return values to update if defined
var ret = cb.call(state, state.node);
if (ret !== undefined && state.update) state.update(ret);
if (modifiers.before) modifiers.before.call(state, state.node);
if (!keepGoing) return state;
if (typeof state.node == 'object'
&& state.node !== null && !state.circular) {
parents.push(state);
forEach(state.keys, function (key, i) {
path.push(key);
if (modifiers.pre) modifiers.pre.call(state, state.node[key], key);
var child = walker(state.node[key]);
if (immutable && Object.hasOwnProperty.call(state.node, key)) {
state.node[key] = child.node;
}
child.isLast = i == state.keys.length - 1;
child.isFirst = i == 0;
if (modifiers.post) modifiers.post.call(state, child);
path.pop();
});
parents.pop();
}
if (modifiers.after) modifiers.after.call(state, state.node);
return state;
})(root).node;
}
function copy (src) {
if (typeof src === 'object' && src !== null) {
var dst;
if (Array_isArray(src)) {
dst = [];
}
else if (src instanceof Date) {
dst = new Date(src);
}
else if (src instanceof Boolean) {
dst = new Boolean(src);
}
else if (src instanceof Number) {
dst = new Number(src);
}
else if (src instanceof String) {
dst = new String(src);
}
else if (Object.create && Object.getPrototypeOf) {
dst = Object.create(Object.getPrototypeOf(src));
}
else if (src.__proto__ || src.constructor.prototype) {
var proto = src.__proto__ || src.constructor.prototype || {};
var T = function () {};
T.prototype = proto;
dst = new T;
if (!dst.__proto__) dst.__proto__ = proto;
}
forEach(Object_keys(src), function (key) {
dst[key] = src[key];
});
return dst;
}
else return src;
}
var Object_keys = Object.keys || function keys (obj) {
var res = [];
for (var key in obj) res.push(key)
return res;
};
var Array_isArray = Array.isArray || function isArray (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
var forEach = function (xs, fn) {
if (xs.forEach) return xs.forEach(fn)
else for (var i = 0; i < xs.length; i++) {
fn(xs[i], i, xs);
}
};
forEach(Object_keys(Traverse.prototype), function (key) {
Traverse[key] = function (obj) {
var args = [].slice.call(arguments, 1);
var t = Traverse(obj);
return t[key].apply(t, args);
};
});

10
node_modules/burrito/node_modules/traverse/main.js generated vendored Executable file
View file

@ -0,0 +1,10 @@
// scrub out circular references
var traverse = require('./index.js');
var obj = { a : 1, b : 2, c : [ 3, 4 ] };
obj.c.push(obj);
var scrubbed = traverse(obj).map(function (x) {
if (this.circular) this.remove()
});
console.dir(scrubbed);

View file

@ -0,0 +1,18 @@
{
"name" : "traverse",
"version" : "0.5.2",
"description" : "Traverse and transform objects by visiting every node on a recursive walk",
"author" : "James Halliday",
"license" : "MIT/X11",
"main" : "./index",
"repository" : {
"type" : "git",
"url" : "http://github.com/substack/js-traverse.git"
},
"devDependencies" : {
"expresso" : "0.7.x"
},
"scripts" : {
"test" : "expresso"
}
}

View file

@ -0,0 +1,115 @@
var assert = require('assert');
var Traverse = require('../');
var deepEqual = require('./lib/deep_equal');
var util = require('util');
exports.circular = function () {
var obj = { x : 3 };
obj.y = obj;
var foundY = false;
Traverse(obj).forEach(function (x) {
if (this.path.join('') == 'y') {
assert.equal(
util.inspect(this.circular.node),
util.inspect(obj)
);
foundY = true;
}
});
assert.ok(foundY);
};
exports.deepCirc = function () {
var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] };
obj.y[2] = obj;
var times = 0;
Traverse(obj).forEach(function (x) {
if (this.circular) {
assert.deepEqual(this.circular.path, []);
assert.deepEqual(this.path, [ 'y', 2 ]);
times ++;
}
});
assert.deepEqual(times, 1);
};
exports.doubleCirc = function () {
var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] };
obj.y[2] = obj;
obj.x.push(obj.y);
var circs = [];
Traverse(obj).forEach(function (x) {
if (this.circular) {
circs.push({ circ : this.circular, self : this, node : x });
}
});
assert.deepEqual(circs[0].self.path, [ 'x', 3, 2 ]);
assert.deepEqual(circs[0].circ.path, []);
assert.deepEqual(circs[1].self.path, [ 'y', 2 ]);
assert.deepEqual(circs[1].circ.path, []);
assert.deepEqual(circs.length, 2);
};
exports.circDubForEach = function () {
var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] };
obj.y[2] = obj;
obj.x.push(obj.y);
Traverse(obj).forEach(function (x) {
if (this.circular) this.update('...');
});
assert.deepEqual(obj, { x : [ 1, 2, 3, [ 4, 5, '...' ] ], y : [ 4, 5, '...' ] });
};
exports.circDubMap = function () {
var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] };
obj.y[2] = obj;
obj.x.push(obj.y);
var c = Traverse(obj).map(function (x) {
if (this.circular) {
this.update('...');
}
});
assert.deepEqual(c, { x : [ 1, 2, 3, [ 4, 5, '...' ] ], y : [ 4, 5, '...' ] });
};
exports.circClone = function () {
var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] };
obj.y[2] = obj;
obj.x.push(obj.y);
var clone = Traverse.clone(obj);
assert.ok(obj !== clone);
assert.ok(clone.y[2] === clone);
assert.ok(clone.y[2] !== obj);
assert.ok(clone.x[3][2] === clone);
assert.ok(clone.x[3][2] !== obj);
assert.deepEqual(clone.x.slice(0,3), [1,2,3]);
assert.deepEqual(clone.y.slice(0,2), [4,5]);
};
exports.circMapScrub = function () {
var obj = { a : 1, b : 2 };
obj.c = obj;
var scrubbed = Traverse(obj).map(function (node) {
if (this.circular) this.remove();
});
assert.deepEqual(
Object.keys(scrubbed).sort(),
[ 'a', 'b' ]
);
assert.ok(deepEqual(scrubbed, { a : 1, b : 2 }));
assert.equal(obj.c, obj);
};

View file

@ -0,0 +1,35 @@
var assert = require('assert');
var Traverse = require('../');
exports.dateEach = function () {
var obj = { x : new Date, y : 10, z : 5 };
var counts = {};
Traverse(obj).forEach(function (node) {
var t = (node instanceof Date && 'Date') || typeof node;
counts[t] = (counts[t] || 0) + 1;
});
assert.deepEqual(counts, {
object : 1,
Date : 1,
number : 2,
});
};
exports.dateMap = function () {
var obj = { x : new Date, y : 10, z : 5 };
var res = Traverse(obj).map(function (node) {
if (typeof node === 'number') this.update(node + 100);
});
assert.ok(obj.x !== res.x);
assert.deepEqual(res, {
x : obj.x,
y : 110,
z : 105,
});
};

View file

@ -0,0 +1,220 @@
var assert = require('assert');
var traverse = require('../');
var deepEqual = require('./lib/deep_equal');
exports.deepDates = function () {
assert.ok(
deepEqual(
{ d : new Date, x : [ 1, 2, 3 ] },
{ d : new Date, x : [ 1, 2, 3 ] }
),
'dates should be equal'
);
var d0 = new Date;
setTimeout(function () {
assert.ok(
!deepEqual(
{ d : d0, x : [ 1, 2, 3 ], },
{ d : new Date, x : [ 1, 2, 3 ] }
),
'microseconds should count in date equality'
);
}, 5);
};
exports.deepCircular = function () {
var a = [1];
a.push(a); // a = [ 1, *a ]
var b = [1];
b.push(a); // b = [ 1, [ 1, *a ] ]
assert.ok(
!deepEqual(a, b),
'circular ref mount points count towards equality'
);
var c = [1];
c.push(c); // c = [ 1, *c ]
assert.ok(
deepEqual(a, c),
'circular refs are structurally the same here'
);
var d = [1];
d.push(a); // c = [ 1, [ 1, *d ] ]
assert.ok(
deepEqual(b, d),
'non-root circular ref structural comparison'
);
};
exports.deepInstances = function () {
assert.ok(
!deepEqual([ new Boolean(false) ], [ false ]),
'boolean instances are not real booleans'
);
assert.ok(
!deepEqual([ new String('x') ], [ 'x' ]),
'string instances are not real strings'
);
assert.ok(
!deepEqual([ new Number(4) ], [ 4 ]),
'number instances are not real numbers'
);
assert.ok(
deepEqual([ new RegExp('x') ], [ /x/ ]),
'regexp instances are real regexps'
);
assert.ok(
!deepEqual([ new RegExp(/./) ], [ /../ ]),
'these regexps aren\'t the same'
);
assert.ok(
!deepEqual(
[ function (x) { return x * 2 } ],
[ function (x) { return x * 2 } ]
),
'functions with the same .toString() aren\'t necessarily the same'
);
var f = function (x) { return x * 2 };
assert.ok(
deepEqual([ f ], [ f ]),
'these functions are actually equal'
);
};
exports.deepEqual = function () {
assert.ok(
!deepEqual([ 1, 2, 3 ], { 0 : 1, 1 : 2, 2 : 3 }),
'arrays are not objects'
);
};
exports.falsy = function () {
assert.ok(
!deepEqual([ undefined ], [ null ]),
'null is not undefined!'
);
assert.ok(
!deepEqual([ null ], [ undefined ]),
'undefined is not null!'
);
assert.ok(
!deepEqual(
{ a : 1, b : 2, c : [ 3, undefined, 5 ] },
{ a : 1, b : 2, c : [ 3, null, 5 ] }
),
'undefined is not null, however deeply!'
);
assert.ok(
!deepEqual(
{ a : 1, b : 2, c : [ 3, undefined, 5 ] },
{ a : 1, b : 2, c : [ 3, null, 5 ] }
),
'null is not undefined, however deeply!'
);
assert.ok(
!deepEqual(
{ a : 1, b : 2, c : [ 3, undefined, 5 ] },
{ a : 1, b : 2, c : [ 3, null, 5 ] }
),
'null is not undefined, however deeply!'
);
};
exports.deletedArrayEqual = function () {
var xs = [ 1, 2, 3, 4 ];
delete xs[2];
var ys = Object.create(Array.prototype);
ys[0] = 1;
ys[1] = 2;
ys[3] = 4;
assert.ok(
deepEqual(xs, ys),
'arrays with deleted elements are only equal to'
+ ' arrays with similarly deleted elements'
);
assert.ok(
!deepEqual(xs, [ 1, 2, undefined, 4 ]),
'deleted array elements cannot be undefined'
);
assert.ok(
!deepEqual(xs, [ 1, 2, null, 4 ]),
'deleted array elements cannot be null'
);
};
exports.deletedObjectEqual = function () {
var obj = { a : 1, b : 2, c : 3 };
delete obj.c;
assert.ok(
deepEqual(obj, { a : 1, b : 2 }),
'deleted object elements should not show up'
);
assert.ok(
!deepEqual(obj, { a : 1, b : 2, c : undefined }),
'deleted object elements are not undefined'
);
assert.ok(
!deepEqual(obj, { a : 1, b : 2, c : null }),
'deleted object elements are not null'
);
};
exports.emptyKeyEqual = function () {
assert.ok(!deepEqual(
{ a : 1 }, { a : 1, '' : 55 }
));
};
exports.deepArguments = function () {
assert.ok(
!deepEqual(
[ 4, 5, 6 ],
(function () { return arguments })(4, 5, 6)
),
'arguments are not arrays'
);
assert.ok(
deepEqual(
(function () { return arguments })(4, 5, 6),
(function () { return arguments })(4, 5, 6)
),
'arguments should equal'
);
};
exports.deepUn = function () {
assert.ok(!deepEqual({ a : 1, b : 2 }, undefined));
assert.ok(!deepEqual({ a : 1, b : 2 }, {}));
assert.ok(!deepEqual(undefined, { a : 1, b : 2 }));
assert.ok(!deepEqual({}, { a : 1, b : 2 }));
assert.ok(deepEqual(undefined, undefined));
assert.ok(deepEqual(null, null));
assert.ok(!deepEqual(undefined, null));
};
exports.deepLevels = function () {
var xs = [ 1, 2, [ 3, 4, [ 5, 6 ] ] ];
assert.ok(!deepEqual(xs, []));
};

View file

@ -0,0 +1,17 @@
var assert = require('assert');
var Traverse = require('../');
var EventEmitter = require('events').EventEmitter;
exports['check instanceof on node elems'] = function () {
var counts = { emitter : 0 };
Traverse([ new EventEmitter, 3, 4, { ev : new EventEmitter }])
.forEach(function (node) {
if (node instanceof EventEmitter) counts.emitter ++;
})
;
assert.equal(counts.emitter, 2);
};

View file

@ -0,0 +1,42 @@
var assert = require('assert');
var Traverse = require('../');
exports['interface map'] = function () {
var obj = { a : [ 5,6,7 ], b : { c : [8] } };
assert.deepEqual(
Traverse.paths(obj)
.sort()
.map(function (path) { return path.join('/') })
.slice(1)
.join(' ')
,
'a a/0 a/1 a/2 b b/c b/c/0'
);
assert.deepEqual(
Traverse.nodes(obj),
[
{ a: [ 5, 6, 7 ], b: { c: [ 8 ] } },
[ 5, 6, 7 ], 5, 6, 7,
{ c: [ 8 ] }, [ 8 ], 8
]
);
assert.deepEqual(
Traverse.map(obj, function (node) {
if (typeof node == 'number') {
return node + 1000;
}
else if (Array.isArray(node)) {
return node.join(' ');
}
}),
{ a: '5 6 7', b: { c: '8' } }
);
var nodes = 0;
Traverse.forEach(obj, function (node) { nodes ++ });
assert.deepEqual(nodes, 8);
};

View file

@ -0,0 +1,47 @@
var assert = require('assert');
var Traverse = require('../');
exports['json test'] = function () {
var id = 54;
var callbacks = {};
var obj = { moo : function () {}, foo : [2,3,4, function () {}] };
var scrubbed = Traverse(obj).map(function (x) {
if (typeof x === 'function') {
callbacks[id] = { id : id, f : x, path : this.path };
this.update('[Function]');
id++;
}
});
assert.equal(
scrubbed.moo, '[Function]',
'obj.moo replaced with "[Function]"'
);
assert.equal(
scrubbed.foo[3], '[Function]',
'obj.foo[3] replaced with "[Function]"'
);
assert.deepEqual(scrubbed, {
moo : '[Function]',
foo : [ 2, 3, 4, "[Function]" ]
}, 'Full JSON string matches');
assert.deepEqual(
typeof obj.moo, 'function',
'Original obj.moo still a function'
);
assert.deepEqual(
typeof obj.foo[3], 'function',
'Original obj.foo[3] still a function'
);
assert.deepEqual(callbacks, {
54: { id: 54, f : obj.moo, path: [ 'moo' ] },
55: { id: 55, f : obj.foo[3], path: [ 'foo', '3' ] },
}, 'Check the generated callbacks list');
};

View file

@ -0,0 +1,29 @@
var assert = require('assert');
var Traverse = require('../');
exports['sort test'] = function () {
var acc = [];
Traverse({
a: 30,
b: 22,
id: 9
}).forEach(function (node) {
if ((! Array.isArray(node)) && typeof node === 'object') {
this.before(function(node) {
this.keys = Object.keys(node);
this.keys.sort(function(a, b) {
a = [a === "id" ? 0 : 1, a];
b = [b === "id" ? 0 : 1, b];
return a < b ? -1 : a > b ? 1 : 0;
});
});
}
if (this.isLeaf) acc.push(node);
});
assert.equal(
acc.join(' '),
'9 30 22',
'Traversal in a custom order'
);
};

View file

@ -0,0 +1,21 @@
var assert = require('assert');
var Traverse = require('../');
exports['leaves test'] = function () {
var acc = [];
Traverse({
a : [1,2,3],
b : 4,
c : [5,6],
d : { e : [7,8], f : 9 }
}).forEach(function (x) {
if (this.isLeaf) acc.push(x);
});
assert.equal(
acc.join(' '),
'1 2 3 4 5 6 7 8 9',
'Traversal in the right(?) order'
);
};

View file

@ -0,0 +1,92 @@
var traverse = require('../../');
module.exports = function (a, b) {
if (arguments.length !== 2) {
throw new Error(
'deepEqual requires exactly two objects to compare against'
);
}
var equal = true;
var node = b;
traverse(a).forEach(function (y) {
var notEqual = (function () {
equal = false;
//this.stop();
return undefined;
}).bind(this);
//if (node === undefined || node === null) return notEqual();
if (!this.isRoot) {
/*
if (!Object.hasOwnProperty.call(node, this.key)) {
return notEqual();
}
*/
if (typeof node !== 'object') return notEqual();
node = node[this.key];
}
var x = node;
this.post(function () {
node = x;
});
var toS = function (o) {
return Object.prototype.toString.call(o);
};
if (this.circular) {
if (traverse(b).get(this.circular.path) !== x) notEqual();
}
else if (typeof x !== typeof y) {
notEqual();
}
else if (x === null || y === null || x === undefined || y === undefined) {
if (x !== y) notEqual();
}
else if (x.__proto__ !== y.__proto__) {
notEqual();
}
else if (x === y) {
// nop
}
else if (typeof x === 'function') {
if (x instanceof RegExp) {
// both regexps on account of the __proto__ check
if (x.toString() != y.toString()) notEqual();
}
else if (x !== y) notEqual();
}
else if (typeof x === 'object') {
if (toS(y) === '[object Arguments]'
|| toS(x) === '[object Arguments]') {
if (toS(x) !== toS(y)) {
notEqual();
}
}
else if (x instanceof Date || y instanceof Date) {
if (!(x instanceof Date) || !(y instanceof Date)
|| x.getTime() !== y.getTime()) {
notEqual();
}
}
else {
var kx = Object.keys(x);
var ky = Object.keys(y);
if (kx.length !== ky.length) return notEqual();
for (var i = 0; i < kx.length; i++) {
var k = kx[i];
if (!Object.hasOwnProperty.call(y, k)) {
notEqual();
}
}
}
}
});
return equal;
};

View file

@ -0,0 +1,252 @@
var assert = require('assert');
var Traverse = require('../');
var deepEqual = require('./lib/deep_equal');
exports.mutate = function () {
var obj = { a : 1, b : 2, c : [ 3, 4 ] };
var res = Traverse(obj).forEach(function (x) {
if (typeof x === 'number' && x % 2 === 0) {
this.update(x * 10);
}
});
assert.deepEqual(obj, res);
assert.deepEqual(obj, { a : 1, b : 20, c : [ 3, 40 ] });
};
exports.mutateT = function () {
var obj = { a : 1, b : 2, c : [ 3, 4 ] };
var res = Traverse.forEach(obj, function (x) {
if (typeof x === 'number' && x % 2 === 0) {
this.update(x * 10);
}
});
assert.deepEqual(obj, res);
assert.deepEqual(obj, { a : 1, b : 20, c : [ 3, 40 ] });
};
exports.map = function () {
var obj = { a : 1, b : 2, c : [ 3, 4 ] };
var res = Traverse(obj).map(function (x) {
if (typeof x === 'number' && x % 2 === 0) {
this.update(x * 10);
}
});
assert.deepEqual(obj, { a : 1, b : 2, c : [ 3, 4 ] });
assert.deepEqual(res, { a : 1, b : 20, c : [ 3, 40 ] });
};
exports.mapT = function () {
var obj = { a : 1, b : 2, c : [ 3, 4 ] };
var res = Traverse.map(obj, function (x) {
if (typeof x === 'number' && x % 2 === 0) {
this.update(x * 10);
}
});
assert.deepEqual(obj, { a : 1, b : 2, c : [ 3, 4 ] });
assert.deepEqual(res, { a : 1, b : 20, c : [ 3, 40 ] });
};
exports.clone = function () {
var obj = { a : 1, b : 2, c : [ 3, 4 ] };
var res = Traverse(obj).clone();
assert.deepEqual(obj, res);
assert.ok(obj !== res);
obj.a ++;
assert.deepEqual(res.a, 1);
obj.c.push(5);
assert.deepEqual(res.c, [ 3, 4 ]);
};
exports.cloneT = function () {
var obj = { a : 1, b : 2, c : [ 3, 4 ] };
var res = Traverse.clone(obj);
assert.deepEqual(obj, res);
assert.ok(obj !== res);
obj.a ++;
assert.deepEqual(res.a, 1);
obj.c.push(5);
assert.deepEqual(res.c, [ 3, 4 ]);
};
exports.reduce = function () {
var obj = { a : 1, b : 2, c : [ 3, 4 ] };
var res = Traverse(obj).reduce(function (acc, x) {
if (this.isLeaf) acc.push(x);
return acc;
}, []);
assert.deepEqual(obj, { a : 1, b : 2, c : [ 3, 4 ] });
assert.deepEqual(res, [ 1, 2, 3, 4 ]);
};
exports.reduceInit = function () {
var obj = { a : 1, b : 2, c : [ 3, 4 ] };
var res = Traverse(obj).reduce(function (acc, x) {
if (this.isRoot) assert.fail('got root');
return acc;
});
assert.deepEqual(obj, { a : 1, b : 2, c : [ 3, 4 ] });
assert.deepEqual(res, obj);
};
exports.remove = function () {
var obj = { a : 1, b : 2, c : [ 3, 4 ] };
Traverse(obj).forEach(function (x) {
if (this.isLeaf && x % 2 == 0) this.remove();
});
assert.deepEqual(obj, { a : 1, c : [ 3 ] });
};
exports.removeNoStop = function() {
var obj = { a : 1, b : 2, c : { d: 3, e: 4 }, f: 5 };
var keys = [];
Traverse(obj).forEach(function (x) {
keys.push(this.key)
if (this.key == 'c') this.remove();
});
assert.deepEqual(keys, [undefined, 'a', 'b', 'c', 'd', 'e', 'f'])
}
exports.removeStop = function() {
var obj = { a : 1, b : 2, c : { d: 3, e: 4 }, f: 5 };
var keys = [];
Traverse(obj).forEach(function (x) {
keys.push(this.key)
if (this.key == 'c') this.remove(true);
});
assert.deepEqual(keys, [undefined, 'a', 'b', 'c', 'f'])
}
exports.removeMap = function () {
var obj = { a : 1, b : 2, c : [ 3, 4 ] };
var res = Traverse(obj).map(function (x) {
if (this.isLeaf && x % 2 == 0) this.remove();
});
assert.deepEqual(obj, { a : 1, b : 2, c : [ 3, 4 ] });
assert.deepEqual(res, { a : 1, c : [ 3 ] });
};
exports.delete = function () {
var obj = { a : 1, b : 2, c : [ 3, 4 ] };
Traverse(obj).forEach(function (x) {
if (this.isLeaf && x % 2 == 0) this.delete();
});
assert.ok(!deepEqual(
obj, { a : 1, c : [ 3, undefined ] }
));
assert.ok(deepEqual(
obj, { a : 1, c : [ 3 ] }
));
assert.ok(!deepEqual(
obj, { a : 1, c : [ 3, null ] }
));
};
exports.deleteNoStop = function() {
var obj = { a : 1, b : 2, c : { d: 3, e: 4 } };
var keys = [];
Traverse(obj).forEach(function (x) {
keys.push(this.key)
if (this.key == 'c') this.delete();
});
assert.deepEqual(keys, [undefined, 'a', 'b', 'c', 'd', 'e'])
}
exports.deleteStop = function() {
var obj = { a : 1, b : 2, c : { d: 3, e: 4 } };
var keys = [];
Traverse(obj).forEach(function (x) {
keys.push(this.key)
if (this.key == 'c') this.delete(true);
});
assert.deepEqual(keys, [undefined, 'a', 'b', 'c'])
}
exports.deleteRedux = function () {
var obj = { a : 1, b : 2, c : [ 3, 4, 5 ] };
Traverse(obj).forEach(function (x) {
if (this.isLeaf && x % 2 == 0) this.delete();
});
assert.ok(!deepEqual(
obj, { a : 1, c : [ 3, undefined, 5 ] }
));
assert.ok(deepEqual(
obj, { a : 1, c : [ 3 ,, 5 ] }
));
assert.ok(!deepEqual(
obj, { a : 1, c : [ 3, null, 5 ] }
));
assert.ok(!deepEqual(
obj, { a : 1, c : [ 3, 5 ] }
));
};
exports.deleteMap = function () {
var obj = { a : 1, b : 2, c : [ 3, 4 ] };
var res = Traverse(obj).map(function (x) {
if (this.isLeaf && x % 2 == 0) this.delete();
});
assert.ok(deepEqual(
obj,
{ a : 1, b : 2, c : [ 3, 4 ] }
));
var xs = [ 3, 4 ];
delete xs[1];
assert.ok(deepEqual(
res, { a : 1, c : xs }
));
assert.ok(deepEqual(
res, { a : 1, c : [ 3, ] }
));
assert.ok(deepEqual(
res, { a : 1, c : [ 3 ] }
));
};
exports.deleteMapRedux = function () {
var obj = { a : 1, b : 2, c : [ 3, 4, 5 ] };
var res = Traverse(obj).map(function (x) {
if (this.isLeaf && x % 2 == 0) this.delete();
});
assert.ok(deepEqual(
obj,
{ a : 1, b : 2, c : [ 3, 4, 5 ] }
));
var xs = [ 3, 4, 5 ];
delete xs[1];
assert.ok(deepEqual(
res, { a : 1, c : xs }
));
assert.ok(!deepEqual(
res, { a : 1, c : [ 3, 5 ] }
));
assert.ok(deepEqual(
res, { a : 1, c : [ 3 ,, 5 ] }
));
};

View file

@ -0,0 +1,20 @@
var Traverse = require('../');
var assert = require('assert');
exports['negative update test'] = function () {
var obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ];
var fixed = Traverse.map(obj, function (x) {
if (x < 0) this.update(x + 128);
});
assert.deepEqual(fixed,
[ 5, 6, 125, [ 7, 8, 126, 1 ], { f: 10, g: 115 } ],
'Negative values += 128'
);
assert.deepEqual(obj,
[ 5, 6, -3, [ 7, 8, -2, 1 ], { f: 10, g: -13 } ],
'Original references not modified'
);
}

15
node_modules/burrito/node_modules/traverse/test/obj.js generated vendored Normal file
View file

@ -0,0 +1,15 @@
var assert = require('assert');
var Traverse = require('../');
exports['traverse an object with nested functions'] = function () {
var to = setTimeout(function () {
assert.fail('never ran');
}, 1000);
function Cons (x) {
clearTimeout(to);
assert.equal(x, 10);
};
Traverse(new Cons(10));
};

View file

@ -0,0 +1,35 @@
var assert = require('assert');
var traverse = require('../');
exports.siblings = function () {
var obj = { a : 1, b : 2, c : [ 4, 5, 6 ] };
var res = traverse(obj).reduce(function (acc, x) {
var p = '/' + this.path.join('/');
if (this.parent) {
acc[p] = {
siblings : this.parent.keys,
key : this.key,
index : this.parent.keys.indexOf(this.key)
};
}
else {
acc[p] = {
siblings : [],
key : this.key,
index : -1
}
}
return acc;
}, {});
assert.deepEqual(res, {
'/' : { siblings : [], key : undefined, index : -1 },
'/a' : { siblings : [ 'a', 'b', 'c' ], key : 'a', index : 0 },
'/b' : { siblings : [ 'a', 'b', 'c' ], key : 'b', index : 1 },
'/c' : { siblings : [ 'a', 'b', 'c' ], key : 'c', index : 2 },
'/c/0' : { siblings : [ '0', '1', '2' ], key : '0', index : 0 },
'/c/1' : { siblings : [ '0', '1', '2' ], key : '1', index : 1 },
'/c/2' : { siblings : [ '0', '1', '2' ], key : '2', index : 2 }
});
};

View file

@ -0,0 +1,41 @@
var assert = require('assert');
var traverse = require('../');
exports.stop = function () {
var visits = 0;
traverse('abcdefghij'.split('')).forEach(function (node) {
if (typeof node === 'string') {
visits ++;
if (node === 'e') this.stop()
}
});
assert.equal(visits, 5);
};
exports.stopMap = function () {
var s = traverse('abcdefghij'.split('')).map(function (node) {
if (typeof node === 'string') {
if (node === 'e') this.stop()
return node.toUpperCase();
}
}).join('');
assert.equal(s, 'ABCDEfghij');
};
exports.stopReduce = function () {
var obj = {
a : [ 4, 5 ],
b : [ 6, [ 7, 8, 9 ] ]
};
var xs = traverse(obj).reduce(function (acc, node) {
if (this.isLeaf) {
if (node === 7) this.stop();
else acc.push(node)
}
return acc;
}, []);
assert.deepEqual(xs, [ 4, 5, 6 ]);
};

View file

@ -0,0 +1,36 @@
var assert = require('assert');
var Traverse = require('../');
exports.stringify = function () {
var obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ];
var s = '';
Traverse(obj).forEach(function (node) {
if (Array.isArray(node)) {
this.before(function () { s += '[' });
this.post(function (child) {
if (!child.isLast) s += ',';
});
this.after(function () { s += ']' });
}
else if (typeof node == 'object') {
this.before(function () { s += '{' });
this.pre(function (x, key) {
s += '"' + key + '"' + ':';
});
this.post(function (child) {
if (!child.isLast) s += ',';
});
this.after(function () { s += '}' });
}
else if (typeof node == 'function') {
s += 'null';
}
else {
s += node.toString();
}
});
assert.equal(s, JSON.stringify(obj));
}

View file

@ -0,0 +1,34 @@
var traverse = require('../');
var assert = require('assert');
exports.subexpr = function () {
var obj = [ 'a', 4, 'b', 5, 'c', 6 ];
var r = traverse(obj).map(function (x) {
if (typeof x === 'number') {
this.update([ x - 0.1, x, x + 0.1 ], true);
}
});
assert.deepEqual(obj, [ 'a', 4, 'b', 5, 'c', 6 ]);
assert.deepEqual(r, [
'a', [ 3.9, 4, 4.1 ],
'b', [ 4.9, 5, 5.1 ],
'c', [ 5.9, 6, 6.1 ],
]);
};
exports.block = function () {
var obj = [ [ 1 ], [ 2 ], [ 3 ] ];
var r = traverse(obj).map(function (x) {
if (Array.isArray(x) && !this.isRoot) {
if (x[0] === 5) this.block()
else this.update([ [ x[0] + 1 ] ])
}
});
assert.deepEqual(r, [
[ [ [ [ [ 5 ] ] ] ] ],
[ [ [ [ 5 ] ] ] ],
[ [ [ 5 ] ] ],
]);
};

View file

@ -0,0 +1,55 @@
var assert = require('assert');
var traverse = require('../');
var deepEqual = require('./lib/deep_equal');
exports.super_deep = function () {
var util = require('util');
var a0 = make();
var a1 = make();
assert.ok(deepEqual(a0, a1));
a0.c.d.moo = true;
assert.ok(!deepEqual(a0, a1));
a1.c.d.moo = true;
assert.ok(deepEqual(a0, a1));
// TODO: this one
//a0.c.a = a1;
//assert.ok(!deepEqual(a0, a1));
};
function make () {
var a = { self : 'a' };
var b = { self : 'b' };
var c = { self : 'c' };
var d = { self : 'd' };
var e = { self : 'e' };
a.a = a;
a.b = b;
a.c = c;
b.a = a;
b.b = b;
b.c = c;
c.a = a;
c.b = b;
c.c = c;
c.d = d;
d.a = a;
d.b = b;
d.c = c;
d.d = d;
d.e = e;
e.a = a;
e.b = b;
e.c = c;
e.d = d;
e.e = e;
return a;
}

43
node_modules/burrito/package.json generated vendored Normal file
View file

@ -0,0 +1,43 @@
{
"name" : "burrito",
"description" : "Wrap up expressions with a trace function while walking the AST with rice and beans on the side",
"version" : "0.2.12",
"repository" : {
"type" : "git",
"url" : "git://github.com/substack/node-burrito.git"
},
"main" : "./index.js",
"keywords" : [
"trace",
"ast",
"walk",
"syntax",
"source",
"tree",
"uglify"
],
"directories" : {
"lib" : ".",
"example" : "example",
"test" : "test"
},
"scripts" : {
"test" : "tap test/*.js"
},
"dependencies" : {
"traverse" : "~0.5.1",
"uglify-js" : "~1.1.1"
},
"devDependencies" : {
"tap" : "~0.2.5"
},
"engines" : {
"node" : ">=0.4.0"
},
"license" : "BSD",
"author" : {
"name" : "James Halliday",
"email" : "mail@substack.net",
"url" : "http://substack.net"
}
}

31
node_modules/burrito/test/ast.js generated vendored Normal file
View file

@ -0,0 +1,31 @@
var test = require('tap').test;
var burrito = require('../');
var vm = require('vm');
test('ast', function (t) {
t.plan(2);
var ast = burrito.parse('f(g(h(5)))', false, true);
var src = burrito(ast, function (node) {
if (node.name === 'call') {
node.wrap(function (s) {
return 'z(' + s + ')';
});
}
});
var times = 0;
t.equal(
vm.runInNewContext(src, {
f : function (x) { return x + 1 },
g : function (x) { return x + 2 },
h : function (x) { return x + 3 },
z : function (x) {
times ++;
return x * 10;
},
}),
(((((5 + 3) * 10) + 2) * 10) + 1) * 10
);
t.equal(times, 3);
});

52
node_modules/burrito/test/err.js generated vendored Normal file
View file

@ -0,0 +1,52 @@
var test = require('tap').test;
var burrito = require('../');
test('wrap error', function (t) {
t.plan(6);
try {
var src = burrito('f() && g()', function (node) {
if (node.name === 'binary') node.wrap('h(%a, %b')
});
t.fail('should have blown up');
}
catch (err) {
t.ok(err.message.match(/unexpected/i));
t.ok(err instanceof SyntaxError);
t.ok(!err.stack.match(/uglify-js/));
t.equal(err.line, 0);
t.equal(err.col, 10);
t.equal(err.pos, 10);
}
});
test('non string', function (t) {
t.plan(3);
t.throws(function () {
burrito.parse(new Buffer('[]'));
});
t.throws(function () {
burrito.parse(new String('[]'));
});
t.throws(function () {
burrito.parse();
});
});
test('syntax error', function (t) {
t.plan(3);
try {
var src = burrito('f() && g())', function (node) {
if (node.name === 'binary') node.wrap('h(%a, %b)')
});
assert.fail('should have blown up');
}
catch (err) {
t.ok(err.message.match(/unexpected/i));
t.ok(err instanceof SyntaxError);
t.ok(!err.stack.match(/uglify-js/));
}
});

9
node_modules/burrito/test/fail.js generated vendored Normal file
View file

@ -0,0 +1,9 @@
var burrito = require('../');
var test = require('tap').test;
var fs = require('fs');
var src = fs.readFileSync(__dirname + '/fail/src.js', 'utf8');
test('fail', function (t) {
burrito(src, function (node) {});
t.end();
});

60
node_modules/burrito/test/fail/src.js generated vendored Normal file
View file

@ -0,0 +1,60 @@
var path = require('path')
module.exports = function(fs, ready) {
var global_files = {}
var recurse = function(dir, okay) {
fs.readdir(dir, function(err, dir_files) {
var countdown = 0
, files = []
, dirs = []
, checked = 0
dir_files.forEach(function(file, idx, all) {
fs.stat(path.join(dir, file), function(err, stat) {
if(stat.isDirectory() && !/node_modules/g.test(dir)) {
dirs.push(file)
} else if(/\.js$/g.test(file)) {
files.push(file)
}
if(++checked >= dir_files.length)
recurse_dirs()
})
})
function recurse_dirs() {
var total = 0
dirs.forEach(function(this_dir) {
recurse(path.join(dir, this_dir), function(err, data) {
if(++total >= dirs.length)
recurse_files()
})
})
if(!dirs.length)
recurse_files()
}
function recurse_files() {
var total = 0
files.forEach(function(file) {
fs.readFile(path.join(dir, file), 'utf8', function(err, src) {
global_files[path.join(dir, file)] = src
++total >= files.length &&
okay(null, global_files)
})
})
if(!files.length)
okay(null, global_files)
}
if(!dir_files.length)
okay(null, global_files)
})
}
recurse('.', ready)
}

92
node_modules/burrito/test/label.js generated vendored Normal file
View file

@ -0,0 +1,92 @@
var test = require('tap').test;
var burrito = require('../');
test('call label', function (t) {
t.plan(1);
burrito('foo(10)', function (node) {
if (node.name === 'call') {
t.equal(node.label(), 'foo');
}
});
});
test('var label', function (t) {
t.plan(1);
burrito('var x = 2', function (node) {
if (node.name === 'var') {
t.same(node.label(), [ 'x' ]);
}
});
});
test('vars label', function (t) {
t.plan(1);
burrito('var x = 2, y = 3', function (node) {
if (node.name === 'var') {
t.same(node.label(), [ 'x', 'y' ]);
}
});
});
test('defun label', function (t) {
t.plan(1);
burrito('function moo () {}', function (node) {
if (node.name === 'defun') {
t.same(node.label(), 'moo');
}
});
});
test('function label', function (t) {
t.plan(1);
burrito('(function zzz () {})()', function (node) {
if (node.name === 'function') {
t.same(node.label(), 'zzz');
}
});
});
test('anon function label', function (t) {
t.plan(1);
burrito('(function () {})()', function (node) {
if (node.name === 'function') {
t.equal(node.label(), null);
}
});
});
test('dot call label', function (t) {
t.plan(1);
burrito('process.nextTick(fn)', function (node) {
if (node.name === 'call') {
t.equal(node.label(), 'nextTick');
}
});
});
test('triple dot label', function (t) {
t.plan(1);
burrito('a.b.c(fn)', function (node) {
if (node.name === 'call') {
t.equal(node.label(), 'c');
}
});
});
test('expr label', function (t) {
t.plan(1);
burrito('a.b[x+1](fn)', function (node) {
if (node.name === 'call') {
t.ok(node.label() === null);
}
});
});

34
node_modules/burrito/test/microwave.js generated vendored Normal file
View file

@ -0,0 +1,34 @@
var test = require('tap').test;
var burrito = require('../');
test('microwave', function (t) {
t.plan(4);
var context = {
f : function (x) { return x + 1 },
g : function (x) { return x + 2 },
h : function (x) { return x + 3 },
z : function (x) {
t.ok(true); // 3 times
return x * 10;
},
};
var res = burrito.microwave('f(g(h(5)))', context, function (node) {
if (node.name === 'call') {
node.wrap(function (s) {
return 'z(' + s + ')';
});
}
});
t.equal(res, (((((5 + 3) * 10) + 2) * 10) + 1) * 10);
});
test('empty context', function (t) {
var res = burrito.microwave('Math.sin(2)', function (node) {
if (node.name === 'num') node.wrap('Math.PI / %s');
});
t.equal(res, 1);
t.end();
});

27
node_modules/burrito/test/parent.js generated vendored Normal file
View file

@ -0,0 +1,27 @@
var test = require('tap').test;
var burrito = require('../');
test('check parent', function (t) {
t.plan(5);
var src = 'Math.tan(0) + Math.sin(0)';
var res = burrito.microwave(src, function (node) {
if (node.name === 'binary') {
node.wrap('%a - %b');
}
else if (node.name === 'num') {
t.equal(node.parent().value[0][0], 'dot');
var fn = node.parent().value[0][2];
if (fn === 'sin') {
node.wrap('Math.PI / 2');
}
else if (fn === 'tan') {
node.wrap('Math.PI / 4');
}
else t.fail('Unknown fn');
}
});
t.equal(res, Math.tan(Math.PI / 4) - Math.sin(Math.PI / 2)); // ~ 0
});

159
node_modules/burrito/test/wrap.js generated vendored Normal file
View file

@ -0,0 +1,159 @@
var test = require('tap').test;
var burrito = require('../');
var vm = require('vm');
test('preserve ternary parentheses', function (t) {
var originalSource = '"anything" + (x ? y : z) + "anything"';
var burritoSource = burrito(originalSource, function (node) {
// do nothing. we just want to check that ternary parens are persisted
});
var ctxt = {
x : false,
y : 'y_'+~~(Math.random()*10),
z : 'z_'+~~(Math.random()*10)
};
var expectedOutput = vm.runInNewContext(originalSource, ctxt);
var burritoOutput = vm.runInNewContext(burritoSource, ctxt);
t.equal(burritoOutput, expectedOutput);
ctxt.x = true;
expectedOutput = vm.runInNewContext(originalSource, ctxt);
burritoOutput = vm.runInNewContext(burritoSource, ctxt);
t.equal(burritoOutput, expectedOutput);
t.end();
});
test('wrap calls', function (t) {
t.plan(20);
var src = burrito('f() && g(h())\nfoo()', function (node) {
if (node.name === 'call') node.wrap('qqq(%s)');
if (node.name === 'binary') node.wrap('bbb(%s)');
t.ok(node.state);
t.equal(this, node.state);
});
var times = { bbb : 0, qqq : 0 };
var res = [];
vm.runInNewContext(src, {
bbb : function (x) {
times.bbb ++;
res.push(x);
return x;
},
qqq : function (x) {
times.qqq ++;
res.push(x);
return x;
},
f : function () { return true },
g : function (h) {
t.equal(h, 7);
return h !== 7
},
h : function () { return 7 },
foo : function () { return 'foo!' },
});
t.same(res, [
true, // f()
7, // h()
false, // g(h())
false, // f() && g(h())
'foo!', // foo()
]);
t.equal(times.bbb, 1);
t.equal(times.qqq, 4);
t.end();
});
test('wrap fn', function (t) {
var src = burrito('f(g(h(5)))', function (node) {
if (node.name === 'call') {
node.wrap(function (s) {
return 'z(' + s + ')';
});
}
});
var times = 0;
t.equal(
vm.runInNewContext(src, {
f : function (x) { return x + 1 },
g : function (x) { return x + 2 },
h : function (x) { return x + 3 },
z : function (x) {
times ++;
return x * 10;
},
}),
(((((5 + 3) * 10) + 2) * 10) + 1) * 10
);
t.equal(times, 3);
t.end();
});
test('binary string', function (t) {
var src = 'z(x + y)';
var context = {
x : 3,
y : 4,
z : function (n) { return n * 10 },
};
var res = burrito.microwave(src, context, function (node) {
if (node.name === 'binary') {
node.wrap('%a*2 - %b*2');
}
});
t.equal(res, 10 * (3*2 - 4*2));
t.end();
});
test('binary fn', function (t) {
var src = 'z(x + y)';
var context = {
x : 3,
y : 4,
z : function (n) { return n * 10 },
};
var res = burrito.microwave(src, context, function (node) {
if (node.name === 'binary') {
node.wrap(function (expr, a, b) {
return '(' + a + ')*2 - ' + '(' + b + ')*2';
});
}
});
t.equal(res, 10 * (3*2 - 4*2));
t.end();
});
test('intersperse', function (t) {
var src = '(' + (function () {
f();
g();
}).toString() + ')()';
var times = { f : 0, g : 0, zzz : 0 };
var context = {
f : function () { times.f ++ },
g : function () { times.g ++ },
zzz : function () { times.zzz ++ },
};
burrito.microwave(src, context, function (node) {
if (node.name === 'stat') node.wrap('{ zzz(); %s }');
});
t.same(times, { f : 1, g : 1, zzz : 3 });
t.end();
});