Repository navigation
Open
Description
Summary
With numbers: 'hexadecimal' | 'binary' | 'octal', negative, fractional and non-finite numbers produce strings that are not valid JavaScript literals (0x-FF, 0x1.8, 0xINFINITY). The default output is correct.
Versions
- jsesc
3.1.0(commit819f534, tagv3.1.0) - Node.js v26.8.2
Reproduction
const jsesc = require('jsesc');
jsesc(-255, { numbers: 'hexadecimal' }); // "0x-FF" -> SyntaxError if embedded in code
jsesc(-10, { numbers: 'binary' }); // "0b-1010"
jsesc(-10, { numbers: 'octal' }); // "0o-12"
jsesc(1.5, { numbers: 'hexadecimal' }); // "0x1.8" -> invalid literal
jsesc(Infinity, { numbers: 'hexadecimal' }); // "0xINFINITY"
jsesc(NaN, { numbers: 'hexadecimal' }); // "0xNAN"
jsesc(-255); // "-255" (default output is valid)Expected behavior
jsesc(-255, { numbers: 'hexadecimal' })should be"-0xFF"(valid as-0xFFin JS source).- Same for binary/octal:
"-0b11111111","-0o377". - Non-integer and non-finite values should either throw a clear error or fall back to
String(value)("1.5","Infinity","NaN"); the current strings cannot be embedded in generated code.
Cause
argument.toString(16) returns a leading - for negative numbers, so '0x' + hexadecimal puts the sign after the prefix. Fractional/infinite values are not valid hex/binary/octal digits at all.
Suggested fix (verified against the reproduction)
--- a/jsesc.js
+++ b/jsesc.js
@@ -217,9 +217,13 @@
- let hexadecimal = argument.toString(16);
- if (!lowercaseHex) {
- hexadecimal = hexadecimal.toUpperCase();
- }
- result = '0x' + hexadecimal;
- } else if (useBinNumbers) {
- result = '0b' + argument.toString(2);
- } else if (useOctNumbers) {
- result = '0o' + argument.toString(8);
+ if (!Number.isFinite(argument) || !Number.isInteger(argument)) {
+ result = String(argument);
+ } else {
+ let hexadecimal = Math.abs(argument).toString(16);
+ if (!lowercaseHex) {
+ hexadecimal = hexadecimal.toUpperCase();
+ }
+ result = (argument < 0 ? '-0x' : '0x') + hexadecimal;
+ }
+ } else if (useBinNumbers) {
+ result = !Number.isFinite(argument) || !Number.isInteger(argument) ? String(argument) : (argument < 0 ? '-0b' : '0b') + Math.abs(argument).toString(2);
+ } else if (useOctNumbers) {
+ result = !Number.isFinite(argument) || !Number.isInteger(argument) ? String(argument) : (argument < 0 ? '-0o' : '0o') + Math.abs(argument).toString(8);The patch was applied to a copy of the module and the reproduction above was re-run: the output becomes -0xFF and remains "-255" for the default case.
Metadata
Metadata
Assignees
Labels
No labels
Activity