Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@bbob/html

Package Overview
Dependencies
Maintainers
1
Versions
56
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@bbob/html - npm Package Compare versions

Comparing version 2.1.1 to 2.2.0

20

CHANGELOG.md

@@ -6,2 +6,22 @@ # Change Log

<a name="2.2.0"></a>
# 2.2.0 (2018-10-11)
### Bug Fixes
* **html:** add more tests ([4ebc512](https://github.com/JiLiZART/bbob/commit/4ebc512))
* **html:** rigt import to support three shaking ([485852d](https://github.com/JiLiZART/bbob/commit/485852d))
### Features
* react render support, move some helper functions to plugin-helper ([1a84968](https://github.com/JiLiZART/bbob/commit/1a84968))
* **parser:** custom open and close tags support, html tags tests ([#3](https://github.com/JiLiZART/bbob/issues/3)) ([790825a](https://github.com/JiLiZART/bbob/commit/790825a))
* base preset package '[@bbob](https://github.com/bbob)/preset' ([b63864c](https://github.com/JiLiZART/bbob/commit/b63864c))
* new [@bbob](https://github.com/bbob)/html api ([#4](https://github.com/JiLiZART/bbob/issues/4)) ([575c1bb](https://github.com/JiLiZART/bbob/commit/575c1bb))
<a name="2.1.1"></a>

@@ -8,0 +28,0 @@ ## [2.1.1](https://github.com/JiLiZART/bbob/compare/@bbob/html@2.1.0...@bbob/html@2.1.1) (2018-10-07)

1152

dist/index.js
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.BbobHtml = {})));
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.BbobHtml = {})));
}(this, (function (exports) { 'use strict';
var escapeQuote = function escapeQuote(value) {
return value.replace(/"/g, '&quot;');
};
function unwrapExports (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
var attrValue = function attrValue(name, value) {
var type = typeof value;
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var types = {
boolean: function boolean() {
return value ? '' + name : '';
},
number: function number() {
return name + '="' + value + '"';
},
string: function string() {
return name + '="' + escapeQuote(value) + '"';
},
object: function object() {
return name + '="' + escapeQuote(JSON.stringify(value)) + '"';
}
};
var char_1 = createCommonjsModule(function (module, exports) {
return types[type] ? types[type]() : '';
};
exports.__esModule = true;
var N = '\n';
var TAB = '\t';
var F = '\f';
var R = '\r';
/**
* Transforms attrs to html params string
* @param values
*/
var attrs = function attrs(values) {
return Object.keys(values).reduce(function (arr, key) {
return [].concat(arr, [attrValue(key, values[key])]);
}, ['']).join(' ');
};
var EQ = '=';
var QUOTEMARK = '"';
var SPACE = ' ';
var SELFCLOSE_END_TAG = '/>';
var CLOSE_START_TAG = '</';
var START_TAG = '<';
var END_TAG = '>';
var OPEN_BRAKET = '[';
var CLOSE_BRAKET = ']';
var renderNode = function renderNode(node, _ref) {
var _ref$stripTags = _ref.stripTags,
stripTags = _ref$stripTags === undefined ? false : _ref$stripTags;
var SLASH = '/';
var BACKSLASH = '\\';
if (!node) return '';
var type = typeof node;
var PLACEHOLDER_SPACE_TAB = ' ';
var PLACEHOLDER_SPACE = ' ';
if (type === 'string' || type === 'number') {
return node;
}
// const getChar = String.fromCharCode;
if (type === 'object') {
if (stripTags === true) {
// eslint-disable-next-line no-use-before-define
return renderNodes(node.content, { stripTags: stripTags });
}
exports.N = N;
exports.F = F;
exports.R = R;
exports.TAB = TAB;
exports.EQ = EQ;
exports.QUOTEMARK = QUOTEMARK;
exports.SPACE = SPACE;
exports.OPEN_BRAKET = OPEN_BRAKET;
exports.CLOSE_BRAKET = CLOSE_BRAKET;
exports.SLASH = SLASH;
exports.PLACEHOLDER_SPACE_TAB = PLACEHOLDER_SPACE_TAB;
exports.PLACEHOLDER_SPACE = PLACEHOLDER_SPACE;
exports.BACKSLASH = BACKSLASH;
});
if (node.content === null) {
return [START_TAG, node.tag, attrs(node.attrs), SELFCLOSE_END_TAG].join('');
}
unwrapExports(char_1);
var char_2 = char_1.N;
var char_3 = char_1.F;
var char_4 = char_1.R;
var char_5 = char_1.TAB;
var char_6 = char_1.EQ;
var char_7 = char_1.QUOTEMARK;
var char_8 = char_1.SPACE;
var char_9 = char_1.OPEN_BRAKET;
var char_10 = char_1.CLOSE_BRAKET;
var char_11 = char_1.SLASH;
var char_12 = char_1.PLACEHOLDER_SPACE_TAB;
var char_13 = char_1.PLACEHOLDER_SPACE;
var char_14 = char_1.BACKSLASH;
// eslint-disable-next-line no-use-before-define
return [START_TAG, node.tag, attrs(node.attrs), END_TAG, renderNodes(node.content), CLOSE_START_TAG, node.tag, END_TAG].join('');
}
var lib = createCommonjsModule(function (module, exports) {
if (Array.isArray(node)) {
// eslint-disable-next-line no-use-before-define
return renderNodes(node, { stripTags: stripTags });
}
exports.__esModule = true;
exports.isEOL = exports.isStringNode = exports.isTagNode = exports.getNodeLength = exports.appendToNode = exports.attrValue = undefined;
return '';
};
var renderNodes = function renderNodes(nodes) {
var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
_ref2$stripTags = _ref2.stripTags,
stripTags = _ref2$stripTags === undefined ? false : _ref2$stripTags;
return [].concat(nodes).reduce(function (r, node) {
return r + renderNode(node, { stripTags: stripTags });
}, '');
};
var isTagNode = function isTagNode(el) {
return typeof el === 'object' && !!el.tag;
};
var isStringNode = function isStringNode(el) {
return typeof el === 'string';
};
var isEOL = function isEOL(el) {
return el === char_1.N;
};
var render = renderNodes;
var getNodeLength = function getNodeLength(node) {
if (isTagNode(node)) {
return node.content.reduce(function (count, contentNode) {
return count + getNodeLength(contentNode);
}, 0);
} else if (isStringNode(node)) {
return node.length;
}
exports.render = render;
exports.default = renderNodes;
return 0;
};
Object.defineProperty(exports, '__esModule', { value: true });
var appendToNode = function appendToNode(node, value) {
node.content.push(value);
};
var escapeQuote = function escapeQuote(value) {
return value.replace(/"/g, '&quot;');
};
var attrValue = function attrValue(name, value) {
var type = typeof value;
var types = {
boolean: function boolean() {
return value ? '' + name : '';
},
number: function number() {
return name + '="' + value + '"';
},
string: function string() {
return name + '="' + escapeQuote(value) + '"';
},
object: function object() {
return name + '="' + escapeQuote(JSON.stringify(value)) + '"';
}
};
return types[type] ? types[type]() : '';
};
exports.attrValue = attrValue;
exports.appendToNode = appendToNode;
exports.getNodeLength = getNodeLength;
exports.isTagNode = isTagNode;
exports.isStringNode = isStringNode;
exports.isEOL = isEOL;
});
unwrapExports(lib);
var lib_1 = lib.isEOL;
var lib_2 = lib.isStringNode;
var lib_3 = lib.isTagNode;
var lib_4 = lib.getNodeLength;
var lib_5 = lib.appendToNode;
var lib_6 = lib.attrValue;
var TagNode_1 = createCommonjsModule(function (module, exports) {
exports.__esModule = true;
exports.TagNode = undefined;
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);
}
}return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;
};
}();
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var TagNode = function () {
function TagNode(tag, attrs, content) {
_classCallCheck(this, TagNode);
this.tag = tag;
this.attrs = attrs;
this.content = [].concat(content);
}
TagNode.prototype.attr = function attr(name, value) {
if (typeof value !== 'undefined') {
this.attrs[name] = value;
}
return this.attrs[name];
};
TagNode.prototype.append = function append(value) {
return (0, lib.appendToNode)(this, value);
};
TagNode.prototype.toString = function toString() {
var OB = char_1.OPEN_BRAKET;
var CB = char_1.CLOSE_BRAKET;
return OB + this.tag + CB + this.content.reduce(function (r, node) {
return r + node.toString();
}, '') + OB + char_1.SLASH + this.tag + CB;
};
_createClass(TagNode, [{
key: 'length',
get: function get() {
return (0, lib.getNodeLength)(this);
}
}]);
return TagNode;
}();
TagNode.create = function (tag) {
var attrs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var content = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
return new TagNode(tag, attrs, content);
};
TagNode.isOf = function (node, type) {
return node.tag === type;
};
exports.TagNode = TagNode;
exports.default = TagNode;
});
var TagNode = unwrapExports(TagNode_1);
var TagNode_2 = TagNode_1.TagNode;
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
// type, value, line, row,
var TOKEN_TYPE_ID = 'type'; // 0;
var TOKEN_VALUE_ID = 'value'; // 1;
var TOKEN_COLUMN_ID = 'row'; // 2;
var TOKEN_LINE_ID = 'line'; // 3;
var TOKEN_TYPE_WORD = 'word';
var TOKEN_TYPE_TAG = 'tag';
var TOKEN_TYPE_ATTR_NAME = 'attr-name';
var TOKEN_TYPE_ATTR_VALUE = 'attr-value';
var TOKEN_TYPE_SPACE = 'space';
var TOKEN_TYPE_NEW_LINE = 'new-line';
var getTokenValue = function getTokenValue(token) {
return token[TOKEN_VALUE_ID];
};
var getTokenLine = function getTokenLine(token) {
return token[TOKEN_LINE_ID];
};
var getTokenColumn = function getTokenColumn(token) {
return token[TOKEN_COLUMN_ID];
};
var isTextToken = function isTextToken(token) {
return token[TOKEN_TYPE_ID] === TOKEN_TYPE_SPACE || token[TOKEN_TYPE_ID] === TOKEN_TYPE_NEW_LINE || token[TOKEN_TYPE_ID] === TOKEN_TYPE_WORD;
};
var isTagToken = function isTagToken(token) {
return token[TOKEN_TYPE_ID] === TOKEN_TYPE_TAG;
};
var isTagEnd = function isTagEnd(token) {
return getTokenValue(token).charCodeAt(0) === char_11.charCodeAt(0);
};
var isTagStart = function isTagStart(token) {
return !isTagEnd(token);
};
var isAttrNameToken = function isAttrNameToken(token) {
return token[TOKEN_TYPE_ID] === TOKEN_TYPE_ATTR_NAME;
};
var isAttrValueToken = function isAttrValueToken(token) {
return token[TOKEN_TYPE_ID] === TOKEN_TYPE_ATTR_VALUE;
};
var getTagName = function getTagName(token) {
var value = getTokenValue(token);
return isTagEnd(token) ? value.slice(1) : value;
};
var convertTagToText = function convertTagToText(token) {
var text = char_9;
if (isTagEnd(token)) {
text += char_11;
}
text += getTokenValue(token);
text += char_10;
return text;
};
var Token = function () {
/**
* @param {String} type
* @param {String} value
* @param line
* @param row
*/
function Token(type, value, line, row) {
_classCallCheck(this, Token);
this[TOKEN_TYPE_ID] = String(type);
this[TOKEN_VALUE_ID] = String(value);
this[TOKEN_LINE_ID] = Number(line);
this[TOKEN_COLUMN_ID] = Number(row);
}
Token.prototype.isEmpty = function isEmpty() {
return !!this[TOKEN_TYPE_ID];
};
Token.prototype.isText = function isText() {
return isTextToken(this);
};
Token.prototype.isTag = function isTag() {
return isTagToken(this);
};
Token.prototype.isAttrName = function isAttrName() {
return isAttrNameToken(this);
};
Token.prototype.isAttrValue = function isAttrValue() {
return isAttrValueToken(this);
};
Token.prototype.isStart = function isStart() {
return isTagStart(this);
};
Token.prototype.isEnd = function isEnd() {
return isTagEnd(this);
};
Token.prototype.getName = function getName() {
return getTagName(this);
};
Token.prototype.getValue = function getValue() {
return getTokenValue(this);
};
Token.prototype.getLine = function getLine() {
return getTokenLine(this);
};
Token.prototype.getColumn = function getColumn() {
return getTokenColumn(this);
};
Token.prototype.toString = function toString() {
return convertTagToText(this);
};
return Token;
}();
var TYPE_WORD = TOKEN_TYPE_WORD;
var TYPE_TAG = TOKEN_TYPE_TAG;
var TYPE_ATTR_NAME = TOKEN_TYPE_ATTR_NAME;
var TYPE_ATTR_VALUE = TOKEN_TYPE_ATTR_VALUE;
var TYPE_SPACE = TOKEN_TYPE_SPACE;
var TYPE_NEW_LINE = TOKEN_TYPE_NEW_LINE;
/* eslint-disable no-plusplus,no-param-reassign */
var EM = '!';
var createCharGrabber = function createCharGrabber(source) {
var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
onSkip = _ref.onSkip;
var idx = 0;
var skip = function skip() {
idx += 1;
if (onSkip) {
onSkip();
}
};
var hasNext = function hasNext() {
return source.length > idx;
};
var getRest = function getRest() {
return source.substr(idx);
};
return {
skip: skip,
hasNext: hasNext,
isLast: function isLast() {
return idx === source.length;
},
grabWhile: function grabWhile(cond) {
var start = idx;
while (hasNext() && cond(source[idx])) {
skip();
}
return source.substr(start, idx - start);
},
getNext: function getNext() {
return source[idx + 1];
},
getPrev: function getPrev() {
return source[idx - 1];
},
getCurr: function getCurr() {
return source[idx];
},
getRest: getRest,
substrUntilChar: function substrUntilChar(char$$1) {
var restStr = getRest();
var indexOfChar = restStr.indexOf(char$$1);
if (indexOfChar >= 0) {
return restStr.substr(0, indexOfChar);
}
return '';
}
};
};
var trimChar = function trimChar(str, charToRemove) {
while (str.charAt(0) === charToRemove) {
str = str.substring(1);
}
while (str.charAt(str.length - 1) === charToRemove) {
str = str.substring(0, str.length - 1);
}
return str;
};
var unquote = function unquote(str) {
return str.replace(char_14 + char_7, char_7);
};
var createToken = function createToken(type, value) {
var r = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
var cl = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
return new Token(type, value, r, cl);
};
/**
* @typedef {Object} Lexer
* @property {Function} tokenize
* @property {Function} isTokenNested
*/
/**
* @param {String} buffer
* @param {Object} options
* @param {Function} options.onToken
* @param {String} options.openTag
* @param {String} options.closeTag
* @return {Lexer}
*/
function createLexer(buffer) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var row = 0;
var col = 0;
var tokenIndex = -1;
var tokens = new Array(Math.floor(buffer.length));
var openTag = options.openTag || char_9;
var closeTag = options.closeTag || char_10;
var RESERVED_CHARS = [closeTag, openTag, char_7, char_14, char_8, char_5, char_6, char_2, EM];
var NOT_CHAR_TOKENS = [openTag, char_8, char_5, char_2];
var WHITESPACES = [char_8, char_5];
var SPECIAL_CHARS = [char_6, char_8, char_5];
var isCharReserved = function isCharReserved(char$$1) {
return RESERVED_CHARS.indexOf(char$$1) >= 0;
};
var isWhiteSpace = function isWhiteSpace(char$$1) {
return WHITESPACES.indexOf(char$$1) >= 0;
};
var isCharToken = function isCharToken(char$$1) {
return NOT_CHAR_TOKENS.indexOf(char$$1) === -1;
};
var isSpecialChar = function isSpecialChar(char$$1) {
return SPECIAL_CHARS.indexOf(char$$1) >= 0;
};
var emitToken = function emitToken(token) {
if (options.onToken) {
options.onToken(token);
}
tokenIndex += 1;
tokens[tokenIndex] = token;
};
var parseAttrs = function parseAttrs(str) {
var tagName = null;
var skipSpecialChars = false;
var attrTokens = [];
var attrCharGrabber = createCharGrabber(str);
var validAttr = function validAttr(char$$1) {
var isEQ = char$$1 === char_6;
var isWS = isWhiteSpace(char$$1);
var prevChar = attrCharGrabber.getPrev();
var nextChar = attrCharGrabber.getNext();
var isPrevSLASH = prevChar === char_14;
var isTagNameEmpty = tagName === null;
if (isTagNameEmpty) {
return (isEQ || isWS || attrCharGrabber.isLast()) === false;
}
if (skipSpecialChars && isSpecialChar(char$$1)) {
return true;
}
if (char$$1 === char_7 && !isPrevSLASH) {
skipSpecialChars = !skipSpecialChars;
if (!skipSpecialChars && !(nextChar === char_6 || isWhiteSpace(nextChar))) {
return false;
}
}
return (isEQ || isWS) === false;
};
var nextAttr = function nextAttr() {
var attrStr = attrCharGrabber.grabWhile(validAttr);
var currChar = attrCharGrabber.getCurr();
// first string before space is a tag name
if (tagName === null) {
tagName = attrStr;
} else if (isWhiteSpace(currChar) || currChar === char_7 || !attrCharGrabber.hasNext()) {
var escaped = unquote(trimChar(attrStr, char_7));
attrTokens.push(createToken(TYPE_ATTR_VALUE, escaped, row, col));
} else {
attrTokens.push(createToken(TYPE_ATTR_NAME, attrStr, row, col));
}
attrCharGrabber.skip();
};
while (attrCharGrabber.hasNext()) {
nextAttr();
}
return { tag: tagName, attrs: attrTokens };
};
var bufferGrabber = createCharGrabber(buffer, {
onSkip: function onSkip() {
col++;
}
});
var next = function next() {
var char$$1 = bufferGrabber.getCurr();
if (char$$1 === char_2) {
bufferGrabber.skip();
col = 0;
row++;
emitToken(createToken(TYPE_NEW_LINE, char$$1, row, col));
} else if (isWhiteSpace(char$$1)) {
var str = bufferGrabber.grabWhile(isWhiteSpace);
emitToken(createToken(TYPE_SPACE, str, row, col));
} else if (char$$1 === openTag) {
var nextChar = bufferGrabber.getNext();
bufferGrabber.skip(); // skip openTag
// detect case where we have '[My word [tag][/tag]' or we have '[My last line word'
var substr = bufferGrabber.substrUntilChar(closeTag);
var hasInvalidChars = substr.length === 0 || substr.indexOf(openTag) >= 0;
if (isCharReserved(nextChar) || hasInvalidChars || bufferGrabber.isLast()) {
emitToken(createToken(TYPE_WORD, char$$1, row, col));
} else {
var _str = bufferGrabber.grabWhile(function (val) {
return val !== closeTag;
});
bufferGrabber.skip(); // skip closeTag
var isNoAttrsInTag = _str.indexOf(char_6) === -1;
var isClosingTag = _str[0] === char_11;
if (isNoAttrsInTag || isClosingTag) {
emitToken(createToken(TYPE_TAG, _str, row, col));
} else {
var parsed = parseAttrs(_str);
emitToken(createToken(TYPE_TAG, parsed.tag, row, col));
parsed.attrs.map(emitToken);
}
}
} else if (char$$1 === closeTag) {
bufferGrabber.skip();
emitToken(createToken(TYPE_WORD, char$$1, row, col));
} else if (isCharToken(char$$1)) {
var _str2 = bufferGrabber.grabWhile(isCharToken);
emitToken(createToken(TYPE_WORD, _str2, row, col));
}
};
var tokenize = function tokenize() {
while (bufferGrabber.hasNext()) {
next();
}
tokens.length = tokenIndex + 1;
return tokens;
};
var isTokenNested = function isTokenNested(token) {
var value = openTag + char_11 + token.getValue();
return buffer.indexOf(value) > -1;
};
return {
tokenize: tokenize,
isTokenNested: isTokenNested
};
}
/**
* @private
* @type {Array}
*/
var nodes = void 0;
/**
* @private
* @type {Array}
*/
var nestedNodes = void 0;
/**
* @private
* @type {Array}
*/
var tagNodes = void 0;
/**
* @private
* @type {Array}
*/
var tagNodesAttrName = void 0;
var options = {};
var tokenizer = null;
// eslint-disable-next-line no-unused-vars
var tokens = null;
/**
* @private
* @param token
* @return {*}
*/
var isTagNested = function isTagNested(token) {
return tokenizer.isTokenNested(token);
};
/**
* @private
* @return {TagNode}
*/
var getLastTagNode = function getLastTagNode() {
return tagNodes.length ? tagNodes[tagNodes.length - 1] : null;
};
/**
* @private
* @param {Token} token
* @return {Array}
*/
var createTagNode = function createTagNode(token) {
return tagNodes.push(TagNode.create(token.getValue()));
};
/**
* @private
* @param {Token} token
* @return {Array}
*/
var createTagNodeAttrName = function createTagNodeAttrName(token) {
return tagNodesAttrName.push(token.getValue());
};
/**
* @private
* @return {Array}
*/
var getTagNodeAttrName = function getTagNodeAttrName() {
return tagNodesAttrName.length ? tagNodesAttrName[tagNodesAttrName.length - 1] : null;
};
/**
* @private
* @return {Array}
*/
var clearTagNodeAttrName = function clearTagNodeAttrName() {
if (tagNodesAttrName.length) {
tagNodesAttrName.pop();
}
};
/**
* @private
* @return {Array}
*/
var clearTagNode = function clearTagNode() {
if (tagNodes.length) {
tagNodes.pop();
clearTagNodeAttrName();
}
};
/**
* @private
* @return {Array}
*/
var getNodes = function getNodes() {
if (nestedNodes.length) {
var nestedNode = nestedNodes[nestedNodes.length - 1];
return nestedNode.content;
}
return nodes;
};
/**
* @private
* @param tag
*/
var appendNode = function appendNode(tag) {
getNodes().push(tag);
};
/**
* @private
* @param value
* @return {boolean}
*/
var isAllowedTag = function isAllowedTag(value) {
if (options.onlyAllowTags && options.onlyAllowTags.length) {
return options.onlyAllowTags.indexOf(value) >= 0;
}
return true;
};
/**
* @private
* @param {Token} token
*/
var handleTagStart = function handleTagStart(token) {
if (token.isStart()) {
createTagNode(token);
if (isTagNested(token)) {
nestedNodes.push(getLastTagNode());
} else {
appendNode(getLastTagNode());
clearTagNode();
}
}
};
/**
* @private
* @param {Token} token
*/
var handleTagEnd = function handleTagEnd(token) {
if (token.isEnd()) {
clearTagNode();
var lastNestedNode = nestedNodes.pop();
if (lastNestedNode) {
appendNode(lastNestedNode);
} else if (options.onError) {
var tag = token.getValue();
var line = token.getLine();
var column = token.getColumn();
options.onError({
message: 'Inconsistent tag \'' + tag + '\' on line ' + line + ' and column ' + column,
lineNumber: line,
columnNumber: column
});
}
}
};
/**
* @private
* @param {Token} token
*/
var handleTagToken = function handleTagToken(token) {
if (token.isTag()) {
if (isAllowedTag(token.getName())) {
// [tag]
handleTagStart(token);
// [/tag]
handleTagEnd(token);
} else {
appendNode(token.toString());
}
}
};
/**
* @private
* @param {Token} token
*/
var handleTagNode = function handleTagNode(token) {
var tagNode = getLastTagNode();
if (tagNode) {
if (token.isAttrName()) {
createTagNodeAttrName(token);
tagNode.attr(getTagNodeAttrName(), '');
} else if (token.isAttrValue()) {
var attrName = getTagNodeAttrName();
var attrValue = token.getValue();
if (attrName) {
tagNode.attr(getTagNodeAttrName(), attrValue);
clearTagNodeAttrName();
} else {
tagNode.attr(attrValue, attrValue);
}
} else if (token.isText()) {
tagNode.append(token.getValue());
}
} else if (token.isText()) {
appendNode(token.getValue());
}
};
/**
* @private
* @param token
*/
var parseToken = function parseToken(token) {
handleTagToken(token);
handleTagNode(token);
};
/**
* @public
* @return {Array}
*/
var parse = function parse(input) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
options = opts;
tokenizer = (opts.createTokenizer ? opts.createTokenizer : createLexer)(input, {
onToken: parseToken,
onlyAllowTags: options.onlyAllowTags,
openTag: options.openTag,
closeTag: options.closeTag
});
nodes = [];
nestedNodes = [];
tagNodes = [];
tagNodesAttrName = [];
tokens = tokenizer.tokenize();
return nodes;
};
/* eslint-disable no-plusplus */
var isObj = function isObj(value) {
return typeof value === 'object';
};
var isBool = function isBool(value) {
return typeof value === 'boolean';
};
function iterate(t, cb) {
var tree = t;
if (Array.isArray(tree)) {
for (var idx = 0; idx < tree.length; idx++) {
tree[idx] = iterate(cb(tree[idx]), cb);
}
} else if (tree && isObj(tree) && tree.content) {
iterate(tree.content, cb);
}
return tree;
}
function same(expected, actual) {
if (typeof expected !== typeof actual) {
return false;
}
if (!isObj(expected) || expected === null) {
return expected === actual;
}
if (Array.isArray(expected)) {
return expected.every(function (exp) {
return [].some.call(actual, function (act) {
return same(exp, act);
});
});
}
return Object.keys(expected).every(function (key) {
var ao = actual[key];
var eo = expected[key];
if (isObj(eo) && eo !== null && ao !== null) {
return same(eo, ao);
}
if (isBool(eo)) {
return eo !== (ao === null);
}
return ao === eo;
});
}
function match(expression, cb) {
return Array.isArray(expression) ? iterate(this, function (node) {
for (var idx = 0; idx < expression.length; idx++) {
if (same(expression[idx], node)) {
return cb(node);
}
}
return node;
}) : iterate(this, function (node) {
return same(expression, node) ? cb(node) : node;
});
}
function walk(cb) {
return iterate(this, cb);
}
function bbob(plugs) {
var plugins = typeof plugs === 'function' ? [plugs] : plugs || [];
var options = {
skipParse: false
};
return {
process: function process(input, opts) {
options = opts || {};
var parseFn = options.parser || parse;
var renderFn = options.render;
if (typeof parseFn !== 'function') {
throw new Error('"parser" is not a function, please pass to "process(input, { parser })" right function');
}
var tree = options.skipParse ? input || [] : parseFn(input, options);
// raw tree before modification with plugins
var raw = tree;
tree.walk = walk;
tree.match = match;
plugins.forEach(function (plugin) {
tree = plugin(tree, {
parse: parseFn,
render: renderFn,
iterate: iterate,
match: match
}) || tree;
});
return {
get html() {
if (typeof renderFn !== 'function') {
throw new Error('"render" function not defined, please pass to "process(input, { render })"');
}
return renderFn(tree, tree.options);
},
tree: tree,
raw: raw,
messages: tree.messages
};
}
};
}
var escapeQuote = function escapeQuote(value) {
return value.replace(/"/g, '&quot;');
};
var attrValue = function attrValue(name, value) {
var type = typeof value;
var types = {
boolean: function boolean() {
return value ? '' + name : '';
},
number: function number() {
return name + '="' + value + '"';
},
string: function string() {
return name + '="' + escapeQuote(value) + '"';
},
object: function object() {
return name + '="' + escapeQuote(JSON.stringify(value)) + '"';
}
};
return types[type] ? types[type]() : '';
};
/**
* Transforms attrs to html params string
* @param values
*/
var attrs = function attrs(values) {
return Object.keys(values).reduce(function (arr, key) {
return [].concat(arr, [attrValue(key, values[key])]);
}, ['']).join(' ');
};
var SELFCLOSE_END_TAG = '/>';
var CLOSE_START_TAG = '</';
var START_TAG = '<';
var END_TAG = '>';
var renderNode = function renderNode(node, _ref) {
var _ref$stripTags = _ref.stripTags,
stripTags = _ref$stripTags === undefined ? false : _ref$stripTags;
if (!node) return '';
var type = typeof node;
if (type === 'string' || type === 'number') {
return node;
}
if (type === 'object') {
if (stripTags === true) {
// eslint-disable-next-line no-use-before-define
return renderNodes(node.content, { stripTags: stripTags });
}
if (node.content === null) {
return [START_TAG, node.tag, attrs(node.attrs), SELFCLOSE_END_TAG].join('');
}
// eslint-disable-next-line no-use-before-define
return [START_TAG, node.tag, attrs(node.attrs), END_TAG, renderNodes(node.content), CLOSE_START_TAG, node.tag, END_TAG].join('');
}
if (Array.isArray(node)) {
// eslint-disable-next-line no-use-before-define
return renderNodes(node, { stripTags: stripTags });
}
return '';
};
var renderNodes = function renderNodes(nodes) {
var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
_ref2$stripTags = _ref2.stripTags,
stripTags = _ref2$stripTags === undefined ? false : _ref2$stripTags;
return [].concat(nodes).reduce(function (r, node) {
return r + renderNode(node, { stripTags: stripTags });
}, '');
};
var toHTML = function toHTML(source, plugins) {
return bbob(plugins).process(source, { render: renderNodes }).html;
};
var render = renderNodes;
exports.render = render;
exports.default = toHTML;
Object.defineProperty(exports, '__esModule', { value: true });
})));

2

dist/index.min.js

@@ -1,1 +0,1 @@

!function(t,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n(t.BbobHtml={})}(this,function(t){"use strict";var c=function(t){return t.replace(/"/g,"&quot;")},u=function(i){return Object.keys(i).reduce(function(t,n){return[].concat(t,[(e=n,r=i[n],o=typeof r,u={boolean:function(){return r?""+e:""},number:function(){return e+'="'+r+'"'},string:function(){return e+'="'+c(r)+'"'},object:function(){return e+'="'+c(JSON.stringify(r))+'"'}},u[o]?u[o]():"")]);var e,r,o,u},[""]).join(" ")},i="/>",f="</",a="<",s=">",d=function(t){var n=(1<arguments.length&&void 0!==arguments[1]?arguments[1]:{}).stripTags,e=void 0!==n&&n;return[].concat(t).reduce(function(t,n){return t+function(t,n){var e=n.stripTags,r=void 0!==e&&e;if(!t)return"";var o=typeof t;return"string"===o||"number"===o?t:"object"===o?!0===r?d(t.content,{stripTags:r}):null===t.content?""+a+t.tag+u(t.attrs)+i:""+a+t.tag+u(t.attrs)+s+d(t.content)+f+t.tag+s:Array.isArray(t)?d(t,{stripTags:r}):""}(n,{stripTags:e})},"")};t.render=d,t.default=d,Object.defineProperty(t,"__esModule",{value:!0})});
!function(t,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n(t.BbobHtml={})}(this,function(t){"use strict";function n(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function e(t,n){return t(n={exports:{}},n.exports),n.exports}var u=e(function(t,n){n.__esModule=!0;n.N="\n",n.F="\f",n.R="\r",n.TAB="\t",n.EQ="=",n.QUOTEMARK='"',n.SPACE=" ",n.OPEN_BRAKET="[",n.CLOSE_BRAKET="]",n.SLASH="/",n.PLACEHOLDER_SPACE_TAB=" ",n.PLACEHOLDER_SPACE=" ",n.BACKSLASH="\\"});n(u);var A=u.N,a=u.TAB,b=u.EQ,E=u.QUOTEMARK,N=u.SPACE,m=u.OPEN_BRAKET,O=u.CLOSE_BRAKET,S=u.SLASH,x=u.BACKSLASH,o=e(function(t,n){n.__esModule=!0,n.isEOL=n.isStringNode=n.isTagNode=n.getNodeLength=n.appendToNode=n.attrValue=void 0;var r=function(t){return"object"==typeof t&&!!t.tag},o=function(t){return"string"==typeof t},i=function(t){return t.replace(/"/g,"&quot;")};n.attrValue=function(t,n){var e=typeof n,r={boolean:function(){return n?""+t:""},number:function(){return t+'="'+n+'"'},string:function(){return t+'="'+i(n)+'"'},object:function(){return t+'="'+i(JSON.stringify(n))+'"'}};return r[e]?r[e]():""},n.appendToNode=function(t,n){t.content.push(n)},n.getNodeLength=function e(t){return r(t)?t.content.reduce(function(t,n){return t+e(n)},0):o(t)?t.length:0},n.isTagNode=r,n.isStringNode=o,n.isEOL=function(t){return t===u.N}});n(o);var r=e(function(t,n){n.__esModule=!0,n.TagNode=void 0;var e=function(){function r(t,n){for(var e=0;e<n.length;e++){var r=n[e];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(t,n,e){return n&&r(t.prototype,n),e&&r(t,e),t}}();var r=function(){function r(t,n,e){!function(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}(this,r),this.tag=t,this.attrs=n,this.content=[].concat(e)}return r.prototype.attr=function(t,n){return void 0!==n&&(this.attrs[t]=n),this.attrs[t]},r.prototype.append=function(t){return(0,o.appendToNode)(this,t)},r.prototype.toString=function(){var t=u.OPEN_BRAKET,n=u.CLOSE_BRAKET;return t+this.tag+n+this.content.reduce(function(t,n){return t+""+n},"")+t+u.SLASH+this.tag+n},e(r,[{key:"length",get:function(){return(0,o.getNodeLength)(this)}}]),r}();r.create=function(t){return new r(t,1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},2<arguments.length&&void 0!==arguments[2]?arguments[2]:[])},r.isOf=function(t,n){return t.tag===n},n.TagNode=r,n.default=r}),i=n(r);var s="type",f="value",c="line",l="word",p="attr-name",g="attr-value",h="space",d="new-line",v=function(t){return t[f]},y=function(t){return v(t).charCodeAt(0)==S.charCodeAt(0)},T=function(){function o(t,n,e,r){!function(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}(this,o),this[s]=t+"",this[f]=n+"",this[c]=+e,this.row=+r}return o.prototype.isEmpty=function(){return!!this[s]},o.prototype.isText=function(){return(t=this)[s]===h||t[s]===d||t[s]===l;var t},o.prototype.isTag=function(){return"tag"===this[s]},o.prototype.isAttrName=function(){return this[s]===p},o.prototype.isAttrValue=function(){return this[s]===g},o.prototype.isStart=function(){return!y(this)},o.prototype.isEnd=function(){return y(this)},o.prototype.getName=function(){return n=v(t=this),y(t)?n.slice(1):n;var t,n},o.prototype.getValue=function(){return v(this)},o.prototype.getLine=function(){return this[c]},o.prototype.getColumn=function(){return this.row},o.prototype.toString=function(){return n=m,y(t=this)&&(n+=S),n+=v(t),n+=O;var t,n},o}(),k=l,w=function(e){var t=(1<arguments.length&&void 0!==arguments[1]?arguments[1]:{}).onSkip,r=0,o=function(){r+=1,t&&t()},i=function(){return r<e.length},u=function(){return e.substr(r)};return{skip:o,hasNext:i,isLast:function(){return r===e.length},grabWhile:function(t){for(var n=r;i()&&t(e[r]);)o();return e.substr(n,r-n)},getNext:function(){return e[r+1]},getPrev:function(){return e[r-1]},getCurr:function(){return e[r]},getRest:u,substrUntilChar:function(t){var n=u(),e=n.indexOf(t);return e<0?"":n.substr(0,e)}}},C=function(t,n){return new T(t,n,2<arguments.length&&void 0!==arguments[2]?arguments[2]:0,3<arguments.length&&void 0!==arguments[3]?arguments[3]:0)};function L(e){var n=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},f=0,c=0,r=-1,o=Array(Math.floor(e.length)),s=n.openTag||m,l=n.closeTag||O,p=[l,s,E,x,N,a,b,A,"!"],i=[s,N,a,A],u=[N,a],g=[b,N,a],h=function(t){return 0<=u.indexOf(t)},d=function(t){return-1==i.indexOf(t)},v=function(t){n.onToken&&n.onToken(t),o[r+=1]=t},y=function(t){for(var u=null,a=!1,r=[],s=w(t),o=function(t){var n=t===b,e=h(t),r=s.getPrev(),o=s.getNext(),i=r===x;return null===u?!1===(n||e||s.isLast()):!(!a||g.indexOf(t)<0)||!!(t!==E||i||(a=!a)||o===b||h(o))&&!1===(n||e)},n=function(){var t=s.grabWhile(o),n=s.getCurr();if(null===u)u=t;else if(h(n)||n===E||!s.hasNext()){var e=function(t,n){for(;t.charAt(0)===n;)t=t.substring(1);for(;t.charAt(t.length-1)===n;)t=t.substring(0,t.length-1);return t}(t,E).replace(x+E,E);r.push(C("attr-value",e,f,c))}else r.push(C("attr-name",t,f,c));s.skip()};s.hasNext();)n();return{tag:u,attrs:r}},T=w(e,{onSkip:function(){c++}}),t=function(){var t=T.getCurr();if(t===A)T.skip(),v(C("new-line",t,++f,c=0));else if(h(t)){var n=T.grabWhile(h);v(C("space",n,f,c))}else if(t===s){var e=T.getNext();T.skip();var r=T.substrUntilChar(l),o=0===r.length||0<=r.indexOf(s);if(0<=p.indexOf(e)||o||T.isLast())v(C(k,t,f,c));else{var i=T.grabWhile(function(t){return t!==l});if(T.skip(),-1==i.indexOf(b)||i[0]===S)v(C("tag",i,f,c));else{var u=y(i);v(C("tag",u.tag,f,c)),u.attrs.map(v)}}}else if(t===l)T.skip(),v(C(k,t,f,c));else if(d(t)){var a=T.grabWhile(d);v(C(k,a,f,c))}};return{tokenize:function(){for(;T.hasNext();)t();return o.length=r+1,o},isTokenNested:function(t){var n=s+S+t.getValue();return-1<e.indexOf(n)}}}var _=void 0,P=void 0,j=void 0,B=void 0,R={},V=null,K=function(){return j.length?j[j.length-1]:null},H=function(){return B.length?B[B.length-1]:null},M=function(){B.length&&B.pop()},W=function(){j.length&&(j.pop(),M())},z=function(t){(P.length?P[P.length-1].content:_).push(t)},Q=function(t){t.isStart()&&(j.push(i.create(t.getValue())),V.isTokenNested(t)?P.push(K()):(z(K()),W()))},U=function(t){var n;t.isTag()&&(n=t.getName(),R.onlyAllowTags&&R.onlyAllowTags.length&&R.onlyAllowTags.indexOf(n)<0?z(""+t):(Q(t),function(t){if(t.isEnd()){W();var n=P.pop();if(n)z(n);else if(R.onError){var e=t.getValue(),r=t.getLine(),o=t.getColumn();R.onError({message:"Inconsistent tag '"+e+"' on line "+r+" and column "+o,lineNumber:r,columnNumber:o})}}}(t)))},q=function(t){var n=K();if(n)if(t.isAttrName())B.push(t.getValue()),n.attr(H(),"");else if(t.isAttrValue()){var e=H(),r=t.getValue();e?(n.attr(H(),r),M()):n.attr(r,r)}else t.isText()&&n.append(t.getValue());else t.isText()&&z(t.getValue())},D=function(t){U(t),q(t)},J=function(t){var n=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{};return V=((R=n).createTokenizer?n.createTokenizer:L)(t,{onToken:D,onlyAllowTags:R.onlyAllowTags,openTag:R.openTag,closeTag:R.closeTag}),_=[],P=[],j=[],B=[],V.tokenize(),_},F=function(t){return"object"==typeof t},I=function(t){return"boolean"==typeof t};function G(t,n){var e=t;if(Array.isArray(e))for(var r=0;r<e.length;r++)e[r]=G(n(e[r]),n);else e&&F(e)&&e.content&&G(e.content,n);return e}function X(r,o){return typeof r==typeof o&&(F(r)&&null!==r?Array.isArray(r)?r.every(function(n){return[].some.call(o,function(t){return X(n,t)})}):Object.keys(r).every(function(t){var n=o[t],e=r[t];return F(e)&&null!==e&&null!==n?X(e,n):I(e)?e!==(null===n):n===e}):r===o)}function Y(e,r){return G(this,Array.isArray(e)?function(t){for(var n=0;n<e.length;n++)if(X(e[n],t))return r(t);return t}:function(t){return X(e,t)?r(t):t})}function Z(t){return G(this,t)}var $=function(t){return t.replace(/"/g,"&quot;")},tt=function(u){return Object.keys(u).reduce(function(t,n){return[].concat(t,[(e=n,r=u[n],o=typeof r,i={boolean:function(){return r?""+e:""},number:function(){return e+'="'+r+'"'},string:function(){return e+'="'+$(r)+'"'},object:function(){return e+'="'+$(JSON.stringify(r))+'"'}},i[o]?i[o]():"")]);var e,r,o,i},[""]).join(" ")},nt="/>",et="</",rt="<",ot=">",it=function(t){var n=(1<arguments.length&&void 0!==arguments[1]?arguments[1]:{}).stripTags,e=void 0!==n&&n;return[].concat(t).reduce(function(t,n){return t+function(t,n){var e=n.stripTags,r=void 0!==e&&e;if(!t)return"";var o=typeof t;return"string"===o||"number"===o?t:"object"===o?!0===r?it(t.content,{stripTags:r}):null===t.content?""+rt+t.tag+tt(t.attrs)+nt:""+rt+t.tag+tt(t.attrs)+ot+it(t.content)+et+t.tag+ot:Array.isArray(t)?it(t,{stripTags:r}):""}(n,{stripTags:e})},"")};t.render=it,t.default=function(t,n){return(e=n,u="function"==typeof e?[e]:e||[],a={skipParse:!1},{process:function(t,n){var e=(a=n||{}).parser||J,r=a.render;if("function"!=typeof e)throw Error('"parser" is not a function, please pass to "process(input, { parser })" right function');var o=a.skipParse?t||[]:e(t,a),i=o;return o.walk=Z,o.match=Y,u.forEach(function(t){o=t(o,{parse:e,render:r,iterate:G,match:Y})||o}),{get html(){if("function"!=typeof r)throw Error('"render" function not defined, please pass to "process(input, { render })"');return r(o,o.options)},tree:o,raw:i,messages:o.messages}}}).process(t,{render:it}).html;var e,u,a},Object.defineProperty(t,"__esModule",{value:!0})});

@@ -0,1 +1,2 @@

import core from '@bbob/core';
import { attrValue } from '@bbob/plugin-helper';

@@ -61,3 +62,7 @@

var toHTML = function toHTML(source, plugins) {
return core(plugins).process(source, { render: renderNodes }).html;
};
export var render = renderNodes;
export default renderNodes;
export default toHTML;

@@ -6,4 +6,10 @@ 'use strict';

var _core = require('@bbob/core');
var _core2 = _interopRequireDefault(_core);
var _pluginHelper = require('@bbob/plugin-helper');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**

@@ -67,3 +73,7 @@ * Transforms attrs to html params string

var toHTML = function toHTML(source, plugins) {
return (0, _core2.default)(plugins).process(source, { render: renderNodes }).html;
};
var render = exports.render = renderNodes;
exports.default = renderNodes;
exports.default = toHTML;
{
"name": "@bbob/html",
"version": "2.1.1",
"version": "2.2.0",
"description": "HTML renderer for BBCode pareser BBob",
"keywords": [],
"dependencies": {
"@bbob/core": "^2.2.0",
"@bbob/plugin-helper": "^2.0.1"
},
"devDependencies": {
"@bbob/parser": "^2.2.0"
},
"main": "lib/index.js",

@@ -13,0 +11,0 @@ "module": "es/index.js",

@@ -0,1 +1,2 @@

import core from '@bbob/core';
import { attrValue } from '@bbob/plugin-helper';

@@ -51,3 +52,5 @@

const toHTML = (source, plugins) => core(plugins).process(source, { render: renderNodes }).html;
export const render = renderNodes;
export default renderNodes;
export default toHTML;
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc