Skip to content

Commit

Permalink
Merge pull request #719 from jportner/frozen-prototype-fix
Browse files Browse the repository at this point in the history
Make escapeXML work when the Function prototype is frozen
  • Loading branch information
mde committed Mar 12, 2023
2 parents f818bce + 181a537 commit 9ea36ba
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 4 deletions.
20 changes: 18 additions & 2 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,25 @@ exports.escapeXML = function (markup) {
: String(markup)
.replace(_MATCH_HTML, encode_char);
};
exports.escapeXML.toString = function () {

function escapeXMLToString() {
return Function.prototype.toString.call(this) + ';\n' + escapeFuncStr;
};
}

try {
if (typeof Object.defineProperty === 'function') {
// If the Function prototype is frozen, the "toString" property is non-writable. This means that any objects which inherit this property
// cannot have the property changed using an assignment. If using strict mode, attempting that will cause an error. If not using strict
// mode, attempting that will be silently ignored.
// However, we can still explicitly shadow the prototype's "toString" property by defining a new "toString" property on this object.
Object.defineProperty(exports.escapeXML, 'toString', { value: escapeXMLToString });
} else {
// If Object.defineProperty() doesn't exist, attempt to shadow this property using the assignment operator.
exports.escapeXML.toString = escapeXMLToString;
}
} catch (err) {
console.warn('Unable to set escapeXML.toString (is the Function prototype frozen?)');
}

/**
* Naive copy of properties from one object to another.
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,6 @@
"node": ">=0.10.0"
},
"scripts": {
"test": "mocha"
"test": "mocha -u tdd"
}
}
21 changes: 20 additions & 1 deletion test/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,27 @@ suite('unit testing exported functions of module \'utils.js\'', function () {
*/
suite('unit testing function \'escapeXML\' of module \'utils.js\'', function () {
test('it should be callable without parameters', function () {
const stringified =
`function (markup) {
return markup == undefined
? ''
: String(markup)
.replace(_MATCH_HTML, encode_char);
};
var _ENCODE_HTML_RULES = {
"&": "&"
, "<": "&lt;"
, ">": "&gt;"
, '"': "&#34;"
, "'": "&#39;"
}
, _MATCH_HTML = /[&<>'"]/g;
function encode_char(c) {
return _ENCODE_HTML_RULES[c] || c;
};
`;
assert.doesNotThrow(() => { utils.escapeXML.toString(); });
assert.ok(typeof(utils.escapeXML.toString())==='string');
assert.ok(utils.escapeXML.toString()===stringified);
});
});

Expand Down

0 comments on commit 9ea36ba

Please sign in to comment.