!nameHasComments || n.attributes.length) && !lastAttrHasTrailingComments; // We should print the opening element expanded if any prop value is a
// string literal with newlines
const shouldBreak = n.attributes && n.attributes.some(attr => attr.value && isStringLiteral$1(attr.value) && attr.value.value.includes("\n"));
return group$b(concat$d(["<", path.call(print, "name"), path.call(print, "typeParameters"), concat$d([indent$7(concat$d(path.map(attr => concat$d([line$9, print(attr)]), "attributes"))), n.selfClosing ? line$9 : bracketSameLine ? ">" : softline$6]), n.selfClosing ? "/>" : bracketSameLine ? "" : ">"]), {
shouldBreak
});
}
case "JSXClosingElement":
return concat$d(["", path.call(print, "name"), ">"]);
case "JSXOpeningFragment":
case "JSXClosingFragment":
{
const hasComment = n.comments && n.comments.length;
const hasOwnLineComment = hasComment && !n.comments.every(comments$1.isBlockComment);
const isOpeningFragment = n.type === "JSXOpeningFragment";
return concat$d([isOpeningFragment ? "<" : "", indent$7(concat$d([hasOwnLineComment ? hardline$9 : hasComment && !isOpeningFragment ? " " : "", comments.printDanglingComments(path, options, true)])), hasOwnLineComment ? hardline$9 : "", ">"]);
}
case "JSXText":
/* istanbul ignore next */
throw new Error("JSXTest should be handled by JSXElement");
case "JSXEmptyExpression":
{
const requiresHardline = n.comments && !n.comments.every(comments$1.isBlockComment);
return concat$d([comments.printDanglingComments(path, options,
/* sameIndent */
!requiresHardline), requiresHardline ? hardline$9 : ""]);
}
case "ClassBody":
if (!n.comments && n.body.length === 0) {
return "{}";
}
return concat$d(["{", n.body.length > 0 ? indent$7(concat$d([hardline$9, path.call(bodyPath => {
return printStatementSequence(bodyPath, options, print);
}, "body")])) : comments.printDanglingComments(path, options), hardline$9, "}"]);
case "ClassProperty":
case "TSAbstractClassProperty":
case "ClassPrivateProperty":
{
if (n.decorators && n.decorators.length !== 0) {
parts.push(printDecorators(path, options, print));
}
if (n.accessibility) {
parts.push(n.accessibility + " ");
}
if (n.declare) {
parts.push("declare ");
}
if (n.static) {
parts.push("static ");
}
if (n.type === "TSAbstractClassProperty" || n.abstract) {
parts.push("abstract ");
}
if (n.readonly) {
parts.push("readonly ");
}
const variance = getFlowVariance$1(n);
if (variance) {
parts.push(variance);
}
parts.push(printPropertyKey(path, options, print), printOptionalToken(path), printTypeAnnotation(path, options, print));
if (n.value) {
parts.push(" =", printAssignmentRight(n.key, n.value, path.call(print, "value"), options));
}
parts.push(semi);
return group$b(concat$d(parts));
}
case "ClassDeclaration":
case "ClassExpression":
if (n.declare) {
parts.push("declare ");
}
parts.push(concat$d(printClass(path, options, print)));
return concat$d(parts);
case "TSInterfaceHeritage":
case "TSExpressionWithTypeArguments":
// Babel AST
parts.push(path.call(print, "expression"));
if (n.typeParameters) {
parts.push(path.call(print, "typeParameters"));
}
return concat$d(parts);
case "TemplateElement":
return join$9(literalline$4, n.value.raw.split(/\r?\n/g));
case "TemplateLiteral":
{
let expressions = path.map(print, "expressions");
const parentNode = path.getParentNode();
if (isJestEachTemplateLiteral$1(n, parentNode)) {
const printed = printJestEachTemplateLiteral(n, expressions, options);
if (printed) {
return printed;
}
}
const isSimple = isSimpleTemplateLiteral$1(n);
if (isSimple) {
expressions = expressions.map(doc => printDocToString$2(doc, Object.assign({}, options, {
printWidth: Infinity
})).formatted);
}
parts.push(lineSuffixBoundary$1, "`");
path.each(childPath => {
const i = childPath.getName();
parts.push(print(childPath));
if (i < expressions.length) {
// For a template literal of the following form:
// `someQuery {
// ${call({
// a,
// b,
// })}
// }`
// the expression is on its own line (there is a \n in the previous
// quasi literal), therefore we want to indent the JavaScript
// expression inside at the beginning of ${ instead of the beginning
// of the `.
const {
tabWidth
} = options;
const quasi = childPath.getValue();
const indentSize = getIndentSize$2(quasi.value.raw, tabWidth);
let printed = expressions[i];
if (!isSimple) {
// Breaks at the template element boundaries (${ and }) are preferred to breaking
// in the middle of a MemberExpression
if (n.expressions[i].comments && n.expressions[i].comments.length || n.expressions[i].type === "MemberExpression" || n.expressions[i].type === "OptionalMemberExpression" || n.expressions[i].type === "ConditionalExpression" || n.expressions[i].type === "LogicalExpression" || n.expressions[i].type === "BinaryExpression" || n.expressions[i].type === "SequenceExpression" || n.expressions[i].type === "TSAsExpression") {
printed = concat$d([indent$7(concat$d([softline$6, printed])), softline$6]);
}
}
const aligned = indentSize === 0 && quasi.value.raw.endsWith("\n") ? align$1(-Infinity, printed) : addAlignmentToDoc$2(printed, indentSize, tabWidth);
parts.push(group$b(concat$d(["${", aligned, lineSuffixBoundary$1, "}"])));
}
}, "quasis");
parts.push("`");
return concat$d(parts);
}
// These types are unprintable because they serve as abstract
// supertypes for other (printable) types.
case "TaggedTemplateExpression":
return concat$d([path.call(print, "tag"), path.call(print, "typeParameters"), path.call(print, "quasi")]);
case "Node":
case "Printable":
case "SourceLocation":
case "Position":
case "Statement":
case "Function":
case "Pattern":
case "Expression":
case "Declaration":
case "Specifier":
case "NamedSpecifier":
case "Comment":
case "MemberTypeAnnotation": // Flow
case "Type":
/* istanbul ignore next */
throw new Error("unprintable type: " + JSON.stringify(n.type));
// Type Annotations for Facebook Flow, typically stripped out or
// transformed away before printing.
case "TypeAnnotation":
case "TSTypeAnnotation":
if (n.typeAnnotation) {
return path.call(print, "typeAnnotation");
}
/* istanbul ignore next */
return "";
case "TSTupleType":
case "TupleTypeAnnotation":
{
const typesField = n.type === "TSTupleType" ? "elementTypes" : "types";
const hasRest = n[typesField].length > 0 && getLast$3(n[typesField]).type === "TSRestType";
return group$b(concat$d(["[", indent$7(concat$d([softline$6, printArrayItems(path, options, typesField, print)])), ifBreak$6(shouldPrintComma$1(options, "all") && !hasRest ? "," : ""), comments.printDanglingComments(path, options,
/* sameIndent */
true), softline$6, "]"]));
}
case "ExistsTypeAnnotation":
return "*";
case "EmptyTypeAnnotation":
return "empty";
case "AnyTypeAnnotation":
return "any";
case "MixedTypeAnnotation":
return "mixed";
case "ArrayTypeAnnotation":
return concat$d([path.call(print, "elementType"), "[]"]);
case "BooleanTypeAnnotation":
return "boolean";
case "BooleanLiteralTypeAnnotation":
return "" + n.value;
case "DeclareClass":
return printFlowDeclaration(path, printClass(path, options, print));
case "TSDeclareFunction":
// For TypeScript the TSDeclareFunction node shares the AST
// structure with FunctionDeclaration
return concat$d([n.declare ? "declare " : "", printFunctionDeclaration(path, print, options), semi]);
case "DeclareFunction":
return printFlowDeclaration(path, ["function ", path.call(print, "id"), n.predicate ? " " : "", path.call(print, "predicate"), semi]);
case "DeclareModule":
return printFlowDeclaration(path, ["module ", path.call(print, "id"), " ", path.call(print, "body")]);
case "DeclareModuleExports":
return printFlowDeclaration(path, ["module.exports", ": ", path.call(print, "typeAnnotation"), semi]);
case "DeclareVariable":
return printFlowDeclaration(path, ["var ", path.call(print, "id"), semi]);
case "DeclareExportAllDeclaration":
return concat$d(["declare export * from ", path.call(print, "source")]);
case "DeclareExportDeclaration":
return concat$d(["declare ", printExportDeclaration(path, options, print)]);
case "DeclareOpaqueType":
case "OpaqueType":
{
parts.push("opaque type ", path.call(print, "id"), path.call(print, "typeParameters"));
if (n.supertype) {
parts.push(": ", path.call(print, "supertype"));
}
if (n.impltype) {
parts.push(" = ", path.call(print, "impltype"));
}
parts.push(semi);
if (n.type === "DeclareOpaqueType") {
return printFlowDeclaration(path, parts);
}
return concat$d(parts);
}
case "EnumDeclaration":
return concat$d(["enum ", path.call(print, "id"), " ", path.call(print, "body")]);
case "EnumBooleanBody":
case "EnumNumberBody":
case "EnumStringBody":
case "EnumSymbolBody":
{
if (n.type === "EnumSymbolBody" || n.explicitType) {
let type = null;
switch (n.type) {
case "EnumBooleanBody":
type = "boolean";
break;
case "EnumNumberBody":
type = "number";
break;
case "EnumStringBody":
type = "string";
break;
case "EnumSymbolBody":
type = "symbol";
break;
}
parts.push("of ", type, " ");
}
if (n.members.length === 0) {
parts.push(group$b(concat$d(["{", comments.printDanglingComments(path, options), softline$6, "}"])));
} else {
parts.push(group$b(concat$d(["{", indent$7(concat$d([hardline$9, printArrayItems(path, options, "members", print), shouldPrintComma$1(options) ? "," : ""])), comments.printDanglingComments(path, options,
/* sameIndent */
true), hardline$9, "}"])));
}
return concat$d(parts);
}
case "EnumBooleanMember":
case "EnumNumberMember":
case "EnumStringMember":
return concat$d([path.call(print, "id"), " = ", typeof n.init === "object" ? path.call(print, "init") : String(n.init)]);
case "EnumDefaultedMember":
return path.call(print, "id");
case "FunctionTypeAnnotation":
case "TSFunctionType":
{
// FunctionTypeAnnotation is ambiguous:
// declare function foo(a: B): void; OR
// var A: (a: B) => void;
const parent = path.getParentNode(0);
const parentParent = path.getParentNode(1);
const parentParentParent = path.getParentNode(2);
let isArrowFunctionTypeAnnotation = n.type === "TSFunctionType" || !((parent.type === "ObjectTypeProperty" || parent.type === "ObjectTypeInternalSlot") && !getFlowVariance$1(parent) && !parent.optional && options.locStart(parent) === options.locStart(n) || parent.type === "ObjectTypeCallProperty" || parentParentParent && parentParentParent.type === "DeclareFunction");
let needsColon = isArrowFunctionTypeAnnotation && (parent.type === "TypeAnnotation" || parent.type === "TSTypeAnnotation"); // Sadly we can't put it inside of FastPath::needsColon because we are
// printing ":" as part of the expression and it would put parenthesis
// around :(
const needsParens = needsColon && isArrowFunctionTypeAnnotation && (parent.type === "TypeAnnotation" || parent.type === "TSTypeAnnotation") && parentParent.type === "ArrowFunctionExpression";
if (isObjectTypePropertyAFunction$1(parent, options)) {
isArrowFunctionTypeAnnotation = true;
needsColon = true;
}
if (needsParens) {
parts.push("(");
}
parts.push(printFunctionParams(path, print, options,
/* expandArg */
false,
/* printTypeParams */
true)); // The returnType is not wrapped in a TypeAnnotation, so the colon
// needs to be added separately.
if (n.returnType || n.predicate || n.typeAnnotation) {
parts.push(isArrowFunctionTypeAnnotation ? " => " : ": ", path.call(print, "returnType"), path.call(print, "predicate"), path.call(print, "typeAnnotation"));
}
if (needsParens) {
parts.push(")");
}
return group$b(concat$d(parts));
}
case "TSRestType":
return concat$d(["...", path.call(print, "typeAnnotation")]);
case "TSOptionalType":
return concat$d([path.call(print, "typeAnnotation"), "?"]);
case "FunctionTypeParam":
return concat$d([path.call(print, "name"), printOptionalToken(path), n.name ? ": " : "", path.call(print, "typeAnnotation")]);
case "GenericTypeAnnotation":
return concat$d([path.call(print, "id"), path.call(print, "typeParameters")]);
case "DeclareInterface":
case "InterfaceDeclaration":
case "InterfaceTypeAnnotation":
{
if (n.type === "DeclareInterface" || n.declare) {
parts.push("declare ");
}
parts.push("interface");
if (n.type === "DeclareInterface" || n.type === "InterfaceDeclaration") {
parts.push(" ", path.call(print, "id"), path.call(print, "typeParameters"));
}
if (n.extends.length > 0) {
parts.push(group$b(indent$7(concat$d([line$9, "extends ", (n.extends.length === 1 ? identity$2 : indent$7)(join$9(concat$d([",", line$9]), path.map(print, "extends")))]))));
}
parts.push(" ", path.call(print, "body"));
return group$b(concat$d(parts));
}
case "ClassImplements":
case "InterfaceExtends":
return concat$d([path.call(print, "id"), path.call(print, "typeParameters")]);
case "TSClassImplements":
return concat$d([path.call(print, "expression"), path.call(print, "typeParameters")]);
case "TSIntersectionType":
case "IntersectionTypeAnnotation":
{
const types = path.map(print, "types");
const result = [];
let wasIndented = false;
for (let i = 0; i < types.length; ++i) {
if (i === 0) {
result.push(types[i]);
} else if (isObjectType$1(n.types[i - 1]) && isObjectType$1(n.types[i])) {
// If both are objects, don't indent
result.push(concat$d([" & ", wasIndented ? indent$7(types[i]) : types[i]]));
} else if (!isObjectType$1(n.types[i - 1]) && !isObjectType$1(n.types[i])) {
// If no object is involved, go to the next line if it breaks
result.push(indent$7(concat$d([" &", line$9, 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$7(types[i]) : types[i]);
}
}
return group$b(concat$d(result));
}
case "TSUnionType":
case "UnionTypeAnnotation":
{
// single-line variation
// A | B | C
// multi-line variation
// | A
// | B
// | C
const parent = path.getParentNode(); // If there's a leading comment, the parent is doing the indentation
const shouldIndent = parent.type !== "TypeParameterInstantiation" && parent.type !== "TSTypeParameterInstantiation" && parent.type !== "GenericTypeAnnotation" && parent.type !== "TSTypeReference" && parent.type !== "TSTypeAssertion" && parent.type !== "TupleTypeAnnotation" && parent.type !== "TSTupleType" && !(parent.type === "FunctionTypeParam" && !parent.name) && !((parent.type === "TypeAlias" || parent.type === "VariableDeclarator" || parent.type === "TSTypeAliasDeclaration") && hasLeadingOwnLineComment$1(options.originalText, n, options)); // {
// a: string
// } | null | void
// should be inlined and not be printed in the multi-line variant
const shouldHug = shouldHugType(n); // We want to align the children but without its comment, so it looks like
// | child1
// // comment
// | child2
const printed = path.map(typePath => {
let printedType = typePath.call(print);
if (!shouldHug) {
printedType = align$1(2, printedType);
}
return comments.printComments(typePath, () => printedType, options);
}, "types");
if (shouldHug) {
return join$9(" | ", printed);
}
const shouldAddStartLine = shouldIndent && !hasLeadingOwnLineComment$1(options.originalText, n, options);
const code = concat$d([ifBreak$6(concat$d([shouldAddStartLine ? line$9 : "", "| "])), join$9(concat$d([line$9, "| "]), printed)]);
if (needsParens_1(path, options)) {
return group$b(concat$d([indent$7(code), softline$6]));
}
if (parent.type === "TupleTypeAnnotation" && parent.types.length > 1 || parent.type === "TSTupleType" && parent.elementTypes.length > 1) {
return group$b(concat$d([indent$7(concat$d([ifBreak$6(concat$d(["(", softline$6])), code])), softline$6, ifBreak$6(")")]));
}
return group$b(shouldIndent ? indent$7(code) : code);
}
case "NullableTypeAnnotation":
return concat$d(["?", path.call(print, "typeAnnotation")]);
case "TSNullKeyword":
case "NullLiteralTypeAnnotation":
return "null";
case "ThisTypeAnnotation":
return "this";
case "NumberTypeAnnotation":
return "number";
case "SymbolTypeAnnotation":
return "symbol";
case "ObjectTypeCallProperty":
if (n.static) {
parts.push("static ");
}
parts.push(path.call(print, "value"));
return concat$d(parts);
case "ObjectTypeIndexer":
{
const variance = getFlowVariance$1(n);
return concat$d([variance || "", "[", path.call(print, "id"), n.id ? ": " : "", path.call(print, "key"), "]: ", path.call(print, "value")]);
}
case "ObjectTypeProperty":
{
const variance = getFlowVariance$1(n);
let modifier = "";
if (n.proto) {
modifier = "proto ";
} else if (n.static) {
modifier = "static ";
}
return concat$d([modifier, isGetterOrSetter$1(n) ? n.kind + " " : "", variance || "", printPropertyKey(path, options, print), printOptionalToken(path), isFunctionNotation$1(n, options) ? "" : ": ", path.call(print, "value")]);
}
case "QualifiedTypeIdentifier":
return concat$d([path.call(print, "qualification"), ".", path.call(print, "id")]);
case "StringLiteralTypeAnnotation":
return nodeStr(n, options);
case "NumberLiteralTypeAnnotation":
assert.strictEqual(typeof n.value, "number");
if (n.extra != null) {
return printNumber$2(n.extra.raw);
}
return printNumber$2(n.raw);
case "StringTypeAnnotation":
return "string";
case "DeclareTypeAlias":
case "TypeAlias":
{
if (n.type === "DeclareTypeAlias" || n.declare) {
parts.push("declare ");
}
const printed = printAssignmentRight(n.id, n.right, path.call(print, "right"), options);
parts.push("type ", path.call(print, "id"), path.call(print, "typeParameters"), " =", printed, semi);
return group$b(concat$d(parts));
}
case "TypeCastExpression":
{
return concat$d(["(", path.call(print, "expression"), printTypeAnnotation(path, options, print), ")"]);
}
case "TypeParameterDeclaration":
case "TypeParameterInstantiation":
{
const value = path.getValue();
const commentStart = value.range ? options.originalText.slice(0, value.range[0]).lastIndexOf("/*") : -1; // As noted in the TypeCastExpression comments above, we're able to use a normal whitespace regex here
// because we know for sure that this is a type definition.
const commentSyntax = commentStart >= 0 && options.originalText.slice(commentStart).match(/^\/\*\s*::/);
if (commentSyntax) {
return concat$d(["/*:: ", printTypeParameters(path, options, print, "params"), " */"]);
}
return printTypeParameters(path, options, print, "params");
}
case "TSTypeParameterDeclaration":
case "TSTypeParameterInstantiation":
return printTypeParameters(path, options, print, "params");
case "TSTypeParameter":
case "TypeParameter":
{
const parent = path.getParentNode();
if (parent.type === "TSMappedType") {
parts.push("[", path.call(print, "name"));
if (n.constraint) {
parts.push(" in ", path.call(print, "constraint"));
}
parts.push("]");
return concat$d(parts);
}
const variance = getFlowVariance$1(n);
if (variance) {
parts.push(variance);
}
parts.push(path.call(print, "name"));
if (n.bound) {
parts.push(": ");
parts.push(path.call(print, "bound"));
}
if (n.constraint) {
parts.push(" extends ", path.call(print, "constraint"));
}
if (n.default) {
parts.push(" = ", path.call(print, "default"));
} // Keep comma if the file extension is .tsx and
// has one type parameter that isn't extend with any types.
// Because, otherwise formatted result will be invalid as tsx.
const grandParent = path.getNode(2);
if (parent.params && parent.params.length === 1 && isTSXFile$1(options) && !n.constraint && grandParent.type === "ArrowFunctionExpression") {
parts.push(",");
}
return concat$d(parts);
}
case "TypeofTypeAnnotation":
return concat$d(["typeof ", path.call(print, "argument")]);
case "VoidTypeAnnotation":
return "void";
case "InferredPredicate":
return "%checks";
// Unhandled types below. If encountered, nodes of these types should
// be either left alone or desugared into AST types that are fully
// supported by the pretty-printer.
case "DeclaredPredicate":
return concat$d(["%checks(", path.call(print, "value"), ")"]);
case "TSAbstractKeyword":
return "abstract";
case "TSAnyKeyword":
return "any";
case "TSAsyncKeyword":
return "async";
case "TSBooleanKeyword":
return "boolean";
case "TSBigIntKeyword":
return "bigint";
case "TSConstKeyword":
return "const";
case "TSDeclareKeyword":
return "declare";
case "TSExportKeyword":
return "export";
case "TSNeverKeyword":
return "never";
case "TSNumberKeyword":
return "number";
case "TSObjectKeyword":
return "object";
case "TSProtectedKeyword":
return "protected";
case "TSPrivateKeyword":
return "private";
case "TSPublicKeyword":
return "public";
case "TSReadonlyKeyword":
return "readonly";
case "TSSymbolKeyword":
return "symbol";
case "TSStaticKeyword":
return "static";
case "TSStringKeyword":
return "string";
case "TSUndefinedKeyword":
return "undefined";
case "TSUnknownKeyword":
return "unknown";
case "TSVoidKeyword":
return "void";
case "TSAsExpression":
return concat$d([path.call(print, "expression"), " as ", path.call(print, "typeAnnotation")]);
case "TSArrayType":
return concat$d([path.call(print, "elementType"), "[]"]);
case "TSPropertySignature":
{
if (n.export) {
parts.push("export ");
}
if (n.accessibility) {
parts.push(n.accessibility + " ");
}
if (n.static) {
parts.push("static ");
}
if (n.readonly) {
parts.push("readonly ");
}
parts.push(printPropertyKey(path, options, print), printOptionalToken(path));
if (n.typeAnnotation) {
parts.push(": ");
parts.push(path.call(print, "typeAnnotation"));
} // This isn't valid semantically, but it's in the AST so we can print it.
if (n.initializer) {
parts.push(" = ", path.call(print, "initializer"));
}
return concat$d(parts);
}
case "TSParameterProperty":
if (n.accessibility) {
parts.push(n.accessibility + " ");
}
if (n.export) {
parts.push("export ");
}
if (n.static) {
parts.push("static ");
}
if (n.readonly) {
parts.push("readonly ");
}
parts.push(path.call(print, "parameter"));
return concat$d(parts);
case "TSTypeReference":
return concat$d([path.call(print, "typeName"), printTypeParameters(path, options, print, "typeParameters")]);
case "TSTypeQuery":
return concat$d(["typeof ", path.call(print, "exprName")]);
case "TSIndexSignature":
{
const parent = path.getParentNode(); // The typescript parser accepts multiple parameters here. If you're
// using them, it makes sense to have a trailing comma. But if you
// aren't, this is more like a computed property name than an array.
// So we leave off the trailing comma when there's just one parameter.
const trailingComma = n.parameters.length > 1 ? ifBreak$6(shouldPrintComma$1(options) ? "," : "") : "";
const parametersGroup = group$b(concat$d([indent$7(concat$d([softline$6, join$9(concat$d([", ", softline$6]), path.map(print, "parameters"))])), trailingComma, softline$6]));
return concat$d([n.export ? "export " : "", n.accessibility ? concat$d([n.accessibility, " "]) : "", n.static ? "static " : "", n.readonly ? "readonly " : "", "[", n.parameters ? parametersGroup : "", n.typeAnnotation ? "]: " : "]", n.typeAnnotation ? path.call(print, "typeAnnotation") : "", parent.type === "ClassBody" ? semi : ""]);
}
case "TSTypePredicate":
return concat$d([n.asserts ? "asserts " : "", path.call(print, "parameterName"), n.typeAnnotation ? concat$d([" is ", path.call(print, "typeAnnotation")]) : ""]);
case "TSNonNullExpression":
return concat$d([path.call(print, "expression"), "!"]);
case "TSThisType":
return "this";
case "TSImportType":
return concat$d([!n.isTypeOf ? "" : "typeof ", "import(", path.call(print, n.parameter ? "parameter" : "argument"), ")", !n.qualifier ? "" : concat$d([".", path.call(print, "qualifier")]), printTypeParameters(path, options, print, "typeParameters")]);
case "TSLiteralType":
return path.call(print, "literal");
case "TSIndexedAccessType":
return concat$d([path.call(print, "objectType"), "[", path.call(print, "indexType"), "]"]);
case "TSConstructSignatureDeclaration":
case "TSCallSignatureDeclaration":
case "TSConstructorType":
{
if (n.type !== "TSCallSignatureDeclaration") {
parts.push("new ");
}
parts.push(group$b(printFunctionParams(path, print, options,
/* expandArg */
false,
/* printTypeParams */
true)));
if (n.returnType || n.typeAnnotation) {
const isType = n.type === "TSConstructorType";
parts.push(isType ? " => " : ": ", path.call(print, "returnType"), path.call(print, "typeAnnotation"));
}
return concat$d(parts);
}
case "TSTypeOperator":
return concat$d([n.operator, " ", path.call(print, "typeAnnotation")]);
case "TSMappedType":
{
const shouldBreak = hasNewlineInRange$3(options.originalText, options.locStart(n), options.locEnd(n));
return group$b(concat$d(["{", indent$7(concat$d([options.bracketSpacing ? line$9 : softline$6, n.readonly ? concat$d([getTypeScriptMappedTypeModifier$1(n.readonly, "readonly"), " "]) : "", printTypeScriptModifiers(path, options, print), path.call(print, "typeParameter"), n.optional ? getTypeScriptMappedTypeModifier$1(n.optional, "?") : "", n.typeAnnotation ? ": " : "", path.call(print, "typeAnnotation"), ifBreak$6(semi, "")])), comments.printDanglingComments(path, options,
/* sameIndent */
true), options.bracketSpacing ? line$9 : softline$6, "}"]), {
shouldBreak
});
}
case "TSMethodSignature":
parts.push(n.accessibility ? concat$d([n.accessibility, " "]) : "", n.export ? "export " : "", n.static ? "static " : "", n.readonly ? "readonly " : "", n.computed ? "[" : "", path.call(print, "key"), n.computed ? "]" : "", printOptionalToken(path), printFunctionParams(path, print, options,
/* expandArg */
false,
/* printTypeParams */
true));
if (n.returnType || n.typeAnnotation) {
parts.push(": ", path.call(print, "returnType"), path.call(print, "typeAnnotation"));
}
return group$b(concat$d(parts));
case "TSNamespaceExportDeclaration":
parts.push("export as namespace ", path.call(print, "id"));
if (options.semi) {
parts.push(";");
}
return group$b(concat$d(parts));
case "TSEnumDeclaration":
if (n.declare) {
parts.push("declare ");
}
if (n.modifiers) {
parts.push(printTypeScriptModifiers(path, options, print));
}
if (n.const) {
parts.push("const ");
}
parts.push("enum ", path.call(print, "id"), " ");
if (n.members.length === 0) {
parts.push(group$b(concat$d(["{", comments.printDanglingComments(path, options), softline$6, "}"])));
} else {
parts.push(group$b(concat$d(["{", indent$7(concat$d([hardline$9, printArrayItems(path, options, "members", print), shouldPrintComma$1(options, "es5") ? "," : ""])), comments.printDanglingComments(path, options,
/* sameIndent */
true), hardline$9, "}"])));
}
return concat$d(parts);
case "TSEnumMember":
parts.push(path.call(print, "id"));
if (n.initializer) {
parts.push(" = ", path.call(print, "initializer"));
}
return concat$d(parts);
case "TSImportEqualsDeclaration":
if (n.isExport) {
parts.push("export ");
}
parts.push("import ", path.call(print, "id"), " = ", path.call(print, "moduleReference"));
if (options.semi) {
parts.push(";");
}
return group$b(concat$d(parts));
case "TSExternalModuleReference":
return concat$d(["require(", path.call(print, "expression"), ")"]);
case "TSModuleDeclaration":
{
const parent = path.getParentNode();
const isExternalModule = isLiteral$1(n.id);
const parentIsDeclaration = parent.type === "TSModuleDeclaration";
const bodyIsDeclaration = n.body && n.body.type === "TSModuleDeclaration";
if (parentIsDeclaration) {
parts.push(".");
} else {
if (n.declare) {
parts.push("declare ");
}
parts.push(printTypeScriptModifiers(path, options, print));
const textBetweenNodeAndItsId = options.originalText.slice(options.locStart(n), options.locStart(n.id)); // Global declaration looks like this:
// (declare)? global { ... }
const isGlobalDeclaration = n.id.type === "Identifier" && n.id.name === "global" && !/namespace|module/.test(textBetweenNodeAndItsId);
if (!isGlobalDeclaration) {
parts.push(isExternalModule || /(^|\s)module(\s|$)/.test(textBetweenNodeAndItsId) ? "module " : "namespace ");
}
}
parts.push(path.call(print, "id"));
if (bodyIsDeclaration) {
parts.push(path.call(print, "body"));
} else if (n.body) {
parts.push(" ", group$b(path.call(print, "body")));
} else {
parts.push(semi);
}
return concat$d(parts);
}
case "PrivateName":
return concat$d(["#", path.call(print, "id")]);
// TODO: Temporary auto-generated node type. To remove when typescript-estree has proper support for private fields.
case "TSPrivateIdentifier":
return n.escapedText;
case "TSConditionalType":
return printTernaryOperator(path, options, print, {
beforeParts: () => [path.call(print, "checkType"), " ", "extends", " ", path.call(print, "extendsType")],
afterParts: () => [],
shouldCheckJsx: false,
conditionalNodeType: "TSConditionalType",
consequentNodePropertyName: "trueType",
alternateNodePropertyName: "falseType",
testNodePropertyNames: ["checkType", "extendsType"]
});
case "TSInferType":
return concat$d(["infer", " ", path.call(print, "typeParameter")]);
case "InterpreterDirective":
parts.push("#!", n.value, hardline$9);
if (isNextLineEmpty$4(options.originalText, n, options.locEnd)) {
parts.push(hardline$9);
}
return concat$d(parts);
case "NGRoot":
return concat$d([].concat(path.call(print, "node"), !n.node.comments || n.node.comments.length === 0 ? [] : concat$d([" //", n.node.comments[0].value.trimEnd()])));
case "NGChainedExpression":
return group$b(join$9(concat$d([";", line$9]), path.map(childPath => hasNgSideEffect$1(childPath) ? print(childPath) : concat$d(["(", print(childPath), ")"]), "expressions")));
case "NGEmptyExpression":
return "";
case "NGQuotedExpression":
return concat$d([n.prefix, ":", n.value]);
case "NGMicrosyntax":
return concat$d(path.map((childPath, index) => concat$d([index === 0 ? "" : isNgForOf$1(childPath.getValue(), index, n) ? " " : concat$d([";", line$9]), print(childPath)]), "body"));
case "NGMicrosyntaxKey":
return /^[a-z_$][a-z0-9_$]*(-[a-z_$][a-z0-9_$])*$/i.test(n.name) ? n.name : JSON.stringify(n.name);
case "NGMicrosyntaxExpression":
return concat$d([path.call(print, "expression"), n.alias === null ? "" : concat$d([" as ", path.call(print, "alias")])]);
case "NGMicrosyntaxKeyedExpression":
{
const index = path.getName();
const parentNode = path.getParentNode();
const shouldNotPrintColon = isNgForOf$1(n, index, parentNode) || (index === 1 && (n.key.name === "then" || n.key.name === "else") || index === 2 && n.key.name === "else" && parentNode.body[index - 1].type === "NGMicrosyntaxKeyedExpression" && parentNode.body[index - 1].key.name === "then") && parentNode.body[0].type === "NGMicrosyntaxExpression";
return concat$d([path.call(print, "key"), shouldNotPrintColon ? " " : ": ", path.call(print, "expression")]);
}
case "NGMicrosyntaxLet":
return concat$d(["let ", path.call(print, "key"), n.value === null ? "" : concat$d([" = ", path.call(print, "value")])]);
case "NGMicrosyntaxAs":
return concat$d([path.call(print, "key"), " as ", path.call(print, "alias")]);
case "ArgumentPlaceholder":
return "?";
// These are not valid TypeScript. Printing them just for the sake of error recovery.
case "TSJSDocAllType":
return "*";
case "TSJSDocUnknownType":
return "?";
case "TSJSDocNullableType":
return concat$d(["?", path.call(print, "typeAnnotation")]);
case "TSJSDocNonNullableType":
return concat$d(["!", path.call(print, "typeAnnotation")]);
case "TSJSDocFunctionType":
return concat$d(["function(", // The parameters could be here, but typescript-estree doesn't convert them anyway (throws an error).
"): ", path.call(print, "typeAnnotation")]);
default:
/* istanbul ignore next */
throw new Error("unknown type: " + JSON.stringify(n.type));
}
}
function printStatementSequence(path, options, print) {
const printed = [];
const bodyNode = path.getNode();
const isClass = bodyNode.type === "ClassBody";
path.map((stmtPath, i) => {
const stmt = stmtPath.getValue(); // Just in case the AST has been modified to contain falsy
// "statements," it's safer simply to skip them.
/* istanbul ignore if */
if (!stmt) {
return;
} // Skip printing EmptyStatement nodes to avoid leaving stray
// semicolons lying around.
if (stmt.type === "EmptyStatement") {
return;
}
const stmtPrinted = print(stmtPath);
const text = options.originalText;
const parts = []; // in no-semi mode, prepend statement with semicolon if it might break ASI
// don't prepend the only JSX element in a program with semicolon
if (!options.semi && !isClass && !isTheOnlyJSXElementInMarkdown$1(options, stmtPath) && stmtNeedsASIProtection(stmtPath, options)) {
if (stmt.comments && stmt.comments.some(comment => comment.leading)) {
parts.push(print(stmtPath, {
needsSemi: true
}));
} else {
parts.push(";", stmtPrinted);
}
} else {
parts.push(stmtPrinted);
}
if (!options.semi && isClass) {
if (classPropMayCauseASIProblems$1(stmtPath)) {
parts.push(";");
} else if (stmt.type === "ClassProperty") {
const nextChild = bodyNode.body[i + 1];
if (classChildNeedsASIProtection$1(nextChild)) {
parts.push(";");
}
}
}
if (isNextLineEmpty$4(text, stmt, options.locEnd) && !isLastStatement$1(stmtPath)) {
parts.push(hardline$9);
}
printed.push(concat$d(parts));
});
return join$9(hardline$9, printed);
}
function printPropertyKey(path, options, print) {
const node = path.getNode();
if (node.computed) {
return concat$d(["[", path.call(print, "key"), "]"]);
}
const parent = path.getParentNode();
const {
key
} = node;
if (node.type === "ClassPrivateProperty" && // flow has `Identifier` key, and babel has `PrivateName` key
key.type === "Identifier") {
return concat$d(["#", path.call(print, "key")]);
}
if (options.quoteProps === "consistent" && !needsQuoteProps.has(parent)) {
const objectHasStringProp = (parent.properties || parent.body || parent.members).some(prop => !prop.computed && prop.key && isStringLiteral$1(prop.key) && !isStringPropSafeToCoerceToIdentifier$1(prop, options));
needsQuoteProps.set(parent, objectHasStringProp);
}
if (key.type === "Identifier" && (options.parser === "json" || options.quoteProps === "consistent" && needsQuoteProps.get(parent))) {
// a -> "a"
const prop = printString$2(JSON.stringify(key.name), options);
return path.call(keyPath => comments.printComments(keyPath, () => prop, options), "key");
}
if (isStringPropSafeToCoerceToIdentifier$1(node, options) && (options.quoteProps === "as-needed" || options.quoteProps === "consistent" && !needsQuoteProps.get(parent))) {
// 'a' -> a
return path.call(keyPath => comments.printComments(keyPath, () => key.value, options), "key");
}
return path.call(print, "key");
}
function printMethod(path, options, print) {
const node = path.getNode();
const {
kind
} = node;
const value = node.value || node;
const parts = [];
if (!kind || kind === "init" || kind === "method" || kind === "constructor") {
if (value.async) {
parts.push("async ");
}
if (value.generator) {
parts.push("*");
}
} else {
assert.ok(kind === "get" || kind === "set");
parts.push(kind, " ");
}
parts.push(printPropertyKey(path, options, print), node.optional || node.key.optional ? "?" : "", node === value ? printMethodInternal(path, options, print) : path.call(path => printMethodInternal(path, options, print), "value"));
return concat$d(parts);
}
function printMethodInternal(path, options, print) {
const parts = [printFunctionTypeParameters(path, options, print), group$b(concat$d([printFunctionParams(path, print, options), printReturnType(path, print, options)]))];
if (path.getNode().body) {
parts.push(" ", path.call(print, "body"));
} else {
parts.push(options.semi ? ";" : "");
}
return concat$d(parts);
}
function couldGroupArg(arg) {
return arg.type === "ObjectExpression" && (arg.properties.length > 0 || arg.comments) || arg.type === "ArrayExpression" && (arg.elements.length > 0 || arg.comments) || arg.type === "TSTypeAssertion" && couldGroupArg(arg.expression) || arg.type === "TSAsExpression" && couldGroupArg(arg.expression) || arg.type === "FunctionExpression" || arg.type === "ArrowFunctionExpression" && ( // we want to avoid breaking inside composite return types but not simple keywords
// https://github.com/prettier/prettier/issues/4070
// export class Thing implements OtherThing {
// do: (type: Type) => Provider
= memoize(
// (type: ObjectType): Provider => {}
// );
// }
// https://github.com/prettier/prettier/issues/6099
// app.get("/", (req, res): void => {
// res.send("Hello World!");
// });
!arg.returnType || !arg.returnType.typeAnnotation || arg.returnType.typeAnnotation.type !== "TSTypeReference") && (arg.body.type === "BlockStatement" || arg.body.type === "ArrowFunctionExpression" || arg.body.type === "ObjectExpression" || arg.body.type === "ArrayExpression" || arg.body.type === "CallExpression" || arg.body.type === "OptionalCallExpression" || arg.body.type === "ConditionalExpression" || isJSXNode$1(arg.body));
}
function shouldGroupLastArg(args) {
const lastArg = getLast$3(args);
const penultimateArg = getPenultimate$1(args);
return !hasLeadingComment$3(lastArg) && !hasTrailingComment$1(lastArg) && couldGroupArg(lastArg) && ( // If the last two arguments are of the same type,
// disable last element expansion.
!penultimateArg || penultimateArg.type !== lastArg.type);
}
function shouldGroupFirstArg(args) {
if (args.length !== 2) {
return false;
}
const [firstArg, secondArg] = args;
return (!firstArg.comments || !firstArg.comments.length) && (firstArg.type === "FunctionExpression" || firstArg.type === "ArrowFunctionExpression" && firstArg.body.type === "BlockStatement") && secondArg.type !== "FunctionExpression" && secondArg.type !== "ArrowFunctionExpression" && secondArg.type !== "ConditionalExpression" && !couldGroupArg(secondArg);
}
function printJestEachTemplateLiteral(node, expressions, options) {
/**
* a | b | expected
* ${1} | ${1} | ${2}
* ${1} | ${2} | ${3}
* ${2} | ${1} | ${3}
*/
const headerNames = node.quasis[0].value.raw.trim().split(/\s*\|\s*/);
if (headerNames.length > 1 || headerNames.some(headerName => headerName.length !== 0)) {
const parts = [];
const stringifiedExpressions = expressions.map(doc => "${" + printDocToString$2(doc, Object.assign({}, options, {
printWidth: Infinity,
endOfLine: "lf"
})).formatted + "}");
const tableBody = [{
hasLineBreak: false,
cells: []
}];
for (let i = 1; i < node.quasis.length; i++) {
const row = tableBody[tableBody.length - 1];
const correspondingExpression = stringifiedExpressions[i - 1];
row.cells.push(correspondingExpression);
if (correspondingExpression.includes("\n")) {
row.hasLineBreak = true;
}
if (node.quasis[i].value.raw.includes("\n")) {
tableBody.push({
hasLineBreak: false,
cells: []
});
}
}
const maxColumnCount = Math.max(headerNames.length, ...tableBody.map(row => row.cells.length));
const maxColumnWidths = Array.from({
length: maxColumnCount
}).fill(0);
const table = [{
cells: headerNames
}, ...tableBody.filter(row => row.cells.length !== 0)];
for (const {
cells
} of table.filter(row => !row.hasLineBreak)) {
cells.forEach((cell, index) => {
maxColumnWidths[index] = Math.max(maxColumnWidths[index], getStringWidth$3(cell));
});
}
parts.push(lineSuffixBoundary$1, "`", indent$7(concat$d([hardline$9, join$9(hardline$9, table.map(row => join$9(" | ", row.cells.map((cell, index) => row.hasLineBreak ? cell : cell + " ".repeat(maxColumnWidths[index] - getStringWidth$3(cell))))))])), hardline$9, "`");
return concat$d(parts);
}
}
function printArgumentsList(path, options, print) {
const node = path.getValue();
const args = node.arguments;
if (args.length === 0) {
return concat$d(["(", comments.printDanglingComments(path, options,
/* sameIndent */
true), ")"]);
} // useEffect(() => { ... }, [foo, bar, baz])
if (args.length === 2 && args[0].type === "ArrowFunctionExpression" && args[0].params.length === 0 && args[0].body.type === "BlockStatement" && args[1].type === "ArrayExpression" && !args.find(arg => arg.comments)) {
return concat$d(["(", path.call(print, "arguments", 0), ", ", path.call(print, "arguments", 1), ")"]);
} // func(
// ({
// a,
// b
// }) => {}
// );
function shouldBreakForArrowFunctionInArguments(arg, argPath) {
if (!arg || arg.type !== "ArrowFunctionExpression" || !arg.body || arg.body.type !== "BlockStatement" || !arg.params || arg.params.length < 1) {
return false;
}
let shouldBreak = false;
argPath.each(paramPath => {
const printed = concat$d([print(paramPath)]);
shouldBreak = shouldBreak || willBreak$1(printed);
}, "params");
return shouldBreak;
}
let anyArgEmptyLine = false;
let shouldBreakForArrowFunction = false;
let hasEmptyLineFollowingFirstArg = false;
const lastArgIndex = args.length - 1;
const printedArguments = path.map((argPath, index) => {
const arg = argPath.getNode();
const parts = [print(argPath)];
if (index === lastArgIndex) ; else if (isNextLineEmpty$4(options.originalText, arg, options.locEnd)) {
if (index === 0) {
hasEmptyLineFollowingFirstArg = true;
}
anyArgEmptyLine = true;
parts.push(",", hardline$9, hardline$9);
} else {
parts.push(",", line$9);
}
shouldBreakForArrowFunction = shouldBreakForArrowFunctionInArguments(arg, argPath);
return concat$d(parts);
}, "arguments");
const maybeTrailingComma = // Dynamic imports cannot have trailing commas
!(node.callee && node.callee.type === "Import") && shouldPrintComma$1(options, "all") ? "," : "";
function allArgsBrokenOut() {
return group$b(concat$d(["(", indent$7(concat$d([line$9, concat$d(printedArguments)])), maybeTrailingComma, line$9, ")"]), {
shouldBreak: true
});
}
if (path.getParentNode().type !== "Decorator" && isFunctionCompositionArgs$1(args)) {
return allArgsBrokenOut();
}
const shouldGroupFirst = shouldGroupFirstArg(args);
const shouldGroupLast = shouldGroupLastArg(args);
if (shouldGroupFirst || shouldGroupLast) {
const shouldBreak = (shouldGroupFirst ? printedArguments.slice(1).some(willBreak$1) : printedArguments.slice(0, -1).some(willBreak$1)) || anyArgEmptyLine || shouldBreakForArrowFunction; // We want to print the last argument with a special flag
let printedExpanded;
let i = 0;
path.each(argPath => {
if (shouldGroupFirst && i === 0) {
printedExpanded = [concat$d([argPath.call(p => print(p, {
expandFirstArg: true
})), printedArguments.length > 1 ? "," : "", hasEmptyLineFollowingFirstArg ? hardline$9 : line$9, hasEmptyLineFollowingFirstArg ? hardline$9 : ""])].concat(printedArguments.slice(1));
}
if (shouldGroupLast && i === args.length - 1) {
printedExpanded = printedArguments.slice(0, -1).concat(argPath.call(p => print(p, {
expandLastArg: true
})));
}
i++;
}, "arguments");
const somePrintedArgumentsWillBreak = printedArguments.some(willBreak$1);
const simpleConcat = concat$d(["(", concat$d(printedExpanded), ")"]);
return concat$d([somePrintedArgumentsWillBreak ? breakParent$3 : "", conditionalGroup$1([!somePrintedArgumentsWillBreak && !node.typeArguments && !node.typeParameters ? simpleConcat : ifBreak$6(allArgsBrokenOut(), simpleConcat), shouldGroupFirst ? concat$d(["(", group$b(printedExpanded[0], {
shouldBreak: true
}), concat$d(printedExpanded.slice(1)), ")"]) : concat$d(["(", concat$d(printedArguments.slice(0, -1)), group$b(getLast$3(printedExpanded), {
shouldBreak: true
}), ")"]), allArgsBrokenOut()], {
shouldBreak
})]);
}
const contents = concat$d(["(", indent$7(concat$d([softline$6, concat$d(printedArguments)])), ifBreak$6(maybeTrailingComma), softline$6, ")"]);
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$b(contents, {
shouldBreak: printedArguments.some(willBreak$1) || anyArgEmptyLine
});
}
function printTypeAnnotation(path, options, print) {
const node = path.getValue();
if (!node.typeAnnotation) {
return "";
}
const parentNode = path.getParentNode();
const isDefinite = node.definite || parentNode && parentNode.type === "VariableDeclarator" && parentNode.definite;
const isFunctionDeclarationIdentifier = parentNode.type === "DeclareFunction" && parentNode.id === node;
if (isFlowAnnotationComment$1(options.originalText, node.typeAnnotation, options)) {
return concat$d([" /*: ", path.call(print, "typeAnnotation"), " */"]);
}
return concat$d([isFunctionDeclarationIdentifier ? "" : isDefinite ? "!: " : ": ", path.call(print, "typeAnnotation")]);
}
function printFunctionTypeParameters(path, options, print) {
const fun = path.getValue();
if (fun.typeArguments) {
return path.call(print, "typeArguments");
}
if (fun.typeParameters) {
return path.call(print, "typeParameters");
}
return "";
}
function printFunctionParams(path, print, options, expandArg, printTypeParams) {
const fun = path.getValue();
const parent = path.getParentNode();
const paramsField = fun.parameters ? "parameters" : "params";
const isParametersInTestCall = isTestCall$1(parent);
const shouldHugParameters = shouldHugArguments(fun);
const shouldExpandParameters = expandArg && !(fun[paramsField] && fun[paramsField].some(n => n.comments));
const typeParams = printTypeParams ? printFunctionTypeParameters(path, options, print) : "";
let printed = [];
if (fun[paramsField]) {
const lastArgIndex = fun[paramsField].length - 1;
printed = path.map((childPath, index) => {
const parts = [];
const param = childPath.getValue();
parts.push(print(childPath));
if (index === lastArgIndex) {
if (fun.rest) {
parts.push(",", line$9);
}
} else if (isParametersInTestCall || shouldHugParameters || shouldExpandParameters) {
parts.push(", ");
} else if (isNextLineEmpty$4(options.originalText, param, options.locEnd)) {
parts.push(",", hardline$9, hardline$9);
} else {
parts.push(",", line$9);
}
return concat$d(parts);
}, paramsField);
}
if (fun.rest) {
printed.push(concat$d(["...", path.call(print, "rest")]));
}
if (printed.length === 0) {
return concat$d([typeParams, "(", comments.printDanglingComments(path, options,
/* sameIndent */
true, comment => getNextNonSpaceNonCommentCharacter$1(options.originalText, comment, options.locEnd) === ")"), ")"]);
}
const lastParam = getLast$3(fun[paramsField]); // If the parent is a call with the first/last argument expansion and this is the
// params of the first/last argument, we don't want the arguments to break and instead
// want the whole expression to be on a new line.
//
// Good: Bad:
// verylongcall( verylongcall((
// (a, b) => { a,
// } b,
// }) ) => {
// })
if (shouldExpandParameters) {
return group$b(concat$d([removeLines$2(typeParams), "(", concat$d(printed.map(removeLines$2)), ")"]));
} // Single object destructuring should hug
//
// function({
// a,
// b,
// c
// }) {}
const hasNotParameterDecorator = fun[paramsField].every(param => !param.decorators);
if (shouldHugParameters && hasNotParameterDecorator) {
return concat$d([typeParams, "(", concat$d(printed), ")"]);
} // don't break in specs, eg; `it("should maintain parens around done even when long", (done) => {})`
if (isParametersInTestCall) {
return concat$d([typeParams, "(", concat$d(printed), ")"]);
}
const isFlowShorthandWithOneArg = (isObjectTypePropertyAFunction$1(parent, options) || isTypeAnnotationAFunction$1(parent, options) || parent.type === "TypeAlias" || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType" || parent.type === "IntersectionTypeAnnotation" || parent.type === "FunctionTypeAnnotation" && parent.returnType === fun) && fun[paramsField].length === 1 && fun[paramsField][0].name === null && fun[paramsField][0].typeAnnotation && fun.typeParameters === null && isSimpleFlowType$1(fun[paramsField][0].typeAnnotation) && !fun.rest;
if (isFlowShorthandWithOneArg) {
if (options.arrowParens === "always") {
return concat$d(["(", concat$d(printed), ")"]);
}
return concat$d(printed);
}
const canHaveTrailingComma = !(lastParam && lastParam.type === "RestElement") && !fun.rest;
return concat$d([typeParams, "(", indent$7(concat$d([softline$6, concat$d(printed)])), ifBreak$6(canHaveTrailingComma && shouldPrintComma$1(options, "all") ? "," : ""), softline$6, ")"]);
}
function shouldPrintParamsWithoutParens(path, options) {
if (options.arrowParens === "always") {
return false;
}
if (options.arrowParens === "avoid") {
const node = path.getValue();
return canPrintParamsWithoutParens(node);
} // Fallback default; should be unreachable
return false;
}
function canPrintParamsWithoutParens(node) {
return node.params.length === 1 && !node.rest && !node.typeParameters && !hasDanglingComments$1(node) && node.params[0].type === "Identifier" && !node.params[0].typeAnnotation && !node.params[0].comments && !node.params[0].optional && !node.predicate && !node.returnType;
}
function printFunctionDeclaration(path, print, options) {
const n = path.getValue();
const parts = [];
if (n.async) {
parts.push("async ");
}
if (n.generator) {
parts.push("function* ");
} else {
parts.push("function ");
}
if (n.id) {
parts.push(path.call(print, "id"));
}
parts.push(printFunctionTypeParameters(path, options, print), group$b(concat$d([printFunctionParams(path, print, options), printReturnType(path, print, options)])), n.body ? " " : "", path.call(print, "body"));
return concat$d(parts);
}
function printReturnType(path, print, options) {
const n = path.getValue();
const returnType = path.call(print, "returnType");
if (n.returnType && isFlowAnnotationComment$1(options.originalText, n.returnType, options)) {
return concat$d([" /*: ", returnType, " */"]);
}
const parts = [returnType]; // prepend colon to TypeScript type annotation
if (n.returnType && n.returnType.typeAnnotation) {
parts.unshift(": ");
}
if (n.predicate) {
// The return type will already add the colon, but otherwise we
// need to do it ourselves
parts.push(n.returnType ? " " : ": ", path.call(print, "predicate"));
}
return concat$d(parts);
}
function printExportDeclaration(path, options, print) {
const decl = path.getValue();
const semi = options.semi ? ";" : "";
const parts = ["export "];
const isDefault = decl.default || decl.type === "ExportDefaultDeclaration";
if (isDefault) {
parts.push("default ");
}
parts.push(comments.printDanglingComments(path, options,
/* sameIndent */
true));
if (needsHardlineAfterDanglingComment$1(decl)) {
parts.push(hardline$9);
}
if (decl.declaration) {
parts.push(path.call(print, "declaration"));
if (isDefault && decl.declaration.type !== "ClassDeclaration" && decl.declaration.type !== "FunctionDeclaration" && decl.declaration.type !== "TSInterfaceDeclaration" && decl.declaration.type !== "DeclareClass" && decl.declaration.type !== "DeclareFunction" && decl.declaration.type !== "TSDeclareFunction") {
parts.push(semi);
}
} else {
if (decl.specifiers && decl.specifiers.length > 0) {
const specifiers = [];
const defaultSpecifiers = [];
const namespaceSpecifiers = [];
path.each(specifierPath => {
const specifierType = path.getValue().type;
if (specifierType === "ExportSpecifier") {
specifiers.push(print(specifierPath));
} else if (specifierType === "ExportDefaultSpecifier") {
defaultSpecifiers.push(print(specifierPath));
} else if (specifierType === "ExportNamespaceSpecifier") {
namespaceSpecifiers.push(concat$d(["* as ", print(specifierPath)]));
}
}, "specifiers");
const isNamespaceFollowed = namespaceSpecifiers.length !== 0 && specifiers.length !== 0;
const isDefaultFollowed = defaultSpecifiers.length !== 0 && (namespaceSpecifiers.length !== 0 || specifiers.length !== 0);
const canBreak = specifiers.length > 1 || defaultSpecifiers.length > 0 || decl.specifiers && decl.specifiers.some(node => node.comments);
let printed = "";
if (specifiers.length !== 0) {
if (canBreak) {
printed = group$b(concat$d(["{", indent$7(concat$d([options.bracketSpacing ? line$9 : softline$6, join$9(concat$d([",", line$9]), specifiers)])), ifBreak$6(shouldPrintComma$1(options) ? "," : ""), options.bracketSpacing ? line$9 : softline$6, "}"]));
} else {
printed = concat$d(["{", options.bracketSpacing ? " " : "", concat$d(specifiers), options.bracketSpacing ? " " : "", "}"]);
}
}
parts.push(decl.exportKind === "type" ? "type " : "", concat$d(defaultSpecifiers), concat$d([isDefaultFollowed ? ", " : ""]), concat$d(namespaceSpecifiers), concat$d([isNamespaceFollowed ? ", " : ""]), printed);
} else {
parts.push("{}");
}
if (decl.source) {
parts.push(" from ", path.call(print, "source"));
}
parts.push(semi);
}
return concat$d(parts);
}
function printFlowDeclaration(path, parts) {
const parentExportDecl = getParentExportDeclaration$1(path);
if (parentExportDecl) {
assert.strictEqual(parentExportDecl.type, "DeclareExportDeclaration");
} else {
// If the parent node has type DeclareExportDeclaration, then it
// will be responsible for printing the "declare" token. Otherwise
// it needs to be printed with this non-exported declaration node.
parts.unshift("declare ");
}
return concat$d(parts);
}
function printTypeScriptModifiers(path, options, print) {
const n = path.getValue();
if (!n.modifiers || !n.modifiers.length) {
return "";
}
return concat$d([join$9(" ", path.map(print, "modifiers")), " "]);
}
function printTypeParameters(path, options, print, paramsKey) {
const n = path.getValue();
if (!n[paramsKey]) {
return "";
} // for TypeParameterDeclaration typeParameters is a single node
if (!Array.isArray(n[paramsKey])) {
return path.call(print, paramsKey);
}
const grandparent = path.getNode(2);
const greatGrandParent = path.getNode(3);
const greatGreatGrandParent = path.getNode(4);
const isParameterInTestCall = grandparent != null && isTestCall$1(grandparent);
const shouldInline = isParameterInTestCall || n[paramsKey].length === 0 || n[paramsKey].length === 1 && (shouldHugType(n[paramsKey][0]) || n[paramsKey][0].type === "GenericTypeAnnotation" && shouldHugType(n[paramsKey][0].id) || n[paramsKey][0].type === "TSTypeReference" && shouldHugType(n[paramsKey][0].typeName) || n[paramsKey][0].type === "NullableTypeAnnotation" || // See https://github.com/prettier/prettier/pull/6467 for the context.
greatGreatGrandParent && greatGreatGrandParent.type === "VariableDeclarator" && grandparent.type === "TSTypeAnnotation" && greatGrandParent.type !== "ArrowFunctionExpression" && n[paramsKey][0].type !== "TSUnionType" && n[paramsKey][0].type !== "UnionTypeAnnotation" && n[paramsKey][0].type !== "TSIntersectionType" && n[paramsKey][0].type !== "IntersectionTypeAnnotation" && n[paramsKey][0].type !== "TSConditionalType" && n[paramsKey][0].type !== "TSMappedType" && n[paramsKey][0].type !== "TSTypeOperator" && n[paramsKey][0].type !== "TSIndexedAccessType" && n[paramsKey][0].type !== "TSArrayType");
function printDanglingCommentsForInline(n) {
if (!hasDanglingComments$1(n)) {
return "";
}
const hasOnlyBlockComments = n.comments.every(comments$1.isBlockComment);
const printed = comments.printDanglingComments(path, options,
/* sameIndent */
hasOnlyBlockComments);
if (hasOnlyBlockComments) {
return printed;
}
return concat$d([printed, hardline$9]);
}
if (shouldInline) {
return concat$d(["<", join$9(", ", path.map(print, paramsKey)), printDanglingCommentsForInline(n), ">"]);
}
return group$b(concat$d(["<", indent$7(concat$d([softline$6, join$9(concat$d([",", line$9]), path.map(print, paramsKey))])), ifBreak$6(options.parser !== "typescript" && options.parser !== "babel-ts" && shouldPrintComma$1(options, "all") ? "," : ""), softline$6, ">"]));
}
function printClass(path, options, print) {
const n = path.getValue();
const parts = [];
if (n.abstract) {
parts.push("abstract ");
}
parts.push("class");
if (n.id) {
parts.push(" ", path.call(print, "id"));
}
parts.push(path.call(print, "typeParameters"));
const partsGroup = [];
if (n.superClass) {
const printed = concat$d(["extends ", path.call(print, "superClass"), path.call(print, "superTypeParameters")]); // Keep old behaviour of extends in same line
// If there is only on extends and there are not comments
if ((!n.implements || n.implements.length === 0) && (!n.superClass.comments || n.superClass.comments.length === 0)) {
parts.push(concat$d([" ", path.call(superClass => comments.printComments(superClass, () => printed, options), "superClass")]));
} else {
partsGroup.push(group$b(concat$d([line$9, path.call(superClass => comments.printComments(superClass, () => printed, options), "superClass")])));
}
} else if (n.extends && n.extends.length > 0) {
parts.push(" extends ", join$9(", ", path.map(print, "extends")));
}
if (n.mixins && n.mixins.length > 0) {
partsGroup.push(line$9, "mixins ", group$b(indent$7(join$9(concat$d([",", line$9]), path.map(print, "mixins")))));
}
if (n.implements && n.implements.length > 0) {
partsGroup.push(line$9, "implements", group$b(indent$7(concat$d([line$9, join$9(concat$d([",", line$9]), path.map(print, "implements"))]))));
}
if (partsGroup.length > 0) {
parts.push(group$b(indent$7(concat$d(partsGroup))));
}
if (n.body && n.body.comments && hasLeadingOwnLineComment$1(options.originalText, n.body, options)) {
parts.push(hardline$9);
} else {
parts.push(" ");
}
parts.push(path.call(print, "body"));
return parts;
}
function printOptionalToken(path) {
const node = path.getValue();
if (!node.optional || // It's an optional computed method parsed by typescript-estree.
// "?" is printed in `printMethod`.
node.type === "Identifier" && node === path.getParentNode().key) {
return "";
}
if (node.type === "OptionalCallExpression" || node.type === "OptionalMemberExpression" && node.computed) {
return "?.";
}
return "?";
}
function printMemberLookup(path, options, print) {
const property = path.call(print, "property");
const n = path.getValue();
const optional = printOptionalToken(path);
if (!n.computed) {
return concat$d([optional, ".", property]);
}
if (!n.property || isNumericLiteral$1(n.property)) {
return concat$d([optional, "[", property, "]"]);
}
return group$b(concat$d([optional, "[", indent$7(concat$d([softline$6, property])), softline$6, "]"]));
}
function printBindExpressionCallee(path, options, print) {
return concat$d(["::", path.call(print, "callee")]);
} // We detect calls on member expressions specially to format a
// common pattern better. The pattern we are looking for is this:
//
// arr
// .map(x => x + 1)
// .filter(x => x > 10)
// .some(x => x % 2)
//
// The way it is structured in the AST is via a nested sequence of
// MemberExpression and CallExpression. We need to traverse the AST
// and make groups out of it to print it in the desired way.
function printMemberChain(path, options, print) {
// The first phase is to linearize the AST by traversing it down.
//
// a().b()
// has the following AST structure:
// CallExpression(MemberExpression(CallExpression(Identifier)))
// and we transform it into
// [Identifier, CallExpression, MemberExpression, CallExpression]
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$3(originalText, node, options.locEnd);
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 isNextLineEmptyAfterIndex$2(originalText, nextCharIndex + 1, options.locEnd);
}
return isNextLineEmpty$4(originalText, node, options.locEnd);
}
function rec(path) {
const node = path.getValue();
if ((node.type === "CallExpression" || node.type === "OptionalCallExpression") && (isMemberish$1(node.callee) || node.callee.type === "CallExpression" || node.callee.type === "OptionalCallExpression")) {
printedNodes.unshift({
node,
printed: concat$d([comments.printComments(path, () => concat$d([printOptionalToken(path), printFunctionTypeParameters(path, options, print), printArgumentsList(path, options, print)]), options), shouldInsertEmptyLineAfter(node) ? hardline$9 : ""])
});
path.call(callee => rec(callee), "callee");
} else if (isMemberish$1(node)) {
printedNodes.unshift({
node,
needsParens: needsParens_1(path, options),
printed: comments.printComments(path, () => node.type === "OptionalMemberExpression" || node.type === "MemberExpression" ? printMemberLookup(path, options, print) : printBindExpressionCallee(path, options, print), options)
});
path.call(object => rec(object), "object");
} else if (node.type === "TSNonNullExpression") {
printedNodes.unshift({
node,
printed: comments.printComments(path, () => "!", options)
});
path.call(expression => rec(expression), "expression");
} else {
printedNodes.unshift({
node,
printed: path.call(print)
});
}
} // Note: the comments of the root node have already been printed, so we
// need to extract this first call without printing them as they would
// if handled inside of the recursive call.
const node = path.getValue();
printedNodes.unshift({
node,
printed: concat$d([printOptionalToken(path), printFunctionTypeParameters(path, options, print), printArgumentsList(path, options, print)])
});
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" || printedNodes[i].node.type === "OptionalCallExpression" || printedNodes[i].node.type === "CallExpression" || (printedNodes[i].node.type === "MemberExpression" || printedNodes[i].node.type === "OptionalMemberExpression") && printedNodes[i].node.computed && isNumericLiteral$1(printedNodes[i].node.property)) {
currentGroup.push(printedNodes[i]);
} else {
break;
}
}
if (printedNodes[0].node.type !== "CallExpression" && printedNodes[0].node.type !== "OptionalCallExpression") {
for (; i + 1 < printedNodes.length; ++i) {
if (isMemberish$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$1(printedNodes[i].node.property)) {
currentGroup.push(printedNodes[i]);
continue;
}
groups.push(currentGroup);
currentGroup = [];
hasSeenCallExpression = false;
}
if (printedNodes[i].node.type === "CallExpression" || printedNodes[i].node.type === "OptionalCallExpression") {
hasSeenCallExpression = true;
}
currentGroup.push(printedNodes[i]);
if (printedNodes[i].node.comments && printedNodes[i].node.comments.some(comment => comment.trailing)) {
groups.push(currentGroup);
currentGroup = [];
hasSeenCallExpression = false;
}
}
if (currentGroup.length > 0) {
groups.push(currentGroup);
} // There are cases like Object.keys(), Observable.of(), _.values() where
// they are the subject of all the chained calls and therefore should
// be kept on the same line:
//
// Object.keys(items)
// .filter(x => x)
// .map(x => x)
//
// In order to detect those cases, we use an heuristic: if the first
// node is an identifier with the name starting with a capital
// letter or just a sequence of _$. The rationale is that they are
// likely to be factories.
function isFactory(name) {
return /^[A-Z]|^[_$]+$/.test(name);
} // In case the Identifier is shorter than tab width, we can keep the
// first call in a single line, if it's an ExpressionStatement.
//
// d3.scaleLinear()
// .domain([0, 100])
// .range([0, width]);
//
function isShort(name) {
return name.length <= options.tabWidth;
}
function shouldNotWrap(groups) {
const parent = path.getParentNode();
const isExpression = parent && parent.type === "ExpressionStatement";
const hasComputed = groups[1].length && 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) || isExpression && isShort(firstNode.name) || hasComputed);
}
const lastNode = getLast$3(groups[0]).node;
return (lastNode.type === "MemberExpression" || lastNode.type === "OptionalMemberExpression") && lastNode.property.type === "Identifier" && (isFactory(lastNode.property.name) || hasComputed);
}
const shouldMerge = groups.length >= 2 && !groups[1][0].node.comments && 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 && printedGroup[printedGroup.length - 1].needsParens) {
return concat$d(["(", ...printed, ")"]);
}
return concat$d(printed);
}
function printIndentedGroup(groups) {
if (groups.length === 0) {
return "";
}
return indent$7(group$b(concat$d([hardline$9, join$9(hardline$9, groups.map(printGroup))])));
}
const printedGroups = groups.map(printGroup);
const oneLine = concat$d(printedGroups);
const cutoff = shouldMerge ? 3 : 2;
const flatGroups = groups.reduce((res, group) => res.concat(group), []);
const hasComment = flatGroups.slice(1, -1).some(node => hasLeadingComment$3(node.node)) || flatGroups.slice(0, -1).some(node => hasTrailingComment$1(node.node)) || groups[cutoff] && hasLeadingComment$3(groups[cutoff][0].node); // If we only have a single `.`, we shouldn't do anything fancy and just
// render everything concatenated together.
if (groups.length <= cutoff && !hasComment) {
if (isLongCurriedCallExpression$1(path)) {
return oneLine;
}
return group$b(oneLine);
} // Find out the last node in the first group and check if it has an
// empty line after
const lastNodeBeforeIndent = getLast$3(shouldMerge ? groups.slice(1, 2)[0] : groups[0]).node;
const shouldHaveEmptyLineBeforeIndent = lastNodeBeforeIndent.type !== "CallExpression" && lastNodeBeforeIndent.type !== "OptionalCallExpression" && shouldInsertEmptyLineAfter(lastNodeBeforeIndent);
const expanded = concat$d([printGroup(groups[0]), shouldMerge ? concat$d(groups.slice(1, 2).map(printGroup)) : "", shouldHaveEmptyLineBeforeIndent ? hardline$9 : "", printIndentedGroup(groups.slice(shouldMerge ? 2 : 1))]);
const callExpressions = printedNodes.map(({
node
}) => node).filter(isCallOrOptionalCallExpression$1); // We don't want to print in one line if the chain has:
// * A comment.
// * Non-trivial arguments.
// * Any group but the last one has a hard line.
// If the last group is a function it's okay to inline if it fits.
if (hasComment || callExpressions.length > 2 && callExpressions.some(expr => !expr.arguments.every(arg => isSimpleCallArgument$1(arg, 0))) || printedGroups.slice(0, -1).some(willBreak$1) ||
/**
* scopes.filter(scope => scope.value !== '').map((scope, i) => {
* // multi line content
* })
*/
((lastGroupDoc, lastGroupNode) => isCallOrOptionalCallExpression$1(lastGroupNode) && willBreak$1(lastGroupDoc))(getLast$3(printedGroups), getLast$3(getLast$3(groups)).node) && callExpressions.slice(0, -1).some(n => n.arguments.some(isFunctionOrArrowExpression$1))) {
return group$b(expanded);
}
return concat$d([// We only need to check `oneLine` because if `expanded` is chosen
// that means that the parent group has already been broken
// naturally
willBreak$1(oneLine) || shouldHaveEmptyLineBeforeIndent ? breakParent$3 : "", conditionalGroup$1([oneLine, expanded])]);
}
function separatorNoWhitespace(isFacebookTranslationTag, child, childNode, nextNode) {
if (isFacebookTranslationTag) {
return "";
}
if (childNode.type === "JSXElement" && !childNode.closingElement || nextNode && nextNode.type === "JSXElement" && !nextNode.closingElement) {
return child.length === 1 ? softline$6 : hardline$9;
}
return softline$6;
}
function separatorWithWhitespace(isFacebookTranslationTag, child, childNode, nextNode) {
if (isFacebookTranslationTag) {
return hardline$9;
}
if (child.length === 1) {
return childNode.type === "JSXElement" && !childNode.closingElement || nextNode && nextNode.type === "JSXElement" && !nextNode.closingElement ? hardline$9 : softline$6;
}
return hardline$9;
} // JSX Children are strange, mostly for two reasons:
// 1. JSX reads newlines into string values, instead of skipping them like JS
// 2. up to one whitespace between elements within a line is significant,
// but not between lines.
//
// Leading, trailing, and lone whitespace all need to
// turn themselves into the rather ugly `{' '}` when breaking.
//
// We print JSX using the `fill` doc primitive.
// This requires that we give it an array of alternating
// content and whitespace elements.
// To ensure this we add dummy `""` content elements as needed.
function printJSXChildren(path, options, print, jsxWhitespace, isFacebookTranslationTag) {
const n = path.getValue();
const children = []; // using `map` instead of `each` because it provides `i`
path.map((childPath, i) => {
const child = childPath.getValue();
if (isLiteral$1(child)) {
const text = rawText$1(child); // Contains a non-whitespace character
if (isMeaningfulJSXText$1(child)) {
const words = text.split(matchJsxWhitespaceRegex$1); // Starts with whitespace
if (words[0] === "") {
children.push("");
words.shift();
if (/\n/.test(words[0])) {
const next = n.children[i + 1];
children.push(separatorWithWhitespace(isFacebookTranslationTag, words[1], child, next));
} else {
children.push(jsxWhitespace);
}
words.shift();
}
let endWhitespace; // Ends with whitespace
if (getLast$3(words) === "") {
words.pop();
endWhitespace = words.pop();
} // This was whitespace only without a new line.
if (words.length === 0) {
return;
}
words.forEach((word, i) => {
if (i % 2 === 1) {
children.push(line$9);
} else {
children.push(word);
}
});
if (endWhitespace !== undefined) {
if (/\n/.test(endWhitespace)) {
const next = n.children[i + 1];
children.push(separatorWithWhitespace(isFacebookTranslationTag, getLast$3(children), child, next));
} else {
children.push(jsxWhitespace);
}
} else {
const next = n.children[i + 1];
children.push(separatorNoWhitespace(isFacebookTranslationTag, getLast$3(children), child, next));
}
} else if (/\n/.test(text)) {
// Keep (up to one) blank line between tags/expressions/text.
// Note: We don't keep blank lines between text elements.
if (text.match(/\n/g).length > 1) {
children.push("");
children.push(hardline$9);
}
} else {
children.push("");
children.push(jsxWhitespace);
}
} else {
const printedChild = print(childPath);
children.push(printedChild);
const next = n.children[i + 1];
const directlyFollowedByMeaningfulText = next && isMeaningfulJSXText$1(next);
if (directlyFollowedByMeaningfulText) {
const firstWord = rawText$1(next).trim().split(matchJsxWhitespaceRegex$1)[0];
children.push(separatorNoWhitespace(isFacebookTranslationTag, firstWord, child, next));
} else {
children.push(hardline$9);
}
}
}, "children");
return children;
} // JSX expands children from the inside-out, instead of the outside-in.
// This is both to break children before attributes,
// and to ensure that when children break, their parents do as well.
//
// Any element that is written without any newlines and fits on a single line
// is left that way.
// Not only that, any user-written-line containing multiple JSX siblings
// should also be kept on one line if possible,
// so each user-written-line is wrapped in its own group.
//
// Elements that contain newlines or don't fit on a single line (recursively)
// are fully-split, using hardline and shouldBreak: true.
//
// To support that case properly, all leading and trailing spaces
// are stripped from the list of children, and replaced with a single hardline.
function printJSXElement(path, options, print) {
const n = path.getValue();
if (n.type === "JSXElement" && isEmptyJSXElement$1(n)) {
return concat$d([path.call(print, "openingElement"), path.call(print, "closingElement")]);
}
const openingLines = n.type === "JSXElement" ? path.call(print, "openingElement") : path.call(print, "openingFragment");
const closingLines = n.type === "JSXElement" ? path.call(print, "closingElement") : path.call(print, "closingFragment");
if (n.children.length === 1 && n.children[0].type === "JSXExpressionContainer" && (n.children[0].expression.type === "TemplateLiteral" || n.children[0].expression.type === "TaggedTemplateExpression")) {
return concat$d([openingLines, concat$d(path.map(print, "children")), closingLines]);
} // Convert `{" "}` to text nodes containing a space.
// This makes it easy to turn them into `jsxWhitespace` which
// can then print as either a space or `{" "}` when breaking.
n.children = n.children.map(child => {
if (isJSXWhitespaceExpression$1(child)) {
return {
type: "JSXText",
value: " ",
raw: " "
};
}
return child;
});
const containsTag = n.children.filter(isJSXNode$1).length > 0;
const containsMultipleExpressions = n.children.filter(child => child.type === "JSXExpressionContainer").length > 1;
const containsMultipleAttributes = n.type === "JSXElement" && n.openingElement.attributes.length > 1; // Record any breaks. Should never go from true to false, only false to true.
let forcedBreak = willBreak$1(openingLines) || containsTag || containsMultipleAttributes || containsMultipleExpressions;
const isMdxBlock = path.getParentNode().rootMarker === "mdx";
const rawJsxWhitespace = options.singleQuote ? "{' '}" : '{" "}';
const jsxWhitespace = isMdxBlock ? concat$d([" "]) : ifBreak$6(concat$d([rawJsxWhitespace, softline$6]), " ");
const isFacebookTranslationTag = n.openingElement && n.openingElement.name && n.openingElement.name.name === "fbt";
const children = printJSXChildren(path, options, print, jsxWhitespace, isFacebookTranslationTag);
const containsText = n.children.some(child => isMeaningfulJSXText$1(child)); // We can end up we multiple whitespace elements with empty string
// content between them.
// We need to remove empty whitespace and softlines before JSX whitespace
// to get the correct output.
for (let i = children.length - 2; i >= 0; i--) {
const isPairOfEmptyStrings = children[i] === "" && children[i + 1] === "";
const isPairOfHardlines = children[i] === hardline$9 && children[i + 1] === "" && children[i + 2] === hardline$9;
const isLineFollowedByJSXWhitespace = (children[i] === softline$6 || children[i] === hardline$9) && children[i + 1] === "" && children[i + 2] === jsxWhitespace;
const isJSXWhitespaceFollowedByLine = children[i] === jsxWhitespace && children[i + 1] === "" && (children[i + 2] === softline$6 || children[i + 2] === hardline$9);
const isDoubleJSXWhitespace = children[i] === jsxWhitespace && children[i + 1] === "" && children[i + 2] === jsxWhitespace;
const isPairOfHardOrSoftLines = children[i] === softline$6 && children[i + 1] === "" && children[i + 2] === hardline$9 || children[i] === hardline$9 && children[i + 1] === "" && children[i + 2] === softline$6;
if (isPairOfHardlines && containsText || isPairOfEmptyStrings || isLineFollowedByJSXWhitespace || isDoubleJSXWhitespace || isPairOfHardOrSoftLines) {
children.splice(i, 2);
} else if (isJSXWhitespaceFollowedByLine) {
children.splice(i + 1, 2);
}
} // Trim trailing lines (or empty strings)
while (children.length && (isLineNext$1(getLast$3(children)) || isEmpty$1(getLast$3(children)))) {
children.pop();
} // Trim leading lines (or empty strings)
while (children.length && (isLineNext$1(children[0]) || isEmpty$1(children[0])) && (isLineNext$1(children[1]) || isEmpty$1(children[1]))) {
children.shift();
children.shift();
} // Tweak how we format children if outputting this element over multiple lines.
// Also detect whether we will force this element to output over multiple lines.
const multilineChildren = [];
children.forEach((child, i) => {
// There are a number of situations where we need to ensure we display
// whitespace as `{" "}` when outputting this element over multiple lines.
if (child === jsxWhitespace) {
if (i === 1 && children[i - 1] === "") {
if (children.length === 2) {
// Solitary whitespace
multilineChildren.push(rawJsxWhitespace);
return;
} // Leading whitespace
multilineChildren.push(concat$d([rawJsxWhitespace, hardline$9]));
return;
} else if (i === children.length - 1) {
// Trailing whitespace
multilineChildren.push(rawJsxWhitespace);
return;
} else if (children[i - 1] === "" && children[i - 2] === hardline$9) {
// Whitespace after line break
multilineChildren.push(rawJsxWhitespace);
return;
}
}
multilineChildren.push(child);
if (willBreak$1(child)) {
forcedBreak = true;
}
}); // If there is text we use `fill` to fit as much onto each line as possible.
// When there is no text (just tags and expressions) we use `group`
// to output each on a separate line.
const content = containsText ? fill$4(multilineChildren) : group$b(concat$d(multilineChildren), {
shouldBreak: true
});
if (isMdxBlock) {
return content;
}
const multiLineElem = group$b(concat$d([openingLines, indent$7(concat$d([hardline$9, content])), hardline$9, closingLines]));
if (forcedBreak) {
return multiLineElem;
}
return conditionalGroup$1([group$b(concat$d([openingLines, concat$d(children), closingLines])), multiLineElem]);
}
function maybeWrapJSXElementInParens(path, elem, options) {
const parent = path.getParentNode();
if (!parent) {
return elem;
}
const NO_WRAP_PARENTS = {
ArrayExpression: true,
JSXAttribute: true,
JSXElement: true,
JSXExpressionContainer: true,
JSXFragment: true,
ExpressionStatement: true,
CallExpression: true,
OptionalCallExpression: true,
ConditionalExpression: true,
JsExpressionRoot: true
};
if (NO_WRAP_PARENTS[parent.type]) {
return elem;
}
const shouldBreak = path.match(undefined, node => node.type === "ArrowFunctionExpression", isCallOrOptionalCallExpression$1, node => node.type === "JSXExpressionContainer");
const needsParens = needsParens_1(path, options);
return group$b(concat$d([needsParens ? "" : ifBreak$6("("), indent$7(concat$d([softline$6, elem])), softline$6, needsParens ? "" : ifBreak$6(")")]), {
shouldBreak
});
}
function shouldInlineLogicalExpression(node) {
if (node.type !== "LogicalExpression") {
return false;
}
if (node.right.type === "ObjectExpression" && node.right.properties.length !== 0) {
return true;
}
if (node.right.type === "ArrayExpression" && node.right.elements.length !== 0) {
return true;
}
if (isJSXNode$1(node.right)) {
return true;
}
return false;
} // For binary expressions to be consistent, we need to group
// subsequent operators with the same precedence level under a single
// group. Otherwise they will be nested such that some of them break
// onto new lines but not all. Operators with the same precedence
// level should either all break or not. Because we group them by
// precedence level and the AST is structured based on precedence
// level, things are naturally broken up correctly, i.e. `&&` is
// broken before `+`.
function printBinaryishExpressions(path, print, options, isNested, isInsideParenthesis) {
let parts = [];
const node = path.getValue(); // We treat BinaryExpression and LogicalExpression nodes the same.
if (isBinaryish$1(node)) {
// Put all operators with the same precedence level in the same
// group. The reason we only need to do this with the `left`
// expression is because given an expression like `1 + 2 - 3`, it
// is always parsed like `((1 + 2) - 3)`, meaning the `left` side
// is where the rest of the expression will exist. Binary
// expressions on the right side mean they have a difference
// precedence level and should be treated as a separate group, so
// print them normally. (This doesn't hold for the `**` operator,
// which is unique in that it is right-associative.)
if (shouldFlatten$1(node.operator, node.left.operator)) {
// Flatten them out by recursively calling this function.
parts = parts.concat(path.call(left => printBinaryishExpressions(left, print, options,
/* isNested */
true, isInsideParenthesis), "left"));
} else {
parts.push(path.call(print, "left"));
}
const shouldInline = shouldInlineLogicalExpression(node);
const lineBeforeOperator = (node.operator === "|>" || node.type === "NGPipeExpression" || node.operator === "|" && options.parser === "__vue_expression") && !hasLeadingOwnLineComment$1(options.originalText, node.right, options);
const operator = node.type === "NGPipeExpression" ? "|" : node.operator;
const rightSuffix = node.type === "NGPipeExpression" && node.arguments.length !== 0 ? group$b(indent$7(concat$d([softline$6, ": ", join$9(concat$d([softline$6, ":", ifBreak$6(" ")]), path.map(print, "arguments").map(arg => align$1(2, group$b(arg))))]))) : "";
const right = shouldInline ? concat$d([operator, " ", path.call(print, "right"), rightSuffix]) : concat$d([lineBeforeOperator ? softline$6 : "", operator, lineBeforeOperator ? " " : line$9, path.call(print, "right"), rightSuffix]); // If there's only a single binary expression, we want to create a group
// in order to avoid having a small right part like -1 be on its own line.
const parent = path.getParentNode();
const shouldGroup = !(isInsideParenthesis && node.type === "LogicalExpression") && parent.type !== node.type && node.left.type !== node.type && node.right.type !== node.type;
parts.push(" ", shouldGroup ? group$b(right) : right); // The root comments are already printed, but we need to manually print
// the other ones since we don't call the normal print on BinaryExpression,
// only for the left and right parts
if (isNested && node.comments) {
parts = comments.printComments(path, () => concat$d(parts), options);
}
} else {
// Our stopping case. Simply print the node normally.
parts.push(path.call(print));
}
return parts;
}
function printAssignmentRight(leftNode, rightNode, printedRight, options) {
if (hasLeadingOwnLineComment$1(options.originalText, rightNode, options)) {
return indent$7(concat$d([line$9, printedRight]));
}
const canBreak = isBinaryish$1(rightNode) && !shouldInlineLogicalExpression(rightNode) || rightNode.type === "ConditionalExpression" && isBinaryish$1(rightNode.test) && !shouldInlineLogicalExpression(rightNode.test) || rightNode.type === "StringLiteralTypeAnnotation" || rightNode.type === "ClassExpression" && rightNode.decorators && rightNode.decorators.length || (leftNode.type === "Identifier" || isStringLiteral$1(leftNode) || leftNode.type === "MemberExpression") && (isStringLiteral$1(rightNode) || isMemberExpressionChain$1(rightNode)) && // do not put values on a separate line from the key in json
options.parser !== "json" && options.parser !== "json5" || rightNode.type === "SequenceExpression";
if (canBreak) {
return group$b(indent$7(concat$d([line$9, printedRight])));
}
return concat$d([" ", printedRight]);
}
function printAssignment(leftNode, printedLeft, operator, rightNode, printedRight, options) {
if (!rightNode) {
return printedLeft;
}
const printed = printAssignmentRight(leftNode, rightNode, printedRight, options);
return group$b(concat$d([printedLeft, operator, printed]));
}
function adjustClause(node, clause, forceSpace) {
if (node.type === "EmptyStatement") {
return ";";
}
if (node.type === "BlockStatement" || forceSpace) {
return concat$d([" ", clause]);
}
return indent$7(concat$d([line$9, clause]));
}
function nodeStr(node, options, isFlowOrTypeScriptDirectiveLiteral) {
const raw = rawText$1(node);
const isDirectiveLiteral = isFlowOrTypeScriptDirectiveLiteral || node.type === "DirectiveLiteral";
return printString$2(raw, options, isDirectiveLiteral);
}
function printRegex(node) {
const flags = node.flags.split("").sort().join("");
return "/".concat(node.pattern, "/").concat(flags);
}
function exprNeedsASIProtection(path, options) {
const node = path.getValue();
const maybeASIProblem = needsParens_1(path, options) || node.type === "ParenthesizedExpression" || node.type === "TypeCastExpression" || node.type === "ArrowFunctionExpression" && !shouldPrintParamsWithoutParens(path, options) || node.type === "ArrayExpression" || node.type === "ArrayPattern" || node.type === "UnaryExpression" && node.prefix && (node.operator === "+" || node.operator === "-") || node.type === "TemplateLiteral" || node.type === "TemplateElement" || isJSXNode$1(node) || node.type === "BindExpression" && !node.object || node.type === "RegExpLiteral" || node.type === "Literal" && node.pattern || node.type === "Literal" && node.regex;
if (maybeASIProblem) {
return true;
}
if (!hasNakedLeftSide$2(node)) {
return false;
}
return path.call(childPath => exprNeedsASIProtection(childPath, options), ...getLeftSidePathName$2(path, node));
}
function stmtNeedsASIProtection(path, options) {
const node = path.getNode();
if (node.type !== "ExpressionStatement") {
return false;
}
return path.call(childPath => exprNeedsASIProtection(childPath, options), "expression");
}
function shouldHugType(node) {
if (isSimpleFlowType$1(node) || isObjectType$1(node)) {
return true;
}
if (node.type === "UnionTypeAnnotation" || node.type === "TSUnionType") {
const voidCount = node.types.filter(n => n.type === "VoidTypeAnnotation" || n.type === "TSVoidKeyword" || n.type === "NullLiteralTypeAnnotation" || n.type === "TSNullKeyword").length;
const hasObject = node.types.some(n => n.type === "ObjectTypeAnnotation" || n.type === "TSTypeLiteral" || // This is a bit aggressive but captures Array<{x}>
n.type === "GenericTypeAnnotation" || n.type === "TSTypeReference");
if (node.types.length - 1 === voidCount && hasObject) {
return true;
}
}
return false;
}
function shouldHugArguments(fun) {
if (!fun || fun.rest) {
return false;
}
const params = fun.params || fun.parameters;
if (!params || params.length !== 1) {
return false;
}
const param = params[0];
return !param.comments && (param.type === "ObjectPattern" || param.type === "ArrayPattern" || param.type === "Identifier" && param.typeAnnotation && (param.typeAnnotation.type === "TypeAnnotation" || param.typeAnnotation.type === "TSTypeAnnotation") && isObjectType$1(param.typeAnnotation.typeAnnotation) || param.type === "FunctionTypeParam" && isObjectType$1(param.typeAnnotation) || param.type === "AssignmentPattern" && (param.left.type === "ObjectPattern" || param.left.type === "ArrayPattern") && (param.right.type === "Identifier" || param.right.type === "ObjectExpression" && param.right.properties.length === 0 || param.right.type === "ArrayExpression" && param.right.elements.length === 0));
}
function printArrayItems(path, options, printPath, print) {
const printedElements = [];
let separatorParts = [];
path.each(childPath => {
printedElements.push(concat$d(separatorParts));
printedElements.push(group$b(print(childPath)));
separatorParts = [",", line$9];
if (childPath.getValue() && isNextLineEmpty$4(options.originalText, childPath.getValue(), options.locEnd)) {
separatorParts.push(softline$6);
}
}, printPath);
return concat$d(printedElements);
}
function printReturnAndThrowArgument(path, options, print) {
const node = path.getValue();
const semi = options.semi ? ";" : "";
const parts = [];
if (node.argument) {
if (returnArgumentHasLeadingComment$1(options, node.argument)) {
parts.push(concat$d([" (", indent$7(concat$d([hardline$9, path.call(print, "argument")])), hardline$9, ")"]));
} else if (node.argument.type === "LogicalExpression" || node.argument.type === "BinaryExpression" || node.argument.type === "SequenceExpression") {
parts.push(group$b(concat$d([ifBreak$6(" (", " "), indent$7(concat$d([softline$6, path.call(print, "argument")])), softline$6, ifBreak$6(")")])));
} else {
parts.push(" ", path.call(print, "argument"));
}
}
const lastComment = Array.isArray(node.comments) && node.comments[node.comments.length - 1];
const isLastCommentLine = lastComment && (lastComment.type === "CommentLine" || lastComment.type === "Line");
if (isLastCommentLine) {
parts.push(semi);
}
if (hasDanglingComments$1(node)) {
parts.push(" ", comments.printDanglingComments(path, options,
/* sameIndent */
true));
}
if (!isLastCommentLine) {
parts.push(semi);
}
return concat$d(parts);
}
function willPrintOwnComments(path
/*, options */
) {
const node = path.getValue();
const parent = path.getParentNode();
return (node && (isJSXNode$1(node) || hasFlowShorthandAnnotationComment$2(node) || parent && (parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && (hasFlowAnnotationComment$1(node.leadingComments) || hasFlowAnnotationComment$1(node.trailingComments))) || parent && (parent.type === "JSXSpreadAttribute" || parent.type === "JSXSpreadChild" || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType" || (parent.type === "ClassDeclaration" || parent.type === "ClassExpression") && parent.superClass === node)) && (!hasIgnoreComment$4(path) || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType");
}
function canAttachComment$1(node) {
return node.type && node.type !== "CommentBlock" && node.type !== "CommentLine" && node.type !== "Line" && node.type !== "Block" && node.type !== "EmptyStatement" && node.type !== "TemplateElement" && node.type !== "Import";
}
function printComment$2(commentPath, options) {
const comment = commentPath.getValue();
switch (comment.type) {
case "CommentBlock":
case "Block":
{
if (isIndentableBlockComment(comment)) {
const printed = printIndentableBlockComment(comment); // We need to prevent an edge case of a previous trailing comment
// printed as a `lineSuffix` which causes the comments to be
// interleaved. See https://github.com/prettier/prettier/issues/4412
if (comment.trailing && !hasNewline$5(options.originalText, options.locStart(comment), {
backwards: true
})) {
return concat$d([hardline$9, printed]);
}
return printed;
}
const commentEnd = options.locEnd(comment);
const isInsideFlowComment = options.originalText.slice(commentEnd - 3, commentEnd) === "*-/";
return "/*" + comment.value + (isInsideFlowComment ? "*-/" : "*/");
}
case "CommentLine":
case "Line":
// Print shebangs with the proper comment characters
if (options.originalText.slice(options.locStart(comment)).startsWith("#!")) {
return "#!" + comment.value.trimEnd();
}
return "//" + comment.value.trimEnd();
default:
throw new Error("Not a comment: " + JSON.stringify(comment));
}
}
function isIndentableBlockComment(comment) {
// If the comment has multiple lines and every line starts with a star
// we can fix the indentation of each line. The stars in the `/*` and
// `*/` delimiters are not included in the comment value, so add them
// back first.
const lines = "*".concat(comment.value, "*").split("\n");
return lines.length > 1 && lines.every(line => line.trim()[0] === "*");
}
function printIndentableBlockComment(comment) {
const lines = comment.value.split("\n");
return concat$d(["/*", join$9(hardline$9, lines.map((line, index) => index === 0 ? line.trimEnd() : " " + (index < lines.length - 1 ? line.trim() : line.trimStart()))), "*/"]);
}
var printerEstree = {
preprocess: preprocess_1$1,
print: genericPrint$3,
embed: embed_1$1,
insertPragma: insertPragma$7,
massageAstNode: clean_1$1,
hasPrettierIgnore: hasPrettierIgnore$5,
willPrintOwnComments,
canAttachComment: canAttachComment$1,
printComment: printComment$2,
isBlockComment: comments$1.isBlockComment,
handleComments: {
ownLine: comments$1.handleOwnLineComment,
endOfLine: comments$1.handleEndOfLineComment,
remaining: comments$1.handleRemainingComment
},
getGapRegex: comments$1.getGapRegex,
getCommentChildNodes: comments$1.getCommentChildNodes
};
const {
concat: concat$e,
hardline: hardline$a,
indent: indent$8,
join: join$a
} = document.builders;
function genericPrint$4(path, options, print) {
const node = path.getValue();
switch (node.type) {
case "JsonRoot":
return concat$e([path.call(print, "node"), hardline$a]);
case "ArrayExpression":
return node.elements.length === 0 ? "[]" : concat$e(["[", indent$8(concat$e([hardline$a, join$a(concat$e([",", hardline$a]), path.map(print, "elements"))])), hardline$a, "]"]);
case "ObjectExpression":
return node.properties.length === 0 ? "{}" : concat$e(["{", indent$8(concat$e([hardline$a, join$a(concat$e([",", hardline$a]), path.map(print, "properties"))])), hardline$a, "}"]);
case "ObjectProperty":
return concat$e([path.call(print, "key"), ": ", path.call(print, "value")]);
case "UnaryExpression":
return concat$e([node.operator === "+" ? "" : node.operator, path.call(print, "argument")]);
case "NullLiteral":
return "null";
case "BooleanLiteral":
return node.value ? "true" : "false";
case "StringLiteral":
case "NumericLiteral":
return JSON.stringify(node.value);
case "Identifier":
return JSON.stringify(node.name);
default:
/* istanbul ignore next */
throw new Error("unknown type: " + JSON.stringify(node.type));
}
}
function clean$5(node, newNode
/*, parent*/
) {
delete newNode.start;
delete newNode.end;
delete newNode.extra;
delete newNode.loc;
delete newNode.comments;
delete newNode.errors;
if (node.type === "Identifier") {
return {
type: "StringLiteral",
value: node.name
};
}
if (node.type === "UnaryExpression" && node.operator === "+") {
return newNode.argument;
}
}
var printerEstreeJson = {
preprocess: preprocess_1$1,
print: genericPrint$4,
massageAstNode: clean$5
};
const CATEGORY_JAVASCRIPT = "JavaScript"; // format based on https://github.com/prettier/prettier/blob/master/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`"
}]
},
bracketSpacing: commonOptions.bracketSpacing,
jsxBracketSameLine: {
since: "0.17.0",
category: CATEGORY_JAVASCRIPT,
type: "boolean",
default: false,
description: "Put > on the last line instead of at a new line."
},
semi: {
since: "1.0.0",
category: CATEGORY_JAVASCRIPT,
type: "boolean",
default: true,
description: "Print semicolons.",
oppositeDescription: "Do not print semicolons, except at the beginning of lines which may need them."
},
singleQuote: commonOptions.singleQuote,
jsxSingleQuote: {
since: "1.15.0",
category: CATEGORY_JAVASCRIPT,
type: "boolean",
default: false,
description: "Use single quotes in JSX."
},
quoteProps: {
since: "1.17.0",
category: CATEGORY_JAVASCRIPT,
type: "choice",
default: "as-needed",
description: "Change when properties in objects are quoted.",
choices: [{
value: "as-needed",
description: "Only add quotes around object properties where required."
}, {
value: "consistent",
description: "If at least one property in an object requires quotes, quote all properties."
}, {
value: "preserve",
description: "Respect the input use of quotes in object properties."
}]
},
trailingComma: {
since: "0.0.0",
category: CATEGORY_JAVASCRIPT,
type: "choice",
default: [{
since: "0.0.0",
value: false
}, {
since: "0.19.0",
value: "none"
}, {
since: "2.0.0",
value: "es5"
}],
description: "Print trailing commas wherever possible when multi-line.",
choices: [{
value: "es5",
description: "Trailing commas where valid in ES5 (objects, arrays, etc.)"
}, {
value: "none",
description: "No trailing commas."
}, {
value: "all",
description: "Trailing commas wherever possible (including function arguments)."
}]
}
};
var name$9 = "JavaScript";
var type$8 = "programming";
var tmScope$8 = "source.js";
var aceMode$8 = "javascript";
var codemirrorMode$4 = "javascript";
var codemirrorMimeType$4 = "text/javascript";
var color$3 = "#f1e05a";
var aliases$2 = [
"js",
"node"
];
var extensions$8 = [
".js",
"._js",
".bones",
".cjs",
".es",
".es6",
".frag",
".gs",
".jake",
".jsb",
".jscad",
".jsfl",
".jsm",
".jss",
".mjs",
".njs",
".pac",
".sjs",
".ssjs",
".xsjs",
".xsjslib"
];
var filenames = [
"Jakefile"
];
var interpreters = [
"chakra",
"d8",
"gjs",
"js",
"node",
"qjs",
"rhino",
"v8",
"v8-shell"
];
var languageId$8 = 183;
var JavaScript = {
name: name$9,
type: type$8,
tmScope: tmScope$8,
aceMode: aceMode$8,
codemirrorMode: codemirrorMode$4,
codemirrorMimeType: codemirrorMimeType$4,
color: color$3,
aliases: aliases$2,
extensions: extensions$8,
filenames: filenames,
interpreters: interpreters,
languageId: languageId$8
};
var JavaScript$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
name: name$9,
type: type$8,
tmScope: tmScope$8,
aceMode: aceMode$8,
codemirrorMode: codemirrorMode$4,
codemirrorMimeType: codemirrorMimeType$4,
color: color$3,
aliases: aliases$2,
extensions: extensions$8,
filenames: filenames,
interpreters: interpreters,
languageId: languageId$8,
'default': JavaScript
});
var name$a = "JSX";
var type$9 = "programming";
var group$c = "JavaScript";
var extensions$9 = [
".jsx"
];
var tmScope$9 = "source.js.jsx";
var aceMode$9 = "javascript";
var codemirrorMode$5 = "jsx";
var codemirrorMimeType$5 = "text/jsx";
var languageId$9 = 178;
var JSX = {
name: name$a,
type: type$9,
group: group$c,
extensions: extensions$9,
tmScope: tmScope$9,
aceMode: aceMode$9,
codemirrorMode: codemirrorMode$5,
codemirrorMimeType: codemirrorMimeType$5,
languageId: languageId$9
};
var JSX$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
name: name$a,
type: type$9,
group: group$c,
extensions: extensions$9,
tmScope: tmScope$9,
aceMode: aceMode$9,
codemirrorMode: codemirrorMode$5,
codemirrorMimeType: codemirrorMimeType$5,
languageId: languageId$9,
'default': JSX
});
var name$b = "TypeScript";
var type$a = "programming";
var color$4 = "#2b7489";
var aliases$3 = [
"ts"
];
var interpreters$1 = [
"deno",
"ts-node"
];
var extensions$a = [
".ts"
];
var tmScope$a = "source.ts";
var aceMode$a = "typescript";
var codemirrorMode$6 = "javascript";
var codemirrorMimeType$6 = "application/typescript";
var languageId$a = 378;
var TypeScript = {
name: name$b,
type: type$a,
color: color$4,
aliases: aliases$3,
interpreters: interpreters$1,
extensions: extensions$a,
tmScope: tmScope$a,
aceMode: aceMode$a,
codemirrorMode: codemirrorMode$6,
codemirrorMimeType: codemirrorMimeType$6,
languageId: languageId$a
};
var TypeScript$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
name: name$b,
type: type$a,
color: color$4,
aliases: aliases$3,
interpreters: interpreters$1,
extensions: extensions$a,
tmScope: tmScope$a,
aceMode: aceMode$a,
codemirrorMode: codemirrorMode$6,
codemirrorMimeType: codemirrorMimeType$6,
languageId: languageId$a,
'default': TypeScript
});
var name$c = "TSX";
var type$b = "programming";
var group$d = "TypeScript";
var extensions$b = [
".tsx"
];
var tmScope$b = "source.tsx";
var aceMode$b = "javascript";
var codemirrorMode$7 = "jsx";
var codemirrorMimeType$7 = "text/jsx";
var languageId$b = 94901924;
var TSX = {
name: name$c,
type: type$b,
group: group$d,
extensions: extensions$b,
tmScope: tmScope$b,
aceMode: aceMode$b,
codemirrorMode: codemirrorMode$7,
codemirrorMimeType: codemirrorMimeType$7,
languageId: languageId$b
};
var TSX$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
name: name$c,
type: type$b,
group: group$d,
extensions: extensions$b,
tmScope: tmScope$b,
aceMode: aceMode$b,
codemirrorMode: codemirrorMode$7,
codemirrorMimeType: codemirrorMimeType$7,
languageId: languageId$b,
'default': TSX
});
var name$d = "JSON";
var type$c = "data";
var tmScope$c = "source.json";
var aceMode$c = "json";
var codemirrorMode$8 = "javascript";
var codemirrorMimeType$8 = "application/json";
var searchable = false;
var extensions$c = [
".json",
".avsc",
".geojson",
".gltf",
".har",
".ice",
".JSON-tmLanguage",
".jsonl",
".mcmeta",
".tfstate",
".tfstate.backup",
".topojson",
".webapp",
".webmanifest",
".yy",
".yyp"
];
var filenames$1 = [
".arcconfig",
".htmlhintrc",
".tern-config",
".tern-project",
".watchmanconfig",
"composer.lock",
"mcmod.info"
];
var languageId$c = 174;
var _JSON = {
name: name$d,
type: type$c,
tmScope: tmScope$c,
aceMode: aceMode$c,
codemirrorMode: codemirrorMode$8,
codemirrorMimeType: codemirrorMimeType$8,
searchable: searchable,
extensions: extensions$c,
filenames: filenames$1,
languageId: languageId$c
};
var _JSON$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
name: name$d,
type: type$c,
tmScope: tmScope$c,
aceMode: aceMode$c,
codemirrorMode: codemirrorMode$8,
codemirrorMimeType: codemirrorMimeType$8,
searchable: searchable,
extensions: extensions$c,
filenames: filenames$1,
languageId: languageId$c,
'default': _JSON
});
var name$e = "JSON with Comments";
var type$d = "data";
var group$e = "JSON";
var tmScope$d = "source.js";
var aceMode$d = "javascript";
var codemirrorMode$9 = "javascript";
var codemirrorMimeType$9 = "text/javascript";
var aliases$4 = [
"jsonc"
];
var extensions$d = [
".jsonc",
".sublime-build",
".sublime-commands",
".sublime-completions",
".sublime-keymap",
".sublime-macro",
".sublime-menu",
".sublime-mousemap",
".sublime-project",
".sublime-settings",
".sublime-theme",
".sublime-workspace",
".sublime_metrics",
".sublime_session"
];
var filenames$2 = [
".babelrc",
".eslintrc.json",
".jscsrc",
".jshintrc",
".jslintrc",
"jsconfig.json",
"language-configuration.json",
"tsconfig.json"
];
var languageId$d = 423;
var JSON_with_Comments = {
name: name$e,
type: type$d,
group: group$e,
tmScope: tmScope$d,
aceMode: aceMode$d,
codemirrorMode: codemirrorMode$9,
codemirrorMimeType: codemirrorMimeType$9,
aliases: aliases$4,
extensions: extensions$d,
filenames: filenames$2,
languageId: languageId$d
};
var JSON_with_Comments$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
name: name$e,
type: type$d,
group: group$e,
tmScope: tmScope$d,
aceMode: aceMode$d,
codemirrorMode: codemirrorMode$9,
codemirrorMimeType: codemirrorMimeType$9,
aliases: aliases$4,
extensions: extensions$d,
filenames: filenames$2,
languageId: languageId$d,
'default': JSON_with_Comments
});
var name$f = "JSON5";
var type$e = "data";
var extensions$e = [
".json5"
];
var tmScope$e = "source.js";
var aceMode$e = "javascript";
var codemirrorMode$a = "javascript";
var codemirrorMimeType$a = "application/json";
var languageId$e = 175;
var JSON5 = {
name: name$f,
type: type$e,
extensions: extensions$e,
tmScope: tmScope$e,
aceMode: aceMode$e,
codemirrorMode: codemirrorMode$a,
codemirrorMimeType: codemirrorMimeType$a,
languageId: languageId$e
};
var JSON5$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
name: name$f,
type: type$e,
extensions: extensions$e,
tmScope: tmScope$e,
aceMode: aceMode$e,
codemirrorMode: codemirrorMode$a,
codemirrorMimeType: codemirrorMimeType$a,
languageId: languageId$e,
'default': JSON5
});
var require$$0$6 = getCjsExportFromNamespace(JavaScript$1);
var require$$1$2 = getCjsExportFromNamespace(JSX$1);
var require$$2$1 = getCjsExportFromNamespace(TypeScript$1);
var require$$3$1 = getCjsExportFromNamespace(TSX$1);
var require$$4 = getCjsExportFromNamespace(_JSON$1);
var require$$5 = getCjsExportFromNamespace(JSON_with_Comments$1);
var require$$6 = getCjsExportFromNamespace(JSON5$1);
const languages$4 = [createLanguage(require$$0$6, data => ({
since: "0.0.0",
parsers: ["babel", "flow"],
vscodeLanguageIds: ["javascript", "mongo"],
interpreters: data.interpreters.concat(["nodejs"])
})), createLanguage(require$$0$6, () => ({
name: "Flow",
since: "0.0.0",
parsers: ["babel", "flow"],
vscodeLanguageIds: ["javascript"],
aliases: [],
filenames: [],
extensions: [".js.flow"]
})), createLanguage(require$$1$2, () => ({
since: "0.0.0",
parsers: ["babel", "flow"],
vscodeLanguageIds: ["javascriptreact"]
})), createLanguage(require$$2$1, () => ({
since: "1.4.0",
parsers: ["typescript", "babel-ts"],
vscodeLanguageIds: ["typescript"]
})), createLanguage(require$$3$1, () => ({
since: "1.4.0",
parsers: ["typescript", "babel-ts"],
vscodeLanguageIds: ["typescriptreact"]
})), createLanguage(require$$4, () => ({
name: "JSON.stringify",
since: "1.13.0",
parsers: ["json-stringify"],
vscodeLanguageIds: ["json"],
extensions: [],
// .json file defaults to json instead of json-stringify
filenames: ["package.json", "package-lock.json", "composer.json"]
})), createLanguage(require$$4, data => ({
since: "1.5.0",
parsers: ["json"],
vscodeLanguageIds: ["json"],
filenames: data.filenames.concat([".prettierrc"])
})), createLanguage(require$$5, data => ({
since: "1.5.0",
parsers: ["json"],
vscodeLanguageIds: ["jsonc"],
filenames: data.filenames.concat([".eslintrc"])
})), createLanguage(require$$6, () => ({
since: "1.13.0",
parsers: ["json5"],
vscodeLanguageIds: ["json5"]
}))];
const printers$4 = {
estree: printerEstree,
"estree-json": printerEstreeJson
};
var languageJs = {
languages: languages$4,
options: options$5,
printers: printers$4
};
var json$1 = {
"cjkPattern": "[\\u02ea-\\u02eb\\u1100-\\u11ff\\u2e80-\\u2e99\\u2e9b-\\u2ef3\\u2f00-\\u2fd5\\u3000-\\u303f\\u3041-\\u3096\\u3099-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u3190-\\u3191\\u3196-\\u31ba\\u31c0-\\u31e3\\u31f0-\\u321e\\u322a-\\u3247\\u3260-\\u327e\\u328a-\\u32b0\\u32c0-\\u32cb\\u32d0-\\u3370\\u337b-\\u337f\\u33e0-\\u33fe\\u3400-\\u4db5\\u4e00-\\u9fef\\ua960-\\ua97c\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufe10-\\ufe1f\\ufe30-\\ufe6f\\uff00-\\uffef]|[\\ud840-\\ud868\\ud86a-\\ud86c\\ud86f-\\ud872\\ud874-\\ud879][\\udc00-\\udfff]|\\ud82c[\\udc00-\\udd1e\\udd50-\\udd52\\udd64-\\udd67]|\\ud83c[\\ude00\\ude50-\\ude51]|\\ud869[\\udc00-\\uded6\\udf00-\\udfff]|\\ud86d[\\udc00-\\udf34\\udf40-\\udfff]|\\ud86e[\\udc00-\\udc1d\\udc20-\\udfff]|\\ud873[\\udc00-\\udea1\\udeb0-\\udfff]|\\ud87a[\\udc00-\\udfe0]|\\ud87e[\\udc00-\\ude1d]",
"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 {
cjkPattern,
kPattern,
punctuationPattern
} = json$1;
const {
getLast: getLast$4
} = util$1;
const INLINE_NODE_TYPES = ["liquidNode", "inlineCode", "emphasis", "strong", "delete", "link", "linkReference", "image", "imageReference", "footnote", "footnoteReference", "sentence", "whitespace", "word", "break", "inlineMath"];
const INLINE_NODE_WRAPPER_TYPES = INLINE_NODE_TYPES.concat(["tableCell", "paragraph", "heading"]);
const kRegex = new RegExp(kPattern);
const punctuationRegex = new RegExp(punctuationPattern);
/**
* split text into whitespaces and words
* @param {string} text
* @return {Array<{ type: "whitespace", value: " " | "\n" | "" } | { type: "word", value: string }>}
*/
function splitText(text, options) {
const KIND_NON_CJK = "non-cjk";
const KIND_CJ_LETTER = "cj-letter";
const KIND_K_LETTER = "k-letter";
const KIND_CJK_PUNCTUATION = "cjk-punctuation";
const nodes = [];
(options.proseWrap === "preserve" ? text : text.replace(new RegExp("(".concat(cjkPattern, ")\n(").concat(cjkPattern, ")"), "g"), "$1$2")).split(/([ \t\n]+)/).forEach((token, index, tokens) => {
// whitespace
if (index % 2 === 1) {
nodes.push({
type: "whitespace",
value: /\n/.test(token) ? "\n" : " "
});
return;
} // word separated by whitespace
if ((index === 0 || index === tokens.length - 1) && token === "") {
return;
}
token.split(new RegExp("(".concat(cjkPattern, ")"))).forEach((innerToken, innerIndex, innerTokens) => {
if ((innerIndex === 0 || innerIndex === innerTokens.length - 1) && innerToken === "") {
return;
} // non-CJK word
if (innerIndex % 2 === 0) {
if (innerToken !== "") {
appendNode({
type: "word",
value: innerToken,
kind: KIND_NON_CJK,
hasLeadingPunctuation: punctuationRegex.test(innerToken[0]),
hasTrailingPunctuation: punctuationRegex.test(getLast$4(innerToken))
});
}
return;
} // CJK character
appendNode(punctuationRegex.test(innerToken) ? {
type: "word",
value: innerToken,
kind: KIND_CJK_PUNCTUATION,
hasLeadingPunctuation: true,
hasTrailingPunctuation: true
} : {
type: "word",
value: innerToken,
kind: kRegex.test(innerToken) ? KIND_K_LETTER : KIND_CJ_LETTER,
hasLeadingPunctuation: false,
hasTrailingPunctuation: false
});
});
});
return nodes;
function appendNode(node) {
const lastNode = getLast$4(nodes);
if (lastNode && lastNode.type === "word") {
if (lastNode.kind === KIND_NON_CJK && node.kind === KIND_CJ_LETTER && !lastNode.hasTrailingPunctuation || lastNode.kind === KIND_CJ_LETTER && node.kind === KIND_NON_CJK && !node.hasLeadingPunctuation) {
nodes.push({
type: "whitespace",
value: " "
});
} else if (!isBetween(KIND_NON_CJK, KIND_CJK_PUNCTUATION) && // disallow leading/trailing full-width whitespace
![lastNode.value, node.value].some(value => /\u3000/.test(value))) {
nodes.push({
type: "whitespace",
value: ""
});
}
}
nodes.push(node);
function isBetween(kind1, kind2) {
return lastNode.kind === kind1 && node.kind === kind2 || lastNode.kind === kind2 && node.kind === kind1;
}
}
}
function getOrderedListItemInfo(orderListItem, originalText) {
const [, numberText, marker, leadingSpaces] = originalText.slice(orderListItem.position.start.offset, orderListItem.position.end.offset).match(/^\s*(\d+)(\.|\))(\s*)/);
return {
numberText,
marker,
leadingSpaces
};
}
function hasGitDiffFriendlyOrderedList(node, options) {
if (!node.ordered) {
return false;
}
if (node.children.length < 2) {
return false;
}
const firstNumber = Number(getOrderedListItemInfo(node.children[0], options.originalText).numberText);
const secondNumber = Number(getOrderedListItemInfo(node.children[1], options.originalText).numberText);
if (firstNumber === 0 && node.children.length > 2) {
const thirdNumber = Number(getOrderedListItemInfo(node.children[2], options.originalText).numberText);
return secondNumber === 1 && thirdNumber === 1;
}
return secondNumber === 1;
} // workaround for https://github.com/remarkjs/remark/issues/351
// leading and trailing newlines are stripped by remark
function getFencedCodeBlockValue(node, originalText) {
const text = originalText.slice(node.position.start.offset, node.position.end.offset);
const leadingSpaceCount = text.match(/^\s*/)[0].length;
const replaceRegex = new RegExp("^\\s{0,".concat(leadingSpaceCount, "}"));
const lineContents = text.split("\n");
const markerStyle = text[leadingSpaceCount]; // ` or ~
const marker = text.slice(leadingSpaceCount).match(new RegExp("^[".concat(markerStyle, "]+")))[0]; // https://spec.commonmark.org/0.28/#example-104: Closing fences may be indented by 0-3 spaces
// https://spec.commonmark.org/0.28/#example-93: The closing code fence must be at least as long as the opening fence
const hasEndMarker = new RegExp("^\\s{0,3}".concat(marker)).test(lineContents[lineContents.length - 1].slice(getIndent(lineContents.length - 1)));
return lineContents.slice(1, hasEndMarker ? -1 : undefined).map((x, i) => x.slice(getIndent(i + 1)).replace(replaceRegex, "")).join("\n");
function getIndent(lineIndex) {
return node.position.indent[lineIndex - 1] - 1;
}
}
function mapAst(ast, handler) {
return function preorder(node, index, parentStack) {
parentStack = parentStack || [];
const newNode = Object.assign({}, handler(node, index, parentStack));
if (newNode.children) {
newNode.children = newNode.children.map((child, index) => {
return preorder(child, index, [newNode].concat(parentStack));
});
}
return newNode;
}(ast, null, null);
}
var utils$6 = {
mapAst,
splitText,
punctuationPattern,
getFencedCodeBlockValue,
getOrderedListItemInfo,
hasGitDiffFriendlyOrderedList,
INLINE_NODE_TYPES,
INLINE_NODE_WRAPPER_TYPES
};
const {
builders: {
hardline: hardline$b,
literalline: literalline$5,
concat: concat$f,
markAsRoot: markAsRoot$3
},
utils: {
mapDoc: mapDoc$5
}
} = document;
const {
getFencedCodeBlockValue: getFencedCodeBlockValue$1
} = utils$6;
function embed$4(path, print, textToDoc, options) {
const node = path.getValue();
if (node.type === "code" && node.lang !== null) {
// only look for the first string so as to support [markdown-preview-enhanced](https://shd101wyy.github.io/markdown-preview-enhanced/#/code-chunk)
const langMatch = node.lang.match(/^[A-Za-z0-9_-]+/);
const lang = langMatch ? langMatch[0] : "";
const parser = getParserName(lang);
if (parser) {
const styleUnit = options.__inJsTemplate ? "~" : "`";
const style = styleUnit.repeat(Math.max(3, util$1.getMaxContinuousCount(node.value, styleUnit) + 1));
const doc = textToDoc(getFencedCodeBlockValue$1(node, options.originalText), {
parser
});
return markAsRoot$3(concat$f([style, node.lang, hardline$b, replaceNewlinesWithLiterallines(doc), style]));
}
}
if (node.type === "yaml") {
return markAsRoot$3(concat$f(["---", hardline$b, node.value && node.value.trim() ? replaceNewlinesWithLiterallines(textToDoc(node.value, {
parser: "yaml"
})) : "", "---"]));
} // MDX
switch (node.type) {
case "importExport":
return textToDoc(node.value, {
parser: "babel"
});
case "jsx":
return textToDoc("<$>".concat(node.value, "$>"), {
parser: "__js_expression",
rootMarker: "mdx"
});
}
return null;
function getParserName(lang) {
const supportInfo = support.getSupportInfo({
plugins: options.plugins
});
const language = supportInfo.languages.find(language => language.name.toLowerCase() === lang || language.aliases && language.aliases.includes(lang) || language.extensions && language.extensions.find(ext => ext === ".".concat(lang)));
if (language) {
return language.parsers[0];
}
return null;
}
function replaceNewlinesWithLiterallines(doc) {
return mapDoc$5(doc, currentDoc => typeof currentDoc === "string" && currentDoc.includes("\n") ? concat$f(currentDoc.split(/(\n)/g).map((v, i) => i % 2 === 0 ? v : literalline$5)) : currentDoc);
}
}
var embed_1$2 = embed$4;
const pragmas = ["format", "prettier"];
function startWithPragma(text) {
const pragma = "@(".concat(pragmas.join("|"), ")");
const regex = new RegExp([""), "")].join("|"), "m");
const matched = text.match(regex);
return matched && matched.index === 0;
}
var pragma$4 = {
startWithPragma,
hasPragma: text => startWithPragma(frontMatter(text).content.trimStart()),
insertPragma: text => {
const extracted = frontMatter(text);
const pragma = "");
return extracted.frontMatter ? "".concat(extracted.frontMatter.raw, "\n\n").concat(pragma, "\n\n").concat(extracted.content) : "".concat(pragma, "\n\n").concat(extracted.content);
}
};
const {
getOrderedListItemInfo: getOrderedListItemInfo$1,
mapAst: mapAst$1,
splitText: splitText$1
} = utils$6; // 0x0 ~ 0x10ffff
// eslint-disable-next-line no-control-regex
const isSingleCharRegex = /^([\u0000-\uffff]|[\ud800-\udbff][\udc00-\udfff])$/;
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$1(ast, node => {
if (node.type !== "import" && node.type !== "export") {
return node;
}
return Object.assign({}, node, {
type: "importExport"
});
});
}
function transformInlineCode(ast) {
return mapAst$1(ast, node => {
if (node.type !== "inlineCode") {
return node;
}
return Object.assign({}, node, {
value: node.value.replace(/\s+/g, " ")
});
});
}
function restoreUnescapedCharacter(ast, options) {
return mapAst$1(ast, node => {
return node.type !== "text" ? node : Object.assign({}, node, {
value: node.value !== "*" && node.value !== "_" && node.value !== "$" && // handle these cases in printer
isSingleCharRegex.test(node.value) && node.position.end.offset - node.position.start.offset !== node.value.length ? options.originalText.slice(node.position.start.offset, node.position.end.offset) : node.value
});
});
}
function mergeContinuousImportExport(ast) {
return mergeChildren(ast, (prevNode, node) => prevNode.type === "importExport" && node.type === "importExport", (prevNode, node) => ({
type: "importExport",
value: prevNode.value + "\n\n" + node.value,
position: {
start: prevNode.position.start,
end: node.position.end
}
}));
}
function mergeChildren(ast, shouldMerge, mergeNode) {
return mapAst$1(ast, node => {
if (!node.children) {
return node;
}
const children = node.children.reduce((current, child) => {
const lastChild = current[current.length - 1];
if (lastChild && shouldMerge(lastChild, child)) {
current.splice(-1, 1, mergeNode(lastChild, child));
} else {
current.push(child);
}
return current;
}, []);
return Object.assign({}, node, {
children
});
});
}
function mergeContinuousTexts(ast) {
return mergeChildren(ast, (prevNode, node) => prevNode.type === "text" && node.type === "text", (prevNode, node) => ({
type: "text",
value: prevNode.value + node.value,
position: {
start: prevNode.position.start,
end: node.position.end
}
}));
}
function splitTextIntoSentences(ast, options) {
return mapAst$1(ast, (node, index, [parentNode]) => {
if (node.type !== "text") {
return node;
}
let {
value
} = node;
if (parentNode.type === "paragraph") {
if (index === 0) {
value = value.trimStart();
}
if (index === parentNode.children.length - 1) {
value = value.trimEnd();
}
}
return {
type: "sentence",
position: node.position,
children: splitText$1(value, options)
};
});
}
function transformIndentedCodeblockAndMarkItsParentList(ast, options) {
return mapAst$1(ast, (node, index, parentStack) => {
if (node.type === "code") {
// the first char may point to `\n`, e.g. `\n\t\tbar`, just ignore it
const isIndented = /^\n?( {4,}|\t)/.test(options.originalText.slice(node.position.start.offset, node.position.end.offset));
node.isIndented = isIndented;
if (isIndented) {
for (let i = 0; i < parentStack.length; i++) {
const parent = parentStack[i]; // no need to check checked items
if (parent.hasIndentedCodeblock) {
break;
}
if (parent.type === "list") {
parent.hasIndentedCodeblock = true;
}
}
}
}
return node;
});
}
function markAlignedList(ast, options) {
return mapAst$1(ast, (node, index, parentStack) => {
if (node.type === "list" && node.children.length !== 0) {
// if one of its parents is not aligned, it's not possible to be aligned in sub-lists
for (let i = 0; i < parentStack.length; i++) {
const parent = parentStack[i];
if (parent.type === "list" && !parent.isAligned) {
node.isAligned = false;
return node;
}
}
node.isAligned = isAligned(node);
}
return node;
});
function getListItemStart(listItem) {
return listItem.children.length === 0 ? -1 : listItem.children[0].position.start.column - 1;
}
function isAligned(list) {
if (!list.ordered) {
/**
* - 123
* - 123
*/
return true;
}
const [firstItem, secondItem] = list.children;
const firstInfo = getOrderedListItemInfo$1(firstItem, options.originalText);
if (firstInfo.leadingSpaces.length > 1) {
/**
* 1. 123
*
* 1. 123
* 1. 123
*/
return true;
}
const firstStart = getListItemStart(firstItem);
if (firstStart === -1) {
/**
* 1.
*
* 1.
* 1.
*/
return false;
}
if (list.children.length === 1) {
/**
* aligned:
*
* 11. 123
*
* not aligned:
*
* 1. 123
*/
return firstStart % options.tabWidth === 0;
}
const secondStart = getListItemStart(secondItem);
if (firstStart !== secondStart) {
/**
* 11. 123
* 1. 123
*
* 1. 123
* 11. 123
*/
return false;
}
if (firstStart % options.tabWidth === 0) {
/**
* 11. 123
* 12. 123
*/
return true;
}
/**
* aligned:
*
* 11. 123
* 1. 123
*
* not aligned:
*
* 1. 123
* 2. 123
*/
const secondInfo = getOrderedListItemInfo$1(secondItem, options.originalText);
return secondInfo.leadingSpaces.length > 1;
}
}
var preprocess_1$2 = preprocess$2;
const {
builders: {
breakParent: breakParent$4,
concat: concat$g,
join: join$b,
line: line$a,
literalline: literalline$6,
markAsRoot: markAsRoot$4,
hardline: hardline$c,
softline: softline$7,
ifBreak: ifBreak$7,
fill: fill$5,
align: align$2,
indent: indent$9,
group: group$f
},
utils: {
mapDoc: mapDoc$6
},
printer: {
printDocToString: printDocToString$3
}
} = document;
const {
getFencedCodeBlockValue: getFencedCodeBlockValue$2,
hasGitDiffFriendlyOrderedList: hasGitDiffFriendlyOrderedList$1,
splitText: splitText$2,
punctuationPattern: punctuationPattern$1,
INLINE_NODE_TYPES: INLINE_NODE_TYPES$1,
INLINE_NODE_WRAPPER_TYPES: INLINE_NODE_WRAPPER_TYPES$1
} = utils$6;
const {
replaceEndOfLineWith: replaceEndOfLineWith$2
} = util$1;
const TRAILING_HARDLINE_NODES = ["importExport"];
const SINGLE_LINE_NODE_TYPES = ["heading", "tableCell", "link"];
const SIBLING_NODE_TYPES = ["listItem", "definition", "footnoteDefinition"];
function genericPrint$5(path, options, print) {
const node = path.getValue();
if (shouldRemainTheSameContent(path)) {
return concat$g(splitText$2(options.originalText.slice(node.position.start.offset, node.position.end.offset), options).map(node => node.type === "word" ? node.value : node.value === "" ? "" : printLine(path, node.value, options)));
}
switch (node.type) {
case "root":
if (node.children.length === 0) {
return "";
}
return concat$g([normalizeDoc(printRoot(path, options, print)), !TRAILING_HARDLINE_NODES.includes(getLastDescendantNode(node).type) ? hardline$c : ""]);
case "paragraph":
return printChildren$2(path, options, print, {
postprocessor: fill$5
});
case "sentence":
return printChildren$2(path, options, print);
case "word":
return node.value.replace(/[*$]/g, "\\$&") // escape all `*` and `$` (math)
.replace(new RegExp(["(^|".concat(punctuationPattern$1, ")(_+)"), "(_+)(".concat(punctuationPattern$1, "|$)")].join("|"), "g"), (_, text1, underscore1, underscore2, text2) => (underscore1 ? "".concat(text1).concat(underscore1) : "".concat(underscore2).concat(text2)).replace(/_/g, "\\_"));
// escape all `_` except concating with non-punctuation, e.g. `1_2_3` is not considered emphasis
case "whitespace":
{
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}|[0-9]+[.)])$/.test(nextNode.value) ? "never" : options.proseWrap;
return printLine(path, node.value, {
proseWrap
});
}
case "emphasis":
{
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 && util$1.getLast(prevNode.children).type === "word" && !util$1.getLast(prevNode.children).hasTrailingPunctuation || nextNode && nextNode.type === "sentence" && nextNode.children.length > 0 && nextNode.children[0].type === "word" && !nextNode.children[0].hasLeadingPunctuation;
const style = hasPrevOrNextWord || getAncestorNode$2(path, "emphasis") ? "*" : "_";
return concat$g([style, printChildren$2(path, options, print), style]);
}
case "strong":
return concat$g(["**", printChildren$2(path, options, print), "**"]);
case "delete":
return concat$g(["~~", printChildren$2(path, options, print), "~~"]);
case "inlineCode":
{
const backtickCount = util$1.getMinNotPresentContinuousCount(node.value, "`");
const style = "`".repeat(backtickCount || 1);
const gap = backtickCount ? " " : "";
return concat$g([style, gap, node.value, gap, style]);
}
case "link":
switch (options.originalText[node.position.start.offset]) {
case "<":
{
const mailto = "mailto:";
const url = // is parsed as { url: "mailto:hello@example.com" }
node.url.startsWith(mailto) && options.originalText.slice(node.position.start.offset + 1, node.position.start.offset + 1 + mailto.length) !== mailto ? node.url.slice(mailto.length) : node.url;
return concat$g(["<", url, ">"]);
}
case "[":
return concat$g(["[", printChildren$2(path, options, print), "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]);
default:
return options.originalText.slice(node.position.start.offset, node.position.end.offset);
}
case "image":
return concat$g(["![", node.alt || "", "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]);
case "blockquote":
return concat$g(["> ", align$2("> ", printChildren$2(path, options, print))]);
case "heading":
return concat$g(["#".repeat(node.depth) + " ", printChildren$2(path, options, print)]);
case "code":
{
if (node.isIndented) {
// indented code block
const alignment = " ".repeat(4);
return align$2(alignment, concat$g([alignment, concat$g(replaceEndOfLineWith$2(node.value, hardline$c))]));
} // fenced code block
const styleUnit = options.__inJsTemplate ? "~" : "`";
const style = styleUnit.repeat(Math.max(3, util$1.getMaxContinuousCount(node.value, styleUnit) + 1));
return concat$g([style, node.lang || "", hardline$c, concat$g(replaceEndOfLineWith$2(getFencedCodeBlockValue$2(node, options.originalText), hardline$c)), hardline$c, style]);
}
case "yaml":
case "toml":
return options.originalText.slice(node.position.start.offset, node.position.end.offset);
case "html":
{
const parentNode = path.getParentNode();
const value = parentNode.type === "root" && util$1.getLast(parentNode.children) === node ? node.value.trimEnd() : node.value;
const isHtmlComment = /^$/.test(value);
return concat$g(replaceEndOfLineWith$2(value, isHtmlComment ? hardline$c : markAsRoot$4(literalline$6)));
}
case "list":
{
const nthSiblingIndex = getNthListSiblingIndex(node, path.getParentNode());
const isGitDiffFriendlyOrderedList = hasGitDiffFriendlyOrderedList$1(node, options);
return printChildren$2(path, options, print, {
processor: (childPath, index) => {
const prefix = getPrefix();
const childNode = childPath.getValue();
if (childNode.children.length === 2 && childNode.children[1].type === "html" && childNode.children[0].position.start.column !== childNode.children[1].position.start.column) {
return concat$g([prefix, printListItem(childPath, options, print, prefix)]);
}
return concat$g([prefix, align$2(" ".repeat(prefix.length), printListItem(childPath, options, print, prefix))]);
function getPrefix() {
const rawPrefix = node.ordered ? (index === 0 ? node.start : isGitDiffFriendlyOrderedList ? 1 : node.start + index) + (nthSiblingIndex % 2 === 0 ? ". " : ") ") : nthSiblingIndex % 2 === 0 ? "- " : "* ";
return node.isAligned ||
/* workaround for https://github.com/remarkjs/remark/issues/315 */
node.hasIndentedCodeblock ? alignListPrefix(rawPrefix, options) : rawPrefix;
}
}
});
}
case "thematicBreak":
{
const counter = getAncestorCounter$1(path, "list");
if (counter === -1) {
return "---";
}
const nthSiblingIndex = getNthListSiblingIndex(path.getParentNode(counter), path.getParentNode(counter + 1));
return nthSiblingIndex % 2 === 0 ? "***" : "---";
}
case "linkReference":
return concat$g(["[", printChildren$2(path, options, print), "]", node.referenceType === "full" ? concat$g(["[", node.identifier, "]"]) : node.referenceType === "collapsed" ? "[]" : ""]);
case "imageReference":
switch (node.referenceType) {
case "full":
return concat$g(["![", node.alt || "", "][", node.identifier, "]"]);
default:
return concat$g(["![", node.alt, "]", node.referenceType === "collapsed" ? "[]" : ""]);
}
case "definition":
{
const lineOrSpace = options.proseWrap === "always" ? line$a : " ";
return group$f(concat$g([concat$g(["[", node.identifier, "]:"]), indent$9(concat$g([lineOrSpace, printUrl(node.url), node.title === null ? "" : concat$g([lineOrSpace, printTitle(node.title, options, false)])]))]));
}
case "footnote":
return concat$g(["[^", printChildren$2(path, options, print), "]"]);
case "footnoteReference":
return concat$g(["[^", node.identifier, "]"]);
case "footnoteDefinition":
{
const nextNode = path.getParentNode().children[path.getName() + 1];
const shouldInlineFootnote = node.children.length === 1 && node.children[0].type === "paragraph" && (options.proseWrap === "never" || options.proseWrap === "preserve" && node.children[0].position.start.line === node.children[0].position.end.line);
return concat$g(["[^", node.identifier, "]: ", shouldInlineFootnote ? printChildren$2(path, options, print) : group$f(concat$g([align$2(" ".repeat(options.tabWidth), printChildren$2(path, options, print, {
processor: (childPath, index) => {
return index === 0 ? group$f(concat$g([softline$7, childPath.call(print)])) : childPath.call(print);
}
})), nextNode && nextNode.type === "footnoteDefinition" ? softline$7 : ""]))]);
}
case "table":
return printTable(path, options, print);
case "tableCell":
return printChildren$2(path, options, print);
case "break":
return /\s/.test(options.originalText[node.position.start.offset]) ? concat$g([" ", markAsRoot$4(literalline$6)]) : concat$g(["\\", hardline$c]);
case "liquidNode":
return concat$g(replaceEndOfLineWith$2(node.value, hardline$c));
// MDX
case "importExport":
case "jsx":
return node.value;
// fallback to the original text if multiparser failed
case "math":
return concat$g(["$$", hardline$c, node.value ? concat$g([concat$g(replaceEndOfLineWith$2(node.value, hardline$c)), hardline$c]) : "", "$$"]);
case "inlineMath":
{
// remark-math trims content but we don't want to remove whitespaces
// since it's very possible that it's recognized as math accidentally
return options.originalText.slice(options.locStart(node), options.locEnd(node));
}
case "tableRow": // handled in "table"
case "listItem": // handled in "list"
default:
throw new Error("Unknown markdown type ".concat(JSON.stringify(node.type)));
}
}
function printListItem(path, options, print, listPrefix) {
const node = path.getValue();
const prefix = node.checked === null ? "" : node.checked ? "[x] " : "[ ] ";
return concat$g([prefix, printChildren$2(path, options, print, {
processor: (childPath, index) => {
if (index === 0 && childPath.getValue().type !== "list") {
return align$2(" ".repeat(prefix.length), childPath.call(print));
}
const alignment = " ".repeat(clamp(options.tabWidth - listPrefix.length, 0, 3) // 4+ will cause indented code block
);
return concat$g([alignment, align$2(alignment, childPath.call(print))]);
}
})]);
}
function alignListPrefix(prefix, options) {
const additionalSpaces = getAdditionalSpaces();
return prefix + " ".repeat(additionalSpaces >= 4 ? 0 : additionalSpaces // 4+ will cause indented code block
);
function getAdditionalSpaces() {
const restSpaces = prefix.length % options.tabWidth;
return restSpaces === 0 ? 0 : options.tabWidth - restSpaces;
}
}
function getNthListSiblingIndex(node, parentNode) {
return getNthSiblingIndex(node, parentNode, siblingNode => siblingNode.ordered === node.ordered);
}
function getNthSiblingIndex(node, parentNode, condition) {
condition = condition || (() => true);
let index = -1;
for (const childNode of parentNode.children) {
if (childNode.type === node.type && condition(childNode)) {
index++;
} else {
index = -1;
}
if (childNode === node) {
return index;
}
}
}
function getAncestorCounter$1(path, typeOrTypes) {
const types = [].concat(typeOrTypes);
let counter = -1;
let ancestorNode;
while (ancestorNode = path.getParentNode(++counter)) {
if (types.includes(ancestorNode.type)) {
return counter;
}
}
return -1;
}
function getAncestorNode$2(path, typeOrTypes) {
const counter = getAncestorCounter$1(path, typeOrTypes);
return counter === -1 ? null : path.getParentNode(counter);
}
function printLine(path, value, options) {
if (options.proseWrap === "preserve" && value === "\n") {
return hardline$c;
}
const isBreakable = options.proseWrap === "always" && !getAncestorNode$2(path, SINGLE_LINE_NODE_TYPES);
return value !== "" ? isBreakable ? line$a : " " : isBreakable ? softline$7 : "";
}
function printTable(path, options, print) {
const hardlineWithoutBreakParent = hardline$c.parts[0];
const node = path.getValue();
const contents = []; // { [rowIndex: number]: { [columnIndex: number]: string } }
path.map(rowPath => {
const rowContents = [];
rowPath.map(cellPath => {
rowContents.push(printDocToString$3(cellPath.call(print), options).formatted);
}, "children");
contents.push(rowContents);
}, "children"); // Get the width of each column
const columnMaxWidths = contents.reduce((currentWidths, rowContents) => currentWidths.map((width, columnIndex) => Math.max(width, util$1.getStringWidth(rowContents[columnIndex]))), contents[0].map(() => 3) // minimum width = 3 (---, :--, :-:, --:)
);
const alignedTable = join$b(hardlineWithoutBreakParent, [printRow(contents[0]), printSeparator(), join$b(hardlineWithoutBreakParent, contents.slice(1).map(rowContents => printRow(rowContents)))]);
if (options.proseWrap !== "never") {
return concat$g([breakParent$4, alignedTable]);
} // Only if the --prose-wrap never is set and it exceeds the print width.
const compactTable = join$b(hardlineWithoutBreakParent, [printRow(contents[0],
/* isCompact */
true), printSeparator(
/* isCompact */
true), join$b(hardlineWithoutBreakParent, contents.slice(1).map(rowContents => printRow(rowContents,
/* isCompact */
true)))]);
return concat$g([breakParent$4, group$f(ifBreak$7(compactTable, alignedTable))]);
function printSeparator(isCompact) {
return concat$g(["| ", join$b(" | ", columnMaxWidths.map((width, index) => {
const spaces = isCompact ? 3 : width;
switch (node.align[index]) {
case "left":
return ":" + "-".repeat(spaces - 1);
case "right":
return "-".repeat(spaces - 1) + ":";
case "center":
return ":" + "-".repeat(spaces - 2) + ":";
default:
return "-".repeat(spaces);
}
})), " |"]);
}
function printRow(rowContents, isCompact) {
return concat$g(["| ", join$b(" | ", isCompact ? rowContents : rowContents.map((rowContent, columnIndex) => {
switch (node.align[columnIndex]) {
case "right":
return alignRight(rowContent, columnMaxWidths[columnIndex]);
case "center":
return alignCenter(rowContent, columnMaxWidths[columnIndex]);
default:
return alignLeft(rowContent, columnMaxWidths[columnIndex]);
}
})), " |"]);
}
function alignLeft(text, width) {
const spaces = width - util$1.getStringWidth(text);
return concat$g([text, " ".repeat(spaces)]);
}
function alignRight(text, width) {
const spaces = width - util$1.getStringWidth(text);
return concat$g([" ".repeat(spaces), text]);
}
function alignCenter(text, width) {
const spaces = width - util$1.getStringWidth(text);
const left = Math.floor(spaces / 2);
const right = spaces - left;
return concat$g([" ".repeat(left), text, " ".repeat(right)]);
}
}
function printRoot(path, options, print) {
/** @typedef {{ index: number, offset: number }} IgnorePosition */
/** @type {Array<{start: IgnorePosition, end: IgnorePosition}>} */
const ignoreRanges = [];
/** @type {IgnorePosition | null} */
let ignoreStart = null;
const {
children
} = path.getValue();
children.forEach((childNode, index) => {
switch (isPrettierIgnore$1(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$2(path, options, print, {
processor: (childPath, index) => {
if (ignoreRanges.length !== 0) {
const ignoreRange = ignoreRanges[0];
if (index === ignoreRange.start.index) {
return concat$g([children[ignoreRange.start.index].value, options.originalText.slice(ignoreRange.start.offset, ignoreRange.end.offset), children[ignoreRange.end.index].value]);
}
if (ignoreRange.start.index < index && index < ignoreRange.end.index) {
return false;
}
if (index === ignoreRange.end.index) {
ignoreRanges.shift();
return false;
}
}
return childPath.call(print);
}
});
}
function printChildren$2(path, options, print, events) {
events = events || {};
const postprocessor = events.postprocessor || concat$g;
const processor = events.processor || (childPath => childPath.call(print));
const node = path.getValue();
const parts = [];
let lastChildNode;
path.map((childPath, index) => {
const childNode = childPath.getValue();
const result = processor(childPath, index);
if (result !== false) {
const data = {
parts,
prevNode: lastChildNode,
parentNode: node,
options
};
if (!shouldNotPrePrintHardline(childNode, data)) {
parts.push(hardline$c);
if (lastChildNode && TRAILING_HARDLINE_NODES.includes(lastChildNode.type)) {
if (shouldPrePrintTripleHardline(childNode, data)) {
parts.push(hardline$c);
}
} else {
if (shouldPrePrintDoubleHardline(childNode, data) || shouldPrePrintTripleHardline(childNode, data)) {
parts.push(hardline$c);
}
if (shouldPrePrintTripleHardline(childNode, data)) {
parts.push(hardline$c);
}
}
}
parts.push(result);
lastChildNode = childNode;
}
}, "children");
return postprocessor(parts);
}
function getLastDescendantNode(node) {
let current = node;
while (current.children && current.children.length !== 0) {
current = current.children[current.children.length - 1];
}
return current;
}
/** @return {false | 'next' | 'start' | 'end'} */
function isPrettierIgnore$1(node) {
if (node.type !== "html") {
return false;
}
const match = node.value.match(/^$/);
return match === null ? false : match[1] ? match[1] : "next";
}
function shouldNotPrePrintHardline(node, data) {
const isFirstNode = data.parts.length === 0;
const isInlineNode = INLINE_NODE_TYPES$1.includes(node.type);
const isInlineHTML = node.type === "html" && INLINE_NODE_WRAPPER_TYPES$1.includes(data.parentNode.type);
return isFirstNode || isInlineNode || isInlineHTML;
}
function shouldPrePrintDoubleHardline(node, data) {
const isSequence = (data.prevNode && data.prevNode.type) === node.type;
const isSiblingNode = isSequence && SIBLING_NODE_TYPES.includes(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$1(data.prevNode) === "next";
const isBlockHtmlWithoutBlankLineBetweenPrevHtml = node.type === "html" && data.prevNode && data.prevNode.type === "html" && data.prevNode.position.end.line + 1 === node.position.start.line;
const isHtmlDirectAfterListItem = node.type === "html" && data.parentNode.type === "listItem" && data.prevNode && data.prevNode.type === "paragraph" && data.prevNode.position.end.line + 1 === node.position.start.line;
return isPrevNodeLooseListItem || !(isSiblingNode || isInTightListItem || isPrevNodePrettierIgnore || isBlockHtmlWithoutBlankLineBetweenPrevHtml || isHtmlDirectAfterListItem);
}
function shouldPrePrintTripleHardline(node, data) {
const isPrevNodeList = data.prevNode && data.prevNode.type === "list";
const isIndentedCode = node.type === "code" && node.isIndented;
return isPrevNodeList && isIndentedCode;
}
function shouldRemainTheSameContent(path) {
const ancestorNode = getAncestorNode$2(path, ["linkReference", "imageReference"]);
return ancestorNode && (ancestorNode.type !== "linkReference" || ancestorNode.referenceType !== "full");
}
function normalizeDoc(doc) {
return mapDoc$6(doc, currentDoc => {
if (!currentDoc.parts) {
return currentDoc;
}
if (currentDoc.type === "concat" && currentDoc.parts.length === 1) {
return currentDoc.parts[0];
}
const parts = currentDoc.parts.reduce((parts, part) => {
if (part.type === "concat") {
parts.push(...part.parts);
} else if (part !== "") {
parts.push(part);
}
return parts;
}, []);
return Object.assign({}, currentDoc, {
parts: normalizeParts$2(parts)
});
});
}
function printUrl(url, dangerousCharOrChars) {
const dangerousChars = [" "].concat(dangerousCharOrChars || []);
return new RegExp(dangerousChars.map(x => "\\".concat(x)).join("|")).test(url) ? "<".concat(url, ">") : url;
}
function printTitle(title, options, printSpace) {
if (printSpace == null) {
printSpace = true;
}
if (!title) {
return "";
}
if (printSpace) {
return " " + printTitle(title, options, false);
}
if (title.includes('"') && title.includes("'") && !title.includes(")")) {
return "(".concat(title, ")"); // avoid escaped quotes
} // faster than using RegExps: https://jsperf.com/performance-of-match-vs-split
const singleCount = title.split("'").length - 1;
const doubleCount = title.split('"').length - 1;
const quote = singleCount > doubleCount ? '"' : doubleCount > singleCount ? "'" : options.singleQuote ? "'" : '"';
title = title.replace(new RegExp("(".concat(quote, ")"), "g"), "\\$1");
return "".concat(quote).concat(title).concat(quote);
}
function normalizeParts$2(parts) {
return parts.reduce((current, part) => {
const lastPart = util$1.getLast(current);
if (typeof lastPart === "string" && typeof part === "string") {
current.splice(-1, 1, lastPart + part);
} else {
current.push(part);
}
return current;
}, []);
}
function clamp(value, min, max) {
return value < min ? min : value > max ? max : value;
}
function clean$6(ast, newObj, parent) {
delete newObj.position;
delete newObj.raw; // front-matter
// for codeblock
if (ast.type === "code" || ast.type === "yaml" || ast.type === "import" || ast.type === "export" || ast.type === "jsx") {
delete newObj.value;
}
if (ast.type === "list") {
delete newObj.isAligned;
} // texts can be splitted or merged
if (ast.type === "text") {
return null;
}
if (ast.type === "inlineCode") {
newObj.value = ast.value.replace(/[ \t\n]+/g, " ");
} // for insert pragma
if (parent && parent.type === "root" && parent.children.length > 0 && (parent.children[0] === ast || (parent.children[0].type === "yaml" || parent.children[0].type === "toml") && parent.children[1] === ast) && ast.type === "html" && pragma$4.startWithPragma(ast.value)) {
return null;
}
}
function hasPrettierIgnore$6(path) {
const index = +path.getName();
if (index === 0) {
return false;
}
const prevNode = path.getParentNode().children[index - 1];
return isPrettierIgnore$1(prevNode) === "next";
}
var printerMarkdown = {
preprocess: preprocess_1$2,
print: genericPrint$5,
embed: embed_1$2,
massageAstNode: clean$6,
hasPrettierIgnore: hasPrettierIgnore$6,
insertPragma: pragma$4.insertPragma
};
var options$6 = {
proseWrap: commonOptions.proseWrap,
singleQuote: commonOptions.singleQuote
};
var name$g = "Markdown";
var type$f = "prose";
var aliases$5 = [
"pandoc"
];
var aceMode$f = "markdown";
var codemirrorMode$b = "gfm";
var codemirrorMimeType$b = "text/x-gfm";
var wrap = true;
var extensions$f = [
".md",
".markdown",
".mdown",
".mdwn",
".mdx",
".mkd",
".mkdn",
".mkdown",
".ronn",
".workbook"
];
var filenames$3 = [
"contents.lr"
];
var tmScope$f = "source.gfm";
var languageId$f = 222;
var Markdown = {
name: name$g,
type: type$f,
aliases: aliases$5,
aceMode: aceMode$f,
codemirrorMode: codemirrorMode$b,
codemirrorMimeType: codemirrorMimeType$b,
wrap: wrap,
extensions: extensions$f,
filenames: filenames$3,
tmScope: tmScope$f,
languageId: languageId$f
};
var Markdown$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
name: name$g,
type: type$f,
aliases: aliases$5,
aceMode: aceMode$f,
codemirrorMode: codemirrorMode$b,
codemirrorMimeType: codemirrorMimeType$b,
wrap: wrap,
extensions: extensions$f,
filenames: filenames$3,
tmScope: tmScope$f,
languageId: languageId$f,
'default': Markdown
});
var require$$0$7 = getCjsExportFromNamespace(Markdown$1);
const languages$5 = [createLanguage(require$$0$7, data => ({
since: "1.8.0",
parsers: ["markdown"],
vscodeLanguageIds: ["markdown"],
filenames: data.filenames.concat(["README"]),
extensions: data.extensions.filter(extension => extension !== ".mdx")
})), createLanguage(require$$0$7, () => ({
name: "MDX",
since: "1.15.0",
parsers: ["mdx"],
vscodeLanguageIds: ["mdx"],
filenames: [],
extensions: [".mdx"]
}))];
const printers$5 = {
mdast: printerMarkdown
};
var languageMarkdown = {
languages: languages$5,
options: options$6,
printers: printers$5
};
function isPragma(text) {
return /^\s*@(prettier|format)\s*$/.test(text);
}
function hasPragma$4(text) {
return /^\s*#[^\n\S]*@(prettier|format)\s*?(\n|$)/.test(text);
}
function insertPragma$8(text) {
return "# @format\n\n".concat(text);
}
var pragma$5 = {
isPragma,
hasPragma: hasPragma$4,
insertPragma: insertPragma$8
};
const {
getLast: getLast$5
} = util$1;
function getAncestorCount(path, filter) {
let counter = 0;
const pathStackLength = path.stack.length - 1;
for (let i = 0; i < pathStackLength; i++) {
const value = path.stack[i];
if (isNode(value) && filter(value)) {
counter++;
}
}
return counter;
}
/**
* @param {any} value
* @param {string[]=} types
*/
function isNode(value, types) {
return value && typeof value.type === "string" && (!types || types.includes(value.type));
}
function mapNode(node, callback, parent) {
return callback("children" in node ? Object.assign({}, node, {
children: node.children.map(childNode => mapNode(childNode, callback, node))
}) : node, parent);
}
function defineShortcut(x, key, getter) {
Object.defineProperty(x, key, {
get: getter,
enumerable: false
});
}
function isNextLineEmpty$5(node, text) {
let newlineCount = 0;
const textLength = text.length;
for (let i = node.position.end.offset - 1; i < textLength; i++) {
const char = text[i];
if (char === "\n") {
newlineCount++;
}
if (newlineCount === 1 && /\S/.test(char)) {
return false;
}
if (newlineCount === 2) {
return true;
}
}
return false;
}
function isLastDescendantNode(path) {
const node = path.getValue();
switch (node.type) {
case "tag":
case "anchor":
case "comment":
return false;
}
const pathStackLength = path.stack.length;
for (let i = 1; i < pathStackLength; i++) {
const item = path.stack[i];
const parentItem = path.stack[i - 1];
if (Array.isArray(parentItem) && typeof item === "number" && item !== parentItem.length - 1) {
return false;
}
}
return true;
}
function getLastDescendantNode$1(node) {
return "children" in node && node.children.length !== 0 ? getLastDescendantNode$1(getLast$5(node.children)) : node;
}
function isPrettierIgnore$2(comment) {
return comment.value.trim() === "prettier-ignore";
}
function hasPrettierIgnore$7(path) {
const node = path.getValue();
if (node.type === "documentBody") {
const document = path.getParentNode();
return hasEndComments(document.head) && isPrettierIgnore$2(getLast$5(document.head.endComments));
}
return hasLeadingComments(node) && isPrettierIgnore$2(getLast$5(node.leadingComments));
}
function isEmptyNode(node) {
return (!node.children || node.children.length === 0) && !hasComments(node);
}
function hasComments(node) {
return hasLeadingComments(node) || hasMiddleComments(node) || hasIndicatorComment(node) || hasTrailingComment$2(node) || hasEndComments(node);
}
function hasLeadingComments(node) {
return node && node.leadingComments && node.leadingComments.length !== 0;
}
function hasMiddleComments(node) {
return node && node.middleComments && node.middleComments.length !== 0;
}
function hasIndicatorComment(node) {
return node && node.indicatorComment;
}
function hasTrailingComment$2(node) {
return node && node.trailingComment;
}
function hasEndComments(node) {
return node && node.endComments && node.endComments.length !== 0;
}
/**
* " a b c d e f " -> [" a b", "c d", "e f "]
*/
function splitWithSingleSpace(text) {
const parts = [];
let lastPart = undefined;
for (const part of text.split(/( +)/g)) {
if (part !== " ") {
if (lastPart === " ") {
parts.push(part);
} else {
parts.push((parts.pop() || "") + part);
}
} else if (lastPart === undefined) {
parts.unshift("");
}
lastPart = part;
}
if (lastPart === " ") {
parts.push((parts.pop() || "") + " ");
}
if (parts[0] === "") {
parts.shift();
parts.unshift(" " + (parts.shift() || ""));
}
return parts;
}
function getFlowScalarLineContents(nodeType, content, options) {
const rawLineContents = content.split("\n").map((lineContent, index, lineContents) => index === 0 && index === lineContents.length - 1 ? lineContent : index !== 0 && index !== lineContents.length - 1 ? lineContent.trim() : index === 0 ? lineContent.trimEnd() : lineContent.trimStart());
if (options.proseWrap === "preserve") {
return rawLineContents.map(lineContent => lineContent.length === 0 ? [] : [lineContent]);
}
return rawLineContents.map(lineContent => lineContent.length === 0 ? [] : splitWithSingleSpace(lineContent)).reduce((reduced, lineContentWords, index) => index !== 0 && rawLineContents[index - 1].length !== 0 && lineContentWords.length !== 0 && !( // trailing backslash in quoteDouble should be preserved
nodeType === "quoteDouble" && getLast$5(getLast$5(reduced)).endsWith("\\")) ? reduced.concat([reduced.pop().concat(lineContentWords)]) : reduced.concat([lineContentWords]), []).map(lineContentWords => options.proseWrap === "never" ? [lineContentWords.join(" ")] : lineContentWords);
}
function getBlockValueLineContents(node, {
parentIndent,
isLastDescendant,
options
}) {
const content = node.position.start.line === node.position.end.line ? "" : options.originalText.slice(node.position.start.offset, node.position.end.offset) // exclude open line `>` or `|`
.match(/^[^\n]*?\n([\s\S]*)$/)[1];
const leadingSpaceCount = node.indent === null ? (match => match ? match[1].length : Infinity)(content.match(/^( *)\S/m)) : node.indent - 1 + parentIndent;
const rawLineContents = content.split("\n").map(lineContent => lineContent.slice(leadingSpaceCount));
if (options.proseWrap === "preserve" || node.type === "blockLiteral") {
return removeUnnecessaryTrailingNewlines(rawLineContents.map(lineContent => lineContent.length === 0 ? [] : [lineContent]));
}
return removeUnnecessaryTrailingNewlines(rawLineContents.map(lineContent => lineContent.length === 0 ? [] : splitWithSingleSpace(lineContent)).reduce((reduced, lineContentWords, index) => index !== 0 && rawLineContents[index - 1].length !== 0 && lineContentWords.length !== 0 && !/^\s/.test(lineContentWords[0]) && !/^\s|\s$/.test(getLast$5(reduced)) ? reduced.concat([reduced.pop().concat(lineContentWords)]) : reduced.concat([lineContentWords]), []).map(lineContentWords => lineContentWords.reduce((reduced, word) => // disallow trailing spaces
reduced.length !== 0 && /\s$/.test(getLast$5(reduced)) ? reduced.concat(reduced.pop() + " " + word) : reduced.concat(word), [])).map(lineContentWords => options.proseWrap === "never" ? [lineContentWords.join(" ")] : lineContentWords));
function removeUnnecessaryTrailingNewlines(lineContents) {
if (node.chomping === "keep") {
return getLast$5(lineContents).length === 0 ? lineContents.slice(0, -1) : lineContents;
}
let trailingNewlineCount = 0;
for (let i = lineContents.length - 1; i >= 0; i--) {
if (lineContents[i].length === 0) {
trailingNewlineCount++;
} else {
break;
}
}
return trailingNewlineCount === 0 ? lineContents : trailingNewlineCount >= 2 && !isLastDescendant ? // next empty line
lineContents.slice(0, -(trailingNewlineCount - 1)) : lineContents.slice(0, -trailingNewlineCount);
}
}
var utils$7 = {
getLast: getLast$5,
getAncestorCount,
isNode,
isEmptyNode,
mapNode,
defineShortcut,
isNextLineEmpty: isNextLineEmpty$5,
isLastDescendantNode,
getBlockValueLineContents,
getFlowScalarLineContents,
getLastDescendantNode: getLastDescendantNode$1,
hasPrettierIgnore: hasPrettierIgnore$7,
hasLeadingComments,
hasMiddleComments,
hasIndicatorComment,
hasTrailingComment: hasTrailingComment$2,
hasEndComments
};
const {
insertPragma: insertPragma$9,
isPragma: isPragma$1
} = pragma$5;
const {
getAncestorCount: getAncestorCount$1,
getBlockValueLineContents: getBlockValueLineContents$1,
getFlowScalarLineContents: getFlowScalarLineContents$1,
getLast: getLast$6,
getLastDescendantNode: getLastDescendantNode$2,
hasLeadingComments: hasLeadingComments$1,
hasMiddleComments: hasMiddleComments$1,
hasIndicatorComment: hasIndicatorComment$1,
hasTrailingComment: hasTrailingComment$3,
hasEndComments: hasEndComments$1,
hasPrettierIgnore: hasPrettierIgnore$8,
isLastDescendantNode: isLastDescendantNode$1,
isNextLineEmpty: isNextLineEmpty$6,
isNode: isNode$1,
isEmptyNode: isEmptyNode$1,
defineShortcut: defineShortcut$1,
mapNode: mapNode$1
} = utils$7;
const docBuilders$2 = document.builders;
const {
conditionalGroup: conditionalGroup$2,
breakParent: breakParent$5,
concat: concat$h,
dedent: dedent$3,
dedentToRoot: dedentToRoot$3,
fill: fill$6,
group: group$g,
hardline: hardline$d,
ifBreak: ifBreak$8,
join: join$c,
line: line$b,
lineSuffix: lineSuffix$2,
literalline: literalline$7,
markAsRoot: markAsRoot$5,
softline: softline$8
} = docBuilders$2;
const {
replaceEndOfLineWith: replaceEndOfLineWith$3
} = util$1;
function preprocess$3(ast) {
return mapNode$1(ast, defineShortcuts);
}
function defineShortcuts(node) {
switch (node.type) {
case "document":
defineShortcut$1(node, "head", () => node.children[0]);
defineShortcut$1(node, "body", () => node.children[1]);
break;
case "documentBody":
case "sequenceItem":
case "flowSequenceItem":
case "mappingKey":
case "mappingValue":
defineShortcut$1(node, "content", () => node.children[0]);
break;
case "mappingItem":
case "flowMappingItem":
defineShortcut$1(node, "key", () => node.children[0]);
defineShortcut$1(node, "value", () => node.children[1]);
break;
}
return node;
}
function genericPrint$6(path, options, print) {
const node = path.getValue();
const parentNode = path.getParentNode();
const tag = !node.tag ? "" : path.call(print, "tag");
const anchor = !node.anchor ? "" : path.call(print, "anchor");
const nextEmptyLine = isNode$1(node, ["mapping", "sequence", "comment", "directive", "mappingItem", "sequenceItem"]) && !isLastDescendantNode$1(path) ? printNextEmptyLine(path, options.originalText) : "";
return concat$h([node.type !== "mappingValue" && hasLeadingComments$1(node) ? concat$h([join$c(hardline$d, path.map(print, "leadingComments")), hardline$d]) : "", tag, tag && anchor ? " " : "", anchor, tag || anchor ? isNode$1(node, ["sequence", "mapping"]) && !hasMiddleComments$1(node) ? hardline$d : " " : "", hasMiddleComments$1(node) ? concat$h([node.middleComments.length === 1 ? "" : hardline$d, join$c(hardline$d, path.map(print, "middleComments")), hardline$d]) : "", hasPrettierIgnore$8(path) ? concat$h(replaceEndOfLineWith$3(options.originalText.slice(node.position.start.offset, node.position.end.offset), literalline$7)) : group$g(_print(node, parentNode, path, options, print)), hasTrailingComment$3(node) && !isNode$1(node, ["document", "documentHead"]) ? lineSuffix$2(concat$h([node.type === "mappingValue" && !node.content ? "" : " ", parentNode.type === "mappingKey" && path.getParentNode(2).type === "mapping" && isInlineNode(node) ? "" : breakParent$5, path.call(print, "trailingComment")])) : "", nextEmptyLine, hasEndComments$1(node) && !isNode$1(node, ["documentHead", "documentBody"]) ? align$3(node.type === "sequenceItem" ? 2 : 0, concat$h([hardline$d, join$c(hardline$d, path.map(print, "endComments"))])) : ""]);
}
function _print(node, parentNode, path, options, print) {
switch (node.type) {
case "root":
return concat$h([join$c(hardline$d, path.map((childPath, index) => {
const document = node.children[index];
const nextDocument = node.children[index + 1];
return concat$h([print(childPath), shouldPrintDocumentEndMarker(document, nextDocument) ? concat$h([hardline$d, "...", hasTrailingComment$3(document) ? concat$h([" ", path.call(print, "trailingComment")]) : ""]) : !nextDocument || hasTrailingComment$3(nextDocument.head) ? "" : concat$h([hardline$d, "---"])]);
}, "children")), node.children.length === 0 || (lastDescendantNode => isNode$1(lastDescendantNode, ["blockLiteral", "blockFolded"]) && lastDescendantNode.chomping === "keep")(getLastDescendantNode$2(node)) ? "" : hardline$d]);
case "document":
{
const nextDocument = parentNode.children[path.getName() + 1];
return join$c(hardline$d, [shouldPrintDocumentHeadEndMarker(node, nextDocument, parentNode, options) === "head" ? join$c(hardline$d, [node.head.children.length === 0 && node.head.endComments.length === 0 ? "" : path.call(print, "head"), concat$h(["---", hasTrailingComment$3(node.head) ? concat$h([" ", path.call(print, "head", "trailingComment")]) : ""])].filter(Boolean)) : "", shouldPrintDocumentBody(node) ? path.call(print, "body") : ""].filter(Boolean));
}
case "documentHead":
return join$c(hardline$d, [].concat(path.map(print, "children"), path.map(print, "endComments")));
case "documentBody":
{
const children = join$c(hardline$d, path.map(print, "children")).parts;
const endComments = join$c(hardline$d, path.map(print, "endComments")).parts;
const separator = children.length === 0 || endComments.length === 0 ? "" : (lastDescendantNode => isNode$1(lastDescendantNode, ["blockFolded", "blockLiteral"]) ? lastDescendantNode.chomping === "keep" ? // there's already a newline printed at the end of blockValue (chomping=keep, lastDescendant=true)
"" : // an extra newline for better readability
concat$h([hardline$d, hardline$d]) : hardline$d)(getLastDescendantNode$2(node));
return concat$h([].concat(children, separator, endComments));
}
case "directive":
return concat$h(["%", join$c(" ", [node.name].concat(node.parameters))]);
case "comment":
return concat$h(["#", node.value]);
case "alias":
return concat$h(["*", node.value]);
case "tag":
return options.originalText.slice(node.position.start.offset, node.position.end.offset);
case "anchor":
return concat$h(["&", node.value]);
case "plain":
return printFlowScalarContent(node.type, options.originalText.slice(node.position.start.offset, node.position.end.offset), options);
case "quoteDouble":
case "quoteSingle":
{
const singleQuote = "'";
const doubleQuote = '"';
const raw = options.originalText.slice(node.position.start.offset + 1, node.position.end.offset - 1);
if (node.type === "quoteSingle" && raw.includes("\\") || node.type === "quoteDouble" && /\\[^"]/.test(raw)) {
// only quoteDouble can use escape chars
// and quoteSingle do not need to escape backslashes
const originalQuote = node.type === "quoteDouble" ? doubleQuote : singleQuote;
return concat$h([originalQuote, printFlowScalarContent(node.type, raw, options), originalQuote]);
} else if (raw.includes(doubleQuote)) {
return concat$h([singleQuote, printFlowScalarContent(node.type, node.type === "quoteDouble" ? raw // double quote needs to be escaped by backslash in quoteDouble
.replace(/\\"/g, doubleQuote).replace(/'/g, singleQuote.repeat(2)) : raw, options), singleQuote]);
}
if (raw.includes(singleQuote)) {
return concat$h([doubleQuote, printFlowScalarContent(node.type, node.type === "quoteSingle" ? // single quote needs to be escaped by 2 single quotes in quoteSingle
raw.replace(/''/g, singleQuote) : raw, options), doubleQuote]);
}
const quote = options.singleQuote ? singleQuote : doubleQuote;
return concat$h([quote, printFlowScalarContent(node.type, raw, options), quote]);
}
case "blockFolded":
case "blockLiteral":
{
const parentIndent = getAncestorCount$1(path, ancestorNode => isNode$1(ancestorNode, ["sequence", "mapping"]));
const isLastDescendant = isLastDescendantNode$1(path);
return concat$h([node.type === "blockFolded" ? ">" : "|", node.indent === null ? "" : node.indent.toString(), node.chomping === "clip" ? "" : node.chomping === "keep" ? "+" : "-", hasIndicatorComment$1(node) ? concat$h([" ", path.call(print, "indicatorComment")]) : "", (node.indent === null ? dedent$3 : dedentToRoot$3)(align$3(node.indent === null ? options.tabWidth : node.indent - 1 + parentIndent, concat$h(getBlockValueLineContents$1(node, {
parentIndent,
isLastDescendant,
options
}).reduce((reduced, lineWords, index, lineContents) => reduced.concat(index === 0 ? hardline$d : "", fill$6(join$c(line$b, lineWords).parts), index !== lineContents.length - 1 ? lineWords.length === 0 ? hardline$d : markAsRoot$5(literalline$7) : node.chomping === "keep" && isLastDescendant ? lineWords.length === 0 ? dedentToRoot$3(hardline$d) : dedentToRoot$3(literalline$7) : ""), []))))]);
}
case "sequence":
return join$c(hardline$d, path.map(print, "children"));
case "sequenceItem":
return concat$h(["- ", align$3(2, !node.content ? "" : path.call(print, "content"))]);
case "mappingKey":
return !node.content ? "" : path.call(print, "content");
case "mappingValue":
return !node.content ? "" : path.call(print, "content");
case "mapping":
return join$c(hardline$d, path.map(print, "children"));
case "mappingItem":
case "flowMappingItem":
{
const isEmptyMappingKey = isEmptyNode$1(node.key);
const isEmptyMappingValue = isEmptyNode$1(node.value);
if (isEmptyMappingKey && isEmptyMappingValue) {
return concat$h([": "]);
}
const key = path.call(print, "key");
const value = path.call(print, "value");
if (isEmptyMappingValue) {
return node.type === "flowMappingItem" && parentNode.type === "flowMapping" ? key : node.type === "mappingItem" && isAbsolutelyPrintedAsSingleLineNode(node.key.content, options) && !hasTrailingComment$3(node.key.content) && (!parentNode.tag || parentNode.tag.value !== "tag:yaml.org,2002:set") ? concat$h([key, needsSpaceInFrontOfMappingValue(node) ? " " : "", ":"]) : concat$h(["? ", align$3(2, key)]);
}
if (isEmptyMappingKey) {
return concat$h([": ", align$3(2, value)]);
}
const groupId = Symbol("mappingKey");
const forceExplicitKey = hasLeadingComments$1(node.value) || !isInlineNode(node.key.content);
return forceExplicitKey ? concat$h(["? ", align$3(2, key), hardline$d, join$c("", path.map(print, "value", "leadingComments").map(comment => concat$h([comment, hardline$d]))), ": ", align$3(2, value)]) : // force singleline
isSingleLineNode(node.key.content) && !hasLeadingComments$1(node.key.content) && !hasMiddleComments$1(node.key.content) && !hasTrailingComment$3(node.key.content) && !hasEndComments$1(node.key) && !hasLeadingComments$1(node.value.content) && !hasMiddleComments$1(node.value.content) && !hasEndComments$1(node.value) && isAbsolutelyPrintedAsSingleLineNode(node.value.content, options) ? concat$h([key, needsSpaceInFrontOfMappingValue(node) ? " " : "", ": ", value]) : conditionalGroup$2([concat$h([group$g(concat$h([ifBreak$8("? "), group$g(align$3(2, key), {
id: groupId
})])), ifBreak$8(concat$h([hardline$d, ": ", align$3(2, value)]), indent(concat$h([needsSpaceInFrontOfMappingValue(node) ? " " : "", ":", hasLeadingComments$1(node.value.content) || hasEndComments$1(node.value) && node.value.content && !isNode$1(node.value.content, ["mapping", "sequence"]) || parentNode.type === "mapping" && hasTrailingComment$3(node.key.content) && isInlineNode(node.value.content) || isNode$1(node.value.content, ["mapping", "sequence"]) && node.value.content.tag === null && node.value.content.anchor === null ? hardline$d : !node.value.content ? "" : line$b, value])), {
groupId
})])]);
}
case "flowMapping":
case "flowSequence":
{
const openMarker = node.type === "flowMapping" ? "{" : "[";
const closeMarker = node.type === "flowMapping" ? "}" : "]";
const bracketSpacing = node.type === "flowMapping" && node.children.length !== 0 && options.bracketSpacing ? line$b : softline$8;
const isLastItemEmptyMappingItem = node.children.length !== 0 && (lastItem => lastItem.type === "flowMappingItem" && isEmptyNode$1(lastItem.key) && isEmptyNode$1(lastItem.value))(getLast$6(node.children));
return concat$h([openMarker, indent(concat$h([bracketSpacing, concat$h(path.map((childPath, index) => concat$h([print(childPath), index === node.children.length - 1 ? "" : concat$h([",", line$b, node.children[index].position.start.line !== node.children[index + 1].position.start.line ? printNextEmptyLine(childPath, options.originalText) : ""])]), "children")), ifBreak$8(",", "")])), isLastItemEmptyMappingItem ? "" : bracketSpacing, closeMarker]);
}
case "flowSequenceItem":
return path.call(print, "content");
// istanbul ignore next
default:
throw new Error("Unexpected node type ".concat(node.type));
}
function indent(doc) {
return docBuilders$2.align(" ".repeat(options.tabWidth), doc);
}
}
function align$3(n, doc) {
return typeof n === "number" && n > 0 ? docBuilders$2.align(" ".repeat(n), doc) : docBuilders$2.align(n, doc);
}
function isInlineNode(node) {
if (!node) {
return true;
}
switch (node.type) {
case "plain":
case "quoteDouble":
case "quoteSingle":
case "alias":
case "flowMapping":
case "flowSequence":
return true;
default:
return false;
}
}
function isSingleLineNode(node) {
if (!node) {
return true;
}
switch (node.type) {
case "plain":
case "quoteDouble":
case "quoteSingle":
return node.position.start.line === node.position.end.line;
case "alias":
return true;
default:
return false;
}
}
function shouldPrintDocumentBody(document) {
return document.body.children.length !== 0 || hasEndComments$1(document.body);
}
function shouldPrintDocumentEndMarker(document, nextDocument) {
return (
/**
*... # trailingComment
*/
hasTrailingComment$3(document) || nextDocument && (
/**
* ...
* %DIRECTIVE
* ---
*/
nextDocument.head.children.length !== 0 ||
/**
* ...
* # endComment
* ---
*/
hasEndComments$1(nextDocument.head))
);
}
function shouldPrintDocumentHeadEndMarker(document, nextDocument, root, options) {
if (
/**
* ---
* preserve the first document head end marker
*/
root.children[0] === document && /---(\s|$)/.test(options.originalText.slice(options.locStart(document), options.locStart(document) + 4)) ||
/**
* %DIRECTIVE
* ---
*/
document.head.children.length !== 0 ||
/**
* # end comment
* ---
*/
hasEndComments$1(document.head) ||
/**
* --- # trailing comment
*/
hasTrailingComment$3(document.head)) {
return "head";
}
if (shouldPrintDocumentEndMarker(document, nextDocument)) {
return false;
}
return nextDocument ? "root" : false;
}
function isAbsolutelyPrintedAsSingleLineNode(node, options) {
if (!node) {
return true;
}
switch (node.type) {
case "plain":
case "quoteSingle":
case "quoteDouble":
break;
case "alias":
return true;
default:
return false;
}
if (options.proseWrap === "preserve") {
return node.position.start.line === node.position.end.line;
}
if ( // backslash-newline
/\\$/m.test(options.originalText.slice(node.position.start.offset, node.position.end.offset))) {
return false;
}
switch (options.proseWrap) {
case "never":
return !node.value.includes("\n");
case "always":
return !/[\n ]/.test(node.value);
// istanbul ignore next
default:
return false;
}
}
function needsSpaceInFrontOfMappingValue(node) {
return node.key.content && node.key.content.type === "alias";
}
function printNextEmptyLine(path, originalText) {
const node = path.getValue();
const root = path.stack[0];
root.isNextEmptyLinePrintedChecklist = root.isNextEmptyLinePrintedChecklist || [];
if (!root.isNextEmptyLinePrintedChecklist[node.position.end.line]) {
if (isNextLineEmpty$6(node, originalText)) {
root.isNextEmptyLinePrintedChecklist[node.position.end.line] = true;
return softline$8;
}
}
return "";
}
function printFlowScalarContent(nodeType, content, options) {
const lineContents = getFlowScalarLineContents$1(nodeType, content, options);
return join$c(hardline$d, lineContents.map(lineContentWords => fill$6(join$c(line$b, lineContentWords).parts)));
}
function clean$7(node, newNode
/*, parent */
) {
if (isNode$1(newNode)) {
delete newNode.position;
switch (newNode.type) {
case "comment":
// insert pragma
if (isPragma$1(newNode.value)) {
return null;
}
break;
case "quoteDouble":
case "quoteSingle":
newNode.type = "quote";
break;
}
}
}
var printerYaml = {
preprocess: preprocess$3,
print: genericPrint$6,
massageAstNode: clean$7,
insertPragma: insertPragma$9
};
var options$7 = {
bracketSpacing: commonOptions.bracketSpacing,
singleQuote: commonOptions.singleQuote,
proseWrap: commonOptions.proseWrap
};
var name$h = "YAML";
var type$g = "data";
var tmScope$g = "source.yaml";
var aliases$6 = [
"yml"
];
var extensions$g = [
".yml",
".mir",
".reek",
".rviz",
".sublime-syntax",
".syntax",
".yaml",
".yaml-tmlanguage",
".yaml.sed",
".yml.mysql"
];
var filenames$4 = [
".clang-format",
".clang-tidy",
".gemrc",
"glide.lock",
"yarn.lock"
];
var aceMode$g = "yaml";
var codemirrorMode$c = "yaml";
var codemirrorMimeType$c = "text/x-yaml";
var languageId$g = 407;
var YAML = {
name: name$h,
type: type$g,
tmScope: tmScope$g,
aliases: aliases$6,
extensions: extensions$g,
filenames: filenames$4,
aceMode: aceMode$g,
codemirrorMode: codemirrorMode$c,
codemirrorMimeType: codemirrorMimeType$c,
languageId: languageId$g
};
var YAML$1 = /*#__PURE__*/Object.freeze({
__proto__: null,
name: name$h,
type: type$g,
tmScope: tmScope$g,
aliases: aliases$6,
extensions: extensions$g,
filenames: filenames$4,
aceMode: aceMode$g,
codemirrorMode: codemirrorMode$c,
codemirrorMimeType: codemirrorMimeType$c,
languageId: languageId$g,
'default': YAML
});
var require$$0$8 = getCjsExportFromNamespace(YAML$1);
const languages$6 = [createLanguage(require$$0$8, data => ({
since: "1.14.0",
parsers: ["yaml"],
vscodeLanguageIds: ["yaml"],
// yarn.lock is not YAML: https://github.com/yarnpkg/yarn/issues/5629
filenames: data.filenames.filter(filename => filename !== "yarn.lock")
}))];
var languageYaml = {
languages: languages$6,
printers: {
yaml: printerYaml
},
options: options$7
};
const {
version: version$2
} = require$$0;
const {
getSupportInfo: getSupportInfo$2
} = support;
const internalPlugins = [languageCss, languageGraphql, languageHandlebars, languageHtml, languageJs, languageMarkdown, languageYaml];
function withPlugins(fn, optsArgIdx = 1 // Usually `opts` is the 2nd argument
) {
return (...args) => {
const opts = args[optsArgIdx] || {};
const plugins = opts.plugins || [];
args[optsArgIdx] = Object.assign({}, opts, {
plugins: [...internalPlugins, ...(Array.isArray(plugins) ? plugins : Object.values(plugins))]
});
return fn(...args);
};
}
const formatWithCursor = withPlugins(core.formatWithCursor);
var standalone = {
formatWithCursor,
format(text, opts) {
return formatWithCursor(text, opts).formatted;
},
check(text, opts) {
const {
formatted
} = formatWithCursor(text, opts);
return formatted === text;
},
doc: document,
getSupportInfo: withPlugins(getSupportInfo$2, 0),
version: version$2,
util: utilShared,
__debug: {
parse: withPlugins(core.parse),
formatAST: withPlugins(core.formatAST),
formatDoc: withPlugins(core.formatDoc),
printToDoc: withPlugins(core.printToDoc),
printDocToString: withPlugins(core.printDocToString)
}
};
var standalone$1 = standalone;
return standalone$1;
})));