Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
121 changes: 82 additions & 39 deletions lib/parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,42 @@ function getter(getFn) {
};
}

function cloneNsMatrix(nsMatrix) {
var clone = Object.create(null), key;
for (key in nsMatrix) {
clone[key] = nsMatrix[key];
/**
* Set a namespace matrix entry, recording the previous
* value on the given change log for later restoration.
*
* @param {Object} nsMatrix
* @param {Object<string, ?string>} changes
* @param {string} key
* @param {string} value
*/
function setNsEntry(nsMatrix, changes, key, value) {
if (!(key in changes)) {
changes[key] = key in nsMatrix ? nsMatrix[key] : null;
}
return clone;

nsMatrix[key] = value;
}

// per-matrix element name cache; stored under a symbol so it is
// invisible to the `for (key in nsMatrix)` clone above and gets
// collected together with the matrix it belongs to
var NAME_CACHE = Symbol('nameCache');
/**
* Restore a namespace matrix, applying the given change log.
*
* @param {Object} nsMatrix
* @param {Object<string, ?string>} changes
*/
function restoreNsMatrix(nsMatrix, changes) {
var key, value;

for (key in changes) {
value = changes[key];

if (value === null) {
delete nsMatrix[key];
} else {
nsMatrix[key] = value;
}
}
}

function uriPrefix(prefix) {
return prefix + '$uri';
Expand Down Expand Up @@ -141,7 +165,7 @@ export default function Parser(options) {
/**
* Namespace + node state shared across (streamed) parse runs.
*/
var nsMatrixStack,
var nsChangesStack,
nsMatrix,
nodeStack;

Expand Down Expand Up @@ -259,7 +283,7 @@ export default function Parser(options) {
* Reset the parser state before a (streamed) parse run.
*/
function resetState() {
nsMatrixStack = isNamespace ? [] : null;
nsChangesStack = isNamespace ? [] : null;
nsMatrix = isNamespace ? buildNsMatrix(nsUriToPrefix) : null;
nodeStack = [];

Expand Down Expand Up @@ -376,10 +400,10 @@ export default function Parser(options) {
*/
function parse(xml, streaming = false) {

var elNameCache = null,
elNameCacheMatrix = null;
var elNameCache = null;

var _nsMatrix,
var nsChanges,
nsSnapshot,
anonymousNsCount = 0,
tagStart = false,
tagEnd = false,
Expand Down Expand Up @@ -446,7 +470,6 @@ export default function Parser(options) {
i = attrsStart,
s = attrsString,
l = s.length,
hasNewMatrix,
newalias,
value,
alias,
Expand Down Expand Up @@ -647,18 +670,25 @@ export default function Parser(options) {
}

if (nsMatrix[newalias] !== alias) {
if (!hasNewMatrix) {
nsMatrix = cloneNsMatrix(nsMatrix);
hasNewMatrix = true;

// mutate matrix in place, tracking changes
// for restoration once the element closes;
// null prototype guards against special keys
if (!nsChanges) {
nsChanges = Object.create(null);
}

nsMatrix[newalias] = alias;
// invalidate cached element names + ns snapshot
elNameCache = null;
nsSnapshot = null;

setNsEntry(nsMatrix, nsChanges, newalias, alias);
if (newalias === 'xmlns') {
nsMatrix[uriPrefix(alias)] = nsUri;
setNsEntry(nsMatrix, nsChanges, uriPrefix(alias), nsUri);
defaultAlias = alias;
}

nsMatrix[nsUriPrefix] = nsUri;
setNsEntry(nsMatrix, nsChanges, nsUriPrefix, nsUri);
}

// expose xmlns(:asd)="..." in attributes
Expand Down Expand Up @@ -781,7 +811,14 @@ export default function Parser(options) {
}),
'attrs': getter(getAttrs),
'ns': getter(function() {
return nsMatrix;

// expose a stable snapshot of the current namespace
// matrix, cached until the matrix changes
if (!nsSnapshot) {
nsSnapshot = Object.assign(Object.create(null), nsMatrix);
}

return nsSnapshot;
})
});
}
Expand Down Expand Up @@ -1038,15 +1075,11 @@ export default function Parser(options) {

if (isNamespace) {

_nsMatrix = nsMatrix;

if (tagStart) {

// remember old namespace
// unless we're self-closing
if (!tagEnd) {
nsMatrixStack.push(_nsMatrix);
}
// track namespace changes on this element
// for later restoration
nsChanges = null;

if (cachedAttrs === null) {

Expand All @@ -1062,18 +1095,21 @@ export default function Parser(options) {
maybeNS = false;
}
}

// remember changes made by this element
// unless we're self-closing
if (!tagEnd) {
nsChangesStack.push(nsChanges);
}
}

_elementName = elementName;

// memoize normalized names per namespace matrix; tag names
// memoize normalized names per namespace state; tag names
// typically repeat heavily and the matrix rarely changes.
if (elNameCacheMatrix !== nsMatrix) {
elNameCache = nsMatrix[NAME_CACHE];
if (elNameCache === undefined) {
elNameCache = nsMatrix[NAME_CACHE] = Object.create(null);
}
elNameCacheMatrix = nsMatrix;
// the cache is rebuilt whenever the matrix changed.
if (elNameCache === null) {
elNameCache = Object.create(null);
}

var _cachedName = elNameCache[elementName];
Expand Down Expand Up @@ -1144,9 +1180,16 @@ export default function Parser(options) {
// restore old namespace
if (isNamespace) {
if (!tagStart) {
nsMatrix = nsMatrixStack.pop();
} else {
nsMatrix = _nsMatrix;
nsChanges = nsChangesStack.pop();
}

if (nsChanges) {
restoreNsMatrix(nsMatrix, nsChanges);
nsChanges = null;

// invalidate cached element names + ns snapshot
elNameCache = null;
nsSnapshot = null;
}
}
}
Expand Down
109 changes: 109 additions & 0 deletions test/elements.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import assert from 'node:assert';

import { Parser } from 'saxen';

import { test } from './helper.js';

// // default ns:
Expand Down Expand Up @@ -1643,4 +1647,109 @@ describe('elements', function() {
],
});


// nested prefix shadowing, restored after close
test({
xml: (
'<root xmlns:a="http://www.w3.org/2005/Atom">' +
'<a:x xmlns:a="http://purl.org/rss/1.0/">' +
'<a:y />' +
'</a:x>' +
'<a:z />' +
'</root>'
),
ns: true,
expect: [
[ 'openTag', 'root' ],
[ 'openTag', 'rss:x' ],
[ 'openTag', 'rss:y' ],
[ 'closeTag', 'rss:y' ],
[ 'closeTag', 'rss:x' ],
[ 'openTag', 'atom:z' ],
[ 'closeTag', 'atom:z' ],
[ 'closeTag', 'root' ],
],
});

// repeated tag name across shadowed scope boundary
test({
xml: (
'<root xmlns:a="http://www.w3.org/2005/Atom">' +
'<a:x xmlns:a="http://purl.org/rss/1.0/">' +
'<a:y />' +
'</a:x>' +
'<a:y />' +
'</root>'
),
ns: true,
expect: [
[ 'openTag', 'root' ],
[ 'openTag', 'rss:x' ],
[ 'openTag', 'rss:y' ],
[ 'closeTag', 'rss:y' ],
[ 'closeTag', 'rss:x' ],
[ 'openTag', 'atom:y' ],
[ 'closeTag', 'atom:y' ],
[ 'closeTag', 'root' ],
],
});

// self-closed element declarations, restored after close
test({
xml: (
'<root xmlns:a="http://www.w3.org/2005/Atom">' +
'<a:x xmlns:b="urn:unknown" />' +
'<b:y />' +
'</root>'
),
ns: true,
expect: [
[ 'openTag', 'root' ],
[ 'openTag', 'atom:x' ],
[ 'closeTag', 'atom:x' ],
[ 'error', 'missing namespace on <b:y>' ],
],
});


describe('namespace declaration scoping', function() {

// verify deeply nested declarations scale linearly
// cf. https://github.com/nikku/saxen/security/advisories/GHSA-6w8c-5m3c-g2m8
it('should handle deeply nested namespace declarations', function() {

// given
var depth = 3000;

var open = '', close = '';
for (var i = 0; i < depth; i++) {
open += '<p' + i + ':e xmlns:p' + i + '="urn:' + i + '">';
close = '</p' + i + ':e>' + close;
}

var xml = '<root xmlns="urn:root">' + open + close + '</root>';

var parser = new Parser({ proxy: true });

parser.ns({});

var count = 0;
var lastName;

parser.on('openTag', function(el) {
count++;
lastName = el.name;
});

// when
var err = parser.parse(xml);

// then
assert.ifError(err);
assert.equal(count, depth + 1);
assert.equal(lastName, 'p' + (depth - 1) + ':e');
});

});

});
46 changes: 46 additions & 0 deletions test/modes.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,52 @@ describe('modes', function() {
assert.ok(counter === 1, 'parsed one node');
});


it('exposing stable ns snapshots', function() {

// given
var parser = new Parser({ proxy: true });

parser.ns({
'urn:1': 'one',
'urn:2': 'two'
});

var captured, capturedAgain;

parser.on('openTag', function(el) {
if (el.originalName === 'a:x') {
captured = el.ns;
capturedAgain = el.ns;
}
});

// when
parser.parse(
'<root xmlns:a="urn:1">' +
'<a:x xmlns:b="urn:2">' +
'<b:y />' +
'</a:x>' +
'</root>'
);

// then
// snapshot is cached while matrix is unchanged
assert.strictEqual(captured, capturedAgain);

// captured snapshot remains valid after parse moved on
assert.deepEqual(captured, {
'one': 'one',
'one$uri': 'urn:1',
'two': 'two',
'two$uri': 'urn:2',
'a': 'one',
'a$uri': 'urn:1',
'b': 'two',
'b$uri': 'urn:2'
});
});

});


Expand Down
Loading