!nameHasComments || n.attributes.length) && !lastAttrHasTrailingComments; // We should print the opening element expanded if any prop value is a
// string literal with newlines
const shouldBreak = n.attributes && n.attributes.some(attr => attr.value && isStringLiteral$1(attr.value) && attr.value.value.includes("\n"));
return group$7(concat$b(["<", path.call(print, "name"), path.call(print, "typeParameters"), concat$b([indent$8(concat$b(path.map(attr => concat$b([line$8, print(attr)]), "attributes"))), n.selfClosing ? line$8 : bracketSameLine ? ">" : softline$6]), n.selfClosing ? "/>" : bracketSameLine ? "" : ">"]), {
shouldBreak
});
}
case "JSXClosingElement":
return concat$b(["", path.call(print, "name"), ">"]);
case "JSXOpeningFragment":
case "JSXClosingFragment":
{
const hasComment = n.comments && n.comments.length;
const hasOwnLineComment = hasComment && !n.comments.every(comments$1.isBlockComment);
const isOpeningFragment = n.type === "JSXOpeningFragment";
return concat$b([isOpeningFragment ? "<" : "", indent$8(concat$b([hasOwnLineComment ? hardline$6 : hasComment && !isOpeningFragment ? " " : "", comments.printDanglingComments(path, options, true)])), hasOwnLineComment ? hardline$6 : "", ">"]);
}
case "JSXText":
/* istanbul ignore next */
throw new Error("JSXTest should be handled by JSXElement");
case "JSXEmptyExpression":
{
const requiresHardline = n.comments && !n.comments.every(comments$1.isBlockComment);
return concat$b([comments.printDanglingComments(path, options,
/* sameIndent */
!requiresHardline), requiresHardline ? hardline$6 : ""]);
}
case "ClassBody":
if (!n.comments && n.body.length === 0) {
return "{}";
}
return concat$b(["{", n.body.length > 0 ? indent$8(concat$b([hardline$6, path.call(bodyPath => {
return printStatementSequence(bodyPath, options, print);
}, "body")])) : comments.printDanglingComments(path, options), hardline$6, "}"]);
case "ClassProperty":
case "TSAbstractClassProperty":
case "ClassPrivateProperty":
{
if (n.decorators && n.decorators.length !== 0) {
parts.push(printDecorators(path, options, print));
}
if (n.accessibility) {
parts.push(n.accessibility + " ");
}
if (n.declare) {
parts.push("declare ");
}
if (n.static) {
parts.push("static ");
}
if (n.type === "TSAbstractClassProperty" || n.abstract) {
parts.push("abstract ");
}
if (n.readonly) {
parts.push("readonly ");
}
const variance = getFlowVariance$1(n);
if (variance) {
parts.push(variance);
}
parts.push(printPropertyKey(path, options, print), printOptionalToken$2(path), printTypeAnnotation(path, options, print));
if (n.value) {
parts.push(" =", printAssignmentRight(n.key, n.value, path.call(print, "value"), options));
}
parts.push(semi);
return group$7(concat$b(parts));
}
case "ClassDeclaration":
case "ClassExpression":
if (n.declare) {
parts.push("declare ");
}
parts.push(concat$b(printClass(path, options, print)));
return concat$b(parts);
case "TSInterfaceHeritage":
case "TSExpressionWithTypeArguments":
// Babel AST
parts.push(path.call(print, "expression"));
if (n.typeParameters) {
parts.push(path.call(print, "typeParameters"));
}
return concat$b(parts);
case "TemplateElement":
return join$6(literalline$2, n.value.raw.split(/\r?\n/g));
case "TemplateLiteral":
{
const parentNode = path.getParentNode();
if (isJestEachTemplateLiteral$1(n, parentNode)) {
const printed = printJestEachTemplateLiteral(path, options, print);
if (printed) {
return printed;
}
}
let expressions = path.map(print, "expressions");
const isSimple = isSimpleTemplateLiteral$1(n);
if (isSimple) {
expressions = expressions.map(doc => printDocToString$2(doc, Object.assign({}, options, {
printWidth: Infinity
})).formatted);
}
parts.push(lineSuffixBoundary$1, "`");
path.each(childPath => {
const 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 `.
const {
tabWidth
} = options;
const quasi = childPath.getValue();
const indentSize = getIndentSize$2(quasi.value.raw, tabWidth);
let printed = expressions[i];
if (!isSimple) {
// Breaks at the template element boundaries (${ and }) are preferred to breaking
// in the middle of a MemberExpression
if (n.expressions[i].comments && n.expressions[i].comments.length || n.expressions[i].type === "MemberExpression" || n.expressions[i].type === "OptionalMemberExpression" || n.expressions[i].type === "ConditionalExpression" || n.expressions[i].type === "SequenceExpression" || n.expressions[i].type === "TSAsExpression" || isBinaryish$1(n.expressions[i])) {
printed = concat$b([indent$8(concat$b([softline$6, printed])), softline$6]);
}
}
const aligned = indentSize === 0 && quasi.value.raw.endsWith("\n") ? align$2(-Infinity, printed) : addAlignmentToDoc$2(printed, indentSize, tabWidth);
parts.push(group$7(concat$b(["${", aligned, lineSuffixBoundary$1, "}"])));
}
}, "quasis");
parts.push("`");
return concat$b(parts);
}
case "TaggedTemplateExpression":
return concat$b([path.call(print, "tag"), path.call(print, "typeParameters"), path.call(print, "quasi")]);
// These types are unprintable because they serve as abstract
// supertypes for other (printable) types.
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 "TSNamedTupleMember":
return concat$b([path.call(print, "label"), n.optional ? "?" : "", ": ", path.call(print, "elementType")]);
case "TSTupleType":
case "TupleTypeAnnotation":
{
const typesField = n.type === "TSTupleType" ? "elementTypes" : "types";
const hasRest = n[typesField].length > 0 && getLast$5(n[typesField]).type === "TSRestType";
return group$7(concat$b(["[", indent$8(concat$b([softline$6, printArrayItems(path, options, typesField, print)])), ifBreak$4(shouldPrintComma$3(options, "all") && !hasRest ? "," : ""), comments.printDanglingComments(path, options,
/* sameIndent */
true), softline$6, "]"]));
}
case "ExistsTypeAnnotation":
return "*";
case "EmptyTypeAnnotation":
return "empty";
case "AnyTypeAnnotation":
return "any";
case "MixedTypeAnnotation":
return "mixed";
case "ArrayTypeAnnotation":
return concat$b([path.call(print, "elementType"), "[]"]);
case "BooleanTypeAnnotation":
return "boolean";
case "BooleanLiteralTypeAnnotation":
return "" + n.value;
case "DeclareClass":
return printFlowDeclaration(path, printClass(path, options, print));
case "TSDeclareFunction":
// For TypeScript the TSDeclareFunction node shares the AST
// structure with FunctionDeclaration
return concat$b([n.declare ? "declare " : "", printFunctionDeclaration(path, print, options), semi]);
case "DeclareFunction":
return printFlowDeclaration(path, ["function ", path.call(print, "id"), n.predicate ? " " : "", path.call(print, "predicate"), semi]);
case "DeclareModule":
return printFlowDeclaration(path, ["module ", path.call(print, "id"), " ", path.call(print, "body")]);
case "DeclareModuleExports":
return printFlowDeclaration(path, ["module.exports", ": ", path.call(print, "typeAnnotation"), semi]);
case "DeclareVariable":
return printFlowDeclaration(path, ["var ", path.call(print, "id"), semi]);
case "DeclareExportAllDeclaration":
return concat$b(["declare export *", printModuleSource$1(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$b(parts);
}
case "EnumDeclaration":
return concat$b(["enum ", path.call(print, "id"), " ", path.call(print, "body")]);
case "EnumBooleanBody":
case "EnumNumberBody":
case "EnumStringBody":
case "EnumSymbolBody":
{
if (n.type === "EnumSymbolBody" || n.explicitType) {
let type = null;
switch (n.type) {
case "EnumBooleanBody":
type = "boolean";
break;
case "EnumNumberBody":
type = "number";
break;
case "EnumStringBody":
type = "string";
break;
case "EnumSymbolBody":
type = "symbol";
break;
}
parts.push("of ", type, " ");
}
if (n.members.length === 0) {
parts.push(group$7(concat$b(["{", comments.printDanglingComments(path, options), softline$6, "}"])));
} else {
parts.push(group$7(concat$b(["{", indent$8(concat$b([hardline$6, printArrayItems(path, options, "members", print), shouldPrintComma$3(options) ? "," : ""])), comments.printDanglingComments(path, options,
/* sameIndent */
true), hardline$6, "}"])));
}
return concat$b(parts);
}
case "EnumBooleanMember":
case "EnumNumberMember":
case "EnumStringMember":
return concat$b([path.call(print, "id"), " = ", typeof n.init === "object" ? path.call(print, "init") : String(n.init)]);
case "EnumDefaultedMember":
return path.call(print, "id");
case "FunctionTypeAnnotation":
case "TSFunctionType":
{
// FunctionTypeAnnotation is ambiguous:
// declare function foo(a: B): void; OR
// var A: (a: B) => void;
const parent = path.getParentNode(0);
const parentParent = path.getParentNode(1);
const parentParentParent = path.getParentNode(2);
let isArrowFunctionTypeAnnotation = n.type === "TSFunctionType" || !((parent.type === "ObjectTypeProperty" || parent.type === "ObjectTypeInternalSlot") && !getFlowVariance$1(parent) && !parent.optional && options.locStart(parent) === options.locStart(n) || parent.type === "ObjectTypeCallProperty" || parentParentParent && parentParentParent.type === "DeclareFunction");
let needsColon = isArrowFunctionTypeAnnotation && (parent.type === "TypeAnnotation" || parent.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 :(
const needsParens = needsColon && isArrowFunctionTypeAnnotation && (parent.type === "TypeAnnotation" || parent.type === "TSTypeAnnotation") && parentParent.type === "ArrowFunctionExpression";
if (isObjectTypePropertyAFunction$1(parent, 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$7(concat$b(parts));
}
case "TSRestType":
return concat$b(["...", path.call(print, "typeAnnotation")]);
case "TSOptionalType":
return concat$b([path.call(print, "typeAnnotation"), "?"]);
case "FunctionTypeParam":
return concat$b([path.call(print, "name"), printOptionalToken$2(path), n.name ? ": " : "", path.call(print, "typeAnnotation")]);
case "GenericTypeAnnotation":
return concat$b([path.call(print, "id"), path.call(print, "typeParameters")]);
case "DeclareInterface":
case "InterfaceDeclaration":
case "InterfaceTypeAnnotation":
case "TSInterfaceDeclaration":
{
if (n.type === "DeclareInterface" || n.declare) {
parts.push("declare ");
}
if (n.type === "TSInterfaceDeclaration") {
parts.push(n.abstract ? "abstract " : "", printTypeScriptModifiers(path, options, print));
}
parts.push("interface");
const partsGroup = [];
const extendsParts = [];
if (n.type !== "InterfaceTypeAnnotation") {
partsGroup.push(" ", path.call(print, "id"), path.call(print, "typeParameters"));
}
const shouldIndentOnlyHeritageClauses = n.typeParameters && !hasTrailingLineComment$1(n.typeParameters);
if (n.extends && n.extends.length !== 0) {
extendsParts.push(shouldIndentOnlyHeritageClauses ? ifBreak$4(" ", line$8, {
groupId: getTypeParametersGroupId(n.typeParameters)
}) : line$8, "extends ", (n.extends.length === 1 ? identity$2 : indent$8)(join$6(concat$b([",", line$8]), path.map(print, "extends"))));
}
if (n.id && hasTrailingComment$3(n.id) || n.extends && n.extends.length !== 0) {
const printedExtends = concat$b(extendsParts);
if (shouldIndentOnlyHeritageClauses) {
parts.push(group$7(concat$b(partsGroup.concat(ifBreak$4(indent$8(printedExtends), printedExtends)))));
} else {
parts.push(group$7(indent$8(concat$b(partsGroup.concat(printedExtends)))));
}
} else {
parts.push(...partsGroup, ...extendsParts);
}
parts.push(" ", path.call(print, "body"));
return group$7(concat$b(parts));
}
case "ClassImplements":
case "InterfaceExtends":
return concat$b([path.call(print, "id"), path.call(print, "typeParameters")]);
case "TSClassImplements":
return concat$b([path.call(print, "expression"), path.call(print, "typeParameters")]);
case "TSIntersectionType":
case "IntersectionTypeAnnotation":
{
const types = path.map(print, "types");
const result = [];
let wasIndented = false;
for (let i = 0; i < types.length; ++i) {
if (i === 0) {
result.push(types[i]);
} else if (isObjectType$1(n.types[i - 1]) && isObjectType$1(n.types[i])) {
// If both are objects, don't indent
result.push(concat$b([" & ", wasIndented ? indent$8(types[i]) : types[i]]));
} else if (!isObjectType$1(n.types[i - 1]) && !isObjectType$1(n.types[i])) {
// If no object is involved, go to the next line if it breaks
result.push(indent$8(concat$b([" &", line$8, types[i]])));
} else {
// If you go from object to non-object or vis-versa, then inline it
if (i > 1) {
wasIndented = true;
}
result.push(" & ", i > 1 ? indent$8(types[i]) : types[i]);
}
}
return group$7(concat$b(result));
}
case "TSUnionType":
case "UnionTypeAnnotation":
{
// single-line variation
// A | B | C
// multi-line variation
// | A
// | B
// | C
const parent = path.getParentNode(); // If there's a leading comment, the parent is doing the indentation
const shouldIndent = parent.type !== "TypeParameterInstantiation" && parent.type !== "TSTypeParameterInstantiation" && parent.type !== "GenericTypeAnnotation" && parent.type !== "TSTypeReference" && parent.type !== "TSTypeAssertion" && parent.type !== "TupleTypeAnnotation" && parent.type !== "TSTupleType" && !(parent.type === "FunctionTypeParam" && !parent.name) && !((parent.type === "TypeAlias" || parent.type === "VariableDeclarator" || parent.type === "TSTypeAliasDeclaration") && hasLeadingOwnLineComment$1(options.originalText, n, options)); // {
// a: string
// } | null | void
// should be inlined and not be printed in the multi-line variant
const shouldHug = shouldHugType(n); // We want to align the children but without its comment, so it looks like
// | child1
// // comment
// | child2
const printed = path.map(typePath => {
let printedType = typePath.call(print);
if (!shouldHug) {
printedType = align$2(2, printedType);
}
return comments.printComments(typePath, () => printedType, options);
}, "types");
if (shouldHug) {
return join$6(" | ", printed);
}
const shouldAddStartLine = shouldIndent && !hasLeadingOwnLineComment$1(options.originalText, n, options);
const code = concat$b([ifBreak$4(concat$b([shouldAddStartLine ? line$8 : "", "| "])), join$6(concat$b([line$8, "| "]), printed)]);
if (needsParens_1(path, options)) {
return group$7(concat$b([indent$8(code), softline$6]));
}
if (parent.type === "TupleTypeAnnotation" && parent.types.length > 1 || parent.type === "TSTupleType" && parent.elementTypes.length > 1) {
return group$7(concat$b([indent$8(concat$b([ifBreak$4(concat$b(["(", softline$6])), code])), softline$6, ifBreak$4(")")]));
}
return group$7(shouldIndent ? indent$8(code) : code);
}
case "NullableTypeAnnotation":
return concat$b(["?", path.call(print, "typeAnnotation")]);
case "TSNullKeyword":
case "NullLiteralTypeAnnotation":
return "null";
case "ThisTypeAnnotation":
return "this";
case "NumberTypeAnnotation":
return "number";
case "SymbolTypeAnnotation":
return "symbol";
case "ObjectTypeCallProperty":
if (n.static) {
parts.push("static ");
}
parts.push(path.call(print, "value"));
return concat$b(parts);
case "ObjectTypeIndexer":
{
const variance = getFlowVariance$1(n);
return concat$b([variance || "", "[", path.call(print, "id"), n.id ? ": " : "", path.call(print, "key"), "]: ", path.call(print, "value")]);
}
case "ObjectTypeProperty":
{
const variance = getFlowVariance$1(n);
let modifier = "";
if (n.proto) {
modifier = "proto ";
} else if (n.static) {
modifier = "static ";
}
return concat$b([modifier, isGetterOrSetter$1(n) ? n.kind + " " : "", variance || "", printPropertyKey(path, options, print), printOptionalToken$2(path), isFunctionNotation$1(n, options) ? "" : ": ", path.call(print, "value")]);
}
case "QualifiedTypeIdentifier":
return concat$b([path.call(print, "qualification"), ".", path.call(print, "id")]);
case "StringLiteralTypeAnnotation":
return nodeStr(n, options);
case "NumberLiteralTypeAnnotation":
assert__default['default'].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" || n.declare) {
parts.push("declare ");
}
const printed = printAssignmentRight(n.id, n.right, path.call(print, "right"), options);
parts.push("type ", path.call(print, "id"), path.call(print, "typeParameters"), " =", printed, semi);
return group$7(concat$b(parts));
}
case "TypeCastExpression":
{
return concat$b(["(", path.call(print, "expression"), printTypeAnnotation(path, options, print), ")"]);
}
case "TypeParameterDeclaration":
case "TypeParameterInstantiation":
{
const value = path.getValue();
const commentStart = options.originalText.slice(0, options.locStart(value)).lastIndexOf("/*"); // As noted in the TypeCastExpression comments above, we're able to use a normal whitespace regex here
// because we know for sure that this is a type definition.
const commentSyntax = commentStart >= 0 && options.originalText.slice(commentStart).match(/^\/\*\s*::/);
if (commentSyntax) {
return concat$b(["/*:: ", printTypeParameters(path, options, print, "params"), " */"]);
}
return printTypeParameters(path, options, print, "params");
}
case "TSTypeParameterDeclaration":
case "TSTypeParameterInstantiation":
return printTypeParameters(path, options, print, "params");
case "TSTypeParameter":
case "TypeParameter":
{
const parent = path.getParentNode();
if (parent.type === "TSMappedType") {
parts.push("[", path.call(print, "name"));
if (n.constraint) {
parts.push(" in ", path.call(print, "constraint"));
}
parts.push("]");
return concat$b(parts);
}
const variance = getFlowVariance$1(n);
if (variance) {
parts.push(variance);
}
parts.push(path.call(print, "name"));
if (n.bound) {
parts.push(": ");
parts.push(path.call(print, "bound"));
}
if (n.constraint) {
parts.push(" extends ", path.call(print, "constraint"));
}
if (n.default) {
parts.push(" = ", path.call(print, "default"));
} // Keep comma if the file extension is .tsx and
// has one type parameter that isn't extend with any types.
// Because, otherwise formatted result will be invalid as tsx.
const grandParent = path.getNode(2);
if (parent.params && parent.params.length === 1 && isTSXFile$1(options) && !n.constraint && grandParent.type === "ArrowFunctionExpression") {
parts.push(",");
}
return concat$b(parts);
}
case "TypeofTypeAnnotation":
return concat$b(["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$b(["%checks(", path.call(print, "value"), ")"]);
case "TSAbstractKeyword":
return "abstract";
case "TSAnyKeyword":
return "any";
case "TSAsyncKeyword":
return "async";
case "TSBooleanKeyword":
return "boolean";
case "TSBigIntKeyword":
return "bigint";
case "TSConstKeyword":
return "const";
case "TSDeclareKeyword":
return "declare";
case "TSExportKeyword":
return "export";
case "TSNeverKeyword":
return "never";
case "TSNumberKeyword":
return "number";
case "TSObjectKeyword":
return "object";
case "TSProtectedKeyword":
return "protected";
case "TSPrivateKeyword":
return "private";
case "TSPublicKeyword":
return "public";
case "TSReadonlyKeyword":
return "readonly";
case "TSSymbolKeyword":
return "symbol";
case "TSStaticKeyword":
return "static";
case "TSStringKeyword":
return "string";
case "TSUndefinedKeyword":
return "undefined";
case "TSUnknownKeyword":
return "unknown";
case "TSVoidKeyword":
return "void";
case "TSAsExpression":
return concat$b([path.call(print, "expression"), " as ", path.call(print, "typeAnnotation")]);
case "TSArrayType":
return concat$b([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 ");
}
parts.push(printPropertyKey(path, options, print), printOptionalToken$2(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$b(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$b(parts);
case "TSTypeReference":
return concat$b([path.call(print, "typeName"), printTypeParameters(path, options, print, "typeParameters")]);
case "TSTypeQuery":
return concat$b(["typeof ", path.call(print, "exprName")]);
case "TSIndexSignature":
{
const parent = path.getParentNode(); // The typescript parser accepts multiple parameters here. If you're
// using them, it makes sense to have a trailing comma. But if you
// aren't, this is more like a computed property name than an array.
// So we leave off the trailing comma when there's just one parameter.
const trailingComma = n.parameters.length > 1 ? ifBreak$4(shouldPrintComma$3(options) ? "," : "") : "";
const parametersGroup = group$7(concat$b([indent$8(concat$b([softline$6, join$6(concat$b([", ", softline$6]), path.map(print, "parameters"))])), trailingComma, softline$6]));
return concat$b([n.export ? "export " : "", n.accessibility ? concat$b([n.accessibility, " "]) : "", n.static ? "static " : "", n.readonly ? "readonly " : "", "[", n.parameters ? parametersGroup : "", n.typeAnnotation ? "]: " : "]", n.typeAnnotation ? path.call(print, "typeAnnotation") : "", parent.type === "ClassBody" ? semi : ""]);
}
case "TSTypePredicate":
return concat$b([n.asserts ? "asserts " : "", path.call(print, "parameterName"), n.typeAnnotation ? concat$b([" is ", path.call(print, "typeAnnotation")]) : ""]);
case "TSNonNullExpression":
return concat$b([path.call(print, "expression"), "!"]);
case "TSThisType":
return "this";
case "TSImportType":
return concat$b([!n.isTypeOf ? "" : "typeof ", "import(", path.call(print, n.parameter ? "parameter" : "argument"), ")", !n.qualifier ? "" : concat$b([".", path.call(print, "qualifier")]), printTypeParameters(path, options, print, "typeParameters")]);
case "TSLiteralType":
return path.call(print, "literal");
case "TSIndexedAccessType":
return concat$b([path.call(print, "objectType"), "[", path.call(print, "indexType"), "]"]);
case "TSConstructSignatureDeclaration":
case "TSCallSignatureDeclaration":
case "TSConstructorType":
{
if (n.type !== "TSCallSignatureDeclaration") {
parts.push("new ");
}
parts.push(group$7(printFunctionParams(path, print, options,
/* expandArg */
false,
/* printTypeParams */
true)));
if (n.returnType || n.typeAnnotation) {
const isType = n.type === "TSConstructorType";
parts.push(isType ? " => " : ": ", path.call(print, "returnType"), path.call(print, "typeAnnotation"));
}
return concat$b(parts);
}
case "TSTypeOperator":
return concat$b([n.operator, " ", path.call(print, "typeAnnotation")]);
case "TSMappedType":
{
const shouldBreak = hasNewlineInRange$5(options.originalText, options.locStart(n), options.locEnd(n));
return group$7(concat$b(["{", indent$8(concat$b([options.bracketSpacing ? line$8 : softline$6, n.readonly ? concat$b([getTypeScriptMappedTypeModifier$1(n.readonly, "readonly"), " "]) : "", printTypeScriptModifiers(path, options, print), path.call(print, "typeParameter"), n.optional ? getTypeScriptMappedTypeModifier$1(n.optional, "?") : "", n.typeAnnotation ? ": " : "", path.call(print, "typeAnnotation"), ifBreak$4(semi, "")])), comments.printDanglingComments(path, options,
/* sameIndent */
true), options.bracketSpacing ? line$8 : softline$6, "}"]), {
shouldBreak
});
}
case "TSMethodSignature":
parts.push(n.accessibility ? concat$b([n.accessibility, " "]) : "", n.export ? "export " : "", n.static ? "static " : "", n.readonly ? "readonly " : "", n.computed ? "[" : "", path.call(print, "key"), n.computed ? "]" : "", printOptionalToken$2(path), printFunctionParams(path, print, options,
/* expandArg */
false,
/* printTypeParams */
true));
if (n.returnType || n.typeAnnotation) {
parts.push(": ", path.call(print, "returnType"), path.call(print, "typeAnnotation"));
}
return group$7(concat$b(parts));
case "TSNamespaceExportDeclaration":
parts.push("export as namespace ", path.call(print, "id"));
if (options.semi) {
parts.push(";");
}
return group$7(concat$b(parts));
case "TSEnumDeclaration":
if (n.declare) {
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$7(concat$b(["{", comments.printDanglingComments(path, options), softline$6, "}"])));
} else {
parts.push(group$7(concat$b(["{", indent$8(concat$b([hardline$6, printArrayItems(path, options, "members", print), shouldPrintComma$3(options, "es5") ? "," : ""])), comments.printDanglingComments(path, options,
/* sameIndent */
true), hardline$6, "}"])));
}
return concat$b(parts);
case "TSEnumMember":
parts.push(path.call(print, "id"));
if (n.initializer) {
parts.push(" = ", path.call(print, "initializer"));
}
return concat$b(parts);
case "TSImportEqualsDeclaration":
if (n.isExport) {
parts.push("export ");
}
parts.push("import ", path.call(print, "id"), " = ", path.call(print, "moduleReference"));
if (options.semi) {
parts.push(";");
}
return group$7(concat$b(parts));
case "TSExternalModuleReference":
return concat$b(["require(", path.call(print, "expression"), ")"]);
case "TSModuleDeclaration":
{
const parent = path.getParentNode();
const isExternalModule = isLiteral$1(n.id);
const parentIsDeclaration = parent.type === "TSModuleDeclaration";
const bodyIsDeclaration = n.body && n.body.type === "TSModuleDeclaration";
if (parentIsDeclaration) {
parts.push(".");
} else {
if (n.declare) {
parts.push("declare ");
}
parts.push(printTypeScriptModifiers(path, options, print));
const textBetweenNodeAndItsId = options.originalText.slice(options.locStart(n), options.locStart(n.id)); // Global declaration looks like this:
// (declare)? global { ... }
const isGlobalDeclaration = n.id.type === "Identifier" && n.id.name === "global" && !/namespace|module/.test(textBetweenNodeAndItsId);
if (!isGlobalDeclaration) {
parts.push(isExternalModule || /(^|\s)module(\s|$)/.test(textBetweenNodeAndItsId) ? "module " : "namespace ");
}
}
parts.push(path.call(print, "id"));
if (bodyIsDeclaration) {
parts.push(path.call(print, "body"));
} else if (n.body) {
parts.push(" ", group$7(path.call(print, "body")));
} else {
parts.push(semi);
}
return concat$b(parts);
}
case "PrivateName":
return concat$b(["#", path.call(print, "id")]);
// TODO: Temporary auto-generated node type. To remove when typescript-estree has proper support for private fields.
case "TSPrivateIdentifier":
return n.escapedText;
case "TSConditionalType":
return ternary(path, options, print, {
beforeParts: () => [path.call(print, "checkType"), " ", "extends", " ", path.call(print, "extendsType")],
afterParts: () => [],
shouldCheckJsx: false,
conditionalNodeType: "TSConditionalType",
consequentNodePropertyName: "trueType",
alternateNodePropertyName: "falseType",
testNodePropertyNames: ["checkType", "extendsType"]
});
case "TSInferType":
return concat$b(["infer", " ", path.call(print, "typeParameter")]);
case "InterpreterDirective":
parts.push("#!", n.value, hardline$6);
if (isNextLineEmpty$4(options.originalText, n, options.locEnd)) {
parts.push(hardline$6);
}
return concat$b(parts);
case "NGRoot":
return concat$b([].concat(path.call(print, "node"), !n.node.comments || n.node.comments.length === 0 ? [] : concat$b([" //", n.node.comments[0].value.trimEnd()])));
case "NGChainedExpression":
return group$7(join$6(concat$b([";", line$8]), path.map(childPath => hasNgSideEffect$1(childPath) ? print(childPath) : concat$b(["(", print(childPath), ")"]), "expressions")));
case "NGEmptyExpression":
return "";
case "NGQuotedExpression":
return concat$b([n.prefix, ": ", n.value.trim()]);
case "NGMicrosyntax":
return concat$b(path.map((childPath, index) => concat$b([index === 0 ? "" : isNgForOf$1(childPath.getValue(), index, n) ? " " : concat$b([";", line$8]), print(childPath)]), "body"));
case "NGMicrosyntaxKey":
return /^[$_a-z][\w$]*(-[$_a-z][\w$])*$/i.test(n.name) ? n.name : JSON.stringify(n.name);
case "NGMicrosyntaxExpression":
return concat$b([path.call(print, "expression"), n.alias === null ? "" : concat$b([" as ", path.call(print, "alias")])]);
case "NGMicrosyntaxKeyedExpression":
{
const index = path.getName();
const parentNode = path.getParentNode();
const shouldNotPrintColon = isNgForOf$1(n, index, parentNode) || (index === 1 && (n.key.name === "then" || n.key.name === "else") || index === 2 && n.key.name === "else" && parentNode.body[index - 1].type === "NGMicrosyntaxKeyedExpression" && parentNode.body[index - 1].key.name === "then") && parentNode.body[0].type === "NGMicrosyntaxExpression";
return concat$b([path.call(print, "key"), shouldNotPrintColon ? " " : ": ", path.call(print, "expression")]);
}
case "NGMicrosyntaxLet":
return concat$b(["let ", path.call(print, "key"), n.value === null ? "" : concat$b([" = ", path.call(print, "value")])]);
case "NGMicrosyntaxAs":
return concat$b([path.call(print, "key"), " as ", path.call(print, "alias")]);
case "PipelineBareFunction":
return path.call(print, "callee");
case "PipelineTopicExpression":
return path.call(print, "expression");
case "PipelinePrimaryTopicReference":
{
parts.push("#");
return concat$b(parts);
}
case "ArgumentPlaceholder":
return "?";
// These are not valid TypeScript. Printing them just for the sake of error recovery.
case "TSJSDocAllType":
return "*";
case "TSJSDocUnknownType":
return "?";
case "TSJSDocNullableType":
return concat$b(["?", path.call(print, "typeAnnotation")]);
case "TSJSDocNonNullableType":
return concat$b(["!", path.call(print, "typeAnnotation")]);
case "TSJSDocFunctionType":
return concat$b(["function(", // The parameters could be here, but typescript-estree doesn't convert them anyway (throws an error).
"): ", path.call(print, "typeAnnotation")]);
default:
/* istanbul ignore next */
throw new Error("unknown type: " + JSON.stringify(n.type));
}
}
function printStatementSequence(path, options, print) {
const printed = [];
const bodyNode = path.getNode();
const isClass = bodyNode.type === "ClassBody";
path.map((stmtPath, i) => {
const 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;
}
const stmtPrinted = print(stmtPath);
const text = options.originalText;
const 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$1(options, stmtPath) && stmtNeedsASIProtection(stmtPath, options)) {
if (stmt.comments && stmt.comments.some(comment => comment.leading)) {
parts.push(print(stmtPath, {
needsSemi: true
}));
} else {
parts.push(";", stmtPrinted);
}
} else {
parts.push(stmtPrinted);
}
if (!options.semi && isClass) {
if (classPropMayCauseASIProblems$1(stmtPath)) {
parts.push(";");
} else if (stmt.type === "ClassProperty") {
const nextChild = bodyNode.body[i + 1];
if (classChildNeedsASIProtection$1(nextChild)) {
parts.push(";");
}
}
}
if (isNextLineEmpty$4(text, stmt, options.locEnd) && !isLastStatement$1(stmtPath)) {
parts.push(hardline$6);
}
printed.push(concat$b(parts));
});
return join$6(hardline$6, printed);
}
function printPropertyKey(path, options, print) {
const node = path.getNode();
if (node.computed) {
return concat$b(["[", path.call(print, "key"), "]"]);
}
const parent = path.getParentNode();
const {
key
} = node;
if (node.type === "ClassPrivateProperty" && // flow has `Identifier` key, and babel has `PrivateName` key
key.type === "Identifier") {
return concat$b(["#", path.call(print, "key")]);
}
if (options.quoteProps === "consistent" && !needsQuoteProps.has(parent)) {
const objectHasStringProp = (parent.properties || parent.body || parent.members).some(prop => !prop.computed && prop.key && isStringLiteral$1(prop.key) && !isStringPropSafeToUnquote$1(prop, options));
needsQuoteProps.set(parent, objectHasStringProp);
}
if ((key.type === "Identifier" || isNumericLiteral$3(key) && isSimpleNumber$1(printNumber$1(rawText$1(key))) && // Avoid converting 999999999999999999999 to 1e+21, 0.99999999999999999 to 1 and 1.0 to 1.
String(key.value) === printNumber$1(rawText$1(key)) && // Quoting number keys is safe in JS and Flow, but not in TypeScript (as
// mentioned in `isStringPropSafeToUnquote`).
!(options.parser === "typescript" || options.parser === "babel-ts")) && (options.parser === "json" || options.quoteProps === "consistent" && needsQuoteProps.get(parent))) {
// a -> "a"
// 1 -> "1"
// 1.5 -> "1.5"
const prop = printString$1(JSON.stringify(key.type === "Identifier" ? key.name : key.value.toString()), options);
return path.call(keyPath => comments.printComments(keyPath, () => prop, options), "key");
}
if (isStringPropSafeToUnquote$1(node, options) && (options.quoteProps === "as-needed" || options.quoteProps === "consistent" && !needsQuoteProps.get(parent))) {
// 'a' -> a
// '1' -> 1
// '1.5' -> 1.5
return path.call(keyPath => comments.printComments(keyPath, () => /^\d/.test(key.value) ? printNumber$1(key.value) : key.value, options), "key");
}
return path.call(print, "key");
}
function printMethod(path, options, print) {
const node = path.getNode();
const {
kind
} = node;
const value = node.value || node;
const parts = [];
if (!kind || kind === "init" || kind === "method" || kind === "constructor") {
if (value.async) {
parts.push("async ");
}
if (value.generator) {
parts.push("*");
}
} else {
assert__default['default'].ok(kind === "get" || kind === "set");
parts.push(kind, " ");
}
parts.push(printPropertyKey(path, options, print), node.optional || node.key.optional ? "?" : "", node === value ? printMethodInternal(path, options, print) : path.call(path => printMethodInternal(path, options, print), "value"));
return concat$b(parts);
}
function printMethodInternal(path, options, print) {
const parts = [printFunctionTypeParameters$2(path, options, print), group$7(concat$b([printFunctionParams(path, print, options), printReturnType(path, print, options)]))];
if (path.getNode().body) {
parts.push(" ", path.call(print, "body"));
} else {
parts.push(options.semi ? ";" : "");
}
return concat$b(parts);
}
function printJestEachTemplateLiteral(path, options, print) {
/**
* a | b | expected
* ${1} | ${1} | ${2}
* ${1} | ${2} | ${3}
* ${2} | ${1} | ${3}
*/
const node = path.getNode();
const headerNames = node.quasis[0].value.raw.trim().split(/\s*\|\s*/);
if (headerNames.length > 1 || headerNames.some(headerName => headerName.length !== 0)) {
options.__inJestEach = true;
const expressions = path.map(print, "expressions");
options.__inJestEach = false;
const parts = [];
const stringifiedExpressions = expressions.map(doc => "${" + printDocToString$2(doc, Object.assign({}, options, {
printWidth: Infinity,
endOfLine: "lf"
})).formatted + "}");
const tableBody = [{
hasLineBreak: false,
cells: []
}];
for (let i = 1; i < node.quasis.length; i++) {
const row = tableBody[tableBody.length - 1];
const correspondingExpression = stringifiedExpressions[i - 1];
row.cells.push(correspondingExpression);
if (correspondingExpression.includes("\n")) {
row.hasLineBreak = true;
}
if (node.quasis[i].value.raw.includes("\n")) {
tableBody.push({
hasLineBreak: false,
cells: []
});
}
}
const maxColumnCount = Math.max(headerNames.length, ...tableBody.map(row => row.cells.length));
const maxColumnWidths = Array.from({
length: maxColumnCount
}).fill(0);
const table = [{
cells: headerNames
}, ...tableBody.filter(row => row.cells.length !== 0)];
for (const {
cells
} of table.filter(row => !row.hasLineBreak)) {
cells.forEach((cell, index) => {
maxColumnWidths[index] = Math.max(maxColumnWidths[index], getStringWidth$3(cell));
});
}
parts.push(lineSuffixBoundary$1, "`", indent$8(concat$b([hardline$6, join$6(hardline$6, table.map(row => join$6(" | ", row.cells.map((cell, index) => row.hasLineBreak ? cell : cell + " ".repeat(maxColumnWidths[index] - getStringWidth$3(cell))))))])), hardline$6, "`");
return concat$b(parts);
}
}
function printTypeAnnotation(path, options, print) {
const node = path.getValue();
if (!node.typeAnnotation) {
return "";
}
const parentNode = path.getParentNode();
const isDefinite = node.definite || parentNode && parentNode.type === "VariableDeclarator" && parentNode.definite;
const isFunctionDeclarationIdentifier = parentNode.type === "DeclareFunction" && parentNode.id === node;
if (isFlowAnnotationComment$1(options.originalText, node.typeAnnotation, options)) {
return concat$b([" /*: ", path.call(print, "typeAnnotation"), " */"]);
}
return concat$b([isFunctionDeclarationIdentifier ? "" : isDefinite ? "!: " : ": ", path.call(print, "typeAnnotation")]);
}
function printFunctionParams(path, print, options, expandArg, printTypeParams) {
const fun = path.getValue();
const parent = path.getParentNode();
const paramsField = fun.parameters ? "parameters" : "params";
const isParametersInTestCall = isTestCall$1(parent);
const shouldHugParameters = shouldHugArguments(fun);
const shouldExpandParameters = expandArg && !(fun[paramsField] && fun[paramsField].some(n => n.comments));
const typeParams = printTypeParams ? printFunctionTypeParameters$2(path, options, print) : "";
let printed = [];
if (fun[paramsField]) {
const lastArgIndex = fun[paramsField].length - 1;
printed = path.map((childPath, index) => {
const parts = [];
const param = childPath.getValue();
parts.push(print(childPath));
if (index === lastArgIndex) {
if (fun.rest) {
parts.push(",", line$8);
}
} else if (isParametersInTestCall || shouldHugParameters || shouldExpandParameters) {
parts.push(", ");
} else if (isNextLineEmpty$4(options.originalText, param, options.locEnd)) {
parts.push(",", hardline$6, hardline$6);
} else {
parts.push(",", line$8);
}
return concat$b(parts);
}, paramsField);
}
if (fun.rest) {
printed.push(concat$b(["...", path.call(print, "rest")]));
}
if (printed.length === 0) {
return concat$b([typeParams, "(", comments.printDanglingComments(path, options,
/* sameIndent */
true, comment => getNextNonSpaceNonCommentCharacter$2(options.originalText, comment, options.locEnd) === ")"), ")"]);
}
const lastParam = getLast$5(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 don't want the arguments to break and instead
// want the whole expression to be on a new line.
//
// Good: Bad:
// verylongcall( verylongcall((
// (a, b) => { a,
// } b,
// }) ) => {
// })
if (shouldExpandParameters) {
return group$7(concat$b([removeLines$1(typeParams), "(", concat$b(printed.map(removeLines$1)), ")"]));
} // Single object destructuring should hug
//
// function({
// a,
// b,
// c
// }) {}
const hasNotParameterDecorator = fun[paramsField].every(param => !param.decorators);
if (shouldHugParameters && hasNotParameterDecorator) {
return concat$b([typeParams, "(", concat$b(printed), ")"]);
} // don't break in specs, eg; `it("should maintain parens around done even when long", (done) => {})`
if (isParametersInTestCall) {
return concat$b([typeParams, "(", concat$b(printed), ")"]);
}
const isFlowShorthandWithOneArg = (isObjectTypePropertyAFunction$1(parent, options) || isTypeAnnotationAFunction$1(parent, options) || parent.type === "TypeAlias" || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType" || parent.type === "IntersectionTypeAnnotation" || parent.type === "FunctionTypeAnnotation" && parent.returnType === fun) && fun[paramsField].length === 1 && fun[paramsField][0].name === null && fun[paramsField][0].typeAnnotation && fun.typeParameters === null && isSimpleFlowType$1(fun[paramsField][0].typeAnnotation) && !fun.rest;
if (isFlowShorthandWithOneArg) {
if (options.arrowParens === "always") {
return concat$b(["(", concat$b(printed), ")"]);
}
return concat$b(printed);
}
const canHaveTrailingComma = !(lastParam && lastParam.type === "RestElement") && !fun.rest;
return concat$b([typeParams, "(", indent$8(concat$b([softline$6, concat$b(printed)])), ifBreak$4(canHaveTrailingComma && shouldPrintComma$3(options, "all") ? "," : ""), softline$6, ")"]);
}
function shouldPrintParamsWithoutParens(path, options) {
if (options.arrowParens === "always") {
return false;
}
if (options.arrowParens === "avoid") {
const node = path.getValue();
return canPrintParamsWithoutParens(node);
} // Fallback default; should be unreachable
/* istanbul ignore next */
return false;
}
function canPrintParamsWithoutParens(node) {
return node.params.length === 1 && !node.rest && !node.typeParameters && !hasDanglingComments$1(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) {
const n = path.getValue();
const parts = [];
if (n.async) {
parts.push("async ");
}
if (n.generator) {
parts.push("function* ");
} else {
parts.push("function ");
}
if (n.id) {
parts.push(path.call(print, "id"));
}
parts.push(printFunctionTypeParameters$2(path, options, print), group$7(concat$b([printFunctionParams(path, print, options), printReturnType(path, print, options)])), n.body ? " " : "", path.call(print, "body"));
return concat$b(parts);
}
function printReturnType(path, print, options) {
const n = path.getValue();
const returnType = path.call(print, "returnType");
if (n.returnType && isFlowAnnotationComment$1(options.originalText, n.returnType, options)) {
return concat$b([" /*: ", returnType, " */"]);
}
const 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$b(parts);
}
function printExportDeclaration(path, options, print) {
const decl = path.getValue();
const semi = options.semi ? ";" : "";
/** @type{Doc[]} */
const parts = ["export "];
const isDefault = decl.default || decl.type === "ExportDefaultDeclaration";
if (isDefault) {
parts.push("default ");
}
parts.push(comments.printDanglingComments(path, options,
/* sameIndent */
true));
if (needsHardlineAfterDanglingComment$1(decl)) {
parts.push(hardline$6);
}
if (decl.declaration) {
parts.push(path.call(print, "declaration"));
if (isDefault && decl.declaration.type !== "ClassDeclaration" && decl.declaration.type !== "FunctionDeclaration" && decl.declaration.type !== "TSInterfaceDeclaration" && decl.declaration.type !== "DeclareClass" && decl.declaration.type !== "DeclareFunction" && decl.declaration.type !== "TSDeclareFunction" && decl.declaration.type !== "EnumDeclaration") {
parts.push(semi);
}
} else {
parts.push(decl.exportKind === "type" ? "type " : "");
parts.push(printModuleSpecifiers$1(path, options, print));
parts.push(printModuleSource$1(path, options, print));
parts.push(semi);
}
return concat$b(parts);
}
function printFlowDeclaration(path, parts) {
const parentExportDecl = getParentExportDeclaration$1(path);
if (parentExportDecl) {
assert__default['default'].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$b(parts);
}
function printTypeScriptModifiers(path, options, print) {
const n = path.getValue();
if (!n.modifiers || !n.modifiers.length) {
return "";
}
return concat$b([join$6(" ", path.map(print, "modifiers")), " "]);
}
const typeParametersGroupIds = new WeakMap();
function getTypeParametersGroupId(node) {
if (!typeParametersGroupIds.has(node)) {
typeParametersGroupIds.set(node, Symbol("typeParameters"));
}
return typeParametersGroupIds.get(node);
}
function printTypeParameters(path, options, print, paramsKey) {
const n = path.getValue();
if (!n[paramsKey]) {
return "";
} // for TypeParameterDeclaration typeParameters is a single node
if (!Array.isArray(n[paramsKey])) {
return path.call(print, paramsKey);
}
const grandparent = path.getNode(2);
const greatGrandParent = path.getNode(3);
const greatGreatGrandParent = path.getNode(4);
const isParameterInTestCall = grandparent != null && isTestCall$1(grandparent);
const 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" || // See https://github.com/prettier/prettier/pull/6467 for the context.
greatGreatGrandParent && greatGreatGrandParent.type === "VariableDeclarator" && grandparent.type === "TSTypeAnnotation" && greatGrandParent.type !== "ArrowFunctionExpression" && n[paramsKey][0].type !== "TSUnionType" && n[paramsKey][0].type !== "UnionTypeAnnotation" && n[paramsKey][0].type !== "TSIntersectionType" && n[paramsKey][0].type !== "IntersectionTypeAnnotation" && n[paramsKey][0].type !== "TSConditionalType" && n[paramsKey][0].type !== "TSMappedType" && n[paramsKey][0].type !== "TSTypeOperator" && n[paramsKey][0].type !== "TSIndexedAccessType" && n[paramsKey][0].type !== "TSArrayType");
function printDanglingCommentsForInline(n) {
if (!hasDanglingComments$1(n)) {
return "";
}
const hasOnlyBlockComments = n.comments.every(comments$1.isBlockComment);
const printed = comments.printDanglingComments(path, options,
/* sameIndent */
hasOnlyBlockComments);
if (hasOnlyBlockComments) {
return printed;
}
return concat$b([printed, hardline$6]);
}
if (shouldInline) {
return concat$b(["<", join$6(", ", path.map(print, paramsKey)), printDanglingCommentsForInline(n), ">"]);
}
return group$7(concat$b(["<", indent$8(concat$b([softline$6, join$6(concat$b([",", line$8]), path.map(print, paramsKey))])), ifBreak$4(options.parser !== "typescript" && options.parser !== "babel-ts" && shouldPrintComma$3(options, "all") ? "," : ""), softline$6, ">"]), {
id: getTypeParametersGroupId(n)
});
}
function printClass(path, options, print) {
const n = path.getValue();
const parts = [];
if (n.abstract) {
parts.push("abstract ");
}
parts.push("class"); // Keep old behaviour of extends in same line
// If there is only on extends and there are not comments
const groupMode = n.id && hasTrailingComment$3(n.id) || n.superClass && n.superClass.comments && n.superClass.comments.length !== 0 || n.extends && n.extends.length !== 0 || // DeclareClass
n.mixins && n.mixins.length !== 0 || n.implements && n.implements.length !== 0;
const partsGroup = [];
const extendsParts = [];
if (n.id) {
partsGroup.push(" ", path.call(print, "id"));
}
partsGroup.push(path.call(print, "typeParameters"));
const hasMultipleHeritage = ["superClass", "extends", "mixins", "implements"].filter(key => !!n[key]).length > 1;
const shouldIndentOnlyHeritageClauses = n.typeParameters && !hasTrailingLineComment$1(n.typeParameters) && !hasMultipleHeritage;
function printList(listName) {
if (n[listName] && n[listName].length !== 0) {
const printedLeadingComments = comments.printDanglingComments(path, options,
/* sameIndent */
true, ({
marker
}) => marker === listName);
extendsParts.push(shouldIndentOnlyHeritageClauses ? ifBreak$4(" ", line$8, {
groupId: getTypeParametersGroupId(n.typeParameters)
}) : line$8, printedLeadingComments, printedLeadingComments && hardline$6, listName, group$7(indent$8(concat$b([line$8, join$6(concat$b([",", line$8]), path.map(print, listName))]))));
}
}
if (n.superClass) {
const printed = concat$b(["extends ", path.call(print, "superClass"), path.call(print, "superTypeParameters")]);
const printedWithComments = path.call(superClass => comments.printComments(superClass, () => printed, options), "superClass");
if (groupMode) {
extendsParts.push(line$8, group$7(printedWithComments));
} else {
extendsParts.push(" ", printedWithComments);
}
} else {
printList("extends");
}
printList("mixins");
printList("implements");
if (groupMode) {
const printedExtends = concat$b(extendsParts);
if (shouldIndentOnlyHeritageClauses) {
parts.push(group$7(concat$b(partsGroup.concat(ifBreak$4(indent$8(printedExtends), printedExtends)))));
} else {
parts.push(group$7(indent$8(concat$b(partsGroup.concat(printedExtends)))));
}
} else {
parts.push(...partsGroup, ...extendsParts);
}
parts.push(" ", path.call(print, "body"));
return parts;
}
function separatorNoWhitespace(isFacebookTranslationTag, child, childNode, nextNode) {
if (isFacebookTranslationTag) {
return "";
}
if (childNode.type === "JSXElement" && !childNode.closingElement || nextNode && nextNode.type === "JSXElement" && !nextNode.closingElement) {
return child.length === 1 ? softline$6 : hardline$6;
}
return softline$6;
}
function separatorWithWhitespace(isFacebookTranslationTag, child, childNode, nextNode) {
if (isFacebookTranslationTag) {
return hardline$6;
}
if (child.length === 1) {
return childNode.type === "JSXElement" && !childNode.closingElement || nextNode && nextNode.type === "JSXElement" && !nextNode.closingElement ? hardline$6 : softline$6;
}
return hardline$6;
} // JSX Children are strange, mostly for two reasons:
// 1. JSX reads newlines into string values, instead of skipping them like JS
// 2. up to one whitespace between elements within a line is significant,
// but not between lines.
//
// Leading, trailing, and lone whitespace all need to
// turn themselves into the rather ugly `{' '}` when breaking.
//
// We print JSX using the `fill` doc primitive.
// This requires that we give it an array of alternating
// content and whitespace elements.
// To ensure this we add dummy `""` content elements as needed.
function printJSXChildren(path, options, print, jsxWhitespace, isFacebookTranslationTag) {
const n = path.getValue();
const children = []; // using `map` instead of `each` because it provides `i`
path.map((childPath, i) => {
const child = childPath.getValue();
if (isLiteral$1(child)) {
const text = rawText$1(child); // Contains a non-whitespace character
if (isMeaningfulJSXText$1(child)) {
const words = text.split(matchJsxWhitespaceRegex$1); // Starts with whitespace
if (words[0] === "") {
children.push("");
words.shift();
if (/\n/.test(words[0])) {
const next = n.children[i + 1];
children.push(separatorWithWhitespace(isFacebookTranslationTag, words[1], child, next));
} else {
children.push(jsxWhitespace);
}
words.shift();
}
let endWhitespace; // Ends with whitespace
if (getLast$5(words) === "") {
words.pop();
endWhitespace = words.pop();
} // This was whitespace only without a new line.
if (words.length === 0) {
return;
}
words.forEach((word, i) => {
if (i % 2 === 1) {
children.push(line$8);
} else {
children.push(word);
}
});
if (endWhitespace !== undefined) {
if (/\n/.test(endWhitespace)) {
const next = n.children[i + 1];
children.push(separatorWithWhitespace(isFacebookTranslationTag, getLast$5(children), child, next));
} else {
children.push(jsxWhitespace);
}
} else {
const next = n.children[i + 1];
children.push(separatorNoWhitespace(isFacebookTranslationTag, getLast$5(children), child, next));
}
} 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$6);
}
} else {
children.push("");
children.push(jsxWhitespace);
}
} else {
const printedChild = print(childPath);
children.push(printedChild);
const next = n.children[i + 1];
const directlyFollowedByMeaningfulText = next && isMeaningfulJSXText$1(next);
if (directlyFollowedByMeaningfulText) {
const firstWord = rawText$1(next).trim().split(matchJsxWhitespaceRegex$1)[0];
children.push(separatorNoWhitespace(isFacebookTranslationTag, firstWord, child, next));
} else {
children.push(hardline$6);
}
}
}, "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) {
const n = path.getValue();
if (n.type === "JSXElement" && isEmptyJSXElement$1(n)) {
return concat$b([path.call(print, "openingElement"), path.call(print, "closingElement")]);
}
const openingLines = n.type === "JSXElement" ? path.call(print, "openingElement") : path.call(print, "openingFragment");
const 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$b([openingLines, concat$b(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(child => {
if (isJSXWhitespaceExpression$1(child)) {
return {
type: "JSXText",
value: " ",
raw: " "
};
}
return child;
});
const containsTag = n.children.filter(isJSXNode$3).length > 0;
const containsMultipleExpressions = n.children.filter(child => child.type === "JSXExpressionContainer").length > 1;
const containsMultipleAttributes = n.type === "JSXElement" && n.openingElement.attributes.length > 1; // Record any breaks. Should never go from true to false, only false to true.
let forcedBreak = willBreak$3(openingLines) || containsTag || containsMultipleAttributes || containsMultipleExpressions;
const isMdxBlock = path.getParentNode().rootMarker === "mdx";
const rawJsxWhitespace = options.singleQuote ? "{' '}" : '{" "}';
const jsxWhitespace = isMdxBlock ? concat$b([" "]) : ifBreak$4(concat$b([rawJsxWhitespace, softline$6]), " ");
const isFacebookTranslationTag = n.openingElement && n.openingElement.name && n.openingElement.name.name === "fbt";
const children = printJSXChildren(path, options, print, jsxWhitespace, isFacebookTranslationTag);
const containsText = n.children.some(child => isMeaningfulJSXText$1(child)); // 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 (let i = children.length - 2; i >= 0; i--) {
const isPairOfEmptyStrings = children[i] === "" && children[i + 1] === "";
const isPairOfHardlines = children[i] === hardline$6 && children[i + 1] === "" && children[i + 2] === hardline$6;
const isLineFollowedByJSXWhitespace = (children[i] === softline$6 || children[i] === hardline$6) && children[i + 1] === "" && children[i + 2] === jsxWhitespace;
const isJSXWhitespaceFollowedByLine = children[i] === jsxWhitespace && children[i + 1] === "" && (children[i + 2] === softline$6 || children[i + 2] === hardline$6);
const isDoubleJSXWhitespace = children[i] === jsxWhitespace && children[i + 1] === "" && children[i + 2] === jsxWhitespace;
const isPairOfHardOrSoftLines = children[i] === softline$6 && children[i + 1] === "" && children[i + 2] === hardline$6 || children[i] === hardline$6 && children[i + 1] === "" && children[i + 2] === softline$6;
if (isPairOfHardlines && containsText || isPairOfEmptyStrings || isLineFollowedByJSXWhitespace || isDoubleJSXWhitespace || isPairOfHardOrSoftLines) {
children.splice(i, 2);
} else if (isJSXWhitespaceFollowedByLine) {
children.splice(i + 1, 2);
}
} // Trim trailing lines (or empty strings)
while (children.length && (isLineNext$1(getLast$5(children)) || isEmpty$1(getLast$5(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.
const multilineChildren = [];
children.forEach((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$b([rawJsxWhitespace, hardline$6]));
return;
} else if (i === children.length - 1) {
// Trailing whitespace
multilineChildren.push(rawJsxWhitespace);
return;
} else if (children[i - 1] === "" && children[i - 2] === hardline$6) {
// Whitespace after line break
multilineChildren.push(rawJsxWhitespace);
return;
}
}
multilineChildren.push(child);
if (willBreak$3(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.
const content = containsText ? fill$3(multilineChildren) : group$7(concat$b(multilineChildren), {
shouldBreak: true
});
if (isMdxBlock) {
return content;
}
const multiLineElem = group$7(concat$b([openingLines, indent$8(concat$b([hardline$6, content])), hardline$6, closingLines]));
if (forcedBreak) {
return multiLineElem;
}
return conditionalGroup$3([group$7(concat$b([openingLines, concat$b(children), closingLines])), multiLineElem]);
}
function maybeWrapJSXElementInParens(path, elem, options) {
const parent = path.getParentNode();
/* istanbul ignore next */
if (!parent) {
return elem;
}
const NO_WRAP_PARENTS = {
ArrayExpression: true,
JSXAttribute: true,
JSXElement: true,
JSXExpressionContainer: true,
JSXFragment: true,
ExpressionStatement: true,
CallExpression: true,
OptionalCallExpression: true,
ConditionalExpression: true,
JsExpressionRoot: true
};
if (NO_WRAP_PARENTS[parent.type]) {
return elem;
}
const shouldBreak = path.match(undefined, node => node.type === "ArrowFunctionExpression", isCallOrOptionalCallExpression$2, node => node.type === "JSXExpressionContainer");
const needsParens = needsParens_1(path, options);
return group$7(concat$b([needsParens ? "" : ifBreak$4("("), indent$8(concat$b([softline$6, elem])), softline$6, needsParens ? "" : ifBreak$4(")")]), {
shouldBreak
});
}
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$3(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) {
/** @type{Doc[]} */
let parts = [];
const node = path.getValue(); // We treat BinaryExpression and LogicalExpression nodes the same.
if (isBinaryish$1(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$2(node.operator, node.left.operator)) {
// Flatten them out by recursively calling this function.
parts = parts.concat(path.call(left => printBinaryishExpressions(left, print, options,
/* isNested */
true, isInsideParenthesis), "left"));
} else {
parts.push(group$7(path.call(print, "left")));
}
const shouldInline = shouldInlineLogicalExpression(node);
const lineBeforeOperator = (node.operator === "|>" || node.type === "NGPipeExpression" || node.operator === "|" && options.parser === "__vue_expression") && !hasLeadingOwnLineComment$1(options.originalText, node.right, options);
const operator = node.type === "NGPipeExpression" ? "|" : node.operator;
const rightSuffix = node.type === "NGPipeExpression" && node.arguments.length !== 0 ? group$7(indent$8(concat$b([softline$6, ": ", join$6(concat$b([softline$6, ":", ifBreak$4(" ")]), path.map(print, "arguments").map(arg => align$2(2, group$7(arg))))]))) : "";
const right = shouldInline ? concat$b([operator, " ", path.call(print, "right"), rightSuffix]) : concat$b([lineBeforeOperator ? line$8 : "", operator, lineBeforeOperator ? " " : line$8, path.call(print, "right"), rightSuffix]); // If there's only a single binary expression, we want to create a group
// in order to avoid having a small right part like -1 be on its own line.
const parent = path.getParentNode();
const shouldBreak = hasTrailingLineComment$1(node.left);
const shouldGroup = shouldBreak || !(isInsideParenthesis && node.type === "LogicalExpression") && parent.type !== node.type && node.left.type !== node.type && node.right.type !== node.type;
parts.push(lineBeforeOperator ? "" : " ", shouldGroup ? group$7(right, {
shouldBreak
}) : 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 = normalizeParts$1(comments.printComments(path, () => concat$b(parts), options).parts);
}
} else {
// Our stopping case. Simply print the node normally.
parts.push(group$7(path.call(print)));
}
return parts;
}
function printAssignmentRight(leftNode, rightNode, printedRight, options) {
if (hasLeadingOwnLineComment$1(options.originalText, rightNode, options)) {
return indent$8(concat$b([line$8, printedRight]));
}
const canBreak = isBinaryish$1(rightNode) && !shouldInlineLogicalExpression(rightNode) || rightNode.type === "ConditionalExpression" && isBinaryish$1(rightNode.test) && !shouldInlineLogicalExpression(rightNode.test) || rightNode.type === "StringLiteralTypeAnnotation" || rightNode.type === "ClassExpression" && rightNode.decorators && rightNode.decorators.length || (leftNode.type === "Identifier" || isStringLiteral$1(leftNode) || leftNode.type === "MemberExpression") && (isStringLiteral$1(rightNode) || isMemberExpressionChain$1(rightNode)) && // do not put values on a separate line from the key in json
options.parser !== "json" && options.parser !== "json5" || rightNode.type === "SequenceExpression";
if (canBreak) {
return group$7(indent$8(concat$b([line$8, printedRight])));
}
return concat$b([" ", printedRight]);
}
function printAssignment(leftNode, printedLeft, operator, rightNode, printedRight, options) {
if (!rightNode) {
return printedLeft;
}
const printed = printAssignmentRight(leftNode, rightNode, printedRight, options);
return group$7(concat$b([printedLeft, operator, printed]));
}
function adjustClause(node, clause, forceSpace) {
if (node.type === "EmptyStatement") {
return ";";
}
if (node.type === "BlockStatement" || forceSpace) {
return concat$b([" ", clause]);
}
return indent$8(concat$b([line$8, clause]));
}
function nodeStr(node, options, isFlowOrTypeScriptDirectiveLiteral) {
const raw = rawText$1(node);
const isDirectiveLiteral = isFlowOrTypeScriptDirectiveLiteral || node.type === "DirectiveLiteral";
return printString$1(raw, options, isDirectiveLiteral);
}
function printRegex(node) {
const flags = node.flags.split("").sort().join("");
return `/${node.pattern}/${flags}`;
}
function exprNeedsASIProtection(path, options) {
const node = path.getValue();
const 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$3(node) || node.type === "BindExpression" && !node.object || node.type === "RegExpLiteral" || node.type === "Literal" && node.pattern || node.type === "Literal" && node.regex;
if (maybeASIProblem) {
return true;
}
if (!hasNakedLeftSide$2(node)) {
return false;
}
return path.call(childPath => exprNeedsASIProtection(childPath, options), ...getLeftSidePathName$2(path, node));
}
function stmtNeedsASIProtection(path, options) {
const node = path.getNode();
if (node.type !== "ExpressionStatement") {
return false;
}
return path.call(childPath => exprNeedsASIProtection(childPath, options), "expression");
}
function shouldHugType(node) {
if (isSimpleFlowType$1(node) || isObjectType$1(node)) {
return true;
}
if (node.type === "UnionTypeAnnotation" || node.type === "TSUnionType") {
const voidCount = node.types.filter(n => n.type === "VoidTypeAnnotation" || n.type === "TSVoidKeyword" || n.type === "NullLiteralTypeAnnotation" || n.type === "TSNullKeyword").length;
const hasObject = node.types.some(n => n.type === "ObjectTypeAnnotation" || n.type === "TSTypeLiteral" || // This is a bit aggressive but captures Array<{x}>
n.type === "GenericTypeAnnotation" || n.type === "TSTypeReference");
if (node.types.length - 1 === voidCount && hasObject) {
return true;
}
}
return false;
}
function shouldHugArguments(fun) {
if (!fun || fun.rest) {
return false;
}
const params = fun.params || fun.parameters;
if (!params || params.length !== 1) {
return false;
}
const param = params[0];
return !param.comments && (param.type === "ObjectPattern" || param.type === "ArrayPattern" || param.type === "Identifier" && param.typeAnnotation && (param.typeAnnotation.type === "TypeAnnotation" || param.typeAnnotation.type === "TSTypeAnnotation") && isObjectType$1(param.typeAnnotation.typeAnnotation) || param.type === "FunctionTypeParam" && isObjectType$1(param.typeAnnotation) || param.type === "AssignmentPattern" && (param.left.type === "ObjectPattern" || param.left.type === "ArrayPattern") && (param.right.type === "Identifier" || param.right.type === "ObjectExpression" && param.right.properties.length === 0 || param.right.type === "ArrayExpression" && param.right.elements.length === 0));
}
function printArrayItems(path, options, printPath, print) {
const printedElements = [];
let separatorParts = [];
path.each(childPath => {
printedElements.push(concat$b(separatorParts));
printedElements.push(group$7(print(childPath)));
separatorParts = [",", line$8];
if (childPath.getValue() && isNextLineEmpty$4(options.originalText, childPath.getValue(), options.locEnd)) {
separatorParts.push(softline$6);
}
}, printPath);
return concat$b(printedElements);
}
function printReturnAndThrowArgument(path, options, print) {
const node = path.getValue();
const semi = options.semi ? ";" : "";
const parts = [];
if (node.argument) {
if (returnArgumentHasLeadingComment$1(options, node.argument)) {
parts.push(concat$b([" (", indent$8(concat$b([hardline$6, path.call(print, "argument")])), hardline$6, ")"]));
} else if (isBinaryish$1(node.argument) || node.argument.type === "SequenceExpression") {
parts.push(group$7(concat$b([ifBreak$4(" (", " "), indent$8(concat$b([softline$6, path.call(print, "argument")])), softline$6, ifBreak$4(")")])));
} else {
parts.push(" ", path.call(print, "argument"));
}
}
const lastComment = Array.isArray(node.comments) && node.comments[node.comments.length - 1];
const isLastCommentLine = lastComment && (lastComment.type === "CommentLine" || lastComment.type === "Line");
if (isLastCommentLine) {
parts.push(semi);
}
if (hasDanglingComments$1(node)) {
parts.push(" ", comments.printDanglingComments(path, options,
/* sameIndent */
true));
}
if (!isLastCommentLine) {
parts.push(semi);
}
return concat$b(parts);
}
function willPrintOwnComments(path
/*, options */
) {
const node = path.getValue();
const parent = path.getParentNode();
return (node && (isJSXNode$3(node) || hasFlowShorthandAnnotationComment$2(node) || parent && (parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && (hasFlowAnnotationComment$1(node.leadingComments) || hasFlowAnnotationComment$1(node.trailingComments))) || parent && (parent.type === "JSXSpreadAttribute" || parent.type === "JSXSpreadChild" || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType" || (parent.type === "ClassDeclaration" || parent.type === "ClassExpression") && parent.superClass === node)) && (!hasIgnoreComment$2(path) || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType");
}
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";
}
function printComment$1(commentPath, options) {
const comment = commentPath.getValue();
switch (comment.type) {
case "CommentBlock":
case "Block":
{
if (isIndentableBlockComment(comment)) {
const printed = printIndentableBlockComment(comment); // We need to prevent an edge case of a previous trailing comment
// printed as a `lineSuffix` which causes the comments to be
// interleaved. See https://github.com/prettier/prettier/issues/4412
if (comment.trailing && !hasNewline$5(options.originalText, options.locStart(comment), {
backwards: true
})) {
return concat$b([hardline$6, printed]);
}
return printed;
}
const commentEnd = options.locEnd(comment);
const isInsideFlowComment = options.originalText.slice(commentEnd - 3, commentEnd) === "*-/";
return "/*" + comment.value + (isInsideFlowComment ? "*-/" : "*/");
}
case "CommentLine":
case "Line":
// Supports `//`, `#!`, ``
return options.originalText.slice(options.locStart(comment), options.locEnd(comment)).trimEnd();
default:
/* istanbul ignore next */
throw new Error("Not a comment: " + JSON.stringify(comment));
}
}
function isIndentableBlockComment(comment) {
// If the comment has multiple lines and every line starts with a star
// we can fix the indentation of each line. The stars in the `/*` and
// `*/` delimiters are not included in the comment value, so add them
// back first.
const lines = `*${comment.value}*`.split("\n");
return lines.length > 1 && lines.every(line => line.trim()[0] === "*");
}
function printIndentableBlockComment(comment) {
const lines = comment.value.split("\n");
return concat$b(["/*", join$6(hardline$6, lines.map((line, index) => index === 0 ? line.trimEnd() : " " + (index < lines.length - 1 ? line.trim() : line.trimStart()))), "*/"]);
}
var printerEstree = {
preprocess: preprocess_1,
print: genericPrint,
embed: embed_1,
insertPragma: insertPragma$1,
massageAstNode: clean_1,
hasPrettierIgnore: hasPrettierIgnore$1,
willPrintOwnComments,
canAttachComment,
printComment: printComment$1,
isBlockComment: comments$1.isBlockComment,
handleComments: {
ownLine: comments$1.handleOwnLineComment,
endOfLine: comments$1.handleEndOfLineComment,
remaining: comments$1.handleRemainingComment
},
getGapRegex: comments$1.getGapRegex,
getCommentChildNodes: comments$1.getCommentChildNodes
};
const {
concat: concat$c,
hardline: hardline$7,
indent: indent$9,
join: join$7
} = document.builders;
function genericPrint$1(path, options, print) {
const node = path.getValue();
switch (node.type) {
case "JsonRoot":
return concat$c([path.call(print, "node"), hardline$7]);
case "ArrayExpression":
return node.elements.length === 0 ? "[]" : concat$c(["[", indent$9(concat$c([hardline$7, join$7(concat$c([",", hardline$7]), path.map(print, "elements"))])), hardline$7, "]"]);
case "ObjectExpression":
return node.properties.length === 0 ? "{}" : concat$c(["{", indent$9(concat$c([hardline$7, join$7(concat$c([",", hardline$7]), path.map(print, "properties"))])), hardline$7, "}"]);
case "ObjectProperty":
return concat$c([path.call(print, "key"), ": ", path.call(print, "value")]);
case "UnaryExpression":
return concat$c([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$1(node, newNode
/*, parent*/
) {
delete newNode.start;
delete newNode.end;
delete newNode.extra;
delete newNode.loc;
delete newNode.comments;
delete newNode.errors;
delete newNode.range;
if (node.type === "Identifier") {
return {
type: "StringLiteral",
value: node.name
};
}
if (node.type === "UnaryExpression" && node.operator === "+") {
return newNode.argument;
}
}
var printerEstreeJson = {
preprocess: preprocess_1,
print: genericPrint$1,
massageAstNode: clean$1
};
const 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."
},
proseWrap: {
since: "1.8.2",
category: CATEGORY_COMMON,
type: "choice",
default: [{
since: "1.8.2",
value: true
}, {
since: "1.9.0",
value: "preserve"
}],
description: "How to wrap prose.",
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."
}]
}
};
const CATEGORY_JAVASCRIPT = "JavaScript"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
var options$2 = {
arrowParens: {
since: "1.9.0",
category: CATEGORY_JAVASCRIPT,
type: "choice",
default: [{
since: "1.9.0",
value: "avoid"
}, {
since: "2.0.0",
value: "always"
}],
description: "Include parentheses around a sole arrow function parameter.",
choices: [{
value: "always",
description: "Always include parens. Example: `(x) => x`"
}, {
value: "avoid",
description: "Omit parens when possible. Example: `x => x`"
}]
},
bracketSpacing: commonOptions.bracketSpacing,
jsxBracketSameLine: {
since: "0.17.0",
category: CATEGORY_JAVASCRIPT,
type: "boolean",
default: false,
description: "Put > on the last line instead of at a new line."
},
semi: {
since: "1.0.0",
category: CATEGORY_JAVASCRIPT,
type: "boolean",
default: true,
description: "Print semicolons.",
oppositeDescription: "Do not print semicolons, except at the beginning of lines which may need them."
},
singleQuote: commonOptions.singleQuote,
jsxSingleQuote: {
since: "1.15.0",
category: CATEGORY_JAVASCRIPT,
type: "boolean",
default: false,
description: "Use single quotes in JSX."
},
quoteProps: {
since: "1.17.0",
category: CATEGORY_JAVASCRIPT,
type: "choice",
default: "as-needed",
description: "Change when properties in objects are quoted.",
choices: [{
value: "as-needed",
description: "Only add quotes around object properties where required."
}, {
value: "consistent",
description: "If at least one property in an object requires quotes, quote all properties."
}, {
value: "preserve",
description: "Respect the input use of quotes in object properties."
}]
},
trailingComma: {
since: "0.0.0",
category: CATEGORY_JAVASCRIPT,
type: "choice",
default: [{
since: "0.0.0",
value: false
}, {
since: "0.19.0",
value: "none"
}, {
since: "2.0.0",
value: "es5"
}],
description: "Print trailing commas wherever possible when multi-line.",
choices: [{
value: "es5",
description: "Trailing commas where valid in ES5 (objects, arrays, etc.)"
}, {
value: "none",
description: "No trailing commas."
}, {
value: "all",
description: "Trailing commas wherever possible (including function arguments)."
}]
}
};
var name$2 = "JavaScript";
var type = "programming";
var tmScope = "source.js";
var aceMode = "javascript";
var codemirrorMode = "javascript";
var codemirrorMimeType = "text/javascript";
var color = "#f1e05a";
var aliases = [
"js",
"node"
];
var extensions = [
".js",
"._js",
".bones",
".cjs",
".es",
".es6",
".frag",
".gs",
".jake",
".jsb",
".jscad",
".jsfl",
".jsm",
".jss",
".mjs",
".njs",
".pac",
".sjs",
".ssjs",
".xsjs",
".xsjslib"
];
var filenames = [
"Jakefile"
];
var interpreters = [
"chakra",
"d8",
"gjs",
"js",
"node",
"qjs",
"rhino",
"v8",
"v8-shell"
];
var languageId = 183;
var JavaScript = {
name: name$2,
type: type,
tmScope: tmScope,
aceMode: aceMode,
codemirrorMode: codemirrorMode,
codemirrorMimeType: codemirrorMimeType,
color: color,
aliases: aliases,
extensions: extensions,
filenames: filenames,
interpreters: interpreters,
languageId: languageId
};
var JavaScript$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
name: name$2,
type: type,
tmScope: tmScope,
aceMode: aceMode,
codemirrorMode: codemirrorMode,
codemirrorMimeType: codemirrorMimeType,
color: color,
aliases: aliases,
extensions: extensions,
filenames: filenames,
interpreters: interpreters,
languageId: languageId,
'default': JavaScript
});
var name$3 = "JSX";
var type$1 = "programming";
var group$8 = "JavaScript";
var extensions$1 = [
".jsx"
];
var tmScope$1 = "source.js.jsx";
var aceMode$1 = "javascript";
var codemirrorMode$1 = "jsx";
var codemirrorMimeType$1 = "text/jsx";
var languageId$1 = 178;
var JSX = {
name: name$3,
type: type$1,
group: group$8,
extensions: extensions$1,
tmScope: tmScope$1,
aceMode: aceMode$1,
codemirrorMode: codemirrorMode$1,
codemirrorMimeType: codemirrorMimeType$1,
languageId: languageId$1
};
var JSX$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
name: name$3,
type: type$1,
group: group$8,
extensions: extensions$1,
tmScope: tmScope$1,
aceMode: aceMode$1,
codemirrorMode: codemirrorMode$1,
codemirrorMimeType: codemirrorMimeType$1,
languageId: languageId$1,
'default': JSX
});
var name$4 = "TypeScript";
var type$2 = "programming";
var color$1 = "#2b7489";
var aliases$1 = [
"ts"
];
var interpreters$1 = [
"deno",
"ts-node"
];
var extensions$2 = [
".ts"
];
var tmScope$2 = "source.ts";
var aceMode$2 = "typescript";
var codemirrorMode$2 = "javascript";
var codemirrorMimeType$2 = "application/typescript";
var languageId$2 = 378;
var TypeScript = {
name: name$4,
type: type$2,
color: color$1,
aliases: aliases$1,
interpreters: interpreters$1,
extensions: extensions$2,
tmScope: tmScope$2,
aceMode: aceMode$2,
codemirrorMode: codemirrorMode$2,
codemirrorMimeType: codemirrorMimeType$2,
languageId: languageId$2
};
var TypeScript$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
name: name$4,
type: type$2,
color: color$1,
aliases: aliases$1,
interpreters: interpreters$1,
extensions: extensions$2,
tmScope: tmScope$2,
aceMode: aceMode$2,
codemirrorMode: codemirrorMode$2,
codemirrorMimeType: codemirrorMimeType$2,
languageId: languageId$2,
'default': TypeScript
});
var name$5 = "TSX";
var type$3 = "programming";
var group$9 = "TypeScript";
var extensions$3 = [
".tsx"
];
var tmScope$3 = "source.tsx";
var aceMode$3 = "javascript";
var codemirrorMode$3 = "jsx";
var codemirrorMimeType$3 = "text/jsx";
var languageId$3 = 94901924;
var TSX = {
name: name$5,
type: type$3,
group: group$9,
extensions: extensions$3,
tmScope: tmScope$3,
aceMode: aceMode$3,
codemirrorMode: codemirrorMode$3,
codemirrorMimeType: codemirrorMimeType$3,
languageId: languageId$3
};
var TSX$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
name: name$5,
type: type$3,
group: group$9,
extensions: extensions$3,
tmScope: tmScope$3,
aceMode: aceMode$3,
codemirrorMode: codemirrorMode$3,
codemirrorMimeType: codemirrorMimeType$3,
languageId: languageId$3,
'default': TSX
});
var name$6 = "JSON";
var type$4 = "data";
var tmScope$4 = "source.json";
var aceMode$4 = "json";
var codemirrorMode$4 = "javascript";
var codemirrorMimeType$4 = "application/json";
var searchable = false;
var extensions$4 = [
".json",
".avsc",
".geojson",
".gltf",
".har",
".ice",
".JSON-tmLanguage",
".jsonl",
".mcmeta",
".tfstate",
".tfstate.backup",
".topojson",
".webapp",
".webmanifest",
".yy",
".yyp"
];
var filenames$1 = [
".arcconfig",
".htmlhintrc",
".tern-config",
".tern-project",
".watchmanconfig",
"composer.lock",
"mcmod.info"
];
var languageId$4 = 174;
var _JSON = {
name: name$6,
type: type$4,
tmScope: tmScope$4,
aceMode: aceMode$4,
codemirrorMode: codemirrorMode$4,
codemirrorMimeType: codemirrorMimeType$4,
searchable: searchable,
extensions: extensions$4,
filenames: filenames$1,
languageId: languageId$4
};
var _JSON$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
name: name$6,
type: type$4,
tmScope: tmScope$4,
aceMode: aceMode$4,
codemirrorMode: codemirrorMode$4,
codemirrorMimeType: codemirrorMimeType$4,
searchable: searchable,
extensions: extensions$4,
filenames: filenames$1,
languageId: languageId$4,
'default': _JSON
});
var name$7 = "JSON with Comments";
var type$5 = "data";
var group$a = "JSON";
var tmScope$5 = "source.js";
var aceMode$5 = "javascript";
var codemirrorMode$5 = "javascript";
var codemirrorMimeType$5 = "text/javascript";
var aliases$2 = [
"jsonc"
];
var extensions$5 = [
".jsonc",
".sublime-build",
".sublime-commands",
".sublime-completions",
".sublime-keymap",
".sublime-macro",
".sublime-menu",
".sublime-mousemap",
".sublime-project",
".sublime-settings",
".sublime-theme",
".sublime-workspace",
".sublime_metrics",
".sublime_session"
];
var filenames$2 = [
".babelrc",
".eslintrc.json",
".jscsrc",
".jshintrc",
".jslintrc",
"jsconfig.json",
"language-configuration.json",
"tsconfig.json"
];
var languageId$5 = 423;
var JSON_with_Comments = {
name: name$7,
type: type$5,
group: group$a,
tmScope: tmScope$5,
aceMode: aceMode$5,
codemirrorMode: codemirrorMode$5,
codemirrorMimeType: codemirrorMimeType$5,
aliases: aliases$2,
extensions: extensions$5,
filenames: filenames$2,
languageId: languageId$5
};
var JSON_with_Comments$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
name: name$7,
type: type$5,
group: group$a,
tmScope: tmScope$5,
aceMode: aceMode$5,
codemirrorMode: codemirrorMode$5,
codemirrorMimeType: codemirrorMimeType$5,
aliases: aliases$2,
extensions: extensions$5,
filenames: filenames$2,
languageId: languageId$5,
'default': JSON_with_Comments
});
var name$8 = "JSON5";
var type$6 = "data";
var extensions$6 = [
".json5"
];
var tmScope$6 = "source.js";
var aceMode$6 = "javascript";
var codemirrorMode$6 = "javascript";
var codemirrorMimeType$6 = "application/json";
var languageId$6 = 175;
var JSON5$1 = {
name: name$8,
type: type$6,
extensions: extensions$6,
tmScope: tmScope$6,
aceMode: aceMode$6,
codemirrorMode: codemirrorMode$6,
codemirrorMimeType: codemirrorMimeType$6,
languageId: languageId$6
};
var JSON5$2 = /*#__PURE__*/Object.freeze({
__proto__: null,
name: name$8,
type: type$6,
extensions: extensions$6,
tmScope: tmScope$6,
aceMode: aceMode$6,
codemirrorMode: codemirrorMode$6,
codemirrorMimeType: codemirrorMimeType$6,
languageId: languageId$6,
'default': JSON5$1
});
var require$$0$2 = getCjsExportFromNamespace(JavaScript$1);
var require$$1 = getCjsExportFromNamespace(JSX$1);
var require$$2 = getCjsExportFromNamespace(TypeScript$1);
var require$$3 = getCjsExportFromNamespace(TSX$1);
var require$$4$1 = getCjsExportFromNamespace(_JSON$1);
var require$$5 = getCjsExportFromNamespace(JSON_with_Comments$1);
var require$$6 = getCjsExportFromNamespace(JSON5$2);
const languages = [createLanguage(require$$0$2, data => ({
since: "0.0.0",
parsers: ["babel", "flow"],
vscodeLanguageIds: ["javascript", "mongo"],
interpreters: data.interpreters.concat(["nodejs"])
})), createLanguage(require$$0$2, () => ({
name: "Flow",
since: "0.0.0",
parsers: ["babel", "flow"],
vscodeLanguageIds: ["javascript"],
aliases: [],
filenames: [],
extensions: [".js.flow"]
})), createLanguage(require$$1, () => ({
since: "0.0.0",
parsers: ["babel", "flow"],
vscodeLanguageIds: ["javascriptreact"]
})), createLanguage(require$$2, () => ({
since: "1.4.0",
parsers: ["typescript", "babel-ts"],
vscodeLanguageIds: ["typescript"]
})), createLanguage(require$$3, () => ({
since: "1.4.0",
parsers: ["typescript", "babel-ts"],
vscodeLanguageIds: ["typescriptreact"]
})), createLanguage(require$$4$1, () => ({
name: "JSON.stringify",
since: "1.13.0",
parsers: ["json-stringify"],
vscodeLanguageIds: ["json"],
extensions: [],
// .json file defaults to json instead of json-stringify
filenames: ["package.json", "package-lock.json", "composer.json"]
})), createLanguage(require$$4$1, data => ({
since: "1.5.0",
parsers: ["json"],
vscodeLanguageIds: ["json"],
filenames: data.filenames.concat([".prettierrc"])
})), createLanguage(require$$5, data => ({
since: "1.5.0",
parsers: ["json"],
vscodeLanguageIds: ["jsonc"],
filenames: data.filenames.concat([".eslintrc"])
})), createLanguage(require$$6, () => ({
since: "1.13.0",
parsers: ["json5"],
vscodeLanguageIds: ["json5"]
}))];
const printers = {
estree: printerEstree,
"estree-json": printerEstreeJson
};
const parsers = {
// JS - Babel
get babel() {
return require("./parser-babel").parsers.babel;
},
get "babel-flow"() {
return require("./parser-babel").parsers["babel-flow"];
},
get "babel-ts"() {
return require("./parser-babel").parsers["babel-ts"];
},
get json() {
return require("./parser-babel").parsers.json;
},
get json5() {
return require("./parser-babel").parsers.json5;
},
get "json-stringify"() {
return require("./parser-babel").parsers["json-stringify"];
},
get __js_expression() {
return require("./parser-babel").parsers.__js_expression;
},
get __vue_expression() {
return require("./parser-babel").parsers.__vue_expression;
},
get __vue_event_binding() {
return require("./parser-babel").parsers.__vue_event_binding;
},
// JS - Flow
get flow() {
return require("./parser-flow").parsers.flow;
},
// JS - TypeScript
get typescript() {
return require("./parser-typescript").parsers.typescript;
},
// JS - Angular Action
get __ng_action() {
return require("./parser-angular").parsers.__ng_action;
},
// JS - Angular Binding
get __ng_binding() {
return require("./parser-angular").parsers.__ng_binding;
},
// JS - Angular Interpolation
get __ng_interpolation() {
return require("./parser-angular").parsers.__ng_interpolation;
},
// JS - Angular Directive
get __ng_directive() {
return require("./parser-angular").parsers.__ng_directive;
}
};
var languageJs = {
languages,
options: options$2,
printers,
parsers
};
const {
isFrontMatterNode: isFrontMatterNode$1
} = util;
function clean$2(ast, newObj, parent) {
["raw", // front-matter
"raws", "sourceIndex", "source", "before", "after", "trailingComma"].forEach(name => {
delete newObj[name];
});
if (isFrontMatterNode$1(ast) && ast.lang === "yaml") {
delete newObj.value;
}
if (ast.type === "css-comment" && parent.type === "css-root" && parent.nodes.length !== 0) {
// --insert-pragma
// first non-front-matter comment
if (parent.nodes[0] === ast || isFrontMatterNode$1(parent.nodes[0]) && parent.nodes[1] === ast) {
/**
* something
*
* @format
*/
delete newObj.text; // standalone pragma
if (/^\*\s*@(format|prettier)\s*$/.test(ast.text)) {
return null;
}
} // Last comment is not parsed, when omitting semicolon, #8675
if (parent.type === "css-root" && getLast(parent.nodes) === ast) {
return null;
}
}
if (ast.type === "value-root") {
delete newObj.text;
}
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"].includes(newObj.value.replace().toLowerCase())) || 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, (match, numStr, unit) => {
const num = Number(numStr);
return isNaN(num) ? match : num + unit.toLowerCase();
});
}
if (ast.type === "selector-tag") {
const lowercasedValue = ast.value.toLowerCase();
if (["from", "to"].includes(lowercasedValue)) {
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(/\\([^\dA-Fa-f])/g, "$1");
}
var clean_1$1 = clean$2;
const {
builders: {
hardline: hardline$8,
concat: concat$d,
markAsRoot: markAsRoot$1
}
} = document;
const DELIMITER_MAP = {
"---": "yaml",
"+++": "toml"
};
function parse$7(text) {
const delimiterRegex = Object.keys(DELIMITER_MAP).map(escapeStringRegexp).join("|");
const match = text.match( // trailing spaces after delimiters are allowed
new RegExp(`^(${delimiterRegex})([^\\n]*)\\n(?:([\\s\\S]*?)\\n)?\\1[^\\n\\S]*(\\n|$)`));
if (match === null) {
return {
frontMatter: null,
content: text
};
}
const [raw, delimiter, language, value] = match;
let lang = DELIMITER_MAP[delimiter];
if (lang !== "toml" && language && language.trim()) {
lang = language.trim();
}
return {
frontMatter: {
type: "front-matter",
lang,
value,
raw: raw.replace(/\n$/, "")
},
content: raw.replace(/[^\n]/g, " ") + text.slice(raw.length)
};
}
function print$1(node, textToDoc) {
if (node.lang === "yaml") {
const value = node.value.trim();
const doc = value ? textToDoc(value, {
parser: "yaml"
}, {
stripTrailingHardline: true
}) : "";
return markAsRoot$1(concat$d(["---", hardline$8, doc, doc ? hardline$8 : "", "---"]));
}
}
var frontMatter = {
parse: parse$7,
print: print$1
};
const {
builders: {
hardline: hardline$9,
concat: concat$e
}
} = document;
const {
print: printFrontMatter
} = frontMatter;
function embed$1(path, print, textToDoc
/*, options */
) {
const node = path.getValue();
if (node.type === "front-matter") {
const doc = printFrontMatter(node, textToDoc);
return doc ? concat$e([doc, hardline$9]) : "";
}
}
var embed_1$1 = embed$1;
const {
parse: parseFrontMatter
} = frontMatter;
function hasPragma$1(text) {
return pragma.hasPragma(parseFrontMatter(text).content);
}
function insertPragma$2(text) {
const {
frontMatter,
content
} = parseFrontMatter(text);
return (frontMatter ? frontMatter.raw + "\n\n" : "") + pragma.insertPragma(content);
}
var pragma$1 = {
hasPragma: hasPragma$1,
insertPragma: insertPragma$2
};
const colorAdjusterFunctions = new Set(["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) {
const types = [].concat(typeOrTypes);
let counter = -1;
let ancestorNode;
while (ancestorNode = path.getParentNode(++counter)) {
if (types.includes(ancestorNode.type)) {
return counter;
}
}
return -1;
}
function getAncestorNode(path, typeOrTypes) {
const counter = getAncestorCounter(path, typeOrTypes);
return counter === -1 ? null : path.getParentNode(counter);
}
function getPropOfDeclNode(path) {
const declAncestorNode = getAncestorNode(path, "css-decl");
return declAncestorNode && declAncestorNode.prop && declAncestorNode.prop.toLowerCase();
}
function hasSCSSInterpolation(groupList) {
if (groupList && groupList.length) {
for (let i = groupList.length - 1; i > 0; i--) {
// If we find `#{`, return true.
if (groupList[i].type === "word" && groupList[i].value === "{" && groupList[i - 1].type === "word" && groupList[i - 1].value.endsWith("#")) {
return true;
}
}
}
return false;
}
function hasStringOrFunction(groupList) {
if (groupList && groupList.length) {
for (let i = 0; i < groupList.length; i++) {
if (groupList[i].type === "string" || groupList[i].type === "func") {
return true;
}
}
}
return false;
}
function isSCSS(parser, text) {
const hasExplicitParserChoice = parser === "less" || parser === "scss";
const IS_POSSIBLY_SCSS = /(\w\s*:\s*[^:}]+|#){|@import[^\n]+(?:url|,)/;
return hasExplicitParserChoice ? parser === "scss" : IS_POSSIBLY_SCSS.test(text);
}
function isSCSSVariable(node) {
return !!(node && node.type === "word" && node.value.startsWith("$"));
}
function isWideKeywords(value) {
return ["initial", "inherit", "unset", "revert"].includes(value.toLowerCase());
}
function isKeyframeAtRuleKeywords(path, value) {
const atRuleAncestorNode = getAncestorNode(path, "css-atrule");
return atRuleAncestorNode && atRuleAncestorNode.name && atRuleAncestorNode.name.toLowerCase().endsWith("keyframes") && ["from", "to"].includes(value.toLowerCase());
}
function maybeToLowerCase(value) {
return value.includes("$") || value.includes("@") || value.includes("#") || value.startsWith("%") || value.startsWith("--") || value.startsWith(":--") || value.includes("(") && value.includes(")") ? value : value.toLowerCase();
}
function insideValueFunctionNode(path, functionName) {
const funcAncestorNode = getAncestorNode(path, "value-func");
return funcAncestorNode && funcAncestorNode.value && funcAncestorNode.value.toLowerCase() === functionName;
}
function insideICSSRuleNode(path) {
const ruleAncestorNode = getAncestorNode(path, "css-rule");
return ruleAncestorNode && ruleAncestorNode.raws && ruleAncestorNode.raws.selector && (ruleAncestorNode.raws.selector.startsWith(":import") || ruleAncestorNode.raws.selector.startsWith(":export"));
}
function insideAtRuleNode(path, atRuleNameOrAtRuleNames) {
const atRuleNames = [].concat(atRuleNameOrAtRuleNames);
const atRuleAncestorNode = getAncestorNode(path, "css-atrule");
return atRuleAncestorNode && atRuleNames.includes(atRuleAncestorNode.name.toLowerCase());
}
function insideURLFunctionInImportAtRuleNode(path) {
const node = path.getValue();
const atRuleAncestorNode = getAncestorNode(path, "css-atrule");
return atRuleAncestorNode && atRuleAncestorNode.name === "import" && node.groups[0].value === "url" && node.groups.length === 2;
}
function isURLFunctionNode(node) {
return node.type === "value-func" && node.value.toLowerCase() === "url";
}
function isLastNode(path, node) {
const parentNode = path.getParentNode();
/* istanbul ignore next */
if (!parentNode) {
return false;
}
const {
nodes
} = parentNode;
return nodes && nodes.indexOf(node) === nodes.length - 1;
}
function isDetachedRulesetDeclarationNode(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.
/* istanbul ignore next */
if (!node.selector) {
return false;
}
return typeof node.selector === "string" && /^@.+:.*$/.test(node.selector) || node.selector.value && /^@.+:.*$/.test(node.selector.value);
}
function isForKeywordNode(node) {
return node.type === "value-word" && ["from", "through", "end"].includes(node.value);
}
function isIfElseKeywordNode(node) {
return node.type === "value-word" && ["and", "or", "not"].includes(node.value);
}
function isEachKeywordNode(node) {
return node.type === "value-word" && node.value === "in";
}
function isMultiplicationNode(node) {
return node.type === "value-operator" && node.value === "*";
}
function isDivisionNode(node) {
return node.type === "value-operator" && node.value === "/";
}
function isAdditionNode(node) {
return node.type === "value-operator" && node.value === "+";
}
function isSubtractionNode(node) {
return node.type === "value-operator" && node.value === "-";
}
function isModuloNode(node) {
return node.type === "value-operator" && node.value === "%";
}
function isMathOperatorNode(node) {
return isMultiplicationNode(node) || isDivisionNode(node) || isAdditionNode(node) || isSubtractionNode(node) || isModuloNode(node);
}
function isEqualityOperatorNode(node) {
return node.type === "value-word" && ["==", "!="].includes(node.value);
}
function isRelationalOperatorNode(node) {
return node.type === "value-word" && ["<", ">", "<=", ">="].includes(node.value);
}
function isSCSSControlDirectiveNode(node) {
return node.type === "css-atrule" && ["if", "else", "for", "each", "while"].includes(node.name);
}
function isSCSSNestedPropertyNode(node) {
/* istanbul ignore next */
if (!node.selector) {
return false;
}
return node.selector.replace(/\/\*.*?\*\//, "").replace(/\/\/.*?\n/, "").trim().endsWith(":");
}
function isDetachedRulesetCallNode(node) {
return node.raws && node.raws.params && /^\(\s*\)$/.test(node.raws.params);
}
function isTemplatePlaceholderNode(node) {
return node.name.startsWith("prettier-placeholder");
}
function isTemplatePropNode(node) {
return node.prop.startsWith("@prettier-placeholder");
}
function isPostcssSimpleVarNode(currentNode, nextNode) {
return currentNode.value === "$$" && currentNode.type === "value-func" && nextNode && nextNode.type === "value-word" && !nextNode.raws.before;
}
function hasComposesNode(node) {
return node.value && node.value.type === "value-root" && node.value.group && node.value.group.type === "value-value" && node.prop.toLowerCase() === "composes";
}
function hasParensAroundNode(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(node) {
return node.raws && node.raws.before === "";
}
function isKeyValuePairNode(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(node.groups[0]);
}
function isSCSSMapItemNode(path) {
const node = path.getValue(); // Ignore empty item (i.e. `$key: ()`)
if (node.groups.length === 0) {
return false;
}
const 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;
}
const declNode = getAncestorNode(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(node) {
return node.type === "value-comment" && node.inline;
}
function isHashNode(node) {
return node.type === "value-word" && node.value === "#";
}
function isLeftCurlyBraceNode(node) {
return node.type === "value-word" && node.value === "{";
}
function isRightCurlyBraceNode(node) {
return node.type === "value-word" && node.value === "}";
}
function isWordNode(node) {
return ["value-word", "value-atword"].includes(node.type);
}
function isColonNode(node) {
return node.type === "value-colon";
}
function isMediaAndSupportsKeywords(node) {
return node.value && ["not", "and", "or"].includes(node.value.toLowerCase());
}
function isColorAdjusterFuncNode(node) {
if (node.type !== "value-func") {
return false;
}
return colorAdjusterFunctions.has(node.value.toLowerCase());
} // TODO: only check `less` when we don't use `less` to parse `css`
function isLessParser(options) {
return options.parser === "css" || options.parser === "less";
}
function lastLineHasInlineComment(text) {
return /\/\//.test(text.split(/[\n\r]/).pop());
}
function stringifyNode(node) {
if (node.groups) {
const open = node.open && node.open.value ? node.open.value : "";
const groups = node.groups.reduce((previousValue, currentValue, index) => {
return previousValue + stringifyNode(currentValue) + (node.groups[0].type === "comma_group" && index !== node.groups.length - 1 ? "," : "");
}, "");
const close = node.close && node.close.value ? node.close.value : "";
return open + groups + close;
}
const before = node.raws && node.raws.before ? node.raws.before : "";
const quote = node.raws && node.raws.quote ? node.raws.quote : "";
const atword = node.type === "atword" ? "@" : "";
const value = node.value ? node.value : "";
const unit = node.unit ? node.unit : "";
const group = node.group ? stringifyNode(node.group) : "";
const after = node.raws && node.raws.after ? node.raws.after : "";
return before + quote + atword + value + quote + unit + group + after;
}
var utils$7 = {
getAncestorCounter,
getAncestorNode,
getPropOfDeclNode,
hasSCSSInterpolation,
hasStringOrFunction,
maybeToLowerCase,
insideValueFunctionNode,
insideICSSRuleNode,
insideAtRuleNode,
insideURLFunctionInImportAtRuleNode,
isKeyframeAtRuleKeywords,
isWideKeywords,
isSCSS,
isSCSSVariable,
isLastNode,
isLessParser,
isSCSSControlDirectiveNode,
isDetachedRulesetDeclarationNode,
isRelationalOperatorNode,
isEqualityOperatorNode,
isMultiplicationNode,
isDivisionNode,
isAdditionNode,
isSubtractionNode,
isModuloNode,
isMathOperatorNode,
isEachKeywordNode,
isForKeywordNode,
isURLFunctionNode,
isIfElseKeywordNode,
hasComposesNode,
hasParensAroundNode,
hasEmptyRawBefore,
isSCSSNestedPropertyNode,
isDetachedRulesetCallNode,
isTemplatePlaceholderNode,
isTemplatePropNode,
isPostcssSimpleVarNode,
isKeyValuePairNode,
isKeyValuePairInParenGroupNode,
isSCSSMapItemNode,
isInlineValueCommentNode,
isHashNode,
isLeftCurlyBraceNode,
isRightCurlyBraceNode,
isWordNode,
isColonNode,
isMediaAndSupportsKeywords,
isColorAdjusterFuncNode,
lastLineHasInlineComment,
stringifyNode
};
const {
printNumber: printNumber$2,
printString: printString$2,
hasIgnoreComment: hasIgnoreComment$3,
hasNewline: hasNewline$6,
isFrontMatterNode: isFrontMatterNode$2,
isNextLineEmpty: isNextLineEmpty$5
} = util;
const {
builders: {
concat: concat$f,
join: join$8,
line: line$9,
hardline: hardline$a,
softline: softline$7,
group: group$b,
fill: fill$4,
indent: indent$a,
dedent: dedent$2,
ifBreak: ifBreak$5,
breakParent: breakParent$5
},
utils: {
removeLines: removeLines$2
}
} = document;
const {
insertPragma: insertPragma$3
} = pragma$1;
const {
getAncestorNode: getAncestorNode$1,
getPropOfDeclNode: getPropOfDeclNode$1,
maybeToLowerCase: maybeToLowerCase$1,
insideValueFunctionNode: insideValueFunctionNode$1,
insideICSSRuleNode: insideICSSRuleNode$1,
insideAtRuleNode: insideAtRuleNode$1,
insideURLFunctionInImportAtRuleNode: insideURLFunctionInImportAtRuleNode$1,
isKeyframeAtRuleKeywords: isKeyframeAtRuleKeywords$1,
isWideKeywords: isWideKeywords$1,
isSCSS: isSCSS$1,
isLastNode: isLastNode$1,
isLessParser: isLessParser$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,
isMathOperatorNode: isMathOperatorNode$1,
isEachKeywordNode: isEachKeywordNode$1,
isForKeywordNode: isForKeywordNode$1,
isURLFunctionNode: isURLFunctionNode$1,
isIfElseKeywordNode: isIfElseKeywordNode$1,
hasComposesNode: hasComposesNode$1,
hasParensAroundNode: hasParensAroundNode$1,
hasEmptyRawBefore: hasEmptyRawBefore$1,
isKeyValuePairNode: isKeyValuePairNode$1,
isDetachedRulesetCallNode: isDetachedRulesetCallNode$1,
isTemplatePlaceholderNode: isTemplatePlaceholderNode$1,
isTemplatePropNode: isTemplatePropNode$1,
isPostcssSimpleVarNode: isPostcssSimpleVarNode$1,
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,
lastLineHasInlineComment: lastLineHasInlineComment$1
} = utils$7;
function shouldPrintComma$4(options) {
return options.trailingComma === "es5" || options.trailingComma === "all";
}
function genericPrint$2(path, options, print) {
const node = path.getValue();
/* istanbul ignore if */
if (!node) {
return "";
}
if (typeof node === "string") {
return node;
}
switch (node.type) {
case "front-matter":
return concat$f([node.raw, hardline$a]);
case "css-root":
{
const nodes = printNodeSequence(path, options, print);
const after = node.raws.after.trim();
return concat$f([nodes, after ? ` ${after}` : "", nodes.parts.length && !options.__isHTMLStyleAttribute ? hardline$a : ""]);
}
case "css-comment":
{
const isInlineComment = node.inline || node.raws.inline;
const text = options.originalText.slice(options.locStart(node), options.locEnd(node));
return isInlineComment ? text.trimEnd() : text;
}
case "css-rule":
{
return concat$f([path.call(print, "selector"), node.important ? " !important" : "", node.nodes ? concat$f([node.selector && node.selector.type === "selector-unknown" && lastLineHasInlineComment$1(node.selector.value) ? line$9 : " ", "{", node.nodes.length > 0 ? indent$a(concat$f([hardline$a, printNodeSequence(path, options, print)])) : "", hardline$a, "}", isDetachedRulesetDeclarationNode$1(node) ? ";" : ""]) : ";"]);
}
case "css-decl":
{
const parentNode = path.getParentNode();
const {
between: rawBetween
} = node.raws;
const trimmedBetween = rawBetween.trim();
const isColon = trimmedBetween === ":";
let value = hasComposesNode$1(node) ? removeLines$2(path.call(print, "value")) : path.call(print, "value");
if (!isColon && lastLineHasInlineComment$1(trimmedBetween)) {
value = indent$a(concat$f([hardline$a, dedent$2(value)]));
}
return concat$f([node.raws.before.replace(/[\s;]/g, ""), insideICSSRuleNode$1(path) ? node.prop : maybeToLowerCase$1(node.prop), trimmedBetween.startsWith("//") ? " " : "", trimmedBetween, node.extend ? "" : " ", isLessParser$1(options) && node.extend && node.selector ? concat$f(["extend(", path.call(print, "selector"), ")"]) : "", 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$f([" {", indent$a(concat$f([softline$7, printNodeSequence(path, options, print)])), softline$7, "}"]) : isTemplatePropNode$1(node) && !parentNode.raws.semicolon && options.originalText[options.locEnd(node) - 1] !== ";" ? "" : options.__isHTMLStyleAttribute && isLastNode$1(path, node) ? ifBreak$5(";", "") : ";"]);
}
case "css-atrule":
{
const parentNode = path.getParentNode();
const isTemplatePlaceholderNodeWithoutSemiColon = isTemplatePlaceholderNode$1(node) && !parentNode.raws.semicolon && options.originalText[options.locEnd(node) - 1] !== ";";
if (isLessParser$1(options)) {
if (node.mixin) {
return concat$f([path.call(print, "selector"), node.important ? " !important" : "", isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]);
}
if (node.function) {
return concat$f([node.name, concat$f([path.call(print, "params")]), isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]);
}
if (node.variable) {
return concat$f(["@", node.name, ": ", node.value ? concat$f([path.call(print, "value")]) : "", node.raws.between.trim() ? node.raws.between.trim() + " " : "", node.nodes ? concat$f(["{", indent$a(concat$f([node.nodes.length > 0 ? softline$7 : "", printNodeSequence(path, options, print)])), softline$7, "}"]) : "", isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]);
}
}
return concat$f(["@", // 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$1(node) || node.name.endsWith(":") ? node.name : maybeToLowerCase$1(node.name), node.params ? concat$f([isDetachedRulesetCallNode$1(node) ? "" : isTemplatePlaceholderNode$1(node) ? node.raws.afterName === "" ? "" : node.name.endsWith(":") ? " " : /^\s*\n\s*\n/.test(node.raws.afterName) ? concat$f([hardline$a, hardline$a]) : /^\s*\n/.test(node.raws.afterName) ? hardline$a : " " : " ", path.call(print, "params")]) : "", node.selector ? indent$a(concat$f([" ", path.call(print, "selector")])) : "", node.value ? group$b(concat$f([" ", path.call(print, "value"), isSCSSControlDirectiveNode$1(node) ? hasParensAroundNode$1(node) ? " " : line$9 : ""])) : node.name === "else" ? " " : "", node.nodes ? concat$f([isSCSSControlDirectiveNode$1(node) ? "" : node.selector && !node.selector.nodes && typeof node.selector.value === "string" && lastLineHasInlineComment$1(node.selector.value) || !node.selector && typeof node.params === "string" && lastLineHasInlineComment$1(node.params) ? line$9 : " ", "{", indent$a(concat$f([node.nodes.length > 0 ? softline$7 : "", printNodeSequence(path, options, print)])), softline$7, "}"]) : isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]);
}
// postcss-media-query-parser
case "media-query-list":
{
const parts = [];
path.each(childPath => {
const node = childPath.getValue();
if (node.type === "media-query" && node.value === "") {
return;
}
parts.push(childPath.call(print));
}, "nodes");
return group$b(indent$a(join$8(line$9, parts)));
}
case "media-query":
{
return concat$f([join$8(" ", path.map(print, "nodes")), isLastNode$1(path, node) ? "" : ","]);
}
case "media-type":
{
return adjustNumbers(adjustStrings(node.value, options));
}
case "media-feature-expression":
{
if (!node.nodes) {
return node.value;
}
return concat$f(["(", concat$f(path.map(print, "nodes")), ")"]);
}
case "media-feature":
{
return maybeToLowerCase$1(adjustStrings(node.value.replace(/ +/g, " "), options));
}
case "media-colon":
{
return concat$f([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$b(concat$f([insideAtRuleNode$1(path, "custom-selector") ? concat$f([getAncestorNode$1(path, "css-atrule").customSelector, line$9]) : "", join$8(concat$f([",", insideAtRuleNode$1(path, ["extend", "custom-selector", "nest"]) ? line$9 : hardline$a]), path.map(print, "nodes"))]));
}
case "selector-selector":
{
return group$b(indent$a(concat$f(path.map(print, "nodes"))));
}
case "selector-comment":
{
return node.value;
}
case "selector-string":
{
return adjustStrings(node.value, options);
}
case "selector-tag":
{
const parentNode = path.getParentNode();
const index = parentNode && parentNode.nodes.indexOf(node);
const prevNode = index && parentNode.nodes[index - 1];
return concat$f([node.namespace ? concat$f([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", prevNode.type === "selector-nesting" ? node.value : adjustNumbers(isKeyframeAtRuleKeywords$1(path, node.value) ? node.value.toLowerCase() : node.value)]);
}
case "selector-id":
{
return concat$f(["#", node.value]);
}
case "selector-class":
{
return concat$f([".", adjustNumbers(adjustStrings(node.value, options))]);
}
case "selector-attribute":
{
return concat$f(["[", node.namespace ? concat$f([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 === ">>>") {
const parentNode = path.getParentNode();
const leading = parentNode.type === "selector-selector" && parentNode.nodes[0] === node ? "" : line$9;
return concat$f([leading, node.value, isLastNode$1(path, node) ? "" : " "]);
}
const leading = node.value.trim().startsWith("(") ? line$9 : "";
const value = adjustNumbers(adjustStrings(node.value.trim(), options)) || line$9;
return concat$f([leading, value]);
}
case "selector-universal":
{
return concat$f([node.namespace ? concat$f([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", node.value]);
}
case "selector-pseudo":
{
return concat$f([maybeToLowerCase$1(node.value), node.nodes && node.nodes.length > 0 ? concat$f(["(", join$8(", ", path.map(print, "nodes")), ")"]) : ""]);
}
case "selector-nesting":
{
return node.value;
}
case "selector-unknown":
{
const ruleAncestorNode = getAncestorNode$1(path, "css-rule"); // Nested SCSS property
if (ruleAncestorNode && ruleAncestorNode.isSCSSNesterProperty) {
return adjustNumbers(adjustStrings(maybeToLowerCase$1(node.value), options));
} // originalText has to be used for Less, see replaceQuotesInInlineComments in loc.js
const parentNode = path.getParentNode();
if (parentNode.raws && parentNode.raws.selector) {
const start = options.locStart(parentNode);
const end = start + parentNode.raws.selector.length;
return options.originalText.slice(start, end).trim();
} // Same reason above
const grandParent = path.getParentNode(1);
if (parentNode.type === "value-paren_group" && grandParent && grandParent.type === "value-func" && grandParent.value === "selector") {
const start = options.locStart(parentNode.open) + 1;
const end = options.locEnd(parentNode.close) - 1;
const selector = options.originalText.slice(start, end).trim();
return lastLineHasInlineComment$1(selector) ? concat$f([breakParent$5, selector]) : selector;
}
return node.value;
}
// postcss-values-parser
case "value-value":
case "value-root":
{
return path.call(print, "group");
}
case "value-comment":
{
return options.originalText.slice(options.locStart(node), options.locEnd(node));
}
case "value-comma_group":
{
const parentNode = path.getParentNode();
const parentParentNode = path.getParentNode(1);
const declAncestorProp = getPropOfDeclNode$1(path);
const isGridValue = declAncestorProp && parentNode.type === "value-value" && (declAncestorProp === "grid" || declAncestorProp.startsWith("grid-template"));
const atRuleAncestorNode = getAncestorNode$1(path, "css-atrule");
const isControlDirective = atRuleAncestorNode && isSCSSControlDirectiveNode$1(atRuleAncestorNode);
const printed = path.map(print, "groups");
const parts = [];
const insideURLFunction = insideValueFunctionNode$1(path, "url");
let insideSCSSInterpolationInString = false;
let didBreak = false;
for (let i = 0; i < node.groups.length; ++i) {
parts.push(printed[i]);
const iPrevNode = node.groups[i - 1];
const iNode = node.groups[i];
const iNextNode = node.groups[i + 1];
const iNextNextNode = node.groups[i + 2];
if (insideURLFunction) {
if (iNextNode && isAdditionNode$1(iNextNode) || isAdditionNode$1(iNode)) {
parts.push(" ");
}
continue;
} // Ignore after latest node (i.e. before semicolon)
if (!iNextNode) {
continue;
} // styled.div` background: var(--${one}); `
if (iNode.type === "value-word" && iNode.value.endsWith("-") && iNextNode.type === "value-atword" && iNextNode.value.startsWith("prettier-placeholder-")) {
continue;
} // Ignore spaces before/after string interpolation (i.e. `"#{my-fn("_")}"`)
const isStartSCSSInterpolationInString = iNode.type === "value-string" && iNode.value.startsWith("#{");
const isEndingSCSSInterpolationInString = insideSCSSInterpolationInString && iNextNode.type === "value-string" && iNextNode.value.endsWith("}");
if (isStartSCSSInterpolationInString || isEndingSCSSInterpolationInString) {
insideSCSSInterpolationInString = !insideSCSSInterpolationInString;
continue;
}
if (insideSCSSInterpolationInString) {
continue;
} // Ignore colon (i.e. `:`)
if (isColonNode$1(iNode) || isColonNode$1(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 escape `\`
if (iNode.value && iNode.value.includes("\\") && iNextNode && iNextNode.type !== "value-comment") {
continue;
} // Ignore escaped `/`
if (iPrevNode && iPrevNode.value && iPrevNode.value.indexOf("\\") === iPrevNode.value.length - 1 && iNode.type === "value-operator" && iNode.value === "/") {
continue;
} // Ignore `\` (i.e. `$variable: \@small;`)
if (iNode.value === "\\") {
continue;
} // Ignore `$$` (i.e. `background-color: $$(style)Color;`)
if (isPostcssSimpleVarNode$1(iNode, iNextNode)) {
continue;
} // Ignore spaces after `#` and after `{` and before `}` in SCSS interpolation (i.e. `#{variable}`)
if (isHashNode$1(iNode) || isLeftCurlyBraceNode$1(iNode) || isRightCurlyBraceNode$1(iNextNode) || isLeftCurlyBraceNode$1(iNextNode) && hasEmptyRawBefore$1(iNextNode) || isRightCurlyBraceNode$1(iNode) && hasEmptyRawBefore$1(iNextNode)) {
continue;
} // Ignore css variables and interpolation in SCSS (i.e. `--#{$var}`)
if (iNode.value === "--" && isHashNode$1(iNextNode)) {
continue;
} // Formatting math operations
const isMathOperator = isMathOperatorNode$1(iNode);
const isNextMathOperator = isMathOperatorNode$1(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$1(iNextNode) || isNextMathOperator && isRightCurlyBraceNode$1(iNode)) && hasEmptyRawBefore$1(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$1(path, "calc") && (isAdditionNode$1(iNode) || isAdditionNode$1(iNextNode) || isSubtractionNode$1(iNode) || isSubtractionNode$1(iNextNode)) && hasEmptyRawBefore$1(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.
const isColorAdjusterNode = (isAdditionNode$1(iNode) || isSubtractionNode$1(iNode)) && i === 0 && (iNextNode.type === "value-number" || iNextNode.isHex) && parentParentNode && isColorAdjusterFuncNode$1(parentParentNode) && !hasEmptyRawBefore$1(iNextNode);
const requireSpaceBeforeOperator = iNextNextNode && iNextNextNode.type === "value-func" || iNextNextNode && isWordNode$1(iNextNextNode) || iNode.type === "value-func" || isWordNode$1(iNode);
const requireSpaceAfterOperator = iNextNode.type === "value-func" || isWordNode$1(iNextNode) || iPrevNode && iPrevNode.type === "value-func" || iPrevNode && isWordNode$1(iPrevNode); // Formatting `/`, `+`, `-` sign
if (!(isMultiplicationNode$1(iNextNode) || isMultiplicationNode$1(iNode)) && !insideValueFunctionNode$1(path, "calc") && !isColorAdjusterNode && (isDivisionNode$1(iNextNode) && !requireSpaceBeforeOperator || isDivisionNode$1(iNode) && !requireSpaceAfterOperator || isAdditionNode$1(iNextNode) && !requireSpaceBeforeOperator || isAdditionNode$1(iNode) && !requireSpaceAfterOperator || isSubtractionNode$1(iNextNode) || isSubtractionNode$1(iNode)) && (hasEmptyRawBefore$1(iNextNode) || isMathOperator && (!iPrevNode || iPrevNode && isMathOperatorNode$1(iPrevNode)))) {
continue;
} // Add `hardline` after inline comment (i.e. `// comment\n foo: bar;`)
if (isInlineValueCommentNode$1(iNode)) {
if (parentNode.type === "value-paren_group") {
parts.push(dedent$2(hardline$a));
continue;
}
parts.push(hardline$a);
continue;
} // Handle keywords in SCSS control directive
if (isControlDirective && (isEqualityOperatorNode$1(iNextNode) || isRelationalOperatorNode$1(iNextNode) || isIfElseKeywordNode$1(iNextNode) || isEachKeywordNode$1(iNode) || isForKeywordNode$1(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 && iNextNode.source && iNode.source.start.line !== iNextNode.source.start.line) {
parts.push(hardline$a);
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;
} // allow function(returns-list($list)...)
if (iNextNode && iNextNode.value === "...") {
continue;
} // Be default all values go through `line`
parts.push(line$9);
}
if (didBreak) {
parts.unshift(hardline$a);
}
if (isControlDirective) {
return group$b(indent$a(concat$f(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$1(path)) {
return group$b(fill$4(parts));
}
return group$b(indent$a(fill$4(parts)));
}
case "value-paren_group":
{
const parentNode = path.getParentNode();
if (parentNode && isURLFunctionNode$1(parentNode) && (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$f([node.open ? path.call(print, "open") : "", join$8(",", path.map(print, "groups")), node.close ? path.call(print, "close") : ""]);
}
if (!node.open) {
const printed = path.map(print, "groups");
const res = [];
for (let i = 0; i < printed.length; i++) {
if (i !== 0) {
res.push(concat$f([",", line$9]));
}
res.push(printed[i]);
}
return group$b(indent$a(fill$4(res)));
}
const isSCSSMapItem = isSCSSMapItemNode$1(path);
const lastItem = node.groups[node.groups.length - 1];
const isLastItemComment = lastItem && lastItem.type === "value-comment";
return group$b(concat$f([node.open ? path.call(print, "open") : "", indent$a(concat$f([softline$7, join$8(concat$f([",", line$9]), path.map(childPath => {
const node = childPath.getValue();
const printed = print(childPath); // Key/Value pair in open paren already indented
if (isKeyValuePairNode$1(node) && node.type === "value-comma_group" && node.groups && node.groups[2] && node.groups[2].type === "value-paren_group") {
printed.contents.contents.parts[1] = group$b(printed.contents.contents.parts[1]);
return group$b(dedent$2(printed));
}
return printed;
}, "groups"))])), ifBreak$5(!isLastItemComment && isSCSS$1(options.parser, options.originalText) && isSCSSMapItem && shouldPrintComma$4(options) ? "," : ""), softline$7, node.close ? path.call(print, "close") : ""]), {
shouldBreak: isSCSSMapItem
});
}
case "value-func":
{
return concat$f([node.value, insideAtRuleNode$1(path, "supports") && isMediaAndSupportsKeywords$1(node) ? " " : "", path.call(print, "group")]);
}
case "value-paren":
{
return node.value;
}
case "value-number":
{
return concat$f([printCssNumber(node.value), maybeToLowerCase$1(node.unit)]);
}
case "value-operator":
{
return node.value;
}
case "value-word":
{
if (node.isColor && node.isHex || isWideKeywords$1(node.value)) {
return node.value.toLowerCase();
}
return node.value;
}
case "value-colon":
{
const parentNode = path.getParentNode();
const index = parentNode && parentNode.groups.indexOf(node);
const prevNode = index && parentNode.groups[index - 1];
return concat$f([node.value, // Don't add spaces on escaped colon `:`, e.g: grid-template-rows: [row-1-00\:00] auto;
prevNode && prevNode.value[prevNode.value.length - 1] === "\\" || // Don't add spaces on `:` in `url` function (i.e. `url(fbglyph: cross-outline, fig-white)`)
insideValueFunctionNode$1(path, "url") ? "" : line$9]);
}
// TODO: confirm this code is dead
/* istanbul ignore next */
case "value-comma":
{
return concat$f([node.value, " "]);
}
case "value-string":
{
return printString$2(node.raws.quote + node.value + node.raws.quote, options);
}
case "value-atword":
{
return concat$f(["@", 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 ${JSON.stringify(node.type)}`);
}
}
function printNodeSequence(path, options, print) {
const node = path.getValue();
const parts = [];
let i = 0;
path.map(pathChild => {
const prevNode = node.nodes[i - 1];
if (prevNode && prevNode.type === "css-comment" && prevNode.text.trim() === "prettier-ignore") {
const 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$6(options.originalText, options.locStart(node.nodes[i + 1]), {
backwards: true
}) && !isFrontMatterNode$2(node.nodes[i]) || node.nodes[i + 1].type === "css-atrule" && node.nodes[i + 1].name === "else" && node.nodes[i].type !== "css-comment") {
parts.push(" ");
} else {
parts.push(options.__isHTMLStyleAttribute ? line$9 : hardline$a);
if (isNextLineEmpty$5(options.originalText, pathChild.getValue(), options.locEnd) && !isFrontMatterNode$2(node.nodes[i])) {
parts.push(hardline$a);
}
}
}
i++;
}, "nodes");
return concat$f(parts);
}
const STRING_REGEX$3 = /(["'])(?:(?!\1)[^\\]|\\[\S\s])*\1/g;
const NUMBER_REGEX = /(?:\d*\.\d+|\d+\.?)(?:[Ee][+-]?\d+)?/g;
const STANDARD_UNIT_REGEX = /[A-Za-z]+/g;
const WORD_PART_REGEX = /[$@]?[A-Z_a-z\u0080-\uFFFF][\w\u0080-\uFFFF-]*/g;
const ADJUST_NUMBERS_REGEX = new RegExp(STRING_REGEX$3.source + "|" + `(${WORD_PART_REGEX.source})?` + `(${NUMBER_REGEX.source})` + `(${STANDARD_UNIT_REGEX.source})?`, "g");
function adjustStrings(value, options) {
return value.replace(STRING_REGEX$3, match => printString$2(match, options));
}
function quoteAttributeValue(value, options) {
const quote = options.singleQuote ? "'" : '"';
return value.includes('"') || value.includes("'") ? value : quote + value + quote;
}
function adjustNumbers(value) {
return value.replace(ADJUST_NUMBERS_REGEX, (match, quote, wordPart, number, unit) => !wordPart && number ? printCssNumber(number) + maybeToLowerCase$1(unit || "") : match);
}
function printCssNumber(rawNumber) {
return printNumber$2(rawNumber) // Remove trailing `.0`.
.replace(/\.0(?=$|e)/, "");
}
var printerPostcss = {
print: genericPrint$2,
embed: embed_1$1,
insertPragma: insertPragma$3,
hasPrettierIgnore: hasIgnoreComment$3,
massageAstNode: clean_1$1
};
var options$3 = {
singleQuote: commonOptions.singleQuote
};
var name$9 = "CSS";
var type$7 = "markup";
var tmScope$7 = "source.css";
var aceMode$7 = "css";
var codemirrorMode$7 = "css";
var codemirrorMimeType$7 = "text/css";
var color$2 = "#563d7c";
var extensions$7 = [
".css"
];
var languageId$7 = 50;
var CSS = {
name: name$9,
type: type$7,
tmScope: tmScope$7,
aceMode: aceMode$7,
codemirrorMode: codemirrorMode$7,
codemirrorMimeType: codemirrorMimeType$7,
color: color$2,
extensions: extensions$7,
languageId: languageId$7
};
var CSS$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
name: name$9,
type: type$7,
tmScope: tmScope$7,
aceMode: aceMode$7,
codemirrorMode: codemirrorMode$7,
codemirrorMimeType: codemirrorMimeType$7,
color: color$2,
extensions: extensions$7,
languageId: languageId$7,
'default': CSS
});
var name$a = "PostCSS";
var type$8 = "markup";
var tmScope$8 = "source.postcss";
var group$c = "CSS";
var extensions$8 = [
".pcss",
".postcss"
];
var aceMode$8 = "text";
var languageId$8 = 262764437;
var PostCSS = {
name: name$a,
type: type$8,
tmScope: tmScope$8,
group: group$c,
extensions: extensions$8,
aceMode: aceMode$8,
languageId: languageId$8
};
var PostCSS$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
name: name$a,
type: type$8,
tmScope: tmScope$8,
group: group$c,
extensions: extensions$8,
aceMode: aceMode$8,
languageId: languageId$8,
'default': PostCSS
});
var name$b = "Less";
var type$9 = "markup";
var group$d = "CSS";
var extensions$9 = [
".less"
];
var tmScope$9 = "source.css.less";
var aceMode$9 = "less";
var codemirrorMode$8 = "css";
var codemirrorMimeType$8 = "text/css";
var languageId$9 = 198;
var Less = {
name: name$b,
type: type$9,
group: group$d,
extensions: extensions$9,
tmScope: tmScope$9,
aceMode: aceMode$9,
codemirrorMode: codemirrorMode$8,
codemirrorMimeType: codemirrorMimeType$8,
languageId: languageId$9
};
var Less$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
name: name$b,
type: type$9,
group: group$d,
extensions: extensions$9,
tmScope: tmScope$9,
aceMode: aceMode$9,
codemirrorMode: codemirrorMode$8,
codemirrorMimeType: codemirrorMimeType$8,
languageId: languageId$9,
'default': Less
});
var name$c = "SCSS";
var type$a = "markup";
var tmScope$a = "source.css.scss";
var group$e = "CSS";
var aceMode$a = "scss";
var codemirrorMode$9 = "css";
var codemirrorMimeType$9 = "text/x-scss";
var extensions$a = [
".scss"
];
var languageId$a = 329;
var SCSS = {
name: name$c,
type: type$a,
tmScope: tmScope$a,
group: group$e,
aceMode: aceMode$a,
codemirrorMode: codemirrorMode$9,
codemirrorMimeType: codemirrorMimeType$9,
extensions: extensions$a,
languageId: languageId$a
};
var SCSS$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
name: name$c,
type: type$a,
tmScope: tmScope$a,
group: group$e,
aceMode: aceMode$a,
codemirrorMode: codemirrorMode$9,
codemirrorMimeType: codemirrorMimeType$9,
extensions: extensions$a,
languageId: languageId$a,
'default': SCSS
});
var require$$0$3 = getCjsExportFromNamespace(CSS$1);
var require$$1$1 = getCjsExportFromNamespace(PostCSS$1);
var require$$2$1 = getCjsExportFromNamespace(Less$1);
var require$$3$1 = getCjsExportFromNamespace(SCSS$1);
const languages$1 = [createLanguage(require$$0$3, () => ({
since: "1.4.0",
parsers: ["css"],
vscodeLanguageIds: ["css"]
})), createLanguage(require$$1$1, () => ({
since: "1.4.0",
parsers: ["css"],
vscodeLanguageIds: ["postcss"]
})), createLanguage(require$$2$1, () => ({
since: "1.4.0",
parsers: ["less"],
vscodeLanguageIds: ["less"]
})), createLanguage(require$$3$1, () => ({
since: "1.4.0",
parsers: ["scss"],
vscodeLanguageIds: ["scss"]
}))];
const printers$1 = {
postcss: printerPostcss
};
const parsers$1 = {
// TODO: switch these to just `postcss` and use `language` instead.
get css() {
return require("./parser-postcss").parsers.css;
},
get less() {
return require("./parser-postcss").parsers.less;
},
get scss() {
return require("./parser-postcss").parsers.scss;
}
};
var languageCss = {
languages: languages$1,
options: options$3,
printers: printers$1,
parsers: parsers$1
};
var clean$3 = function (ast, newNode) {
delete newNode.loc;
delete newNode.selfClosing; // (Glimmer/HTML) ignore TextNode whitespace
if (ast.type === "TextNode") {
const trimmed = ast.chars.trim();
if (!trimmed) {
return null;
}
newNode.chars = trimmed;
}
};
var index = [
"area",
"base",
"basefont",
"bgsound",
"br",
"col",
"command",
"embed",
"frame",
"hr",
"image",
"img",
"input",
"isindex",
"keygen",
"link",
"menuitem",
"meta",
"nextid",
"param",
"source",
"track",
"wbr"
];
var htmlVoidElements = /*#__PURE__*/Object.freeze({
__proto__: null,
'default': index
});
var htmlVoidElements$1 = getCjsExportFromNamespace(htmlVoidElements);
function isUppercase(string) {
return string.toUpperCase() === string;
}
function isGlimmerComponent(node) {
return isNodeOfSomeType(node, ["ElementNode"]) && typeof node.tag === "string" && (isUppercase(node.tag[0]) || node.tag.includes("."));
}
const voidTags = new Set(htmlVoidElements$1);
function isVoid(node) {
return isGlimmerComponent(node) && (node.children === 0 || node.children.every(n => isWhitespaceNode(n))) || voidTags.has(node.tag);
}
function isWhitespaceNode(node) {
return isNodeOfSomeType(node, ["TextNode"]) && !/\S/.test(node.chars);
}
function isNodeOfSomeType(node, types) {
return node && types.some(type => node.type === type);
}
function isParentOfSomeType(path, types) {
const parentNode = path.getParentNode(0);
return isNodeOfSomeType(parentNode, types);
}
function isPreviousNodeOfSomeType(path, types) {
const previousNode = getPreviousNode(path);
return isNodeOfSomeType(previousNode, types);
}
function isNextNodeOfSomeType(path, types) {
const nextNode = getNextNode(path);
return isNodeOfSomeType(nextNode, types);
}
function getSiblingNode(path, offset) {
const node = path.getValue();
const parentNode = path.getParentNode(0) || {};
const children = parentNode.children || parentNode.body || parentNode.parts || [];
const index = children.indexOf(node);
return index !== -1 && children[index + offset];
}
function getPreviousNode(path, lookBack = 1) {
return getSiblingNode(path, -lookBack);
}
function getNextNode(path) {
return getSiblingNode(path, 1);
}
function isPrettierIgnoreNode(node) {
return isNodeOfSomeType(node, ["MustacheCommentStatement"]) && typeof node.value === "string" && node.value.trim() === "prettier-ignore";
}
function hasPrettierIgnore$2(path) {
const node = path.getValue();
const previousPreviousNode = getPreviousNode(path, 2);
return isPrettierIgnoreNode(node) || isPrettierIgnoreNode(previousPreviousNode);
}
var utils$8 = {
getNextNode,
getPreviousNode,
hasPrettierIgnore: hasPrettierIgnore$2,
isNextNodeOfSomeType,
isNodeOfSomeType,
isParentOfSomeType,
isPreviousNodeOfSomeType,
isVoid,
isWhitespaceNode
};
const {
concat: concat$g,
group: group$f,
hardline: hardline$b,
ifBreak: ifBreak$6,
indent: indent$b,
join: join$9,
line: line$a,
softline: softline$8
} = document.builders;
const {
getNextNode: getNextNode$1,
getPreviousNode: getPreviousNode$1,
hasPrettierIgnore: hasPrettierIgnore$3,
isNextNodeOfSomeType: isNextNodeOfSomeType$1,
isNodeOfSomeType: isNodeOfSomeType$1,
isParentOfSomeType: isParentOfSomeType$1,
isPreviousNodeOfSomeType: isPreviousNodeOfSomeType$1,
isVoid: isVoid$1,
isWhitespaceNode: isWhitespaceNode$1
} = utils$8; // Formatter based on @glimmerjs/syntax's built-in test formatter:
// https://github.com/glimmerjs/glimmer-vm/blob/master/packages/%40glimmer/syntax/lib/generation/print.ts
function print$2(path, options, print) {
const n = path.getValue();
/* istanbul ignore if*/
if (!n) {
return "";
}
if (hasPrettierIgnore$3(path)) {
const startOffset = locationToOffset(options.originalText, n.loc.start.line - 1, n.loc.start.column);
const endOffset = locationToOffset(options.originalText, n.loc.end.line - 1, n.loc.end.column);
const ignoredText = options.originalText.slice(startOffset, endOffset);
return ignoredText;
}
switch (n.type) {
case "Block":
case "Program":
case "Template":
{
return group$f(concat$g(path.map(print, "body")));
}
case "ElementNode":
{
// TODO: make it whitespace sensitive
const bim = isNextNodeOfSomeType$1(path, ["ElementNode"]) ? hardline$b : "";
if (isVoid$1(n)) {
return concat$g([group$f(printStartingTag(path, print)), bim]);
}
const isWhitespaceOnly = n.children.every(n => isWhitespaceNode$1(n));
return concat$g([group$f(printStartingTag(path, print)), group$f(concat$g([isWhitespaceOnly ? "" : indent$b(printChildren(path, options, print)), n.children.length ? hardline$b : "", concat$g(["", n.tag, ">"])])), bim]);
}
case "BlockStatement":
{
const pp = path.getParentNode(1);
const isElseIf = pp && pp.inverse && pp.inverse.body.length === 1 && pp.inverse.body[0] === n && pp.inverse.body[0].path.parts[0] === "if";
if (isElseIf) {
return concat$g([printElseIfBlock(path, print), printProgram(path, print), printInverse(path, print)]);
}
return concat$g([printOpenBlock(path, print), group$f(concat$g([printProgram(path, print), printInverse(path, print), printCloseBlock(path, print)]))]);
}
case "ElementModifierStatement":
{
return group$f(concat$g(["{{", printPathAndParams(path, print), softline$8, "}}"]));
}
case "MustacheStatement":
{
const isParentOfSpecifiedTypes = isParentOfSomeType$1(path, ["AttrNode", "ConcatStatement"]);
const isChildOfElementNodeAndDoesNotHaveParams = isParentOfSomeType$1(path, ["ElementNode"]) && doesNotHaveHashParams(n) && doesNotHavePositionalParams(n);
const shouldBreakOpeningMustache = isParentOfSpecifiedTypes || isChildOfElementNodeAndDoesNotHaveParams;
return group$f(concat$g([printOpeningMustache(n), shouldBreakOpeningMustache ? indent$b(softline$8) : "", printPathAndParams(path, print), softline$8, printClosingMustache(n)]));
}
case "SubExpression":
{
return group$f(concat$g(["(", printSubExpressionPathAndParams(path, print), softline$8, ")"]));
}
case "AttrNode":
{
const isText = n.value.type === "TextNode";
const isEmptyText = isText && n.value.chars === ""; // If the text is empty and the value's loc start and end columns are the
// same, there is no value for this AttrNode and it should be printed
// without the `=""`. Example: `
` -> `
`
const isEmptyValue = isEmptyText && n.value.loc.start.column === n.value.loc.end.column;
if (isEmptyValue) {
return concat$g([n.name]);
}
const value = path.call(print, "value");
const quotedValue = isText ? printStringLiteral(value.parts.join(), options) : value;
return concat$g([n.name, "=", quotedValue]);
}
case "ConcatStatement":
{
const quote = options.singleQuote ? "'" : '"';
return concat$g([quote, ...path.map(partPath => print(partPath), "parts"), quote]);
}
case "Hash":
{
return concat$g([join$9(line$a, path.map(print, "pairs"))]);
}
case "HashPair":
{
return concat$g([n.key, "=", path.call(print, "value")]);
}
case "TextNode":
{
const maxLineBreaksToPreserve = 2;
const isFirstElement = !getPreviousNode$1(path);
const isLastElement = !getNextNode$1(path);
const isWhitespaceOnly = !/\S/.test(n.chars);
const lineBreaksCount = countNewLines(n.chars);
let leadingLineBreaksCount = countLeadingNewLines(n.chars);
let trailingLineBreaksCount = countTrailingNewLines(n.chars);
if ((isFirstElement || isLastElement) && isWhitespaceOnly && isParentOfSomeType$1(path, ["Block", "ElementNode", "Template"])) {
return "";
}
if (isWhitespaceOnly && lineBreaksCount) {
leadingLineBreaksCount = Math.min(lineBreaksCount, maxLineBreaksToPreserve);
trailingLineBreaksCount = 0;
} else {
if (isNextNodeOfSomeType$1(path, ["BlockStatement", "ElementNode"])) {
trailingLineBreaksCount = Math.max(trailingLineBreaksCount, 1);
}
if (isPreviousNodeOfSomeType$1(path, ["BlockStatement", "ElementNode"])) {
leadingLineBreaksCount = Math.max(leadingLineBreaksCount, 1);
}
}
const inAttrNode = path.stack.includes("attributes");
if (inAttrNode) {
// TODO: format style and srcset attributes
// and cleanup concat that is not necessary
if (!isInAttributeOfName(path, "class")) {
return concat$g([n.chars]);
}
let leadingSpace = "";
let trailingSpace = "";
if (isParentOfSomeType$1(path, ["ConcatStatement"])) {
if (isPreviousNodeOfSomeType$1(path, ["MustacheStatement"])) {
leadingSpace = " ";
}
if (isNextNodeOfSomeType$1(path, ["MustacheStatement"])) {
trailingSpace = " ";
}
}
return concat$g([...generateHardlines(leadingLineBreaksCount, maxLineBreaksToPreserve), n.chars.replace(/^\s+/g, leadingSpace).replace(/\s+$/, trailingSpace), ...generateHardlines(trailingLineBreaksCount, maxLineBreaksToPreserve)]);
}
let leadingSpace = "";
let trailingSpace = "";
if (trailingLineBreaksCount === 0 && isNextNodeOfSomeType$1(path, ["MustacheStatement"])) {
trailingSpace = " ";
}
if (leadingLineBreaksCount === 0 && isPreviousNodeOfSomeType$1(path, ["MustacheStatement"])) {
leadingSpace = " ";
}
if (isFirstElement) {
leadingLineBreaksCount = 0;
leadingSpace = "";
}
if (isLastElement) {
trailingLineBreaksCount = 0;
trailingSpace = "";
}
let text = n.chars;
/* if `{{my-component}}` (or any text starting with a mustache)
* makes it to the TextNode,
* it means it was escaped,
* so let's print it escaped, ie.; `\{{my-component}}` */
if (text.startsWith("{{") && text.includes("}}")) {
text = "\\" + text;
}
return concat$g([...generateHardlines(leadingLineBreaksCount, maxLineBreaksToPreserve), text.replace(/^\s+/g, leadingSpace).replace(/\s+$/, trailingSpace), ...generateHardlines(trailingLineBreaksCount, maxLineBreaksToPreserve)]);
}
case "MustacheCommentStatement":
{
const dashes = n.value.includes("}}") ? "--" : "";
return concat$g(["{{!", dashes, n.value, dashes, "}}"]);
}
case "PathExpression":
{
return n.original;
}
case "BooleanLiteral":
{
return String(n.value);
}
case "CommentStatement":
{
return concat$g([""]);
}
case "StringLiteral":
{
return printStringLiteral(n.value, options);
}
case "NumberLiteral":
{
return String(n.value);
}
case "UndefinedLiteral":
{
return "undefined";
}
case "NullLiteral":
{
return "null";
}
/* istanbul ignore next */
default:
throw new Error("unknown glimmer type: " + JSON.stringify(n.type));
}
}
/* ElementNode print helpers */
function printStartingTag(path, print) {
const node = path.getValue();
return concat$g(["<", node.tag, printAttributesLike(path, print), printBlockParams(node), printStartingTagEndMarker(node)]);
}
function printAttributesLike(path, print) {
const node = path.getValue();
return indent$b(concat$g([node.attributes.length ? line$a : "", join$9(line$a, path.map(print, "attributes")), node.modifiers.length ? line$a : "", join$9(line$a, path.map(print, "modifiers")), node.comments.length ? line$a : "", join$9(line$a, path.map(print, "comments"))]));
}
function printChildren(path, options, print) {
return concat$g(path.map((childPath, childIndex) => {
if (childIndex === 0) {
return concat$g([softline$8, print(childPath, options, print)]);
}
return print(childPath, options, print);
}, "children"));
}
function printStartingTagEndMarker(node) {
if (isVoid$1(node)) {
return ifBreak$6(concat$g([softline$8, "/>"]), concat$g([" />", softline$8]));
}
return ifBreak$6(concat$g([softline$8, ">"]), ">");
}
/* MustacheStatement print helpers */
function printOpeningMustache(node) {
const mustache = node.escaped === false ? "{{{" : "{{";
const strip = node.strip && node.strip.open ? "~" : "";
return concat$g([mustache, strip]);
}
function printClosingMustache(node) {
const mustache = node.escaped === false ? "}}}" : "}}";
const strip = node.strip && node.strip.close ? "~" : "";
return concat$g([strip, mustache]);
}
/* BlockStatement print helpers */
function printOpeningBlockOpeningMustache(node) {
const opening = printOpeningMustache(node);
const strip = node.openStrip.open ? "~" : "";
return concat$g([opening, strip, "#"]);
}
function printOpeningBlockClosingMustache(node) {
const closing = printClosingMustache(node);
const strip = node.openStrip.close ? "~" : "";
return concat$g([strip, closing]);
}
function printClosingBlockOpeningMustache(node) {
const opening = printOpeningMustache(node);
const strip = node.closeStrip.open ? "~" : "";
return concat$g([opening, strip, "/"]);
}
function printClosingBlockClosingMustache(node) {
const closing = printClosingMustache(node);
const strip = node.closeStrip.close ? "~" : "";
return concat$g([strip, closing]);
}
function printInverseBlockOpeningMustache(node) {
const opening = printOpeningMustache(node);
const strip = node.inverseStrip.open ? "~" : "";
return concat$g([opening, strip]);
}
function printInverseBlockClosingMustache(node) {
const closing = printClosingMustache(node);
const strip = node.inverseStrip.close ? "~" : "";
return concat$g([strip, closing]);
}
function printOpenBlock(path, print) {
const node = path.getValue();
return group$f(concat$g([printOpeningBlockOpeningMustache(node), printPathAndParams(path, print), printBlockParams(node.program), softline$8, printOpeningBlockClosingMustache(node)]));
}
function printElseBlock(node) {
return concat$g([hardline$b, printInverseBlockOpeningMustache(node), "else", printInverseBlockClosingMustache(node)]);
}
function printElseIfBlock(path, print) {
const parentNode = path.getParentNode(1);
return concat$g([printInverseBlockOpeningMustache(parentNode), "else ", printPathAndParams(path, print), printInverseBlockClosingMustache(parentNode)]);
}
function printCloseBlock(path, print) {
const node = path.getValue();
return concat$g([blockStatementHasOnlyWhitespaceInProgram(node) ? softline$8 : hardline$b, printClosingBlockOpeningMustache(node), path.call(print, "path"), printClosingBlockClosingMustache(node)]);
}
function blockStatementHasOnlyWhitespaceInProgram(node) {
return isNodeOfSomeType$1(node, ["BlockStatement"]) && node.program.body.every(n => isWhitespaceNode$1(n));
}
function blockStatementHasElseIf(node) {
return blockStatementHasElse(node) && node.inverse.body.length === 1 && isNodeOfSomeType$1(node.inverse.body[0], ["BlockStatement"]) && node.inverse.body[0].path.parts[0] === "if";
}
function blockStatementHasElse(node) {
return isNodeOfSomeType$1(node, ["BlockStatement"]) && node.inverse;
}
function printProgram(path, print) {
const node = path.getValue();
if (blockStatementHasOnlyWhitespaceInProgram(node)) {
return "";
}
const program = path.call(print, "program");
return indent$b(concat$g([hardline$b, program]));
}
function printInverse(path, print) {
const node = path.getValue();
const inverse = path.call(print, "inverse");
const parts = concat$g([hardline$b, inverse]);
if (blockStatementHasElseIf(node)) {
return parts;
}
if (blockStatementHasElse(node)) {
return concat$g([printElseBlock(node), indent$b(parts)]);
}
return "";
}
/* TextNode print helpers */
function isInAttributeOfName(path, type) {
return isParentOfSomeType$1(path, ["AttrNode"]) && path.getParentNode().name.toLowerCase() === type || isParentOfSomeType$1(path, ["ConcatStatement"]) && path.getParentNode(1).name.toLowerCase() === type;
}
function countNewLines(string) {
/* istanbul ignore next */
string = typeof string === "string" ? string : "";
return string.split("\n").length - 1;
}
function countLeadingNewLines(string) {
/* istanbul ignore next */
string = typeof string === "string" ? string : "";
const newLines = (string.match(/^([^\S\n\r]*[\n\r])+/g) || [])[0] || "";
return countNewLines(newLines);
}
function countTrailingNewLines(string) {
/* istanbul ignore next */
string = typeof string === "string" ? string : "";
const newLines = (string.match(/([\n\r][^\S\n\r]*)+$/g) || [])[0] || "";
return countNewLines(newLines);
}
function generateHardlines(number = 0, max = 0) {
return new Array(Math.min(number, max)).fill(hardline$b);
}
/* StringLiteral print helpers */
/**
* Prints a string literal with the correct surrounding quotes based on
* `options.singleQuote` and the number of escaped quotes contained in
* the string literal. This function is the glimmer equivalent of `printString`
* in `common/util`, but has differences because of the way escaped characters
* are treated in hbs string literals.
* @param {string} stringLiteral - the string literal value
* @param {object} options - the prettier options object
*/
function printStringLiteral(stringLiteral, options) {
const double = {
quote: '"',
regex: /"/g
};
const single = {
quote: "'",
regex: /'/g
};
const preferred = options.singleQuote ? single : double;
const alternate = preferred === single ? double : single;
let shouldUseAlternateQuote = false; // If `stringLiteral` contains at least one of the quote preferred for
// enclosing the string, we might want to enclose with the alternate quote
// instead, to minimize the number of escaped quotes.
if (stringLiteral.includes(preferred.quote) || stringLiteral.includes(alternate.quote)) {
const numPreferredQuotes = (stringLiteral.match(preferred.regex) || []).length;
const numAlternateQuotes = (stringLiteral.match(alternate.regex) || []).length;
shouldUseAlternateQuote = numPreferredQuotes > numAlternateQuotes;
}
const enclosingQuote = shouldUseAlternateQuote ? alternate : preferred;
const escapedStringLiteral = stringLiteral.replace(enclosingQuote.regex, `\\${enclosingQuote.quote}`);
return concat$g([enclosingQuote.quote, escapedStringLiteral, enclosingQuote.quote]);
}
/* SubExpression print helpers */
function printSubExpressionPathAndParams(path, print) {
const p = printPath(path, print);
const params = printParams(path, print);
if (!params) {
return p;
}
return indent$b(concat$g([p, line$a, group$f(params)]));
}
/* misc. print helpers */
function printPathAndParams(path, print) {
const p = printPath(path, print);
const params = printParams(path, print);
if (!params) {
return p;
}
return indent$b(group$f(concat$g([p, line$a, params])));
}
function printPath(path, print) {
return path.call(print, "path");
}
function printParams(path, print) {
const node = path.getValue();
const parts = [];
if (node.params.length) {
const params = path.map(print, "params");
parts.push(...params);
}
if (node.hash && node.hash.pairs.length > 0) {
const hash = path.call(print, "hash");
parts.push(hash);
}
if (!parts.length) {
return "";
}
return join$9(line$a, parts);
}
function printBlockParams(node) {
if (!node || !node.blockParams.length) {
return "";
}
return concat$g([" as |", node.blockParams.join(" "), "|"]);
}
/* istanbul ignore next
https://github.com/glimmerjs/glimmer-vm/blob/master/packages/%40glimmer/compiler/lib/location.ts#L5-L29
*/
function locationToOffset(source, line, column) {
let seenLines = 0;
let seenChars = 0; // eslint-disable-next-line no-constant-condition
while (true) {
if (seenChars === source.length) {
return null;
}
let nextLine = source.indexOf("\n", seenChars);
if (nextLine === -1) {
nextLine = source.length;
}
if (seenLines === line) {
if (seenChars + column > nextLine) {
return null;
}
return seenChars + column;
} else if (nextLine === -1) {
return null;
}
seenLines += 1;
seenChars = nextLine + 1;
}
}
function doesNotHaveHashParams(node) {
return node.hash.pairs.length === 0;
}
function doesNotHavePositionalParams(node) {
return node.params.length === 0;
}
var printerGlimmer = {
print: print$2,
massageAstNode: clean$3
};
var name$d = "Handlebars";
var type$b = "markup";
var group$g = "HTML";
var aliases$3 = [
"hbs",
"htmlbars"
];
var extensions$b = [
".handlebars",
".hbs"
];
var tmScope$b = "text.html.handlebars";
var aceMode$b = "handlebars";
var languageId$b = 155;
var Handlebars = {
name: name$d,
type: type$b,
group: group$g,
aliases: aliases$3,
extensions: extensions$b,
tmScope: tmScope$b,
aceMode: aceMode$b,
languageId: languageId$b
};
var Handlebars$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
name: name$d,
type: type$b,
group: group$g,
aliases: aliases$3,
extensions: extensions$b,
tmScope: tmScope$b,
aceMode: aceMode$b,
languageId: languageId$b,
'default': Handlebars
});
var require$$0$4 = getCjsExportFromNamespace(Handlebars$1);
const languages$2 = [createLanguage(require$$0$4, () => ({
since: null,
// unreleased
parsers: ["glimmer"],
vscodeLanguageIds: ["handlebars"]
}))];
const printers$2 = {
glimmer: printerGlimmer
};
const parsers$2 = {
get glimmer() {
return require("./parser-glimmer").parsers.glimmer;
}
};
var languageHandlebars = {
languages: languages$2,
printers: printers$2,
parsers: parsers$2
};
function hasPragma$2(text) {
return /^\s*#[^\S\n]*@(format|prettier)\s*(\n|$)/.test(text);
}
function insertPragma$4(text) {
return "# @format\n\n" + text;
}
var pragma$2 = {
hasPragma: hasPragma$2,
insertPragma: insertPragma$4
};
const {
concat: concat$h,
join: join$a,
hardline: hardline$c,
line: line$b,
softline: softline$9,
group: group$h,
indent: indent$c,
ifBreak: ifBreak$7
} = document.builders;
const {
hasIgnoreComment: hasIgnoreComment$4,
isNextLineEmpty: isNextLineEmpty$6
} = util;
const {
insertPragma: insertPragma$5
} = pragma$2;
function genericPrint$3(path, options, print) {
const n = path.getValue();
if (!n) {
return "";
}
if (typeof n === "string") {
return n;
}
switch (n.kind) {
case "Document":
{
const parts = [];
path.map((pathChild, index) => {
parts.push(concat$h([pathChild.call(print)]));
if (index !== n.definitions.length - 1) {
parts.push(hardline$c);
if (isNextLineEmpty$6(options.originalText, pathChild.getValue(), options.locEnd)) {
parts.push(hardline$c);
}
}
}, "definitions");
return concat$h([concat$h(parts), hardline$c]);
}
case "OperationDefinition":
{
const hasOperation = options.originalText[options.locStart(n)] !== "{";
const hasName = !!n.name;
return concat$h([hasOperation ? n.operation : "", hasOperation && hasName ? concat$h([" ", path.call(print, "name")]) : "", n.variableDefinitions && n.variableDefinitions.length ? group$h(concat$h(["(", indent$c(concat$h([softline$9, join$a(concat$h([ifBreak$7("", ", "), softline$9]), path.map(print, "variableDefinitions"))])), softline$9, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? !hasOperation && !hasName ? "" : " " : "", path.call(print, "selectionSet")]);
}
case "FragmentDefinition":
{
return concat$h(["fragment ", path.call(print, "name"), n.variableDefinitions && n.variableDefinitions.length ? group$h(concat$h(["(", indent$c(concat$h([softline$9, join$a(concat$h([ifBreak$7("", ", "), softline$9]), path.map(print, "variableDefinitions"))])), softline$9, ")"])) : "", " on ", path.call(print, "typeCondition"), printDirectives(path, print, n), " ", path.call(print, "selectionSet")]);
}
case "SelectionSet":
{
return concat$h(["{", indent$c(concat$h([hardline$c, join$a(hardline$c, path.call(selectionsPath => printSequence(selectionsPath, options, print), "selections"))])), hardline$c, "}"]);
}
case "Field":
{
return group$h(concat$h([n.alias ? concat$h([path.call(print, "alias"), ": "]) : "", path.call(print, "name"), n.arguments.length > 0 ? group$h(concat$h(["(", indent$c(concat$h([softline$9, join$a(concat$h([ifBreak$7("", ", "), softline$9]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$9, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? " " : "", path.call(print, "selectionSet")]));
}
case "Name":
{
return n.value;
}
case "StringValue":
{
if (n.block) {
return concat$h(['"""', hardline$c, join$a(hardline$c, n.value.replace(/"""/g, "\\$&").split("\n")), hardline$c, '"""']);
}
return concat$h(['"', n.value.replace(/["\\]/g, "\\$&").replace(/\n/g, "\\n"), '"']);
}
case "IntValue":
case "FloatValue":
case "EnumValue":
{
return n.value;
}
case "BooleanValue":
{
return n.value ? "true" : "false";
}
case "NullValue":
{
return "null";
}
case "Variable":
{
return concat$h(["$", path.call(print, "name")]);
}
case "ListValue":
{
return group$h(concat$h(["[", indent$c(concat$h([softline$9, join$a(concat$h([ifBreak$7("", ", "), softline$9]), path.map(print, "values"))])), softline$9, "]"]));
}
case "ObjectValue":
{
return group$h(concat$h(["{", options.bracketSpacing && n.fields.length > 0 ? " " : "", indent$c(concat$h([softline$9, join$a(concat$h([ifBreak$7("", ", "), softline$9]), path.map(print, "fields"))])), softline$9, ifBreak$7("", options.bracketSpacing && n.fields.length > 0 ? " " : ""), "}"]));
}
case "ObjectField":
case "Argument":
{
return concat$h([path.call(print, "name"), ": ", path.call(print, "value")]);
}
case "Directive":
{
return concat$h(["@", path.call(print, "name"), n.arguments.length > 0 ? group$h(concat$h(["(", indent$c(concat$h([softline$9, join$a(concat$h([ifBreak$7("", ", "), softline$9]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$9, ")"])) : ""]);
}
case "NamedType":
{
return path.call(print, "name");
}
case "VariableDefinition":
{
return concat$h([path.call(print, "variable"), ": ", path.call(print, "type"), n.defaultValue ? concat$h([" = ", path.call(print, "defaultValue")]) : "", printDirectives(path, print, n)]);
}
case "ObjectTypeExtension":
case "ObjectTypeDefinition":
{
return concat$h([path.call(print, "description"), n.description ? hardline$c : "", n.kind === "ObjectTypeExtension" ? "extend " : "", "type ", path.call(print, "name"), n.interfaces.length > 0 ? concat$h([" implements ", concat$h(printInterfaces(path, options, print))]) : "", printDirectives(path, print, n), n.fields.length > 0 ? concat$h([" {", indent$c(concat$h([hardline$c, join$a(hardline$c, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$c, "}"]) : ""]);
}
case "FieldDefinition":
{
return concat$h([path.call(print, "description"), n.description ? hardline$c : "", path.call(print, "name"), n.arguments.length > 0 ? group$h(concat$h(["(", indent$c(concat$h([softline$9, join$a(concat$h([ifBreak$7("", ", "), softline$9]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$9, ")"])) : "", ": ", path.call(print, "type"), printDirectives(path, print, n)]);
}
case "DirectiveDefinition":
{
return concat$h([path.call(print, "description"), n.description ? hardline$c : "", "directive ", "@", path.call(print, "name"), n.arguments.length > 0 ? group$h(concat$h(["(", indent$c(concat$h([softline$9, join$a(concat$h([ifBreak$7("", ", "), softline$9]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$9, ")"])) : "", n.repeatable ? " repeatable" : "", concat$h([" on ", join$a(" | ", path.map(print, "locations"))])]);
}
case "EnumTypeExtension":
case "EnumTypeDefinition":
{
return concat$h([path.call(print, "description"), n.description ? hardline$c : "", n.kind === "EnumTypeExtension" ? "extend " : "", "enum ", path.call(print, "name"), printDirectives(path, print, n), n.values.length > 0 ? concat$h([" {", indent$c(concat$h([hardline$c, join$a(hardline$c, path.call(valuesPath => printSequence(valuesPath, options, print), "values"))])), hardline$c, "}"]) : ""]);
}
case "EnumValueDefinition":
{
return concat$h([path.call(print, "description"), n.description ? hardline$c : "", path.call(print, "name"), printDirectives(path, print, n)]);
}
case "InputValueDefinition":
{
return concat$h([path.call(print, "description"), n.description ? n.description.block ? hardline$c : line$b : "", path.call(print, "name"), ": ", path.call(print, "type"), n.defaultValue ? concat$h([" = ", path.call(print, "defaultValue")]) : "", printDirectives(path, print, n)]);
}
case "InputObjectTypeExtension":
case "InputObjectTypeDefinition":
{
return concat$h([path.call(print, "description"), n.description ? hardline$c : "", n.kind === "InputObjectTypeExtension" ? "extend " : "", "input ", path.call(print, "name"), printDirectives(path, print, n), n.fields.length > 0 ? concat$h([" {", indent$c(concat$h([hardline$c, join$a(hardline$c, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$c, "}"]) : ""]);
}
case "SchemaDefinition":
{
return concat$h(["schema", printDirectives(path, print, n), " {", n.operationTypes.length > 0 ? indent$c(concat$h([hardline$c, join$a(hardline$c, path.call(opsPath => printSequence(opsPath, options, print), "operationTypes"))])) : "", hardline$c, "}"]);
}
case "OperationTypeDefinition":
{
return concat$h([path.call(print, "operation"), ": ", path.call(print, "type")]);
}
case "InterfaceTypeExtension":
case "InterfaceTypeDefinition":
{
return concat$h([path.call(print, "description"), n.description ? hardline$c : "", n.kind === "InterfaceTypeExtension" ? "extend " : "", "interface ", path.call(print, "name"), n.interfaces.length > 0 ? concat$h([" implements ", concat$h(printInterfaces(path, options, print))]) : "", printDirectives(path, print, n), n.fields.length > 0 ? concat$h([" {", indent$c(concat$h([hardline$c, join$a(hardline$c, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$c, "}"]) : ""]);
}
case "FragmentSpread":
{
return concat$h(["...", path.call(print, "name"), printDirectives(path, print, n)]);
}
case "InlineFragment":
{
return concat$h(["...", n.typeCondition ? concat$h([" on ", path.call(print, "typeCondition")]) : "", printDirectives(path, print, n), " ", path.call(print, "selectionSet")]);
}
case "UnionTypeExtension":
case "UnionTypeDefinition":
{
return group$h(concat$h([path.call(print, "description"), n.description ? hardline$c : "", group$h(concat$h([n.kind === "UnionTypeExtension" ? "extend " : "", "union ", path.call(print, "name"), printDirectives(path, print, n), n.types.length > 0 ? concat$h([" =", ifBreak$7("", " "), indent$c(concat$h([ifBreak$7(concat$h([line$b, " "])), join$a(concat$h([line$b, "| "]), path.map(print, "types"))]))]) : ""]))]));
}
case "ScalarTypeExtension":
case "ScalarTypeDefinition":
{
return concat$h([path.call(print, "description"), n.description ? hardline$c : "", n.kind === "ScalarTypeExtension" ? "extend " : "", "scalar ", path.call(print, "name"), printDirectives(path, print, n)]);
}
case "NonNullType":
{
return concat$h([path.call(print, "type"), "!"]);
}
case "ListType":
{
return concat$h(["[", 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 group$h(concat$h([line$b, join$a(line$b, path.map(print, "directives"))]));
}
function printSequence(sequencePath, options, print) {
const count = sequencePath.getValue().length;
return sequencePath.map((path, i) => {
const printed = print(path);
if (isNextLineEmpty$6(options.originalText, path.getValue(), options.locEnd) && i < count - 1) {
return concat$h([printed, hardline$c]);
}
return printed;
});
}
function canAttachComment$1(node) {
return node.kind && node.kind !== "Comment";
}
function printComment$2(commentPath) {
const comment = commentPath.getValue();
if (comment.kind === "Comment") {
return "#" + comment.value.trimEnd();
}
/* istanbul ignore next */
throw new Error("Not a comment: " + JSON.stringify(comment));
}
function printInterfaces(path, options, print) {
const node = path.getNode();
const parts = [];
const {
interfaces
} = node;
const printed = path.map(node => print(node), "interfaces");
for (let index = 0; index < interfaces.length; index++) {
const interfaceNode = interfaces[index];
parts.push(printed[index]);
const nextInterfaceNode = interfaces[index + 1];
if (nextInterfaceNode) {
const textBetween = options.originalText.slice(interfaceNode.loc.end, nextInterfaceNode.loc.start);
const hasComment = textBetween.includes("#");
const separator = textBetween.replace(/#.*/g, "").trim();
parts.push(separator === "," ? "," : " &");
parts.push(hasComment ? line$b : " ");
}
}
return parts;
}
function clean$4(node, newNode
/*, parent*/
) {
delete newNode.loc;
delete newNode.comments;
}
var printerGraphql = {
print: genericPrint$3,
massageAstNode: clean$4,
hasPrettierIgnore: hasIgnoreComment$4,
insertPragma: insertPragma$5,
printComment: printComment$2,
canAttachComment: canAttachComment$1
};
var options$4 = {
bracketSpacing: commonOptions.bracketSpacing
};
var name$e = "GraphQL";
var type$c = "data";
var extensions$c = [
".graphql",
".gql",
".graphqls"
];
var tmScope$c = "source.graphql";
var aceMode$c = "text";
var languageId$c = 139;
var GraphQL = {
name: name$e,
type: type$c,
extensions: extensions$c,
tmScope: tmScope$c,
aceMode: aceMode$c,
languageId: languageId$c
};
var GraphQL$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
name: name$e,
type: type$c,
extensions: extensions$c,
tmScope: tmScope$c,
aceMode: aceMode$c,
languageId: languageId$c,
'default': GraphQL
});
var require$$0$5 = getCjsExportFromNamespace(GraphQL$1);
const languages$3 = [createLanguage(require$$0$5, () => ({
since: "1.5.0",
parsers: ["graphql"],
vscodeLanguageIds: ["graphql"]
}))];
const printers$3 = {
graphql: printerGraphql
};
const parsers$3 = {
get graphql() {
return require("./parser-graphql").parsers.graphql;
}
};
var languageGraphql = {
languages: languages$3,
options: options$4,
printers: printers$3,
parsers: parsers$3
};
var json = {
"cjkPattern": "(?:[\\u02ea-\\u02eb\\u1100-\\u11ff\\u2e80-\\u2e99\\u2e9b-\\u2ef3\\u2f00-\\u2fd5\\u3000-\\u303f\\u3041-\\u3096\\u3099-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u3190-\\u3191\\u3196-\\u31ba\\u31c0-\\u31e3\\u31f0-\\u321e\\u322a-\\u3247\\u3260-\\u327e\\u328a-\\u32b0\\u32c0-\\u32cb\\u32d0-\\u3370\\u337b-\\u337f\\u33e0-\\u33fe\\u3400-\\u4db5\\u4e00-\\u9fef\\ua960-\\ua97c\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufe10-\\ufe1f\\ufe30-\\ufe6f\\uff00-\\uffef]|[\\ud840-\\ud868\\ud86a-\\ud86c\\ud86f-\\ud872\\ud874-\\ud879][\\udc00-\\udfff]|\\ud82c[\\udc00-\\udd1e\\udd50-\\udd52\\udd64-\\udd67]|\\ud83c[\\ude00\\ude50-\\ude51]|\\ud869[\\udc00-\\uded6\\udf00-\\udfff]|\\ud86d[\\udc00-\\udf34\\udf40-\\udfff]|\\ud86e[\\udc00-\\udc1d\\udc20-\\udfff]|\\ud873[\\udc00-\\udea1\\udeb0-\\udfff]|\\ud87a[\\udc00-\\udfe0]|\\ud87e[\\udc00-\\ude1d])(?:[\\ufe00-\\ufe0f]|\\udb40[\\udd00-\\uddef])?",
"kPattern": "[\\u1100-\\u11ff\\u3001-\\u3003\\u3008-\\u3011\\u3013-\\u301f\\u302e-\\u3030\\u3037\\u30fb\\u3131-\\u318e\\u3200-\\u321e\\u3260-\\u327e\\ua960-\\ua97c\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\ufe45-\\ufe46\\uff61-\\uff65\\uffa0-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc]",
"punctuationPattern": "[\\u0021-\\u002f\\u003a-\\u0040\\u005b-\\u0060\\u007b-\\u007e\\u00a1\\u00a7\\u00ab\\u00b6-\\u00b7\\u00bb\\u00bf\\u037e\\u0387\\u055a-\\u055f\\u0589-\\u058a\\u05be\\u05c0\\u05c3\\u05c6\\u05f3-\\u05f4\\u0609-\\u060a\\u060c-\\u060d\\u061b\\u061e-\\u061f\\u066a-\\u066d\\u06d4\\u0700-\\u070d\\u07f7-\\u07f9\\u0830-\\u083e\\u085e\\u0964-\\u0965\\u0970\\u09fd\\u0a76\\u0af0\\u0c77\\u0c84\\u0df4\\u0e4f\\u0e5a-\\u0e5b\\u0f04-\\u0f12\\u0f14\\u0f3a-\\u0f3d\\u0f85\\u0fd0-\\u0fd4\\u0fd9-\\u0fda\\u104a-\\u104f\\u10fb\\u1360-\\u1368\\u1400\\u166e\\u169b-\\u169c\\u16eb-\\u16ed\\u1735-\\u1736\\u17d4-\\u17d6\\u17d8-\\u17da\\u1800-\\u180a\\u1944-\\u1945\\u1a1e-\\u1a1f\\u1aa0-\\u1aa6\\u1aa8-\\u1aad\\u1b5a-\\u1b60\\u1bfc-\\u1bff\\u1c3b-\\u1c3f\\u1c7e-\\u1c7f\\u1cc0-\\u1cc7\\u1cd3\\u2010-\\u2027\\u2030-\\u2043\\u2045-\\u2051\\u2053-\\u205e\\u207d-\\u207e\\u208d-\\u208e\\u2308-\\u230b\\u2329-\\u232a\\u2768-\\u2775\\u27c5-\\u27c6\\u27e6-\\u27ef\\u2983-\\u2998\\u29d8-\\u29db\\u29fc-\\u29fd\\u2cf9-\\u2cfc\\u2cfe-\\u2cff\\u2d70\\u2e00-\\u2e2e\\u2e30-\\u2e4f\\u3001-\\u3003\\u3008-\\u3011\\u3014-\\u301f\\u3030\\u303d\\u30a0\\u30fb\\ua4fe-\\ua4ff\\ua60d-\\ua60f\\ua673\\ua67e\\ua6f2-\\ua6f7\\ua874-\\ua877\\ua8ce-\\ua8cf\\ua8f8-\\ua8fa\\ua8fc\\ua92e-\\ua92f\\ua95f\\ua9c1-\\ua9cd\\ua9de-\\ua9df\\uaa5c-\\uaa5f\\uaade-\\uaadf\\uaaf0-\\uaaf1\\uabeb\\ufd3e-\\ufd3f\\ufe10-\\ufe19\\ufe30-\\ufe52\\ufe54-\\ufe61\\ufe63\\ufe68\\ufe6a-\\ufe6b\\uff01-\\uff03\\uff05-\\uff0a\\uff0c-\\uff0f\\uff1a-\\uff1b\\uff1f-\\uff20\\uff3b-\\uff3d\\uff3f\\uff5b\\uff5d\\uff5f-\\uff65]|\\ud800[\\udd00-\\udd02\\udf9f\\udfd0]|\\ud801[\\udd6f]|\\ud802[\\udc57\\udd1f\\udd3f\\ude50-\\ude58\\ude7f\\udef0-\\udef6\\udf39-\\udf3f\\udf99-\\udf9c]|\\ud803[\\udf55-\\udf59]|\\ud804[\\udc47-\\udc4d\\udcbb-\\udcbc\\udcbe-\\udcc1\\udd40-\\udd43\\udd74-\\udd75\\uddc5-\\uddc8\\uddcd\\udddb\\udddd-\\udddf\\ude38-\\ude3d\\udea9]|\\ud805[\\udc4b-\\udc4f\\udc5b\\udc5d\\udcc6\\uddc1-\\uddd7\\ude41-\\ude43\\ude60-\\ude6c\\udf3c-\\udf3e]|\\ud806[\\udc3b\\udde2\\ude3f-\\ude46\\ude9a-\\ude9c\\ude9e-\\udea2]|\\ud807[\\udc41-\\udc45\\udc70-\\udc71\\udef7-\\udef8\\udfff]|\\ud809[\\udc70-\\udc74]|\\ud81a[\\ude6e-\\ude6f\\udef5\\udf37-\\udf3b\\udf44]|\\ud81b[\\ude97-\\ude9a\\udfe2]|\\ud82f[\\udc9f]|\\ud836[\\ude87-\\ude8b]|\\ud83a[\\udd5e-\\udd5f]"
};
const {
getLast: getLast$6
} = util;
const {
cjkPattern,
kPattern,
punctuationPattern
} = json;
const INLINE_NODE_TYPES = ["liquidNode", "inlineCode", "emphasis", "strong", "delete", "link", "linkReference", "image", "imageReference", "footnote", "footnoteReference", "sentence", "whitespace", "word", "break", "inlineMath"];
const INLINE_NODE_WRAPPER_TYPES = INLINE_NODE_TYPES.concat(["tableCell", "paragraph", "heading"]);
const kRegex = new RegExp(kPattern);
const punctuationRegex = new RegExp(punctuationPattern);
/**
* split text into whitespaces and words
* @param {string} text
* @return {Array<{ type: "whitespace", value: " " | "\n" | "" } | { type: "word", value: string }>}
*/
function splitText(text, options) {
const KIND_NON_CJK = "non-cjk";
const KIND_CJ_LETTER = "cj-letter";
const KIND_K_LETTER = "k-letter";
const KIND_CJK_PUNCTUATION = "cjk-punctuation";
const nodes = [];
(options.proseWrap === "preserve" ? text : text.replace(new RegExp(`(${cjkPattern})\n(${cjkPattern})`, "g"), "$1$2")).split(/([\t\n ]+)/).forEach((token, index, tokens) => {
// whitespace
if (index % 2 === 1) {
nodes.push({
type: "whitespace",
value: /\n/.test(token) ? "\n" : " "
});
return;
} // word separated by whitespace
if ((index === 0 || index === tokens.length - 1) && token === "") {
return;
}
token.split(new RegExp(`(${cjkPattern})`)).forEach((innerToken, innerIndex, innerTokens) => {
if ((innerIndex === 0 || innerIndex === innerTokens.length - 1) && innerToken === "") {
return;
} // non-CJK word
if (innerIndex % 2 === 0) {
if (innerToken !== "") {
appendNode({
type: "word",
value: innerToken,
kind: KIND_NON_CJK,
hasLeadingPunctuation: punctuationRegex.test(innerToken[0]),
hasTrailingPunctuation: punctuationRegex.test(getLast$6(innerToken))
});
}
return;
} // CJK character
appendNode(punctuationRegex.test(innerToken) ? {
type: "word",
value: innerToken,
kind: KIND_CJK_PUNCTUATION,
hasLeadingPunctuation: true,
hasTrailingPunctuation: true
} : {
type: "word",
value: innerToken,
kind: kRegex.test(innerToken) ? KIND_K_LETTER : KIND_CJ_LETTER,
hasLeadingPunctuation: false,
hasTrailingPunctuation: false
});
});
});
return nodes;
function appendNode(node) {
const lastNode = getLast$6(nodes);
if (lastNode && lastNode.type === "word") {
if (lastNode.kind === KIND_NON_CJK && node.kind === KIND_CJ_LETTER && !lastNode.hasTrailingPunctuation || lastNode.kind === KIND_CJ_LETTER && node.kind === KIND_NON_CJK && !node.hasLeadingPunctuation) {
nodes.push({
type: "whitespace",
value: " "
});
} else if (!isBetween(KIND_NON_CJK, KIND_CJK_PUNCTUATION) && // disallow leading/trailing full-width whitespace
![lastNode.value, node.value].some(value => /\u3000/.test(value))) {
nodes.push({
type: "whitespace",
value: ""
});
}
}
nodes.push(node);
function isBetween(kind1, kind2) {
return lastNode.kind === kind1 && node.kind === kind2 || lastNode.kind === kind2 && node.kind === kind1;
}
}
}
function getOrderedListItemInfo(orderListItem, originalText) {
const [, numberText, marker, leadingSpaces] = originalText.slice(orderListItem.position.start.offset, orderListItem.position.end.offset).match(/^\s*(\d+)(\.|\))(\s*)/);
return {
numberText,
marker,
leadingSpaces
};
}
function hasGitDiffFriendlyOrderedList(node, options) {
if (!node.ordered) {
return false;
}
if (node.children.length < 2) {
return false;
}
const firstNumber = Number(getOrderedListItemInfo(node.children[0], options.originalText).numberText);
const secondNumber = Number(getOrderedListItemInfo(node.children[1], options.originalText).numberText);
if (firstNumber === 0 && node.children.length > 2) {
const thirdNumber = Number(getOrderedListItemInfo(node.children[2], options.originalText).numberText);
return secondNumber === 1 && thirdNumber === 1;
}
return secondNumber === 1;
} // workaround for https://github.com/remarkjs/remark/issues/351
// leading and trailing newlines are stripped by remark
function getFencedCodeBlockValue(node, originalText) {
const text = originalText.trimEnd().slice(node.position.start.offset, node.position.end.offset);
const leadingSpaceCount = text.match(/^\s*/)[0].length;
const replaceRegex = new RegExp(`^\\s{0,${leadingSpaceCount}}`);
const lineContents = text.split("\n");
const markerStyle = text[leadingSpaceCount]; // ` or ~
const marker = text.slice(leadingSpaceCount).match(new RegExp(`^[${markerStyle}]+`))[0]; // https://spec.commonmark.org/0.28/#example-104: Closing fences may be indented by 0-3 spaces
// https://spec.commonmark.org/0.28/#example-93: The closing code fence must be at least as long as the opening fence
const hasEndMarker = new RegExp(`^\\s{0,3}${marker}`).test(lineContents[lineContents.length - 1].slice(getIndent(lineContents.length - 1)));
return lineContents.slice(1, hasEndMarker ? -1 : undefined).map((x, i) => x.slice(getIndent(i + 1)).replace(replaceRegex, "")).join("\n");
function getIndent(lineIndex) {
return node.position.indent[lineIndex - 1] - 1;
}
}
function mapAst(ast, handler) {
return function preorder(node, index, parentStack) {
parentStack = parentStack || [];
const newNode = Object.assign({}, handler(node, index, parentStack));
if (newNode.children) {
newNode.children = newNode.children.map((child, index) => {
return preorder(child, index, [newNode].concat(parentStack));
});
}
return newNode;
}(ast, null, null);
}
function isAutolink(node, options) {
if (!node || node.type !== "link" || node.children.length !== 1) {
return false;
}
const child = node.children[0];
return child && options.locStart(node) === options.locStart(child) && options.locEnd(node) === options.locEnd(child);
}
var utils$9 = {
mapAst,
splitText,
punctuationPattern,
getFencedCodeBlockValue,
getOrderedListItemInfo,
hasGitDiffFriendlyOrderedList,
INLINE_NODE_TYPES,
INLINE_NODE_WRAPPER_TYPES,
isAutolink
};
const {
getParserName: getParserName$1,
getMaxContinuousCount: getMaxContinuousCount$2
} = util;
const {
builders: {
hardline: hardline$d,
literalline: literalline$3,
concat: concat$i,
markAsRoot: markAsRoot$2
},
utils: {
mapDoc: mapDoc$2
}
} = document;
const {
print: printFrontMatter$1
} = frontMatter;
const {
getFencedCodeBlockValue: getFencedCodeBlockValue$1
} = utils$9;
function embed$2(path, print, textToDoc, options) {
const 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)
const langMatch = node.lang.match(/^[\w-]+/);
const lang = langMatch ? langMatch[0] : "";
const parser = getParserName$1(lang, options);
if (parser) {
const styleUnit = options.__inJsTemplate ? "~" : "`";
const style = styleUnit.repeat(Math.max(3, getMaxContinuousCount$2(node.value, styleUnit) + 1));
const doc = textToDoc(getFencedCodeBlockValue$1(node, options.originalText), {
parser
}, {
stripTrailingHardline: true
});
return markAsRoot$2(concat$i([style, node.lang, node.meta ? " " + node.meta : "", hardline$d, replaceNewlinesWithLiterallines(doc), hardline$d, style]));
}
}
switch (node.type) {
case "front-matter":
return printFrontMatter$1(node, textToDoc);
// MDX
case "importExport":
return concat$i([textToDoc(node.value, {
parser: "babel"
}, {
stripTrailingHardline: true
}), hardline$d]);
case "jsx":
return textToDoc(`<$>${node.value}$>`, {
parser: "__js_expression",
rootMarker: "mdx"
}, {
stripTrailingHardline: true
});
}
return null;
function replaceNewlinesWithLiterallines(doc) {
return mapDoc$2(doc, currentDoc => typeof currentDoc === "string" && currentDoc.includes("\n") ? concat$i(currentDoc.split(/(\n)/g).map((v, i) => i % 2 === 0 ? v : literalline$3)) : currentDoc);
}
}
var embed_1$2 = embed$2;
const {
parse: parseFrontMatter$1
} = frontMatter;
const pragmas = ["format", "prettier"];
function startWithPragma(text) {
const pragma = `@(${pragmas.join("|")})`;
const regex = new RegExp([``, ``].join("|"), "m");
const matched = text.match(regex);
return matched && matched.index === 0;
}
var pragma$3 = {
startWithPragma,
hasPragma: text => startWithPragma(parseFrontMatter$1(text).content.trimStart()),
insertPragma: text => {
const extracted = parseFrontMatter$1(text);
const pragma = ``;
return extracted.frontMatter ? `${extracted.frontMatter.raw}\n\n${pragma}\n\n${extracted.content}` : `${pragma}\n\n${extracted.content}`;
}
};
const {
getOrderedListItemInfo: getOrderedListItemInfo$1,
mapAst: mapAst$1,
splitText: splitText$1
} = utils$9; // 0x0 ~ 0x10ffff
// eslint-disable-next-line no-control-regex
const isSingleCharRegex = /^([\u0000-\uffff]|[\ud800-\udbff][\udc00-\udfff])$/;
function preprocess$1(ast, options) {
ast = restoreUnescapedCharacter(ast, options);
ast = mergeContinuousTexts(ast);
ast = transformInlineCode(ast);
ast = transformIndentedCodeblockAndMarkItsParentList(ast, options);
ast = markAlignedList(ast, options);
ast = splitTextIntoSentences(ast, options);
ast = transformImportExport(ast);
ast = mergeContinuousImportExport(ast);
return ast;
}
function transformImportExport(ast) {
return mapAst$1(ast, node => {
if (node.type !== "import" && node.type !== "export") {
return node;
}
return Object.assign({}, node, {
type: "importExport"
});
});
}
function transformInlineCode(ast) {
return mapAst$1(ast, node => {
if (node.type !== "inlineCode") {
return node;
}
return Object.assign({}, node, {
value: node.value.replace(/\s+/g, " ")
});
});
}
function restoreUnescapedCharacter(ast, options) {
return mapAst$1(ast, node => {
return node.type !== "text" ? node : Object.assign({}, node, {
value: node.value !== "*" && node.value !== "_" && node.value !== "$" && // handle these cases in printer
isSingleCharRegex.test(node.value) && node.position.end.offset - node.position.start.offset !== node.value.length ? options.originalText.slice(node.position.start.offset, node.position.end.offset) : node.value
});
});
}
function mergeContinuousImportExport(ast) {
return mergeChildren(ast, (prevNode, node) => prevNode.type === "importExport" && node.type === "importExport", (prevNode, node) => ({
type: "importExport",
value: prevNode.value + "\n\n" + node.value,
position: {
start: prevNode.position.start,
end: node.position.end
}
}));
}
function mergeChildren(ast, shouldMerge, mergeNode) {
return mapAst$1(ast, node => {
if (!node.children) {
return node;
}
const children = node.children.reduce((current, child) => {
const lastChild = current[current.length - 1];
if (lastChild && shouldMerge(lastChild, child)) {
current.splice(-1, 1, mergeNode(lastChild, child));
} else {
current.push(child);
}
return current;
}, []);
return Object.assign({}, node, {
children
});
});
}
function mergeContinuousTexts(ast) {
return mergeChildren(ast, (prevNode, node) => prevNode.type === "text" && node.type === "text", (prevNode, node) => ({
type: "text",
value: prevNode.value + node.value,
position: {
start: prevNode.position.start,
end: node.position.end
}
}));
}
function splitTextIntoSentences(ast, options) {
return mapAst$1(ast, (node, index, [parentNode]) => {
if (node.type !== "text") {
return node;
}
let {
value
} = node;
if (parentNode.type === "paragraph") {
if (index === 0) {
value = value.trimStart();
}
if (index === parentNode.children.length - 1) {
value = value.trimEnd();
}
}
return {
type: "sentence",
position: node.position,
children: splitText$1(value, options)
};
});
}
function transformIndentedCodeblockAndMarkItsParentList(ast, options) {
return mapAst$1(ast, (node, index, parentStack) => {
if (node.type === "code") {
// the first char may point to `\n`, e.g. `\n\t\tbar`, just ignore it
const isIndented = /^\n?( {4,}|\t)/.test(options.originalText.slice(node.position.start.offset, node.position.end.offset));
node.isIndented = isIndented;
if (isIndented) {
for (let i = 0; i < parentStack.length; i++) {
const parent = parentStack[i]; // no need to check checked items
if (parent.hasIndentedCodeblock) {
break;
}
if (parent.type === "list") {
parent.hasIndentedCodeblock = true;
}
}
}
}
return node;
});
}
function markAlignedList(ast, options) {
return mapAst$1(ast, (node, index, parentStack) => {
if (node.type === "list" && node.children.length !== 0) {
// if one of its parents is not aligned, it's not possible to be aligned in sub-lists
for (let i = 0; i < parentStack.length; i++) {
const parent = parentStack[i];
if (parent.type === "list" && !parent.isAligned) {
node.isAligned = false;
return node;
}
}
node.isAligned = isAligned(node);
}
return node;
});
function getListItemStart(listItem) {
return listItem.children.length === 0 ? -1 : listItem.children[0].position.start.column - 1;
}
function isAligned(list) {
if (!list.ordered) {
/**
* - 123
* - 123
*/
return true;
}
const [firstItem, secondItem] = list.children;
const firstInfo = getOrderedListItemInfo$1(firstItem, options.originalText);
if (firstInfo.leadingSpaces.length > 1) {
/**
* 1. 123
*
* 1. 123
* 1. 123
*/
return true;
}
const firstStart = getListItemStart(firstItem);
if (firstStart === -1) {
/**
* 1.
*
* 1.
* 1.
*/
return false;
}
if (list.children.length === 1) {
/**
* aligned:
*
* 11. 123
*
* not aligned:
*
* 1. 123
*/
return firstStart % options.tabWidth === 0;
}
const secondStart = getListItemStart(secondItem);
if (firstStart !== secondStart) {
/**
* 11. 123
* 1. 123
*
* 1. 123
* 11. 123
*/
return false;
}
if (firstStart % options.tabWidth === 0) {
/**
* 11. 123
* 12. 123
*/
return true;
}
/**
* aligned:
*
* 11. 123
* 1. 123
*
* not aligned:
*
* 1. 123
* 2. 123
*/
const secondInfo = getOrderedListItemInfo$1(secondItem, options.originalText);
return secondInfo.leadingSpaces.length > 1;
}
}
var preprocess_1$1 = preprocess$1;
const {
getLast: getLast$7,
getMinNotPresentContinuousCount: getMinNotPresentContinuousCount$1,
getMaxContinuousCount: getMaxContinuousCount$3,
getStringWidth: getStringWidth$4
} = util;
const {
builders: {
breakParent: breakParent$6,
concat: concat$j,
join: join$b,
line: line$c,
literalline: literalline$4,
markAsRoot: markAsRoot$3,
hardline: hardline$e,
softline: softline$a,
ifBreak: ifBreak$8,
fill: fill$5,
align: align$3,
indent: indent$d,
group: group$i
},
utils: {
normalizeDoc: normalizeDoc$1
},
printer: {
printDocToString: printDocToString$3
}
} = document;
const {
replaceEndOfLineWith: replaceEndOfLineWith$1,
isFrontMatterNode: isFrontMatterNode$3
} = util;
const {
getFencedCodeBlockValue: getFencedCodeBlockValue$2,
hasGitDiffFriendlyOrderedList: hasGitDiffFriendlyOrderedList$1,
splitText: splitText$2,
punctuationPattern: punctuationPattern$1,
INLINE_NODE_TYPES: INLINE_NODE_TYPES$1,
INLINE_NODE_WRAPPER_TYPES: INLINE_NODE_WRAPPER_TYPES$1,
isAutolink: isAutolink$1
} = utils$9;
const TRAILING_HARDLINE_NODES = new Set(["importExport"]);
const SINGLE_LINE_NODE_TYPES = ["heading", "tableCell", "link"];
const SIBLING_NODE_TYPES = new Set(["listItem", "definition", "footnoteDefinition"]);
function genericPrint$4(path, options, print) {
const node = path.getValue();
if (shouldRemainTheSameContent(path)) {
return concat$j(splitText$2(options.originalText.slice(node.position.start.offset, node.position.end.offset), options).map(node => node.type === "word" ? node.value : node.value === "" ? "" : printLine(path, node.value, options)));
}
switch (node.type) {
case "front-matter":
return options.originalText.slice(node.position.start.offset, node.position.end.offset);
case "root":
if (node.children.length === 0) {
return "";
}
return concat$j([normalizeDoc$1(printRoot(path, options, print)), !TRAILING_HARDLINE_NODES.has(getLastDescendantNode(node).type) ? hardline$e : ""]);
case "paragraph":
return printChildren$1(path, options, print, {
postprocessor: fill$5
});
case "sentence":
return printChildren$1(path, options, print);
case "word":
{
let escapedValue = node.value.replace(/[$*]/g, "\\$&") // escape all `*` and `$` (math)
.replace(new RegExp([`(^|${punctuationPattern$1})(_+)`, `(_+)(${punctuationPattern$1}|$)`].join("|"), "g"), (_, text1, underscore1, underscore2, text2) => (underscore1 ? `${text1}${underscore1}` : `${underscore2}${text2}`).replace(/_/g, "\\_")); // escape all `_` except concating with non-punctuation, e.g. `1_2_3` is not considered emphasis
const isFirstSentence = (node, name, index) => node.type === "sentence" && index === 0;
const isLastChildAutolink = (node, name, index) => isAutolink$1(node.children[index - 1], options);
if (escapedValue !== node.value && (path.match(undefined, isFirstSentence, isLastChildAutolink) || path.match(undefined, isFirstSentence, (node, name, index) => node.type === "emphasis" && index === 0, isLastChildAutolink))) {
// backslash is parsed as part of autolinks, so we need to remove it
escapedValue = escapedValue.replace(/^(\\?[*_])+/, prefix => prefix.replace(/\\/g, ""));
}
return escapedValue;
}
case "whitespace":
{
const parentNode = path.getParentNode();
const index = parentNode.children.indexOf(node);
const nextNode = parentNode.children[index + 1];
const proseWrap = // leading char that may cause different syntax
nextNode && /^>|^([*+-]|#{1,6}|\d+[).])$/.test(nextNode.value) ? "never" : options.proseWrap;
return printLine(path, node.value, {
proseWrap
});
}
case "emphasis":
{
let style;
if (isAutolink$1(node.children[0], options)) {
style = options.originalText[node.position.start.offset];
} else {
const parentNode = path.getParentNode();
const index = parentNode.children.indexOf(node);
const prevNode = parentNode.children[index - 1];
const nextNode = parentNode.children[index + 1];
const hasPrevOrNextWord = // `1*2*3` is considered emphasis but `1_2_3` is not
prevNode && prevNode.type === "sentence" && prevNode.children.length > 0 && getLast$7(prevNode.children).type === "word" && !getLast$7(prevNode.children).hasTrailingPunctuation || nextNode && nextNode.type === "sentence" && nextNode.children.length > 0 && nextNode.children[0].type === "word" && !nextNode.children[0].hasLeadingPunctuation;
style = hasPrevOrNextWord || getAncestorNode$2(path, "emphasis") ? "*" : "_";
}
return concat$j([style, printChildren$1(path, options, print), style]);
}
case "strong":
return concat$j(["**", printChildren$1(path, options, print), "**"]);
case "delete":
return concat$j(["~~", printChildren$1(path, options, print), "~~"]);
case "inlineCode":
{
const backtickCount = getMinNotPresentContinuousCount$1(node.value, "`");
const style = "`".repeat(backtickCount || 1);
const gap = backtickCount && !/^\s/.test(node.value) ? " " : "";
return concat$j([style, gap, node.value, gap, style]);
}
case "link":
switch (options.originalText[node.position.start.offset]) {
case "<":
{
const mailto = "mailto:";
const url = //
is parsed as { url: "mailto:hello@example.com" }
node.url.startsWith(mailto) && options.originalText.slice(node.position.start.offset + 1, node.position.start.offset + 1 + mailto.length) !== mailto ? node.url.slice(mailto.length) : node.url;
return concat$j(["<", url, ">"]);
}
case "[":
return concat$j(["[", printChildren$1(path, options, print), "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]);
default:
return options.originalText.slice(node.position.start.offset, node.position.end.offset);
}
case "image":
return concat$j(["![", node.alt || "", "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]);
case "blockquote":
return concat$j(["> ", align$3("> ", printChildren$1(path, options, print))]);
case "heading":
return concat$j(["#".repeat(node.depth) + " ", printChildren$1(path, options, print)]);
case "code":
{
if (node.isIndented) {
// indented code block
const alignment = " ".repeat(4);
return align$3(alignment, concat$j([alignment, concat$j(replaceEndOfLineWith$1(node.value, hardline$e))]));
} // fenced code block
const styleUnit = options.__inJsTemplate ? "~" : "`";
const style = styleUnit.repeat(Math.max(3, getMaxContinuousCount$3(node.value, styleUnit) + 1));
return concat$j([style, node.lang || "", node.meta ? " " + node.meta : "", hardline$e, concat$j(replaceEndOfLineWith$1(getFencedCodeBlockValue$2(node, options.originalText), hardline$e)), hardline$e, style]);
}
case "html":
{
const parentNode = path.getParentNode();
const value = parentNode.type === "root" && getLast$7(parentNode.children) === node ? node.value.trimEnd() : node.value;
const isHtmlComment = /^$/.test(value);
return concat$j(replaceEndOfLineWith$1(value, isHtmlComment ? hardline$e : markAsRoot$3(literalline$4)));
}
case "list":
{
const nthSiblingIndex = getNthListSiblingIndex(node, path.getParentNode());
const isGitDiffFriendlyOrderedList = hasGitDiffFriendlyOrderedList$1(node, options);
return printChildren$1(path, options, print, {
processor: (childPath, index) => {
const prefix = getPrefix();
const childNode = childPath.getValue();
if (childNode.children.length === 2 && childNode.children[1].type === "html" && childNode.children[0].position.start.column !== childNode.children[1].position.start.column) {
return concat$j([prefix, printListItem(childPath, options, print, prefix)]);
}
return concat$j([prefix, align$3(" ".repeat(prefix.length), printListItem(childPath, options, print, prefix))]);
function getPrefix() {
const rawPrefix = node.ordered ? (index === 0 ? node.start : isGitDiffFriendlyOrderedList ? 1 : node.start + index) + (nthSiblingIndex % 2 === 0 ? ". " : ") ") : nthSiblingIndex % 2 === 0 ? "- " : "* ";
return node.isAligned ||
/* workaround for https://github.com/remarkjs/remark/issues/315 */
node.hasIndentedCodeblock ? alignListPrefix(rawPrefix, options) : rawPrefix;
}
}
});
}
case "thematicBreak":
{
const counter = getAncestorCounter$1(path, "list");
if (counter === -1) {
return "---";
}
const nthSiblingIndex = getNthListSiblingIndex(path.getParentNode(counter), path.getParentNode(counter + 1));
return nthSiblingIndex % 2 === 0 ? "***" : "---";
}
case "linkReference":
return concat$j(["[", printChildren$1(path, options, print), "]", node.referenceType === "full" ? concat$j(["[", node.identifier, "]"]) : node.referenceType === "collapsed" ? "[]" : ""]);
case "imageReference":
switch (node.referenceType) {
case "full":
return concat$j(["![", node.alt || "", "][", node.identifier, "]"]);
default:
return concat$j(["![", node.alt, "]", node.referenceType === "collapsed" ? "[]" : ""]);
}
case "definition":
{
const lineOrSpace = options.proseWrap === "always" ? line$c : " ";
return group$i(concat$j([concat$j(["[", node.identifier, "]:"]), indent$d(concat$j([lineOrSpace, printUrl(node.url), node.title === null ? "" : concat$j([lineOrSpace, printTitle(node.title, options, false)])]))]));
}
// `footnote` requires `.use(footnotes, {inlineNotes: true})`, we are not using this option
// https://github.com/remarkjs/remark-footnotes#optionsinlinenotes
/* istanbul ignore next */
case "footnote":
return concat$j(["[^", printChildren$1(path, options, print), "]"]);
case "footnoteReference":
return concat$j(["[^", node.identifier, "]"]);
case "footnoteDefinition":
{
const nextNode = path.getParentNode().children[path.getName() + 1];
const shouldInlineFootnote = node.children.length === 1 && node.children[0].type === "paragraph" && (options.proseWrap === "never" || options.proseWrap === "preserve" && node.children[0].position.start.line === node.children[0].position.end.line);
return concat$j(["[^", node.identifier, "]: ", shouldInlineFootnote ? printChildren$1(path, options, print) : group$i(concat$j([align$3(" ".repeat(4), printChildren$1(path, options, print, {
processor: (childPath, index) => {
return index === 0 ? group$i(concat$j([softline$a, childPath.call(print)])) : childPath.call(print);
}
})), nextNode && nextNode.type === "footnoteDefinition" ? softline$a : ""]))]);
}
case "table":
return printTable(path, options, print);
case "tableCell":
return printChildren$1(path, options, print);
case "break":
return /\s/.test(options.originalText[node.position.start.offset]) ? concat$j([" ", markAsRoot$3(literalline$4)]) : concat$j(["\\", hardline$e]);
case "liquidNode":
return concat$j(replaceEndOfLineWith$1(node.value, hardline$e));
// MDX
case "importExport":
case "jsx":
// fallback to the original text if multiparser failed
// or `embeddedLanguageFormatting: "off"`
return concat$j([node.value, hardline$e]);
case "math":
return concat$j(["$$", hardline$e, node.value ? concat$j([concat$j(replaceEndOfLineWith$1(node.value, hardline$e)), hardline$e]) : "", "$$"]);
case "inlineMath":
{
// remark-math trims content but we don't want to remove whitespaces
// since it's very possible that it's recognized as math accidentally
return options.originalText.slice(options.locStart(node), options.locEnd(node));
}
case "tableRow": // handled in "table"
case "listItem": // handled in "list"
default:
/* istanbul ignore next */
throw new Error(`Unknown markdown type ${JSON.stringify(node.type)}`);
}
}
function printListItem(path, options, print, listPrefix) {
const node = path.getValue();
const prefix = node.checked === null ? "" : node.checked ? "[x] " : "[ ] ";
return concat$j([prefix, printChildren$1(path, options, print, {
processor: (childPath, index) => {
if (index === 0 && childPath.getValue().type !== "list") {
return align$3(" ".repeat(prefix.length), childPath.call(print));
}
const alignment = " ".repeat(clamp(options.tabWidth - listPrefix.length, 0, 3) // 4+ will cause indented code block
);
return concat$j([alignment, align$3(alignment, childPath.call(print))]);
}
})]);
}
function alignListPrefix(prefix, options) {
const additionalSpaces = getAdditionalSpaces();
return prefix + " ".repeat(additionalSpaces >= 4 ? 0 : additionalSpaces // 4+ will cause indented code block
);
function getAdditionalSpaces() {
const restSpaces = prefix.length % options.tabWidth;
return restSpaces === 0 ? 0 : options.tabWidth - restSpaces;
}
}
function getNthListSiblingIndex(node, parentNode) {
return getNthSiblingIndex(node, parentNode, siblingNode => siblingNode.ordered === node.ordered);
}
function getNthSiblingIndex(node, parentNode, condition) {
condition = condition || (() => true);
let index = -1;
for (const childNode of parentNode.children) {
if (childNode.type === node.type && condition(childNode)) {
index++;
} else {
index = -1;
}
if (childNode === node) {
return index;
}
}
}
function getAncestorCounter$1(path, typeOrTypes) {
const types = [].concat(typeOrTypes);
let counter = -1;
let ancestorNode;
while (ancestorNode = path.getParentNode(++counter)) {
if (types.includes(ancestorNode.type)) {
return counter;
}
}
return -1;
}
function getAncestorNode$2(path, typeOrTypes) {
const 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$e;
}
const isBreakable = options.proseWrap === "always" && !getAncestorNode$2(path, SINGLE_LINE_NODE_TYPES);
return value !== "" ? isBreakable ? line$c : " " : isBreakable ? softline$a : "";
}
function printTable(path, options, print) {
const hardlineWithoutBreakParent = hardline$e.parts[0];
const node = path.getValue();
const contents = []; // { [rowIndex: number]: { [columnIndex: number]: string } }
path.map(rowPath => {
const rowContents = [];
rowPath.map(cellPath => {
rowContents.push(printDocToString$3(cellPath.call(print), options).formatted);
}, "children");
contents.push(rowContents);
}, "children"); // Get the width of each column
const columnMaxWidths = contents.reduce((currentWidths, rowContents) => currentWidths.map((width, columnIndex) => Math.max(width, getStringWidth$4(rowContents[columnIndex]))), contents[0].map(() => 3) // minimum width = 3 (---, :--, :-:, --:)
);
const alignedTable = join$b(hardlineWithoutBreakParent, [printRow(contents[0]), printSeparator(), join$b(hardlineWithoutBreakParent, contents.slice(1).map(rowContents => printRow(rowContents)))]);
if (options.proseWrap !== "never") {
return concat$j([breakParent$6, alignedTable]);
} // Only if the --prose-wrap never is set and it exceeds the print width.
const compactTable = join$b(hardlineWithoutBreakParent, [printRow(contents[0],
/* isCompact */
true), printSeparator(
/* isCompact */
true), join$b(hardlineWithoutBreakParent, contents.slice(1).map(rowContents => printRow(rowContents,
/* isCompact */
true)))]);
return concat$j([breakParent$6, group$i(ifBreak$8(compactTable, alignedTable))]);
function printSeparator(isCompact) {
return concat$j(["| ", join$b(" | ", columnMaxWidths.map((width, index) => {
const spaces = isCompact ? 3 : width;
switch (node.align[index]) {
case "left":
return ":" + "-".repeat(spaces - 1);
case "right":
return "-".repeat(spaces - 1) + ":";
case "center":
return ":" + "-".repeat(spaces - 2) + ":";
default:
return "-".repeat(spaces);
}
})), " |"]);
}
function printRow(rowContents, isCompact) {
return concat$j(["| ", join$b(" | ", isCompact ? rowContents : rowContents.map((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) {
const spaces = width - getStringWidth$4(text);
return concat$j([text, " ".repeat(spaces)]);
}
function alignRight(text, width) {
const spaces = width - getStringWidth$4(text);
return concat$j([" ".repeat(spaces), text]);
}
function alignCenter(text, width) {
const spaces = width - getStringWidth$4(text);
const left = Math.floor(spaces / 2);
const right = spaces - left;
return concat$j([" ".repeat(left), text, " ".repeat(right)]);
}
}
function printRoot(path, options, print) {
/** @typedef {{ index: number, offset: number }} IgnorePosition */
/** @type {Array<{start: IgnorePosition, end: IgnorePosition}>} */
const ignoreRanges = [];
/** @type {IgnorePosition | null} */
let ignoreStart = null;
const {
children
} = path.getValue();
children.forEach((childNode, index) => {
switch (isPrettierIgnore(childNode)) {
case "start":
if (ignoreStart === null) {
ignoreStart = {
index,
offset: childNode.position.end.offset
};
}
break;
case "end":
if (ignoreStart !== null) {
ignoreRanges.push({
start: ignoreStart,
end: {
index,
offset: childNode.position.start.offset
}
});
ignoreStart = null;
}
break;
}
});
return printChildren$1(path, options, print, {
processor: (childPath, index) => {
if (ignoreRanges.length !== 0) {
const ignoreRange = ignoreRanges[0];
if (index === ignoreRange.start.index) {
return concat$j([children[ignoreRange.start.index].value, options.originalText.slice(ignoreRange.start.offset, ignoreRange.end.offset), children[ignoreRange.end.index].value]);
}
if (ignoreRange.start.index < index && index < ignoreRange.end.index) {
return false;
}
if (index === ignoreRange.end.index) {
ignoreRanges.shift();
return false;
}
}
return childPath.call(print);
}
});
}
function printChildren$1(path, options, print, events) {
events = events || {};
const postprocessor = events.postprocessor || concat$j;
const processor = events.processor || (childPath => childPath.call(print));
const node = path.getValue();
const parts = [];
let lastChildNode;
path.map((childPath, index) => {
const childNode = childPath.getValue();
const result = processor(childPath, index);
if (result !== false) {
const data = {
parts,
prevNode: lastChildNode,
parentNode: node,
options
};
if (!shouldNotPrePrintHardline(childNode, data)) {
parts.push(hardline$e); // Can't find a case to pass `shouldPrePrintTripleHardline`
/* istanbul ignore next */
if (lastChildNode && TRAILING_HARDLINE_NODES.has(lastChildNode.type)) {
if (shouldPrePrintTripleHardline(childNode, data)) {
parts.push(hardline$e);
}
} else {
if (shouldPrePrintDoubleHardline(childNode, data) || shouldPrePrintTripleHardline(childNode, data)) {
parts.push(hardline$e);
}
if (shouldPrePrintTripleHardline(childNode, data)) {
parts.push(hardline$e);
}
}
}
parts.push(result);
lastChildNode = childNode;
}
}, "children");
return postprocessor(parts);
}
function getLastDescendantNode(node) {
let current = node;
while (current.children && current.children.length !== 0) {
current = current.children[current.children.length - 1];
}
return current;
}
/** @return {false | 'next' | 'start' | 'end'} */
function isPrettierIgnore(node) {
if (node.type !== "html") {
return false;
}
const match = node.value.match(/^$/);
return match === null ? false : match[1] ? match[1] : "next";
}
function shouldNotPrePrintHardline(node, data) {
const isFirstNode = data.parts.length === 0;
const isInlineNode = INLINE_NODE_TYPES$1.includes(node.type);
const isInlineHTML = node.type === "html" && INLINE_NODE_WRAPPER_TYPES$1.includes(data.parentNode.type);
return isFirstNode || isInlineNode || isInlineHTML;
}
function shouldPrePrintDoubleHardline(node, data) {
const isSequence = (data.prevNode && data.prevNode.type) === node.type;
const isSiblingNode = isSequence && SIBLING_NODE_TYPES.has(node.type);
const isInTightListItem = data.parentNode.type === "listItem" && !data.parentNode.loose;
const isPrevNodeLooseListItem = data.prevNode && data.prevNode.type === "listItem" && data.prevNode.loose;
const isPrevNodePrettierIgnore = isPrettierIgnore(data.prevNode) === "next";
const isBlockHtmlWithoutBlankLineBetweenPrevHtml = node.type === "html" && data.prevNode && data.prevNode.type === "html" && data.prevNode.position.end.line + 1 === node.position.start.line;
const isHtmlDirectAfterListItem = node.type === "html" && data.parentNode.type === "listItem" && data.prevNode && data.prevNode.type === "paragraph" && data.prevNode.position.end.line + 1 === node.position.start.line;
return isPrevNodeLooseListItem || !(isSiblingNode || isInTightListItem || isPrevNodePrettierIgnore || isBlockHtmlWithoutBlankLineBetweenPrevHtml || isHtmlDirectAfterListItem);
}
function shouldPrePrintTripleHardline(node, data) {
const isPrevNodeList = data.prevNode && data.prevNode.type === "list";
const isIndentedCode = node.type === "code" && node.isIndented;
return isPrevNodeList && isIndentedCode;
}
function shouldRemainTheSameContent(path) {
const ancestorNode = getAncestorNode$2(path, ["linkReference", "imageReference"]);
return ancestorNode && (ancestorNode.type !== "linkReference" || ancestorNode.referenceType !== "full");
}
function printUrl(url, dangerousCharOrChars) {
const dangerousChars = [" "].concat(dangerousCharOrChars || []);
return new RegExp(dangerousChars.map(x => `\\${x}`).join("|")).test(url) ? `<${url}>` : url;
}
function printTitle(title, options, printSpace) {
if (printSpace == null) {
printSpace = true;
}
if (!title) {
return "";
}
if (printSpace) {
return " " + printTitle(title, options, false);
} // title is escaped after `remark-parse` v7
title = title.replace(/\\(["')])/g, "$1");
if (title.includes('"') && title.includes("'") && !title.includes(")")) {
return `(${title})`; // avoid escaped quotes
} // faster than using RegExps: https://jsperf.com/performance-of-match-vs-split
const singleCount = title.split("'").length - 1;
const doubleCount = title.split('"').length - 1;
const quote = singleCount > doubleCount ? '"' : doubleCount > singleCount ? "'" : options.singleQuote ? "'" : '"';
title = title.replace(/\\/, "\\\\");
title = title.replace(new RegExp(`(${quote})`, "g"), "\\$1");
return `${quote}${title}${quote}`;
}
function clamp(value, min, max) {
return value < min ? min : value > max ? max : value;
}
function clean$5(ast, newObj, parent) {
delete newObj.position;
delete newObj.raw; // front-matter
// for codeblock
if (ast.type === "front-matter" || ast.type === "code" || ast.type === "yaml" || ast.type === "import" || ast.type === "export" || ast.type === "jsx") {
delete newObj.value;
}
if (ast.type === "list") {
delete newObj.isAligned;
}
if (ast.type === "list" || ast.type === "listItem") {
delete newObj.spread;
delete newObj.loose;
} // texts can be splitted or merged
if (ast.type === "text") {
return null;
}
if (ast.type === "inlineCode") {
newObj.value = ast.value.replace(/[\t\n ]+/g, " ");
}
if (ast.type === "definition" || ast.type === "linkReference") {
newObj.label = ast.label.trim().replace(/[\t\n ]+/g, " ").toLowerCase();
}
if ((ast.type === "definition" || ast.type === "link" || ast.type === "image") && ast.title) {
newObj.title = ast.title.replace(/\\(["')])/g, "$1");
} // for insert pragma
if (parent && parent.type === "root" && parent.children.length > 0 && (parent.children[0] === ast || isFrontMatterNode$3(parent.children[0]) && parent.children[1] === ast) && ast.type === "html" && pragma$3.startWithPragma(ast.value)) {
return null;
}
}
function hasPrettierIgnore$4(path) {
const index = +path.getName();
if (index === 0) {
return false;
}
const prevNode = path.getParentNode().children[index - 1];
return isPrettierIgnore(prevNode) === "next";
}
var printerMarkdown = {
preprocess: preprocess_1$1,
print: genericPrint$4,
embed: embed_1$2,
massageAstNode: clean$5,
hasPrettierIgnore: hasPrettierIgnore$4,
insertPragma: pragma$3.insertPragma
};
var options$5 = {
proseWrap: commonOptions.proseWrap,
singleQuote: commonOptions.singleQuote
};
var name$f = "Markdown";
var type$d = "prose";
var aliases$4 = [
"pandoc"
];
var aceMode$d = "markdown";
var codemirrorMode$a = "gfm";
var codemirrorMimeType$a = "text/x-gfm";
var wrap = true;
var extensions$d = [
".md",
".markdown",
".mdown",
".mdwn",
".mdx",
".mkd",
".mkdn",
".mkdown",
".ronn",
".workbook"
];
var filenames$3 = [
"contents.lr"
];
var tmScope$d = "source.gfm";
var languageId$d = 222;
var Markdown = {
name: name$f,
type: type$d,
aliases: aliases$4,
aceMode: aceMode$d,
codemirrorMode: codemirrorMode$a,
codemirrorMimeType: codemirrorMimeType$a,
wrap: wrap,
extensions: extensions$d,
filenames: filenames$3,
tmScope: tmScope$d,
languageId: languageId$d
};
var Markdown$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
name: name$f,
type: type$d,
aliases: aliases$4,
aceMode: aceMode$d,
codemirrorMode: codemirrorMode$a,
codemirrorMimeType: codemirrorMimeType$a,
wrap: wrap,
extensions: extensions$d,
filenames: filenames$3,
tmScope: tmScope$d,
languageId: languageId$d,
'default': Markdown
});
var require$$0$6 = getCjsExportFromNamespace(Markdown$1);
const languages$4 = [createLanguage(require$$0$6, data => ({
since: "1.8.0",
parsers: ["markdown"],
vscodeLanguageIds: ["markdown"],
filenames: data.filenames.concat(["README"]),
extensions: data.extensions.filter(extension => extension !== ".mdx")
})), createLanguage(require$$0$6, () => ({
name: "MDX",
since: "1.15.0",
parsers: ["mdx"],
vscodeLanguageIds: ["mdx"],
filenames: [],
extensions: [".mdx"]
}))];
const printers$4 = {
mdast: printerMarkdown
};
const parsers$4 = {
/* istanbul ignore next */
get remark() {
return require("./parser-markdown").parsers.remark;
},
get markdown() {
return require("./parser-markdown").parsers.remark;
},
get mdx() {
return require("./parser-markdown").parsers.mdx;
}
};
var languageMarkdown = {
languages: languages$4,
options: options$5,
printers: printers$4,
parsers: parsers$4
};
const {
isFrontMatterNode: isFrontMatterNode$4
} = util;
var clean$6 = function (ast, newNode) {
delete newNode.sourceSpan;
delete newNode.startSourceSpan;
delete newNode.endSourceSpan;
delete newNode.nameSpan;
delete newNode.valueSpan;
if (ast.type === "text" || ast.type === "comment") {
return null;
} // may be formatted by multiparser
if (isFrontMatterNode$4(ast) || ast.type === "yaml" || ast.type === "toml") {
return null;
}
if (ast.type === "attribute") {
delete newNode.value;
}
if (ast.type === "docType") {
delete newNode.value;
}
};
var index$1 = [
"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 = /*#__PURE__*/Object.freeze({
__proto__: null,
'default': index$1
});
var a = [
"accesskey",
"charset",
"coords",
"download",
"href",
"hreflang",
"name",
"ping",
"referrerpolicy",
"rel",
"rev",
"shape",
"tabindex",
"target",
"type"
];
var abbr = [
"title"
];
var applet = [
"align",
"alt",
"archive",
"code",
"codebase",
"height",
"hspace",
"name",
"object",
"vspace",
"width"
];
var area = [
"accesskey",
"alt",
"coords",
"download",
"href",
"hreflang",
"nohref",
"ping",
"referrerpolicy",
"rel",
"shape",
"tabindex",
"target",
"type"
];
var audio = [
"autoplay",
"controls",
"crossorigin",
"loop",
"muted",
"preload",
"src"
];
var base = [
"href",
"target"
];
var basefont = [
"color",
"face",
"size"
];
var bdo = [
"dir"
];
var blockquote = [
"cite"
];
var body = [
"alink",
"background",
"bgcolor",
"link",
"text",
"vlink"
];
var br = [
"clear"
];
var button = [
"accesskey",
"autofocus",
"disabled",
"form",
"formaction",
"formenctype",
"formmethod",
"formnovalidate",
"formtarget",
"name",
"tabindex",
"type",
"value"
];
var canvas = [
"height",
"width"
];
var caption = [
"align"
];
var col = [
"align",
"char",
"charoff",
"span",
"valign",
"width"
];
var colgroup = [
"align",
"char",
"charoff",
"span",
"valign",
"width"
];
var data$1 = [
"value"
];
var del$1 = [
"cite",
"datetime"
];
var details = [
"open"
];
var dfn = [
"title"
];
var dialog = [
"open"
];
var dir = [
"compact"
];
var div = [
"align"
];
var dl = [
"compact"
];
var embed$3 = [
"height",
"src",
"type",
"width"
];
var fieldset = [
"disabled",
"form",
"name"
];
var font = [
"color",
"face",
"size"
];
var form = [
"accept",
"accept-charset",
"action",
"autocomplete",
"enctype",
"method",
"name",
"novalidate",
"target"
];
var frame = [
"frameborder",
"longdesc",
"marginheight",
"marginwidth",
"name",
"noresize",
"scrolling",
"src"
];
var frameset = [
"cols",
"rows"
];
var h1 = [
"align"
];
var h2 = [
"align"
];
var h3 = [
"align"
];
var h4 = [
"align"
];
var h5 = [
"align"
];
var h6 = [
"align"
];
var head = [
"profile"
];
var hr = [
"align",
"noshade",
"size",
"width"
];
var html = [
"manifest",
"version"
];
var iframe = [
"align",
"allow",
"allowfullscreen",
"allowpaymentrequest",
"allowusermedia",
"frameborder",
"height",
"longdesc",
"marginheight",
"marginwidth",
"name",
"referrerpolicy",
"sandbox",
"scrolling",
"src",
"srcdoc",
"width"
];
var img = [
"align",
"alt",
"border",
"crossorigin",
"decoding",
"height",
"hspace",
"ismap",
"longdesc",
"name",
"referrerpolicy",
"sizes",
"src",
"srcset",
"usemap",
"vspace",
"width"
];
var input = [
"accept",
"accesskey",
"align",
"alt",
"autocomplete",
"autofocus",
"checked",
"dirname",
"disabled",
"form",
"formaction",
"formenctype",
"formmethod",
"formnovalidate",
"formtarget",
"height",
"ismap",
"list",
"max",
"maxlength",
"min",
"minlength",
"multiple",
"name",
"pattern",
"placeholder",
"readonly",
"required",
"size",
"src",
"step",
"tabindex",
"title",
"type",
"usemap",
"value",
"width"
];
var ins = [
"cite",
"datetime"
];
var isindex = [
"prompt"
];
var label = [
"accesskey",
"for",
"form"
];
var legend = [
"accesskey",
"align"
];
var li = [
"type",
"value"
];
var link$3 = [
"as",
"charset",
"color",
"crossorigin",
"href",
"hreflang",
"imagesizes",
"imagesrcset",
"integrity",
"media",
"nonce",
"referrerpolicy",
"rel",
"rev",
"sizes",
"target",
"title",
"type"
];
var map$1 = [
"name"
];
var menu = [
"compact"
];
var meta = [
"charset",
"content",
"http-equiv",
"name",
"scheme"
];
var meter = [
"high",
"low",
"max",
"min",
"optimum",
"value"
];
var object = [
"align",
"archive",
"border",
"classid",
"codebase",
"codetype",
"data",
"declare",
"form",
"height",
"hspace",
"name",
"standby",
"tabindex",
"type",
"typemustmatch",
"usemap",
"vspace",
"width"
];
var ol = [
"compact",
"reversed",
"start",
"type"
];
var optgroup = [
"disabled",
"label"
];
var option = [
"disabled",
"label",
"selected",
"value"
];
var output = [
"for",
"form",
"name"
];
var p = [
"align"
];
var param = [
"name",
"type",
"value",
"valuetype"
];
var pre = [
"width"
];
var progress = [
"max",
"value"
];
var q = [
"cite"
];
var script = [
"async",
"charset",
"crossorigin",
"defer",
"integrity",
"language",
"nomodule",
"nonce",
"referrerpolicy",
"src",
"type"
];
var select = [
"autocomplete",
"autofocus",
"disabled",
"form",
"multiple",
"name",
"required",
"size",
"tabindex"
];
var slot = [
"name"
];
var source$2 = [
"media",
"sizes",
"src",
"srcset",
"type"
];
var style = [
"media",
"nonce",
"title",
"type"
];
var table = [
"align",
"bgcolor",
"border",
"cellpadding",
"cellspacing",
"frame",
"rules",
"summary",
"width"
];
var tbody = [
"align",
"char",
"charoff",
"valign"
];
var td = [
"abbr",
"align",
"axis",
"bgcolor",
"char",
"charoff",
"colspan",
"headers",
"height",
"nowrap",
"rowspan",
"scope",
"valign",
"width"
];
var textarea = [
"accesskey",
"autocomplete",
"autofocus",
"cols",
"dirname",
"disabled",
"form",
"maxlength",
"minlength",
"name",
"placeholder",
"readonly",
"required",
"rows",
"tabindex",
"wrap"
];
var tfoot = [
"align",
"char",
"charoff",
"valign"
];
var th = [
"abbr",
"align",
"axis",
"bgcolor",
"char",
"charoff",
"colspan",
"headers",
"height",
"nowrap",
"rowspan",
"scope",
"valign",
"width"
];
var thead = [
"align",
"char",
"charoff",
"valign"
];
var time = [
"datetime"
];
var tr = [
"align",
"bgcolor",
"char",
"charoff",
"valign"
];
var track = [
"default",
"kind",
"label",
"src",
"srclang"
];
var ul = [
"compact",
"type"
];
var video = [
"autoplay",
"controls",
"crossorigin",
"height",
"loop",
"muted",
"playsinline",
"poster",
"preload",
"src",
"width"
];
var index$2 = {
"*": [
"accesskey",
"autocapitalize",
"autofocus",
"class",
"contenteditable",
"dir",
"draggable",
"enterkeyhint",
"hidden",
"id",
"inputmode",
"is",
"itemid",
"itemprop",
"itemref",
"itemscope",
"itemtype",
"lang",
"nonce",
"slot",
"spellcheck",
"style",
"tabindex",
"title",
"translate"
],
a: a,
abbr: abbr,
applet: applet,
area: area,
audio: audio,
base: base,
basefont: basefont,
bdo: bdo,
blockquote: blockquote,
body: body,
br: br,
button: button,
canvas: canvas,
caption: caption,
col: col,
colgroup: colgroup,
data: data$1,
del: del$1,
details: details,
dfn: dfn,
dialog: dialog,
dir: dir,
div: div,
dl: dl,
embed: embed$3,
fieldset: fieldset,
font: font,
form: form,
frame: frame,
frameset: frameset,
h1: h1,
h2: h2,
h3: h3,
h4: h4,
h5: h5,
h6: h6,
head: head,
hr: hr,
html: html,
iframe: iframe,
img: img,
input: input,
ins: ins,
isindex: isindex,
label: label,
legend: legend,
li: li,
link: link$3,
map: map$1,
menu: menu,
meta: meta,
meter: meter,
object: object,
ol: ol,
optgroup: optgroup,
option: option,
output: output,
p: p,
param: param,
pre: pre,
progress: progress,
q: q,
script: script,
select: select,
slot: slot,
source: source$2,
style: style,
table: table,
tbody: tbody,
td: td,
textarea: textarea,
tfoot: tfoot,
th: th,
thead: thead,
time: time,
tr: tr,
track: track,
ul: ul,
video: video
};
var htmlElementAttributes = /*#__PURE__*/Object.freeze({
__proto__: null,
a: a,
abbr: abbr,
applet: applet,
area: area,
audio: audio,
base: base,
basefont: basefont,
bdo: bdo,
blockquote: blockquote,
body: body,
br: br,
button: button,
canvas: canvas,
caption: caption,
col: col,
colgroup: colgroup,
data: data$1,
del: del$1,
details: details,
dfn: dfn,
dialog: dialog,
dir: dir,
div: div,
dl: dl,
embed: embed$3,
fieldset: fieldset,
font: font,
form: form,
frame: frame,
frameset: frameset,
h1: h1,
h2: h2,
h3: h3,
h4: h4,
h5: h5,
h6: h6,
head: head,
hr: hr,
html: html,
iframe: iframe,
img: img,
input: input,
ins: ins,
isindex: isindex,
label: label,
legend: legend,
li: li,
link: link$3,
map: map$1,
menu: menu,
meta: meta,
meter: meter,
object: object,
ol: ol,
optgroup: optgroup,
option: option,
output: output,
p: p,
param: param,
pre: pre,
progress: progress,
q: q,
script: script,
select: select,
slot: slot,
source: source$2,
style: style,
table: table,
tbody: tbody,
td: td,
textarea: textarea,
tfoot: tfoot,
th: th,
thead: thead,
time: time,
tr: tr,
track: track,
ul: ul,
video: video,
'default': index$2
});
var json$1 = {
"CSS_DISPLAY_TAGS": {
"area": "none",
"base": "none",
"basefont": "none",
"datalist": "none",
"head": "none",
"link": "none",
"meta": "none",
"noembed": "none",
"noframes": "none",
"param": "block",
"rp": "none",
"script": "block",
"source": "block",
"style": "none",
"template": "inline",
"track": "block",
"title": "none",
"html": "block",
"body": "block",
"address": "block",
"blockquote": "block",
"center": "block",
"div": "block",
"figure": "block",
"figcaption": "block",
"footer": "block",
"form": "block",
"header": "block",
"hr": "block",
"legend": "block",
"listing": "block",
"main": "block",
"p": "block",
"plaintext": "block",
"pre": "block",
"xmp": "block",
"slot": "contents",
"ruby": "ruby",
"rt": "ruby-text",
"article": "block",
"aside": "block",
"h1": "block",
"h2": "block",
"h3": "block",
"h4": "block",
"h5": "block",
"h6": "block",
"hgroup": "block",
"nav": "block",
"section": "block",
"dir": "block",
"dd": "block",
"dl": "block",
"dt": "block",
"ol": "block",
"ul": "block",
"li": "list-item",
"table": "table",
"caption": "table-caption",
"colgroup": "table-column-group",
"col": "table-column",
"thead": "table-header-group",
"tbody": "table-row-group",
"tfoot": "table-footer-group",
"tr": "table-row",
"td": "table-cell",
"th": "table-cell",
"fieldset": "block",
"button": "inline-block",
"details": "block",
"summary": "block",
"dialog": "block",
"meter": "inline-block",
"progress": "inline-block",
"object": "inline-block",
"video": "inline-block",
"audio": "inline-block",
"select": "inline-block",
"option": "block",
"optgroup": "block"
},
"CSS_DISPLAY_DEFAULT": "inline",
"CSS_WHITE_SPACE_TAGS": {
"listing": "pre",
"plaintext": "pre",
"pre": "pre",
"xmp": "pre",
"nobr": "nowrap",
"table": "initial",
"textarea": "pre-wrap"
},
"CSS_WHITE_SPACE_DEFAULT": "normal"
};
var htmlTagNames$1 = getCjsExportFromNamespace(htmlTagNames);
var htmlElementAttributes$1 = getCjsExportFromNamespace(htmlElementAttributes);
const {
getParserName: getParserName$2,
isFrontMatterNode: isFrontMatterNode$5
} = util;
const {
CSS_DISPLAY_TAGS,
CSS_DISPLAY_DEFAULT,
CSS_WHITE_SPACE_TAGS,
CSS_WHITE_SPACE_DEFAULT
} = json$1;
const HTML_TAGS = arrayToMap(htmlTagNames$1);
const HTML_ELEMENT_ATTRIBUTES = mapObject(htmlElementAttributes$1, arrayToMap); // https://infra.spec.whatwg.org/#ascii-whitespace
const HTML_WHITESPACE = new Set(["\t", "\n", "\f", "\r", " "]);
const htmlTrimStart = string => string.replace(/^[\t\n\f\r ]+/, "");
const htmlTrimEnd = string => string.replace(/[\t\n\f\r ]+$/, "");
const htmlTrim = string => htmlTrimStart(htmlTrimEnd(string));
const htmlTrimLeadingBlankLines = string => string.replace(/^[\t\f\r ]*?\n/g, "");
const htmlTrimPreserveIndentation = string => htmlTrimLeadingBlankLines(htmlTrimEnd(string));
const splitByHtmlWhitespace = string => string.split(/[\t\n\f\r ]+/);
const getLeadingHtmlWhitespace = string => string.match(/^[\t\n\f\r ]*/)[0];
const getLeadingAndTrailingHtmlWhitespace = string => {
const [, leadingWhitespace, text, trailingWhitespace] = string.match(/^([\t\n\f\r ]*)([\S\s]*?)([\t\n\f\r ]*)$/);
return {
leadingWhitespace,
trailingWhitespace,
text
};
};
const hasHtmlWhitespace = string => /[\t\n\f\r ]/.test(string);
function arrayToMap(array) {
const map = Object.create(null);
for (const value of array) {
map[value] = true;
}
return map;
}
function mapObject(object, fn) {
const newObject = Object.create(null);
for (const key of Object.keys(object)) {
newObject[key] = fn(object[key], key);
}
return newObject;
}
function shouldPreserveContent(node, options) {
// unterminated node in ie conditional comment
// e.g.
if (node.type === "ieConditionalComment" && node.lastChild && !node.lastChild.isSelfClosing && !node.lastChild.endSourceSpan) {
return true;
} // incomplete html in ie conditional comment
// e.g.
if (node.type === "ieConditionalComment" && !node.complete) {
return true;
} // TODO: handle non-text children in
if (isPreLikeNode(node) && node.children.some(child => child.type !== "text" && child.type !== "interpolation")) {
return true;
}
if (isVueNonHtmlBlock(node, options) && !isScriptLikeTag(node) && node.type !== "interpolation") {
return true;
}
return false;
}
function hasPrettierIgnore$5(node) {
/* istanbul ignore next */
if (node.type === "attribute") {
return false;
}
/* istanbul ignore next */
if (!node.parent) {
return false;
}
if (typeof node.index !== "number" || node.index === 0) {
return false;
}
const prevNode = node.parent.children[node.index - 1];
return isPrettierIgnore$1(prevNode);
}
function isPrettierIgnore$1(node) {
return node.type === "comment" && node.value.trim() === "prettier-ignore";
}
function getPrettierIgnoreAttributeCommentData(value) {
const match = value.trim().match(/^prettier-ignore-attribute(?:\s+([^]+))?$/);
if (!match) {
return false;
}
if (!match[1]) {
return true;
}
return match[1].split(/\s+/);
}
/** there's no opening/closing tag or it's considered not breakable */
function isTextLikeNode(node) {
return node.type === "text" || node.type === "comment";
}
function isScriptLikeTag(node) {
return node.type === "element" && (node.fullName === "script" || node.fullName === "style" || node.fullName === "svg:style" || isUnknownNamespace(node) && (node.name === "script" || node.name === "style"));
}
function canHaveInterpolation(node) {
return node.children && !isScriptLikeTag(node);
}
function isWhitespaceSensitiveNode(node) {
return isScriptLikeTag(node) || node.type === "interpolation" || isIndentationSensitiveNode(node);
}
function isIndentationSensitiveNode(node) {
return getNodeCssStyleWhiteSpace(node).startsWith("pre");
}
function isLeadingSpaceSensitiveNode(node, options) {
const isLeadingSpaceSensitive = _isLeadingSpaceSensitiveNode();
if (isLeadingSpaceSensitive && !node.prev && node.parent && node.parent.tagDefinition && node.parent.tagDefinition.ignoreFirstLf) {
return node.type === "interpolation";
}
return isLeadingSpaceSensitive;
function _isLeadingSpaceSensitiveNode() {
if (isFrontMatterNode$5(node)) {
return false;
}
if ((node.type === "text" || node.type === "interpolation") && node.prev && (node.prev.type === "text" || node.prev.type === "interpolation")) {
return true;
}
if (!node.parent || node.parent.cssDisplay === "none") {
return false;
}
if (isPreLikeNode(node.parent)) {
return true;
}
if (!node.prev && (node.parent.type === "root" || isPreLikeNode(node) && node.parent || isScriptLikeTag(node.parent) || isVueCustomBlock(node.parent, options) || !isFirstChildLeadingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) {
return false;
}
if (node.prev && !isNextLeadingSpaceSensitiveCssDisplay(node.prev.cssDisplay)) {
return false;
}
return true;
}
}
function isTrailingSpaceSensitiveNode(node, options) {
if (isFrontMatterNode$5(node)) {
return false;
}
if ((node.type === "text" || node.type === "interpolation") && node.next && (node.next.type === "text" || node.next.type === "interpolation")) {
return true;
}
if (!node.parent || node.parent.cssDisplay === "none") {
return false;
}
if (isPreLikeNode(node.parent)) {
return true;
}
if (!node.next && (node.parent.type === "root" || isPreLikeNode(node) && node.parent || isScriptLikeTag(node.parent) || isVueCustomBlock(node.parent, options) || !isLastChildTrailingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) {
return false;
}
if (node.next && !isPrevTrailingSpaceSensitiveCssDisplay(node.next.cssDisplay)) {
return false;
}
return true;
}
function isDanglingSpaceSensitiveNode(node) {
return isDanglingSpaceSensitiveCssDisplay(node.cssDisplay) && !isScriptLikeTag(node);
}
function forceNextEmptyLine(node) {
return isFrontMatterNode$5(node) || node.next && node.sourceSpan.end && node.sourceSpan.end.line + 1 < node.next.sourceSpan.start.line;
}
/** firstChild leadingSpaces and lastChild trailingSpaces */
function forceBreakContent(node) {
return forceBreakChildren(node) || node.type === "element" && node.children.length !== 0 && (["body", "script", "style"].includes(node.name) || node.children.some(child => hasNonTextChild(child))) || node.firstChild && node.firstChild === node.lastChild && node.firstChild.type !== "text" && hasLeadingLineBreak(node.firstChild) && (!node.lastChild.isTrailingSpaceSensitive || hasTrailingLineBreak(node.lastChild));
}
/** spaces between children */
function forceBreakChildren(node) {
return node.type === "element" && node.children.length !== 0 && (["html", "head", "ul", "ol", "select"].includes(node.name) || node.cssDisplay.startsWith("table") && node.cssDisplay !== "table-cell");
}
function preferHardlineAsLeadingSpaces(node) {
return preferHardlineAsSurroundingSpaces(node) || node.prev && preferHardlineAsTrailingSpaces(node.prev) || hasSurroundingLineBreak(node);
}
function preferHardlineAsTrailingSpaces(node) {
return preferHardlineAsSurroundingSpaces(node) || node.type === "element" && node.fullName === "br" || hasSurroundingLineBreak(node);
}
function hasSurroundingLineBreak(node) {
return hasLeadingLineBreak(node) && hasTrailingLineBreak(node);
}
function hasLeadingLineBreak(node) {
return node.hasLeadingSpaces && (node.prev ? node.prev.sourceSpan.end.line < node.sourceSpan.start.line : node.parent.type === "root" || node.parent.startSourceSpan.end.line < node.sourceSpan.start.line);
}
function hasTrailingLineBreak(node) {
return node.hasTrailingSpaces && (node.next ? node.next.sourceSpan.start.line > node.sourceSpan.end.line : node.parent.type === "root" || node.parent.endSourceSpan && node.parent.endSourceSpan.start.line > node.sourceSpan.end.line);
}
function preferHardlineAsSurroundingSpaces(node) {
switch (node.type) {
case "ieConditionalComment":
case "comment":
case "directive":
return true;
case "element":
return ["script", "select"].includes(node.name);
}
return false;
}
function getLastDescendant(node) {
return node.lastChild ? getLastDescendant(node.lastChild) : node;
}
function hasNonTextChild(node) {
return node.children && node.children.some(child => child.type !== "text");
}
function _inferScriptParser(node) {
const {
type,
lang
} = node.attrMap;
if (type === "module" || type === "text/javascript" || type === "text/babel" || type === "application/javascript" || lang === "jsx") {
return "babel";
}
if (type === "application/x-typescript" || lang === "ts" || lang === "tsx") {
return "typescript";
}
if (type === "text/markdown") {
return "markdown";
}
if (type === "text/html") {
return "html";
}
if (type && (type.endsWith("json") || type.endsWith("importmap"))) {
return "json";
}
if (type === "text/x-handlebars-template") {
return "glimmer";
}
}
function inferStyleParser(node) {
const {
lang
} = node.attrMap;
if (!lang || lang === "postcss" || lang === "css") {
return "css";
}
if (lang === "scss") {
return "scss";
}
if (lang === "less") {
return "less";
}
}
function inferScriptParser(node, options) {
if (node.name === "script" && !node.attrMap.src) {
if (!node.attrMap.lang && !node.attrMap.type) {
return "babel";
}
return _inferScriptParser(node);
}
if (node.name === "style") {
return inferStyleParser(node);
}
if (options && isVueNonHtmlBlock(node, options)) {
return _inferScriptParser(node) || !("src" in node.attrMap) && getParserName$2(node.attrMap.lang, options);
}
}
function isBlockLikeCssDisplay(cssDisplay) {
return cssDisplay === "block" || cssDisplay === "list-item" || cssDisplay.startsWith("table");
}
function isFirstChildLeadingSpaceSensitiveCssDisplay(cssDisplay) {
return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
}
function isLastChildTrailingSpaceSensitiveCssDisplay(cssDisplay) {
return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
}
function isPrevTrailingSpaceSensitiveCssDisplay(cssDisplay) {
return !isBlockLikeCssDisplay(cssDisplay);
}
function isNextLeadingSpaceSensitiveCssDisplay(cssDisplay) {
return !isBlockLikeCssDisplay(cssDisplay);
}
function isDanglingSpaceSensitiveCssDisplay(cssDisplay) {
return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
}
function isPreLikeNode(node) {
return getNodeCssStyleWhiteSpace(node).startsWith("pre");
}
function countParents(path, predicate) {
let counter = 0;
for (let i = path.stack.length - 1; i >= 0; i--) {
const value = path.stack[i];
if (value && typeof value === "object" && !Array.isArray(value) && predicate(value)) {
counter++;
}
}
return counter;
}
function hasParent(node, fn) {
let current = node;
while (current) {
if (fn(current)) {
return true;
}
current = current.parent;
}
return false;
}
function getNodeCssStyleDisplay(node, options) {
if (node.prev && node.prev.type === "comment") {
//
const match = node.prev.value.match(/^\s*display:\s*([a-z]+)\s*$/);
if (match) {
return match[1];
}
}
let isInSvgForeignObject = false;
if (node.type === "element" && node.namespace === "svg") {
if (hasParent(node, parent => parent.fullName === "svg:foreignObject")) {
isInSvgForeignObject = true;
} else {
return node.name === "svg" ? "inline-block" : "block";
}
}
switch (options.htmlWhitespaceSensitivity) {
case "strict":
return "inline";
case "ignore":
return "block";
default:
{
// See https://github.com/prettier/prettier/issues/8151
if (options.parser === "vue" && node.parent && node.parent.type === "root") {
return "block";
}
return node.type === "element" && (!node.namespace || isInSvgForeignObject || isUnknownNamespace(node)) && CSS_DISPLAY_TAGS[node.name] || CSS_DISPLAY_DEFAULT;
}
}
}
function isUnknownNamespace(node) {
return node.type === "element" && !node.hasExplicitNamespace && !["html", "svg"].includes(node.namespace);
}
function getNodeCssStyleWhiteSpace(node) {
return node.type === "element" && (!node.namespace || isUnknownNamespace(node)) && CSS_WHITE_SPACE_TAGS[node.name] || CSS_WHITE_SPACE_DEFAULT;
}
function getMinIndentation(text) {
let minIndentation = Infinity;
for (const lineText of text.split("\n")) {
if (lineText.length === 0) {
continue;
}
if (!HTML_WHITESPACE.has(lineText[0])) {
return 0;
}
const indentation = getLeadingHtmlWhitespace(lineText).length;
if (lineText.length === indentation) {
continue;
}
if (indentation < minIndentation) {
minIndentation = indentation;
}
}
return minIndentation === Infinity ? 0 : minIndentation;
}
function dedentString(text, minIndent = getMinIndentation(text)) {
return minIndent === 0 ? text : text.split("\n").map(lineText => lineText.slice(minIndent)).join("\n");
}
function shouldNotPrintClosingTag(node, options) {
return !node.isSelfClosing && !node.endSourceSpan && (hasPrettierIgnore$5(node) || shouldPreserveContent(node.parent, options));
}
function countChars(text, char) {
let counter = 0;
for (let i = 0; i < text.length; i++) {
if (text[i] === char) {
counter++;
}
}
return counter;
}
function unescapeQuoteEntities(text) {
return text.replace(/'/g, "'").replace(/"/g, '"');
} // top-level elements (excluding ,