!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$1(concat$4(["<", path.call(print, "name"), path.call(print, "typeParameters"), concat$4([indent$2(concat$4(path.map(function (attr) {
return concat$4([line$3, print(attr)]);
}, "attributes"))), _n.selfClosing ? line$3 : bracketSameLine ? ">" : softline$1]), _n.selfClosing ? "/>" : bracketSameLine ? "" : ">"]), {
shouldBreak: _shouldBreak
});
}
case "JSXClosingElement":
return concat$4(["", path.call(print, "name"), ">"]);
case "JSXOpeningFragment":
case "JSXClosingFragment":
case "TSJsxOpeningFragment":
case "TSJsxClosingFragment":
{
var hasComment = n.comments && n.comments.length;
var hasOwnLineComment = hasComment && !n.comments.every(comments$3.isBlockComment);
var isOpeningFragment = n.type === "JSXOpeningFragment" || n.type === "TSJsxOpeningFragment";
return concat$4([isOpeningFragment ? "<" : "", indent$2(concat$4([hasOwnLineComment ? hardline$3 : hasComment && !isOpeningFragment ? " " : "", comments.printDanglingComments(path, options, true)])), hasOwnLineComment ? hardline$3 : "", ">"]);
}
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$4([comments.printDanglingComments(path, options,
/* sameIndent */
!requiresHardline), requiresHardline ? hardline$3 : ""]);
}
case "ClassBody":
if (!n.comments && n.body.length === 0) {
return "{}";
}
return concat$4(["{", n.body.length > 0 ? indent$2(concat$4([hardline$3, path.call(function (bodyPath) {
return printStatementSequence(bodyPath, options, print);
}, "body")])) : comments.printDanglingComments(path, options), hardline$3, "}"]);
case "ClassProperty":
case "TSAbstractClassProperty":
case "ClassPrivateProperty":
{
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(printTypeAnnotation(path, options, print));
if (n.value) {
parts.push(" =", printAssignmentRight(n.key, n.value, path.call(print, "value"), options));
}
parts.push(semi);
return group$1(concat$4(parts));
}
case "ClassDeclaration":
case "ClassExpression":
case "TSAbstractClassDeclaration":
if (isNodeStartingWithDeclare(n, options)) {
parts.push("declare ");
}
parts.push(concat$4(printClass(path, options, print)));
return concat$4(parts);
case "TSInterfaceHeritage":
parts.push(path.call(print, "id"));
if (n.typeParameters) {
parts.push(path.call(print, "typeParameters"));
}
return concat$4(parts);
case "TemplateElement":
return join$2(literalline$1, n.value.raw.split(/\r?\n/g));
case "TemplateLiteral":
{
var expressions = path.map(print, "expressions");
var _parentNode = path.getParentNode();
/**
* 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)$/;
if (_parentNode.type === "TaggedTemplateExpression" && _parentNode.quasi === n && _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))) {
/**
* a | b | expected
* ${1} | ${1} | ${2}
* ${1} | ${2} | ${3}
* ${2} | ${1} | ${3}
*/
var headerNames = n.quasis[0].value.raw.trim().split(/\s*\|\s*/);
if (headerNames.length > 1 || headerNames.some(function (headerName) {
return headerName.length !== 0;
})) {
var stringifiedExpressions = expressions.map(function (doc$$2) {
return "${" + printDocToString$1(doc$$2, Object.assign({}, options, {
printWidth: Infinity
})).formatted + "}";
});
var tableBody = [{
hasLineBreak: false,
cells: []
}];
for (var _i = 1; _i < n.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 (n.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$1(cell));
});
});
parts.push("`", indent$2(concat$4([hardline$3, join$2(hardline$3, table.map(function (row) {
return join$2(" | ", row.cells.map(function (cell, index) {
return row.hasLineBreak ? cell : cell + " ".repeat(maxColumnWidths[index] - getStringWidth$1(cell));
}));
}))])), hardline$3, "`");
return concat$4(parts);
}
}
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 indentSize = getIndentSize$1(childPath.getValue().value.raw, tabWidth);
var _printed = expressions[i];
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") {
_printed = concat$4([indent$2(concat$4([softline$1, _printed])), softline$1]);
}
var aligned = addAlignmentToDoc$2(_printed, indentSize, tabWidth);
parts.push(group$1(concat$4(["${", aligned, lineSuffixBoundary$1, "}"])));
}
}, "quasis");
parts.push("`");
return concat$4(parts);
}
// These types are unprintable because they serve as abstract
// supertypes for other (printable) types.
case "TaggedTemplateExpression":
return concat$4([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$1(concat$4(["[", indent$2(concat$4([softline$1, printArrayItems(path, options, typesField, print)])), // TypeScript doesn't support trailing commas in tuple types
n.type === "TSTupleType" ? "" : ifBreak$1(shouldPrintComma(options) ? "," : ""), comments.printDanglingComments(path, options,
/* sameIndent */
true), softline$1, "]"]));
}
case "ExistsTypeAnnotation":
return "*";
case "EmptyTypeAnnotation":
return "empty";
case "AnyTypeAnnotation":
return "any";
case "MixedTypeAnnotation":
return "mixed";
case "ArrayTypeAnnotation":
return concat$4([path.call(print, "elementType"), "[]"]);
case "BooleanTypeAnnotation":
return "boolean";
case "BooleanLiteralTypeAnnotation":
return "" + n.value;
case "DeclareClass":
return printFlowDeclaration(path, printClass(path, options, print));
case "DeclareFunction":
// For TypeScript the DeclareFunction node shares the AST
// structure with FunctionDeclaration
if (n.params) {
return concat$4(["declare ", printFunctionDeclaration(path, print, options), semi]);
}
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$4(["declare export * from ", path.call(print, "source")]);
case "DeclareExportDeclaration":
return concat$4(["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$4(parts);
}
case "FunctionTypeAnnotation":
case "TSFunctionType":
{
// FunctionTypeAnnotation is ambiguous:
// declare function foo(a: B): void; OR
// var A: (a: B) => void;
var _parent6 = path.getParentNode(0);
var _parentParent2 = path.getParentNode(1);
var _parentParentParent = path.getParentNode(2);
var isArrowFunctionTypeAnnotation = n.type === "TSFunctionType" || !(_parent6.type === "ObjectTypeProperty" && !getFlowVariance(_parent6) && !_parent6.optional && options.locStart(_parent6) === options.locStart(n) || _parent6.type === "ObjectTypeCallProperty" || _parentParentParent && _parentParentParent.type === "DeclareFunction");
var needsColon = isArrowFunctionTypeAnnotation && (_parent6.type === "TypeAnnotation" || _parent6.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 && (_parent6.type === "TypeAnnotation" || _parent6.type === "TSTypeAnnotation") && _parentParent2.type === "ArrowFunctionExpression";
if (isObjectTypePropertyAFunction(_parent6, 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$1(concat$4(parts));
}
case "FunctionTypeParam":
return concat$4([path.call(print, "name"), printOptionalToken(path), n.name ? ": " : "", path.call(print, "typeAnnotation")]);
case "GenericTypeAnnotation":
return concat$4([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$1(indent$2(concat$4([line$3, "extends ", join$2(", ", path.map(print, "extends"))]))));
}
parts.push(" ", path.call(print, "body"));
return group$1(concat$4(parts));
}
case "ClassImplements":
case "InterfaceExtends":
return concat$4([path.call(print, "id"), path.call(print, "typeParameters")]);
case "TSIntersectionType":
case "IntersectionTypeAnnotation":
{
var types = path.map(print, "types");
var result = [];
var wasIndented = false;
for (var _i2 = 0; _i2 < types.length; ++_i2) {
if (_i2 === 0) {
result.push(types[_i2]);
} else if (isObjectType(n.types[_i2 - 1]) && isObjectType(n.types[_i2])) {
// If both are objects, don't indent
result.push(concat$4([" & ", wasIndented ? indent$2(types[_i2]) : types[_i2]]));
} else if (!isObjectType(n.types[_i2 - 1]) && !isObjectType(n.types[_i2])) {
// If no object is involved, go to the next line if it breaks
result.push(indent$2(concat$4([" &", line$3, types[_i2]])));
} else {
// If you go from object to non-object or vis-versa, then inline it
if (_i2 > 1) {
wasIndented = true;
}
result.push(" & ", _i2 > 1 ? indent$2(types[_i2]) : types[_i2]);
}
}
return group$1(concat$4(result));
}
case "TSUnionType":
case "UnionTypeAnnotation":
{
// single-line variation
// A | B | C
// multi-line variation
// | A
// | B
// | C
var _parent7 = path.getParentNode();
var _parentParent3 = path.getParentNode(1); // If there's a leading comment, the parent is doing the indentation
var shouldIndent = _parent7.type !== "TypeParameterInstantiation" && _parent7.type !== "TSTypeParameterInstantiation" && _parent7.type !== "GenericTypeAnnotation" && _parent7.type !== "TSTypeReference" && !(_parent7.type === "FunctionTypeParam" && !_parent7.name) && _parentParent3.type !== "TSTypeAssertionExpression" && !((_parent7.type === "TypeAlias" || _parent7.type === "VariableDeclarator") && 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 _printed2 = 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$2(" | ", _printed2);
}
var code = concat$4([ifBreak$1(concat$4([shouldIndent ? line$3 : "", "| "])), join$2(concat$4([line$3, "| "]), _printed2)]);
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$1(concat$4([indent$2(code), softline$1]));
}
return group$1(shouldIndent ? indent$2(code) : code);
}
case "NullableTypeAnnotation":
return concat$4(["?", 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$4(parts);
case "ObjectTypeIndexer":
{
var _variance = getFlowVariance(n);
return concat$4([_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$4([modifier, isGetterOrSetter(n) ? n.kind + " " : "", _variance2 || "", printPropertyKey(path, options, print), printOptionalToken(path), isFunctionNotation(n, options) ? "" : ": ", path.call(print, "value")]);
}
case "QualifiedTypeIdentifier":
return concat$4([path.call(print, "qualification"), ".", path.call(print, "id")]);
case "StringLiteralTypeAnnotation":
return nodeStr(n, options);
case "NumberLiteralTypeAnnotation":
assert.strictEqual(_typeof(n.value), "number");
if (n.extra != null) {
return printNumber$1(n.extra.raw);
}
return printNumber$1(n.raw);
case "StringTypeAnnotation":
return "string";
case "DeclareTypeAlias":
case "TypeAlias":
{
if (n.type === "DeclareTypeAlias" || isNodeStartingWithDeclare(n, options)) {
parts.push("declare ");
}
var _printed3 = printAssignmentRight(n.id, n.right, path.call(print, "right"), options);
parts.push("type ", path.call(print, "id"), path.call(print, "typeParameters"), " =", _printed3, semi);
return group$1(concat$4(parts));
}
case "TypeCastExpression":
return concat$4(["(", path.call(print, "expression"), ": ", path.call(print, "typeAnnotation"), ")"]);
case "TypeParameterDeclaration":
case "TypeParameterInstantiation":
case "TSTypeParameterDeclaration":
case "TSTypeParameterInstantiation":
return printTypeParameters(path, options, print, "params");
case "TSTypeParameter":
case "TypeParameter":
{
var _parent8 = path.getParentNode();
if (_parent8.type === "TSMappedType") {
parts.push("[", path.call(print, "name"));
if (n.constraint) {
parts.push(" in ", path.call(print, "constraint"));
}
parts.push("]");
return concat$4(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"));
}
return concat$4(parts);
}
case "TypeofTypeAnnotation":
return concat$4(["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$4(["%checks(", path.call(print, "value"), ")"]);
case "TSAbstractKeyword":
return "abstract";
case "TSAnyKeyword":
return "any";
case "TSAsyncKeyword":
return "async";
case "TSBooleanKeyword":
return "boolean";
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 "TSVoidKeyword":
return "void";
case "TSAsExpression":
return concat$4([path.call(print, "expression"), " as ", path.call(print, "typeAnnotation")]);
case "TSArrayType":
return concat$4([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$4(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$4(parts);
case "TSTypeReference":
return concat$4([path.call(print, "typeName"), printTypeParameters(path, options, print, "typeParameters")]);
case "TSTypeQuery":
return concat$4(["typeof ", path.call(print, "exprName")]);
case "TSParenthesizedType":
{
return path.call(print, "typeAnnotation");
}
case "TSIndexSignature":
{
var _parent9 = path.getParentNode();
return concat$4([n.export ? "export " : "", n.accessibility ? concat$4([n.accessibility, " "]) : "", n.static ? "static " : "", n.readonly ? "readonly " : "", "[", path.call(print, "index"), "]: ", path.call(print, "typeAnnotation"), _parent9.type === "ClassBody" ? semi : ""]);
}
case "TSTypePredicate":
return concat$4([path.call(print, "parameterName"), " is ", path.call(print, "typeAnnotation")]);
case "TSNonNullExpression":
return concat$4([path.call(print, "expression"), "!"]);
case "TSThisType":
return "this";
case "TSLastTypeNode":
// TSImportType
return concat$4([!n.isTypeOf ? "" : "typeof ", "import(", path.call(print, "argument"), ")", !n.qualifier ? "" : concat$4([".", path.call(print, "qualifier")]), printTypeParameters(path, options, print, "typeParameters")]);
case "TSLiteralType":
return path.call(print, "literal");
case "TSIndexedAccessType":
return concat$4([path.call(print, "objectType"), "[", path.call(print, "indexType"), "]"]);
case "TSConstructSignature":
case "TSConstructorType":
case "TSCallSignature":
{
if (n.type !== "TSCallSignature") {
parts.push("new ");
}
parts.push(group$1(printFunctionParams(path, print, options,
/* expandArg */
false,
/* printTypeParams */
true)));
if (n.typeAnnotation) {
var isType = n.type === "TSConstructorType";
parts.push(isType ? " => " : ": ", path.call(print, "typeAnnotation"));
}
return concat$4(parts);
}
case "TSTypeOperator":
return concat$4([n.operator, " ", path.call(print, "typeAnnotation")]);
case "TSMappedType":
return group$1(concat$4(["{", indent$2(concat$4([options.bracketSpacing ? line$3 : softline$1, n.readonlyToken ? concat$4([getTypeScriptMappedTypeModifier(n.readonlyToken, "readonly"), " "]) : "", printTypeScriptModifiers(path, options, print), path.call(print, "typeParameter"), n.questionToken ? getTypeScriptMappedTypeModifier(n.questionToken, "?") : "", ": ", path.call(print, "typeAnnotation")])), comments.printDanglingComments(path, options,
/* sameIndent */
true), options.bracketSpacing ? line$3 : softline$1, "}"]));
case "TSMethodSignature":
parts.push(n.accessibility ? concat$4([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.typeAnnotation) {
parts.push(": ", path.call(print, "typeAnnotation"));
}
return group$1(concat$4(parts));
case "TSNamespaceExportDeclaration":
parts.push("export as namespace ", path.call(print, "name"));
if (options.semi) {
parts.push(";");
}
return group$1(concat$4(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$1(concat$4(["{", comments.printDanglingComments(path, options), softline$1, "}"])));
} else {
parts.push(group$1(concat$4(["{", indent$2(concat$4([hardline$3, printArrayItems(path, options, "members", print), shouldPrintComma(options, "es5") ? "," : ""])), comments.printDanglingComments(path, options,
/* sameIndent */
true), hardline$3, "}"])));
}
return concat$4(parts);
case "TSEnumMember":
parts.push(path.call(print, "id"));
if (n.initializer) {
parts.push(" = ", path.call(print, "initializer"));
}
return concat$4(parts);
case "TSImportEqualsDeclaration":
parts.push(printTypeScriptModifiers(path, options, print), "import ", path.call(print, "name"), " = ", path.call(print, "moduleReference"));
if (options.semi) {
parts.push(";");
}
return group$1(concat$4(parts));
case "TSExternalModuleReference":
return concat$4(["require(", path.call(print, "expression"), ")"]);
case "TSModuleDeclaration":
{
var _parent10 = path.getParentNode();
var isExternalModule = isLiteral(n.id);
var parentIsDeclaration = _parent10.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)); // Global declaration looks like this:
// (declare)? global { ... }
var isGlobalDeclaration = n.id.type === "Identifier" && n.id.name === "global" && !/namespace|module/.test(options.originalText.slice(options.locStart(n), options.locStart(n.id)));
if (!isGlobalDeclaration) {
parts.push(isExternalModule ? "module " : "namespace ");
}
}
parts.push(path.call(print, "id"));
if (bodyIsDeclaration) {
parts.push(path.call(print, "body"));
} else if (n.body) {
parts.push(" {", indent$2(concat$4([line$3, path.call(function (bodyPath) {
return comments.printDanglingComments(bodyPath, options, true);
}, "body"), group$1(path.call(print, "body"))])), line$3, "}");
} else {
parts.push(semi);
}
return concat$4(parts);
}
case "TSModuleBlock":
return path.call(function (bodyPath) {
return printStatementSequence(bodyPath, options, print);
}, "body");
case "PrivateName":
return concat$4(["#", path.call(print, "id")]);
case "TSConditionalType":
return formatTernaryOperator(path, options, print, {
beforeParts: function beforeParts() {
return [path.call(print, "checkType"), " ", "extends", " ", path.call(print, "extendsType")];
},
shouldCheckJsx: false,
operatorName: "TSConditionalType",
consequentNode: "trueType",
alternateNode: "falseType",
testNode: "checkType",
breakNested: false
});
case "TSInferType":
return concat$4(["infer", " ", path.call(print, "typeParameter")]);
case "InterpreterDirective":
parts.push("#!", n.value, hardline$3);
if (isNextLineEmpty$2(options.originalText, n, options)) {
parts.push(hardline$3);
}
return concat$4(parts);
default:
/* istanbul ignore next */
throw new Error("unknown type: " + JSON.stringify(n.type));
}
}
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$2(text, stmt, options) && !isLastStatement(stmtPath)) {
parts.push(hardline$3);
}
printed.push(concat$4(parts));
});
return join$2(hardline$3, printed);
}
function printPropertyKey(path, options, print) {
var node = path.getNode();
var key = node.key;
if (key.type === "Identifier" && !node.computed && options.parser === "json") {
// a -> "a"
return path.call(function (keyPath) {
return comments.printComments(keyPath, function () {
return JSON.stringify(key.name);
}, options);
}, "key");
}
if (isStringLiteral(key) && isIdentifierName(key.value) && !node.computed && options.parser !== "json" && !(options.parser === "typescript" && node.type === "ClassProperty")) {
// '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.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.ok(kind === "get" || kind === "set");
parts.push(kind, " ");
}
var key = printPropertyKey(path, options, print);
if (node.computed) {
key = concat$4(["[", key, "]"]);
}
parts.push(key, concat$4(path.call(function (valuePath) {
return [printFunctionTypeParameters(valuePath, options, print), group$1(concat$4([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$4(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 === "TSTypeAssertionExpression" || arg.type === "TSAsExpression" || arg.type === "FunctionExpression" || arg.type === "ArrowFunctionExpression" && !arg.returnType && (arg.body.type === "BlockStatement" || arg.body.type === "ArrowFunctionExpression" || arg.body.type === "ObjectExpression" || arg.body.type === "ArrayExpression" || arg.body.type === "CallExpression" || arg.body.type === "OptionalCallExpression" || isJSXNode(arg.body));
}
function shouldGroupLastArg(args) {
var lastArg = getLast$4(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") && !couldGroupArg(secondArg);
}
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
]);
function isFunctionCompositionFunction(node) {
switch (node.type) {
case "OptionalMemberExpression":
case "MemberExpression":
{
return isFunctionCompositionFunction(node.property);
}
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$4(["(", comments.printDanglingComments(path, options,
/* sameIndent */
true), ")"]);
}
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$2(options.originalText, arg, options)) {
if (index === 0) {
hasEmptyLineFollowingFirstArg = true;
}
anyArgEmptyLine = true;
parts.push(",", hardline$3, hardline$3);
} else {
parts.push(",", line$3);
}
return concat$4(parts);
}, "arguments");
var maybeTrailingComma = shouldPrintComma(options, "all") ? "," : "";
function allArgsBrokenOut() {
return group$1(concat$4(["(", indent$2(concat$4([line$3, concat$4(printedArguments)])), maybeTrailingComma, line$3, ")"]), {
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$4([argPath.call(function (p) {
return print(p, {
expandFirstArg: true
});
}), printedArguments.length > 1 ? "," : "", hasEmptyLineFollowingFirstArg ? hardline$3 : line$3, hasEmptyLineFollowingFirstArg ? hardline$3 : ""])].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$4([somePrintedArgumentsWillBreak ? breakParent$2 : "", conditionalGroup$1([concat$4([ifBreak$1(indent$2(concat$4(["(", softline$1, concat$4(printedExpanded)])), concat$4(["(", concat$4(printedExpanded)])), somePrintedArgumentsWillBreak ? concat$4([ifBreak$1(maybeTrailingComma), softline$1]) : "", ")"]), shouldGroupFirst ? concat$4(["(", group$1(printedExpanded[0], {
shouldBreak: true
}), concat$4(printedExpanded.slice(1)), ")"]) : concat$4(["(", concat$4(printedArguments.slice(0, -1)), group$1(getLast$4(printedExpanded), {
shouldBreak: true
}), ")"]), allArgsBrokenOut()], {
shouldBreak: shouldBreak
})]);
}
return group$1(concat$4(["(", indent$2(concat$4([softline$1, concat$4(printedArguments)])), ifBreak$1(shouldPrintComma(options, "all") ? "," : ""), softline$1, ")"]), {
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$4([" /*: ", path.call(print, "typeAnnotation"), " */"]);
}
return concat$4([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 paramsField = fun.parameters ? "parameters" : "params";
var typeParams = printTypeParams ? printFunctionTypeParameters(path, options, print) : "";
var printed = [];
if (fun[paramsField]) {
printed = path.map(print, paramsField);
}
if (fun.rest) {
printed.push(concat$4(["...", path.call(print, "rest")]));
}
if (printed.length === 0) {
return concat$4([typeParams, "(", comments.printDanglingComments(path, options,
/* sameIndent */
true, function (comment) {
return getNextNonSpaceNonCommentCharacter$1(options.originalText, comment, options.locEnd) === ")";
}), ")"]);
}
var lastParam = getLast$4(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 (expandArg && !(fun[paramsField] && fun[paramsField].some(function (n) {
return n.comments;
}))) {
return group$1(concat$4([removeLines$1(typeParams), "(", join$2(", ", printed.map(removeLines$1)), ")"]));
} // Single object destructuring should hug
//
// function({
// a,
// b,
// c
// }) {}
if (shouldHugArguments(fun)) {
return concat$4([typeParams, "(", join$2(", ", printed), ")"]);
}
var parent = path.getParentNode(); // don't break in specs, eg; `it("should maintain parens around done even when long", (done) => {})`
if (isTestCall(parent)) {
return concat$4([typeParams, "(", join$2(", ", printed), ")"]);
}
var flowTypeAnnotations = ["AnyTypeAnnotation", "NullLiteralTypeAnnotation", "GenericTypeAnnotation", "ThisTypeAnnotation", "NumberTypeAnnotation", "VoidTypeAnnotation", "EmptyTypeAnnotation", "MixedTypeAnnotation", "BooleanTypeAnnotation", "BooleanLiteralTypeAnnotation", "StringTypeAnnotation"];
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 && flowTypeAnnotations.indexOf(fun[paramsField][0].typeAnnotation.type) !== -1 && !(fun[paramsField][0].typeAnnotation.type === "GenericTypeAnnotation" && fun[paramsField][0].typeAnnotation.typeParameters) && !fun.rest;
if (isFlowShorthandWithOneArg) {
if (options.arrowParens === "always") {
return concat$4(["(", concat$4(printed), ")"]);
}
return concat$4(printed);
}
var canHaveTrailingComma = !(lastParam && lastParam.type === "RestElement") && !fun.rest;
return concat$4([typeParams, "(", indent$2(concat$4([softline$1, join$2(concat$4([",", line$3]), printed)])), ifBreak$1(canHaveTrailingComma && shouldPrintComma(options, "all") ? "," : ""), softline$1, ")"]);
}
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$1(concat$4([printFunctionParams(path, print, options), printReturnType(path, print, options)])), n.body ? " " : "", path.call(print, "body"));
return concat$4(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$1(concat$4([printFunctionParams(path, print, options), printReturnType(path, print, options)])), " ", path.call(print, "body"));
return concat$4(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$4([" /*: ", 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$4(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$3);
}
if (decl.declaration) {
parts.push(path.call(print, "declaration"));
if (isDefault && decl.declaration.type !== "ClassDeclaration" && decl.declaration.type !== "FunctionDeclaration" && decl.declaration.type !== "TSAbstractClassDeclaration" && decl.declaration.type !== "TSInterfaceDeclaration" && decl.declaration.type !== "DeclareClass" && decl.declaration.type !== "DeclareFunction") {
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$4(["* 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$4(defaultSpecifiers), concat$4([isDefaultFollowed ? ", " : ""]), concat$4(namespaceSpecifiers), concat$4([isNamespaceFollowed ? ", " : ""]), specifiers.length !== 0 ? group$1(concat$4(["{", indent$2(concat$4([options.bracketSpacing ? line$3 : softline$1, join$2(concat$4([",", line$3]), specifiers)])), ifBreak$1(shouldPrintComma(options) ? "," : ""), options.bracketSpacing ? line$3 : softline$1, "}"])) : "");
} else {
parts.push("{}");
}
if (decl.source) {
parts.push(" from ", path.call(print, "source"));
}
parts.push(semi);
}
return concat$4(parts);
}
function printFlowDeclaration(path, parts) {
var parentExportDecl = getParentExportDeclaration$1(path);
if (parentExportDecl) {
assert.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$4(parts);
}
function getFlowVariance(path) {
if (!path.variance) {
return null;
} // Babylon 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$4([join$2(" ", 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$4(["<", join$2(", ", path.map(print, paramsKey)), ">"]);
}
return group$1(concat$4(["<", indent$2(concat$4([softline$1, join$2(concat$4([",", line$3]), path.map(print, paramsKey))])), ifBreak$1(options.parser !== "typescript" && shouldPrintComma(options, "all") ? "," : ""), softline$1, ">"]));
}
function printClass(path, options, print) {
var n = path.getValue();
var parts = [];
if (n.type === "TSAbstractClassDeclaration") {
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$4(["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$4([" ", path.call(function (superClass) {
return comments.printComments(superClass, function () {
return printed;
}, options);
}, "superClass")]));
} else {
partsGroup.push(group$1(concat$4([line$3, 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$2(", ", path.map(print, "extends")));
}
if (n["mixins"] && n["mixins"].length > 0) {
partsGroup.push(line$3, "mixins ", group$1(indent$2(join$2(concat$4([",", line$3]), path.map(print, "mixins")))));
}
if (n["implements"] && n["implements"].length > 0) {
partsGroup.push(line$3, "implements", group$1(indent$2(concat$4([line$3, join$2(concat$4([",", line$3]), path.map(print, "implements"))]))));
}
if (partsGroup.length > 0) {
parts.push(group$1(indent$2(concat$4(partsGroup))));
}
if (n.body && n.body.comments && hasLeadingOwnLineComment(options.originalText, n.body, options)) {
parts.push(hardline$3);
} 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$4([optional, ".", property]);
}
if (!n.property || isNumericLiteral(n.property)) {
return concat$4([optional, "[", property, "]"]);
}
return group$1(concat$4([optional, "[", indent$2(concat$4([softline$1, property])), softline$1, "]"]));
}
function printBindExpressionCallee(path, options, print) {
return concat$4(["::", 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$2(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$4([comments.printComments(path, function () {
return concat$4([printOptionalToken(path), printFunctionTypeParameters(path, options, print), printArgumentsList(path, options, print)]);
}, options), shouldInsertEmptyLineAfter(node) ? hardline$3 : ""])
});
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$4([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$4(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 result = [];
for (var _i3 = 0; _i3 < printedGroup.length; _i3++) {
// Checks if the next node (i.e. the parent node) needs parens
// and print accordingl y
if (printedGroup[_i3 + 1] && printedGroup[_i3 + 1].needsParens) {
result.push("(", printedGroup[_i3].printed, printedGroup[_i3 + 1].printed, ")");
_i3++;
} else {
result.push(printedGroup[_i3].printed);
}
}
return concat$4(result);
}
function printIndentedGroup(groups) {
if (groups.length === 0) {
return "";
}
return indent$2(group$1(concat$4([hardline$3, join$2(hardline$3, groups.map(printGroup))])));
}
var printedGroups = groups.map(printGroup);
var oneLine = concat$4(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$1(oneLine);
} // Find out the last node in the first group and check if it has an
// empty line after
var lastNodeBeforeIndent = getLast$4(shouldMerge ? groups.slice(1, 2)[0] : groups[0]).node;
var shouldHaveEmptyLineBeforeIndent = lastNodeBeforeIndent.type !== "CallExpression" && lastNodeBeforeIndent.type !== "OptionalCallExpression" && shouldInsertEmptyLineAfter(lastNodeBeforeIndent);
var expanded = concat$4([printGroup(groups[0]), shouldMerge ? concat$4(groups.slice(1, 2).map(printGroup)) : "", shouldHaveEmptyLineBeforeIndent ? hardline$3 : "", printIndentedGroup(groups.slice(shouldMerge ? 2 : 1))]);
var callExpressionCount = printedNodes.filter(function (tuple) {
return tuple.node.type === "CallExpression" || tuple.node.type === "OptionalCallExpression";
}).length; // 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 || callExpressionCount >= 3 || printedGroups.slice(0, -1).some(willBreak$1)) {
return group$1(expanded);
}
return concat$4([// 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$2 : "", conditionalGroup$1([oneLine, expanded])]);
}
function isJSXNode(node) {
return node.type === "JSXElement" || node.type === "JSXFragment" || node.type === "TSJsxFragment";
}
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;
} // 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) {
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])) {
children.push(hardline$3);
} else {
children.push(jsxWhitespace);
}
words.shift();
}
var endWhitespace; // Ends with whitespace
if (getLast$4(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$3);
} else {
children.push(word);
}
});
if (endWhitespace !== undefined) {
if (/\n/.test(endWhitespace)) {
children.push(hardline$3);
} else {
children.push(jsxWhitespace);
}
} else {
// Ideally this would be a `hardline` to allow a break between
// tags and text.
// Unfortunately Facebook have a custom translation pipeline
// (https://github.com/prettier/prettier/issues/1581#issuecomment-300975032)
// that uses the JSX syntax, but does not follow the React whitespace
// rules.
// Ensuring that we never have a break between tags and text in JSX
// will allow Facebook to adopt Prettier without too much of an
// adverse effect on formatting algorithm.
children.push("");
}
} 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$3);
}
} else {
children.push("");
children.push(jsxWhitespace);
}
} else {
var printedChild = print(childPath);
children.push(printedChild);
var next = n.children[i + 1];
var directlyFollowedByMeaningfulText = next && isMeaningfulJSXText(next) && !/^[ \n\r\t]/.test(rawText(next));
if (directlyFollowedByMeaningfulText) {
// Potentially this could be a hardline as well.
// See the comment above about the Facebook translation pipeline as
// to why this is an empty string.
children.push("");
} else {
children.push(hardline$3);
}
}
}, "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(); // Turn
into
if (n.type === "JSXElement" && isEmptyJSXElement(n)) {
n.openingElement.selfClosing = true;
return path.call(print, "openingElement");
}
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$4([openingLines, concat$4(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$1(concat$4([rawJsxWhitespace, softline$1]), " ");
var children = printJSXChildren(path, options, print, jsxWhitespace);
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$3 && children[i + 1] === "" && children[i + 2] === hardline$3;
var isLineFollowedByJSXWhitespace = (children[i] === softline$1 || children[i] === hardline$3) && children[i + 1] === "" && children[i + 2] === jsxWhitespace;
var isJSXWhitespaceFollowedByLine = children[i] === jsxWhitespace && children[i + 1] === "" && (children[i + 2] === softline$1 || children[i + 2] === hardline$3);
var isDoubleJSXWhitespace = children[i] === jsxWhitespace && children[i + 1] === "" && children[i + 2] === jsxWhitespace;
if (isPairOfHardlines && containsText || isPairOfEmptyStrings || isLineFollowedByJSXWhitespace || isDoubleJSXWhitespace) {
children.splice(i, 2);
} else if (isJSXWhitespaceFollowedByLine) {
children.splice(i + 1, 2);
}
} // Trim trailing lines (or empty strings)
while (children.length && (isLineNext$1(getLast$4(children)) || isEmpty$1(getLast$4(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$4([rawJsxWhitespace, hardline$3]));
return;
} else if (i === children.length - 1) {
// Trailing whitespace
multilineChildren.push(rawJsxWhitespace);
return;
} else if (children[i - 1] === "" && children[i - 2] === hardline$3) {
// 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$2(multilineChildren) : group$1(concat$4(multilineChildren), {
shouldBreak: true
});
var multiLineElem = group$1(concat$4([openingLines, indent$2(concat$4([hardline$3, content])), hardline$3, closingLines]));
if (forcedBreak) {
return multiLineElem;
}
return conditionalGroup$1([group$1(concat$4([openingLines, concat$4(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,
TSJsxFragment: true,
ExpressionStatement: true,
CallExpression: true,
OptionalCallExpression: true,
ConditionalExpression: true
};
if (NO_WRAP_PARENTS[parent.type]) {
return elem;
}
return group$1(concat$4([ifBreak$1("("), indent$2(concat$4([softline$1, elem])), softline$1, ifBreak$1(")")]));
}
function isBinaryish(node) {
return node.type === "BinaryExpression" || node.type === "LogicalExpression";
}
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 === "|>";
var right = shouldInline ? concat$4([node.operator, " ", path.call(print, "right")]) : concat$4([lineBeforeOperator ? softline$1 : "", node.operator, lineBeforeOperator ? " " : line$3, path.call(print, "right")]); // 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$1(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$4(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$2(concat$4([hardline$3, printedRight]));
}
var canBreak = isBinaryish(rightNode) && !shouldInlineLogicalExpression(rightNode) || rightNode.type === "ConditionalExpression" && isBinaryish(rightNode.test) && !shouldInlineLogicalExpression(rightNode.test) || rightNode.type === "StringLiteralTypeAnnotation" || (leftNode.type === "Identifier" || isStringLiteral(leftNode) || leftNode.type === "MemberExpression") && (isStringLiteral(rightNode) || isMemberExpressionChain(rightNode));
if (canBreak) {
return indent$2(concat$4([line$3, printedRight]));
}
return concat$4([" ", printedRight]);
}
function printAssignment(leftNode, printedLeft, operator, rightNode, printedRight, options) {
if (!rightNode) {
return printedLeft;
}
var printed = printAssignmentRight(leftNode, rightNode, printedRight, options);
return group$1(concat$4([printedLeft, operator, printed]));
}
function adjustClause(node, clause, forceSpace) {
if (node.type === "EmptyStatement") {
return ";";
}
if (node.type === "BlockStatement" || forceSpace) {
return concat$4([" ", clause]);
}
return indent$2(concat$4([line$3, clause]));
}
function nodeStr(node, options, isFlowOrTypeScriptDirectiveLiteral) {
var raw = rawText(node);
var isDirectiveLiteral = isFlowOrTypeScriptDirectiveLiteral || node.type === "DirectiveLiteral";
return printString$1(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$2(text, options.locEnd(comment));
});
return res;
}
function hasNakedLeftSide(node) {
return node.type === "AssignmentExpression" || node.type === "BinaryExpression" || node.type === "LogicalExpression" || node.type === "ConditionalExpression" || node.type === "CallExpression" || node.type === "OptionalCallExpression" || node.type === "MemberExpression" || node.type === "OptionalMemberExpression" || node.type === "SequenceExpression" || node.type === "TaggedTemplateExpression" || node.type === "BindExpression" && !node.object || node.type === "UpdateExpression" && !node.prefix;
}
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 getLeftSide(node) {
if (node.expressions) {
return node.expressions[0];
}
return node.left || node.test || node.callee || node.object || node.tag || node.argument || node.expression;
}
function getLeftSidePathName(path, node) {
if (node.expressions) {
return ["expressions", 0];
}
if (node.left) {
return ["left"];
}
if (node.test) {
return ["test"];
}
if (node.callee) {
return ["callee"];
}
if (node.object) {
return ["object"];
}
if (node.tag) {
return ["tag"];
}
if (node.argument) {
return ["argument"];
}
if (node.expression) {
return ["expression"];
}
throw new Error("Unexpected node has no left side", node);
}
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.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.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":
{
// Babylon
var isAsync = node.value ? node.value.async : node.async;
var isGenerator = node.value ? node.value.generator : node.generator;
if (isAsync || node.static || 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.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 (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$2(text, options.locStart(n), {
backwards: true
});
}
function printArrayItems(path, options, printPath, print) {
var printedElements = [];
var separatorParts = [];
path.each(function (childPath) {
printedElements.push(concat$4(separatorParts));
printedElements.push(group$1(print(childPath)));
separatorParts = [",", line$3];
if (childPath.getValue() && isNextLineEmpty$2(options.originalText, childPath.getValue(), options)) {
separatorParts.push(softline$1);
}
}, printPath);
return concat$4(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$4(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 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].type);
}
if (isUnitTestSetUp(n)) {
return isFunctionOrArrowExpression(n.arguments[0].type) || isAngularTestWrapper(n.arguments[0]);
}
} else if (n.arguments.length === 2) {
if ((n.callee.type === "Identifier" && unitTestRe.test(n.callee.name) || isSkipOrOnlyBlock(n)) && (isTemplateLiteral(n.arguments[0]) || isStringLiteral(n.arguments[0]))) {
return isFunctionOrArrowExpression(n.arguments[1].type) && 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");
}
function isFunctionOrArrowExpression(type) {
return type === "FunctionExpression" || type === "ArrowFunctionExpression";
}
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") {
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) {
var node = path.getValue();
var parent = path.getParentNode();
return (node && isJSXNode(node) || parent && (parent.type === "JSXSpreadAttribute" || parent.type === "JSXSpreadChild" || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType" || (parent.type === "ClassDeclaration" || parent.type === "ClassExpression") && parent.superClass === node)) && !hasIgnoreComment$1(path);
}
function canAttachComment(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" && !(node.callee && node.callee.type === "Import");
}
function printComment$1(commentPath, options) {
var comment = commentPath.getValue();
switch (comment.type) {
case "CommentBlock":
case "Block":
{
if (isJsDocComment(comment)) {
var printed = printJsDocComment(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$2(options.originalText, options.locStart(comment), {
backwards: true
})) {
return concat$4([hardline$3, 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 isJsDocComment(comment) {
var lines = comment.value.split("\n");
return lines.length > 1 && lines.slice(0, lines.length - 1).every(function (line) {
return line.trim()[0] === "*";
});
}
function printJsDocComment(comment) {
var lines = comment.value.split("\n");
return concat$4(["/*", join$2(hardline$3, lines.map(function (line, index) {
return (index > 0 ? " " : "") + (index < lines.length - 1 ? line.trim() : line.trimLeft());
})), "*/"]);
}
function rawText(node) {
return node.extra ? node.extra.raw : node.raw;
}
var printerEstree = {
print: genericPrint$1,
embed: embed_1,
insertPragma: insertPragma,
massageAstNode: clean_1,
hasPrettierIgnore: hasPrettierIgnore,
willPrintOwnComments: willPrintOwnComments,
canAttachComment: canAttachComment,
printComment: printComment$1,
isBlockComment: comments$3.isBlockComment,
handleComments: {
ownLine: comments$3.handleOwnLineComment,
endOfLine: comments$3.handleEndOfLineComment,
remaining: comments$3.handleRemainingComment
}
};
var _require$$0$builders$2 = doc.builders;
var concat$6 = _require$$0$builders$2.concat;
var hardline$5 = _require$$0$builders$2.hardline;
var indent$4 = _require$$0$builders$2.indent;
var join$4 = _require$$0$builders$2.join;
function genericPrint$2(path, options, print) {
var node = path.getValue();
switch (node.type) {
case "ArrayExpression":
return node.elements.length === 0 ? "[]" : concat$6(["[", indent$4(concat$6([hardline$5, join$4(concat$6([",", hardline$5]), path.map(print, "elements"))])), hardline$5, "]"]);
case "ObjectExpression":
return node.properties.length === 0 ? "{}" : concat$6(["{", indent$4(concat$6([hardline$5, join$4(concat$6([",", hardline$5]), path.map(print, "properties"))])), hardline$5, "}"]);
case "ObjectProperty":
return concat$6([path.call(print, "key"), ": ", path.call(print, "value")]);
case "UnaryExpression":
return concat$6([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$2(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 = {
print: genericPrint$2,
massageAstNode: clean$2
};
var CATEGORY_COMMON = "Common"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
var commonOptions = {
bracketSpacing: {
since: "0.0.0",
category: CATEGORY_COMMON,
type: "boolean",
default: true,
description: "Print spaces between brackets.",
oppositeDescription: "Do not print spaces between brackets."
},
singleQuote: {
since: "0.0.0",
category: CATEGORY_COMMON,
type: "boolean",
default: false,
description: "Use single quotes instead of double quotes."
}
};
var CATEGORY_JAVASCRIPT = "JavaScript"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
var options$3 = {
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,
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"
}]
}
};
// https://github.com/github/linguist/blob/master/lib/linguist/languages.yml
var languages = [{
name: "JavaScript",
since: "0.0.0",
parsers: ["babylon", "flow"],
group: "JavaScript",
tmScope: "source.js",
aceMode: "javascript",
codemirrorMode: "javascript",
codemirrorMimeType: "text/javascript",
aliases: ["js", "node"],
extensions: [".js", "._js", ".bones", ".es", ".es6", ".frag", ".gs", ".jake", ".jsb", ".jscad", ".jsfl", ".jsm", ".jss", ".mjs", ".njs", ".pac", ".sjs", ".ssjs", ".xsjs", ".xsjslib"],
filenames: ["Jakefile"],
linguistLanguageId: 183,
vscodeLanguageIds: ["javascript"]
}, {
name: "JSX",
since: "0.0.0",
parsers: ["babylon", "flow"],
group: "JavaScript",
extensions: [".jsx"],
tmScope: "source.js.jsx",
aceMode: "javascript",
codemirrorMode: "jsx",
codemirrorMimeType: "text/jsx",
liguistLanguageId: 178,
vscodeLanguageIds: ["javascriptreact"]
}, {
name: "TypeScript",
since: "1.4.0",
parsers: ["typescript-eslint"],
group: "JavaScript",
aliases: ["ts"],
extensions: [".ts", ".tsx"],
tmScope: "source.ts",
aceMode: "typescript",
codemirrorMode: "javascript",
codemirrorMimeType: "application/typescript",
liguistLanguageId: 378,
vscodeLanguageIds: ["typescript", "typescriptreact"]
}, {
name: "JSON.stringify",
since: "1.13.0",
parsers: ["json-stringify"],
group: "JavaScript",
tmScope: "source.json",
aceMode: "json",
codemirrorMode: "javascript",
codemirrorMimeType: "application/json",
extensions: [],
// .json file defaults to json instead of json-stringify
filenames: ["package.json", "package-lock.json", "composer.json"],
linguistLanguageId: 174,
vscodeLanguageIds: ["json"]
}, {
name: "JSON",
since: "1.5.0",
parsers: ["json"],
group: "JavaScript",
tmScope: "source.json",
aceMode: "json",
codemirrorMode: "javascript",
codemirrorMimeType: "application/json",
extensions: [".json", ".geojson", ".JSON-tmLanguage", ".topojson"],
filenames: [".arcconfig", ".jshintrc", ".eslintrc", ".prettierrc", "composer.lock", "mcmod.info"],
linguistLanguageId: 174,
vscodeLanguageIds: ["json", "jsonc"]
}, {
name: "JSON5",
since: "1.13.0",
parsers: ["json5"],
group: "JavaScript",
tmScope: "source.json",
aceMode: "json",
codemirrorMode: "javascript",
codemirrorMimeType: "application/json",
extensions: [".json5"],
filenames: [".babelrc"],
linguistLanguageId: 175,
vscodeLanguageIds: ["json5"]
}];
var printers = {
estree: printerEstree,
"estree-json": printerEstreeJson
};
var languageJs = {
languages: languages,
options: options$3,
printers: printers
};
var index$5 = ["a", "abbr", "acronym", "address", "applet", "area", "article", "aside", "audio", "b", "base", "basefont", "bdi", "bdo", "bgsound", "big", "blink", "blockquote", "body", "br", "button", "canvas", "caption", "center", "cite", "code", "col", "colgroup", "command", "content", "data", "datalist", "dd", "del", "details", "dfn", "dialog", "dir", "div", "dl", "dt", "element", "em", "embed", "fieldset", "figcaption", "figure", "font", "footer", "form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "i", "iframe", "image", "img", "input", "ins", "isindex", "kbd", "keygen", "label", "legend", "li", "link", "listing", "main", "map", "mark", "marquee", "math", "menu", "menuitem", "meta", "meter", "multicol", "nav", "nextid", "nobr", "noembed", "noframes", "noscript", "object", "ol", "optgroup", "option", "output", "p", "param", "picture", "plaintext", "pre", "progress", "q", "rb", "rbc", "rp", "rt", "rtc", "ruby", "s", "samp", "script", "section", "select", "shadow", "slot", "small", "source", "spacer", "span", "strike", "strong", "style", "sub", "summary", "sup", "svg", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "time", "title", "tr", "track", "tt", "u", "ul", "var", "video", "wbr", "xmp"];
var htmlTagNames = Object.freeze({
default: index$5
});
var htmlTagNames$1 = ( htmlTagNames && index$5 ) || htmlTagNames;
function clean$3(ast, newObj) {
["raws", "sourceIndex", "source", "before", "after", "trailingComma"].forEach(function (name) {
delete newObj[name];
});
if (ast.type === "media-query" || ast.type === "media-query-list" || ast.type === "media-feature-expression") {
delete newObj.value;
}
if (ast.type === "css-rule") {
delete newObj.params;
}
if (ast.type === "selector-combinator") {
newObj.value = newObj.value.replace(/\s+/g, " ");
}
if (ast.type === "media-feature") {
newObj.value = newObj.value.replace(/ /g, "");
}
if (ast.type === "value-word" && (ast.isColor && ast.isHex || ["initial", "inherit", "unset", "revert"].indexOf(newObj.value.replace().toLowerCase()) !== -1) || ast.type === "media-feature" || ast.type === "selector-root-invalid" || ast.type === "selector-pseudo") {
newObj.value = newObj.value.toLowerCase();
}
if (ast.type === "css-decl") {
newObj.prop = newObj.prop.toLowerCase();
}
if (ast.type === "css-atrule" || ast.type === "css-import") {
newObj.name = newObj.name.toLowerCase();
}
if (ast.type === "value-number") {
newObj.unit = newObj.unit.toLowerCase();
}
if ((ast.type === "media-feature" || ast.type === "media-keyword" || ast.type === "media-type" || ast.type === "media-unknown" || ast.type === "media-url" || ast.type === "media-value" || ast.type === "selector-attribute" || ast.type === "selector-string" || ast.type === "selector-class" || ast.type === "selector-combinator" || ast.type === "value-string") && newObj.value) {
newObj.value = cleanCSSStrings(newObj.value);
}
if (ast.type === "selector-attribute") {
newObj.attribute = newObj.attribute.trim();
if (newObj.namespace) {
if (typeof newObj.namespace === "string") {
newObj.namespace = newObj.namespace.trim();
if (newObj.namespace.length === 0) {
newObj.namespace = true;
}
}
}
if (newObj.value) {
newObj.value = newObj.value.trim().replace(/^['"]|['"]$/g, "");
delete newObj.quoted;
}
}
if ((ast.type === "media-value" || ast.type === "media-type" || ast.type === "value-number" || ast.type === "selector-root-invalid" || ast.type === "selector-class" || ast.type === "selector-combinator" || ast.type === "selector-tag") && newObj.value) {
newObj.value = newObj.value.replace(/([\d.eE+-]+)([a-zA-Z]*)/g, function (match, numStr, unit) {
var num = Number(numStr);
return isNaN(num) ? match : num + unit.toLowerCase();
});
}
if (ast.type === "selector-tag") {
var lowercasedValue = ast.value.toLowerCase();
if (htmlTagNames$1.indexOf(lowercasedValue) !== -1) {
newObj.value = lowercasedValue;
}
if (["from", "to"].indexOf(lowercasedValue) !== -1) {
newObj.value = lowercasedValue;
}
} // Workaround when `postcss-values-parser` parse `not`, `and` or `or` keywords as `value-func`
if (ast.type === "css-atrule" && ast.name.toLowerCase() === "supports") {
delete newObj.value;
} // Workaround for SCSS nested properties
if (ast.type === "selector-unknown") {
delete newObj.value;
}
}
function cleanCSSStrings(value) {
return value.replace(/'/g, '"').replace(/\\([^a-fA-F\d])/g, "$1");
}
var clean_1$2 = clean$3;
var colorAdjusterFunctions = ["red", "green", "blue", "alpha", "a", "rgb", "hue", "h", "saturation", "s", "lightness", "l", "whiteness", "w", "blackness", "b", "tint", "shade", "blend", "blenda", "contrast", "hsl", "hsla", "hwb", "hwba"];
function getAncestorCounter(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$1(path, typeOrTypes) {
var counter = getAncestorCounter(path, typeOrTypes);
return counter === -1 ? null : path.getParentNode(counter);
}
function getPropOfDeclNode$1(path) {
var declAncestorNode = getAncestorNode$1(path, "css-decl");
return declAncestorNode && declAncestorNode.prop && declAncestorNode.prop.toLowerCase();
}
function isSCSS$1(parser, text) {
var hasExplicitParserChoice = parser === "less" || parser === "scss";
var IS_POSSIBLY_SCSS = /(\w\s*: [^}:]+|#){|@import[^\n]+(url|,)/;
return hasExplicitParserChoice ? parser === "scss" : IS_POSSIBLY_SCSS.test(text);
}
function isWideKeywords$1(value) {
return ["initial", "inherit", "unset", "revert"].indexOf(value.toLowerCase()) !== -1;
}
function isKeyframeAtRuleKeywords$1(path, value) {
var atRuleAncestorNode = getAncestorNode$1(path, "css-atrule");
return atRuleAncestorNode && atRuleAncestorNode.name && atRuleAncestorNode.name.toLowerCase().endsWith("keyframes") && ["from", "to"].indexOf(value.toLowerCase()) !== -1;
}
function maybeToLowerCase$1(value) {
return value.includes("$") || value.includes("@") || value.includes("#") || value.startsWith("%") || value.startsWith("--") || value.startsWith(":--") || value.includes("(") && value.includes(")") ? value : value.toLowerCase();
}
function insideValueFunctionNode$1(path, functionName) {
var funcAncestorNode = getAncestorNode$1(path, "value-func");
return funcAncestorNode && funcAncestorNode.value && funcAncestorNode.value.toLowerCase() === functionName;
}
function insideICSSRuleNode$1(path) {
var ruleAncestorNode = getAncestorNode$1(path, "css-rule");
return ruleAncestorNode && ruleAncestorNode.raws && ruleAncestorNode.raws.selector && (ruleAncestorNode.raws.selector.startsWith(":import") || ruleAncestorNode.raws.selector.startsWith(":export"));
}
function insideAtRuleNode$1(path, atRuleNameOrAtRuleNames) {
var atRuleNames = [].concat(atRuleNameOrAtRuleNames);
var atRuleAncestorNode = getAncestorNode$1(path, "css-atrule");
return atRuleAncestorNode && atRuleNames.indexOf(atRuleAncestorNode.name.toLowerCase()) !== -1;
}
function insideURLFunctionInImportAtRuleNode$1(path) {
var node = path.getValue();
var atRuleAncestorNode = getAncestorNode$1(path, "css-atrule");
return atRuleAncestorNode && atRuleAncestorNode.name === "import" && node.groups[0].value === "url" && node.groups.length === 2;
}
function isURLFunctionNode$1(node) {
return node.type === "value-func" && node.value.toLowerCase() === "url";
}
function isLastNode$1(path, node) {
var parentNode = path.getParentNode();
if (!parentNode) {
return false;
}
var nodes = parentNode.nodes;
return nodes && nodes.indexOf(node) === nodes.length - 1;
}
function isHTMLTag$1(value) {
return htmlTagNames$1.indexOf(value.toLowerCase()) !== -1;
}
function isDetachedRulesetDeclarationNode$1(node) {
// If a Less file ends up being parsed with the SCSS parser, Less
// variable declarations will be parsed as atrules with names ending
// with a colon, so keep the original case then.
if (!node.selector) {
return false;
}
return typeof node.selector === "string" && /^@.+:.*$/.test(node.selector) || node.selector.value && /^@.+:.*$/.test(node.selector.value);
}
function isForKeywordNode$1(node) {
return node.type === "value-word" && ["from", "through", "end"].indexOf(node.value) !== -1;
}
function isIfElseKeywordNode$1(node) {
return node.type === "value-word" && ["and", "or", "not"].indexOf(node.value) !== -1;
}
function isEachKeywordNode$1(node) {
return node.type === "value-word" && node.value === "in";
}
function isMultiplicationNode$1(node) {
return node.type === "value-operator" && node.value === "*";
}
function isDivisionNode$1(node) {
return node.type === "value-operator" && node.value === "/";
}
function isAdditionNode$1(node) {
return node.type === "value-operator" && node.value === "+";
}
function isSubtractionNode$1(node) {
return node.type === "value-operator" && node.value === "-";
}
function isModuloNode(node) {
return node.type === "value-operator" && node.value === "%";
}
function isMathOperatorNode$1(node) {
return isMultiplicationNode$1(node) || isDivisionNode$1(node) || isAdditionNode$1(node) || isSubtractionNode$1(node) || isModuloNode(node);
}
function isEqualityOperatorNode$1(node) {
return node.type === "value-word" && ["==", "!="].indexOf(node.value) !== -1;
}
function isRelationalOperatorNode$1(node) {
return node.type === "value-word" && ["<", ">", "<=", ">="].indexOf(node.value) !== -1;
}
function isSCSSControlDirectiveNode$1(node) {
return node.type === "css-atrule" && ["if", "else", "for", "each", "while"].indexOf(node.name) !== -1;
}
function isSCSSNestedPropertyNode(node) {
if (!node.selector) {
return false;
}
return node.selector.replace(/\/\*.*?\*\//, "").replace(/\/\/.*?\n/, "").trim().endsWith(":");
}
function isDetachedRulesetCallNode$1(node) {
return node.raws && node.raws.params && /^\(\s*\)$/.test(node.raws.params);
}
function isPostcssSimpleVarNode$1(currentNode, nextNode) {
return currentNode.value === "$$" && currentNode.type === "value-func" && nextNode && nextNode.type === "value-word" && !nextNode.raws.before;
}
function hasComposesNode$1(node) {
return node.value && node.value.type === "value-root" && node.value.group && node.value.group.type === "value-value" && node.prop.toLowerCase() === "composes";
}
function hasParensAroundNode$1(node) {
return node.value && node.value.group && node.value.group.group && node.value.group.group.type === "value-paren_group" && node.value.group.group.open !== null && node.value.group.group.close !== null;
}
function hasEmptyRawBefore$1(node) {
return node.raws && node.raws.before === "";
}
function isKeyValuePairNode$1(node) {
return node.type === "value-comma_group" && node.groups && node.groups[1] && node.groups[1].type === "value-colon";
}
function isKeyValuePairInParenGroupNode(node) {
return node.type === "value-paren_group" && node.groups && node.groups[0] && isKeyValuePairNode$1(node.groups[0]);
}
function isSCSSMapItemNode$1(path) {
var node = path.getValue(); // Ignore empty item (i.e. `$key: ()`)
if (node.groups.length === 0) {
return false;
}
var parentParentNode = path.getParentNode(1); // Check open parens contain key/value pair (i.e. `(key: value)` and `(key: (value, other-value)`)
if (!isKeyValuePairInParenGroupNode(node) && !(parentParentNode && isKeyValuePairInParenGroupNode(parentParentNode))) {
return false;
}
var declNode = getAncestorNode$1(path, "css-decl"); // SCSS map declaration (i.e. `$map: (key: value, other-key: other-value)`)
if (declNode && declNode.prop && declNode.prop.startsWith("$")) {
return true;
} // List as value of key inside SCSS map (i.e. `$map: (key: (value other-value other-other-value))`)
if (isKeyValuePairInParenGroupNode(parentParentNode)) {
return true;
} // SCSS Map is argument of function (i.e. `func((key: value, other-key: other-value))`)
if (parentParentNode.type === "value-func") {
return true;
}
return false;
}
function isInlineValueCommentNode$1(node) {
return node.type === "value-comment" && node.inline;
}
function isHashNode$1(node) {
return node.type === "value-word" && node.value === "#";
}
function isLeftCurlyBraceNode$1(node) {
return node.type === "value-word" && node.value === "{";
}
function isRightCurlyBraceNode$1(node) {
return node.type === "value-word" && node.value === "}";
}
function isWordNode$1(node) {
return ["value-word", "value-atword"].indexOf(node.type) !== -1;
}
function isColonNode$1(node) {
return node.type === "value-colon";
}
function isMediaAndSupportsKeywords$1(node) {
return node.value && ["not", "and", "or"].indexOf(node.value.toLowerCase()) !== -1;
}
function isColorAdjusterFuncNode$1(node) {
if (node.type !== "value-func") {
return false;
}
return colorAdjusterFunctions.indexOf(node.value.toLowerCase()) !== -1;
}
var utils$4 = {
getAncestorCounter: getAncestorCounter,
getAncestorNode: getAncestorNode$1,
getPropOfDeclNode: getPropOfDeclNode$1,
maybeToLowerCase: maybeToLowerCase$1,
insideValueFunctionNode: insideValueFunctionNode$1,
insideICSSRuleNode: insideICSSRuleNode$1,
insideAtRuleNode: insideAtRuleNode$1,
insideURLFunctionInImportAtRuleNode: insideURLFunctionInImportAtRuleNode$1,
isKeyframeAtRuleKeywords: isKeyframeAtRuleKeywords$1,
isHTMLTag: isHTMLTag$1,
isWideKeywords: isWideKeywords$1,
isSCSS: isSCSS$1,
isLastNode: isLastNode$1,
isSCSSControlDirectiveNode: isSCSSControlDirectiveNode$1,
isDetachedRulesetDeclarationNode: isDetachedRulesetDeclarationNode$1,
isRelationalOperatorNode: isRelationalOperatorNode$1,
isEqualityOperatorNode: isEqualityOperatorNode$1,
isMultiplicationNode: isMultiplicationNode$1,
isDivisionNode: isDivisionNode$1,
isAdditionNode: isAdditionNode$1,
isSubtractionNode: isSubtractionNode$1,
isModuloNode: isModuloNode,
isMathOperatorNode: isMathOperatorNode$1,
isEachKeywordNode: isEachKeywordNode$1,
isForKeywordNode: isForKeywordNode$1,
isURLFunctionNode: isURLFunctionNode$1,
isIfElseKeywordNode: isIfElseKeywordNode$1,
hasComposesNode: hasComposesNode$1,
hasParensAroundNode: hasParensAroundNode$1,
hasEmptyRawBefore: hasEmptyRawBefore$1,
isSCSSNestedPropertyNode: isSCSSNestedPropertyNode,
isDetachedRulesetCallNode: isDetachedRulesetCallNode$1,
isPostcssSimpleVarNode: isPostcssSimpleVarNode$1,
isKeyValuePairNode: isKeyValuePairNode$1,
isKeyValuePairInParenGroupNode: isKeyValuePairInParenGroupNode,
isSCSSMapItemNode: isSCSSMapItemNode$1,
isInlineValueCommentNode: isInlineValueCommentNode$1,
isHashNode: isHashNode$1,
isLeftCurlyBraceNode: isLeftCurlyBraceNode$1,
isRightCurlyBraceNode: isRightCurlyBraceNode$1,
isWordNode: isWordNode$1,
isColonNode: isColonNode$1,
isMediaAndSupportsKeywords: isMediaAndSupportsKeywords$1,
isColorAdjusterFuncNode: isColorAdjusterFuncNode$1
};
var printNumber$2 = util.printNumber;
var printString$2 = util.printString;
var hasIgnoreComment$2 = util.hasIgnoreComment;
var hasNewline$3 = util.hasNewline;
var isNextLineEmpty$3 = utilShared.isNextLineEmpty;
var _require$$2$builders = doc.builders;
var concat$7 = _require$$2$builders.concat;
var join$5 = _require$$2$builders.join;
var line$4 = _require$$2$builders.line;
var hardline$6 = _require$$2$builders.hardline;
var softline$3 = _require$$2$builders.softline;
var group$2 = _require$$2$builders.group;
var fill$3 = _require$$2$builders.fill;
var indent$5 = _require$$2$builders.indent;
var dedent$3 = _require$$2$builders.dedent;
var ifBreak$2 = _require$$2$builders.ifBreak;
var removeLines$2 = doc.utils.removeLines;
var getAncestorNode = utils$4.getAncestorNode;
var getPropOfDeclNode = utils$4.getPropOfDeclNode;
var maybeToLowerCase = utils$4.maybeToLowerCase;
var insideValueFunctionNode = utils$4.insideValueFunctionNode;
var insideICSSRuleNode = utils$4.insideICSSRuleNode;
var insideAtRuleNode = utils$4.insideAtRuleNode;
var insideURLFunctionInImportAtRuleNode = utils$4.insideURLFunctionInImportAtRuleNode;
var isKeyframeAtRuleKeywords = utils$4.isKeyframeAtRuleKeywords;
var isHTMLTag = utils$4.isHTMLTag;
var isWideKeywords = utils$4.isWideKeywords;
var isSCSS = utils$4.isSCSS;
var isLastNode = utils$4.isLastNode;
var isSCSSControlDirectiveNode = utils$4.isSCSSControlDirectiveNode;
var isDetachedRulesetDeclarationNode = utils$4.isDetachedRulesetDeclarationNode;
var isRelationalOperatorNode = utils$4.isRelationalOperatorNode;
var isEqualityOperatorNode = utils$4.isEqualityOperatorNode;
var isMultiplicationNode = utils$4.isMultiplicationNode;
var isDivisionNode = utils$4.isDivisionNode;
var isAdditionNode = utils$4.isAdditionNode;
var isSubtractionNode = utils$4.isSubtractionNode;
var isMathOperatorNode = utils$4.isMathOperatorNode;
var isEachKeywordNode = utils$4.isEachKeywordNode;
var isForKeywordNode = utils$4.isForKeywordNode;
var isURLFunctionNode = utils$4.isURLFunctionNode;
var isIfElseKeywordNode = utils$4.isIfElseKeywordNode;
var hasComposesNode = utils$4.hasComposesNode;
var hasParensAroundNode = utils$4.hasParensAroundNode;
var hasEmptyRawBefore = utils$4.hasEmptyRawBefore;
var isKeyValuePairNode = utils$4.isKeyValuePairNode;
var isDetachedRulesetCallNode = utils$4.isDetachedRulesetCallNode;
var isPostcssSimpleVarNode = utils$4.isPostcssSimpleVarNode;
var isSCSSMapItemNode = utils$4.isSCSSMapItemNode;
var isInlineValueCommentNode = utils$4.isInlineValueCommentNode;
var isHashNode = utils$4.isHashNode;
var isLeftCurlyBraceNode = utils$4.isLeftCurlyBraceNode;
var isRightCurlyBraceNode = utils$4.isRightCurlyBraceNode;
var isWordNode = utils$4.isWordNode;
var isColonNode = utils$4.isColonNode;
var isMediaAndSupportsKeywords = utils$4.isMediaAndSupportsKeywords;
var isColorAdjusterFuncNode = utils$4.isColorAdjusterFuncNode;
function shouldPrintComma$1(options) {
switch (options.trailingComma) {
case "all":
case "es5":
return true;
case "none":
default:
return false;
}
}
function genericPrint$3(path, options, print) {
var node = path.getValue();
/* istanbul ignore if */
if (!node) {
return "";
}
if (typeof node === "string") {
return node;
}
switch (node.type) {
case "front-matter":
return concat$7([node.value, hardline$6]);
case "css-root":
{
var nodes = printNodeSequence(path, options, print);
if (nodes.parts.length) {
return concat$7([nodes, hardline$6]);
}
return nodes;
}
case "css-comment":
{
if (node.raws.content) {
return node.raws.content;
}
var text = options.originalText.slice(options.locStart(node), options.locEnd(node));
var rawText = node.raws.text || node.text; // Workaround a bug where the location is off.
// https://github.com/postcss/postcss-scss/issues/63
if (text.indexOf(rawText) === -1) {
if (node.raws.inline) {
return concat$7(["// ", rawText]);
}
return concat$7(["/* ", rawText, " */"]);
}
return text;
}
case "css-rule":
{
return concat$7([path.call(print, "selector"), node.important ? " !important" : "", node.nodes ? concat$7([" {", node.nodes.length > 0 ? indent$5(concat$7([hardline$6, printNodeSequence(path, options, print)])) : "", hardline$6, "}", isDetachedRulesetDeclarationNode(node) ? ";" : ""]) : ";"]);
}
case "css-decl":
{
return concat$7([node.raws.before.replace(/[\s;]/g, ""), insideICSSRuleNode(path) ? node.prop : maybeToLowerCase(node.prop), node.raws.between.trim() === ":" ? ":" : node.raws.between.trim(), node.extend ? "" : " ", hasComposesNode(node) ? removeLines$2(path.call(print, "value")) : path.call(print, "value"), node.raws.important ? node.raws.important.replace(/\s*!\s*important/i, " !important") : node.important ? " !important" : "", node.raws.scssDefault ? node.raws.scssDefault.replace(/\s*!default/i, " !default") : node.scssDefault ? " !default" : "", node.raws.scssGlobal ? node.raws.scssGlobal.replace(/\s*!global/i, " !global") : node.scssGlobal ? " !global" : "", node.nodes ? concat$7([" {", indent$5(concat$7([softline$3, printNodeSequence(path, options, print)])), softline$3, "}"]) : ";"]);
}
case "css-atrule":
{
return concat$7(["@", // If a Less file ends up being parsed with the SCSS parser, Less
// variable declarations will be parsed as at-rules with names ending
// with a colon, so keep the original case then.
isDetachedRulesetCallNode(node) || node.name.endsWith(":") ? node.name : maybeToLowerCase(node.name), node.params ? concat$7([isDetachedRulesetCallNode(node) ? "" : " ", path.call(print, "params")]) : "", node.selector ? indent$5(concat$7([" ", path.call(print, "selector")])) : "", node.value ? group$2(concat$7([" ", path.call(print, "value"), isSCSSControlDirectiveNode(node) ? hasParensAroundNode(node) ? " " : line$4 : ""])) : node.name === "else" ? " " : "", node.nodes ? concat$7([isSCSSControlDirectiveNode(node) ? "" : " ", "{", indent$5(concat$7([node.nodes.length > 0 ? softline$3 : "", printNodeSequence(path, options, print)])), softline$3, "}"]) : ";"]);
}
// postcss-media-query-parser
case "media-query-list":
{
var parts = [];
path.each(function (childPath) {
var node = childPath.getValue();
if (node.type === "media-query" && node.value === "") {
return;
}
parts.push(childPath.call(print));
}, "nodes");
return group$2(indent$5(join$5(line$4, parts)));
}
case "media-query":
{
return concat$7([join$5(" ", path.map(print, "nodes")), isLastNode(path, node) ? "" : ","]);
}
case "media-type":
{
return adjustNumbers(adjustStrings(node.value, options));
}
case "media-feature-expression":
{
if (!node.nodes) {
return node.value;
}
return concat$7(["(", concat$7(path.map(print, "nodes")), ")"]);
}
case "media-feature":
{
return maybeToLowerCase(adjustStrings(node.value.replace(/ +/g, " "), options));
}
case "media-colon":
{
return concat$7([node.value, " "]);
}
case "media-value":
{
return adjustNumbers(adjustStrings(node.value, options));
}
case "media-keyword":
{
return adjustStrings(node.value, options);
}
case "media-url":
{
return adjustStrings(node.value.replace(/^url\(\s+/gi, "url(").replace(/\s+\)$/gi, ")"), options);
}
case "media-unknown":
{
return node.value;
}
// postcss-selector-parser
case "selector-root":
{
return group$2(concat$7([insideAtRuleNode(path, "custom-selector") ? concat$7([getAncestorNode(path, "css-atrule").customSelector, line$4]) : "", join$5(concat$7([",", insideAtRuleNode(path, ["extend", "custom-selector", "nest"]) ? line$4 : hardline$6]), path.map(print, "nodes"))]));
}
case "selector-selector":
{
return group$2(indent$5(concat$7(path.map(print, "nodes"))));
}
case "selector-comment":
{
return node.value;
}
case "selector-string":
{
return adjustStrings(node.value, options);
}
case "selector-tag":
{
var parentNode = path.getParentNode();
var index = parentNode && parentNode.nodes.indexOf(node);
var prevNode = index && parentNode.nodes[index - 1];
return concat$7([node.namespace ? concat$7([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", prevNode.type === "selector-nesting" ? node.value : adjustNumbers(isHTMLTag(node.value) || isKeyframeAtRuleKeywords(path, node.value) ? node.value.toLowerCase() : node.value)]);
}
case "selector-id":
{
return concat$7(["#", node.value]);
}
case "selector-class":
{
return concat$7([".", adjustNumbers(adjustStrings(node.value, options))]);
}
case "selector-attribute":
{
return concat$7(["[", node.namespace ? concat$7([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", node.attribute.trim(), node.operator ? node.operator : "", node.value ? quoteAttributeValue(adjustStrings(node.value.trim(), options), options) : "", node.insensitive ? " i" : "", "]"]);
}
case "selector-combinator":
{
if (node.value === "+" || node.value === ">" || node.value === "~" || node.value === ">>>") {
var _parentNode = path.getParentNode();
var _leading = _parentNode.type === "selector-selector" && _parentNode.nodes[0] === node ? "" : line$4;
return concat$7([_leading, node.value, isLastNode(path, node) ? "" : " "]);
}
var leading = node.value.trim().startsWith("(") ? line$4 : "";
var value = adjustNumbers(adjustStrings(node.value.trim(), options)) || line$4;
return concat$7([leading, value]);
}
case "selector-universal":
{
return concat$7([node.namespace ? concat$7([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", adjustNumbers(node.value)]);
}
case "selector-pseudo":
{
return concat$7([maybeToLowerCase(node.value), node.nodes && node.nodes.length > 0 ? concat$7(["(", join$5(", ", path.map(print, "nodes")), ")"]) : ""]);
}
case "selector-nesting":
{
return node.value;
}
case "selector-unknown":
{
var ruleAncestorNode = getAncestorNode(path, "css-rule"); // Nested SCSS property
if (ruleAncestorNode && ruleAncestorNode.isSCSSNesterProperty) {
return adjustNumbers(adjustStrings(maybeToLowerCase(node.value), options));
}
return node.value;
}
// postcss-values-parser
case "value-value":
case "value-root":
{
return path.call(print, "group");
}
case "value-comment":
{
return concat$7([node.inline ? "//" : "/*", node.value, node.inline ? "" : "*/"]);
}
case "value-comma_group":
{
var _parentNode2 = path.getParentNode();
var parentParentNode = path.getParentNode(1);
var declAncestorProp = getPropOfDeclNode(path);
var isGridValue = declAncestorProp && _parentNode2.type === "value-value" && (declAncestorProp === "grid" || declAncestorProp.startsWith("grid-template"));
var atRuleAncestorNode = getAncestorNode(path, "css-atrule");
var isControlDirective = atRuleAncestorNode && isSCSSControlDirectiveNode(atRuleAncestorNode);
var printed = path.map(print, "groups");
var _parts = [];
var insideURLFunction = insideValueFunctionNode(path, "url");
var insideSCSSInterpolationInString = false;
var didBreak = false;
for (var i = 0; i < node.groups.length; ++i) {
_parts.push(printed[i]); // Ignore value inside `url()`
if (insideURLFunction) {
continue;
}
var iPrevNode = node.groups[i - 1];
var iNode = node.groups[i];
var iNextNode = node.groups[i + 1];
var iNextNextNode = node.groups[i + 2]; // Ignore after latest node (i.e. before semicolon)
if (!iNextNode) {
continue;
} // Ignore spaces before/after string interpolation (i.e. `"#{my-fn("_")}"`)
var isStartSCSSinterpolationInString = iNode.type === "value-string" && iNode.value.startsWith("#{");
var isEndingSCSSinterpolationInString = insideSCSSInterpolationInString && iNextNode.type === "value-string" && iNextNode.value.endsWith("}");
if (isStartSCSSinterpolationInString || isEndingSCSSinterpolationInString) {
insideSCSSInterpolationInString = !insideSCSSInterpolationInString;
continue;
}
if (insideSCSSInterpolationInString) {
continue;
} // Ignore colon (i.e. `:`)
if (isColonNode(iNode) || isColonNode(iNextNode)) {
continue;
} // Ignore `@` in Less (i.e. `@@var;`)
if (iNode.type === "value-atword" && iNode.value === "") {
continue;
} // Ignore `~` in Less (i.e. `content: ~"^//* some horrible but needed css hack";`)
if (iNode.value === "~") {
continue;
} // Ignore `\` (i.e. `$variable: \@small;`)
if (iNode.value === "\\") {
continue;
} // Ignore `$$` (i.e. `background-color: $$(style)Color;`)
if (isPostcssSimpleVarNode(iNode, iNextNode)) {
continue;
} // Ignore spaces after `#` and after `{` and before `}` in SCSS interpolation (i.e. `#{variable}`)
if (isHashNode(iNode) || isLeftCurlyBraceNode(iNode) || isRightCurlyBraceNode(iNextNode) || isLeftCurlyBraceNode(iNextNode) && hasEmptyRawBefore(iNextNode) || isRightCurlyBraceNode(iNode) && hasEmptyRawBefore(iNextNode)) {
continue;
} // Ignore css variables and interpolation in SCSS (i.e. `--#{$var}`)
if (iNode.value === "--" && isHashNode(iNextNode)) {
continue;
} // Formatting math operations
var isMathOperator = isMathOperatorNode(iNode);
var isNextMathOperator = isMathOperatorNode(iNextNode); // Print spaces before and after math operators beside SCSS interpolation as is
// (i.e. `#{$var}+5`, `#{$var} +5`, `#{$var}+ 5`, `#{$var} + 5`)
// (i.e. `5+#{$var}`, `5 +#{$var}`, `5+ #{$var}`, `5 + #{$var}`)
if ((isMathOperator && isHashNode(iNextNode) || isNextMathOperator && isRightCurlyBraceNode(iNode)) && hasEmptyRawBefore(iNextNode)) {
continue;
} // Print spaces before and after addition and subtraction math operators as is in `calc` function
// due to the fact that it is not valid syntax
// (i.e. `calc(1px+1px)`, `calc(1px+ 1px)`, `calc(1px +1px)`, `calc(1px + 1px)`)
if (insideValueFunctionNode(path, "calc") && (isAdditionNode(iNode) || isAdditionNode(iNextNode) || isSubtractionNode(iNode) || isSubtractionNode(iNextNode)) && hasEmptyRawBefore(iNextNode)) {
continue;
} // Print spaces after `+` and `-` in color adjuster functions as is (e.g. `color(red l(+ 20%))`)
// Adjusters with signed numbers (e.g. `color(red l(+20%))`) output as-is.
var isColorAdjusterNode = (isAdditionNode(iNode) || isSubtractionNode(iNode)) && i === 0 && (iNextNode.type === "value-number" || iNextNode.isHex) && parentParentNode && isColorAdjusterFuncNode(parentParentNode) && !hasEmptyRawBefore(iNextNode);
var requireSpaceBeforeOperator = iNextNextNode && iNextNextNode.type === "value-func" || iNextNextNode && isWordNode(iNextNextNode) || iNode.type === "value-func" || isWordNode(iNode);
var requireSpaceAfterOperator = iNextNode.type === "value-func" || isWordNode(iNextNode) || iPrevNode && iPrevNode.type === "value-func" || iPrevNode && isWordNode(iPrevNode); // Formatting `/`, `+`, `-` sign
if (!(isMultiplicationNode(iNextNode) || isMultiplicationNode(iNode)) && !insideValueFunctionNode(path, "calc") && !isColorAdjusterNode && (isDivisionNode(iNextNode) && !requireSpaceBeforeOperator || isDivisionNode(iNode) && !requireSpaceAfterOperator || isAdditionNode(iNextNode) && !requireSpaceBeforeOperator || isAdditionNode(iNode) && !requireSpaceAfterOperator || isSubtractionNode(iNextNode) || isSubtractionNode(iNode)) && (hasEmptyRawBefore(iNextNode) || isMathOperator && (!iPrevNode || iPrevNode && isMathOperatorNode(iPrevNode)))) {
continue;
} // Ignore inline comment, they already contain newline at end (i.e. `// Comment`)
// Add `hardline` after inline comment (i.e. `// comment\n foo: bar;`)
var isInlineComment = isInlineValueCommentNode(iNode);
if (iPrevNode && isInlineValueCommentNode(iPrevNode) || isInlineComment || isInlineValueCommentNode(iNextNode)) {
if (isInlineComment) {
_parts.push(hardline$6);
}
continue;
} // Handle keywords in SCSS control directive
if (isControlDirective && (isEqualityOperatorNode(iNextNode) || isRelationalOperatorNode(iNextNode) || isIfElseKeywordNode(iNextNode) || isEachKeywordNode(iNode) || isForKeywordNode(iNode))) {
_parts.push(" ");
continue;
} // At-rule `namespace` should be in one line
if (atRuleAncestorNode && atRuleAncestorNode.name.toLowerCase() === "namespace") {
_parts.push(" ");
continue;
} // Formatting `grid` property
if (isGridValue) {
if (iNode.source.start.line !== iNextNode.source.start.line) {
_parts.push(hardline$6);
didBreak = true;
} else {
_parts.push(" ");
}
continue;
} // Add `space` before next math operation
// Note: `grip` property have `/` delimiter and it is not math operation, so
// `grid` property handles above
if (isNextMathOperator) {
_parts.push(" ");
continue;
} // Be default all values go through `line`
_parts.push(line$4);
}
if (didBreak) {
_parts.unshift(hardline$6);
}
if (isControlDirective) {
return group$2(indent$5(concat$7(_parts)));
} // Indent is not needed for import url when url is very long
// and node has two groups
// when type is value-comma_group
// example @import url("verylongurl") projection,tv
if (insideURLFunctionInImportAtRuleNode(path)) {
return group$2(fill$3(_parts));
}
return group$2(indent$5(fill$3(_parts)));
}
case "value-paren_group":
{
var _parentNode3 = path.getParentNode();
if (_parentNode3 && isURLFunctionNode(_parentNode3) && (node.groups.length === 1 || node.groups.length > 0 && node.groups[0].type === "value-comma_group" && node.groups[0].groups.length > 0 && node.groups[0].groups[0].type === "value-word" && node.groups[0].groups[0].value.startsWith("data:"))) {
return concat$7([node.open ? path.call(print, "open") : "", join$5(",", path.map(print, "groups")), node.close ? path.call(print, "close") : ""]);
}
if (!node.open) {
var _printed = path.map(print, "groups");
var res = [];
for (var _i = 0; _i < _printed.length; _i++) {
if (_i !== 0) {
res.push(concat$7([",", line$4]));
}
res.push(_printed[_i]);
}
return group$2(indent$5(fill$3(res)));
}
var isSCSSMapItem = isSCSSMapItemNode(path);
return group$2(concat$7([node.open ? path.call(print, "open") : "", indent$5(concat$7([softline$3, join$5(concat$7([",", line$4]), path.map(function (childPath) {
var node = childPath.getValue();
var printed = print(childPath); // Key/Value pair in open paren already indented
if (isKeyValuePairNode(node) && node.type === "value-comma_group" && node.groups && node.groups[2] && node.groups[2].type === "value-paren_group") {
printed.contents.contents.parts[1] = group$2(printed.contents.contents.parts[1]);
return group$2(dedent$3(printed));
}
return printed;
}, "groups"))])), ifBreak$2(isSCSS(options.parser, options.originalText) && isSCSSMapItem && shouldPrintComma$1(options) ? "," : ""), softline$3, node.close ? path.call(print, "close") : ""]), {
shouldBreak: isSCSSMapItem
});
}
case "value-func":
{
return concat$7([node.value, insideAtRuleNode(path, "supports") && isMediaAndSupportsKeywords(node) ? " " : "", path.call(print, "group")]);
}
case "value-paren":
{
return node.value;
}
case "value-number":
{
return concat$7([printCssNumber(node.value), maybeToLowerCase(node.unit)]);
}
case "value-operator":
{
return node.value;
}
case "value-word":
{
if (node.isColor && node.isHex || isWideKeywords(node.value)) {
return node.value.toLowerCase();
}
return node.value;
}
case "value-colon":
{
return concat$7([node.value, // Don't add spaces on `:` in `url` function (i.e. `url(fbglyph: cross-outline, fig-white)`)
insideValueFunctionNode(path, "url") ? "" : line$4]);
}
case "value-comma":
{
return concat$7([node.value, " "]);
}
case "value-string":
{
return printString$2(node.raws.quote + node.value + node.raws.quote, options);
}
case "value-atword":
{
return concat$7(["@", node.value]);
}
case "value-unicode-range":
{
return node.value;
}
case "value-unknown":
{
return node.value;
}
default:
/* istanbul ignore next */
throw new Error("Unknown postcss type ".concat(JSON.stringify(node.type)));
}
}
function printNodeSequence(path, options, print) {
var node = path.getValue();
var parts = [];
var i = 0;
path.map(function (pathChild) {
var prevNode = node.nodes[i - 1];
if (prevNode && prevNode.type === "css-comment" && prevNode.text.trim() === "prettier-ignore") {
var childNode = pathChild.getValue();
parts.push(options.originalText.slice(options.locStart(childNode), options.locEnd(childNode)));
} else {
parts.push(pathChild.call(print));
}
if (i !== node.nodes.length - 1) {
if (node.nodes[i + 1].type === "css-comment" && !hasNewline$3(options.originalText, options.locStart(node.nodes[i + 1]), {
backwards: true
}) || node.nodes[i + 1].type === "css-atrule" && node.nodes[i + 1].name === "else" && node.nodes[i].type !== "css-comment") {
parts.push(" ");
} else {
parts.push(hardline$6);
if (isNextLineEmpty$3(options.originalText, pathChild.getValue(), options)) {
parts.push(hardline$6);
}
}
}
i++;
}, "nodes");
return concat$7(parts);
}
var STRING_REGEX = /(['"])(?:(?!\1)[^\\]|\\[\s\S])*\1/g;
var NUMBER_REGEX = /(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g;
var STANDARD_UNIT_REGEX = /[a-zA-Z]+/g;
var WORD_PART_REGEX = /[$@]?[a-zA-Z_\u0080-\uFFFF][\w\-\u0080-\uFFFF]*/g;
var ADJUST_NUMBERS_REGEX = RegExp(STRING_REGEX.source + "|" + "(".concat(WORD_PART_REGEX.source, ")?") + "(".concat(NUMBER_REGEX.source, ")") + "(".concat(STANDARD_UNIT_REGEX.source, ")?"), "g");
function adjustStrings(value, options) {
return value.replace(STRING_REGEX, function (match) {
return printString$2(match, options);
});
}
function quoteAttributeValue(value, options) {
var quote = options.singleQuote ? "'" : '"';
return value.includes('"') || value.includes("'") ? value : quote + value + quote;
}
function adjustNumbers(value) {
return value.replace(ADJUST_NUMBERS_REGEX, function (match, quote, wordPart, number, unit) {
return !wordPart && number ? (wordPart || "") + printCssNumber(number) + maybeToLowerCase(unit || "") : match;
});
}
function printCssNumber(rawNumber) {
return printNumber$2(rawNumber) // Remove trailing `.0`.
.replace(/\.0(?=$|e)/, "");
}
var printerPostcss = {
print: genericPrint$3,
hasPrettierIgnore: hasIgnoreComment$2,
massageAstNode: clean_1$2
};
var options$6 = {
singleQuote: commonOptions.singleQuote
};
// https://github.com/github/linguist/blob/master/lib/linguist/languages.yml
var languages$1 = [{
name: "CSS",
since: "1.4.0",
parsers: ["css"],
group: "CSS",
tmScope: "source.css",
aceMode: "css",
codemirrorMode: "css",
codemirrorMimeType: "text/css",
extensions: [".css", ".pcss", ".postcss"],
liguistLanguageId: 50,
vscodeLanguageIds: ["css", "postcss"]
}, {
name: "Less",
since: "1.4.0",
parsers: ["less"],
group: "CSS",
extensions: [".less"],
tmScope: "source.css.less",
aceMode: "less",
codemirrorMode: "css",
codemirrorMimeType: "text/css",
liguistLanguageId: 198,
vscodeLanguageIds: ["less"]
}, {
name: "SCSS",
since: "1.4.0",
parsers: ["scss"],
group: "CSS",
tmScope: "source.scss",
aceMode: "scss",
codemirrorMode: "css",
codemirrorMimeType: "text/x-scss",
extensions: [".scss"],
liguistLanguageId: 329,
vscodeLanguageIds: ["scss"]
}];
var printers$1 = {
postcss: printerPostcss
};
var languageCss = {
languages: languages$1,
options: options$6,
printers: printers$1
};
var _require$$0$builders$3 = doc.builders;
var concat$8 = _require$$0$builders$3.concat;
var join$6 = _require$$0$builders$3.join;
var hardline$7 = _require$$0$builders$3.hardline;
var line$5 = _require$$0$builders$3.line;
var softline$4 = _require$$0$builders$3.softline;
var group$3 = _require$$0$builders$3.group;
var indent$6 = _require$$0$builders$3.indent;
var ifBreak$3 = _require$$0$builders$3.ifBreak;
var hasIgnoreComment$3 = util.hasIgnoreComment;
var isNextLineEmpty$4 = utilShared.isNextLineEmpty;
function genericPrint$4(path, options, print) {
var n = path.getValue();
if (!n) {
return "";
}
if (typeof n === "string") {
return n;
}
switch (n.kind) {
case "Document":
{
var parts = [];
path.map(function (pathChild, index) {
parts.push(concat$8([pathChild.call(print)]));
if (index !== n.definitions.length - 1) {
parts.push(hardline$7);
if (isNextLineEmpty$4(options.originalText, pathChild.getValue(), options)) {
parts.push(hardline$7);
}
}
}, "definitions");
return concat$8([concat$8(parts), hardline$7]);
}
case "OperationDefinition":
{
var hasOperation = options.originalText[options.locStart(n)] !== "{";
var hasName = !!n.name;
return concat$8([hasOperation ? n.operation : "", hasOperation && hasName ? concat$8([" ", path.call(print, "name")]) : "", n.variableDefinitions && n.variableDefinitions.length ? group$3(concat$8(["(", indent$6(concat$8([softline$4, join$6(concat$8([ifBreak$3("", ", "), softline$4]), path.map(print, "variableDefinitions"))])), softline$4, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? !hasOperation && !hasName ? "" : " " : "", path.call(print, "selectionSet")]);
}
case "FragmentDefinition":
{
return concat$8(["fragment ", path.call(print, "name"), " on ", path.call(print, "typeCondition"), printDirectives(path, print, n), " ", path.call(print, "selectionSet")]);
}
case "SelectionSet":
{
return concat$8(["{", indent$6(concat$8([hardline$7, join$6(hardline$7, path.call(function (selectionsPath) {
return printSequence(selectionsPath, options, print);
}, "selections"))])), hardline$7, "}"]);
}
case "Field":
{
return group$3(concat$8([n.alias ? concat$8([path.call(print, "alias"), ": "]) : "", path.call(print, "name"), n.arguments.length > 0 ? group$3(concat$8(["(", indent$6(concat$8([softline$4, join$6(concat$8([ifBreak$3("", ", "), softline$4]), path.call(function (argsPath) {
return printSequence(argsPath, options, print);
}, "arguments"))])), softline$4, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? " " : "", path.call(print, "selectionSet")]));
}
case "Name":
{
return n.value;
}
case "StringValue":
{
if (n.block) {
return concat$8(['"""', hardline$7, join$6(hardline$7, n.value.replace(/"""/g, "\\$&").split("\n")), hardline$7, '"""']);
}
return concat$8(['"', n.value.replace(/["\\]/g, "\\$&"), '"']);
}
case "IntValue":
case "FloatValue":
case "EnumValue":
{
return n.value;
}
case "BooleanValue":
{
return n.value ? "true" : "false";
}
case "NullValue":
{
return "null";
}
case "Variable":
{
return concat$8(["$", path.call(print, "name")]);
}
case "ListValue":
{
return group$3(concat$8(["[", indent$6(concat$8([softline$4, join$6(concat$8([ifBreak$3("", ", "), softline$4]), path.map(print, "values"))])), softline$4, "]"]));
}
case "ObjectValue":
{
return group$3(concat$8(["{", options.bracketSpacing && n.fields.length > 0 ? " " : "", indent$6(concat$8([softline$4, join$6(concat$8([ifBreak$3("", ", "), softline$4]), path.map(print, "fields"))])), softline$4, ifBreak$3("", options.bracketSpacing && n.fields.length > 0 ? " " : ""), "}"]));
}
case "ObjectField":
case "Argument":
{
return concat$8([path.call(print, "name"), ": ", path.call(print, "value")]);
}
case "Directive":
{
return concat$8(["@", path.call(print, "name"), n.arguments.length > 0 ? group$3(concat$8(["(", indent$6(concat$8([softline$4, join$6(concat$8([ifBreak$3("", ", "), softline$4]), path.call(function (argsPath) {
return printSequence(argsPath, options, print);
}, "arguments"))])), softline$4, ")"])) : ""]);
}
case "NamedType":
{
return path.call(print, "name");
}
case "VariableDefinition":
{
return concat$8([path.call(print, "variable"), ": ", path.call(print, "type"), n.defaultValue ? concat$8([" = ", path.call(print, "defaultValue")]) : ""]);
}
case "TypeExtensionDefinition":
{
return concat$8(["extend ", path.call(print, "definition")]);
}
case "ObjectTypeExtension":
case "ObjectTypeDefinition":
{
return concat$8([path.call(print, "description"), n.description ? hardline$7 : "", n.kind === "ObjectTypeExtension" ? "extend " : "", "type ", path.call(print, "name"), n.interfaces.length > 0 ? concat$8([" implements ", join$6(determineInterfaceSeparator(options.originalText.substr(options.locStart(n), options.locEnd(n))), path.map(print, "interfaces"))]) : "", printDirectives(path, print, n), n.fields.length > 0 ? concat$8([" {", indent$6(concat$8([hardline$7, join$6(hardline$7, path.call(function (fieldsPath) {
return printSequence(fieldsPath, options, print);
}, "fields"))])), hardline$7, "}"]) : ""]);
}
case "FieldDefinition":
{
return concat$8([path.call(print, "description"), n.description ? hardline$7 : "", path.call(print, "name"), n.arguments.length > 0 ? group$3(concat$8(["(", indent$6(concat$8([softline$4, join$6(concat$8([ifBreak$3("", ", "), softline$4]), path.call(function (argsPath) {
return printSequence(argsPath, options, print);
}, "arguments"))])), softline$4, ")"])) : "", ": ", path.call(print, "type"), printDirectives(path, print, n)]);
}
case "DirectiveDefinition":
{
return concat$8([path.call(print, "description"), n.description ? hardline$7 : "", "directive ", "@", path.call(print, "name"), n.arguments.length > 0 ? group$3(concat$8(["(", indent$6(concat$8([softline$4, join$6(concat$8([ifBreak$3("", ", "), softline$4]), path.call(function (argsPath) {
return printSequence(argsPath, options, print);
}, "arguments"))])), softline$4, ")"])) : "", concat$8([" on ", join$6(" | ", path.map(print, "locations"))])]);
}
case "EnumTypeExtension":
case "EnumTypeDefinition":
{
return concat$8([path.call(print, "description"), n.description ? hardline$7 : "", n.kind === "EnumTypeExtension" ? "extend " : "", "enum ", path.call(print, "name"), printDirectives(path, print, n), n.values.length > 0 ? concat$8([" {", indent$6(concat$8([hardline$7, join$6(hardline$7, path.call(function (valuesPath) {
return printSequence(valuesPath, options, print);
}, "values"))])), hardline$7, "}"]) : ""]);
}
case "EnumValueDefinition":
{
return concat$8([path.call(print, "description"), n.description ? hardline$7 : "", path.call(print, "name"), printDirectives(path, print, n)]);
}
case "InputValueDefinition":
{
return concat$8([path.call(print, "description"), n.description ? n.description.block ? hardline$7 : line$5 : "", path.call(print, "name"), ": ", path.call(print, "type"), n.defaultValue ? concat$8([" = ", path.call(print, "defaultValue")]) : "", printDirectives(path, print, n)]);
}
case "InputObjectTypeExtension":
case "InputObjectTypeDefinition":
{
return concat$8([path.call(print, "description"), n.description ? hardline$7 : "", n.kind === "InputObjectTypeExtension" ? "extend " : "", "input ", path.call(print, "name"), printDirectives(path, print, n), n.fields.length > 0 ? concat$8([" {", indent$6(concat$8([hardline$7, join$6(hardline$7, path.call(function (fieldsPath) {
return printSequence(fieldsPath, options, print);
}, "fields"))])), hardline$7, "}"]) : ""]);
}
case "SchemaDefinition":
{
return concat$8(["schema", printDirectives(path, print, n), " {", n.operationTypes.length > 0 ? indent$6(concat$8([hardline$7, join$6(hardline$7, path.call(function (opsPath) {
return printSequence(opsPath, options, print);
}, "operationTypes"))])) : "", hardline$7, "}"]);
}
case "OperationTypeDefinition":
{
return concat$8([path.call(print, "operation"), ": ", path.call(print, "type")]);
}
case "InterfaceTypeExtension":
case "InterfaceTypeDefinition":
{
return concat$8([path.call(print, "description"), n.description ? hardline$7 : "", n.kind === "InterfaceTypeExtension" ? "extend " : "", "interface ", path.call(print, "name"), printDirectives(path, print, n), n.fields.length > 0 ? concat$8([" {", indent$6(concat$8([hardline$7, join$6(hardline$7, path.call(function (fieldsPath) {
return printSequence(fieldsPath, options, print);
}, "fields"))])), hardline$7, "}"]) : ""]);
}
case "FragmentSpread":
{
return concat$8(["...", path.call(print, "name"), printDirectives(path, print, n)]);
}
case "InlineFragment":
{
return concat$8(["...", n.typeCondition ? concat$8([" on ", path.call(print, "typeCondition")]) : "", printDirectives(path, print, n), " ", path.call(print, "selectionSet")]);
}
case "UnionTypeExtension":
case "UnionTypeDefinition":
{
return group$3(concat$8([path.call(print, "description"), n.description ? hardline$7 : "", group$3(concat$8([n.kind === "UnionTypeExtension" ? "extend " : "", "union ", path.call(print, "name"), printDirectives(path, print, n), n.types.length > 0 ? concat$8([" =", ifBreak$3("", " "), indent$6(concat$8([ifBreak$3(concat$8([line$5, " "])), join$6(concat$8([line$5, "| "]), path.map(print, "types"))]))]) : ""]))]));
}
case "ScalarTypeExtension":
case "ScalarTypeDefinition":
{
return concat$8([path.call(print, "description"), n.description ? hardline$7 : "", n.kind === "ScalarTypeExtension" ? "extend " : "", "scalar ", path.call(print, "name"), printDirectives(path, print, n)]);
}
case "NonNullType":
{
return concat$8([path.call(print, "type"), "!"]);
}
case "ListType":
{
return concat$8(["[", path.call(print, "type"), "]"]);
}
default:
/* istanbul ignore next */
throw new Error("unknown graphql type: " + JSON.stringify(n.kind));
}
}
function printDirectives(path, print, n) {
if (n.directives.length === 0) {
return "";
}
return concat$8([" ", group$3(indent$6(concat$8([softline$4, join$6(concat$8([ifBreak$3("", " "), softline$4]), path.map(print, "directives"))])))]);
}
function printSequence(sequencePath, options, print) {
var count = sequencePath.getValue().length;
return sequencePath.map(function (path, i) {
var printed = print(path);
if (isNextLineEmpty$4(options.originalText, path.getValue(), options) && i < count - 1) {
return concat$8([printed, hardline$7]);
}
return printed;
});
}
function canAttachComment$1(node) {
return node.kind && node.kind !== "Comment";
}
function printComment$2(commentPath) {
var comment = commentPath.getValue();
switch (comment.kind) {
case "Comment":
return "#" + comment.value.trimRight();
default:
throw new Error("Not a comment: " + JSON.stringify(comment));
}
}
function determineInterfaceSeparator(originalSource) {
var start = originalSource.indexOf("implements");
if (start === -1) {
throw new Error("Must implement interfaces: " + originalSource);
}
var end = originalSource.indexOf("{");
if (end === -1) {
end = originalSource.length;
}
return originalSource.substr(start, end).includes("&") ? " & " : ", ";
}
function clean$5(node, newNode
/*, parent*/
) {
delete newNode.loc;
delete newNode.comments;
}
var printerGraphql = {
print: genericPrint$4,
massageAstNode: clean$5,
hasPrettierIgnore: hasIgnoreComment$3,
printComment: printComment$2,
canAttachComment: canAttachComment$1
};
var options$9 = {
bracketSpacing: commonOptions.bracketSpacing
};
// https://github.com/github/linguist/blob/master/lib/linguist/languages.yml
var languages$2 = [{
name: "GraphQL",
since: "1.5.0",
parsers: ["graphql"],
extensions: [".graphql", ".gql"],
tmScope: "source.graphql",
aceMode: "text",
liguistLanguageId: 139,
vscodeLanguageIds: ["graphql"]
}];
var printers$2 = {
graphql: printerGraphql
};
var languageGraphql = {
languages: languages$2,
options: options$9,
printers: printers$2
};
var _require$$0$builders$5 = doc.builders;
var hardline$9 = _require$$0$builders$5.hardline;
var literalline$4 = _require$$0$builders$5.literalline;
var concat$10 = _require$$0$builders$5.concat;
var markAsRoot$2 = _require$$0$builders$5.markAsRoot;
var mapDoc$4 = doc.utils.mapDoc;
function embed$2(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 lang = node.lang.split(/\s/, 1)[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(node.value, {
parser: parser
});
return markAsRoot$2(concat$10([style, node.lang, hardline$9, replaceNewlinesWithLiterallines(doc$$2), style]));
}
}
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.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$4(doc$$2, function (currentDoc) {
return typeof currentDoc === "string" && currentDoc.includes("\n") ? concat$10(currentDoc.split(/(\n)/g).map(function (v, i) {
return i % 2 === 0 ? v : literalline$4;
})) : currentDoc;
});
}
}
var embed_1$2 = embed$2;
function parse$3(text) {
var delimiter;
if (text.indexOf("---") === 0) {
delimiter = "---";
} else if (text.indexOf("+++") === 0) {
delimiter = "+++";
}
var end = -1;
if (!delimiter || (end = text.indexOf("\n".concat(delimiter), 3)) === -1) {
return {
frontMatter: null,
content: text
};
}
end = end + 4;
return {
frontMatter: text.slice(0, end),
content: text.slice(end)
};
}
var frontMatter = parse$3;
var pragma$2 = 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, "\n\n").concat(pragma, "\n\n").concat(extracted.content) : "".concat(pragma, "\n\n").concat(extracted.content);
}
};
});
var _require$$0$builders$4 = doc.builders;
var concat$9 = _require$$0$builders$4.concat;
var join$7 = _require$$0$builders$4.join;
var line$6 = _require$$0$builders$4.line;
var literalline$3 = _require$$0$builders$4.literalline;
var markAsRoot$1 = _require$$0$builders$4.markAsRoot;
var hardline$8 = _require$$0$builders$4.hardline;
var softline$5 = _require$$0$builders$4.softline;
var fill$4 = _require$$0$builders$4.fill;
var align$2 = _require$$0$builders$4.align;
var indent$7 = _require$$0$builders$4.indent;
var group$4 = _require$$0$builders$4.group;
var mapDoc$3 = doc.utils.mapDoc;
var printDocToString$2 = doc.printer.printDocToString;
var SINGLE_LINE_NODE_TYPES = ["heading", "tableCell", "link"];
var SIBLING_NODE_TYPES = ["listItem", "definition", "footnoteDefinition"];
var INLINE_NODE_TYPES = ["liquidNode", "inlineCode", "emphasis", "strong", "delete", "link", "linkReference", "image", "imageReference", "footnote", "footnoteReference", "sentence", "whitespace", "word", "break"];
var INLINE_NODE_WRAPPER_TYPES = INLINE_NODE_TYPES.concat(["tableCell", "paragraph", "heading"]);
function genericPrint$5(path, options, print) {
var node = path.getValue();
if (shouldRemainTheSameContent(path)) {
return concat$9(util.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$9([normalizeDoc(printRoot(path, options, print)), hardline$8]);
case "paragraph":
return printChildren(path, options, print, {
postprocessor: fill$4
});
case "sentence":
return printChildren(path, options, print);
case "word":
return node.value.replace(/[*]/g, "\\*") // escape all `*`
.replace(new RegExp(["(^|[".concat(util.punctuationCharRange, "])(_+)"), "(_+)([".concat(util.punctuationCharRange, "]|$)")].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$9([style, printChildren(path, options, print), style]);
}
case "strong":
return concat$9(["**", printChildren(path, options, print), "**"]);
case "delete":
return concat$9(["~~", printChildren(path, options, print), "~~"]);
case "inlineCode":
{
var backtickCount = util.getMaxContinuousCount(node.value, "`");
var _style = backtickCount === 1 ? "``" : "`";
var gap = backtickCount ? " " : "";
return concat$9([_style, gap, node.value, gap, _style]);
}
case "link":
switch (options.originalText[node.position.start.offset]) {
case "<":
return concat$9(["<", node.url, ">"]);
case "[":
return concat$9(["[", printChildren(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$9(["![", node.alt || "", "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]);
case "blockquote":
return concat$9(["> ", align$2("> ", printChildren(path, options, print))]);
case "heading":
return concat$9(["#".repeat(node.depth) + " ", printChildren(path, options, print)]);
case "code":
{
if ( // the first char may point to `\n`, e.g. `\n\t\tbar`, just ignore it
/^\n?( {4,}|\t)/.test(options.originalText.slice(node.position.start.offset, node.position.end.offset))) {
// indented code block
var alignment = " ".repeat(4);
return align$2(alignment, concat$9([alignment, join$7(hardline$8, node.value.split("\n"))]));
} // fenced code block
var styleUnit = options.__inJsTemplate ? "~" : "`";
var _style2 = styleUnit.repeat(Math.max(3, util.getMaxContinuousCount(node.value, styleUnit) + 1));
return concat$9([_style2, node.lang || "", hardline$8, join$7(hardline$8, node.value.split("\n")), hardline$8, _style2]);
}
case "front-matter":
return node.value;
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 replaceNewlinesWith(value, isHtmlComment ? hardline$8 : markAsRoot$1(literalline$3));
}
case "list":
{
var nthSiblingIndex = getNthListSiblingIndex(node, path.getParentNode());
var isGitDiffFriendlyOrderedList = node.ordered && node.children.length > 1 && /^\s*1(\.|\))/.test(options.originalText.slice(node.children[1].position.start.offset, node.children[1].position.end.offset));
return printChildren(path, options, print, {
processor: function processor(childPath, index) {
var prefix = getPrefix();
return concat$9([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 ? "- " : "* "; // do not print trailing spaces for empty list item since it might be treated as `break` node
// by [doc-printer](https://github.com/prettier/prettier/blob/1.10.2/src/doc/doc-printer.js#L395-L405),
// we don't want to preserve unnecessary trailing spaces.
var listItem = childPath.getValue();
return listItem.children.length ? 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$9(["[", printChildren(path, options, print), "]", node.referenceType === "full" ? concat$9(["[", node.identifier, "]"]) : node.referenceType === "collapsed" ? "[]" : ""]);
case "imageReference":
switch (node.referenceType) {
case "full":
return concat$9(["![", node.alt || "", "][", node.identifier, "]"]);
default:
return concat$9(["![", node.alt, "]", node.referenceType === "collapsed" ? "[]" : ""]);
}
case "definition":
{
var lineOrSpace = options.proseWrap === "always" ? line$6 : " ";
return group$4(concat$9([concat$9(["[", node.identifier, "]:"]), indent$7(concat$9([lineOrSpace, printUrl(node.url), node.title === null ? "" : concat$9([lineOrSpace, printTitle(node.title, options, false)])]))]));
}
case "footnote":
return concat$9(["[^", printChildren(path, options, print), "]"]);
case "footnoteReference":
return concat$9(["[^", node.identifier, "]"]);
case "footnoteDefinition":
{
var _nextNode2 = path.getParentNode().children[path.getName() + 1];
return concat$9(["[^", node.identifier, "]: ", group$4(concat$9([align$2(" ".repeat(options.tabWidth), printChildren(path, options, print, {
processor: function processor(childPath, index) {
return index === 0 ? group$4(concat$9([softline$5, softline$5, childPath.call(print)])) : childPath.call(print);
}
})), _nextNode2 && _nextNode2.type === "footnoteDefinition" ? softline$5 : ""]))]);
}
case "table":
return printTable(path, options, print);
case "tableCell":
return printChildren(path, options, print);
case "break":
return /\s/.test(options.originalText[node.position.start.offset]) ? concat$9([" ", markAsRoot$1(literalline$3)]) : concat$9(["\\", hardline$8]);
case "liquidNode":
return replaceNewlinesWith(node.value, hardline$8);
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$9([prefix, printChildren(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$9([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 replaceNewlinesWith(str, doc$$2) {
return join$7(doc$$2, str.split("\n"));
}
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$8;
}
var isBreakable = options.proseWrap === "always" && !getAncestorNode$2(path, SINGLE_LINE_NODE_TYPES);
return value !== "" ? isBreakable ? line$6 : " " : isBreakable ? softline$5 : "";
}
function printTable(path, options, print) {
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");
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 (---, :--, :-:, --:)
);
return join$7(hardline$8, [printRow(contents[0]), printSeparator(), join$7(hardline$8, contents.slice(1).map(printRow))]);
function printSeparator() {
return concat$9(["| ", join$7(" | ", columnMaxWidths.map(function (width, index) {
switch (node.align[index]) {
case "left":
return ":" + "-".repeat(width - 1);
case "right":
return "-".repeat(width - 1) + ":";
case "center":
return ":" + "-".repeat(width - 2) + ":";
default:
return "-".repeat(width);
}
})), " |"]);
}
function printRow(rowContents) {
return concat$9(["| ", join$7(" | ", 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) {
return concat$9([text, " ".repeat(width - util.getStringWidth(text))]);
}
function alignRight(text, width) {
return concat$9([" ".repeat(width - util.getStringWidth(text)), text]);
}
function alignCenter(text, width) {
var spaces = width - util.getStringWidth(text);
var left = Math.floor(spaces / 2);
var right = spaces - left;
return concat$9([" ".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(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(path, options, print, {
processor: function processor(childPath, index) {
if (ignoreRanges.length !== 0) {
var ignoreRange = ignoreRanges[0];
if (index === ignoreRange.start.index) {
return concat$9([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(path, options, print, events) {
events = events || {};
var postprocessor = events.postprocessor || concat$9;
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$8);
if (shouldPrePrintDoubleHardline(childNode, data) || shouldPrePrintTripleHardline(childNode, data)) {
parts.push(hardline$8);
}
if (shouldPrePrintTripleHardline(childNode, data)) {
parts.push(hardline$8);
}
}
parts.push(result);
lastChildNode = childNode;
}
}, "children");
return postprocessor(parts);
}
/** @return {false | 'next' | 'start' | 'end'} */
function isPrettierIgnore(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(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" && /\s/.test(data.options.originalText[node.position.start.offset]);
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$3(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(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(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$6(ast, newObj, parent) {
delete newObj.position; // for codeblock
if (ast.type === "code") {
delete newObj.value;
} // for whitespace: "\n" and " " are considered the same
if (ast.type === "whitespace" && ast.value === "\n") {
newObj.value = " ";
} // for insert pragma
if (parent && parent.type === "root" && parent.children.length > 0 && (parent.children[0] === ast || parent.children[0].type === "front-matter" && parent.children[1] === ast) && ast.type === "html" && pragma$2.startWithPragma(ast.value)) {
return null;
}
}
function hasPrettierIgnore$1(path) {
var index = +path.getName();
if (index === 0) {
return false;
}
var prevNode = path.getParentNode().children[index - 1];
return isPrettierIgnore(prevNode) === "next";
}
var printerMarkdown = {
print: genericPrint$5,
embed: embed_1$2,
massageAstNode: clean$6,
hasPrettierIgnore: hasPrettierIgnore$1,
insertPragma: pragma$2.insertPragma
};
var CATEGORY_MARKDOWN = "Markdown"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
var options$12 = {
proseWrap: {
since: "1.8.2",
category: CATEGORY_MARKDOWN,
type: "choice",
default: [{
since: "1.8.2",
value: true
}, {
since: "1.9.0",
value: "preserve"
}],
description: "How to wrap prose. (markdown)",
choices: [{
since: "1.9.0",
value: "always",
description: "Wrap prose if it exceeds the print width."
}, {
since: "1.9.0",
value: "never",
description: "Do not wrap prose."
}, {
since: "1.9.0",
value: "preserve",
description: "Wrap prose as-is."
}, {
value: false,
deprecated: "1.9.0",
redirect: "never"
}, {
value: true,
deprecated: "1.9.0",
redirect: "always"
}]
},
singleQuote: commonOptions.singleQuote
};
// https://github.com/github/linguist/blob/master/lib/linguist/languages.yml
var languages$3 = [{
name: "Markdown",
since: "1.8.0",
parsers: ["remark"],
aliases: ["pandoc"],
aceMode: "markdown",
codemirrorMode: "gfm",
codemirrorMimeType: "text/x-gfm",
wrap: true,
extensions: [".md", ".markdown", ".mdown", ".mdwn", ".mkd", ".mkdn", ".mkdown", ".ron", ".workbook"],
filenames: ["README"],
tmScope: "source.gfm",
linguistLanguageId: 222,
vscodeLanguageIds: ["markdown"]
}];
var printers$3 = {
mdast: printerMarkdown
};
var languageMarkdown = {
languages: languages$3,
options: options$12,
printers: printers$3
};
var _require$$0$builders$7 = doc.builders;
var concat$12 = _require$$0$builders$7.concat;
var hardline$11 = _require$$0$builders$7.hardline;
function embed$4(path, print, textToDoc, options) {
var node = path.getValue();
var parent = path.getParentNode();
if (!parent || parent.tag !== "root" || node.unary) {
return null;
}
var parser;
if (node.tag === "style") {
var langAttr = node.attrs.find(function (attr) {
return attr.name === "lang";
});
if (!langAttr || langAttr.value === "postcss") {
parser = "css";
} else if (langAttr.value === "scss") {
parser = "scss";
} else if (langAttr.value === "less") {
parser = "less";
}
}
if (node.tag === "script") {
var _langAttr = node.attrs.find(function (attr) {
return attr.name === "lang";
});
if (!_langAttr) {
parser = "babylon";
} else if (_langAttr.value === "ts" || _langAttr.value === "tsx") {
parser = "typescript";
}
}
if (!parser) {
return null;
}
return concat$12([options.originalText.slice(node.start, node.contentStart), hardline$11, textToDoc(options.originalText.slice(node.contentStart, node.contentEnd), {
parser: parser
}), options.originalText.slice(node.contentEnd, node.end)]);
}
var embed_1$4 = embed$4;
var _require$$0$builders$6 = doc.builders;
var concat$11 = _require$$0$builders$6.concat;
var hardline$10 = _require$$0$builders$6.hardline;
function genericPrint$6(path, options, print) {
var n = path.getValue();
var res = [];
var index = n.start;
path.each(function (childPath) {
var child = childPath.getValue();
res.push(options.originalText.slice(index, child.start));
res.push(childPath.call(print));
index = child.end;
}, "children"); // If there are no children, we just print the node from start to end.
// Otherwise, index should point to the end of the last child, and we
// need to print the closing tag.
res.push(options.originalText.slice(index, n.end)); // Only force a trailing newline if there were any contents.
if (n.tag === "root" && n.children.length) {
res.push(hardline$10);
}
return concat$11(res);
}
var clean$7 = function clean(ast, newObj) {
delete newObj.start;
delete newObj.end;
delete newObj.contentStart;
delete newObj.contentEnd;
};
var printerVue = {
print: genericPrint$6,
embed: embed_1$4,
massageAstNode: clean$7
};
// https://github.com/github/linguist/blob/master/lib/linguist/languages.yml
var languages$4 = [{
name: "Vue",
since: "1.10.0",
parsers: ["vue"],
group: "HTML",
tmScope: "text.html.vue",
aceMode: "html",
codemirrorMode: "htmlmixed",
codemirrorMimeType: "text/html",
extensions: [".vue"],
linguistLanguageId: 146,
vscodeLanguageIds: ["vue"]
}];
var printers$4 = {
vue: printerVue
};
var languageVue = {
languages: languages$4,
printers: printers$4
};
var version = require$$0.version;
var getSupportInfo = support.getSupportInfo;
var internalPlugins = [languageJs, languageCss, languageGraphql, languageMarkdown, languageVue];
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 = {
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)
}
};
return standalone;
})));