Comparing version 1.0.0-beta.5 to 1.0.0-beta.6
@@ -6,6 +6,13 @@ "use strict"; | ||
}); | ||
exports.addCommentBefore = addCommentBefore; | ||
exports.default = addComment; | ||
function addCommentBefore(str, indent, comment) { | ||
if (!comment) return str; | ||
var cc = comment.replace(/[\s\S]^/gm, "$&".concat(indent, "#")); | ||
return "#".concat(cc, "\n").concat(indent).concat(str); | ||
} | ||
function addComment(str, indent, comment) { | ||
return !comment ? str : comment.indexOf('\n') === -1 ? "".concat(str, " #").concat(comment) : "".concat(str, "\n") + comment.replace(/^/gm, "".concat(indent || '', "#")); | ||
} |
@@ -74,4 +74,7 @@ "use strict"; | ||
var parseNode = context.parseNode, | ||
src = context.src; | ||
var lineStart = context.lineStart; | ||
src = context.src; // It's easier to recalculate lineStart here rather than tracking down the | ||
// last context from which to read it -- eemeli/yaml#2 | ||
var lineStart = _Node2.default.startOfLine(src, start); | ||
var firstItem = this.items[0]; | ||
@@ -83,3 +86,3 @@ this.valueRange = _Range.default.copy(firstItem.valueRange); | ||
var ch = src[offset]; | ||
var atLineStart = false; | ||
var atLineStart = _Node2.default.endOfWhiteSpace(src, lineStart) === offset; | ||
@@ -86,0 +89,0 @@ while (ch) { |
@@ -228,3 +228,3 @@ "use strict"; | ||
var src = context.src; | ||
var offset = src.charCodeAt(start) === 0xFEFF ? start + 1 : start; // skip BOM | ||
var offset = src.charCodeAt(start) === 0xfeff ? start + 1 : start; // skip BOM | ||
@@ -231,0 +231,0 @@ offset = this.parseDirectives(offset); |
@@ -70,6 +70,6 @@ "use strict"; | ||
value: function atDocumentBoundary(src, offset, sep) { | ||
var ch0 = src[offset]; | ||
if (!ch0) return true; | ||
var prev = src[offset - 1]; | ||
if (prev && prev !== '\n') return false; | ||
var ch0 = src[offset]; | ||
if (!ch0) return true; | ||
@@ -135,2 +135,13 @@ if (sep) { | ||
} | ||
}, { | ||
key: "startOfLine", | ||
value: function startOfLine(src, offset) { | ||
var ch = src[offset - 1]; | ||
while (ch && ch !== '\n') { | ||
ch = src[offset -= 1]; | ||
} | ||
return offset + 1; | ||
} | ||
/** | ||
@@ -137,0 +148,0 @@ * End of indentation, or null if the line's indent level is not more |
@@ -77,3 +77,3 @@ "use strict"; | ||
src = _this$context.src; | ||
if (src[end - 1] !== "'") errors.push(new _errors.YAMLSyntaxError(this, 'Missing closing \'quote')); | ||
if (src[end - 1] !== "'") errors.push(new _errors.YAMLSyntaxError(this, "Missing closing 'quote")); | ||
var str = ''; | ||
@@ -80,0 +80,0 @@ |
@@ -18,3 +18,3 @@ "use strict"; | ||
var _Tags = _interopRequireWildcard(require("./Tags")); | ||
var _schema = _interopRequireWildcard(require("./schema")); | ||
@@ -48,19 +48,12 @@ var _Collection = _interopRequireWildcard(require("./schema/Collection")); | ||
function () { | ||
function Document(tags) { | ||
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
function Document(schema) { | ||
_classCallCheck(this, Document); | ||
this.anchors = []; | ||
this.anchors = {}; | ||
this.commentBefore = null; | ||
this.comment = null; | ||
this.contents = null; | ||
this.directives = []; | ||
this.errors = []; | ||
this.options = options.merge ? { | ||
merge: options.merge | ||
} : {}; | ||
this.rawContents = null; | ||
this.tagPrefixes = []; | ||
this.tags = tags || new _Tags.default(options); | ||
this.schema = schema instanceof _schema.default ? schema : new _schema.default(schema); | ||
this.version = null; | ||
@@ -80,3 +73,2 @@ this.warnings = []; | ||
error = _ref.error; | ||
this.directives = directives; | ||
@@ -88,3 +80,2 @@ if (error) { | ||
this.rawContents = contents; | ||
var directiveComments = []; | ||
@@ -120,2 +111,6 @@ directives.forEach(function (directive) { | ||
if (node.valueRange && !node.valueRange.isEmpty) { | ||
if (contentNodes.length === 1) { | ||
_this.errors.push(new _errors.YAMLSemanticError(node, 'Document is not valid YAML (bad indentation?)')); | ||
} | ||
contentNodes.push(_this.resolveNode(node)); | ||
@@ -151,3 +146,2 @@ } else if (node.comment) { | ||
default: | ||
this.errors.push(new _errors.YAMLSyntaxError(null, 'Document is not valid YAML (bad indentation?)')); | ||
this.contents = contentNodes; | ||
@@ -176,6 +170,6 @@ if (this.contents[0]) this.contents[0].commentBefore = comments.before.join('\n') || null;else comments.after = comments.before.concat(comments.after); | ||
} else { | ||
this.errors.push(new _errors.YAMLSyntaxError(directive, 'The TAG directive must only be given at most once per handle in the same document.')); | ||
this.errors.push(new _errors.YAMLSemanticError(directive, 'The TAG directive must only be given at most once per handle in the same document.')); | ||
} | ||
} else { | ||
this.errors.push(new _errors.YAMLSyntaxError(directive, 'Insufficient parameters given for TAG directive')); | ||
this.errors.push(new _errors.YAMLSemanticError(directive, 'Insufficient parameters given for TAG directive')); | ||
} | ||
@@ -189,4 +183,4 @@ } | ||
if (this.version) this.errors.push(new _errors.YAMLSyntaxError(directive, 'The YAML directive must only be given at most once per document.')); | ||
if (!version) this.errors.push(new _errors.YAMLSyntaxError(directive, 'Insufficient parameters given for YAML directive'));else if (version !== '1.2') this.warnings.push(new _errors.YAMLWarning(directive, "Document will be parsed as YAML 1.2 rather than YAML ".concat(version))); | ||
if (this.version) this.errors.push(new _errors.YAMLSemanticError(directive, 'The YAML directive must only be given at most once per document.')); | ||
if (!version) this.errors.push(new _errors.YAMLSemanticError(directive, 'Insufficient parameters given for YAML directive'));else if (version !== '1.2') this.warnings.push(new _errors.YAMLWarning(directive, "Document will be parsed as YAML 1.2 rather than YAML ".concat(version))); | ||
this.version = version; | ||
@@ -208,3 +202,3 @@ } | ||
if (verbatim !== '!' && verbatim !== '!!') return verbatim; | ||
this.errors.push(new _errors.YAMLSyntaxError(node, "Verbatim tags aren't resolved, so ".concat(verbatim, " is invalid."))); | ||
this.errors.push(new _errors.YAMLSemanticError(node, "Verbatim tags aren't resolved, so ".concat(verbatim, " is invalid."))); | ||
} else if (handle === '!' && !suffix) { | ||
@@ -215,3 +209,3 @@ nonSpecific = true; | ||
return p.handle === handle; | ||
}) || _Tags.DefaultTagPrefixes.find(function (p) { | ||
}) || _schema.DefaultTagPrefixes.find(function (p) { | ||
return p.handle === handle; | ||
@@ -222,5 +216,5 @@ }); | ||
if (suffix) return prefix.prefix + suffix; | ||
this.errors.push(new _errors.YAMLSyntaxError(node, "The ".concat(handle, " tag has no suffix."))); | ||
this.errors.push(new _errors.YAMLSemanticError(node, "The ".concat(handle, " tag has no suffix."))); | ||
} else { | ||
this.errors.push(new _errors.YAMLSyntaxError(node, "The ".concat(handle, " tag handle is non-default and was not declared."))); | ||
this.errors.push(new _errors.YAMLSemanticError(node, "The ".concat(handle, " tag handle is non-default and was not declared."))); | ||
} | ||
@@ -235,14 +229,14 @@ } | ||
case _Node.Type.QUOTE_SINGLE: | ||
return _Tags.DefaultTags.STR; | ||
return _schema.DefaultTags.STR; | ||
case _Node.Type.FLOW_MAP: | ||
case _Node.Type.MAP: | ||
return _Tags.DefaultTags.MAP; | ||
return _schema.DefaultTags.MAP; | ||
case _Node.Type.FLOW_SEQ: | ||
case _Node.Type.SEQ: | ||
return _Tags.DefaultTags.SEQ; | ||
return _schema.DefaultTags.SEQ; | ||
case _Node.Type.PLAIN: | ||
return nonSpecific ? _Tags.DefaultTags.STR : null; | ||
return nonSpecific ? _schema.DefaultTags.STR : null; | ||
@@ -259,3 +253,3 @@ default: | ||
errors = this.errors, | ||
tags = this.tags; | ||
schema = this.schema; | ||
var hasAnchor = false; | ||
@@ -274,3 +268,3 @@ var hasTag = false; | ||
case _Node.Char.COMMENT: | ||
if (!node.commentHasRequiredWhitespace(start)) errors.push(new _errors.YAMLSyntaxError(node, 'Comments must be separated from other tokens by white space characters')); | ||
if (!node.commentHasRequiredWhitespace(start)) errors.push(new _errors.YAMLSemanticError(node, 'Comments must be separated from other tokens by white space characters')); | ||
var c = node.context.src.slice(start + 1, end); | ||
@@ -289,3 +283,3 @@ var header = node.header, | ||
case _Node.Char.ANCHOR: | ||
if (hasAnchor) errors.push(new _errors.YAMLSyntaxError(node, 'A node can have at most one anchor')); | ||
if (hasAnchor) errors.push(new _errors.YAMLSemanticError(node, 'A node can have at most one anchor')); | ||
hasAnchor = true; | ||
@@ -295,3 +289,3 @@ break; | ||
case _Node.Char.TAG: | ||
if (hasTag) errors.push(new _errors.YAMLSyntaxError(node, 'A node can have at most one tag')); | ||
if (hasTag) errors.push(new _errors.YAMLSemanticError(node, 'A node can have at most one tag')); | ||
hasTag = true; | ||
@@ -305,3 +299,3 @@ break; | ||
if (node.type === _Node.Type.ALIAS) { | ||
if (hasAnchor || hasTag) errors.push(new _errors.YAMLSyntaxError(node, 'An alias node must not specify any properties')); | ||
if (hasAnchor || hasTag) errors.push(new _errors.YAMLSemanticError(node, 'An alias node must not specify any properties')); | ||
var src = anchors[node.rawValue]; | ||
@@ -319,6 +313,6 @@ | ||
if (tagName) { | ||
res = tags.resolveNodeWithFallback(this, node, tagName); | ||
res = schema.resolveNodeWithFallback(this, node, tagName); | ||
} else { | ||
if (node.type !== _Node.Type.PLAIN) { | ||
errors.push(new _errors.YAMLSyntaxError(node, "Failed to resolve ".concat(node.type, " node here"))); | ||
errors.push(new _errors.YAMLSemanticError(node, "Failed to resolve ".concat(node.type, " node here"))); | ||
return null; | ||
@@ -328,3 +322,3 @@ } | ||
try { | ||
res = tags.resolveScalar(node.strValue || ''); | ||
res = schema.resolveScalar(node.strValue || ''); | ||
} catch (error) { | ||
@@ -355,3 +349,3 @@ if (!error.source) error.source = node; | ||
value: function listNonDefaultTags() { | ||
var _DefaultTagPrefixes$f = _Tags.DefaultTagPrefixes.find(function (p) { | ||
var _DefaultTagPrefixes$f = _schema.DefaultTagPrefixes.find(function (p) { | ||
return p.handle === '!!'; | ||
@@ -393,9 +387,4 @@ }), | ||
if (this.errors.length > 0) throw new Error('Document with errors cannot be stringified'); | ||
var lines = this.directives.filter(function (_ref3) { | ||
var comment = _ref3.comment; | ||
return comment; | ||
}).map(function (_ref4) { | ||
var comment = _ref4.comment; | ||
return comment.replace(/^/gm, '#'); | ||
}); | ||
var lines = []; | ||
if (this.commentBefore) lines.push(this.commentBefore.replace(/^/gm, '#')); | ||
var hasDirectives = false; | ||
@@ -409,5 +398,5 @@ | ||
var tagNames = this.listNonDefaultTags(); | ||
this.tagPrefixes.forEach(function (_ref5) { | ||
var handle = _ref5.handle, | ||
prefix = _ref5.prefix; | ||
this.tagPrefixes.forEach(function (_ref3) { | ||
var handle = _ref3.handle, | ||
prefix = _ref3.prefix; | ||
@@ -431,6 +420,10 @@ if (tagNames.some(function (t) { | ||
var comment = this.contents.comment; | ||
var body = this.tags.stringify(this, this.contents, options, function () { | ||
var body = this.schema.stringify(this, this.contents, options, function () { | ||
comment = null; | ||
}); | ||
lines.push((0, _addComment.default)(body, '', comment)); | ||
} else if (this.contents !== undefined) { | ||
lines.push(this.schema.stringify(this, this.contents, { | ||
indent: '' | ||
})); | ||
} | ||
@@ -437,0 +430,0 @@ |
@@ -6,3 +6,3 @@ "use strict"; | ||
}); | ||
exports.YAMLWarning = exports.YAMLSyntaxError = exports.YAMLReferenceError = void 0; | ||
exports.YAMLWarning = exports.YAMLSyntaxError = exports.YAMLSemanticError = exports.YAMLReferenceError = void 0; | ||
@@ -49,12 +49,12 @@ function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } | ||
var YAMLSyntaxError = | ||
var YAMLSemanticError = | ||
/*#__PURE__*/ | ||
function (_SyntaxError) { | ||
function YAMLSyntaxError(source, message) { | ||
function YAMLSemanticError(source, message) { | ||
var _this2; | ||
_classCallCheck(this, YAMLSyntaxError); | ||
_classCallCheck(this, YAMLSemanticError); | ||
_this2 = _possibleConstructorReturn(this, _getPrototypeOf(YAMLSyntaxError).call(this)); | ||
_this2.name = 'YAMLSyntaxError'; | ||
_this2 = _possibleConstructorReturn(this, _getPrototypeOf(YAMLSemanticError).call(this)); | ||
_this2.name = 'YAMLSemanticError'; | ||
_this2.message = message; | ||
@@ -65,4 +65,26 @@ _this2.source = source; | ||
_inherits(YAMLSyntaxError, _SyntaxError); | ||
_inherits(YAMLSemanticError, _SyntaxError); | ||
return YAMLSemanticError; | ||
}(_wrapNativeSuper(SyntaxError)); | ||
exports.YAMLSemanticError = YAMLSemanticError; | ||
var YAMLSyntaxError = | ||
/*#__PURE__*/ | ||
function (_SyntaxError2) { | ||
function YAMLSyntaxError(source, message) { | ||
var _this3; | ||
_classCallCheck(this, YAMLSyntaxError); | ||
_this3 = _possibleConstructorReturn(this, _getPrototypeOf(YAMLSyntaxError).call(this)); | ||
_this3.name = 'YAMLSyntaxError'; | ||
_this3.message = message; | ||
_this3.source = source; | ||
return _this3; | ||
} | ||
_inherits(YAMLSyntaxError, _SyntaxError2); | ||
return YAMLSyntaxError; | ||
@@ -77,11 +99,11 @@ }(_wrapNativeSuper(SyntaxError)); | ||
function YAMLWarning(source, message) { | ||
var _this3; | ||
var _this4; | ||
_classCallCheck(this, YAMLWarning); | ||
_this3 = _possibleConstructorReturn(this, _getPrototypeOf(YAMLWarning).call(this)); | ||
_this3.name = 'YAMLWarning'; | ||
_this3.message = message; | ||
_this3.source = source; | ||
return _this3; | ||
_this4 = _possibleConstructorReturn(this, _getPrototypeOf(YAMLWarning).call(this)); | ||
_this4.name = 'YAMLWarning'; | ||
_this4.message = message; | ||
_this4.source = source; | ||
return _this4; | ||
} | ||
@@ -88,0 +110,0 @@ |
@@ -10,49 +10,88 @@ "use strict"; | ||
var _Document = _interopRequireDefault(require("./Document")); | ||
var _Document3 = _interopRequireDefault(require("./Document")); | ||
var _errors = require("./errors"); | ||
var _schema = _interopRequireDefault(require("./schema")); | ||
var _Tags = _interopRequireDefault(require("./Tags")); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
var parseStream = function parseStream(src) { | ||
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
var ast = (0, _parse.default)(src); | ||
var tags = new _Tags.default(options); | ||
return ast.map(function (astDoc) { | ||
var doc = new _Document.default(tags, options); | ||
return doc.parse(astDoc); | ||
}); | ||
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } | ||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } _setPrototypeOf(subClass.prototype, superClass && superClass.prototype); if (superClass) _setPrototypeOf(subClass, superClass); } | ||
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } | ||
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } | ||
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } | ||
function _getPrototypeOf(o) { _getPrototypeOf = Object.getPrototypeOf || function _getPrototypeOf(o) { return o.__proto__; }; return _getPrototypeOf(o); } | ||
var defaultOptions = { | ||
merge: false, | ||
schema: 'core', | ||
tags: null | ||
}; | ||
var parse = function parse(src) { | ||
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
var stream = parseStream(src, options); | ||
stream.forEach(function (doc) { | ||
return doc.errors.forEach(function (error) { | ||
if (error instanceof _errors.YAMLWarning) { | ||
if (typeof console !== 'undefined') console.warn(error); | ||
} else { | ||
throw error; | ||
} | ||
function parseDocuments(src, options) { | ||
var resolvedOptions = options ? Object.assign({}, defaultOptions, options) : defaultOptions; | ||
var schema = new _schema.default(resolvedOptions); | ||
return (0, _parse.default)(src).map(function (astDoc) { | ||
return new _Document3.default(schema).parse(astDoc); | ||
}); | ||
} | ||
function parse(src, options) { | ||
var docs = parseDocuments(src, options); | ||
docs.forEach(function (doc) { | ||
doc.warnings.forEach(function (warning) { | ||
return console.warn(warning); | ||
}); | ||
doc.errors.forEach(function (error) { | ||
throw error; | ||
}); | ||
}); | ||
if (options.docArray) return stream.map(function (doc) { | ||
return doc.toJSON(); | ||
}); | ||
if (stream.length > 1) { | ||
throw new Error('Source contains multiple documents; set options.docArray = true or use parseStream()'); | ||
if (docs.length > 1) { | ||
throw new Error('Source contains multiple documents; please use YAML.parseDocuments()'); | ||
} | ||
return stream[0] && stream[0].toJSON(); | ||
}; | ||
return docs[0] && docs[0].toJSON(); | ||
} | ||
function stringify(value, options) { | ||
var resolvedOptions = options ? Object.assign({}, defaultOptions, options) : defaultOptions; | ||
var doc = new _Document3.default(resolvedOptions); | ||
doc.contents = value; | ||
return String(doc); | ||
} | ||
var _default = { | ||
Document: _Document.default, | ||
defaultOptions: defaultOptions, | ||
Document: | ||
/*#__PURE__*/ | ||
function (_Document2) { | ||
function Document(schema) { | ||
var _this; | ||
_classCallCheck(this, Document); | ||
if (schema instanceof _schema.default) { | ||
_this = _possibleConstructorReturn(this, _getPrototypeOf(Document).call(this, schema)); | ||
} else { | ||
_this = _possibleConstructorReturn(this, _getPrototypeOf(Document).call(this, Object.assign({}, defaultOptions, schema))); | ||
} | ||
return _possibleConstructorReturn(_this); | ||
} | ||
_inherits(Document, _Document2); | ||
return Document; | ||
}(_Document3.default), | ||
parse: parse, | ||
parseAST: _parse.default, | ||
parseStream: parseStream | ||
parseDocuments: parseDocuments, | ||
stringify: stringify | ||
}; | ||
exports.default = _default; |
@@ -8,4 +8,10 @@ "use strict"; | ||
var _addComment = require("../addComment"); | ||
var _Node = require("../ast/Node"); | ||
var _foldFlowLines = _interopRequireWildcard(require("../foldFlowLines")); | ||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } | ||
var strOptions = { | ||
@@ -17,2 +23,6 @@ defaultType: _Node.Type.PLAIN, | ||
minMultiLineLength: 40 | ||
}, | ||
fold: { | ||
lineWidth: 80, | ||
minContentWidth: 20 | ||
} | ||
@@ -126,3 +136,4 @@ }; | ||
return start ? str + json.slice(start) : json; | ||
str = start ? str + json.slice(start) : json; | ||
return oneLine ? str : (0, _foldFlowLines.default)(str, indent, _foldFlowLines.FOLD_QUOTED, strOptions.fold); | ||
} | ||
@@ -138,4 +149,4 @@ | ||
value = value.replace(/'/g, "''").replace(/\n+/g, "$&\n".concat(indent)); | ||
return "'".concat(value, "'"); | ||
value = "'" + value.replace(/'/g, "''").replace(/\n+/g, "$&\n".concat(indent)) + "'"; | ||
return oneLine ? value : (0, _foldFlowLines.default)(value, indent, _foldFlowLines.FOLD_FLOW, strOptions.fold); | ||
} | ||
@@ -188,9 +199,10 @@ | ||
value = value.replace(/\n+/g, "$&".concat(indent)); | ||
} else { | ||
value = value.replace(/\n+/g, '\n$&').replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, '$1$2') // more-indented lines aren't folded | ||
// ^ ind.line ^ empty ^ capture next empty lines only at end of indent | ||
.replace(/\n+/g, "$&".concat(indent)); | ||
return "".concat(header, "\n").concat(indent).concat(wsStart).concat(value).concat(wsEnd); | ||
} | ||
return "".concat(header, "\n").concat(indent).concat(wsStart).concat(value).concat(wsEnd); | ||
value = value.replace(/\n+/g, '\n$&').replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, '$1$2') // more-indented lines aren't folded | ||
// ^ ind.line ^ empty ^ capture next empty lines only at end of indent | ||
.replace(/\n+/g, "$&".concat(indent)); | ||
var body = (0, _foldFlowLines.default)("".concat(wsStart).concat(value).concat(wsEnd), indent, _foldFlowLines.FOLD_BLOCK, strOptions.fold); | ||
return "".concat(header, "\n").concat(indent).concat(body); | ||
} | ||
@@ -220,9 +232,10 @@ | ||
if (comment && !inFlow && (str.indexOf('\n') !== -1 || comment.indexOf('\n') !== -1)) { | ||
var body = implicitKey ? str : (0, _foldFlowLines.default)(str, indent, _foldFlowLines.FOLD_FLOW, strOptions.fold); | ||
if (comment && !inFlow && (body.indexOf('\n') !== -1 || comment.indexOf('\n') !== -1)) { | ||
if (onComment) onComment(); | ||
var cc = comment.replace(/[\s\S]^/gm, "$&".concat(indent, "#")); | ||
return "#".concat(cc, "\n").concat(indent).concat(str); | ||
return (0, _addComment.addCommentBefore)(body, indent, comment); | ||
} | ||
return str; | ||
return body; | ||
} | ||
@@ -229,0 +242,0 @@ |
@@ -65,3 +65,3 @@ "use strict"; | ||
var k = String(key).substr(0, 8) + '...' + String(key).substr(-8); | ||
doc.errors.push(new _errors.YAMLSyntaxError(node, "The \"".concat(k, "\" key is too long"))); | ||
doc.errors.push(new _errors.YAMLSemanticError(node, "The \"".concat(k, "\" key is too long"))); | ||
} | ||
@@ -121,3 +121,3 @@ } | ||
var tags = this.doc.tags; | ||
var schema = this.doc.schema; | ||
var blockItem = options.blockItem, | ||
@@ -150,3 +150,3 @@ flowChars = options.flowChars, | ||
if (comment) hasItemWithComment = true; | ||
var str = tags.stringify(_this3.doc, item, opt, function () { | ||
var str = schema.stringify(_this3.doc, item, opt, function () { | ||
comment = null; | ||
@@ -153,0 +153,0 @@ }); |
@@ -6,4 +6,10 @@ "use strict"; | ||
}); | ||
exports.default = void 0; | ||
exports.default = exports.DefaultTags = exports.DefaultTagPrefixes = exports.availableSchema = void 0; | ||
var _Node = require("../ast/Node"); | ||
var _errors = require("../errors"); | ||
var _Collection = _interopRequireDefault(require("./Collection")); | ||
var _core = _interopRequireDefault(require("./core")); | ||
@@ -17,6 +23,19 @@ | ||
var _Pair = _interopRequireDefault(require("./Pair")); | ||
var _Scalar = _interopRequireDefault(require("./Scalar")); | ||
var _string = require("./_string"); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
var _default = { | ||
'': _core.default, | ||
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } | ||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } | ||
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } | ||
var availableSchema = { | ||
core: _core.default, | ||
@@ -27,2 +46,216 @@ extended: _extended.default, | ||
}; | ||
exports.default = _default; | ||
exports.availableSchema = availableSchema; | ||
var defaultPrefix = 'tag:yaml.org,2002:'; | ||
var DefaultTagPrefixes = [{ | ||
handle: '!', | ||
prefix: '!' | ||
}, { | ||
handle: '!!', | ||
prefix: defaultPrefix | ||
}]; | ||
exports.DefaultTagPrefixes = DefaultTagPrefixes; | ||
var DefaultTags = { | ||
MAP: 'tag:yaml.org,2002:map', | ||
SEQ: 'tag:yaml.org,2002:seq', | ||
STR: 'tag:yaml.org,2002:str' | ||
}; | ||
exports.DefaultTags = DefaultTags; | ||
var isMap = function isMap(_ref) { | ||
var type = _ref.type; | ||
return type === _Node.Type.FLOW_MAP || type === _Node.Type.MAP; | ||
}; | ||
var isSeq = function isSeq(_ref2) { | ||
var type = _ref2.type; | ||
return type === _Node.Type.FLOW_SEQ || type === _Node.Type.SEQ; | ||
}; | ||
var Schema = | ||
/*#__PURE__*/ | ||
function () { | ||
_createClass(Schema, null, [{ | ||
key: "defaultStringifier", | ||
value: function defaultStringifier(value) { | ||
return JSON.stringify(value); | ||
} | ||
}]); | ||
function Schema(_ref3) { | ||
var merge = _ref3.merge, | ||
schema = _ref3.schema, | ||
tags = _ref3.tags; | ||
_classCallCheck(this, Schema); | ||
this.merge = !!merge; | ||
this.schema = Array.isArray(schema) ? schema : availableSchema[schema]; | ||
if (!this.schema) { | ||
var keys = Object.keys(availableSchema).map(function (key) { | ||
return JSON.stringify(key); | ||
}).join(', '); | ||
throw new Error("Unknown schema; use ".concat(keys, ", or { tag, test, resolve }[]")); | ||
} | ||
if (Array.isArray(tags)) { | ||
this.schema = this.schema.concat(tags); | ||
} else if (typeof tags === 'function') { | ||
this.schema = tags(this.schema.slice()); | ||
} | ||
} // falls back to string on no match | ||
_createClass(Schema, [{ | ||
key: "resolveScalar", | ||
value: function resolveScalar(str, tags) { | ||
if (!tags) tags = this.schema; | ||
for (var i = 0; i < tags.length; ++i) { | ||
var _tags$i = tags[i], | ||
test = _tags$i.test, | ||
resolve = _tags$i.resolve; | ||
if (test) { | ||
var match = str.match(test); | ||
if (match) return new _Scalar.default(resolve.apply(null, match)); | ||
} | ||
} | ||
if (this.schema.scalarFallback) str = this.schema.scalarFallback(str); | ||
return new _Scalar.default(str); | ||
} // sets node.resolved on success | ||
}, { | ||
key: "resolveNode", | ||
value: function resolveNode(doc, node, tagName) { | ||
var tags = this.schema.filter(function (_ref4) { | ||
var tag = _ref4.tag; | ||
return tag === tagName; | ||
}); | ||
var generic = tags.find(function (_ref5) { | ||
var test = _ref5.test; | ||
return !test; | ||
}); | ||
if (node.error) doc.errors.push(node.error); | ||
try { | ||
if (generic) { | ||
var res = generic.resolve(doc, node); | ||
if (!(res instanceof _Collection.default)) res = new _Scalar.default(res); | ||
node.resolved = res; | ||
} else { | ||
var str = (0, _string.resolve)(doc, node); | ||
if (typeof str === 'string' && tags.length > 0) { | ||
node.resolved = this.resolveScalar(str, tags); | ||
} | ||
} | ||
} catch (error) { | ||
if (!error.source) error.source = node; | ||
doc.errors.push(error); | ||
node.resolved = null; | ||
} | ||
if (!node.resolved) return null; | ||
if (node.hasProps) node.resolved.anchor = node.anchor; | ||
if (tagName) node.resolved.tag = tagName; | ||
return node.resolved; | ||
} | ||
}, { | ||
key: "resolveNodeWithFallback", | ||
value: function resolveNodeWithFallback(doc, node, tagName) { | ||
var res = this.resolveNode(doc, node, tagName); | ||
if (node.hasOwnProperty('resolved')) return res; | ||
var fallback = isMap(node) ? DefaultTags.MAP : isSeq(node) ? DefaultTags.SEQ : DefaultTags.STR; | ||
if (fallback) { | ||
doc.warnings.push(new _errors.YAMLWarning(node, "The tag ".concat(tagName, " is unavailable, falling back to ").concat(fallback))); | ||
var _res = this.resolveNode(doc, node, fallback); | ||
_res.origTag = tagName; | ||
return _res; | ||
} else { | ||
doc.errors.push(new _errors.YAMLReferenceError(node, "The tag ".concat(tagName, " is unavailable"))); | ||
} | ||
return null; | ||
} | ||
}, { | ||
key: "stringify", | ||
value: function stringify(doc, item, options, onComment) { | ||
if (!(item instanceof _Scalar.default || item instanceof _Collection.default || item instanceof _Pair.default)) { | ||
item = doc.resolveValue(item, true); | ||
} | ||
options.tags = this; | ||
var match; | ||
if (item instanceof _Pair.default) { | ||
return item.toString(doc, options, onComment); | ||
} else if (item.tag) { | ||
match = this.schema.filter(function (_ref6) { | ||
var format = _ref6.format, | ||
tag = _ref6.tag; | ||
return tag === item.tag && (!item.format || format === item.format); | ||
}); | ||
if (match.length === 0) throw new Error("Tag not available: ".concat(item.tag).concat(item.format ? ', format ' + item.format : '')); | ||
} else if (item.value === null) { | ||
match = this.schema.filter(function (t) { | ||
return t.class === null && !t.format; | ||
}); | ||
if (match.length === 0) throw new Error('Schema is missing a null stringifier'); | ||
} else { | ||
var obj = item; | ||
if (item.hasOwnProperty('value')) { | ||
switch (_typeof(item.value)) { | ||
case 'boolean': | ||
obj = new Boolean(); | ||
break; | ||
case 'number': | ||
obj = new Number(); | ||
break; | ||
case 'string': | ||
obj = new String(); | ||
break; | ||
default: | ||
obj = item.value; | ||
} | ||
} | ||
match = this.schema.filter(function (t) { | ||
return t.class && obj instanceof t.class && !t.format; | ||
}); | ||
if (match.length === 0) throw new Error("Tag not resolved for ".concat(obj && obj.constructor ? obj.constructor.name : _typeof(obj))); | ||
} | ||
var stringify = match[0].stringify || Schema.defaultStringifier; | ||
var str = stringify(item, options, onComment); | ||
var tag = item.origTag || item.tag; | ||
if (tag && tag.indexOf(defaultPrefix) !== 0) { | ||
var p = doc.tagPrefixes.find(function (p) { | ||
return tag.indexOf(p.prefix) === 0; | ||
}); | ||
var tagProp = p ? p.handle + tag.substr(p.prefix.length) : tag[0] === '!' ? tag : "!<".concat(tag, ">"); | ||
if (item instanceof _Collection.default && !options.inFlow && item.items.length > 0) { | ||
return "".concat(tagProp, "\n").concat(options.indent).concat(str); | ||
} else { | ||
return "".concat(tagProp, " ").concat(str); | ||
} | ||
} | ||
return str; | ||
} | ||
}]); | ||
return Schema; | ||
}(); | ||
exports.default = Schema; |
@@ -83,3 +83,3 @@ "use strict"; | ||
if (iKey === jKey || iKey && jKey && iKey.hasOwnProperty('value') && iKey.value === jKey.value) { | ||
this.doc.errors.push(new _errors.YAMLSyntaxError(ast, "Map keys must be unique; \"".concat(iKey, "\" is repeated"))); | ||
this.doc.errors.push(new _errors.YAMLSemanticError(ast, "Map keys must be unique; \"".concat(iKey, "\" is repeated"))); | ||
break; | ||
@@ -89,3 +89,3 @@ } | ||
if (this.doc.options.merge && iKey.value === '<<') { | ||
if (this.doc.schema.merge && iKey.value === '<<') { | ||
var src = this.items[i].value; | ||
@@ -139,3 +139,3 @@ var srcItems = src instanceof _Seq.default ? src.items.reduce(function (acc, _ref) { | ||
if (!item.context.atLineStart && item.node && item.node.type === _Node.Type.MAP && !item.node.context.atLineStart) { | ||
this.doc.errors.push(new _errors.YAMLSyntaxError(item.node, 'Nested mappings are not allowed in compact mappings')); | ||
this.doc.errors.push(new _errors.YAMLSemanticError(item.node, 'Nested mappings are not allowed in compact mappings')); | ||
} | ||
@@ -155,4 +155,5 @@ | ||
keyStart = item.range.start; | ||
if (map.items[i + 1].type !== _Node.Type.MAP_VALUE) this.doc.errors.push(new _errors.YAMLSyntaxError(node, 'Implicit map keys need to be followed by map values')); | ||
if (item.valueRangeContainsNewline) this.doc.errors.push(new _errors.YAMLSyntaxError(node, 'Implicit map keys need to be on a single line')); | ||
var nextItem = map.items[i + 1]; | ||
if (!nextItem || nextItem.type !== _Node.Type.MAP_VALUE) this.doc.errors.push(new _errors.YAMLSemanticError(item.node, 'Implicit map keys need to be followed by map values')); | ||
if (item.valueRangeContainsNewline) this.doc.errors.push(new _errors.YAMLSemanticError(item.node, 'Implicit map keys need to be on a single line')); | ||
} | ||
@@ -210,13 +211,14 @@ } | ||
this.doc.errors.push(new _errors.YAMLSyntaxError(map, "Flow map contains an unexpected ".concat(item))); | ||
this.doc.errors.push(new _errors.YAMLSemanticError(map, "Flow map contains an unexpected ".concat(item))); | ||
} else if (item.type === _Node.Type.COMMENT) { | ||
this.addComment(item.comment); | ||
} else if (key === undefined) { | ||
if (next === ',') this.doc.errors.push(new _errors.YAMLSyntaxError(item, 'Separator , missing in flow map')); | ||
if (next === ',') this.doc.errors.push(new _errors.YAMLSemanticError(item, 'Separator , missing in flow map')); | ||
key = this.doc.resolveNode(item); | ||
keyStart = explicitKey ? null : item.range.start; // TODO: add error for non-explicit multiline plain key | ||
} else { | ||
if (next !== ',') this.doc.errors.push(new _errors.YAMLSyntaxError(item, 'Indicator : missing in flow map entry')); | ||
if (next !== ',') this.doc.errors.push(new _errors.YAMLSemanticError(item, 'Indicator : missing in flow map entry')); | ||
this.items.push(new _Pair.default(key, this.doc.resolveNode(item))); | ||
key = undefined; | ||
explicitKey = false; | ||
} | ||
@@ -223,0 +225,0 @@ } |
@@ -58,3 +58,3 @@ "use strict"; | ||
var keyComment = key && key.comment; | ||
var keyStr = doc.tags.stringify(doc, key, opt, function () { | ||
var keyStr = doc.schema.stringify(doc, key, opt, function () { | ||
keyComment = null; | ||
@@ -64,3 +64,3 @@ }); | ||
opt.implicitKey = false; | ||
var valueStr = doc.tags.stringify(doc, value, opt, onComment); | ||
var valueStr = doc.schema.stringify(doc, value, opt, onComment); | ||
@@ -67,0 +67,0 @@ if (explicitKey) { |
@@ -79,7 +79,7 @@ "use strict"; | ||
this.items.push(this.doc.resolveNode(item.node)); | ||
if (item.hasProps) this.doc.errors.push(new _errors.YAMLSyntaxError(item, 'Sequence items cannot have tags or anchors before the - indicator')); | ||
if (item.hasProps) this.doc.errors.push(new _errors.YAMLSemanticError(item, 'Sequence items cannot have tags or anchors before the - indicator')); | ||
break; | ||
default: | ||
this.doc.errors.push(new _errors.YAMLSyntaxError(item, "Unexpected ".concat(item.type, " node in sequence"))); | ||
this.doc.errors.push(new _errors.YAMLSemanticError(item, "Unexpected ".concat(item.type, " node in sequence"))); | ||
} | ||
@@ -115,3 +115,3 @@ } | ||
key = this.items.pop(); | ||
if (key instanceof _Pair.default) this.doc.errors.push(new _errors.YAMLSyntaxError(item, 'Chaining flow sequence pairs is invalid (e.g. [ a : b : c ])')); | ||
if (key instanceof _Pair.default) this.doc.errors.push(new _errors.YAMLSemanticError(item, 'Chaining flow sequence pairs is invalid (e.g. [ a : b : c ])')); | ||
if (!explicitKey) _Collection2.default.checkKeyLength(this.doc, seq, i, key, keyStart); | ||
@@ -127,3 +127,3 @@ } else { | ||
} else if (next === '[' || item !== ']' || i < seq.items.length - 1) { | ||
this.doc.errors.push(new _errors.YAMLSyntaxError(seq, "Flow sequence contains an unexpected ".concat(item))); | ||
this.doc.errors.push(new _errors.YAMLSemanticError(seq, "Flow sequence contains an unexpected ".concat(item))); | ||
} | ||
@@ -133,3 +133,3 @@ } else if (item.type === _Node.Type.COMMENT) { | ||
} else { | ||
if (next) this.doc.errors.push(new _errors.YAMLSyntaxError(item, "Expected a ".concat(next, " here in flow sequence"))); | ||
if (next) this.doc.errors.push(new _errors.YAMLSemanticError(item, "Expected a ".concat(next, " here in flow sequence"))); | ||
var value = this.doc.resolveNode(item); | ||
@@ -149,3 +149,3 @@ | ||
if (seq.items[seq.items.length - 1] !== ']') this.doc.errors.push(new _errors.YAMLSyntaxError(seq, 'Expected flow sequence to end with ]')); | ||
if (seq.items[seq.items.length - 1] !== ']') this.doc.errors.push(new _errors.YAMLSemanticError(seq, 'Expected flow sequence to end with ]')); | ||
if (key !== undefined) this.items.push(new _Pair.default(key)); | ||
@@ -152,0 +152,0 @@ } |
{ | ||
"name": "yaml", | ||
"version": "1.0.0-beta.5", | ||
"version": "1.0.0-beta.6", | ||
"main": "dist/index.js", | ||
@@ -20,4 +20,8 @@ "license": "ISC", | ||
"build": "babel src/ --out-dir dist/", | ||
"prettier": "prettier --write \"{src,__tests__}/**/*.js\"", | ||
"test": "TRACE_LEVEL=log jest", | ||
"test:trace": "TRACE_LEVEL=trace,log jest --no-cache", | ||
"docs:install": "cd docs/ && bundle install", | ||
"docs:deploy": "cd docs/ && ./deploy.sh", | ||
"docs": "cd docs/ && bundle exec middleman server", | ||
"preversion": "npm test && npm run build", | ||
@@ -48,2 +52,6 @@ "version": "git commit -am \"Update version\" && git add -f dist/", | ||
}, | ||
"prettier": { | ||
"semi": false, | ||
"singleQuote": true | ||
}, | ||
"devDependencies": { | ||
@@ -57,5 +65,6 @@ "@babel/cli": "^7.0.0-beta.46", | ||
"babel-plugin-trace": "^1.1.0", | ||
"jest": "^22.4.3" | ||
"jest": "^22.4.3", | ||
"prettier": "1.12.1" | ||
}, | ||
"dependencies": {} | ||
} |
@@ -36,4 +36,4 @@ # YAML | ||
const docStream = YAML.parseStream(yaml) | ||
docStream[0].toString() === yaml | ||
const docs = YAML.parseDocuments(yaml) | ||
docs[0].toString() === yaml | ||
``` | ||
@@ -53,3 +53,3 @@ | ||
- `YAML.parse` converts string input to native JavaScript values | ||
- Comments are parsed and included in the outputs of `YAML.parseAST` ([lower-level AST] of the input) and `YAML.parseStream` (array of `Document` objects with `Map`/`Seq`/`Scalar` contents). These functions should never throw, but include arrays of `errors` and `warnings`. | ||
- Comments are parsed and included in the outputs of `YAML.parseAST` ([lower-level AST] of the input) and `YAML.parseDocuments` (array of `Document` objects with `Map`/`Seq`/`Scalar` contents). These functions should never throw, but include arrays of `errors` and `warnings`. | ||
- Support for `<<` merge keys (default-disabled, enable with `merge: true` option) | ||
@@ -75,3 +75,4 @@ - Complete match between the parsed `in.yaml`, `in.json`, `out.yaml`, and `error` files across all of the [yaml-test-suite] test cases (note: A few of the tests are not in agreement with the spec, so this requires the use of a [custom branch] until the relevant [pull requests] and [issues] are resolved) | ||
- `Document#toString()` produces idempotent YAML from all non-error spec examples and test suite cases | ||
- Non-default tags are explicitly included in the output | ||
- Comments and non-default tags are explicitly included in the output | ||
- String output is folded when possible to fit to a max width of 80 characters (customisable) | ||
- `AST#toString()` works completely, but is clumsy to use | ||
@@ -81,4 +82,4 @@ | ||
### Still Needs Work | ||
- Long lines should be wrapped | ||
- API needs finalising | ||
- Alias nodes are resolved too early, and can't be created | ||
- Need to consider handling stream input | ||
- Better documentation |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
198144
4332
82
9