!nameHasComments && !hasComment$e(node.attributes[0])) {
return group$y(["<", print("name"), print("typeParameters"), " ", ...path.map(print, "attributes"), node.selfClosing ? " />" : ">"]);
}
const lastAttrHasTrailingComments = node.attributes.length > 0 && hasComment$e(getLast$a(node.attributes), CommentCheckFlags$c.Trailing);
const bracketSameLine = // Simple tags (no attributes and no comment in tag name) should be
// kept unbroken regardless of `bracketSameLine`.
// jsxBracketSameLine is deprecated in favour of bracketSameLine,
// but is still needed for backwards compatibility.
node.attributes.length === 0 && !nameHasComments || (options.bracketSameLine || options.jsxBracketSameLine) && (!nameHasComments || node.attributes.length > 0) && !lastAttrHasTrailingComments; // We should print the opening element expanded if any prop value is a
// string literal with newlines
const shouldBreak = node.attributes && node.attributes.some(attr => attr.value && isStringLiteral$4(attr.value) && attr.value.value.includes("\n"));
return group$y(["<", print("name"), print("typeParameters"), indent$s(path.map(() => [line$u, print()], "attributes")), node.selfClosing ? line$u : bracketSameLine ? ">" : softline$p, node.selfClosing ? "/>" : bracketSameLine ? "" : ">"], {
shouldBreak
});
}
function printJsxClosingElement(path, options, print) {
const node = path.getValue();
const parts = [];
parts.push("");
const printed = print("name");
if (hasComment$e(node.name, CommentCheckFlags$c.Leading | CommentCheckFlags$c.Line)) {
parts.push(indent$s([hardline$w, printed]), hardline$w);
} else if (hasComment$e(node.name, CommentCheckFlags$c.Leading | CommentCheckFlags$c.Block)) {
parts.push(" ", printed);
} else {
parts.push(printed);
}
parts.push(">");
return parts;
}
function printJsxOpeningClosingFragment(path, options
/*, print*/
) {
const node = path.getValue();
const nodeHasComment = hasComment$e(node);
const hasOwnLineComment = hasComment$e(node, CommentCheckFlags$c.Line);
const isOpeningFragment = node.type === "JSXOpeningFragment";
return [isOpeningFragment ? "<" : "", indent$s([hasOwnLineComment ? hardline$w : nodeHasComment && !isOpeningFragment ? " " : "", printDanglingComments$d(path, options, true)]), hasOwnLineComment ? hardline$w : "", ">"];
}
function printJsxElement(path, options, print) {
const elem = printComments$4(path, printJsxElementInternal(path, options, print), options);
return maybeWrapJsxElementInParens(path, elem, options);
}
function printJsxEmptyExpression(path, options
/*, print*/
) {
const node = path.getValue();
const requiresHardline = hasComment$e(node, CommentCheckFlags$c.Line);
return [printDanglingComments$d(path, options,
/* sameIndent */
!requiresHardline), requiresHardline ? hardline$w : ""];
} // `JSXSpreadAttribute` and `JSXSpreadChild`
function printJsxSpreadAttribute(path, options, print) {
const node = path.getValue();
return ["{", path.call(p => {
const printed = ["...", print()];
const node = p.getValue();
if (!hasComment$e(node) || !willPrintOwnComments(p)) {
return printed;
}
return [indent$s([softline$p, printComments$4(p, printed, options)]), softline$p];
}, node.type === "JSXSpreadAttribute" ? "argument" : "expression"), "}"];
}
function printJsx$1(path, options, print) {
const node = path.getValue(); // JSX nodes always starts with `JSX`
if (!node.type.startsWith("JSX")) {
return;
}
switch (node.type) {
case "JSXAttribute":
return printJsxAttribute(path, options, print);
case "JSXIdentifier":
return String(node.name);
case "JSXNamespacedName":
return join$p(":", [print("namespace"), print("name")]);
case "JSXMemberExpression":
return join$p(".", [print("object"), print("property")]);
case "JSXSpreadAttribute":
return printJsxSpreadAttribute(path, options, print);
case "JSXSpreadChild":
{
// Same as `printJsxSpreadAttribute`
const printJsxSpreadChild = printJsxSpreadAttribute;
return printJsxSpreadChild(path, options, print);
}
case "JSXExpressionContainer":
return printJsxExpressionContainer(path, options, print);
case "JSXFragment":
case "JSXElement":
return printJsxElement(path, options, print);
case "JSXOpeningElement":
return printJsxOpeningElement(path, options, print);
case "JSXClosingElement":
return printJsxClosingElement(path, options, print);
case "JSXOpeningFragment":
case "JSXClosingFragment":
return printJsxOpeningClosingFragment(path, options
/*, print*/
);
case "JSXEmptyExpression":
return printJsxEmptyExpression(path, options
/*, print*/
);
case "JSXText":
/* istanbul ignore next */
throw new Error("JSXTest should be handled by JSXElement");
default:
/* istanbul ignore next */
throw new Error(`Unknown JSX node type: ${JSON.stringify(node.type)}.`);
}
} // Only space, newline, carriage return, and tab are treated as whitespace
// inside JSX.
const jsxWhitespaceChars = " \n\r\t";
const matchJsxWhitespaceRegex = new RegExp("([" + jsxWhitespaceChars + "]+)");
const containsNonJsxWhitespaceRegex = new RegExp("[^" + jsxWhitespaceChars + "]");
const trimJsxWhitespace = text => text.replace(new RegExp("(?:^" + matchJsxWhitespaceRegex.source + "|" + matchJsxWhitespaceRegex.source + "$)"), "");
/**
* @param {JSXElement} node
* @returns {boolean}
*/
function isEmptyJsxElement(node) {
if (node.children.length === 0) {
return true;
}
if (node.children.length > 1) {
return false;
} // if there is one text child and does not contain any meaningful text
// we can treat the element as empty.
const child = node.children[0];
return isLiteral$2(child) && !isMeaningfulJsxText(child);
} // Meaningful if it contains non-whitespace characters,
// or it contains whitespace without a new line.
/**
* @param {Node} node
* @returns {boolean}
*/
function isMeaningfulJsxText(node) {
return isLiteral$2(node) && (containsNonJsxWhitespaceRegex.test(rawText$4(node)) || !/\n/.test(rawText$4(node)));
} // Detect an expression node representing `{" "}`
function isJsxWhitespaceExpression(node) {
return node.type === "JSXExpressionContainer" && isLiteral$2(node.expression) && node.expression.value === " " && !hasComment$e(node.expression);
}
/**
* @param {AstPath} path
* @returns {boolean}
*/
function hasJsxIgnoreComment$1(path) {
const node = path.getValue();
const parent = path.getParentNode();
if (!parent || !node || !isJsxNode$4(node) || !isJsxNode$4(parent)) {
return false;
} // Lookup the previous sibling, ignoring any empty JSXText elements
const index = parent.children.indexOf(node);
let prevSibling = null;
for (let i = index; i > 0; i--) {
const candidate = parent.children[i - 1];
if (candidate.type === "JSXText" && !isMeaningfulJsxText(candidate)) {
continue;
}
prevSibling = candidate;
break;
}
return prevSibling && prevSibling.type === "JSXExpressionContainer" && prevSibling.expression.type === "JSXEmptyExpression" && hasNodeIgnoreComment(prevSibling.expression);
}
var jsx = {
hasJsxIgnoreComment: hasJsxIgnoreComment$1,
printJsx: printJsx$1
};
// `Array.prototype.flat` method
// https://tc39.es/ecma262/#sec-array.prototype.flat
_export({ target: 'Array', proto: true }, {
flat: function flat(/* depthArg = 1 */) {
var depthArg = arguments.length ? arguments[0] : undefined;
var O = toObject(this);
var sourceLen = toLength(O.length);
var A = arraySpeciesCreate(O, 0);
A.length = flattenIntoArray_1(A, O, O, sourceLen, 0, depthArg === undefined ? 1 : toInteger(depthArg));
return A;
}
});
const {
isNonEmptyArray: isNonEmptyArray$e
} = util$5;
const {
builders: {
indent: indent$r,
join: join$o,
line: line$t
}
} = doc;
const {
isFlowAnnotationComment: isFlowAnnotationComment$1
} = utils$5;
function printOptionalToken$9(path) {
const node = path.getValue();
if (!node.optional || node.type === "Identifier" && node === path.getParentNode().key) {
return "";
}
if (node.type === "OptionalCallExpression" || node.type === "OptionalMemberExpression" && node.computed) {
return "?.";
}
return "?";
}
function printFunctionTypeParameters$4(path, options, print) {
const fun = path.getValue();
if (fun.typeArguments) {
return print("typeArguments");
}
if (fun.typeParameters) {
return print("typeParameters");
}
return "";
}
function printTypeAnnotation$5(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)) {
return [" /*: ", print("typeAnnotation"), " */"];
}
return [isFunctionDeclarationIdentifier ? "" : isDefinite ? "!: " : ": ", print("typeAnnotation")];
}
function printBindExpressionCallee$2(path, options, print) {
return ["::", print("callee")];
}
function printTypeScriptModifiers$2(path, options, print) {
const node = path.getValue();
if (!isNonEmptyArray$e(node.modifiers)) {
return "";
}
return [join$o(" ", path.map(print, "modifiers")), " "];
}
function adjustClause$1(node, clause, forceSpace) {
if (node.type === "EmptyStatement") {
return ";";
}
if (node.type === "BlockStatement" || forceSpace) {
return [" ", clause];
}
return indent$r([line$t, clause]);
}
function printRestSpread$2(path, options, print) {
return ["...", print("argument"), printTypeAnnotation$5(path, options, print)];
}
var misc$1 = {
printOptionalToken: printOptionalToken$9,
printFunctionTypeParameters: printFunctionTypeParameters$4,
printBindExpressionCallee: printBindExpressionCallee$2,
printTypeScriptModifiers: printTypeScriptModifiers$2,
printTypeAnnotation: printTypeAnnotation$5,
printRestSpread: printRestSpread$2,
adjustClause: adjustClause$1
};
const {
printDanglingComments: printDanglingComments$c
} = comments$1;
const {
builders: {
line: line$s,
softline: softline$o,
hardline: hardline$v,
group: group$x,
indent: indent$q,
ifBreak: ifBreak$k,
fill: fill$7
}
} = doc;
const {
getLast: getLast$9,
hasNewline: hasNewline$5
} = util$5;
const {
shouldPrintComma: shouldPrintComma$a,
hasComment: hasComment$d,
CommentCheckFlags: CommentCheckFlags$b,
isNextLineEmpty: isNextLineEmpty$b,
isNumericLiteral: isNumericLiteral$4,
isSignedNumericLiteral: isSignedNumericLiteral$1
} = utils$5;
const {
locStart: locStart$o
} = loc$6;
const {
printOptionalToken: printOptionalToken$8,
printTypeAnnotation: printTypeAnnotation$4
} = misc$1;
/** @typedef {import("../../document").Doc} Doc */
function printArray$1(path, options, print) {
const node = path.getValue();
/** @type{Doc[]} */
const parts = [];
const openBracket = node.type === "TupleExpression" ? "#[" : "[";
const closeBracket = "]";
if (node.elements.length === 0) {
if (!hasComment$d(node, CommentCheckFlags$b.Dangling)) {
parts.push(openBracket, closeBracket);
} else {
parts.push(group$x([openBracket, printDanglingComments$c(path, options), softline$o, closeBracket]));
}
} else {
const lastElem = getLast$9(node.elements);
const canHaveTrailingComma = !(lastElem && lastElem.type === "RestElement"); // JavaScript allows you to have empty elements in an array which
// changes its length based on the number of commas. The algorithm
// is that if the last argument is null, we need to force insert
// a comma to ensure JavaScript recognizes it.
// [,].length === 1
// [1,].length === 1
// [1,,].length === 2
//
// Note that getLast returns null if the array is empty, but
// we already check for an empty array just above so we are safe
const needsForcedTrailingComma = lastElem === null;
const groupId = Symbol("array");
const shouldBreak = !options.__inJestEach && node.elements.length > 1 && node.elements.every((element, i, elements) => {
const elementType = element && element.type;
if (elementType !== "ArrayExpression" && elementType !== "ObjectExpression") {
return false;
}
const nextElement = elements[i + 1];
if (nextElement && elementType !== nextElement.type) {
return false;
}
const itemsKey = elementType === "ArrayExpression" ? "elements" : "properties";
return element[itemsKey] && element[itemsKey].length > 1;
});
const shouldUseConciseFormatting = isConciselyPrintedArray$1(node, options);
const trailingComma = !canHaveTrailingComma ? "" : needsForcedTrailingComma ? "," : !shouldPrintComma$a(options) ? "" : shouldUseConciseFormatting ? ifBreak$k(",", "", {
groupId
}) : ifBreak$k(",");
parts.push(group$x([openBracket, indent$q([softline$o, shouldUseConciseFormatting ? printArrayItemsConcisely(path, options, print, trailingComma) : [printArrayItems$3(path, options, "elements", print), trailingComma], printDanglingComments$c(path, options,
/* sameIndent */
true)]), softline$o, closeBracket], {
shouldBreak,
id: groupId
}));
}
parts.push(printOptionalToken$8(path), printTypeAnnotation$4(path, options, print));
return parts;
}
function isConciselyPrintedArray$1(node, options) {
return node.elements.length > 1 && node.elements.every(element => element && (isNumericLiteral$4(element) || isSignedNumericLiteral$1(element) && !hasComment$d(element.argument)) && !hasComment$d(element, CommentCheckFlags$b.Trailing | CommentCheckFlags$b.Line, comment => !hasNewline$5(options.originalText, locStart$o(comment), {
backwards: true
})));
}
function printArrayItems$3(path, options, printPath, print) {
const printedElements = [];
let separatorParts = [];
path.each(childPath => {
printedElements.push(separatorParts, group$x(print()));
separatorParts = [",", line$s];
if (childPath.getValue() && isNextLineEmpty$b(childPath.getValue(), options)) {
separatorParts.push(softline$o);
}
}, printPath);
return printedElements;
}
function printArrayItemsConcisely(path, options, print, trailingComma) {
const parts = [];
path.each((childPath, i, elements) => {
const isLast = i === elements.length - 1;
parts.push([print(), isLast ? trailingComma : ","]);
if (!isLast) {
parts.push(isNextLineEmpty$b(childPath.getValue(), options) ? [hardline$v, hardline$v] : hasComment$d(elements[i + 1], CommentCheckFlags$b.Leading | CommentCheckFlags$b.Line) ? hardline$v : line$s);
}
}, "elements");
return fill$7(parts);
}
var array = {
printArray: printArray$1,
printArrayItems: printArrayItems$3,
isConciselyPrintedArray: isConciselyPrintedArray$1
};
const {
printDanglingComments: printDanglingComments$b
} = comments$1;
const {
getLast: getLast$8,
getPenultimate
} = util$5;
const {
getFunctionParameters: getFunctionParameters$3,
hasComment: hasComment$c,
CommentCheckFlags: CommentCheckFlags$a,
isFunctionCompositionArgs,
isJsxNode: isJsxNode$3,
isLongCurriedCallExpression: isLongCurriedCallExpression$1,
shouldPrintComma: shouldPrintComma$9,
getCallArguments: getCallArguments$3,
iterateCallArgumentsPath: iterateCallArgumentsPath$1,
isNextLineEmpty: isNextLineEmpty$a,
isCallExpression: isCallExpression$8,
isStringLiteral: isStringLiteral$3,
isObjectProperty: isObjectProperty$1
} = utils$5;
const {
builders: {
line: line$r,
hardline: hardline$u,
softline: softline$n,
group: group$w,
indent: indent$p,
conditionalGroup: conditionalGroup$3,
ifBreak: ifBreak$j,
breakParent: breakParent$9
},
utils: {
willBreak: willBreak$4
}
} = doc;
const {
ArgExpansionBailout: ArgExpansionBailout$2
} = errors;
const {
isConciselyPrintedArray
} = array;
function printCallArguments(path, options, print) {
const node = path.getValue();
const isDynamicImport = node.type === "ImportExpression";
const args = getCallArguments$3(node);
if (args.length === 0) {
return ["(", printDanglingComments$b(path, options,
/* sameIndent */
true), ")"];
} // useEffect(() => { ... }, [foo, bar, baz])
if (isReactHookCallWithDepsArray(args)) {
return ["(", print(["arguments", 0]), ", ", print(["arguments", 1]), ")"];
}
let anyArgEmptyLine = false;
let hasEmptyLineFollowingFirstArg = false;
const lastArgIndex = args.length - 1;
const printedArguments = [];
iterateCallArgumentsPath$1(path, (argPath, index) => {
const arg = argPath.getNode();
const parts = [print()];
if (index === lastArgIndex) ; else if (isNextLineEmpty$a(arg, options)) {
if (index === 0) {
hasEmptyLineFollowingFirstArg = true;
}
anyArgEmptyLine = true;
parts.push(",", hardline$u, hardline$u);
} else {
parts.push(",", line$r);
}
printedArguments.push(parts);
});
const maybeTrailingComma = // Dynamic imports cannot have trailing commas
!(isDynamicImport || node.callee && node.callee.type === "Import") && shouldPrintComma$9(options, "all") ? "," : "";
function allArgsBrokenOut() {
return group$w(["(", indent$p([line$r, ...printedArguments]), maybeTrailingComma, line$r, ")"], {
shouldBreak: true
});
}
if (anyArgEmptyLine || path.getParentNode().type !== "Decorator" && isFunctionCompositionArgs(args)) {
return allArgsBrokenOut();
}
const shouldGroupFirst = shouldGroupFirstArg(args);
const shouldGroupLast = shouldGroupLastArg(args, options);
if (shouldGroupFirst || shouldGroupLast) {
if (shouldGroupFirst ? printedArguments.slice(1).some(willBreak$4) : printedArguments.slice(0, -1).some(willBreak$4)) {
return allArgsBrokenOut();
} // We want to print the last argument with a special flag
let printedExpanded = [];
try {
path.try(() => {
iterateCallArgumentsPath$1(path, (argPath, i) => {
if (shouldGroupFirst && i === 0) {
printedExpanded = [[print([], {
expandFirstArg: true
}), printedArguments.length > 1 ? "," : "", hasEmptyLineFollowingFirstArg ? hardline$u : line$r, hasEmptyLineFollowingFirstArg ? hardline$u : ""], ...printedArguments.slice(1)];
}
if (shouldGroupLast && i === lastArgIndex) {
printedExpanded = [...printedArguments.slice(0, -1), print([], {
expandLastArg: true
})];
}
});
});
} catch (caught) {
if (caught instanceof ArgExpansionBailout$2) {
return allArgsBrokenOut();
}
/* istanbul ignore next */
throw caught;
}
return [printedArguments.some(willBreak$4) ? breakParent$9 : "", conditionalGroup$3([["(", ...printedExpanded, ")"], shouldGroupFirst ? ["(", group$w(printedExpanded[0], {
shouldBreak: true
}), ...printedExpanded.slice(1), ")"] : ["(", ...printedArguments.slice(0, -1), group$w(getLast$8(printedExpanded), {
shouldBreak: true
}), ")"], allArgsBrokenOut()])];
}
const contents = ["(", indent$p([softline$n, ...printedArguments]), ifBreak$j(maybeTrailingComma), softline$n, ")"];
if (isLongCurriedCallExpression$1(path)) {
// By not wrapping the arguments in a group, the printer prioritizes
// breaking up these arguments rather than the args of the parent call.
return contents;
}
return group$w(contents, {
shouldBreak: printedArguments.some(willBreak$4) || anyArgEmptyLine
});
}
function couldGroupArg(arg, arrowChainRecursion = false) {
return arg.type === "ObjectExpression" && (arg.properties.length > 0 || hasComment$c(arg)) || arg.type === "ArrayExpression" && (arg.elements.length > 0 || hasComment$c(arg)) || arg.type === "TSTypeAssertion" && couldGroupArg(arg.expression) || arg.type === "TSAsExpression" && couldGroupArg(arg.expression) || arg.type === "FunctionExpression" || arg.type === "ArrowFunctionExpression" && (!arg.returnType || !arg.returnType.typeAnnotation || arg.returnType.typeAnnotation.type !== "TSTypeReference" || // https://github.com/prettier/prettier/issues/7542
isNonEmptyBlockStatement(arg.body)) && (arg.body.type === "BlockStatement" || arg.body.type === "ArrowFunctionExpression" && couldGroupArg(arg.body, true) || arg.body.type === "ObjectExpression" || arg.body.type === "ArrayExpression" || !arrowChainRecursion && (isCallExpression$8(arg.body) || arg.body.type === "ConditionalExpression") || isJsxNode$3(arg.body)) || arg.type === "DoExpression" || arg.type === "ModuleExpression";
}
function shouldGroupLastArg(args, options) {
const lastArg = getLast$8(args);
const penultimateArg = getPenultimate(args);
return !hasComment$c(lastArg, CommentCheckFlags$a.Leading) && !hasComment$c(lastArg, CommentCheckFlags$a.Trailing) && couldGroupArg(lastArg) && (!penultimateArg || penultimateArg.type !== lastArg.type) && (args.length !== 2 || penultimateArg.type !== "ArrowFunctionExpression" || lastArg.type !== "ArrayExpression") && !(args.length > 1 && lastArg.type === "ArrayExpression" && isConciselyPrintedArray(lastArg, options));
}
function shouldGroupFirstArg(args) {
if (args.length !== 2) {
return false;
}
const [firstArg, secondArg] = args;
if (firstArg.type === "ModuleExpression" && isTypeModuleObjectExpression(secondArg)) {
return true;
}
return !hasComment$c(firstArg) && (firstArg.type === "FunctionExpression" || firstArg.type === "ArrowFunctionExpression" && firstArg.body.type === "BlockStatement") && secondArg.type !== "FunctionExpression" && secondArg.type !== "ArrowFunctionExpression" && secondArg.type !== "ConditionalExpression" && !couldGroupArg(secondArg);
}
function isReactHookCallWithDepsArray(args) {
return args.length === 2 && args[0].type === "ArrowFunctionExpression" && getFunctionParameters$3(args[0]).length === 0 && args[0].body.type === "BlockStatement" && args[1].type === "ArrayExpression" && !args.some(arg => hasComment$c(arg));
}
function isNonEmptyBlockStatement(node) {
return node.type === "BlockStatement" && (node.body.some(node => node.type !== "EmptyStatement") || hasComment$c(node, CommentCheckFlags$a.Dangling));
} // { type: "module" }
function isTypeModuleObjectExpression(node) {
return node.type === "ObjectExpression" && node.properties.length === 1 && isObjectProperty$1(node.properties[0]) && node.properties[0].key.type === "Identifier" && node.properties[0].key.name === "type" && isStringLiteral$3(node.properties[0].value) && node.properties[0].value.value === "module";
}
var callArguments = printCallArguments;
const {
builders: {
softline: softline$m,
group: group$v,
indent: indent$o,
label: label$2
}
} = doc;
const {
isNumericLiteral: isNumericLiteral$3,
isMemberExpression: isMemberExpression$5,
isCallExpression: isCallExpression$7
} = utils$5;
const {
printOptionalToken: printOptionalToken$7
} = misc$1;
function printMemberExpression$1(path, options, print) {
const node = path.getValue();
const parent = path.getParentNode();
let firstNonMemberParent;
let i = 0;
do {
firstNonMemberParent = path.getParentNode(i);
i++;
} while (firstNonMemberParent && (isMemberExpression$5(firstNonMemberParent) || firstNonMemberParent.type === "TSNonNullExpression"));
const objectDoc = print("object");
const lookupDoc = printMemberLookup$1(path, options, print);
const shouldInline = firstNonMemberParent && (firstNonMemberParent.type === "NewExpression" || firstNonMemberParent.type === "BindExpression" || firstNonMemberParent.type === "AssignmentExpression" && firstNonMemberParent.left.type !== "Identifier") || node.computed || node.object.type === "Identifier" && node.property.type === "Identifier" && !isMemberExpression$5(parent) || (parent.type === "AssignmentExpression" || parent.type === "VariableDeclarator") && (isCallExpression$7(node.object) && node.object.arguments.length > 0 || node.object.type === "TSNonNullExpression" && isCallExpression$7(node.object.expression) && node.object.expression.arguments.length > 0 || objectDoc.label === "member-chain");
return label$2(objectDoc.label === "member-chain" ? "member-chain" : "member", [objectDoc, shouldInline ? lookupDoc : group$v(indent$o([softline$m, lookupDoc]))]);
}
function printMemberLookup$1(path, options, print) {
const property = print("property");
const node = path.getValue();
const optional = printOptionalToken$7(path);
if (!node.computed) {
return [optional, ".", property];
}
if (!node.property || isNumericLiteral$3(node.property)) {
return [optional, "[", property, "]"];
}
return group$v([optional, "[", indent$o([softline$m, property]), softline$m, "]"]);
}
var member = {
printMemberExpression: printMemberExpression$1,
printMemberLookup: printMemberLookup$1
};
const {
printComments: printComments$3
} = comments$1;
const {
getLast: getLast$7,
isNextLineEmptyAfterIndex,
getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$1
} = util$5;
const {
isCallExpression: isCallExpression$6,
isMemberExpression: isMemberExpression$4,
isFunctionOrArrowExpression,
isLongCurriedCallExpression,
isMemberish: isMemberish$1,
isNumericLiteral: isNumericLiteral$2,
isSimpleCallArgument,
hasComment: hasComment$b,
CommentCheckFlags: CommentCheckFlags$9,
isNextLineEmpty: isNextLineEmpty$9
} = utils$5;
const {
locEnd: locEnd$n
} = loc$6;
const {
builders: {
join: join$n,
hardline: hardline$t,
group: group$u,
indent: indent$n,
conditionalGroup: conditionalGroup$2,
breakParent: breakParent$8,
label: label$1
},
utils: {
willBreak: willBreak$3
}
} = doc;
const {
printMemberLookup
} = member;
const {
printOptionalToken: printOptionalToken$6,
printFunctionTypeParameters: printFunctionTypeParameters$3,
printBindExpressionCallee: printBindExpressionCallee$1
} = misc$1; // We detect calls on member expressions specially to format a
// common pattern better. The pattern we are looking for is this:
//
// arr
// .map(x => x + 1)
// .filter(x => x > 10)
// .some(x => x % 2)
//
// The way it is structured in the AST is via a nested sequence of
// MemberExpression and CallExpression. We need to traverse the AST
// and make groups out of it to print it in the desired way.
function printMemberChain(path, options, print) {
const parent = path.getParentNode();
const isExpressionStatement = !parent || parent.type === "ExpressionStatement"; // The first phase is to linearize the AST by traversing it down.
//
// a().b()
// has the following AST structure:
// CallExpression(MemberExpression(CallExpression(Identifier)))
// and we transform it into
// [Identifier, CallExpression, MemberExpression, CallExpression]
const printedNodes = []; // Here we try to retain one typed empty line after each call expression or
// the first group whether it is in parentheses or not
function shouldInsertEmptyLineAfter(node) {
const {
originalText
} = options;
const nextCharIndex = getNextNonSpaceNonCommentCharacterIndex$1(originalText, node, locEnd$n);
const nextChar = originalText.charAt(nextCharIndex); // if it is cut off by a parenthesis, we only account for one typed empty
// line after that parenthesis
if (nextChar === ")") {
return nextCharIndex !== false && isNextLineEmptyAfterIndex(originalText, nextCharIndex + 1);
}
return isNextLineEmpty$9(node, options);
}
function rec(path) {
const node = path.getValue();
if (isCallExpression$6(node) && (isMemberish$1(node.callee) || isCallExpression$6(node.callee))) {
printedNodes.unshift({
node,
printed: [printComments$3(path, [printOptionalToken$6(path), printFunctionTypeParameters$3(path, options, print), callArguments(path, options, print)], options), shouldInsertEmptyLineAfter(node) ? hardline$t : ""]
});
path.call(callee => rec(callee), "callee");
} else if (isMemberish$1(node)) {
printedNodes.unshift({
node,
needsParens: needsParens_1(path, options),
printed: printComments$3(path, isMemberExpression$4(node) ? printMemberLookup(path, options, print) : printBindExpressionCallee$1(path, options, print), options)
});
path.call(object => rec(object), "object");
} else if (node.type === "TSNonNullExpression") {
printedNodes.unshift({
node,
printed: printComments$3(path, "!", options)
});
path.call(expression => rec(expression), "expression");
} else {
printedNodes.unshift({
node,
printed: print()
});
}
} // Note: the comments of the root node have already been printed, so we
// need to extract this first call without printing them as they would
// if handled inside of the recursive call.
const node = path.getValue();
printedNodes.unshift({
node,
printed: [printOptionalToken$6(path), printFunctionTypeParameters$3(path, options, print), callArguments(path, options, print)]
});
if (node.callee) {
path.call(callee => rec(callee), "callee");
} // Once we have a linear list of printed nodes, we want to create groups out
// of it.
//
// a().b.c().d().e
// will be grouped as
// [
// [Identifier, CallExpression],
// [MemberExpression, MemberExpression, CallExpression],
// [MemberExpression, CallExpression],
// [MemberExpression],
// ]
// so that we can print it as
// a()
// .b.c()
// .d()
// .e
// The first group is the first node followed by
// - as many CallExpression as possible
// < fn()()() >.something()
// - as many array accessors as possible
// < fn()[0][1][2] >.something()
// - then, as many MemberExpression as possible but the last one
// < this.items >.something()
const groups = [];
let currentGroup = [printedNodes[0]];
let i = 1;
for (; i < printedNodes.length; ++i) {
if (printedNodes[i].node.type === "TSNonNullExpression" || isCallExpression$6(printedNodes[i].node) || isMemberExpression$4(printedNodes[i].node) && printedNodes[i].node.computed && isNumericLiteral$2(printedNodes[i].node.property)) {
currentGroup.push(printedNodes[i]);
} else {
break;
}
}
if (!isCallExpression$6(printedNodes[0].node)) {
for (; i + 1 < printedNodes.length; ++i) {
if (isMemberish$1(printedNodes[i].node) && isMemberish$1(printedNodes[i + 1].node)) {
currentGroup.push(printedNodes[i]);
} else {
break;
}
}
}
groups.push(currentGroup);
currentGroup = []; // Then, each following group is a sequence of MemberExpression followed by
// a sequence of CallExpression. To compute it, we keep adding things to the
// group until we has seen a CallExpression in the past and reach a
// MemberExpression
let hasSeenCallExpression = false;
for (; i < printedNodes.length; ++i) {
if (hasSeenCallExpression && isMemberish$1(printedNodes[i].node)) {
// [0] should be appended at the end of the group instead of the
// beginning of the next one
if (printedNodes[i].node.computed && isNumericLiteral$2(printedNodes[i].node.property)) {
currentGroup.push(printedNodes[i]);
continue;
}
groups.push(currentGroup);
currentGroup = [];
hasSeenCallExpression = false;
}
if (isCallExpression$6(printedNodes[i].node) || printedNodes[i].node.type === "ImportExpression") {
hasSeenCallExpression = true;
}
currentGroup.push(printedNodes[i]);
if (hasComment$b(printedNodes[i].node, CommentCheckFlags$9.Trailing)) {
groups.push(currentGroup);
currentGroup = [];
hasSeenCallExpression = false;
}
}
if (currentGroup.length > 0) {
groups.push(currentGroup);
} // There are cases like Object.keys(), Observable.of(), _.values() where
// they are the subject of all the chained calls and therefore should
// be kept on the same line:
//
// Object.keys(items)
// .filter(x => x)
// .map(x => x)
//
// In order to detect those cases, we use an heuristic: if the first
// node is an identifier with the name starting with a capital
// letter or just a sequence of _$. The rationale is that they are
// likely to be factories.
function isFactory(name) {
return /^[A-Z]|^[$_]+$/.test(name);
} // In case the Identifier is shorter than tab width, we can keep the
// first call in a single line, if it's an ExpressionStatement.
//
// d3.scaleLinear()
// .domain([0, 100])
// .range([0, width]);
//
function isShort(name) {
return name.length <= options.tabWidth;
}
function shouldNotWrap(groups) {
const hasComputed = groups[1].length > 0 && groups[1][0].node.computed;
if (groups[0].length === 1) {
const firstNode = groups[0][0].node;
return firstNode.type === "ThisExpression" || firstNode.type === "Identifier" && (isFactory(firstNode.name) || isExpressionStatement && isShort(firstNode.name) || hasComputed);
}
const lastNode = getLast$7(groups[0]).node;
return isMemberExpression$4(lastNode) && lastNode.property.type === "Identifier" && (isFactory(lastNode.property.name) || hasComputed);
}
const shouldMerge = groups.length >= 2 && !hasComment$b(groups[1][0].node) && shouldNotWrap(groups);
function printGroup(printedGroup) {
const printed = printedGroup.map(tuple => tuple.printed); // Checks if the last node (i.e. the parent node) needs parens and print
// accordingly
if (printedGroup.length > 0 && getLast$7(printedGroup).needsParens) {
return ["(", ...printed, ")"];
}
return printed;
}
function printIndentedGroup(groups) {
/* istanbul ignore next */
if (groups.length === 0) {
return "";
}
return indent$n(group$u([hardline$t, join$n(hardline$t, groups.map(printGroup))]));
}
const printedGroups = groups.map(printGroup);
const oneLine = printedGroups;
const cutoff = shouldMerge ? 3 : 2;
const flatGroups = groups.flat();
const nodeHasComment = flatGroups.slice(1, -1).some(node => hasComment$b(node.node, CommentCheckFlags$9.Leading)) || flatGroups.slice(0, -1).some(node => hasComment$b(node.node, CommentCheckFlags$9.Trailing)) || groups[cutoff] && hasComment$b(groups[cutoff][0].node, CommentCheckFlags$9.Leading); // If we only have a single `.`, we shouldn't do anything fancy and just
// render everything concatenated together.
if (groups.length <= cutoff && !nodeHasComment) {
if (isLongCurriedCallExpression(path)) {
return oneLine;
}
return group$u(oneLine);
} // Find out the last node in the first group and check if it has an
// empty line after
const lastNodeBeforeIndent = getLast$7(groups[shouldMerge ? 1 : 0]).node;
const shouldHaveEmptyLineBeforeIndent = !isCallExpression$6(lastNodeBeforeIndent) && shouldInsertEmptyLineAfter(lastNodeBeforeIndent);
const expanded = [printGroup(groups[0]), shouldMerge ? groups.slice(1, 2).map(printGroup) : "", shouldHaveEmptyLineBeforeIndent ? hardline$t : "", printIndentedGroup(groups.slice(shouldMerge ? 2 : 1))];
const callExpressions = printedNodes.map(({
node
}) => node).filter(isCallExpression$6);
function lastGroupWillBreakAndOtherCallsHaveFunctionArguments() {
const lastGroupNode = getLast$7(getLast$7(groups)).node;
const lastGroupDoc = getLast$7(printedGroups);
return isCallExpression$6(lastGroupNode) && willBreak$3(lastGroupDoc) && callExpressions.slice(0, -1).some(node => node.arguments.some(isFunctionOrArrowExpression));
}
let result; // We don't want to print in one line if at least one of these conditions occurs:
// * the chain has comments,
// * the chain is an expression statement and all the arguments are literal-like ("fluent configuration" pattern),
// * the chain is longer than 2 calls and has non-trivial arguments or more than 2 arguments in any call but the first one,
// * any group but the last one has a hard line,
// * the last call's arguments have a hard line and other calls have non-trivial arguments.
if (nodeHasComment || callExpressions.length > 2 && callExpressions.some(expr => !expr.arguments.every(arg => isSimpleCallArgument(arg, 0))) || printedGroups.slice(0, -1).some(willBreak$3) || lastGroupWillBreakAndOtherCallsHaveFunctionArguments()) {
result = group$u(expanded);
} else {
result = [// We only need to check `oneLine` because if `expanded` is chosen
// that means that the parent group has already been broken
// naturally
willBreak$3(oneLine) || shouldHaveEmptyLineBeforeIndent ? breakParent$8 : "", conditionalGroup$2([oneLine, expanded])];
}
return label$1("member-chain", result);
}
var memberChain = printMemberChain;
const {
builders: {
join: join$m,
group: group$t
}
} = doc;
const {
getCallArguments: getCallArguments$2,
hasFlowAnnotationComment,
isCallExpression: isCallExpression$5,
isMemberish,
isStringLiteral: isStringLiteral$2,
isTemplateOnItsOwnLine: isTemplateOnItsOwnLine$1,
isTestCall: isTestCall$2,
iterateCallArgumentsPath
} = utils$5;
const {
printOptionalToken: printOptionalToken$5,
printFunctionTypeParameters: printFunctionTypeParameters$2
} = misc$1;
function printCallExpression$2(path, options, print) {
const node = path.getValue();
const parentNode = path.getParentNode();
const isNew = node.type === "NewExpression";
const isDynamicImport = node.type === "ImportExpression";
const optional = printOptionalToken$5(path);
const args = getCallArguments$2(node);
if ( // Dangling comments are not handled, all these special cases should have arguments #9668
args.length > 0 && (!isDynamicImport && !isNew && isCommonsJsOrAmdCall(node, parentNode) || args.length === 1 && isTemplateOnItsOwnLine$1(args[0], options.originalText) || !isNew && isTestCall$2(node, parentNode))) {
const printed = [];
iterateCallArgumentsPath(path, () => {
printed.push(print());
});
return [isNew ? "new " : "", print("callee"), optional, printFunctionTypeParameters$2(path, options, print), "(", join$m(", ", printed), ")"];
} // Inline Flow annotation comments following Identifiers in Call nodes need to
// stay with the Identifier. For example:
//
// foo /*::
*/(bar);
//
// Here, we ensure that such comments stay between the Identifier and the Callee.
const isIdentifierWithFlowAnnotation = (options.parser === "babel" || options.parser === "babel-flow") && node.callee && node.callee.type === "Identifier" && hasFlowAnnotationComment(node.callee.trailingComments);
if (isIdentifierWithFlowAnnotation) {
node.callee.trailingComments[0].printed = true;
} // We detect calls on member lookups and possibly print them in a
// special chain format. See `printMemberChain` for more info.
if (!isDynamicImport && !isNew && isMemberish(node.callee) && !path.call(path => needsParens_1(path, options), "callee")) {
return memberChain(path, options, print);
}
const contents = [isNew ? "new " : "", isDynamicImport ? "import" : print("callee"), optional, isIdentifierWithFlowAnnotation ? `/*:: ${node.callee.trailingComments[0].value.slice(2).trim()} */` : "", printFunctionTypeParameters$2(path, options, print), callArguments(path, options, print)]; // We group here when the callee is itself a call expression.
// See `isLongCurriedCallExpression` for more info.
if (isDynamicImport || isCallExpression$5(node.callee)) {
return group$t(contents);
}
return contents;
}
function isCommonsJsOrAmdCall(node, parentNode) {
if (node.callee.type !== "Identifier") {
return false;
}
if (node.callee.name === "require") {
return true;
}
if (node.callee.name === "define") {
const args = getCallArguments$2(node);
return parentNode.type === "ExpressionStatement" && (args.length === 1 || args.length === 2 && args[0].type === "ArrayExpression" || args.length === 3 && isStringLiteral$2(args[0]) && args[1].type === "ArrayExpression");
}
return false;
}
var callExpression = {
printCallExpression: printCallExpression$2
};
const {
isNonEmptyArray: isNonEmptyArray$d,
getStringWidth: getStringWidth$1
} = util$5;
const {
builders: {
line: line$q,
group: group$s,
indent: indent$m,
indentIfBreak: indentIfBreak$2
},
utils: {
cleanDoc: cleanDoc$1,
willBreak: willBreak$2
}
} = doc;
const {
hasLeadingOwnLineComment: hasLeadingOwnLineComment$2,
isBinaryish: isBinaryish$1,
isStringLiteral: isStringLiteral$1,
isLiteral: isLiteral$1,
isNumericLiteral: isNumericLiteral$1,
isCallExpression: isCallExpression$4,
isMemberExpression: isMemberExpression$3,
getCallArguments: getCallArguments$1,
rawText: rawText$3,
hasComment: hasComment$a,
isSignedNumericLiteral,
isObjectProperty
} = utils$5;
const {
shouldInlineLogicalExpression
} = binaryish;
const {
printCallExpression: printCallExpression$1
} = callExpression;
function printAssignment$3(path, options, print, leftDoc, operator, rightPropertyName) {
const layout = chooseLayout(path, options, print, leftDoc, rightPropertyName);
const rightDoc = print(rightPropertyName, {
assignmentLayout: layout
});
switch (layout) {
// First break after operator, then the sides are broken independently on their own lines
case "break-after-operator":
return group$s([group$s(leftDoc), operator, group$s(indent$m([line$q, rightDoc]))]);
// First break right-hand side, then left-hand side
case "never-break-after-operator":
return group$s([group$s(leftDoc), operator, " ", rightDoc]);
// First break right-hand side, then after operator
case "fluid":
{
const groupId = Symbol("assignment");
return group$s([group$s(leftDoc), operator, group$s(indent$m(line$q), {
id: groupId
}), indentIfBreak$2(rightDoc, {
groupId
})]);
}
case "break-lhs":
return group$s([leftDoc, operator, " ", group$s(rightDoc)]);
// Parts of assignment chains aren't wrapped in groups.
// Once one of them breaks, the chain breaks too.
case "chain":
return [group$s(leftDoc), operator, line$q, rightDoc];
case "chain-tail":
return [group$s(leftDoc), operator, indent$m([line$q, rightDoc])];
case "chain-tail-arrow-chain":
return [group$s(leftDoc), operator, rightDoc];
case "only-left":
return leftDoc;
}
}
function printAssignmentExpression$1(path, options, print) {
const node = path.getValue();
return printAssignment$3(path, options, print, print("left"), [" ", node.operator], "right");
}
function printVariableDeclarator$1(path, options, print) {
return printAssignment$3(path, options, print, print("id"), " =", "init");
}
function chooseLayout(path, options, print, leftDoc, rightPropertyName) {
const node = path.getValue();
const rightNode = node[rightPropertyName];
if (!rightNode) {
return "only-left";
} // Short assignment chains (only 2 segments) are NOT formatted as chains.
// 1) a = b = c; (expression statements)
// 2) var/let/const a = b = c;
const isTail = !isAssignment(rightNode);
const shouldUseChainFormatting = path.match(isAssignment, isAssignmentOrVariableDeclarator, node => !isTail || node.type !== "ExpressionStatement" && node.type !== "VariableDeclaration");
if (shouldUseChainFormatting) {
return !isTail ? "chain" : rightNode.type === "ArrowFunctionExpression" && rightNode.body.type === "ArrowFunctionExpression" ? "chain-tail-arrow-chain" : "chain-tail";
}
const isHeadOfLongChain = !isTail && isAssignment(rightNode.right);
if (isHeadOfLongChain || hasLeadingOwnLineComment$2(options.originalText, rightNode)) {
return "break-after-operator";
}
if (rightNode.type === "CallExpression" && rightNode.callee.name === "require" || // do not put values on a separate line from the key in json
options.parser === "json5" || options.parser === "json") {
return "never-break-after-operator";
}
if (isComplexDestructuring(node) || isComplexTypeAliasParams(node) || hasComplexTypeAnnotation(node)) {
return "break-lhs";
} // wrapping object properties with very short keys usually doesn't add much value
const hasShortKey = isObjectPropertyWithShortKey(node, leftDoc, options);
if (path.call(() => shouldBreakAfterOperator(path, options, print, hasShortKey), rightPropertyName)) {
return "break-after-operator";
}
if (hasShortKey || rightNode.type === "TemplateLiteral" || rightNode.type === "TaggedTemplateExpression" || rightNode.type === "BooleanLiteral" || isNumericLiteral$1(rightNode) || rightNode.type === "ClassExpression") {
return "never-break-after-operator";
}
return "fluid";
}
function shouldBreakAfterOperator(path, options, print, hasShortKey) {
const rightNode = path.getValue();
if (isBinaryish$1(rightNode) && !shouldInlineLogicalExpression(rightNode)) {
return true;
}
switch (rightNode.type) {
case "StringLiteralTypeAnnotation":
case "SequenceExpression":
return true;
case "ConditionalExpression":
{
const {
test
} = rightNode;
return isBinaryish$1(test) && !shouldInlineLogicalExpression(test);
}
case "ClassExpression":
return isNonEmptyArray$d(rightNode.decorators);
}
if (hasShortKey) {
return false;
}
let node = rightNode;
const propertiesForPath = [];
for (;;) {
if (node.type === "UnaryExpression") {
node = node.argument;
propertiesForPath.push("argument");
} else if (node.type === "TSNonNullExpression") {
node = node.expression;
propertiesForPath.push("expression");
} else {
break;
}
}
if (isStringLiteral$1(node) || path.call(() => isPoorlyBreakableMemberOrCallChain(path, options, print), ...propertiesForPath)) {
return true;
}
return false;
} // prefer to break destructuring assignment
// if it includes default values or non-shorthand properties
function isComplexDestructuring(node) {
if (isAssignmentOrVariableDeclarator(node)) {
const leftNode = node.left || node.id;
return leftNode.type === "ObjectPattern" && leftNode.properties.length > 2 && leftNode.properties.some(property => isObjectProperty(property) && (!property.shorthand || property.value && property.value.type === "AssignmentPattern"));
}
return false;
}
function isAssignment(node) {
return node.type === "AssignmentExpression";
}
function isAssignmentOrVariableDeclarator(node) {
return isAssignment(node) || node.type === "VariableDeclarator";
}
function isComplexTypeAliasParams(node) {
const typeParams = getTypeParametersFromTypeAlias(node);
if (isNonEmptyArray$d(typeParams)) {
const constraintPropertyName = node.type === "TSTypeAliasDeclaration" ? "constraint" : "bound";
if (typeParams.length > 1 && typeParams.some(param => param[constraintPropertyName] || param.default)) {
return true;
}
}
return false;
}
function getTypeParametersFromTypeAlias(node) {
if (isTypeAlias(node) && node.typeParameters && node.typeParameters.params) {
return node.typeParameters.params;
}
return null;
}
function isTypeAlias(node) {
return node.type === "TSTypeAliasDeclaration" || node.type === "TypeAlias";
}
function hasComplexTypeAnnotation(node) {
if (node.type !== "VariableDeclarator") {
return false;
}
const {
typeAnnotation
} = node.id;
if (!typeAnnotation || !typeAnnotation.typeAnnotation) {
return false;
}
const typeParams = getTypeParametersFromTypeReference(typeAnnotation.typeAnnotation);
return isNonEmptyArray$d(typeParams) && typeParams.length > 1 && typeParams.some(param => isNonEmptyArray$d(getTypeParametersFromTypeReference(param)) || param.type === "TSConditionalType");
}
function getTypeParametersFromTypeReference(node) {
if (isTypeReference(node) && node.typeParameters && node.typeParameters.params) {
return node.typeParameters.params;
}
return null;
}
function isTypeReference(node) {
return node.type === "TSTypeReference" || node.type === "GenericTypeAnnotation";
}
/**
* A chain with no calls at all or whose calls are all without arguments or with lone short arguments,
* excluding chains printed by `printMemberChain`
*/
function isPoorlyBreakableMemberOrCallChain(path, options, print, deep = false) {
const node = path.getValue();
const goDeeper = () => isPoorlyBreakableMemberOrCallChain(path, options, print, true);
if (node.type === "TSNonNullExpression") {
return path.call(goDeeper, "expression");
}
if (isCallExpression$4(node)) {
/** @type {any} TODO */
const doc = printCallExpression$1(path, options, print);
if (doc.label === "member-chain") {
return false;
}
const args = getCallArguments$1(node);
const isPoorlyBreakableCall = args.length === 0 || args.length === 1 && isLoneShortArgument(args[0], options);
if (!isPoorlyBreakableCall) {
return false;
}
if (isCallExpressionWithComplexTypeArguments(node, print)) {
return false;
}
return path.call(goDeeper, "callee");
}
if (isMemberExpression$3(node)) {
return path.call(goDeeper, "object");
}
return deep && (node.type === "Identifier" || node.type === "ThisExpression");
}
const LONE_SHORT_ARGUMENT_THRESHOLD_RATE = 0.25;
function isLoneShortArgument(node, {
printWidth
}) {
if (hasComment$a(node)) {
return false;
}
const threshold = printWidth * LONE_SHORT_ARGUMENT_THRESHOLD_RATE;
if (node.type === "ThisExpression" || node.type === "Identifier" && node.name.length <= threshold || isSignedNumericLiteral(node) && !hasComment$a(node.argument)) {
return true;
}
const regexpPattern = node.type === "Literal" && "regex" in node && node.regex.pattern || node.type === "RegExpLiteral" && node.pattern;
if (regexpPattern) {
return regexpPattern.length <= threshold;
}
if (isStringLiteral$1(node)) {
return rawText$3(node).length <= threshold;
}
if (node.type === "TemplateLiteral") {
return node.expressions.length === 0 && node.quasis[0].value.raw.length <= threshold && !node.quasis[0].value.raw.includes("\n");
}
return isLiteral$1(node);
}
function isObjectPropertyWithShortKey(node, keyDoc, options) {
if (!isObjectProperty(node)) {
return false;
} // TODO: for performance, it might make sense to use a more lightweight
// version of cleanDoc, such that it would stop once it detects that
// the doc can't be reduced to a string.
keyDoc = cleanDoc$1(keyDoc);
const MIN_OVERLAP_FOR_BREAK = 3; // ↓↓ - insufficient overlap for a line break
// key1: longValue1,
// ↓↓↓↓↓↓ - overlap is long enough to break
// key2abcd:
// longValue2
return typeof keyDoc === "string" && getStringWidth$1(keyDoc) < options.tabWidth + MIN_OVERLAP_FOR_BREAK;
}
function isCallExpressionWithComplexTypeArguments(node, print) {
const typeArgs = getTypeArgumentsFromCallExpression(node);
if (isNonEmptyArray$d(typeArgs)) {
if (typeArgs.length > 1) {
return true;
}
if (typeArgs.length === 1) {
const firstArg = typeArgs[0];
if (firstArg.type === "TSUnionType" || firstArg.type === "UnionTypeAnnotation" || firstArg.type === "TSIntersectionType" || firstArg.type === "IntersectionTypeAnnotation") {
return true;
}
}
const typeArgsKeyName = node.typeParameters ? "typeParameters" : "typeArguments";
if (willBreak$2(print(typeArgsKeyName))) {
return true;
}
}
return false;
}
function getTypeArgumentsFromCallExpression(node) {
return node.typeParameters && node.typeParameters.params || node.typeArguments && node.typeArguments.params;
}
var assignment = {
printVariableDeclarator: printVariableDeclarator$1,
printAssignmentExpression: printAssignmentExpression$1,
printAssignment: printAssignment$3
};
const {
getNextNonSpaceNonCommentCharacter
} = util$5;
const {
printDanglingComments: printDanglingComments$a
} = comments$1;
const {
builders: {
line: line$p,
hardline: hardline$s,
softline: softline$l,
group: group$r,
indent: indent$l,
ifBreak: ifBreak$i
},
utils: {
removeLines: removeLines$2,
willBreak: willBreak$1
}
} = doc;
const {
getFunctionParameters: getFunctionParameters$2,
iterateFunctionParametersPath,
isSimpleType: isSimpleType$1,
isTestCall: isTestCall$1,
isTypeAnnotationAFunction,
isObjectType: isObjectType$1,
isObjectTypePropertyAFunction: isObjectTypePropertyAFunction$1,
hasRestParameter,
shouldPrintComma: shouldPrintComma$8,
hasComment: hasComment$9,
isNextLineEmpty: isNextLineEmpty$8
} = utils$5;
const {
locEnd: locEnd$m
} = loc$6;
const {
ArgExpansionBailout: ArgExpansionBailout$1
} = errors;
const {
printFunctionTypeParameters: printFunctionTypeParameters$1
} = misc$1;
function printFunctionParameters$3(path, print, options, expandArg, printTypeParams) {
const functionNode = path.getValue();
const parameters = getFunctionParameters$2(functionNode);
const typeParams = printTypeParams ? printFunctionTypeParameters$1(path, options, print) : "";
if (parameters.length === 0) {
return [typeParams, "(", printDanglingComments$a(path, options,
/* sameIndent */
true, comment => getNextNonSpaceNonCommentCharacter(options.originalText, comment, locEnd$m) === ")"), ")"];
}
const parent = path.getParentNode();
const isParametersInTestCall = isTestCall$1(parent);
const shouldHugParameters = shouldHugFunctionParameters$1(functionNode);
const printed = [];
iterateFunctionParametersPath(path, (parameterPath, index) => {
const isLastParameter = index === parameters.length - 1;
if (isLastParameter && functionNode.rest) {
printed.push("...");
}
printed.push(print());
if (isLastParameter) {
return;
}
printed.push(",");
if (isParametersInTestCall || shouldHugParameters) {
printed.push(" ");
} else if (isNextLineEmpty$8(parameters[index], options)) {
printed.push(hardline$s, hardline$s);
} else {
printed.push(line$p);
}
}); // 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 (expandArg) {
if (willBreak$1(typeParams) || willBreak$1(printed)) {
// Removing lines in this case leads to broken or ugly output
throw new ArgExpansionBailout$1();
}
return group$r([removeLines$2(typeParams), "(", removeLines$2(printed), ")"]);
} // Single object destructuring should hug
//
// function({
// a,
// b,
// c
// }) {}
const hasNotParameterDecorator = parameters.every(node => !node.decorators);
if (shouldHugParameters && hasNotParameterDecorator) {
return [typeParams, "(", ...printed, ")"];
} // don't break in specs, eg; `it("should maintain parens around done even when long", (done) => {})`
if (isParametersInTestCall) {
return [typeParams, "(", ...printed, ")"];
}
const isFlowShorthandWithOneArg = (isObjectTypePropertyAFunction$1(parent) || isTypeAnnotationAFunction(parent) || parent.type === "TypeAlias" || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType" || parent.type === "IntersectionTypeAnnotation" || parent.type === "FunctionTypeAnnotation" && parent.returnType === functionNode) && parameters.length === 1 && parameters[0].name === null && // `type q = (this: string) => void;`
functionNode.this !== parameters[0] && parameters[0].typeAnnotation && functionNode.typeParameters === null && isSimpleType$1(parameters[0].typeAnnotation) && !functionNode.rest;
if (isFlowShorthandWithOneArg) {
if (options.arrowParens === "always") {
return ["(", ...printed, ")"];
}
return printed;
}
return [typeParams, "(", indent$l([softline$l, ...printed]), ifBreak$i(!hasRestParameter(functionNode) && shouldPrintComma$8(options, "all") ? "," : ""), softline$l, ")"];
}
function shouldHugFunctionParameters$1(node) {
if (!node) {
return false;
}
const parameters = getFunctionParameters$2(node);
if (parameters.length !== 1) {
return false;
}
const [parameter] = parameters;
return !hasComment$9(parameter) && (parameter.type === "ObjectPattern" || parameter.type === "ArrayPattern" || parameter.type === "Identifier" && parameter.typeAnnotation && (parameter.typeAnnotation.type === "TypeAnnotation" || parameter.typeAnnotation.type === "TSTypeAnnotation") && isObjectType$1(parameter.typeAnnotation.typeAnnotation) || parameter.type === "FunctionTypeParam" && isObjectType$1(parameter.typeAnnotation) || parameter.type === "AssignmentPattern" && (parameter.left.type === "ObjectPattern" || parameter.left.type === "ArrayPattern") && (parameter.right.type === "Identifier" || parameter.right.type === "ObjectExpression" && parameter.right.properties.length === 0 || parameter.right.type === "ArrayExpression" && parameter.right.elements.length === 0));
}
function getReturnTypeNode(functionNode) {
let returnTypeNode;
if (functionNode.returnType) {
returnTypeNode = functionNode.returnType;
if (returnTypeNode.typeAnnotation) {
returnTypeNode = returnTypeNode.typeAnnotation;
}
} else if (functionNode.typeAnnotation) {
returnTypeNode = functionNode.typeAnnotation;
}
return returnTypeNode;
} // When parameters are grouped, the return type annotation breaks first.
function shouldGroupFunctionParameters$3(functionNode, returnTypeDoc) {
const returnTypeNode = getReturnTypeNode(functionNode);
if (!returnTypeNode) {
return false;
}
const typeParameters = functionNode.typeParameters && functionNode.typeParameters.params;
if (typeParameters) {
if (typeParameters.length > 1) {
return false;
}
if (typeParameters.length === 1) {
const typeParameter = typeParameters[0];
if (typeParameter.constraint || typeParameter.default) {
return false;
}
}
}
return getFunctionParameters$2(functionNode).length === 1 && (isObjectType$1(returnTypeNode) || willBreak$1(returnTypeDoc));
}
var functionParameters = {
printFunctionParameters: printFunctionParameters$3,
shouldHugFunctionParameters: shouldHugFunctionParameters$1,
shouldGroupFunctionParameters: shouldGroupFunctionParameters$3
};
const {
printComments: printComments$2,
printDanglingComments: printDanglingComments$9
} = comments$1;
const {
getLast: getLast$6
} = util$5;
const {
builders: {
group: group$q,
join: join$l,
line: line$o,
softline: softline$k,
indent: indent$k,
align: align$3,
ifBreak: ifBreak$h
}
} = doc;
const {
locStart: locStart$n
} = loc$6;
const {
isSimpleType,
isObjectType,
hasLeadingOwnLineComment: hasLeadingOwnLineComment$1,
isObjectTypePropertyAFunction,
shouldPrintComma: shouldPrintComma$7
} = utils$5;
const {
printAssignment: printAssignment$2
} = assignment;
const {
printFunctionParameters: printFunctionParameters$2,
shouldGroupFunctionParameters: shouldGroupFunctionParameters$2
} = functionParameters;
const {
printArrayItems: printArrayItems$2
} = array;
function shouldHugType$2(node) {
if (isSimpleType(node) || isObjectType(node)) {
return true;
}
if (node.type === "UnionTypeAnnotation" || node.type === "TSUnionType") {
const voidCount = node.types.filter(node => node.type === "VoidTypeAnnotation" || node.type === "TSVoidKeyword" || node.type === "NullLiteralTypeAnnotation" || node.type === "TSNullKeyword").length;
const hasObject = node.types.some(node => node.type === "ObjectTypeAnnotation" || node.type === "TSTypeLiteral" || // This is a bit aggressive but captures Array<{x}>
node.type === "GenericTypeAnnotation" || node.type === "TSTypeReference");
if (node.types.length - 1 === voidCount && hasObject) {
return true;
}
}
return false;
}
function printOpaqueType$1(path, options, print) {
const semi = options.semi ? ";" : "";
const node = path.getValue();
const parts = [];
parts.push("opaque type ", print("id"), print("typeParameters"));
if (node.supertype) {
parts.push(": ", print("supertype"));
}
if (node.impltype) {
parts.push(" = ", print("impltype"));
}
parts.push(semi);
return parts;
}
function printTypeAlias$2(path, options, print) {
const semi = options.semi ? ";" : "";
const node = path.getValue();
const parts = [];
if (node.declare) {
parts.push("declare ");
}
parts.push("type ", print("id"), print("typeParameters"));
const rightPropertyName = node.type === "TSTypeAliasDeclaration" ? "typeAnnotation" : "right";
return [printAssignment$2(path, options, print, parts, " =", rightPropertyName), semi];
} // `TSIntersectionType` and `IntersectionTypeAnnotation`
function printIntersectionType$2(path, options, print) {
const node = path.getValue();
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(node.types[i - 1]) && isObjectType(node.types[i])) {
// If both are objects, don't indent
result.push([" & ", wasIndented ? indent$k(types[i]) : types[i]]);
} else if (!isObjectType(node.types[i - 1]) && !isObjectType(node.types[i])) {
// If no object is involved, go to the next line if it breaks
result.push(indent$k([" &", line$o, 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$k(types[i]) : types[i]);
}
}
return group$q(result);
} // `TSUnionType` and `UnionTypeAnnotation`
function printUnionType$2(path, options, print) {
const node = path.getValue(); // 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 && path.getParentNode(1).this !== parent) && !((parent.type === "TypeAlias" || parent.type === "VariableDeclarator" || parent.type === "TSTypeAliasDeclaration") && hasLeadingOwnLineComment$1(options.originalText, node)); // {
// a: string
// } | null | void
// should be inlined and not be printed in the multi-line variant
const shouldHug = shouldHugType$2(node); // We want to align the children but without its comment, so it looks like
// | child1
// // comment
// | child2
const printed = path.map(typePath => {
let printedType = print();
if (!shouldHug) {
printedType = align$3(2, printedType);
}
return printComments$2(typePath, printedType, options);
}, "types");
if (shouldHug) {
return join$l(" | ", printed);
}
const shouldAddStartLine = shouldIndent && !hasLeadingOwnLineComment$1(options.originalText, node);
const code = [ifBreak$h([shouldAddStartLine ? line$o : "", "| "]), join$l([line$o, "| "], printed)];
if (needsParens_1(path, options)) {
return group$q([indent$k(code), softline$k]);
}
if (parent.type === "TupleTypeAnnotation" && parent.types.length > 1 || parent.type === "TSTupleType" && parent.elementTypes.length > 1) {
return group$q([indent$k([ifBreak$h(["(", softline$k]), code]), softline$k, ifBreak$h(")")]);
}
return group$q(shouldIndent ? indent$k(code) : code);
} // `TSFunctionType` and `FunctionTypeAnnotation`
function printFunctionType$2(path, options, print) {
const node = path.getValue();
const parts = []; // 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 = node.type === "TSFunctionType" || !((parent.type === "ObjectTypeProperty" || parent.type === "ObjectTypeInternalSlot") && !parent.variance && !parent.optional && locStart$n(parent) === locStart$n(node) || parent.type === "ObjectTypeCallProperty" || parentParentParent && parentParentParent.type === "DeclareFunction");
let needsColon = isArrowFunctionTypeAnnotation && (parent.type === "TypeAnnotation" || parent.type === "TSTypeAnnotation"); // Sadly we can't put it inside of AstPath::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(parent)) {
isArrowFunctionTypeAnnotation = true;
needsColon = true;
}
if (needsParens) {
parts.push("(");
}
const parametersDoc = printFunctionParameters$2(path, print, options,
/* expandArg */
false,
/* printTypeParams */
true); // The returnType is not wrapped in a TypeAnnotation, so the colon
// needs to be added separately.
const returnTypeDoc = node.returnType || node.predicate || node.typeAnnotation ? [isArrowFunctionTypeAnnotation ? " => " : ": ", print("returnType"), print("predicate"), print("typeAnnotation")] : "";
const shouldGroupParameters = shouldGroupFunctionParameters$2(node, returnTypeDoc);
parts.push(shouldGroupParameters ? group$q(parametersDoc) : parametersDoc);
if (returnTypeDoc) {
parts.push(returnTypeDoc);
}
if (needsParens) {
parts.push(")");
}
return group$q(parts);
} // `TSTupleType` and `TupleTypeAnnotation`
function printTupleType$2(path, options, print) {
const node = path.getValue();
const typesField = node.type === "TSTupleType" ? "elementTypes" : "types";
const hasRest = node[typesField].length > 0 && getLast$6(node[typesField]).type === "TSRestType";
return group$q(["[", indent$k([softline$k, printArrayItems$2(path, options, typesField, print)]), ifBreak$h(shouldPrintComma$7(options, "all") && !hasRest ? "," : ""), printDanglingComments$9(path, options,
/* sameIndent */
true), softline$k, "]"]);
} // `TSIndexedAccessType`, `IndexedAccessType`, and `OptionalIndexedAccessType`
function printIndexedAccessType$2(path, options, print) {
const node = path.getValue();
const leftDelimiter = node.type === "OptionalIndexedAccessType" && node.optional ? "?.[" : "[";
return [print("objectType"), leftDelimiter, print("indexType"), "]"];
}
var typeAnnotation = {
printOpaqueType: printOpaqueType$1,
printTypeAlias: printTypeAlias$2,
printIntersectionType: printIntersectionType$2,
printUnionType: printUnionType$2,
printFunctionType: printFunctionType$2,
printTupleType: printTupleType$2,
printIndexedAccessType: printIndexedAccessType$2,
shouldHugType: shouldHugType$2
};
const {
printDanglingComments: printDanglingComments$8
} = comments$1;
const {
builders: {
join: join$k,
line: line$n,
hardline: hardline$r,
softline: softline$j,
group: group$p,
indent: indent$j,
ifBreak: ifBreak$g
}
} = doc;
const {
isTestCall,
hasComment: hasComment$8,
CommentCheckFlags: CommentCheckFlags$8,
isTSXFile,
shouldPrintComma: shouldPrintComma$6,
getFunctionParameters: getFunctionParameters$1
} = utils$5;
const {
createGroupIdMapper: createGroupIdMapper$1
} = util$5;
const {
shouldHugType: shouldHugType$1
} = typeAnnotation;
const getTypeParametersGroupId$2 = createGroupIdMapper$1("typeParameters");
function printTypeParameters$2(path, options, print, paramsKey) {
const node = path.getValue();
if (!node[paramsKey]) {
return "";
} // for TypeParameterDeclaration typeParameters is a single node
if (!Array.isArray(node[paramsKey])) {
return print(paramsKey);
}
const grandparent = path.getNode(2);
const isParameterInTestCall = grandparent && isTestCall(grandparent);
const shouldInline = isParameterInTestCall || node[paramsKey].length === 0 || node[paramsKey].length === 1 && (shouldHugType$1(node[paramsKey][0]) || node[paramsKey][0].type === "NullableTypeAnnotation");
if (shouldInline) {
return ["<", join$k(", ", path.map(print, paramsKey)), printDanglingCommentsForInline(path, options), ">"];
} // 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 trailingComma = node.type === "TSTypeParameterInstantiation" // https://github.com/microsoft/TypeScript/issues/21984
? "" : getFunctionParameters$1(node).length === 1 && isTSXFile(options) && !node[paramsKey][0].constraint && path.getParentNode().type === "ArrowFunctionExpression" ? "," : shouldPrintComma$6(options, "all") ? ifBreak$g(",") : "";
return group$p(["<", indent$j([softline$j, join$k([",", line$n], path.map(print, paramsKey))]), trailingComma, softline$j, ">"], {
id: getTypeParametersGroupId$2(node)
});
}
function printDanglingCommentsForInline(path, options) {
const node = path.getValue();
if (!hasComment$8(node, CommentCheckFlags$8.Dangling)) {
return "";
}
const hasOnlyBlockComments = !hasComment$8(node, CommentCheckFlags$8.Line);
const printed = printDanglingComments$8(path, options,
/* sameIndent */
hasOnlyBlockComments);
if (hasOnlyBlockComments) {
return printed;
}
return [printed, hardline$r];
}
function printTypeParameter$2(path, options, print) {
const node = path.getValue();
const parts = [];
const parent = path.getParentNode();
if (parent.type === "TSMappedType") {
parts.push("[", print("name"));
if (node.constraint) {
parts.push(" in ", print("constraint"));
}
if (parent.nameType) {
parts.push(" as ", path.callParent(() => print("nameType")));
}
parts.push("]");
return parts;
}
if (node.variance) {
parts.push(print("variance"));
}
parts.push(print("name"));
if (node.bound) {
parts.push(": ", print("bound"));
}
if (node.constraint) {
parts.push(" extends ", print("constraint"));
}
if (node.default) {
parts.push(" = ", print("default"));
}
return parts;
}
var typeParameters = {
printTypeParameter: printTypeParameter$2,
printTypeParameters: printTypeParameters$2,
getTypeParametersGroupId: getTypeParametersGroupId$2
};
const {
printComments: printComments$1
} = comments$1;
const {
printString: printString$3,
printNumber: printNumber$3
} = util$5;
const {
isNumericLiteral,
isSimpleNumber,
isStringLiteral,
isStringPropSafeToUnquote,
rawText: rawText$2
} = utils$5;
const {
printAssignment: printAssignment$1
} = assignment;
const needsQuoteProps = new WeakMap();
function printPropertyKey$4(path, options, print) {
const node = path.getNode();
if (node.computed) {
return ["[", print("key"), "]"];
}
const parent = path.getParentNode();
const {
key
} = node; // flow has `Identifier` key, other parsers use `PrivateIdentifier` (ESTree) or `PrivateName`
if (node.type === "ClassPrivateProperty" && key.type === "Identifier") {
return ["#", print("key")];
}
if (options.quoteProps === "consistent" && !needsQuoteProps.has(parent)) {
const objectHasStringProp = (parent.properties || parent.body || parent.members).some(prop => !prop.computed && prop.key && isStringLiteral(prop.key) && !isStringPropSafeToUnquote(prop, options));
needsQuoteProps.set(parent, objectHasStringProp);
}
if ((key.type === "Identifier" || isNumericLiteral(key) && isSimpleNumber(printNumber$3(rawText$2(key))) && // Avoid converting 999999999999999999999 to 1e+21, 0.99999999999999999 to 1 and 1.0 to 1.
String(key.value) === printNumber$3(rawText$2(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$3(JSON.stringify(key.type === "Identifier" ? key.name : key.value.toString()), options);
return path.call(keyPath => printComments$1(keyPath, prop, options), "key");
}
if (isStringPropSafeToUnquote(node, options) && (options.quoteProps === "as-needed" || options.quoteProps === "consistent" && !needsQuoteProps.get(parent))) {
// 'a' -> a
// '1' -> 1
// '1.5' -> 1.5
return path.call(keyPath => printComments$1(keyPath, /^\d/.test(key.value) ? printNumber$3(key.value) : key.value, options), "key");
}
return print("key");
}
function printProperty$1(path, options, print) {
const node = path.getValue();
if (node.shorthand) {
return print("value");
}
return printAssignment$1(path, options, print, printPropertyKey$4(path, options, print), ":", "value");
}
var property = {
printProperty: printProperty$1,
printPropertyKey: printPropertyKey$4
};
/** @typedef {import("../../document/doc-builders").Doc} Doc */
const {
printDanglingComments: printDanglingComments$7,
printCommentsSeparately
} = comments$1;
const {
getNextNonSpaceNonCommentCharacterIndex
} = util$5;
const {
builders: {
line: line$m,
softline: softline$i,
group: group$o,
indent: indent$i,
ifBreak: ifBreak$f,
hardline: hardline$q,
join: join$j,
indentIfBreak: indentIfBreak$1
},
utils: {
removeLines: removeLines$1,
willBreak
}
} = doc;
const {
ArgExpansionBailout
} = errors;
const {
getFunctionParameters,
hasLeadingOwnLineComment,
isFlowAnnotationComment,
isJsxNode: isJsxNode$2,
isTemplateOnItsOwnLine,
shouldPrintComma: shouldPrintComma$5,
startsWithNoLookaheadToken,
isBinaryish,
isLineComment: isLineComment$2,
hasComment: hasComment$7,
getComments: getComments$2,
CommentCheckFlags: CommentCheckFlags$7,
isCallLikeExpression,
isCallExpression: isCallExpression$3,
getCallArguments,
hasNakedLeftSide: hasNakedLeftSide$1,
getLeftSide
} = utils$5;
const {
locEnd: locEnd$l
} = loc$6;
const {
printFunctionParameters: printFunctionParameters$1,
shouldGroupFunctionParameters: shouldGroupFunctionParameters$1
} = functionParameters;
const {
printPropertyKey: printPropertyKey$3
} = property;
const {
printFunctionTypeParameters
} = misc$1;
function printFunction$2(path, print, options, args) {
const node = path.getValue();
let expandArg = false;
if ((node.type === "FunctionDeclaration" || node.type === "FunctionExpression") && args && args.expandLastArg) {
const parent = path.getParentNode();
if (isCallExpression$3(parent) && getCallArguments(parent).length > 1) {
expandArg = true;
}
}
const parts = []; // For TypeScript the TSDeclareFunction node shares the AST
// structure with FunctionDeclaration
if (node.type === "TSDeclareFunction" && node.declare) {
parts.push("declare ");
}
if (node.async) {
parts.push("async ");
}
if (node.generator) {
parts.push("function* ");
} else {
parts.push("function ");
}
if (node.id) {
parts.push(print("id"));
}
const parametersDoc = printFunctionParameters$1(path, print, options, expandArg);
const returnTypeDoc = printReturnType(path, print, options);
const shouldGroupParameters = shouldGroupFunctionParameters$1(node, returnTypeDoc);
parts.push(printFunctionTypeParameters(path, options, print), group$o([shouldGroupParameters ? group$o(parametersDoc) : parametersDoc, returnTypeDoc]), node.body ? " " : "", print("body"));
if (options.semi && (node.declare || !node.body)) {
parts.push(";");
}
return parts;
}
function printMethod$2(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 ");
}
} else {
assert__default['default'].ok(kind === "get" || kind === "set");
parts.push(kind, " ");
} // A `getter`/`setter` can't be a generator, but it's recoverable
if (value.generator) {
parts.push("*");
}
parts.push(printPropertyKey$3(path, options, print), node.optional || node.key.optional ? "?" : "");
if (node === value) {
parts.push(printMethodInternal$1(path, options, print));
} else if (value.type === "FunctionExpression") {
parts.push(path.call(path => printMethodInternal$1(path, options, print), "value"));
} else {
parts.push(print("value"));
}
return parts;
}
function printMethodInternal$1(path, options, print) {
const node = path.getNode();
const parametersDoc = printFunctionParameters$1(path, print, options);
const returnTypeDoc = printReturnType(path, print, options);
const shouldGroupParameters = shouldGroupFunctionParameters$1(node, returnTypeDoc);
const parts = [printFunctionTypeParameters(path, options, print), group$o([shouldGroupParameters ? group$o(parametersDoc) : parametersDoc, returnTypeDoc])];
if (node.body) {
parts.push(" ", print("body"));
} else {
parts.push(options.semi ? ";" : "");
}
return parts;
}
function printArrowFunctionSignature(path, options, print, args) {
const node = path.getValue();
const parts = [];
if (node.async) {
parts.push("async ");
}
if (shouldPrintParamsWithoutParens$1(path, options)) {
parts.push(print(["params", 0]));
} else {
const expandArg = args && (args.expandLastArg || args.expandFirstArg);
let returnTypeDoc = printReturnType(path, print, options);
if (expandArg) {
if (willBreak(returnTypeDoc)) {
throw new ArgExpansionBailout();
}
returnTypeDoc = group$o(removeLines$1(returnTypeDoc));
}
parts.push(group$o([printFunctionParameters$1(path, print, options, expandArg,
/* printTypeParams */
true), returnTypeDoc]));
}
const dangling = printDanglingComments$7(path, options,
/* sameIndent */
true, comment => {
const nextCharacter = getNextNonSpaceNonCommentCharacterIndex(options.originalText, comment, locEnd$l);
return nextCharacter !== false && options.originalText.slice(nextCharacter, nextCharacter + 2) === "=>";
});
if (dangling) {
parts.push(" ", dangling);
}
return parts;
}
function printArrowChain(path, args, signatures, shouldBreak, bodyDoc, tailNode) {
const name = path.getName();
const parent = path.getParentNode();
const isCallee = isCallLikeExpression(parent) && name === "callee";
const isAssignmentRhs = Boolean(args && args.assignmentLayout);
const shouldPutBodyOnSeparateLine = tailNode.body.type !== "BlockStatement" && tailNode.body.type !== "ObjectExpression";
const shouldBreakBeforeChain = isCallee && shouldPutBodyOnSeparateLine || args && args.assignmentLayout === "chain-tail-arrow-chain";
const groupId = Symbol("arrow-chain");
return group$o([group$o(indent$i([isCallee || isAssignmentRhs ? softline$i : "", group$o(join$j([" =>", line$m], signatures), {
shouldBreak
})]), {
id: groupId,
shouldBreak: shouldBreakBeforeChain
}), " =>", indentIfBreak$1(shouldPutBodyOnSeparateLine ? indent$i([line$m, bodyDoc]) : [" ", bodyDoc], {
groupId
}), isCallee ? ifBreak$f(softline$i, "", {
groupId
}) : ""]);
}
function printArrowFunction$1(path, options, print, args) {
let node = path.getValue();
/** @type {Doc[]} */
const signatures = [];
const body = [];
let chainShouldBreak = false;
(function rec() {
const doc = printArrowFunctionSignature(path, options, print, args);
if (signatures.length === 0) {
signatures.push(doc);
} else {
const {
leading,
trailing
} = printCommentsSeparately(path, options);
signatures.push([leading, doc]);
body.unshift(trailing);
}
chainShouldBreak = chainShouldBreak || node.returnType && getFunctionParameters(node).length > 0 || node.typeParameters || getFunctionParameters(node).some(param => param.type !== "Identifier");
if (node.body.type !== "ArrowFunctionExpression" || args && args.expandLastArg) {
body.unshift(print("body", args));
} else {
node = node.body;
path.call(rec, "body");
}
})();
if (signatures.length > 1) {
return printArrowChain(path, args, signatures, chainShouldBreak, body, node);
}
const parts = signatures;
parts.push(" =>"); // We want to always keep these types of nodes on the same line
// as the arrow.
if (!hasLeadingOwnLineComment(options.originalText, node.body) && (node.body.type === "ArrayExpression" || node.body.type === "ObjectExpression" || node.body.type === "BlockStatement" || isJsxNode$2(node.body) || isTemplateOnItsOwnLine(node.body, options.originalText) || node.body.type === "ArrowFunctionExpression" || node.body.type === "DoExpression")) {
return group$o([...parts, " ", body]);
} // We handle sequence expressions as the body of arrows specially,
// so that the required parentheses end up on their own lines.
if (node.body.type === "SequenceExpression") {
return group$o([...parts, group$o([" (", indent$i([softline$i, body]), softline$i, ")"])]);
} // if the arrow function is expanded as last argument, we are adding a
// level of indentation and need to add a softline to align the closing )
// with the opening (, or if it's inside a JSXExpression (e.g. an attribute)
// we should align the expression's closing } with the line with the opening {.
const shouldAddSoftLine = (args && args.expandLastArg || path.getParentNode().type === "JSXExpressionContainer") && !hasComment$7(node);
const printTrailingComma = args && args.expandLastArg && shouldPrintComma$5(options, "all"); // In order to avoid confusion between
// a => a ? a : a
// a <= a ? a : a
const shouldAddParens = node.body.type === "ConditionalExpression" && !startsWithNoLookaheadToken(node.body,
/* forbidFunctionAndClass */
false);
return group$o([...parts, group$o([indent$i([line$m, shouldAddParens ? ifBreak$f("", "(") : "", body, shouldAddParens ? ifBreak$f("", ")") : ""]), shouldAddSoftLine ? [ifBreak$f(printTrailingComma ? "," : ""), softline$i] : ""])]);
}
function canPrintParamsWithoutParens(node) {
const parameters = getFunctionParameters(node);
return parameters.length === 1 && !node.typeParameters && !hasComment$7(node, CommentCheckFlags$7.Dangling) && parameters[0].type === "Identifier" && !parameters[0].typeAnnotation && !hasComment$7(parameters[0]) && !parameters[0].optional && !node.predicate && !node.returnType;
}
function shouldPrintParamsWithoutParens$1(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;
}
/** @returns {Doc} */
function printReturnType(path, print, options) {
const node = path.getValue();
const returnType = print("returnType");
if (node.returnType && isFlowAnnotationComment(options.originalText, node.returnType)) {
return [" /*: ", returnType, " */"];
}
const parts = [returnType]; // prepend colon to TypeScript type annotation
if (node.returnType && node.returnType.typeAnnotation) {
parts.unshift(": ");
}
if (node.predicate) {
// The return type will already add the colon, but otherwise we
// need to do it ourselves
parts.push(node.returnType ? " " : ": ", print("predicate"));
}
return parts;
} // `ReturnStatement` and `ThrowStatement`
function printReturnOrThrowArgument(path, options, print) {
const node = path.getValue();
const semi = options.semi ? ";" : "";
const parts = [];
if (node.argument) {
if (returnArgumentHasLeadingComment(options, node.argument)) {
parts.push([" (", indent$i([hardline$q, print("argument")]), hardline$q, ")"]);
} else if (isBinaryish(node.argument) || node.argument.type === "SequenceExpression") {
parts.push(group$o([ifBreak$f(" (", " "), indent$i([softline$i, print("argument")]), softline$i, ifBreak$f(")")]));
} else {
parts.push(" ", print("argument"));
}
}
const comments = getComments$2(node);
const lastComment = getLast_1(comments);
const isLastCommentLine = lastComment && isLineComment$2(lastComment);
if (isLastCommentLine) {
parts.push(semi);
}
if (hasComment$7(node, CommentCheckFlags$7.Dangling)) {
parts.push(" ", printDanglingComments$7(path, options,
/* sameIndent */
true));
}
if (!isLastCommentLine) {
parts.push(semi);
}
return parts;
}
function printReturnStatement$1(path, options, print) {
return ["return", printReturnOrThrowArgument(path, options, print)];
}
function printThrowStatement$1(path, options, print) {
return ["throw", printReturnOrThrowArgument(path, options, print)];
} // This recurses the return argument, looking for the first token
// (the leftmost leaf node) and, if it (or its parents) has any
// leadingComments, returns true (so it can be wrapped in parens).
function returnArgumentHasLeadingComment(options, argument) {
if (hasLeadingOwnLineComment(options.originalText, argument)) {
return true;
}
if (hasNakedLeftSide$1(argument)) {
let leftMost = argument;
let newLeftMost;
while (newLeftMost = getLeftSide(leftMost)) {
leftMost = newLeftMost;
if (hasLeadingOwnLineComment(options.originalText, leftMost)) {
return true;
}
}
}
return false;
}
var _function = {
printFunction: printFunction$2,
printArrowFunction: printArrowFunction$1,
printMethod: printMethod$2,
printReturnStatement: printReturnStatement$1,
printThrowStatement: printThrowStatement$1,
printMethodInternal: printMethodInternal$1,
shouldPrintParamsWithoutParens: shouldPrintParamsWithoutParens$1
};
const {
isNonEmptyArray: isNonEmptyArray$c,
hasNewline: hasNewline$4
} = util$5;
const {
builders: {
line: line$l,
hardline: hardline$p,
join: join$i,
breakParent: breakParent$7,
group: group$n
}
} = doc;
const {
locStart: locStart$m,
locEnd: locEnd$k
} = loc$6;
const {
getParentExportDeclaration: getParentExportDeclaration$1
} = utils$5;
function printClassMemberDecorators$1(path, options, print) {
const node = path.getValue();
return group$n([join$i(line$l, path.map(print, "decorators")), hasNewlineBetweenOrAfterDecorators(node, options) ? hardline$p : line$l]);
}
function printDecoratorsBeforeExport$1(path, options, print) {
// Export declarations are responsible for printing any decorators
// that logically apply to node.declaration.
return [join$i(hardline$p, path.map(print, "declaration", "decorators")), hardline$p];
}
function printDecorators$1(path, options, print) {
const node = path.getValue();
const {
decorators
} = node;
if (!isNonEmptyArray$c(decorators) || // If the parent node is an export declaration and the decorator
// was written before the export, the export will be responsible
// for printing the decorators.
hasDecoratorsBeforeExport$1(path.getParentNode())) {
return;
}
const shouldBreak = node.type === "ClassExpression" || node.type === "ClassDeclaration" || hasNewlineBetweenOrAfterDecorators(node, options);
return [getParentExportDeclaration$1(path) ? hardline$p : shouldBreak ? breakParent$7 : "", join$i(line$l, path.map(print, "decorators")), line$l];
}
function hasNewlineBetweenOrAfterDecorators(node, options) {
return node.decorators.some(decorator => hasNewline$4(options.originalText, locEnd$k(decorator)));
}
function hasDecoratorsBeforeExport$1(node) {
if (node.type !== "ExportDefaultDeclaration" && node.type !== "ExportNamedDeclaration" && node.type !== "DeclareExportDeclaration") {
return false;
}
const decorators = node.declaration && node.declaration.decorators;
return isNonEmptyArray$c(decorators) && locStart$m(node, {
ignoreDecorators: true
}) > locStart$m(decorators[0]);
}
var decorators = {
printDecorators: printDecorators$1,
printClassMemberDecorators: printClassMemberDecorators$1,
printDecoratorsBeforeExport: printDecoratorsBeforeExport$1,
hasDecoratorsBeforeExport: hasDecoratorsBeforeExport$1
};
const {
isNonEmptyArray: isNonEmptyArray$b,
createGroupIdMapper
} = util$5;
const {
printComments,
printDanglingComments: printDanglingComments$6
} = comments$1;
const {
builders: {
join: join$h,
line: line$k,
hardline: hardline$o,
softline: softline$h,
group: group$m,
indent: indent$h,
ifBreak: ifBreak$e
}
} = doc;
const {
hasComment: hasComment$6,
CommentCheckFlags: CommentCheckFlags$6
} = utils$5;
const {
getTypeParametersGroupId: getTypeParametersGroupId$1
} = typeParameters;
const {
printMethod: printMethod$1
} = _function;
const {
printOptionalToken: printOptionalToken$4,
printTypeAnnotation: printTypeAnnotation$3
} = misc$1;
const {
printPropertyKey: printPropertyKey$2
} = property;
const {
printAssignment
} = assignment;
const {
printClassMemberDecorators
} = decorators;
function printClass$2(path, options, print) {
const node = path.getValue();
const parts = [];
if (node.declare) {
parts.push("declare ");
}
if (node.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 = node.id && hasComment$6(node.id, CommentCheckFlags$6.Trailing) || node.superClass && hasComment$6(node.superClass) || isNonEmptyArray$b(node.extends) || // DeclareClass
isNonEmptyArray$b(node.mixins) || isNonEmptyArray$b(node.implements);
const partsGroup = [];
const extendsParts = [];
if (node.id) {
partsGroup.push(" ", print("id"));
}
partsGroup.push(print("typeParameters"));
if (node.superClass) {
const printed = ["extends ", printSuperClass(path, options, print), print("superTypeParameters")];
const printedWithComments = path.call(superClass => printComments(superClass, printed, options), "superClass");
if (groupMode) {
extendsParts.push(line$k, group$m(printedWithComments));
} else {
extendsParts.push(" ", printedWithComments);
}
} else {
extendsParts.push(printList(path, options, print, "extends"));
}
extendsParts.push(printList(path, options, print, "mixins"), printList(path, options, print, "implements"));
if (groupMode) {
let printedPartsGroup;
if (shouldIndentOnlyHeritageClauses(node)) {
printedPartsGroup = [...partsGroup, indent$h(extendsParts)];
} else {
printedPartsGroup = indent$h([...partsGroup, extendsParts]);
}
parts.push(group$m(printedPartsGroup, {
id: getHeritageGroupId(node)
}));
} else {
parts.push(...partsGroup, ...extendsParts);
}
parts.push(" ", print("body"));
return parts;
}
const getHeritageGroupId = createGroupIdMapper("heritageGroup");
function printHardlineAfterHeritage$2(node) {
return ifBreak$e(hardline$o, "", {
groupId: getHeritageGroupId(node)
});
}
function hasMultipleHeritage(node) {
return ["superClass", "extends", "mixins", "implements"].filter(key => Boolean(node[key])).length > 1;
}
function shouldIndentOnlyHeritageClauses(node) {
return node.typeParameters && !hasComment$6(node.typeParameters, CommentCheckFlags$6.Trailing | CommentCheckFlags$6.Line) && !hasMultipleHeritage(node);
}
function printList(path, options, print, listName) {
const node = path.getValue();
if (!isNonEmptyArray$b(node[listName])) {
return "";
}
const printedLeadingComments = printDanglingComments$6(path, options,
/* sameIndent */
true, ({
marker
}) => marker === listName);
return [shouldIndentOnlyHeritageClauses(node) ? ifBreak$e(" ", line$k, {
groupId: getTypeParametersGroupId$1(node.typeParameters)
}) : line$k, printedLeadingComments, printedLeadingComments && hardline$o, listName, group$m(indent$h([line$k, join$h([",", line$k], path.map(print, listName))]))];
}
function printSuperClass(path, options, print) {
const printed = print("superClass");
const parent = path.getParentNode();
if (parent.type === "AssignmentExpression") {
return group$m(ifBreak$e(["(", indent$h([softline$h, printed]), softline$h, ")"], printed));
}
return printed;
}
function printClassMethod$2(path, options, print) {
const node = path.getValue();
const parts = [];
if (isNonEmptyArray$b(node.decorators)) {
parts.push(printClassMemberDecorators(path, options, print));
}
if (node.accessibility) {
parts.push(node.accessibility + " ");
} // "readonly" and "declare" are supported by only "babel-ts"
// https://github.com/prettier/prettier/issues/9760
if (node.readonly) {
parts.push("readonly ");
}
if (node.declare) {
parts.push("declare ");
}
if (node.static) {
parts.push("static ");
}
if (node.type === "TSAbstractMethodDefinition" || node.abstract) {
parts.push("abstract ");
}
if (node.override) {
parts.push("override ");
}
parts.push(printMethod$1(path, options, print));
return parts;
}
function printClassProperty$2(path, options, print) {
const node = path.getValue();
const parts = [];
const semi = options.semi ? ";" : "";
if (isNonEmptyArray$b(node.decorators)) {
parts.push(printClassMemberDecorators(path, options, print));
}
if (node.accessibility) {
parts.push(node.accessibility + " ");
}
if (node.declare) {
parts.push("declare ");
}
if (node.static) {
parts.push("static ");
}
if (node.type === "TSAbstractClassProperty" || node.abstract) {
parts.push("abstract ");
}
if (node.override) {
parts.push("override ");
}
if (node.readonly) {
parts.push("readonly ");
}
if (node.variance) {
parts.push(print("variance"));
}
parts.push(printPropertyKey$2(path, options, print), printOptionalToken$4(path), printTypeAnnotation$3(path, options, print));
return [printAssignment(path, options, print, parts, " =", "value"), semi];
}
var _class = {
printClass: printClass$2,
printClassMethod: printClassMethod$2,
printClassProperty: printClassProperty$2,
printHardlineAfterHeritage: printHardlineAfterHeritage$2
};
const {
isNonEmptyArray: isNonEmptyArray$a
} = util$5;
const {
builders: {
join: join$g,
line: line$j,
group: group$l,
indent: indent$g,
ifBreak: ifBreak$d
}
} = doc;
const {
hasComment: hasComment$5,
identity,
CommentCheckFlags: CommentCheckFlags$5
} = utils$5;
const {
getTypeParametersGroupId
} = typeParameters;
const {
printTypeScriptModifiers: printTypeScriptModifiers$1
} = misc$1;
function printInterface$2(path, options, print) {
const node = path.getValue();
const parts = [];
if (node.declare) {
parts.push("declare ");
}
if (node.type === "TSInterfaceDeclaration") {
parts.push(node.abstract ? "abstract " : "", printTypeScriptModifiers$1(path, options, print));
}
parts.push("interface");
const partsGroup = [];
const extendsParts = [];
if (node.type !== "InterfaceTypeAnnotation") {
partsGroup.push(" ", print("id"), print("typeParameters"));
}
const shouldIndentOnlyHeritageClauses = node.typeParameters && !hasComment$5(node.typeParameters, CommentCheckFlags$5.Trailing | CommentCheckFlags$5.Line);
if (isNonEmptyArray$a(node.extends)) {
extendsParts.push(shouldIndentOnlyHeritageClauses ? ifBreak$d(" ", line$j, {
groupId: getTypeParametersGroupId(node.typeParameters)
}) : line$j, "extends ", (node.extends.length === 1 ? identity : indent$g)(join$g([",", line$j], path.map(print, "extends"))));
}
if (node.id && hasComment$5(node.id, CommentCheckFlags$5.Trailing) || isNonEmptyArray$a(node.extends)) {
if (shouldIndentOnlyHeritageClauses) {
parts.push(group$l([...partsGroup, indent$g(extendsParts)]));
} else {
parts.push(group$l(indent$g([...partsGroup, ...extendsParts])));
}
} else {
parts.push(...partsGroup, ...extendsParts);
}
parts.push(" ", print("body"));
return group$l(parts);
}
var _interface = {
printInterface: printInterface$2
};
const {
isNonEmptyArray: isNonEmptyArray$9
} = util$5;
const {
builders: {
softline: softline$g,
group: group$k,
indent: indent$f,
join: join$f,
line: line$i,
ifBreak: ifBreak$c,
hardline: hardline$n
}
} = doc;
const {
printDanglingComments: printDanglingComments$5
} = comments$1;
const {
hasComment: hasComment$4,
CommentCheckFlags: CommentCheckFlags$4,
shouldPrintComma: shouldPrintComma$4,
needsHardlineAfterDanglingComment: needsHardlineAfterDanglingComment$1
} = utils$5;
const {
locStart: locStart$l,
hasSameLoc
} = loc$6;
const {
hasDecoratorsBeforeExport,
printDecoratorsBeforeExport
} = decorators;
/**
* @typedef {import("../../document").Doc} Doc
*/
function printImportDeclaration$1(path, options, print) {
const node = path.getValue();
const semi = options.semi ? ";" : "";
/** @type{Doc[]} */
const parts = [];
const {
importKind
} = node;
parts.push("import");
if (importKind && importKind !== "value") {
parts.push(" ", importKind);
}
parts.push(printModuleSpecifiers(path, options, print), printModuleSource(path, options, print), printImportAssertions(path, options, print), semi);
return parts;
}
function printExportDeclaration$2(path, options, print) {
const node = path.getValue();
/** @type{Doc[]} */
const parts = []; // Only print decorators here if they were written before the export,
// otherwise they are printed by the node.declaration
if (hasDecoratorsBeforeExport(node)) {
parts.push(printDecoratorsBeforeExport(path, options, print));
}
const {
type,
exportKind,
declaration
} = node;
parts.push("export");
const isDefaultExport = node.default || type === "ExportDefaultDeclaration";
if (isDefaultExport) {
parts.push(" default");
}
if (hasComment$4(node, CommentCheckFlags$4.Dangling)) {
parts.push(" ", printDanglingComments$5(path, options,
/* sameIndent */
true));
if (needsHardlineAfterDanglingComment$1(node)) {
parts.push(hardline$n);
}
}
if (declaration) {
parts.push(" ", print("declaration"));
} else {
parts.push(exportKind === "type" ? " type" : "", printModuleSpecifiers(path, options, print), printModuleSource(path, options, print), printImportAssertions(path, options, print));
}
if (shouldExportDeclarationPrintSemi(node, options)) {
parts.push(";");
}
return parts;
}
function printExportAllDeclaration$2(path, options, print) {
const node = path.getValue();
const semi = options.semi ? ";" : "";
/** @type{Doc[]} */
const parts = [];
const {
exportKind,
exported
} = node;
parts.push("export");
if (exportKind === "type") {
parts.push(" type");
}
parts.push(" *");
if (exported) {
parts.push(" as ", print("exported"));
}
parts.push(printModuleSource(path, options, print), printImportAssertions(path, options, print), semi);
return parts;
}
function shouldExportDeclarationPrintSemi(node, options) {
if (!options.semi) {
return false;
}
const {
type,
declaration
} = node;
const isDefaultExport = node.default || type === "ExportDefaultDeclaration";
if (!declaration) {
return true;
}
const {
type: declarationType
} = declaration;
if (isDefaultExport && declarationType !== "ClassDeclaration" && declarationType !== "FunctionDeclaration" && declarationType !== "TSInterfaceDeclaration" && declarationType !== "DeclareClass" && declarationType !== "DeclareFunction" && declarationType !== "TSDeclareFunction" && declarationType !== "EnumDeclaration") {
return true;
}
return false;
}
function printModuleSource(path, options, print) {
const node = path.getValue();
if (!node.source) {
return "";
}
/** @type{Doc[]} */
const parts = [];
if (!shouldNotPrintSpecifiers(node, options)) {
parts.push(" from");
}
parts.push(" ", print("source"));
return parts;
}
function printModuleSpecifiers(path, options, print) {
const node = path.getValue();
if (shouldNotPrintSpecifiers(node, options)) {
return "";
}
/** @type{Doc[]} */
const parts = [" "];
if (isNonEmptyArray$9(node.specifiers)) {
const standaloneSpecifiers = [];
const groupedSpecifiers = [];
path.each(() => {
const specifierType = path.getValue().type;
if (specifierType === "ExportNamespaceSpecifier" || specifierType === "ExportDefaultSpecifier" || specifierType === "ImportNamespaceSpecifier" || specifierType === "ImportDefaultSpecifier") {
standaloneSpecifiers.push(print());
} else if (specifierType === "ExportSpecifier" || specifierType === "ImportSpecifier") {
groupedSpecifiers.push(print());
} else {
/* istanbul ignore next */
throw new Error(`Unknown specifier type ${JSON.stringify(specifierType)}`);
}
}, "specifiers");
parts.push(join$f(", ", standaloneSpecifiers));
if (groupedSpecifiers.length > 0) {
if (standaloneSpecifiers.length > 0) {
parts.push(", ");
}
const canBreak = groupedSpecifiers.length > 1 || standaloneSpecifiers.length > 0 || node.specifiers.some(node => hasComment$4(node));
if (canBreak) {
parts.push(group$k(["{", indent$f([options.bracketSpacing ? line$i : softline$g, join$f([",", line$i], groupedSpecifiers)]), ifBreak$c(shouldPrintComma$4(options) ? "," : ""), options.bracketSpacing ? line$i : softline$g, "}"]));
} else {
parts.push(["{", options.bracketSpacing ? " " : "", ...groupedSpecifiers, options.bracketSpacing ? " " : "", "}"]);
}
}
} else {
parts.push("{}");
}
return parts;
}
function shouldNotPrintSpecifiers(node, options) {
const {
type,
importKind,
source,
specifiers
} = node;
if (type !== "ImportDeclaration" || isNonEmptyArray$9(specifiers) || importKind === "type") {
return false;
} // TODO: check tokens
return !/{\s*}/.test(options.originalText.slice(locStart$l(node), locStart$l(source)));
}
function printImportAssertions(path, options, print) {
const node = path.getNode();
if (isNonEmptyArray$9(node.assertions)) {
return [" assert {", options.bracketSpacing ? " " : "", join$f(", ", path.map(print, "assertions")), options.bracketSpacing ? " " : "", "}"];
}
return "";
}
function printModuleSpecifier$1(path, options, print) {
const node = path.getNode();
const {
type,
importKind
} = node;
/** @type{Doc[]} */
const parts = [];
if (type === "ImportSpecifier" && importKind) {
parts.push(importKind, " ");
}
const isImport = type.startsWith("Import");
const leftSideProperty = isImport ? "imported" : "local";
const rightSideProperty = isImport ? "local" : "exported";
let left = "";
let right = "";
if (type === "ExportNamespaceSpecifier" || type === "ImportNamespaceSpecifier") {
left = "*";
} else if (node[leftSideProperty]) {
left = print(leftSideProperty);
}
if (node[rightSideProperty] && (!node[leftSideProperty] || // import {a as a} from '.'
!hasSameLoc(node[leftSideProperty], node[rightSideProperty]))) {
right = print(rightSideProperty);
}
parts.push(left, left && right ? " as " : "", right);
return parts;
}
var module$1 = {
printImportDeclaration: printImportDeclaration$1,
printExportDeclaration: printExportDeclaration$2,
printExportAllDeclaration: printExportAllDeclaration$2,
printModuleSpecifier: printModuleSpecifier$1
};
const {
printDanglingComments: printDanglingComments$4
} = comments$1;
const {
builders: {
line: line$h,
softline: softline$f,
group: group$j,
indent: indent$e,
ifBreak: ifBreak$b,
hardline: hardline$m
}
} = doc;
const {
getLast: getLast$5,
hasNewlineInRange: hasNewlineInRange$2,
hasNewline: hasNewline$3,
isNonEmptyArray: isNonEmptyArray$8
} = util$5;
const {
shouldPrintComma: shouldPrintComma$3,
hasComment: hasComment$3,
getComments: getComments$1,
CommentCheckFlags: CommentCheckFlags$3,
isNextLineEmpty: isNextLineEmpty$7
} = utils$5;
const {
locStart: locStart$k,
locEnd: locEnd$j
} = loc$6;
const {
printOptionalToken: printOptionalToken$3,
printTypeAnnotation: printTypeAnnotation$2
} = misc$1;
const {
shouldHugFunctionParameters
} = functionParameters;
const {
shouldHugType
} = typeAnnotation;
const {
printHardlineAfterHeritage: printHardlineAfterHeritage$1
} = _class;
/** @typedef {import("../../document").Doc} Doc */
function printObject$3(path, options, print) {
const semi = options.semi ? ";" : "";
const node = path.getValue();
let propertiesField;
if (node.type === "TSTypeLiteral") {
propertiesField = "members";
} else if (node.type === "TSInterfaceBody") {
propertiesField = "body";
} else {
propertiesField = "properties";
}
const isTypeAnnotation = node.type === "ObjectTypeAnnotation";
const fields = [propertiesField];
if (isTypeAnnotation) {
fields.push("indexers", "callProperties", "internalSlots");
}
const firstProperty = fields.map(field => node[field][0]).sort((a, b) => locStart$k(a) - locStart$k(b))[0];
const parent = path.getParentNode(0);
const isFlowInterfaceLikeBody = isTypeAnnotation && parent && (parent.type === "InterfaceDeclaration" || parent.type === "DeclareInterface" || parent.type === "DeclareClass") && path.getName() === "body";
const shouldBreak = node.type === "TSInterfaceBody" || isFlowInterfaceLikeBody || node.type === "ObjectPattern" && parent.type !== "FunctionDeclaration" && parent.type !== "FunctionExpression" && parent.type !== "ArrowFunctionExpression" && parent.type !== "ObjectMethod" && parent.type !== "ClassMethod" && parent.type !== "ClassPrivateMethod" && parent.type !== "AssignmentPattern" && parent.type !== "CatchClause" && node.properties.some(property => property.value && (property.value.type === "ObjectPattern" || property.value.type === "ArrayPattern")) || node.type !== "ObjectPattern" && firstProperty && hasNewlineInRange$2(options.originalText, locStart$k(node), locStart$k(firstProperty));
const separator = isFlowInterfaceLikeBody ? ";" : node.type === "TSInterfaceBody" || node.type === "TSTypeLiteral" ? ifBreak$b(semi, ";") : ",";
const leftBrace = node.type === "RecordExpression" ? "#{" : node.exact ? "{|" : "{";
const rightBrace = node.exact ? "|}" : "}"; // Unfortunately, things are grouped together in the ast can be
// interleaved in the source code. So we need to reorder them before
// printing them.
const propsAndLoc = [];
for (const field of fields) {
path.each(childPath => {
const node = childPath.getValue();
propsAndLoc.push({
node,
printed: print(),
loc: locStart$k(node)
});
}, field);
}
if (fields.length > 1) {
propsAndLoc.sort((a, b) => a.loc - b.loc);
}
/** @type {Doc[]} */
let separatorParts = [];
const props = propsAndLoc.map(prop => {
const result = [...separatorParts, group$j(prop.printed)];
separatorParts = [separator, line$h];
if ((prop.node.type === "TSPropertySignature" || prop.node.type === "TSMethodSignature" || prop.node.type === "TSConstructSignatureDeclaration") && hasComment$3(prop.node, CommentCheckFlags$3.PrettierIgnore)) {
separatorParts.shift();
}
if (isNextLineEmpty$7(prop.node, options)) {
separatorParts.push(hardline$m);
}
return result;
});
if (node.inexact) {
let printed;
if (hasComment$3(node, CommentCheckFlags$3.Dangling)) {
const hasLineComments = hasComment$3(node, CommentCheckFlags$3.Line);
const printedDanglingComments = printDanglingComments$4(path, options,
/* sameIndent */
true);
printed = [printedDanglingComments, hasLineComments || hasNewline$3(options.originalText, locEnd$j(getLast$5(getComments$1(node)))) ? hardline$m : line$h, "..."];
} else {
printed = ["..."];
}
props.push([...separatorParts, ...printed]);
}
const lastElem = getLast$5(node[propertiesField]);
const canHaveTrailingSeparator = !(node.inexact || lastElem && lastElem.type === "RestElement" || lastElem && (lastElem.type === "TSPropertySignature" || lastElem.type === "TSCallSignatureDeclaration" || lastElem.type === "TSMethodSignature" || lastElem.type === "TSConstructSignatureDeclaration") && hasComment$3(lastElem, CommentCheckFlags$3.PrettierIgnore));
let content;
if (props.length === 0) {
if (!hasComment$3(node, CommentCheckFlags$3.Dangling)) {
return [leftBrace, rightBrace, printTypeAnnotation$2(path, options, print)];
}
content = group$j([leftBrace, printDanglingComments$4(path, options), softline$f, rightBrace, printOptionalToken$3(path), printTypeAnnotation$2(path, options, print)]);
} else {
content = [isFlowInterfaceLikeBody && isNonEmptyArray$8(node.properties) ? printHardlineAfterHeritage$1(parent) : "", leftBrace, indent$e([options.bracketSpacing ? line$h : softline$f, ...props]), ifBreak$b(canHaveTrailingSeparator && (separator !== "," || shouldPrintComma$3(options)) ? separator : ""), options.bracketSpacing ? line$h : softline$f, rightBrace, printOptionalToken$3(path), printTypeAnnotation$2(path, options, print)];
} // If we inline the object as first argument of the parent, we don't want
// to create another group so that the object breaks before the return
// type
if (path.match(node => node.type === "ObjectPattern" && !node.decorators, (node, name, number) => shouldHugFunctionParameters(node) && (name === "params" || name === "parameters" || name === "this" || name === "rest") && number === 0) || path.match(shouldHugType, (node, name) => name === "typeAnnotation", (node, name) => name === "typeAnnotation", (node, name, number) => shouldHugFunctionParameters(node) && (name === "params" || name === "parameters" || name === "this" || name === "rest") && number === 0) || !shouldBreak && path.match(node => node.type === "ObjectPattern", node => node.type === "AssignmentExpression" || node.type === "VariableDeclarator")) {
return content;
}
return group$j(content, {
shouldBreak
});
}
var object$1 = {
printObject: printObject$3
};
/** @typedef {import("../../document").Doc} Doc */
const {
printDanglingComments: printDanglingComments$3
} = comments$1;
const {
printString: printString$2,
printNumber: printNumber$2
} = util$5;
const {
builders: {
hardline: hardline$l,
softline: softline$e,
group: group$i,
indent: indent$d
}
} = doc;
const {
getParentExportDeclaration,
isFunctionNotation,
isGetterOrSetter,
rawText: rawText$1,
shouldPrintComma: shouldPrintComma$2
} = utils$5;
const {
locStart: locStart$j,
locEnd: locEnd$i
} = loc$6;
const {
printClass: printClass$1
} = _class;
const {
printOpaqueType,
printTypeAlias: printTypeAlias$1,
printIntersectionType: printIntersectionType$1,
printUnionType: printUnionType$1,
printFunctionType: printFunctionType$1,
printTupleType: printTupleType$1,
printIndexedAccessType: printIndexedAccessType$1
} = typeAnnotation;
const {
printInterface: printInterface$1
} = _interface;
const {
printTypeParameter: printTypeParameter$1,
printTypeParameters: printTypeParameters$1
} = typeParameters;
const {
printExportDeclaration: printExportDeclaration$1,
printExportAllDeclaration: printExportAllDeclaration$1
} = module$1;
const {
printArrayItems: printArrayItems$1
} = array;
const {
printObject: printObject$2
} = object$1;
const {
printPropertyKey: printPropertyKey$1
} = property;
const {
printOptionalToken: printOptionalToken$2,
printTypeAnnotation: printTypeAnnotation$1,
printRestSpread: printRestSpread$1
} = misc$1;
function printFlow$1(path, options, print) {
const node = path.getValue();
const semi = options.semi ? ";" : "";
/** @type{Doc[]} */
const parts = [];
switch (node.type) {
case "DeclareClass":
return printFlowDeclaration(path, printClass$1(path, options, print));
case "DeclareFunction":
return printFlowDeclaration(path, ["function ", print("id"), node.predicate ? " " : "", print("predicate"), semi]);
case "DeclareModule":
return printFlowDeclaration(path, ["module ", print("id"), " ", print("body")]);
case "DeclareModuleExports":
return printFlowDeclaration(path, ["module.exports", ": ", print("typeAnnotation"), semi]);
case "DeclareVariable":
return printFlowDeclaration(path, ["var ", print("id"), semi]);
case "DeclareOpaqueType":
return printFlowDeclaration(path, printOpaqueType(path, options, print));
case "DeclareInterface":
return printFlowDeclaration(path, printInterface$1(path, options, print));
case "DeclareTypeAlias":
return printFlowDeclaration(path, printTypeAlias$1(path, options, print));
case "DeclareExportDeclaration":
return printFlowDeclaration(path, printExportDeclaration$1(path, options, print));
case "DeclareExportAllDeclaration":
return printFlowDeclaration(path, printExportAllDeclaration$1(path, options, print));
case "OpaqueType":
return printOpaqueType(path, options, print);
case "TypeAlias":
return printTypeAlias$1(path, options, print);
case "IntersectionTypeAnnotation":
return printIntersectionType$1(path, options, print);
case "UnionTypeAnnotation":
return printUnionType$1(path, options, print);
case "FunctionTypeAnnotation":
return printFunctionType$1(path, options, print);
case "TupleTypeAnnotation":
return printTupleType$1(path, options, print);
case "GenericTypeAnnotation":
return [print("id"), printTypeParameters$1(path, options, print, "typeParameters")];
case "IndexedAccessType":
case "OptionalIndexedAccessType":
return printIndexedAccessType$1(path, options, print);
// Type Annotations for Facebook Flow, typically stripped out or
// transformed away before printing.
case "TypeAnnotation":
return print("typeAnnotation");
case "TypeParameter":
return printTypeParameter$1(path, options, print);
case "TypeofTypeAnnotation":
return ["typeof ", print("argument")];
case "ExistsTypeAnnotation":
return "*";
case "EmptyTypeAnnotation":
return "empty";
case "MixedTypeAnnotation":
return "mixed";
case "ArrayTypeAnnotation":
return [print("elementType"), "[]"];
case "BooleanLiteralTypeAnnotation":
return String(node.value);
case "EnumDeclaration":
return ["enum ", print("id"), " ", print("body")];
case "EnumBooleanBody":
case "EnumNumberBody":
case "EnumStringBody":
case "EnumSymbolBody":
{
if (node.type === "EnumSymbolBody" || node.explicitType) {
let type = null;
switch (node.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 (node.members.length === 0 && !node.hasUnknownMembers) {
parts.push(group$i(["{", printDanglingComments$3(path, options), softline$e, "}"]));
} else {
const members = node.members.length > 0 ? [hardline$l, printArrayItems$1(path, options, "members", print), node.hasUnknownMembers || shouldPrintComma$2(options) ? "," : ""] : [];
parts.push(group$i(["{", indent$d([...members, ...(node.hasUnknownMembers ? [hardline$l, "..."] : [])]), printDanglingComments$3(path, options,
/* sameIndent */
true), hardline$l, "}"]));
}
return parts;
}
case "EnumBooleanMember":
case "EnumNumberMember":
case "EnumStringMember":
return [print("id"), " = ", typeof node.init === "object" ? print("init") : String(node.init)];
case "EnumDefaultedMember":
return print("id");
case "FunctionTypeParam":
{
const name = node.name ? print("name") : path.getParentNode().this === node ? "this" : "";
return [name, printOptionalToken$2(path), name ? ": " : "", print("typeAnnotation")];
}
case "InterfaceDeclaration":
case "InterfaceTypeAnnotation":
return printInterface$1(path, options, print);
case "ClassImplements":
case "InterfaceExtends":
return [print("id"), print("typeParameters")];
case "NullableTypeAnnotation":
return ["?", print("typeAnnotation")];
case "Variance":
{
const {
kind
} = node;
assert__default['default'].ok(kind === "plus" || kind === "minus");
return kind === "plus" ? "+" : "-";
}
case "ObjectTypeCallProperty":
if (node.static) {
parts.push("static ");
}
parts.push(print("value"));
return parts;
case "ObjectTypeIndexer":
{
return [node.variance ? print("variance") : "", "[", print("id"), node.id ? ": " : "", print("key"), "]: ", print("value")];
}
case "ObjectTypeProperty":
{
let modifier = "";
if (node.proto) {
modifier = "proto ";
} else if (node.static) {
modifier = "static ";
}
return [modifier, isGetterOrSetter(node) ? node.kind + " " : "", node.variance ? print("variance") : "", printPropertyKey$1(path, options, print), printOptionalToken$2(path), isFunctionNotation(node) ? "" : ": ", print("value")];
}
case "ObjectTypeAnnotation":
return printObject$2(path, options, print);
case "ObjectTypeInternalSlot":
return [node.static ? "static " : "", "[[", print("id"), "]]", printOptionalToken$2(path), node.method ? "" : ": ", print("value")];
// Same as `RestElement`
case "ObjectTypeSpreadProperty":
return printRestSpread$1(path, options, print);
case "QualifiedTypeIdentifier":
return [print("qualification"), ".", print("id")];
case "StringLiteralTypeAnnotation":
return printString$2(rawText$1(node), options);
case "NumberLiteralTypeAnnotation":
assert__default['default'].strictEqual(typeof node.value, "number");
// fall through
case "BigIntLiteralTypeAnnotation":
if (node.extra) {
return printNumber$2(node.extra.raw);
}
return printNumber$2(node.raw);
case "TypeCastExpression":
{
return ["(", print("expression"), printTypeAnnotation$1(path, options, print), ")"];
}
case "TypeParameterDeclaration":
case "TypeParameterInstantiation":
{
const printed = printTypeParameters$1(path, options, print, "params");
if (options.parser === "flow") {
const start = locStart$j(node);
const end = locEnd$i(node);
const commentStartIndex = options.originalText.lastIndexOf("/*", start);
const commentEndIndex = options.originalText.indexOf("*/", end);
if (commentStartIndex !== -1 && commentEndIndex !== -1) {
const comment = options.originalText.slice(commentStartIndex + 2, commentEndIndex).trim();
if (comment.startsWith("::") && !comment.includes("/*") && !comment.includes("*/")) {
return ["/*:: ", printed, " */"];
}
}
}
return printed;
}
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 ["%checks(", print("value"), ")"];
case "AnyTypeAnnotation":
return "any";
case "BooleanTypeAnnotation":
return "boolean";
case "BigIntTypeAnnotation":
return "bigint";
case "NullLiteralTypeAnnotation":
return "null";
case "NumberTypeAnnotation":
return "number";
case "SymbolTypeAnnotation":
return "symbol";
case "StringTypeAnnotation":
return "string";
case "VoidTypeAnnotation":
return "void";
case "ThisTypeAnnotation":
return "this";
// 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(node.type));
}
}
function printFlowDeclaration(path, printed) {
const parentExportDecl = getParentExportDeclaration(path);
if (parentExportDecl) {
assert__default['default'].strictEqual(parentExportDecl.type, "DeclareExportDeclaration");
return printed;
} // 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.
return ["declare ", printed];
}
var flow = {
printFlow: printFlow$1
};
const {
hasNewlineInRange: hasNewlineInRange$1
} = util$5;
const {
isJsxNode: isJsxNode$1,
isBlockComment: isBlockComment$2,
getComments,
isCallExpression: isCallExpression$2,
isMemberExpression: isMemberExpression$2
} = utils$5;
const {
locStart: locStart$i,
locEnd: locEnd$h
} = loc$6;
const {
builders: {
line: line$g,
softline: softline$d,
group: group$h,
indent: indent$c,
align: align$2,
ifBreak: ifBreak$a,
dedent: dedent$3,
breakParent: breakParent$6
}
} = doc;
/**
* @typedef {import("../../document").Doc} Doc
* @typedef {import("../../common/ast-path")} AstPath
*
* @typedef {any} Options - Prettier options (TBD ...)
*/
// If we have nested conditional expressions, we want to print them in JSX mode
// if there's at least one JSXElement somewhere in the tree.
//
// A conditional expression chain like this should be printed in normal mode,
// because there aren't JSXElements anywhere in it:
//
// isA ? "A" : isB ? "B" : isC ? "C" : "Unknown";
//
// But a conditional expression chain like this should be printed in JSX mode,
// because there is a JSXElement in the last ConditionalExpression:
//
// isA ? "A" : isB ? "B" : isC ? "C" : Unknown;
//
// This type of ConditionalExpression chain is structured like this in the AST:
//
// ConditionalExpression {
// test: ...,
// consequent: ...,
// alternate: ConditionalExpression {
// test: ...,
// consequent: ...,
// alternate: ConditionalExpression {
// test: ...,
// consequent: ...,
// alternate: ...,
// }
// }
// }
function conditionalExpressionChainContainsJsx(node) {
// Given this code:
//
// // Using a ConditionalExpression as the consequent is uncommon, but should
// // be handled.
// A ? B : C ? D : E ? F ? G : H : I
//
// which has this AST:
//
// ConditionalExpression {
// test: Identifier(A),
// consequent: Identifier(B),
// alternate: ConditionalExpression {
// test: Identifier(C),
// consequent: Identifier(D),
// alternate: ConditionalExpression {
// test: Identifier(E),
// consequent: ConditionalExpression {
// test: Identifier(F),
// consequent: Identifier(G),
// alternate: Identifier(H),
// },
// alternate: Identifier(I),
// }
// }
// }
//
// We don't care about whether each node was the test, consequent, or alternate
// We are only checking if there's any JSXElements inside.
const conditionalExpressions = [node];
for (let index = 0; index < conditionalExpressions.length; index++) {
const conditionalExpression = conditionalExpressions[index];
for (const property of ["test", "consequent", "alternate"]) {
const node = conditionalExpression[property];
if (isJsxNode$1(node)) {
return true;
}
if (node.type === "ConditionalExpression") {
conditionalExpressions.push(node);
}
}
}
return false;
}
function printTernaryTest(path, options, print) {
const node = path.getValue();
const isConditionalExpression = node.type === "ConditionalExpression";
const alternateNodePropertyName = isConditionalExpression ? "alternate" : "falseType";
const parent = path.getParentNode();
const printed = isConditionalExpression ? print("test") : [print("checkType"), " ", "extends", " ", print("extendsType")];
/**
* a
* ? b
* : multiline
* test
* node
* ^^ align(2)
* ? d
* : e
*/
if (parent.type === node.type && parent[alternateNodePropertyName] === node) {
return align$2(2, printed);
}
return printed;
}
const ancestorNameMap = new Map([["AssignmentExpression", "right"], ["VariableDeclarator", "init"], ["ReturnStatement", "argument"], ["ThrowStatement", "argument"], ["UnaryExpression", "argument"], ["YieldExpression", "argument"]]);
function shouldExtraIndentForConditionalExpression(path) {
const node = path.getValue();
if (node.type !== "ConditionalExpression") {
return false;
}
let parent;
let child = node;
for (let ancestorCount = 0; !parent; ancestorCount++) {
const node = path.getParentNode(ancestorCount);
if (isCallExpression$2(node) && node.callee === child || isMemberExpression$2(node) && node.object === child || node.type === "TSNonNullExpression" && node.expression === child) {
child = node;
continue;
} // Reached chain root
if (node.type === "NewExpression" && node.callee === child || node.type === "TSAsExpression" && node.expression === child) {
parent = path.getParentNode(ancestorCount + 1);
child = node;
} else {
parent = node;
}
} // Do not add indent to direct `ConditionalExpression`
if (child === node) {
return false;
}
return parent[ancestorNameMap.get(parent.type)] === child;
}
/**
* The following is the shared logic for
* ternary operators, namely ConditionalExpression
* and TSConditionalType
* @param {AstPath} path - The path to the ConditionalExpression/TSConditionalType node.
* @param {Options} options - Prettier options
* @param {Function} print - Print function to call recursively
* @returns {Doc}
*/
function printTernary$2(path, options, print) {
const node = path.getValue();
const isConditionalExpression = node.type === "ConditionalExpression";
const consequentNodePropertyName = isConditionalExpression ? "consequent" : "trueType";
const alternateNodePropertyName = isConditionalExpression ? "alternate" : "falseType";
const testNodePropertyNames = isConditionalExpression ? ["test"] : ["checkType", "extendsType"];
const consequentNode = node[consequentNodePropertyName];
const alternateNode = node[alternateNodePropertyName];
const parts = []; // We print a ConditionalExpression in either "JSX mode" or "normal mode".
// See `tests/format/jsx/conditional-expression.js` for more info.
let jsxMode = false;
const parent = path.getParentNode();
const isParentTest = parent.type === node.type && testNodePropertyNames.some(prop => parent[prop] === node);
let forceNoIndent = parent.type === node.type && !isParentTest; // Find the outermost non-ConditionalExpression parent, and the outermost
// ConditionalExpression parent. We'll use these to determine if we should
// print in JSX mode.
let currentParent;
let previousParent;
let i = 0;
do {
previousParent = currentParent || node;
currentParent = path.getParentNode(i);
i++;
} while (currentParent && currentParent.type === node.type && testNodePropertyNames.every(prop => currentParent[prop] !== previousParent));
const firstNonConditionalParent = currentParent || parent;
const lastConditionalParent = previousParent;
if (isConditionalExpression && (isJsxNode$1(node[testNodePropertyNames[0]]) || isJsxNode$1(consequentNode) || isJsxNode$1(alternateNode) || conditionalExpressionChainContainsJsx(lastConditionalParent))) {
jsxMode = true;
forceNoIndent = true; // Even though they don't need parens, we wrap (almost) everything in
// parens when using ?: within JSX, because the parens are analogous to
// curly braces in an if statement.
const wrap = doc => [ifBreak$a("("), indent$c([softline$d, doc]), softline$d, ifBreak$a(")")]; // The only things we don't wrap are:
// * Nested conditional expressions in alternates
// * null
// * undefined
const isNil = node => node.type === "NullLiteral" || node.type === "Literal" && node.value === null || node.type === "Identifier" && node.name === "undefined";
parts.push(" ? ", isNil(consequentNode) ? print(consequentNodePropertyName) : wrap(print(consequentNodePropertyName)), " : ", alternateNode.type === node.type || isNil(alternateNode) ? print(alternateNodePropertyName) : wrap(print(alternateNodePropertyName)));
} else {
// normal mode
const part = [line$g, "? ", consequentNode.type === node.type ? ifBreak$a("", "(") : "", align$2(2, print(consequentNodePropertyName)), consequentNode.type === node.type ? ifBreak$a("", ")") : "", line$g, ": ", alternateNode.type === node.type ? print(alternateNodePropertyName) : align$2(2, print(alternateNodePropertyName))];
parts.push(parent.type !== node.type || parent[alternateNodePropertyName] === node || isParentTest ? part : options.useTabs ? dedent$3(indent$c(part)) : align$2(Math.max(0, options.tabWidth - 2), part));
} // We want a whole chain of ConditionalExpressions to all
// break if any of them break. That means we should only group around the
// outer-most ConditionalExpression.
const comments = [...testNodePropertyNames.map(propertyName => getComments(node[propertyName])), getComments(consequentNode), getComments(alternateNode)].flat();
const shouldBreak = comments.some(comment => isBlockComment$2(comment) && hasNewlineInRange$1(options.originalText, locStart$i(comment), locEnd$h(comment)));
const maybeGroup = doc => parent === firstNonConditionalParent ? group$h(doc, {
shouldBreak
}) : shouldBreak ? [doc, breakParent$6] : doc; // Break the closing paren to keep the chain right after it:
// (a
// ? b
// : c
// ).call()
const breakClosingParen = !jsxMode && (isMemberExpression$2(parent) || parent.type === "NGPipeExpression" && parent.left === node) && !parent.computed;
const shouldExtraIndent = shouldExtraIndentForConditionalExpression(path);
const result = maybeGroup([printTernaryTest(path, options, print), forceNoIndent ? parts : indent$c(parts), isConditionalExpression && breakClosingParen && !shouldExtraIndent ? softline$d : ""]);
return isParentTest || shouldExtraIndent ? group$h([indent$c([softline$d, result]), softline$d]) : result;
}
var ternary = {
printTernary: printTernary$2
};
const {
builders: {
hardline: hardline$k
}
} = doc;
const {
getLeftSidePathName,
hasNakedLeftSide,
isJsxNode,
isTheOnlyJsxElementInMarkdown: isTheOnlyJsxElementInMarkdown$1,
hasComment: hasComment$2,
CommentCheckFlags: CommentCheckFlags$2,
isNextLineEmpty: isNextLineEmpty$6
} = utils$5;
const {
shouldPrintParamsWithoutParens
} = _function;
/**
* @typedef {import("../../document").Doc} Doc
* @typedef {import("../../common/ast-path")} AstPath
*/
function printStatementSequence(path, options, print, property) {
const node = path.getValue();
const parts = [];
const isClassBody = node.type === "ClassBody";
const lastStatement = getLastStatement(node[property]);
path.each((path, index, statements) => {
const node = path.getValue(); // Skip printing EmptyStatement nodes to avoid leaving stray
// semicolons lying around.
if (node.type === "EmptyStatement") {
return;
}
const printed = print(); // 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 && !isClassBody && !isTheOnlyJsxElementInMarkdown$1(options, path) && statementNeedsASIProtection(path, options)) {
if (hasComment$2(node, CommentCheckFlags$2.Leading)) {
parts.push(print([], {
needsSemi: true
}));
} else {
parts.push(";", printed);
}
} else {
parts.push(printed);
}
if (!options.semi && isClassBody && isClassProperty(node) && // `ClassBody` don't allow `EmptyStatement`,
// so we can use `statements` to get next node
shouldPrintSemicolonAfterClassProperty(node, statements[index + 1])) {
parts.push(";");
}
if (node !== lastStatement) {
parts.push(hardline$k);
if (isNextLineEmpty$6(node, options)) {
parts.push(hardline$k);
}
}
}, property);
return parts;
}
function getLastStatement(statements) {
for (let i = statements.length - 1; i >= 0; i--) {
const statement = statements[i];
if (statement.type !== "EmptyStatement") {
return statement;
}
}
}
function statementNeedsASIProtection(path, options) {
const node = path.getNode();
if (node.type !== "ExpressionStatement") {
return false;
}
return path.call(childPath => expressionNeedsASIProtection(childPath, options), "expression");
}
function expressionNeedsASIProtection(path, options) {
const node = path.getValue();
switch (node.type) {
case "ParenthesizedExpression":
case "TypeCastExpression":
case "ArrayExpression":
case "ArrayPattern":
case "TemplateLiteral":
case "TemplateElement":
case "RegExpLiteral":
return true;
case "ArrowFunctionExpression":
{
if (!shouldPrintParamsWithoutParens(path, options)) {
return true;
}
break;
}
case "UnaryExpression":
{
const {
prefix,
operator
} = node;
if (prefix && (operator === "+" || operator === "-")) {
return true;
}
break;
}
case "BindExpression":
{
if (!node.object) {
return true;
}
break;
}
case "Literal":
{
if (node.regex) {
return true;
}
break;
}
default:
{
if (isJsxNode(node)) {
return true;
}
}
}
if (needsParens_1(path, options)) {
return true;
}
if (!hasNakedLeftSide(node)) {
return false;
}
return path.call(childPath => expressionNeedsASIProtection(childPath, options), ...getLeftSidePathName(path, node));
}
function printBody$1(path, options, print) {
return printStatementSequence(path, options, print, "body");
}
function printSwitchCaseConsequent$1(path, options, print) {
return printStatementSequence(path, options, print, "consequent");
}
const isClassProperty = ({
type
}) => type === "ClassProperty" || type === "PropertyDefinition" || type === "ClassPrivateProperty";
/**
* @returns {boolean}
*/
function shouldPrintSemicolonAfterClassProperty(node, nextNode) {
const name = node.key && node.key.name; // this isn't actually possible yet with most parsers available today
// so isn't properly tested yet.
if ((name === "static" || name === "get" || name === "set") && !node.value && !node.typeAnnotation) {
return true;
}
if (!nextNode) {
return false;
}
if (nextNode.static || nextNode.accessibility // TypeScript
) {
return false;
}
if (!nextNode.computed) {
const name = nextNode.key && nextNode.key.name;
if (name === "in" || name === "instanceof") {
return true;
}
} // Flow variance sigil +/- requires semi if there's no
// "declare" or "static" keyword before it.
if (isClassProperty(nextNode) && nextNode.variance && !nextNode.static && !nextNode.declare) {
return true;
}
switch (nextNode.type) {
case "ClassProperty":
case "PropertyDefinition":
case "TSAbstractClassProperty":
return nextNode.computed;
case "MethodDefinition": // Flow
case "TSAbstractMethodDefinition": // TypeScript
case "ClassMethod":
case "ClassPrivateMethod":
{
// Babel
const isAsync = nextNode.value ? nextNode.value.async : nextNode.async;
if (isAsync || nextNode.kind === "get" || nextNode.kind === "set") {
return false;
}
const isGenerator = nextNode.value ? nextNode.value.generator : nextNode.generator;
if (nextNode.computed || isGenerator) {
return true;
}
return false;
}
case "TSIndexSignature":
return true;
}
/* istanbul ignore next */
return false;
}
var statement = {
printBody: printBody$1,
printSwitchCaseConsequent: printSwitchCaseConsequent$1
};
const {
printDanglingComments: printDanglingComments$2
} = comments$1;
const {
isNonEmptyArray: isNonEmptyArray$7
} = util$5;
const {
builders: {
hardline: hardline$j,
indent: indent$b
}
} = doc;
const {
hasComment: hasComment$1,
CommentCheckFlags: CommentCheckFlags$1,
isNextLineEmpty: isNextLineEmpty$5
} = utils$5;
const {
printHardlineAfterHeritage
} = _class;
const {
printBody
} = statement;
/** @typedef {import("../../document").Doc} Doc */
function printBlock$3(path, options, print) {
const node = path.getValue();
const parts = [];
if (node.type === "StaticBlock") {
parts.push("static ");
}
if (node.type === "ClassBody" && isNonEmptyArray$7(node.body)) {
const parent = path.getParentNode();
parts.push(printHardlineAfterHeritage(parent));
}
parts.push("{");
const printed = printBlockBody$1(path, options, print);
if (printed) {
parts.push(indent$b([hardline$j, printed]), hardline$j);
} else {
const parent = path.getParentNode();
const parentParent = path.getParentNode(1);
if (!(parent.type === "ArrowFunctionExpression" || parent.type === "FunctionExpression" || parent.type === "FunctionDeclaration" || parent.type === "ObjectMethod" || parent.type === "ClassMethod" || parent.type === "ClassPrivateMethod" || parent.type === "ForStatement" || parent.type === "WhileStatement" || parent.type === "DoWhileStatement" || parent.type === "DoExpression" || parent.type === "CatchClause" && !parentParent.finalizer || parent.type === "TSModuleDeclaration" || parent.type === "TSDeclareFunction" || node.type === "StaticBlock" || node.type === "ClassBody")) {
parts.push(hardline$j);
}
}
parts.push("}");
return parts;
}
function printBlockBody$1(path, options, print) {
const node = path.getValue();
const nodeHasDirectives = isNonEmptyArray$7(node.directives);
const nodeHasBody = node.body.some(node => node.type !== "EmptyStatement");
const nodeHasComment = hasComment$1(node, CommentCheckFlags$1.Dangling);
if (!nodeHasDirectives && !nodeHasBody && !nodeHasComment) {
return "";
}
const parts = []; // Babel 6
if (nodeHasDirectives) {
path.each((childPath, index, directives) => {
parts.push(print());
if (index < directives.length - 1 || nodeHasBody || nodeHasComment) {
parts.push(hardline$j);
if (isNextLineEmpty$5(childPath.getValue(), options)) {
parts.push(hardline$j);
}
}
}, "directives");
}
if (nodeHasBody) {
parts.push(printBody(path, options, print));
}
if (nodeHasComment) {
parts.push(printDanglingComments$2(path, options,
/* sameIndent */
true));
}
if (node.type === "Program") {
const parent = path.getParentNode();
if (!parent || parent.type !== "ModuleExpression") {
parts.push(hardline$j);
}
}
return parts;
}
var block$1 = {
printBlock: printBlock$3,
printBlockBody: printBlockBody$1
};
const {
printDanglingComments: printDanglingComments$1
} = comments$1;
const {
hasNewlineInRange
} = util$5;
const {
builders: {
join: join$e,
line: line$f,
hardline: hardline$i,
softline: softline$c,
group: group$g,
indent: indent$a,
conditionalGroup: conditionalGroup$1,
ifBreak: ifBreak$9
}
} = doc;
const {
isLiteral,
getTypeScriptMappedTypeModifier,
shouldPrintComma: shouldPrintComma$1,
isCallExpression: isCallExpression$1,
isMemberExpression: isMemberExpression$1
} = utils$5;
const {
locStart: locStart$h,
locEnd: locEnd$g
} = loc$6;
const {
printOptionalToken: printOptionalToken$1,
printTypeScriptModifiers
} = misc$1;
const {
printTernary: printTernary$1
} = ternary;
const {
printFunctionParameters,
shouldGroupFunctionParameters
} = functionParameters;
const {
printTemplateLiteral: printTemplateLiteral$1
} = templateLiteral;
const {
printArrayItems
} = array;
const {
printObject: printObject$1
} = object$1;
const {
printClassProperty: printClassProperty$1,
printClassMethod: printClassMethod$1
} = _class;
const {
printTypeParameter,
printTypeParameters
} = typeParameters;
const {
printPropertyKey
} = property;
const {
printFunction: printFunction$1,
printMethodInternal
} = _function;
const {
printInterface
} = _interface;
const {
printBlock: printBlock$2
} = block$1;
const {
printTypeAlias,
printIntersectionType,
printUnionType,
printFunctionType,
printTupleType,
printIndexedAccessType
} = typeAnnotation;
function printTypescript$1(path, options, print) {
const node = path.getValue(); // TypeScript nodes always starts with `TS`
if (!node.type.startsWith("TS")) {
return;
}
if (node.type.endsWith("Keyword")) {
return node.type.slice(2, -7).toLowerCase();
}
const semi = options.semi ? ";" : "";
const parts = [];
switch (node.type) {
case "TSThisType":
return "this";
case "TSTypeAssertion":
{
const shouldBreakAfterCast = !(node.expression.type === "ArrayExpression" || node.expression.type === "ObjectExpression");
const castGroup = group$g(["<", indent$a([softline$c, print("typeAnnotation")]), softline$c, ">"]);
const exprContents = [ifBreak$9("("), indent$a([softline$c, print("expression")]), softline$c, ifBreak$9(")")];
if (shouldBreakAfterCast) {
return conditionalGroup$1([[castGroup, print("expression")], [castGroup, group$g(exprContents, {
shouldBreak: true
})], [castGroup, print("expression")]]);
}
return group$g([castGroup, print("expression")]);
}
case "TSDeclareFunction":
return printFunction$1(path, print, options);
case "TSExportAssignment":
return ["export = ", print("expression"), semi];
case "TSModuleBlock":
return printBlock$2(path, options, print);
case "TSInterfaceBody":
case "TSTypeLiteral":
return printObject$1(path, options, print);
case "TSTypeAliasDeclaration":
return printTypeAlias(path, options, print);
case "TSQualifiedName":
return join$e(".", [print("left"), print("right")]);
case "TSAbstractMethodDefinition":
case "TSDeclareMethod":
return printClassMethod$1(path, options, print);
case "TSAbstractClassProperty":
return printClassProperty$1(path, options, print);
case "TSInterfaceHeritage":
case "TSExpressionWithTypeArguments":
// Babel AST
parts.push(print("expression"));
if (node.typeParameters) {
parts.push(print("typeParameters"));
}
return parts;
case "TSTemplateLiteralType":
return printTemplateLiteral$1(path, print, options);
case "TSNamedTupleMember":
return [print("label"), node.optional ? "?" : "", ": ", print("elementType")];
case "TSRestType":
return ["...", print("typeAnnotation")];
case "TSOptionalType":
return [print("typeAnnotation"), "?"];
case "TSInterfaceDeclaration":
return printInterface(path, options, print);
case "TSClassImplements":
return [print("expression"), print("typeParameters")];
case "TSTypeParameterDeclaration":
case "TSTypeParameterInstantiation":
return printTypeParameters(path, options, print, "params");
case "TSTypeParameter":
return printTypeParameter(path, options, print);
case "TSAsExpression":
{
parts.push(print("expression"), " as ", print("typeAnnotation"));
const parent = path.getParentNode();
if (isCallExpression$1(parent) && parent.callee === node || isMemberExpression$1(parent) && parent.object === node) {
return group$g([indent$a([softline$c, ...parts]), softline$c]);
}
return parts;
}
case "TSArrayType":
return [print("elementType"), "[]"];
case "TSPropertySignature":
{
if (node.readonly) {
parts.push("readonly ");
}
parts.push(printPropertyKey(path, options, print), printOptionalToken$1(path));
if (node.typeAnnotation) {
parts.push(": ", print("typeAnnotation"));
} // This isn't valid semantically, but it's in the AST so we can print it.
if (node.initializer) {
parts.push(" = ", print("initializer"));
}
return parts;
}
case "TSParameterProperty":
if (node.accessibility) {
parts.push(node.accessibility + " ");
}
if (node.export) {
parts.push("export ");
}
if (node.static) {
parts.push("static ");
}
if (node.override) {
parts.push("override ");
}
if (node.readonly) {
parts.push("readonly ");
}
parts.push(print("parameter"));
return parts;
case "TSTypeQuery":
return ["typeof ", 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 = node.parameters.length > 1 ? ifBreak$9(shouldPrintComma$1(options) ? "," : "") : "";
const parametersGroup = group$g([indent$a([softline$c, join$e([", ", softline$c], path.map(print, "parameters"))]), trailingComma, softline$c]);
return [node.export ? "export " : "", node.accessibility ? [node.accessibility, " "] : "", node.static ? "static " : "", node.readonly ? "readonly " : "", node.declare ? "declare " : "", "[", node.parameters ? parametersGroup : "", node.typeAnnotation ? "]: " : "]", node.typeAnnotation ? print("typeAnnotation") : "", parent.type === "ClassBody" ? semi : ""];
}
case "TSTypePredicate":
return [node.asserts ? "asserts " : "", print("parameterName"), node.typeAnnotation ? [" is ", print("typeAnnotation")] : ""];
case "TSNonNullExpression":
return [print("expression"), "!"];
case "TSImportType":
return [!node.isTypeOf ? "" : "typeof ", "import(", print(node.parameter ? "parameter" : "argument"), ")", !node.qualifier ? "" : [".", print("qualifier")], printTypeParameters(path, options, print, "typeParameters")];
case "TSLiteralType":
return print("literal");
case "TSIndexedAccessType":
return printIndexedAccessType(path, options, print);
case "TSConstructSignatureDeclaration":
case "TSCallSignatureDeclaration":
case "TSConstructorType":
{
if (node.type === "TSConstructorType" && node.abstract) {
parts.push("abstract ");
}
if (node.type !== "TSCallSignatureDeclaration") {
parts.push("new ");
}
parts.push(group$g(printFunctionParameters(path, print, options,
/* expandArg */
false,
/* printTypeParams */
true)));
if (node.returnType || node.typeAnnotation) {
const isType = node.type === "TSConstructorType";
parts.push(isType ? " => " : ": ", print("returnType"), print("typeAnnotation"));
}
return parts;
}
case "TSTypeOperator":
return [node.operator, " ", print("typeAnnotation")];
case "TSMappedType":
{
const shouldBreak = hasNewlineInRange(options.originalText, locStart$h(node), locEnd$g(node));
return group$g(["{", indent$a([options.bracketSpacing ? line$f : softline$c, node.readonly ? [getTypeScriptMappedTypeModifier(node.readonly, "readonly"), " "] : "", printTypeScriptModifiers(path, options, print), print("typeParameter"), node.optional ? getTypeScriptMappedTypeModifier(node.optional, "?") : "", node.typeAnnotation ? ": " : "", print("typeAnnotation"), ifBreak$9(semi)]), printDanglingComments$1(path, options,
/* sameIndent */
true), options.bracketSpacing ? line$f : softline$c, "}"], {
shouldBreak
});
}
case "TSMethodSignature":
{
const kind = node.kind && node.kind !== "method" ? `${node.kind} ` : "";
parts.push(node.accessibility ? [node.accessibility, " "] : "", kind, node.export ? "export " : "", node.static ? "static " : "", node.readonly ? "readonly " : "", // "abstract" and "declare" are supported by only "babel-ts"
// https://github.com/prettier/prettier/issues/9760
node.abstract ? "abstract " : "", node.declare ? "declare " : "", node.computed ? "[" : "", print("key"), node.computed ? "]" : "", printOptionalToken$1(path));
const parametersDoc = printFunctionParameters(path, print, options,
/* expandArg */
false,
/* printTypeParams */
true);
const returnTypePropertyName = node.returnType ? "returnType" : "typeAnnotation";
const returnTypeNode = node[returnTypePropertyName];
const returnTypeDoc = returnTypeNode ? print(returnTypePropertyName) : "";
const shouldGroupParameters = shouldGroupFunctionParameters(node, returnTypeDoc);
parts.push(shouldGroupParameters ? group$g(parametersDoc) : parametersDoc);
if (returnTypeNode) {
parts.push(": ", group$g(returnTypeDoc));
}
return group$g(parts);
}
case "TSNamespaceExportDeclaration":
parts.push("export as namespace ", print("id"));
if (options.semi) {
parts.push(";");
}
return group$g(parts);
case "TSEnumDeclaration":
if (node.declare) {
parts.push("declare ");
}
if (node.modifiers) {
parts.push(printTypeScriptModifiers(path, options, print));
}
if (node.const) {
parts.push("const ");
}
parts.push("enum ", print("id"), " ");
if (node.members.length === 0) {
parts.push(group$g(["{", printDanglingComments$1(path, options), softline$c, "}"]));
} else {
parts.push(group$g(["{", indent$a([hardline$i, printArrayItems(path, options, "members", print), shouldPrintComma$1(options, "es5") ? "," : ""]), printDanglingComments$1(path, options,
/* sameIndent */
true), hardline$i, "}"]));
}
return parts;
case "TSEnumMember":
parts.push(print("id"));
if (node.initializer) {
parts.push(" = ", print("initializer"));
}
return parts;
case "TSImportEqualsDeclaration":
if (node.isExport) {
parts.push("export ");
}
parts.push("import ");
if (node.importKind && node.importKind !== "value") {
parts.push(node.importKind, " ");
}
parts.push(print("id"), " = ", print("moduleReference"));
if (options.semi) {
parts.push(";");
}
return group$g(parts);
case "TSExternalModuleReference":
return ["require(", print("expression"), ")"];
case "TSModuleDeclaration":
{
const parent = path.getParentNode();
const isExternalModule = isLiteral(node.id);
const parentIsDeclaration = parent.type === "TSModuleDeclaration";
const bodyIsDeclaration = node.body && node.body.type === "TSModuleDeclaration";
if (parentIsDeclaration) {
parts.push(".");
} else {
if (node.declare) {
parts.push("declare ");
}
parts.push(printTypeScriptModifiers(path, options, print));
const textBetweenNodeAndItsId = options.originalText.slice(locStart$h(node), locStart$h(node.id)); // Global declaration looks like this:
// (declare)? global { ... }
const isGlobalDeclaration = node.id.type === "Identifier" && node.id.name === "global" && !/namespace|module/.test(textBetweenNodeAndItsId);
if (!isGlobalDeclaration) {
parts.push(isExternalModule || /(?:^|\s)module(?:\s|$)/.test(textBetweenNodeAndItsId) ? "module " : "namespace ");
}
}
parts.push(print("id"));
if (bodyIsDeclaration) {
parts.push(print("body"));
} else if (node.body) {
parts.push(" ", group$g(print("body")));
} else {
parts.push(semi);
}
return parts;
}
// TODO: Temporary auto-generated node type. To remove when typescript-estree has proper support for private fields.
case "TSPrivateIdentifier":
return node.escapedText;
case "TSConditionalType":
return printTernary$1(path, options, print);
case "TSInferType":
return ["infer", " ", print("typeParameter")];
case "TSIntersectionType":
return printIntersectionType(path, options, print);
case "TSUnionType":
return printUnionType(path, options, print);
case "TSFunctionType":
return printFunctionType(path, options, print);
case "TSTupleType":
return printTupleType(path, options, print);
case "TSTypeReference":
return [print("typeName"), printTypeParameters(path, options, print, "typeParameters")];
case "TSTypeAnnotation":
return print("typeAnnotation");
case "TSEmptyBodyFunctionExpression":
return printMethodInternal(path, options, print);
// These are not valid TypeScript. Printing them just for the sake of error recovery.
case "TSJSDocAllType":
return "*";
case "TSJSDocUnknownType":
return "?";
case "TSJSDocNullableType":
return ["?", print("typeAnnotation")];
case "TSJSDocNonNullableType":
return ["!", print("typeAnnotation")];
default:
/* istanbul ignore next */
throw new Error(`Unknown TypeScript node type: ${JSON.stringify(node.type)}.`);
}
}
var typescript = {
printTypescript: printTypescript$1
};
const {
hasNewline: hasNewline$2
} = util$5;
const {
builders: {
join: join$d,
hardline: hardline$h
},
utils: {
replaceTextEndOfLine: replaceTextEndOfLine$a
}
} = doc;
const {
isLineComment: isLineComment$1,
isBlockComment: isBlockComment$1
} = utils$5;
const {
locStart: locStart$g,
locEnd: locEnd$f
} = loc$6;
function printComment$2(commentPath, options) {
const comment = commentPath.getValue();
if (isLineComment$1(comment)) {
// Supports `//`, `#!`, ``
return options.originalText.slice(locStart$g(comment), locEnd$f(comment)).trimEnd();
}
if (isBlockComment$1(comment)) {
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$2(options.originalText, locStart$g(comment), {
backwards: true
})) {
return [hardline$h, printed];
}
return printed;
}
const commentEnd = locEnd$f(comment);
const isInsideFlowComment = options.originalText.slice(commentEnd - 3, commentEnd) === "*-/";
return ["/*", replaceTextEndOfLine$a(comment.value), isInsideFlowComment ? "*-/" : "*/"];
}
/* 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 ["/*", join$d(hardline$h, lines.map((line, index) => index === 0 ? line.trimEnd() : " " + (index < lines.length - 1 ? line.trim() : line.trimStart()))), "*/"];
}
var comment = {
printComment: printComment$2
};
const {
printString: printString$1,
printNumber: printNumber$1
} = util$5;
function printLiteral$1(path, options
/*, print*/
) {
const node = path.getNode();
switch (node.type) {
case "RegExpLiteral":
// Babel 6 Literal split
return printRegex(node);
case "BigIntLiteral":
// babel: node.extra.raw, flow: node.bigint
return printBigInt(node.bigint || node.extra.raw);
case "NumericLiteral":
// Babel 6 Literal split
return printNumber$1(node.extra.raw);
case "StringLiteral":
// Babel 6 Literal split
return printString$1(node.extra.raw, options);
case "NullLiteral":
// Babel 6 Literal split
return "null";
case "BooleanLiteral":
// Babel 6 Literal split
return String(node.value);
case "DecimalLiteral":
return printNumber$1(node.value) + "m";
case "Literal":
{
if (node.regex) {
return printRegex(node.regex);
}
if (node.bigint) {
return printBigInt(node.raw);
}
if (node.decimal) {
return printNumber$1(node.decimal) + "m";
}
const {
value
} = node;
if (typeof value === "number") {
return printNumber$1(node.raw);
}
if (typeof value === "string") {
return printString$1(node.raw, options);
}
return String(value);
}
}
}
function printBigInt(raw) {
return raw.toLowerCase();
}
function printRegex({
pattern,
flags
}) {
flags = [...flags].sort().join("");
return `/${pattern}/${flags}`;
}
var literal = {
printLiteral: printLiteral$1
};
/** @typedef {import("../document").Doc} Doc */
// TODO(azz): anything that imports from main shouldn't be in a `language-*` dir.
const {
printDanglingComments
} = comments$1;
const {
hasNewline: hasNewline$1
} = util$5;
const {
builders: {
join: join$c,
line: line$e,
hardline: hardline$g,
softline: softline$b,
group: group$f,
indent: indent$9
},
utils: {
replaceTextEndOfLine: replaceTextEndOfLine$9
}
} = doc;
const {
insertPragma: insertPragma$9
} = pragma$5;
const {
hasFlowShorthandAnnotationComment,
hasComment,
CommentCheckFlags,
isTheOnlyJsxElementInMarkdown,
isBlockComment,
isLineComment,
isNextLineEmpty: isNextLineEmpty$4,
needsHardlineAfterDanglingComment,
rawText,
hasIgnoreComment,
isCallExpression,
isMemberExpression
} = utils$5;
const {
locStart: locStart$f,
locEnd: locEnd$e
} = loc$6;
const {
printHtmlBinding,
isVueEventBindingExpression: isVueEventBindingExpression$2
} = htmlBinding;
const {
printAngular
} = angular;
const {
printJsx,
hasJsxIgnoreComment
} = jsx;
const {
printFlow
} = flow;
const {
printTypescript
} = typescript;
const {
printOptionalToken,
printBindExpressionCallee,
printTypeAnnotation,
adjustClause,
printRestSpread
} = misc$1;
const {
printImportDeclaration,
printExportDeclaration,
printExportAllDeclaration,
printModuleSpecifier
} = module$1;
const {
printTernary
} = ternary;
const {
printTemplateLiteral
} = templateLiteral;
const {
printArray
} = array;
const {
printObject
} = object$1;
const {
printClass,
printClassMethod,
printClassProperty
} = _class;
const {
printProperty
} = property;
const {
printFunction,
printArrowFunction,
printMethod,
printReturnStatement,
printThrowStatement
} = _function;
const {
printCallExpression
} = callExpression;
const {
printVariableDeclarator,
printAssignmentExpression
} = assignment;
const {
printBinaryishExpression
} = binaryish;
const {
printSwitchCaseConsequent
} = statement;
const {
printMemberExpression
} = member;
const {
printBlock: printBlock$1,
printBlockBody
} = block$1;
const {
printComment: printComment$1
} = comment;
const {
printLiteral
} = literal;
const {
printDecorators
} = decorators;
function genericPrint$6(path, options, print, args) {
const printed = printPathNoParens(path, options, print, args);
if (!printed) {
return "";
}
const node = path.getValue();
const {
type
} = node; // Their decorators are handled themselves, and they can't have parentheses
if (type === "ClassMethod" || type === "ClassPrivateMethod" || type === "ClassProperty" || type === "PropertyDefinition" || type === "TSAbstractClassProperty" || type === "ClassPrivateProperty" || type === "MethodDefinition" || type === "TSAbstractMethodDefinition" || type === "TSDeclareMethod") {
return printed;
}
const printedDecorators = printDecorators(path, options, print); // Nodes with decorators can't have parentheses and don't need leading semicolons
if (printedDecorators) {
return group$f([...printedDecorators, printed]);
}
const needsParens = needsParens_1(path, options);
if (!needsParens) {
return args && args.needsSemi ? [";", printed] : printed;
}
const parts = [args && args.needsSemi ? ";(" : "(", printed];
if (hasFlowShorthandAnnotationComment(node)) {
const [comment] = node.trailingComments;
parts.push(" /*", comment.value.trimStart(), "*/");
comment.printed = true;
}
parts.push(")");
return parts;
}
function printPathNoParens(path, options, print, args) {
const node = path.getValue();
const semi = options.semi ? ";" : "";
if (!node) {
return "";
}
if (typeof node === "string") {
return node;
}
for (const printer of [printLiteral, printHtmlBinding, printAngular, printJsx, printFlow, printTypescript]) {
const printed = printer(path, options, print);
if (typeof printed !== "undefined") {
return printed;
}
}
/** @type{Doc[]} */
let parts = [];
switch (node.type) {
case "JsExpressionRoot":
return print("node");
case "JsonRoot":
return [print("node"), hardline$g];
case "File":
// Print @babel/parser's InterpreterDirective here so that
// leading comments on the `Program` node get printed after the hashbang.
if (node.program && node.program.interpreter) {
parts.push(print(["program", "interpreter"]));
}
parts.push(print("program"));
return parts;
case "Program":
return printBlockBody(path, options, print);
// Babel extension.
case "EmptyStatement":
return "";
case "ExpressionStatement":
// Detect Flow and TypeScript directives
if (node.directive) {
return [printDirective(node.expression, options), semi];
}
if (options.parser === "__vue_event_binding") {
const parent = path.getParentNode();
if (parent.type === "Program" && parent.body.length === 1 && parent.body[0] === node) {
return [print("expression"), isVueEventBindingExpression$2(node.expression) ? ";" : ""];
}
} // Do not append semicolon after the only JSX element in a program
return [print("expression"), isTheOnlyJsxElementInMarkdown(options, path) ? "" : semi];
// Babel non-standard node. Used for Closure-style type casts. See postprocess.js.
case "ParenthesizedExpression":
{
const shouldHug = !hasComment(node.expression) && (node.expression.type === "ObjectExpression" || node.expression.type === "ArrayExpression");
if (shouldHug) {
return ["(", print("expression"), ")"];
}
return group$f(["(", indent$9([softline$b, print("expression")]), softline$b, ")"]);
}
case "AssignmentExpression":
return printAssignmentExpression(path, options, print);
case "VariableDeclarator":
return printVariableDeclarator(path, options, print);
case "BinaryExpression":
case "LogicalExpression":
return printBinaryishExpression(path, options, print);
case "AssignmentPattern":
return [print("left"), " = ", print("right")];
case "OptionalMemberExpression":
case "MemberExpression":
{
return printMemberExpression(path, options, print);
}
case "MetaProperty":
return [print("meta"), ".", print("property")];
case "BindExpression":
if (node.object) {
parts.push(print("object"));
}
parts.push(group$f(indent$9([softline$b, printBindExpressionCallee(path, options, print)])));
return parts;
case "Identifier":
{
return [node.name, printOptionalToken(path), printTypeAnnotation(path, options, print)];
}
case "V8IntrinsicIdentifier":
return ["%", node.name];
case "SpreadElement":
case "SpreadElementPattern":
case "SpreadProperty":
case "SpreadPropertyPattern":
case "RestElement":
return printRestSpread(path, options, print);
case "FunctionDeclaration":
case "FunctionExpression":
return printFunction(path, print, options, args);
case "ArrowFunctionExpression":
return printArrowFunction(path, options, print, args);
case "YieldExpression":
parts.push("yield");
if (node.delegate) {
parts.push("*");
}
if (node.argument) {
parts.push(" ", print("argument"));
}
return parts;
case "AwaitExpression":
{
parts.push("await");
if (node.argument) {
parts.push(" ", print("argument"));
const parent = path.getParentNode();
if (isCallExpression(parent) && parent.callee === node || isMemberExpression(parent) && parent.object === node) {
parts = [indent$9([softline$b, ...parts]), softline$b];
const parentAwaitOrBlock = path.findAncestor(node => node.type === "AwaitExpression" || node.type === "BlockStatement");
if (!parentAwaitOrBlock || parentAwaitOrBlock.type !== "AwaitExpression") {
return group$f(parts);
}
}
}
return parts;
}
case "ExportDefaultDeclaration":
case "ExportNamedDeclaration":
return printExportDeclaration(path, options, print);
case "ExportAllDeclaration":
return printExportAllDeclaration(path, options, print);
case "ImportDeclaration":
return printImportDeclaration(path, options, print);
case "ImportSpecifier":
case "ExportSpecifier":
case "ImportNamespaceSpecifier":
case "ExportNamespaceSpecifier":
case "ImportDefaultSpecifier":
case "ExportDefaultSpecifier":
return printModuleSpecifier(path, options, print);
case "ImportAttribute":
return [print("key"), ": ", print("value")];
case "Import":
return "import";
case "BlockStatement":
case "StaticBlock":
case "ClassBody":
return printBlock$1(path, options, print);
case "ThrowStatement":
return printThrowStatement(path, options, print);
case "ReturnStatement":
return printReturnStatement(path, options, print);
case "NewExpression":
case "ImportExpression":
case "OptionalCallExpression":
case "CallExpression":
return printCallExpression(path, options, print);
case "ObjectExpression":
case "ObjectPattern":
case "RecordExpression":
return printObject(path, options, print);
// Babel 6
case "ObjectProperty": // Non-standard AST node type.
case "Property":
if (node.method || node.kind === "get" || node.kind === "set") {
return printMethod(path, options, print);
}
return printProperty(path, options, print);
case "ObjectMethod":
return printMethod(path, options, print);
case "Decorator":
return ["@", print("expression")];
case "ArrayExpression":
case "ArrayPattern":
case "TupleExpression":
return printArray(path, options, print);
case "SequenceExpression":
{
const parent = path.getParentNode(0);
if (parent.type === "ExpressionStatement" || parent.type === "ForStatement") {
// For ExpressionStatements and for-loop heads, which are among
// the few places a SequenceExpression appears unparenthesized, we want
// to indent expressions after the first.
const parts = [];
path.each((expressionPath, index) => {
if (index === 0) {
parts.push(print());
} else {
parts.push(",", indent$9([line$e, print()]));
}
}, "expressions");
return group$f(parts);
}
return group$f(join$c([",", line$e], path.map(print, "expressions")));
}
case "ThisExpression":
return "this";
case "Super":
return "super";
case "Directive":
return [print("value"), semi];
// Babel 6
case "DirectiveLiteral":
return printDirective(node, options);
case "UnaryExpression":
parts.push(node.operator);
if (/[a-z]$/.test(node.operator)) {
parts.push(" ");
}
if (hasComment(node.argument)) {
parts.push(group$f(["(", indent$9([softline$b, print("argument")]), softline$b, ")"]));
} else {
parts.push(print("argument"));
}
return parts;
case "UpdateExpression":
parts.push(print("argument"), node.operator);
if (node.prefix) {
parts.reverse();
}
return parts;
case "ConditionalExpression":
return printTernary(path, options, print);
case "VariableDeclaration":
{
const printed = path.map(print, "declarations"); // We generally want to terminate all variable declarations with a
// semicolon, except when they in the () part of for loops.
const parentNode = path.getParentNode();
const isParentForLoop = parentNode.type === "ForStatement" || parentNode.type === "ForInStatement" || parentNode.type === "ForOfStatement";
const hasValue = node.declarations.some(decl => decl.init);
let firstVariable;
if (printed.length === 1 && !hasComment(node.declarations[0])) {
firstVariable = printed[0];
} else if (printed.length > 0) {
// Indent first var to comply with eslint one-var rule
firstVariable = indent$9(printed[0]);
}
parts = [node.declare ? "declare " : "", node.kind, firstVariable ? [" ", firstVariable] : "", indent$9(printed.slice(1).map(p => [",", hasValue && !isParentForLoop ? hardline$g : line$e, p]))];
if (!(isParentForLoop && parentNode.body !== node)) {
parts.push(semi);
}
return group$f(parts);
}
case "WithStatement":
return group$f(["with (", print("object"), ")", adjustClause(node.body, print("body"))]);
case "IfStatement":
{
const con = adjustClause(node.consequent, print("consequent"));
const opening = group$f(["if (", group$f([indent$9([softline$b, print("test")]), softline$b]), ")", con]);
parts.push(opening);
if (node.alternate) {
const commentOnOwnLine = hasComment(node.consequent, CommentCheckFlags.Trailing | CommentCheckFlags.Line) || needsHardlineAfterDanglingComment(node);
const elseOnSameLine = node.consequent.type === "BlockStatement" && !commentOnOwnLine;
parts.push(elseOnSameLine ? " " : hardline$g);
if (hasComment(node, CommentCheckFlags.Dangling)) {
parts.push(printDanglingComments(path, options, true), commentOnOwnLine ? hardline$g : " ");
}
parts.push("else", group$f(adjustClause(node.alternate, print("alternate"), node.alternate.type === "IfStatement")));
}
return parts;
}
case "ForStatement":
{
const body = adjustClause(node.body, print("body")); // We want to keep dangling comments above the loop to stay consistent.
// Any comment positioned between the for statement and the parentheses
// is going to be printed before the statement.
const dangling = printDanglingComments(path, options,
/* sameLine */
true);
const printedComments = dangling ? [dangling, softline$b] : "";
if (!node.init && !node.test && !node.update) {
return [printedComments, group$f(["for (;;)", body])];
}
return [printedComments, group$f(["for (", group$f([indent$9([softline$b, print("init"), ";", line$e, print("test"), ";", line$e, print("update")]), softline$b]), ")", body])];
}
case "WhileStatement":
return group$f(["while (", group$f([indent$9([softline$b, print("test")]), softline$b]), ")", adjustClause(node.body, print("body"))]);
case "ForInStatement":
return group$f(["for (", print("left"), " in ", print("right"), ")", adjustClause(node.body, print("body"))]);
case "ForOfStatement":
return group$f(["for", node.await ? " await" : "", " (", print("left"), " of ", print("right"), ")", adjustClause(node.body, print("body"))]);
case "DoWhileStatement":
{
const clause = adjustClause(node.body, print("body"));
const doBody = group$f(["do", clause]);
parts = [doBody];
if (node.body.type === "BlockStatement") {
parts.push(" ");
} else {
parts.push(hardline$g);
}
parts.push("while (", group$f([indent$9([softline$b, print("test")]), softline$b]), ")", semi);
return parts;
}
case "DoExpression":
return [node.async ? "async " : "", "do ", print("body")];
case "BreakStatement":
parts.push("break");
if (node.label) {
parts.push(" ", print("label"));
}
parts.push(semi);
return parts;
case "ContinueStatement":
parts.push("continue");
if (node.label) {
parts.push(" ", print("label"));
}
parts.push(semi);
return parts;
case "LabeledStatement":
if (node.body.type === "EmptyStatement") {
return [print("label"), ":;"];
}
return [print("label"), ": ", print("body")];
case "TryStatement":
return ["try ", print("block"), node.handler ? [" ", print("handler")] : "", node.finalizer ? [" finally ", print("finalizer")] : ""];
case "CatchClause":
if (node.param) {
const parameterHasComments = hasComment(node.param, comment => !isBlockComment(comment) || comment.leading && hasNewline$1(options.originalText, locEnd$e(comment)) || comment.trailing && hasNewline$1(options.originalText, locStart$f(comment), {
backwards: true
}));
const param = print("param");
return ["catch ", parameterHasComments ? ["(", indent$9([softline$b, param]), softline$b, ") "] : ["(", param, ") "], print("body")];
}
return ["catch ", print("body")];
// Note: ignoring n.lexical because it has no printing consequences.
case "SwitchStatement":
return [group$f(["switch (", indent$9([softline$b, print("discriminant")]), softline$b, ")"]), " {", node.cases.length > 0 ? indent$9([hardline$g, join$c(hardline$g, path.map((casePath, index, cases) => {
const caseNode = casePath.getValue();
return [print(), index !== cases.length - 1 && isNextLineEmpty$4(caseNode, options) ? hardline$g : ""];
}, "cases"))]) : "", hardline$g, "}"];
case "SwitchCase":
{
if (node.test) {
parts.push("case ", print("test"), ":");
} else {
parts.push("default:");
}
const consequent = node.consequent.filter(node => node.type !== "EmptyStatement");
if (consequent.length > 0) {
const cons = printSwitchCaseConsequent(path, options, print);
parts.push(consequent.length === 1 && consequent[0].type === "BlockStatement" ? [" ", cons] : indent$9([hardline$g, cons]));
}
return parts;
}
// JSX extensions below.
case "DebuggerStatement":
return ["debugger", semi];
case "ClassDeclaration":
case "ClassExpression":
return printClass(path, options, print);
case "ClassMethod":
case "ClassPrivateMethod":
case "MethodDefinition":
return printClassMethod(path, options, print);
case "ClassProperty":
case "PropertyDefinition":
case "ClassPrivateProperty":
return printClassProperty(path, options, print);
case "TemplateElement":
return replaceTextEndOfLine$9(node.value.raw);
case "TemplateLiteral":
return printTemplateLiteral(path, print, options);
case "TaggedTemplateExpression":
return [print("tag"), print("typeParameters"), print("quasi")];
case "PrivateIdentifier":
return ["#", print("name")];
case "PrivateName":
return ["#", print("id")];
case "InterpreterDirective":
parts.push("#!", node.value, hardline$g);
if (isNextLineEmpty$4(node, options)) {
parts.push(hardline$g);
}
return parts;
// For hack-style pipeline
case "TopicReference":
return "%";
case "ArgumentPlaceholder":
return "?";
case "ModuleExpression":
{
parts.push("module {");
const printed = print("body");
if (printed) {
parts.push(indent$9([hardline$g, printed]), hardline$g);
}
parts.push("}");
return parts;
}
default:
/* istanbul ignore next */
throw new Error("unknown type: " + JSON.stringify(node.type));
}
}
function printDirective(node, options) {
const raw = rawText(node);
const rawContent = raw.slice(1, -1); // Check for the alternate quote, to determine if we're allowed to swap
// the quotes on a DirectiveLiteral.
if (rawContent.includes('"') || rawContent.includes("'")) {
return raw;
}
const enclosingQuote = options.singleQuote ? "'" : '"'; // Directives are exact code unit sequences, which means that you can't
// change the escape sequences they use.
// See https://github.com/prettier/prettier/issues/1555
// and https://tc39.github.io/ecma262/#directive-prologue
return enclosingQuote + rawContent + enclosingQuote;
}
function canAttachComment$1(node) {
return node.type && !isBlockComment(node) && !isLineComment(node) && node.type !== "EmptyStatement" && node.type !== "TemplateElement" && node.type !== "Import" && // `babel-ts` don't have similar node for `class Foo { bar() /* bat */; }`
node.type !== "TSEmptyBodyFunctionExpression";
}
var printerEstree = {
preprocess: printPreprocess$3,
print: genericPrint$6,
embed: embed_1$4,
insertPragma: insertPragma$9,
massageAstNode: clean_1$4,
hasPrettierIgnore(path) {
return hasIgnoreComment(path) || hasJsxIgnoreComment(path);
},
willPrintOwnComments: comments.willPrintOwnComments,
canAttachComment: canAttachComment$1,
printComment: printComment$1,
isBlockComment,
handleComments: {
// TODO: Make this as default behavior
avoidAstMutation: true,
ownLine: comments.handleOwnLineComment,
endOfLine: comments.handleEndOfLineComment,
remaining: comments.handleRemainingComment
},
getCommentChildNodes: comments.getCommentChildNodes
};
const {
builders: {
hardline: hardline$f,
indent: indent$8,
join: join$b
}
} = doc;
function genericPrint$5(path, options, print) {
const node = path.getValue();
switch (node.type) {
case "JsonRoot":
return [print("node"), hardline$f];
case "ArrayExpression":
{
if (node.elements.length === 0) {
return "[]";
}
const printed = path.map(() => path.getValue() === null ? "null" : print(), "elements");
return ["[", indent$8([hardline$f, join$b([",", hardline$f], printed)]), hardline$f, "]"];
}
case "ObjectExpression":
return node.properties.length === 0 ? "{}" : ["{", indent$8([hardline$f, join$b([",", hardline$f], path.map(print, "properties"))]), hardline$f, "}"];
case "ObjectProperty":
return [print("key"), ": ", print("value")];
case "UnaryExpression":
return [node.operator === "+" ? "" : node.operator, print("argument")];
case "NullLiteral":
return "null";
case "BooleanLiteral":
return node.value ? "true" : "false";
case "StringLiteral":
case "NumericLiteral":
return JSON.stringify(node.value);
case "Identifier":
{
const parent = path.getParentNode();
if (parent && parent.type === "ObjectProperty" && parent.key === node) {
return JSON.stringify(node.name);
}
return node.name;
}
case "TemplateLiteral":
// There is only one `TemplateElement`
return print(["quasis", 0]);
case "TemplateElement":
return JSON.stringify(node.value.cooked);
default:
/* istanbul ignore next */
throw new Error("unknown type: " + JSON.stringify(node.type));
}
}
const ignoredProperties$3 = new Set(["start", "end", "extra", "loc", "comments", "leadingComments", "trailingComments", "innerComments", "errors", "range", "tokens"]);
function clean$6(node, newNode
/*, parent*/
) {
const {
type
} = node; // We print quoted key
if (type === "ObjectProperty" && node.key.type === "Identifier") {
newNode.key = {
type: "StringLiteral",
value: node.key.name
};
return;
}
if (type === "UnaryExpression" && node.operator === "+") {
return newNode.argument;
} // We print holes in array as `null`
if (type === "ArrayExpression") {
for (const [index, element] of node.elements.entries()) {
if (element === null) {
newNode.elements.splice(index, 0, {
type: "NullLiteral"
});
}
}
return;
} // We print `TemplateLiteral` as string
if (type === "TemplateLiteral") {
return {
type: "StringLiteral",
value: node.quasis[0].value.cooked
};
}
}
clean$6.ignoredProperties = ignoredProperties$3;
var printerEstreeJson = {
preprocess: printPreprocess$3,
print: genericPrint$5,
massageAstNode: clean$6
};
const CATEGORY_COMMON = "Common"; // format based on https://github.com/prettier/prettier/blob/main/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."
}]
},
bracketSameLine: {
since: "2.4.0",
category: CATEGORY_COMMON,
type: "boolean",
default: false,
description: "Put > of opening tags on the last line instead of on a new line."
}
};
const CATEGORY_JAVASCRIPT = "JavaScript"; // format based on https://github.com/prettier/prettier/blob/main/src/main/core-options.js
var options$5 = {
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`"
}]
},
bracketSameLine: commonOptions.bracketSameLine,
bracketSpacing: commonOptions.bracketSpacing,
jsxBracketSameLine: {
since: "0.17.0",
category: CATEGORY_JAVASCRIPT,
type: "boolean",
description: "Put > on the last line instead of at a new line.",
deprecated: "2.4.0"
},
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 require$$0$7 = require("./parser-babel.js");
var require$$1$3 = require("./parser-flow.js");
var require$$2$4 = require("./parser-typescript.js");
var require$$3$2 = require("./parser-angular.js");
var require$$4$1 = require("./parser-espree.js");
var require$$5$1 = require("./parser-meriyah.js");
var parsers$6 = {
// JS - Babel
get babel() {
return require$$0$7.parsers.babel;
},
get "babel-flow"() {
return require$$0$7.parsers["babel-flow"];
},
get "babel-ts"() {
return require$$0$7.parsers["babel-ts"];
},
get json() {
return require$$0$7.parsers.json;
},
get json5() {
return require$$0$7.parsers.json5;
},
get "json-stringify"() {
return require$$0$7.parsers["json-stringify"];
},
get __js_expression() {
return require$$0$7.parsers.__js_expression;
},
get __vue_expression() {
return require$$0$7.parsers.__vue_expression;
},
get __vue_event_binding() {
return require$$0$7.parsers.__vue_event_binding;
},
// JS - Flow
get flow() {
return require$$1$3.parsers.flow;
},
// JS - TypeScript
get typescript() {
return require$$2$4.parsers.typescript;
},
// JS - Angular Action
get __ng_action() {
return require$$3$2.parsers.__ng_action;
},
// JS - Angular Binding
get __ng_binding() {
return require$$3$2.parsers.__ng_binding;
},
// JS - Angular Interpolation
get __ng_interpolation() {
return require$$3$2.parsers.__ng_interpolation;
},
// JS - Angular Directive
get __ng_directive() {
return require$$3$2.parsers.__ng_directive;
},
// JS - espree
get espree() {
return require$$4$1.parsers.espree;
},
// JS - meriyah
get meriyah() {
return require$$5$1.parsers.meriyah;
},
// JS - Babel Estree
get __babel_estree() {
return require$$0$7.parsers.__babel_estree;
}
};
var name$f = "JavaScript";
var type$f = "programming";
var tmScope$f = "source.js";
var aceMode$f = "javascript";
var codemirrorMode$b = "javascript";
var codemirrorMimeType$b = "text/javascript";
var color$a = "#f1e05a";
var aliases$6 = [
"js",
"node"
];
var extensions$f = [
".js",
"._js",
".bones",
".cjs",
".es",
".es6",
".frag",
".gs",
".jake",
".jsb",
".jscad",
".jsfl",
".jsm",
".jss",
".jsx",
".mjs",
".njs",
".pac",
".sjs",
".ssjs",
".xsjs",
".xsjslib"
];
var filenames$4 = [
"Jakefile"
];
var interpreters$1 = [
"chakra",
"d8",
"gjs",
"js",
"node",
"nodejs",
"qjs",
"rhino",
"v8",
"v8-shell"
];
var languageId$f = 183;
var require$$0$6 = {
name: name$f,
type: type$f,
tmScope: tmScope$f,
aceMode: aceMode$f,
codemirrorMode: codemirrorMode$b,
codemirrorMimeType: codemirrorMimeType$b,
color: color$a,
aliases: aliases$6,
extensions: extensions$f,
filenames: filenames$4,
interpreters: interpreters$1,
languageId: languageId$f
};
var name$e = "TypeScript";
var type$e = "programming";
var color$9 = "#2b7489";
var aliases$5 = [
"ts"
];
var interpreters = [
"deno",
"ts-node"
];
var extensions$e = [
".ts"
];
var tmScope$e = "source.ts";
var aceMode$e = "typescript";
var codemirrorMode$a = "javascript";
var codemirrorMimeType$a = "application/typescript";
var languageId$e = 378;
var require$$1$2 = {
name: name$e,
type: type$e,
color: color$9,
aliases: aliases$5,
interpreters: interpreters,
extensions: extensions$e,
tmScope: tmScope$e,
aceMode: aceMode$e,
codemirrorMode: codemirrorMode$a,
codemirrorMimeType: codemirrorMimeType$a,
languageId: languageId$e
};
var name$d = "TSX";
var type$d = "programming";
var group$e = "TypeScript";
var extensions$d = [
".tsx"
];
var tmScope$d = "source.tsx";
var aceMode$d = "javascript";
var codemirrorMode$9 = "jsx";
var codemirrorMimeType$9 = "text/jsx";
var languageId$d = 94901924;
var require$$2$3 = {
name: name$d,
type: type$d,
group: group$e,
extensions: extensions$d,
tmScope: tmScope$d,
aceMode: aceMode$d,
codemirrorMode: codemirrorMode$9,
codemirrorMimeType: codemirrorMimeType$9,
languageId: languageId$d
};
var name$c = "JSON";
var type$c = "data";
var tmScope$c = "source.json";
var aceMode$c = "json";
var codemirrorMode$8 = "javascript";
var codemirrorMimeType$8 = "application/json";
var extensions$c = [
".json",
".avsc",
".geojson",
".gltf",
".har",
".ice",
".JSON-tmLanguage",
".jsonl",
".mcmeta",
".tfstate",
".tfstate.backup",
".topojson",
".webapp",
".webmanifest",
".yy",
".yyp"
];
var filenames$3 = [
".arcconfig",
".htmlhintrc",
".imgbotconfig",
".tern-config",
".tern-project",
".watchmanconfig",
"Pipfile.lock",
"composer.lock",
"mcmod.info"
];
var languageId$c = 174;
var require$$3$1 = {
name: name$c,
type: type$c,
tmScope: tmScope$c,
aceMode: aceMode$c,
codemirrorMode: codemirrorMode$8,
codemirrorMimeType: codemirrorMimeType$8,
extensions: extensions$c,
filenames: filenames$3,
languageId: languageId$c
};
var name$b = "JSON with Comments";
var type$b = "data";
var group$d = "JSON";
var tmScope$b = "source.js";
var aceMode$b = "javascript";
var codemirrorMode$7 = "javascript";
var codemirrorMimeType$7 = "text/javascript";
var aliases$4 = [
"jsonc"
];
var extensions$b = [
".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",
"api-extractor.json",
"devcontainer.json",
"jsconfig.json",
"language-configuration.json",
"tsconfig.json",
"tslint.json"
];
var languageId$b = 423;
var require$$4 = {
name: name$b,
type: type$b,
group: group$d,
tmScope: tmScope$b,
aceMode: aceMode$b,
codemirrorMode: codemirrorMode$7,
codemirrorMimeType: codemirrorMimeType$7,
aliases: aliases$4,
extensions: extensions$b,
filenames: filenames$2,
languageId: languageId$b
};
var name$a = "JSON5";
var type$a = "data";
var extensions$a = [
".json5"
];
var tmScope$a = "source.js";
var aceMode$a = "javascript";
var codemirrorMode$6 = "javascript";
var codemirrorMimeType$6 = "application/json";
var languageId$a = 175;
var require$$5 = {
name: name$a,
type: type$a,
extensions: extensions$a,
tmScope: tmScope$a,
aceMode: aceMode$a,
codemirrorMode: codemirrorMode$6,
codemirrorMimeType: codemirrorMimeType$6,
languageId: languageId$a
};
const languages$7 = [createLanguage(require$$0$6, data => ({
since: "0.0.0",
parsers: ["babel", "espree", "meriyah", "babel-flow", "babel-ts", "flow", "typescript"],
vscodeLanguageIds: ["javascript", "mongo"],
interpreters: [...data.interpreters, // https://github.com/google/zx
"zx"],
extensions: [...data.extensions.filter(extension => extension !== ".jsx"), // WeiXin Script (Weixin Mini Programs)
// https://developers.weixin.qq.com/miniprogram/en/dev/framework/view/wxs/
".wxs"]
})), createLanguage(require$$0$6, () => ({
name: "Flow",
since: "0.0.0",
parsers: ["flow", "babel-flow"],
vscodeLanguageIds: ["javascript"],
aliases: [],
filenames: [],
extensions: [".js.flow"]
})), createLanguage(require$$0$6, () => ({
name: "JSX",
since: "0.0.0",
parsers: ["babel", "babel-flow", "babel-ts", "flow", "typescript", "espree", "meriyah"],
vscodeLanguageIds: ["javascriptreact"],
aliases: undefined,
filenames: undefined,
extensions: [".jsx"],
group: "JavaScript",
interpreters: undefined,
tmScope: "source.js.jsx",
aceMode: "javascript",
codemirrorMode: "jsx",
codemirrorMimeType: "text/jsx",
color: undefined
})), createLanguage(require$$1$2, () => ({
since: "1.4.0",
parsers: ["typescript", "babel-ts"],
vscodeLanguageIds: ["typescript"]
})), createLanguage(require$$2$3, () => ({
since: "1.4.0",
parsers: ["typescript", "babel-ts"],
vscodeLanguageIds: ["typescriptreact"]
})), createLanguage(require$$3$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$$3$1, data => ({
since: "1.5.0",
parsers: ["json"],
vscodeLanguageIds: ["json"],
extensions: data.extensions.filter(extension => extension !== ".jsonl")
})), createLanguage(require$$4, data => ({
since: "1.5.0",
parsers: ["json"],
vscodeLanguageIds: ["jsonc"],
filenames: [...data.filenames, ".eslintrc"]
})), createLanguage(require$$5, () => ({
since: "1.13.0",
parsers: ["json5"],
vscodeLanguageIds: ["json5"]
}))];
const printers$5 = {
estree: printerEstree,
"estree-json": printerEstreeJson
};
var languageJs = {
languages: languages$7,
options: options$5,
printers: printers$5,
parsers: parsers$6
};
const {
isFrontMatterNode: isFrontMatterNode$4
} = util$5;
const ignoredProperties$2 = new Set(["raw", // front-matter
"raws", "sourceIndex", "source", "before", "after", "trailingComma"]);
function clean$5(ast, newObj, parent) {
if (isFrontMatterNode$4(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$4(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_1(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 Number.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;
}
}
clean$5.ignoredProperties = ignoredProperties$2;
function cleanCSSStrings(value) {
return value.replace(/'/g, '"').replace(/\\([^\dA-Fa-f])/g, "$1");
}
var clean_1$3 = clean$5;
const {
builders: {
hardline: hardline$e,
markAsRoot: markAsRoot$3
}
} = doc;
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$3([node.startDelimiter, hardline$e, doc, doc ? hardline$e : "", node.endDelimiter]);
}
}
var print_1 = print$1;
const {
builders: {
hardline: hardline$d
}
} = doc;
function embed$4(path, print, textToDoc
/*, options */
) {
const node = path.getValue();
if (node.type === "front-matter") {
const doc = print_1(node, textToDoc);
return doc ? [doc, hardline$d] : "";
}
}
var embed_1$3 = embed$4;
const frontMatterRegex = new RegExp("^(?-{3}|\\+{3})" + // trailing spaces after delimiters are allowed
"(?[^\\n]*)" + "\\n(?:|(?.*?)\\n)" + // In some markdown processors such as pandoc,
// "..." can be used as the end delimiter for YAML front-matter.
// Adding `\.{3}` make the regex matches `+++\n...`, but we'll exclude it later
"(?\\k|\\.{3})" + "[^\\S\\n]*(?:\\n|$)", "s");
function parse(text) {
const match = text.match(frontMatterRegex);
if (!match) {
return {
content: text
};
}
const {
startDelimiter,
language,
value = "",
endDelimiter
} = match.groups;
let lang = language.trim() || "yaml";
if (startDelimiter === "+++") {
lang = "toml";
} // Only allow yaml to parse with a different end delimiter
if (lang !== "yaml" && startDelimiter !== endDelimiter) {
return {
content: text
};
}
const [raw] = match;
const frontMatter = {
type: "front-matter",
lang,
value,
startDelimiter,
endDelimiter,
raw: raw.replace(/\n$/, "")
};
return {
frontMatter,
content: raw.replace(/[^\n]/g, " ") + text.slice(raw.length)
};
}
var parse_1 = parse;
function hasPragma$3(text) {
return pragma$5.hasPragma(parse_1(text).content);
}
function insertPragma$8(text) {
const {
frontMatter,
content
} = parse_1(text);
return (frontMatter ? frontMatter.raw + "\n\n" : "") + pragma$5.insertPragma(content);
}
var pragma$4 = {
hasPragma: hasPragma$3,
insertPragma: insertPragma$8
};
const {
isNonEmptyArray: isNonEmptyArray$6
} = util$5;
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"]);
const moduleRuleNames = new Set(["import", "use", "forward"]);
function getAncestorCounter$1(path, typeOrTypes) {
const types = Array.isArray(typeOrTypes) ? typeOrTypes : [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 getPropOfDeclNode$1(path) {
const declAncestorNode = getAncestorNode$2(path, "css-decl");
return declAncestorNode && declAncestorNode.prop && declAncestorNode.prop.toLowerCase();
}
function hasSCSSInterpolation(groupList) {
if (isNonEmptyArray$6(groupList)) {
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 (isNonEmptyArray$6(groupList)) {
for (let i = 0; i < groupList.length; i++) {
if (groupList[i].type === "string" || groupList[i].type === "func") {
return true;
}
}
}
return false;
}
function isSCSS$1(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 Boolean(node && node.type === "word" && node.value.startsWith("$"));
}
function isWideKeywords$1(value) {
return ["initial", "inherit", "unset", "revert"].includes(value.toLowerCase());
}
function isKeyframeAtRuleKeywords$1(path, value) {
const atRuleAncestorNode = getAncestorNode$2(path, "css-atrule");
return atRuleAncestorNode && atRuleAncestorNode.name && atRuleAncestorNode.name.toLowerCase().endsWith("keyframes") && ["from", "to"].includes(value.toLowerCase());
}
function maybeToLowerCase$1(value) {
return value.includes("$") || value.includes("@") || value.includes("#") || value.startsWith("%") || value.startsWith("--") || value.startsWith(":--") || value.includes("(") && value.includes(")") ? value : value.toLowerCase();
}
function insideValueFunctionNode$1(path, functionName) {
const funcAncestorNode = getAncestorNode$2(path, "value-func");
return funcAncestorNode && funcAncestorNode.value && funcAncestorNode.value.toLowerCase() === functionName;
}
function insideICSSRuleNode$1(path) {
const ruleAncestorNode = getAncestorNode$2(path, "css-rule");
return ruleAncestorNode && ruleAncestorNode.raws && ruleAncestorNode.raws.selector && (ruleAncestorNode.raws.selector.startsWith(":import") || ruleAncestorNode.raws.selector.startsWith(":export"));
}
function insideAtRuleNode$1(path, atRuleNameOrAtRuleNames) {
const atRuleNames = Array.isArray(atRuleNameOrAtRuleNames) ? atRuleNameOrAtRuleNames : [atRuleNameOrAtRuleNames];
const atRuleAncestorNode = getAncestorNode$2(path, "css-atrule");
return atRuleAncestorNode && atRuleNames.includes(atRuleAncestorNode.name.toLowerCase());
}
function insideURLFunctionInImportAtRuleNode$1(path) {
const node = path.getValue();
const atRuleAncestorNode = getAncestorNode$2(path, "css-atrule");
return atRuleAncestorNode && atRuleAncestorNode.name === "import" && node.groups[0].value === "url" && node.groups.length === 2;
}
function isURLFunctionNode$1(node) {
return node.type === "value-func" && node.value.toLowerCase() === "url";
}
function isLastNode$1(path, node) {
const parentNode = path.getParentNode();
/* istanbul ignore next */
if (!parentNode) {
return false;
}
const {
nodes
} = parentNode;
return nodes && nodes.indexOf(node) === nodes.length - 1;
}
function isDetachedRulesetDeclarationNode$1(node) {
// If a Less file ends up being parsed with the SCSS parser, Less
// variable declarations will be parsed as atrules with names ending
// with a colon, so keep the original case then.
/* 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$1(node) {
return node.type === "value-word" && ["from", "through", "end"].includes(node.value);
}
function isIfElseKeywordNode$1(node) {
return node.type === "value-word" && ["and", "or", "not"].includes(node.value);
}
function isEachKeywordNode$1(node) {
return node.type === "value-word" && node.value === "in";
}
function isMultiplicationNode$1(node) {
return node.type === "value-operator" && node.value === "*";
}
function isDivisionNode$1(node) {
return node.type === "value-operator" && node.value === "/";
}
function isAdditionNode$1(node) {
return node.type === "value-operator" && node.value === "+";
}
function isSubtractionNode$1(node) {
return node.type === "value-operator" && node.value === "-";
}
function isModuloNode(node) {
return node.type === "value-operator" && node.value === "%";
}
function isMathOperatorNode$1(node) {
return isMultiplicationNode$1(node) || isDivisionNode$1(node) || isAdditionNode$1(node) || isSubtractionNode$1(node) || isModuloNode(node);
}
function isEqualityOperatorNode$1(node) {
return node.type === "value-word" && ["==", "!="].includes(node.value);
}
function isRelationalOperatorNode$1(node) {
return node.type === "value-word" && ["<", ">", "<=", ">="].includes(node.value);
}
function isSCSSControlDirectiveNode$1(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$1(node) {
return node.raws && node.raws.params && /^\(\s*\)$/.test(node.raws.params);
}
function isTemplatePlaceholderNode$1(node) {
return node.name.startsWith("prettier-placeholder");
}
function isTemplatePropNode$1(node) {
return node.prop.startsWith("@prettier-placeholder");
}
function isPostcssSimpleVarNode$1(currentNode, nextNode) {
return currentNode.value === "$$" && currentNode.type === "value-func" && nextNode && nextNode.type === "value-word" && !nextNode.raws.before;
}
function hasComposesNode$1(node) {
return node.value && node.value.type === "value-root" && node.value.group && node.value.group.type === "value-value" && node.prop.toLowerCase() === "composes";
}
function hasParensAroundNode$1(node) {
return node.value && node.value.group && node.value.group.group && node.value.group.group.type === "value-paren_group" && node.value.group.group.open !== null && node.value.group.group.close !== null;
}
function hasEmptyRawBefore$1(node) {
return node.raws && node.raws.before === "";
}
function isKeyValuePairNode$1(node) {
return node.type === "value-comma_group" && node.groups && node.groups[1] && node.groups[1].type === "value-colon";
}
function isKeyValuePairInParenGroupNode(node) {
return node.type === "value-paren_group" && node.groups && node.groups[0] && isKeyValuePairNode$1(node.groups[0]);
}
function isSCSSMapItemNode$1(path) {
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$2(path, "css-decl"); // SCSS map declaration (i.e. `$map: (key: value, other-key: other-value)`)
if (declNode && declNode.prop && declNode.prop.startsWith("$")) {
return true;
} // List as value of key inside SCSS map (i.e. `$map: (key: (value other-value other-other-value))`)
if (isKeyValuePairInParenGroupNode(parentParentNode)) {
return true;
} // SCSS Map is argument of function (i.e. `func((key: value, other-key: other-value))`)
if (parentParentNode.type === "value-func") {
return true;
}
return false;
}
function isInlineValueCommentNode$1(node) {
return node.type === "value-comment" && node.inline;
}
function isHashNode$1(node) {
return node.type === "value-word" && node.value === "#";
}
function isLeftCurlyBraceNode$1(node) {
return node.type === "value-word" && node.value === "{";
}
function isRightCurlyBraceNode$1(node) {
return node.type === "value-word" && node.value === "}";
}
function isWordNode$1(node) {
return ["value-word", "value-atword"].includes(node.type);
}
function isColonNode$1(node) {
return node && node.type === "value-colon";
}
function isKeyInValuePairNode$1(node, parentNode) {
if (!isKeyValuePairNode$1(parentNode)) {
return false;
}
const {
groups
} = parentNode;
const index = groups.indexOf(node);
if (index === -1) {
return false;
}
return isColonNode$1(groups[index + 1]);
}
function isMediaAndSupportsKeywords$1(node) {
return node.value && ["not", "and", "or"].includes(node.value.toLowerCase());
}
function isColorAdjusterFuncNode$1(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$1(options) {
return options.parser === "css" || options.parser === "less";
}
function lastLineHasInlineComment$1(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) => 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;
}
function isAtWordPlaceholderNode$1(node) {
return node && node.type === "value-atword" && node.value.startsWith("prettier-placeholder-");
}
function isModuleRuleName(name) {
return moduleRuleNames.has(name);
}
var utils$4 = {
getAncestorCounter: getAncestorCounter$1,
getAncestorNode: getAncestorNode$2,
getPropOfDeclNode: getPropOfDeclNode$1,
hasSCSSInterpolation,
hasStringOrFunction,
maybeToLowerCase: maybeToLowerCase$1,
insideValueFunctionNode: insideValueFunctionNode$1,
insideICSSRuleNode: insideICSSRuleNode$1,
insideAtRuleNode: insideAtRuleNode$1,
insideURLFunctionInImportAtRuleNode: insideURLFunctionInImportAtRuleNode$1,
isKeyframeAtRuleKeywords: isKeyframeAtRuleKeywords$1,
isWideKeywords: isWideKeywords$1,
isSCSS: isSCSS$1,
isSCSSVariable,
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,
isModuloNode,
isMathOperatorNode: isMathOperatorNode$1,
isEachKeywordNode: isEachKeywordNode$1,
isForKeywordNode: isForKeywordNode$1,
isURLFunctionNode: isURLFunctionNode$1,
isIfElseKeywordNode: isIfElseKeywordNode$1,
hasComposesNode: hasComposesNode$1,
hasParensAroundNode: hasParensAroundNode$1,
hasEmptyRawBefore: hasEmptyRawBefore$1,
isSCSSNestedPropertyNode,
isDetachedRulesetCallNode: isDetachedRulesetCallNode$1,
isTemplatePlaceholderNode: isTemplatePlaceholderNode$1,
isTemplatePropNode: isTemplatePropNode$1,
isPostcssSimpleVarNode: isPostcssSimpleVarNode$1,
isKeyValuePairNode: isKeyValuePairNode$1,
isKeyValuePairInParenGroupNode,
isKeyInValuePairNode: isKeyInValuePairNode$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,
stringifyNode,
isAtWordPlaceholderNode: isAtWordPlaceholderNode$1,
isModuleRuleName
};
var lineColumnToIndex = function (lineColumn, text) {
let index = 0;
for (let i = 0; i < lineColumn.line - 1; ++i) {
index = text.indexOf("\n", index) + 1;
}
return index + lineColumn.column;
};
const {
getLast: getLast$4,
skipEverythingButNewLine
} = util$5;
function calculateLocStart(node, text) {
// value-* nodes have this
if (typeof node.sourceIndex === "number") {
return node.sourceIndex;
}
return node.source ? lineColumnToIndex(node.source.start, text) - 1 : null;
}
function calculateLocEnd(node, text) {
if (node.type === "css-comment" && node.inline) {
return skipEverythingButNewLine(text, node.source.startOffset);
}
const endNode = node.nodes && getLast$4(node.nodes);
if (endNode && node.source && !node.source.end) {
node = endNode;
}
if (node.source && node.source.end) {
return lineColumnToIndex(node.source.end, text);
}
return null;
}
function calculateLoc(node, text) {
if (node.source) {
node.source.startOffset = calculateLocStart(node, text);
node.source.endOffset = calculateLocEnd(node, text);
}
for (const key in node) {
const child = node[key];
if (key === "source" || !child || typeof child !== "object") {
continue;
}
if (child.type === "value-root" || child.type === "value-unknown") {
calculateValueNodeLoc(child, getValueRootOffset(node), child.text || child.value);
} else {
calculateLoc(child, text);
}
}
}
function calculateValueNodeLoc(node, rootOffset, text) {
if (node.source) {
node.source.startOffset = calculateLocStart(node, text) + rootOffset;
node.source.endOffset = calculateLocEnd(node, text) + rootOffset;
}
for (const key in node) {
const child = node[key];
if (key === "source" || !child || typeof child !== "object") {
continue;
}
calculateValueNodeLoc(child, rootOffset, text);
}
}
function getValueRootOffset(node) {
let result = node.source.startOffset;
if (typeof node.prop === "string") {
result += node.prop.length;
}
if (node.type === "css-atrule" && typeof node.name === "string") {
result += 1 + node.name.length + node.raws.afterName.match(/^\s*:?\s*/)[0].length;
}
if (node.type !== "css-atrule" && node.raws && typeof node.raws.between === "string") {
result += node.raws.between.length;
}
return result;
}
/**
* Workaround for a bug: quotes and asterisks in inline comments corrupt loc data of subsequent nodes.
* This function replaces the quotes and asterisks with spaces. Later, when the comments are printed,
* their content is extracted from the original text.
* - https://github.com/prettier/prettier/issues/7780
* - https://github.com/shellscape/postcss-less/issues/145
* - https://github.com/prettier/prettier/issues/8130
* @param text {string}
*/
function replaceQuotesInInlineComments(text) {
/** @typedef { 'initial' | 'single-quotes' | 'double-quotes' | 'url' | 'comment-block' | 'comment-inline' } State */
/** @type {State} */
let state = "initial";
/** @type {State} */
let stateToReturnFromQuotes = "initial";
let inlineCommentStartIndex;
let inlineCommentContainsQuotes = false;
const inlineCommentsToReplace = [];
for (let i = 0; i < text.length; i++) {
const c = text[i];
switch (state) {
case "initial":
if (c === "'") {
state = "single-quotes";
continue;
}
if (c === '"') {
state = "double-quotes";
continue;
}
if ((c === "u" || c === "U") && text.slice(i, i + 4).toLowerCase() === "url(") {
state = "url";
i += 3;
continue;
}
if (c === "*" && text[i - 1] === "/") {
state = "comment-block";
continue;
}
if (c === "/" && text[i - 1] === "/") {
state = "comment-inline";
inlineCommentStartIndex = i - 1;
continue;
}
continue;
case "single-quotes":
if (c === "'" && text[i - 1] !== "\\") {
state = stateToReturnFromQuotes;
stateToReturnFromQuotes = "initial";
}
if (c === "\n" || c === "\r") {
return text; // invalid input
}
continue;
case "double-quotes":
if (c === '"' && text[i - 1] !== "\\") {
state = stateToReturnFromQuotes;
stateToReturnFromQuotes = "initial";
}
if (c === "\n" || c === "\r") {
return text; // invalid input
}
continue;
case "url":
if (c === ")") {
state = "initial";
}
if (c === "\n" || c === "\r") {
return text; // invalid input
}
if (c === "'") {
state = "single-quotes";
stateToReturnFromQuotes = "url";
continue;
}
if (c === '"') {
state = "double-quotes";
stateToReturnFromQuotes = "url";
continue;
}
continue;
case "comment-block":
if (c === "/" && text[i - 1] === "*") {
state = "initial";
}
continue;
case "comment-inline":
if (c === '"' || c === "'" || c === "*") {
inlineCommentContainsQuotes = true;
}
if (c === "\n" || c === "\r") {
if (inlineCommentContainsQuotes) {
inlineCommentsToReplace.push([inlineCommentStartIndex, i]);
}
state = "initial";
inlineCommentContainsQuotes = false;
}
continue;
}
}
for (const [start, end] of inlineCommentsToReplace) {
text = text.slice(0, start) + text.slice(start, end).replace(/["'*]/g, " ") + text.slice(end);
}
return text;
}
function locStart$e(node) {
return node.source.startOffset;
}
function locEnd$d(node) {
return node.source.endOffset;
}
var loc$5 = {
locStart: locStart$e,
locEnd: locEnd$d,
calculateLoc,
replaceQuotesInInlineComments
};
const {
printNumber,
printString,
hasNewline,
isFrontMatterNode: isFrontMatterNode$3,
isNextLineEmpty: isNextLineEmpty$3,
isNonEmptyArray: isNonEmptyArray$5
} = util$5;
const {
builders: {
join: join$a,
line: line$d,
hardline: hardline$c,
softline: softline$a,
group: group$c,
fill: fill$6,
indent: indent$7,
dedent: dedent$2,
ifBreak: ifBreak$8,
breakParent: breakParent$5
},
utils: {
removeLines,
getDocParts: getDocParts$5
}
} = doc;
const {
insertPragma: insertPragma$7
} = pragma$4;
const {
getAncestorNode: getAncestorNode$1,
getPropOfDeclNode,
maybeToLowerCase,
insideValueFunctionNode,
insideICSSRuleNode,
insideAtRuleNode,
insideURLFunctionInImportAtRuleNode,
isKeyframeAtRuleKeywords,
isWideKeywords,
isSCSS,
isLastNode,
isLessParser,
isSCSSControlDirectiveNode,
isDetachedRulesetDeclarationNode,
isRelationalOperatorNode,
isEqualityOperatorNode,
isMultiplicationNode,
isDivisionNode,
isAdditionNode,
isSubtractionNode,
isMathOperatorNode,
isEachKeywordNode,
isForKeywordNode,
isURLFunctionNode,
isIfElseKeywordNode,
hasComposesNode,
hasParensAroundNode,
hasEmptyRawBefore,
isKeyValuePairNode,
isKeyInValuePairNode,
isDetachedRulesetCallNode,
isTemplatePlaceholderNode,
isTemplatePropNode,
isPostcssSimpleVarNode,
isSCSSMapItemNode,
isInlineValueCommentNode,
isHashNode,
isLeftCurlyBraceNode,
isRightCurlyBraceNode,
isWordNode,
isColonNode,
isMediaAndSupportsKeywords,
isColorAdjusterFuncNode,
lastLineHasInlineComment,
isAtWordPlaceholderNode
} = utils$4;
const {
locStart: locStart$d,
locEnd: locEnd$c
} = loc$5;
function shouldPrintComma(options) {
return options.trailingComma === "es5" || options.trailingComma === "all";
}
function genericPrint$4(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 [node.raw, hardline$c];
case "css-root":
{
const nodes = printNodeSequence(path, options, print);
const after = node.raws.after.trim();
return [nodes, after ? ` ${after}` : "", getDocParts$5(nodes).length > 0 ? hardline$c : ""];
}
case "css-comment":
{
const isInlineComment = node.inline || node.raws.inline;
const text = options.originalText.slice(locStart$d(node), locEnd$c(node));
return isInlineComment ? text.trimEnd() : text;
}
case "css-rule":
{
return [print("selector"), node.important ? " !important" : "", node.nodes ? [node.selector && node.selector.type === "selector-unknown" && lastLineHasInlineComment(node.selector.value) ? line$d : " ", "{", node.nodes.length > 0 ? indent$7([hardline$c, printNodeSequence(path, options, print)]) : "", hardline$c, "}", isDetachedRulesetDeclarationNode(node) ? ";" : ""] : ";"];
}
case "css-decl":
{
const parentNode = path.getParentNode();
const {
between: rawBetween
} = node.raws;
const trimmedBetween = rawBetween.trim();
const isColon = trimmedBetween === ":";
let value = hasComposesNode(node) ? removeLines(print("value")) : print("value");
if (!isColon && lastLineHasInlineComment(trimmedBetween)) {
value = indent$7([hardline$c, dedent$2(value)]);
}
return [node.raws.before.replace(/[\s;]/g, ""), insideICSSRuleNode(path) ? node.prop : maybeToLowerCase(node.prop), trimmedBetween.startsWith("//") ? " " : "", trimmedBetween, node.extend ? "" : " ", isLessParser(options) && node.extend && node.selector ? ["extend(", 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 ? [" {", indent$7([softline$a, printNodeSequence(path, options, print)]), softline$a, "}"] : isTemplatePropNode(node) && !parentNode.raws.semicolon && options.originalText[locEnd$c(node) - 1] !== ";" ? "" : options.__isHTMLStyleAttribute && isLastNode(path, node) ? ifBreak$8(";") : ";"];
}
case "css-atrule":
{
const parentNode = path.getParentNode();
const isTemplatePlaceholderNodeWithoutSemiColon = isTemplatePlaceholderNode(node) && !parentNode.raws.semicolon && options.originalText[locEnd$c(node) - 1] !== ";";
if (isLessParser(options)) {
if (node.mixin) {
return [print("selector"), node.important ? " !important" : "", isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"];
}
if (node.function) {
return [node.name, print("params"), isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"];
}
if (node.variable) {
return ["@", node.name, ": ", node.value ? print("value") : "", node.raws.between.trim() ? node.raws.between.trim() + " " : "", node.nodes ? ["{", indent$7([node.nodes.length > 0 ? softline$a : "", printNodeSequence(path, options, print)]), softline$a, "}"] : "", isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"];
}
}
return ["@", // If a Less file ends up being parsed with the SCSS parser, Less
// variable declarations will be parsed as at-rules with names ending
// with a colon, so keep the original case then.
isDetachedRulesetCallNode(node) || node.name.endsWith(":") ? node.name : maybeToLowerCase(node.name), node.params ? [isDetachedRulesetCallNode(node) ? "" : isTemplatePlaceholderNode(node) ? node.raws.afterName === "" ? "" : node.name.endsWith(":") ? " " : /^\s*\n\s*\n/.test(node.raws.afterName) ? [hardline$c, hardline$c] : /^\s*\n/.test(node.raws.afterName) ? hardline$c : " " : " ", print("params")] : "", node.selector ? indent$7([" ", print("selector")]) : "", node.value ? group$c([" ", print("value"), isSCSSControlDirectiveNode(node) ? hasParensAroundNode(node) ? " " : line$d : ""]) : node.name === "else" ? " " : "", node.nodes ? [isSCSSControlDirectiveNode(node) ? "" : node.selector && !node.selector.nodes && typeof node.selector.value === "string" && lastLineHasInlineComment(node.selector.value) || !node.selector && typeof node.params === "string" && lastLineHasInlineComment(node.params) ? line$d : " ", "{", indent$7([node.nodes.length > 0 ? softline$a : "", printNodeSequence(path, options, print)]), softline$a, "}"] : 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(print());
}, "nodes");
return group$c(indent$7(join$a(line$d, parts)));
}
case "media-query":
{
return [join$a(" ", path.map(print, "nodes")), isLastNode(path, node) ? "" : ","];
}
case "media-type":
{
return adjustNumbers(adjustStrings(node.value, options));
}
case "media-feature-expression":
{
if (!node.nodes) {
return node.value;
}
return ["(", ...path.map(print, "nodes"), ")"];
}
case "media-feature":
{
return maybeToLowerCase(adjustStrings(node.value.replace(/ +/g, " "), options));
}
case "media-colon":
{
return [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+\)$/g, ")"), options);
}
case "media-unknown":
{
return node.value;
}
// postcss-selector-parser
case "selector-root":
{
return group$c([insideAtRuleNode(path, "custom-selector") ? [getAncestorNode$1(path, "css-atrule").customSelector, line$d] : "", join$a([",", insideAtRuleNode(path, ["extend", "custom-selector", "nest"]) ? line$d : hardline$c], path.map(print, "nodes"))]);
}
case "selector-selector":
{
return group$c(indent$7(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 [node.namespace ? [node.namespace === true ? "" : node.namespace.trim(), "|"] : "", prevNode.type === "selector-nesting" ? node.value : adjustNumbers(isKeyframeAtRuleKeywords(path, node.value) ? node.value.toLowerCase() : node.value)];
}
case "selector-id":
{
return ["#", node.value];
}
case "selector-class":
{
return [".", adjustNumbers(adjustStrings(node.value, options))];
}
case "selector-attribute":
{
return ["[", node.namespace ? [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$d;
return [leading, node.value, isLastNode(path, node) ? "" : " "];
}
const leading = node.value.trim().startsWith("(") ? line$d : "";
const value = adjustNumbers(adjustStrings(node.value.trim(), options)) || line$d;
return [leading, value];
}
case "selector-universal":
{
return [node.namespace ? [node.namespace === true ? "" : node.namespace.trim(), "|"] : "", node.value];
}
case "selector-pseudo":
{
return [maybeToLowerCase(node.value), isNonEmptyArray$5(node.nodes) ? ["(", join$a(", ", 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(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 = locStart$d(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 = locStart$d(parentNode.open) + 1;
const end = locEnd$c(parentNode.close) - 1;
const selector = options.originalText.slice(start, end).trim();
return lastLineHasInlineComment(selector) ? [breakParent$5, selector] : selector;
}
return node.value;
}
// postcss-values-parser
case "value-value":
case "value-root":
{
return print("group");
}
case "value-comment":
{
return options.originalText.slice(locStart$d(node), locEnd$c(node));
}
case "value-comma_group":
{
const parentNode = path.getParentNode();
const parentParentNode = path.getParentNode(1);
const declAncestorProp = getPropOfDeclNode(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(atRuleAncestorNode);
const hasInlineComment = node.groups.some(node => isInlineValueCommentNode(node));
const printed = path.map(print, "groups");
const parts = [];
const insideURLFunction = insideValueFunctionNode(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(iNextNode) || isAdditionNode(iNode)) {
parts.push(" ");
}
continue;
} // Ignore SCSS @forward wildcard suffix
if (insideAtRuleNode(path, "forward") && iNode.type === "value-word" && iNode.value && iPrevNode.type === "value-word" && iPrevNode.value === "as" && iNextNode.type === "value-operator" && iNextNode.value === "*") {
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("-") && isAtWordPlaceholderNode(iNextNode)) {
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(iNode) || isColonNode(iNextNode)) {
continue;
} // Ignore `@` in Less (i.e. `@@var;`)
if (iNode.type === "value-atword" && iNode.value === "") {
continue;
} // Ignore `~` in Less (i.e. `content: ~"^//* some horrible but needed css hack";`)
if (iNode.value === "~") {
continue;
} // Ignore 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(iNode, iNextNode)) {
continue;
} // Ignore spaces after `#` and after `{` and before `}` in SCSS interpolation (i.e. `#{variable}`)
if (isHashNode(iNode) || isLeftCurlyBraceNode(iNode) || isRightCurlyBraceNode(iNextNode) || isLeftCurlyBraceNode(iNextNode) && hasEmptyRawBefore(iNextNode) || isRightCurlyBraceNode(iNode) && hasEmptyRawBefore(iNextNode)) {
continue;
} // Ignore css variables and interpolation in SCSS (i.e. `--#{$var}`)
if (iNode.value === "--" && isHashNode(iNextNode)) {
continue;
} // Formatting math operations
const isMathOperator = isMathOperatorNode(iNode);
const isNextMathOperator = isMathOperatorNode(iNextNode); // Print spaces before and after math operators beside SCSS interpolation as is
// (i.e. `#{$var}+5`, `#{$var} +5`, `#{$var}+ 5`, `#{$var} + 5`)
// (i.e. `5+#{$var}`, `5 +#{$var}`, `5+ #{$var}`, `5 + #{$var}`)
if ((isMathOperator && isHashNode(iNextNode) || isNextMathOperator && isRightCurlyBraceNode(iNode)) && hasEmptyRawBefore(iNextNode)) {
continue;
} // absolute paths are only parsed as one token if they are part of url(/abs/path) call
// but if you have custom -fb-url(/abs/path/) then it is parsed as "division /" and rest
// of the path. We don't want to put a space after that first division in this case.
if (!iPrevNode && isDivisionNode(iNode)) {
continue;
} // Print spaces before and after addition and subtraction math operators as is in `calc` function
// due to the fact that it is not valid syntax
// (i.e. `calc(1px+1px)`, `calc(1px+ 1px)`, `calc(1px +1px)`, `calc(1px + 1px)`)
if (insideValueFunctionNode(path, "calc") && (isAdditionNode(iNode) || isAdditionNode(iNextNode) || isSubtractionNode(iNode) || isSubtractionNode(iNextNode)) && hasEmptyRawBefore(iNextNode)) {
continue;
} // Print spaces after `+` and `-` in color adjuster functions as is (e.g. `color(red l(+ 20%))`)
// Adjusters with signed numbers (e.g. `color(red l(+20%))`) output as-is.
const isColorAdjusterNode = (isAdditionNode(iNode) || isSubtractionNode(iNode)) && i === 0 && (iNextNode.type === "value-number" || iNextNode.isHex) && parentParentNode && isColorAdjusterFuncNode(parentParentNode) && !hasEmptyRawBefore(iNextNode);
const requireSpaceBeforeOperator = iNextNextNode && iNextNextNode.type === "value-func" || iNextNextNode && isWordNode(iNextNextNode) || iNode.type === "value-func" || isWordNode(iNode);
const requireSpaceAfterOperator = iNextNode.type === "value-func" || isWordNode(iNextNode) || iPrevNode && iPrevNode.type === "value-func" || iPrevNode && isWordNode(iPrevNode); // Formatting `/`, `+`, `-` sign
if (!(isMultiplicationNode(iNextNode) || isMultiplicationNode(iNode)) && !insideValueFunctionNode(path, "calc") && !isColorAdjusterNode && (isDivisionNode(iNextNode) && !requireSpaceBeforeOperator || isDivisionNode(iNode) && !requireSpaceAfterOperator || isAdditionNode(iNextNode) && !requireSpaceBeforeOperator || isAdditionNode(iNode) && !requireSpaceAfterOperator || isSubtractionNode(iNextNode) || isSubtractionNode(iNode)) && (hasEmptyRawBefore(iNextNode) || isMathOperator && (!iPrevNode || iPrevNode && isMathOperatorNode(iPrevNode)))) {
continue;
} // Add `hardline` after inline comment (i.e. `// comment\n foo: bar;`)
if (isInlineValueCommentNode(iNode)) {
if (parentNode.type === "value-paren_group") {
parts.push(dedent$2(hardline$c));
continue;
}
parts.push(hardline$c);
continue;
} // Handle keywords in SCSS control directive
if (isControlDirective && (isEqualityOperatorNode(iNextNode) || isRelationalOperatorNode(iNextNode) || isIfElseKeywordNode(iNextNode) || isEachKeywordNode(iNode) || isForKeywordNode(iNode))) {
parts.push(" ");
continue;
} // At-rule `namespace` should be in one line
if (atRuleAncestorNode && atRuleAncestorNode.name.toLowerCase() === "namespace") {
parts.push(" ");
continue;
} // Formatting `grid` property
if (isGridValue) {
if (iNode.source && iNextNode.source && iNode.source.start.line !== iNextNode.source.start.line) {
parts.push(hardline$c);
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;
}
if (isAtWordPlaceholderNode(iNode) && isAtWordPlaceholderNode(iNextNode) && locEnd$c(iNode) === locStart$d(iNextNode)) {
continue;
} // Be default all values go through `line`
parts.push(line$d);
}
if (hasInlineComment) {
parts.push(breakParent$5);
}
if (didBreak) {
parts.unshift(hardline$c);
}
if (isControlDirective) {
return group$c(indent$7(parts));
} // Indent is not needed for import url when url is very long
// and node has two groups
// when type is value-comma_group
// example @import url("verylongurl") projection,tv
if (insideURLFunctionInImportAtRuleNode(path)) {
return group$c(fill$6(parts));
}
return group$c(indent$7(fill$6(parts)));
}
case "value-paren_group":
{
const parentNode = path.getParentNode();
if (parentNode && isURLFunctionNode(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 [node.open ? print("open") : "", join$a(",", path.map(print, "groups")), node.close ? 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([",", line$d]);
}
res.push(printed[i]);
}
return group$c(indent$7(fill$6(res)));
}
const isSCSSMapItem = isSCSSMapItemNode(path);
const lastItem = getLast_1(node.groups);
const isLastItemComment = lastItem && lastItem.type === "value-comment";
const isKey = isKeyInValuePairNode(node, parentNode);
const printed = group$c([node.open ? print("open") : "", indent$7([softline$a, join$a([",", line$d], path.map(childPath => {
const node = childPath.getValue();
const printed = print(); // Key/Value pair in open paren already indented
if (isKeyValuePairNode(node) && node.type === "value-comma_group" && node.groups && node.groups[0].type !== "value-paren_group" && node.groups[2] && node.groups[2].type === "value-paren_group") {
const parts = getDocParts$5(printed.contents.contents);
parts[1] = group$c(parts[1]);
return group$c(dedent$2(printed));
}
return printed;
}, "groups"))]), ifBreak$8(!isLastItemComment && isSCSS(options.parser, options.originalText) && isSCSSMapItem && shouldPrintComma(options) ? "," : ""), softline$a, node.close ? print("close") : ""], {
shouldBreak: isSCSSMapItem && !isKey
});
return isKey ? dedent$2(printed) : printed;
}
case "value-func":
{
return [node.value, insideAtRuleNode(path, "supports") && isMediaAndSupportsKeywords(node) ? " " : "", print("group")];
}
case "value-paren":
{
return node.value;
}
case "value-number":
{
return [printCssNumber(node.value), maybeToLowerCase(node.unit)];
}
case "value-operator":
{
return node.value;
}
case "value-word":
{
if (node.isColor && node.isHex || isWideKeywords(node.value)) {
return node.value.toLowerCase();
}
return node.value;
}
case "value-colon":
{
const parentNode = path.getParentNode();
const index = parentNode && parentNode.groups.indexOf(node);
const prevNode = index && parentNode.groups[index - 1];
return [node.value, // Don't add spaces on escaped colon `:`, e.g: grid-template-rows: [row-1-00\:00] auto;
prevNode && typeof prevNode.value === "string" && getLast_1(prevNode.value) === "\\" || // Don't add spaces on `:` in `url` function (i.e. `url(fbglyph: cross-outline, fig-white)`)
insideValueFunctionNode(path, "url") ? "" : line$d];
}
// TODO: confirm this code is dead
/* istanbul ignore next */
case "value-comma":
{
return [node.value, " "];
}
case "value-string":
{
return printString(node.raws.quote + node.value + node.raws.quote, options);
}
case "value-atword":
{
return ["@", 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 parts = [];
path.each((pathChild, i, nodes) => {
const prevNode = nodes[i - 1];
if (prevNode && prevNode.type === "css-comment" && prevNode.text.trim() === "prettier-ignore") {
const childNode = pathChild.getValue();
parts.push(options.originalText.slice(locStart$d(childNode), locEnd$c(childNode)));
} else {
parts.push(print());
}
if (i !== nodes.length - 1) {
if (nodes[i + 1].type === "css-comment" && !hasNewline(options.originalText, locStart$d(nodes[i + 1]), {
backwards: true
}) && !isFrontMatterNode$3(nodes[i]) || nodes[i + 1].type === "css-atrule" && nodes[i + 1].name === "else" && nodes[i].type !== "css-comment") {
parts.push(" ");
} else {
parts.push(options.__isHTMLStyleAttribute ? line$d : hardline$c);
if (isNextLineEmpty$3(options.originalText, pathChild.getValue(), locEnd$c) && !isFrontMatterNode$3(nodes[i])) {
parts.push(hardline$c);
}
}
}
}, "nodes");
return parts;
}
const STRING_REGEX = /(["'])(?:(?!\1)[^\\]|\\.)*\1/gs;
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.source + "|" + `(${WORD_PART_REGEX.source})?` + `(${NUMBER_REGEX.source})` + `(${STANDARD_UNIT_REGEX.source})?`, "g");
function adjustStrings(value, options) {
return value.replace(STRING_REGEX, match => printString(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(unit || "") : match);
}
function printCssNumber(rawNumber) {
return printNumber(rawNumber) // Remove trailing `.0`.
.replace(/\.0(?=$|e)/, "");
}
var printerPostcss = {
print: genericPrint$4,
embed: embed_1$3,
insertPragma: insertPragma$7,
massageAstNode: clean_1$3
};
var options$4 = {
singleQuote: commonOptions.singleQuote
};
var parsers$5 = {
// TODO: switch these to just `postcss` and use `language` instead.
get css() {
return require("./parser-postcss.js").parsers.css;
},
get less() {
return require("./parser-postcss.js").parsers.less;
},
get scss() {
return require("./parser-postcss.js").parsers.scss;
}
};
var name$9 = "CSS";
var type$9 = "markup";
var tmScope$9 = "source.css";
var aceMode$9 = "css";
var codemirrorMode$5 = "css";
var codemirrorMimeType$5 = "text/css";
var color$8 = "#563d7c";
var extensions$9 = [
".css"
];
var languageId$9 = 50;
var require$$0$5 = {
name: name$9,
type: type$9,
tmScope: tmScope$9,
aceMode: aceMode$9,
codemirrorMode: codemirrorMode$5,
codemirrorMimeType: codemirrorMimeType$5,
color: color$8,
extensions: extensions$9,
languageId: languageId$9
};
var name$8 = "PostCSS";
var type$8 = "markup";
var tmScope$8 = "source.postcss";
var group$b = "CSS";
var extensions$8 = [
".pcss",
".postcss"
];
var aceMode$8 = "text";
var languageId$8 = 262764437;
var require$$1$1 = {
name: name$8,
type: type$8,
tmScope: tmScope$8,
group: group$b,
extensions: extensions$8,
aceMode: aceMode$8,
languageId: languageId$8
};
var name$7 = "Less";
var type$7 = "markup";
var color$7 = "#1d365d";
var extensions$7 = [
".less"
];
var tmScope$7 = "source.css.less";
var aceMode$7 = "less";
var codemirrorMode$4 = "css";
var codemirrorMimeType$4 = "text/css";
var languageId$7 = 198;
var require$$2$2 = {
name: name$7,
type: type$7,
color: color$7,
extensions: extensions$7,
tmScope: tmScope$7,
aceMode: aceMode$7,
codemirrorMode: codemirrorMode$4,
codemirrorMimeType: codemirrorMimeType$4,
languageId: languageId$7
};
var name$6 = "SCSS";
var type$6 = "markup";
var color$6 = "#c6538c";
var tmScope$6 = "source.css.scss";
var aceMode$6 = "scss";
var codemirrorMode$3 = "css";
var codemirrorMimeType$3 = "text/x-scss";
var extensions$6 = [
".scss"
];
var languageId$6 = 329;
var require$$3 = {
name: name$6,
type: type$6,
color: color$6,
tmScope: tmScope$6,
aceMode: aceMode$6,
codemirrorMode: codemirrorMode$3,
codemirrorMimeType: codemirrorMimeType$3,
extensions: extensions$6,
languageId: languageId$6
};
const languages$6 = [createLanguage(require$$0$5, data => ({
since: "1.4.0",
parsers: ["css"],
vscodeLanguageIds: ["css"],
extensions: [...data.extensions, // `WeiXin Style Sheets`(Weixin Mini Programs)
// https://developers.weixin.qq.com/miniprogram/en/dev/framework/view/wxs/
".wxss"]
})), createLanguage(require$$1$1, () => ({
since: "1.4.0",
parsers: ["css"],
vscodeLanguageIds: ["postcss"]
})), createLanguage(require$$2$2, () => ({
since: "1.4.0",
parsers: ["less"],
vscodeLanguageIds: ["less"]
})), createLanguage(require$$3, () => ({
since: "1.4.0",
parsers: ["scss"],
vscodeLanguageIds: ["scss"]
}))];
const printers$4 = {
postcss: printerPostcss
};
var languageCss = {
languages: languages$6,
options: options$4,
printers: printers$4,
parsers: parsers$5
};
function locStart$c(node) {
return node.loc.start.offset;
}
function locEnd$b(node) {
return node.loc.end.offset;
}
var loc$4 = {
locStart: locStart$c,
locEnd: locEnd$b
};
function clean$4(ast, newNode
/*, parent*/
) {
// (Glimmer/HTML) ignore TextNode
if (ast.type === "TextNode") {
const trimmed = ast.chars.trim();
if (!trimmed) {
return null;
}
newNode.chars = trimmed.replace(/[\t\n\f\r ]+/g, " ");
} // `class` is reformatted
if (ast.type === "AttrNode" && ast.name.toLowerCase() === "class") {
delete newNode.value;
}
}
clean$4.ignoredProperties = new Set(["loc", "selfClosing"]);
var clean_1$2 = clean$4;
var htmlVoidElements = [
"area",
"base",
"basefont",
"bgsound",
"br",
"col",
"command",
"embed",
"frame",
"hr",
"image",
"img",
"input",
"isindex",
"keygen",
"link",
"menuitem",
"meta",
"nextid",
"param",
"source",
"track",
"wbr"
];
function isLastNodeOfSiblings$1(path) {
const node = path.getValue();
const parentNode = path.getParentNode(0);
if (isParentOfSomeType$1(path, ["ElementNode"]) && getLast_1(parentNode.children) === node) {
return true;
}
if (isParentOfSomeType$1(path, ["Block"]) && getLast_1(parentNode.body) === node) {
return true;
}
return false;
}
function isUppercase(string) {
return string.toUpperCase() === string;
}
function isGlimmerComponent(node) {
return isNodeOfSomeType$1(node, ["ElementNode"]) && typeof node.tag === "string" && (isUppercase(node.tag[0]) || node.tag.includes("."));
}
const voidTags = new Set(htmlVoidElements);
function isVoid$1(node) {
return isGlimmerComponent(node) && node.children.every(node => isWhitespaceNode$1(node)) || voidTags.has(node.tag);
}
function isWhitespaceNode$1(node) {
return isNodeOfSomeType$1(node, ["TextNode"]) && !/\S/.test(node.chars);
}
function isNodeOfSomeType$1(node, types) {
return node && types.includes(node.type);
}
function isParentOfSomeType$1(path, types) {
const parentNode = path.getParentNode(0);
return isNodeOfSomeType$1(parentNode, types);
}
function isPreviousNodeOfSomeType$1(path, types) {
const previousNode = getPreviousNode$1(path);
return isNodeOfSomeType$1(previousNode, types);
}
function isNextNodeOfSomeType$1(path, types) {
const nextNode = getNextNode$1(path);
return isNodeOfSomeType$1(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$1(path, lookBack = 1) {
return getSiblingNode(path, -lookBack);
}
function getNextNode$1(path) {
return getSiblingNode(path, 1);
}
function isPrettierIgnoreNode(node) {
return isNodeOfSomeType$1(node, ["MustacheCommentStatement"]) && typeof node.value === "string" && node.value.trim() === "prettier-ignore";
}
function hasPrettierIgnore$8(path) {
const node = path.getValue();
const previousPreviousNode = getPreviousNode$1(path, 2);
return isPrettierIgnoreNode(node) || isPrettierIgnoreNode(previousPreviousNode);
}
var utils$3 = {
getNextNode: getNextNode$1,
getPreviousNode: getPreviousNode$1,
hasPrettierIgnore: hasPrettierIgnore$8,
isLastNodeOfSiblings: isLastNodeOfSiblings$1,
isNextNodeOfSomeType: isNextNodeOfSomeType$1,
isNodeOfSomeType: isNodeOfSomeType$1,
isParentOfSomeType: isParentOfSomeType$1,
isPreviousNodeOfSomeType: isPreviousNodeOfSomeType$1,
isVoid: isVoid$1,
isWhitespaceNode: isWhitespaceNode$1
};
const {
builders: {
dedent: dedent$1,
fill: fill$5,
group: group$a,
hardline: hardline$b,
ifBreak: ifBreak$7,
indent: indent$6,
join: join$9,
line: line$c,
softline: softline$9
},
utils: {
getDocParts: getDocParts$4,
replaceTextEndOfLine: replaceTextEndOfLine$8
}
} = doc;
const {
isNonEmptyArray: isNonEmptyArray$4
} = util$5;
const {
locStart: locStart$b,
locEnd: locEnd$a
} = loc$4;
const {
getNextNode,
getPreviousNode,
hasPrettierIgnore: hasPrettierIgnore$7,
isLastNodeOfSiblings,
isNextNodeOfSomeType,
isNodeOfSomeType,
isParentOfSomeType,
isPreviousNodeOfSomeType,
isVoid,
isWhitespaceNode
} = utils$3;
const NEWLINES_TO_PRESERVE_MAX = 2; // 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(path, options, print) {
const node = path.getValue();
/* istanbul ignore if*/
if (!node) {
return "";
}
if (hasPrettierIgnore$7(path)) {
return options.originalText.slice(locStart$b(node), locEnd$a(node));
}
switch (node.type) {
case "Block":
case "Program":
case "Template":
{
return group$a(path.map(print, "body"));
}
case "ElementNode":
{
const startingTag = group$a(printStartingTag(path, print));
const escapeNextElementNode = options.htmlWhitespaceSensitivity === "ignore" && isNextNodeOfSomeType(path, ["ElementNode"]) ? softline$9 : "";
if (isVoid(node)) {
return [startingTag, escapeNextElementNode];
}
const endingTag = ["", node.tag, ">"];
if (node.children.length === 0) {
return [startingTag, indent$6(endingTag), escapeNextElementNode];
}
if (options.htmlWhitespaceSensitivity === "ignore") {
return [startingTag, indent$6(printChildren$5(path, options, print)), hardline$b, indent$6(endingTag), escapeNextElementNode];
}
return [startingTag, indent$6(group$a(printChildren$5(path, options, print))), indent$6(endingTag), escapeNextElementNode];
}
case "BlockStatement":
{
const pp = path.getParentNode(1);
const isElseIf = pp && pp.inverse && pp.inverse.body.length === 1 && pp.inverse.body[0] === node && pp.inverse.body[0].path.parts[0] === "if";
if (isElseIf) {
return [printElseIfBlock(path, print), printProgram(path, print, options), printInverse(path, print, options)];
}
return [printOpenBlock(path, print), group$a([printProgram(path, print, options), printInverse(path, print, options), printCloseBlock(path, print, options)])];
}
case "ElementModifierStatement":
{
return group$a(["{{", printPathAndParams(path, print), "}}"]);
}
case "MustacheStatement":
{
return group$a([printOpeningMustache(node), printPathAndParams(path, print), printClosingMustache(node)]);
}
case "SubExpression":
{
return group$a(["(", printSubExpressionPathAndParams(path, print), softline$9, ")"]);
}
case "AttrNode":
{
const isText = node.value.type === "TextNode";
const isEmptyText = isText && node.value.chars === ""; // If the text is empty and the value's loc start and end offsets are the
// same, there is no value for this AttrNode and it should be printed
// without the `=""`. Example: `` -> ``
if (isEmptyText && locStart$b(node.value) === locEnd$a(node.value)) {
return node.name;
} // Let's assume quotes inside the content of text nodes are already
// properly escaped with entities, otherwise the parse wouldn't have parsed them.
const quote = isText ? chooseEnclosingQuote(options, node.value.chars).quote : node.value.type === "ConcatStatement" ? chooseEnclosingQuote(options, node.value.parts.filter(part => part.type === "TextNode").map(part => part.chars).join("")).quote : "";
const valueDoc = print("value");
return [node.name, "=", quote, node.name === "class" && quote ? group$a(indent$6(valueDoc)) : valueDoc, quote];
}
case "ConcatStatement":
{
return path.map(print, "parts");
}
case "Hash":
{
return join$9(line$c, path.map(print, "pairs"));
}
case "HashPair":
{
return [node.key, "=", print("value")];
}
case "TextNode":
{
/* if `{{my-component}}` (or any text containing "{{")
* makes it to the TextNode, it means it was escaped,
* so let's print it escaped, ie.; `\{{my-component}}` */
let text = node.chars.replace(/{{/g, "\\{{");
const attrName = getCurrentAttributeName(path);
if (attrName) {
// TODO: format style and srcset attributes
if (attrName === "class") {
const formattedClasses = text.trim().split(/\s+/).join(" ");
let leadingSpace = false;
let trailingSpace = false;
if (isParentOfSomeType(path, ["ConcatStatement"])) {
if (isPreviousNodeOfSomeType(path, ["MustacheStatement"]) && /^\s/.test(text)) {
leadingSpace = true;
}
if (isNextNodeOfSomeType(path, ["MustacheStatement"]) && /\s$/.test(text) && formattedClasses !== "") {
trailingSpace = true;
}
}
return [leadingSpace ? line$c : "", formattedClasses, trailingSpace ? line$c : ""];
}
return replaceTextEndOfLine$8(text);
}
const whitespacesOnlyRE = /^[\t\n\f\r ]*$/;
const isWhitespaceOnly = whitespacesOnlyRE.test(text);
const isFirstElement = !getPreviousNode(path);
const isLastElement = !getNextNode(path);
if (options.htmlWhitespaceSensitivity !== "ignore") {
// https://infra.spec.whatwg.org/#ascii-whitespace
const leadingWhitespacesRE = /^[\t\n\f\r ]*/;
const trailingWhitespacesRE = /[\t\n\f\r ]*$/; // let's remove the file's final newline
// https://github.com/ember-cli/ember-new-output/blob/1a04c67ddd02ccb35e0ff41bb5cbce34b31173ef/.editorconfig#L16
const shouldTrimTrailingNewlines = isLastElement && isParentOfSomeType(path, ["Template"]);
const shouldTrimLeadingNewlines = isFirstElement && isParentOfSomeType(path, ["Template"]);
if (isWhitespaceOnly) {
if (shouldTrimLeadingNewlines || shouldTrimTrailingNewlines) {
return "";
}
let breaks = [line$c];
const newlines = countNewLines(text);
if (newlines) {
breaks = generateHardlines(newlines);
}
if (isLastNodeOfSiblings(path)) {
breaks = breaks.map(newline => dedent$1(newline));
}
return breaks;
}
const [lead] = text.match(leadingWhitespacesRE);
const [tail] = text.match(trailingWhitespacesRE);
let leadBreaks = [];
if (lead) {
leadBreaks = [line$c];
const leadingNewlines = countNewLines(lead);
if (leadingNewlines) {
leadBreaks = generateHardlines(leadingNewlines);
}
text = text.replace(leadingWhitespacesRE, "");
}
let trailBreaks = [];
if (tail) {
if (!shouldTrimTrailingNewlines) {
trailBreaks = [line$c];
const trailingNewlines = countNewLines(tail);
if (trailingNewlines) {
trailBreaks = generateHardlines(trailingNewlines);
}
if (isLastNodeOfSiblings(path)) {
trailBreaks = trailBreaks.map(hardline => dedent$1(hardline));
}
}
text = text.replace(trailingWhitespacesRE, "");
}
return [...leadBreaks, fill$5(getTextValueParts$3(text)), ...trailBreaks];
}
const lineBreaksCount = countNewLines(text);
let leadingLineBreaksCount = countLeadingNewLines(text);
let trailingLineBreaksCount = countTrailingNewLines(text);
if ((isFirstElement || isLastElement) && isWhitespaceOnly && isParentOfSomeType(path, ["Block", "ElementNode", "Template"])) {
return "";
}
if (isWhitespaceOnly && lineBreaksCount) {
leadingLineBreaksCount = Math.min(lineBreaksCount, NEWLINES_TO_PRESERVE_MAX);
trailingLineBreaksCount = 0;
} else {
if (isNextNodeOfSomeType(path, ["BlockStatement", "ElementNode"])) {
trailingLineBreaksCount = Math.max(trailingLineBreaksCount, 1);
}
if (isPreviousNodeOfSomeType(path, ["BlockStatement", "ElementNode"])) {
leadingLineBreaksCount = Math.max(leadingLineBreaksCount, 1);
}
}
let leadingSpace = "";
let trailingSpace = "";
if (trailingLineBreaksCount === 0 && isNextNodeOfSomeType(path, ["MustacheStatement"])) {
trailingSpace = " ";
}
if (leadingLineBreaksCount === 0 && isPreviousNodeOfSomeType(path, ["MustacheStatement"])) {
leadingSpace = " ";
}
if (isFirstElement) {
leadingLineBreaksCount = 0;
leadingSpace = "";
}
if (isLastElement) {
trailingLineBreaksCount = 0;
trailingSpace = "";
}
text = text.replace(/^[\t\n\f\r ]+/g, leadingSpace).replace(/[\t\n\f\r ]+$/, trailingSpace);
return [...generateHardlines(leadingLineBreaksCount), fill$5(getTextValueParts$3(text)), ...generateHardlines(trailingLineBreaksCount)];
}
case "MustacheCommentStatement":
{
const start = locStart$b(node);
const end = locEnd$a(node); // Starts with `{{~`
const isLeftWhiteSpaceSensitive = options.originalText.charAt(start + 2) === "~"; // Ends with `{{~`
const isRightWhitespaceSensitive = options.originalText.charAt(end - 3) === "~";
const dashes = node.value.includes("}}") ? "--" : "";
return ["{{", isLeftWhiteSpaceSensitive ? "~" : "", "!", dashes, node.value, dashes, isRightWhitespaceSensitive ? "~" : "", "}}"];
}
case "PathExpression":
{
return node.original;
}
case "BooleanLiteral":
{
return String(node.value);
}
case "CommentStatement":
{
return [""];
}
case "StringLiteral":
{
return printStringLiteral(node.value, options);
}
case "NumberLiteral":
{
return String(node.value);
}
case "UndefinedLiteral":
{
return "undefined";
}
case "NullLiteral":
{
return "null";
}
/* istanbul ignore next */
default:
throw new Error("unknown glimmer type: " + JSON.stringify(node.type));
}
}
/* ElementNode print helpers */
function sortByLoc(a, b) {
return locStart$b(a) - locStart$b(b);
}
function printStartingTag(path, print) {
const node = path.getValue();
const types = ["attributes", "modifiers", "comments"].filter(property => isNonEmptyArray$4(node[property]));
const attributes = types.flatMap(type => node[type]).sort(sortByLoc);
for (const attributeType of types) {
path.each(attributePath => {
const index = attributes.indexOf(attributePath.getValue());
attributes.splice(index, 1, [line$c, print()]);
}, attributeType);
}
if (isNonEmptyArray$4(node.blockParams)) {
attributes.push(line$c, printBlockParams(node));
}
return ["<", node.tag, indent$6(attributes), printStartingTagEndMarker(node)];
}
function printChildren$5(path, options, print) {
const node = path.getValue();
const isEmpty = node.children.every(node => isWhitespaceNode(node));
if (options.htmlWhitespaceSensitivity === "ignore" && isEmpty) {
return "";
}
return path.map((childPath, childIndex) => {
const printedChild = print();
if (childIndex === 0 && options.htmlWhitespaceSensitivity === "ignore") {
return [softline$9, printedChild];
}
return printedChild;
}, "children");
}
function printStartingTagEndMarker(node) {
if (isVoid(node)) {
return ifBreak$7([softline$9, "/>"], [" />", softline$9]);
}
return ifBreak$7([softline$9, ">"], ">");
}
/* MustacheStatement print helpers */
function printOpeningMustache(node) {
const mustache = node.escaped === false ? "{{{" : "{{";
const strip = node.strip && node.strip.open ? "~" : "";
return [mustache, strip];
}
function printClosingMustache(node) {
const mustache = node.escaped === false ? "}}}" : "}}";
const strip = node.strip && node.strip.close ? "~" : "";
return [strip, mustache];
}
/* BlockStatement print helpers */
function printOpeningBlockOpeningMustache(node) {
const opening = printOpeningMustache(node);
const strip = node.openStrip.open ? "~" : "";
return [opening, strip, "#"];
}
function printOpeningBlockClosingMustache(node) {
const closing = printClosingMustache(node);
const strip = node.openStrip.close ? "~" : "";
return [strip, closing];
}
function printClosingBlockOpeningMustache(node) {
const opening = printOpeningMustache(node);
const strip = node.closeStrip.open ? "~" : "";
return [opening, strip, "/"];
}
function printClosingBlockClosingMustache(node) {
const closing = printClosingMustache(node);
const strip = node.closeStrip.close ? "~" : "";
return [strip, closing];
}
function printInverseBlockOpeningMustache(node) {
const opening = printOpeningMustache(node);
const strip = node.inverseStrip.open ? "~" : "";
return [opening, strip];
}
function printInverseBlockClosingMustache(node) {
const closing = printClosingMustache(node);
const strip = node.inverseStrip.close ? "~" : "";
return [strip, closing];
}
function printOpenBlock(path, print) {
const node = path.getValue();
const openingMustache = printOpeningBlockOpeningMustache(node);
const closingMustache = printOpeningBlockClosingMustache(node);
const attributes = [printPath(path, print)];
const params = printParams(path, print);
if (params) {
attributes.push(line$c, params);
}
if (isNonEmptyArray$4(node.program.blockParams)) {
const block = printBlockParams(node.program);
attributes.push(line$c, block);
}
return group$a([openingMustache, indent$6(attributes), softline$9, closingMustache]);
}
function printElseBlock(node, options) {
return [options.htmlWhitespaceSensitivity === "ignore" ? hardline$b : "", printInverseBlockOpeningMustache(node), "else", printInverseBlockClosingMustache(node)];
}
function printElseIfBlock(path, print) {
const parentNode = path.getParentNode(1);
return [printInverseBlockOpeningMustache(parentNode), "else if ", printParams(path, print), printInverseBlockClosingMustache(parentNode)];
}
function printCloseBlock(path, print, options) {
const node = path.getValue();
if (options.htmlWhitespaceSensitivity === "ignore") {
const escape = blockStatementHasOnlyWhitespaceInProgram(node) ? softline$9 : hardline$b;
return [escape, printClosingBlockOpeningMustache(node), print("path"), printClosingBlockClosingMustache(node)];
}
return [printClosingBlockOpeningMustache(node), print("path"), printClosingBlockClosingMustache(node)];
}
function blockStatementHasOnlyWhitespaceInProgram(node) {
return isNodeOfSomeType(node, ["BlockStatement"]) && node.program.body.every(node => isWhitespaceNode(node));
}
function blockStatementHasElseIf(node) {
return blockStatementHasElse(node) && node.inverse.body.length === 1 && isNodeOfSomeType(node.inverse.body[0], ["BlockStatement"]) && node.inverse.body[0].path.parts[0] === "if";
}
function blockStatementHasElse(node) {
return isNodeOfSomeType(node, ["BlockStatement"]) && node.inverse;
}
function printProgram(path, print, options) {
const node = path.getValue();
if (blockStatementHasOnlyWhitespaceInProgram(node)) {
return "";
}
const program = print("program");
if (options.htmlWhitespaceSensitivity === "ignore") {
return indent$6([hardline$b, program]);
}
return indent$6(program);
}
function printInverse(path, print, options) {
const node = path.getValue();
const inverse = print("inverse");
const printed = options.htmlWhitespaceSensitivity === "ignore" ? [hardline$b, inverse] : inverse;
if (blockStatementHasElseIf(node)) {
return printed;
}
if (blockStatementHasElse(node)) {
return [printElseBlock(node, options), indent$6(printed)];
}
return "";
}
/* TextNode print helpers */
function getTextValueParts$3(value) {
return getDocParts$4(join$9(line$c, splitByHtmlWhitespace$1(value)));
}
function splitByHtmlWhitespace$1(string) {
return string.split(/[\t\n\f\r ]+/);
}
function getCurrentAttributeName(path) {
for (let depth = 0; depth < 2; depth++) {
const parentNode = path.getParentNode(depth);
if (parentNode && parentNode.type === "AttrNode") {
return parentNode.name.toLowerCase();
}
}
}
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) {
return new Array(Math.min(number, NEWLINES_TO_PRESERVE_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 {
quote,
regex
} = chooseEnclosingQuote(options, stringLiteral);
return [quote, stringLiteral.replace(regex, `\\${quote}`), quote];
}
function chooseEnclosingQuote(options, stringLiteral) {
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;
}
return shouldUseAlternateQuote ? alternate : preferred;
}
/* SubExpression print helpers */
function printSubExpressionPathAndParams(path, print) {
const p = printPath(path, print);
const params = printParams(path, print);
if (!params) {
return p;
}
return indent$6([p, line$c, group$a(params)]);
}
/* misc. print helpers */
function printPathAndParams(path, print) {
const p = printPath(path, print);
const params = printParams(path, print);
if (!params) {
return p;
}
return [indent$6([p, line$c, params]), softline$9];
}
function printPath(path, print) {
return print("path");
}
function printParams(path, print) {
const node = path.getValue();
const parts = [];
if (node.params.length > 0) {
const params = path.map(print, "params");
parts.push(...params);
}
if (node.hash && node.hash.pairs.length > 0) {
const hash = print("hash");
parts.push(hash);
}
if (parts.length === 0) {
return "";
}
return join$9(line$c, parts);
}
function printBlockParams(node) {
return ["as |", node.blockParams.join(" "), "|"];
}
var printerGlimmer = {
print,
massageAstNode: clean_1$2
};
var parsers$4 = {
get glimmer() {
return require("./parser-glimmer.js").parsers.glimmer;
}
};
var name$5 = "Handlebars";
var type$5 = "markup";
var color$5 = "#f7931e";
var aliases$3 = [
"hbs",
"htmlbars"
];
var extensions$5 = [
".handlebars",
".hbs"
];
var tmScope$5 = "text.html.handlebars";
var aceMode$5 = "handlebars";
var languageId$5 = 155;
var require$$0$4 = {
name: name$5,
type: type$5,
color: color$5,
aliases: aliases$3,
extensions: extensions$5,
tmScope: tmScope$5,
aceMode: aceMode$5,
languageId: languageId$5
};
const languages$5 = [createLanguage(require$$0$4, () => ({
since: "2.3.0",
parsers: ["glimmer"],
vscodeLanguageIds: ["handlebars"]
}))];
const printers$3 = {
glimmer: printerGlimmer
};
var languageHandlebars = {
languages: languages$5,
printers: printers$3,
parsers: parsers$4
};
function hasPragma$2(text) {
return /^\s*#[^\S\n]*@(?:format|prettier)\s*(?:\n|$)/.test(text);
}
function insertPragma$6(text) {
return "# @format\n\n" + text;
}
var pragma$3 = {
hasPragma: hasPragma$2,
insertPragma: insertPragma$6
};
function locStart$a(node) {
if (typeof node.start === "number") {
return node.start;
}
return node.loc && node.loc.start;
}
function locEnd$9(node) {
if (typeof node.end === "number") {
return node.end;
}
return node.loc && node.loc.end;
}
var loc$3 = {
locStart: locStart$a,
locEnd: locEnd$9
};
const {
builders: {
join: join$8,
hardline: hardline$a,
line: line$b,
softline: softline$8,
group: group$9,
indent: indent$5,
ifBreak: ifBreak$6
}
} = doc;
const {
isNextLineEmpty: isNextLineEmpty$2,
isNonEmptyArray: isNonEmptyArray$3
} = util$5;
const {
insertPragma: insertPragma$5
} = pragma$3;
const {
locStart: locStart$9,
locEnd: locEnd$8
} = loc$3;
function genericPrint$3(path, options, print) {
const node = path.getValue();
if (!node) {
return "";
}
if (typeof node === "string") {
return node;
}
switch (node.kind) {
case "Document":
{
const parts = [];
path.each((pathChild, index, definitions) => {
parts.push(print());
if (index !== definitions.length - 1) {
parts.push(hardline$a);
if (isNextLineEmpty$2(options.originalText, pathChild.getValue(), locEnd$8)) {
parts.push(hardline$a);
}
}
}, "definitions");
return [...parts, hardline$a];
}
case "OperationDefinition":
{
const hasOperation = options.originalText[locStart$9(node)] !== "{";
const hasName = Boolean(node.name);
return [hasOperation ? node.operation : "", hasOperation && hasName ? [" ", print("name")] : "", hasOperation && !hasName && isNonEmptyArray$3(node.variableDefinitions) ? " " : "", isNonEmptyArray$3(node.variableDefinitions) ? group$9(["(", indent$5([softline$8, join$8([ifBreak$6("", ", "), softline$8], path.map(print, "variableDefinitions"))]), softline$8, ")"]) : "", printDirectives(path, print, node), node.selectionSet ? !hasOperation && !hasName ? "" : " " : "", print("selectionSet")];
}
case "FragmentDefinition":
{
return ["fragment ", print("name"), isNonEmptyArray$3(node.variableDefinitions) ? group$9(["(", indent$5([softline$8, join$8([ifBreak$6("", ", "), softline$8], path.map(print, "variableDefinitions"))]), softline$8, ")"]) : "", " on ", print("typeCondition"), printDirectives(path, print, node), " ", print("selectionSet")];
}
case "SelectionSet":
{
return ["{", indent$5([hardline$a, join$8(hardline$a, path.call(selectionsPath => printSequence(selectionsPath, options, print), "selections"))]), hardline$a, "}"];
}
case "Field":
{
return group$9([node.alias ? [print("alias"), ": "] : "", print("name"), node.arguments.length > 0 ? group$9(["(", indent$5([softline$8, join$8([ifBreak$6("", ", "), softline$8], path.call(argsPath => printSequence(argsPath, options, print), "arguments"))]), softline$8, ")"]) : "", printDirectives(path, print, node), node.selectionSet ? " " : "", print("selectionSet")]);
}
case "Name":
{
return node.value;
}
case "StringValue":
{
if (node.block) {
return ['"""', hardline$a, join$8(hardline$a, node.value.replace(/"""/g, "\\$&").split("\n")), hardline$a, '"""'];
}
return ['"', node.value.replace(/["\\]/g, "\\$&").replace(/\n/g, "\\n"), '"'];
}
case "IntValue":
case "FloatValue":
case "EnumValue":
{
return node.value;
}
case "BooleanValue":
{
return node.value ? "true" : "false";
}
case "NullValue":
{
return "null";
}
case "Variable":
{
return ["$", print("name")];
}
case "ListValue":
{
return group$9(["[", indent$5([softline$8, join$8([ifBreak$6("", ", "), softline$8], path.map(print, "values"))]), softline$8, "]"]);
}
case "ObjectValue":
{
return group$9(["{", options.bracketSpacing && node.fields.length > 0 ? " " : "", indent$5([softline$8, join$8([ifBreak$6("", ", "), softline$8], path.map(print, "fields"))]), softline$8, ifBreak$6("", options.bracketSpacing && node.fields.length > 0 ? " " : ""), "}"]);
}
case "ObjectField":
case "Argument":
{
return [print("name"), ": ", print("value")];
}
case "Directive":
{
return ["@", print("name"), node.arguments.length > 0 ? group$9(["(", indent$5([softline$8, join$8([ifBreak$6("", ", "), softline$8], path.call(argsPath => printSequence(argsPath, options, print), "arguments"))]), softline$8, ")"]) : ""];
}
case "NamedType":
{
return print("name");
}
case "VariableDefinition":
{
return [print("variable"), ": ", print("type"), node.defaultValue ? [" = ", print("defaultValue")] : "", printDirectives(path, print, node)];
}
case "ObjectTypeExtension":
case "ObjectTypeDefinition":
{
return [print("description"), node.description ? hardline$a : "", node.kind === "ObjectTypeExtension" ? "extend " : "", "type ", print("name"), node.interfaces.length > 0 ? [" implements ", ...printInterfaces(path, options, print)] : "", printDirectives(path, print, node), node.fields.length > 0 ? [" {", indent$5([hardline$a, join$8(hardline$a, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))]), hardline$a, "}"] : ""];
}
case "FieldDefinition":
{
return [print("description"), node.description ? hardline$a : "", print("name"), node.arguments.length > 0 ? group$9(["(", indent$5([softline$8, join$8([ifBreak$6("", ", "), softline$8], path.call(argsPath => printSequence(argsPath, options, print), "arguments"))]), softline$8, ")"]) : "", ": ", print("type"), printDirectives(path, print, node)];
}
case "DirectiveDefinition":
{
return [print("description"), node.description ? hardline$a : "", "directive ", "@", print("name"), node.arguments.length > 0 ? group$9(["(", indent$5([softline$8, join$8([ifBreak$6("", ", "), softline$8], path.call(argsPath => printSequence(argsPath, options, print), "arguments"))]), softline$8, ")"]) : "", node.repeatable ? " repeatable" : "", " on ", join$8(" | ", path.map(print, "locations"))];
}
case "EnumTypeExtension":
case "EnumTypeDefinition":
{
return [print("description"), node.description ? hardline$a : "", node.kind === "EnumTypeExtension" ? "extend " : "", "enum ", print("name"), printDirectives(path, print, node), node.values.length > 0 ? [" {", indent$5([hardline$a, join$8(hardline$a, path.call(valuesPath => printSequence(valuesPath, options, print), "values"))]), hardline$a, "}"] : ""];
}
case "EnumValueDefinition":
{
return [print("description"), node.description ? hardline$a : "", print("name"), printDirectives(path, print, node)];
}
case "InputValueDefinition":
{
return [print("description"), node.description ? node.description.block ? hardline$a : line$b : "", print("name"), ": ", print("type"), node.defaultValue ? [" = ", print("defaultValue")] : "", printDirectives(path, print, node)];
}
case "InputObjectTypeExtension":
case "InputObjectTypeDefinition":
{
return [print("description"), node.description ? hardline$a : "", node.kind === "InputObjectTypeExtension" ? "extend " : "", "input ", print("name"), printDirectives(path, print, node), node.fields.length > 0 ? [" {", indent$5([hardline$a, join$8(hardline$a, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))]), hardline$a, "}"] : ""];
}
case "SchemaDefinition":
{
return ["schema", printDirectives(path, print, node), " {", node.operationTypes.length > 0 ? indent$5([hardline$a, join$8(hardline$a, path.call(opsPath => printSequence(opsPath, options, print), "operationTypes"))]) : "", hardline$a, "}"];
}
case "OperationTypeDefinition":
{
return [print("operation"), ": ", print("type")];
}
case "InterfaceTypeExtension":
case "InterfaceTypeDefinition":
{
return [print("description"), node.description ? hardline$a : "", node.kind === "InterfaceTypeExtension" ? "extend " : "", "interface ", print("name"), node.interfaces.length > 0 ? [" implements ", ...printInterfaces(path, options, print)] : "", printDirectives(path, print, node), node.fields.length > 0 ? [" {", indent$5([hardline$a, join$8(hardline$a, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))]), hardline$a, "}"] : ""];
}
case "FragmentSpread":
{
return ["...", print("name"), printDirectives(path, print, node)];
}
case "InlineFragment":
{
return ["...", node.typeCondition ? [" on ", print("typeCondition")] : "", printDirectives(path, print, node), " ", print("selectionSet")];
}
case "UnionTypeExtension":
case "UnionTypeDefinition":
{
return group$9([print("description"), node.description ? hardline$a : "", group$9([node.kind === "UnionTypeExtension" ? "extend " : "", "union ", print("name"), printDirectives(path, print, node), node.types.length > 0 ? [" =", ifBreak$6("", " "), indent$5([ifBreak$6([line$b, " "]), join$8([line$b, "| "], path.map(print, "types"))])] : ""])]);
}
case "ScalarTypeExtension":
case "ScalarTypeDefinition":
{
return [print("description"), node.description ? hardline$a : "", node.kind === "ScalarTypeExtension" ? "extend " : "", "scalar ", print("name"), printDirectives(path, print, node)];
}
case "NonNullType":
{
return [print("type"), "!"];
}
case "ListType":
{
return ["[", print("type"), "]"];
}
default:
/* istanbul ignore next */
throw new Error("unknown graphql type: " + JSON.stringify(node.kind));
}
}
function printDirectives(path, print, node) {
if (node.directives.length === 0) {
return "";
}
const printed = join$8(line$b, path.map(print, "directives"));
if (node.kind === "FragmentDefinition" || node.kind === "OperationDefinition") {
return group$9([line$b, printed]);
}
return [" ", group$9(indent$5([softline$8, printed]))];
}
function printSequence(sequencePath, options, print) {
const count = sequencePath.getValue().length;
return sequencePath.map((path, i) => {
const printed = print();
if (isNextLineEmpty$2(options.originalText, path.getValue(), locEnd$8) && i < count - 1) {
return [printed, hardline$a];
}
return printed;
});
}
function canAttachComment(node) {
return node.kind && node.kind !== "Comment";
}
function printComment(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 === "," ? "," : " &", hasComment ? line$b : " ");
}
}
return parts;
}
function clean$3() {}
clean$3.ignoredProperties = new Set(["loc", "comments"]);
function hasPrettierIgnore$6(path) {
const node = path.getValue();
return node && Array.isArray(node.comments) && node.comments.some(comment => comment.value.trim() === "prettier-ignore");
}
var printerGraphql = {
print: genericPrint$3,
massageAstNode: clean$3,
hasPrettierIgnore: hasPrettierIgnore$6,
insertPragma: insertPragma$5,
printComment,
canAttachComment
};
var options$3 = {
bracketSpacing: commonOptions.bracketSpacing
};
var parsers$3 = {
get graphql() {
return require("./parser-graphql.js").parsers.graphql;
}
};
var name$4 = "GraphQL";
var type$4 = "data";
var color$4 = "#e10098";
var extensions$4 = [
".graphql",
".gql",
".graphqls"
];
var tmScope$4 = "source.graphql";
var aceMode$4 = "text";
var languageId$4 = 139;
var require$$0$3 = {
name: name$4,
type: type$4,
color: color$4,
extensions: extensions$4,
tmScope: tmScope$4,
aceMode: aceMode$4,
languageId: languageId$4
};
const languages$4 = [createLanguage(require$$0$3, () => ({
since: "1.5.0",
parsers: ["graphql"],
vscodeLanguageIds: ["graphql"]
}))];
const printers$2 = {
graphql: printerGraphql
};
var languageGraphql = {
languages: languages$4,
options: options$3,
printers: printers$2,
parsers: parsers$3
};
function locStart$8(node) {
return node.position.start.offset;
}
function locEnd$7(node) {
return node.position.end.offset;
}
var loc$2 = {
locStart: locStart$8,
locEnd: locEnd$7
};
var require$$2$1 = {
"cjkPattern": "(?:[\\u02ea-\\u02eb\\u1100-\\u11ff\\u2e80-\\u2e99\\u2e9b-\\u2ef3\\u2f00-\\u2fd5\\u2ff0-\\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$3
} = util$5;
const {
locStart: locStart$7,
locEnd: locEnd$6
} = loc$2;
const {
cjkPattern,
kPattern,
punctuationPattern: punctuationPattern$1
} = require$$2$1;
const INLINE_NODE_TYPES$1 = ["liquidNode", "inlineCode", "emphasis", "strong", "delete", "wikiLink", "link", "linkReference", "image", "imageReference", "footnote", "footnoteReference", "sentence", "whitespace", "word", "break", "inlineMath"];
const INLINE_NODE_WRAPPER_TYPES$1 = [...INLINE_NODE_TYPES$1, "tableCell", "paragraph", "heading"];
const kRegex = new RegExp(kPattern);
const punctuationRegex = new RegExp(punctuationPattern$1);
/**
* split text into whitespaces and words
* @param {string} text
*/
function splitText$2(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";
/** @type {Array<{ type: "whitespace", value: " " | "\n" | "" } | { type: "word", value: string }>} */
const nodes = [];
const tokens = (options.proseWrap === "preserve" ? text : text.replace(new RegExp(`(${cjkPattern})\n(${cjkPattern})`, "g"), "$1$2")).split(/([\t\n ]+)/);
for (const [index, token] of tokens.entries()) {
// whitespace
if (index % 2 === 1) {
nodes.push({
type: "whitespace",
value: /\n/.test(token) ? "\n" : " "
});
continue;
} // word separated by whitespace
if ((index === 0 || index === tokens.length - 1) && token === "") {
continue;
}
const innerTokens = token.split(new RegExp(`(${cjkPattern})`));
for (const [innerIndex, innerToken] of innerTokens.entries()) {
if ((innerIndex === 0 || innerIndex === innerTokens.length - 1) && innerToken === "") {
continue;
} // 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$3(innerToken))
});
}
continue;
} // 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$3(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$1(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$1(node, options) {
if (!node.ordered) {
return false;
}
if (node.children.length < 2) {
return false;
}
const firstNumber = Number(getOrderedListItemInfo$1(node.children[0], options.originalText).numberText);
const secondNumber = Number(getOrderedListItemInfo$1(node.children[1], options.originalText).numberText);
if (firstNumber === 0 && node.children.length > 2) {
const thirdNumber = Number(getOrderedListItemInfo$1(node.children[2], options.originalText).numberText);
return secondNumber === 1 && thirdNumber === 1;
}
return secondNumber === 1;
} // The final new line should not include in value
// https://github.com/remarkjs/remark/issues/512
function getFencedCodeBlockValue$2(node, originalText) {
const {
value
} = node;
if (node.position.end.offset === originalText.length && value.endsWith("\n") && // Code block has no end mark
originalText.endsWith("\n")) {
return value.slice(0, -1);
}
return value;
}
function mapAst$1(ast, handler) {
return function preorder(node, index, parentStack) {
const newNode = Object.assign({}, handler(node, index, parentStack));
if (newNode.children) {
newNode.children = newNode.children.map((child, index) => preorder(child, index, [newNode, ...parentStack]));
}
return newNode;
}(ast, null, []);
}
function isAutolink$1(node) {
if (!node || node.type !== "link" || node.children.length !== 1) {
return false;
}
const child = node.children[0];
return child && locStart$7(node) === locStart$7(child) && locEnd$6(node) === locEnd$6(child);
}
var utils$2 = {
mapAst: mapAst$1,
splitText: splitText$2,
punctuationPattern: punctuationPattern$1,
getFencedCodeBlockValue: getFencedCodeBlockValue$2,
getOrderedListItemInfo: getOrderedListItemInfo$1,
hasGitDiffFriendlyOrderedList: hasGitDiffFriendlyOrderedList$1,
INLINE_NODE_TYPES: INLINE_NODE_TYPES$1,
INLINE_NODE_WRAPPER_TYPES: INLINE_NODE_WRAPPER_TYPES$1,
isAutolink: isAutolink$1
};
const {
inferParserByLanguage: inferParserByLanguage$1,
getMaxContinuousCount: getMaxContinuousCount$1
} = util$5;
const {
builders: {
hardline: hardline$9,
markAsRoot: markAsRoot$2
},
utils: {
replaceEndOfLine
}
} = doc;
const {
getFencedCodeBlockValue: getFencedCodeBlockValue$1
} = utils$2;
function embed$3(path, print, textToDoc, options) {
const node = path.getValue();
if (node.type === "code" && node.lang !== null) {
const parser = inferParserByLanguage$1(node.lang, options);
if (parser) {
const styleUnit = options.__inJsTemplate ? "~" : "`";
const style = styleUnit.repeat(Math.max(3, getMaxContinuousCount$1(node.value, styleUnit) + 1));
const doc = textToDoc(getFencedCodeBlockValue$1(node, options.originalText), {
parser
}, {
stripTrailingHardline: true
});
return markAsRoot$2([style, node.lang, node.meta ? " " + node.meta : "", hardline$9, replaceEndOfLine(doc), hardline$9, style]);
}
}
switch (node.type) {
case "front-matter":
return print_1(node, textToDoc);
// MDX
case "importExport":
return [textToDoc(node.value, {
parser: "babel"
}, {
stripTrailingHardline: true
}), hardline$9];
case "jsx":
return textToDoc(`<$>${node.value}$>`, {
parser: "__js_expression",
rootMarker: "mdx"
}, {
stripTrailingHardline: true
});
}
return null;
}
var embed_1$2 = embed$3;
const pragmas = ["format", "prettier"];
function startWithPragma$1(text) {
const pragma = `@(${pragmas.join("|")})`;
const regex = new RegExp([``, ``].join("|"), "m");
const matched = text.match(regex);
return matched && matched.index === 0;
}
var pragma$2 = {
startWithPragma: startWithPragma$1,
hasPragma: text => startWithPragma$1(parse_1(text).content.trimStart()),
insertPragma: text => {
const extracted = parse_1(text);
const pragma = ``;
return extracted.frontMatter ? `${extracted.frontMatter.raw}\n\n${pragma}\n\n${extracted.content}` : `${pragma}\n\n${extracted.content}`;
}
};
const {
getOrderedListItemInfo,
mapAst,
splitText: splitText$1
} = utils$2; // 0x0 ~ 0x10ffff
const isSingleCharRegex = /^.$/su;
function preprocess$2(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(ast, node => {
if (node.type !== "import" && node.type !== "export") {
return node;
}
return Object.assign(Object.assign({}, node), {}, {
type: "importExport"
});
});
}
function transformInlineCode(ast) {
return mapAst(ast, node => {
if (node.type !== "inlineCode") {
return node;
}
return Object.assign(Object.assign({}, node), {}, {
value: node.value.replace(/\s+/g, " ")
});
});
}
function restoreUnescapedCharacter(ast, options) {
return mapAst(ast, node => node.type !== "text" || node.value === "*" || node.value === "_" || // handle these cases in printer
!isSingleCharRegex.test(node.value) || node.position.end.offset - node.position.start.offset === node.value.length ? node : Object.assign(Object.assign({}, node), {}, {
value: options.originalText.slice(node.position.start.offset, node.position.end.offset)
}));
}
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(ast, node => {
if (!node.children) {
return node;
}
const children = node.children.reduce((current, child) => {
const lastChild = getLast_1(current);
if (lastChild && shouldMerge(lastChild, child)) {
current.splice(-1, 1, mergeNode(lastChild, child));
} else {
current.push(child);
}
return current;
}, []);
return Object.assign(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(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(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(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(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(secondItem, options.originalText);
return secondInfo.leadingSpaces.length > 1;
}
}
var printPreprocess$2 = preprocess$2;
const {
isFrontMatterNode: isFrontMatterNode$2
} = util$5;
const {
startWithPragma
} = pragma$2;
const ignoredProperties$1 = new Set(["position", "raw" // front-matter
]);
function clean$2(ast, newObj, parent) {
// 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 === "wikiLink") {
newObj.value = ast.value.trim().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$2(parent.children[0]) && parent.children[1] === ast) && ast.type === "html" && startWithPragma(ast.value)) {
return null;
}
}
clean$2.ignoredProperties = ignoredProperties$1;
var clean_1$1 = clean$2;
const {
getLast: getLast$2,
getMinNotPresentContinuousCount,
getMaxContinuousCount,
getStringWidth,
isNonEmptyArray: isNonEmptyArray$2
} = util$5;
const {
builders: {
breakParent: breakParent$4,
join: join$7,
line: line$a,
literalline: literalline$3,
markAsRoot: markAsRoot$1,
hardline: hardline$8,
softline: softline$7,
ifBreak: ifBreak$5,
fill: fill$4,
align: align$1,
indent: indent$4,
group: group$8,
hardlineWithoutBreakParent
},
utils: {
normalizeDoc,
replaceTextEndOfLine: replaceTextEndOfLine$7
},
printer: {
printDocToString
}
} = doc;
const {
insertPragma: insertPragma$4
} = pragma$2;
const {
locStart: locStart$6,
locEnd: locEnd$5
} = loc$2;
const {
getFencedCodeBlockValue,
hasGitDiffFriendlyOrderedList,
splitText,
punctuationPattern,
INLINE_NODE_TYPES,
INLINE_NODE_WRAPPER_TYPES,
isAutolink
} = utils$2;
/**
* @typedef {import("../document").Doc} Doc
*/
const TRAILING_HARDLINE_NODES = new Set(["importExport"]);
const SINGLE_LINE_NODE_TYPES = ["heading", "tableCell", "link", "wikiLink"];
const SIBLING_NODE_TYPES = new Set(["listItem", "definition", "footnoteDefinition"]);
function genericPrint$2(path, options, print) {
const node = path.getValue();
if (shouldRemainTheSameContent(path)) {
return splitText(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 [normalizeDoc(printRoot(path, options, print)), !TRAILING_HARDLINE_NODES.has(getLastDescendantNode$2(node).type) ? hardline$8 : ""];
case "paragraph":
return printChildren$4(path, options, print, {
postprocessor: fill$4
});
case "sentence":
return printChildren$4(path, options, print);
case "word":
{
let escapedValue = node.value.replace(/\*/g, "\\$&") // escape all `*`
.replace(new RegExp([`(^|${punctuationPattern})(_+)`, `(_+)(${punctuationPattern}|$)`].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(node.children[index - 1]);
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(node.children[0])) {
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$2(prevNode.children).type === "word" && !getLast$2(prevNode.children).hasTrailingPunctuation || nextNode && nextNode.type === "sentence" && nextNode.children.length > 0 && nextNode.children[0].type === "word" && !nextNode.children[0].hasLeadingPunctuation;
style = hasPrevOrNextWord || getAncestorNode(path, "emphasis") ? "*" : "_";
}
return [style, printChildren$4(path, options, print), style];
}
case "strong":
return ["**", printChildren$4(path, options, print), "**"];
case "delete":
return ["~~", printChildren$4(path, options, print), "~~"];
case "inlineCode":
{
const backtickCount = getMinNotPresentContinuousCount(node.value, "`");
const style = "`".repeat(backtickCount || 1);
const gap = backtickCount && !/^\s/.test(node.value) ? " " : "";
return [style, gap, node.value, gap, style];
}
case "wikiLink":
{
let contents = "";
if (options.proseWrap === "preserve") {
contents = node.value;
} else {
contents = node.value.replace(/[\t\n]+/g, " ");
}
return ["[[", contents, "]]"];
}
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 ["<", url, ">"];
}
case "[":
return ["[", printChildren$4(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 ["![", node.alt || "", "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"];
case "blockquote":
return ["> ", align$1("> ", printChildren$4(path, options, print))];
case "heading":
return ["#".repeat(node.depth) + " ", printChildren$4(path, options, print)];
case "code":
{
if (node.isIndented) {
// indented code block
const alignment = " ".repeat(4);
return align$1(alignment, [alignment, ...replaceTextEndOfLine$7(node.value, hardline$8)]);
} // fenced code block
const styleUnit = options.__inJsTemplate ? "~" : "`";
const style = styleUnit.repeat(Math.max(3, getMaxContinuousCount(node.value, styleUnit) + 1));
return [style, node.lang || "", node.meta ? " " + node.meta : "", hardline$8, ...replaceTextEndOfLine$7(getFencedCodeBlockValue(node, options.originalText), hardline$8), hardline$8, style];
}
case "html":
{
const parentNode = path.getParentNode();
const value = parentNode.type === "root" && getLast$2(parentNode.children) === node ? node.value.trimEnd() : node.value;
const isHtmlComment = /^$/s.test(value);
return replaceTextEndOfLine$7(value, // @ts-expect-error
isHtmlComment ? hardline$8 : markAsRoot$1(literalline$3));
}
case "list":
{
const nthSiblingIndex = getNthListSiblingIndex(node, path.getParentNode());
const isGitDiffFriendlyOrderedList = hasGitDiffFriendlyOrderedList(node, options);
return printChildren$4(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 [prefix, printListItem(childPath, options, print, prefix)];
}
return [prefix, align$1(" ".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(path, "list");
if (counter === -1) {
return "---";
}
const nthSiblingIndex = getNthListSiblingIndex(path.getParentNode(counter), path.getParentNode(counter + 1));
return nthSiblingIndex % 2 === 0 ? "***" : "---";
}
case "linkReference":
return ["[", printChildren$4(path, options, print), "]", node.referenceType === "full" ? ["[", node.identifier, "]"] : node.referenceType === "collapsed" ? "[]" : ""];
case "imageReference":
switch (node.referenceType) {
case "full":
return ["![", node.alt || "", "][", node.identifier, "]"];
default:
return ["![", node.alt, "]", node.referenceType === "collapsed" ? "[]" : ""];
}
case "definition":
{
const lineOrSpace = options.proseWrap === "always" ? line$a : " ";
return group$8(["[", node.identifier, "]:", indent$4([lineOrSpace, printUrl(node.url), node.title === null ? "" : [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 ["[^", printChildren$4(path, options, print), "]"];
case "footnoteReference":
return ["[^", 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 ["[^", node.identifier, "]: ", shouldInlineFootnote ? printChildren$4(path, options, print) : group$8([align$1(" ".repeat(4), printChildren$4(path, options, print, {
processor: (childPath, index) => index === 0 ? group$8([softline$7, print()]) : print()
})), nextNode && nextNode.type === "footnoteDefinition" ? softline$7 : ""])];
}
case "table":
return printTable(path, options, print);
case "tableCell":
return printChildren$4(path, options, print);
case "break":
return /\s/.test(options.originalText[node.position.start.offset]) ? [" ", markAsRoot$1(literalline$3)] : ["\\", hardline$8];
case "liquidNode":
return replaceTextEndOfLine$7(node.value, hardline$8);
// MDX
// fallback to the original text if multiparser failed
// or `embeddedLanguageFormatting: "off"`
case "importExport":
return [node.value, hardline$8];
case "jsx":
return node.value;
case "math":
return ["$$", hardline$8, node.value ? [...replaceTextEndOfLine$7(node.value, hardline$8), hardline$8] : "", "$$"];
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(locStart$6(node), locEnd$5(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 [prefix, printChildren$4(path, options, print, {
processor: (childPath, index) => {
if (index === 0 && childPath.getValue().type !== "list") {
return align$1(" ".repeat(prefix.length), print());
}
const alignment = " ".repeat(clamp(options.tabWidth - listPrefix.length, 0, 3) // 4+ will cause indented code block
);
return [alignment, align$1(alignment, 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) {
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(path, typeOrTypes) {
const types = Array.isArray(typeOrTypes) ? typeOrTypes : [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 printLine(path, value, options) {
if (options.proseWrap === "preserve" && value === "\n") {
return hardline$8;
}
const isBreakable = options.proseWrap === "always" && !getAncestorNode(path, SINGLE_LINE_NODE_TYPES);
return value !== "" ? isBreakable ? line$a : " " : isBreakable ? softline$7 : "";
}
function printTable(path, options, print) {
const node = path.getValue();
const columnMaxWidths = []; // { [rowIndex: number]: { [columnIndex: number]: {text: string, width: number} } }
const contents = path.map(rowPath => rowPath.map((cellPath, columnIndex) => {
const text = printDocToString(print(), options).formatted;
const width = getStringWidth(text);
columnMaxWidths[columnIndex] = Math.max(columnMaxWidths[columnIndex] || 3, // minimum width = 3 (---, :--, :-:, --:)
width);
return {
text,
width
};
}, "children"), "children");
const alignedTable = printTableContents(
/* isCompact */
false);
if (options.proseWrap !== "never") {
return [breakParent$4, alignedTable];
} // Only if the --prose-wrap never is set and it exceeds the print width.
const compactTable = printTableContents(
/* isCompact */
true);
return [breakParent$4, group$8(ifBreak$5(compactTable, alignedTable))];
function printTableContents(isCompact) {
/** @type{Doc[]} */
const parts = [printRow(contents[0], isCompact), printAlign(isCompact)];
if (contents.length > 1) {
parts.push(join$7(hardlineWithoutBreakParent, contents.slice(1).map(rowContents => printRow(rowContents, isCompact))));
}
return join$7(hardlineWithoutBreakParent, parts);
}
function printAlign(isCompact) {
const align = columnMaxWidths.map((width, index) => {
const align = node.align[index];
const first = align === "center" || align === "left" ? ":" : "-";
const last = align === "center" || align === "right" ? ":" : "-";
const middle = isCompact ? "-" : "-".repeat(width - 2);
return `${first}${middle}${last}`;
});
return `| ${align.join(" | ")} |`;
}
function printRow(rowContents, isCompact) {
const columns = rowContents.map(({
text,
width
}, columnIndex) => {
if (isCompact) {
return text;
}
const spaces = columnMaxWidths[columnIndex] - width;
const align = node.align[columnIndex];
let before = 0;
if (align === "right") {
before = spaces;
} else if (align === "center") {
before = Math.floor(spaces / 2);
}
const after = spaces - before;
return `${" ".repeat(before)}${text}${" ".repeat(after)}`;
});
return `| ${columns.join(" | ")} |`;
}
}
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();
for (const [index, childNode] of children.entries()) {
switch (isPrettierIgnore$2(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$4(path, options, print, {
processor: (childPath, index) => {
if (ignoreRanges.length > 0) {
const ignoreRange = ignoreRanges[0];
if (index === ignoreRange.start.index) {
return [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 print();
}
});
}
function printChildren$4(path, options, print, events = {}) {
const {
postprocessor
} = events;
const processor = events.processor || (() => print());
const node = path.getValue();
const parts = [];
let lastChildNode;
path.each((childPath, index) => {
const childNode = childPath.getValue();
const result = processor(childPath, index);
if (result !== false) {
const data = {
parts,
prevNode: lastChildNode,
parentNode: node,
options
};
if (shouldPrePrintHardline(childNode, data)) {
parts.push(hardline$8); // 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$8);
}
} else {
if (shouldPrePrintDoubleHardline(childNode, data) || shouldPrePrintTripleHardline(childNode, data)) {
parts.push(hardline$8);
}
if (shouldPrePrintTripleHardline(childNode, data)) {
parts.push(hardline$8);
}
}
}
parts.push(result);
lastChildNode = childNode;
}
}, "children");
return postprocessor ? postprocessor(parts) : parts;
}
function getLastDescendantNode$2(node) {
let current = node;
while (isNonEmptyArray$2(current.children)) {
current = getLast$2(current.children);
}
return current;
}
/** @return {false | 'next' | 'start' | 'end'} */
function isPrettierIgnore$2(node) {
if (node.type !== "html") {
return false;
}
const match = node.value.match(/^$/);
return match === null ? false : match[1] ? match[1] : "next";
}
function shouldPrePrintHardline(node, data) {
const isFirstNode = data.parts.length === 0;
const isInlineNode = INLINE_NODE_TYPES.includes(node.type);
const isInlineHTML = node.type === "html" && INLINE_NODE_WRAPPER_TYPES.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$2(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(path, ["linkReference", "imageReference"]);
return ancestorNode && (ancestorNode.type !== "linkReference" || ancestorNode.referenceType !== "full");
}
/**
* @param {string} url
* @param {string[] | string} [dangerousCharOrChars]
* @returns {string}
*/
function printUrl(url, dangerousCharOrChars = []) {
const dangerousChars = [" ", ...(Array.isArray(dangerousCharOrChars) ? dangerousCharOrChars : [dangerousCharOrChars])];
return new RegExp(dangerousChars.map(x => `\\${x}`).join("|")).test(url) ? `<${url}>` : url;
}
function printTitle(title, options, 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 hasPrettierIgnore$5(path) {
const index = Number(path.getName());
if (index === 0) {
return false;
}
const prevNode = path.getParentNode().children[index - 1];
return isPrettierIgnore$2(prevNode) === "next";
}
var printerMarkdown = {
preprocess: printPreprocess$2,
print: genericPrint$2,
embed: embed_1$2,
massageAstNode: clean_1$1,
hasPrettierIgnore: hasPrettierIgnore$5,
insertPragma: insertPragma$4
};
var options$2 = {
proseWrap: commonOptions.proseWrap,
singleQuote: commonOptions.singleQuote
};
var parsers$2 = {
/* istanbul ignore next */
get remark() {
return require("./parser-markdown.js").parsers.remark;
},
get markdown() {
return require("./parser-markdown.js").parsers.remark;
},
get mdx() {
return require("./parser-markdown.js").parsers.mdx;
}
};
var name$3 = "Markdown";
var type$3 = "prose";
var color$3 = "#083fa1";
var aliases$2 = [
"pandoc"
];
var aceMode$3 = "markdown";
var codemirrorMode$2 = "gfm";
var codemirrorMimeType$2 = "text/x-gfm";
var wrap = true;
var extensions$3 = [
".md",
".markdown",
".mdown",
".mdwn",
".mdx",
".mkd",
".mkdn",
".mkdown",
".ronn",
".scd",
".workbook"
];
var filenames$1 = [
"contents.lr"
];
var tmScope$3 = "source.gfm";
var languageId$3 = 222;
var require$$0$2 = {
name: name$3,
type: type$3,
color: color$3,
aliases: aliases$2,
aceMode: aceMode$3,
codemirrorMode: codemirrorMode$2,
codemirrorMimeType: codemirrorMimeType$2,
wrap: wrap,
extensions: extensions$3,
filenames: filenames$1,
tmScope: tmScope$3,
languageId: languageId$3
};
const languages$3 = [createLanguage(require$$0$2, data => ({
since: "1.8.0",
parsers: ["markdown"],
vscodeLanguageIds: ["markdown"],
filenames: [...data.filenames, "README"],
extensions: data.extensions.filter(extension => extension !== ".mdx")
})), createLanguage(require$$0$2, () => ({
name: "MDX",
since: "1.15.0",
parsers: ["mdx"],
vscodeLanguageIds: ["mdx"],
filenames: [],
extensions: [".mdx"]
}))];
const printers$1 = {
mdast: printerMarkdown
};
var languageMarkdown = {
languages: languages$3,
options: options$2,
printers: printers$1,
parsers: parsers$2
};
const {
isFrontMatterNode: isFrontMatterNode$1
} = util$5;
const ignoredProperties = new Set(["sourceSpan", "startSourceSpan", "endSourceSpan", "nameSpan", "valueSpan"]);
function clean$1(ast, newNode) {
if (ast.type === "text" || ast.type === "comment") {
return null;
} // may be formatted by multiparser
if (isFrontMatterNode$1(ast) || ast.type === "yaml" || ast.type === "toml") {
return null;
}
if (ast.type === "attribute") {
delete newNode.value;
}
if (ast.type === "docType") {
delete newNode.value;
}
}
clean$1.ignoredProperties = ignoredProperties;
var clean_1 = clean$1;
var htmlTagNames = [
"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 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 = [
"value"
];
var del = [
"cite",
"datetime"
];
var details = [
"open"
];
var dfn = [
"title"
];
var dialog = [
"open"
];
var dir = [
"compact"
];
var div = [
"align"
];
var dl = [
"compact"
];
var embed$2 = [
"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",
"loading",
"longdesc",
"marginheight",
"marginwidth",
"name",
"referrerpolicy",
"sandbox",
"scrolling",
"src",
"srcdoc",
"width"
];
var img = [
"align",
"alt",
"border",
"crossorigin",
"decoding",
"height",
"hspace",
"ismap",
"loading",
"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 = [
"as",
"charset",
"color",
"crossorigin",
"disabled",
"href",
"hreflang",
"imagesizes",
"imagesrcset",
"integrity",
"media",
"nonce",
"referrerpolicy",
"rel",
"rev",
"sizes",
"target",
"title",
"type"
];
var map = [
"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 = [
"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 htmlElementAttributes = {
"*": [
"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,
del: del,
details: details,
dfn: dfn,
dialog: dialog,
dir: dir,
div: div,
dl: dl,
embed: embed$2,
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,
map: map,
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,
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 require$$2 = {
"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"
};
/**
* @typedef {import("../common/ast-path")} AstPath
*/
const {
inferParserByLanguage,
isFrontMatterNode
} = util$5;
const {
builders: {
line: line$9,
hardline: hardline$7,
join: join$6
},
utils: {
getDocParts: getDocParts$3,
replaceTextEndOfLine: replaceTextEndOfLine$6
}
} = doc;
const {
CSS_DISPLAY_TAGS,
CSS_DISPLAY_DEFAULT,
CSS_WHITE_SPACE_TAGS,
CSS_WHITE_SPACE_DEFAULT
} = require$$2;
const HTML_TAGS = arrayToMap(htmlTagNames);
const HTML_ELEMENT_ATTRIBUTES = mapObject(htmlElementAttributes, 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$1 = string => htmlTrimStart(htmlTrimEnd(string));
const htmlTrimLeadingBlankLines = string => string.replace(/^[\t\f\r ]*?\n/g, "");
const htmlTrimPreserveIndentation$1 = 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$1 = string => {
const [, leadingWhitespace, text, trailingWhitespace] = string.match(/^([\t\n\f\r ]*)(.*?)([\t\n\f\r ]*)$/s);
return {
leadingWhitespace,
trailingWhitespace,
text
};
};
const hasHtmlWhitespace$1 = 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, value] of Object.entries(object)) {
newObject[key] = fn(value, key);
}
return newObject;
}
function shouldPreserveContent$2(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$1(node) && node.children.some(child => child.type !== "text" && child.type !== "interpolation")) {
return true;
}
if (isVueNonHtmlBlock$1(node, options) && !isScriptLikeTag$2(node) && node.type !== "interpolation") {
return true;
}
return false;
}
function hasPrettierIgnore$4(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";
}
/** there's no opening/closing tag or it's considered not breakable */
function isTextLikeNode$2(node) {
return node.type === "text" || node.type === "comment";
}
function isScriptLikeTag$2(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$1(node) {
return node.children && !isScriptLikeTag$2(node);
}
function isWhitespaceSensitiveNode$1(node) {
return isScriptLikeTag$2(node) || node.type === "interpolation" || isIndentationSensitiveNode$1(node);
}
function isIndentationSensitiveNode$1(node) {
return getNodeCssStyleWhiteSpace(node).startsWith("pre");
}
function isLeadingSpaceSensitiveNode$1(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(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$1(node.parent)) {
return true;
}
if (!node.prev && (node.parent.type === "root" || isPreLikeNode$1(node) && node.parent || isScriptLikeTag$2(node.parent) || isVueCustomBlock$1(node.parent, options) || !isFirstChildLeadingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) {
return false;
}
if (node.prev && !isNextLeadingSpaceSensitiveCssDisplay(node.prev.cssDisplay)) {
return false;
}
return true;
}
}
function isTrailingSpaceSensitiveNode$1(node, options) {
if (isFrontMatterNode(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$1(node.parent)) {
return true;
}
if (!node.next && (node.parent.type === "root" || isPreLikeNode$1(node) && node.parent || isScriptLikeTag$2(node.parent) || isVueCustomBlock$1(node.parent, options) || !isLastChildTrailingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) {
return false;
}
if (node.next && !isPrevTrailingSpaceSensitiveCssDisplay(node.next.cssDisplay)) {
return false;
}
return true;
}
function isDanglingSpaceSensitiveNode$1(node) {
return isDanglingSpaceSensitiveCssDisplay(node.cssDisplay) && !isScriptLikeTag$2(node);
}
function forceNextEmptyLine$1(node) {
return isFrontMatterNode(node) || node.next && node.sourceSpan.end && node.sourceSpan.end.line + 1 < node.next.sourceSpan.start.line;
}
/** firstChild leadingSpaces and lastChild trailingSpaces */
function forceBreakContent$1(node) {
return forceBreakChildren$1(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$1(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$1(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$1(node) {
return node.lastChild ? getLastDescendant$1(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$1(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$1(node, options)) {
return _inferScriptParser(node) || !("src" in node.attrMap) && inferParserByLanguage(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$1(node) {
return getNodeCssStyleWhiteSpace(node).startsWith("pre");
}
/**
* @param {AstPath} path
* @param {(any) => boolean} predicate
*/
function countParents$1(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$1(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 = Number.POSITIVE_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 === Number.POSITIVE_INFINITY ? 0 : minIndentation;
}
function dedentString$1(text, minIndent = getMinIndentation(text)) {
return minIndent === 0 ? text : text.split("\n").map(lineText => lineText.slice(minIndent)).join("\n");
}
function countChars$1(text, char) {
let counter = 0;
for (let i = 0; i < text.length; i++) {
if (text[i] === char) {
counter++;
}
}
return counter;
}
function unescapeQuoteEntities$2(text) {
return text.replace(/'/g, "'").replace(/"/g, '"');
} // top-level elements (excluding ,