!nameHasComments || _n.attributes.length) && !lastAttrHasTrailingComments; // We should print the opening element expanded if any prop value is a
// string literal with newlines
var _shouldBreak = _n.attributes && _n.attributes.some(function (attr) {
return attr.value && isStringLiteral(attr.value) && attr.value.value.includes("\n");
});
return group$10(concat$11(["<", path.call(print, "name"), path.call(print, "typeParameters"), concat$11([indent$6(concat$11(path.map(function (attr) {
return concat$11([line$8, print(attr)]);
}, "attributes"))), _n.selfClosing ? line$8 : bracketSameLine ? ">" : softline$5]), _n.selfClosing ? "/>" : bracketSameLine ? "" : ">"]), {
shouldBreak: _shouldBreak
});
}
case "JSXClosingElement":
return concat$11(["", path.call(print, "name"), ">"]);
case "JSXOpeningFragment":
case "JSXClosingFragment":
{
var hasComment = n.comments && n.comments.length;
var hasOwnLineComment = hasComment && !n.comments.every(comments$3.isBlockComment);
var isOpeningFragment = n.type === "JSXOpeningFragment";
return concat$11([isOpeningFragment ? "<" : "", indent$6(concat$11([hasOwnLineComment ? hardline$8 : hasComment && !isOpeningFragment ? " " : "", comments.printDanglingComments(path, options, true)])), hasOwnLineComment ? hardline$8 : "", ">"]);
}
case "JSXText":
/* istanbul ignore next */
throw new Error("JSXTest should be handled by JSXElement");
case "JSXEmptyExpression":
{
var requiresHardline = n.comments && !n.comments.every(comments$3.isBlockComment);
return concat$11([comments.printDanglingComments(path, options,
/* sameIndent */
!requiresHardline), requiresHardline ? hardline$8 : ""]);
}
case "ClassBody":
if (!n.comments && n.body.length === 0) {
return "{}";
}
return concat$11(["{", n.body.length > 0 ? indent$6(concat$11([hardline$8, path.call(function (bodyPath) {
return printStatementSequence(bodyPath, options, print);
}, "body")])) : comments.printDanglingComments(path, options), hardline$8, "}"]);
case "ClassProperty":
case "TSAbstractClassProperty":
case "ClassPrivateProperty":
{
if (n.decorators && n.decorators.length !== 0) {
parts.push(printDecorators(path, options, print));
}
if (n.accessibility) {
parts.push(n.accessibility + " ");
}
if (n.static) {
parts.push("static ");
}
if (n.type === "TSAbstractClassProperty") {
parts.push("abstract ");
}
if (n.readonly) {
parts.push("readonly ");
}
var variance = getFlowVariance(n);
if (variance) {
parts.push(variance);
}
if (n.computed) {
parts.push("[", path.call(print, "key"), "]");
} else {
parts.push(printPropertyKey(path, options, print));
}
parts.push(printOptionalToken(path));
parts.push(printTypeAnnotation(path, options, print));
if (n.value) {
parts.push(" =", printAssignmentRight(n.key, n.value, path.call(print, "value"), options));
}
parts.push(semi);
return group$10(concat$11(parts));
}
case "ClassDeclaration":
case "ClassExpression":
if (isNodeStartingWithDeclare(n, options)) {
parts.push("declare ");
}
parts.push(concat$11(printClass(path, options, print)));
return concat$11(parts);
case "TSInterfaceHeritage":
parts.push(path.call(print, "expression"));
if (n.typeParameters) {
parts.push(path.call(print, "typeParameters"));
}
return concat$11(parts);
case "TemplateElement":
return join$7(literalline$3, n.value.raw.split(/\r?\n/g));
case "TemplateLiteral":
{
var expressions = path.map(print, "expressions");
var _parentNode = path.getParentNode();
if (isJestEachTemplateLiteral(n, _parentNode)) {
var _printed2 = printJestEachTemplateLiteral(n, expressions, options);
if (_printed2) {
return _printed2;
}
}
var isSimple = isSimpleTemplateLiteral(n);
if (isSimple) {
expressions = expressions.map(function (doc$$2) {
return printDocToString$1(doc$$2, Object.assign({}, options, {
printWidth: Infinity
})).formatted;
});
}
parts.push("`");
path.each(function (childPath) {
var i = childPath.getName();
parts.push(print(childPath));
if (i < expressions.length) {
// For a template literal of the following form:
// `someQuery {
// ${call({
// a,
// b,
// })}
// }`
// the expression is on its own line (there is a \n in the previous
// quasi literal), therefore we want to indent the JavaScript
// expression inside at the beginning of ${ instead of the beginning
// of the `.
var tabWidth = options.tabWidth;
var quasi = childPath.getValue();
var indentSize = getIndentSize$1(quasi.value.raw, tabWidth);
var _printed3 = expressions[i];
if (!isSimple) {
// Breaks at the template element boundaries (${ and }) are preferred to breaking
// in the middle of a MemberExpression
if (n.expressions[i].comments && n.expressions[i].comments.length || n.expressions[i].type === "MemberExpression" || n.expressions[i].type === "OptionalMemberExpression" || n.expressions[i].type === "ConditionalExpression") {
_printed3 = concat$11([indent$6(concat$11([softline$5, _printed3])), softline$5]);
}
}
var aligned = indentSize === 0 && quasi.value.raw.endsWith("\n") ? align$1(-Infinity, _printed3) : addAlignmentToDoc$2(_printed3, indentSize, tabWidth);
parts.push(group$10(concat$11(["${", aligned, lineSuffixBoundary$1, "}"])));
}
}, "quasis");
parts.push("`");
return concat$11(parts);
}
// These types are unprintable because they serve as abstract
// supertypes for other (printable) types.
case "TaggedTemplateExpression":
return concat$11([path.call(print, "tag"), path.call(print, "typeParameters"), path.call(print, "quasi")]);
case "Node":
case "Printable":
case "SourceLocation":
case "Position":
case "Statement":
case "Function":
case "Pattern":
case "Expression":
case "Declaration":
case "Specifier":
case "NamedSpecifier":
case "Comment":
case "MemberTypeAnnotation": // Flow
case "Type":
/* istanbul ignore next */
throw new Error("unprintable type: " + JSON.stringify(n.type));
// Type Annotations for Facebook Flow, typically stripped out or
// transformed away before printing.
case "TypeAnnotation":
case "TSTypeAnnotation":
if (n.typeAnnotation) {
return path.call(print, "typeAnnotation");
}
/* istanbul ignore next */
return "";
case "TSTupleType":
case "TupleTypeAnnotation":
{
var typesField = n.type === "TSTupleType" ? "elementTypes" : "types";
return group$10(concat$11(["[", indent$6(concat$11([softline$5, printArrayItems(path, options, typesField, print)])), ifBreak$6(shouldPrintComma$1(options, "all") ? "," : ""), comments.printDanglingComments(path, options,
/* sameIndent */
true), softline$5, "]"]));
}
case "ExistsTypeAnnotation":
return "*";
case "EmptyTypeAnnotation":
return "empty";
case "AnyTypeAnnotation":
return "any";
case "MixedTypeAnnotation":
return "mixed";
case "ArrayTypeAnnotation":
return concat$11([path.call(print, "elementType"), "[]"]);
case "BooleanTypeAnnotation":
return "boolean";
case "BooleanLiteralTypeAnnotation":
return "" + n.value;
case "DeclareClass":
return printFlowDeclaration(path, printClass(path, options, print));
case "TSDeclareFunction":
// For TypeScript the TSDeclareFunction node shares the AST
// structure with FunctionDeclaration
return concat$11([n.declare ? "declare " : "", printFunctionDeclaration(path, print, options), semi]);
case "DeclareFunction":
return printFlowDeclaration(path, ["function ", path.call(print, "id"), n.predicate ? " " : "", path.call(print, "predicate"), semi]);
case "DeclareModule":
return printFlowDeclaration(path, ["module ", path.call(print, "id"), " ", path.call(print, "body")]);
case "DeclareModuleExports":
return printFlowDeclaration(path, ["module.exports", ": ", path.call(print, "typeAnnotation"), semi]);
case "DeclareVariable":
return printFlowDeclaration(path, ["var ", path.call(print, "id"), semi]);
case "DeclareExportAllDeclaration":
return concat$11(["declare export * from ", path.call(print, "source")]);
case "DeclareExportDeclaration":
return concat$11(["declare ", printExportDeclaration(path, options, print)]);
case "DeclareOpaqueType":
case "OpaqueType":
{
parts.push("opaque type ", path.call(print, "id"), path.call(print, "typeParameters"));
if (n.supertype) {
parts.push(": ", path.call(print, "supertype"));
}
if (n.impltype) {
parts.push(" = ", path.call(print, "impltype"));
}
parts.push(semi);
if (n.type === "DeclareOpaqueType") {
return printFlowDeclaration(path, parts);
}
return concat$11(parts);
}
case "FunctionTypeAnnotation":
case "TSFunctionType":
{
// FunctionTypeAnnotation is ambiguous:
// declare function foo(a: B): void; OR
// var A: (a: B) => void;
var _parent7 = path.getParentNode(0);
var _parentParent2 = path.getParentNode(1);
var _parentParentParent = path.getParentNode(2);
var isArrowFunctionTypeAnnotation = n.type === "TSFunctionType" || !((_parent7.type === "ObjectTypeProperty" || _parent7.type === "ObjectTypeInternalSlot") && !getFlowVariance(_parent7) && !_parent7.optional && options.locStart(_parent7) === options.locStart(n) || _parent7.type === "ObjectTypeCallProperty" || _parentParentParent && _parentParentParent.type === "DeclareFunction");
var needsColon = isArrowFunctionTypeAnnotation && (_parent7.type === "TypeAnnotation" || _parent7.type === "TSTypeAnnotation"); // Sadly we can't put it inside of FastPath::needsColon because we are
// printing ":" as part of the expression and it would put parenthesis
// around :(
var needsParens = needsColon && isArrowFunctionTypeAnnotation && (_parent7.type === "TypeAnnotation" || _parent7.type === "TSTypeAnnotation") && _parentParent2.type === "ArrowFunctionExpression";
if (isObjectTypePropertyAFunction(_parent7, options)) {
isArrowFunctionTypeAnnotation = true;
needsColon = true;
}
if (needsParens) {
parts.push("(");
}
parts.push(printFunctionParams(path, print, options,
/* expandArg */
false,
/* printTypeParams */
true)); // The returnType is not wrapped in a TypeAnnotation, so the colon
// needs to be added separately.
if (n.returnType || n.predicate || n.typeAnnotation) {
parts.push(isArrowFunctionTypeAnnotation ? " => " : ": ", path.call(print, "returnType"), path.call(print, "predicate"), path.call(print, "typeAnnotation"));
}
if (needsParens) {
parts.push(")");
}
return group$10(concat$11(parts));
}
case "TSRestType":
return concat$11(["...", path.call(print, "typeAnnotation")]);
case "TSOptionalType":
return concat$11([path.call(print, "typeAnnotation"), "?"]);
case "FunctionTypeParam":
return concat$11([path.call(print, "name"), printOptionalToken(path), n.name ? ": " : "", path.call(print, "typeAnnotation")]);
case "GenericTypeAnnotation":
return concat$11([path.call(print, "id"), path.call(print, "typeParameters")]);
case "DeclareInterface":
case "InterfaceDeclaration":
case "InterfaceTypeAnnotation":
{
if (n.type === "DeclareInterface" || isNodeStartingWithDeclare(n, options)) {
parts.push("declare ");
}
parts.push("interface");
if (n.type === "DeclareInterface" || n.type === "InterfaceDeclaration") {
parts.push(" ", path.call(print, "id"), path.call(print, "typeParameters"));
}
if (n["extends"].length > 0) {
parts.push(group$10(indent$6(concat$11([line$8, "extends ", (n.extends.length === 1 ? identity$1 : indent$6)(join$7(concat$11([",", line$8]), path.map(print, "extends")))]))));
}
parts.push(" ", path.call(print, "body"));
return group$10(concat$11(parts));
}
case "ClassImplements":
case "InterfaceExtends":
return concat$11([path.call(print, "id"), path.call(print, "typeParameters")]);
case "TSClassImplements":
return concat$11([path.call(print, "expression"), path.call(print, "typeParameters")]);
case "TSIntersectionType":
case "IntersectionTypeAnnotation":
{
var types = path.map(print, "types");
var result = [];
var wasIndented = false;
for (var _i = 0; _i < types.length; ++_i) {
if (_i === 0) {
result.push(types[_i]);
} else if (isObjectType(n.types[_i - 1]) && isObjectType(n.types[_i])) {
// If both are objects, don't indent
result.push(concat$11([" & ", wasIndented ? indent$6(types[_i]) : types[_i]]));
} else if (!isObjectType(n.types[_i - 1]) && !isObjectType(n.types[_i])) {
// If no object is involved, go to the next line if it breaks
result.push(indent$6(concat$11([" &", line$8, types[_i]])));
} else {
// If you go from object to non-object or vis-versa, then inline it
if (_i > 1) {
wasIndented = true;
}
result.push(" & ", _i > 1 ? indent$6(types[_i]) : types[_i]);
}
}
return group$10(concat$11(result));
}
case "TSUnionType":
case "UnionTypeAnnotation":
{
// single-line variation
// A | B | C
// multi-line variation
// | A
// | B
// | C
var _parent8 = path.getParentNode(); // If there's a leading comment, the parent is doing the indentation
var shouldIndent = _parent8.type !== "TypeParameterInstantiation" && _parent8.type !== "TSTypeParameterInstantiation" && _parent8.type !== "GenericTypeAnnotation" && _parent8.type !== "TSTypeReference" && _parent8.type !== "TSTypeAssertion" && !(_parent8.type === "FunctionTypeParam" && !_parent8.name) && !((_parent8.type === "TypeAlias" || _parent8.type === "VariableDeclarator" || _parent8.type === "TSTypeAliasDeclaration") && hasLeadingOwnLineComment(options.originalText, n, options)); // {
// a: string
// } | null | void
// should be inlined and not be printed in the multi-line variant
var shouldHug = shouldHugType(n); // We want to align the children but without its comment, so it looks like
// | child1
// // comment
// | child2
var _printed4 = path.map(function (typePath) {
var printedType = typePath.call(print);
if (!shouldHug) {
printedType = align$1(2, printedType);
}
return comments.printComments(typePath, function () {
return printedType;
}, options);
}, "types");
if (shouldHug) {
return join$7(" | ", _printed4);
}
var shouldAddStartLine = shouldIndent && !hasLeadingOwnLineComment(options.originalText, n, options);
var code = concat$11([ifBreak$6(concat$11([shouldAddStartLine ? line$8 : "", "| "])), join$7(concat$11([line$8, "| "]), _printed4)]);
var hasParens;
if (n.type === "TSUnionType") {
var greatGrandParent = path.getParentNode(2);
var greatGreatGrandParent = path.getParentNode(3);
hasParens = greatGrandParent && greatGrandParent.type === "TSParenthesizedType" && greatGreatGrandParent && (greatGreatGrandParent.type === "TSUnionType" || greatGreatGrandParent.type === "TSIntersectionType");
} else {
hasParens = needsParens_1(path, options);
}
if (hasParens) {
return group$10(concat$11([indent$6(code), softline$5]));
}
return group$10(shouldIndent ? indent$6(code) : code);
}
case "NullableTypeAnnotation":
return concat$11(["?", path.call(print, "typeAnnotation")]);
case "TSNullKeyword":
case "NullLiteralTypeAnnotation":
return "null";
case "ThisTypeAnnotation":
return "this";
case "NumberTypeAnnotation":
return "number";
case "ObjectTypeCallProperty":
if (n.static) {
parts.push("static ");
}
parts.push(path.call(print, "value"));
return concat$11(parts);
case "ObjectTypeIndexer":
{
var _variance = getFlowVariance(n);
return concat$11([_variance || "", "[", path.call(print, "id"), n.id ? ": " : "", path.call(print, "key"), "]: ", path.call(print, "value")]);
}
case "ObjectTypeProperty":
{
var _variance2 = getFlowVariance(n);
var modifier = "";
if (n.proto) {
modifier = "proto ";
} else if (n.static) {
modifier = "static ";
}
return concat$11([modifier, isGetterOrSetter(n) ? n.kind + " " : "", _variance2 || "", printPropertyKey(path, options, print), printOptionalToken(path), isFunctionNotation(n, options) ? "" : ": ", path.call(print, "value")]);
}
case "QualifiedTypeIdentifier":
return concat$11([path.call(print, "qualification"), ".", path.call(print, "id")]);
case "StringLiteralTypeAnnotation":
return nodeStr(n, options);
case "NumberLiteralTypeAnnotation":
assert$3.strictEqual(_typeof(n.value), "number");
if (n.extra != null) {
return printNumber$2(n.extra.raw);
}
return printNumber$2(n.raw);
case "StringTypeAnnotation":
return "string";
case "DeclareTypeAlias":
case "TypeAlias":
{
if (n.type === "DeclareTypeAlias" || isNodeStartingWithDeclare(n, options)) {
parts.push("declare ");
}
var _printed5 = printAssignmentRight(n.id, n.right, path.call(print, "right"), options);
parts.push("type ", path.call(print, "id"), path.call(print, "typeParameters"), " =", _printed5, semi);
return group$10(concat$11(parts));
}
case "TypeCastExpression":
{
var value = path.getValue(); // Flow supports a comment syntax for specifying type annotations: https://flow.org/en/docs/types/comments/.
// Unfortunately, its parser doesn't differentiate between comment annotations and regular
// annotations when producing an AST. So to preserve parentheses around type casts that use
// the comment syntax, we need to hackily read the source itself to see if the code contains
// a type annotation comment.
//
// Note that we're able to use the normal whitespace regex here because the Flow parser has
// already deemed this AST node to be a type cast. Only the Babel parser needs the
// non-line-break whitespace regex, which is why hasFlowShorthandAnnotationComment() is
// implemented differently.
var commentSyntax = value && value.typeAnnotation && value.typeAnnotation.range && options.originalText.substring(value.typeAnnotation.range[0]).match(/^\/\*\s*:/);
return concat$11(["(", path.call(print, "expression"), commentSyntax ? " /*" : "", ": ", path.call(print, "typeAnnotation"), commentSyntax ? " */" : "", ")"]);
}
case "TypeParameterDeclaration":
case "TypeParameterInstantiation":
{
var _value = path.getValue();
var commentStart = _value.range ? options.originalText.substring(0, _value.range[0]).lastIndexOf("/*") : -1; // As noted in the TypeCastExpression comments above, we're able to use a normal whitespace regex here
// because we know for sure that this is a type definition.
var _commentSyntax = commentStart >= 0 && options.originalText.substring(commentStart).match(/^\/\*\s*::/);
if (_commentSyntax) {
return concat$11(["/*:: ", printTypeParameters(path, options, print, "params"), " */"]);
}
return printTypeParameters(path, options, print, "params");
}
case "TSTypeParameterDeclaration":
case "TSTypeParameterInstantiation":
return printTypeParameters(path, options, print, "params");
case "TSTypeParameter":
case "TypeParameter":
{
var _parent9 = path.getParentNode();
if (_parent9.type === "TSMappedType") {
parts.push("[", path.call(print, "name"));
if (n.constraint) {
parts.push(" in ", path.call(print, "constraint"));
}
parts.push("]");
return concat$11(parts);
}
var _variance3 = getFlowVariance(n);
if (_variance3) {
parts.push(_variance3);
}
parts.push(path.call(print, "name"));
if (n.bound) {
parts.push(": ");
parts.push(path.call(print, "bound"));
}
if (n.constraint) {
parts.push(" extends ", path.call(print, "constraint"));
}
if (n["default"]) {
parts.push(" = ", path.call(print, "default"));
} // Keep comma if the file extension is .tsx and
// has one type parameter that isn't extend with any types.
// Because, otherwise formatted result will be invalid as tsx.
var _grandParent = path.getNode(2);
if (_parent9.params && _parent9.params.length === 1 && options.filepath && /\.tsx$/i.test(options.filepath) && !n.constraint && _grandParent.type === "ArrowFunctionExpression") {
parts.push(",");
}
return concat$11(parts);
}
case "TypeofTypeAnnotation":
return concat$11(["typeof ", path.call(print, "argument")]);
case "VoidTypeAnnotation":
return "void";
case "InferredPredicate":
return "%checks";
// Unhandled types below. If encountered, nodes of these types should
// be either left alone or desugared into AST types that are fully
// supported by the pretty-printer.
case "DeclaredPredicate":
return concat$11(["%checks(", path.call(print, "value"), ")"]);
case "TSAbstractKeyword":
return "abstract";
case "TSAnyKeyword":
return "any";
case "TSAsyncKeyword":
return "async";
case "TSBooleanKeyword":
return "boolean";
case "TSBigIntKeyword":
return "bigint";
case "TSConstKeyword":
return "const";
case "TSDeclareKeyword":
return "declare";
case "TSExportKeyword":
return "export";
case "TSNeverKeyword":
return "never";
case "TSNumberKeyword":
return "number";
case "TSObjectKeyword":
return "object";
case "TSProtectedKeyword":
return "protected";
case "TSPrivateKeyword":
return "private";
case "TSPublicKeyword":
return "public";
case "TSReadonlyKeyword":
return "readonly";
case "TSSymbolKeyword":
return "symbol";
case "TSStaticKeyword":
return "static";
case "TSStringKeyword":
return "string";
case "TSUndefinedKeyword":
return "undefined";
case "TSUnknownKeyword":
return "unknown";
case "TSVoidKeyword":
return "void";
case "TSAsExpression":
return concat$11([path.call(print, "expression"), " as ", path.call(print, "typeAnnotation")]);
case "TSArrayType":
return concat$11([path.call(print, "elementType"), "[]"]);
case "TSPropertySignature":
{
if (n.export) {
parts.push("export ");
}
if (n.accessibility) {
parts.push(n.accessibility + " ");
}
if (n.static) {
parts.push("static ");
}
if (n.readonly) {
parts.push("readonly ");
}
if (n.computed) {
parts.push("[");
}
parts.push(printPropertyKey(path, options, print));
if (n.computed) {
parts.push("]");
}
parts.push(printOptionalToken(path));
if (n.typeAnnotation) {
parts.push(": ");
parts.push(path.call(print, "typeAnnotation"));
} // This isn't valid semantically, but it's in the AST so we can print it.
if (n.initializer) {
parts.push(" = ", path.call(print, "initializer"));
}
return concat$11(parts);
}
case "TSParameterProperty":
if (n.accessibility) {
parts.push(n.accessibility + " ");
}
if (n.export) {
parts.push("export ");
}
if (n.static) {
parts.push("static ");
}
if (n.readonly) {
parts.push("readonly ");
}
parts.push(path.call(print, "parameter"));
return concat$11(parts);
case "TSTypeReference":
return concat$11([path.call(print, "typeName"), printTypeParameters(path, options, print, "typeParameters")]);
case "TSTypeQuery":
return concat$11(["typeof ", path.call(print, "exprName")]);
case "TSParenthesizedType":
{
return path.call(print, "typeAnnotation");
}
case "TSIndexSignature":
{
var _parent10 = path.getParentNode();
return concat$11([n.export ? "export " : "", n.accessibility ? concat$11([n.accessibility, " "]) : "", n.static ? "static " : "", n.readonly ? "readonly " : "", "[", n.parameters ? concat$11(path.map(print, "parameters")) : "", "]: ", path.call(print, "typeAnnotation"), _parent10.type === "ClassBody" ? semi : ""]);
}
case "TSTypePredicate":
return concat$11([path.call(print, "parameterName"), " is ", path.call(print, "typeAnnotation")]);
case "TSNonNullExpression":
return concat$11([path.call(print, "expression"), "!"]);
case "TSThisType":
return "this";
case "TSImportType":
return concat$11([!n.isTypeOf ? "" : "typeof ", "import(", path.call(print, "parameter"), ")", !n.qualifier ? "" : concat$11([".", path.call(print, "qualifier")]), printTypeParameters(path, options, print, "typeParameters")]);
case "TSLiteralType":
return path.call(print, "literal");
case "TSIndexedAccessType":
return concat$11([path.call(print, "objectType"), "[", path.call(print, "indexType"), "]"]);
case "TSConstructSignatureDeclaration":
case "TSCallSignatureDeclaration":
case "TSConstructorType":
{
if (n.type !== "TSCallSignatureDeclaration") {
parts.push("new ");
}
parts.push(group$10(printFunctionParams(path, print, options,
/* expandArg */
false,
/* printTypeParams */
true)));
if (n.returnType) {
var isType = n.type === "TSConstructorType";
parts.push(isType ? " => " : ": ", path.call(print, "returnType"));
}
return concat$11(parts);
}
case "TSTypeOperator":
return concat$11([n.operator, " ", path.call(print, "typeAnnotation")]);
case "TSMappedType":
{
var _shouldBreak2 = hasNewlineInRange$1(options.originalText, options.locStart(n), options.locEnd(n));
return group$10(concat$11(["{", indent$6(concat$11([options.bracketSpacing ? line$8 : softline$5, n.readonly ? concat$11([getTypeScriptMappedTypeModifier(n.readonly, "readonly"), " "]) : "", printTypeScriptModifiers(path, options, print), path.call(print, "typeParameter"), n.optional ? getTypeScriptMappedTypeModifier(n.optional, "?") : "", ": ", path.call(print, "typeAnnotation"), _shouldBreak2 && options.semi ? ";" : ""])), comments.printDanglingComments(path, options,
/* sameIndent */
true), options.bracketSpacing ? line$8 : softline$5, "}"]), {
shouldBreak: _shouldBreak2
});
}
case "TSMethodSignature":
parts.push(n.accessibility ? concat$11([n.accessibility, " "]) : "", n.export ? "export " : "", n.static ? "static " : "", n.readonly ? "readonly " : "", n.computed ? "[" : "", path.call(print, "key"), n.computed ? "]" : "", printOptionalToken(path), printFunctionParams(path, print, options,
/* expandArg */
false,
/* printTypeParams */
true));
if (n.returnType) {
parts.push(": ", path.call(print, "returnType"));
}
return group$10(concat$11(parts));
case "TSNamespaceExportDeclaration":
parts.push("export as namespace ", path.call(print, "id"));
if (options.semi) {
parts.push(";");
}
return group$10(concat$11(parts));
case "TSEnumDeclaration":
if (isNodeStartingWithDeclare(n, options)) {
parts.push("declare ");
}
if (n.modifiers) {
parts.push(printTypeScriptModifiers(path, options, print));
}
if (n.const) {
parts.push("const ");
}
parts.push("enum ", path.call(print, "id"), " ");
if (n.members.length === 0) {
parts.push(group$10(concat$11(["{", comments.printDanglingComments(path, options), softline$5, "}"])));
} else {
parts.push(group$10(concat$11(["{", indent$6(concat$11([hardline$8, printArrayItems(path, options, "members", print), shouldPrintComma$1(options, "es5") ? "," : ""])), comments.printDanglingComments(path, options,
/* sameIndent */
true), hardline$8, "}"])));
}
return concat$11(parts);
case "TSEnumMember":
parts.push(path.call(print, "id"));
if (n.initializer) {
parts.push(" = ", path.call(print, "initializer"));
}
return concat$11(parts);
case "TSImportEqualsDeclaration":
if (n.isExport) {
parts.push("export ");
}
parts.push("import ", path.call(print, "id"), " = ", path.call(print, "moduleReference"));
if (options.semi) {
parts.push(";");
}
return group$10(concat$11(parts));
case "TSExternalModuleReference":
return concat$11(["require(", path.call(print, "expression"), ")"]);
case "TSModuleDeclaration":
{
var _parent11 = path.getParentNode();
var isExternalModule = isLiteral(n.id);
var parentIsDeclaration = _parent11.type === "TSModuleDeclaration";
var bodyIsDeclaration = n.body && n.body.type === "TSModuleDeclaration";
if (parentIsDeclaration) {
parts.push(".");
} else {
if (n.declare === true) {
parts.push("declare ");
}
parts.push(printTypeScriptModifiers(path, options, print));
var textBetweenNodeAndItsId = options.originalText.slice(options.locStart(n), options.locStart(n.id)); // Global declaration looks like this:
// (declare)? global { ... }
var isGlobalDeclaration = n.id.type === "Identifier" && n.id.name === "global" && !/namespace|module/.test(textBetweenNodeAndItsId);
if (!isGlobalDeclaration) {
parts.push(isExternalModule || /(^|\s)module(\s|$)/.test(textBetweenNodeAndItsId) ? "module " : "namespace ");
}
}
parts.push(path.call(print, "id"));
if (bodyIsDeclaration) {
parts.push(path.call(print, "body"));
} else if (n.body) {
parts.push(" ", group$10(path.call(print, "body")));
} else {
parts.push(semi);
}
return concat$11(parts);
}
case "PrivateName":
return concat$11(["#", path.call(print, "id")]);
case "TSConditionalType":
return printTernaryOperator(path, options, print, {
beforeParts: function beforeParts() {
return [path.call(print, "checkType"), " ", "extends", " ", path.call(print, "extendsType")];
},
afterParts: function afterParts() {
return [];
},
shouldCheckJsx: false,
conditionalNodeType: "TSConditionalType",
consequentNodePropertyName: "trueType",
alternateNodePropertyName: "falseType",
testNodePropertyName: "checkType",
breakNested: true
});
case "TSInferType":
return concat$11(["infer", " ", path.call(print, "typeParameter")]);
case "InterpreterDirective":
parts.push("#!", n.value, hardline$8);
if (isNextLineEmpty$4(options.originalText, n, options)) {
parts.push(hardline$8);
}
return concat$11(parts);
case "NGRoot":
return concat$11([].concat(path.call(print, "node"), !n.node.comments || n.node.comments.length === 0 ? [] : concat$11([" //", n.node.comments[0].value.trimRight()])));
case "NGChainedExpression":
return group$10(join$7(concat$11([";", line$8]), path.map(function (childPath) {
return hasNgSideEffect(childPath) ? print(childPath) : concat$11(["(", print(childPath), ")"]);
}, "expressions")));
case "NGEmptyExpression":
return "";
case "NGQuotedExpression":
return concat$11([n.prefix, ":", n.value]);
case "NGMicrosyntax":
return concat$11(path.map(function (childPath, index) {
return concat$11([index === 0 ? "" : isNgForOf(childPath.getValue(), index, n) ? " " : concat$11([";", line$8]), print(childPath)]);
}, "body"));
case "NGMicrosyntaxKey":
return /^[a-z_$][a-z0-9_$]*(-[a-z_$][a-z0-9_$])*$/i.test(n.name) ? n.name : JSON.stringify(n.name);
case "NGMicrosyntaxExpression":
return concat$11([path.call(print, "expression"), n.alias === null ? "" : concat$11([" as ", path.call(print, "alias")])]);
case "NGMicrosyntaxKeyedExpression":
{
var index = path.getName();
var _parentNode2 = path.getParentNode();
var shouldNotPrintColon = isNgForOf(n, index, _parentNode2) || (index === 1 && (n.key.name === "then" || n.key.name === "else") || index === 2 && n.key.name === "else" && _parentNode2.body[index - 1].type === "NGMicrosyntaxKeyedExpression" && _parentNode2.body[index - 1].key.name === "then") && _parentNode2.body[0].type === "NGMicrosyntaxExpression";
return concat$11([path.call(print, "key"), shouldNotPrintColon ? " " : ": ", path.call(print, "expression")]);
}
case "NGMicrosyntaxLet":
return concat$11(["let ", path.call(print, "key"), n.value === null ? "" : concat$11([" = ", path.call(print, "value")])]);
case "NGMicrosyntaxAs":
return concat$11([path.call(print, "key"), " as ", path.call(print, "alias")]);
default:
/* istanbul ignore next */
throw new Error("unknown type: " + JSON.stringify(n.type));
}
}
function isNgForOf(node, index, parentNode) {
return node.type === "NGMicrosyntaxKeyedExpression" && node.key.name === "of" && index === 1 && parentNode.body[0].type === "NGMicrosyntaxLet" && parentNode.body[0].value === null;
}
/** identify if an angular expression seems to have side effects */
function hasNgSideEffect(path) {
return hasNode(path.getValue(), function (node) {
switch (node.type) {
case undefined:
return false;
case "CallExpression":
case "OptionalCallExpression":
case "AssignmentExpression":
return true;
}
});
}
function printStatementSequence(path, options, print) {
var printed = [];
var bodyNode = path.getNode();
var isClass = bodyNode.type === "ClassBody";
path.map(function (stmtPath, i) {
var stmt = stmtPath.getValue(); // Just in case the AST has been modified to contain falsy
// "statements," it's safer simply to skip them.
/* istanbul ignore if */
if (!stmt) {
return;
} // Skip printing EmptyStatement nodes to avoid leaving stray
// semicolons lying around.
if (stmt.type === "EmptyStatement") {
return;
}
var stmtPrinted = print(stmtPath);
var text = options.originalText;
var parts = []; // in no-semi mode, prepend statement with semicolon if it might break ASI
// don't prepend the only JSX element in a program with semicolon
if (!options.semi && !isClass && !isTheOnlyJSXElementInMarkdown(options, stmtPath) && stmtNeedsASIProtection(stmtPath, options)) {
if (stmt.comments && stmt.comments.some(function (comment) {
return comment.leading;
})) {
parts.push(print(stmtPath, {
needsSemi: true
}));
} else {
parts.push(";", stmtPrinted);
}
} else {
parts.push(stmtPrinted);
}
if (!options.semi && isClass) {
if (classPropMayCauseASIProblems(stmtPath)) {
parts.push(";");
} else if (stmt.type === "ClassProperty") {
var nextChild = bodyNode.body[i + 1];
if (classChildNeedsASIProtection(nextChild)) {
parts.push(";");
}
}
}
if (isNextLineEmpty$4(text, stmt, options) && !isLastStatement(stmtPath)) {
parts.push(hardline$8);
}
printed.push(concat$11(parts));
});
return join$7(hardline$8, printed);
}
function printPropertyKey(path, options, print) {
var node = path.getNode();
var parent = path.getParentNode();
var key = node.key;
if (options.quoteProps === "consistent" && !needsQuoteProps.has(parent)) {
var objectHasStringProp = (parent.properties || parent.body || parent.members).some(function (prop) {
return !prop.computed && prop.key && isStringLiteral(prop.key) && !isStringPropSafeToCoerceToIdentifier(prop, options);
});
needsQuoteProps.set(parent, objectHasStringProp);
}
if (key.type === "Identifier" && !node.computed && (options.parser === "json" || options.quoteProps === "consistent" && needsQuoteProps.get(parent))) {
// a -> "a"
var prop = printString$2(JSON.stringify(key.name), options);
return path.call(function (keyPath) {
return comments.printComments(keyPath, function () {
return prop;
}, options);
}, "key");
}
if (!node.computed && isStringPropSafeToCoerceToIdentifier(node, options) && (options.quoteProps === "as-needed" || options.quoteProps === "consistent" && !needsQuoteProps.get(parent))) {
// 'a' -> a
return path.call(function (keyPath) {
return comments.printComments(keyPath, function () {
return key.value;
}, options);
}, "key");
}
return path.call(print, "key");
}
function printMethod(path, options, print) {
var node = path.getNode();
var semi = options.semi ? ";" : "";
var kind = node.kind;
var parts = [];
if (node.type === "ObjectMethod" || node.type === "ClassMethod" || node.type === "ClassPrivateMethod") {
node.value = node;
}
if (node.value.async) {
parts.push("async ");
}
if (!kind || kind === "init" || kind === "method" || kind === "constructor") {
if (node.value.generator) {
parts.push("*");
}
} else {
assert$3.ok(kind === "get" || kind === "set");
parts.push(kind, " ");
}
var key = printPropertyKey(path, options, print);
if (node.computed) {
key = concat$11(["[", key, "]"]);
}
parts.push(key, concat$11(path.call(function (valuePath) {
return [printFunctionTypeParameters(valuePath, options, print), group$10(concat$11([printFunctionParams(valuePath, print, options), printReturnType(valuePath, print, options)]))];
}, "value")));
if (!node.value.body || node.value.body.length === 0) {
parts.push(semi);
} else {
parts.push(" ", path.call(print, "value", "body"));
}
return concat$11(parts);
}
function couldGroupArg(arg) {
return arg.type === "ObjectExpression" && (arg.properties.length > 0 || arg.comments) || arg.type === "ArrayExpression" && (arg.elements.length > 0 || arg.comments) || arg.type === "TSTypeAssertion" || arg.type === "TSAsExpression" || arg.type === "FunctionExpression" || arg.type === "ArrowFunctionExpression" && ( // we want to avoid breaking inside composite return types but not simple keywords
// https://github.com/prettier/prettier/issues/4070
// export class Thing implements OtherThing {
// do: (type: Type) => Provider
= memoize(
// (type: ObjectType): Provider => {}
// );
// }
// https://github.com/prettier/prettier/issues/6099
// app.get("/", (req, res): void => {
// res.send("Hello World!");
// });
!arg.returnType || !arg.returnType.typeAnnotation || arg.returnType.typeAnnotation.type !== "TSTypeReference") && (arg.body.type === "BlockStatement" || arg.body.type === "ArrowFunctionExpression" || arg.body.type === "ObjectExpression" || arg.body.type === "ArrayExpression" || arg.body.type === "CallExpression" || arg.body.type === "OptionalCallExpression" || arg.body.type === "ConditionalExpression" || isJSXNode(arg.body));
}
function shouldGroupLastArg(args) {
var lastArg = getLast$3(args);
var penultimateArg = getPenultimate$1(args);
return !hasLeadingComment(lastArg) && !hasTrailingComment(lastArg) && couldGroupArg(lastArg) && ( // If the last two arguments are of the same type,
// disable last element expansion.
!penultimateArg || penultimateArg.type !== lastArg.type);
}
function shouldGroupFirstArg(args) {
if (args.length !== 2) {
return false;
}
var firstArg = args[0];
var secondArg = args[1];
return (!firstArg.comments || !firstArg.comments.length) && (firstArg.type === "FunctionExpression" || firstArg.type === "ArrowFunctionExpression" && firstArg.body.type === "BlockStatement") && secondArg.type !== "FunctionExpression" && secondArg.type !== "ArrowFunctionExpression" && secondArg.type !== "ConditionalExpression" && !couldGroupArg(secondArg);
}
function isSimpleFlowType(node) {
var flowTypeAnnotations = ["AnyTypeAnnotation", "NullLiteralTypeAnnotation", "GenericTypeAnnotation", "ThisTypeAnnotation", "NumberTypeAnnotation", "VoidTypeAnnotation", "EmptyTypeAnnotation", "MixedTypeAnnotation", "BooleanTypeAnnotation", "BooleanLiteralTypeAnnotation", "StringTypeAnnotation"];
return node && flowTypeAnnotations.indexOf(node.type) !== -1 && !(node.type === "GenericTypeAnnotation" && node.typeParameters);
}
function isJestEachTemplateLiteral(node, parentNode) {
/**
* describe.each`table`(name, fn)
* describe.only.each`table`(name, fn)
* describe.skip.each`table`(name, fn)
* test.each`table`(name, fn)
* test.only.each`table`(name, fn)
* test.skip.each`table`(name, fn)
*
* Ref: https://github.com/facebook/jest/pull/6102
*/
var jestEachTriggerRegex = /^[xf]?(describe|it|test)$/;
return parentNode.type === "TaggedTemplateExpression" && parentNode.quasi === node && parentNode.tag.type === "MemberExpression" && parentNode.tag.property.type === "Identifier" && parentNode.tag.property.name === "each" && (parentNode.tag.object.type === "Identifier" && jestEachTriggerRegex.test(parentNode.tag.object.name) || parentNode.tag.object.type === "MemberExpression" && parentNode.tag.object.property.type === "Identifier" && (parentNode.tag.object.property.name === "only" || parentNode.tag.object.property.name === "skip") && parentNode.tag.object.object.type === "Identifier" && jestEachTriggerRegex.test(parentNode.tag.object.object.name));
}
function printJestEachTemplateLiteral(node, expressions, options) {
/**
* a | b | expected
* ${1} | ${1} | ${2}
* ${1} | ${2} | ${3}
* ${2} | ${1} | ${3}
*/
var headerNames = node.quasis[0].value.raw.trim().split(/\s*\|\s*/);
if (headerNames.length > 1 || headerNames.some(function (headerName) {
return headerName.length !== 0;
})) {
var parts = [];
var stringifiedExpressions = expressions.map(function (doc$$2) {
return "${" + printDocToString$1(doc$$2, Object.assign({}, options, {
printWidth: Infinity,
endOfLine: "lf"
})).formatted + "}";
});
var tableBody = [{
hasLineBreak: false,
cells: []
}];
for (var i = 1; i < node.quasis.length; i++) {
var row = tableBody[tableBody.length - 1];
var correspondingExpression = stringifiedExpressions[i - 1];
row.cells.push(correspondingExpression);
if (correspondingExpression.indexOf("\n") !== -1) {
row.hasLineBreak = true;
}
if (node.quasis[i].value.raw.indexOf("\n") !== -1) {
tableBody.push({
hasLineBreak: false,
cells: []
});
}
}
var maxColumnCount = tableBody.reduce(function (maxColumnCount, row) {
return Math.max(maxColumnCount, row.cells.length);
}, headerNames.length);
var maxColumnWidths = Array.from(new Array(maxColumnCount), function () {
return 0;
});
var table = [{
cells: headerNames
}].concat(tableBody.filter(function (row) {
return row.cells.length !== 0;
}));
table.filter(function (row) {
return !row.hasLineBreak;
}).forEach(function (row) {
row.cells.forEach(function (cell, index) {
maxColumnWidths[index] = Math.max(maxColumnWidths[index], getStringWidth$2(cell));
});
});
parts.push("`", indent$6(concat$11([hardline$8, join$7(hardline$8, table.map(function (row) {
return join$7(" | ", row.cells.map(function (cell, index) {
return row.hasLineBreak ? cell : cell + " ".repeat(maxColumnWidths[index] - getStringWidth$2(cell));
}));
}))])), hardline$8, "`");
return concat$11(parts);
}
}
function isSimpleTemplateLiteral(node) {
if (node.expressions.length === 0) {
return false;
}
return node.expressions.every(function (expr) {
// Disallow comments since printDocToString can't print them here
if (expr.comments) {
return false;
} // Allow `x` and `this`
if (expr.type === "Identifier" || expr.type === "ThisExpression") {
return true;
} // Allow `a.b.c`, `a.b[c]`, and `this.x.y`
if ((expr.type === "MemberExpression" || expr.type === "OptionalMemberExpression") && (expr.property.type === "Identifier" || expr.property.type === "Literal")) {
var ancestor = expr;
while (ancestor.type === "MemberExpression" || ancestor.type === "OptionalMemberExpression") {
ancestor = ancestor.object;
if (ancestor.comments) {
return false;
}
}
if (ancestor.type === "Identifier" || ancestor.type === "ThisExpression") {
return true;
}
return false;
}
return false;
});
}
var functionCompositionFunctionNames = new Set(["pipe", // RxJS, Ramda
"pipeP", // Ramda
"pipeK", // Ramda
"compose", // Ramda, Redux
"composeFlipped", // Not from any library, but common in Haskell, so supported
"composeP", // Ramda
"composeK", // Ramda
"flow", // Lodash
"flowRight", // Lodash
"connect", // Redux
"createSelector" // Reselect
]);
var ordinaryMethodNames = new Set(["connect" // GObject, MongoDB
]);
function isFunctionCompositionFunction(node) {
switch (node.type) {
case "OptionalMemberExpression":
case "MemberExpression":
{
return isFunctionCompositionFunction(node.property) && !ordinaryMethodNames.has(node.property.name);
}
case "Identifier":
{
return functionCompositionFunctionNames.has(node.name);
}
case "StringLiteral":
case "Literal":
{
return functionCompositionFunctionNames.has(node.value);
}
}
}
function printArgumentsList(path, options, print) {
var node = path.getValue();
var args = node.arguments;
if (args.length === 0) {
return concat$11(["(", comments.printDanglingComments(path, options,
/* sameIndent */
true), ")"]);
} // useEffect(() => { ... }, [foo, bar, baz])
if (args.length === 2 && args[0].type === "ArrowFunctionExpression" && args[0].params.length === 0 && args[0].body.type === "BlockStatement" && args[1].type === "ArrayExpression" && !args.find(function (arg) {
return arg.leadingComments || arg.trailingComments;
})) {
return concat$11(["(", path.call(print, "arguments", 0), ", ", path.call(print, "arguments", 1), ")"]);
}
var anyArgEmptyLine = false;
var hasEmptyLineFollowingFirstArg = false;
var lastArgIndex = args.length - 1;
var printedArguments = path.map(function (argPath, index) {
var arg = argPath.getNode();
var parts = [print(argPath)];
if (index === lastArgIndex) {// do nothing
} else if (isNextLineEmpty$4(options.originalText, arg, options)) {
if (index === 0) {
hasEmptyLineFollowingFirstArg = true;
}
anyArgEmptyLine = true;
parts.push(",", hardline$8, hardline$8);
} else {
parts.push(",", line$8);
}
return concat$11(parts);
}, "arguments");
var maybeTrailingComma = // Dynamic imports cannot have trailing commas
!(node.callee && node.callee.type === "Import") && shouldPrintComma$1(options, "all") ? "," : "";
function allArgsBrokenOut() {
return group$10(concat$11(["(", indent$6(concat$11([line$8, concat$11(printedArguments)])), maybeTrailingComma, line$8, ")"]), {
shouldBreak: true
});
} // We want to get
// pipe(
// x => x + 1,
// x => x - 1
// )
// here, but not
// process.stdout.pipe(socket)
if (isFunctionCompositionFunction(node.callee) && args.length > 1) {
return allArgsBrokenOut();
}
var shouldGroupFirst = shouldGroupFirstArg(args);
var shouldGroupLast = shouldGroupLastArg(args);
if (shouldGroupFirst || shouldGroupLast) {
var shouldBreak = (shouldGroupFirst ? printedArguments.slice(1).some(willBreak$1) : printedArguments.slice(0, -1).some(willBreak$1)) || anyArgEmptyLine; // We want to print the last argument with a special flag
var printedExpanded;
var i = 0;
path.each(function (argPath) {
if (shouldGroupFirst && i === 0) {
printedExpanded = [concat$11([argPath.call(function (p) {
return print(p, {
expandFirstArg: true
});
}), printedArguments.length > 1 ? "," : "", hasEmptyLineFollowingFirstArg ? hardline$8 : line$8, hasEmptyLineFollowingFirstArg ? hardline$8 : ""])].concat(printedArguments.slice(1));
}
if (shouldGroupLast && i === args.length - 1) {
printedExpanded = printedArguments.slice(0, -1).concat(argPath.call(function (p) {
return print(p, {
expandLastArg: true
});
}));
}
i++;
}, "arguments");
var somePrintedArgumentsWillBreak = printedArguments.some(willBreak$1);
return concat$11([somePrintedArgumentsWillBreak ? breakParent$3 : "", conditionalGroup$1([concat$11([ifBreak$6(indent$6(concat$11(["(", softline$5, concat$11(printedExpanded)])), concat$11(["(", concat$11(printedExpanded)])), somePrintedArgumentsWillBreak ? concat$11([ifBreak$6(maybeTrailingComma), softline$5]) : "", ")"]), shouldGroupFirst ? concat$11(["(", group$10(printedExpanded[0], {
shouldBreak: true
}), concat$11(printedExpanded.slice(1)), ")"]) : concat$11(["(", concat$11(printedArguments.slice(0, -1)), group$10(getLast$3(printedExpanded), {
shouldBreak: true
}), ")"]), allArgsBrokenOut()], {
shouldBreak: shouldBreak
})]);
}
return group$10(concat$11(["(", indent$6(concat$11([softline$5, concat$11(printedArguments)])), ifBreak$6(maybeTrailingComma), softline$5, ")"]), {
shouldBreak: printedArguments.some(willBreak$1) || anyArgEmptyLine
});
}
function printTypeAnnotation(path, options, print) {
var node = path.getValue();
if (!node.typeAnnotation) {
return "";
}
var parentNode = path.getParentNode();
var isDefinite = node.definite || parentNode && parentNode.type === "VariableDeclarator" && parentNode.definite;
var isFunctionDeclarationIdentifier = parentNode.type === "DeclareFunction" && parentNode.id === node;
if (isFlowAnnotationComment(options.originalText, node.typeAnnotation, options)) {
return concat$11([" /*: ", path.call(print, "typeAnnotation"), " */"]);
}
return concat$11([isFunctionDeclarationIdentifier ? "" : isDefinite ? "!: " : ": ", path.call(print, "typeAnnotation")]);
}
function printFunctionTypeParameters(path, options, print) {
var fun = path.getValue();
if (fun.typeArguments) {
return path.call(print, "typeArguments");
}
if (fun.typeParameters) {
return path.call(print, "typeParameters");
}
return "";
}
function printFunctionParams(path, print, options, expandArg, printTypeParams) {
var fun = path.getValue();
var parent = path.getParentNode();
var paramsField = fun.parameters ? "parameters" : "params";
var isParametersInTestCall = isTestCall(parent);
var shouldHugParameters = shouldHugArguments(fun);
var shouldExpandParameters = expandArg && !(fun[paramsField] && fun[paramsField].some(function (n) {
return n.comments;
}));
var typeParams = printTypeParams ? printFunctionTypeParameters(path, options, print) : "";
var printed = [];
if (fun[paramsField]) {
var lastArgIndex = fun[paramsField].length - 1;
printed = path.map(function (childPath, index) {
var parts = [];
var param = childPath.getValue();
parts.push(print(childPath));
if (index === lastArgIndex) {
if (fun.rest) {
parts.push(",", line$8);
}
} else if (isParametersInTestCall || shouldHugParameters || shouldExpandParameters) {
parts.push(", ");
} else if (isNextLineEmpty$4(options.originalText, param, options)) {
parts.push(",", hardline$8, hardline$8);
} else {
parts.push(",", line$8);
}
return concat$11(parts);
}, paramsField);
}
if (fun.rest) {
printed.push(concat$11(["...", path.call(print, "rest")]));
}
if (printed.length === 0) {
return concat$11([typeParams, "(", comments.printDanglingComments(path, options,
/* sameIndent */
true, function (comment) {
return getNextNonSpaceNonCommentCharacter$1(options.originalText, comment, options.locEnd) === ")";
}), ")"]);
}
var lastParam = getLast$3(fun[paramsField]); // If the parent is a call with the first/last argument expansion and this is the
// params of the first/last argument, we dont want the arguments to break and instead
// want the whole expression to be on a new line.
//
// Good: Bad:
// verylongcall( verylongcall((
// (a, b) => { a,
// } b,
// }) ) => {
// })
if (shouldExpandParameters) {
return group$10(concat$11([removeLines$2(typeParams), "(", concat$11(printed.map(removeLines$2)), ")"]));
} // Single object destructuring should hug
//
// function({
// a,
// b,
// c
// }) {}
if (shouldHugParameters) {
return concat$11([typeParams, "(", concat$11(printed), ")"]);
} // don't break in specs, eg; `it("should maintain parens around done even when long", (done) => {})`
if (isParametersInTestCall) {
return concat$11([typeParams, "(", concat$11(printed), ")"]);
}
var isFlowShorthandWithOneArg = (isObjectTypePropertyAFunction(parent, options) || isTypeAnnotationAFunction(parent, options) || parent.type === "TypeAlias" || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType" || parent.type === "IntersectionTypeAnnotation" || parent.type === "FunctionTypeAnnotation" && parent.returnType === fun) && fun[paramsField].length === 1 && fun[paramsField][0].name === null && fun[paramsField][0].typeAnnotation && fun.typeParameters === null && isSimpleFlowType(fun[paramsField][0].typeAnnotation) && !fun.rest;
if (isFlowShorthandWithOneArg) {
if (options.arrowParens === "always") {
return concat$11(["(", concat$11(printed), ")"]);
}
return concat$11(printed);
}
var canHaveTrailingComma = !(lastParam && lastParam.type === "RestElement") && !fun.rest;
return concat$11([typeParams, "(", indent$6(concat$11([softline$5, concat$11(printed)])), ifBreak$6(canHaveTrailingComma && shouldPrintComma$1(options, "all") ? "," : ""), softline$5, ")"]);
}
function shouldPrintParamsWithoutParens(path, options) {
if (options.arrowParens === "always") {
return false;
}
if (options.arrowParens === "avoid") {
var node = path.getValue();
return canPrintParamsWithoutParens(node);
} // Fallback default; should be unreachable
return false;
}
function canPrintParamsWithoutParens(node) {
return node.params.length === 1 && !node.rest && !node.typeParameters && !hasDanglingComments(node) && node.params[0].type === "Identifier" && !node.params[0].typeAnnotation && !node.params[0].comments && !node.params[0].optional && !node.predicate && !node.returnType;
}
function printFunctionDeclaration(path, print, options) {
var n = path.getValue();
var parts = [];
if (n.async) {
parts.push("async ");
}
parts.push("function");
if (n.generator) {
parts.push("*");
}
if (n.id) {
parts.push(" ", path.call(print, "id"));
}
parts.push(printFunctionTypeParameters(path, options, print), group$10(concat$11([printFunctionParams(path, print, options), printReturnType(path, print, options)])), n.body ? " " : "", path.call(print, "body"));
return concat$11(parts);
}
function printObjectMethod(path, options, print) {
var objMethod = path.getValue();
var parts = [];
if (objMethod.async) {
parts.push("async ");
}
if (objMethod.generator) {
parts.push("*");
}
if (objMethod.method || objMethod.kind === "get" || objMethod.kind === "set") {
return printMethod(path, options, print);
}
var key = printPropertyKey(path, options, print);
if (objMethod.computed) {
parts.push("[", key, "]");
} else {
parts.push(key);
}
parts.push(printFunctionTypeParameters(path, options, print), group$10(concat$11([printFunctionParams(path, print, options), printReturnType(path, print, options)])), " ", path.call(print, "body"));
return concat$11(parts);
}
function printReturnType(path, print, options) {
var n = path.getValue();
var returnType = path.call(print, "returnType");
if (n.returnType && isFlowAnnotationComment(options.originalText, n.returnType, options)) {
return concat$11([" /*: ", returnType, " */"]);
}
var parts = [returnType]; // prepend colon to TypeScript type annotation
if (n.returnType && n.returnType.typeAnnotation) {
parts.unshift(": ");
}
if (n.predicate) {
// The return type will already add the colon, but otherwise we
// need to do it ourselves
parts.push(n.returnType ? " " : ": ", path.call(print, "predicate"));
}
return concat$11(parts);
}
function printExportDeclaration(path, options, print) {
var decl = path.getValue();
var semi = options.semi ? ";" : "";
var parts = ["export "];
var isDefault = decl["default"] || decl.type === "ExportDefaultDeclaration";
if (isDefault) {
parts.push("default ");
}
parts.push(comments.printDanglingComments(path, options,
/* sameIndent */
true));
if (needsHardlineAfterDanglingComment(decl)) {
parts.push(hardline$8);
}
if (decl.declaration) {
parts.push(path.call(print, "declaration"));
if (isDefault && decl.declaration.type !== "ClassDeclaration" && decl.declaration.type !== "FunctionDeclaration" && decl.declaration.type !== "TSInterfaceDeclaration" && decl.declaration.type !== "DeclareClass" && decl.declaration.type !== "DeclareFunction" && decl.declaration.type !== "TSDeclareFunction") {
parts.push(semi);
}
} else {
if (decl.specifiers && decl.specifiers.length > 0) {
var specifiers = [];
var defaultSpecifiers = [];
var namespaceSpecifiers = [];
path.each(function (specifierPath) {
var specifierType = path.getValue().type;
if (specifierType === "ExportSpecifier") {
specifiers.push(print(specifierPath));
} else if (specifierType === "ExportDefaultSpecifier") {
defaultSpecifiers.push(print(specifierPath));
} else if (specifierType === "ExportNamespaceSpecifier") {
namespaceSpecifiers.push(concat$11(["* as ", print(specifierPath)]));
}
}, "specifiers");
var isNamespaceFollowed = namespaceSpecifiers.length !== 0 && specifiers.length !== 0;
var isDefaultFollowed = defaultSpecifiers.length !== 0 && (namespaceSpecifiers.length !== 0 || specifiers.length !== 0);
parts.push(decl.exportKind === "type" ? "type " : "", concat$11(defaultSpecifiers), concat$11([isDefaultFollowed ? ", " : ""]), concat$11(namespaceSpecifiers), concat$11([isNamespaceFollowed ? ", " : ""]), specifiers.length !== 0 ? group$10(concat$11(["{", indent$6(concat$11([options.bracketSpacing ? line$8 : softline$5, join$7(concat$11([",", line$8]), specifiers)])), ifBreak$6(shouldPrintComma$1(options) ? "," : ""), options.bracketSpacing ? line$8 : softline$5, "}"])) : "");
} else {
parts.push("{}");
}
if (decl.source) {
parts.push(" from ", path.call(print, "source"));
}
parts.push(semi);
}
return concat$11(parts);
}
function printFlowDeclaration(path, parts) {
var parentExportDecl = getParentExportDeclaration$1(path);
if (parentExportDecl) {
assert$3.strictEqual(parentExportDecl.type, "DeclareExportDeclaration");
} else {
// If the parent node has type DeclareExportDeclaration, then it
// will be responsible for printing the "declare" token. Otherwise
// it needs to be printed with this non-exported declaration node.
parts.unshift("declare ");
}
return concat$11(parts);
}
function getFlowVariance(path) {
if (!path.variance) {
return null;
} // Babel 7.0 currently uses variance node type, and flow should
// follow suit soon:
// https://github.com/babel/babel/issues/4722
var variance = path.variance.kind || path.variance;
switch (variance) {
case "plus":
return "+";
case "minus":
return "-";
default:
/* istanbul ignore next */
return variance;
}
}
function printTypeScriptModifiers(path, options, print) {
var n = path.getValue();
if (!n.modifiers || !n.modifiers.length) {
return "";
}
return concat$11([join$7(" ", path.map(print, "modifiers")), " "]);
}
function printTypeParameters(path, options, print, paramsKey) {
var n = path.getValue();
if (!n[paramsKey]) {
return "";
} // for TypeParameterDeclaration typeParameters is a single node
if (!Array.isArray(n[paramsKey])) {
return path.call(print, paramsKey);
}
var grandparent = path.getNode(2);
var isParameterInTestCall = grandparent != null && isTestCall(grandparent);
var shouldInline = isParameterInTestCall || n[paramsKey].length === 0 || n[paramsKey].length === 1 && (shouldHugType(n[paramsKey][0]) || n[paramsKey][0].type === "GenericTypeAnnotation" && shouldHugType(n[paramsKey][0].id) || n[paramsKey][0].type === "TSTypeReference" && shouldHugType(n[paramsKey][0].typeName) || n[paramsKey][0].type === "NullableTypeAnnotation");
if (shouldInline) {
return concat$11(["<", join$7(", ", path.map(print, paramsKey)), ">"]);
}
return group$10(concat$11(["<", indent$6(concat$11([softline$5, join$7(concat$11([",", line$8]), path.map(print, paramsKey))])), ifBreak$6(options.parser !== "typescript" && shouldPrintComma$1(options, "all") ? "," : ""), softline$5, ">"]));
}
function printClass(path, options, print) {
var n = path.getValue();
var parts = [];
if (n.abstract) {
parts.push("abstract ");
}
parts.push("class");
if (n.id) {
parts.push(" ", path.call(print, "id"));
}
parts.push(path.call(print, "typeParameters"));
var partsGroup = [];
if (n.superClass) {
var printed = concat$11(["extends ", path.call(print, "superClass"), path.call(print, "superTypeParameters")]); // Keep old behaviour of extends in same line
// If there is only on extends and there are not comments
if ((!n.implements || n.implements.length === 0) && (!n.superClass.comments || n.superClass.comments.length === 0)) {
parts.push(concat$11([" ", path.call(function (superClass) {
return comments.printComments(superClass, function () {
return printed;
}, options);
}, "superClass")]));
} else {
partsGroup.push(group$10(concat$11([line$8, path.call(function (superClass) {
return comments.printComments(superClass, function () {
return printed;
}, options);
}, "superClass")])));
}
} else if (n.extends && n.extends.length > 0) {
parts.push(" extends ", join$7(", ", path.map(print, "extends")));
}
if (n["mixins"] && n["mixins"].length > 0) {
partsGroup.push(line$8, "mixins ", group$10(indent$6(join$7(concat$11([",", line$8]), path.map(print, "mixins")))));
}
if (n["implements"] && n["implements"].length > 0) {
partsGroup.push(line$8, "implements", group$10(indent$6(concat$11([line$8, join$7(concat$11([",", line$8]), path.map(print, "implements"))]))));
}
if (partsGroup.length > 0) {
parts.push(group$10(indent$6(concat$11(partsGroup))));
}
if (n.body && n.body.comments && hasLeadingOwnLineComment(options.originalText, n.body, options)) {
parts.push(hardline$8);
} else {
parts.push(" ");
}
parts.push(path.call(print, "body"));
return parts;
}
function printOptionalToken(path) {
var node = path.getValue();
if (!node.optional) {
return "";
}
if (node.type === "OptionalCallExpression" || node.type === "OptionalMemberExpression" && node.computed) {
return "?.";
}
return "?";
}
function printMemberLookup(path, options, print) {
var property = path.call(print, "property");
var n = path.getValue();
var optional = printOptionalToken(path);
if (!n.computed) {
return concat$11([optional, ".", property]);
}
if (!n.property || isNumericLiteral(n.property)) {
return concat$11([optional, "[", property, "]"]);
}
return group$10(concat$11([optional, "[", indent$6(concat$11([softline$5, property])), softline$5, "]"]));
}
function printBindExpressionCallee(path, options, print) {
return concat$11(["::", path.call(print, "callee")]);
} // We detect calls on member expressions specially to format a
// common pattern better. The pattern we are looking for is this:
//
// arr
// .map(x => x + 1)
// .filter(x => x > 10)
// .some(x => x % 2)
//
// The way it is structured in the AST is via a nested sequence of
// MemberExpression and CallExpression. We need to traverse the AST
// and make groups out of it to print it in the desired way.
function printMemberChain(path, options, print) {
// The first phase is to linearize the AST by traversing it down.
//
// a().b()
// has the following AST structure:
// CallExpression(MemberExpression(CallExpression(Identifier)))
// and we transform it into
// [Identifier, CallExpression, MemberExpression, CallExpression]
var printedNodes = []; // Here we try to retain one typed empty line after each call expression or
// the first group whether it is in parentheses or not
function shouldInsertEmptyLineAfter(node) {
var originalText = options.originalText;
var nextCharIndex = getNextNonSpaceNonCommentCharacterIndex$2(originalText, node, options);
var nextChar = originalText.charAt(nextCharIndex); // if it is cut off by a parenthesis, we only account for one typed empty
// line after that parenthesis
if (nextChar == ")") {
return isNextLineEmptyAfterIndex$1(originalText, nextCharIndex + 1, options);
}
return isNextLineEmpty$4(originalText, node, options);
}
function rec(path) {
var node = path.getValue();
if ((node.type === "CallExpression" || node.type === "OptionalCallExpression") && (isMemberish(node.callee) || node.callee.type === "CallExpression" || node.callee.type === "OptionalCallExpression")) {
printedNodes.unshift({
node: node,
printed: concat$11([comments.printComments(path, function () {
return concat$11([printOptionalToken(path), printFunctionTypeParameters(path, options, print), printArgumentsList(path, options, print)]);
}, options), shouldInsertEmptyLineAfter(node) ? hardline$8 : ""])
});
path.call(function (callee) {
return rec(callee);
}, "callee");
} else if (isMemberish(node)) {
printedNodes.unshift({
node: node,
needsParens: needsParens_1(path, options),
printed: comments.printComments(path, function () {
return node.type === "OptionalMemberExpression" || node.type === "MemberExpression" ? printMemberLookup(path, options, print) : printBindExpressionCallee(path, options, print);
}, options)
});
path.call(function (object) {
return rec(object);
}, "object");
} else if (node.type === "TSNonNullExpression") {
printedNodes.unshift({
node: node,
printed: comments.printComments(path, function () {
return "!";
}, options)
});
path.call(function (expression) {
return rec(expression);
}, "expression");
} else {
printedNodes.unshift({
node: node,
printed: path.call(print)
});
}
} // Note: the comments of the root node have already been printed, so we
// need to extract this first call without printing them as they would
// if handled inside of the recursive call.
var node = path.getValue();
printedNodes.unshift({
node: node,
printed: concat$11([printOptionalToken(path), printFunctionTypeParameters(path, options, print), printArgumentsList(path, options, print)])
});
path.call(function (callee) {
return rec(callee);
}, "callee"); // Once we have a linear list of printed nodes, we want to create groups out
// of it.
//
// a().b.c().d().e
// will be grouped as
// [
// [Identifier, CallExpression],
// [MemberExpression, MemberExpression, CallExpression],
// [MemberExpression, CallExpression],
// [MemberExpression],
// ]
// so that we can print it as
// a()
// .b.c()
// .d()
// .e
// The first group is the first node followed by
// - as many CallExpression as possible
// < fn()()() >.something()
// - as many array acessors as possible
// < fn()[0][1][2] >.something()
// - then, as many MemberExpression as possible but the last one
// < this.items >.something()
var groups = [];
var currentGroup = [printedNodes[0]];
var i = 1;
for (; i < printedNodes.length; ++i) {
if (printedNodes[i].node.type === "TSNonNullExpression" || printedNodes[i].node.type === "OptionalCallExpression" || printedNodes[i].node.type === "CallExpression" || (printedNodes[i].node.type === "MemberExpression" || printedNodes[i].node.type === "OptionalMemberExpression") && printedNodes[i].node.computed && isNumericLiteral(printedNodes[i].node.property)) {
currentGroup.push(printedNodes[i]);
} else {
break;
}
}
if (printedNodes[0].node.type !== "CallExpression" && printedNodes[0].node.type !== "OptionalCallExpression") {
for (; i + 1 < printedNodes.length; ++i) {
if (isMemberish(printedNodes[i].node) && isMemberish(printedNodes[i + 1].node)) {
currentGroup.push(printedNodes[i]);
} else {
break;
}
}
}
groups.push(currentGroup);
currentGroup = []; // Then, each following group is a sequence of MemberExpression followed by
// a sequence of CallExpression. To compute it, we keep adding things to the
// group until we has seen a CallExpression in the past and reach a
// MemberExpression
var hasSeenCallExpression = false;
for (; i < printedNodes.length; ++i) {
if (hasSeenCallExpression && isMemberish(printedNodes[i].node)) {
// [0] should be appended at the end of the group instead of the
// beginning of the next one
if (printedNodes[i].node.computed && isNumericLiteral(printedNodes[i].node.property)) {
currentGroup.push(printedNodes[i]);
continue;
}
groups.push(currentGroup);
currentGroup = [];
hasSeenCallExpression = false;
}
if (printedNodes[i].node.type === "CallExpression" || printedNodes[i].node.type === "OptionalCallExpression") {
hasSeenCallExpression = true;
}
currentGroup.push(printedNodes[i]);
if (printedNodes[i].node.comments && printedNodes[i].node.comments.some(function (comment) {
return comment.trailing;
})) {
groups.push(currentGroup);
currentGroup = [];
hasSeenCallExpression = false;
}
}
if (currentGroup.length > 0) {
groups.push(currentGroup);
} // There are cases like Object.keys(), Observable.of(), _.values() where
// they are the subject of all the chained calls and therefore should
// be kept on the same line:
//
// Object.keys(items)
// .filter(x => x)
// .map(x => x)
//
// In order to detect those cases, we use an heuristic: if the first
// node is an identifier with the name starting with a capital
// letter or just a sequence of _$. The rationale is that they are
// likely to be factories.
function isFactory(name) {
return /^[A-Z]|^[_$]+$/.test(name);
} // In case the Identifier is shorter than tab width, we can keep the
// first call in a single line, if it's an ExpressionStatement.
//
// d3.scaleLinear()
// .domain([0, 100])
// .range([0, width]);
//
function isShort(name) {
return name.length <= options.tabWidth;
}
function shouldNotWrap(groups) {
var parent = path.getParentNode();
var isExpression = parent && parent.type === "ExpressionStatement";
var hasComputed = groups[1].length && groups[1][0].node.computed;
if (groups[0].length === 1) {
var firstNode = groups[0][0].node;
return firstNode.type === "ThisExpression" || firstNode.type === "Identifier" && (isFactory(firstNode.name) || isExpression && isShort(firstNode.name) || hasComputed);
}
var lastNode = getLast$3(groups[0]).node;
return (lastNode.type === "MemberExpression" || lastNode.type === "OptionalMemberExpression") && lastNode.property.type === "Identifier" && (isFactory(lastNode.property.name) || hasComputed);
}
var shouldMerge = groups.length >= 2 && !groups[1][0].node.comments && shouldNotWrap(groups);
function printGroup(printedGroup) {
var printed = printedGroup.map(function (tuple) {
return tuple.printed;
}); // Checks if the last node (i.e. the parent node) needs parens and print
// accordingly
if (printedGroup.length > 0 && printedGroup[printedGroup.length - 1].needsParens) {
return concat$11(["("].concat(_toConsumableArray(printed), [")"]));
}
return concat$11(printed);
}
function printIndentedGroup(groups) {
if (groups.length === 0) {
return "";
}
return indent$6(group$10(concat$11([hardline$8, join$7(hardline$8, groups.map(printGroup))])));
}
var printedGroups = groups.map(printGroup);
var oneLine = concat$11(printedGroups);
var cutoff = shouldMerge ? 3 : 2;
var flatGroups = groups.slice(0, cutoff).reduce(function (res, group) {
return res.concat(group);
}, []);
var hasComment = flatGroups.slice(1, -1).some(function (node) {
return hasLeadingComment(node.node);
}) || flatGroups.slice(0, -1).some(function (node) {
return hasTrailingComment(node.node);
}) || groups[cutoff] && hasLeadingComment(groups[cutoff][0].node); // If we only have a single `.`, we shouldn't do anything fancy and just
// render everything concatenated together.
if (groups.length <= cutoff && !hasComment) {
return group$10(oneLine);
} // Find out the last node in the first group and check if it has an
// empty line after
var lastNodeBeforeIndent = getLast$3(shouldMerge ? groups.slice(1, 2)[0] : groups[0]).node;
var shouldHaveEmptyLineBeforeIndent = lastNodeBeforeIndent.type !== "CallExpression" && lastNodeBeforeIndent.type !== "OptionalCallExpression" && shouldInsertEmptyLineAfter(lastNodeBeforeIndent);
var expanded = concat$11([printGroup(groups[0]), shouldMerge ? concat$11(groups.slice(1, 2).map(printGroup)) : "", shouldHaveEmptyLineBeforeIndent ? hardline$8 : "", printIndentedGroup(groups.slice(shouldMerge ? 2 : 1))]);
var callExpressions = printedNodes.map(function (_ref) {
var node = _ref.node;
return node;
}).filter(isCallOrOptionalCallExpression); // We don't want to print in one line if there's:
// * A comment.
// * 3 or more chained calls.
// * Any group but the last one has a hard line.
// If the last group is a function it's okay to inline if it fits.
if (hasComment || callExpressions.length >= 3 || printedGroups.slice(0, -1).some(willBreak$1) ||
/**
* scopes.filter(scope => scope.value !== '').map((scope, i) => {
* // multi line content
* })
*/
function (lastGroupDoc, lastGroupNode) {
return isCallOrOptionalCallExpression(lastGroupNode) && willBreak$1(lastGroupDoc);
}(getLast$3(printedGroups), getLast$3(getLast$3(groups)).node) && callExpressions.slice(0, -1).some(function (n) {
return n.arguments.some(isFunctionOrArrowExpression);
})) {
return group$10(expanded);
}
return concat$11([// We only need to check `oneLine` because if `expanded` is chosen
// that means that the parent group has already been broken
// naturally
willBreak$1(oneLine) || shouldHaveEmptyLineBeforeIndent ? breakParent$3 : "", conditionalGroup$1([oneLine, expanded])]);
}
function isCallOrOptionalCallExpression(node) {
return node.type === "CallExpression" || node.type === "OptionalCallExpression";
}
function isJSXNode(node) {
return node.type === "JSXElement" || node.type === "JSXFragment";
}
function isEmptyJSXElement(node) {
if (node.children.length === 0) {
return true;
}
if (node.children.length > 1) {
return false;
} // if there is one text child and does not contain any meaningful text
// we can treat the element as empty.
var child = node.children[0];
return isLiteral(child) && !isMeaningfulJSXText(child);
} // Only space, newline, carriage return, and tab are treated as whitespace
// inside JSX.
var jsxWhitespaceChars = " \n\r\t";
var containsNonJsxWhitespaceRegex = new RegExp("[^" + jsxWhitespaceChars + "]");
var matchJsxWhitespaceRegex = new RegExp("([" + jsxWhitespaceChars + "]+)"); // Meaningful if it contains non-whitespace characters,
// or it contains whitespace without a new line.
function isMeaningfulJSXText(node) {
return isLiteral(node) && (containsNonJsxWhitespaceRegex.test(rawText(node)) || !/\n/.test(rawText(node)));
}
function conditionalExpressionChainContainsJSX(node) {
return Boolean(getConditionalChainContents(node).find(isJSXNode));
} // If we have nested conditional expressions, we want to print them in JSX mode
// if there's at least one JSXElement somewhere in the tree.
//
// A conditional expression chain like this should be printed in normal mode,
// because there aren't JSXElements anywhere in it:
//
// isA ? "A" : isB ? "B" : isC ? "C" : "Unknown";
//
// But a conditional expression chain like this should be printed in JSX mode,
// because there is a JSXElement in the last ConditionalExpression:
//
// isA ? "A" : isB ? "B" : isC ? "C" : Unknown;
//
// This type of ConditionalExpression chain is structured like this in the AST:
//
// ConditionalExpression {
// test: ...,
// consequent: ...,
// alternate: ConditionalExpression {
// test: ...,
// consequent: ...,
// alternate: ConditionalExpression {
// test: ...,
// consequent: ...,
// alternate: ...,
// }
// }
// }
//
// We want to traverse over that shape and convert it into a flat structure so
// that we can find if there's a JSXElement somewhere inside.
function getConditionalChainContents(node) {
// Given this code:
//
// // Using a ConditionalExpression as the consequent is uncommon, but should
// // be handled.
// A ? B : C ? D : E ? F ? G : H : I
//
// which has this AST:
//
// ConditionalExpression {
// test: Identifier(A),
// consequent: Identifier(B),
// alternate: ConditionalExpression {
// test: Identifier(C),
// consequent: Identifier(D),
// alternate: ConditionalExpression {
// test: Identifier(E),
// consequent: ConditionalExpression {
// test: Identifier(F),
// consequent: Identifier(G),
// alternate: Identifier(H),
// },
// alternate: Identifier(I),
// }
// }
// }
//
// we should return this Array:
//
// [
// Identifier(A),
// Identifier(B),
// Identifier(C),
// Identifier(D),
// Identifier(E),
// Identifier(F),
// Identifier(G),
// Identifier(H),
// Identifier(I)
// ];
//
// This loses the information about whether each node was the test,
// consequent, or alternate, but we don't care about that here- we are only
// flattening this structure to find if there's any JSXElements inside.
var nonConditionalExpressions = [];
function recurse(node) {
if (node.type === "ConditionalExpression") {
recurse(node.test);
recurse(node.consequent);
recurse(node.alternate);
} else {
nonConditionalExpressions.push(node);
}
}
recurse(node);
return nonConditionalExpressions;
} // Detect an expression node representing `{" "}`
function isJSXWhitespaceExpression(node) {
return node.type === "JSXExpressionContainer" && isLiteral(node.expression) && node.expression.value === " " && !node.expression.comments;
}
function separatorNoWhitespace(isFacebookTranslationTag, child, childNode, nextNode) {
if (isFacebookTranslationTag) {
return "";
}
if (childNode.type === "JSXElement" && !childNode.closingElement || nextNode && nextNode.type === "JSXElement" && !nextNode.closingElement) {
return child.length === 1 ? softline$5 : hardline$8;
}
return softline$5;
}
function separatorWithWhitespace(isFacebookTranslationTag, child, childNode, nextNode) {
if (isFacebookTranslationTag) {
return hardline$8;
}
if (child.length === 1) {
return childNode.type === "JSXElement" && !childNode.closingElement || nextNode && nextNode.type === "JSXElement" && !nextNode.closingElement ? hardline$8 : softline$5;
}
return hardline$8;
} // JSX Children are strange, mostly for two reasons:
// 1. JSX reads newlines into string values, instead of skipping them like JS
// 2. up to one whitespace between elements within a line is significant,
// but not between lines.
//
// Leading, trailing, and lone whitespace all need to
// turn themselves into the rather ugly `{' '}` when breaking.
//
// We print JSX using the `fill` doc primitive.
// This requires that we give it an array of alternating
// content and whitespace elements.
// To ensure this we add dummy `""` content elements as needed.
function printJSXChildren(path, options, print, jsxWhitespace, isFacebookTranslationTag) {
var n = path.getValue();
var children = []; // using `map` instead of `each` because it provides `i`
path.map(function (childPath, i) {
var child = childPath.getValue();
if (isLiteral(child)) {
var text = rawText(child); // Contains a non-whitespace character
if (isMeaningfulJSXText(child)) {
var words = text.split(matchJsxWhitespaceRegex); // Starts with whitespace
if (words[0] === "") {
children.push("");
words.shift();
if (/\n/.test(words[0])) {
var next = n.children[i + 1];
children.push(separatorWithWhitespace(isFacebookTranslationTag, words[1], child, next));
} else {
children.push(jsxWhitespace);
}
words.shift();
}
var endWhitespace; // Ends with whitespace
if (getLast$3(words) === "") {
words.pop();
endWhitespace = words.pop();
} // This was whitespace only without a new line.
if (words.length === 0) {
return;
}
words.forEach(function (word, i) {
if (i % 2 === 1) {
children.push(line$8);
} else {
children.push(word);
}
});
if (endWhitespace !== undefined) {
if (/\n/.test(endWhitespace)) {
var _next = n.children[i + 1];
children.push(separatorWithWhitespace(isFacebookTranslationTag, getLast$3(children), child, _next));
} else {
children.push(jsxWhitespace);
}
} else {
var _next2 = n.children[i + 1];
children.push(separatorNoWhitespace(isFacebookTranslationTag, getLast$3(children), child, _next2));
}
} else if (/\n/.test(text)) {
// Keep (up to one) blank line between tags/expressions/text.
// Note: We don't keep blank lines between text elements.
if (text.match(/\n/g).length > 1) {
children.push("");
children.push(hardline$8);
}
} else {
children.push("");
children.push(jsxWhitespace);
}
} else {
var printedChild = print(childPath);
children.push(printedChild);
var _next3 = n.children[i + 1];
var directlyFollowedByMeaningfulText = _next3 && isMeaningfulJSXText(_next3);
if (directlyFollowedByMeaningfulText) {
var firstWord = rawText(_next3).trim().split(matchJsxWhitespaceRegex)[0];
children.push(separatorNoWhitespace(isFacebookTranslationTag, firstWord, child, _next3));
} else {
children.push(hardline$8);
}
}
}, "children");
return children;
} // JSX expands children from the inside-out, instead of the outside-in.
// This is both to break children before attributes,
// and to ensure that when children break, their parents do as well.
//
// Any element that is written without any newlines and fits on a single line
// is left that way.
// Not only that, any user-written-line containing multiple JSX siblings
// should also be kept on one line if possible,
// so each user-written-line is wrapped in its own group.
//
// Elements that contain newlines or don't fit on a single line (recursively)
// are fully-split, using hardline and shouldBreak: true.
//
// To support that case properly, all leading and trailing spaces
// are stripped from the list of children, and replaced with a single hardline.
function printJSXElement(path, options, print) {
var n = path.getValue();
if (n.type === "JSXElement" && isEmptyJSXElement(n)) {
return concat$11([path.call(print, "openingElement"), path.call(print, "closingElement")]);
}
var openingLines = n.type === "JSXElement" ? path.call(print, "openingElement") : path.call(print, "openingFragment");
var closingLines = n.type === "JSXElement" ? path.call(print, "closingElement") : path.call(print, "closingFragment");
if (n.children.length === 1 && n.children[0].type === "JSXExpressionContainer" && (n.children[0].expression.type === "TemplateLiteral" || n.children[0].expression.type === "TaggedTemplateExpression")) {
return concat$11([openingLines, concat$11(path.map(print, "children")), closingLines]);
} // Convert `{" "}` to text nodes containing a space.
// This makes it easy to turn them into `jsxWhitespace` which
// can then print as either a space or `{" "}` when breaking.
n.children = n.children.map(function (child) {
if (isJSXWhitespaceExpression(child)) {
return {
type: "JSXText",
value: " ",
raw: " "
};
}
return child;
});
var containsTag = n.children.filter(isJSXNode).length > 0;
var containsMultipleExpressions = n.children.filter(function (child) {
return child.type === "JSXExpressionContainer";
}).length > 1;
var containsMultipleAttributes = n.type === "JSXElement" && n.openingElement.attributes.length > 1; // Record any breaks. Should never go from true to false, only false to true.
var forcedBreak = willBreak$1(openingLines) || containsTag || containsMultipleAttributes || containsMultipleExpressions;
var rawJsxWhitespace = options.singleQuote ? "{' '}" : '{" "}';
var jsxWhitespace = ifBreak$6(concat$11([rawJsxWhitespace, softline$5]), " ");
var isFacebookTranslationTag = n.openingElement && n.openingElement.name && n.openingElement.name.name === "fbt";
var children = printJSXChildren(path, options, print, jsxWhitespace, isFacebookTranslationTag);
var containsText = n.children.filter(function (child) {
return isMeaningfulJSXText(child);
}).length > 0; // We can end up we multiple whitespace elements with empty string
// content between them.
// We need to remove empty whitespace and softlines before JSX whitespace
// to get the correct output.
for (var i = children.length - 2; i >= 0; i--) {
var isPairOfEmptyStrings = children[i] === "" && children[i + 1] === "";
var isPairOfHardlines = children[i] === hardline$8 && children[i + 1] === "" && children[i + 2] === hardline$8;
var isLineFollowedByJSXWhitespace = (children[i] === softline$5 || children[i] === hardline$8) && children[i + 1] === "" && children[i + 2] === jsxWhitespace;
var isJSXWhitespaceFollowedByLine = children[i] === jsxWhitespace && children[i + 1] === "" && (children[i + 2] === softline$5 || children[i + 2] === hardline$8);
var isDoubleJSXWhitespace = children[i] === jsxWhitespace && children[i + 1] === "" && children[i + 2] === jsxWhitespace;
var isPairOfHardOrSoftLines = children[i] === softline$5 && children[i + 1] === "" && children[i + 2] === hardline$8 || children[i] === hardline$8 && children[i + 1] === "" && children[i + 2] === softline$5;
if (isPairOfHardlines && containsText || isPairOfEmptyStrings || isLineFollowedByJSXWhitespace || isDoubleJSXWhitespace || isPairOfHardOrSoftLines) {
children.splice(i, 2);
} else if (isJSXWhitespaceFollowedByLine) {
children.splice(i + 1, 2);
}
} // Trim trailing lines (or empty strings)
while (children.length && (isLineNext$1(getLast$3(children)) || isEmpty$1(getLast$3(children)))) {
children.pop();
} // Trim leading lines (or empty strings)
while (children.length && (isLineNext$1(children[0]) || isEmpty$1(children[0])) && (isLineNext$1(children[1]) || isEmpty$1(children[1]))) {
children.shift();
children.shift();
} // Tweak how we format children if outputting this element over multiple lines.
// Also detect whether we will force this element to output over multiple lines.
var multilineChildren = [];
children.forEach(function (child, i) {
// There are a number of situations where we need to ensure we display
// whitespace as `{" "}` when outputting this element over multiple lines.
if (child === jsxWhitespace) {
if (i === 1 && children[i - 1] === "") {
if (children.length === 2) {
// Solitary whitespace
multilineChildren.push(rawJsxWhitespace);
return;
} // Leading whitespace
multilineChildren.push(concat$11([rawJsxWhitespace, hardline$8]));
return;
} else if (i === children.length - 1) {
// Trailing whitespace
multilineChildren.push(rawJsxWhitespace);
return;
} else if (children[i - 1] === "" && children[i - 2] === hardline$8) {
// Whitespace after line break
multilineChildren.push(rawJsxWhitespace);
return;
}
}
multilineChildren.push(child);
if (willBreak$1(child)) {
forcedBreak = true;
}
}); // If there is text we use `fill` to fit as much onto each line as possible.
// When there is no text (just tags and expressions) we use `group`
// to output each on a separate line.
var content = containsText ? fill$4(multilineChildren) : group$10(concat$11(multilineChildren), {
shouldBreak: true
});
var multiLineElem = group$10(concat$11([openingLines, indent$6(concat$11([hardline$8, content])), hardline$8, closingLines]));
if (forcedBreak) {
return multiLineElem;
}
return conditionalGroup$1([group$10(concat$11([openingLines, concat$11(children), closingLines])), multiLineElem]);
}
function maybeWrapJSXElementInParens(path, elem) {
var parent = path.getParentNode();
if (!parent) {
return elem;
}
var NO_WRAP_PARENTS = {
ArrayExpression: true,
JSXAttribute: true,
JSXElement: true,
JSXExpressionContainer: true,
JSXFragment: true,
ExpressionStatement: true,
CallExpression: true,
OptionalCallExpression: true,
ConditionalExpression: true,
JsExpressionRoot: true
};
if (NO_WRAP_PARENTS[parent.type]) {
return elem;
}
var shouldBreak = matchAncestorTypes$1(path, ["ArrowFunctionExpression", "CallExpression", "JSXExpressionContainer"]);
return group$10(concat$11([ifBreak$6("("), indent$6(concat$11([softline$5, elem])), softline$5, ifBreak$6(")")]), {
shouldBreak: shouldBreak
});
}
function isBinaryish(node) {
return node.type === "BinaryExpression" || node.type === "LogicalExpression" || node.type === "NGPipeExpression";
}
function isMemberish(node) {
return node.type === "MemberExpression" || node.type === "OptionalMemberExpression" || node.type === "BindExpression" && node.object;
}
function shouldInlineLogicalExpression(node) {
if (node.type !== "LogicalExpression") {
return false;
}
if (node.right.type === "ObjectExpression" && node.right.properties.length !== 0) {
return true;
}
if (node.right.type === "ArrayExpression" && node.right.elements.length !== 0) {
return true;
}
if (isJSXNode(node.right)) {
return true;
}
return false;
} // For binary expressions to be consistent, we need to group
// subsequent operators with the same precedence level under a single
// group. Otherwise they will be nested such that some of them break
// onto new lines but not all. Operators with the same precedence
// level should either all break or not. Because we group them by
// precedence level and the AST is structured based on precedence
// level, things are naturally broken up correctly, i.e. `&&` is
// broken before `+`.
function printBinaryishExpressions(path, print, options, isNested, isInsideParenthesis) {
var parts = [];
var node = path.getValue(); // We treat BinaryExpression and LogicalExpression nodes the same.
if (isBinaryish(node)) {
// Put all operators with the same precedence level in the same
// group. The reason we only need to do this with the `left`
// expression is because given an expression like `1 + 2 - 3`, it
// is always parsed like `((1 + 2) - 3)`, meaning the `left` side
// is where the rest of the expression will exist. Binary
// expressions on the right side mean they have a difference
// precedence level and should be treated as a separate group, so
// print them normally. (This doesn't hold for the `**` operator,
// which is unique in that it is right-associative.)
if (shouldFlatten$1(node.operator, node.left.operator)) {
// Flatten them out by recursively calling this function.
parts = parts.concat(path.call(function (left) {
return printBinaryishExpressions(left, print, options,
/* isNested */
true, isInsideParenthesis);
}, "left"));
} else {
parts.push(path.call(print, "left"));
}
var shouldInline = shouldInlineLogicalExpression(node);
var lineBeforeOperator = (node.operator === "|>" || node.type === "NGPipeExpression" || node.operator === "|" && options.parser === "__vue_expression") && !hasLeadingOwnLineComment(options.originalText, node.right, options);
var operator = node.type === "NGPipeExpression" ? "|" : node.operator;
var rightSuffix = node.type === "NGPipeExpression" && node.arguments.length !== 0 ? group$10(indent$6(concat$11([softline$5, ": ", join$7(concat$11([softline$5, ":", ifBreak$6(" ")]), path.map(print, "arguments").map(function (arg) {
return align$1(2, group$10(arg));
}))]))) : "";
var right = shouldInline ? concat$11([operator, " ", path.call(print, "right"), rightSuffix]) : concat$11([lineBeforeOperator ? softline$5 : "", operator, lineBeforeOperator ? " " : line$8, path.call(print, "right"), rightSuffix]); // If there's only a single binary expression, we want to create a group
// in order to avoid having a small right part like -1 be on its own line.
var parent = path.getParentNode();
var shouldGroup = !(isInsideParenthesis && node.type === "LogicalExpression") && parent.type !== node.type && node.left.type !== node.type && node.right.type !== node.type;
parts.push(" ", shouldGroup ? group$10(right) : right); // The root comments are already printed, but we need to manually print
// the other ones since we don't call the normal print on BinaryExpression,
// only for the left and right parts
if (isNested && node.comments) {
parts = comments.printComments(path, function () {
return concat$11(parts);
}, options);
}
} else {
// Our stopping case. Simply print the node normally.
parts.push(path.call(print));
}
return parts;
}
function printAssignmentRight(leftNode, rightNode, printedRight, options) {
if (hasLeadingOwnLineComment(options.originalText, rightNode, options)) {
return indent$6(concat$11([hardline$8, printedRight]));
}
var canBreak = isBinaryish(rightNode) && !shouldInlineLogicalExpression(rightNode) || rightNode.type === "ConditionalExpression" && isBinaryish(rightNode.test) && !shouldInlineLogicalExpression(rightNode.test) || rightNode.type === "StringLiteralTypeAnnotation" || rightNode.type === "ClassExpression" && rightNode.decorators && rightNode.decorators.length || (leftNode.type === "Identifier" || isStringLiteral(leftNode) || leftNode.type === "MemberExpression") && (isStringLiteral(rightNode) || isMemberExpressionChain(rightNode)) && // do not put values on a separate line from the key in json
options.parser !== "json" && options.parser !== "json5" || rightNode.type === "SequenceExpression";
if (canBreak) {
return group$10(indent$6(concat$11([line$8, printedRight])));
}
return concat$11([" ", printedRight]);
}
function printAssignment(leftNode, printedLeft, operator, rightNode, printedRight, options) {
if (!rightNode) {
return printedLeft;
}
var printed = printAssignmentRight(leftNode, rightNode, printedRight, options);
return group$10(concat$11([printedLeft, operator, printed]));
}
function adjustClause(node, clause, forceSpace) {
if (node.type === "EmptyStatement") {
return ";";
}
if (node.type === "BlockStatement" || forceSpace) {
return concat$11([" ", clause]);
}
return indent$6(concat$11([line$8, clause]));
}
function nodeStr(node, options, isFlowOrTypeScriptDirectiveLiteral) {
var raw = rawText(node);
var isDirectiveLiteral = isFlowOrTypeScriptDirectiveLiteral || node.type === "DirectiveLiteral";
return printString$2(raw, options, isDirectiveLiteral);
}
function printRegex(node) {
var flags = node.flags.split("").sort().join("");
return "/".concat(node.pattern, "/").concat(flags);
}
function isLastStatement(path) {
var parent = path.getParentNode();
if (!parent) {
return true;
}
var node = path.getValue();
var body = (parent.body || parent.consequent).filter(function (stmt) {
return stmt.type !== "EmptyStatement";
});
return body && body[body.length - 1] === node;
}
function hasLeadingComment(node) {
return node.comments && node.comments.some(function (comment) {
return comment.leading;
});
}
function hasTrailingComment(node) {
return node.comments && node.comments.some(function (comment) {
return comment.trailing;
});
}
function hasLeadingOwnLineComment(text, node, options) {
if (isJSXNode(node)) {
return hasNodeIgnoreComment$1(node);
}
var res = node.comments && node.comments.some(function (comment) {
return comment.leading && hasNewline$3(text, options.locEnd(comment));
});
return res;
}
function isFlowAnnotationComment(text, typeAnnotation, options) {
var start = options.locStart(typeAnnotation);
var end = skipWhitespace$1(text, options.locEnd(typeAnnotation));
return text.substr(start, 2) === "/*" && text.substr(end, 2) === "*/";
}
function exprNeedsASIProtection(path, options) {
var node = path.getValue();
var maybeASIProblem = needsParens_1(path, options) || node.type === "ParenthesizedExpression" || node.type === "TypeCastExpression" || node.type === "ArrowFunctionExpression" && !shouldPrintParamsWithoutParens(path, options) || node.type === "ArrayExpression" || node.type === "ArrayPattern" || node.type === "UnaryExpression" && node.prefix && (node.operator === "+" || node.operator === "-") || node.type === "TemplateLiteral" || node.type === "TemplateElement" || isJSXNode(node) || node.type === "BindExpression" && !node.object || node.type === "RegExpLiteral" || node.type === "Literal" && node.pattern || node.type === "Literal" && node.regex;
if (maybeASIProblem) {
return true;
}
if (!hasNakedLeftSide(node)) {
return false;
}
return path.call.apply(path, [function (childPath) {
return exprNeedsASIProtection(childPath, options);
}].concat(getLeftSidePathName(path, node)));
}
function stmtNeedsASIProtection(path, options) {
var node = path.getNode();
if (node.type !== "ExpressionStatement") {
return false;
}
return path.call(function (childPath) {
return exprNeedsASIProtection(childPath, options);
}, "expression");
}
function classPropMayCauseASIProblems(path) {
var node = path.getNode();
if (node.type !== "ClassProperty") {
return false;
}
var name = node.key && node.key.name; // this isn't actually possible yet with most parsers available today
// so isn't properly tested yet.
if ((name === "static" || name === "get" || name === "set") && !node.value && !node.typeAnnotation) {
return true;
}
}
function classChildNeedsASIProtection(node) {
if (!node) {
return;
}
if (node.static || node.accessibility // TypeScript
) {
return false;
}
if (!node.computed) {
var name = node.key && node.key.name;
if (name === "in" || name === "instanceof") {
return true;
}
}
switch (node.type) {
case "ClassProperty":
case "TSAbstractClassProperty":
return node.computed;
case "MethodDefinition": // Flow
case "TSAbstractMethodDefinition": // TypeScript
case "ClassMethod":
case "ClassPrivateMethod":
{
// Babel
var isAsync = node.value ? node.value.async : node.async;
var isGenerator = node.value ? node.value.generator : node.generator;
if (isAsync || node.kind === "get" || node.kind === "set") {
return false;
}
if (node.computed || isGenerator) {
return true;
}
return false;
}
default:
/* istanbul ignore next */
return false;
}
} // This recurses the return argument, looking for the first token
// (the leftmost leaf node) and, if it (or its parents) has any
// leadingComments, returns true (so it can be wrapped in parens).
function returnArgumentHasLeadingComment(options, argument) {
if (hasLeadingOwnLineComment(options.originalText, argument, options)) {
return true;
}
if (hasNakedLeftSide(argument)) {
var leftMost = argument;
var newLeftMost;
while (newLeftMost = getLeftSide(leftMost)) {
leftMost = newLeftMost;
if (hasLeadingOwnLineComment(options.originalText, leftMost, options)) {
return true;
}
}
}
return false;
}
function isMemberExpressionChain(node) {
if (node.type !== "MemberExpression" && node.type !== "OptionalMemberExpression") {
return false;
}
if (node.object.type === "Identifier") {
return true;
}
return isMemberExpressionChain(node.object);
} // Hack to differentiate between the following two which have the same ast
// type T = { method: () => void };
// type T = { method(): void };
function isObjectTypePropertyAFunction(node, options) {
return (node.type === "ObjectTypeProperty" || node.type === "ObjectTypeInternalSlot") && node.value.type === "FunctionTypeAnnotation" && !node.static && !isFunctionNotation(node, options);
} // TODO: This is a bad hack and we need a better way to distinguish between
// arrow functions and otherwise
function isFunctionNotation(node, options) {
return isGetterOrSetter(node) || sameLocStart(node, node.value, options);
}
function isGetterOrSetter(node) {
return node.kind === "get" || node.kind === "set";
}
function sameLocStart(nodeA, nodeB, options) {
return options.locStart(nodeA) === options.locStart(nodeB);
} // Hack to differentiate between the following two which have the same ast
// declare function f(a): void;
// var f: (a) => void;
function isTypeAnnotationAFunction(node, options) {
return (node.type === "TypeAnnotation" || node.type === "TSTypeAnnotation") && node.typeAnnotation.type === "FunctionTypeAnnotation" && !node.static && !sameLocStart(node, node.typeAnnotation, options);
}
function isNodeStartingWithDeclare(node, options) {
if (!(options.parser === "flow" || options.parser === "typescript")) {
return false;
}
return options.originalText.slice(0, options.locStart(node)).match(/declare[ \t]*$/) || options.originalText.slice(node.range[0], node.range[1]).startsWith("declare ");
}
function shouldHugType(node) {
if (isSimpleFlowType(node) || isObjectType(node)) {
return true;
}
if (node.type === "UnionTypeAnnotation" || node.type === "TSUnionType") {
var voidCount = node.types.filter(function (n) {
return n.type === "VoidTypeAnnotation" || n.type === "TSVoidKeyword" || n.type === "NullLiteralTypeAnnotation" || n.type === "TSNullKeyword";
}).length;
var objectCount = node.types.filter(function (n) {
return n.type === "ObjectTypeAnnotation" || n.type === "TSTypeLiteral" || // This is a bit aggressive but captures Array<{x}>
n.type === "GenericTypeAnnotation" || n.type === "TSTypeReference";
}).length;
if (node.types.length - 1 === voidCount && objectCount > 0) {
return true;
}
}
return false;
}
function shouldHugArguments(fun) {
return fun && fun.params && fun.params.length === 1 && !fun.params[0].comments && (fun.params[0].type === "ObjectPattern" || fun.params[0].type === "ArrayPattern" || fun.params[0].type === "Identifier" && fun.params[0].typeAnnotation && (fun.params[0].typeAnnotation.type === "TypeAnnotation" || fun.params[0].typeAnnotation.type === "TSTypeAnnotation") && isObjectType(fun.params[0].typeAnnotation.typeAnnotation) || fun.params[0].type === "FunctionTypeParam" && isObjectType(fun.params[0].typeAnnotation) || fun.params[0].type === "AssignmentPattern" && (fun.params[0].left.type === "ObjectPattern" || fun.params[0].left.type === "ArrayPattern") && (fun.params[0].right.type === "Identifier" || fun.params[0].right.type === "ObjectExpression" && fun.params[0].right.properties.length === 0 || fun.params[0].right.type === "ArrayExpression" && fun.params[0].right.elements.length === 0)) && !fun.rest;
}
function templateLiteralHasNewLines(template) {
return template.quasis.some(function (quasi) {
return quasi.value.raw.includes("\n");
});
}
function isTemplateOnItsOwnLine(n, text, options) {
return (n.type === "TemplateLiteral" && templateLiteralHasNewLines(n) || n.type === "TaggedTemplateExpression" && templateLiteralHasNewLines(n.quasi)) && !hasNewline$3(text, options.locStart(n), {
backwards: true
});
}
function printArrayItems(path, options, printPath, print) {
var printedElements = [];
var separatorParts = [];
path.each(function (childPath) {
printedElements.push(concat$11(separatorParts));
printedElements.push(group$10(print(childPath)));
separatorParts = [",", line$8];
if (childPath.getValue() && isNextLineEmpty$4(options.originalText, childPath.getValue(), options)) {
separatorParts.push(softline$5);
}
}, printPath);
return concat$11(printedElements);
}
function hasDanglingComments(node) {
return node.comments && node.comments.some(function (comment) {
return !comment.leading && !comment.trailing;
});
}
function needsHardlineAfterDanglingComment(node) {
if (!node.comments) {
return false;
}
var lastDanglingComment = getLast$3(node.comments.filter(function (comment) {
return !comment.leading && !comment.trailing;
}));
return lastDanglingComment && !comments$3.isBlockComment(lastDanglingComment);
}
function isLiteral(node) {
return node.type === "BooleanLiteral" || node.type === "DirectiveLiteral" || node.type === "Literal" || node.type === "NullLiteral" || node.type === "NumericLiteral" || node.type === "RegExpLiteral" || node.type === "StringLiteral" || node.type === "TemplateLiteral" || node.type === "TSTypeLiteral" || node.type === "JSXText";
}
function isStringPropSafeToCoerceToIdentifier(node, options) {
return isStringLiteral(node.key) && isIdentifierName(node.key.value) && options.parser !== "json" && !(options.parser === "typescript" && node.type === "ClassProperty");
}
function isNumericLiteral(node) {
return node.type === "NumericLiteral" || node.type === "Literal" && typeof node.value === "number";
}
function isStringLiteral(node) {
return node.type === "StringLiteral" || node.type === "Literal" && typeof node.value === "string";
}
function isObjectType(n) {
return n.type === "ObjectTypeAnnotation" || n.type === "TSTypeLiteral";
}
var unitTestRe = /^(skip|[fx]?(it|describe|test))$/; // eg; `describe("some string", (done) => {})`
function isTestCall(n, parent) {
if (n.type !== "CallExpression") {
return false;
}
if (n.arguments.length === 1) {
if (isAngularTestWrapper(n) && parent && isTestCall(parent)) {
return isFunctionOrArrowExpression(n.arguments[0]);
}
if (isUnitTestSetUp(n)) {
return isAngularTestWrapper(n.arguments[0]);
}
} else if (n.arguments.length === 2 || n.arguments.length === 3) {
if ((n.callee.type === "Identifier" && unitTestRe.test(n.callee.name) || isSkipOrOnlyBlock(n)) && (isTemplateLiteral(n.arguments[0]) || isStringLiteral(n.arguments[0]))) {
// it("name", () => { ... }, 2500)
if (n.arguments[2] && !isNumericLiteral(n.arguments[2])) {
return false;
}
return (n.arguments.length === 2 ? isFunctionOrArrowExpression(n.arguments[1]) : isFunctionOrArrowExpressionWithBody(n.arguments[1]) && n.arguments[1].params.length <= 1) || isAngularTestWrapper(n.arguments[1]);
}
}
return false;
}
function isSkipOrOnlyBlock(node) {
return (node.callee.type === "MemberExpression" || node.callee.type === "OptionalMemberExpression") && node.callee.object.type === "Identifier" && node.callee.property.type === "Identifier" && unitTestRe.test(node.callee.object.name) && (node.callee.property.name === "only" || node.callee.property.name === "skip");
}
function isTemplateLiteral(node) {
return node.type === "TemplateLiteral";
} // `inject` is used in AngularJS 1.x, `async` in Angular 2+
// example: https://docs.angularjs.org/guide/unit-testing#using-beforeall-
function isAngularTestWrapper(node) {
return (node.type === "CallExpression" || node.type === "OptionalCallExpression") && node.callee.type === "Identifier" && (node.callee.name === "async" || node.callee.name === "inject" || node.callee.name === "fakeAsync");
}
function isFunctionOrArrowExpression(node) {
return node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression";
}
function isFunctionOrArrowExpressionWithBody(node) {
return node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression" && node.body.type === "BlockStatement";
}
function isUnitTestSetUp(n) {
var unitTestSetUpRe = /^(before|after)(Each|All)$/;
return n.callee.type === "Identifier" && unitTestSetUpRe.test(n.callee.name) && n.arguments.length === 1;
}
function isTheOnlyJSXElementInMarkdown(options, path) {
if (options.parentParser !== "markdown" && options.parentParser !== "mdx") {
return false;
}
var node = path.getNode();
if (!node.expression || !isJSXNode(node.expression)) {
return false;
}
var parent = path.getParentNode();
return parent.type === "Program" && parent.body.length == 1;
}
function willPrintOwnComments(path
/*, options */
) {
var node = path.getValue();
var parent = path.getParentNode();
return (node && (isJSXNode(node) || hasFlowShorthandAnnotationComment(node) || parent && parent.type === "CallExpression" && (hasFlowAnnotationComment(node.leadingComments) || hasFlowAnnotationComment(node.trailingComments))) || parent && (parent.type === "JSXSpreadAttribute" || parent.type === "JSXSpreadChild" || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType" || (parent.type === "ClassDeclaration" || parent.type === "ClassExpression") && parent.superClass === node)) && !hasIgnoreComment$3(path);
}
function canAttachComment$1(node) {
return node.type && node.type !== "CommentBlock" && node.type !== "CommentLine" && node.type !== "Line" && node.type !== "Block" && node.type !== "EmptyStatement" && node.type !== "TemplateElement" && node.type !== "Import";
}
function printComment$2(commentPath, options) {
var comment = commentPath.getValue();
switch (comment.type) {
case "CommentBlock":
case "Block":
{
if (isIndentableBlockComment(comment)) {
var printed = printIndentableBlockComment(comment); // We need to prevent an edge case of a previous trailing comment
// printed as a `lineSuffix` which causes the comments to be
// interleaved. See https://github.com/prettier/prettier/issues/4412
if (comment.trailing && !hasNewline$3(options.originalText, options.locStart(comment), {
backwards: true
})) {
return concat$11([hardline$8, printed]);
}
return printed;
}
var isInsideFlowComment = options.originalText.substr(options.locEnd(comment) - 3, 3) === "*-/";
return "/*" + comment.value + (isInsideFlowComment ? "*-/" : "*/");
}
case "CommentLine":
case "Line":
// Print shebangs with the proper comment characters
if (options.originalText.slice(options.locStart(comment)).startsWith("#!")) {
return "#!" + comment.value.trimRight();
}
return "//" + comment.value.trimRight();
default:
throw new Error("Not a comment: " + JSON.stringify(comment));
}
}
function isIndentableBlockComment(comment) {
// If the comment has multiple lines and every line starts with a star
// we can fix the indentation of each line. The stars in the `/*` and
// `*/` delimiters are not included in the comment value, so add them
// back first.
var lines = "*".concat(comment.value, "*").split("\n");
return lines.length > 1 && lines.every(function (line) {
return line.trim()[0] === "*";
});
}
function printIndentableBlockComment(comment) {
var lines = comment.value.split("\n");
return concat$11(["/*", join$7(hardline$8, lines.map(function (line, index) {
return index === 0 ? line.trimRight() : " " + (index < lines.length - 1 ? line.trim() : line.trimLeft());
})), "*/"]);
}
function rawText(node) {
return node.extra ? node.extra.raw : node.raw;
}
function identity$1(x) {
return x;
}
var printerEstree = {
preprocess: preprocess_1$2,
print: genericPrint$3,
embed: embed_1$2,
insertPragma: insertPragma$7,
massageAstNode: clean_1$2,
hasPrettierIgnore: hasPrettierIgnore$2,
willPrintOwnComments: willPrintOwnComments,
canAttachComment: canAttachComment$1,
printComment: printComment$2,
isBlockComment: comments$3.isBlockComment,
handleComments: {
ownLine: comments$3.handleOwnLineComment,
endOfLine: comments$3.handleEndOfLineComment,
remaining: comments$3.handleRemainingComment
}
};
var _require$$0$builders$7 = doc.builders;
var concat$14 = _require$$0$builders$7.concat;
var hardline$10 = _require$$0$builders$7.hardline;
var indent$8 = _require$$0$builders$7.indent;
var join$10 = _require$$0$builders$7.join;
function genericPrint$4(path, options, print) {
var node = path.getValue();
switch (node.type) {
case "JsonRoot":
return concat$14([path.call(print, "node"), hardline$10]);
case "ArrayExpression":
return node.elements.length === 0 ? "[]" : concat$14(["[", indent$8(concat$14([hardline$10, join$10(concat$14([",", hardline$10]), path.map(print, "elements"))])), hardline$10, "]"]);
case "ObjectExpression":
return node.properties.length === 0 ? "{}" : concat$14(["{", indent$8(concat$14([hardline$10, join$10(concat$14([",", hardline$10]), path.map(print, "properties"))])), hardline$10, "}"]);
case "ObjectProperty":
return concat$14([path.call(print, "key"), ": ", path.call(print, "value")]);
case "UnaryExpression":
return concat$14([node.operator === "+" ? "" : node.operator, path.call(print, "argument")]);
case "NullLiteral":
return "null";
case "BooleanLiteral":
return node.value ? "true" : "false";
case "StringLiteral":
case "NumericLiteral":
return JSON.stringify(node.value);
case "Identifier":
return JSON.stringify(node.name);
default:
/* istanbul ignore next */
throw new Error("unknown type: " + JSON.stringify(node.type));
}
}
function clean$9(node, newNode
/*, parent*/
) {
delete newNode.start;
delete newNode.end;
delete newNode.extra;
delete newNode.loc;
delete newNode.comments;
if (node.type === "Identifier") {
return {
type: "StringLiteral",
value: node.name
};
}
if (node.type === "UnaryExpression" && node.operator === "+") {
return newNode.argument;
}
}
var printerEstreeJson = {
preprocess: preprocess_1$2,
print: genericPrint$4,
massageAstNode: clean$9
};
var CATEGORY_JAVASCRIPT = "JavaScript"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
var options$12 = {
arrowParens: {
since: "1.9.0",
category: CATEGORY_JAVASCRIPT,
type: "choice",
default: "avoid",
description: "Include parentheses around a sole arrow function parameter.",
choices: [{
value: "avoid",
description: "Omit parens when possible. Example: `x => x`"
}, {
value: "always",
description: "Always include parens. Example: `(x) => x`"
}]
},
bracketSpacing: commonOptions.bracketSpacing,
jsxBracketSameLine: {
since: "0.17.0",
category: CATEGORY_JAVASCRIPT,
type: "boolean",
default: false,
description: "Put > on the last line instead of at a new line."
},
semi: {
since: "1.0.0",
category: CATEGORY_JAVASCRIPT,
type: "boolean",
default: true,
description: "Print semicolons.",
oppositeDescription: "Do not print semicolons, except at the beginning of lines which may need them."
},
singleQuote: commonOptions.singleQuote,
jsxSingleQuote: {
since: "1.15.0",
category: CATEGORY_JAVASCRIPT,
type: "boolean",
default: false,
description: "Use single quotes in JSX."
},
quoteProps: {
since: "1.17.0",
category: CATEGORY_JAVASCRIPT,
type: "choice",
default: "as-needed",
description: "Change when properties in objects are quoted.",
choices: [{
value: "as-needed",
description: "Only add quotes around object properties where required."
}, {
value: "consistent",
description: "If at least one property in an object requires quotes, quote all properties."
}, {
value: "preserve",
description: "Respect the input use of quotes in object properties."
}]
},
trailingComma: {
since: "0.0.0",
category: CATEGORY_JAVASCRIPT,
type: "choice",
default: [{
since: "0.0.0",
value: false
}, {
since: "0.19.0",
value: "none"
}],
description: "Print trailing commas wherever possible when multi-line.",
choices: [{
value: "none",
description: "No trailing commas."
}, {
value: "es5",
description: "Trailing commas where valid in ES5 (objects, arrays, etc.)"
}, {
value: "all",
description: "Trailing commas wherever possible (including function arguments)."
}, {
value: true,
deprecated: "0.19.0",
redirect: "es5"
}, {
value: false,
deprecated: "0.19.0",
redirect: "none"
}]
}
};
var name$9 = "JavaScript";
var type$8 = "programming";
var tmScope$8 = "source.js";
var aceMode$8 = "javascript";
var codemirrorMode$4 = "javascript";
var codemirrorMimeType$4 = "text/javascript";
var color$3 = "#f1e05a";
var aliases$2 = ["js", "node"];
var extensions$8 = [".js", "._js", ".bones", ".es", ".es6", ".frag", ".gs", ".jake", ".jsb", ".jscad", ".jsfl", ".jsm", ".jss", ".mjs", ".njs", ".pac", ".sjs", ".ssjs", ".xsjs", ".xsjslib"];
var filenames = ["Jakefile"];
var interpreters = ["node"];
var languageId$8 = 183;
var javascript = {
name: name$9,
type: type$8,
tmScope: tmScope$8,
aceMode: aceMode$8,
codemirrorMode: codemirrorMode$4,
codemirrorMimeType: codemirrorMimeType$4,
color: color$3,
aliases: aliases$2,
extensions: extensions$8,
filenames: filenames,
interpreters: interpreters,
languageId: languageId$8
};
var javascript$1 = Object.freeze({
name: name$9,
type: type$8,
tmScope: tmScope$8,
aceMode: aceMode$8,
codemirrorMode: codemirrorMode$4,
codemirrorMimeType: codemirrorMimeType$4,
color: color$3,
aliases: aliases$2,
extensions: extensions$8,
filenames: filenames,
interpreters: interpreters,
languageId: languageId$8,
default: javascript
});
var name$10 = "JSX";
var type$9 = "programming";
var group$12 = "JavaScript";
var extensions$9 = [".jsx"];
var tmScope$9 = "source.js.jsx";
var aceMode$9 = "javascript";
var codemirrorMode$5 = "jsx";
var codemirrorMimeType$5 = "text/jsx";
var languageId$9 = 178;
var jsx = {
name: name$10,
type: type$9,
group: group$12,
extensions: extensions$9,
tmScope: tmScope$9,
aceMode: aceMode$9,
codemirrorMode: codemirrorMode$5,
codemirrorMimeType: codemirrorMimeType$5,
languageId: languageId$9
};
var jsx$1 = Object.freeze({
name: name$10,
type: type$9,
group: group$12,
extensions: extensions$9,
tmScope: tmScope$9,
aceMode: aceMode$9,
codemirrorMode: codemirrorMode$5,
codemirrorMimeType: codemirrorMimeType$5,
languageId: languageId$9,
default: jsx
});
var name$11 = "TypeScript";
var type$10 = "programming";
var color$4 = "#2b7489";
var aliases$3 = ["ts"];
var extensions$10 = [".ts", ".tsx"];
var tmScope$10 = "source.ts";
var aceMode$10 = "typescript";
var codemirrorMode$6 = "javascript";
var codemirrorMimeType$6 = "application/typescript";
var languageId$10 = 378;
var typescript = {
name: name$11,
type: type$10,
color: color$4,
aliases: aliases$3,
extensions: extensions$10,
tmScope: tmScope$10,
aceMode: aceMode$10,
codemirrorMode: codemirrorMode$6,
codemirrorMimeType: codemirrorMimeType$6,
languageId: languageId$10
};
var typescript$1 = Object.freeze({
name: name$11,
type: type$10,
color: color$4,
aliases: aliases$3,
extensions: extensions$10,
tmScope: tmScope$10,
aceMode: aceMode$10,
codemirrorMode: codemirrorMode$6,
codemirrorMimeType: codemirrorMimeType$6,
languageId: languageId$10,
default: typescript
});
var name$12 = "JSON";
var type$11 = "data";
var tmScope$11 = "source.json";
var group$13 = "JavaScript";
var aceMode$11 = "json";
var codemirrorMode$7 = "javascript";
var codemirrorMimeType$7 = "application/json";
var searchable = false;
var extensions$11 = [".json", ".avsc", ".geojson", ".gltf", ".JSON-tmLanguage", ".jsonl", ".tfstate", ".tfstate.backup", ".topojson", ".webapp", ".webmanifest"];
var filenames$1 = [".arcconfig", ".htmlhintrc", ".tern-config", ".tern-project", "composer.lock", "mcmod.info"];
var languageId$11 = 174;
var json$5 = {
name: name$12,
type: type$11,
tmScope: tmScope$11,
group: group$13,
aceMode: aceMode$11,
codemirrorMode: codemirrorMode$7,
codemirrorMimeType: codemirrorMimeType$7,
searchable: searchable,
extensions: extensions$11,
filenames: filenames$1,
languageId: languageId$11
};
var json$6 = Object.freeze({
name: name$12,
type: type$11,
tmScope: tmScope$11,
group: group$13,
aceMode: aceMode$11,
codemirrorMode: codemirrorMode$7,
codemirrorMimeType: codemirrorMimeType$7,
searchable: searchable,
extensions: extensions$11,
filenames: filenames$1,
languageId: languageId$11,
default: json$5
});
var name$13 = "JSON with Comments";
var type$12 = "data";
var group$14 = "JSON";
var tmScope$12 = "source.js";
var aceMode$12 = "javascript";
var codemirrorMode$8 = "javascript";
var codemirrorMimeType$8 = "text/javascript";
var aliases$4 = ["jsonc"];
var extensions$12 = [".sublime-build", ".sublime-commands", ".sublime-completions", ".sublime-keymap", ".sublime-macro", ".sublime-menu", ".sublime-mousemap", ".sublime-project", ".sublime-settings", ".sublime-theme", ".sublime-workspace", ".sublime_metrics", ".sublime_session"];
var filenames$2 = [".babelrc", ".eslintrc.json", ".jscsrc", ".jshintrc", ".jslintrc", "tsconfig.json"];
var languageId$12 = 423;
var jsonWithComments = {
name: name$13,
type: type$12,
group: group$14,
tmScope: tmScope$12,
aceMode: aceMode$12,
codemirrorMode: codemirrorMode$8,
codemirrorMimeType: codemirrorMimeType$8,
aliases: aliases$4,
extensions: extensions$12,
filenames: filenames$2,
languageId: languageId$12
};
var jsonWithComments$1 = Object.freeze({
name: name$13,
type: type$12,
group: group$14,
tmScope: tmScope$12,
aceMode: aceMode$12,
codemirrorMode: codemirrorMode$8,
codemirrorMimeType: codemirrorMimeType$8,
aliases: aliases$4,
extensions: extensions$12,
filenames: filenames$2,
languageId: languageId$12,
default: jsonWithComments
});
var name$14 = "JSON5";
var type$13 = "data";
var extensions$13 = [".json5"];
var tmScope$13 = "source.js";
var aceMode$13 = "javascript";
var codemirrorMode$9 = "javascript";
var codemirrorMimeType$9 = "application/json";
var languageId$13 = 175;
var json5 = {
name: name$14,
type: type$13,
extensions: extensions$13,
tmScope: tmScope$13,
aceMode: aceMode$13,
codemirrorMode: codemirrorMode$9,
codemirrorMimeType: codemirrorMimeType$9,
languageId: languageId$13
};
var json5$1 = Object.freeze({
name: name$14,
type: type$13,
extensions: extensions$13,
tmScope: tmScope$13,
aceMode: aceMode$13,
codemirrorMode: codemirrorMode$9,
codemirrorMimeType: codemirrorMimeType$9,
languageId: languageId$13,
default: json5
});
var require$$0$24 = ( javascript$1 && javascript ) || javascript$1;
var require$$1$10 = ( jsx$1 && jsx ) || jsx$1;
var require$$2$10 = ( typescript$1 && typescript ) || typescript$1;
var require$$3$7 = ( json$6 && json$5 ) || json$6;
var require$$4$4 = ( jsonWithComments$1 && jsonWithComments ) || jsonWithComments$1;
var require$$5$2 = ( json5$1 && json5 ) || json5$1;
var languages$4 = [createLanguage(require$$0$24, {
override: {
since: "0.0.0",
parsers: ["babel", "flow"],
vscodeLanguageIds: ["javascript"]
},
extend: {
interpreters: ["nodejs"]
}
}), createLanguage(require$$0$24, {
override: {
name: "Flow",
since: "0.0.0",
parsers: ["babel", "flow"],
vscodeLanguageIds: ["javascript"],
aliases: [],
filenames: [],
extensions: [".js.flow"]
}
}), createLanguage(require$$1$10, {
override: {
since: "0.0.0",
parsers: ["babel", "flow"],
vscodeLanguageIds: ["javascriptreact"]
}
}), createLanguage(require$$2$10, {
override: {
since: "1.4.0",
parsers: ["typescript"],
vscodeLanguageIds: ["typescript", "typescriptreact"]
}
}), createLanguage(require$$3$7, {
override: {
name: "JSON.stringify",
since: "1.13.0",
parsers: ["json-stringify"],
vscodeLanguageIds: ["json"],
extensions: [],
// .json file defaults to json instead of json-stringify
filenames: ["package.json", "package-lock.json", "composer.json"]
}
}), createLanguage(require$$3$7, {
override: {
since: "1.5.0",
parsers: ["json"],
vscodeLanguageIds: ["json"]
},
extend: {
filenames: [".prettierrc"]
}
}), createLanguage(require$$4$4, {
override: {
since: "1.5.0",
parsers: ["json"],
vscodeLanguageIds: ["jsonc"]
},
extend: {
filenames: [".eslintrc"]
}
}), createLanguage(require$$5$2, {
override: {
since: "1.13.0",
parsers: ["json5"],
vscodeLanguageIds: ["json5"]
}
})];
var printers$4 = {
estree: printerEstree,
"estree-json": printerEstreeJson
};
var languageJs = {
languages: languages$4,
options: options$12,
printers: printers$4
};
var json$9 = {"cjkPattern":"[\\u02ea-\\u02eb\\u1100-\\u11ff\\u2e80-\\u2e99\\u2e9b-\\u2ef3\\u2f00-\\u2fd5\\u3000-\\u303f\\u3041-\\u3096\\u3099-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312e\\u3131-\\u318e\\u3190-\\u3191\\u3196-\\u31ba\\u31c0-\\u31e3\\u31f0-\\u321e\\u322a-\\u3247\\u3260-\\u327e\\u328a-\\u32b0\\u32c0-\\u32cb\\u32d0-\\u32fe\\u3300-\\u3370\\u337b-\\u337f\\u33e0-\\u33fe\\u3400-\\u4db5\\u4e00-\\u9fea\\ua960-\\ua97c\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufe10-\\ufe1f\\ufe30-\\ufe6f\\uff00-\\uffef]|[\\ud840-\\ud868\\ud86a-\\ud86c\\ud86f-\\ud872\\ud874-\\ud879][\\udc00-\\udfff]|\\ud82c[\\udc00-\\udd1e]|\\ud83c[\\ude00\\ude50-\\ude51]|\\ud869[\\udc00-\\uded6\\udf00-\\udfff]|\\ud86d[\\udc00-\\udf34\\udf40-\\udfff]|\\ud86e[\\udc00-\\udc1d\\udc20-\\udfff]|\\ud873[\\udc00-\\udea1\\udeb0-\\udfff]|\\ud87a[\\udc00-\\udfe0]|\\ud87e[\\udc00-\\ude1d]","kPattern":"[\\u1100-\\u11ff\\u3001-\\u3003\\u3008-\\u3011\\u3013-\\u301f\\u302e-\\u3030\\u3037\\u30fb\\u3131-\\u318e\\u3200-\\u321e\\u3260-\\u327e\\ua960-\\ua97c\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\ufe45-\\ufe46\\uff61-\\uff65\\uffa0-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc]","punctuationPattern":"[\\u0021-\\u002f\\u003a-\\u0040\\u005b-\\u0060\\u007b-\\u007e\\u00a1\\u00a7\\u00ab\\u00b6-\\u00b7\\u00bb\\u00bf\\u037e\\u0387\\u055a-\\u055f\\u0589-\\u058a\\u05be\\u05c0\\u05c3\\u05c6\\u05f3-\\u05f4\\u0609-\\u060a\\u060c-\\u060d\\u061b\\u061e-\\u061f\\u066a-\\u066d\\u06d4\\u0700-\\u070d\\u07f7-\\u07f9\\u0830-\\u083e\\u085e\\u0964-\\u0965\\u0970\\u09fd\\u0af0\\u0df4\\u0e4f\\u0e5a-\\u0e5b\\u0f04-\\u0f12\\u0f14\\u0f3a-\\u0f3d\\u0f85\\u0fd0-\\u0fd4\\u0fd9-\\u0fda\\u104a-\\u104f\\u10fb\\u1360-\\u1368\\u1400\\u166d-\\u166e\\u169b-\\u169c\\u16eb-\\u16ed\\u1735-\\u1736\\u17d4-\\u17d6\\u17d8-\\u17da\\u1800-\\u180a\\u1944-\\u1945\\u1a1e-\\u1a1f\\u1aa0-\\u1aa6\\u1aa8-\\u1aad\\u1b5a-\\u1b60\\u1bfc-\\u1bff\\u1c3b-\\u1c3f\\u1c7e-\\u1c7f\\u1cc0-\\u1cc7\\u1cd3\\u2010-\\u2027\\u2030-\\u2043\\u2045-\\u2051\\u2053-\\u205e\\u207d-\\u207e\\u208d-\\u208e\\u2308-\\u230b\\u2329-\\u232a\\u2768-\\u2775\\u27c5-\\u27c6\\u27e6-\\u27ef\\u2983-\\u2998\\u29d8-\\u29db\\u29fc-\\u29fd\\u2cf9-\\u2cfc\\u2cfe-\\u2cff\\u2d70\\u2e00-\\u2e2e\\u2e30-\\u2e49\\u3001-\\u3003\\u3008-\\u3011\\u3014-\\u301f\\u3030\\u303d\\u30a0\\u30fb\\ua4fe-\\ua4ff\\ua60d-\\ua60f\\ua673\\ua67e\\ua6f2-\\ua6f7\\ua874-\\ua877\\ua8ce-\\ua8cf\\ua8f8-\\ua8fa\\ua8fc\\ua92e-\\ua92f\\ua95f\\ua9c1-\\ua9cd\\ua9de-\\ua9df\\uaa5c-\\uaa5f\\uaade-\\uaadf\\uaaf0-\\uaaf1\\uabeb\\ufd3e-\\ufd3f\\ufe10-\\ufe19\\ufe30-\\ufe52\\ufe54-\\ufe61\\ufe63\\ufe68\\ufe6a-\\ufe6b\\uff01-\\uff03\\uff05-\\uff0a\\uff0c-\\uff0f\\uff1a-\\uff1b\\uff1f-\\uff20\\uff3b-\\uff3d\\uff3f\\uff5b\\uff5d\\uff5f-\\uff65]|\\ud800[\\udd00-\\udd02\\udf9f\\udfd0]|\\ud801[\\udd6f]|\\ud802[\\udc57\\udd1f\\udd3f\\ude50-\\ude58\\ude7f\\udef0-\\udef6\\udf39-\\udf3f\\udf99-\\udf9c]|\\ud804[\\udc47-\\udc4d\\udcbb-\\udcbc\\udcbe-\\udcc1\\udd40-\\udd43\\udd74-\\udd75\\uddc5-\\uddc9\\uddcd\\udddb\\udddd-\\udddf\\ude38-\\ude3d\\udea9]|\\ud805[\\udc4b-\\udc4f\\udc5b\\udc5d\\udcc6\\uddc1-\\uddd7\\ude41-\\ude43\\ude60-\\ude6c\\udf3c-\\udf3e]|\\ud806[\\ude3f-\\ude46\\ude9a-\\ude9c\\ude9e-\\udea2]|\\ud807[\\udc41-\\udc45\\udc70-\\udc71]|\\ud809[\\udc70-\\udc74]|\\ud81a[\\ude6e-\\ude6f\\udef5\\udf37-\\udf3b\\udf44]|\\ud82f[\\udc9f]|\\ud836[\\ude87-\\ude8b]|\\ud83a[\\udd5e-\\udd5f]"};
var cjkPattern = json$9.cjkPattern;
var kPattern = json$9.kPattern;
var punctuationPattern$1 = json$9.punctuationPattern;
var getLast$4 = util.getLast;
var INLINE_NODE_TYPES$1 = ["liquidNode", "inlineCode", "emphasis", "strong", "delete", "link", "linkReference", "image", "imageReference", "footnote", "footnoteReference", "sentence", "whitespace", "word", "break", "inlineMath"];
var INLINE_NODE_WRAPPER_TYPES$1 = INLINE_NODE_TYPES$1.concat(["tableCell", "paragraph", "heading"]);
var kRegex = new RegExp(kPattern);
var punctuationRegex = new RegExp(punctuationPattern$1);
/**
* split text into whitespaces and words
* @param {string} text
* @return {Array<{ type: "whitespace", value: " " | "\n" | "" } | { type: "word", value: string }>}
*/
function splitText$1(text, options) {
var KIND_NON_CJK = "non-cjk";
var KIND_CJ_LETTER = "cj-letter";
var KIND_K_LETTER = "k-letter";
var KIND_CJK_PUNCTUATION = "cjk-punctuation";
var nodes = [];
(options.proseWrap === "preserve" ? text : text.replace(new RegExp("(".concat(cjkPattern, ")\n(").concat(cjkPattern, ")"), "g"), "$1$2")).split(/([ \t\n]+)/).forEach(function (token, index, tokens) {
// whitespace
if (index % 2 === 1) {
nodes.push({
type: "whitespace",
value: /\n/.test(token) ? "\n" : " "
});
return;
} // word separated by whitespace
if ((index === 0 || index === tokens.length - 1) && token === "") {
return;
}
token.split(new RegExp("(".concat(cjkPattern, ")"))).forEach(function (innerToken, innerIndex, innerTokens) {
if ((innerIndex === 0 || innerIndex === innerTokens.length - 1) && innerToken === "") {
return;
} // non-CJK word
if (innerIndex % 2 === 0) {
if (innerToken !== "") {
appendNode({
type: "word",
value: innerToken,
kind: KIND_NON_CJK,
hasLeadingPunctuation: punctuationRegex.test(innerToken[0]),
hasTrailingPunctuation: punctuationRegex.test(getLast$4(innerToken))
});
}
return;
} // CJK character
appendNode(punctuationRegex.test(innerToken) ? {
type: "word",
value: innerToken,
kind: KIND_CJK_PUNCTUATION,
hasLeadingPunctuation: true,
hasTrailingPunctuation: true
} : {
type: "word",
value: innerToken,
kind: kRegex.test(innerToken) ? KIND_K_LETTER : KIND_CJ_LETTER,
hasLeadingPunctuation: false,
hasTrailingPunctuation: false
});
});
});
return nodes;
function appendNode(node) {
var lastNode = getLast$4(nodes);
if (lastNode && lastNode.type === "word") {
if (lastNode.kind === KIND_NON_CJK && node.kind === KIND_CJ_LETTER && !lastNode.hasTrailingPunctuation || lastNode.kind === KIND_CJ_LETTER && node.kind === KIND_NON_CJK && !node.hasLeadingPunctuation) {
nodes.push({
type: "whitespace",
value: " "
});
} else if (!isBetween(KIND_NON_CJK, KIND_CJK_PUNCTUATION) && // disallow leading/trailing full-width whitespace
![lastNode.value, node.value].some(function (value) {
return /\u3000/.test(value);
})) {
nodes.push({
type: "whitespace",
value: ""
});
}
}
nodes.push(node);
function isBetween(kind1, kind2) {
return lastNode.kind === kind1 && node.kind === kind2 || lastNode.kind === kind2 && node.kind === kind1;
}
}
}
function getOrderedListItemInfo$1(orderListItem, originalText) {
var _originalText$slice$m = originalText.slice(orderListItem.position.start.offset, orderListItem.position.end.offset).match(/^\s*(\d+)(\.|\))(\s*)/),
_originalText$slice$m2 = _slicedToArray(_originalText$slice$m, 4),
numberText = _originalText$slice$m2[1],
marker = _originalText$slice$m2[2],
leadingSpaces = _originalText$slice$m2[3];
return {
numberText: numberText,
marker: marker,
leadingSpaces: leadingSpaces
};
} // workaround for https://github.com/remarkjs/remark/issues/351
// leading and trailing newlines are stripped by remark
function getFencedCodeBlockValue$2(node, originalText) {
var text = originalText.slice(node.position.start.offset, node.position.end.offset);
var leadingSpaceCount = text.match(/^\s*/)[0].length;
var replaceRegex = new RegExp("^\\s{0,".concat(leadingSpaceCount, "}"));
var lineContents = text.split("\n");
var markerStyle = text[leadingSpaceCount]; // ` or ~
var marker = text.slice(leadingSpaceCount).match(new RegExp("^[".concat(markerStyle, "]+")))[0]; // https://spec.commonmark.org/0.28/#example-104: Closing fences may be indented by 0-3 spaces
// https://spec.commonmark.org/0.28/#example-93: The closing code fence must be at least as long as the opening fence
var hasEndMarker = new RegExp("^\\s{0,3}".concat(marker)).test(lineContents[lineContents.length - 1].slice(getIndent(lineContents.length - 1)));
return lineContents.slice(1, hasEndMarker ? -1 : undefined).map(function (x, i) {
return x.slice(getIndent(i + 1)).replace(replaceRegex, "");
}).join("\n");
function getIndent(lineIndex) {
return node.position.indent[lineIndex - 1] - 1;
}
}
function mapAst(ast, handler) {
return function preorder(node, index, parentStack) {
parentStack = parentStack || [];
var newNode = Object.assign({}, handler(node, index, parentStack));
if (newNode.children) {
newNode.children = newNode.children.map(function (child, index) {
return preorder(child, index, [newNode].concat(parentStack));
});
}
return newNode;
}(ast, null, null);
}
var utils$10 = {
mapAst: mapAst,
splitText: splitText$1,
punctuationPattern: punctuationPattern$1,
getFencedCodeBlockValue: getFencedCodeBlockValue$2,
getOrderedListItemInfo: getOrderedListItemInfo$1,
INLINE_NODE_TYPES: INLINE_NODE_TYPES$1,
INLINE_NODE_WRAPPER_TYPES: INLINE_NODE_WRAPPER_TYPES$1
};
var _require$$0$builders$9 = doc.builders;
var hardline$12 = _require$$0$builders$9.hardline;
var literalline$6 = _require$$0$builders$9.literalline;
var concat$16 = _require$$0$builders$9.concat;
var markAsRoot$4 = _require$$0$builders$9.markAsRoot;
var mapDoc$7 = doc.utils.mapDoc;
var getFencedCodeBlockValue$1 = utils$10.getFencedCodeBlockValue;
function embed$6(path, print, textToDoc, options) {
var node = path.getValue();
if (node.type === "code" && node.lang !== null) {
// only look for the first string so as to support [markdown-preview-enhanced](https://shd101wyy.github.io/markdown-preview-enhanced/#/code-chunk)
var langMatch = node.lang.match(/^[A-Za-z0-9_-]+/);
var lang = langMatch ? langMatch[0] : "";
var parser = getParserName(lang);
if (parser) {
var styleUnit = options.__inJsTemplate ? "~" : "`";
var style = styleUnit.repeat(Math.max(3, util.getMaxContinuousCount(node.value, styleUnit) + 1));
var doc$$2 = textToDoc(getFencedCodeBlockValue$1(node, options.originalText), {
parser: parser
});
return markAsRoot$4(concat$16([style, node.lang, hardline$12, replaceNewlinesWithLiterallines(doc$$2), style]));
}
}
if (node.type === "yaml") {
return markAsRoot$4(concat$16(["---", hardline$12, node.value && node.value.trim() ? replaceNewlinesWithLiterallines(textToDoc(node.value, {
parser: "yaml"
})) : "", "---"]));
} // MDX
switch (node.type) {
case "importExport":
return textToDoc(node.value, {
parser: "babel"
});
case "jsx":
return textToDoc(node.value, {
parser: "__js_expression"
});
}
return null;
function getParserName(lang) {
var supportInfo = support.getSupportInfo(null, {
plugins: options.plugins
});
var language = supportInfo.languages.find(function (language) {
return language.name.toLowerCase() === lang || language.aliases && language.aliases.indexOf(lang) !== -1 || language.extensions && language.extensions.find(function (ext) {
return ext.substring(1) === lang;
});
});
if (language) {
return language.parsers[0];
}
return null;
}
function replaceNewlinesWithLiterallines(doc$$2) {
return mapDoc$7(doc$$2, function (currentDoc) {
return typeof currentDoc === "string" && currentDoc.includes("\n") ? concat$16(currentDoc.split(/(\n)/g).map(function (v, i) {
return i % 2 === 0 ? v : literalline$6;
})) : currentDoc;
});
}
}
var embed_1$4 = embed$6;
var pragma$8 = createCommonjsModule(function (module) {
"use strict";
var pragmas = ["format", "prettier"];
function startWithPragma(text) {
var pragma = "@(".concat(pragmas.join("|"), ")");
var regex = new RegExp([""), "")].join("|"), "m");
var matched = text.match(regex);
return matched && matched.index === 0;
}
module.exports = {
startWithPragma: startWithPragma,
hasPragma: function hasPragma(text) {
return startWithPragma(frontMatter(text).content.trimLeft());
},
insertPragma: function insertPragma(text) {
var extracted = frontMatter(text);
var pragma = "");
return extracted.frontMatter ? "".concat(extracted.frontMatter.raw, "\n\n").concat(pragma, "\n\n").concat(extracted.content) : "".concat(pragma, "\n\n").concat(extracted.content);
}
};
});
var getOrderedListItemInfo$2 = utils$10.getOrderedListItemInfo;
var mapAst$1 = utils$10.mapAst;
var splitText$2 = utils$10.splitText; // 0x0 ~ 0x10ffff
var isSingleCharRegex = /^([\u0000-\uffff]|[\ud800-\udbff][\udc00-\udfff])$/;
function preprocess$4(ast, options) {
ast = restoreUnescapedCharacter(ast, options);
ast = mergeContinuousTexts(ast);
ast = transformInlineCode(ast);
ast = transformIndentedCodeblockAndMarkItsParentList(ast, options);
ast = markAlignedList(ast, options);
ast = splitTextIntoSentences(ast, options);
ast = transformImportExport(ast);
ast = mergeContinuousImportExport(ast);
return ast;
}
function transformImportExport(ast) {
return mapAst$1(ast, function (node) {
if (node.type !== "import" && node.type !== "export") {
return node;
}
return Object.assign({}, node, {
type: "importExport"
});
});
}
function transformInlineCode(ast) {
return mapAst$1(ast, function (node) {
if (node.type !== "inlineCode") {
return node;
}
return Object.assign({}, node, {
value: node.value.replace(/\s+/g, " ")
});
});
}
function restoreUnescapedCharacter(ast, options) {
return mapAst$1(ast, function (node) {
return node.type !== "text" ? node : Object.assign({}, node, {
value: node.value !== "*" && node.value !== "_" && node.value !== "$" && // handle these cases in printer
isSingleCharRegex.test(node.value) && node.position.end.offset - node.position.start.offset !== node.value.length ? options.originalText.slice(node.position.start.offset, node.position.end.offset) : node.value
});
});
}
function mergeContinuousImportExport(ast) {
return mergeChildren(ast, function (prevNode, node) {
return prevNode.type === "importExport" && node.type === "importExport";
}, function (prevNode, node) {
return {
type: "importExport",
value: prevNode.value + "\n\n" + node.value,
position: {
start: prevNode.position.start,
end: node.position.end
}
};
});
}
function mergeChildren(ast, shouldMerge, mergeNode) {
return mapAst$1(ast, function (node) {
if (!node.children) {
return node;
}
var children = node.children.reduce(function (current, child) {
var lastChild = current[current.length - 1];
if (lastChild && shouldMerge(lastChild, child)) {
current.splice(-1, 1, mergeNode(lastChild, child));
} else {
current.push(child);
}
return current;
}, []);
return Object.assign({}, node, {
children: children
});
});
}
function mergeContinuousTexts(ast) {
return mergeChildren(ast, function (prevNode, node) {
return prevNode.type === "text" && node.type === "text";
}, function (prevNode, node) {
return {
type: "text",
value: prevNode.value + node.value,
position: {
start: prevNode.position.start,
end: node.position.end
}
};
});
}
function splitTextIntoSentences(ast, options) {
return mapAst$1(ast, function (node, index, _ref) {
var _ref2 = _slicedToArray(_ref, 1),
parentNode = _ref2[0];
if (node.type !== "text") {
return node;
}
var value = node.value;
if (parentNode.type === "paragraph") {
if (index === 0) {
value = value.trimLeft();
}
if (index === parentNode.children.length - 1) {
value = value.trimRight();
}
}
return {
type: "sentence",
position: node.position,
children: splitText$2(value, options)
};
});
}
function transformIndentedCodeblockAndMarkItsParentList(ast, options) {
return mapAst$1(ast, function (node, index, parentStack) {
if (node.type === "code") {
// the first char may point to `\n`, e.g. `\n\t\tbar`, just ignore it
var isIndented = /^\n?( {4,}|\t)/.test(options.originalText.slice(node.position.start.offset, node.position.end.offset));
node.isIndented = isIndented;
if (isIndented) {
for (var i = 0; i < parentStack.length; i++) {
var parent = parentStack[i]; // no need to check checked items
if (parent.hasIndentedCodeblock) {
break;
}
if (parent.type === "list") {
parent.hasIndentedCodeblock = true;
}
}
}
}
return node;
});
}
function markAlignedList(ast, options) {
return mapAst$1(ast, function (node, index, parentStack) {
if (node.type === "list" && node.children.length !== 0) {
// if one of its parents is not aligned, it's not possible to be aligned in sub-lists
for (var i = 0; i < parentStack.length; i++) {
var parent = parentStack[i];
if (parent.type === "list" && !parent.isAligned) {
node.isAligned = false;
return node;
}
}
node.isAligned = isAligned(node);
}
return node;
});
function getListItemStart(listItem) {
return listItem.children.length === 0 ? -1 : listItem.children[0].position.start.column - 1;
}
function isAligned(list) {
if (!list.ordered) {
/**
* - 123
* - 123
*/
return true;
}
var _list$children = _slicedToArray(list.children, 2),
firstItem = _list$children[0],
secondItem = _list$children[1];
var firstInfo = getOrderedListItemInfo$2(firstItem, options.originalText);
if (firstInfo.leadingSpaces.length > 1) {
/**
* 1. 123
*
* 1. 123
* 1. 123
*/
return true;
}
var firstStart = getListItemStart(firstItem);
if (firstStart === -1) {
/**
* 1.
*
* 1.
* 1.
*/
return false;
}
if (list.children.length === 1) {
/**
* aligned:
*
* 11. 123
*
* not aligned:
*
* 1. 123
*/
return firstStart % options.tabWidth === 0;
}
var secondStart = getListItemStart(secondItem);
if (firstStart !== secondStart) {
/**
* 11. 123
* 1. 123
*
* 1. 123
* 11. 123
*/
return false;
}
if (firstStart % options.tabWidth === 0) {
/**
* 11. 123
* 12. 123
*/
return true;
}
/**
* aligned:
*
* 11. 123
* 1. 123
*
* not aligned:
*
* 1. 123
* 2. 123
*/
var secondInfo = getOrderedListItemInfo$2(secondItem, options.originalText);
return secondInfo.leadingSpaces.length > 1;
}
}
var preprocess_1$4 = preprocess$4;
var _require$$0$builders$8 = doc.builders;
var breakParent$4 = _require$$0$builders$8.breakParent;
var concat$15 = _require$$0$builders$8.concat;
var join$11 = _require$$0$builders$8.join;
var line$10 = _require$$0$builders$8.line;
var literalline$5 = _require$$0$builders$8.literalline;
var markAsRoot$3 = _require$$0$builders$8.markAsRoot;
var hardline$11 = _require$$0$builders$8.hardline;
var softline$7 = _require$$0$builders$8.softline;
var ifBreak$7 = _require$$0$builders$8.ifBreak;
var fill$5 = _require$$0$builders$8.fill;
var align$2 = _require$$0$builders$8.align;
var indent$9 = _require$$0$builders$8.indent;
var group$15 = _require$$0$builders$8.group;
var mapDoc$6 = doc.utils.mapDoc;
var printDocToString$2 = doc.printer.printDocToString;
var getFencedCodeBlockValue = utils$10.getFencedCodeBlockValue;
var getOrderedListItemInfo = utils$10.getOrderedListItemInfo;
var splitText = utils$10.splitText;
var punctuationPattern = utils$10.punctuationPattern;
var INLINE_NODE_TYPES = utils$10.INLINE_NODE_TYPES;
var INLINE_NODE_WRAPPER_TYPES = utils$10.INLINE_NODE_WRAPPER_TYPES;
var replaceEndOfLineWith$2 = util.replaceEndOfLineWith;
var TRAILING_HARDLINE_NODES = ["importExport"];
var SINGLE_LINE_NODE_TYPES = ["heading", "tableCell", "link"];
var SIBLING_NODE_TYPES = ["listItem", "definition", "footnoteDefinition"];
function genericPrint$5(path, options, print) {
var node = path.getValue();
if (shouldRemainTheSameContent(path)) {
return concat$15(splitText(options.originalText.slice(node.position.start.offset, node.position.end.offset), options).map(function (node) {
return node.type === "word" ? node.value : node.value === "" ? "" : printLine(path, node.value, options);
}));
}
switch (node.type) {
case "root":
if (node.children.length === 0) {
return "";
}
return concat$15([normalizeDoc(printRoot(path, options, print)), TRAILING_HARDLINE_NODES.indexOf(getLastDescendantNode(node).type) === -1 ? hardline$11 : ""]);
case "paragraph":
return printChildren$1(path, options, print, {
postprocessor: fill$5
});
case "sentence":
return printChildren$1(path, options, print);
case "word":
return node.value.replace(/[*$]/g, "\\$&") // escape all `*` and `$` (math)
.replace(new RegExp(["(^|".concat(punctuationPattern, ")(_+)"), "(_+)(".concat(punctuationPattern, "|$)")].join("|"), "g"), function (_, text1, underscore1, underscore2, text2) {
return (underscore1 ? "".concat(text1).concat(underscore1) : "".concat(underscore2).concat(text2)).replace(/_/g, "\\_");
});
// escape all `_` except concating with non-punctuation, e.g. `1_2_3` is not considered emphasis
case "whitespace":
{
var parentNode = path.getParentNode();
var index = parentNode.children.indexOf(node);
var nextNode = parentNode.children[index + 1];
var proseWrap = // leading char that may cause different syntax
nextNode && /^>|^([-+*]|#{1,6}|[0-9]+[.)])$/.test(nextNode.value) ? "never" : options.proseWrap;
return printLine(path, node.value, {
proseWrap: proseWrap
});
}
case "emphasis":
{
var _parentNode = path.getParentNode();
var _index = _parentNode.children.indexOf(node);
var prevNode = _parentNode.children[_index - 1];
var _nextNode = _parentNode.children[_index + 1];
var hasPrevOrNextWord = // `1*2*3` is considered emphais but `1_2_3` is not
prevNode && prevNode.type === "sentence" && prevNode.children.length > 0 && util.getLast(prevNode.children).type === "word" && !util.getLast(prevNode.children).hasTrailingPunctuation || _nextNode && _nextNode.type === "sentence" && _nextNode.children.length > 0 && _nextNode.children[0].type === "word" && !_nextNode.children[0].hasLeadingPunctuation;
var style = hasPrevOrNextWord || getAncestorNode$2(path, "emphasis") ? "*" : "_";
return concat$15([style, printChildren$1(path, options, print), style]);
}
case "strong":
return concat$15(["**", printChildren$1(path, options, print), "**"]);
case "delete":
return concat$15(["~~", printChildren$1(path, options, print), "~~"]);
case "inlineCode":
{
var backtickCount = util.getMinNotPresentContinuousCount(node.value, "`");
var _style = "`".repeat(backtickCount || 1);
var gap = backtickCount ? " " : "";
return concat$15([_style, gap, node.value, gap, _style]);
}
case "link":
switch (options.originalText[node.position.start.offset]) {
case "<":
{
var mailto = "mailto:";
var url = // is parsed as { url: "mailto:hello@example.com" }
node.url.startsWith(mailto) && options.originalText.slice(node.position.start.offset + 1, node.position.start.offset + 1 + mailto.length) !== mailto ? node.url.slice(mailto.length) : node.url;
return concat$15(["<", url, ">"]);
}
case "[":
return concat$15(["[", printChildren$1(path, options, print), "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]);
default:
return options.originalText.slice(node.position.start.offset, node.position.end.offset);
}
case "image":
return concat$15(["![", node.alt || "", "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]);
case "blockquote":
return concat$15(["> ", align$2("> ", printChildren$1(path, options, print))]);
case "heading":
return concat$15(["#".repeat(node.depth) + " ", printChildren$1(path, options, print)]);
case "code":
{
if (node.isIndented) {
// indented code block
var alignment = " ".repeat(4);
return align$2(alignment, concat$15([alignment, concat$15(replaceEndOfLineWith$2(node.value, hardline$11))]));
} // fenced code block
var styleUnit = options.__inJsTemplate ? "~" : "`";
var _style2 = styleUnit.repeat(Math.max(3, util.getMaxContinuousCount(node.value, styleUnit) + 1));
return concat$15([_style2, node.lang || "", hardline$11, concat$15(replaceEndOfLineWith$2(getFencedCodeBlockValue(node, options.originalText), hardline$11)), hardline$11, _style2]);
}
case "yaml":
case "toml":
return options.originalText.slice(node.position.start.offset, node.position.end.offset);
case "html":
{
var _parentNode2 = path.getParentNode();
var value = _parentNode2.type === "root" && util.getLast(_parentNode2.children) === node ? node.value.trimRight() : node.value;
var isHtmlComment = /^$/.test(value);
return concat$15(replaceEndOfLineWith$2(value, isHtmlComment ? hardline$11 : markAsRoot$3(literalline$5)));
}
case "list":
{
var nthSiblingIndex = getNthListSiblingIndex(node, path.getParentNode());
var isGitDiffFriendlyOrderedList = node.ordered && node.children.length > 1 && +getOrderedListItemInfo(node.children[1], options.originalText).numberText === 1;
return printChildren$1(path, options, print, {
processor: function processor(childPath, index) {
var prefix = getPrefix();
return concat$15([prefix, align$2(" ".repeat(prefix.length), printListItem(childPath, options, print, prefix))]);
function getPrefix() {
var rawPrefix = node.ordered ? (index === 0 ? node.start : isGitDiffFriendlyOrderedList ? 1 : node.start + index) + (nthSiblingIndex % 2 === 0 ? ". " : ") ") : nthSiblingIndex % 2 === 0 ? "- " : "* ";
return node.isAligned ||
/* workaround for https://github.com/remarkjs/remark/issues/315 */
node.hasIndentedCodeblock ? alignListPrefix(rawPrefix, options) : rawPrefix;
}
}
});
}
case "thematicBreak":
{
var counter = getAncestorCounter$1(path, "list");
if (counter === -1) {
return "---";
}
var _nthSiblingIndex = getNthListSiblingIndex(path.getParentNode(counter), path.getParentNode(counter + 1));
return _nthSiblingIndex % 2 === 0 ? "***" : "---";
}
case "linkReference":
return concat$15(["[", printChildren$1(path, options, print), "]", node.referenceType === "full" ? concat$15(["[", node.identifier, "]"]) : node.referenceType === "collapsed" ? "[]" : ""]);
case "imageReference":
switch (node.referenceType) {
case "full":
return concat$15(["![", node.alt || "", "][", node.identifier, "]"]);
default:
return concat$15(["![", node.alt, "]", node.referenceType === "collapsed" ? "[]" : ""]);
}
case "definition":
{
var lineOrSpace = options.proseWrap === "always" ? line$10 : " ";
return group$15(concat$15([concat$15(["[", node.identifier, "]:"]), indent$9(concat$15([lineOrSpace, printUrl(node.url), node.title === null ? "" : concat$15([lineOrSpace, printTitle(node.title, options, false)])]))]));
}
case "footnote":
return concat$15(["[^", printChildren$1(path, options, print), "]"]);
case "footnoteReference":
return concat$15(["[^", node.identifier, "]"]);
case "footnoteDefinition":
{
var _nextNode2 = path.getParentNode().children[path.getName() + 1];
var shouldInlineFootnote = node.children.length === 1 && node.children[0].type === "paragraph" && (options.proseWrap === "never" || options.proseWrap === "preserve" && node.children[0].position.start.line === node.children[0].position.end.line);
return concat$15(["[^", node.identifier, "]: ", shouldInlineFootnote ? printChildren$1(path, options, print) : group$15(concat$15([align$2(" ".repeat(options.tabWidth), printChildren$1(path, options, print, {
processor: function processor(childPath, index) {
return index === 0 ? group$15(concat$15([softline$7, softline$7, childPath.call(print)])) : childPath.call(print);
}
})), _nextNode2 && _nextNode2.type === "footnoteDefinition" ? softline$7 : ""]))]);
}
case "table":
return printTable(path, options, print);
case "tableCell":
return printChildren$1(path, options, print);
case "break":
return /\s/.test(options.originalText[node.position.start.offset]) ? concat$15([" ", markAsRoot$3(literalline$5)]) : concat$15(["\\", hardline$11]);
case "liquidNode":
return concat$15(replaceEndOfLineWith$2(node.value, hardline$11));
// MDX
case "importExport":
case "jsx":
return node.value;
// fallback to the original text if multiparser failed
case "math":
return concat$15(["$$", hardline$11, node.value ? concat$15([concat$15(replaceEndOfLineWith$2(node.value, hardline$11)), hardline$11]) : "", "$$"]);
case "inlineMath":
{
// remark-math trims content but we don't want to remove whitespaces
// since it's very possible that it's recognized as math accidentally
return options.originalText.slice(options.locStart(node), options.locEnd(node));
}
case "tableRow": // handled in "table"
case "listItem": // handled in "list"
default:
throw new Error("Unknown markdown type ".concat(JSON.stringify(node.type)));
}
}
function printListItem(path, options, print, listPrefix) {
var node = path.getValue();
var prefix = node.checked === null ? "" : node.checked ? "[x] " : "[ ] ";
return concat$15([prefix, printChildren$1(path, options, print, {
processor: function processor(childPath, index) {
if (index === 0 && childPath.getValue().type !== "list") {
return align$2(" ".repeat(prefix.length), childPath.call(print));
}
var alignment = " ".repeat(clamp(options.tabWidth - listPrefix.length, 0, 3) // 4+ will cause indented code block
);
return concat$15([alignment, align$2(alignment, childPath.call(print))]);
}
})]);
}
function alignListPrefix(prefix, options) {
var additionalSpaces = getAdditionalSpaces();
return prefix + " ".repeat(additionalSpaces >= 4 ? 0 : additionalSpaces // 4+ will cause indented code block
);
function getAdditionalSpaces() {
var restSpaces = prefix.length % options.tabWidth;
return restSpaces === 0 ? 0 : options.tabWidth - restSpaces;
}
}
function getNthListSiblingIndex(node, parentNode) {
return getNthSiblingIndex(node, parentNode, function (siblingNode) {
return siblingNode.ordered === node.ordered;
});
}
function getNthSiblingIndex(node, parentNode, condition) {
condition = condition || function () {
return true;
};
var index = -1;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = parentNode.children[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var childNode = _step.value;
if (childNode.type === node.type && condition(childNode)) {
index++;
} else {
index = -1;
}
if (childNode === node) {
return index;
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
}
function getAncestorCounter$1(path, typeOrTypes) {
var types = [].concat(typeOrTypes);
var counter = -1;
var ancestorNode;
while (ancestorNode = path.getParentNode(++counter)) {
if (types.indexOf(ancestorNode.type) !== -1) {
return counter;
}
}
return -1;
}
function getAncestorNode$2(path, typeOrTypes) {
var counter = getAncestorCounter$1(path, typeOrTypes);
return counter === -1 ? null : path.getParentNode(counter);
}
function printLine(path, value, options) {
if (options.proseWrap === "preserve" && value === "\n") {
return hardline$11;
}
var isBreakable = options.proseWrap === "always" && !getAncestorNode$2(path, SINGLE_LINE_NODE_TYPES);
return value !== "" ? isBreakable ? line$10 : " " : isBreakable ? softline$7 : "";
}
function printTable(path, options, print) {
var hardlineWithoutBreakParent = hardline$11.parts[0];
var node = path.getValue();
var contents = []; // { [rowIndex: number]: { [columnIndex: number]: string } }
path.map(function (rowPath) {
var rowContents = [];
rowPath.map(function (cellPath) {
rowContents.push(printDocToString$2(cellPath.call(print), options).formatted);
}, "children");
contents.push(rowContents);
}, "children"); // Get the width of each column
var columnMaxWidths = contents.reduce(function (currentWidths, rowContents) {
return currentWidths.map(function (width, columnIndex) {
return Math.max(width, util.getStringWidth(rowContents[columnIndex]));
});
}, contents[0].map(function () {
return 3;
}) // minimum width = 3 (---, :--, :-:, --:)
);
var alignedTable = join$11(hardlineWithoutBreakParent, [printRow(contents[0]), printSeparator(), join$11(hardlineWithoutBreakParent, contents.slice(1).map(function (rowContents) {
return printRow(rowContents);
}))]);
if (options.proseWrap !== "never") {
return concat$15([breakParent$4, alignedTable]);
} // Only if the --prose-wrap never is set and it exceeds the print width.
var compactTable = join$11(hardlineWithoutBreakParent, [printRow(contents[0],
/* isCompact */
true), printSeparator(
/* isCompact */
true), join$11(hardlineWithoutBreakParent, contents.slice(1).map(function (rowContents) {
return printRow(rowContents,
/* isCompact */
true);
}))]);
return concat$15([breakParent$4, group$15(ifBreak$7(compactTable, alignedTable))]);
function printSeparator(isCompact) {
return concat$15(["| ", join$11(" | ", columnMaxWidths.map(function (width, index) {
var spaces = isCompact ? 3 : width;
switch (node.align[index]) {
case "left":
return ":" + "-".repeat(spaces - 1);
case "right":
return "-".repeat(spaces - 1) + ":";
case "center":
return ":" + "-".repeat(spaces - 2) + ":";
default:
return "-".repeat(spaces);
}
})), " |"]);
}
function printRow(rowContents, isCompact) {
return concat$15(["| ", join$11(" | ", isCompact ? rowContents : rowContents.map(function (rowContent, columnIndex) {
switch (node.align[columnIndex]) {
case "right":
return alignRight(rowContent, columnMaxWidths[columnIndex]);
case "center":
return alignCenter(rowContent, columnMaxWidths[columnIndex]);
default:
return alignLeft(rowContent, columnMaxWidths[columnIndex]);
}
})), " |"]);
}
function alignLeft(text, width) {
var spaces = width - util.getStringWidth(text);
return concat$15([text, " ".repeat(spaces)]);
}
function alignRight(text, width) {
var spaces = width - util.getStringWidth(text);
return concat$15([" ".repeat(spaces), text]);
}
function alignCenter(text, width) {
var spaces = width - util.getStringWidth(text);
var left = Math.floor(spaces / 2);
var right = spaces - left;
return concat$15([" ".repeat(left), text, " ".repeat(right)]);
}
}
function printRoot(path, options, print) {
/** @typedef {{ index: number, offset: number }} IgnorePosition */
/** @type {Array<{start: IgnorePosition, end: IgnorePosition}>} */
var ignoreRanges = [];
/** @type {IgnorePosition | null} */
var ignoreStart = null;
var children = path.getValue().children;
children.forEach(function (childNode, index) {
switch (isPrettierIgnore$1(childNode)) {
case "start":
if (ignoreStart === null) {
ignoreStart = {
index: index,
offset: childNode.position.end.offset
};
}
break;
case "end":
if (ignoreStart !== null) {
ignoreRanges.push({
start: ignoreStart,
end: {
index: index,
offset: childNode.position.start.offset
}
});
ignoreStart = null;
}
break;
default:
// do nothing
break;
}
});
return printChildren$1(path, options, print, {
processor: function processor(childPath, index) {
if (ignoreRanges.length !== 0) {
var ignoreRange = ignoreRanges[0];
if (index === ignoreRange.start.index) {
return concat$15([children[ignoreRange.start.index].value, options.originalText.slice(ignoreRange.start.offset, ignoreRange.end.offset), children[ignoreRange.end.index].value]);
}
if (ignoreRange.start.index < index && index < ignoreRange.end.index) {
return false;
}
if (index === ignoreRange.end.index) {
ignoreRanges.shift();
return false;
}
}
return childPath.call(print);
}
});
}
function printChildren$1(path, options, print, events) {
events = events || {};
var postprocessor = events.postprocessor || concat$15;
var processor = events.processor || function (childPath) {
return childPath.call(print);
};
var node = path.getValue();
var parts = [];
var lastChildNode;
path.map(function (childPath, index) {
var childNode = childPath.getValue();
var result = processor(childPath, index);
if (result !== false) {
var data = {
parts: parts,
prevNode: lastChildNode,
parentNode: node,
options: options
};
if (!shouldNotPrePrintHardline(childNode, data)) {
parts.push(hardline$11);
if (lastChildNode && TRAILING_HARDLINE_NODES.indexOf(lastChildNode.type) !== -1) {
if (shouldPrePrintTripleHardline(childNode, data)) {
parts.push(hardline$11);
}
} else {
if (shouldPrePrintDoubleHardline(childNode, data) || shouldPrePrintTripleHardline(childNode, data)) {
parts.push(hardline$11);
}
if (shouldPrePrintTripleHardline(childNode, data)) {
parts.push(hardline$11);
}
}
}
parts.push(result);
lastChildNode = childNode;
}
}, "children");
return postprocessor(parts);
}
function getLastDescendantNode(node) {
var current = node;
while (current.children && current.children.length !== 0) {
current = current.children[current.children.length - 1];
}
return current;
}
/** @return {false | 'next' | 'start' | 'end'} */
function isPrettierIgnore$1(node) {
if (node.type !== "html") {
return false;
}
var match = node.value.match(/^$/);
return match === null ? false : match[1] ? match[1] : "next";
}
function shouldNotPrePrintHardline(node, data) {
var isFirstNode = data.parts.length === 0;
var isInlineNode = INLINE_NODE_TYPES.indexOf(node.type) !== -1;
var isInlineHTML = node.type === "html" && INLINE_NODE_WRAPPER_TYPES.indexOf(data.parentNode.type) !== -1;
return isFirstNode || isInlineNode || isInlineHTML;
}
function shouldPrePrintDoubleHardline(node, data) {
var isSequence = (data.prevNode && data.prevNode.type) === node.type;
var isSiblingNode = isSequence && SIBLING_NODE_TYPES.indexOf(node.type) !== -1;
var isInTightListItem = data.parentNode.type === "listItem" && !data.parentNode.loose;
var isPrevNodeLooseListItem = data.prevNode && data.prevNode.type === "listItem" && data.prevNode.loose;
var isPrevNodePrettierIgnore = isPrettierIgnore$1(data.prevNode) === "next";
var isBlockHtmlWithoutBlankLineBetweenPrevHtml = node.type === "html" && data.prevNode && data.prevNode.type === "html" && data.prevNode.position.end.line + 1 === node.position.start.line;
return isPrevNodeLooseListItem || !(isSiblingNode || isInTightListItem || isPrevNodePrettierIgnore || isBlockHtmlWithoutBlankLineBetweenPrevHtml);
}
function shouldPrePrintTripleHardline(node, data) {
var isPrevNodeList = data.prevNode && data.prevNode.type === "list";
var isIndentedCode = node.type === "code" && node.isIndented;
return isPrevNodeList && isIndentedCode;
}
function shouldRemainTheSameContent(path) {
var ancestorNode = getAncestorNode$2(path, ["linkReference", "imageReference"]);
return ancestorNode && (ancestorNode.type !== "linkReference" || ancestorNode.referenceType !== "full");
}
function normalizeDoc(doc$$2) {
return mapDoc$6(doc$$2, function (currentDoc) {
if (!currentDoc.parts) {
return currentDoc;
}
if (currentDoc.type === "concat" && currentDoc.parts.length === 1) {
return currentDoc.parts[0];
}
var parts = [];
currentDoc.parts.forEach(function (part) {
if (part.type === "concat") {
parts.push.apply(parts, part.parts);
} else if (part !== "") {
parts.push(part);
}
});
return Object.assign({}, currentDoc, {
parts: normalizeParts$2(parts)
});
});
}
function printUrl(url, dangerousCharOrChars) {
var dangerousChars = [" "].concat(dangerousCharOrChars || []);
return new RegExp(dangerousChars.map(function (x) {
return "\\".concat(x);
}).join("|")).test(url) ? "<".concat(url, ">") : url;
}
function printTitle(title, options, printSpace) {
if (printSpace == null) {
printSpace = true;
}
if (!title) {
return "";
}
if (printSpace) {
return " " + printTitle(title, options, false);
}
if (title.includes('"') && title.includes("'") && !title.includes(")")) {
return "(".concat(title, ")"); // avoid escaped quotes
} // faster than using RegExps: https://jsperf.com/performance-of-match-vs-split
var singleCount = title.split("'").length - 1;
var doubleCount = title.split('"').length - 1;
var quote = singleCount > doubleCount ? '"' : doubleCount > singleCount ? "'" : options.singleQuote ? "'" : '"';
title = title.replace(new RegExp("(".concat(quote, ")"), "g"), "\\$1");
return "".concat(quote).concat(title).concat(quote);
}
function normalizeParts$2(parts) {
return parts.reduce(function (current, part) {
var lastPart = util.getLast(current);
if (typeof lastPart === "string" && typeof part === "string") {
current.splice(-1, 1, lastPart + part);
} else {
current.push(part);
}
return current;
}, []);
}
function clamp(value, min, max) {
return value < min ? min : value > max ? max : value;
}
function clean$10(ast, newObj, parent) {
delete newObj.position;
delete newObj.raw; // front-matter
// for codeblock
if (ast.type === "code" || ast.type === "yaml" || ast.type === "import" || ast.type === "export" || ast.type === "jsx") {
delete newObj.value;
}
if (ast.type === "list") {
delete newObj.isAligned;
} // texts can be splitted or merged
if (ast.type === "text") {
return null;
}
if (ast.type === "inlineCode") {
newObj.value = ast.value.replace(/[ \t\n]+/g, " ");
} // for insert pragma
if (parent && parent.type === "root" && parent.children.length > 0 && (parent.children[0] === ast || (parent.children[0].type === "yaml" || parent.children[0].type === "toml") && parent.children[1] === ast) && ast.type === "html" && pragma$8.startWithPragma(ast.value)) {
return null;
}
}
function hasPrettierIgnore$3(path) {
var index = +path.getName();
if (index === 0) {
return false;
}
var prevNode = path.getParentNode().children[index - 1];
return isPrettierIgnore$1(prevNode) === "next";
}
var printerMarkdown = {
preprocess: preprocess_1$4,
print: genericPrint$5,
embed: embed_1$4,
massageAstNode: clean$10,
hasPrettierIgnore: hasPrettierIgnore$3,
insertPragma: pragma$8.insertPragma
};
var options$15 = {
proseWrap: commonOptions.proseWrap,
singleQuote: commonOptions.singleQuote
};
var name$15 = "Markdown";
var type$14 = "prose";
var aliases$5 = ["pandoc"];
var aceMode$14 = "markdown";
var codemirrorMode$10 = "gfm";
var codemirrorMimeType$10 = "text/x-gfm";
var wrap = true;
var extensions$14 = [".md", ".markdown", ".mdown", ".mdwn", ".mkd", ".mkdn", ".mkdown", ".ronn", ".workbook"];
var tmScope$14 = "source.gfm";
var languageId$14 = 222;
var markdown = {
name: name$15,
type: type$14,
aliases: aliases$5,
aceMode: aceMode$14,
codemirrorMode: codemirrorMode$10,
codemirrorMimeType: codemirrorMimeType$10,
wrap: wrap,
extensions: extensions$14,
tmScope: tmScope$14,
languageId: languageId$14
};
var markdown$1 = Object.freeze({
name: name$15,
type: type$14,
aliases: aliases$5,
aceMode: aceMode$14,
codemirrorMode: codemirrorMode$10,
codemirrorMimeType: codemirrorMimeType$10,
wrap: wrap,
extensions: extensions$14,
tmScope: tmScope$14,
languageId: languageId$14,
default: markdown
});
var require$$0$27 = ( markdown$1 && markdown ) || markdown$1;
var languages$5 = [createLanguage(require$$0$27, {
override: {
since: "1.8.0",
parsers: ["remark"],
vscodeLanguageIds: ["markdown"]
},
extend: {
filenames: ["README"]
}
}), createLanguage({
name: "MDX",
extensions: [".mdx"]
}, // TODO: use linguist data
{
override: {
since: "1.15.0",
parsers: ["mdx"],
vscodeLanguageIds: ["mdx"]
}
})];
var printers$5 = {
mdast: printerMarkdown
};
var languageMarkdown = {
languages: languages$5,
options: options$15,
printers: printers$5
};
function isPragma$1(text) {
return /^\s*@(prettier|format)\s*$/.test(text);
}
function hasPragma$4(text) {
return /^\s*#[^\n\S]*@(prettier|format)\s*?(\n|$)/.test(text);
}
function insertPragma$9(text) {
return "# @format\n\n".concat(text);
}
var pragma$11 = {
isPragma: isPragma$1,
hasPragma: hasPragma$4,
insertPragma: insertPragma$9
};
var getLast$6 = util.getLast;
function getAncestorCount$1(path, filter) {
var counter = 0;
var pathStackLength = path.stack.length - 1;
for (var i = 0; i < pathStackLength; i++) {
var value = path.stack[i];
if (isNode$1(value) && filter(value)) {
counter++;
}
}
return counter;
}
/**
* @param {any} value
* @param {string[]=} types
*/
function isNode$1(value, types) {
return value && typeof value.type === "string" && (!types || types.indexOf(value.type) !== -1);
}
function mapNode$1(node, callback, parent) {
return callback("children" in node ? Object.assign({}, node, {
children: node.children.map(function (childNode) {
return mapNode$1(childNode, callback, node);
})
}) : node, parent);
}
function defineShortcut$1(x, key, getter) {
Object.defineProperty(x, key, {
get: getter,
enumerable: false
});
}
function isNextLineEmpty$6(node, text) {
var newlineCount = 0;
var textLength = text.length;
for (var i = node.position.end.offset - 1; i < textLength; i++) {
var char = text[i];
if (char === "\n") {
newlineCount++;
}
if (newlineCount === 1 && /\S/.test(char)) {
return false;
}
if (newlineCount === 2) {
return true;
}
}
return false;
}
function isLastDescendantNode$1(path) {
var node = path.getValue();
switch (node.type) {
case "tag":
case "anchor":
case "comment":
return false;
}
var pathStackLength = path.stack.length;
for (var i = 1; i < pathStackLength; i++) {
var item = path.stack[i];
var parentItem = path.stack[i - 1];
if (Array.isArray(parentItem) && typeof item === "number" && item !== parentItem.length - 1) {
return false;
}
}
return true;
}
function getLastDescendantNode$2(node) {
return "children" in node && node.children.length !== 0 ? getLastDescendantNode$2(getLast$6(node.children)) : node;
}
function isPrettierIgnore$2(comment) {
return comment.value.trim() === "prettier-ignore";
}
function hasPrettierIgnore$5(path) {
var node = path.getValue();
if (node.type === "documentBody") {
var document = path.getParentNode();
return hasEndComments$1(document.head) && isPrettierIgnore$2(getLast$6(document.head.endComments));
}
return hasLeadingComments$1(node) && isPrettierIgnore$2(getLast$6(node.leadingComments));
}
function isEmptyNode$1(node) {
return (!node.children || node.children.length === 0) && !hasComments(node);
}
function hasComments(node) {
return hasLeadingComments$1(node) || hasMiddleComments$1(node) || hasIndicatorComment$1(node) || hasTrailingComment$2(node) || hasEndComments$1(node);
}
function hasLeadingComments$1(node) {
return node && node.leadingComments && node.leadingComments.length !== 0;
}
function hasMiddleComments$1(node) {
return node && node.middleComments && node.middleComments.length !== 0;
}
function hasIndicatorComment$1(node) {
return node && node.indicatorComment;
}
function hasTrailingComment$2(node) {
return node && node.trailingComment;
}
function hasEndComments$1(node) {
return node && node.endComments && node.endComments.length !== 0;
}
/**
* " a b c d e f " -> [" a b", "c d", "e f "]
*/
function splitWithSingleSpace(text) {
var parts = [];
var lastPart = undefined;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = text.split(/( +)/g)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var part = _step.value;
if (part !== " ") {
if (lastPart === " ") {
parts.push(part);
} else {
parts.push((parts.pop() || "") + part);
}
} else if (lastPart === undefined) {
parts.unshift("");
}
lastPart = part;
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
if (lastPart === " ") {
parts.push((parts.pop() || "") + " ");
}
if (parts[0] === "") {
parts.shift();
parts.unshift(" " + (parts.shift() || ""));
}
return parts;
}
function getFlowScalarLineContents$1(nodeType, content, options) {
var rawLineContents = content.split("\n").map(function (lineContent, index, lineContents) {
return index === 0 && index === lineContents.length - 1 ? lineContent : index !== 0 && index !== lineContents.length - 1 ? lineContent.trim() : index === 0 ? lineContent.trimRight() : lineContent.trimLeft();
});
if (options.proseWrap === "preserve") {
return rawLineContents.map(function (lineContent) {
return lineContent.length === 0 ? [] : [lineContent];
});
}
return rawLineContents.map(function (lineContent) {
return lineContent.length === 0 ? [] : splitWithSingleSpace(lineContent);
}).reduce(function (reduced, lineContentWords, index) {
return index !== 0 && rawLineContents[index - 1].length !== 0 && lineContentWords.length !== 0 && !( // trailing backslash in quoteDouble should be preserved
nodeType === "quoteDouble" && getLast$6(getLast$6(reduced)).endsWith("\\")) ? reduced.concat([reduced.pop().concat(lineContentWords)]) : reduced.concat([lineContentWords]);
}, []).map(function (lineContentWords) {
return options.proseWrap === "never" ? [lineContentWords.join(" ")] : lineContentWords;
});
}
function getBlockValueLineContents$1(node, _ref) {
var parentIndent = _ref.parentIndent,
isLastDescendant = _ref.isLastDescendant,
options = _ref.options;
var content = node.position.start.line === node.position.end.line ? "" : options.originalText.slice(node.position.start.offset, node.position.end.offset) // exclude open line `>` or `|`
.match(/^[^\n]*?\n([\s\S]*)$/)[1];
var leadingSpaceCount = node.indent === null ? function (match) {
return match ? match[1].length : Infinity;
}(content.match(/^( *)\S/m)) : node.indent - 1 + parentIndent;
var rawLineContents = content.split("\n").map(function (lineContent) {
return lineContent.slice(leadingSpaceCount);
});
if (options.proseWrap === "preserve" || node.type === "blockLiteral") {
return removeUnnecessaryTrailingNewlines(rawLineContents.map(function (lineContent) {
return lineContent.length === 0 ? [] : [lineContent];
}));
}
return removeUnnecessaryTrailingNewlines(rawLineContents.map(function (lineContent) {
return lineContent.length === 0 ? [] : splitWithSingleSpace(lineContent);
}).reduce(function (reduced, lineContentWords, index) {
return index !== 0 && rawLineContents[index - 1].length !== 0 && lineContentWords.length !== 0 && !/^\s/.test(lineContentWords[0]) && !/^\s|\s$/.test(getLast$6(reduced)) ? reduced.concat([reduced.pop().concat(lineContentWords)]) : reduced.concat([lineContentWords]);
}, []).map(function (lineContentWords) {
return lineContentWords.reduce(function (reduced, word) {
return (// disallow trailing spaces
reduced.length !== 0 && /\s$/.test(getLast$6(reduced)) ? reduced.concat(reduced.pop() + " " + word) : reduced.concat(word)
);
}, []);
}).map(function (lineContentWords) {
return options.proseWrap === "never" ? [lineContentWords.join(" ")] : lineContentWords;
}));
function removeUnnecessaryTrailingNewlines(lineContents) {
if (node.chomping === "keep") {
return getLast$6(lineContents).length === 0 ? lineContents.slice(0, -1) : lineContents;
}
var trailingNewlineCount = 0;
for (var i = lineContents.length - 1; i >= 0; i--) {
if (lineContents[i].length === 0) {
trailingNewlineCount++;
} else {
break;
}
}
return trailingNewlineCount === 0 ? lineContents : trailingNewlineCount >= 2 && !isLastDescendant ? // next empty line
lineContents.slice(0, -(trailingNewlineCount - 1)) : lineContents.slice(0, -trailingNewlineCount);
}
}
var utils$12 = {
getLast: getLast$6,
getAncestorCount: getAncestorCount$1,
isNode: isNode$1,
isEmptyNode: isEmptyNode$1,
mapNode: mapNode$1,
defineShortcut: defineShortcut$1,
isNextLineEmpty: isNextLineEmpty$6,
isLastDescendantNode: isLastDescendantNode$1,
getBlockValueLineContents: getBlockValueLineContents$1,
getFlowScalarLineContents: getFlowScalarLineContents$1,
getLastDescendantNode: getLastDescendantNode$2,
hasPrettierIgnore: hasPrettierIgnore$5,
hasLeadingComments: hasLeadingComments$1,
hasMiddleComments: hasMiddleComments$1,
hasIndicatorComment: hasIndicatorComment$1,
hasTrailingComment: hasTrailingComment$2,
hasEndComments: hasEndComments$1
};
var insertPragma$8 = pragma$11.insertPragma;
var isPragma = pragma$11.isPragma;
var getAncestorCount = utils$12.getAncestorCount;
var getBlockValueLineContents = utils$12.getBlockValueLineContents;
var getFlowScalarLineContents = utils$12.getFlowScalarLineContents;
var getLast$5 = utils$12.getLast;
var getLastDescendantNode$1 = utils$12.getLastDescendantNode;
var hasLeadingComments = utils$12.hasLeadingComments;
var hasMiddleComments = utils$12.hasMiddleComments;
var hasIndicatorComment = utils$12.hasIndicatorComment;
var hasTrailingComment$1 = utils$12.hasTrailingComment;
var hasEndComments = utils$12.hasEndComments;
var hasPrettierIgnore$4 = utils$12.hasPrettierIgnore;
var isLastDescendantNode = utils$12.isLastDescendantNode;
var isNextLineEmpty$5 = utils$12.isNextLineEmpty;
var isNode = utils$12.isNode;
var isEmptyNode = utils$12.isEmptyNode;
var defineShortcut = utils$12.defineShortcut;
var mapNode = utils$12.mapNode;
var docBuilders$3 = doc.builders;
var conditionalGroup$2 = docBuilders$3.conditionalGroup;
var breakParent$5 = docBuilders$3.breakParent;
var concat$17 = docBuilders$3.concat;
var dedent$4 = docBuilders$3.dedent;
var dedentToRoot$3 = docBuilders$3.dedentToRoot;
var fill$6 = docBuilders$3.fill;
var group$16 = docBuilders$3.group;
var hardline$13 = docBuilders$3.hardline;
var ifBreak$8 = docBuilders$3.ifBreak;
var join$12 = docBuilders$3.join;
var line$11 = docBuilders$3.line;
var lineSuffix$2 = docBuilders$3.lineSuffix;
var literalline$7 = docBuilders$3.literalline;
var markAsRoot$5 = docBuilders$3.markAsRoot;
var softline$8 = docBuilders$3.softline;
var replaceEndOfLineWith$3 = util.replaceEndOfLineWith;
function preprocess$6(ast) {
return mapNode(ast, defineShortcuts);
}
function defineShortcuts(node) {
switch (node.type) {
case "document":
defineShortcut(node, "head", function () {
return node.children[0];
});
defineShortcut(node, "body", function () {
return node.children[1];
});
break;
case "documentBody":
case "sequenceItem":
case "flowSequenceItem":
case "mappingKey":
case "mappingValue":
defineShortcut(node, "content", function () {
return node.children[0];
});
break;
case "mappingItem":
case "flowMappingItem":
defineShortcut(node, "key", function () {
return node.children[0];
});
defineShortcut(node, "value", function () {
return node.children[1];
});
break;
}
return node;
}
function genericPrint$6(path, options, print) {
var node = path.getValue();
var parentNode = path.getParentNode();
var tag = !node.tag ? "" : path.call(print, "tag");
var anchor = !node.anchor ? "" : path.call(print, "anchor");
var nextEmptyLine = isNode(node, ["mapping", "sequence", "comment", "directive", "mappingItem", "sequenceItem"]) && !isLastDescendantNode(path) ? printNextEmptyLine(path, options.originalText) : "";
return concat$17([node.type !== "mappingValue" && hasLeadingComments(node) ? concat$17([join$12(hardline$13, path.map(print, "leadingComments")), hardline$13]) : "", tag, tag && anchor ? " " : "", anchor, tag || anchor ? isNode(node, ["sequence", "mapping"]) && !hasMiddleComments(node) ? hardline$13 : " " : "", hasMiddleComments(node) ? concat$17([node.middleComments.length === 1 ? "" : hardline$13, join$12(hardline$13, path.map(print, "middleComments")), hardline$13]) : "", hasPrettierIgnore$4(path) ? concat$17(replaceEndOfLineWith$3(options.originalText.slice(node.position.start.offset, node.position.end.offset), literalline$7)) : group$16(_print(node, parentNode, path, options, print)), hasTrailingComment$1(node) && !isNode(node, ["document", "documentHead"]) ? lineSuffix$2(concat$17([node.type === "mappingValue" && !node.content ? "" : " ", parentNode.type === "mappingKey" && path.getParentNode(2).type === "mapping" && isInlineNode(node) ? "" : breakParent$5, path.call(print, "trailingComment")])) : "", nextEmptyLine, hasEndComments(node) && !isNode(node, ["documentHead", "documentBody"]) ? align$3(node.type === "sequenceItem" ? 2 : 0, concat$17([hardline$13, join$12(hardline$13, path.map(print, "endComments"))])) : ""]);
}
function _print(node, parentNode, path, options, print) {
switch (node.type) {
case "root":
return concat$17([join$12(hardline$13, path.map(function (childPath, index) {
var document = node.children[index];
var nextDocument = node.children[index + 1];
return concat$17([print(childPath), shouldPrintDocumentEndMarker(document, nextDocument) ? concat$17([hardline$13, "...", hasTrailingComment$1(document) ? concat$17([" ", path.call(print, "trailingComment")]) : ""]) : !nextDocument || hasTrailingComment$1(nextDocument.head) ? "" : concat$17([hardline$13, "---"])]);
}, "children")), node.children.length === 0 || function (lastDescendantNode) {
return isNode(lastDescendantNode, ["blockLiteral", "blockFolded"]) && lastDescendantNode.chomping === "keep";
}(getLastDescendantNode$1(node)) ? "" : hardline$13]);
case "document":
{
var nextDocument = parentNode.children[path.getName() + 1];
return join$12(hardline$13, [shouldPrintDocumentHeadEndMarker(node, nextDocument, parentNode, options) === "head" ? join$12(hardline$13, [node.head.children.length === 0 && node.head.endComments.length === 0 ? "" : path.call(print, "head"), concat$17(["---", hasTrailingComment$1(node.head) ? concat$17([" ", path.call(print, "head", "trailingComment")]) : ""])].filter(Boolean)) : "", shouldPrintDocumentBody(node) ? path.call(print, "body") : ""].filter(Boolean));
}
case "documentHead":
return join$12(hardline$13, [].concat(path.map(print, "children"), path.map(print, "endComments")));
case "documentBody":
{
var children = join$12(hardline$13, path.map(print, "children")).parts;
var endComments = join$12(hardline$13, path.map(print, "endComments")).parts;
var separator = children.length === 0 || endComments.length === 0 ? "" : function (lastDescendantNode) {
return isNode(lastDescendantNode, ["blockFolded", "blockLiteral"]) ? lastDescendantNode.chomping === "keep" ? // there's already a newline printed at the end of blockValue (chomping=keep, lastDescendant=true)
"" : // an extra newline for better readability
concat$17([hardline$13, hardline$13]) : hardline$13;
}(getLastDescendantNode$1(node));
return concat$17([].concat(children, separator, endComments));
}
case "directive":
return concat$17(["%", join$12(" ", [node.name].concat(node.parameters))]);
case "comment":
return concat$17(["#", node.value]);
case "alias":
return concat$17(["*", node.value]);
case "tag":
return options.originalText.slice(node.position.start.offset, node.position.end.offset);
case "anchor":
return concat$17(["&", node.value]);
case "plain":
return printFlowScalarContent(node.type, options.originalText.slice(node.position.start.offset, node.position.end.offset), options);
case "quoteDouble":
case "quoteSingle":
{
var singleQuote = "'";
var doubleQuote = '"';
var raw = options.originalText.slice(node.position.start.offset + 1, node.position.end.offset - 1);
if (node.type === "quoteSingle" && raw.includes("\\") || node.type === "quoteDouble" && /\\[^"]/.test(raw)) {
// only quoteDouble can use escape chars
// and quoteSingle do not need to escape backslashes
var originalQuote = node.type === "quoteDouble" ? doubleQuote : singleQuote;
return concat$17([originalQuote, printFlowScalarContent(node.type, raw, options), originalQuote]);
} else if (raw.includes(doubleQuote)) {
return concat$17([singleQuote, printFlowScalarContent(node.type, node.type === "quoteDouble" ? raw // double quote needs to be escaped by backslash in quoteDouble
.replace(/\\"/g, doubleQuote).replace(/'/g, singleQuote.repeat(2)) : raw, options), singleQuote]);
}
if (raw.includes(singleQuote)) {
return concat$17([doubleQuote, printFlowScalarContent(node.type, node.type === "quoteSingle" ? // single quote needs to be escaped by 2 single quotes in quoteSingle
raw.replace(/''/g, singleQuote) : raw, options), doubleQuote]);
}
var quote = options.singleQuote ? singleQuote : doubleQuote;
return concat$17([quote, printFlowScalarContent(node.type, raw, options), quote]);
}
case "blockFolded":
case "blockLiteral":
{
var parentIndent = getAncestorCount(path, function (ancestorNode) {
return isNode(ancestorNode, ["sequence", "mapping"]);
});
var isLastDescendant = isLastDescendantNode(path);
return concat$17([node.type === "blockFolded" ? ">" : "|", node.indent === null ? "" : node.indent.toString(), node.chomping === "clip" ? "" : node.chomping === "keep" ? "+" : "-", hasIndicatorComment(node) ? concat$17([" ", path.call(print, "indicatorComment")]) : "", (node.indent === null ? dedent$4 : dedentToRoot$3)(align$3(node.indent === null ? options.tabWidth : node.indent - 1 + parentIndent, concat$17(getBlockValueLineContents(node, {
parentIndent: parentIndent,
isLastDescendant: isLastDescendant,
options: options
}).reduce(function (reduced, lineWords, index, lineContents) {
return reduced.concat(index === 0 ? hardline$13 : "", fill$6(join$12(line$11, lineWords).parts), index !== lineContents.length - 1 ? lineWords.length === 0 ? hardline$13 : markAsRoot$5(literalline$7) : node.chomping === "keep" && isLastDescendant ? lineWords.length === 0 ? dedentToRoot$3(hardline$13) : dedentToRoot$3(literalline$7) : "");
}, []))))]);
}
case "sequence":
return join$12(hardline$13, path.map(print, "children"));
case "sequenceItem":
return concat$17(["- ", align$3(2, !node.content ? "" : path.call(print, "content"))]);
case "mappingKey":
return !node.content ? "" : path.call(print, "content");
case "mappingValue":
return !node.content ? "" : path.call(print, "content");
case "mapping":
return join$12(hardline$13, path.map(print, "children"));
case "mappingItem":
case "flowMappingItem":
{
var isEmptyMappingKey = isEmptyNode(node.key);
var isEmptyMappingValue = isEmptyNode(node.value);
if (isEmptyMappingKey && isEmptyMappingValue) {
return concat$17([": "]);
}
var key = path.call(print, "key");
var value = path.call(print, "value");
if (isEmptyMappingValue) {
return node.type === "flowMappingItem" && parentNode.type === "flowMapping" ? key : node.type === "mappingItem" && isAbsolutelyPrintedAsSingleLineNode(node.key.content, options) && !hasTrailingComment$1(node.key.content) && (!parentNode.tag || parentNode.tag.value !== "tag:yaml.org,2002:set") ? concat$17([key, needsSpaceInFrontOfMappingValue(node) ? " " : "", ":"]) : concat$17(["? ", align$3(2, key)]);
}
if (isEmptyMappingKey) {
return concat$17([": ", align$3(2, value)]);
}
var groupId = Symbol("mappingKey");
var forceExplicitKey = hasLeadingComments(node.value) || !isInlineNode(node.key.content);
return forceExplicitKey ? concat$17(["? ", align$3(2, key), hardline$13, join$12("", path.map(print, "value", "leadingComments").map(function (comment) {
return concat$17([comment, hardline$13]);
})), ": ", align$3(2, value)]) : // force singleline
isSingleLineNode(node.key.content) && !hasLeadingComments(node.key.content) && !hasMiddleComments(node.key.content) && !hasTrailingComment$1(node.key.content) && !hasEndComments(node.key) && !hasLeadingComments(node.value.content) && !hasMiddleComments(node.value.content) && !hasEndComments(node.value) && isAbsolutelyPrintedAsSingleLineNode(node.value.content, options) ? concat$17([key, needsSpaceInFrontOfMappingValue(node) ? " " : "", ": ", value]) : conditionalGroup$2([concat$17([group$16(concat$17([ifBreak$8("? "), group$16(align$3(2, key), {
id: groupId
})])), ifBreak$8(concat$17([hardline$13, ": ", align$3(2, value)]), indent(concat$17([needsSpaceInFrontOfMappingValue(node) ? " " : "", ":", hasLeadingComments(node.value.content) || hasEndComments(node.value) && node.value.content && !isNode(node.value.content, ["mapping", "sequence"]) || parentNode.type === "mapping" && hasTrailingComment$1(node.key.content) && isInlineNode(node.value.content) || isNode(node.value.content, ["mapping", "sequence"]) && node.value.content.tag === null && node.value.content.anchor === null ? hardline$13 : !node.value.content ? "" : line$11, value])), {
groupId: groupId
})])]);
}
case "flowMapping":
case "flowSequence":
{
var openMarker = node.type === "flowMapping" ? "{" : "[";
var closeMarker = node.type === "flowMapping" ? "}" : "]";
var bracketSpacing = node.type === "flowMapping" && node.children.length !== 0 && options.bracketSpacing ? line$11 : softline$8;
var isLastItemEmptyMappingItem = node.children.length !== 0 && function (lastItem) {
return lastItem.type === "flowMappingItem" && isEmptyNode(lastItem.key) && isEmptyNode(lastItem.value);
}(getLast$5(node.children));
return concat$17([openMarker, indent(concat$17([bracketSpacing, concat$17(path.map(function (childPath, index) {
return concat$17([print(childPath), index === node.children.length - 1 ? "" : concat$17([",", line$11, node.children[index].position.start.line !== node.children[index + 1].position.start.line ? printNextEmptyLine(childPath, options.originalText) : ""])]);
}, "children")), ifBreak$8(",", "")])), isLastItemEmptyMappingItem ? "" : bracketSpacing, closeMarker]);
}
case "flowSequenceItem":
return path.call(print, "content");
// istanbul ignore next
default:
throw new Error("Unexpected node type ".concat(node.type));
}
function indent(doc$$2) {
return docBuilders$3.align(" ".repeat(options.tabWidth), doc$$2);
}
}
function align$3(n, doc$$2) {
return typeof n === "number" && n > 0 ? docBuilders$3.align(" ".repeat(n), doc$$2) : docBuilders$3.align(n, doc$$2);
}
function isInlineNode(node) {
if (!node) {
return true;
}
switch (node.type) {
case "plain":
case "quoteDouble":
case "quoteSingle":
case "alias":
case "flowMapping":
case "flowSequence":
return true;
default:
return false;
}
}
function isSingleLineNode(node) {
if (!node) {
return true;
}
switch (node.type) {
case "plain":
case "quoteDouble":
case "quoteSingle":
return node.position.start.line === node.position.end.line;
case "alias":
return true;
default:
return false;
}
}
function shouldPrintDocumentBody(document) {
return document.body.children.length !== 0 || hasEndComments(document.body);
}
function shouldPrintDocumentEndMarker(document, nextDocument) {
return (
/**
*... # trailingComment
*/
hasTrailingComment$1(document) || nextDocument && (
/**
* ...
* %DIRECTIVE
* ---
*/
nextDocument.head.children.length !== 0 ||
/**
* ...
* # endComment
* ---
*/
hasEndComments(nextDocument.head))
);
}
function shouldPrintDocumentHeadEndMarker(document, nextDocument, root, options) {
if (
/**
* ---
* preserve the first document head end marker
*/
root.children[0] === document && /---(\s|$)/.test(options.originalText.slice(options.locStart(document), options.locStart(document) + 4)) ||
/**
* %DIRECTIVE
* ---
*/
document.head.children.length !== 0 ||
/**
* # end comment
* ---
*/
hasEndComments(document.head) ||
/**
* --- # trailing comment
*/
hasTrailingComment$1(document.head)) {
return "head";
}
if (shouldPrintDocumentEndMarker(document, nextDocument)) {
return false;
}
return nextDocument ? "root" : false;
}
function isAbsolutelyPrintedAsSingleLineNode(node, options) {
if (!node) {
return true;
}
switch (node.type) {
case "plain":
case "quoteSingle":
case "quoteDouble":
break;
case "alias":
return true;
default:
return false;
}
if (options.proseWrap === "preserve") {
return node.position.start.line === node.position.end.line;
}
if ( // backslash-newline
/\\$/m.test(options.originalText.slice(node.position.start.offset, node.position.end.offset))) {
return false;
}
switch (options.proseWrap) {
case "never":
return node.value.indexOf("\n") === -1;
case "always":
return !/[\n ]/.test(node.value);
// istanbul ignore next
default:
return false;
}
}
function needsSpaceInFrontOfMappingValue(node) {
return node.key.content && node.key.content.type === "alias";
}
function printNextEmptyLine(path, originalText) {
var node = path.getValue();
var root = path.stack[0];
root.isNextEmptyLinePrintedChecklist = root.isNextEmptyLinePrintedChecklist || [];
if (!root.isNextEmptyLinePrintedChecklist[node.position.end.line]) {
if (isNextLineEmpty$5(node, originalText)) {
root.isNextEmptyLinePrintedChecklist[node.position.end.line] = true;
return softline$8;
}
}
return "";
}
function printFlowScalarContent(nodeType, content, options) {
var lineContents = getFlowScalarLineContents(nodeType, content, options);
return join$12(hardline$13, lineContents.map(function (lineContentWords) {
return fill$6(join$12(line$11, lineContentWords).parts);
}));
}
function clean$11(node, newNode
/*, parent */
) {
if (isNode(newNode)) {
delete newNode.position;
switch (newNode.type) {
case "comment":
// insert pragma
if (isPragma(newNode.value)) {
return null;
}
break;
case "quoteDouble":
case "quoteSingle":
newNode.type = "quote";
break;
}
}
}
var printerYaml = {
preprocess: preprocess$6,
print: genericPrint$6,
massageAstNode: clean$11,
insertPragma: insertPragma$8
};
var options$18 = {
bracketSpacing: commonOptions.bracketSpacing,
singleQuote: commonOptions.singleQuote,
proseWrap: commonOptions.proseWrap
};
var name$16 = "YAML";
var type$15 = "data";
var tmScope$15 = "source.yaml";
var aliases$6 = ["yml"];
var extensions$15 = [".yml", ".mir", ".reek", ".rviz", ".sublime-syntax", ".syntax", ".yaml", ".yaml-tmlanguage", ".yml.mysql"];
var filenames$3 = [".clang-format", ".clang-tidy", ".gemrc", "glide.lock"];
var aceMode$15 = "yaml";
var codemirrorMode$11 = "yaml";
var codemirrorMimeType$11 = "text/x-yaml";
var languageId$15 = 407;
var yaml = {
name: name$16,
type: type$15,
tmScope: tmScope$15,
aliases: aliases$6,
extensions: extensions$15,
filenames: filenames$3,
aceMode: aceMode$15,
codemirrorMode: codemirrorMode$11,
codemirrorMimeType: codemirrorMimeType$11,
languageId: languageId$15
};
var yaml$1 = Object.freeze({
name: name$16,
type: type$15,
tmScope: tmScope$15,
aliases: aliases$6,
extensions: extensions$15,
filenames: filenames$3,
aceMode: aceMode$15,
codemirrorMode: codemirrorMode$11,
codemirrorMimeType: codemirrorMimeType$11,
languageId: languageId$15,
default: yaml
});
var require$$0$29 = ( yaml$1 && yaml ) || yaml$1;
var languages$6 = [createLanguage(require$$0$29, {
override: {
since: "1.14.0",
parsers: ["yaml"],
vscodeLanguageIds: ["yaml"]
}
})];
var languageYaml = {
languages: languages$6,
printers: {
yaml: printerYaml
},
options: options$18
};
var version = require$$0.version;
var getSupportInfo = support.getSupportInfo;
var internalPlugins = [languageCss, languageGraphql, languageHandlebars, languageHtml, languageJs, languageMarkdown, languageYaml];
var isArray = Array.isArray || function (arr) {
return Object.prototype.toString.call(arr) === "[object Array]";
}; // Luckily `opts` is always the 2nd argument
function withPlugins(fn) {
return function () {
var args = Array.from(arguments);
var plugins = args[1] && args[1].plugins || [];
if (!isArray(plugins)) {
plugins = Object.values(plugins);
}
args[1] = Object.assign({}, args[1], {
plugins: internalPlugins.concat(plugins)
});
return fn.apply(null, args);
};
}
var formatWithCursor = withPlugins(core.formatWithCursor);
var standalone$2 = {
formatWithCursor: formatWithCursor,
format: function format(text, opts) {
return formatWithCursor(text, opts).formatted;
},
check: function check(text, opts) {
var formatted = formatWithCursor(text, opts).formatted;
return formatted === text;
},
doc: doc,
getSupportInfo: withPlugins(getSupportInfo),
version: version,
util: utilShared,
__debug: {
parse: withPlugins(core.parse),
formatAST: withPlugins(core.formatAST),
formatDoc: withPlugins(core.formatDoc),
printToDoc: withPlugins(core.printToDoc),
printDocToString: withPlugins(core.printDocToString)
}
};
var standalone = standalone$2;
return standalone;
})));