[Pkg-javascript-commits] [ltx] 400/469: use standard JavaScript style and improvements
Jonas Smedegaard
dr at jones.dk
Wed Aug 31 13:03:31 UTC 2016
This is an automated email from the git hooks/post-receive script.
js pushed a commit to branch master
in repository ltx.
commit 34138b22097b16a4384f1f593f8e1df124b75d53
Author: Sonny Piers <sonny at fastmail.net>
Date: Sun Oct 25 02:12:05 2015 +0100
use standard JavaScript style and improvements
---
.editorconfig | 4 -
.eslintignore | 3 -
.eslintrc | 36 ----
.gitignore | 4 +-
.npmignore | 2 -
.travis.yml | 18 +-
README.md | 12 +-
benchmark.js | 26 +--
lib/index.js => index.js | 8 +-
lib/DOMElement.js | 126 ++++++------
lib/Element.js | 485 +++++++++++++++++++++++-----------------------
lib/Parser.js | 94 +++++----
lib/escape.js | 16 +-
lib/parse.js | 34 ++--
lib/parsers/easysax.js | 88 ++++-----
lib/parsers/index.js | 14 +-
lib/parsers/ltx.js | 302 +++++++++++++++--------------
lib/parsers/node-expat.js | 60 +++---
lib/parsers/node-xml.js | 99 +++++-----
lib/parsers/sax.js | 65 +++----
package.json | 25 ++-
test/dom-element-test.js | 100 +++++-----
test/element-test.js | 476 ++++++++++++++++++++++-----------------------
test/parse-test.js | 303 +++++++++++++++--------------
test/unicode-test.js | 76 ++++----
25 files changed, 1210 insertions(+), 1266 deletions(-)
diff --git a/.editorconfig b/.editorconfig
index 10e960a..a996a2d 100644
--- a/.editorconfig
+++ b/.editorconfig
@@ -9,7 +9,3 @@ charset = utf-8
trim_trailing_whitespace = true
indent_style = space
indent_size = 2
-charset = utf-8
-
-[*.js]
-indent_size = 4
diff --git a/.eslintignore b/.eslintignore
deleted file mode 100644
index a430685..0000000
--- a/.eslintignore
+++ /dev/null
@@ -1,3 +0,0 @@
-node_modules/
-
-ltx.js
diff --git a/.eslintrc b/.eslintrc
deleted file mode 100644
index 9d8907c..0000000
--- a/.eslintrc
+++ /dev/null
@@ -1,36 +0,0 @@
-root: true
-
-# http://eslint.org/docs/user-guide/configuring.html#extending-configuration-files
-extends:
- - eslint:recommended
-
-# http://eslint.org/docs/user-guide/configuring.html#specifying-environments
-env:
- node: true
-
-# http://eslint.org/docs/rules/
-rules:
- # http://eslint.org/docs/rules/#possible-errors
- no-console: 0
- valid-jsdoc: 0
- no-unexpected-multiline: 2
-
- # http://eslint.org/docs/rules/#best-practices
-
-
- # http://eslint.org/docs/rules/#strict-mode
- strict: [2, global]
-
- # http://eslint.org/docs/rules/#variables
-
-
- # http://eslint.org/docs/rules/#nodejs
-
-
- # http://eslint.org/docs/rules/#stylistic-issues
- camelcase: 2
- comma-spacing: 2
- eqeqeq: 2
- indent: [2, 4]
- new-cap: 2
- semi: [2, never]
diff --git a/.gitignore b/.gitignore
index 9cdead9..e4adf3b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,10 +1,8 @@
node_modules/
!.editorconfig
-!.eslintignore
-!.eslintrc
!.gitignore
!.npmignore
!.travis.yml
-ltx.js
+/ltx.js
diff --git a/.npmignore b/.npmignore
index 1d9cf36..940389c 100644
--- a/.npmignore
+++ b/.npmignore
@@ -1,8 +1,6 @@
test/
.editorconfig
-.eslintignore
-.eslintrc
.gitignore
.npmignore
.travis.yml
diff --git a/.travis.yml b/.travis.yml
index b1deb34..2bd48c4 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -2,20 +2,24 @@ sudo: false
language: node_js
+env:
+ - CXX="g++-4.8"
+
node_js:
- - '0.8'
- '0.10'
- '0.12'
- '4.0'
+ - '4.1'
+ - '4.2'
+ - 'stable'
addons:
apt:
+ sources:
+ - ubuntu-toolchain-r-test
packages:
- - libicu-dev
-
-before_install:
- # npm shipped with Node.js 0.8 doesn't support carret so let's update it
- - 'if [ "$TRAVIS_NODE_VERSION" == "0.8" ]; then npm i -g npm; fi'
+ - g++-4.8
+ - gcc-4.8
before_script:
- - npm install -g browserify
+ - npm install -g browserify standard
diff --git a/README.md b/README.md
index 015847e..ec1fe4a 100644
--- a/README.md
+++ b/README.md
@@ -1,18 +1,18 @@
# Less-Than XML
-* *Element:* any XML Element
-* Text nodes are Strings
-* Runs on node.js and browserify
+`<xml for=\"JavaScript\">`
-## Build status
+[![build status](https://img.shields.io/travis/node-xmpp/ltx/master.svg?style=flat-square)](https://travis-ci.org/node-xmpp/ltx/branches)
+[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square)](http://standardjs.com/)
-[![Build Status](https://secure.travis-ci.org/node-xmpp/ltx.png)](http://travis-ci.org/node-xmpp/ltx)
+* *Element:* any XML Element
+* Text nodes are Strings
+* Runs on Node.js and browsers
# Documentation
For documentation please see http://node-xmpp.org/doc/ltx.html
-
## TODO
* More documentation
diff --git a/benchmark.js b/benchmark.js
index 4955663..9038a93 100644
--- a/benchmark.js
+++ b/benchmark.js
@@ -1,27 +1,27 @@
'use strict'
var benchmark = require('benchmark')
-var ltx = require('./lib/index')
+var ltx = require('./index')
var parsers = require('./lib/parsers')
var XML = [
- '<message to="foo at bar" from="bar at to" type="chat" id="foobar">',
- '<body>Where there is love there is life.</body>',
- '</message>'
+ '<message to="foo at bar" from="bar at to" type="chat" id="foobar">',
+ '<body>Where there is love there is life.</body>',
+ '</message>'
].join('')
var suite = new benchmark.Suite('parse')
-parsers.forEach(function(Parser) {
- suite.add(Parser.name, function() {
- ltx.parse(XML, {Parser: Parser})
- })
+parsers.forEach(function (Parser) {
+ suite.add(Parser.name, function () {
+ ltx.parse(XML, {Parser: Parser})
+ })
})
-suite.on('cycle', function(event) {
- console.log(event.target.toString())
+suite.on('cycle', function (event) {
+ console.log(event.target.toString())
})
-.on('complete', function() {
+ .on('complete', function () {
console.log('Fastest is ' + this.filter('fastest').pluck('name'))
-})
-.run({'async': true})
+ })
+ .run({'async': true})
diff --git a/lib/index.js b/index.js
similarity index 65%
rename from lib/index.js
rename to index.js
index 0791e95..bf462ab 100644
--- a/lib/index.js
+++ b/index.js
@@ -1,9 +1,9 @@
'use strict'
-var parse = require('./parse')
-var Parser = require('./Parser')
-var escape = require('./escape')
-var Element = require('./Element')
+var parse = require('./lib/parse')
+var Parser = require('./lib/Parser')
+var escape = require('./lib/escape')
+var Element = require('./lib/Element')
/**
* Element
diff --git a/lib/DOMElement.js b/lib/DOMElement.js
index df6fb7f..085242d 100644
--- a/lib/DOMElement.js
+++ b/lib/DOMElement.js
@@ -1,121 +1,121 @@
'use strict'
var inherits = require('inherits')
- , Element = require('./Element')
+var Element = require('./Element')
-function DOMElement(name, attrs) {
- Element.call(this, name, attrs)
+function DOMElement (name, attrs) {
+ Element.call(this, name, attrs)
- this.nodeType = 1
- this.nodeName = this.localName
+ this.nodeType = 1
+ this.nodeName = this.localName
}
inherits(DOMElement, Element)
-DOMElement.prototype._getElement = function(name, attrs) {
- var element = new DOMElement(name, attrs)
- return element
+DOMElement.prototype._getElement = function (name, attrs) {
+ var element = new DOMElement(name, attrs)
+ return element
}
Object.defineProperty(DOMElement.prototype, 'localName', {
- get: function () {
- return this.getName()
- }
+ get: function () {
+ return this.getName()
+ }
})
Object.defineProperty(DOMElement.prototype, 'namespaceURI', {
- get: function () {
- return this.getNS()
- }
+ get: function () {
+ return this.getNS()
+ }
})
Object.defineProperty(DOMElement.prototype, 'parentNode', {
- get: function () {
- return this.parent
- }
+ get: function () {
+ return this.parent
+ }
})
Object.defineProperty(DOMElement.prototype, 'childNodes', {
- get: function () {
- return this.children
- }
+ get: function () {
+ return this.children
+ }
})
Object.defineProperty(DOMElement.prototype, 'textContent', {
- get: function () {
- return this.getText()
- },
- set: function (value) {
- this.children.push(value)
- }
+ get: function () {
+ return this.getText()
+ },
+ set: function (value) {
+ this.children.push(value)
+ }
})
DOMElement.prototype.getElementsByTagName = function (name) {
- return this.getChildren(name)
+ return this.getChildren(name)
}
DOMElement.prototype.getAttribute = function (name) {
- return this.getAttr(name)
+ return this.getAttr(name)
}
DOMElement.prototype.setAttribute = function (name, value) {
- this.attr(name, value)
+ this.attr(name, value)
}
DOMElement.prototype.getAttributeNS = function (ns, name) {
- if (ns === 'http://www.w3.org/XML/1998/namespace') {
- return this.getAttr(['xml', name].join(':'))
- }
- return this.getAttr(name, ns)
+ if (ns === 'http://www.w3.org/XML/1998/namespace') {
+ return this.getAttr(['xml', name].join(':'))
+ }
+ return this.getAttr(name, ns)
}
DOMElement.prototype.setAttributeNS = function (ns, name, value) {
- var prefix
- if (ns === 'http://www.w3.org/XML/1998/namespace') {
- prefix = 'xml'
- } else {
- var nss = this.getXmlns()
- prefix = nss[ns] || ''
- }
- if (prefix) {
- this.attr([prefix, name].join(':'), value)
- }
+ var prefix
+ if (ns === 'http://www.w3.org/XML/1998/namespace') {
+ prefix = 'xml'
+ } else {
+ var nss = this.getXmlns()
+ prefix = nss[ns] || ''
+ }
+ if (prefix) {
+ this.attr([prefix, name].join(':'), value)
+ }
}
DOMElement.prototype.removeAttribute = function (name) {
- this.attr(name, null)
+ this.attr(name, null)
}
DOMElement.prototype.removeAttributeNS = function (ns, name) {
- var prefix
- if (ns === 'http://www.w3.org/XML/1998/namespace') {
- prefix = 'xml'
- } else {
- var nss = this.getXmlns()
- prefix = nss[ns] || ''
- }
- if (prefix) {
- this.attr([prefix, name].join(':'), null)
- }
+ var prefix
+ if (ns === 'http://www.w3.org/XML/1998/namespace') {
+ prefix = 'xml'
+ } else {
+ var nss = this.getXmlns()
+ prefix = nss[ns] || ''
+ }
+ if (prefix) {
+ this.attr([prefix, name].join(':'), null)
+ }
}
DOMElement.prototype.appendChild = function (el) {
- this.cnode(el)
+ this.cnode(el)
}
DOMElement.prototype.removeChild = function (el) {
- this.remove(el)
+ this.remove(el)
}
-DOMElement.createElement = function(name, attrs /*, child1, child2, ...*/) {
- var el = new DOMElement(name, attrs)
+DOMElement.createElement = function (name, attrs /*, child1, child2, ...*/) {
+ var el = new DOMElement(name, attrs)
- var children = Array.prototype.slice.call(arguments, 2)
+ var children = Array.prototype.slice.call(arguments, 2)
- children.forEach(function(child) {
- el.appendChild(child)
- })
- return el
+ children.forEach(function (child) {
+ el.appendChild(child)
+ })
+ return el
}
module.exports = DOMElement
diff --git a/lib/Element.js b/lib/Element.js
index 62328d4..f410380 100644
--- a/lib/Element.js
+++ b/lib/Element.js
@@ -10,193 +10,196 @@ var escapeXMLText = escape.escapeXMLText
* Attributes are in the element.attrs object. Children is a list of
* either other Elements or Strings for text content.
**/
-function Element(name, attrs) {
- this.name = name
- this.parent = null
- this.children = []
- this.setAttrs(attrs)
+function Element (name, attrs) {
+ this.name = name
+ this.parent = null
+ this.children = []
+ this.setAttrs(attrs)
}
-/*** Accessors ***/
+/* Accessors */
/**
* if (element.is('message', 'jabber:client')) ...
**/
-Element.prototype.is = function(name, xmlns) {
- return (this.getName() === name) &&
- (!xmlns || (this.getNS() === xmlns))
+Element.prototype.is = function (name, xmlns) {
+ return (this.getName() === name) &&
+ (!xmlns || (this.getNS() === xmlns))
}
/* without prefix */
-Element.prototype.getName = function() {
- if (this.name.indexOf(':') >= 0) {
- return this.name.substr(this.name.indexOf(':') + 1)
- } else {
- return this.name
- }
+Element.prototype.getName = function () {
+ if (this.name.indexOf(':') >= 0) {
+ return this.name.substr(this.name.indexOf(':') + 1)
+ } else {
+ return this.name
+ }
}
/**
* retrieves the namespace of the current element, upwards recursively
**/
-Element.prototype.getNS = function() {
- if (this.name.indexOf(':') >= 0) {
- var prefix = this.name.substr(0, this.name.indexOf(':'))
- return this.findNS(prefix)
- }
- return this.findNS()
+Element.prototype.getNS = function () {
+ if (this.name.indexOf(':') >= 0) {
+ var prefix = this.name.substr(0, this.name.indexOf(':'))
+ return this.findNS(prefix)
+ }
+ return this.findNS()
}
/**
* find the namespace to the given prefix, upwards recursively
**/
-Element.prototype.findNS = function(prefix) {
- if (!prefix) {
- /* default namespace */
- if (this.attrs.xmlns) {
- return this.attrs.xmlns
- } else if (this.parent) {
- return this.parent.findNS()
- }
- } else {
- /* prefixed namespace */
- var attr = 'xmlns:' + prefix
- if (this.attrs[attr]) {
- return this.attrs[attr]
- } else if (this.parent) {
- return this.parent.findNS(prefix)
- }
+Element.prototype.findNS = function (prefix) {
+ if (!prefix) {
+ /* default namespace */
+ if (this.attrs.xmlns) {
+ return this.attrs.xmlns
+ } else if (this.parent) {
+ return this.parent.findNS()
}
+ } else {
+ /* prefixed namespace */
+ var attr = 'xmlns:' + prefix
+ if (this.attrs[attr]) {
+ return this.attrs[attr]
+ } else if (this.parent) {
+ return this.parent.findNS(prefix)
+ }
+ }
}
/**
* Recursiverly gets all xmlns defined, in the form of {url:prefix}
**/
-Element.prototype.getXmlns = function() {
- var namespaces = {}
+Element.prototype.getXmlns = function () {
+ var namespaces = {}
- if (this.parent) {
- namespaces = this.parent.getXmlns()
- }
+ if (this.parent) {
+ namespaces = this.parent.getXmlns()
+ }
- for (var attr in this.attrs) {
- var m = attr.match('xmlns:?(.*)')
- if (this.attrs.hasOwnProperty(attr) && m) {
- namespaces[this.attrs[attr]] = m[1]
- }
+ for (var attr in this.attrs) {
+ var m = attr.match('xmlns:?(.*)')
+ if (this.attrs.hasOwnProperty(attr) && m) {
+ namespaces[this.attrs[attr]] = m[1]
}
- return namespaces
+ }
+ return namespaces
}
-Element.prototype.setAttrs = function(attrs) {
- this.attrs = {}
+Element.prototype.setAttrs = function (attrs) {
+ this.attrs = {}
- if (typeof attrs === 'string')
- this.attrs.xmlns = attrs
- else if (attrs) {
- Object.keys(attrs).forEach(function(key) {
- this.attrs[key] = attrs[key]
- }, this)
- }
+ if (typeof attrs === 'string') {
+ this.attrs.xmlns = attrs
+ } else if (attrs) {
+ Object.keys(attrs).forEach(function (key) {
+ this.attrs[key] = attrs[key]
+ }, this)
+ }
}
/**
* xmlns can be null, returns the matching attribute.
**/
-Element.prototype.getAttr = function(name, xmlns) {
- if (!xmlns) {
- return this.attrs[name]
- }
+Element.prototype.getAttr = function (name, xmlns) {
+ if (!xmlns) {
+ return this.attrs[name]
+ }
- var namespaces = this.getXmlns()
+ var namespaces = this.getXmlns()
- if (!namespaces[xmlns]) {
- return null
- }
+ if (!namespaces[xmlns]) {
+ return null
+ }
- return this.attrs[[namespaces[xmlns], name].join(':')]
+ return this.attrs[[namespaces[xmlns], name].join(':')]
}
/**
* xmlns can be null
**/
-Element.prototype.getChild = function(name, xmlns) {
- return this.getChildren(name, xmlns)[0]
+Element.prototype.getChild = function (name, xmlns) {
+ return this.getChildren(name, xmlns)[0]
}
/**
* xmlns can be null
**/
-Element.prototype.getChildren = function(name, xmlns) {
- var result = []
- for (var i = 0; i < this.children.length; i++) {
- var child = this.children[i]
- if (child.getName &&
- (child.getName() === name) &&
- (!xmlns || (child.getNS() === xmlns)))
- result.push(child)
+Element.prototype.getChildren = function (name, xmlns) {
+ var result = []
+ for (var i = 0; i < this.children.length; i++) {
+ var child = this.children[i]
+ if (child.getName &&
+ (child.getName() === name) &&
+ (!xmlns || (child.getNS() === xmlns))) {
+ result.push(child)
}
- return result
+ }
+ return result
}
/**
* xmlns and recursive can be null
**/
-Element.prototype.getChildByAttr = function(attr, val, xmlns, recursive) {
- return this.getChildrenByAttr(attr, val, xmlns, recursive)[0]
+Element.prototype.getChildByAttr = function (attr, val, xmlns, recursive) {
+ return this.getChildrenByAttr(attr, val, xmlns, recursive)[0]
}
/**
* xmlns and recursive can be null
**/
-Element.prototype.getChildrenByAttr = function(attr, val, xmlns, recursive) {
- var result = []
- for (var i = 0; i < this.children.length; i++) {
- var child = this.children[i]
- if (child.attrs &&
- (child.attrs[attr] === val) &&
- (!xmlns || (child.getNS() === xmlns)))
- result.push(child)
- if (recursive && child.getChildrenByAttr) {
- result.push(child.getChildrenByAttr(attr, val, xmlns, true))
- }
+Element.prototype.getChildrenByAttr = function (attr, val, xmlns, recursive) {
+ var result = []
+ for (var i = 0; i < this.children.length; i++) {
+ var child = this.children[i]
+ if (child.attrs &&
+ (child.attrs[attr] === val) &&
+ (!xmlns || (child.getNS() === xmlns))) {
+ result.push(child)
}
- if (recursive) {
- result = [].concat.apply([], result)
+ if (recursive && child.getChildrenByAttr) {
+ result.push(child.getChildrenByAttr(attr, val, xmlns, true))
}
- return result
+ }
+ if (recursive) {
+ result = [].concat.apply([], result)
+ }
+ return result
}
-Element.prototype.getChildrenByFilter = function(filter, recursive) {
- var result = []
- for (var i = 0; i < this.children.length; i++) {
- var child = this.children[i]
- if (filter(child))
- result.push(child)
- if (recursive && child.getChildrenByFilter){
- result.push(child.getChildrenByFilter(filter, true))
- }
+Element.prototype.getChildrenByFilter = function (filter, recursive) {
+ var result = []
+ for (var i = 0; i < this.children.length; i++) {
+ var child = this.children[i]
+ if (filter(child)) {
+ result.push(child)
}
- if (recursive) {
- result = [].concat.apply([], result)
+ if (recursive && child.getChildrenByFilter) {
+ result.push(child.getChildrenByFilter(filter, true))
}
- return result
+ }
+ if (recursive) {
+ result = [].concat.apply([], result)
+ }
+ return result
}
-Element.prototype.getText = function() {
- var text = ''
- for (var i = 0; i < this.children.length; i++) {
- var child = this.children[i]
- if ((typeof child === 'string') || (typeof child === 'number')) {
- text += child
- }
+Element.prototype.getText = function () {
+ var text = ''
+ for (var i = 0; i < this.children.length; i++) {
+ var child = this.children[i]
+ if ((typeof child === 'string') || (typeof child === 'number')) {
+ text += child
}
- return text
+ }
+ return text
}
-Element.prototype.getChildText = function(name, xmlns) {
- var child = this.getChild(name, xmlns)
- return child ? child.getText() : null
+Element.prototype.getChildText = function (name, xmlns) {
+ var child = this.getChild(name, xmlns)
+ return child ? child.getText() : null
}
/**
@@ -204,80 +207,80 @@ Element.prototype.getChildText = function(name, xmlns) {
* This differs from `getChildren` in that it will exclude text nodes,
* processing instructions, etc.
*/
-Element.prototype.getChildElements = function() {
- return this.getChildrenByFilter(function(child) {
- return child instanceof Element
- })
+Element.prototype.getChildElements = function () {
+ return this.getChildrenByFilter(function (child) {
+ return child instanceof Element
+ })
}
-/*** Builder ***/
+/* Builder */
/** returns uppermost parent */
-Element.prototype.root = function() {
- if (this.parent) {
- return this.parent.root()
- }
- return this
+Element.prototype.root = function () {
+ if (this.parent) {
+ return this.parent.root()
+ }
+ return this
}
Element.prototype.tree = Element.prototype.root
/** just parent or itself */
-Element.prototype.up = function() {
- if (this.parent) {
- return this.parent
- }
- return this
+Element.prototype.up = function () {
+ if (this.parent) {
+ return this.parent
+ }
+ return this
}
-Element.prototype._getElement = function(name, attrs) {
- var element = new Element(name, attrs)
- return element
+Element.prototype._getElement = function (name, attrs) {
+ var element = new Element(name, attrs)
+ return element
}
/** create child node and return it */
-Element.prototype.c = function(name, attrs) {
- return this.cnode(this._getElement(name, attrs))
+Element.prototype.c = function (name, attrs) {
+ return this.cnode(this._getElement(name, attrs))
}
-Element.prototype.cnode = function(child) {
- this.children.push(child)
- if (typeof child === 'object') {
- child.parent = this
- }
- return child
+Element.prototype.cnode = function (child) {
+ this.children.push(child)
+ if (typeof child === 'object') {
+ child.parent = this
+ }
+ return child
}
/** add text node and return element */
-Element.prototype.t = function(text) {
- this.children.push(text)
- return this
+Element.prototype.t = function (text) {
+ this.children.push(text)
+ return this
}
-/*** Manipulation ***/
+/* Manipulation */
/**
* Either:
* el.remove(childEl)
* el.remove('author', 'urn:...')
*/
-Element.prototype.remove = function(el, xmlns) {
- var filter
- if (typeof el === 'string') {
- /* 1st parameter is tag name */
- filter = function(child) {
- return !(child.is &&
- child.is(el, xmlns))
- }
- } else {
- /* 1st parameter is element */
- filter = function(child) {
- return child !== el
- }
+Element.prototype.remove = function (el, xmlns) {
+ var filter
+ if (typeof el === 'string') {
+ /* 1st parameter is tag name */
+ filter = function (child) {
+ return !(child.is &&
+ child.is(el, xmlns))
+ }
+ } else {
+ /* 1st parameter is element */
+ filter = function (child) {
+ return child !== el
}
+ }
- this.children = this.children.filter(filter)
+ this.children = this.children.filter(filter)
- return this
+ return this
}
/**
@@ -285,106 +288,106 @@ Element.prototype.remove = function(el, xmlns) {
* Please refrain from this practise unless you know what you are
* doing. Building XML with ltx is easy!
*/
-Element.prototype.clone = function() {
- var clone = this._getElement(this.name, this.attrs)
- for (var i = 0; i < this.children.length; i++) {
- var child = this.children[i]
- clone.cnode(child.clone ? child.clone() : child)
- }
- return clone
+Element.prototype.clone = function () {
+ var clone = this._getElement(this.name, this.attrs)
+ for (var i = 0; i < this.children.length; i++) {
+ var child = this.children[i]
+ clone.cnode(child.clone ? child.clone() : child)
+ }
+ return clone
}
-Element.prototype.text = function(val) {
- if (val && this.children.length === 1) {
- this.children[0] = val
- return this
- }
- return this.getText()
+Element.prototype.text = function (val) {
+ if (val && this.children.length === 1) {
+ this.children[0] = val
+ return this
+ }
+ return this.getText()
}
-Element.prototype.attr = function(attr, val) {
- if (((typeof val !== 'undefined') || (val === null))) {
- if (!this.attrs) {
- this.attrs = {}
- }
- this.attrs[attr] = val
- return this
+Element.prototype.attr = function (attr, val) {
+ if (typeof val !== 'undefined' || val === null) {
+ if (!this.attrs) {
+ this.attrs = {}
}
- return this.attrs[attr]
+ this.attrs[attr] = val
+ return this
+ }
+ return this.attrs[attr]
}
-/*** Serialization ***/
+/* Serialization */
-Element.prototype.toString = function() {
- var s = ''
- this.write(function(c) {
- s += c
- })
- return s
+Element.prototype.toString = function () {
+ var s = ''
+ this.write(function (c) {
+ s += c
+ })
+ return s
}
-Element.prototype.toJSON = function() {
- return {
- name: this.name,
- attrs: this.attrs,
- children: this.children.map(function(child) {
- return child && child.toJSON ? child.toJSON() : child
- })
- }
+Element.prototype.toJSON = function () {
+ return {
+ name: this.name,
+ attrs: this.attrs,
+ children: this.children.map(function (child) {
+ return child && child.toJSON ? child.toJSON() : child
+ })
+ }
}
-Element.prototype._addChildren = function(writer) {
- writer('>')
- for (var i = 0; i < this.children.length; i++) {
- var child = this.children[i]
- /* Skip null/undefined */
- if (child || (child === 0)) {
- if (child.write) {
- child.write(writer)
- } else if (typeof child === 'string') {
- writer(escapeXMLText(child))
- } else if (child.toString) {
- writer(escapeXMLText(child.toString(10)))
- }
- }
+Element.prototype._addChildren = function (writer) {
+ writer('>')
+ for (var i = 0; i < this.children.length; i++) {
+ var child = this.children[i]
+ /* Skip null/undefined */
+ if (child || (child === 0)) {
+ if (child.write) {
+ child.write(writer)
+ } else if (typeof child === 'string') {
+ writer(escapeXMLText(child))
+ } else if (child.toString) {
+ writer(escapeXMLText(child.toString(10)))
+ }
}
- writer('</')
- writer(this.name)
- writer('>')
+ }
+ writer('</')
+ writer(this.name)
+ writer('>')
}
-Element.prototype.write = function(writer) {
- writer('<')
- writer(this.name)
- for (var k in this.attrs) {
- var v = this.attrs[k]
- if (v || (v === '') || (v === 0)) {
- writer(' ')
- writer(k)
- writer('="')
- if (typeof v !== 'string') {
- v = v.toString(10)
- }
- writer(escapeXML(v))
- writer('"')
- }
- }
- if (this.children.length === 0) {
- writer('/>')
- } else {
- this._addChildren(writer)
+Element.prototype.write = function (writer) {
+ writer('<')
+ writer(this.name)
+ for (var k in this.attrs) {
+ var v = this.attrs[k]
+ if (v || (v === '') || (v === 0)) {
+ writer(' ')
+ writer(k)
+ writer('="')
+ if (typeof v !== 'string') {
+ v = v.toString(10)
+ }
+ writer(escapeXML(v))
+ writer('"')
}
+ }
+ if (this.children.length === 0) {
+ writer('/>')
+ } else {
+ this._addChildren(writer)
+ }
}
-Element.createElement = function(name, attrs /*, child1, child2, ...*/) {
- var el = new Element(name, attrs)
+Element.createElement = function (name, attrs /*, child1, child2, ...*/) {
+ var el = new Element(name, attrs)
- var children = Array.prototype.slice.call(arguments, 2)
+ var children = Array.prototype.slice.call(arguments, 2)
- children.forEach(function(child) {
- el.cnode(child)
- })
- return el
+ children.forEach(function (child) {
+ el.cnode(child)
+ })
+ return el
}
module.exports = Element
diff --git a/lib/Parser.js b/lib/Parser.js
index 908c555..e9a0f78 100644
--- a/lib/Parser.js
+++ b/lib/Parser.js
@@ -5,65 +5,63 @@ var inherits = require('inherits')
var Element = require('./Element')
var LtxParser = require('./parsers/ltx')
-var Parser = function(options) {
- EventEmitter.call(this)
+var Parser = function (options) {
+ EventEmitter.call(this)
- var ParserInterface = this.Parser = (options && options.Parser) || LtxParser
- var ElementInterface = this.Element = (options && options.Element) || Element
+ var ParserInterface = this.Parser = (options && options.Parser) || LtxParser
+ var ElementInterface = this.Element = (options && options.Element) || Element
- this.parser = new ParserInterface()
+ this.parser = new ParserInterface()
- var el
- , self = this
- this.parser.on('startElement', function(name, attrs) {
- var child = new ElementInterface(name, attrs)
- if (!el) {
- el = child
- } else {
- el = el.cnode(child)
- }
- })
- this.parser.on('endElement', function(name) {
- /* jshint -W035 */
- if (!el) {
- /* Err */
- } else if (name === el.name) {
- if (el.parent) {
- el = el.parent
- } else if (!self.tree) {
- self.tree = el
- el = undefined
- }
- }
- /* jshint +W035 */
- })
- this.parser.on('text', function(str) {
- if (el) {
- el.t(str)
- }
- })
- this.parser.on('error', function(e) {
- self.error = e
- self.emit('error', e)
- })
+ var el
+ var self = this
+ this.parser.on('startElement', function (name, attrs) {
+ var child = new ElementInterface(name, attrs)
+ if (!el) {
+ el = child
+ } else {
+ el = el.cnode(child)
+ }
+ })
+ this.parser.on('endElement', function (name) {
+ if (!el) {
+ /* Err */
+ } else if (name === el.name) {
+ if (el.parent) {
+ el = el.parent
+ } else if (!self.tree) {
+ self.tree = el
+ el = undefined
+ }
+ }
+ })
+ this.parser.on('text', function (str) {
+ if (el) {
+ el.t(str)
+ }
+ })
+ this.parser.on('error', function (e) {
+ self.error = e
+ self.emit('error', e)
+ })
}
inherits(Parser, EventEmitter)
-Parser.prototype.write = function(data) {
- this.parser.write(data)
+Parser.prototype.write = function (data) {
+ this.parser.write(data)
}
-Parser.prototype.end = function(data) {
- this.parser.end(data)
+Parser.prototype.end = function (data) {
+ this.parser.end(data)
- if (!this.error) {
- if (this.tree) {
- this.emit('tree', this.tree)
- } else {
- this.emit('error', new Error('Incomplete document'))
- }
+ if (!this.error) {
+ if (this.tree) {
+ this.emit('tree', this.tree)
+ } else {
+ this.emit('error', new Error('Incomplete document'))
}
+ }
}
module.exports = Parser
diff --git a/lib/escape.js b/lib/escape.js
index f0b4d3e..26a4589 100644
--- a/lib/escape.js
+++ b/lib/escape.js
@@ -1,17 +1,9 @@
'use strict'
-module.exports.escapeXML = function escapeXML(s) {
- return s.
- replace(/\&/g, '&').
- replace(/</g, '<').
- replace(/>/g, '>').
- replace(/"/g, '"').
- replace(/"/g, ''')
+module.exports.escapeXML = function escapeXML (s) {
+ return s.replace(/\&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/"/g, ''')
}
-module.exports.escapeXMLText = function escapeXMLText(s) {
- return s.
- replace(/\&/g, '&').
- replace(/</g, '<').
- replace(/>/g, '>')
+module.exports.escapeXMLText = function escapeXMLText (s) {
+ return s.replace(/\&/g, '&').replace(/</g, '<').replace(/>/g, '>')
}
diff --git a/lib/parse.js b/lib/parse.js
index bbb0243..216ed2a 100644
--- a/lib/parse.js
+++ b/lib/parse.js
@@ -2,24 +2,24 @@
var Parser = require('./Parser')
-module.exports = function parse(data, options) {
- var p = new Parser(options)
- var result = null
- , error = null
+module.exports = function parse (data, options) {
+ var p = new Parser(options)
+ var result = null
+ var error = null
- p.on('tree', function(tree) {
- result = tree
- })
- p.on('error', function(e) {
- error = e
- })
+ p.on('tree', function (tree) {
+ result = tree
+ })
+ p.on('error', function (e) {
+ error = e
+ })
- p.write(data)
- p.end()
+ p.write(data)
+ p.end()
- if (error) {
- throw error
- } else {
- return result
- }
+ if (error) {
+ throw error
+ } else {
+ return result
+ }
}
diff --git a/lib/parsers/easysax.js b/lib/parsers/easysax.js
index b02d346..fa3ab63 100644
--- a/lib/parsers/easysax.js
+++ b/lib/parsers/easysax.js
@@ -1,8 +1,8 @@
'use strict'
var inherits = require('inherits')
- , EventEmitter = require('events').EventEmitter
- , Easysax = require('easysax')
+var EventEmitter = require('events').EventEmitter
+var Easysax = require('easysax')
/**
* FIXME: This SAX parser cannot be pushed to!
@@ -10,51 +10,49 @@ var inherits = require('inherits')
module.exports = SaxEasysax
inherits(SaxEasysax, EventEmitter)
+function SaxEasysax () {
+ EventEmitter.call(this)
+ this.parser = new Easysax()
-function SaxEasysax() {
- EventEmitter.call(this)
- this.parser = new Easysax()
-
- var self = this
-
- this.parser.on('startNode', function(name, attr, uq) {
- attr = attr()
-
- if (attr === false) {
- self.emit('error', 'attr char')
- return false
- }
-
- for(var k in attr) {
- attr[k] = uq(attr[k])
- }
-
- self.emit('startElement', name, attr)
- })
- /* jshint -W098 */
- this.parser.on('endNode', function(name) {
- self.emit('endElement', name)
- })
- this.parser.on('textNode', function(str, uq) {
- self.emit('text', uq(str))
- })
- this.parser.on('cdata', function(str) {
- self.emit('text', str)
- })
- this.parser.on('error', function(e) {
- self.emit('error', e)
- })
- // TODO: other events, esp. entityDecl (billion laughs!)
-
- var sbuffer = ''
-
- this.write = function(data) {
- sbuffer += typeof data !== 'string' ? data.toString() : data
+ var self = this
+
+ this.parser.on('startNode', function (name, attr, uq) {
+ attr = attr()
+
+ if (attr === false) {
+ self.emit('error', 'attr char')
+ return false
}
- this.end = function(data) {
- sbuffer += typeof data !== 'string' ? data.toString() : data
- this.parser(sbuffer)
- sbuffer = ''
+ for (var k in attr) {
+ attr[k] = uq(attr[k])
}
+
+ self.emit('startElement', name, attr)
+ })
+ this.parser.on('endNode', function (name) {
+ self.emit('endElement', name)
+ })
+ this.parser.on('textNode', function (str, uq) {
+ self.emit('text', uq(str))
+ })
+ this.parser.on('cdata', function (str) {
+ self.emit('text', str)
+ })
+ this.parser.on('error', function (e) {
+ self.emit('error', e)
+ })
+ // TODO: other events, esp. entityDecl (billion laughs!)
+
+ var sbuffer = ''
+
+ this.write = function (data) {
+ sbuffer += typeof data !== 'string' ? data.toString() : data
+ }
+
+ this.end = function (data) {
+ sbuffer += typeof data !== 'string' ? data.toString() : data
+ this.parser(sbuffer)
+ sbuffer = ''
+ }
}
diff --git a/lib/parsers/index.js b/lib/parsers/index.js
index 650e247..694da5f 100644
--- a/lib/parsers/index.js
+++ b/lib/parsers/index.js
@@ -1,11 +1,11 @@
'use strict'
module.exports = [
- // 'easysax',
- 'ltx',
- 'node-expat',
- 'node-xml',
- 'sax'
-].map(function(name) {
- return require('./' + name)
+ // 'easysax',
+ 'ltx',
+ 'node-expat',
+ 'node-xml',
+ 'sax'
+].map(function (name) {
+ return require('./' + name)
})
diff --git a/lib/parsers/ltx.js b/lib/parsers/ltx.js
index e392e33..c0b891a 100644
--- a/lib/parsers/ltx.js
+++ b/lib/parsers/ltx.js
@@ -1,170 +1,172 @@
'use strict'
var inherits = require('inherits')
- , EventEmitter = require('events').EventEmitter
-
-var STATE_TEXT = 0,
- STATE_IGNORE_TAG = 1,
- STATE_TAG_NAME = 2,
- STATE_TAG = 3,
- STATE_ATTR_NAME = 4,
- STATE_ATTR_EQ = 5,
- STATE_ATTR_QUOT = 6,
- STATE_ATTR_VALUE = 7
-
-var SaxLtx = module.exports = function SaxLtx() {
- EventEmitter.call(this)
-
- var state = STATE_TEXT, remainder
- var tagName, attrs, endTag, selfClosing, attrQuote
- var recordStart = 0
- var attrName
-
- this._handleTagOpening = function(endTag, tagName, attrs) {
- if (!endTag) {
- this.emit('startElement', tagName, attrs)
- if (selfClosing) {
- this.emit('endElement', tagName)
- }
- } else {
- this.emit('endElement', tagName)
- }
+var EventEmitter = require('events').EventEmitter
+
+var STATE_TEXT = 0
+var STATE_IGNORE_TAG = 1
+var STATE_TAG_NAME = 2
+var STATE_TAG = 3
+var STATE_ATTR_NAME = 4
+var STATE_ATTR_EQ = 5
+var STATE_ATTR_QUOT = 6
+var STATE_ATTR_VALUE = 7
+
+var SaxLtx = module.exports = function SaxLtx () {
+ EventEmitter.call(this)
+
+ var state = STATE_TEXT
+ var remainder
+ var tagName
+ var attrs
+ var endTag
+ var selfClosing
+ var attrQuote
+ var recordStart = 0
+ var attrName
+
+ this._handleTagOpening = function (endTag, tagName, attrs) {
+ if (!endTag) {
+ this.emit('startElement', tagName, attrs)
+ if (selfClosing) {
+ this.emit('endElement', tagName)
+ }
+ } else {
+ this.emit('endElement', tagName)
}
+ }
- this.write = function(data) {
- /* jshint -W071 */
- /* jshint -W074 */
- if (typeof data !== 'string') {
- data = data.toString()
- }
- var pos = 0
+ this.write = function (data) {
+ if (typeof data !== 'string') {
+ data = data.toString()
+ }
+ var pos = 0
- /* Anything from previous write()? */
- if (remainder) {
- data = remainder + data
- pos += remainder.length
- remainder = null
- }
+ /* Anything from previous write()? */
+ if (remainder) {
+ data = remainder + data
+ pos += remainder.length
+ remainder = null
+ }
- function endRecording() {
- if (typeof recordStart === 'number') {
- var recorded = data.slice(recordStart, pos)
- recordStart = undefined
- return recorded
- }
- }
+ function endRecording () {
+ if (typeof recordStart === 'number') {
+ var recorded = data.slice(recordStart, pos)
+ recordStart = undefined
+ return recorded
+ }
+ }
- for(; pos < data.length; pos++) {
- var c = data.charCodeAt(pos)
- //console.log("state", state, "c", c, data[pos])
- switch(state) {
- case STATE_TEXT:
- if (c === 60 /* < */) {
- var text = endRecording()
- if (text) {
- this.emit('text', unescapeXml(text))
- }
- state = STATE_TAG_NAME
- recordStart = pos + 1
- attrs = {}
- }
- break
- case STATE_TAG_NAME:
- if (c === 47 /* / */ && recordStart === pos) {
- recordStart = pos + 1
- endTag = true
- } else if (c === 33 /* ! */ || c === 63 /* ? */) {
- recordStart = undefined
- state = STATE_IGNORE_TAG
- } else if (c <= 32 || c === 47 /* / */ || c === 62 /* > */) {
- tagName = endRecording()
- pos--
- state = STATE_TAG
- }
- break
- case STATE_IGNORE_TAG:
- if (c === 62 /* > */) {
- state = STATE_TEXT
- }
- break
- case STATE_TAG:
- if (c === 62 /* > */) {
- this._handleTagOpening(endTag, tagName, attrs)
- tagName = undefined
- attrs = undefined
- endTag = undefined
- selfClosing = undefined
- state = STATE_TEXT
- recordStart = pos + 1
- } else if (c === 47 /* / */) {
- selfClosing = true
- } else if (c > 32) {
- recordStart = pos
- state = STATE_ATTR_NAME
- }
- break
- case STATE_ATTR_NAME:
- if (c <= 32 || c === 61 /* = */) {
- attrName = endRecording()
- pos--
- state = STATE_ATTR_EQ
- }
- break
- case STATE_ATTR_EQ:
- if (c === 61 /* = */) {
- state = STATE_ATTR_QUOT
- }
- break
- case STATE_ATTR_QUOT:
- if (c === 34 /* " */ || c === 39 /* ' */) {
- attrQuote = c
- state = STATE_ATTR_VALUE
- recordStart = pos + 1
- }
- break
- case STATE_ATTR_VALUE:
- if (c === attrQuote) {
- var value = unescapeXml(endRecording())
- attrs[attrName] = value
- attrName = undefined
- state = STATE_TAG
- }
- break
+ for (; pos < data.length; pos++) {
+ var c = data.charCodeAt(pos)
+ // console.log("state", state, "c", c, data[pos])
+ switch (state) {
+ case STATE_TEXT:
+ if (c === 60 /* < */) {
+ var text = endRecording()
+ if (text) {
+ this.emit('text', unescapeXml(text))
}
- }
-
- if (typeof recordStart === 'number' &&
- recordStart <= data.length) {
-
- remainder = data.slice(recordStart)
- recordStart = 0
- }
+ state = STATE_TAG_NAME
+ recordStart = pos + 1
+ attrs = {}
+ }
+ break
+ case STATE_TAG_NAME:
+ if (c === 47 /* / */ && recordStart === pos) {
+ recordStart = pos + 1
+ endTag = true
+ } else if (c === 33 /* ! */ || c === 63 /* ? */) {
+ recordStart = undefined
+ state = STATE_IGNORE_TAG
+ } else if (c <= 32 || c === 47 /* / */ || c === 62 /* > */) {
+ tagName = endRecording()
+ pos--
+ state = STATE_TAG
+ }
+ break
+ case STATE_IGNORE_TAG:
+ if (c === 62 /* > */) {
+ state = STATE_TEXT
+ }
+ break
+ case STATE_TAG:
+ if (c === 62 /* > */) {
+ this._handleTagOpening(endTag, tagName, attrs)
+ tagName = undefined
+ attrs = undefined
+ endTag = undefined
+ selfClosing = undefined
+ state = STATE_TEXT
+ recordStart = pos + 1
+ } else if (c === 47 /* / */) {
+ selfClosing = true
+ } else if (c > 32) {
+ recordStart = pos
+ state = STATE_ATTR_NAME
+ }
+ break
+ case STATE_ATTR_NAME:
+ if (c <= 32 || c === 61 /* = */) {
+ attrName = endRecording()
+ pos--
+ state = STATE_ATTR_EQ
+ }
+ break
+ case STATE_ATTR_EQ:
+ if (c === 61 /* = */) {
+ state = STATE_ATTR_QUOT
+ }
+ break
+ case STATE_ATTR_QUOT:
+ if (c === 34 /* " */ || c === 39 /* ' */) {
+ attrQuote = c
+ state = STATE_ATTR_VALUE
+ recordStart = pos + 1
+ }
+ break
+ case STATE_ATTR_VALUE:
+ if (c === attrQuote) {
+ var value = unescapeXml(endRecording())
+ attrs[attrName] = value
+ attrName = undefined
+ state = STATE_TAG
+ }
+ break
+ }
}
- /*var origEmit = this.emit
- this.emit = function() {
+ if (typeof recordStart === 'number' &&
+ recordStart <= data.length) {
+ remainder = data.slice(recordStart)
+ recordStart = 0
+ }
+ }
+ /*
+ var origEmit = this.emit
+ this.emit = function() {
console.log('ltx', arguments)
origEmit.apply(this, arguments)
- }*/
+ }
+ */
}
inherits(SaxLtx, EventEmitter)
+SaxLtx.prototype.end = function (data) {
+ if (data) {
+ this.write(data)
+ }
-SaxLtx.prototype.end = function(data) {
- if (data) {
- this.write(data)
- }
-
- /* Uh, yeah */
- this.write = function() {}
+ /* Uh, yeah */
+ this.write = function () {}
}
-function unescapeXml(s) {
- return s.
- replace(/\&(amp|#38);/g, '&').
- replace(/\&(lt|#60);/g, '<').
- replace(/\&(gt|#62);/g, '>').
- replace(/\&(quot|#34);/g, '"').
- replace(/\&(apos|#39);/g, '\'').
- replace(/\&(nbsp|#160);/g, '\n')
+function unescapeXml (s) {
+ return s
+ .replace(/\&(amp|#38);/g, '&')
+ .replace(/\&(lt|#60);/g, '<')
+ .replace(/\&(gt|#62);/g, '>')
+ .replace(/\&(quot|#34);/g, '"')
+ .replace(/\&(apos|#39);/g, "'")
+ .replace(/\&(nbsp|#160);/g, '\n')
}
diff --git a/lib/parsers/node-expat.js b/lib/parsers/node-expat.js
index 2d9448a..4153590 100644
--- a/lib/parsers/node-expat.js
+++ b/lib/parsers/node-expat.js
@@ -1,43 +1,43 @@
'use strict'
var inherits = require('inherits')
- , EventEmitter = require('events').EventEmitter
- , expat = require('node-expat')
+var EventEmitter = require('events').EventEmitter
+var expat = require('node-expat')
-var SaxExpat = module.exports = function SaxExpat() {
- EventEmitter.call(this)
- this.parser = new expat.Parser('UTF-8')
+var SaxExpat = module.exports = function SaxExpat () {
+ EventEmitter.call(this)
+ this.parser = new expat.Parser('UTF-8')
- var that = this
- this.parser.on('startElement', function(name, attrs) {
- that.emit('startElement', name, attrs)
- })
- this.parser.on('endElement', function(name) {
- that.emit('endElement', name)
- })
- this.parser.on('text', function(str) {
- that.emit('text', str)
- })
- // TODO: other events, esp. entityDecl (billion laughs!)
+ var that = this
+ this.parser.on('startElement', function (name, attrs) {
+ that.emit('startElement', name, attrs)
+ })
+ this.parser.on('endElement', function (name) {
+ that.emit('endElement', name)
+ })
+ this.parser.on('text', function (str) {
+ that.emit('text', str)
+ })
+// TODO: other events, esp. entityDecl (billion laughs!)
}
inherits(SaxExpat, EventEmitter)
-SaxExpat.prototype.write = function(data) {
- if (!this.parser.parse(data, false)) {
- this.emit('error', new Error(this.parser.getError()))
+SaxExpat.prototype.write = function (data) {
+ if (!this.parser.parse(data, false)) {
+ this.emit('error', new Error(this.parser.getError()))
- // Premature error thrown,
- // disable all functionality:
- this.write = function() { }
- this.end = function() { }
- }
+ // Premature error thrown,
+ // disable all functionality:
+ this.write = function () {}
+ this.end = function () {}
+ }
}
-SaxExpat.prototype.end = function() {
- if (!this.parser.parse('', true)) {
- this.emit('error', new Error(this.parser.getError()))
- } else {
- this.emit('end')
- }
+SaxExpat.prototype.end = function () {
+ if (!this.parser.parse('', true)) {
+ this.emit('error', new Error(this.parser.getError()))
+ } else {
+ this.emit('end')
+ }
}
diff --git a/lib/parsers/node-xml.js b/lib/parsers/node-xml.js
index 5c68ee5..cb5b9e3 100644
--- a/lib/parsers/node-xml.js
+++ b/lib/parsers/node-xml.js
@@ -1,70 +1,65 @@
'use strict'
var inherits = require('inherits')
- , EventEmitter = require('events').EventEmitter
- , xml = require('node-xml')
+var EventEmitter = require('events').EventEmitter
+var xml = require('node-xml')
/**
* This cannot be used as long as node-xml starts parsing only after
* setTimeout(f, 0)
*/
-var SaxNodeXML = module.exports = function SaxNodeXML() {
- EventEmitter.call(this)
- var self = this
- this.parser = new xml.SaxParser(function(handler) {
- /* jshint -W072 */
- handler.onStartElementNS(function(elem, attrs, prefix, uri, namespaces) {
- var i, attrsHash = {}
- if (prefix) {
- elem = prefix + ':' + elem
- }
- for (i = 0; i < attrs.length; i++) {
- var attr = attrs[i]
- attrsHash[attr[0]] = unescapeXml(attr[1])
- }
- for(i = 0; i < namespaces.length; i++) {
- var namespace = namespaces[i]
- var k = !namespace[0] ? 'xmlns' : 'xmlns:' + namespace[0]
- attrsHash[k] = unescapeXml(namespace[1])
- }
- self.emit('startElement', elem, attrsHash)
- })
- handler.onEndElementNS(function(elem, prefix) {
- if (prefix) {
- elem = prefix + ':' + elem
- }
- self.emit('endElement', elem)
- })
- handler.onCharacters(function(str) {
- self.emit('text', str)
- })
- handler.onCdata(function(str) {
- self.emit('text', str)
- })
- handler.onError(function(e) {
- self.emit('error', e)
- })
- // TODO: other events, esp. entityDecl (billion laughs!)
+var SaxNodeXML = module.exports = function SaxNodeXML () {
+ EventEmitter.call(this)
+ var self = this
+ this.parser = new xml.SaxParser(function (handler) {
+ handler.onStartElementNS(function (elem, attrs, prefix, uri, namespaces) {
+ var i
+ var attrsHash = {}
+ if (prefix) {
+ elem = prefix + ':' + elem
+ }
+ for (i = 0; i < attrs.length; i++) {
+ var attr = attrs[i]
+ attrsHash[attr[0]] = unescapeXml(attr[1])
+ }
+ for (i = 0; i < namespaces.length; i++) {
+ var namespace = namespaces[i]
+ var k = !namespace[0] ? 'xmlns' : 'xmlns:' + namespace[0]
+ attrsHash[k] = unescapeXml(namespace[1])
+ }
+ self.emit('startElement', elem, attrsHash)
})
+ handler.onEndElementNS(function (elem, prefix) {
+ if (prefix) {
+ elem = prefix + ':' + elem
+ }
+ self.emit('endElement', elem)
+ })
+ handler.onCharacters(function (str) {
+ self.emit('text', str)
+ })
+ handler.onCdata(function (str) {
+ self.emit('text', str)
+ })
+ handler.onError(function (e) {
+ self.emit('error', e)
+ })
+ // TODO: other events, esp. entityDecl (billion laughs!)
+ })
}
inherits(SaxNodeXML, EventEmitter)
-SaxNodeXML.prototype.write = function(data) {
- this.parser.parseString(data)
+SaxNodeXML.prototype.write = function (data) {
+ this.parser.parseString(data)
}
-SaxNodeXML.prototype.end = function(data) {
- if (data) {
- this.write(data)
- }
+SaxNodeXML.prototype.end = function (data) {
+ if (data) {
+ this.write(data)
+ }
}
-function unescapeXml(s) {
- return s.
- replace(/\&/g, '&').
- replace(/\</g, '<').
- replace(/\>/g, '>').
- replace(/\"/g, '"').
- replace(/\'/g, '\'')
+function unescapeXml (s) {
+ return s.replace(/\&/g, '&').replace(/\</g, '<').replace(/\>/g, '>').replace(/\"/g, '"').replace(/\'/g, "'")
}
diff --git a/lib/parsers/sax.js b/lib/parsers/sax.js
index 71fc192..b2c4f0c 100644
--- a/lib/parsers/sax.js
+++ b/lib/parsers/sax.js
@@ -1,45 +1,44 @@
'use strict'
var inherits = require('inherits')
- , EventEmitter = require('events').EventEmitter
- , sax = require('sax')
+var EventEmitter = require('events').EventEmitter
+var sax = require('sax')
-var SaxSaxjs = module.exports = function SaxSaxjs() {
+var SaxSaxjs = module.exports = function SaxSaxjs () {
+ EventEmitter.call(this)
+ this.parser = sax.parser(true)
- EventEmitter.call(this)
- this.parser = sax.parser(true)
-
- var that = this
- this.parser.onopentag = function(a) {
- that.emit('startElement', a.name, a.attributes)
- }
- this.parser.onclosetag = function(name) {
- that.emit('endElement', name)
- }
- this.parser.ontext = function(str) {
- that.emit('text', str)
- }
- this.parser.onend = function() {
- that.emit('end')
- }
- this.parser.onerror = function(e) {
- that.emit('error', e)
- }
- // TODO: other events, esp. entityDecl (billion laughs!)
+ var that = this
+ this.parser.onopentag = function (a) {
+ that.emit('startElement', a.name, a.attributes)
+ }
+ this.parser.onclosetag = function (name) {
+ that.emit('endElement', name)
+ }
+ this.parser.ontext = function (str) {
+ that.emit('text', str)
+ }
+ this.parser.onend = function () {
+ that.emit('end')
+ }
+ this.parser.onerror = function (e) {
+ that.emit('error', e)
+ }
+// TODO: other events, esp. entityDecl (billion laughs!)
}
inherits(SaxSaxjs, EventEmitter)
-SaxSaxjs.prototype.write = function(data) {
- if (typeof data !== 'string') {
- data = data.toString()
- }
- this.parser.write(data)
+SaxSaxjs.prototype.write = function (data) {
+ if (typeof data !== 'string') {
+ data = data.toString()
+ }
+ this.parser.write(data)
}
-SaxSaxjs.prototype.end = function(data) {
- if (data) {
- this.parser.write(data)
- }
- this.parser.close()
+SaxSaxjs.prototype.end = function (data) {
+ if (data) {
+ this.parser.write(data)
+ }
+ this.parser.close()
}
diff --git a/package.json b/package.json
index a613dcf..2ed0359 100644
--- a/package.json
+++ b/package.json
@@ -1,9 +1,7 @@
{
"name": "ltx",
"version": "2.0.0",
- "main": "./lib/index",
- "browser": "./lib/index-browserify",
- "description": "<xml for=\"node.js\" browserify=\"too\">",
+ "description": "<xml for=\"JavaScript\">",
"author": "Astro",
"repository": "github:node-xmpp/ltx",
"homepage": "http://github.com/node-xmpp/ltx",
@@ -30,23 +28,22 @@
],
"license": "MIT",
"engine": "node",
+ "scripts": {
+ "webify": "browserify -s ltx index.js -o ltx.js",
+ "unit": "vows --spec",
+ "lint": "standard",
+ "test": "npm run unit && npm run lint && npm run webify"
+ },
+ "dependencies": {
+ "inherits": "^2.0.1"
+ },
"devDependencies": {
"benchmark": "^1.0.0",
"easysax": "^0.1.14",
- "eslint": "^1.3.1",
"microtime": "^2.0.0",
- "node-expat": "^2.3.9",
+ "node-expat": "^2.3.10",
"node-xml": "^1.0.2",
"sax": "^1.1.2",
"vows": "^0.8.1"
- },
- "scripts": {
- "webify": "browserify -s ltx lib/index.js -o ltx.js",
- "unit": "./node_modules/.bin/vows --spec",
- "lint": "./node_modules/.bin/eslint .",
- "test": "npm run unit && npm run lint && npm run webify"
- },
- "dependencies": {
- "inherits": "^2.0.1"
}
}
diff --git a/test/dom-element-test.js b/test/dom-element-test.js
index 3f7c645..ad77666 100644
--- a/test/dom-element-test.js
+++ b/test/dom-element-test.js
@@ -1,55 +1,55 @@
'use strict'
var vows = require('vows')
- , assert = require('assert')
- , ltx = require('../lib/index')
- , parsers = require('../lib/parsers')
- , DOMElement = require('../lib/DOMElement')
-
-parsers.forEach(function(Parser) {
- var parse = function(s) {
- return ltx.parse(s, {Parser: Parser, Element: DOMElement})
+var assert = require('assert')
+var ltx = require('..')
+var parsers = require('../lib/parsers')
+var DOMElement = require('../lib/DOMElement')
+
+parsers.forEach(function (Parser) {
+ var parse = function (s) {
+ return ltx.parse(s, {Parser: Parser, Element: DOMElement})
+ }
+ vows.describe("Parsing returns DOMElement's").addBatch({
+ 'DOMElement': {
+ 'Returns DOMElement on parse': function () {
+ var stanza = '<message><body xmlns="http://www.w3.org/1999/xhtml">' +
+ '<p>DOM</p></body></message>'
+ var el = parse(stanza)
+
+ assert(el.getChild('body') instanceof DOMElement)
+ assert.equal(el.getChild('body').constructor.name, 'DOMElement')
+ var body = el.getChild('body')
+ assert.isDefined(body.localName)
+ assert.equal(body.localName, 'body')
+
+ assert.isDefined(body.namespaceURI)
+ assert.equal(body.namespaceURI, 'http://www.w3.org/1999/xhtml')
+
+ assert.isDefined(body.parentNode)
+ assert.equal(body.parentNode.getName(), 'message')
+
+ assert.isDefined(body.childNodes)
+ assert.isArray(body.childNodes)
+ assert.equal(body.childNodes.length, 1)
+
+ assert.isDefined(body.textContent)
+ assert.equal(body.textContent, '')
+
+ assert.equal(body.getChild('p').textContent, 'DOM')
+ }
+ },
+ 'createElement': {
+ 'create a new element and set children': function () {
+ var c = new DOMElement('bar')
+ var e = DOMElement.createElement('foo', {'foo': 'bar'}, 'foo', c)
+ assert(e instanceof DOMElement)
+ assert.equal(e.localName, 'foo')
+ assert.equal(e.getAttribute('foo'), 'bar')
+ assert.equal(e.childNodes.length, 2)
+ assert.equal(e.childNodes[0], 'foo')
+ assert.equal(e.childNodes[1], c)
+ }
}
- vows.describe('Parsing returns DOMElement\'s').addBatch({
- 'DOMElement': {
- 'Returns DOMElement on parse': function() {
- var stanza = '<message><body xmlns="http://www.w3.org/1999/xhtml">' +
- '<p>DOM</p></body></message>'
- var el = parse(stanza)
-
- assert(el.getChild('body') instanceof DOMElement)
- assert.equal(el.getChild('body').constructor.name, 'DOMElement')
- var body = el.getChild('body')
- assert.isDefined(body.localName)
- assert.equal(body.localName, 'body')
-
- assert.isDefined(body.namespaceURI)
- assert.equal(body.namespaceURI, 'http://www.w3.org/1999/xhtml')
-
- assert.isDefined(body.parentNode)
- assert.equal(body.parentNode.getName(), 'message')
-
- assert.isDefined(body.childNodes)
- assert.isArray(body.childNodes)
- assert.equal(body.childNodes.length, 1)
-
- assert.isDefined(body.textContent)
- assert.equal(body.textContent, '')
-
- assert.equal(body.getChild('p').textContent, 'DOM')
- }
- },
- 'createElement': {
- 'create a new element and set children': function() {
- var c = new DOMElement('bar')
- var e = DOMElement.createElement('foo', {'foo': 'bar'}, 'foo', c)
- assert(e instanceof DOMElement)
- assert.equal(e.localName, 'foo')
- assert.equal(e.getAttribute('foo'), 'bar')
- assert.equal(e.childNodes.length, 2)
- assert.equal(e.childNodes[0], 'foo')
- assert.equal(e.childNodes[1], c)
- }
- }
- }).export(module)
+ }).export(module)
})
diff --git a/test/element-test.js b/test/element-test.js
index 05c7617..1e65961 100644
--- a/test/element-test.js
+++ b/test/element-test.js
@@ -1,267 +1,259 @@
'use strict'
var vows = require('vows')
- , assert = require('assert')
- , ltx = require('../lib/index')
- , Element = require('../lib/Element')
+var assert = require('assert')
+var ltx = require('..')
+var Element = require('../lib/Element')
vows.describe('ltx').addBatch({
- 'new element': {
- 'doesn\'t reference original attrs object': function() {
- var o = { foo: 'bar' }
- var e = new ltx.Element('e', o)
- assert.notEqual(e.attrs, o)
- e.attrs.bar = 'foo'
- assert.equal(o.bar, undefined)
- o.foobar = 'barfoo'
- assert.equal(e.attrs.foobar, undefined)
- },
- 'set xmlns attribute if a string is passed as second argument': function() {
- var ns = 'xmlns:test'
- var e = new ltx.Element('e', ns)
- assert.equal(e.attrs.xmlns, ns)
- assert.equal(e.getAttr('xmlns'), ns)
- }
+ 'new element': {
+ "doesn't reference original attrs object": function () {
+ var o = { foo: 'bar' }
+ var e = new ltx.Element('e', o)
+ assert.notEqual(e.attrs, o)
+ e.attrs.bar = 'foo'
+ assert.equal(o.bar, undefined)
+ o.foobar = 'barfoo'
+ assert.equal(e.attrs.foobar, undefined)
},
- 'createElement': {
- 'create a new element and set children': function() {
- var c = new ltx.Element('bar')
- var e = ltx.createElement('foo', {'foo': 'bar'}, 'foo', c)
- assert(e instanceof Element)
- assert(e.is('foo'))
- assert.equal(e.attrs.foo, 'bar')
- assert.equal(e.children.length, 2)
- assert.equal(e.children[0], 'foo')
- assert.equal(e.children[1], c)
- }
+ 'set xmlns attribute if a string is passed as second argument': function () {
+ var ns = 'xmlns:test'
+ var e = new ltx.Element('e', ns)
+ assert.equal(e.attrs.xmlns, ns)
+ assert.equal(e.getAttr('xmlns'), ns)
+ }
+ },
+ 'createElement': {
+ 'create a new element and set children': function () {
+ var c = new ltx.Element('bar')
+ var e = ltx.createElement('foo', {'foo': 'bar'}, 'foo', c)
+ assert(e instanceof Element)
+ assert(e.is('foo'))
+ assert.equal(e.attrs.foo, 'bar')
+ assert.equal(e.children.length, 2)
+ assert.equal(e.children[0], 'foo')
+ assert.equal(e.children[1], c)
+ }
+ },
+ 'serialization': {
+ 'serialize an element': function () {
+ var e = new ltx.Element('e')
+ assert.equal(e.toString(), '<e/>')
},
- 'serialization': {
- 'serialize an element': function() {
- var e = new ltx.Element('e')
- assert.equal(e.toString(), '<e/>')
- },
- 'serialize an element with attributes': function() {
- var e = new ltx.Element('e', { a1: 'foo' })
- assert.equal(e.toString(), '<e a1="foo"/>')
- },
- 'serialize an element with attributes to entities': function() {
- var e = new ltx.Element('e', { a1: '"well"' })
- assert.equal(e.toString(), '<e a1=""well""/>')
- },
- 'serialize an element with text': function() {
- var e = new ltx.Element('e').t('bar').root()
- assert.equal(e.toString(), '<e>bar</e>')
- },
- 'serialize an element with text to entities': function() {
- var e = new ltx.Element('e').t('1 < 2').root()
- assert.equal(e.toString(), '<e>1 < 2</e>')
- },
- 'serialize an element with a number attribute': function() {
- var e = new ltx.Element('e', { a: 23 })
- assert.equal(e.toString(), '<e a="23"/>')
- },
- 'serialize an element with number contents': function() {
- var e = new ltx.Element('e')
- e.c('foo').t(23)
- e.c('bar').t(0)
- assert.equal(e.toString(), '<e><foo>23</foo><bar>0</bar></e>')
- },
- 'serialize with undefined attribute': function() {
- var e = new ltx.Element('e', { foo: undefined })
- assert.equal(e.toString(), '<e/>')
- },
- 'serialize with null attribute': function() {
- var e = new ltx.Element('e', { foo: null })
- assert.equal(e.toString(), '<e/>')
- },
- 'serialize with number attribute': function() {
- var e = new ltx.Element('e', { foo: 23, bar: 0 })
- var s = e.toString()
- assert.ok(s.match(/foo="23"/))
- assert.ok(s.match(/bar="0"/))
- },
- 'serialize with undefined child': function() {
- var e = new ltx.Element('e')
- e.children = [undefined]
- assert.equal(e.toString(), '<e></e>')
- },
- 'serialize with null child': function() {
- var e = new ltx.Element('e')
- e.children = [null]
- assert.equal(e.toString(), '<e></e>')
- },
- 'serialize with integer text': function() {
- var e = new ltx.Element('e').t(1000)
- assert.equal(e.getText(), 1000)
- },
- 'serialize to json': function() {
- var e = new ltx.Element('e', { foo: 23, bar: 0, nil:null }).c('f').t(1000).up()
- assert.deepEqual(e.toJSON(), {
- name: 'e',
- attrs: { foo: 23, bar: 0, nil:null },
- children: [
- { name: 'f', attrs: {}, children: [1000] }
- ]
- })
- }
+ 'serialize an element with attributes': function () {
+ var e = new ltx.Element('e', { a1: 'foo' })
+ assert.equal(e.toString(), '<e a1="foo"/>')
},
- 'remove': {
- 'by element': function() {
- var el = new ltx.Element('e').
- c('c').c('x').up().up().
- c('c2').up().
- c('c').up()
- el.remove(el.getChild('c'))
- assert.equal(el.getChildren('c').length, 1)
- assert.equal(el.getChildren('c2').length, 1)
- },
- 'by name': function() {
- var el = new ltx.Element('e').
- c('c').up().
- c('c2').up().
- c('c').up()
- el.remove('c')
- assert.equal(el.getChildren('c').length, 0)
- assert.equal(el.getChildren('c2').length, 1)
- }
+ 'serialize an element with attributes to entities': function () {
+ var e = new ltx.Element('e', { a1: '"well"' })
+ assert.equal(e.toString(), '<e a1=""well""/>')
},
- 'getAttr': {
- 'without ns': function() {
- var stanza = '<team xmlns:job="http://site.tld/job">' +
- '<person name="julien" job:title="hacker" /></team>'
- var doc = ltx.parse(stanza)
- var el = doc.getChild('person')
- assert.equal(el.getAttr('name'), 'julien')
- },
- 'with ns': function() {
- var stanza = '<team xmlns:job="http://site.tld/job">' +
- '<person name="julien" job:title="hacker" /></team>'
- var doc = ltx.parse(stanza)
- var el = doc.getChild('person')
- assert.equal(el.getAttr('title', 'http://site.tld/job'), 'hacker')
- }
+ 'serialize an element with text': function () {
+ var e = new ltx.Element('e').t('bar').root()
+ assert.equal(e.toString(), '<e>bar</e>')
},
- 'clone': {
- 'clones': function() {
- var orig = new ltx.Element('msg', { type: 'get' }).
- c('content').t('foo').root()
- var clone = orig.clone()
- assert.equal(clone.name, orig.name)
- assert.equal(clone.attrs.type, orig.attrs.type)
- assert.equal(clone.attrs.to, orig.attrs.to)
- assert.equal(clone.children.length, orig.children.length)
- assert.equal(clone.getChildText('content'), orig.getChildText('content'))
-
- assert.equal(orig.getChild('content').up(), orig)
- assert.equal(clone.getChild('content').up(), clone)
- },
- 'mod attr': function() {
- var orig = new ltx.Element('msg', { type: 'get' })
- var clone = orig.clone()
- clone.attrs.type += '-result'
+ 'serialize an element with text to entities': function () {
+ var e = new ltx.Element('e').t('1 < 2').root()
+ assert.equal(e.toString(), '<e>1 < 2</e>')
+ },
+ 'serialize an element with a number attribute': function () {
+ var e = new ltx.Element('e', { a: 23 })
+ assert.equal(e.toString(), '<e a="23"/>')
+ },
+ 'serialize an element with number contents': function () {
+ var e = new ltx.Element('e')
+ e.c('foo').t(23)
+ e.c('bar').t(0)
+ assert.equal(e.toString(), '<e><foo>23</foo><bar>0</bar></e>')
+ },
+ 'serialize with undefined attribute': function () {
+ var e = new ltx.Element('e', { foo: undefined })
+ assert.equal(e.toString(), '<e/>')
+ },
+ 'serialize with null attribute': function () {
+ var e = new ltx.Element('e', { foo: null })
+ assert.equal(e.toString(), '<e/>')
+ },
+ 'serialize with number attribute': function () {
+ var e = new ltx.Element('e', { foo: 23, bar: 0 })
+ var s = e.toString()
+ assert.ok(s.match(/foo="23"/))
+ assert.ok(s.match(/bar="0"/))
+ },
+ 'serialize with undefined child': function () {
+ var e = new ltx.Element('e')
+ e.children = [undefined]
+ assert.equal(e.toString(), '<e></e>')
+ },
+ 'serialize with null child': function () {
+ var e = new ltx.Element('e')
+ e.children = [null]
+ assert.equal(e.toString(), '<e></e>')
+ },
+ 'serialize with integer text': function () {
+ var e = new ltx.Element('e').t(1000)
+ assert.equal(e.getText(), 1000)
+ },
+ 'serialize to json': function () {
+ var e = new ltx.Element('e', { foo: 23, bar: 0, nil: null }).c('f').t(1000).up()
+ assert.deepEqual(e.toJSON(), {
+ name: 'e',
+ attrs: { foo: 23, bar: 0, nil: null },
+ children: [
+ { name: 'f', attrs: {}, children: [1000] }
+ ]
+ })
+ }
+ },
+ 'remove': {
+ 'by element': function () {
+ var el = new ltx.Element('e').c('c').c('x').up().up().c('c2').up().c('c').up()
+ el.remove(el.getChild('c'))
+ assert.equal(el.getChildren('c').length, 1)
+ assert.equal(el.getChildren('c2').length, 1)
+ },
+ 'by name': function () {
+ var el = new ltx.Element('e').c('c').up().c('c2').up().c('c').up()
+ el.remove('c')
+ assert.equal(el.getChildren('c').length, 0)
+ assert.equal(el.getChildren('c2').length, 1)
+ }
+ },
+ 'getAttr': {
+ 'without ns': function () {
+ var stanza = '<team xmlns:job="http://site.tld/job">' +
+ '<person name="julien" job:title="hacker" /></team>'
+ var doc = ltx.parse(stanza)
+ var el = doc.getChild('person')
+ assert.equal(el.getAttr('name'), 'julien')
+ },
+ 'with ns': function () {
+ var stanza = '<team xmlns:job="http://site.tld/job">' +
+ '<person name="julien" job:title="hacker" /></team>'
+ var doc = ltx.parse(stanza)
+ var el = doc.getChild('person')
+ assert.equal(el.getAttr('title', 'http://site.tld/job'), 'hacker')
+ }
+ },
+ 'clone': {
+ 'clones': function () {
+ var orig = new ltx.Element('msg', { type: 'get' }).c('content').t('foo').root()
+ var clone = orig.clone()
+ assert.equal(clone.name, orig.name)
+ assert.equal(clone.attrs.type, orig.attrs.type)
+ assert.equal(clone.attrs.to, orig.attrs.to)
+ assert.equal(clone.children.length, orig.children.length)
+ assert.equal(clone.getChildText('content'), orig.getChildText('content'))
- assert.equal(orig.attrs.type, 'get')
- assert.equal(clone.attrs.type, 'get-result')
- },
- 'rm attr': function() {
- var orig = new ltx.Element('msg', { from: 'me' })
- var clone = orig.clone()
- delete clone.attrs.from
- clone.attrs.to = 'you'
+ assert.equal(orig.getChild('content').up(), orig)
+ assert.equal(clone.getChild('content').up(), clone)
+ },
+ 'mod attr': function () {
+ var orig = new ltx.Element('msg', { type: 'get' })
+ var clone = orig.clone()
+ clone.attrs.type += '-result'
- assert.equal(orig.attrs.from, 'me')
- assert.equal(orig.attrs.to, undefined)
- assert.equal(clone.attrs.from, undefined)
- assert.equal(clone.attrs.to, 'you')
- },
- 'mod child': function() {
- var orig = new ltx.Element('msg', { type: 'get' }).
- c('content').t('foo').root()
- var clone = orig.clone()
- clone.getChild('content').t('bar').name = 'description'
+ assert.equal(orig.attrs.type, 'get')
+ assert.equal(clone.attrs.type, 'get-result')
+ },
+ 'rm attr': function () {
+ var orig = new ltx.Element('msg', { from: 'me' })
+ var clone = orig.clone()
+ delete clone.attrs.from
+ clone.attrs.to = 'you'
- assert.equal(orig.children[0].name, 'content')
- assert.equal(orig.getChildText('content'), 'foo')
- assert.equal(clone.children[0].name, 'description')
- assert.equal(clone.getChildText('description'), 'foobar')
- }
+ assert.equal(orig.attrs.from, 'me')
+ assert.equal(orig.attrs.to, undefined)
+ assert.equal(clone.attrs.from, undefined)
+ assert.equal(clone.attrs.to, 'you')
},
- 'children': {
- 'getChildren': function() {
- var el = new ltx.Element('a')
- .c('b')
- .c('b2').up().up()
- .t('foo')
- .c('c').t('cbar').up()
- .t('bar')
- .root()
+ 'mod child': function () {
+ var orig = new ltx.Element('msg', { type: 'get' }).c('content').t('foo').root()
+ var clone = orig.clone()
+ clone.getChild('content').t('bar').name = 'description'
- var children = el.children
- assert.equal(children.length, 4)
- assert.equal(children[0].name, 'b')
- assert.equal(children[1], 'foo')
- assert.equal(children[2].name, 'c')
- assert.equal(children[3], 'bar')
- },
- 'getChildElements': function() {
- var el = new ltx.Element('a')
- .c('b')
- .c('b2').up().up()
- .t('foo')
- .c('c').t('cbar').up()
- .t('bar')
- .root()
+ assert.equal(orig.children[0].name, 'content')
+ assert.equal(orig.getChildText('content'), 'foo')
+ assert.equal(clone.children[0].name, 'description')
+ assert.equal(clone.getChildText('description'), 'foobar')
+ }
+ },
+ 'children': {
+ 'getChildren': function () {
+ var el = new ltx.Element('a')
+ .c('b')
+ .c('b2').up().up()
+ .t('foo')
+ .c('c').t('cbar').up()
+ .t('bar')
+ .root()
- var children = el.getChildElements()
- assert.equal(children.length, 2)
- assert.equal(children[0].name, 'b')
- assert.equal(children[1].name, 'c')
- }
+ var children = el.children
+ assert.equal(children.length, 4)
+ assert.equal(children[0].name, 'b')
+ assert.equal(children[1], 'foo')
+ assert.equal(children[2].name, 'c')
+ assert.equal(children[3], 'bar')
},
+ 'getChildElements': function () {
+ var el = new ltx.Element('a')
+ .c('b')
+ .c('b2').up().up()
+ .t('foo')
+ .c('c').t('cbar').up()
+ .t('bar')
+ .root()
- 'recursive': {
- 'getChildrenByAttr': function() {
- var el = new ltx.Element('a')
- .c('b')
- .c('c', {myProperty:'x'}).t('bar').up().up().up()
- .c('d', {id: 'x'})
- .c('e', {myProperty:'x'}).root()
+ var children = el.getChildElements()
+ assert.equal(children.length, 2)
+ assert.equal(children[0].name, 'b')
+ assert.equal(children[1].name, 'c')
+ }
+ },
- var results = el.getChildrenByAttr('myProperty', 'x', null, true)
- assert.equal( results[0].toString(), '<c myProperty="x">bar</c>')
- assert.equal( results[1].toString(), '<e myProperty="x"/>')
- },
- 'getChildByAttr': function() {
- var el = new ltx.Element('a')
- .c('b')
- .c('c', {id:'x'})
- .t('bar').root()
- assert.equal(el.getChildByAttr('id', 'x', null, true).toString(), '<c id="x">bar</c>')
- }
+ 'recursive': {
+ 'getChildrenByAttr': function () {
+ var el = new ltx.Element('a')
+ .c('b')
+ .c('c', {myProperty: 'x'}).t('bar').up().up().up()
+ .c('d', {id: 'x'})
+ .c('e', {myProperty: 'x'}).root()
+
+ var results = el.getChildrenByAttr('myProperty', 'x', null, true)
+ assert.equal(results[0].toString(), '<c myProperty="x">bar</c>')
+ assert.equal(results[1].toString(), '<e myProperty="x"/>')
},
+ 'getChildByAttr': function () {
+ var el = new ltx.Element('a')
+ .c('b')
+ .c('c', {id: 'x'})
+ .t('bar').root()
+ assert.equal(el.getChildByAttr('id', 'x', null, true).toString(), '<c id="x">bar</c>')
+ }
+ },
- 'issue #15: Inconsistency with prefixed elements': {
- topic: function() {
- return ltx.parse('<root><x:foo>bar</x:foo></root>')
- },
- 'getChildText prefixed': function(el) {
- assert.equal(el.getChildText('x:foo'), null)
- },
- 'getChildText unprefixed': function(el) {
- assert.equal(el.getChildText('foo'), 'bar')
- },
- 'getChild prefixed': function(el) {
- assert.equal(el.getChild('x:foo'), null)
- },
- 'getChild unprefixed': function(el) {
- assert.equal(el.getChild('foo').getText(), 'bar')
- }
+ 'issue #15: Inconsistency with prefixed elements': {
+ topic: function () {
+ return ltx.parse('<root><x:foo>bar</x:foo></root>')
+ },
+ 'getChildText prefixed': function (el) {
+ assert.equal(el.getChildText('x:foo'), null)
},
+ 'getChildText unprefixed': function (el) {
+ assert.equal(el.getChildText('foo'), 'bar')
+ },
+ 'getChild prefixed': function (el) {
+ assert.equal(el.getChild('x:foo'), null)
+ },
+ 'getChild unprefixed': function (el) {
+ assert.equal(el.getChild('foo').getText(), 'bar')
+ }
+ },
- 'issue-37: Element instanceof Fails': {
- 'instanceof': function() {
- var el = new ltx.Element('root').c('children')
- assert.ok(el instanceof ltx.Element)
- }
+ 'issue-37: Element instanceof Fails': {
+ 'instanceof': function () {
+ var el = new ltx.Element('root').c('children')
+ assert.ok(el instanceof ltx.Element)
}
+ }
}).export(module)
diff --git a/test/parse-test.js b/test/parse-test.js
index 8ae10b2..82428ac 100644
--- a/test/parse-test.js
+++ b/test/parse-test.js
@@ -1,154 +1,165 @@
'use strict'
var vows = require('vows')
- , assert = require('assert')
- , ltx = require('../lib/index')
- , parsers = require('../lib/parsers')
+var assert = require('assert')
+var ltx = require('..')
+var parsers = require('../lib/parsers')
-parsers.forEach(function(Parser) {
- var parse = function(s) {
- return ltx.parse(s, {Parser: Parser})
+parsers.forEach(function (Parser) {
+ var parse = function (s) {
+ return ltx.parse(s, {Parser: Parser})
+ }
+ vows.describe('ltx with ' + Parser.name).addBatch({
+ 'DOM parsing': {
+ 'simple document': function () {
+ var el = parse('<root/>')
+ assert.equal(el.name, 'root')
+ assert.equal(0, el.children.length)
+ },
+ 'text with commas': function () {
+ var el = parse("<body>sa'sa'1'sasa</body>")
+ assert.equal("sa'sa'1'sasa", el.getText())
+ },
+ 'text with entities': function () {
+ var el = parse('<body><>&"'</body>')
+ assert.equal('<>&"\'', el.getText())
+ },
+ 'attribute with entities': function () {
+ var el = parse("<body title='<>&"''/>")
+ assert.equal('<>&"\'', el.attrs.title)
+ },
+ 'erroneous document raises error': function () {
+ assert.throws(function () {
+ parse('<root></toor>')
+ })
+ },
+ 'incomplete document raises error': function () {
+ assert.throws(function () {
+ parse('<root>')
+ })
+ },
+ 'namespace declaration': function () {
+ var el = parse("<root xmlns='https://github.com/astro/ltx'/>")
+ assert.equal(el.name, 'root')
+ assert.equal(el.attrs.xmlns, 'https://github.com/astro/ltx')
+ assert.ok(el.is('root', 'https://github.com/astro/ltx'))
+ },
+ 'namespace declaration with prefix': function () {
+ var el = parse("<x:root xmlns:x='https://github.com/astro/ltx'/>")
+ assert.equal(el.name, 'x:root')
+ assert.equal(el.getName(), 'root')
+ assert.ok(el.is('root', 'https://github.com/astro/ltx'))
+ },
+ 'buffer': function () {
+ var buf = new Buffer('<root/>')
+ var el = parse(buf)
+ assert.equal(el.name, 'root')
+ assert.equal(0, el.children.length)
+ },
+ 'utf-8 text': function () {
+ var el = parse('<?xml version="1.0" encoding="utf-8"?><text>Möwe</text>')
+ assert.equal(el.name, 'text')
+ assert.equal(el.getText(), 'Möwe')
+ },
+ 'iso8859-1 text': function () {
+ var el = parse('<?xml version="1.0" encoding="iso-8859-1"?><text>M\xF6we</text>')
+ assert.equal(el.name, 'text')
+ assert.equal(el.getText(), 'Möwe')
+ }
+ },
+ 'SAX parsing': {
+ 'XMPP stream': function () {
+ var parser = new Parser()
+ var events = []
+ parser.on('startElement', function (name, attrs) {
+ events.push({ start: name, attrs: attrs })
+ })
+ parser.on('endElement', function (name) {
+ events.push({ end: name })
+ })
+ parser.on('text', function (s) {
+ events.push({ text: s })
+ })
+ parser.write("<?xml version='1.0'?><stream:stream xmlns='jabber:client'")
+ parser.write(" xmlns:stream='http://etherx.jabber.org/streams' id='5568")
+ assert.equal(events.length, 0)
+ parser.write("90365' from='jabber.ccc.de' version='1.0' xml:lang='en'><")
+ assert.equal(events.length, 1)
+ testStanza(events[0], {
+ name: 'stream:stream',
+ attrs: {
+ xmlns: 'jabber:client',
+ 'xmlns:stream': 'http://etherx.jabber.org/streams',
+ id: '556890365',
+ from: 'jabber.ccc.de',
+ version: '1.0',
+ 'xml:lang': 'en'
+ }
+ })
+ parser.write("stream:features><starttls xmlns='urn:ietf:params:xml:ns:x")
+ assert.equal(events.length, 2)
+ testStanza(events[1], {name: 'stream:features', attrs: {}})
+ parser.write("mpp-tls'/><mechanisms xmlns='urn:ietf:params:xml:ns:xmpp-")
+ assert.equal(events.length, 4)
+ testStanza(events[2], {
+ name: 'starttls',
+ attrs: {
+ xmlns: 'urn:ietf:params:xml:ns:xmpp-tls'
+ }
+ })
+ assert.equal(events[3].end, 'starttls')
+ parser.write("sasl'><mechanism>PLAIN</mechanism><mechanism>DIGEST-MD5</")
+ assert.ok(events.length >= 9)
+ parser.write('mechanism><mechanism>SCRAM-SHA-1</mechanism></mechanisms>')
+ assert.equal(events.length, 15)
+ parser.write("<register xmlns='http://jabber.org/features/iq-register'/")
+ assert.equal(events.length, 15)
+ parser.write('></stream:features>')
+ assert.equal(events.length, 18)
+ },
+ 'bug: partial attrs': function () {
+ var parser = new Parser()
+ var events = []
+ parser.on('startElement', function (name, attrs) {
+ events.push({ start: name, attrs: attrs })
+ })
+ parser.on('endElement', function (name) {
+ events.push({ end: name })
+ })
+ parser.on('text', function (s) {
+ events.push({ text: s })
+ })
+ parser.write('<')
+ parser.write('stream:features')
+ parser.write('>')
+ parser.write('<')
+ parser.write('mechanisms')
+ parser.write(' ')
+ parser.write('xmlns')
+ parser.write('="')
+ parser.write('urn:ietf:params:xml:ns:xmpp-sasl')
+ parser.write('"')
+ parser.write('>')
+ assert.equal(events.length, 2)
+ testStanza(events[0], {
+ name: 'stream:features',
+ attrs: {}
+ })
+ testStanza(events[1], {
+ name: 'mechanisms',
+ attrs: {
+ xmlns: 'urn:ietf:params:xml:ns:xmpp-sasl'
+ }
+ })
+ }
}
- vows.describe('ltx with ' + Parser.name).addBatch({
- 'DOM parsing': {
- 'simple document': function() {
- var el = parse('<root/>')
- assert.equal(el.name, 'root')
- assert.equal(0, el.children.length)
- },
- 'text with commas': function() {
- var el = parse('<body>sa\'sa\'1\'sasa</body>')
- assert.equal('sa\'sa\'1\'sasa', el.getText())
- },
- 'text with entities': function() {
- var el = parse('<body><>&"'</body>')
- assert.equal('<>&"\'', el.getText())
- },
- 'attribute with entities': function() {
- var el = parse('<body title=\'<>&"'\'/>')
- assert.equal('<>&"\'', el.attrs.title)
- },
- 'erroneous document raises error': function() {
- assert.throws(function() {
- parse('<root></toor>')
- })
- },
- 'incomplete document raises error': function() {
- assert.throws(function() {
- parse('<root>')
- })
- },
- 'namespace declaration': function() {
- var el = parse('<root xmlns=\'https://github.com/astro/ltx\'/>')
- assert.equal(el.name, 'root')
- assert.equal(el.attrs.xmlns, 'https://github.com/astro/ltx')
- assert.ok(el.is('root', 'https://github.com/astro/ltx'))
- },
- 'namespace declaration with prefix': function() {
- var el = parse('<x:root xmlns:x=\'https://github.com/astro/ltx\'/>')
- assert.equal(el.name, 'x:root')
- assert.equal(el.getName(), 'root')
- assert.ok(el.is('root', 'https://github.com/astro/ltx'))
- },
- 'buffer': function() {
- var buf = new Buffer('<root/>')
- var el = parse(buf)
- assert.equal(el.name, 'root')
- assert.equal(0, el.children.length)
- },
- 'utf-8 text': function() {
- var el = parse('<?xml version="1.0" encoding="utf-8"?><text>Möwe</text>')
- assert.equal(el.name, 'text')
- assert.equal(el.getText(), 'Möwe')
- },
- 'iso8859-1 text': function() {
- var el = parse('<?xml version="1.0" encoding="iso-8859-1"?><text>M\xF6we</text>')
- assert.equal(el.name, 'text')
- assert.equal(el.getText(), 'Möwe')
- }
- },
- 'SAX parsing': {
- /* jshint -W071 */
- 'XMPP stream': function() {
- var parser = new Parser()
- var events = []
- parser.on('startElement', function(name, attrs) {
- events.push({ start: name, attrs: attrs })
- })
- parser.on('endElement', function(name) {
- events.push({ end: name })
- })
- parser.on('text', function(s) {
- events.push({ text: s })
- })
- parser.write('<?xml version=\'1.0\'?><stream:stream xmlns=\'jabber:client\'')
- parser.write(' xmlns:stream=\'http://etherx.jabber.org/streams\' id=\'5568')
- assert.equal(events.length, 0)
- parser.write('90365\' from=\'jabber.ccc.de\' version=\'1.0\' xml:lang=\'en\'><')
- assert.equal(events.length, 1)
- testStanza(events[0], { name: 'stream:stream', attrs: {
- xmlns: 'jabber:client',
- 'xmlns:stream': 'http://etherx.jabber.org/streams',
- id: '556890365',
- from: 'jabber.ccc.de',
- version: '1.0',
- 'xml:lang': 'en'
- }})
- parser.write('stream:features><starttls xmlns=\'urn:ietf:params:xml:ns:x')
- assert.equal(events.length, 2)
- testStanza(events[1], {name:'stream:features', attrs:{}})
- parser.write('mpp-tls\'/><mechanisms xmlns=\'urn:ietf:params:xml:ns:xmpp-')
- assert.equal(events.length, 4)
- testStanza(events[2], {name: 'starttls', attrs: {
- xmlns: 'urn:ietf:params:xml:ns:xmpp-tls'
- }})
- assert.equal(events[3].end, 'starttls')
- parser.write('sasl\'><mechanism>PLAIN</mechanism><mechanism>DIGEST-MD5</')
- assert.ok(events.length >= 9)
- parser.write('mechanism><mechanism>SCRAM-SHA-1</mechanism></mechanisms>')
- assert.equal(events.length, 15)
- parser.write('<register xmlns=\'http://jabber.org/features/iq-register\'/')
- assert.equal(events.length, 15)
- parser.write('></stream:features>')
- assert.equal(events.length, 18)
- },
- 'bug: partial attrs': function() {
- var parser = new Parser()
- var events = []
- parser.on('startElement', function(name, attrs) {
- events.push({ start: name, attrs:attrs })
- })
- parser.on('endElement', function(name) {
- events.push({ end: name })
- })
- parser.on('text', function(s) {
- events.push({ text: s })
- })
- parser.write('<')
- parser.write('stream:features')
- parser.write('>')
- parser.write('<')
- parser.write('mechanisms')
- parser.write(' ')
- parser.write('xmlns')
- parser.write('="')
- parser.write('urn:ietf:params:xml:ns:xmpp-sasl')
- parser.write('"')
- parser.write('>')
- assert.equal(events.length, 2)
- testStanza(events[0], {name: 'stream:features', attrs:{}})
- testStanza(events[1], {name: 'mechanisms', attrs:{
- xmlns: 'urn:ietf:params:xml:ns:xmpp-sasl'
- }})
- }
- }
- }).export(module)
+ }).export(module)
})
-function testStanza(data, stanza) {
- assert.equal(data.start, stanza.name)
- assert.equal(Object.keys(data.attrs).length,
- Object.keys(stanza.attrs).length)
- for (var k in stanza.attrs)
- assert.equal(data.attrs[k], stanza.attrs[k])
+function testStanza (data, stanza) {
+ assert.equal(data.start, stanza.name)
+ assert.equal(Object.keys(data.attrs).length,
+ Object.keys(stanza.attrs).length)
+ for (var k in stanza.attrs)
+ assert.equal(data.attrs[k], stanza.attrs[k])
}
diff --git a/test/unicode-test.js b/test/unicode-test.js
index 0123000..895695b 100644
--- a/test/unicode-test.js
+++ b/test/unicode-test.js
@@ -1,45 +1,45 @@
'use strict'
var vows = require('vows')
- , assert = require('assert')
- , Element = require('../lib/Element')
+var assert = require('assert')
+var Element = require('../lib/Element')
vows.describe('unicode').addBatch({
- 'unicode forming': {
- 'issue-29': function() {
- var text = 'Hello ɝ'
- var element = new Element('iq')
- element.t(text)
- assert.equal(element.toString(), '<iq>' + text + '</iq>')
- },
- /*
- 'issue-29 test #2': function() {
- var text = '니코드<'
- var element = new Element(
- 'message', { to: 'you at server.com', type: 'chat' }
- )
- .c('body').t('니코드<'.toString('utf8'))
- assert.equal(element.getChildText('body'), text)
- },
- */
- 'issue-29 test #3': function() {
- var text = '니코드<'
- var element = new Element(
- 'message', { to: 'you at server.com', type: 'chat' }
- ).c('body').t('니코드<'.toString('utf8'))
- assert.equal(element.getText(), text)
- },
- 'issue-29 test write': function() {
- var text = '유니코드'
- var result = '<0message0 0to0="0-1 at chat.fb.com0"0 0type0="0chat0"0>0<0body0>'.split(0)
- result.push(text)
- result = result.concat('</0body0>0</0message0>'.split(0))
- var element = new Element('message', {to:'-1 at chat.fb.com', type:'chat'})
- element.c('body').t(text.toString('utf8'))
- element.write(function(c) {
- assert.equal(result.shift(), c)
- })
- assert.equal(result.length, 0)
- }
+ 'unicode forming': {
+ 'issue-29': function () {
+ var text = 'Hello ɝ'
+ var element = new Element('iq')
+ element.t(text)
+ assert.equal(element.toString(), '<iq>' + text + '</iq>')
+ },
+ /*
+ 'issue-29 test #2': function() {
+ var text = '니코드<'
+ var element = new Element(
+ 'message', { to: 'you at server.com', type: 'chat' }
+ )
+ .c('body').t('니코드<'.toString('utf8'))
+ assert.equal(element.getChildText('body'), text)
+ },
+ */
+ 'issue-29 test #3': function () {
+ var text = '니코드<'
+ var element = new Element(
+ 'message', { to: 'you at server.com', type: 'chat' }
+ ).c('body').t('니코드<'.toString('utf8'))
+ assert.equal(element.getText(), text)
+ },
+ 'issue-29 test write': function () {
+ var text = '유니코드'
+ var result = '<0message0 0to0="0-1 at chat.fb.com0"0 0type0="0chat0"0>0<0body0>'.split(0)
+ result.push(text)
+ result = result.concat('</0body0>0</0message0>'.split(0))
+ var element = new Element('message', {to: '-1 at chat.fb.com', type: 'chat'})
+ element.c('body').t(text.toString('utf8'))
+ element.write(function (c) {
+ assert.equal(result.shift(), c)
+ })
+ assert.equal(result.length, 0)
}
+ }
}).export(module)
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-javascript/ltx.git
More information about the Pkg-javascript-commits
mailing list