github-pages-deploy-action/node_modules/strip-json-comments/index.js

74 lines
2.0 KiB
JavaScript
Raw Normal View History

2020-03-07 11:45:40 +08:00
'use strict';
2020-03-31 20:40:00 +08:00
const singleComment = Symbol('singleComment');
const multiComment = Symbol('multiComment');
const stripWithoutWhitespace = () => '';
const stripWithWhitespace = (string, start, end) => string.slice(start, end).replace(/\S/g, ' ');
2020-03-07 11:45:40 +08:00
2020-03-31 20:40:00 +08:00
const isEscaped = (jsonString, quotePosition) => {
let index = quotePosition - 1;
let backslashCount = 0;
2020-03-07 11:45:40 +08:00
2020-03-31 20:40:00 +08:00
while (jsonString[index] === '\\') {
index -= 1;
backslashCount += 1;
}
return Boolean(backslashCount % 2);
};
2020-03-07 11:45:40 +08:00
2020-03-31 20:40:00 +08:00
module.exports = (jsonString, options = {}) => {
const strip = options.whitespace === false ? stripWithoutWhitespace : stripWithWhitespace;
2020-03-07 11:45:40 +08:00
2020-03-31 20:40:00 +08:00
let insideString = false;
let insideComment = false;
let offset = 0;
let result = '';
2020-03-07 11:45:40 +08:00
2020-03-31 20:40:00 +08:00
for (let i = 0; i < jsonString.length; i++) {
const currentCharacter = jsonString[i];
const nextCharacter = jsonString[i + 1];
2020-03-07 11:45:40 +08:00
2020-03-31 20:40:00 +08:00
if (!insideComment && currentCharacter === '"') {
const escaped = isEscaped(jsonString, i);
2020-03-07 11:45:40 +08:00
if (!escaped) {
insideString = !insideString;
}
}
if (insideString) {
continue;
}
2020-03-31 20:40:00 +08:00
if (!insideComment && currentCharacter + nextCharacter === '//') {
result += jsonString.slice(offset, i);
2020-03-07 11:45:40 +08:00
offset = i;
insideComment = singleComment;
i++;
2020-03-31 20:40:00 +08:00
} else if (insideComment === singleComment && currentCharacter + nextCharacter === '\r\n') {
2020-03-07 11:45:40 +08:00
i++;
insideComment = false;
2020-03-31 20:40:00 +08:00
result += strip(jsonString, offset, i);
2020-03-07 11:45:40 +08:00
offset = i;
continue;
2020-03-31 20:40:00 +08:00
} else if (insideComment === singleComment && currentCharacter === '\n') {
2020-03-07 11:45:40 +08:00
insideComment = false;
2020-03-31 20:40:00 +08:00
result += strip(jsonString, offset, i);
2020-03-07 11:45:40 +08:00
offset = i;
2020-03-31 20:40:00 +08:00
} else if (!insideComment && currentCharacter + nextCharacter === '/*') {
result += jsonString.slice(offset, i);
2020-03-07 11:45:40 +08:00
offset = i;
insideComment = multiComment;
i++;
continue;
2020-03-31 20:40:00 +08:00
} else if (insideComment === multiComment && currentCharacter + nextCharacter === '*/') {
2020-03-07 11:45:40 +08:00
i++;
insideComment = false;
2020-03-31 20:40:00 +08:00
result += strip(jsonString, offset, i + 1);
2020-03-07 11:45:40 +08:00
offset = i + 1;
continue;
}
}
2020-03-31 20:40:00 +08:00
return result + (insideComment ? strip(jsonString.slice(offset)) : jsonString.slice(offset));
2020-03-07 11:45:40 +08:00
};